[
  {
    "path": ".checkapi.yaml",
    "content": "ignored_paths:\n  - confmap/doc_test.go\nexcluded_files:\n  - example_*.go\n  - \"*_test.go\"\nunkeyed_literal_initialization:\n  enabled: true\n  limit: 6\n"
  },
  {
    "path": ".chloggen/README.md",
    "content": "### Changelog folder\n\nThis repo uses `chloggen` to manage its changelog files. You can find the source code for the tool [here](https://github.com/open-telemetry/opentelemetry-go-build-tools/tree/main/chloggen).\n\nHere is a quick explanation of the `config.yaml` file for chloggen:\n\n```yaml\n# The directory that stores individual changelog entries.\n# Each entry is stored in a dedicated yaml file.\n# - 'chloggen new' will copy the 'template_yaml' to this directory as a new entry file.\n# - 'chloggen validate' will validate that all entry files are valid.\n# - 'chloggen update' will read and delete all entry files in this directory, and update 'changelog_md'.\n# Specify as relative path from root of repo.\n# (Optional) Default: .chloggen\nentries_dir: .chloggen\n\n# This file is used as the input for individual changelog entries.\n# Specify as relative path from root of repo.\n# (Optional) Default: .chloggen/TEMPLATE.yaml\ntemplate_yaml: .chloggen/TEMPLATE.yaml\n\nsummary_template: .chloggen/summary.tmpl\n\n# The CHANGELOG file or files to which 'chloggen update' will write new entries\n# (Optional) Default filename: CHANGELOG.md\nchange_logs:\n  user: CHANGELOG.md\n  api: CHANGELOG-API.md\n\n# The default change_log or change_logs to which an entry should be added.\n# If 'change_logs' is specified in this file, and no value is specified for 'default_change_logs',\n# then 'change_logs' MUST be specified in every entry file.\ndefault_change_logs: [user]\n```\n"
  },
  {
    "path": ".chloggen/TEMPLATE.yaml",
    "content": "# Use this changelog template to create an entry for release notes.\n\n# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'\nchange_type:\n\n# The name of the component, or a single word describing the area of concern, (e.g. receiver/otlp)\ncomponent:\n\n# A brief description of the change.  Surround your text with quotes (\"\") if it needs to start with a backtick (`).\nnote:\n\n# One or more tracking issues or pull requests related to the change\nissues: []\n\n# (Optional) One or more lines of additional information to render under the primary note.\n# These lines will be padded with 2 spaces and then inserted directly into the document.\n# Use pipe (|) for multiline entries.\nsubtext:\n\n# Optional: The change log or logs in which this entry should be included.\n# e.g. '[user]' or '[user, api]'\n# Include 'user' if the change is relevant to end users.\n# Include 'api' if there is a change to a library API.\n# Default: '[user]'\nchange_logs: []\n"
  },
  {
    "path": ".chloggen/aix_tier3.yaml",
    "content": "# Use this changelog template to create an entry for release notes.\n\n# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'\nchange_type: enhancement\n\n# The name of the component, or a single word describing the area of concern, (e.g. receiver/otlp)\ncomponent: all\n\n# A brief description of the change.  Surround your text with quotes (\"\") if it needs to start with a backtick (`).\nnote: Move aix/ppc64 to tier 3 support\n\n# One or more tracking issues or pull requests related to the change\nissues: [13380]\n\n# (Optional) One or more lines of additional information to render under the primary note.\n# These lines will be padded with 2 spaces and then inserted directly into the document.\n# Use pipe (|) for multiline entries.\nsubtext:\n\n# Optional: The change log or logs in which this entry should be included.\n# e.g. '[user]' or '[user, api]'\n# Include 'user' if the change is relevant to end users.\n# Include 'api' if there is a change to a library API.\n# Default: '[user]'\nchange_logs: []\n"
  },
  {
    "path": ".chloggen/alpha-profiles.yaml",
    "content": "# Use this changelog template to create an entry for release notes.\n\n# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'\nchange_type: enhancement\n\n# The name of the component, or a single word describing the area of concern, (e.g. receiver/otlp)\ncomponent: all\n\n# A brief description of the change.  Surround your text with quotes (\"\") if it needs to start with a backtick (`).\nnote: Upgrade the profiles stability status to alpha\n\n# One or more tracking issues or pull requests related to the change\nissues: [14817]\n\n# (Optional) One or more lines of additional information to render under the primary note.\n# These lines will be padded with 2 spaces and then inserted directly into the document.\n# Use pipe (|) for multiline entries.\nsubtext: |\n  The following components have their profiles status upgraded from development to alpha:\n\n  * pdata/pprofile\n  * connector/forward\n  * exporter/debug\n  * receiver/nop\n  * exporter/nop\n  * exporter/otlp_grpc\n  * exporter/otlp_http\n\n# Optional: The change log or logs in which this entry should be included.\n# e.g. '[user]' or '[user, api]'\n# Include 'user' if the change is relevant to end users.\n# Include 'api' if there is a change to a library API.\n# Default: '[user]'\nchange_logs: []\n"
  },
  {
    "path": ".chloggen/config.yaml",
    "content": "change_logs:\n    api: CHANGELOG-API.md\n    user: CHANGELOG.md\ndefault_change_logs:\n    - user\nentries_dir: .chloggen\ntemplate_yaml: .chloggen/TEMPLATE.yaml\nsummary_template: .chloggen/summary.tmpl\ncomponents:\n    - all\n    - cmd/builder\n    - cmd/mdatagen\n    - connector/forward\n    - connector/sample\n    - consumer/consumererror/xconsumererror\n    - consumer/xconsumer\n    - docs/rfcs\n    - exporter/debug\n    - exporter/nop\n    - exporter/otlp_grpc\n    - exporter/otlp_http\n    - extension/memory_limiter\n    - extension/zpages\n    - pdata/pprofile\n    - pkg/client\n    - pkg/component\n    - pkg/component/componentstatus\n    - pkg/component/componenttest\n    - pkg/config/configauth\n    - pkg/config/configcompression\n    - pkg/config/configgrpc\n    - pkg/config/confighttp/xconfighttp\n    - pkg/config/configmiddleware\n    - pkg/config/confignet\n    - pkg/config/configopaque\n    - pkg/config/configretry\n    - pkg/config/configtelemetry\n    - pkg/config/configtls\n    - pkg/confighttp\n    - pkg/configoptional\n    - pkg/confmap\n    - pkg/connector\n    - pkg/connector/connectortest\n    - pkg/consumer\n    - pkg/consumer/consumererror\n    - pkg/consumer/consumertest\n    - pkg/exporter\n    - pkg/exporter/exportertest\n    - pkg/exporterhelper\n    - pkg/extension\n    - pkg/extension/extensiontest\n    - pkg/extensionauth\n    - pkg/extensionauth/extensionauthtest\n    - pkg/extensioncapabilities\n    - pkg/extensionmiddleware\n    - pkg/extensionmiddleware/extensionmiddlewaretest\n    - pkg/featuregate\n    - pkg/filter\n    - pkg/otelcol\n    - pkg/otelcol/otelcoltest\n    - pkg/pdata\n    - pkg/pipeline\n    - pkg/processor\n    - pkg/processor/processortest\n    - pkg/processorhelper\n    - pkg/queuebatch\n    - pkg/receiver\n    - pkg/receiver/receivertest\n    - pkg/receiverhelper\n    - pkg/scraper\n    - pkg/scraper/scrapertest\n    - pkg/scraperhelper\n    - pkg/service\n    - pkg/service/hostcapabilities\n    - pkg/service/telemetry/telemetrytest\n    - pkg/xconfmap\n    - pkg/xconnector\n    - pkg/xexporter\n    - pkg/xexporterhelper\n    - pkg/xextension\n    - pkg/xextension/storage\n    - pkg/xpdata\n    - pkg/xpipeline\n    - pkg/xprocessor\n    - pkg/xprocessorhelper\n    - pkg/xreceiver\n    - pkg/xscraper\n    - pkg/xscraperhelper\n    - processor/batch\n    - processor/memory_limiter\n    - processor/sample\n    - provider/env\n    - provider/file\n    - provider/http\n    - provider/https\n    - provider/yaml\n    - receiver/nop\n    - receiver/otlp\n    - receiver/sample\n    - receiver/sample\n    - receiver/sampleentity\n    - scraper/sample\n    - service/graph\n"
  },
  {
    "path": ".chloggen/fix-mdatagen-entity-builder.yaml",
    "content": "change_type: bug_fix\ncomponent: cmd/mdatagen\nnote: Fix entity code generation so `extra_attributes` are emitted as resource attributes instead of entity descriptive attributes.\nissues: [14778]\n"
  },
  {
    "path": ".chloggen/mdatagen_fix_reporoot.yaml",
    "content": "# Use this changelog template to create an entry for release notes.\n\n# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix'\nchange_type: bug_fix\n\n# The name of the component, or a single word describing the area of concern, (e.g. receiver/otlp)\ncomponent: cmd/mdatagen\n\n# A brief description of the change.  Surround your text with quotes (\"\") if it needs to start with a backtick (`).\nnote: Fix RootPackage to use go module root instead of git repo root\n\n# One or more tracking issues or pull requests related to the change\nissues: [14801]\n\n# (Optional) One or more lines of additional information to render under the primary note.\n# These lines will be padded with 2 spaces and then inserted directly into the document.\n# Use pipe (|) for multiline entries.\nsubtext: Fixes issue with running mdatagen when the git repository root is different from the go module root.\n\n# Optional: The change log or logs in which this entry should be included.\n# e.g. '[user]' or '[user, api]'\n# Include 'user' if the change is relevant to end users.\n# Include 'api' if there is a change to a library API.\n# Default: '[user]'\nchange_logs: [api]\n"
  },
  {
    "path": ".chloggen/remove-resource-constant-labels.yaml",
    "content": "change_type: breaking\n\ncomponent: pkg/service\n\nnote: Remove `service_name`, `service_instance_id`, and `service_version` as constant labels on every internal metric datapoint. These attributes are already present in `target_info` and were being duplicated on each series for OpenCensus backwards compatibility.\n\nissues: [14811]\n\nsubtext: |\n  Previously, the collector stamped every internal metric series (e.g. `otelcol_process_runtime_heap_alloc_bytes`)\n  with `service_name`, `service_instance_id`, and `service_version` labels to match the old OpenCensus behavior.\n  These attributes are now only present in the `target_info` metric, which is the correct Prometheus/OTel convention.\n  Users who filter or group by these labels on individual metrics will need to update their queries to use\n  `target_info` joins instead.\n\nchange_logs: [user]\n"
  },
  {
    "path": ".chloggen/summary.tmpl",
    "content": "{{- define \"entry\" -}}\n- `{{ .Component }}`: {{ .Note }} (\n{{- range $i, $issue := .Issues }}\n{{- if $i }}, {{ end -}}\n#{{ $issue }}\n{{- end -}}\n)\n\n{{- if .SubText }}\n{{ .SubText | indent 2 }}\n{{- end }}\n{{- end }}\n## {{ .Version }}\n\n{{- if .BreakingChanges }}\n\n### 🛑 Breaking changes 🛑\n\n{{- range $i, $change := .BreakingChanges }}\n{{- if eq $i 0}}\n{{end}}\n{{ template \"entry\" $change }}\n{{- end }}\n{{- end }}\n\n{{- if .Deprecations }}\n\n### 🚩 Deprecations 🚩\n\n{{- range $i, $change := .Deprecations }}\n{{- if eq $i 0}}\n{{end}}\n{{ template \"entry\" $change }}\n{{- end }}\n{{- end }}\n\n{{- if .NewComponents }}\n\n### 🚀 New components 🚀\n\n{{- range $i, $change := .NewComponents }}\n{{- if eq $i 0}}\n{{end}}\n{{ template \"entry\" $change }}\n{{- end }}\n{{- end }}\n\n{{- if .Enhancements }}\n\n### 💡 Enhancements 💡\n\n{{- range $i, $change := .Enhancements }}\n{{- if eq $i 0}}\n{{end}}\n{{ template \"entry\" $change }}\n{{- end }}\n{{- end }}\n\n{{- if .BugFixes }}\n\n### 🧰 Bug fixes 🧰\n\n{{- range $i, $change := .BugFixes }}\n{{- if eq $i 0}}\n{{end}}\n{{ template \"entry\" $change }}\n{{- end }}\n{{- end }}\n\n<!-- previous-version -->\n"
  },
  {
    "path": ".codecov.yml",
    "content": "codecov:\n  branch: main\n  # only use the latest copy on main branch\n  strict_yaml_branch: main\n\ncoverage:\n  precision: 2\n  round: down\n  range: \"80...100\"\n  status:\n    project:\n      default:\n        enabled: yes\n        target: 90%\n    patch:\n      default:\n        enabled: yes\n        target: 95%\n\nignore:\n  - \"pdata/internal/data/protogen/**/*\"\n  - \"**/*.pb.go\"\n  - \"cmd/mdatagen/third_party/**/*\"\n"
  },
  {
    "path": ".gitattributes",
    "content": "# This file is documented at https://git-scm.com/docs/gitattributes.\n# Linguist-specific attributes are documented at\n# https://github.com/github/linguist.\n\ngo.sum linguist-generated=true\n\n# Avoid git status and other tools (lint, fmt) reporting whitespace differences\n# on Windows machines by ensuring that `lf` on text files are not converted to `crlf`.\n* text=auto eol=lf\n"
  },
  {
    "path": ".github/ALLOWLIST",
    "content": "# Code generated by githubgen. DO NOT EDIT.\n#####################################################\n#\n# List of components\n# waiting on owners to be assigned\n#\n#####################################################\n#\n# Learn about CODEOWNERS file format:\n#  https://help.github.com/en/articles/about-code-owners\n#\n\n## \n# NOTE: New components MUST have one or more codeowners. Add codeowners to the component metadata.yaml and run make gengithub\n##\n\n## COMMON & SHARED components\ninternal/common\n\n## DEPRECATED components\n# Start deprecated components list\n\n\n\n# End deprecated components list\n\n## UNMAINTAINED components\n\n# Start unmaintained components list\n\n\n\n# End unmaintained components list\n"
  },
  {
    "path": ".github/CODEOWNERS",
    "content": "# Code generated by githubgen. DO NOT EDIT.\n#####################################################\n#\n# List of codeowners\n#\n#####################################################\n#\n# Learn about CODEOWNERS file format:\n# https://help.github.com/en/articles/about-code-owners\n#\n\n* @open-telemetry/collector-approvers\n\n# Files owned by collector-releases-approvers\n.github/workflows/prepare-release.yml    @open-telemetry/collector-approvers @open-telemetry/collector-releases-approvers\n.github/workflows/sourcecode-release.yml @open-telemetry/collector-approvers @open-telemetry/collector-releases-approvers\n.github/workflows/scripts/release-*.sh   @open-telemetry/collector-approvers @open-telemetry/collector-releases-approvers\n\n# Start components list\n\ncmd/builder/                                 @open-telemetry/collector-approvers @ArthurSens @dmathieu\ncmd/mdatagen/                                @open-telemetry/collector-approvers @dmitryax\ncmd/mdatagen/internal/sampleconnector/       @open-telemetry/collector-approvers\ncmd/mdatagen/internal/sampleentityreceiver/  @open-telemetry/collector-approvers @dmitryax\ncmd/mdatagen/internal/samplefactoryreceiver/ @open-telemetry/collector-approvers @dmitryax\ncmd/mdatagen/internal/sampleprocessor/       @open-telemetry/collector-approvers\ncmd/mdatagen/internal/samplereceiver/        @open-telemetry/collector-approvers @dmitryax\ncmd/mdatagen/internal/samplescraper/         @open-telemetry/collector-approvers @dmitryax\nconfig/configauth/                           @open-telemetry/collector-approvers\nconfig/configcompression/                    @open-telemetry/collector-approvers\nconfig/configgrpc/                           @open-telemetry/collector-approvers\nconfig/confighttp/                           @open-telemetry/collector-approvers\nconfig/configmiddleware/                     @open-telemetry/collector-approvers\nconfig/confignet/                            @open-telemetry/collector-approvers\nconfig/configopaque/                         @open-telemetry/collector-approvers\nconfig/configoptional/                       @open-telemetry/collector-approvers\nconfig/configretry/                          @open-telemetry/collector-approvers\nconfig/configtelemetry/                      @open-telemetry/collector-approvers\nconfig/configtls/                            @open-telemetry/collector-approvers\nconfmap/                                     @open-telemetry/collector-approvers @mx-psi @evan-bradley\nconfmap/provider/envprovider/                @open-telemetry/collector-approvers\nconfmap/provider/fileprovider/               @open-telemetry/collector-approvers\nconfmap/provider/httpprovider/               @open-telemetry/collector-approvers\nconfmap/provider/httpsprovider/              @open-telemetry/collector-approvers\nconfmap/provider/yamlprovider/               @open-telemetry/collector-approvers\nconnector/forwardconnector/                  @open-telemetry/collector-approvers\nconnector/xconnector/                        @open-telemetry/collector-approvers @mx-psi @dmathieu\nconsumer/consumererror/xconsumererror/       @open-telemetry/collector-approvers\nconsumer/xconsumer/                          @open-telemetry/collector-approvers @mx-psi @dmathieu\ndocs/rfcs/                                   @open-telemetry/collector-approvers @codeboten @bogdandrutu @dmitryax @mx-psi\nexporter/debugexporter/                      @open-telemetry/collector-approvers @andrzej-stencel\nexporter/exporterhelper/                     @open-telemetry/collector-approvers @bogdandrutu @dmitryax\nexporter/exporterhelper/internal/queuebatch/ @open-telemetry/collector-approvers\nexporter/exporterhelper/xexporterhelper/     @open-telemetry/collector-approvers @mx-psi @dmathieu\nexporter/nopexporter/                        @open-telemetry/collector-approvers @evan-bradley\nexporter/otlpexporter/                       @open-telemetry/collector-approvers\nexporter/otlphttpexporter/                   @open-telemetry/collector-approvers\nexporter/xexporter/                          @open-telemetry/collector-approvers @mx-psi @dmathieu\nextension/memorylimiterextension/            @open-telemetry/collector-approvers\nextension/xextension/                        @open-telemetry/collector-approvers\nextension/xextension/storage/                @open-telemetry/collector-approvers @swiatekm\nextension/zpagesextension/                   @open-telemetry/collector-approvers\notelcol/                                     @open-telemetry/collector-approvers\npdata/                                       @open-telemetry/collector-approvers @bogdandrutu @dmitryax\npdata/pprofile/                              @open-telemetry/collector-approvers @mx-psi @dmathieu\npdata/xpdata/                                @open-telemetry/collector-approvers\nprocessor/batchprocessor/                    @open-telemetry/collector-approvers\nprocessor/memorylimiterprocessor/            @open-telemetry/collector-approvers\nprocessor/processorhelper/                   @open-telemetry/collector-approvers\nprocessor/xprocessor/                        @open-telemetry/collector-approvers @mx-psi @dmathieu\nreceiver/nopreceiver/                        @open-telemetry/collector-approvers @evan-bradley\nreceiver/otlpreceiver/                       @open-telemetry/collector-approvers\nreceiver/receiverhelper/                     @open-telemetry/collector-approvers\nreceiver/xreceiver/                          @open-telemetry/collector-approvers @mx-psi @dmathieu\nscraper/                                     @open-telemetry/collector-approvers\nscraper/xscraper                             @open-telemetry/collector-approvers\nscraper/scraperhelper/                       @open-telemetry/collector-approvers\nscraper/scraperhelper/xscraperhelper         @open-telemetry/collector-approvers\nservice/                                     @open-telemetry/collector-approvers\nservice/internal/graph/                      @open-telemetry/collector-approvers\n\n# End components list\n\n#####################################################\n#\n# List of distribution maintainers\n#\n#####################################################\n\n# Start distribution list\n\nreports/distributions/core.yaml    @open-telemetry/collector-approvers\nreports/distributions/contrib.yaml @open-telemetry/collector-approvers\nreports/distributions/k8s.yaml     @open-telemetry/collector-approvers\nreports/distributions/otlp.yaml    @open-telemetry/collector-approvers\n\n# End distribution list\n\n#####################################################\n#\n## UNMAINTAINED components\n#\n#####################################################\n\n# Start unmaintained components list\n\n\n\n# End unmaintained components list\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.yaml",
    "content": "name: Bug report\ndescription: Create a report to help us improve\nlabels: [\"bug\"]\nbody:\n  - type: markdown\n    attributes:\n      value: |\n        Thanks for taking the time to fill out this bug report! Please make sure to fill out the entire form below, providing as much context as you can in order to help us triage and track down your bug as quickly as possible.\n\n        Before filing a bug, please be sure you have searched through [existing bugs](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc+label%3Abug) to see if an existing issue covers your bug.\n  - type: dropdown\n    id: component\n    attributes:\n      label: Component(s)\n      description: Which component(s) does your bug report concern?\n      multiple: true\n      options:\n      # NOTE: The list below is autogenerated using `make generate-gh-issue-templates`\n      # Do not manually edit it.\n      # Start components list\n      - cmd/builder\n      - cmd/mdatagen\n      - cmd/mdatagen/internal/sampleconnector\n      - cmd/mdatagen/internal/samplefactoryreceiver\n      - cmd/mdatagen/internal/sampleprocessor\n      - cmd/mdatagen/internal/samplereceiver\n      - cmd/mdatagen/internal/samplescraper\n      - config/configauth\n      - config/configcompression\n      - config/configgrpc\n      - config/confighttp\n      - config/configmiddleware\n      - config/confignet\n      - config/configopaque\n      - config/configoptional\n      - config/configretry\n      - config/configtelemetry\n      - config/configtls\n      - confmap\n      - confmap/provider/envprovider\n      - confmap/provider/fileprovider\n      - confmap/provider/httpprovider\n      - confmap/provider/httpsprovider\n      - confmap/provider/yamlprovider\n      - connector/forward\n      - connector/x\n      - consumer/consumererror/xconsumererror\n      - consumer/xconsumer\n      - docs/rfcs\n      - exporter/debug\n      - exporter/exporterhelper\n      - exporter/exporterhelper/internal/queuebatch\n      - exporter/exporterhelper/xexporterhelper\n      - exporter/nop\n      - exporter/otlp\n      - exporter/otlp_http\n      - exporter/x\n      - extension/memorylimiter\n      - extension/x\n      - extension/x/storage\n      - extension/zpages\n      - otelcol\n      - pdata\n      - pdata/pprofile\n      - pdata/xpdata\n      - processor/batch\n      - processor/memorylimiter\n      - processor/processorhelper\n      - processor/x\n      - receiver/nop\n      - receiver/otlp\n      - receiver/receiverhelper\n      - receiver/x\n      - scraper\n      - scraper/scraperhelper\n      - scraper/scraperhelper/xscraperhelper\n      - scraper/xscraper\n      - service\n      - service/internal/graph\n      # End components list\n  - type: textarea\n    attributes:\n      label: What happened?\n      description: Please provide as much detail as you reasonably can.\n      value: |\n        **Describe the bug**\n        <!-- A clear and concise description of what the bug is. -->\n        \n        **Steps to reproduce**\n        <!-- If possible, provide a recipe for reproducing the error. -->\n        \n        **What did you expect to see?**\n        <!-- A clear and concise description of what you expected to see. -->\n        \n        **What did you see instead?**\n        <!-- A clear and concise description of what you saw instead. -->\n\n    validations:\n      required: true\n  - type: input\n    attributes:\n      label: Collector version\n      description: What version did you use? (e.g., `v0.4.0`, `1eb551b`, etc)\n    validations:\n      required: true\n  - type: textarea\n    attributes:\n      label: Environment information\n      description: Please provide any additional information about your installation.\n      value: |\n        ## Environment\n        OS: (e.g., \"Ubuntu 20.04\")\n        Compiler(if manually compiled): (e.g., \"go 14.2\")\n\n  - type: textarea\n    attributes:\n      label: OpenTelemetry Collector configuration\n      description: Please provide the configuration you are using (e.g. the YAML config file).\n      placeholder: | # Empty Collector config\n        receivers:\n        exporters:\n        processors:\n        extensions:\n        service:\n          pipelines:\n            traces:\n              receivers: []\n              exporters: []\n              processors: []\n            metrics:\n              receivers: []\n              exporters: []\n              processors: []\n            logs:\n              receivers: []\n              exporters: []\n              processors: []\n      render: yaml\n  - type: textarea\n    attributes:\n      label: Log output\n      description: |\n        Please copy and paste any relevant log output.\n      render: shell\n  - type: textarea\n    attributes:\n      label: Additional context\n      description: Any additional information you think may be relevant to this issue.\n  - type: dropdown\n    attributes:\n      label: Tip\n      description: This element is static, used to render a helpful sub-heading for end-users and community members to help prioritize issues. Please leave as is.\n      options:\n        - <sub>[React](https://github.blog/news-insights/product-news/add-reactions-to-pull-requests-issues-and-comments/) with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding `+1` or `me too`, to help us triage it. Learn more [here](https://opentelemetry.io/community/end-user/issue-participation/).</sub>\n      default: 0\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/component-graduation.md",
    "content": "---\nname: Component Graduation\nabout: Graduate a component from beta to stable\ntitle: 'Graduate component X to stable'\nlabels: 'graduation'\nassignees: ''\n---\n\nThis issue requests the graduation of a component to stable. Please review the [Component Graduation to Stable](https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#component-graduation-to-stable) documentation for full details.\n\n## Component Information\n\n- **Component name**: <!-- e.g., otlpreceiver -->\n- **Component type**: <!-- receiver/processor/exporter/connector/extension -->\n- **Repository**: <!-- e.g., opentelemetry-collector or opentelemetry-collector-contrib -->\n\n## Signal Requirements\n\n- [ ] All supported signals for signal types that are stable in the OpenTelemetry specification are at beta stability or higher\n- [ ] At least one signal is at stable stability\n\n## Code Owner Requirements\n\n- [ ] The component has at least three active code owners\n- [ ] Within the 60 days prior to this request, the code owners have reviewed and replied to at least 80% of the issues and pull requests opened against the component\n\nList the current code owners:\n1. <!-- @username -->\n2. <!-- @username -->\n3. <!-- @username -->\n\n## Technical Requirements\n\n- [ ] The component meets all [testing requirements](https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#testing-requirements) for stable components\n- [ ] The component meets all [documentation requirements](https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#documentation-requirements) for stable components\n- [ ] The component meets all [observability requirements](https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#observability-requirements) for stable components\n- [ ] The component follows the [coding guidelines](https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/coding-guidelines.md), including naming conventions\n\nPlease provide links to evidence:\n- **Test coverage report**: <!-- link -->\n- **Benchmark results**: <!-- link -->\n- **Documentation**: <!-- link to component README -->\n\n## Adoption Evidence\n\nThe component must have evidence of real-world adoption. Provide at least one of the following:\n\n### Option 1: Public Adopter Testimonials\nAt least two organizations have publicly stated they use the component in production.\n\n- [ ] Adopter 1: <!-- Link to blog post, conference talk, GitHub issue, vendor documentation or other public statement -->\n- [ ] Adopter 2: <!-- Link to blog post, conference talk, GitHub issue, vendor documentation or other public statement -->\n\n### Option 2: Private Attestation\nIf adopters cannot be named publicly, provide private attestation to the assigned maintainer.\n\n- [ ] Private attestation provided to maintainer\n\nThe attestation must include a general description of the scale of usage (e.g., \"processing millions of spans per day\").\n\n---\n\n## For Maintainers\n\nA maintainer will be assigned on a rotating basis to verify this graduation request.\n\n- [ ] Maintainer assigned: <!-- @username -->\n- [ ] All requirements verified\n- [ ] Adoption evidence verified as credible\n\nOnce verified, the code owners should open a PR to update the component's stability level.\n\n<sub>**Tip**: [React](https://github.blog/news-insights/product-news/add-reactions-to-pull-requests-issues-and-comments/) with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding `+1` or `me too`, to help us triage it. Learn more [here](https://opentelemetry.io/community/end-user/issue-participation/).</sub>\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature_request.yaml",
    "content": "name: Feature request\ndescription: Suggest an idea for this project\nlabels: [\"feature request\"]\nbody:\n  - type: dropdown\n    id: component\n    attributes:\n      label: Component(s)\n      description: Which component(s) does your feature request concern?\n      multiple: true\n      options:\n      # NOTE: The list below is autogenerated using `make generate-gh-issue-templates`\n      # Do not manually edit it.\n      # Start components list\n      - cmd/builder\n      - cmd/mdatagen\n      - cmd/mdatagen/internal/sampleconnector\n      - cmd/mdatagen/internal/samplefactoryreceiver\n      - cmd/mdatagen/internal/sampleprocessor\n      - cmd/mdatagen/internal/samplereceiver\n      - cmd/mdatagen/internal/samplescraper\n      - config/configauth\n      - config/configcompression\n      - config/configgrpc\n      - config/confighttp\n      - config/configmiddleware\n      - config/confignet\n      - config/configopaque\n      - config/configoptional\n      - config/configretry\n      - config/configtelemetry\n      - config/configtls\n      - confmap\n      - confmap/provider/envprovider\n      - confmap/provider/fileprovider\n      - confmap/provider/httpprovider\n      - confmap/provider/httpsprovider\n      - confmap/provider/yamlprovider\n      - connector/forward\n      - connector/x\n      - consumer/consumererror/xconsumererror\n      - consumer/xconsumer\n      - docs/rfcs\n      - exporter/debug\n      - exporter/exporterhelper\n      - exporter/exporterhelper/internal/queuebatch\n      - exporter/exporterhelper/xexporterhelper\n      - exporter/nop\n      - exporter/otlp_grpc\n      - exporter/otlp_http\n      - exporter/x\n      - extension/memorylimiter\n      - extension/x\n      - extension/x/storage\n      - extension/zpages\n      - otelcol\n      - pdata\n      - pdata/pprofile\n      - pdata/xpdata\n      - processor/batch\n      - processor/memorylimiter\n      - processor/processorhelper\n      - processor/x\n      - receiver/nop\n      - receiver/otlp\n      - receiver/receiverhelper\n      - receiver/x\n      - scraper\n      - scraper/scraperhelper\n      - scraper/scraperhelper/xscraperhelper\n      - scraper/xscraper\n      - service\n      - service/internal/graph\n      # End components list\n  - type: textarea\n    attributes:\n      label: Is your feature request related to a problem? Please describe.\n      description: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]. We are currently preparing for the upcoming 1.0 GA release. Feature requests that are not aligned with the current roadmap and are not aimed at stabilizing and preparing the Collector for the release will not be prioritized.\n    validations:\n      required: true\n  - type: textarea\n    attributes:\n      label: Describe the solution you'd like\n      description: A clear and concise description of what you want to happen.\n    validations:\n      required: true\n  - type: textarea\n    attributes:\n      label: Describe alternatives you've considered\n      description: A clear and concise description of any alternative solutions or features you've considered.\n  - type: textarea\n    attributes:\n      label: Additional context\n      description: Add any other context or screenshots about the feature request here.\n  - type: dropdown\n    attributes:\n      label: Tip\n      description: This element is static, used to render a helpful sub-heading for end-users and community members to help prioritize issues. Please leave as is.\n      options:\n        - <sub>[React](https://github.blog/news-insights/product-news/add-reactions-to-pull-requests-issues-and-comments/) with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding `+1` or `me too`, to help us triage it. Learn more [here](https://opentelemetry.io/community/end-user/issue-participation/).</sub>\n      default: 0\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/other.yaml",
    "content": "name: Other issue\ndescription: Create a new issue to help us improve the collector\nbody:\n  - type: dropdown\n    id: component\n    attributes:\n      label: Component(s)\n      description: Which component(s) does your issue concern?\n      multiple: true\n      options:\n      # NOTE: The list below is autogenerated using `make generate-gh-issue-templates`\n      # Do not manually edit it.\n      # Start components list\n      - cmd/builder\n      - cmd/mdatagen\n      - cmd/mdatagen/internal/sampleconnector\n      - cmd/mdatagen/internal/samplefactoryreceiver\n      - cmd/mdatagen/internal/sampleprocessor\n      - cmd/mdatagen/internal/samplereceiver\n      - cmd/mdatagen/internal/samplescraper\n      - config/configauth\n      - config/configcompression\n      - config/configgrpc\n      - config/confighttp\n      - config/configmiddleware\n      - config/confignet\n      - config/configopaque\n      - config/configoptional\n      - config/configretry\n      - config/configtelemetry\n      - config/configtls\n      - confmap\n      - confmap/provider/envprovider\n      - confmap/provider/fileprovider\n      - confmap/provider/httpprovider\n      - confmap/provider/httpsprovider\n      - confmap/provider/yamlprovider\n      - connector/forward\n      - connector/x\n      - consumer/consumererror/xconsumererror\n      - consumer/xconsumer\n      - docs/rfcs\n      - exporter/debug\n      - exporter/exporterhelper\n      - exporter/exporterhelper/internal/queuebatch\n      - exporter/exporterhelper/xexporterhelper\n      - exporter/nop\n      - exporter/otlp_grpc\n      - exporter/otlp_http\n      - exporter/x\n      - extension/memorylimiter\n      - extension/x\n      - extension/x/storage\n      - extension/zpages\n      - otelcol\n      - pdata\n      - pdata/pprofile\n      - pdata/xpdata\n      - processor/batch\n      - processor/memorylimiter\n      - processor/processorhelper\n      - processor/x\n      - receiver/nop\n      - receiver/otlp\n      - receiver/receiverhelper\n      - receiver/x\n      - scraper\n      - scraper/scraperhelper\n      - scraper/scraperhelper/xscraperhelper\n      - scraper/xscraper\n      - service\n      - service/internal/graph\n      # End components list\n  - type: textarea\n    attributes:\n      label: Describe the issue you're reporting\n      description: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]\n    validations:\n      required: true\n  - type: dropdown\n    attributes:\n      label: Tip\n      description: This element is static, used to render a helpful sub-heading for end-users and community members to help prioritize issues. Please leave as is.\n      options:\n        - <sub>[React](https://github.blog/news-insights/product-news/add-reactions-to-pull-requests-issues-and-comments/) with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding `+1` or `me too`, to help us triage it. Learn more [here](https://opentelemetry.io/community/end-user/issue-participation/).</sub>\n      default: 0\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/stabilization.md",
    "content": "---\nname: Module stabilization\nabout: Stabilize a module before a 1.0 release\ntitle: 'Stabilize module X'\nlabels: 'stabilization'\nassignees: ''\n---\n\nBefore stabilizing a module, an approver or maintainer must make sure that the following criteria have been met for at least two successive minor version releases (regardless of when this issue was opened):\n\n- [ ] No open issues or PRs in the module that would require breaking changes\n- [ ] No TODOs in the module code that would require breaking changes\n- [ ] No deprecated symbols in the module\n- [ ] No symbols marked as experimental in the module\n- [ ] The module follows the [Coding guidelines](https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/coding-guidelines.md)\n\nPlease also make sure to publicly announce our intent to stabilize the module on:\n\n- [ ] The #otel-collector CNCF Slack Channel\n- [ ] The #opentelemetry CNCF Slack channel\n- [ ] A Collector SIG meeting (if unable to attend, just add to the agenda)\n\nTo help other people verify the above criteria, please link to the announcement and other links used to complete the above in a comment on this issue.\n\nOnce all criteria are met, close this issue by moving this module to the `stable` module set.\n\n<sub>**Tip**: [React](https://github.blog/news-insights/product-news/add-reactions-to-pull-requests-issues-and-comments/) with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding `+1` or `me too`, to help us triage it. Learn more [here](https://opentelemetry.io/community/end-user/issue-participation/).</sub>\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/vote.md",
    "content": "---\nname: Vote\nabout: Vote to make a decision related to an RFC \ntitle: '[Vote] RFC #XXXX:'\nlabels: \"rfc:vote-needed\"\nassignees: ''\n---\n\nA [vote](https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/rfcs/README.md#voting) has been called for RFC #XXXX following the RFC process.\n\n### Stakeholders\n\nAny person in the community may vote. Votes of the stakeholders are binding. Stakeholders are\nencouraged to consider the views from the wider community when casting their vote. As defined in the\nRFC, there are N stakeholders for this RFC divided as follows:\n\n| Stakeholders                        | As defined on date | Number of people |\n|-------------------------------------|--------------------|------------------|\n| @open-telemetry/collector-approvers | yyyy-mm-dd         | N                |\n\n<!--Add additional rows if there are additional stakeholders for the RFC-->\n\nFor any stakeholder team, we consider the people that were part of the team at the time the vote is called.\n\n### Voting options\n\n| Option | Description | # Votes (stakeholders) | # Votes (total) |\n|--------|-------------|------------------------|-----------------|\n| Option 1 | Description of the option | 0 | 0 |\n\n<!--Add additional rows if there are additional options for the RFC-->\n\n### Result\n\nThe vote is in progress. A minimum of X votes is required to select an option.\n\n<!--Uncomment the sentence below when the vote has been closed and the result is known.-->\n<!--The vote has been closed. X stakeholders voted out of a total of Y. **Option N** has been selected with Z votes from the stakeholders.-->\n\n### Vote process\n\nPlease **leave a comment** with your vote and any additional context you would like to provide.\nStart your comment with \"I vote for **Option N**.\" and then provide any additional context.\n\n### Related links\n\nInclude here any links to the RFC, other PRs and resources that help make an informed vote.\n\n### Checklists\n\nWhen starting the vote:\n\n- [ ] Announce the vote in the #otel-collector-dev CNCF Slack channel.\n- [ ] Add an entry to announce the vote in the next Collector SIG meeting.\n\nFor closing the vote:\n\n- [ ] At least five business days have passed since the vote was announced.\n- [ ] At least one-third of the stakeholders have voted.\n- [ ] The \"Voting options\" and \"Result\" sections have been updated reflecting the votes casted.\n- [ ] The RFC has been updated reflecting the votes casted.\n\n<sub>**Tip**: [React](https://github.blog/news-insights/product-news/add-reactions-to-pull-requests-issues-and-comments/) with 👍 to help prioritize this issue. Please use comments to provide useful context, avoiding `+1` or `me too`, to help us triage it. Learn more [here](https://opentelemetry.io/community/end-user/issue-participation/).</sub>\n"
  },
  {
    "path": ".github/actionlint.yaml",
    "content": "self-hosted-runner:\n  labels: []\n\nconfig-variables: null\n\npaths:\n  .github/workflows/**/*.{yml,yaml}:\n    ignore:\n      # SC1070: Suppressing because scripts intentionally contain valid but unusual characters,\n      # Escape characters like `\\o` used purposefully, and tested for clarity\n      - '.*shellcheck reported issue in this script: SC1070:.+'\n\n      # SC1133: ShellCheck suggests optimizing conditional expressions, but these scripts\n      # operate correctly and readability is prioritized in real-world use. This ensures familiarity for contributors.\n      - '.*shellcheck reported issue in this script: SC1133:.+'\n\n      # SC2086: Ignored because word splitting is intentional in commands like `git diff`,\n      # where simple, predictable paths are passed as arguments. No unintended globbing occurs in this context.\n      - '.*shellcheck reported issue in this script: SC2086:.+'\n\n      # SC2046: Suppressed because word splitting is desired and necessary in certain scenarios,\n      # PR_HEAD is set by GitHub Actions and paths are fixed/controlled.\n      - '.*shellcheck reported issue in this script: SC2046:.+'\n\n      # SC2059: Format strings in `printf` are deliberately designed and controlled for specific outputs.\n      # ShellCheck’s safeguard warning is appreciated but not critical in these cases.\n      - '.*shellcheck reported issue in this script: SC2059:.+'\n\n      # SC2236: Both `! -z` and `-n` achieve the same result, and while `-n` is idiomatic. (Just a style suggestion)\n      # suppressing this warning allows scripts to remain consistent with existing standards.\n      - '.*shellcheck reported issue in this script: SC2236:.+'\n\n      # SC1001: Escaped characters (like `\\o`) are deliberate in certain scripts for expected functionality.\n      # ShellCheck’s flagging of these characters as potential issues isn’t applicable to this use case.\n      - '.*shellcheck reported issue in this script: SC1001:.+'\n\n      # SC2129: Individual redirections are chosen for simplicity and clarity in the workflows.\n      # combining them is technically efficient, the current approach ensures more readable scripts.\n      - '.*shellcheck reported issue in this script: SC2129:.+'\n\n      # Runner warnings ignored because scripts are validated against specific configurations\n      # and tested on GitHub Actions, ensuring compatibility. These warnings do not affect functionality.\n      - '.*the runner of \".+\" action is too old to run on GitHub Actions.+'\n\n"
  },
  {
    "path": ".github/lychee.toml",
    "content": "include_fragments = true\n\naccept = [\"200..=299\", \"429\"]\n\nexclude  = [\n    \"^http(s)?://localhost\",\n    \"^http(s)?://example.com\"\n]\n"
  },
  {
    "path": ".github/pull_request_template.md",
    "content": "<!--Ex. Fixing a bug - Describe the bug and how this fixes the issue.\nEx. Adding a feature - Explain what this achieves.-->\n#### Description\n\n<!-- Issue number if applicable -->\n#### Link to tracking issue\nFixes #\n\n<!--Describe what testing was performed and which tests were added.-->\n#### Testing\n\n<!--Describe the documentation added.-->\n#### Documentation\n\n<!--Please delete paragraphs that you did not use before submitting.-->\n"
  },
  {
    "path": ".github/workflows/add-labels-and-owners.yml",
    "content": "name: 'Add labels and code owners to PR'\non:\n  pull_request_target:\n    types:\n      - opened\n      - synchronize\n      - ready_for_review\n\npermissions: read-all\n\njobs:\n  add-labels-and-owners:\n    permissions:\n      pull-requests: write\n    runs-on: ubuntu-24.04\n    if: ${{ github.actor != 'dependabot[bot]' && github.actor != 'renovate[bot]' && github.repository_owner == 'open-telemetry' && github.event.pull_request.draft == false }}\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n\n      - name: Run add-codeowners-to-pr.sh\n        run: ./.github/workflows/scripts/add-labels-and-owners.sh\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          REPO: ${{ github.repository }}\n          PR: ${{ github.event.number }}\n"
  },
  {
    "path": ".github/workflows/add-labels-command.yml",
    "content": "name: 'Add Labels'\non:\n  issue_comment:\n    types: [created]\n\npermissions: read-all\n\njobs:\n  add-labels-command:\n    if: ${{ !github.event.issue.pull_request && startsWith(github.event.comment.body, '/label') && github.repository_owner == 'open-telemetry' }}\n    permissions:\n      issues: write\n\n    runs-on: ubuntu-24.04\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n\n      - name: Run add-labels-command.sh\n        run: ./.github/workflows/scripts/add-labels-command.sh\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          ISSUE: ${{ github.event.issue.number }}\n          COMMENT: ${{ github.event.comment.body }}\n          SENDER: ${{ github.event.sender.login }}\n"
  },
  {
    "path": ".github/workflows/api-compatibility.yml",
    "content": "# This GitHub action is used to compare API state snapshots of Main\n# to Head of the PR in order to validate releases are not breaking\n# backwards compatibility.\n#\n# This GitHub action will fail if there are incompatible changes.\n#\nname: \"Inform Incompatible PRs\"\non:\n  pull_request:\n    branches:\n      - main\n\npermissions: read-all\n\njobs:\n  Check-Compatibility:\n    runs-on: ubuntu-latest\n    env:\n      BASE_REF: ${{ github.base_ref }}\n      HEAD_REF: ${{ github.head_ref }}\n    steps:\n      - name: Checkout-Main\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          ref: ${{ github.base_ref }}\n          path: ${{ github.base_ref }}\n\n      - name: Checkout-HEAD\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          path: ${{ github.head_ref }}\n\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: oldstable\n          cache: false\n\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n\n      # Generate apidiff states of Main\n      - name: Generate-States\n        run: |\n          cd $BASE_REF\n          make apidiff-build\n\n      # Compare apidiff states of Main with PR\n      - name: Compare-States\n        env:\n          CI: true\n          COMPARE_OPTS: -d \"../${{ github.base_ref }}/internal/data/apidiff\"\n        run: |\n          cd $HEAD_REF\n          make apidiff-compare\n\n      # Fail GitHub Action if there are incompatible changes\n      - name: Check-States\n        env:\n          CI: true\n          COMPARE_OPTS: -d \"../${{ github.base_ref }}/internal/data/apidiff\" -c\n        run: |\n          cd $HEAD_REF\n          make apidiff-compare\n"
  },
  {
    "path": ".github/workflows/build-and-test-arm.yml",
    "content": "name: build-and-test-arm\non:\n  push:\n    branches: [main]\n    tags:\n      - \"v[0-9]+.[0-9]+.[0-9]+*\"\n  merge_group:\n    types: [checks_requested]\n  pull_request:\nenv:\n  TEST_RESULTS: testbed/tests/results/junit/results.xml\n  # Make sure to exit early if cache segment download times out after 2 minutes.\n  # We limit cache download as a whole to 5 minutes.\n  SEGMENT_DOWNLOAD_TIMEOUT_MINS: 2\n\npermissions: read-all\n\n# Do not cancel this workflow on main. See https://github.com/open-telemetry/opentelemetry-collector-contrib/pull/16616\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref_name }}\n  cancel-in-progress: true\n\njobs:\n  arm-unittest-matrix:\n    strategy:\n      matrix:\n        os: [ubuntu-22.04-arm, macos-14]\n    if: ${{ github.actor != 'dependabot[bot]' && (contains(github.event.pull_request.labels.*.name, 'Run ARM') || github.event_name == 'push' || github.event_name == 'merge_group') }}\n    runs-on: ${{ matrix.os }}\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: oldstable\n          cache: false\n      - name: Cache Go\n        id: go-cache\n        timeout-minutes: 5\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n      - name: Install dependencies\n        if: steps.go-cache.outputs.cache-hit != 'true'\n        run: make gomoddownload\n      - name: Run Unit Tests\n        run: make -j4 gotest\n  arm-unittest:\n    if: ${{ github.actor != 'dependabot[bot]' && (contains(github.event.pull_request.labels.*.name, 'Run ARM') || github.event_name == 'push' || github.event_name == 'merge_group') }}\n    runs-on: ubuntu-latest\n    needs: [arm-unittest-matrix]\n    steps:\n      - name: Print result\n        run: echo ${{ needs.arm-unittest-matrix.result }}\n      - name: Interpret result\n        run: |\n          if [[ success == ${{ needs.arm-unittest-matrix.result }} ]]\n          then\n            echo \"All matrix jobs passed!\"\n          else\n            echo \"One or more matrix jobs failed.\"\n            false\n          fi\n"
  },
  {
    "path": ".github/workflows/build-and-test-windows.yaml",
    "content": "name: build-and-test-windows\non:\n  push:\n    branches: [main]\n    tags:\n      - \"v[0-9]+.[0-9]+.[0-9]+*\"\n  merge_group:\n    types: [checks_requested]\n  pull_request:\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref_name }}\n  cancel-in-progress: true\n\npermissions: read-all\n\njobs:\n  windows-unittest:\n    strategy:\n      fail-fast: false\n      matrix:\n        os: [windows-2022, windows-2025, windows-11-arm]\n    runs-on: ${{ matrix.os }}\n    steps:\n      - name: Checkout Repo\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: oldstable\n          cache: false\n      - name: Cache Go\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        env:\n          cache-name: cache-go-modules\n        with:\n          path: |\n            ~\\go\\pkg\\mod\n            ~\\AppData\\Local\\go-build\n          key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}\n      - name: Ensure required ports in the dynamic range are available\n        run: |\n          & ${{ github.workspace }}\\.github\\workflows\\scripts\\win-required-ports.ps1\n      - name: Run Unit Tests\n        run: make gotest\n\n  windows-service-test:\n    strategy:\n      fail-fast: false\n      matrix:\n        os: [windows-2022, windows-2025, windows-11-arm]\n    runs-on: ${{ matrix.os }}\n    steps:\n      - name: Checkout Repo\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: oldstable\n          cache: false\n      - name: Cache Go\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        env:\n          cache-name: cache-go-modules\n        with:\n          path: |\n            ~\\go\\pkg\\mod\n            ~\\AppData\\Local\\go-build\n          key: ${{ runner.os }}-go-${{ hashFiles('**/go.sum') }}\n      - name: Ensure required ports in the dynamic range are available\n        run: |\n          & ${{ github.workspace }}\\.github\\workflows\\scripts\\win-required-ports.ps1\n\n      - name: Make otelcorecol\n        run: make otelcorecol\n\n      - name: Install otelcorecol as a service\n        run: |\n          New-Service -Name \"otelcorecol\" -StartupType \"Manual\" -BinaryPathName \"${PWD}\\bin\\otelcorecol_windows_$(go env GOARCH) --config ${PWD}\\examples\\local\\otel-config.yaml\"\n          eventcreate.exe /t information /id 1 /l application /d \"Creating event provider for 'otelcorecol'\" /so otelcorecol\n\n      - name: Test otelcorecol service\n        working-directory: ${{ github.workspace }}/otelcol\n        run: |\n          go test -timeout 90s -run ^TestCollectorAsService$  -v -tags=win32service\n\n      - name: Remove otelcorecol service\n        if: always()\n        run: |\n          Remove-Service otelcorecol\n          Remove-Item HKLM:\\SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\otelcorecol\n"
  },
  {
    "path": ".github/workflows/build-and-test.yml",
    "content": "name: build-and-test\non:\n  push:\n    branches: [main]\n    tags:\n      - \"v[0-9]+.[0-9]+.[0-9]+*\"\n  merge_group:\n    types: [checks_requested]\n  pull_request:\n\npermissions: read-all\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref_name }}\n  cancel-in-progress: true\n\njobs:\n  setup-environment:\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout Repo\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: oldstable\n          cache: false\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n      - name: Install dependencies\n        if: steps.go-cache.outputs.cache-hit != 'true'\n        run: make gomoddownload\n\n  lint:\n    runs-on: ubuntu-latest\n    needs: [setup-environment]\n    steps:\n      - name: Checkout Repo\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: oldstable\n          cache: false\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n      - name: golint\n        run: make -j2 golint\n      - name: goimpi\n        run: make goimpi\n\n  govulncheck:\n    runs-on: ubuntu-latest\n    timeout-minutes: 30\n    needs: [setup-environment]\n    steps:\n      - name: Checkout Repo\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: oldstable\n          cache: false\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n      - name: Run `govulncheck`\n        run: make govulncheck\n\n  checks:\n    runs-on: ubuntu-latest\n    needs: [setup-environment]\n    steps:\n      - name: Checkout Repo\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: stable\n          cache: false\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n      - name: Setup Node\n        uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0\n        with:\n          node-version: \"24\"\n      - name: checklicense\n        run: make checklicense\n      - name: misspell\n        run: make misspell\n      - name: checkdoc\n        run: make checkdoc\n      - name: markdownlint\n        run: make markdownlint\n      - name: checkapi\n        run: make checkapi\n      - name: Check for go mod dependency changes\n        run: |\n          make gotidy\n          git diff --exit-code || (echo 'go.mod/go.sum deps changes detected, please run \"make gotidy\" and commit the changes in this PR.' && exit 1)\n      - name: go:porto\n        run: |\n          make goporto\n          git diff --exit-code || (echo 'Porto links are out of date, please run \"make goporto\" and commit the changes in this PR.' && exit 1)\n      - name: go:generate\n        run: |\n          make gogenerate\n          git diff --exit-code || (echo 'Generated code is out of date, please run \"make gogenerate\" and commit the changes in this PR.' && exit 1)\n      - name: Generate proto files\n        run: |\n          make genproto\n          git diff --exit-code || (echo 'Generated code is out of date, please run \"make genproto\" and commit the changes in this PR.' && exit 1)\n      - name: Gen Pdata\n        run: |\n          make genpdata\n          git diff --exit-code || (echo 'Generated code is out of date, please run \"make genpdata\" and commit the changes in this PR.' && exit 1)\n      - name: Gen otelcorecol\n        run: |\n          make genotelcorecol\n          git diff --exit-code || (echo 'Generated code is out of date, please run \"make genotelcorecol\" and commit the changes in this PR.' && exit 1)\n      - name: Multimod verify\n        run: make multimod-verify\n      - name: crosslink\n        run: |\n          make crosslink\n          git diff -s --exit-code || (echo 'Replace statements are out of date, please run \"make crosslink\" and commit the changes in this PR.' && exit 1)\n      - name: generate-chloggen-components\n        run: |\n          make generate-chloggen-components\n          git diff --exit-code || (echo '.chloggen/config.yaml is out of date, please run \"make generate-chloggen-components\" and commit the changes.' && exit 1)\n\n  unittest-matrix:\n    strategy:\n      matrix:\n        runner: [ubuntu-latest]\n        go-version: [\"stable\", \"oldstable\"]\n    runs-on: ${{ matrix.runner }}\n    needs: [setup-environment]\n    steps:\n      - name: Checkout Repo\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: ${{ matrix.go-version }}\n          cache: false\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n      - name: Cache Build\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: ~/.cache/go-build\n          key: unittest-${{ runner.os }}-${{ matrix.runner }}-go-build-${{ matrix.go-version }}-${{ hashFiles('**/go.sum') }}\n      - name: Run Unit Tests\n        run: |\n          make -j4 gotest-with-junit\n      - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0\n        with:\n          name: test-results-${{ runner.os }}-${{ matrix.runner }}-${{ matrix.go-version }}\n          path: internal/tools/testresults/\n          retention-days: 4\n  unittest:\n    if: always()\n    runs-on: ubuntu-latest\n    needs: [setup-environment, unittest-matrix]\n    steps:\n      - name: Print result\n        run: echo ${{ needs.unittest-matrix.result }}\n      - name: Interpret result\n        run: |\n          if [[ success == ${{ needs.unittest-matrix.result }} ]]\n          then\n            echo \"All matrix jobs passed!\"\n          else\n            echo \"One or more matrix jobs failed.\"\n            false\n          fi\n\n  test-coverage:\n    runs-on: ubuntu-latest\n    needs: [setup-environment]\n    steps:\n      - name: Checkout Repo\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: oldstable\n          cache: false\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n      - name: Cache Build\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: ~/.cache/go-build\n          key: coverage-${{ runner.os }}-go-build-${{ hashFiles('**/go.sum') }}\n      - name: Run Unit Tests With Coverage\n        run: make gotest-with-cover\n      - name: Upload coverage report\n        uses: codecov/codecov-action@671740ac38dd9b0130fbe1cec585b89eea48d3de # 5.5.2\n        env:\n          CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}\n\n  cross-build-collector:\n    needs: [setup-environment]\n    runs-on: ubuntu-latest\n    timeout-minutes: 10\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n          # Go 1.15 dropped support for 32-bit binaries\n          # on macOS: https://go.dev/doc/go1.15\n          #- goos: darwin\n          #  goarch: 386\n          - goos: aix\n            goarch: ppc64\n          - goos: darwin\n            goarch: amd64\n          - goos: darwin\n            goarch: arm64\n          - goos: js\n            goarch: wasm\n          - goos: linux\n            goarch: 386\n          - goos: linux\n            goarch: amd64\n          - goos: linux\n            goarch: arm64\n          - goos: linux\n            goarch: ppc64le\n          - goos: linux\n            goarch: riscv64\n          - goos: linux\n            goarch: arm\n            goarm: 7\n          - goos: linux\n            goarch: s390x\n          - goos: windows\n            goarch: 386\n          - goos: windows\n            goarch: amd64\n          - goos: windows\n            goarch: arm64\n\n    steps:\n      - name: Checkout Repo\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: oldstable\n          cache: false\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n      - name: Build\n        env:\n          GOOS: ${{matrix.goos}}\n          GOARCH: ${{matrix.goarch}}\n          GOARM: ${{matrix.goarm}}\n        run: |\n          make otelcorecol\n"
  },
  {
    "path": ".github/workflows/builder-integration-test.yaml",
    "content": "name: Builder - Integration tests\n\non:\n  # on changes to the main branch touching the builder\n  push:\n    branches: [main]\n\n  # on PRs touching the builder\n  pull_request:\n    branches: [main]\n\n  # once a day at 6:17 AM UTC\n  schedule:\n    - cron: \"17 6 * * *\"\n\n  # manual execution\n  workflow_dispatch:\n\n  merge_group:\n    types: [checks_requested]\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref_name }}\n  cancel-in-progress: true\n\npermissions: read-all\n\njobs:\n  integration-test:\n    name: Integration test\n    runs-on: ubuntu-latest\n    steps:\n      - name: Checkout Repo\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: oldstable\n          cache: false\n\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n\n      - name: Test\n        run: make builder-integration-test\n"
  },
  {
    "path": ".github/workflows/builder-snapshot.yaml",
    "content": "name: Builder - Snapshot build\non:\n  push:\n    branches: [main]\n\n  # on PRs touching the builder\n  pull_request:\n    branches: [main]\n    paths:\n      - \"cmd/builder/**\"\n\npermissions:\n  contents: read\n\nenv:\n  # renovate: datasource=github-tags depName=goreleaser-pro packageName=goreleaser/goreleaser-pro\n  GORELEASER_PRO_VERSION: v2.11.1\n\njobs:\n  snapshot:\n    runs-on: ubuntu-24.04\n    if: ${{ github.repository_owner == 'open-telemetry' }}\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          path: .core\n\n      - name: Pull the latest releases repo\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          path: opentelemetry-collector-releases\n          repository: open-telemetry/opentelemetry-collector-releases\n\n      - name: Copy release files\n        run: cp -R ./opentelemetry-collector-releases/cmd/builder/. ./.core/cmd/builder/\n\n      - uses: sigstore/cosign-installer@ba7bc0a3fef59531c69a25acd34668d6d3fe6f22 # v4.1.0\n\n      - uses: anchore/sbom-action/download-syft@57aae528053a48a3f6235f2d9461b05fbcb7366d # v0.23.1\n\n      - uses: docker/setup-qemu-action@ce360397dd3f832beb865e1373c09c0e9f86d70a # v4.0.0\n        with:\n          platforms: amd64,arm64,ppc64le,s390x,riscv64\n\n      - uses: docker/setup-buildx-action@4d04d5d9486b7bd6fa91e7baf45bbb4f8b9deedd # v4.0.0\n\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: stable\n          cache: false\n\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n\n      - name: Check GoReleaser\n        uses: goreleaser/goreleaser-action@ec59f474b9834571250b370d4735c50f8e2d1e29 # v7.0.0\n        with:\n          distribution: goreleaser-pro\n          version: ${{ env.GORELEASER_PRO_VERSION }}\n          args: check --verbose -f .core/cmd/builder/.goreleaser.yaml\n        env:\n          GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }}\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n\n      - name: Run GoReleaser\n        uses: goreleaser/goreleaser-action@ec59f474b9834571250b370d4735c50f8e2d1e29 # v7.0.0\n        with:\n          distribution: goreleaser-pro\n          version: ${{ env.GORELEASER_PRO_VERSION }}\n          args: --snapshot --clean -f .core/cmd/builder/.goreleaser.yaml --skip sign\n        env:\n          GORELEASER_KEY: ${{ secrets.GORELEASER_KEY }}\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          COSIGN_YES: false\n\n        # Only create an issue if the workflows fails on push to main branch\n      - name: File an issue if the workflow failed\n        if: failure() && github.ref == 'refs/heads/main'\n        run: |\n          template=$(cat <<'END'\n          [Link to job log](%s)\n          END\n          )\n          job_url=\"$(gh run view ${{ github.run_id }} -R ${{ github.repository }} --json jobs -q '.jobs[] | select(.name == \"snapshot\") | .url')\"\n          body=\"$(printf \"$template\" \"$job_url\")\"\n          gh issue create -R ${{ github.repository }} -t 'OCB snapshot workflow failed' -b \"$body\" -l 'ci-cd' -l 'area:builder'\n        env:\n          GH_TOKEN: ${{ github.token }}\n"
  },
  {
    "path": ".github/workflows/changelog.yml",
    "content": "# This action requires that any PR targeting the main branch should touch at\n# least one CHANGELOG file. If a CHANGELOG entry is not required, add the \"Skip\n# Changelog\" label to disable this action.\n\nname: changelog\n\non:\n  pull_request:\n    types: [opened, ready_for_review, synchronize, reopened, labeled, unlabeled, edited]\n    branches:\n      - main\n  merge_group:\n    types: [checks_requested]\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref_name }}\n  cancel-in-progress: true\n\npermissions: read-all\n\njobs:\n  changelog:\n    runs-on: ubuntu-latest\n    if: ${{ github.event_name == 'pull_request' && !contains(github.event.pull_request.labels.*.name, 'dependencies') && !contains(github.event.pull_request.labels.*.name, 'Skip Changelog') && !contains(github.event.pull_request.title, '[chore]') }}\n\n    env:\n      PR_HEAD: ${{ github.event.pull_request.head.sha }}\n    steps:\n      - name: Checkout Repo\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          fetch-depth: 0\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: oldstable\n          cache: false\n\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n\n      - name: Ensure no changes to the CHANGELOG.md or CHANGELOG-API.md\n        run: |\n          if [[ $(git diff --name-only $(git merge-base origin/main $PR_HEAD) $PR_HEAD ./CHANGELOG*.md) ]]\n          then\n          echo \"CHANGELOG.md and CHANGELOG-API.md should not be directly modified.\"\n            echo \"Please add a .yaml file to the ./.chloggen/ directory.\"\n            echo \"See CONTRIBUTING.md for more details.\"\n            echo \"Alternately, add either \\\"[chore]\\\" to the title of the pull request or add the \\\"Skip Changelog\\\" label if this job should be skipped.\"\n            false\n          else\n          echo \"CHANGELOG.md and CHANGELOG-API.md were not modified.\"\n          fi\n\n      - name: Ensure ./.chloggen/*.yaml addition(s)\n        run: |\n          if [[ 1 -gt $(git diff --diff-filter=A --name-only $(git merge-base origin/main $PR_HEAD) $PR_HEAD ./.chloggen | grep -c \\\\.yaml) ]]\n          then\n            echo \"No changelog entry was added to the ./.chloggen/ directory.\"\n            echo \"Please add a .yaml file to the ./.chloggen/ directory.\"\n            echo \"See CONTRIBUTING.md for more details.\"\n            echo \"Alternately, add either \\\"[chore]\\\" to the title of the pull request or add the \\\"Skip Changelog\\\" label if this job should be skipped.\"\n            false\n          else\n            echo \"A changelog entry was added to the ./.chloggen/ directory.\"\n          fi\n\n      - name: Validate ./.chloggen/*.yaml changes\n        run: |\n          make chlog-validate \\\n            || { echo \"New ./.chloggen/*.yaml file failed validation.\"; exit 1; }\n\n      # In order to validate any links in the yaml file, render the config to markdown\n      - name: Render .chloggen changelog entries\n        run: make chlog-preview > changelog_preview.md\n      - name: Link Checker\n        id: lychee\n        uses: lycheeverse/lychee-action@8646ba30535128ac92d33dfc9133794bfdd9b411 # v2.8.0\n        with:\n          args: \"--verbose --no-progress ./changelog_preview.md --config .github/lychee.toml\"\n          failIfEmpty: false\n"
  },
  {
    "path": ".github/workflows/check-codeowners.yaml",
    "content": "name: codeowners\non:\n  push:\n    branches: [main]\n    paths:\n      - \".github/CODEOWNERS\"\n      - \"**/metadata.yaml\"\n    tags:\n      - \"v[0-9]+.[0-9]+.[0-9]+*\"\n  pull_request_target:\n    paths:\n      - \".github/CODEOWNERS\"\n      - \"**/metadata.yaml\"\n    types:\n      - opened\n      - synchronize\n      - edited\n      - reopened\nenv:\n  # Make sure to exit early if cache segment download times out after 2 minutes.\n  # We limit cache download as a whole to 5 minutes.\n  SEGMENT_DOWNLOAD_TIMEOUT_MINS: 2\n\n# Do not cancel this workflow on main. See https://github.com/open-telemetry/opentelemetry-collector-contrib/pull/16616\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}\n  cancel-in-progress: true\n\npermissions: read-all\n\njobs:\n  check-codeowners:\n    timeout-minutes: 30\n    runs-on: ubuntu-24.04\n    if: ${{ github.actor != 'dependabot[bot]' && github.repository == 'open-telemetry/opentelemetry-collector' }}\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6\n\n      - uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6\n        id: go-setup\n        with:\n          go-version: oldstable\n          cache-dependency-path: \"**/*.sum\"\n\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6\n        with:\n          ref: ${{github.event.pull_request.head.ref}}\n          repository: ${{github.event.pull_request.head.repo.full_name}}\n          path: pr\n\n      - uses: actions/create-github-app-token@29824e69f54612133e76f7eaac726eef6c875baf # v2.2.1\n        id: otelbot-token\n        with:\n          app-id: ${{ vars.OTELBOT_APP_ID }}\n          private-key: ${{ secrets.OTELBOT_PRIVATE_KEY }}\n\n      # NOTE: the make command below intentionally uses the Makefile from the\n      # target branch, and not the PR checkout, since it runs with the\n      # pull_request_target event and has elevated permissions.\n      - name: Gen CODEOWNERS\n        run: |\n          GITHUB_TOKEN=${{ steps.otelbot-token.outputs.token }} GITHUBGEN_ARGS=\"-folder=./pr\" make generate-codeowners\n          git diff -s --exit-code || (echo 'Generated code is out of date, please run \"make generate-codeowners\" or apply this diff and commit the changes in this PR.' && git diff && exit 1)\n"
  },
  {
    "path": ".github/workflows/check-links.yaml",
    "content": "name: check-links\non:\n  push:\n    branches: [main]\n  pull_request:\n  merge_group:\n    types: [checks_requested]\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref_name }}\n  cancel-in-progress: true\n\npermissions: read-all\n\njobs:\n  changedfiles:\n    name: changed files\n    runs-on: ubuntu-latest\n    env:\n      PR_HEAD: ${{ github.event.pull_request.head.sha }}\n    outputs:\n      files: ${{ steps.changes.outputs.files }}\n    steps:\n      - name: Checkout Repo\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          fetch-depth: 0\n      - name: Get changed files\n        id: changes\n        run: |\n          files=$(git diff --name-only --diff-filter=ACMRTUXB $(git merge-base origin/main $PR_HEAD) $PR_HEAD | grep .md$ | xargs)\n\n          if [ -z \"$files\" ] && git diff --name-only $(git merge-base origin/main $PR_HEAD) $PR_HEAD | grep -q \"package.json\"; then\n            files=\"**/*.md\"\n          fi\n\n          echo \"files=$files\" >> $GITHUB_OUTPUT\n  check-links:\n    runs-on: ubuntu-latest\n    needs: changedfiles\n    if: ${{needs.changedfiles.outputs.files}}\n    steps:\n      - name: Checkout Repo\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          fetch-depth: 0\n\n      - name: Link Checker\n        id: lychee\n        uses: lycheeverse/lychee-action@8646ba30535128ac92d33dfc9133794bfdd9b411 # v2.8.0\n        with:\n          args: \"--verbose --no-progress ${{needs.changedfiles.outputs.files}} --config .github/lychee.toml\"\n          failIfEmpty: false\n"
  },
  {
    "path": ".github/workflows/check-merge-freeze.yml",
    "content": "name: Merge freeze\n\non:\n  pull_request:\n    types:\n      [\n        opened,\n        ready_for_review,\n        synchronize,\n        reopened,\n        labeled,\n        unlabeled,\n        enqueued,\n      ]\n    branches: [main]\n  merge_group:\n    types: [checks_requested]\n\npermissions: read-all\n\njobs:\n  check-merge-freeze:\n    name: Check\n    # This condition is to avoid blocking the PR causing the freeze in the first place.\n    if: |\n      (!startsWith(github.event.pull_request.title || github.event.merge_group.head_commit.message, '[chore] Prepare release')) ||\n      ((github.event.pull_request.user.login || github.event.merge_group.head_commit.author.name) != 'otelbot[bot]')\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          sparse-checkout: .github/workflows/scripts\n      - run: ./.github/workflows/scripts/check-merge-freeze.sh\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          REPO: open-telemetry/opentelemetry-collector\n"
  },
  {
    "path": ".github/workflows/codeql-analysis.yml",
    "content": "name: \"CodeQL Analysis\"\non:\n  push:\n    branches: [main]\n  pull_request:\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref_name }}\n  cancel-in-progress: true\n\npermissions: read-all\n\njobs:\n  CodeQL-Build:\n    permissions:\n      actions: read # for github/codeql-action/init to get workflow details\n      contents: read # for actions/checkout to fetch code\n      security-events: write # for github/codeql-action/autobuild to send a status report\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: oldstable\n          cache: false\n\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n\n      # Initializes the CodeQL tools for scanning.\n      - name: Initialize CodeQL\n        uses: github/codeql-action/init@0d579ffd059c29b07949a3cce3983f0780820c98 # v4.32.6\n        with:\n          languages: go\n\n      - name: Autobuild\n        uses: github/codeql-action/autobuild@0d579ffd059c29b07949a3cce3983f0780820c98 # v4.32.6\n\n      - name: Perform CodeQL Analysis\n        uses: github/codeql-action/analyze@0d579ffd059c29b07949a3cce3983f0780820c98 # v4.32.6\n"
  },
  {
    "path": ".github/workflows/contrib-tests.yml",
    "content": "name: contrib-tests\non:\n  push:\n    branches: [main]\n    tags:\n      - v[0-9]+.[0-9]+.[0-9]+.*\n  pull_request:\n    types: [opened, ready_for_review, synchronize, reopened, labeled, unlabeled]\n    branches: [main]\n  merge_group:\n    types: [checks_requested]\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.ref_name }}\n  cancel-in-progress: true\n\npermissions: read-all\n\njobs:\n  contrib-tests-prepare:\n    runs-on: ubuntu-latest\n    if: ${{ !contains(github.event.pull_request.labels.*.name, 'Skip Contrib Tests') }}\n    steps:\n      - name: Checkout Repo\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - name: Prepare Contrib Tests\n        run: |\n          contrib_path=/tmp/opentelemetry-collector-contrib\n          git clone --depth=1 https://github.com/open-telemetry/opentelemetry-collector-contrib.git $contrib_path\n          make CONTRIB_PATH=$contrib_path prepare-contrib\n      - uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0\n        with:\n          name: contrib\n          path: /tmp/opentelemetry-collector-contrib/\n          include-hidden-files: true\n\n  contrib-tests-matrix:\n    runs-on: ubuntu-latest\n    needs: [contrib-tests-prepare]\n    if: ${{ !contains(github.event.pull_request.labels.*.name, 'Skip Contrib Tests') }}\n    strategy:\n      fail-fast: false\n      matrix:\n        group:\n          - receiver-0\n          - receiver-1\n          - receiver-2\n          - receiver-3\n          - processor\n          - exporter-0\n          - exporter-1\n          - extension\n          - connector\n          - internal\n          - pkg\n          - cmd-0\n          - other\n    steps:\n      - name: Checkout Repo\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - name: Download contrib\n        uses: actions/download-artifact@70fc10c6e5e1ce46ad2ea6f2b72d43f7d47b13c3 # v8.0.0\n        with:\n          name: contrib\n          path: /tmp/contrib\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: oldstable\n          cache: false\n\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n\n      - name: Run tests\n        run: |\n          make CONTRIB_PATH=/tmp/contrib SKIP_RESTORE_CONTRIB=true GROUP=${{ matrix.group }} check-contrib\n\n  contrib_tests:\n    runs-on: ubuntu-latest\n    if: ${{ !contains(github.event.pull_request.labels.*.name, 'Skip Contrib Tests') }}\n    needs: [contrib-tests-matrix]\n    steps:\n      - name: Print result\n        run: echo ${{ needs.contrib-tests-matrix.result }}\n      - name: Interpret result\n        run: |\n          if [[ success == ${{ needs.contrib-tests-matrix.result }} ]]\n          then\n            echo \"All matrix jobs passed!\"\n          else\n            echo \"One or more matrix jobs failed.\"\n            false\n          fi\n"
  },
  {
    "path": ".github/workflows/fossa.yml",
    "content": "name: FOSSA scanning\n\non:\n  push:\n    branches:\n      - main\n\npermissions:\n  contents: read\n\njobs:\n  fossa:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n\n      - uses: fossas/fossa-action@c414b9ad82eaad041e47a7cf62a4f02411f427a0 # v1.8.0\n        with:\n          api-key: ${{secrets.FOSSA_API_KEY}}\n          team: OpenTelemetry\n"
  },
  {
    "path": ".github/workflows/go-benchmarks.yml",
    "content": "name: CodSpeed Benchmarks\n\non:\n  push:\n    branches:\n      - \"main\"\n  pull_request:\n  workflow_dispatch:\n\njobs:\n  benchmarks:\n    name: Run benchmarks\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        group:\n          - receiver\n          - processor\n          - exporter\n          - pkg\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - run: ./.github/workflows/scripts/free-disk-space.sh\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: stable\n          cache: true\n          \n      - name: Calculate Modules\n        id: calc\n        run: |\n          if [ \"${{ matrix.group }}\" == \"root\" ]; then\n            echo \"TARGET_MODULES=$(pwd)\" >> $GITHUB_ENV\n          else\n            MODULES=$(find ./${{ matrix.group }} -mindepth 1 -maxdepth 2 -type f -name \"go.mod\" -exec dirname {} \\; 2>/dev/null | sort | xargs echo -n || true)\n            if [ -z \"$MODULES\" ]; then\n              echo \"SKIP_BENCH=true\" >> $GITHUB_ENV\n              echo \"No Go modules found in ${{ matrix.group }}, skipping this job.\"\n            else\n              echo \"TARGET_MODULES=$MODULES\" >> $GITHUB_ENV\n            fi\n          fi\n\n      - name: Run the benchmarks\n        if: env.SKIP_BENCH != 'true'\n        uses: CodSpeedHQ/action@281164b0f014a4e7badd2c02cecad9b595b70537 # v4.11.1\n        with:\n          mode: walltime\n          run: make for-all-target TARGET=\"timebenchmark\" GOMODULES=\"${{ env.TARGET_MODULES }}\"\n          cache-instruments: true\n"
  },
  {
    "path": ".github/workflows/lint-workflow-files.yml",
    "content": "name: Lint GitHub Workflow YAML Files\n\non:\n  push:\n    branches:\n      - main\n  pull_request:\n    paths:\n      - '.github/workflows/*.yml'\n      - '.github/workflows/*.yaml'\n      - '.github/actionlint.yaml'\n\npermissions:\n  contents: read\n\njobs:\n  lint:\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout code\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n\n      - name: Set up Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6\n        with:\n          go-version: stable\n          cache: false\n\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n\n      - name: Run Actionlint\n        run: |\n          make actionlint\n\n      - name: Reminder to Address Linting Errors\n        if: failure()\n        run: echo \"⚠️ Please address all linting errors before merging this pull request.\"\n\n      - name: All linting checks passed\n        if: success()\n        run: echo \"✅ All linting checks passed.\"\n"
  },
  {
    "path": ".github/workflows/milestone-add-to-pr.yml",
    "content": "# This action adds the \"next release\" milestone to a pull request\n# when it is merged\n\nname: \"Project: Add PR to Milestone\"\non:\n  pull_request_target:\n    types:\n      - closed\n\npermissions: read-all\n\njobs:\n  update-pr:\n    if: github.event.pull_request.merged\n    runs-on: ubuntu-latest\n    permissions:\n      pull-requests: write\n    steps:\n      - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0\n        with:\n          script: |\n            const milestones = await github.rest.issues.listMilestones({\n              owner: context.repo.owner,\n              repo: context.repo.repo,\n              state: \"open\"\n            })\n            for (const milestone of milestones.data) {\n              if (milestone.title == \"next release\") {\n                await github.rest.issues.update({\n                  owner: context.repo.owner,\n                  repo: context.repo.repo,\n                  issue_number: context.issue.number,\n                  milestone: milestone.number\n                });\n                return\n              }\n            }\n"
  },
  {
    "path": ".github/workflows/perf.yml",
    "content": "name: Automation - Performance\n\non:\n  push:\n    branches: [main]\n\npermissions: read-all\n\njobs:\n  runperf:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: oldstable\n          cache: false\n\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n\n      - name: Run benchmark\n        run: make gobenchmark\n\n      # Disabling until fine-grained permissions token enabled for the\n      # repository\n      #- name: Store benchmark result\n      #  uses: benchmark-action/github-action-benchmark@v1\n      #  with:\n      #    tool: 'go'\n      #    output-file-path: benchmarks.txt\n      #    gh-pages-branch: gh-pages\n      #    auto-push: true\n      #    github-token: ${{ secrets.GITHUB_TOKEN }}\n      #    benchmark-data-dir-path: \"docs/dev/bench\"\n"
  },
  {
    "path": ".github/workflows/ping-codeowners-issues.yml",
    "content": "name: 'Ping code owners on issues'\non:\n  issues:\n    types: [labeled]\n\npermissions: read-all\n\njobs:\n  ping-owners:\n    permissions:\n      issues: write\n    runs-on: ubuntu-24.04\n    if: ${{ github.repository_owner == 'open-telemetry' }}\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n\n      - name: Run ping-codeowners-issues.sh\n        run: ./.github/workflows/scripts/ping-codeowners-issues.sh\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          ISSUE: ${{ github.event.issue.number }}\n          COMPONENT: ${{ github.event.label.name }}\n"
  },
  {
    "path": ".github/workflows/ping-codeowners-on-new-issue.yml",
    "content": "name: 'Ping code owners on a new issue'\non:\n  issues:\n    types: [opened]\n\npermissions: read-all\n\njobs:\n  ping-owners-on-new-issue:\n    permissions:\n      issues: write\n    runs-on: ubuntu-24.04\n    if: ${{ github.repository_owner == 'open-telemetry' }}\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n\n      - name: Run ping-codeowners-on-new-issue.sh\n        run: ./.github/workflows/scripts/ping-codeowners-on-new-issue.sh\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          ISSUE: ${{ github.event.issue.number }}\n          TITLE: ${{ github.event.issue.title }}\n          BODY: ${{ github.event.issue.body }}\n          OPENER: ${{ github.event.issue.user.login }}\n"
  },
  {
    "path": ".github/workflows/ping-codeowners-prs.yml",
    "content": "name: 'Ping code owners on PRs'\non:\n  pull_request_target:\n    types:\n      - labeled\n      - ready_for_review\n\npermissions: read-all\n\njobs:\n  ping-owners:\n    permissions:\n      pull-requests: write\n    runs-on: ubuntu-24.04\n    if: ${{ github.actor != 'dependabot[bot]' && github.actor != 'renovate[bot]' && github.repository_owner == 'open-telemetry' && github.event.pull_request.draft == false }}\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n\n      - name: Run ping-codeowners-prs.sh\n        run: ./.github/workflows/scripts/ping-codeowners-prs.sh\n        env:\n          REPO: ${{ github.repository }}\n          AUTHOR: ${{ github.event.pull_request.user.login }}\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          PR: ${{ github.event.number }}\n          COMPONENT: ${{ github.event.label.name }}\n"
  },
  {
    "path": ".github/workflows/prepare-release.yml",
    "content": "name: Automation - Prepare Release\n\non:\n  workflow_dispatch:\n    # Determine the version number that will be assigned to the release. During the beta phase, we increment\n    # the minor version number and set the patch number to 0.\n    inputs:\n      candidate-stable:\n        description: Release candidate version (stable, like 1.3.0). Don't include a leading `v`.\n\n      current-stable:\n        required: true\n        description: Current version (stable, like 1.2.0). Don't include a leading `v`.\n\n      candidate-beta:\n        description: Release candidate version (beta, like 0.96.0). Don't include `v`.\n\n      current-beta:\n        required: true\n        description: Current version (beta, like 0.95.1). Don't include `v`.\n\npermissions: read-all\n\njobs:\n  validate-versions-format:\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Validate version format\n        shell: bash\n        run: |\n          validate_beta_version() {\n            local regex_pattern_beta='^[0-9]+\\.[0-9]+\\.[0-9]+$'\n            if [[ ! \"$1\" =~ $regex_pattern_beta ]]; then\n              echo \"Invalid $2 version format. For beta, it can be 0.1.0 or higher\"\n              exit 1\n            fi\n          }\n\n          validate_stable_version() {\n            local regex_pattern_stable='^[1-9][0-9]*\\.[0-9]+\\.[0-9]+$'\n            if [[ ! \"$1\" =~ $regex_pattern_stable ]]; then\n              echo \"Invalid stable version format for $2. Major version must be greater than 1.\"\n              exit 1\n            fi\n          }\n\n          if [[ ! -z \"${{ inputs.candidate-beta }}\" ]]; then\n            validate_beta_version \"${{ inputs.candidate-beta }}\" \"candidate-beta\"\n          fi\n          validate_beta_version \"${{ inputs.current-beta }}\" \"current-beta\"\n\n          if [[ ! -z \"${{ inputs.candidate-stable }}\" ]]; then\n            validate_stable_version \"${{ inputs.candidate-stable }}\" \"candidate-stable\"\n          fi\n          validate_stable_version \"${{ inputs.current-stable }}\" \"current-stable\"\n\n          if [[ -z \"${{ inputs.candidate-beta }}\" && -z \"${{ inputs.candidate-stable }}\" ]]; then\n            echo \"Candidate version is not set for beta or stable. Please set a version to proceed.\"\n            exit 1\n          fi\n\n  check-blockers:\n    needs:\n      - validate-versions-format\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          fetch-depth: 0\n      # Make sure that there are no open issues with release:blocker label in Core. The release has to be delayed until they are resolved.\n      - name: Check blockers in core\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          REPO: open-telemetry/opentelemetry-collector\n        run: ./.github/workflows/scripts/release-check-blockers.sh\n      # Make sure that there are no open issues with release:blocker label in Contrib. The release has to be delayed until they are resolved.\n      - name: Check blockers in contrib\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          REPO: open-telemetry/opentelemetry-collector-contrib\n        run: ./.github/workflows/scripts/release-check-blockers.sh\n      # Make sure the current main branch build successfully passes (Core).\n      - name: Check build status in core\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          REPO: open-telemetry/opentelemetry-collector\n        run: ./.github/workflows/scripts/release-check-build-status.sh\n      # Make sure the current main branch build successfully passes (Contrib).\n      - name: Check build status in contrib\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          REPO: open-telemetry/opentelemetry-collector-contrib\n        run: ./.github/workflows/scripts/release-check-build-status.sh\n\n  create-release-issue:\n    needs:\n      - check-blockers\n    runs-on: ubuntu-latest\n    permissions:\n      issues: write\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          fetch-depth: 0\n      # To keep track of the progress, it might be helpful to create a tracking issue similar to #6067. You are responsible\n      # for all of the steps under the \"Performed by collector release manager\" heading. Once the issue is created, you can\n      # create the individual ones by hovering them and clicking the \"Convert to issue\" button on the right hand side.\n      - name: Create issue for tracking release\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          CANDIDATE_BETA: ${{ inputs.candidate-beta }}\n          CANDIDATE_STABLE: ${{ inputs.candidate-stable }}\n          CURRENT_BETA: ${{ inputs.current-beta }}\n          CURRENT_STABLE: ${{ inputs.current-stable }}\n          REPO: open-telemetry/opentelemetry-collector\n        run: ./.github/workflows/scripts/release-create-tracking-issue.sh\n\n  # Releasing opentelemetry-collector\n  prepare-release:\n    needs:\n      - check-blockers\n    runs-on: ubuntu-latest\n    permissions:\n      contents: write\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          fetch-depth: 0\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: stable\n          cache: false\n\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n\n      - uses: actions/create-github-app-token@29824e69f54612133e76f7eaac726eef6c875baf # v2.2.1\n        id: otelbot-token\n        with:\n          app-id: ${{ vars.OTELBOT_APP_ID }}\n          private-key: ${{ secrets.OTELBOT_PRIVATE_KEY }}\n      # Prepare Core for release.\n      #   - Update CHANGELOG.md file, this is done via chloggen\n      #   - Run make prepare-release PREVIOUS_VERSION=1.0.0 RELEASE_CANDIDATE=1.1.0 MODSET=stable\n      #   - Run make prepare-release PREVIOUS_VERSION=0.52.0 RELEASE_CANDIDATE=0.53.0 MODSET=beta\n      - name: Prepare release for core\n        env:\n          GITHUB_TOKEN: ${{ steps.otelbot-token.outputs.token }}\n          REPO: open-telemetry/opentelemetry-collector\n          CANDIDATE_BETA: ${{ inputs.candidate-beta }}\n          CANDIDATE_STABLE: ${{ inputs.candidate-stable }}\n          CURRENT_BETA: ${{ inputs.current-beta }}\n          CURRENT_STABLE: ${{ inputs.current-stable }}\n        run: ./.github/workflows/scripts/release-prepare-release.sh\n"
  },
  {
    "path": ".github/workflows/release-branch.yml",
    "content": "name: Automation - Release Branch\n\non:\n  push:\n    tags:\n      # Trigger on beta version tags (0.x.x series) to create release branch\n      # This pattern matches: v0.{minor}.{patch} for new releases and bugfix releases\n      - 'v0.[0-9]+.[0-9]+'\n      - 'v0.[0-9]+.[0-9]+-*' # Also support release candidates if needed\n\npermissions:\n  contents: read\n\njobs:\n  release-branch:\n    runs-on: ubuntu-latest\n    permissions:\n      contents: write\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          fetch-depth: 0\n\n      - name: Setup Go\n        uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: oldstable\n          cache: false\n\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n\n      - name: Setup Git config\n        run: |\n          git config --global user.name \"otelbot\"\n          git config --global user.email \"197425009+otelbot@users.noreply.github.com\"\n\n      - name: Run release-branch.sh\n        run: |\n          ./.github/workflows/scripts/release-branch.sh\n        env:\n          UPSTREAM_REMOTE_NAME: \"origin\"\n          MAIN_BRANCH_NAME: \"main\"\n          GITHUB_REF: ${{ github.ref }}\n"
  },
  {
    "path": ".github/workflows/rerun-workflows.yml",
    "content": "name: \"Rerun Failed Workflows\"\non:\n  issue_comment:\n    types:\n      - created\n\npermissions: read-all\n\njobs:\n  rerun-failed:\n    if: ${{ github.event.issue.pull_request && startsWith(github.event.comment.body, '/rerun') && github.repository_owner == 'open-telemetry' }}\n    permissions:\n      actions: write\n      checks: read\n    runs-on: ubuntu-24.04\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6\n      - name: Run rerun-failed-workflows.sh\n        run: ./.github/workflows/scripts/rerun-failed-workflows.sh\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n          PR_NUMBER: ${{ github.event.issue.number }}\n          COMMENT: ${{ github.event.comment.body }}\n          SENDER: ${{ github.event.comment.user.login }}\n"
  },
  {
    "path": ".github/workflows/scorecard.yml",
    "content": "name: Scorecard supply-chain security\n\non:\n  # For Branch-Protection check. Only the default branch is supported. See\n  # https://github.com/ossf/scorecard/blob/main/docs/checks.md#branch-protection\n  branch_protection_rule:\n  # To guarantee Maintained check is occasionally updated. See\n  # https://github.com/ossf/scorecard/blob/main/docs/checks.md#maintained\n  schedule:\n    - cron: '39 1 * * 3'\n  push:\n    branches: [ \"main\" ]\n\n# Declare default permissions as read only.\npermissions: read-all\n\njobs:\n  analysis:\n    name: Scorecard analysis\n    runs-on: ubuntu-latest\n    permissions:\n      # Needed to upload the results to code-scanning dashboard.\n      security-events: write\n      # Needed to publish results and get a badge (see publish_results below).\n      id-token: write\n      # Uncomment the permissions below if installing in a private repository.\n      # contents: read\n      # actions: read\n\n    steps:\n      - name: \"Checkout code\"\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          persist-credentials: false\n\n      - name: \"Run analysis\"\n        uses: ossf/scorecard-action@4eaacf0543bb3f2c246792bd56e8cdeffafb205a # v2.4.3\n        with:\n          results_file: results.sarif\n          results_format: sarif\n          # (Optional) \"write\" PAT token. Uncomment the `repo_token` line below if:\n          # - you want to enable the Branch-Protection check on a *public* repository, or\n          # - you are installing Scorecard on a *private* repository\n          # To create the PAT, follow the steps in https://github.com/ossf/scorecard-action#authentication-with-pat.\n          # repo_token: ${{ secrets.SCORECARD_TOKEN }}\n\n          # Public repositories:\n          #   - Publish results to OpenSSF REST API for easy access by consumers\n          #   - Allows the repository to include the Scorecard badge.\n          #   - See https://github.com/ossf/scorecard-action#publishing-results.\n          # For private repositories:\n          #   - `publish_results` will always be set to `false`, regardless\n          #     of the value entered here.\n          publish_results: true\n\n      # Upload the results as artifacts (optional). Commenting out will disable uploads of run results in SARIF\n      # format to the repository Actions tab.\n      - name: \"Upload artifact\"\n        uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0\n        with:\n          name: SARIF file\n          path: results.sarif\n          retention-days: 5\n\n      # Upload the results to GitHub's code scanning dashboard.\n      - name: \"Upload to code-scanning\"\n        uses: github/codeql-action/upload-sarif@0d579ffd059c29b07949a3cce3983f0780820c98 # v4.32.6\n        with:\n          sarif_file: results.sarif\n"
  },
  {
    "path": ".github/workflows/scripts/add-labels-and-owners.sh",
    "content": "#!/usr/bin/env bash\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n#\n# Adds code owners without write access as reviewers on a PR. Note that\n# the code owners must still be a member of the `open-telemetry`\n# organization.\n#\n# Note that since this script is considered a requirement for PRs,\n# it should never fail.\n\nset -euo pipefail\n\nif [[ -z \"${REPO:-}\" || -z \"${PR:-}\" ]]; then\n    echo \"One or more of REPO and PR have not been set, please ensure each is set.\"\n    exit 0\nfi\n\nmain () {\n    CUR_DIRECTORY=$(dirname \"$0\")\n    # Reviews may have comments that need to be cleaned up for jq,\n    # so restrict output to only printable characters and ensure escape\n    # sequences are removed.\n    # The latestReviews key only returns the latest review for each reviewer,\n    # cutting out any other reviews. We use that instead of requestedReviews\n    # since we need to get the list of users eligible for requesting another\n    # review. The GitHub CLI does not offer a list of all reviewers, which\n    # is only available through the API. To cut down on API calls to GitHub,\n    # we use the latest reviews to determine which users to filter out.\n    JSON=$(gh pr view \"${PR}\" --json \"files,author,latestReviews\" | LC_ALL=C tr -dc '[:print:]' | sed -E 's/\\\\[a-z]//g')\n    AUTHOR=$(echo -n \"${JSON}\"| jq -r '.author.login')\n    FILES=$(echo -n \"${JSON}\"| jq -r '.files[].path')\n    REVIEW_LOGINS=$(echo -n \"${JSON}\"| jq -r '.latestReviews[].author.login')\n    COMPONENTS=$(bash \"${CUR_DIRECTORY}/get-components.sh\")\n    REVIEWERS=\"\"\n    LABELS=\"\"\n    declare -A PROCESSED_COMPONENTS\n    declare -A REVIEWED\n\n    for REVIEWER in ${REVIEW_LOGINS}; do\n        # GitHub adds \"app/\" in front of user logins. The API docs don't make\n        # it clear what this means or whether it will always be present. The\n        # '/' character isn't a valid character for usernames, so this won't\n        # replace characters within a username.\n        REVIEWED[\"@${REVIEWER//app\\//}\"]=true\n    done\n\n    if [[ -v REVIEWED[@] ]]; then\n        echo \"Users that have already reviewed this PR and will not have another review requested:\" \"${!REVIEWED[@]}\"\n    else\n        echo \"This PR has not yet been reviewed, all code owners are eligible for a review request\"\n    fi\n\n    RISKY_REGEX='\n     ^.github/workflows/prepare-release.yml$\n    |^.github/workflows/scripts/release-prepare-release.sh$\n    |^Makefile$\n    |^Makefile.Common$\n    '\n    RISKY_REGEX=\"$(echo \"$RISKY_REGEX\" | tr -d ' \\n')\"\n    RISKY_FILES=\"$(echo \"$FILES\" | grep -E \"$RISKY_REGEX\")\"\n    if [[ -n \"${RISKY_FILES}\" ]]; then\n        echo \"This PR may affect the release process, as it touches the following files:\" \\\n            \"$(echo \"$RISKY_FILES\" | sed -E 's/\\n/, /')\"\n        LABELS=\"release:risky-change\"\n    else\n        echo \"This PR does not have release-affecting changes.\"\n    fi\n\n    for COMPONENT in ${COMPONENTS}; do\n        # Files will be in alphabetical order and there are many files to\n        # a component, so loop through files in an inner loop. This allows\n        # us to remove all files for a component from the list so they\n        # won't be checked against the remaining components in the components\n        # list. This provides a meaningful speedup in practice.\n        for FILE in ${FILES}; do\n            MATCH=$(echo -n \"${FILE}\" | grep -E \"^${COMPONENT}\" || true)\n\n            if [[ -z \"${MATCH}\" ]]; then\n                continue\n            fi\n\n            # If we match a file with a component we don't need to process the file again.\n            FILES=$(echo -n \"${FILES}\" | grep -v \"${FILE}\")\n\n            if [[ -v PROCESSED_COMPONENTS[\"${COMPONENT}\"] ]]; then\n                continue\n            fi\n\n            PROCESSED_COMPONENTS[\"${COMPONENT}\"]=true\n\n            OWNERS=$(COMPONENT=\"${COMPONENT}\" bash \"${CUR_DIRECTORY}/get-codeowners.sh\")\n\n            for OWNER in ${OWNERS}; do\n                # Users that leave reviews are removed from the \"requested reviewers\"\n                # list and are eligible to have another review requested. We only want\n                # to request a review once, so remove them from the list.\n                if [[ -v REVIEWED[\"${OWNER}\"] || \"${OWNER}\" = \"@${AUTHOR}\" ]]; then\n                    continue\n                fi\n\n                if [[ -n \"${REVIEWERS}\" ]]; then\n                    REVIEWERS+=\",\"\n                fi\n                REVIEWERS+=$(echo -n \"${OWNER}\" | sed -E 's/@(.+)/\"\\1\"/')\n            done\n\n            # Convert the CODEOWNERS entry to a label\n            COMPONENT_NAME=$(echo -n \"${COMPONENT}\" | sed -E 's%^(.+)/(.+)\\1%\\1/\\2%')\n\n            if (( \"${#COMPONENT_NAME}\" > 50 )); then\n                echo \"'${COMPONENT_NAME}' exceeds GitHub's 50-character limit on labels, skipping adding label\"\n                continue\n            fi\n\n            if [[ -n \"${LABELS}\" ]]; then\n                LABELS+=\",\"\n            fi\n            LABELS+=\"${COMPONENT_NAME}\"\n        done\n    done\n\n    if [[ -n \"${LABELS}\" ]]; then\n        echo \"Adding labels: ${LABELS}\"\n        gh pr edit \"${PR}\" --add-label \"${LABELS}\" || echo \"Failed to add labels\"\n    else\n        echo \"No labels found\"\n    fi\n\n    # Note that adding the labels above will not trigger any other workflows to\n    # add code owners, so we have to do it here.\n    #\n    # We have to use the GitHub API directly due to an issue with how the CLI\n    # handles PR updates that causes it require access to organization teams,\n    # and the GitHub token doesn't provide that permission.\n    # For more: https://github.com/cli/cli/issues/4844\n    #\n    # The GitHub API validates that authors are not requested to review, but\n    # accepts duplicate logins and logins that are already reviewers.\n    if [[ -n \"${REVIEWERS}\" ]]; then\n        echo \"Requesting review from ${REVIEWERS}\"\n        curl \\\n            -X POST \\\n            -H \"Accept: application/vnd.github+json\" \\\n            -H \"Authorization: Bearer ${GITHUB_TOKEN}\" \\\n            \"https://api.github.com/repos/${REPO}/pulls/${PR}/requested_reviewers\" \\\n            -d \"{\\\"reviewers\\\":[${REVIEWERS}]}\" \\\n            | jq \".message\" \\\n            || echo \"jq was unable to parse GitHub's response\"\n    else\n        echo \"No code owners found\"\n    fi\n}\n\n# We don't want this workflow to ever fail and block a PR,\n# so ensure all errors are caught.\nmain || echo \"Failed to run $0\"\n"
  },
  {
    "path": ".github/workflows/scripts/add-labels-command.sh",
    "content": "#!/usr/bin/env bash\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n#\n#\n\nset -euo pipefail\n\nif [[ -z \"${ISSUE:-}\" || -z \"${COMMENT:-}\" || -z \"${SENDER:-}\" ]]; then\n    echo \"At least one of ISSUE, COMMENT, or SENDER has not been set, please ensure each is set.\"\n    exit 0\nfi\n\nCUR_DIRECTORY=$(dirname \"$0\")\n\nif [[ ${COMMENT:0:6} != \"/label\" ]]; then\n    echo \"Comment is not a label comment, exiting.\"\n    exit 0\nfi\n\n# key: label in comment\n# value: actual label\ndeclare -A COMMON_LABELS\nCOMMON_LABELS[\"arm64\"]=\"arm64\"\nCOMMON_LABELS[\"good-first-issue\"]=\"good first issue\"\nCOMMON_LABELS[\"help-wanted\"]=\"help wanted\"\nCOMMON_LABELS[\"discussion-needed\"]=\"discussion-needed\"\nCOMMON_LABELS[\"os:macos\"]=\"os:macos\"\nCOMMON_LABELS[\"os:windows\"]=\"os:windows\"\nCOMMON_LABELS[\"waiting-for-author\"]=\"waiting-for-author\"\nCOMMON_LABELS[\"waiting-for-codeowners\"]=\"waiting-for-codeowners\"\nCOMMON_LABELS[\"bug\"]=\"bug\"\nCOMMON_LABELS[\"priority:p0\"]=\"priority:p0\"\nCOMMON_LABELS[\"priority:p1\"]=\"priority:p1\"\nCOMMON_LABELS[\"priority:p2\"]=\"priority:p2\"\nCOMMON_LABELS[\"priority:p3\"]=\"priority:p3\"\nCOMMON_LABELS[\"stale\"]=\"Stale\"\n\nLABELS=$(echo \"${COMMENT}\" | sed -E 's%^/label%%')\n\nfor LABEL_REQ in ${LABELS}; do\n    LABEL=$(echo \"${LABEL_REQ}\" | sed -E s/^[+-]?//)\n    # Trim newlines from label that would cause matching to fail\n    LABEL=$(echo \"${LABEL}\" | tr -d '\\n')\n\n    SHOULD_ADD=true\n    if [[ \"${LABEL_REQ:0:1}\" = \"-\" ]]; then\n        SHOULD_ADD=false\n    fi\n\n    if [[ -v COMMON_LABELS[\"${LABEL}\"] ]]; then\n        if [[ ${SHOULD_ADD} = true ]]; then\n            gh issue edit \"${ISSUE}\" --add-label \"${COMMON_LABELS[\"${LABEL}\"]}\"\n        else\n            gh issue edit \"${ISSUE}\" --remove-label \"${COMMON_LABELS[\"${LABEL}\"]}\"\n        fi\n        continue\n    fi\n\n    # Grep exits with status code 1 if there are no matches,\n    # so we manually set RESULT to 0 if nothing is found.\n    RESULT=$(grep -c \"${LABEL}\" .github/CODEOWNERS || true)\n\n    if [[ ${RESULT} = 0 ]]; then\n        echo \"\\\"${LABEL}\\\" doesn't correspond to a component, skipping.\"\n        continue\n    fi\n\n    if [[ ${SHOULD_ADD} = true ]]; then\n        gh issue edit \"${ISSUE}\" --add-label \"${LABEL}\"\n\n        # Labels added by a GitHub Actions workflow don't trigger other workflows\n        # by design, so we have to manually ping code owners here.\n        COMPONENT=\"${LABEL}\" ISSUE=${ISSUE} SENDER=\"${SENDER}\" bash \"${CUR_DIRECTORY}/ping-codeowners-issues.sh\"\n    else\n        gh issue edit \"${ISSUE}\" --remove-label \"${LABEL}\"\n    fi\ndone\n\n\n"
  },
  {
    "path": ".github/workflows/scripts/check-merge-freeze.sh",
    "content": "#!/bin/bash -e\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n\n# Check for [chore] Prepare release PRs in core repo\nBLOCKERS=$( gh pr list -A \"otelbot[bot]\" -S \"[chore] Prepare release\" --json url -q '.[].url' -R \"${REPO}\" )\n\n# Check for [chore] Update core dependencies PRs in opentelemetry-collector-contrib\nCONTRIB_REPO=\"open-telemetry/opentelemetry-collector-contrib\"\nCONTRIB_BLOCKERS=$( gh pr list -A \"otelbot[bot]\" -S \"[chore] Update core dependencies\" --json url -q '.[].url' -R \"${CONTRIB_REPO}\" )\n\n# Combine both blockers\nBLOCKERS=\"${BLOCKERS}${BLOCKERS:+ }${CONTRIB_BLOCKERS}\"\n\nif [ \"${BLOCKERS}\" != \"\" ]; then\n    echo \"Merging in main is frozen, as there are open release/update PRs: ${BLOCKERS}\"\n    echo \"If you believe this is no longer true, re-run this job to unblock your PR.\"\n    exit 1\nfi\n"
  },
  {
    "path": ".github/workflows/scripts/free-disk-space.sh",
    "content": "#!/usr/bin/env bash\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n\necho \"Available disk space before:\"\ndf -h /\n\n# The Android SDK is the biggest culprit for the lack of disk space in CI.\n# It is installed into /usr/local/lib/android manually (ie. not with apt) by this script:\n# https://github.com/actions/runner-images/blob/main/images/ubuntu/scripts/build/install-android-sdk.sh\n# so let's delete the directory manually.\necho \"Deleting unused Android SDK and tools...\"\nsudo rm -rf /usr/local/lib/android\n\necho \"Available disk space after:\"\ndf -h /\n"
  },
  {
    "path": ".github/workflows/scripts/get-codeowners.sh",
    "content": "#!/usr/bin/env bash\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n#\n# This script checks the GitHub CODEOWNERS file for any code owners\n# of contrib components and returns a string of the code owners if it\n# finds them.\n\nset -euo pipefail\n\nget_component_type() {\n  echo \"${COMPONENT}\" | cut -f 1 -d '/'\n}\n\nget_codeowners() {\n  # grep arguments explained:\n  #   -m 1: Match the first occurrence\n  #   ^: Match from the beginning of the line\n  #   ${1}: Insert first argument given to this function\n  #   [\\/]\\?: Match 0 or 1 instances of a forward slash\n  #   \\s: Match any whitespace character\n(grep -m 1 \"^${1}[\\/]\\?\\s\" .github/CODEOWNERS || true) | \\\n        sed 's/   */ /g' | \\\n        cut -f3- -d ' '\n}\n\nif [[ -z \"${COMPONENT:-}\" ]]; then\n    echo \"COMPONENT has not been set, please ensure it is set.\"\n    exit 1\nfi\n\nOWNERS=\"$(get_codeowners \"${COMPONENT}\")\"\n\nif [[ -z \"${OWNERS:-}\" ]]; then\n    COMPONENT_TYPE=$(get_component_type \"${COMPONENT}\")\n    OWNERS=\"$(get_codeowners \"${COMPONENT}${COMPONENT_TYPE}\")\"\nfi\n\necho \"${OWNERS}\"\n"
  },
  {
    "path": ".github/workflows/scripts/get-components.sh",
    "content": "#!/usr/bin/env sh\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n#\n# Get a list of components within the repository that have some form of ownership\n# ascribed to them.\n\ngrep -E '^[A-Za-z0-9/]' .github/CODEOWNERS | \\\n    awk '{ print $1 }' | \\\n    sed -E 's%(.+)/$%\\1%'\n"
  },
  {
    "path": ".github/workflows/scripts/ping-codeowners-issues.sh",
    "content": "#!/usr/bin/env bash\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n#\n#\n\nset -euo pipefail\n\nif [[ -z \"${COMPONENT:-}\" || -z \"${ISSUE:-}\" ]]; then\n    echo \"Either COMPONENT or ISSUE has not been set, please ensure both are set.\"\n    exit 0\nfi\n\nCUR_DIRECTORY=$(dirname \"$0\")\n\nOWNERS=$(COMPONENT=\"${COMPONENT}\" bash \"${CUR_DIRECTORY}/get-codeowners.sh\")\n\nif [[ -z \"${OWNERS}\" ]]; then\n    exit 0\nfi\n\ngh issue comment \"${ISSUE}\" --body \"Pinging code owners for ${COMPONENT}: ${OWNERS}. See [Adding Labels via Comments](https://github.com/open-telemetry/opentelemetry-collector/blob/main/CONTRIBUTING.md#adding-labels-via-comments) if you do not have permissions to add labels yourself. For example, comment '/label priority:p2 -needs-triage' to set the priority and remove the needs-triage label.\"\n"
  },
  {
    "path": ".github/workflows/scripts/ping-codeowners-on-new-issue.sh",
    "content": "#!/usr/bin/env bash\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n#\n#\n\nset -euo pipefail\n\nif [[ -z \"${ISSUE:-}\" || -z \"${TITLE:-}\" || -z \"${BODY:-}\" || -z \"${OPENER:-}\" ]]; then\n  echo \"Missing one of ISSUE, TITLE, BODY, or OPENER, please ensure all are set.\"\n  exit 0\nfi\n\nLABELS_COMMENT='See [Adding Labels via Comments](https://github.com/open-telemetry/opentelemetry-collector/blob/main/CONTRIBUTING.md#adding-labels-via-comments) if you do not have permissions to add labels yourself.'\nCUR_DIRECTORY=$(dirname \"$0\")\nLABELS=\"\"\nPING_LINES=\"\"\ndeclare -A PINGED_COMPONENTS\n\nTITLE_COMPONENT=$(echo \"${TITLE}\" | (grep -oE \"\\[.+\\]\" || true) | sed -E 's/\\[(.+)\\]/\\1/' | sed -E 's%^(.+)/(.+)\\1%\\1/\\2%')\n\nCOMPONENTS_SECTION_START=$( (echo \"${BODY}\" | grep -n '### Component(s)' | awk '{ print $1 }' | grep -oE '[0-9]+') || echo '-1' )\nBODY_COMPONENTS=\"\"\n\nif [[ \"${COMPONENTS_SECTION_START}\" != '-1' ]]; then\n  BODY_COMPONENTS=$(echo \"${BODY}\" | sed -n $((COMPONENTS_SECTION_START+2))p)\nfi\n\nif [[ -n \"${TITLE_COMPONENT}\" && ! (\"${TITLE_COMPONENT}\" =~ \" \") ]]; then\n  CODEOWNERS=$(COMPONENT=\"${TITLE_COMPONENT}\" \"${CUR_DIRECTORY}/get-codeowners.sh\" || true)\n\n  if [[ -n \"${CODEOWNERS}\" ]]; then\n    PING_LINES+=\"- ${TITLE_COMPONENT}: ${CODEOWNERS}\\n\"\n    PINGED_COMPONENTS[\"${TITLE_COMPONENT}\"]=1\n\n    if (( \"${#TITLE_COMPONENT}\" <= 50 )); then\n      LABELS+=\"${TITLE_COMPONENT}\"\n    else\n      echo \"'${TITLE_COMPONENT}' exceeds GitHub's 50-character limit, skipping adding a label\"\n    fi\n  fi\nfi\n\nfor COMPONENT in ${BODY_COMPONENTS}; do\n  # Comments are delimited by ', ' and the for loop separates on spaces, so remove the extra comma.\n  COMPONENT=${COMPONENT//,/}\n\n  CODEOWNERS=$(COMPONENT=\"${COMPONENT}\" \"${CUR_DIRECTORY}/get-codeowners.sh\" || true)\n\n  if [[ -n \"${CODEOWNERS}\" ]]; then\n    if [[ -v PINGED_COMPONENTS[\"${COMPONENT}\"] ]]; then\n      continue\n    fi\n\n    PING_LINES+=\"- ${COMPONENT}: ${CODEOWNERS}\\n\"\n    PINGED_COMPONENTS[\"${COMPONENT}\"]=1\n\n    if (( \"${#COMPONENT}\" > 50 )); then\n      echo \"'${COMPONENT}' exceeds GitHub's 50-character limit on labels, skipping adding a label\"\n      continue\n    fi\n\n    if [[ -n \"${LABELS}\" ]]; then\n      LABELS+=\",\"\n    fi\n    LABELS+=\"${COMPONENT}\"\n  fi\ndone\n\nif [[ -v PINGED_COMPONENTS[@] ]]; then\n  echo \"The issue was associated with components:\" \"${!PINGED_COMPONENTS[@]}\"\nelse\n  echo \"No related components were given\"\nfi\n\nif [[ -n \"${LABELS}\" ]]; then\n  # Notes on this call:\n  # 1. Labels will be deduplicated by the GitHub CLI.\n  # 2. The call to edit the issue will fail if any of the\n  #    labels doesn't exist. We can be reasonably sure that\n  #    all labels will exist since they come from a known set.\n  echo \"Adding the following labels: ${LABELS//,/ /}\"\n  gh issue edit \"${ISSUE}\" --add-label \"${LABELS}\" || true\nelse\n  echo \"No labels were found to add\"\nfi\n\nif [[ -n \"${PING_LINES}\" ]]; then\n  # Notes on this call:\n  # 1. Adding labels above will not trigger the ping-codeowners flow,\n  #    since GitHub Actions disallows triggering a workflow from a\n  #    workflow, so we have to ping code owners here.\n  # 2. The GitHub CLI only offers multiline strings through file input,\n  #    so we provide the comment through stdin.\n  # 3. The PING_LINES variable must be directly put into the echo string\n  #    to get the newlines to render correctly, using string formatting\n  #    causes the newlines to be interpreted literally.\n  echo -e \"Pinging code owners:\\n${PING_LINES}\"\n  echo -e \"Pinging code owners:\\n${PING_LINES}\\n\" \"${LABELS_COMMENT}\"  \\\n  | gh issue comment \"${ISSUE}\" -F -\nelse\n  echo \"No code owners were found to ping\"\nfi\n"
  },
  {
    "path": ".github/workflows/scripts/ping-codeowners-prs.sh",
    "content": "#!/usr/bin/env bash\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n#\n\nset -euo pipefail\n\nif [[  -z \"${REPO:-}\" || -z \"${AUTHOR:-}\" || -z \"${COMPONENT:-}\" || -z \"${PR:-}\" ]]; then\n    echo \"At least one of REPO, AUTHOR, COMPONENT, or PR has not been set, please ensure each is set.\"\n    exit 0\nfi\n\nCUR_DIRECTORY=$(dirname \"$0\")\n\nmain() {\n    OWNERS=$(COMPONENT=\"${COMPONENT}\" bash \"${CUR_DIRECTORY}/get-codeowners.sh\")\n    REVIEWERS=\"\"\n\n    if [[ -z \"${OWNERS}\" ]]; then\n        exit 0\n    fi\n\n    for OWNER in ${OWNERS}; do\n        if [[ \"${OWNER}\" = \"@${AUTHOR}\" ]]; then\n            continue\n        fi\n    \n        if [[ -n \"${REVIEWERS}\" ]]; then\n            REVIEWERS+=\",\"\n        fi\n        REVIEWERS+=$(echo \"${OWNER}\" | sed -E 's/@(.+)/\"\\1\"/')\n    done\n\n    # We have to use the GitHub API directly due to an issue with how the CLI\n    # handles PR updates that causes it require access to organization teams,\n    # and the GitHub token doesn't provide that permission.\n    # For more: https://github.com/cli/cli/issues/4844\n    #\n    # The GitHub API validates that authors are not requested to review, but\n    # accepts duplicate logins and logins that are already reviewers.\n    echo \"Requesting review from code owners: ${REVIEWERS}\"\n    curl \\\n        -X POST \\\n        -H \"Accept: application/vnd.github+json\" \\\n        -H \"Authorization: Bearer ${GITHUB_TOKEN}\" \\\n        \"https://api.github.com/repos/${REPO}/pulls/${PR}/requested_reviewers\" \\\n        -d \"{\\\"reviewers\\\":[${REVIEWERS}]}\" \\\n        | jq \".message\" \\\n        || echo \"jq was unable to parse GitHub's response\"\n}\n\n# We don't want this workflow to ever fail and block a PR,\n# so ensure all errors are caught.\nmain || echo \"Failed to run $0\"\n"
  },
  {
    "path": ".github/workflows/scripts/release-branch.sh",
    "content": "#!/bin/bash -ex\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n\n# --- Configuration ---\nUPSTREAM_REMOTE_NAME=${UPSTREAM_REMOTE_NAME:-\"upstream\"} # Your upstream remote name for open-telemetry/opentelemetry-collector\nMAIN_BRANCH_NAME=${MAIN_BRANCH_NAME:-\"main\"}\nLOCAL_MAIN_BRANCH_NAME=${LOCAL_MAIN_BRANCH_NAME:-\"${MAIN_BRANCH_NAME}\"}\n# These variables are only used if git user.name and git user.email are not configured\nGIT_CONFIG_USER_NAME=${GIT_CONFIG_USER_NAME:-\"otelbot\"}\nGIT_CONFIG_USER_EMAIL=${GIT_CONFIG_USER_EMAIL:-\"197425009+otelbot@users.noreply.github.com\"}\n\n# --- Extract release information from tag ---\nif [[ -z \"$GITHUB_REF\" ]]; then\n  echo \"Error: GITHUB_REF environment variable must be provided when running in GitHub Actions.\"\n  echo \"For manual usage: GITHUB_REF=refs/tags/v0.85.0 $0\"\n  exit 1\nfi\n\n# Extract tag name and validate format using regex\nif [[ ! $GITHUB_REF =~ ^refs/tags/v([0-9]+\\.[0-9]+)\\.[0-9]+(-.+)?$ ]]; then\n    echo \"Error: GITHUB_REF did not match expected format (refs/tags/vX.XX.X)\"\n    exit 1\nfi\n\n# Extract version numbers from regex match\nVERSION_MAJOR_MINOR=${BASH_REMATCH[1]}\nRELEASE_SERIES=\"v${VERSION_MAJOR_MINOR}.x\"\necho \"Release series: ${RELEASE_SERIES}\"\n\n# --- Use current commit as prepare release commit ---\nPREPARE_RELEASE_COMMIT_HASH=\"${GITHUB_SHA:-HEAD}\"\necho \"Using current commit as prepare release commit: ${PREPARE_RELEASE_COMMIT_HASH}\"\n\nRELEASE_BRANCH_NAME=\"release/${RELEASE_SERIES}\"\n\necho \"Automating Release Steps for: ${RELEASE_SERIES}\"\necho \"Release Branch Name: ${RELEASE_BRANCH_NAME}\"\necho \"'Prepare release' commit hash: ${PREPARE_RELEASE_COMMIT_HASH}\"\necho \"Upstream Remote: ${UPSTREAM_REMOTE_NAME}\"\necho \"--------------------------------------------------\"\n\n# --- Step 4: Checkout main, Pull, Create/Update and Push Release Branch ---\necho \"\"\necho \"=== Step 4: Preparing and Pushing Release Branch ===\"\n\n# 1. Checkout main\ngit checkout \"${LOCAL_MAIN_BRANCH_NAME}\"\n\n# 2. Fetch from upstream (updates remote-tracking branches including potential existing release branch)\ngit fetch \"${UPSTREAM_REMOTE_NAME}\"\n\n# 3. Rebase local main with upstream/main\ngit rebase \"${UPSTREAM_REMOTE_NAME}/${MAIN_BRANCH_NAME}\"\necho \"'${LOCAL_MAIN_BRANCH_NAME}' branch is now up-to-date.\"\n\n# Verify the commit exists (it should be reachable from main after fetch)\nif ! git cat-file -e \"${PREPARE_RELEASE_COMMIT_HASH}^{commit}\" 2>/dev/null; then\n  echo \"Error: Provided 'Prepare release' commit hash '${PREPARE_RELEASE_COMMIT_HASH}' not found.\"\n  exit 1\nfi\n# 4. Handle Release Branch: Check existence, create or switch, and merge/base\nBRANCH_EXISTS_LOCALLY=$(git branch --list \"${RELEASE_BRANCH_NAME}\")\n# Check remote by looking for the remote tracking branch ref after fetch\nif git rev-parse --verify --quiet \"${UPSTREAM_REMOTE_NAME}/${RELEASE_BRANCH_NAME}\" > /dev/null 2>&1; then\n  BRANCH_EXISTS_REMOTELY=true\nfi\n\nif [[ -n \"$BRANCH_EXISTS_LOCALLY\" ]]; then\n  echo \"Release branch '${RELEASE_BRANCH_NAME}' found locally.\"\n  echo \"Please delete local release branch using 'git branch -D ${RELEASE_BRANCH_NAME}' and run the script again.\"\n  exit 1\nelif [[ -n \"$BRANCH_EXISTS_REMOTELY\" ]]; then\n  echo \"Release branch '${RELEASE_BRANCH_NAME}' found on remote '${UPSTREAM_REMOTE_NAME}'.\"\n  echo \"Nothing to do, exiting.\"\n  exit 0\nelse\n  echo \"Release branch '${RELEASE_BRANCH_NAME}' not found locally or on remote.\"\n  git switch -c \"${RELEASE_BRANCH_NAME}\" \"${PREPARE_RELEASE_COMMIT_HASH}\"\nfi\n\necho \"Current branch is now '${RELEASE_BRANCH_NAME}'.\"\ngit --no-pager log -1 --pretty=oneline # Show the commit at the tip of the release branch\n\n# 5. Push the release branch to upstream\ngit push -u \"${UPSTREAM_REMOTE_NAME}\" \"${RELEASE_BRANCH_NAME}\"\necho \"Branch '${RELEASE_BRANCH_NAME}' pushed (or updated) on '${UPSTREAM_REMOTE_NAME}'.\"\necho \"Step 4 completed.\"\necho \"--------------------------------------------------\"\n\necho \"\"\necho \"Automation for release branch creation complete.\"\necho \"Release branch '${RELEASE_BRANCH_NAME}' has been created from the prepare release commit.\"\necho \"Tag-triggered build workflows should now be running for the pushed tags.\"\n"
  },
  {
    "path": ".github/workflows/scripts/release-check-blockers.sh",
    "content": "#!/bin/bash -ex\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n\nBLOCKERS=$( gh issue list --search \"label:release:blocker\" --json url --jq '.[].url' --repo \"${REPO}\" )\nif [ \"${BLOCKERS}\" != \"\" ]; then\n    echo \"Release blockers in ${REPO} repo: ${BLOCKERS}\"\n    exit 1\nfi\n"
  },
  {
    "path": ".github/workflows/scripts/release-check-build-status.sh",
    "content": "#!/bin/bash -ex\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n\nBRANCH=main\nWORKFLOW=build-and-test\n\nRESULT=$(gh run list --branch \"${BRANCH}\" --json status --jq '[.[] | select(.status != \"queued\" and .status != \"in_progress\")][0].status' --workflow \"${WORKFLOW}\" --repo \"${REPO}\" )\nif [ \"${RESULT}\" != \"completed\" ]; then\n    echo \"Build status in ${REPO} is not completed: ${RESULT}\"\n    gh run list --branch \"${BRANCH}\" --json status,url --jq '[.[] | select(.status != \"queued\" and .status != \"in_progress\")][0].url' --workflow \"${WORKFLOW}\" --repo \"${REPO}\"\n    exit 1\nfi\n"
  },
  {
    "path": ".github/workflows/scripts/release-create-tracking-issue.sh",
    "content": "#!/bin/bash -ex\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n\nRELEASE_VERSION=v${CANDIDATE_STABLE}/v${CANDIDATE_BETA}\nif [ \"${CANDIDATE_STABLE}\" == \"\" ]; then\n    RELEASE_VERSION=\"v${CANDIDATE_BETA}\"\nfi\nif [ \"${CANDIDATE_BETA}\" == \"\" ]; then\n    RELEASE_VERSION=\"v${CANDIDATE_STABLE}\"\nfi\n\nEXISTING_ISSUE=$( gh issue list --search \"in:title Release ${RELEASE_VERSION}\" --json url --jq '.[].url' --repo \"${REPO}\" --state open --label release )\n\nif [ \"${EXISTING_ISSUE}\" != \"\" ]; then\n    echo \"Issue already exists: ${EXISTING_ISSUE}\"\n    exit 0\nfi\n\ngh issue create -a \"${GITHUB_ACTOR}\" --repo \"${REPO}\" --label release --title \"Release ${RELEASE_VERSION}\" --body \"Like #14236, but for ${RELEASE_VERSION}\n**Performed by collector release manager**\n\n- [ ] Prepare core release ${RELEASE_VERSION}\n- [ ] Tag and release core ${RELEASE_VERSION}\n\n**Performed by collector contrib release manager**\n\n- [ ] Prepare contrib release v${CANDIDATE_BETA}\n- [ ] Tag and release contrib v${CANDIDATE_BETA}\n\n**Performed by collector releases release manager**\n\n- [ ] Prepare otelcol containers images release v${CANDIDATE_BETA}\n- [ ] Tag and otelcol containers images release v${CANDIDATE_BETA}\n\n**Performed by operator maintainers**\n\n- [ ] Release the operator v${CANDIDATE_BETA}\n\n**Performed by helm chart maintainers**\n\n- [ ] Update the opentelemetry-collector helm chart to use v${CANDIDATE_BETA}\"\n"
  },
  {
    "path": ".github/workflows/scripts/release-prepare-release.sh",
    "content": "#!/bin/bash -ex\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n\nif [ \"${CANDIDATE_STABLE}\" == \"\" ] && [ \"${CANDIDATE_BETA}\" == \"\" ]; then\n    echo \"One of CANDIDATE_STABLE or CANDIDATE_BETA must be set\"\n    exit 1\nfi\n\n# Expand CURRENT_STABLE and CURRENT_BETA to escape . character by using [.]\nCURRENT_STABLE_ESCAPED=${CURRENT_STABLE//./[.]}\nCURRENT_BETA_ESCAPED=${CURRENT_BETA//./[.]}\n\nRELEASE_VERSION=v${CANDIDATE_STABLE}/v${CANDIDATE_BETA}\nif [ \"${CANDIDATE_STABLE}\" == \"\" ]; then\n    RELEASE_VERSION=\"v${CANDIDATE_BETA}\"\nfi\nif [ \"${CANDIDATE_BETA}\" == \"\" ]; then\n    RELEASE_VERSION=\"v${CANDIDATE_STABLE}\"\nfi\n\nmake chlog-update VERSION=\"${RELEASE_VERSION}\"\nCOMMANDS=\"- make chlog-update VERSION=${RELEASE_VERSION}\"\ngit config user.name otelbot\ngit config user.email 197425009+otelbot@users.noreply.github.com\nBRANCH=\"prepare-release-prs/${CANDIDATE_BETA}\"\ngit checkout -b \"${BRANCH}\"\ngit add --all\ngit commit -m \"Changelog update ${RELEASE_VERSION}\"\n\nif [ \"${CANDIDATE_STABLE}\" != \"\" ]; then\n    make prepare-release PREVIOUS_VERSION=\"${CURRENT_STABLE_ESCAPED}\" RELEASE_CANDIDATE=\"${CANDIDATE_STABLE}\" MODSET=stable\n    COMMANDS+=\"\n- make prepare-release PREVIOUS_VERSION=${CURRENT_STABLE_ESCAPED} RELEASE_CANDIDATE=${CANDIDATE_STABLE} MODSET=stable\"\nfi\nif [ \"${CANDIDATE_BETA}\" != \"\" ]; then\n    make prepare-release PREVIOUS_VERSION=\"${CURRENT_BETA_ESCAPED}\" RELEASE_CANDIDATE=\"${CANDIDATE_BETA}\" MODSET=beta\n    COMMANDS+=\"\n- make prepare-release PREVIOUS_VERSION=${CURRENT_BETA_ESCAPED} RELEASE_CANDIDATE=${CANDIDATE_BETA} MODSET=beta\"\nfi\ngit push --set-upstream origin \"${BRANCH}\"\n\n# Use OpenTelemetryBot account to create PR, allowing workflows to run\n# The title must match the checks in check-merge-freeze.yml\ngh pr create --head \"$(git branch --show-current)\" --title \"[chore] Prepare release ${RELEASE_VERSION}\" --body \"\nThe following commands were run to prepare this release:\n${COMMANDS}\n\"\n"
  },
  {
    "path": ".github/workflows/scripts/rerun-failed-workflows.sh",
    "content": "#!/usr/bin/env bash\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n#\n\nset -euo pipefail\n\nif [[ -z \"${PR_NUMBER:-}\" || -z \"${COMMENT:-}\" || -z \"${SENDER:-}\" ]]; then\n    echo \"PR_NUMBER, COMMENT, or SENDER not set\"\n    exit 0\nfi\n\nif [[ ${COMMENT:0:6} != \"/rerun\" ]]; then\n    echo \"Not a rerun command\"\n    exit 0\nfi\n\nPR_DATA=$(gh pr view \"${PR_NUMBER}\" --json headRefOid,author)\nHEAD_SHA=$(echo \"${PR_DATA}\" | jq -r '.headRefOid')\nPR_AUTHOR=$(echo \"${PR_DATA}\" | jq -r '.author.login')\n\nif [[ \"${SENDER}\" != \"${PR_AUTHOR}\" ]]; then\n    echo \"Only PR author can rerun workflows\"\n    exit 0\nfi\n\necho \"Finding failed workflows for commit: ${HEAD_SHA}\"\n\nFAILED_RUNS=$(gh run list \\\n    --commit \"${HEAD_SHA}\" \\\n    --status failure \\\n    --json databaseId \\\n    --jq '.[].databaseId')\n\nif [[ -z \"${FAILED_RUNS}\" ]]; then\n    echo \"No failed workflows found\"\n    exit 0\nelse\n    for RUN_ID in ${FAILED_RUNS}; do\n        echo \"Rerunning workflow: ${RUN_ID}\"\n        gh run rerun \"${RUN_ID}\" --failed\n    done\nfi\n"
  },
  {
    "path": ".github/workflows/scripts/win-required-ports.ps1",
    "content": "<#\n.SYNOPSIS\n    This script ensures that the ports required by the default configuration of the collector are available.\n.DESCRIPTION\n    Certain runs on GitHub Actions sometimes have ports required by the default configuration reserved by other\n    applications via the WinNAT service.\n#>\n\n#Requires -RunAsAdministrator\n\nnetsh interface ip show excludedportrange protocol=tcp\n\nStop-Service winnat\n\n# Only port in the dynamic range that is being, from time to time, reserved by other applications.\nnetsh interface ip add excludedportrange protocol=tcp startport=55679 numberofports=1\n\nStart-Service winnat\n\nnetsh interface ip show excludedportrange protocol=tcp\n"
  },
  {
    "path": ".github/workflows/shellcheck.yml",
    "content": "name: Shellcheck lint\non:\n  push:\n    branches: [main]\n  pull_request:\n    branches: [main]\n  merge_group:\n    types: [checks_requested]\n\npermissions: read-all\n\njobs:\n  shellcheck:\n    name: Shellcheck\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n      - name: Run ShellCheck\n        uses: ludeeus/action-shellcheck@00cae500b08a931fb5698e11e79bfbd38e612a38 # 2.0.0\n"
  },
  {
    "path": ".github/workflows/sourcecode-release.yaml",
    "content": "name: Source Code - Release\n\non:\n  push:\n    tags:\n      - \"v*\"\n\npermissions:\n  contents: read\n\njobs:\n  goreleaser:\n    runs-on: ubuntu-latest\n    permissions:\n      contents: write # Grant write permissions to repository contents\n      issues: write # Grant write permissions to PR milestones\n    steps:\n      - name: Checkout Repo\n        uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          fetch-depth: 0\n\n        # Extract title from latest version title in CHANGELOG.md\n      - name: Prepare release title\n        id: release-title\n        run: |\n          echo \"title=$(grep -A 2 '<!-- next version -->' CHANGELOG.md | awk '/##/{print $2}')\" >> $GITHUB_OUTPUT\n\n      - name: Prepare release notes\n        run: |\n          touch release-notes.md\n          echo \"### Images and binaries here: https://github.com/open-telemetry/opentelemetry-collector-releases/releases/tag/${{ github.ref_name }}\" >> release-notes.md\n          echo \"\" >> release-notes.md\n          echo \"## End User Changelog\" >> release-notes.md\n\n          awk '/<!-- next version -->/,/<!-- previous-version -->/' CHANGELOG.md > tmp-chlog.md # select changelog of latest version only\n          sed '1,3d' tmp-chlog.md >> release-notes.md # delete first 3 lines of file\n\n          echo \"\" >> release-notes.md\n          echo \"## API Changelog\" >> release-notes.md\n\n          awk '/<!-- next version -->/,/<!-- previous-version -->/' CHANGELOG-API.md > tmp-chlog-api.md # select changelog of latest version only\n          sed '1,3d' tmp-chlog-api.md >> release-notes.md # delete first 3 lines of file\n\n      - name: Create Github Release\n        run: |\n          gh release create ${{ github.ref_name }} -t ${{ steps.release-title.outputs.title }} -F release-notes.md\n        env:\n          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}\n      - uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0\n        with:\n          script: |\n            const milestones = await github.rest.issues.listMilestones({\n              owner: context.repo.owner,\n              repo: context.repo.repo,\n              state: \"open\"\n            })\n            for (const milestone of milestones.data) {\n              if (milestone.title == \"next release\") {\n                await github.rest.issues.updateMilestone({\n                  owner: context.repo.owner,\n                  repo: context.repo.repo,\n                  milestone_number: milestone.number,\n                  title: \"${{ github.ref_name }}\"\n                });\n                await github.rest.issues.createMilestone({\n                  owner: context.repo.owner,\n                  repo: context.repo.repo,\n                  title: \"next release\"\n                });\n                return\n              }\n            }\n"
  },
  {
    "path": ".github/workflows/spell-check.yaml",
    "content": "name: Spell Check\n\non:\n  push:\n    branches: [main]\n  pull_request:\n\npermissions:\n  contents: read\n\njobs:\n  spell-check:\n    runs-on: ubuntu-latest\n\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n\n      - name: Run cSpell\n        uses: streetsidesoftware/cspell-action@9cd41bb518a24fefdafd9880cbab8f0ceba04d28 # v8.3.0\n        with:\n          incremental_files_only: false\n          use_cspell_files: true\n          config: '.github/workflows/utils/cspell.json'\n"
  },
  {
    "path": ".github/workflows/stale-pr.yaml",
    "content": "name: \"Close stale pull requests\"\non:\n  schedule:\n    - cron: \"12 3 * * *\" # arbitrary time not to DDOS GitHub\n\npermissions: read-all\n\njobs:\n  stale:\n    permissions:\n      issues: write # for actions/stale to close stale issues\n      pull-requests: write # for actions/stale to close stale PRs\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/stale@b5d41d4e1d5dceea10e7104786b73624c18a190f # v10.2.0\n        with:\n          repo-token: ${{ secrets.GITHUB_TOKEN }}\n          stale-pr-message: \"This PR was marked stale due to lack of activity. It will be closed in 14 days.\"\n          close-pr-message: \"Closed as inactive. Feel free to reopen if this PR is still being worked on.\"\n          days-before-pr-stale: 14\n          days-before-issue-stale: 730\n          days-before-pr-close: 14\n          days-before-issue-close: 30\n"
  },
  {
    "path": ".github/workflows/survey-on-merged-pr.yml",
    "content": "name: Survey on Merged PR by Non-Member\n\non:\n  pull_request_target:\n    types: [closed]\n\npermissions:\n  contents: read\n\nenv:\n  PR_NUM: ${{ github.event.pull_request.number }}\n  SURVEY_URL: https://docs.google.com/forms/d/e/1FAIpQLSf2FfCsW-DimeWzdQgfl0KDzT2UEAqu69_f7F2BVPSxVae1cQ/viewform?entry.1540511742=open-telemetry/opentelemetry-collector\n\njobs:\n  comment-on-pr:\n    name: Add survey to PR if author is not a member\n    runs-on: ubuntu-latest\n    if: github.event.pull_request.merged == true\n    steps:\n      - uses: actions/create-github-app-token@29824e69f54612133e76f7eaac726eef6c875baf # v2.2.1\n        id: otelbot-token\n        with:\n          app-id: ${{ vars.OTELBOT_APP_ID }}\n          private-key: ${{ secrets.OTELBOT_PRIVATE_KEY }}\n\n      - name: Add survey comment if author is not a member or bot\n        run: |\n          USERNAME=\"${{ github.event.pull_request.user.login }}\"\n          USER_TYPE=\"${{ github.event.pull_request.user.type }}\"\n          ORG=\"${{ github.repository_owner }}\"\n          \n          # Skip if user is a bot\n          if [[ \"$USER_TYPE\" == \"Bot\" ]]; then\n            echo \"Skipping survey for bot user: $USERNAME\"\n            exit 0\n          fi\n          \n          # Skip if user is an org member\n          if gh api \"orgs/$ORG/members/$USERNAME\" --silent; then\n            echo \"Skipping survey for org member: $USERNAME\"\n            exit 0\n          fi\n          \n          # Add survey comment for external contributor\n          echo \"Adding survey comment for external contributor: $USERNAME\"\n          gh pr comment ${PR_NUM} --repo ${{ github.repository }} --body \"Thank you for your contribution @${USERNAME}! 🎉 We would like to hear from you about your experience contributing to OpenTelemetry by taking a few minutes to fill out this [survey](${SURVEY_URL}).\"\n        env:\n          GH_TOKEN: ${{ steps.otelbot-token.outputs.token }}"
  },
  {
    "path": ".github/workflows/tidy-dependencies.yml",
    "content": "name: \"Project: Tidy\"\non:\n  pull_request_target:\n    types: [opened, ready_for_review, synchronize, reopened, labeled, unlabeled]\n    branches:\n      - main\n\npermissions: read-all\n\njobs:\n  setup-environment:\n    permissions:\n      contents: write # for Git to git push\n    timeout-minutes: 30\n    runs-on: ubuntu-latest\n    if: ${{ !contains(github.event.pull_request.labels.*.name, 'dependency-major-update') && (github.actor == 'renovate[bot]' || contains(github.event.pull_request.labels.*.name, 'renovatebot')) && github.event.pull_request.head.repo.fork == false }}\n    steps:\n      - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2\n        with:\n          ref: ${{ github.head_ref }}\n      - uses: actions/setup-go@4b73464bb391d4059bd26b0524d20df3927bd417 # v6.3.0\n        with:\n          go-version: oldstable\n          cache: false\n      - name: Cache Go\n        id: go-cache\n        uses: actions/cache@cdf6c1fa76f9f475f3d7449005a359c84ca0f306 # v5.0.3\n        with:\n          path: |\n            ~/go/bin\n            ~/go/pkg/mod\n          key: go-cache-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('**/go.sum') }}\n      - name: Install dependencies\n        if: steps.go-cache.outputs.cache-hit != 'true'\n        run: make -j2 gomoddownload\n      - name: go mod tidy\n        run: |\n          make gotidy\n          git config user.name otelbot\n          git config user.email 197425009+otelbot@users.noreply.github.com\n          echo \"git diff --exit-code || (git add . && git commit -m \\\"go mod tidy\\\" && git push)\"\n          git diff --exit-code || (git add . && git commit -m \"go mod tidy\" && git push)\n      - uses: actions-ecosystem/action-remove-labels@2ce5d41b4b6aa8503e285553f75ed56e0a40bae0 # v1.3.0\n        with:\n          labels: renovatebot\n"
  },
  {
    "path": ".github/workflows/utils/cspell.json",
    "content": "{\n    \"version\": \"0.2\",\n    \"language\": \"en\",\n    \"words\": [\n      \"aggregatable\",\n      \"Alolita\",\n      \"Andrzej\",\n      \"Anoshin\",\n      \"Appy\",\n      \"Autobuild\",\n      \"Backpressure\",\n      \"Baeyens\",\n      \"Bebbington\",\n      \"Biswal\",\n      \"Bogdan\",\n      \"Boten\",\n      \"CHACHA\",\n      \"CODEOWNERS\",\n      \"Chao\",\n      \"Chrs\",\n      \"Confmap\",\n      \"DOLLARSIGN\",\n      \"Distro\",\n      \"Dmitrii\",\n      \"Dockerhub\",\n      \"Dont\",\n      \"Drutu\",\n      \"Dynatrace\",\n      \"Excalidraw\",\n      \"Expvar\",\n      \"Fanout\",\n      \"FIPS\",\n      \"Funcs\",\n      \"GHSA\",\n      \"GOARCH\",\n      \"GOARM\",\n      \"GOBIN\",\n      \"GOCMD\",\n      \"GOMEMLIMIT\",\n      \"GOPATH\",\n      \"GOPROXY\",\n      \"Guiton\",\n      \"HKLM\",\n      \"Helmuth\",\n      \"Hostfeature\",\n      \"Islamov\",\n      \"Jaglowski\",\n      \"Janotti\",\n      \"Juraci\",\n      \"Karis\",\n      \"Keepalive\",\n      \"Koanf\",\n      \"Kröhling\",\n      \"MODSET\",\n      \"Makwana\",\n      \"Mapprovider\",\n      \"Marshalers\",\n      \"Marshallers\",\n      \"Mathieu\",\n      \"Mirabella\",\n      \"Najaryan\",\n      \"Nanos\",\n      \"OTELBOT\",\n      \"OTEP\",\n      \"OTTL\",\n      \"Olly\",\n      \"Owais\",\n      \"Paixão\",\n      \"Pdata\",\n      \"Prometheusremotewrite\",\n      \"Punya\",\n      \"RCPC\",\n      \"Rahul\",\n      \"SASL\",\n      \"Samplingdecision\",\n      \"Sharma\",\n      \"Statefulness\",\n      \"Stencel\",\n      \"Strindices\",\n      \"Tailsampling\",\n      \"Tigran\",\n      \"Toulme\",\n      \"Triagers\",\n      \"Unconfigured\",\n      \"Unmarshable\",\n      \"Unmarshal\",\n      \"Unmarshalable\",\n      \"Unmarshaller\",\n      \"Unmarshallers\",\n      \"unmarshalled\",\n      \"Vihas\",\n      \"Weng\",\n      \"Zipkin\",\n      \"adilhusain\",\n      \"alibabacloudlogserviceexporter\",\n      \"alives\",\n      \"anchore\",\n      \"andrzej\",\n      \"apidiff\",\n      \"atombender\",\n      \"atoulme\",\n      \"attributeprocessor\",\n      \"attributesprocessor\",\n      \"authextension\",\n      \"authtest\",\n      \"autobuild\",\n      \"backoffs\",\n      \"backpressure\",\n      \"ballastextension\",\n      \"batchprocessor\",\n      \"bearertokenauthextension\",\n      \"behaviour\",\n      \"bogdandrutu\",\n      \"braydonk\",\n      \"bucketize\",\n      \"buildinfo\",\n      \"buildx\",\n      \"bwalk\",\n      \"capabilityconsumer\",\n      \"certfile\",\n      \"cgroupv\",\n      \"checkapi\",\n      \"checkdoc\",\n      \"checklicense\",\n      \"cheung\",\n      \"chlog\",\n      \"chloggen\",\n      \"cmux\",\n      \"codeboten\",\n      \"codeowners\",\n      \"componentalias\",\n      \"componenterror\",\n      \"componenthelper\",\n      \"componentprofiles\",\n      \"componentstatus\",\n      \"componenttest\",\n      \"configauth\",\n      \"configcheck\",\n      \"configcompression\",\n      \"configcompressions\",\n      \"configerror\",\n      \"configgrpc\",\n      \"confighttp\",\n      \"configloader\",\n      \"configmapprovider\",\n      \"configmiddleware\",\n      \"configmodels\",\n      \"confignet\",\n      \"configopaque\",\n      \"configoptional\",\n      \"configparser\",\n      \"configretry\",\n      \"configrpc\",\n      \"configschema\",\n      \"configsource\",\n      \"configtelemetry\",\n      \"configtest\",\n      \"configtls\",\n      \"configunmarshaler\",\n      \"confmap\",\n      \"confmaptest\",\n      \"connectorprofiles\",\n      \"connectortest\",\n      \"consumerdata\",\n      \"consumererror\",\n      \"consumererrorprofiles\",\n      \"consumerfanout\",\n      \"consumerhelper\",\n      \"consumerprofiles\",\n      \"consumertest\",\n      \"consumetest\",\n      \"conv\",\n      \"cookiejar\",\n      \"coreinternal\",\n      \"cpus\",\n      \"cpuscraper\",\n      \"crobert\",\n      \"crosslink\",\n      \"cumulativetodeltaprocessor\",\n      \"customname\",\n      \"dataloss\",\n      \"datapoints\",\n      \"debugexporter\",\n      \"defaultcomponents\",\n      \"dehaansa\",\n      \"distro\",\n      \"distros\",\n      \"djaglowski\",\n      \"dmathieu\",\n      \"dmitryax\",\n      \"dokey\",\n      \"envmapprovider\",\n      \"envprovider\",\n      \"eventcreate\",\n      \"exampleexporter\",\n      \"examplereceiver\",\n      \"expandconverter\",\n      \"expandmapconverter\",\n      \"expandvar\",\n      \"exporterbatch\",\n      \"exporterbatcher\",\n      \"exporterhelper\",\n      \"exporterhelperprofiles\",\n      \"exporterprofiles\",\n      \"exporterqueue\",\n      \"exportertest\",\n      \"exporthelper\",\n      \"expvar\",\n      \"extensionauth\",\n      \"extensionauthtest\",\n      \"extensioncapabilities\",\n      \"extensionhelper\",\n      \"extensionmiddleware\",\n      \"extensionmiddlewaretest\",\n      \"extensiontest\",\n      \"extensionz\",\n      \"fanout\",\n      \"fanoutconsumer\",\n      \"featureflags\",\n      \"featuregate\",\n      \"featuregates\",\n      \"featurez\",\n      \"fieldalignment\",\n      \"fileexporter\",\n      \"filemapprovider\",\n      \"fileprovider\",\n      \"filterprocessor\",\n      \"filterset\",\n      \"florianl\",\n      \"fluentbit\",\n      \"fluentforward\",\n      \"forwardconnector\",\n      \"fsnotify\",\n      \"funcs\",\n      \"gcflags\",\n      \"genotelcorecol\",\n      \"genpdata\",\n      \"genproto\",\n      \"goarm\",\n      \"gobenchmark\",\n      \"godoc\",\n      \"gofmt\",\n      \"gogenerate\",\n      \"goimpi\",\n      \"golangci\",\n      \"goldendataset\",\n      \"goleak\",\n      \"golint\",\n      \"gomod\",\n      \"gomoddownload\",\n      \"goporto\",\n      \"goproxy\",\n      \"goreleaser\",\n      \"goroutines\",\n      \"gotest\",\n      \"gotidy\",\n      \"govulncheck\",\n      \"groupbyattrprocessor\",\n      \"groupbytrace\",\n      \"groupbytraceprocessor\",\n      \"grpclb\",\n      \"guiton\",\n      \"healthcheck\",\n      \"healthcheckextension\",\n      \"healthcheckv\",\n      \"hostcapabilities\",\n      \"hostmetrics\",\n      \"hostmetricsreceiver\",\n      \"httpclientconfig\",\n      \"httpprovider\",\n      \"httpsprovider\",\n      \"httptest\",\n      \"illumos\",\n      \"incorrectclass\",\n      \"incorrectcomponent\",\n      \"incorrectstability\",\n      \"instrgen\",\n      \"internaldata\",\n      \"ints\",\n      \"invalidaggregation\",\n      \"invalidtype\",\n      \"iruntime\",\n      \"jaegerexporter\",\n      \"jaegerreceiver\",\n      \"jmacd\",\n      \"jpkrohling\",\n      \"jsoniter\",\n      \"jsonpb\",\n      \"kafkaexporter\",\n      \"kafkaexporter's\",\n      \"kafkareceiver\",\n      \"keepalive\",\n      \"koanf\",\n      \"labeldrop\",\n      \"ldflags\",\n      \"limitermiddleware\",\n      \"localhostgate\",\n      \"loggingexporter\",\n      \"logstest\",\n      \"lycheeverse\",\n      \"mapconverter\",\n      \"mapstructure\",\n      \"marshalers\",\n      \"mdatagen\",\n      \"mdatagen's\",\n      \"memorylimiter\",\n      \"memorylimiterextension\",\n      \"memorylimiterprocessor\",\n      \"metadatatest\",\n      \"metricfamily\",\n      \"metricreceiver\",\n      \"metricsexporter\",\n      \"metricsgenerationprocessor\",\n      \"metricstransformprocessor\",\n      \"middleware\",\n      \"mostynb\",\n      \"mowies\",\n      \"muehle\",\n      \"multiclient\",\n      \"multimod\",\n      \"mycert\",\n      \"mycomponent\",\n      \"myconnector\",\n      \"myexporter\",\n      \"myextension\",\n      \"myorg\",\n      \"myprocessor\",\n      \"myreceiver\",\n      \"myrepo\",\n      \"mysite\",\n      \"nodisplayname\",\n      \"nonclobbering\",\n      \"nopexporter\",\n      \"nopreceiver\",\n      \"nosuchprocessor\",\n      \"notls\",\n      \"obsreceiver\",\n      \"obsreport\",\n      \"obsreporttest\",\n      \"oidcauthextension\",\n      \"okey\",\n      \"oldstable\",\n      \"oltp\",\n      \"omitempty\",\n      \"omnition\",\n      \"opencensus\",\n      \"opencensusexporter\",\n      \"opencensusreceiver\",\n      \"otelbot\",\n      \"otelcol\",\n      \"otelcoltest\",\n      \"otelconf\",\n      \"otelconftelemetry\",\n      \"otelcorecol\",\n      \"otelgrpc\",\n      \"otelhttp\",\n      \"otelsvc\",\n      \"oteltest\",\n      \"otelzap\",\n      \"otlpexporter\",\n      \"otlpgrpc\",\n      \"otlp_http\",\n      \"otlphttp\",\n      \"otlphttpexporter\",\n      \"otlphttpexporter's\",\n      \"otlphttpreceiver\",\n      \"otlpjson\",\n      \"otlpmetrics\",\n      \"otlpreceiver\",\n      \"otlptext\",\n      \"overwritepropertiesconverter\",\n      \"overwritepropertiesmapconverter\",\n      \"parserprovider\",\n      \"pcommon\",\n      \"pdata\",\n      \"pdatagen\",\n      \"pdatagrpc\",\n      \"perfcounters\",\n      \"perflib\",\n      \"pipelineprofiles\",\n      \"pipelinez\",\n      \"pjanotti\",\n      \"plog\",\n      \"plogotlp\",\n      \"plogs\",\n      \"pmetric\",\n      \"pmetricotlp\",\n      \"policyevaluation\",\n      \"pprof\",\n      \"pprofextension\",\n      \"pprofile\",\n      \"pprofiles\",\n      \"pprofileotlp\",\n      \"preconfigured\",\n      \"priya\",\n      \"probabilisticsamplerprocessor\",\n      \"processorhelper\",\n      \"processorhelperprofiles\",\n      \"processorprofiles\",\n      \"processortest\",\n      \"processscraper\",\n      \"proctelemetry\",\n      \"prometheusexporter\",\n      \"prometheusreceiver\",\n      \"prometheusremotewrite\",\n      \"prometheusremotewriteexporter\",\n      \"protogen\",\n      \"protos\",\n      \"ptraceotlp\",\n      \"queuebatch\",\n      \"reaggregate\",\n      \"receiverhelper\",\n      \"receiverprofiles\",\n      \"receivertest\",\n      \"replicaset\",\n      \"renovatebot\",\n      \"resourcedetection\",\n      \"resourcedetectionprocessor\",\n      \"resourceprocessor\",\n      \"resourcetolabel\",\n      \"retryable\",\n      \"riscv\",\n      \"rpcz\",\n      \"rrschulze\",\n      \"runperf\",\n      \"safelist\",\n      \"sampleentity\",\n      \"sampleentityreceiver\",\n      \"samplefactoryreceiver\",\n      \"samplereceiver\",\n      \"samplingdecision\",\n      \"samplingprocessor\",\n      \"sarama\",\n      \"sattributes\",\n      \"sattributesprocessor\",\n      \"schemagen\",\n      \"scrapererror\",\n      \"scraperhelper\",\n      \"scrapertest\",\n      \"semconv\",\n      \"servicetelemetry\",\n      \"servicetest\",\n      \"servicez\",\n      \"sfixed\",\n      \"shanduur\",\n      \"sharedcomponent\",\n      \"sigstore\",\n      \"someclientid\",\n      \"someclientsecret\",\n      \"somevalue\",\n      \"songy\",\n      \"spanmetricsconnector\",\n      \"spanmetricsprocessor\",\n      \"spanprocessor\",\n      \"sprocessor\",\n      \"statusdata\",\n      \"statusreporting\",\n      \"statuswatcher\",\n      \"stdlib\",\n      \"stencel\",\n      \"stretchr\",\n      \"subcomponent\",\n      \"subcomponents\",\n      \"subpackages\",\n      \"swiatekm\",\n      \"syft\",\n      \"tailsampling\",\n      \"tchannel\",\n      \"telemetrygen\",\n      \"telemetrytest\",\n      \"testcomponents\",\n      \"testconverter\",\n      \"testdata\",\n      \"testdesc\",\n      \"testfunc\",\n      \"testonly\",\n      \"testprocessor\",\n      \"testprovider\",\n      \"testresults\",\n      \"testutil\",\n      \"tlsconfig\",\n      \"tmpl\",\n      \"tocstop\",\n      \"tpmrm\",\n      \"tracecontext\",\n      \"traceid\",\n      \"tracesonmemory\",\n      \"tracetranslator\",\n      \"tracez\",\n      \"transformprocessor\",\n      \"triager\",\n      \"triagers\",\n      \"triaging\",\n      \"uints\",\n      \"unixgram\",\n      \"unixpacket\",\n      \"unkeyed\",\n      \"unmarshal\",\n      \"unmarshalling\",\n      \"unmarshalls\",\n      \"unredacted\",\n      \"unshallow\",\n      \"unstarted\",\n      \"userfriendly\",\n      \"validatable\",\n      \"vanityurl\",\n      \"vmmetrics\",\n      \"withauth\",\n      \"xconfighttp\",\n      \"xconfmap\",\n      \"xconnector\",\n      \"xconsumer\",\n      \"xconsumererror\",\n      \"xexporter\",\n      \"xexporterhelper\",\n      \"xextension\",\n      \"xpdata\",\n      \"xpipeline\",\n      \"xprocessor\",\n      \"xprocessorhelper\",\n      \"xreceiver\",\n      \"xscraper\",\n      \"xscraperhelper\",\n      \"yamlmapprovider\",\n      \"yamlprovider\",\n      \"yamls\",\n      \"zapcore\",\n      \"zipkin\",\n      \"zipkinexporter\",\n      \"zipkinreceiver\",\n      \"zipkinv\",\n      \"zpages\",\n      \"zpagesextension\",\n      \"zstd\"\n    ],\n    \"enableGlobDot\": true,\n    \"useGitignore\": true,\n    \"files\": [\"**/*.{md,yaml,yml}\"],\n    \"globRoot\": \"../../..\",\n    \"ignorePaths\": [\n      \".git/*\",\n      \".git/!{COMMIT_EDITMSG,EDITMSG}\",\n      \".git/*/**\",\n      \".golangci.yml\",\n      \".github/**/*\"\n    ]\n}\n"
  },
  {
    "path": ".gitignore",
    "content": "bin/\ndist/\n/local\n.schemas\n\n# GoLand IDEA\n/.idea/\n*.iml\n\n# VS Code\n.vscode/\n.devcontainer/\n\n# Cursor\n.cursor\n\n# Emacs\n*~\n\\#*\\#\n\n# Miscellaneous files\n*.sw[op]\n*.DS_Store\n\n# Coverage\ncoverage/*\ncoverage.txt\n\n# Benchmarks\n**/benchmark.txt\nbenchmarks.txt\n\n# Wix\n*.wixobj\n*.wixpdb\n\n# golang\ngo.work*\n\n# npm (used for markdown-link-check)\nnode_modules/*\npackage-lock.json\n"
  },
  {
    "path": ".golangci.yml",
    "content": "formatters:\n  enable:\n    - gofumpt\n    - goimports\n\n  settings:\n    gofmt:\n      # simplify code: gofmt with `-s` option, true by default\n      simplify: true\n\n    gofumpt:\n      # Choose whether to use the extra rules\n      extra-rules: true\n\n    goimports:\n      # put imports beginning with prefix after 3rd-party packages;\n      # it's a comma-separated list of prefixes\n      local-prefixes:\n        - go.opentelemetry.io/collector\n\nissues:\n  # Maximum issues count per one linter.\n  max-issues-per-linter: 0\n  # Maximum count of issues with the same text.\n  max-same-issues: 0\n\nlinters:\n  enable:\n    - asasalint\n    - contextcheck\n    - copyloopvar\n    - decorder\n    - depguard\n    - errcheck\n    - errorlint\n    - fatcontext\n    - gocritic\n    - gosec\n    - govet\n    - misspell\n    - modernize\n    - nolintlint\n    - perfsprint\n    - revive\n    - staticcheck\n    - testifylint\n    - thelper\n    - unconvert\n    - unparam\n    - unused\n    - usestdlibvars\n    - usetesting\n    - whitespace\n\n  exclusions:\n    presets:\n      - std-error-handling\n\n    # Excluding configuration per-path, per-linter, per-text and per-source\n    rules: []\n\n    # Log a warning if an exclusion rule is unused.\n    warn-unused: true\n\n  # all available settings of specific linters\n  settings:\n    depguard:\n      rules:\n        denied-deps:\n          deny:\n            - pkg: \"go.uber.org/atomic\"\n              desc: \"Use 'sync/atomic' instead of go.uber.org/atomic\"\n            - pkg: \"gopkg.in/yaml.v3\"\n              desc: \"Use 'go.yaml.in/yaml/v3' instead of gopkg.in/yaml.v3\"\n            - pkg: \"github.com/pkg/errors\"\n              desc: \"Use 'errors' or 'fmt' instead of github.com/pkg/errors\"\n            - pkg: \"github.com/hashicorp/go-multierror\"\n              desc: \"Use go.uber.org/multierr instead of github.com/hashicorp/go-multierror\"\n            - pkg: \"math/rand$\"\n              desc: \"Use the newer 'math/rand/v2' instead of math/rand\"\n            - pkg: \"sigs.k8s.io/yaml\"\n              desc: \"Use 'go.yaml.in/yaml' instead of sigs.k8s.io/yaml\"\n        semconv:\n          list-mode: lax\n          files:\n            - \"!cmd/mdatagen/**\" # Exclude mdatagen\n          deny:\n            - pkg: go.opentelemetry.io/otel/semconv\n              desc: Use go.opentelemetry.io/otel/semconv/v1.38.0 instead. If a newer semconv version has been released, update the depguard rule.\n          allow:\n            - go.opentelemetry.io/otel/semconv/v1.38.0\n        # Add a different guard rule so that we can ignore tests.\n        ignore-in-test:\n          # Allow in tests for testing pdata or other receivers/exporters that expect OTLP.\n          files:\n            - '!**/*_test.go'\n          deny:\n            - pkg: go.opentelemetry.io/proto\n              desc: Use go.opentelemetry.io/collector/pdata instead\n\n    gocritic:\n      disabled-checks:\n        - commentedOutCode\n        - deferInLoop\n        - filepathJoin\n        - hugeParam\n        - importShadow\n        - rangeValCopy\n        - unnamedResult\n        - whyNoLint\n      enable-all: true\n\n    gosec:\n      excludes:\n        - G104 # FIXME\n        - G402\n        - G404\n\n    govet:\n      disable:\n        # We want to order fields according to readability and grouping them by use cases.\n        # This linter does not offer a discernible performance improvement as the structs\n        # defined in this repository are not in the execution hot path.\n        # See https://github.com/open-telemetry/opentelemetry-collector/issues/2789\n        - fieldalignment\n      enable-all: true\n      # settings per analyzer\n      settings:\n        printf: # analyzer name, run `go tool vet help` to see all analyzers\n          funcs: # run `go tool vet help printf` to see available settings for `printf` analyzer\n            - Infof\n            - Warnf\n            - Errorf\n            - Fatalf\n\n    misspell:\n      # Correct spellings using locale preferences for US or UK.\n      # Default is to use a neutral variety of English.\n      # Setting locale to US will correct the British spelling of 'colour' to 'color'.\n      locale: US\n      ignore-rules:\n        - cancelled\n\n    nolintlint:\n      require-specific: true\n\n    perfsprint:\n      # Optimizes even if it requires an int or uint type cast.\n      int-conversion: true\n      # Optimizes into `err.Error()` even if it is only equivalent for non-nil errors.\n      err-error: true\n      # Optimizes `fmt.Errorf`.\n      errorf: true\n      # Optimizes `fmt.Sprintf` with only one argument.\n      sprintf1: true\n      # Optimizes into strings concatenation.\n      strconcat: true\n\n    revive:\n      # minimal confidence for issues, default is 0.8\n      confidence: 0.8\n      rules:\n        # Blank import should be only in a main or test package, or have a comment justifying it.\n        - name: blank-imports\n        # context.Context() should be the first parameter of a function when provided as argument.\n        - name: context-as-argument\n        # Basic types should not be used as a key in `context.WithValue`\n        - name: context-keys-type\n        # Importing with `.` makes the programs much harder to understand\n        - name: dot-imports\n        - name: early-return\n          arguments:\n            - preserveScope\n        # Empty blocks make code less readable and could be a symptom of a bug or unfinished refactoring.\n        - name: empty-block\n        # for better readability, variables of type `error` must be named with the prefix `err`.\n        - name: error-naming\n        # for better readability, the errors should be last in the list of returned values by a function.\n        - name: error-return\n        # for better readability, error messages should not be capitalized or end with punctuation or a newline.\n        - name: error-strings\n        # report when replacing `errors.New(fmt.Sprintf())` with `fmt.Errorf()` is possible\n        - name: errorf\n        # incrementing an integer variable by 1 is recommended to be done using the `++` operator\n        - name: increment-decrement\n        # highlights redundant else-blocks that can be eliminated from the code\n        - name: indent-error-flow\n        # This rule suggests a shorter way of writing ranges that do not use the second value.\n        - name: range\n        # receiver names in a method should reflect the struct name (p for Person, for example)\n        - name: receiver-naming\n        # redefining built in names (true, false, append, make) can lead to bugs very difficult to detect.\n        - name: redefines-builtin-id\n        # redundant else-blocks that can be eliminated from the code.\n        - name: superfluous-else\n          arguments:\n            - preserveScope\n        # prevent confusing name for variables when using `time` package\n        - name: time-naming\n        # warns when an exported function or method returns a value of an un-exported type.\n        - name: unexported-return\n        - name: unnecessary-stmt\n        # spots and proposes to remove unreachable code. also helps to spot errors\n        - name: unreachable-code\n        # Functions or methods with unused parameters can be a symptom of an unfinished refactoring or a bug.\n        - name: unused-parameter\n        # Since Go 1.18, interface{} has an alias: any. This rule proposes to replace instances of interface{} with any.\n        - name: use-any\n        # report when a variable declaration can be simplified\n        - name: var-declaration\n        # warns when initialism, variable or package naming conventions are not followed.\n        - name: var-naming\n\n    staticcheck:\n      checks:\n        - all\n        - -ST1000\n        - -ST1021\n        - -ST1022\n\n    testifylint:\n      enable-all: true\n\n    thelper:\n      benchmark:\n        begin: false\n      fuzz:\n        begin: false\n      tb:\n        begin: false\n      test:\n        begin: false\n\n# output configuration options\noutput:\n  # The formats used to render issues.\n  formats:\n    # Prints issues in a text format with colors, line number, and linter name.\n    text:\n      # Output path can be either `stdout`, `stderr` or path to the file to write to.\n      path: stdout\n      # print linter name in the end of issue text, default is true\n      print-linter-name: true\n      # print lines of code with issue, default is true\n      print-issued-lines: true\n\n  # Show statistics per linter.\n  show-stats: false\n\n# options for analysis running\nrun:\n  # Allow multiple parallel golangci-lint instances running.\n  # If false (default) - golangci-lint acquires file lock on start.\n  allow-parallel-runners: true\n\n  # default concurrency is a available CPU number\n  concurrency: 4\n\n  # by default isn't set. If set we pass it to \"go list -mod={option}\". From \"go help modules\":\n  # If invoked with -mod=readonly, the go command is disallowed from the implicit\n  # automatic updating of go.mod described above. Instead, it fails when any changes\n  # to go.mod are needed. This setting is most useful to check that go.mod does\n  # not need updates, such as in a continuous integration and testing system.\n  # If invoked with -mod=vendor, the go command assumes that the vendor\n  # directory holds the correct copies of dependencies and ignores\n  # the dependency descriptions in go.mod.\n  modules-download-mode: readonly\n\n  # exit code when at least one issue was found, default is 1\n  issues-exit-code: 1\n\n  # include test files or not, default is true\n  tests: true\n\n  # timeout for analysis, e.g. 30s, 5m, default is 1m\n  timeout: 10m\n\nversion: \"2\"\n"
  },
  {
    "path": ".markdownlint.yaml",
    "content": "# markdownlint configuration for OpenTelemetry Collector\n# https://github.com/DavidAnson/markdownlint/blob/main/doc/Rules.md\n#\n# Start permissive to establish a baseline; tighten rules over time.\ndefault: true\n\n# Disabled rules (existing codebase has many violations)\nMD001: false  # heading increment\nMD004: false  # unordered list style\nMD007: false  # unordered list indentation\nMD009: false  # trailing spaces\nMD010: false  # hard tabs\nMD012: false  # multiple consecutive blank lines\nMD013: false  # line length\nMD014: false  # dollar signs in commands\nMD022: false  # blanks around headings\nMD024: false  # duplicate headings\nMD025: false  # multiple top-level headings\nMD026: false  # trailing punctuation in heading\nMD029: false  # ordered list prefix\nMD030: false  # spaces after list markers\nMD031: false  # blanks around fences\nMD032: false  # blanks around lists\nMD033: false  # inline HTML\nMD034: false  # bare URLs\nMD036: false  # emphasis as heading\nMD038: false  # spaces in code spans\nMD040: false  # fenced code language\nMD041: false  # first line heading\nMD047: false  # single trailing newline\nMD049: false  # emphasis style\nMD051: false  # link fragments\nMD053: false  # unused link definitions\nMD058: false  # blanks around tables\nMD059: false  # descriptive link text\nMD060: false  # table column style\nMD018: false  # no space after hash in heading\nMD028: false  # blank line inside blockquote\nMD037: false  # spaces inside emphasis\n"
  },
  {
    "path": ".markdownlintignore",
    "content": "# Changelogs (autogenerated, chloggen manages structure)\nCHANGELOG.md\nCHANGELOG-API.md\n\n# GitHub templates (intentional structure/HTML)\n.github/\n"
  },
  {
    "path": "AGENTS.md",
    "content": "# AGENTS.md\n\nThis file is here to steer AI assisted PRs towards being high quality and valuable contributions\nthat do not create excessive maintainer burden. It is inspired by the Open Policy Agent and Fedora\nprojects policies.\n\n## General Rules and Guidelines\n\nThe most important rule is not to post comments on issues or PRs that are AI-generated. Discussions\non the OpenTelemetry repositories are for Users/Humans only.\n\nFollow the PR scoping guidance in [CONTRIBUTING.md](CONTRIBUTING.md). Keep AI-assisted PRs tightly\nisolated to the requested change and never include unrelated cleanup or opportunistic improvements\nunless they are strictly necessary for correctness.\n\nIf you have been assigned an issue by the user or their prompt, please ensure that the\nimplementation direction is agreed on with the maintainers first in the issue comments. If there are\nunknowns, discuss these on the issue before starting implementation. Do not forget that you cannot\ncomment for users on issue threads on their behalf as it is against the rules of this project.\n\n## Developer environment\n\nMake sure to follow docs/coding-guidelines.md on any contributions.\n\nNon-exhaustively, the important points are:\n\n* Whenever applicable, all code changes should have tests that actually validate the changes.\n\n## Commit formatting\n\nWe appreciate it if users disclose the use of AI tools when the significant part of a commit is\ntaken from a tool without changes. When making a commit this should be disclosed through an\nAssisted-by: commit message trailer.\n\nExamples:\n\n```\nAssisted-by: ChatGPT 5.2\nAssisted-by: Claude Opus 4.5\n```\n"
  },
  {
    "path": "CHANGELOG-API.md",
    "content": "<!-- This file is autogenerated. See CONTRIBUTING.md for instructions to add an entry. -->\n\n# Go API Changelog\n\nThis changelog includes only developer-facing changes.\nIf you are looking for user-facing changes, check out [CHANGELOG.md](./CHANGELOG.md).\n\n<!-- next version -->\n\n## v1.54.0/v0.148.0\n\n### 🛑 Breaking changes 🛑\n\n- `cmd/mdatagen`: Generate a per-metric config type `<MetricName>Config` for each metric when `reaggregation_enabled: true` (#14689)\n  Metrics with aggregatable attributes get `AggregationStrategy` and `EnabledAttributes []<MetricName>AttributeKey`\n  fields; others get `Enabled` only. Typed attribute key constants (e.g. `DefaultMetricAttributeKeyStringAttr`)\n  replace `[]string`, eliminating runtime attribute slice allocations. Validation errors now list valid attributes\n  and strategies by name. Components using `reaggregation_enabled: true` will need to update references to `MetricConfig`.\n  \n- `pdata/pprofile`: Update protoID for message Sample fields (#14652)\n\n### 💡 Enhancements 💡\n\n- `cmd/mdatagen`: Extend mdatagen tool to generate go config structs for OpenTelemetry collector components. (#14561)\n  The component config go code is generated from `config` section of the metadata.yaml file.\n- `cmd/mdatagen`: Extend mdatagen tool to generate config JSON schema for OpenTelemetry components. (#14543)\n  The component config JSON schema is generated from `config` section of the metadata.yaml file.\n- `cmd/mdatagen`: Schema generation for mdatagen-controlled config parts (#14562)\n  The schema is generated in separate yaml file and used to create full component schema.\n- `pdata/pprofile`: Implement reference based attributes in Profiles (#14546)\n- `pkg/pdata`: Upgrade the OTLP protobuf definitions to version 1.10.0 (#14766)\n- `pkg/service`: The internal status reporter no longer drops repeated Ok and RecoverableError statuses (#14282)\n  Status events can now carry metadata and there's value in allowing them to be emitted despite the status value itself \n  not changing.\n  \n- `pkg/xexporterhelper`: Add logic to cleanup partitions from memory which are not being used for specific time period. (#14526)\n- `pkg/xpdata`: Add `NewEntity` constructor, `Entity.CopyToResource`, and `EntityAttributeMap.All` to `pdata/xpdata/entity` (#14659)\n\n### 🧰 Bug fixes 🧰\n\n- `cmd/mdatagen`: Preserve custom extensions (e.g., `x-customType`, `x-pointer`) during schema reference resolution. (#14713, #14565)\n  Fixes an issue where custom properties defined locally on a node were \n  overwritten and lost when resolving a `$ref` to an external/internal schema.\n  \n- `pkg/xexporterhelper`: Fix race when partition is being removed from LRU and new items are being added at the same time. (#14526)\n\n<!-- previous-version -->\n\n## v1.53.0/v0.147.0\n\n### 💡 Enhancements 💡\n\n- `pkg/exporterhelper`: Add `metadata_keys` configuration to `sending_queue.batch.partition` to partition batches by client metadata (#14139)\n  The `metadata_keys` configuration option is now available in the `sending_queue.batch.partition` section for all exporters.\n  When specified, batches are partitioned based on the values of the listed metadata keys, allowing separate batching per metadata partition. This feature\n  is automatically configured when using `exporterhelper.WithQueue()`.\n  \n- `pkg/xexporterhelper`: Add code structure to handle unbounded partitions in sending queue. (#14526)\n\n### 🧰 Bug fixes 🧰\n\n- `pkg/config/configmiddleware`: Add context.Context to gRPC middleware interface constructors. (#14523)\n- `pkg/extensionmiddleware`: Add context.Context to gRPC middleware interface constructors. (#14523)\n  This is a breaking API change for components that implement or use extensionmiddleware.\n\n<!-- previous-version -->\n\n## v1.52.0/v0.146.1\n\n<!-- previous-version -->\n\n## v0.146.0\n\n### 🛑 Breaking changes 🛑\n\n- `cmd/mdatagen`: Flatten the metric stability field (#14113)\n  So we better match the weaver schema. Additional deprecation data can be set within the `deprecated` field.\n\n### 🚩 Deprecations 🚩\n\n- `pdata/pprofile`: Declare removed aggregation elements as deprecated. (#14528)\n\n### 💡 Enhancements 💡\n\n- `cmd/mdatagen`: Add entity association requirement for metrics and events when entities are defined (#14284)\n- `pkg/otelcol`: Gate process signals behind build tags (#14542)\n  Particularly for Wasm on JS, there are no invalid process signal references, which would cause build failures.\n\n<!-- previous-version -->\n\n## v1.51.0/v0.145.0\n\n### 💡 Enhancements 💡\n\n- `pkg/config/configgrpc`: add client info to context before server authentication (#12836)\n- `pkg/xscraperhelper`: Add AddProfilesScraper similar to scraperhelper.AddMetricsScraper (#14427)\n\n### 🧰 Bug fixes 🧰\n\n- `pkg/config/configoptional`: Fix `Unmarshal` methods not being called when config is wrapped inside `Optional` (#14500)\n  This bug notably manifested in the fact that the `sending_queue::batch::sizer` config for exporters\n  stopped defaulting to `sending_queue::sizer`, which sometimes caused the wrong units to be used\n  when configuring `sending_queue::batch::min_size` and `max_size`.\n  \n  As part of the fix, `xconfmap` exposes a new `xconfmap.WithForceUnmarshaler` option, to be used in the `Unmarshal` methods\n  of wrapper types like `configoptional.Optional` to make sure the `Unmarshal` method of the inner type is called.\n  \n  The default behavior remains that calling `conf.Unmarshal` on the `confmap.Conf` passed as argument to an `Unmarshal`\n  method will skip any top-level `Unmarshal` methods to avoid infinite recursion in standard use cases. \n  \n\n<!-- previous-version -->\n\n## v1.50.0/v0.144.0\n\n### 🛑 Breaking changes 🛑\n\n- `pkg/config/confighttp`: Replace `ServerConfig.Endpoint` with `NetAddr confignet.AddrConfig`, enabling more flexible transport configuration. (#14187, #8752)\n  This change adds \"transport\" as a configuration option, allowing users to specify\n  different transport protocols (e.g., \"tcp\", \"unix\").\n  \n\n### 🚩 Deprecations 🚩\n\n- `pkg/scraperhelper`: Deprecate the `AddScraper` method. (#14428)\n\n### 🚀 New components 🚀\n\n- `pkg/xscraperhelper`: Add xscraperhelper for the experimental OTel profiling signal. (#14235)\n\n### 💡 Enhancements 💡\n\n- `all`: Add support for deprecated component type aliases (#14208)\n  To add a deprecated type alias to a component factory, use the `WithDeprecatedTypeAlias` option.\n  ```go\n  return xexporter.NewFactory(\n      metadata.Type,\n      createDefaultConfig,\n      xexporter.WithTraces(createTracesExporter, metadata.TracesStability),\n      xexporter.WithDeprecatedTypeAlias(\"old_component_name\"),\n  )\n  ```\n  When the alias is used in configuration, a deprecation warning will be automatically logged, and the component will function normally using the original implementation.\n  \n- `cmd/mdatagen`: Add the ability to disable attributes at the metric level and re-aggregate data points based off of these new dimensions (#10726)\n- `extension/xextension`: Add deprecated type alias support for extensions via `xextension` module (#14208)\n  Extensions can now register deprecated type aliases using the experimental `xextension.WithDeprecatedTypeAlias` option.\n  ```go\n  return xextension.NewFactory(\n      metadata.Type,\n      createDefaultConfig,\n      createExtension,\n      metadata.Stability,\n      xextension.WithDeprecatedTypeAlias(\"old_extension_name\"),\n  )\n  ```\n  When the alias is used in configuration, a deprecation warning will be automatically logged, and the extension will function normally using the original implementation.\n  \n- `pkg/consumer/consumertest`: Add ProfileCount() (#14251)\n- `pkg/exporterhelper`: Add support for profile samples metrics (#14423)\n- `pkg/receiverhelper`: Add support for profile samples metrics (#14226)\n- `pkg/scraperhelper`: Introduce `AddMetricsScraper` to be more explicit than `AddScraper`. (#14428)\n- `receiver/otlp`: Add metrics tracking the number of receiver, refused and failed profile samples (#14226)\n\n### 🧰 Bug fixes 🧰\n\n- `pkg/xconnector`: Add component ID type validation to all xconnector Create methods (#14357)\n\n<!-- previous-version -->\n\n## v1.49.0/v0.143.0\n\n### 🛑 Breaking changes 🛑\n\n- `pkg/xprocessor`: Use pointer receivers in xprocessor factory methods for consistency with other factories. (#14348)\n\n<!-- previous-version -->\n\n## v1.48.0/v0.142.0\n\n### 🛑 Breaking changes 🛑\n\n- `pdata/xpdata`: Rename `Entity.IDAttributes()` to `Entity.IdentifyingAttributes()` and `Entity.DescriptionAttributes()` to `Entity.DescriptiveAttributes()` to align with OpenTelemetry specification terminology for attributes. (#14275)\n- `pkg/exporterhelper`: Use `configoptional.Optional` for the `exporterhelper.QueueBatchConfig` (#14155)\n  It's recommended to change the field type in your component configuration to be `configoptional.Optional[exporterhelper.QueueBatchConfig]` to keep the `enabled` subfield. Use configoptional.Some(exporterhelper.NewDefaultQueueConfig()) to enable by default. Use configoptional.Default(exporterhelper.NewDefaultQueueConfig()) to disable by default.\n  \n\n### 🚩 Deprecations 🚩\n\n- `pkg/service`: Deprecate Settings.LoggingOptions and telemetry.LoggerSettings.ZapOptions, add telemetry.LoggerSettings.BuildZapLogger (#14002)\n  BuildZapLogger provides a more flexible way to build the Zap logger,\n  since the function will have access to the zap.Config. This is used\n  in otelcol to install a Windows Event Log output when the zap config\n  does not specify any file output.\n  \n\n### 💡 Enhancements 💡\n\n- `pdata/pprofile`: add ProfileCount() (#14239)\n\n### 🧰 Bug fixes 🧰\n\n- `pkg/confmap`: Ensure that embedded structs are not overwritten after Unmarshal is called (#14213)\n  This allows embedding structs which implement Unmarshal and contain a configopaque.String.\n  \n\n<!-- previous-version -->\n\n## v1.47.0/v0.141.0\n\n### 🛑 Breaking changes 🛑\n\n- `pkg/config/configgrpc`: Replace `component.Host` parameter of ToServer/ToClientConn by map of extensions (#13640)\n  Components must now pass the map obtained from the host's `GetExtensions` method\n  instead of the host itself.\n  \n  Nil may be used in tests where no middleware or authentication extensions are used.\n  \n- `pkg/config/confighttp`: Replace `component.Host` parameter of ToServer/ToClient by map of extensions (#13640)\n  Components must now pass the map obtained from the host's `GetExtensions` method\n  instead of the host itself.\n  \n  Nil may be used in tests where no middleware or authentication extensions are used.\n  \n\n### 🚩 Deprecations 🚩\n\n- `pkg/pdata`: Deprecate profile.Duration() and profile.SetDuration() (#14188)\n\n### 💡 Enhancements 💡\n\n- `pdata/pprofile`: Introduce `MergeTo` method (#14091)\n- `pkg/pdata`: Add profile.DurationNano() and profile.SetDurationNano() (#14188)\n\n<!-- previous-version -->\n\n## v1.46.0/v0.140.0\n\n### 🛑 Breaking changes 🛑\n\n- `pdata/pprofile`: Upgrade the OTLP protobuf definitions to version 1.9.0 (#14128)\n  * Drop field `CommentStrindices` in `Profile`.\n  * Rename `Sample` to `Samples` in `Profile`.\n  * Rename `Line` to `Lines` in `Location`.\n  * Remove `AggregationTemporality` field in `ValueType`.\n  \n  See https://github.com/open-telemetry/opentelemetry-proto/releases/tag/v1.9.0\n  \n- `pkg/otelcol`: The `otelcol.Factories.Telemetry` field is now required (#14003)\n  Previously if this field was not set, then it would default to an otelconftelemetry factory.\n  Callers of the otelcol package must now set the field explicitly.\n  \n\n### 💡 Enhancements 💡\n\n- `pkg/pdata`: Upgrade the OTLP protobuf definitions to version 1.9.0 (#14128)\n\n<!-- previous-version -->\n\n## v1.45.0/v0.139.0\n\n### 🛑 Breaking changes 🛑\n\n- `all`: Change type of `configgrpc.ClientConfig.Headers`, `confighttp.ClientConfig.Headers`, and `confighttp.ServerConfig.ResponseHeaders` (#13930)\n  `configopaque.MapList` is a new alternative to `map[string]configopaque.String` which can unmarshal\n  both maps and lists of name/value pairs.\n  \n  For example, if `headers` is a field of type `configopaque.MapList`,\n  then the following YAML configs will unmarshal to the same thing:\n  ```yaml\n  headers:\n    \"foo\": \"bar\"\n  \n  headers:\n  - name: \"foo\"\n    value: \"bar\"\n  ```\n  \n- `pdata/pprofile`: Update `SetFunction` to return the function's ID rather than update the Line (#14016, #14032)\n- `pdata/pprofile`: Update `SetLink` to return the link's ID rather than update the Sample (#14016, #14031)\n- `pdata/pprofile`: Update `SetMapping` to return the mapping's ID rather than update the Location (#14016, #14030)\n- `pkg/otelcol`: Require a telemetry factory to be injected through otelcol.Factories (#4970)\n  otelcol.Factories now has a required Telemetry field,\n  which contains the telemetry factory to be used by the service.\n  Set it to otelconftelemetry.NewFactory() for the existing behavior.\n  \n- `pkg/pdata`: Remove unused generated code from pprofile (#14073)\n  Experimental package, ok to break since not used.\n\n### 💡 Enhancements 💡\n\n- `pdata/pprofile`: Introduce `SetStack` method (#14007)\n- `pdata/xpdata`: Add high-level Entity API for managing entities attached to resources (#14042)\n  Introduces `Entity`, `EntitySlice`, and `EntityAttributeMap` types that provide a user-friendly interface\n  for working with resource entities. The new API ensures consistency between entity and resource attributes\n  by sharing the underlying attribute map, and prevents attribute conflicts between entities. This API may\n  eventually replace the generated protobuf-based API for better usability.\n  \n\n### 🧰 Bug fixes 🧰\n\n- `cmd/mdatagen`: Fix mdatagen generated_metrics for connectors (#12402)\n\n<!-- previous-version -->\n\n## v1.44.0/v0.138.0\n\n### 🛑 Breaking changes 🛑\n\n- `pkg/xexporterhelper`: Remove definition of Sizer from public API and ability to configure. (#14001)\n  Now that Request has both Items/Bytes sizes no need to allow custom sizers.\n  \n- `pkg/service`: The `service.Settings` type now requires a `telemetry.Factory` to be provided (#4970)\n\n### 🚩 Deprecations 🚩\n\n- `pdata/pprofile`: Deprecated `PutAttribute` helper method (#14016, #14041)\n- `pdata/pprofile`: Deprecated `PutLocation` helper method (#14019)\n\n### 💡 Enhancements 💡\n\n- `all`: Add `keep_alives_enabled` option to ServerConfig to control HTTP keep-alives for all components that create an HTTP server. (#13783)\n- `pkg/pdata`: Add pcommon.Map helper to add a key to the map if does not exists (#14023)\n- `pdata/pprofile`: Introduce `Equal` method on the `KeyValueAndUnit` type (#14041)\n- `pkg/pdata`: Add `RemoveIf` method to primitive slice types (StringSlice, Int64Slice, UInt64Slice, Float64Slice, Int32Slice, ByteSlice) (#14027)\n- `pdata/pprofile`: Introduce `SetAttribute` helper method (#14016, #14041)\n- `pdata/pprofile`: Introduce `SetLocation` helper method (#14019)\n- `pdata/pprofile`: Introduce `Equal` method on the `Stack` type (#13952)\n\n<!-- previous-version -->\n\n## v1.43.0/v0.137.0\n\n### 🛑 Breaking changes 🛑\n\n- `pkg/exporterhelper`: Remove all experimental symbols in exporterhelper (#11143)\n  They have all been moved to xexporterhelper\n  \n\n### 🚩 Deprecations 🚩\n\n- `all`: service/telemetry.TracesConfig is deprecated (#13904)\n  This type alias has been added to otelconftelemetry.TracesConfig,\n  where the otelconf-based telemetry implementation now lives.\n  \n\n### 💡 Enhancements 💡\n\n- `all`: Mark configoptional as stable (#13403)\n- `all`: Mark configauth module as 1.0 (#9476)\n- `pkg/pdata`: Mark featuregate pdata.useCustomProtoEncoding as stable (#13883)\n\n<!-- previous-version -->\n\n## v1.42.0/v0.136.0\n\n### 🛑 Breaking changes 🛑\n\n- `exporterhelper`: Remove deprecated function NewRequestsSizer (#13803)\n- `pdata/pprofile`: Upgrade the OTLP protobuf definitions to version 1.8.0 (#13758, #13825, #13839)\n- `pdata/pprofile`: Remove deprecated ProfilesDictionary method (#13858)\n\n### 🚩 Deprecations 🚩\n\n- `exporterhelper`: Deprecate all experimental symbols in exporterhelper and move them to xexporterhelper (#11143)\n\n### 💡 Enhancements 💡\n\n- `configoptional`: Add `GetOrInsertDefault` method to `configoptional.Optional` (#13856)\n  This method inserts a default or zero value into a `None`/`Default` `Optional` before `Get`ting its inner value.\n  \n- `exporter`: Stabilize exporter module. (#12978)\n  This does not stabilize the exporterhelper module or configuration\n- `pdata`: Upgrade the OTLP protobuf definitions to version 1.8.0 (#13758)\n\n<!-- previous-version -->\n\n## v1.41.0/v0.135.0\n\n### 🛑 Breaking changes 🛑\n\n- `pdata/pprofile`: Remove deprecated AddAttribute method (#13764)\n\n### 💡 Enhancements 💡\n\n- `configmiddleware`: Stabilize `configmiddleware` module (#13422)\n  This only stabilizes the configuration interface but does not stabilize the middlewares themselves or the way of implementing them.\n- `xpdata`: Add experimental MapBuilder struct to optimize pcommon.Map construction (#13617)\n\n<!-- previous-version -->\n\n## v1.40.0/v0.134.0\n\n### 💡 Enhancements 💡\n\n- `exporterhelper`: Split exporterhelper into a separate module (#12985)\n\n<!-- previous-version -->\n\n## v1.39.0/v0.133.0\n\n### 🛑 Breaking changes 🛑\n\n- `configgrpc`: Set `tcp` as the default transport type (#13657)\n  gRPC is generally used with HTTP/2, so this will simplify usage for most components.\n\n### 🚩 Deprecations 🚩\n\n- `pdata/pprofile`: Deprecate Profiles.ProfilesDictionary in favor of Profiles.Dictionary. (#13644)\n\n### 💡 Enhancements 💡\n\n- `pdata`: Add support for local memory pooling for data objects. (#13678)\n  This is still an early experimental (alpha) feature. Do not recommended to be used production. To enable use \"--featuregate=+pdata.useProtoPooling\"\n\n### 🧰 Bug fixes 🧰\n\n- `configoptional`: Allow validating nested types (#13579)\n  `configoptional.Optional` now implements `xconfmap.Validator`\n\n<!-- previous-version -->\n\n## v1.38.0/v0.132.0\n\n### 🛑 Breaking changes 🛑\n\n- `componenttest`: Remove `GetFactory` from the host returned by `NewNopHost` (#13577)\n  This method is no longer part of the `component.Host` interface.\n\n### 💡 Enhancements 💡\n\n- `exporterhelper`: Provide an interface `queue_batch.Setting.MergeCtx` so users can control how context values are preserved or combined (#13320)\n  By supplying a custom mergeCtx function, users can control how context values are preserved or combined.\n  The default behavior is to preserve no context values.\n  \n- `pdata`: Generate Logs/Traces/Metrics/Profiles and p[log|trace|metric|profile]ExportResponse with pdatagen. (#13597)\n  This change brings consistency on how these structs are written and remove JSON marshaling/unmarshaling hand written logic.\n- `pdata`: Avoid unnecessary buffer copy when JSON marshal fails. (#13598)\n- `pipeline`: Mark module as stable (#12831)\n\n<!-- previous-version -->\n\n## v1.37.0/v0.131.0\n\n### 🛑 Breaking changes 🛑\n\n- `configgrpc`: Update optional fields to use `configoptional.Optional` field for optional values. (#13252, #13364)\n  Specifically, the following fields have been updated to `configoptional`:\n  - `KeepaliveServerConfig.ServerParameters` (`KeepaliveServerParameters` type)\n  - `KeepaliveServerConfig.EnforcementPolicy` (`KeepaliveEnforcementPolicy` type)\n  \n- `xexporterhelper`: Remove deprecated NewProfilesExporter function from xexporterhelper package (#13391)\n\n### 💡 Enhancements 💡\n\n- `consumererror`: Add new \"Downstream\" error marker (#13234)\n  This new error wrapper type indicates that the error returned by a component's\n  `Consume` method is not an internal failure of the component, but instead\n  was passed through from another component further downstream.\n  This is used internally by the new pipeline instrumentation feature to\n  determine the `outcome` of a component call. This wrapper is not intended to\n  be used by components directly.\n  \n- `pdata/pprofile`: Introduce `Equal` method on the `Function` type (#13222)\n- `pdata/pprofile`: Introduce `Equal` method on the `Link` type (#13223)\n- `pdata/pprofile`: Add new helper method `SetFunction` to set a new function on a line. (#13222)\n- `pdata/pprofile`: Add new helper method `SetLink` to set a new link on a sample. (#13223)\n- `pdata/pprofile`: Add new helper method `SetString` to set or retrieve the index of a value in the StringTable. (#13225)\n\n<!-- previous-version -->\n\n## v1.36.1/v0.130.1\n\n<!-- previous-version -->\n\nNo API-only changes in this release.\n\n## v1.36.0/v0.130.0\n\n### 🛑 Breaking changes 🛑\n\n- `exporterhelper`: Use configoptional for sending_queue::batch field (#13345)\n- `configgrpc`: Update optional fields to use `configoptional.Optional` field for optional values. (#13250, #13252)\n  Components using `configgrpc` package may need to update config values.\n- `confighttp`: Use configoptional.Optional in confighttp (#9478)\n- `exporterhelper`: Remove sizer map in favor of items/bytes sizers. Request based is automatically supported. (#13262)\n- `pdata/pprofile`: Remove field Profile.StartTime from pdata/pprofile (#13315)\n  Remove Profile.StartTime from OTel Profiling signal.\n- `exporterhelper`: Remove deprecated old batcher config (#13003)\n- `exporter/otlp`: Remove deprecated batcher config from OTLP, use queuebatch (#13339)\n\n### 🚩 Deprecations 🚩\n\n- `exporterhelper`: Deprecate NewRequestsSizer always supported. (#13262)\n- `xexporterhelper`: Introduce NewProfiles method and deprecate NewProfilesExporter (#13372)\n\n### 💡 Enhancements 💡\n\n- `consumererror`: Add `Error` type (#7047)\n  This type can contain information about errors that allow components (e.g. exporters)\n  to communicate error information back up the pipeline.\n  \n- `pdata`: Document that changing pcommon.Map (Remove/removeIf/Put*) invalidates Value references obtained via Get. (#13073)\n- `cmd/mdatagen`: Add support for optional attribute (#12571)\n- `exporterhelper`: Add support to configure a different Sizer for the batcher than the queue (#13313)\n- `pdata`: Add support for the new resource-entity reference API as part of the experimental xpdata package. (#13264)\n\n<!-- previous-version -->\n\n## v1.35.0/v0.129.0\n\n### 🛑 Breaking changes 🛑\n\n- `semconv`: Removing deprecated semconv package (#13071)\n- `configgrpc,confighttp`: Unify return type of `NewDefault*Config` functions to return a struct instead of a pointer. (#13169)\n- `exporterhelper`: QueueBatchEncoding interface is changed to support marshaling and unmarshaling of request context. (#13188)\n\n### 💡 Enhancements 💡\n\n- `pdata/pprofile`: Introduce `Equal` method on the `Mapping` type (#13197)\n- `configoptional`: Make unmarshaling into `None[T]` work the same as unmarshaling into `(*T)(nil)`. (#13168)\n- `configoptional`: Add a confmap.Marshaler implementation for configoptional.Optional (#13196)\n- `pdata/pprofile`: Introduce `Equal` methods on the `Line` and `Location` types (#13150)\n- `pdata/pprofile`: Add new helper method `SetMapping` to set a new mapping on a location. (#13197)\n\n### 🧰 Bug fixes 🧰\n\n- `confmap`: Distinguish between empty and nil values when marshaling `confmap.Conf` structs. (#13196)\n\n<!-- previous-version -->\n\n## v1.34.0/v0.128.0\n\n### 🛑 Breaking changes 🛑\n\n- `exporterhelper`: Remove deprecated NewProfilesRequestExporter function from xexporterhelper package (#13157)\n- `confighttp`: Remove pointer to field `cookies` in confighttp.ClientConfig (#13116)\n- `otlpreceiver`: Use `configoptional.Optional` to define optional configuration sections in the OTLP receiver. Remove `Unmarshal` method. (#13119)\n- `confighttp,configgrpc`: Rename `ClientConfig.TLSSetting` and `ServerConfig.TLSSetting` to `ClientConfig.TLS` and `ServerConfig.TLS`. (#13115)\n- `pdata/pprofile`: Upgrade the OTLP protobuf definitions to version 1.7.0 (#13075)\n  Note that the batcher is temporarily a noop.\n- `pipeline`: Remove deprecated MustNewID[WithName] (#13139)\n\n### 🚀 New components 🚀\n\n- `configoptional`: Add a new configoptional module to support optional configuration fields. (#12981)\n\n### 💡 Enhancements 💡\n\n- `pdata`: Introduce `MoveAndAppendTo` methods to the generated primitive slices (#13074)\n- `pdata`: Upgrade the OTLP protobuf definitions to version 1.7.0 (#13075)\n\n### 🧰 Bug fixes 🧰\n\n- `confmap`: Correctly distinguish between `nil` and empty map values on the `ToStringMap` method (#13161)\n  This means that `ToStringMap()` method can now return a nil map if the original value was `nil`.\n  If you were not doing so already, make sure to check for `nil` before writing to the map to avoid panics.\n  \n- `confighttp`: Make the `NewDefaultServerConfig` function return a nil TLS config by default. (#13129)\n  - The previous default was a TLS config with no certificates, which would fail at runtime.\n  \n\n<!-- previous-version -->\n\n## v1.33.0/v0.127.0\n\n### 🛑 Breaking changes 🛑\n\n- `mdatagen`: Add context parameter for recording event to set traceID and spanID (#12571)\n- `otlpreceiver`: Use wrapper type for URL paths (#13046)\n\n### 🚩 Deprecations 🚩\n\n- `pipeline`: Deprecate MustNewID and MustNewIDWithName (#12831)\n- `pdata/profile`: Replace AddAttribute with the PutAttribute helper method to modify the content of attributable records. (#12798)\n\n### 💡 Enhancements 💡\n\n- `consumer/consumertest`: Add context to sinks (#13039)\n- `cmd/mdatagen`: Add events in generated documentation (#12571)\n- `confmap`: Add a `Conf.Delete` method to remove a path from the configuration map. (#13064)\n- `confmap`: Support running Unmarshal hooks on nil values. (#12981)\n\n<!-- previous-version -->\n\n## v1.32.0/v0.126.0\n\n### 🚩 Deprecations 🚩\n\n- `configauth`: Deprecate `configauth.Authentication` in favor of `configauth.Config`. (#12875)\n\n### 💡 Enhancements 💡\n\n- `cmd/mdatagen`: Add type definition for events in mdatagen (#12571)\n- `cmd/mdatagen`: Add functions for processing structured events in mdatagen (#12571)\n\n<!-- previous-version -->\n\n## v1.31.0/v0.125.0\n\n### 🚩 Deprecations 🚩\n\n- `extensionauthtest`: Deprecate NewErrorClient in favor of NewErrClient. (#12874)\n\n### 💡 Enhancements 💡\n\n- `xextension/storage`: ErrStorageFull error added to xextension/storage contract (#12925)\n- `pdata`: Add MoveTo to pcommon.Value, only type missing this (#12877)\n\n### 🧰 Bug fixes 🧰\n\n- `pdata`: Fix MoveTo when moving to the same destination (#12887)\n\n<!-- previous-version -->\n\n## v1.30.0/v0.124.0\n\n### 🛑 Breaking changes 🛑\n\n- `exporterbatcher`: Remove deprecated package exporterbatcher (#12780)\n- `exporterqueue`: Remove deprecated package exporterqueue (#12779)\n\n### 💡 Enhancements 💡\n\n- `mdatagen`: Add variable for metric name in mdatagen (#12459)\n  Access metric name via `metadata.MetricsInfo.<metric-variable>.Name`\n- `client`: Add support for iterating over client metadata keys (#12804)\n- `service`: Adds the GetFactory interface to the hostcapabilities package (#12789)\n- `cmd/mdatagen`: Add the foundational changes necessary for supporting logs data in `mdatagen` (#12571)\n\n<!-- previous-version -->\n\n## v1.29.0/v0.123.0\n\n### 🛑 Breaking changes 🛑\n\n- `otlpreceiver/otlpexporter/otlphttpexporter`: Avoid using go embedded messages in Config (#12718)\n- `exporterqueue`: Move Queue interface to internal, disallow alternative implementations (#12680)\n- `extensionauth, configauth`: Remove deprecated types and functions from `extensionauth` and `configauth` packages. (#12672)\n  This includes:\n  - `extensionauth.NewClient`,\n  - `extensionauth.ClientOption` and all its implementations,\n  - `extensionauth.NewServer`,\n  - `extensionauth.ServerOption` and all its implementations and\n  - `configauth.Authenticator.GetClientAuthenticator`.\n  \n- `exporterhelper`: Remove deprecated converter types from exporterhelper (#12686)\n- `exporterbatch`: Remove deprecated fields `min_size_items` and `max_size_items` from batch config. (#12684)\n\n### 🚩 Deprecations 🚩\n\n- `exporterhelper`: Deprecate BatcherConfig, SizeConfig and WithBatcher in favor of the new QueueBatchConfig. (#12748)\n- `exporterbatcher`: Deprecated Config, SizeConfig, SizerType, SizerType[Requests|Items|Bytes], NewDefaultConfig. Use alias from exporterhelper. (#12707)\n- `exporterqueue`: Deprecated Config, NewDefaultConfig, Encoding, ErrQueueFull. Use alias from exporterhelper. (#12706)\n- `exporterhelper`: Deprecate exporterhelper WithRequestQueue in favor of WithQueueBatch (#12679)\n- `exporterhelper`: Deprecate `QueueConfig` in favor of `QueueBatchConfig`. (#12746)\n\n### 💡 Enhancements 💡\n\n- `extensionauth`: Mark module as stable (#11006)\n- `processor`: Mark module as stable. (#12677)\n- `processorhelper`: Split processorhelper into a separate module. (#12678)\n\n<!-- previous-version -->\n\n## v1.28.1/v0.122.1\n\n<!-- previous-version -->\n\n## v1.28.0/v0.122.0\n\n### 🛑 Breaking changes 🛑\n\n- `auth, authtest`: Remove deprecated modules extension/auth and extension/auth/authtest (#12543)\n  Use extension/extensionauth and extension/extensionauth/extensionauthtest instead.\n  \n- `extensionauth`: Remove deprecated methods from the `Func` types. (#12547)\n- `extensiontest, connectortest, processortest, receivertest, scrapertest, exportertest`: Remove deprecated `NewNopSettingsWithType` functions, use `NewNopSettings` instead. (#12221)\n- `extensionauthtest`: Remove the `extensionauthtest.MockClient` struct. (#12567)\n  - Use `extensionauthtest.NewNopClient` to create a client with a noop implementation. \n  - Use `extensionauthtest.NewErrorClient` to create a client that always returns an error.\n  - Implement the `extensionauth` interfaces for custom mock client implementations.\n  \n- `component/componenttest`: Remove the deprecated componenttest.TestTelemetry in favor of componenttest.Telemetry (#12419)\n- `exporterhelper`: Remove the Request.Export function in favor of an equivalent request consume func in the New[Traces|Metrics|Logs|Profiles]Request (#12637)\n\n### 🚩 Deprecations 🚩\n\n- `exporterhelper`: Deprecate per signal converter in favor of generic version (#12631)\n- `extensionauth`: Deprecate `extensionauth.NewClient` and `extensionauth.NewServer`. (#12574)\n  - Manually implement the interfaces instead.\n  \n- `configauth`: Deprecate `configauth.Authenticator.GetClientAuthenticator`. (#12574)\n  - Use the per-protocol methods instead.\n  \n\n### 🚀 New components 🚀\n\n- `receiverhelper`: Split `receiverhelper` into a separate module (#28328)\n\n### 💡 Enhancements 💡\n\n- `cmd/mdatagen`: Add `supportsSignal` func for `Metadata` type in `mdatagen`. (#12640)\n- `receiver`: Mark module as stable (#12513)\n- `pdata/pcommon`: Introduce `Equal()` method for comparison equality to `Value`, `ByteSlice`, `Float64Slice`, `Int32Slice`, `Int64Slice`, `StringSlice`, `Uint64Slice`, `Map` and `Slice` (#12594)\n- `pdata`: Add iterator All method to pdata slices and map types. (#11982)\n- `pdata/pprofile`: Introduce AddAttribute helper method to modify the content of attributable records (#12206)\n\n<!-- previous-version -->\n\n## v1.27.0/v0.121.0\n\n### 🛑 Breaking changes 🛑\n\n- `exporterqueue`: Remove exporterqueue.Factory in favor of the NewQueue function, and merge configs for memory and persistent. (#12509)\n  As a side effect of this change, no alternative implementation of the queue are supported and the Queue interface will be hidden.\n- `exporterhelper`: Update MergeSplit function signature to use the new SizeConfig (#12486)\n- `extension, connector, processor, receiver, exporter, scraper`: Remove deprecated `Create*` methods from `Create*Func` types. (#12305)\n  The `xconnector.CreateMetricsToProfilesFunc.CreateMetricsToProfiles` method has been removed without a deprecation.\n  \n- `component`: Remove deprecated function and interface `ConfigValidator` and `ValidateConfig`. (#11524)\n  - Use `xconfmap.Validator` and `xconfmap.Validate` instead.\n  \n- `receiver, scraper, processor, exporter, extension`: Remove deprecated MakeFactoryMap functions in favor of generic implementation (#12222)\n- `exporterhelper`: Change the signature of the exporterhelper.WithQueueRequest to accept Encoding instead of the Factory. (#12509)\n- `component/componenttest`: Removing the deprecated `CheckReceiverMetrics` and `CheckReceiverTraces` functions. (#12185)\n\n### 🚩 Deprecations 🚩\n\n- `componenttest`: Deprecated componenttest.TestTelemetry in favor of componenttest.Telemetry (#12419)\n- `connector, exporter, extension, processor, receiver, scraper`: Add type parameter to `NewNopSettings` and deprecate `NewNopSettingsWithType` (#12305)\n- `exporterhelper`: Deprecate MinSizeConfig and MaxSizeItems. (#12486)\n- `extension/extensionauth`: Deprecate methods on `*Func` types. (#12480)\n- `extension/auth, extension/auth/authtest`: Deprecate extension/auth and the related test module in favor of extension/extensionauth (#12478)\n\n### 🚀 New components 🚀\n\n- `service/hostcapabilities`: create `service/hostcapabilities` module (#12296, #12375)\n  Removes getExporters interface in service/internal/graph.\n  Removes getModuleInfos interface in service/internal/graph.\n  Creates interface ExposeExporters in service/hostcapabilities to expose GetExporters function.\n  Creates interface ModuleInfo in service/hostcapabilities to expose GetModuleInfos function.\n  \n\n### 💡 Enhancements 💡\n\n- `exporterhelper`: Adds the config API to support serialized bytes based batching (#3262)\n- `configauth`: Add the `omitempty` mapstructure tag to struct fields (#12191)\n  This results in unset fields not being rendered when marshaling.\n- `confighttp`: Add the `omitempty` mapstructure tag to struct fields (#12191)\n  This results in unset fields not being rendered when marshaling.\n- `otelcol`: Converters are now available in the `components` command. (#11900, #12385)\n- `extension`: Mark module as stable (#11005)\n- `pcommon.Map`: preallocate go map in Map.AsRaw() (#12406)\n- `exporterhelper`: Stabilize exporter.UsePullingBasedExporterQueueBatcher and remove old batch sender (#12425)\n- `service`: Add the `omitempty` mapstructure tag to struct fields (#12191)\n  This results in unset fields not being rendered when marshaling.\n\n### 🧰 Bug fixes 🧰\n\n- `mdatagen`: Fix broken imports in the generated files. (#12298)\n- `processor, connector, exporter, receiver`: Explicitly error out at component creation time if there is a type mismatch. (#12305)\n\n## v1.26.0/v0.120.0\n\n### 🛑 Breaking changes 🛑\n\n- `configauth`: Remove NewDefaultAuthentication (#12223)\n  The value returned by this function will always cause an error on startup.\n  In `configgrpc.Client/ServerConfig.Auth`, `nil` should be used instead to disable authentication.\n  \n- `otelcol`: Make the `ConfigProvider` interface a struct (#12297)\n  Calls to `NewConfigProvider` will now return `*ConfigProvider`,\n  but will otherwise work the same as before.\n  \n- `extension`: Remove `extension.Settings.ModuleInfo` (#12296)\n  - The functionality is now available as an optional, hidden interface on `service`'s implementation of the `Host`\n  \n- `component`: Remove deprecated field `component.TelemetrySettings.MetricsLevel`. (#11061)\n- `confighttp`: Add `ToClientOption` type and add it to signature of `ToClient` method. (#12353)\n  - This has no use for now, it may be used in the future.\n  \n- `mdatagen`: Remove unused not_component config for mdatagen (#12237)\n\n### 🚩 Deprecations 🚩\n\n- `component/componenttest`: Deprecate CheckReceiverMetrics in componenttest (#12185)\n  Use the `metadatatest.AssertEqualMetric` series of functions instead of `obsreporttest.CheckReceiverMetrics`\n- `component/componenttest`: Deprecate CheckReceiverTraces in componenttest (#12185)\n  Use the `metadatatest.AssertEqualMetric` series of functions instead of `obsreporttest.CheckReceiverTraces`\n- `component`: Deprecate `ConfigValidator` and `ValidateConfig` (#11524)\n  Please use `Validator` and `Validate` respectively from `xconfmap`.\n- `receiver, scraper, processor, exporter, extension`: Deprecate existing MakeFactoryMap functions in favor of generic implementation (#12222)\n- `extension, connector, processor, receiver, exporter, scraper`: Deprecate `Create*` methods from `Create*Func` types. (#12305)\n- `extensiontest, connectortest, processortest, receivertest, exportertest, scrapertest`: Deprecate `*test.NewNopSettings` in favor of `*test.NewNopSettingsWithType` (#12305)\n\n### 🚀 New components 🚀\n\n- `xconfmap`: Create the xconfmap module and add the `Validator` interface and `Validate` function to facilitate config validation (#11524)\n\n### 💡 Enhancements 💡\n\n- `configgrpc`: Add the `omitempty` mapstructure tag to struct fields (#12191)\n  This results in unset fields not being rendered when marshaling.\n- `confignet`: Add the `omitempty` mapstructure tag to struct fields (#12191)\n  This results in unset fields not being rendered when marshaling.\n- `configtls`: Add the `omitempty` mapstructure tag to struct fields (#12191)\n  This results in unset fields not being rendered when marshaling.\n- `consumer`: Clarify that data cannot be accessed after Consume* func is called. (#12284)\n- `pdata/pprofile`: Introduce aggregation temporality constants (#12253)\n\n### 🧰 Bug fixes 🧰\n\n- `configgrpc`: Apply configured Headers automatically (#12307)\n  configgrpc now calls metadata.AppendToOutgoingContext automatically in an interceptor.\n  Components that were manually using metadata.NewOutgoingContext as a workaround no longer need to\n  do so, unless they are overwriting or adding header keys.\n  \n- `configgrpc`: Set Auth to nil in NewDefaultClientConfig/NewDefaultServerConfig (#12223)\n  The value that was used previously would always cause an error on startup.\n  \n- `exporterqueue`: Fix async queue to propagate cancellation all they way to the queue (#12282)\n- `otlpreceiver`: Fix OTLP http receiver to correctly set Retry-After (#12367)\n- `extension`: Explicitly error out at extension creation time if there is a type mismatch. (#12305)\n\n## v1.25.0/v0.119.0\n\n### 🛑 Breaking changes 🛑\n\n- `exporterhelper`: Change queue to embed the async consumers. (#12242)\n- `exporterqueue`: Change Queue interface to return a callback instead of an index (#8122)\n- `cmd/mdatagen`: Allow passing OTel Metric SDK options to the generated `SetupTelemetry` function. (#12166)\n- `exporterhelper`: Rename exporter span signal specific attributes (e.g. \"sent_spans\" / \"send_failed_span\") to \"items.sent\" / \"items.failed\". (#12165)\n- `component`: Change underlying type for `component.Kind` to be a struct. (#12214)\n- `extension`: Change `extension.Extension` to be an interface that embeds `component.Component` instead of an alias (#11443)\n- `component/componenttest`: Remove deprecated `CheckScraperMetrics` functions (#12183)\n- `scraperhelper`: Remove deprecated ScrapperControllerOption and NewScraperControllerMetrics from scraperhelper. (#12147)\n\n### 🚩 Deprecations 🚩\n\n- `metadatatest`: Deprecate metadatatest.Telemetry in favor of componenttest.Telemetry (#12218)\n  metadatatest.Telemetry -> componenttest.Telemetry |\n  metadatatest.SetupTelemetry -> componenttest.NewTelemetry |\n  metadatatest.Telemetry.NewSettings -> metadatatest.NewSettings |\n  metadatatest.Telemetry.AssertMetrics -> metadatatest.AssertEqual* |\n  \n- `component/componenttest`: Deprecate `CheckExporterEnqueue*` functions in componenttest (#12185)\n  Use the `metadatatest.AssertEqualMetric` series of functions instead of `obsreporttest.CheckExporterEnqueue*` functions.\n- `component/componenttest`: Deprecate CheckExporterLogs in componenttest (#12185)\n  Use the `metadatatest.AssertEqualMetric` series of functions instead of `obsreporttest.CheckExporterLogs`\n- `component/componenttest`: Deprecate CheckExporterMetricGauge in componenttest (#12185)\n  Use the `metadatatest.AssertEqualMetric` series of functions instead of `obsreporttest.CheckReceiverMetricGauge`\n- `component/componenttest`: Deprecate CheckExporterMetrics in componenttest (#12185)\n  Use the `metadatatest.AssertEqualMetric` series of functions instead of `obsreporttest.CheckExporterMetrics`\n- `component/componenttest`: Deprecate CheckExporterTraces in componenttest (#12185)\n  Use the `metadatatest.AssertEqualMetric` series of functions instead of `obsreporttest.CheckExporterTraces`\n- `component/componenttest`: Deprecate CheckReceiverLogs in componenttest (#12185)\n  Use the `metadatatest.AssertEqualMetric` series of functions instead of `obsreporttest.CheckReceiverLogs`\n- `mdatagen`: Make registration of callback for async metric always optional. (#12204)\n  Deprecate `metadata.TelemetryBuilder.Init*` and `metadata.With*Callback` in favor of `metadata.TelemetryBuilder.Register*Callback`\n- `component`: Deprecate `component.TelemetrySettings.MetricsLevel` in favor of using views and 'Enabled' method. (#12159)\n  - Components will temporarily need the service to support using views.\n  \n\n### 💡 Enhancements 💡\n\n- `componenttest`: Add helper to get a metric for componenttest.Telemetry (#12215)\n- `componenttest`: Extract componenttest.Telemetry as generic struct for telemetry testing (#12151)\n- `mdatagen`: Generate assert function for each metric in mdatagen (#12179)\n- `metadatatest`: Generate NewSettings that accepts componenttest.Telemetry (#12216)\n- `pdata/pprofile`: Add new helper method `FromAttributeIndices` to build a `pcommon.Map` out of `AttributeIndices`. (#12176)\n- `scraper`: Support logs scraper (#12116)\n- `component`: Allow `component.ValidateConfig` to recurse through all fields in a config object (#11524)\n- `component`: Show path to invalid config in errors returned from `component.ValidateConfig` (#12108)\n\n### 🧰 Bug fixes 🧰\n\n- `mdatagen`: All register callbacks to async instruments can now be unregistered by calling `metadata.TelemetryBuilder.Shutdown()` (#12204)\n- `mdatagen`: Fix bug where Histograms were marked as not supporting temporal aggregation (#12168)\n\n## v1.24.0/v0.118.0\n\n### 🛑 Breaking changes 🛑\n\n- `exporterqueue`: Change Queue Size and Capacity to return explicit int64. (#12076)\n- `receiver/scraperhelper`: Removing the deprecated receiver/scraperhelper package (#12054)\n- `processortest`: Revert the nop_processor.NewNopSettings change, as it is no longer needed (#11433)\n- `experimental/storage`: Remove deprecated package/module experimental/storage (#12109)\n- `mdatagen`: Remove deprecated generated_component_telemetry_test file from being generated and delete it. (#12068)\n- `receivertest`: Remove deprecated receivertest.NewNopFactoryForType (#12110)\n\n### 🚩 Deprecations 🚩\n\n- `componenttest`: Deprecate CheckScraperMetrics in componenttest (#12105)\n  Use `metadatatest.AssertMetrics` instead of `obsreporttest.CheckScraperMetrics`\n- `scraperhelper`: Deprecate `scraperhelper.NewScraperControllerReceiver` and `scraperhelper.ScraperControllerOption`. (#12103)\n  Use `scraperhelper.NewMetricsController` instead of `scraperhelper.NewScraperControllerReceiver` | Use `scraperhelper.ScraperControllerOption` instead of `scraperhelper.ControllerOption`\n\n### 💡 Enhancements 💡\n\n- `exporterhelper`: Add capability for memory and persistent queue to block when add items (#12074)\n- `scraper/scraperhelper`: Add obs_logs for scraper/scraperhelper (#12036)\n  This change adds obs for logs in scraper/scraperhelper, also introduced new metrics for scraping logs.\n- `mdatagen`: Add scraper component type support to mdatagen (#12092)\n- `mdatagen`: Add tracing support in metadatatest (#12106)\n- `exporterhelper`: Change persistent queue to not use sized channel, improve memory usage and simplify sized_channel. (#12060)\n- `confighttp`: Added support for configuring compression levels. (#10467)\n  A new configuration option called CompressionParams has been added to confighttp. | This allows users to configure the compression levels for the confighttp client.\n\n## v1.23.0/v0.117.0\n\n### 🛑 Breaking changes 🛑\n\n- `pdata/pprofile`: Remove duplicate Attributes field from profile (#11932)\n- `connector`: Remove deprecated connectorprofiles module, use xconnector instead. (#11778)\n- `consumererror`: Remove deprecated consumererrorprofiles module, use xconsumererror instead. (#11778)\n- `consumer`: Remove deprecated consumerprofiles module, use xconsumer instead. (#11778)\n- `exporterhelper`: Remove deprecated exporterhelperprofiles module, use xexporterhelper instead. (#11778)\n- `exporter`: Remove deprecated exporterprofiles module, use xexporter instead. (#11778)\n- `pipeline`: Remove deprecated pipelineprofiles module, use xpipeline instead. (#11778)\n- `processorhelper`: Remove deprecated processorhelperprofiles module, use xprocessorhelper instead. (#11778)\n- `processor`: Remove deprecated processorprofiles module, use xprocessor instead. (#11778)\n- `receiver`: Remove deprecated receiverprofiles module, use xreceiver instead. (#11778)\n- `exporterhelper`: Remove Merge function from experimental Request interface (#12012)\n\n### 🚩 Deprecations 🚩\n\n- `mdatagen`: Deprecate component_test in favor of metadatatest (#11812)\n- `receivertest`: Deprecate receivertest.NewNopFactoryForType (#11993)\n- `extension/experimental`: Deprecate extension/experimental in favor of extension/xextension (#12010)\n- `scraperhelper`: Move scraperhelper under scraper and in a separate module. (#11003)\n\n### 💡 Enhancements 💡\n\n- `scrapertest`: Add scrapertest package in a separate module (#11988)\n- `pdata`: Upgrade pdata to opentelemetry-proto v1.5.0 (#11932)\n\n## v1.22.0/v0.116.0\n\n### 🛑 Breaking changes 🛑\n\n- `component`: Remove deprecated TelemetrySettings.LeveledMeterProvider (#11811)\n- `scraperhelper`: Remove deprecated scraperhelper.Scraper and helpers (#11803)\n\n### 🚩 Deprecations 🚩\n\n- `connector`: Deprecate connectorprofiles module in favor of xconnector to allow adding more experimental data types. (#11778)\n- `consumererror`: Deprecate consumererrorprofiles module in favor of xconsumererror to allow adding more experimental data types. (#11778)\n- `consumer`: Deprecate consumerprofiles module in favor of xconsumer to allow adding more experimental data types. (#11778)\n- `exporterhelper`: Deprecate exporterhelperprofiles module in favor of xexporterhelper to allow adding more experimental data types. (#11778)\n- `exporter`: Deprecate exporterprofiles module in favor of xexporter to allow adding more experimental data types. (#11778)\n- `pipeline`: Deprecate pipelineprofiles module in favor of xpipeline to allow adding more experimental data types. (#11778)\n- `processorhelper`: Deprecate processorhelperprofiles module in favor of xprocessorhelper to allow adding more experimental data types. (#11778)\n- `processor`: Deprecate processorprofiles module in favor of xprocessor to allow adding more experimental data types. (#11778)\n- `receiver`: Deprecate receiverprofiles module in favor of xreceiver to allow adding more experimental data types. (#11778)\n- `receiver/scrapererror`: Remove the receiver/scrapererror alias. (#11003)\n\n### 💡 Enhancements 💡\n\n- `receiver/scraperhelper`: Add scraper for logs (#11238)\n\n## v1.21.0/v0.115.0\n\n### 🛑 Breaking changes 🛑\n\n- `extension/auth/authtest`: `authtest` is now its own module (#11465, #11705)\n- `pdata/pprofile`: AttributeTable is now a slice rather than a map (#11706)\n- `scraperhelper`: Remove deprecated scraperhelper funcs Scraper.ID, NewScraper, AddScraper. (#11710)\n- `mdatagen`: Remove deprecated LeveledMeter from the generated code (#11696)\n\n### 🚩 Deprecations 🚩\n\n- `component`: Mark `TelemetrySettings.LeveledMeterProvider` as deprecated (#11697)\n- `receiver/scraper`: Move receiver/scrapererror package to scraper/scrapererror and deprecate original receiver/scrapererror package. (#11003)\n- `scraperhelper`: Make Scraper compatible with the new scraper.Metrics (#11682)\n  Deprecate scraperhelper.Scraper in favor of scraper.Metrics\n\n## v1.20.0/v0.114.0\n\n### 🛑 Breaking changes 🛑\n\n- `extensiontest`: Make extensiontest into its own module (#11463)\n- `component`: Make componenttest into its own module (#11464)\n- `expandconverter`: Remove deprecated expandvar converter (#11672)\n- `exporter`: Remove deprecated funcs Create[*]Exporter and [*]ExporterStability (#11662)\n- `exporterhelper`: Remove deprecated NewLogs[Request]Exporter funcs (#11661)\n- `extension`: Remove deprecated funcs CreateExtension and ExtensionStability (#11663)\n- `processortest`: Remove deprecated func NewUnhealthyProcessorCreateSettings (#11665)\n\n### 🚩 Deprecations 🚩\n\n- `component`: Deprecate `TelemetrySettings.LeveledMeterProvider` and undo deprecation of `TelemetrySettings.MeterProvider` (#11061)\n- `scraperhelper`: Deprecate Scraper.ID func, pass type when register Scraper (#11238)\n\n## v1.19.0/v0.113.0\n\n### 🛑 Breaking changes 🛑\n\n- `builder`: Remove deprecated flags from Builder (#11576)\n  Here is the list of flags | --name, --description, --version, --otelcol-version, --go, --module\n\n### 🚀 New components 🚀\n\n- `processorhelperprofiles`: Add processorhelperprofiles to support profiles signal (#11556)\n\n### 💡 Enhancements 💡\n\n- `mdatagen`: Add newTelemetrySettings to be generated all the time even for pkg class (#11535)\n- `debugexporter`: Add profiles support to debug exporter (#11155)\n- `component`: Add UnmarshalText for StabilityLevel (#11520)\n\n## v1.18.0/v0.112.0\n\n### 🛑 Breaking changes 🛑\n\n- `service`: Change Host to not implement GetExportersWithSignal (#11444)\n  Use Host.GetExporters if still needed.\n- `componentstatus`: Remove deprecated `NewInstanceIDWithPipelineIDs`, `AllPipelineIDsWithPipelineIDs`, and `WithPipelineIDs`. Use `NewInstanceID`, `AllPipelineIDs` and `WithPipelines` instead. (#11363)\n- `configgrpc`: Removed deprecated `ClientConfig.ToClientConnWithOptions`/`ServerConfig.ToServerWithOptions`. (#11359, #9480)\n  These methods were renamed to `ClientConfig.ToClientConn`/`ServerConfig.ToServer` in v0.111.0.\n- `connector`: Put connectortest in its own module (#11216)\n- `exporter`: Disables setting batch option to batch sender directly. (#10368)\n  Removed WithRequestBatchFuncs(BatcherOption) in favor of WithBatchFuncs(Option), where | BatcherOption is a function that operates on batch sender and Option is one that operates | on BaseExporter\n- `exporter`: Made mergeFunc and mergeSplitFunc required method of exporter.Request (#10368)\n  mergeFunc and mergeSplitFunc used to be part of the configuration pass to the exporter. Now it is changed | to be a method function of request.\n- `componentprofiles`: Move componentprofiles to pipelineprofiles (#11421)\n- `processor`: Put processortest in its own module (#11218)\n- `receivertest`: Removed deprecated `NewNopFactoryForTypeWithSignal`. Use `NewNopFactoryForType` instead. (#11362)\n- `processor`: Remove deprecated funcs from processor package (#11368)\n- `receiver`: Remove deprecated funcs from receiver package (#11367)\n- `processorhelper`: Remove deprecated funcs/types from processorhelper & componenttest (#11302)\n- `service`: Remove deprecated `pipelines.ConfigWithPipelineID` and `Config.PipelinesWithPipelineID`. Use `pipelines.Config` and `Config.Pipelines` instead. (#11361)\n\n### 🚩 Deprecations 🚩\n\n- `extension`: Deprecate funcs that repeat extension in name (#11413)\n  Factory.CreateExtension -> Factory.Create |\n  Factory.ExtensionStability -> Factory.Stability\n  \n- `exporter`: Deprecate funcs that repeat exporter in name (#11370)\n  Factory.Create[Traces|Metrics|Logs|Profiles]Exporter -> Factory.Create[Traces|Metrics|Logs|Profiles] |\n  Factory.[Traces|Metrics|Logs|Profiles]ExporterStability -> Factory.[Traces|Metrics|Logs|Profiles]Stability\n  \n\n### 🚀 New components 🚀\n\n- `consumererrorprofiles`: Add new module consumererrorprofiles for consumer error profiles. (#11131)\n\n### 💡 Enhancements 💡\n\n- `configcompression`: Add support for lz4 compression (#9128)\n- `otlpexporter`: Add profiles support to OTLP exporter (#11435)\n- `otlphttpexporter`: Add profiles support to OTLP HTTP exporter (#11450)\n\n## v1.17.0/v0.111.0\n\n### 🛑 Breaking changes 🛑\n\n- `service/telemetry`: Change default metrics address to \"localhost:8888\" instead of \":8888\" (#11251)\n  This behavior can be disabled by disabling the feature gate 'telemetry.UseLocalHostAsDefaultMetricsAddress'.\n- `componentprofiles`: Removed deprecated `DataTypeProfiles`.  Use `SignalProfiles` instead. (#11312)\n- `configgrpc`: Replace ToClientConn and ToServer with ToClientConnWithOptions and ToServerWithOptions. (#11271, #9480)\n  `ClientConfig.ToClientConn` and `ServerConfig.ToServer` were deprecated in v0.110.0 in favor of\n  `ClientConfig.ToClientConnWithOptions` and `ServerConfig.ToServerWithOptions` which use a more\n  flexible option type. The original functions are now removed, and the new ones are renamed to the\n  old names. The `WithOptions` names are kept as deprecated aliases for now.\n  \n- `exporterhelper`: Removed deprecated `QueueTimeout`/`TimeoutSettings` aliases in favor of `QueueConfig`/`TimeoutConfig`. (#11264, #6767)\n  `NewDefaultQueueSettings` and `NewDefaultTimeoutSettings` have been similarly renamed.\n- `exporterqueue`: Remove deprecated `Settings.DataType`. Use `Settings.Signal` instead. (#11305)\n- `exportertest`: Remove deprecated `CheckConsumeContractParams.DataType`. Use `CheckConsumeContractParams.Signal` instead. (#11305)\n- `component`: Removed deprecated `ErrDataTypeIsNotSupported`, `DataType`, `DataTypeTraces`, `DataTypeMetrics`, and `DataTypeLogs`.  Use `pipeline.ErrSignalNotSupported`, `pipeline.Signal`, `pipeline.SignalTraces`, `pipeline.SignalMetrics`, and `pipeline.SignalLogs` instead. (#11253)\n- `pdata/pprofile`: Replace slices of values to slices of pointers for the `Mapping`, `Location`, `Line`, `Function`, `AttributeUnit`, `Link`, `Value`, `Sample` and `Labels` attributes. (#11339)\n- `receivertest`: Remove deprecated `CheckConsumeContractParams.DataType`. Use `CheckConsumeContractParams.Signal` instead. (#11304)\n- `scraperhelper`: Remove deprecated function `NewScraperWithComponentType`. (#11294)\n- `processorhelper`: Remove deprecated funcs form processorhelper.ObsReport (#11289)\n  The \"otelcol_processor_dropped_log_records\", \"otelcol_processor_dropped_log_records\" | and \"otelcol_processor_dropped_spans\" metrics are complete removed, before they were always record with 0 values.\n\n### 🚩 Deprecations 🚩\n\n- `componentstatus`: Deprecated `NewInstanceIDWithPipelineIDs`, `AllPipelineIDsWithPipelineIDs`, and `WithPipelineIDs`. Use `NewInstanceID`, `AllPipelineIDs`, and `WithPipelines` instead. (#11313)\n- `processorhelper`: Deprecate unused and empty struct processorhelper.ObsReport (#11293)\n- `processor`: Deprecate funcs that repeat \"processor\" in name (#11310)\n  Factory.Create[Traces|Metrics|Logs|Profiles]Processor -> Factory.Create[Traces|Metrics|Logs|Profiles]\n  Factory.[Traces|Metrics|Logs|Profiles]ProcessorStability -> Factory.[Traces|Metrics|Logs|Profiles]Stability\n  \n- `receiver`: Deprecate funcs that repeat \"receiver\" in name (#11287)\n  Factory.Create[Traces|Metrics|Logs|Profiles]Receiver -> Factory.Create[Traces|Metrics|Logs|Profiles]\n  Factory.[Traces|Metrics|Logs|Profiles]ReceiverStability -> Factory.[Traces|Metrics|Logs|Profiles]Stability\n  \n- `receivertest`: Deprecated `NewNopFactoryForTypeWithSignal`. Use `NewNopFactoryForType` instead. (#11304)\n- `service`: Deprecates `Config.PipelinesWithPipelineID`, `pipelines.ConfigWithPipelineID` and `GetExportersWithSignal` interface implementation. Use `Config.Pipelines`, `pipelines.Config`, and `GetExporters` interface implementation instead. (#11303)\n\n## v1.16.0/v0.110.0\n\n### 🛑 Breaking changes 🛑\n\n- `otlpexporter`: The `TimeoutSettings` field in `otlpexporter.Config` was renamed to `TimeoutConfig`. (#11132)\n- `connector`: Change `TracesRouterAndConsumer`, `NewTracesRouter`, `MetricsRouterAndConsumer`, `NewMetricsRouter`, `LogsRouterAndConsumer`, and `NewLogsRouter` to use `pipeline.ID` instead of `component.ID`. (#11204)\n- `extension`: Remove deprecated extension interfaces. (#11043)\n  They are now available in the `extensioncapabilities` module.\n  \n\n### 🚩 Deprecations 🚩\n\n- `exporterhelper`: Deprecate TimeoutSettings/QueueSettings in favor of TimeoutConfig/QueueConfig. (#6767)\n- `configgrpc`: Deprecate `ClientConfig.ToClientConn`/`ServerConfig.ToServer` in favor of `ToClientConnWithOptions`/`ToServerWithOptions` (#9480)\n  Users providing a grpc.DialOption/grpc.ServerOption should now wrap them into\n  a generic option with `WithGrpcDialOption`/`WithGrpcServerOption`.\n  \n- `componentprofiles`: Deprecates `DataTypeProfiles`. Use `SignalProfiles` instead. (#11204)\n- `componentstatus`: Deprecates `NewInstanceID`, `AllPipelineIDs`, and `WithPipelines`. Use `NewInstanceIDWithPipelineIDs`, `AllPipelineIDsWithPipelineIDs`, and `WithPipelineIDs` instead. (#11204)\n- `exporterqueue`: Deprecates `Settings.DataType`. Use `Settings.Signal` instead. (#11204)\n- `service`: Deprecates `pipelines.Config`. Use `pipelines.ConfigWithPipelineID` instead. (#11204)\n- `component`: Deprecates `DataType`, `DataTypeTraces`, `DataTypeMetrics`, and `DataTypeLogs`. Use `pipeline.Signal`, `SignalTraces`, `SignalMetrics`, and `SignalLogs` instead. (#11204)\n- `service`: Deprecates service's implementation of `GetExporters` interface.  Use `GetExportersWithSignal` instead. (#11249)\n- `scraperhelper`: Deprecate NewScraperWithComponentType, should use NewScraper (#11159)\n\n### 🚀 New components 🚀\n\n- `pipeline`: Adds new `pipeline` module to house the concept of pipeline ID and Signal. (#11209)\n\n### 💡 Enhancements 💡\n\n- `pdata`: Add support to MoveTo for Map, allow avoiding copies (#11175)\n- `options`: Avoid using private types in public APIs and also protect options to be implemented outside this module. (#11054)\n- `mdatagen`: Avoid using private types in public APIs and also protect options to be implemented outside this module. (#11040)\n- `consumertest`: Introduce SampleCount method in ProfilesSink struct. (#11225)\n- `otlpreceiver`: Support profiles in the OTLP receiver (#11071)\n\n## v1.15.0/v0.109.0\n\n### 🛑 Breaking changes 🛑\n\n- `Remove `extensiontest` StatusWatcher helpers`: They were unused. They may be added back on a different module or after `componentstatus` is marked 1.0\n (#11044)\n- `pprofile`: Change Profile ID field from a byte array to a custom data type (#11048)\n- `connector`: Remove deprecated connector builder (#11019)\n- `exporter`: Remove deprecated exporter builder (#11019)\n- `extension`: Remove deprecated extension builder (#11019)\n- `processor`: Remove deprecated processor builder (#11019)\n- `receiver`: Remove deprecated receiver builder (#11019)\n\n### 🚩 Deprecations 🚩\n\n- `configtelemetry`: Deprecating `TelemetrySettings.MeterProvider` in favour of `TelemetrySettings.LeveledMeterProvider` (#10912)\n- `extension`: Deprecate `extension.ConfigWatcher`, `extension.PipelineWatcher` and `extension.Dependent` in favor of equivalents in the `extensioncapabilities` module. (#11000)\n- `scraperhelper`: deprecate NewScraper, should use NewScraperWithComponentType (#11082)\n\n### 🚀 New components 🚀\n\n- `extensioncapabilities`: Create a new module for optional extension capabilities. (#11000)\n\n### 💡 Enhancements 💡\n\n- `connectorprofiles`: Add ProfilesRouterAndConsumer interface, and NewProfilesRouter method. (#11023)\n- `pprofileotlp`: Introduce grpc service implementation of pprofileotlp (#11048)\n- `pprofile`: Introduce marshalling and unmarshalling of pprofile data (#11048)\n- `service`: Support profiles in the service package (#11024)\n\n## v1.14.1/v0.108.1\n\n## v1.14.0/v0.108.0\n\n### 🛑 Breaking changes 🛑\n\n- `extensions`: Remove `StatusWatcher` interface.  Use `componentstatus.Watcher` instead. (#10777)\n- `component`: Removed Status related types and functions.  Use `componentstatus` instead. (#10777)\n- `component`: Remove `ReportStatus` from `TelemetrySettings`. Use `componentstatus.ReportStatus` instead. (#10777)\n- `componentstatus`: Make componentstatus.InstanceID immutable. (#10494)\n\n### 🚩 Deprecations 🚩\n\n- `scraperhelper`: deprecate NewObsReport, ObsReport, ObsReportSettings, scrapers should use NewScraperControllerReceiver (#10959)\n- `mdatagen`: Deprecating generated `Meter` func in favour of `LeveledMeter` (#10939)\n- `connector`: Deprecate connector.Builder, and move it into an internal package of the service module (#10784)\n- `exporter`: Deprecate exporter.Builder, and move it into an internal package of the service module (#10783)\n- `extension`: Deprecate extension.Builder, and move it into an internal package of the service module (#10785)\n- `processor`: Deprecate processor.Builder, and move it into an internal package of the service module (#10782)\n- `receiver`: Deprecate receiver.Builder, and move it into an internal package of the service module (#10781)\n\n## v1.13.0/v0.107.0\n\n### 🛑 Breaking changes 🛑\n\n- `otelcol`: Delete deprecated NewCommandMustSetProvider (#10778)\n- `component`: Removes the deprecated `Host.GetFactory` method. (#10771)\n- `otelcoltest`: The `otelcol.LoadConfig` method no longer sets the `expandconverter`. (#10510)\n- `ocb`: Collectors built with OCB will no longer include the `expandconverter` (#10510)\n- `exporterhelper`: Delete deprecated `exporterhelper.ObsReport` and `exporterhelper.NewObsReport` (#10779, #10592)\n\n### 🚩 Deprecations 🚩\n\n- `expandconverter`: Deprecate `expandconverter`. (#10510)\n\n### 🚀 New components 🚀\n\n- `componentstatus`: Adds new componentstatus module that will soon replace status content in component. (#10730)\n- `connector/connectorprofiles`: Allow handling profiles in connector. (#10703)\n- `exporter/exporterprofiles`: Allow handling profiles in exporter. (#10702)\n- `processor/processorprofiles`: Allow handling profiles in processor. (#10691)\n- `receiver/receiverprofiles`: Allow handling profiles in receiver. (#10690)\n\n### 💡 Enhancements 💡\n\n- `confmap`: Check that providers have a correct scheme when building a confmap.Resolver. (#10786)\n- `confighttp`: Add `NewDefaultCORSConfig` function to initialize the default `confighttp.CORSConfig` (#9655)\n\n## v0.106.0\n\n### 🛑 Breaking changes 🛑\n\n- `configauth`: removing deprecated methods GetServerAuthenticatorContext and GetClientAuthenticatorContext (#9808)\n- `connector,exporter,receiver,extension,processor`: Remove deprecated funcs/structs (#10423)\n  Remove the following funcs & structs:\n  - connector.CreateSettings -> connector.Settings\n  - connectortest.NewNopCreateSettings -> connectortest.NewNopSettings\n  - exporter.CreateSettings -> exporter.Settings\n  - exportertest.NewNopCreateSettings -> exportertest.NewNopSettings\n  - extension.CreateSettings -> extension.Settings\n  - extensiontest.NewNopCreateSettings -> extensiontest.NewNopSettings\n  - processor.CreateSettings -> processor.Settings\n  - processortest.NewNopCreateSettings -> processortest.NewNopSettings\n  - receiver.CreateSettings -> receiver.Settings\n  - receivertest.NewNopCreateSettings -> receivertest.NewNopSettings\n  \n- `component/componenttest`: Add optional ...attribute.KeyValue argument to TestTelemetry.CheckExporterMetricGauge. (#10593)\n- `confighttp`: Auth data type signature has changed (#4806)\n  As part of the linked PR, the `auth` attribute was moved from `configauth.Authentication` \n  to a new `AuthConfig`, which contains a `configauth.Authentication`. For end-users, this\n  is a non-breaking change. For users of the API, create a new AuthConfig using the\n  `configauth.Authentication` instance that was being used before.\n  \n- `mdatagen`: Remove WithAttributes option from the telemetry builder constructor. (#10608)\n  Attribute sets for async instruments now can be set as options to callback setters and async instruments initializers.\n  This allows each async instrument to have its own attribute set.\n  \n- `service/extensions`: Adds `Options` to `extensions.New`. (#10728)\n  This is only a breaking change if you are depending on `extensions.New`'s signature. Calls to `extensions.New` are not broken.\n\n### 🚩 Deprecations 🚩\n\n- `component`: Deprecates Host.GetFactory. (#10709)\n\n### 🚀 New components 🚀\n\n- `component/componentprofiles`: Add componentprofiles module. (#10525)\n\n### 💡 Enhancements 💡\n\n- `exporter, processor, receiver`: Document factory functions. (#9323)\n- `component`: Document status enums and New constructors (#9822)\n- `confighttp, configgrpc`: Remove the experimental comment on `IncludeMetadata` in confighttp and configgrpc (#9381)\n- `confighttp`: Add `confighttp.NewDefaultServerConfig()` to instantiate the default HTTP server configuration (#9655)\n- `consumer/consumertest`: Allow testing profiles with consumertest. (#10692)\n\n### 🧰 Bug fixes 🧰\n\n- `confmap`: Fix wrong expansion of environment variables escaped with `$$`, e.g. `$${ENV_VAR}` and `$$ENV_VAR`. (#10713)\n  This change fixes the issue where environment variables escaped with $$ were expanded. \n  The collector now converts `$${ENV_VAR}` to `${ENV_VAR}` and `$$ENV_VAR` to `$ENV_VAR` without further expansion.\n  \n\n## v1.12.0/v0.105.0\n\n### 🛑 Breaking changes 🛑\n\n- `otelcol`: Obtain the Collector's effective config from otelcol.Config (#10139)\n  `otelcol.Collector` will now marshal `confmap.Conf` objects from `otelcol.Config` itself.\n- `otelcoltest`: Remove deprecated methods `LoadConfigWithSettings` and `LoadConfigAndValidateWithSettings` (#10512)\n\n### 🚩 Deprecations 🚩\n\n- `configauth`: Deprecated `Authentication.GetClientAuthenticatorContext` and `Authentication.GetServerAuthenticatorContext` (#10578)\n- `otelcol`: Deprecate `otelcol.ConfmapProvider` (#10139)\n  `otelcol.Collector` will now marshal `confmap.Conf` objects from `otelcol.Config` itself.\n- `otelcol`: Deprecate `(*otelcol.ConfigProvider).GetConfmap` (#10139)\n  Call `(*confmap.Conf).Marshal(*otelcol.Config)` to get the Collector's configuration.\n- `exporterhelper`: Deprecate the obsreport API in the exporterhelper package. (#10592)\n\n### 🚀 New components 🚀\n\n- `consumer/consumerprofiles`: Allow handling profiles in consumer. (#10464)\n\n## v1.11.0/v0.104.0\n\n### 🛑 Breaking changes 🛑\n\n- `otelcol`: The `otelcol.NewCommand` now requires at least one provider be set. (#10436)\n- `component/componenttest`: Added additional \"inserted\" count to `TestTelemetry.CheckProcessor*` methods. (#10353)\n\n### 🚩 Deprecations 🚩\n\n- `otelcoltest`: Deprecates `LoadConfigWithSettings` and `LoadConfigAndValidateWithSettings`.  Use `LoadConfig` and `LoadConfigAndValidate` instead. (#10417)\n- `otelcol`: The `otelcol.NewCommandMustSetProvider` is deprecated. Use `otelcol.NewCommand` instead. (#10436)\n\n### 🚀 New components 🚀\n\n- `otelcoltest`: Split off go.opentelemetry.io/collector/otelcol/otelcoltest into its own module (#10417)\n\n### 💡 Enhancements 💡\n\n- `pdata/pprofile`: Add pprofile wrapper to convert proto into pprofile. (#10401)\n- `pdata/testdata`: Add pdata testdata for profiles. (#10401)\n\n## v1.10.0/v0.103.0\n\n### 🛑 Breaking changes 🛑\n\n- `component`: Remove deprecated `component.UnmarshalConfig` (#7102)\n- `confighttp`: Use `confighttp.ServerConfig` as part of zpagesextension.Config. Previously the extension used `confignet.TCPAddrConfig` (#9368)\n\n### 🚩 Deprecations 🚩\n\n- `connector`: Deprecate CreateSettings and NewNopCreateSettings (#9428)\n  The following methods are being renamed:\n  - connector.CreateSettings -> connector.Settings\n  - connector.NewNopCreateSettings -> connector.NewNopSettings\n  \n- `exporter`: Deprecate CreateSettings and NewNopCreateSettings (#9428)\n  The following methods are being renamed:\n  - exporter.CreateSettings -> exporter.Settings\n  - exporter.NewNopCreateSettings -> exporter.NewNopSettings\n  \n- `extension`: Deprecate CreateSettings and NewNopCreateSettings (#9428)\n  The following methods are being renamed:\n  - extension.CreateSettings -> extension.Settings\n  - extension.NewNopCreateSettings -> extension.NewNopSettings\n  \n- `processor`: Deprecate CreateSettings and NewNopCreateSettings (#9428)\n  The following methods are being renamed:\n  - processor.CreateSettings -> processor.Settings\n  - processor.NewNopCreateSettings -> processor.NewNopSettings\n  \n- `receiver`: Deprecate CreateSettings and NewNopCreateSettings (#9428)\n  The following methods are being renamed:\n  - receiver.CreateSettings -> receiver.Settings\n  - receiver.NewNopCreateSettings -> receiver.NewNopSettings\n  \n- `configauth`: Deprecate `GetClientAuthenticator` and `GetServerAuthenticator`, use `GetClientAuthenticatorContext` and `GetServerAuthenticatorContext` instead. (#9808)\n- `confighttp`: Deprecate `ClientConfig.CustomRoundTripper` (#8627)\n  Set the `Transport` field on the `*http.Client` object returned from `(ClientConfig).ToClient` instead.\n- `filter`: Deprecate the `filter.CombinedFilter` struct (#10348)\n- `otelcol`: Deprecate `otelcol.NewCommand`. Use `otelcol.NewCommandMustProviderSettings` instead. (#10359)\n- `otelcoltest`: Deprecate `LoadConfig` and `LoadConfigAndValidate`. Use `LoadConfigWithSettings` and `LoadConfigAndValidateWithSettings` instead (#10359)\n\n### 💡 Enhancements 💡\n\n- `confmap`: Adds `confmap.Retrieved.AsString` method that returns the configuration value as a string (#9532)\n- `confmap`: Adds `confmap.NewRetrievedFromYAML` helper to create `confmap.Retrieved` values from YAML bytes (#9532)\n\n## v0.102.1\n\nNo API-only changes on this release. **This release addresses [GHSA-c74f-6mfw-mm4v](https://github.com/open-telemetry/opentelemetry-collector/security/advisories/GHSA-c74f-6mfw-mm4v) for `configgrpc`.**\n\n## v1.9.0/v0.102.0\n\n**This release addresses [GHSA-c74f-6mfw-mm4v](https://github.com/open-telemetry/opentelemetry-collector/security/advisories/GHSA-c74f-6mfw-mm4v) for `confighttp`.**\n\n### 🛑 Breaking changes 🛑\n\n- `otelcol`: Remove deprecated `ConfigProvider` field from `CollectorSettings` (#10281)\n- `exporterhelper`: remove deprecated RequestMarshaler & RequestUnmarshaler types (#10283)\n- `service`: remove deprecated Telemetry struct and New func (#10285)\n- `configtls`: remove deprecated LoadTLSConfigContext funcs (#10283)\n\n### 🚩 Deprecations 🚩\n\n- `component`: Deprecate `component.UnmarshalConfig`, use `(*confmap.Conf).Unmarshal(&intoCfg)` instead. (#7102)\n- `service/telemetry`: Deprecate telemetry.New in favor of telemetry.NewFactory (#4970)\n\n### 💡 Enhancements 💡\n\n- `confmap`: Allow setting a default Provider on a Resolver to use when `${}` syntax is used without a scheme (#10182)\n- `pdata`: Introduce string and int64 slices to pcommon (#10148)\n- `pdata`: Introduce generated experimental pdata for profiling signal. (#10195)\n- `confmap`: Remove top level condition when considering struct as Unmarshalers (#7101)\n\n### 🧰 Bug fixes 🧰\n\n- `otelcol`: Update validate command to use the new configuration options (#10203)\n\n## v1.8.0/v0.101.0\n\n### 🛑 Breaking changes 🛑\n\n- `confighttp`: Removes deprecated functions `ToClientContext`, `ToListenerContext`, and `ToServerContext`. (#10138)\n- `confmap`: Deprecate `NewWithSettings` for all Providers and `New` for all Converters (#10134)\n  Use `NewFactory` instead for all affected modules.\n- `confmap`: Remove deprecated `Providers` and `Converters` from `confmap.ResolverSettings` (#10173)\n  Use `ProviderSettings` and `ConverterSettings` instead.\n\n### 🧰 Bug fixes 🧰\n\n- `otelcol`: Add explicit mapstructure tags to main configuration struct (#10152)\n- `confmap`: Support string-like types as map keys when marshaling (#10137)\n\n## v1.7.0/v0.100.0\n\n### 💡 Enhancements 💡\n\n- `configgrpc`: Adds `NewDefault*` functions for all the config structs. (#9654)\n- `exporterqueue`: Expose ErrQueueIsFull so upstream components can retry or apply backpressure. (#10070)\n\n### 🧰 Bug fixes 🧰\n\n- `mdatagen`: Call connectors with routers to be the same as the service graph (#10079)\n\n## v1.6.0/v0.99.0\n\n### 🛑 Breaking changes 🛑\n\n- `component`: Removed deprecated function `GetExporters` from `component.Host` interface (#9987)\n\n### 🚩 Deprecations 🚩\n\n- `confighttp`: deprecate ToClientContext, ToServerContext, ToListenerContext, replaced by ToClient, ToServer, ToListener (#9807)\n- `configtls`: Deprecates `ClientConfig.LoadTLSConfigContext` and `ServerConfig.LoadTLSConfigContext`, use `ClientConfig.LoadTLSConfig` and `ServerConfig.LoadTLSConfig` instead. (#9945)\n- `confmap`: Deprecate the `Providers` and `Converters` fields in `confmap.ResolverSettings` (#9516)\nUse the `ProviderFactories` and `ConverterFactories` fields instead.\n\n### 💡 Enhancements 💡\n\n- `configauth`: Adds `NewDefault*` functions for all the config structs. (#9821)\n- `configtls`: Adds `NewDefault*` functions for all the config structs. (#9658)\n- `pmetric`: Support metric.metadata in pdata/pmetric (#10006)\n\n## v1.5.0/v0.98.0\n\n### 🛑 Breaking changes 🛑\n\n- `component`: Restricts maximum length for `component.Type` to 63 characters. (#9872)\n- `configgrpc`: Remove deprecated `ToServerContext`, use `ToServer` instead. (#9836)\n- `configgrpc`: Remove deprecated `SanitizedEndpoint`. (#9836)\n- `configtls`: Remove Deprecated `TLSSetting`, `TLSClientSetting`, and `TLSServerSetting`. (#9786)\n- `configtls`: Rename `TLSSetting` to `Config` on `ClientConfig` and `ServerConfig`. (#9786)\n\n### 🚩 Deprecations 🚩\n\n- `confighttp`: Deprecate `ToClient`,`ToListener`and `ToServer` use `ToClientContext`,`ToListenerContext` and `ToServerContext`instead. (#9807)\n- `configtls`: Deprecate `ClientConfig.LoadTLSConfig` and `ServerConfig.LoadTLSConfig`, use `ClientConfig.LoadTLSConfigContext` and `ServerConfig.LoadTLSConfigContext` instead. (#9811)\n\n### 💡 Enhancements 💡\n\n- Introduce new module for generating pdata: pdata/testdata (#9886)\n- `exporterhelper`: Make the `WithBatcher` option available for regular exporter helpers based on OTLP data type. (#8122)\n  Now, `WithBatcher` can be used with both regular exporter helper (e.g. NewTracesExporter) and the request-based exporter \n  helper (e.g. NewTracesRequestExporter). The request-based exporter helpers require `WithRequestBatchFuncs` option \n  providing batching functions. \n  \n- `confmap`: Creates a logger in the confmap.ProviderSettings and uses it to log when there is a missing or blank environment variable referenced in config. For now the noop logger is used everywhere except tests. (#5615)\n\n## v1.4.0/v0.97.0\n\n### 🛑 Breaking changes 🛑\n\n- `configgrpc`: Remove deprecated `ToServer` function. (#9787)\n- `confignet`: Change `Transport` field from `string` to `TransportType` (#9385)\n- `component`: Change underlying type of `component.Type` to an opaque struct. (#9208)\n- `obsreport`: Remove deprecated obsreport/obsreporttest package. (#9724)\n- `component`: Remove deprecated error `ErrNilNextConsumer` (#9322)\n- `connector`: Remove `LogsRouter`, `MetricsRouter` and `TracesRouter`. Use `LogsRouterAndConsumer`, `MetricsRouterAndConsumer`, `TracesRouterAndConsumer` respectively instead. (#9095)\n- `receiver`: Remove deprecated struct `ScraperControllerSettings` and function `NewDefaultScraperControllerSettings` (#6767)\n- `confmap`: Remove deprecated `provider.New` methods, use `NewWithSettings` moving forward. (#9443)\n\n### 🚩 Deprecations 🚩\n\n- `configgrpc`: Deprecated `ToServerContext`, use `ToServer` instead. (#9787)\n- `configgrpc`: Deprecate `SanitizedEndpoint` (#9788)\n\n### 💡 Enhancements 💡\n\n- `exporterhelper`: Add experimental batching capabilities to the exporter helper (#8122)\n- `confignet`: Adds `NewDefault*` functions for all the config structs. (#9656)\n- `configtls`: Validates TLS min_version and max_version (#9475)\n  Introduces `Validate()` method in TLSSetting.\n- `exporterhelper`: Invalid exporterhelper options now make the exporter creation error out instead of panicking. (#9717)\n- `components`: Give NoOp components a unique name (#9637)\n\n## v1.3.0/v0.96.0\n\n### 🚩 Deprecations 🚩\n\n- `configgrpc`: Deprecates `ToServer`.  Use `ToServerContext` instead. (#9624)\n- `component`: deprecate component.ErrNilNextConsumer (#9526)\n- `configtls`: Rename TLSClientSetting, TLSServerSetting, and TLSSetting based on the naming convention used in other config packages. (#9474)\n\n### 💡 Enhancements 💡\n\n- `receivertest`: add support for metrics in contract checker (#9551)\n\n## v1.2.0/v0.95.0\n\n### 🛑 Breaking changes 🛑\n\n- `all`: Bump minimum go version to go 1.21 (#9507)\n- `service/telemetry`: Delete generated_config types, use go.opentelemetry.io/contrib/config types instead (#9546)\n- `configcompression`: Remove deprecated `configcompression` types, constants and methods. (#9388)\n- `component`: Remove `host.ReportFatalError` (#6344)\n- `configgrpc`: Remove deprecated `configgrpc.ServerConfig.ToListener` (#9481)\n- `confmap`: Remove deprecated `confmap.WithErrorUnused` (#9484)\n\n### 🚩 Deprecations 🚩\n\n- `confignet`: Deprecate `confignet.NetAddr` and `confignet.TCPAddr` in favor of `confignet.AddrConfig` and `confignet.TCPAddrConfig`. (#9509)\n- `config/configgrpc`: Deprecate `configgrpc.ClientConfig.SanitizedEndpoint`, `configgrpc.ServerConfig.ToListener` and `configgrpc.ServerConfig.ToListenerContext` (#9481, #9482)\n- `scraperhelper`: Deprecate ScraperControllerSettings, use ControllerConfig instead (#6767)\n\n## v1.1.0/v0.94.0\n\n### 🛑 Breaking changes 🛑\n\n- `confignet`: Remove deprecated `DialContext` and `ListenContext` functions (#9363)\n- `confmap/converter/expandconverter`: Add `confmap.ConverterSettings` argument to experimental `expandconverter.New` function. (#5615, #9162)\n  - The `confmap.ConverterSettings` struct currently has no fields. It will be used to pass a logger.\n  \n- `component`: Remove deprecated funcs and types (#9283)\n- `otlpexporter`: Config struct is moving from embedding the deprecated GRPCClientSettings struct to using ClientConfig instead. (#6767)\n- `otlphttpexporter`: otlphttpexporter.Config embeds the struct confighttp.ClientConfig instead of confighttp.HTTPClientSettings (#6767)\n- `otlpreceiver`: HTTPConfig struct is moving from embedding the deprecated ServerSettings struct to using HTTPServerConfig instead. (#6767)\n- `component`: Validate component.Type at creation and unmarshaling time. (#9208)\n  - A component.Type must start with an ASCII alphabetic character and can only contain ASCII alphanumeric characters and '_'.\n  \n\n### 🚩 Deprecations 🚩\n\n- `configcompressions`: Deprecate `IsCompressed`.  Use `CompressionType.IsCompressed instead` instead. (#9435)\n- `configcompression`: Deprecate `CompressionType`, use `Type` instead. (#9416)\n- `confighttp`: Deprecate CORSSettings, use CORSConfig instead (#6767)\n- `configgrpc`: Deprecate `ToListener` function in favor of `ToListenerContext` (#9389)\n- `configgrpc`: Deprecate GRPCServerSettings, use ServerConfig instead (#6767)\n- `confighttp`: Deprecate HTTPClientSettings, use ClientConfig instead (#6767)\n- `confighttp`: Deprecate HTTPServerSettings, use ServerConfig instead (#6767)\n- `confmap/provider`: Deprecate <provider>.New in favor of <provider>.NewWithSettings for all core providers (#5615, #9162)\n  - NewWithSettings now takes an empty confmap.ProviderSettings struct. This will be used to pass a logger in the future.\n  \n\n### 💡 Enhancements 💡\n\n- `exporter/exporterhelper`: Add API for enabling queue in the new exporter helpers. (#7874)\n  The following experimental API is introduced in exporter package:\n    - `exporterhelper.WithRequestQueue`: a new exporter helper option for using a queue.\n    - `exporterqueue.Queue`: an interface for queue implementations.\n    - `exporterqueue.Factory`: a queue factory interface, implementations of this interface are intended to be used with WithRequestQueue option.\n    - `exporterqueue.Settings`: queue factory settings.\n    - `exporterqueue.Config`: common configuration for queue implementations.\n    - `exporterqueue.NewDefaultConfig`: a function for creating a default queue configuration.\n    - `exporterqueue.NewMemoryQueueFactory`: a new factory for creating a memory queue.\n    - `exporterqueue.NewPersistentQueueFactory: a factory for creating a persistent queue.\n  \n- `featuregate`: Add the `featuregate.ErrAlreadyRegistered` error, which is returned by `featuregate.Registry`'s `Register` when adding a feature gate that is already registered. (#8622)\n  Use `errors.Is` to check for this error.\n  \n\n## v0.93.0\n\n### 🛑 Breaking changes 🛑\n\n- `bug_fix`: Implement `encoding.BinaryMarshaler` interface to prevent `configopaque` -> `[]byte` -> `string` conversions from leaking the value (#9279)\n- `configopaque`: configopaque.String implements `fmt.Stringer` and `fmt.GoStringer`, outputting [REDACTED] when formatted with the %s, %q or %#v verbs` (#9213)\n  This may break applications that rely on the previous behavior of opaque strings with `fmt.Sprintf` to e.g. build URLs or headers.\n  Explicitly cast the opaque string to a string before using it in `fmt.Sprintf` to restore the previous behavior.\n  \n- `all`: Remove obsolete \"// +build\" directives (#9304)\n- `connectortest`: Remove deprecated connectortest router helpers. (#9278)\n\n### 🚩 Deprecations 🚩\n\n- `obsreporttest`: deprecate test funcs/structs (#8492)\n  The following methods/structs have been moved from obsreporttest to componenttest:\n  - obsreporttest.TestTelemetry -> componenttest.TestTelemetry\n  - obsreporttest.SetupTelemetry -> componenttest.SetupTelemetry\n  - obsreporttest.CheckScraperMetrics -> TestTelemetry.CheckScraperMetrics\n  - obsreporttest.TestTelemetry.TelemetrySettings -> componenttest.TestTelemetry.TelemetrySettings()\n  \n- `confignet`: Deprecates `DialContext` and `ListenContext` functions. Use `Dial` and `Listen` instead. (#9258)\n  Unlike the previous `Dial` and `Listen` functions, the new `Dial` and `Listen` functions take a `context.Context` like `DialContext` and `ListenContext`.\n\n## v1.0.1/v0.92.0\n\n### 🛑 Breaking changes 🛑\n\n- `otlpexporter`: Change Config members names to use Config suffix. (#9091)\n- `component`: Remove deprecated unused TelemetrySettingsBase (#9145)\n\n### 🚩 Deprecations 🚩\n\n- `confignet`: Deprecates the `Dial` and `Listen` functions in favor of `DialContext` and `ListenContext`. (#9163)\n- `component`: Deprecate unnecessary type StatusFunc (#9146)\n\n## v0.91.0\n\n## v1.0.0/v0.90.0\n\n### 🛑 Breaking changes 🛑\n\n- `exporterhelper`: Replace converter interface with function in the new experimental exporter helper. (#8122)\n- `featuregate`: Remove deprecate function `featuregate.NewFlag` (#8727)\n  Use `featuregate.Registry`'s `RegisterFlags` method instead.\n\n### 🚩 Deprecations 🚩\n\n- `telemetry`: deprecate jsonschema generated types (#15009)\n\n### 💡 Enhancements 💡\n\n- `pdata`: Add ZeroThreshold field to exponentialHistogramDataPoint in pmetric package. (#8802)\n\n## v1.0.0-rcv0018/v0.89.0\n\n### 🛑 Breaking changes 🛑\n\n- `otelcol`: CollectorSettings.Factories now expects: `func() (Factories, error)` (#8478)\n- `exporter/exporterhelper`: The experimental Request API is updated. (#7874)\n  - `Request` interface now includes ItemsCount() method.\n  - `RequestItemsCounter` is removed.\n  - The following interfaces are added:\n    - Added an optional interface for handling errors that occur during request processing `RequestErrorHandler`.\n    - Added a function to unmarshal bytes into a Request `RequestUnmarshaler`.\n    - Added a function to marshal a Request into bytes `RequestMarshaler`\n  \n\n### 🚩 Deprecations 🚩\n\n- `featuregate`: Deprecate `featuregate.NewFlag` in favor of `featuregate.Registry`'s `RegisterFlags` method (#8727)\n\n### 💡 Enhancements 💡\n\n- `featuregate`: Add validation for feature gates ID, URL and versions. (#8766)\n  Feature gates IDs are now explicitly restricted to ASCII alphanumerics and dots.\n  \n\n## v1.0.0-rcv0017/v0.88.0\n\n### 💡 Enhancements 💡\n\n- `pdata`: Add IsReadOnly() method to p[metrics|logs|traces].[Metrics|Logs|Spans] pdata structs allowing to check if the struct is read-only. (#6794)\n\n## v1.0.0-rcv0016/v0.87.0\n\n### 💡 Enhancements 💡\n\n- `pdata`: Introduce API to control pdata mutability (#6794)\n  This change introduces new API pdata methods to control the mutability:\n  - p[metric|trace|log].[Metrics|Traces|Logs].MarkReadOnly() - marks the pdata as read-only. Any subsequent\n    mutations will result in a panic.\n  - p[metric|trace|log].[Metrics|Traces|Logs].IsReadOnly() - returns true if the pdata is marked as read-only.\n  Currently, all the data is kept mutable. This API will be used by fanout consumer in the following releases. \n\n### 🛑 Breaking changes 🛑\n\n- `obsreport`: remove methods/structs deprecated in previous release. (#8492)\n- `extension`: remove deprecated Configs and Factories (#8631)\n\n## v1.0.0-rcv0015/v0.86.0\n\n### 🛑 Breaking changes 🛑\n\n- `service`: remove deprecated service.PipelineConfig (#8485)\n\n### 🚩 Deprecations 🚩\n\n- `obsreporttest`: deprecate To*CreateSettings funcs in obsreporttest (#8492)\n  The following TestTelemetry methods have been deprecated. Use structs instead:\n  -  ToExporterCreateSettings -> exporter.CreateSettings\n  -  ToProcessorCreateSettings -> processor.CreateSettings\n  -  ToReceiverCreateSettings -> receiver.CreateSettings\n  \n- `obsreport`: Deprecating `obsreport.Exporter`, `obsreport.ExporterSettings`, `obsreport.NewExporter` (#8492)\n  These deprecated methods/structs have been moved to exporterhelper:\n  - `obsreport.Exporter` -> `exporterhelper.ObsReport`\n  - `obsreport.ExporterSettings` -> `exporterhelper.ObsReportSettings`\n  - `obsreport.NewExporter` -> `exporterhelper.NewObsReport`\n  \n- `obsreport`: Deprecating `obsreport.BuildProcessorCustomMetricName`, `obsreport.Processor`, `obsreport.ProcessorSettings`, `obsreport.NewProcessor` (#8492)\n  These deprecated methods/structs have been moved to processorhelper:\n  - `obsreport.BuildProcessorCustomMetricName` -> `processorhelper.BuildCustomMetricName`\n  - `obsreport.Processor` -> `processorhelper.ObsReport`\n  - `obsreport.ProcessorSettings` -> `processorhelper.ObsReportSettings`\n  - `obsreport.NewProcessor` -> `processorhelper.NewObsReport`\n  \n- `obsreport`: Deprecating obsreport scraper and receiver API (#8492)\n  These deprecated methods/structs have been moved to receiverhelper and scraperhelper:\n  - `obsreport.Receiver` -> `receiverhelper.ObsReport`\n  - `obsreport.ReceiverSettings` -> `receiverhelper.ObsReportSettings`\n  - `obsreport.NewReceiver` -> `receiverhelper.NewObsReport`\n  - `obsreport.Scraper` -> `scraperhelper.ObsReport`\n  - `obsreport.ScraperSettings` -> `scraperhelper.ObsReportSettings`\n  - `obsreport.NewScraper` -> `scraperhelper.NewObsReport`\n  \n\n### 💡 Enhancements 💡\n\n- `otelcol`: Splitting otelcol into its own module. (#7924)\n- `service`: Split service into its own module (#7923)\n\n## v0.85.0\n\n## v0.84.0\n\n### 💡 Enhancements 💡\n\n- `exporter/exporterhelper`: Introduce a new exporter helper that operates over client-provided requests instead of pdata (#7874)\n  The following experimental API is introduced in exporter/exporterhelper package:\n    - `NewLogsRequestExporter`: a new exporter helper for logs.\n    - `NewMetricsRequestExporter`: a new exporter helper for metrics.\n    - `NewTracesRequestExporter`: a new exporter helper for traces.\n    - `Request`: an interface for client-defined requests.\n    - `RequestItemsCounter`: an optional interface for counting the number of items in a Request.\n    - `LogsConverter`: an interface for converting plog.Logs to Request.\n    - `MetricsConverter`: an interface for converting pmetric.Metrics to Request.\n    - `TracesConverter`: an interface for converting ptrace.Traces to Request.\n    All the new APIs are intended to be used by exporters that need to operate over client-provided requests instead of pdata.\n  \n- `otlpreceiver`: Export HTTPConfig as part of the API for creating the otlpreceiver configuration. (#8175)\n  Changes signature of receiver/otlpreceiver/config.go type httpServerSettings to HTTPConfig.\n\n## v0.83.0\n\n### 🛑 Breaking changes 🛑\n\n- `all`: Remove go 1.19 support, bump minimum to go 1.20 and add testing for 1.21 (#8207)\n\n### 💡 Enhancements 💡\n\n- `changelog`: Generate separate changelogs for end users and package consumers (#8153)\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "<!-- This file is autogenerated. See CONTRIBUTING.md for instructions to add an entry. -->\n\n# Changelog\n\nStarting with version v0.83.0, this changelog includes only user-facing changes.\nIf you are looking for developer-facing changes, check out [CHANGELOG-API.md](./CHANGELOG-API.md).\n\n<!-- next version -->\n\n## v1.54.0/v0.148.0\n\n### ❗ Known Issues ❗\n\n- `service`: The collector's internal Prometheus metrics endpoint (`:8888`) now emits OTel service labels with underscore\n  names (`service_name`, `service_instance_id`, `service_version`) instead of dot-notation names (`service.name`,\n  `service.instance.id`, `service.version`). Users scraping this endpoint with the Prometheus receiver will see these renamed\n  labels in resource and datapoint attributes. As a workaround, add the following `metric_relabel_configs` to your scrape\n  config in prometheus receiver:\n  ```yaml\n  metric_relabel_configs:\n    - source_labels: [service_name]\n      target_label: service.name\n    - source_labels: [service_instance_id]\n      target_label: service.instance.id\n    - source_labels: [service_version]\n      target_label: service.version\n    - regex: service_name|service_instance_id|service_version\n      action: labeldrop\n  ```\n  See https://github.com/open-telemetry/opentelemetry-collector/issues/14814 for details and updates.\n\n### 🛑 Breaking changes 🛑\n\n- `all`: Change metric units to be singular to match OTel specification, e.g. `{requests}` -> `{request}` (#14753)\n\n### 💡 Enhancements 💡\n\n- `cmd/mdatagen`: Add deprecated_type field to allow specifying an alias for component types. (#14718)\n- `cmd/mdatagen`: Generate entity-scoped MetricsBuilder API that enforces entity-metric associations at compile time (#14659)\n- `cmd/mdatagen`: Skip generating reaggregation config options for metrics that have no aggregatable attributes. (#14689)\n- `pkg/service`: The internal status reporter no longer drops repeated Ok and RecoverableError statuses (#14282)\n  Status events can now carry metadata and there's value in allowing them to be emitted despite the status value itself \n  not changing.\n  \n\n### 🧰 Bug fixes 🧰\n\n- `cmd/builder`: Add `.exe` to output binary names when building for Windows targets. (#12591)\n- `exporter/debug`: Add printing of metric metadata in detailed verbosity. (#14667)\n- `exporter/otlp_grpc`: Prevent nil pointer panic when push methods are called before the OTLP exporter initializes its gRPC clients. (#14663)\n  When the sending queue and retry are disabled, calling ConsumeTraces,\n  ConsumeMetrics, ConsumeLogs, or ConsumeProfiles before the OTLP exporter\n  initializes its gRPC clients could cause a nil pointer dereference panic.\n  The push methods now return an error instead of panicking.\n  \n- `exporter/otlp_http`: Show the actual destination URL in error messages when request URL is modified by middleware. (#14673)\n  Unwraps the `*url.Error` returned by `http.Client.Do()` to prevent misleading error logs when a middleware extension dynamically updates the endpoint.\n  \n- `pdata/pprofile`: Switch the dictionary of dictionary tables entries only once when merging profiles (#14709)\n  For dictionary table data, we used to switch their dictionaries when doing\n  the switch for the data that uses them.\n  However, when an entry is associated with multiple other data (several\n  samples can use the same stack), we would have been switching the\n  dictionaries of the entry multiple times.\n  \n  We now switch dictionaries for dictionary table data only once, before\n  switching the resource profiles.\n  \n\n<!-- previous-version -->\n\n## v1.53.0/v0.147.0\n\n### 💡 Enhancements 💡\n\n- `exporter/debug`: Output bucket counts for exponential histogram data points in normal verbosity. (#10463)\n- `pkg/exporterhelper`: Add `metadata_keys` configuration to `sending_queue.batch.partition` to partition batches by client metadata (#14139)\n  The `metadata_keys` configuration option is now available in the `sending_queue.batch.partition` section for all exporters.\n  When specified, batches are partitioned based on the values of the listed metadata keys, allowing separate batching per metadata partition. This feature\n  is automatically configured when using `exporterhelper.WithQueue()`.\n  \n\n### 🧰 Bug fixes 🧰\n\n- `cmd/builder`: Fix duplicate error output when CLI command execution fails in the builder tool. (#14436)\n- `cmd/mdatagen`: Fix duplicate error output when CLI command execution fails in the mdatagen tool. (#14436)\n- `cmd/mdatagen`: Fix semconv URL validation for metrics with underscores in their names (#14583)\n  Metrics like `system.disk.io_time` now correctly validate against semantic convention URLs containing underscores in the anchor tag.\n- `extension/memory_limiter`: Use ChainUnaryInterceptor instead of UnaryInterceptor to allow multiple interceptors. (#14634)\n  If multiple extensions that use the UnaryInterceptor are set the binary panics at start time.\n- `extension/memory_limiter`: Add support for streaming services. (#14634)\n- `pkg/config/configmiddleware`: Add context.Context to HTTP middleware interface constructors. (#14523)\n  This is a breaking API change for components that implement or use extensionmiddleware.\n- `pkg/confmap`: Fix another issue where configs could fail to decode when using interpolated values in string fields. (#14034)\n  For example, a resource attribute can be set via an environment variable to a string that is parseable as a number, e.g. `1234`.\n  \n  (A similar bug was fixed in a previous release: that one was triggered when the field was nested in a struct,\n  whereas this one is triggered when the field internally has type \"pointer to string\" rather than \"string\".)\n  \n- `pkg/otelcol`: The featuregate subcommand now rejects extra positional arguments instead of silently ignoring them. (#14554)\n- `pkg/queuebatch`: Fix data race in partition_batcher where resetTimer() was called outside mutex, causing concurrent timer.Reset() calls and unpredictable batch flush timing under load. (#14491)\n- `pkg/scraperhelper`: Log scrapers now emit log-appropriate receiver telemetry (#14654)\n  Log scrapers previously emitted the same receiver telemetry as metric scrapers,\n  such as the otelcol_receiver_accepted_metric_points metric (instead of otelcol_receiver_accepted_log_records),\n  or spans named receiver/myreceiver/MetricsReceived (instead of receiver/myreceiver/LogsReceived).\n  \n  This did not affect scraper-specific spans and metrics.\n  \n- `processor/batch`: Fixes a bug where the batch processor would not copy `SchemaUrl` metadata from resource and scope containers during partial batch splits. (#12279, #14620)\n\n<!-- previous-version -->\n\n## v1.52.0/v0.146.1\n\n<!-- previous-version -->\n\n## v0.146.0\n\n### 🛑 Breaking changes 🛑\n\n- `all`: Increase minimum Go version to 1.25 (#14567)\n\n### 🚩 Deprecations 🚩\n\n- `pdata/pprofile`: Declare removed aggregation elements as deprecated. (#14528)\n\n### 💡 Enhancements 💡\n\n- `all`: Add detailed failure attributes to exporter send_failed metrics at detailed telemetry level. (#13956)\n  The `otelcol_exporter_send_failed_{spans,metric_points,log_records}` metrics now include\n  failure attributes when telemetry level is Detailed: `error.type` (OpenTelemetry semantic convention\n  describing the error class) and `error.permanent` (indicates if error is permanent/non-retryable).\n  The `error.type` attribute captures gRPC status codes (e.g., \"Unavailable\", \"ResourceExhausted\"),\n  standard Go context errors (e.g., \"canceled\", \"deadline_exceeded\"),\n  and collector-specific errors (e.g., \"shutdown\").\n  This enables better alerting and debugging by providing standardized error classification.\n- `cmd/builder`: Introduce new experimental `init` subcommand (#14530)\n  The new `init` subcommand initializes a new custom collector\n- `cmd/builder`: Add \"telemetry\" field to allow configuring telemetry providers (#14575)\n  Most users should not need to use this, this field should only be set if you\n  intend to provide your own OpenTelemetry SDK.\n  \n- `cmd/mdatagen`: Introduce additional metadata (the version since the deprecation started, and the deprecation reason) for deprecated metrics. (#14113)\n- `cmd/mdatagen`: Add optional `relationships` field to entity schema in metadata.yaml (#14284)\n- `exporter/debug`: Add `output_paths` configuration option to control output destination when `use_internal_logger` is false. (#10472)\n  When `use_internal_logger` is set to `false`, the debug exporter now supports configuring the output destination via the `output_paths` option.\n  This allows users to send debug exporter output to `stdout`, `stderr`, or a file path.\n  The default value is `[\"stdout\"]` to maintain backward compatibility.\n  \n- `pkg/confmap`: Add experimental `ToStringMapRaw` function to decode `confmap.Conf` into a string map without losing internal types (#14480)\n  This method exposes the internal structure of a `confmap.Conf` which may change at any time without prior notice\n  \n\n### 🧰 Bug fixes 🧰\n\n- `cmd/mdatagen`: Reset aggDataPoints during metric init to avoid index out of range panic across emit cycles when reaggregation is enabled. (#14569)\n- `cmd/mdatagen`: Fix panic when mdatagen is run without arguments. (#14506)\n- `pdata/pprofile`: Fix off-by-one issue in dictionary lookups. (#14534)\n- `pkg/config/confighttp`: Fix high cardinality span name from request method from confighttp server internal telemetry (#14516)\n  Follow spec to bound request method cardinality.\n- `pkg/otelcol`: Ignore component aliases in the `otelcol components` command (#14492)\n- `pkg/otelcol`: Order providers and converters in alphabetical order in the `components` subcommand. (#14476)\n\n<!-- previous-version -->\n\n## v1.51.0/v0.145.0\n\n### 💡 Enhancements 💡\n\n- `pkg/scraperhelper`: ScraperID has been added to the logs for metrics, logs, and profiles (#14461)\n\n### 🧰 Bug fixes 🧰\n\n- `exporter/otlp_grpc`: Fix the OTLP exporter balancer to use round_robin by default, as intended. (#14090)\n- `pkg/config/configoptional`: Fix `Unmarshal` methods not being called when config is wrapped inside `Optional` (#14500)\n  This bug notably manifested in the fact that the `sending_queue::batch::sizer` config for exporters\n  stopped defaulting to `sending_queue::sizer`, which sometimes caused the wrong units to be used\n  when configuring `sending_queue::batch::min_size` and `max_size`.\n  \n  As part of the fix, `xconfmap` exposes a new `xconfmap.WithForceUnmarshaler` option, to be used in the `Unmarshal` methods\n  of wrapper types like `configoptional.Optional` to make sure the `Unmarshal` method of the inner type is called.\n  \n  The default behavior remains that calling `conf.Unmarshal` on the `confmap.Conf` passed as argument to an `Unmarshal`\n  method will skip any top-level `Unmarshal` methods to avoid infinite recursion in standard use cases. \n  \n- `pkg/confmap`: Fix an issue where configs could fail to decode when using interpolated values in string fields. (#14413)\n  For example, a header can be set via an environment variable to a string that is parseable as a number, e.g. `1234`\n  \n- `pkg/service`: Don't error on startup when process metrics are enabled on unsupported OSes (e.g. AIX) (#14307)\n\n<!-- previous-version -->\n\n## v1.50.0/v0.144.0\n\n### 🛑 Breaking changes 🛑\n\n- `pkg/exporterhelper`: Change verbosity level for otelcol_exporter_queue_batch_send_size metric to detailed. (#14278)\n- `pkg/service`: Remove deprecated `telemetry.disableHighCardinalityMetrics` feature gate. (#14373)\n- `pkg/service`: Remove deprecated `service.noopTracerProvider` feature gate. (#14374)\n\n### 🚩 Deprecations 🚩\n\n- `exporter/otlp_grpc`: Rename `otlp` exporter to `otlp_grpc` exporter and add deprecated alias `otlp`. (#14403)\n- `exporter/otlp_http`: Rename `otlphttp` exporter to `otlp_http` exporter and add deprecated alias `otlphttp`. (#14396)\n\n### 💡 Enhancements 💡\n\n- `cmd/builder`: Avoid duplicate CLI error logging in generated collector binaries by relying on cobra's error handling. (#14317)\n- `cmd/mdatagen`: Add the ability to disable attributes at the metric level and re-aggregate data points based off of these new dimensions (#10726)\n- `cmd/mdatagen`: Add optional `display_name` and `description` fields to metadata.yaml for human-readable component names (#14114)\n  The `display_name` field allows components to specify a human-readable name in metadata.yaml.\n  When provided, this name is used as the title in generated README files.\n  The `description` field allows components to include a brief description in generated README files.\n  \n- `cmd/mdatagen`: Validate stability level for entities (#14425)\n- `pkg/xexporterhelper`: Reenable batching for profiles (#14313)\n- `receiver/nop`: add profiles signal support (#14253)\n\n### 🧰 Bug fixes 🧰\n\n- `pkg/exporterhelper`: Fix reference count bug in partition batcher (#14444)\n\n<!-- previous-version -->\n\n## v1.49.0/v0.143.0\n\n### 💡 Enhancements 💡\n\n- `all`: Update semconv import to 1.38.0 (#14305)\n- `exporter/nop`: Add profiles support to nop exporter (#14331)\n- `pkg/pdata`: Optimize the size and pointer bytes for pdata structs (#14339)\n- `pkg/pdata`: Avoid using interfaces/oneof like style for optional fields (#14333)\n\n<!-- previous-version -->\n\n## v1.48.0/v0.142.0\n\n### 💡 Enhancements 💡\n\n- `exporter/debug`: Add logging of dropped attributes, events, and links counts in detailed verbosity (#14202)\n- `extension/memory_limiter`: The memorylimiter extension can be used as an HTTP/GRPC middleware. (#14081)\n- `pkg/config/configgrpc`: Statically validate gRPC endpoint (#10451)\n  This validation was already done in the OTLP exporter. It will now be applied to any gRPC client.\n  \n- `pkg/service`: Add support to disabling adding resource attributes as zap fields in internal logging (#13869)\n  Note that this does not affect logs exported through OTLP.\n  \n\n<!-- previous-version -->\n\n## v1.47.0/v0.141.0\n\n### 🛑 Breaking changes 🛑\n\n- `pkg/config/confighttp`: Use configoptional.Optional for confighttp.ClientConfig.Cookies field (#14021)\n\n### 💡 Enhancements 💡\n\n- `pkg/config/confighttp`: Setting `compression_algorithms` to an empty list now disables automatic decompression, ignoring Content-Encoding (#14131)\n- `pkg/service`: Update semantic conventions from internal telemetry to v1.37.0 (#14232)\n- `pkg/xscraper`: Implement xscraper for Profiles. (#13915)\n\n### 🧰 Bug fixes 🧰\n\n- `pkg/config/configoptional`: Ensure that configoptional.None values resulting from unmarshaling are equivalent to configoptional.Optional zero value. (#14218)\n\n<!-- previous-version -->\n\n## v1.46.0/v0.140.0\n\n### 💡 Enhancements 💡\n\n- `cmd/mdatagen`: `metadata.yaml` now supports an optional `entities` section to organize resource attributes into logical entities with identity and description attributes (#14051)\n  When entities are defined, mdatagen generates `AssociateWith{EntityType}()` methods on ResourceBuilder\n  that associate resources with entity types using the entity refs API. The entities section is backward\n  compatible - existing metadata.yaml files without entities continue to work as before.\n  \n- `cmd/mdatagen`: Add semconv reference for metrics (#13920)\n- `connector/forward`: Add support for Profiles to Profiles (#14092)\n- `exporter/debug`: Disable sending queue by default (#14138)\n  The recently added sending queue configuration in Debug exporter was enabled by default and had a problematic default size of 1.\n  This change disables the sending queue by default.\n  Users can enable and configure the sending queue if needed.\n  \n- `pkg/config/configoptional`: Mark `configoptional.AddEnabledField` as beta (#14021)\n- `pkg/otelcol`: This feature has been improved and tested; secure-by-default redacts configopaque values (#12369)\n\n### 🧰 Bug fixes 🧰\n\n- `all`: Ensure service service.instance.id is the same for all the signals when it is autogenerated. (#14140)\n\n<!-- previous-version -->\n\n## v1.45.0/v0.139.0\n\n### 🛑 Breaking changes 🛑\n\n- `cmd/mdatagen`: Make stability.level a required field for metrics (#14070)\n- `cmd/mdatagen`: Replace `optional` field with `requirement_level` field for attributes in metadata schema (#13913)\n  The `optional` boolean field for attributes has been replaced with a `requirement_level` field that accepts enum values: `required`, `conditionally_required`, `recommended`, or `opt_in`.\n  - `required`: attribute is always included and cannot be excluded\n  - `conditionally_required`: attribute is included by default when certain conditions are met (replaces `optional: true`)\n  - `recommended`: attribute is included by default but can be disabled via configuration (replaces `optional: false`)\n  - `opt_in`: attribute is not included unless explicitly enabled in user config\n  When `requirement_level` is not specified, it defaults to `recommended`.\n  \n- `pdata/pprofile`: Remove deprecated `PutAttribute` helper method (#14082)\n- `pdata/pprofile`: Remove deprecated `PutLocation` helper method (#14082)\n\n### 💡 Enhancements 💡\n\n- `all`: Add FIPS and non-FIPS implementations for allowed TLS curves (#13990)\n- `cmd/builder`: Set CGO_ENABLED=0 by default, add the `cgo_enabled` configuration to enable it. (#10028)\n- `pkg/config/configgrpc`: Errors of type status.Status returned from an Authenticator extension are being propagated as is to the upstream client. (#14005)\n- `pkg/config/configoptional`: Adds new `configoptional.AddEnabledField` feature gate that allows users to explicitly disable a `configoptional.Optional` through a new `enabled` field. (#14021)\n- `pkg/exporterhelper`: Replace usage of gogo proto for persistent queue metadata (#14079)\n- `pkg/pdata`: Remove usage of gogo proto and generate the structs with pdatagen (#14078)\n\n### 🧰 Bug fixes 🧰\n\n- `exporter/debug`: add queue configuration (#14101)\n\n<!-- previous-version -->\n\n## v1.44.0/v0.138.0\n\n### 🛑 Breaking changes 🛑\n\n- `all`: Remove deprecated type `TracesConfig` (#14036)\n- `pkg/exporterhelper`: Add default values for `sending_queue::batch` configuration. (#13766)\n  Setting `sending_queue::batch` to an empty value now results in the same setup as the default batch processor configuration.\n  \n- `all`: Add unified print-config command with mode support (redacted, unredacted), json support (unstable), and validation support. (#11775)\n  This replaces the `print-initial-config` command. See the `service` package README for more details. The original command name `print-initial-config` remains an alias, to be retired with the feature flag.\n\n### 💡 Enhancements 💡\n\n- `all`: Add `keep_alives_enabled` option to ServerConfig to control HTTP keep-alives for all components that create an HTTP server. (#13783)\n- `pkg/otelcol`: Avoid unnecessary mutex in collector logs, replace by atomic pointer (#14008)\n- `cmd/mdatagen`: Add lint/ordering validation for metadata.yaml (#13781)\n- `pdata/xpdata`: Refactor JSON marshaling and unmarshaling to use `pcommon.Value` instead of `AnyValue`. (#13837)\n- `pkg/exporterhelper`: Expose `MergeCtx` in exporterhelper's queue batch settings` (#13742)\n\n### 🧰 Bug fixes 🧰\n\n- `all`: Fix zstd decoder data corruption due to decoder pooling for all components that create an HTTP server. (#13954)\n- `pkg/otelcol`: Remove UB when taking internal logs and move them to the final zapcore.Core (#14009)\n  This can happen because of a race on accessing `logsTaken`.\n- `pkg/confmap`: Fix a potential race condition in confmap by closing the providers first. (#14018)\n\n<!-- previous-version -->\n\n## v1.43.0/v0.137.0\n\n### 💡 Enhancements 💡\n\n- `cmd/mdatagen`: Improve validation for resource attribute `enabled` field in metadata files (#12722)\n  Resource attributes now require an explicit `enabled` field in metadata.yaml files, while regular attributes\n  are prohibited from having this field. This improves validation and prevents configuration errors.\n  \n- `all`: Changelog entries will now have their component field checked against a list of valid components. (#13924)\n  This will ensure a more standardized changelog format which makes it easier to parse.\n- `pkg/pdata`: Mark featuregate pdata.useCustomProtoEncoding as stable (#13883)\n\n<!-- previous-version -->\n\n## v1.42.0/v0.136.0\n\n### 💡 Enhancements 💡\n\n- `xpdata`: Add Serialization and Deserialization of AnyValue (#12826)\n- `debugexporter`: add support for batching (#13791)\n  The default queue size is 1\n- `configtls`: Add early validation for TLS server configurations to fail fast when certificates are missing instead of failing at runtime. (#13130, #13245)\n- `mdatagen`: Expose stability level in generated metric documentation (#13748)\n- `internal/tools`: Add support for modernize in Makefile (#13796)\n\n### 🧰 Bug fixes 🧰\n\n- `otelcol`: Fix a potential deadlock during collector shutdown. (#13740)\n- `otlpexporter`: fix the validation of unix socket endpoints (#13826)\n\n<!-- previous-version -->\n\n## v1.41.0/v0.135.0\n\n### 💡 Enhancements 💡\n\n- `exporterhelper`: Add new `exporter_queue_batch_send_size` and `exporter_queue_batch_send_size_bytes` metrics, showing the size of telemetry batches from the exporter. (#12894)\n\n<!-- previous-version -->\n\n## v1.40.0/v0.134.0\n\n### 💡 Enhancements 💡\n\n- `pdata`: Add custom grpc/encoding that replaces proto and calls into the custom marshal/unmarshal logic in pdata. (#13631)\n  This change should not affect other gRPC calls since it fallbacks to the default grpc/proto encoding if requests are not pdata/otlp requests.\n- `pdata`: Avoid copying the pcommon.Map when same origin (#13731)\n  This is a very large improvement if using OTTL with map functions since it will avoid a map copy.\n- `exporterhelper`: Respect `num_consumers` when batching and partitioning are enabled. (#13607)\n\n### 🧰 Bug fixes 🧰\n\n- `pdata`: Correctly parse OTLP payloads containing non-packed repeated primitive fields (#13727, #13730)\n  This bug prevented the Collector from ingesting most Histogram, ExponentialHistogram,\n  and Profile payloads.\n  \n\n<!-- previous-version -->\n\n## v1.39.0/v0.133.0\n\n### 🛑 Breaking changes 🛑\n\n- `all`: Increase minimum Go version to 1.24 (#13627)\n\n### 💡 Enhancements 💡\n\n- `otlphttpexporter`: Add `profiles_endpoint` configuration option to allow custom endpoint for profiles data export (#13504)\n  The `profiles_endpoint` configuration follows the same pattern as `traces_endpoint`, `metrics_endpoint`, and `logs_endpoint`.\n  When specified, profiles data will be sent to the custom URL instead of the default `{endpoint}/v1development/profiles`.\n  \n- `pdata`: Add support for local memory pooling for data objects. (#13678)\n  This is still an early experimental (alpha) feature. Do not recommended to be used production. To enable use \"--featuregate=+pdata.useProtoPooling\"\n- `pdata`: Optimize CopyTo messages to avoid any copy when same source and destination (#13680)\n- `receiverhelper`: New feature flag to make receiverhelper distinguish internal vs. downstream errors using new `otelcol_receiver_failed_x` and `otelcol_receiver_requests` metrics (#12207, #12802)\n  This is a breaking change for the semantics of the otelcol_receiver_refused_metric_points,  otelcol_receiver_refused_log_records and otelcol_receiver_refused_spans metrics.\n  These new metrics and semantics are enabled through the `receiverhelper.newReceiverMetrics` feature gate.\n  \n- `debugexporter`: Add support for entity references in debug exporter output (#13324)\n- `pdata`: Fix unnecessary allocation of a new state when adding new values to pcommon.Map (#13634)\n- `service`: Implement refcounting for pipeline data owned memory. (#13631)\n  This feature is protected by `--featuregate=+pdata.useProtoPooling`.\n- `service`: Add a debug-level log message when a consumer returns an error. (#13357)\n- `xpdata`: Optimize xpdata/context for persistent queue when only one value for key (#13636)\n- `otlpreceiver`: Log the listening addresses of the receiver, rather than the configured endpoints. (#13654)\n- `pdata`: Use the newly added proto marshaler/unmarshaler for the official proto Marshaler/Unmarshaler (#13637)\n  If any problems observed with this consider to disable the featuregate `--feature-gates=-pdata.useCustomProtoEncoding`\n<!-- cspell:ignore MLKEM mlkem -->\n- `configtls`: Enable X25519MLKEM768 as per draft-ietf-tls-ecdhe-mlkem (#13670)\n\n### 🧰 Bug fixes 🧰\n\n- `exporterhelper`: Prevent uncontrolled goroutines in batcher due to a incorrect worker pool behaviour. (#13689)\n- `service`: Ensure the insecure configuration is accounted for when normalizing the endpoint. (#13691)\n- `configoptional`: Allow validating nested types (#13579)\n  `configoptional.Optional` now implements `xconfmap.Validator`\n- `batchprocessor`: Fix UB in batch processor when trying to read bytes size after adding request to pipeline (#13698)\n  This bug only happens id detailed metrics are enabled and also an async (sending queue enabled) exporter that mutates data is configure.\n\n<!-- previous-version -->\n\n## v1.38.0/v0.132.0\n\n### 🛑 Breaking changes 🛑\n\n- `componentstatus`: Change the signature of the componentstatus.NewEvent to accept multiple options. (#13210)\n  Changes the signature of the component.NewEvent to accept multiple EventBuilderOption,\n  like the new WithAttributes constructor.\n  \n\n### 🚩 Deprecations 🚩\n\n- `service`: move service.noopTraceProvider feature gate to deprecated stage (#13492)\n  The functionality of the feature gate is available via configuration with the following telemetry settings:\n  ```\n  service:\n    telemetry:\n      traces:\n        level: none\n  ```\n  \n- `mdatagen`: Remove the deletion of `generated_component_telemetry_test.go`. (#12067)\n  This file used to be generated by mdatagen. Starting with 0.122.0, the code deletes that file.\n  It is no longer necessary to delete the file, as code has had time to upgrade to mdatagen and delete the file.\n  \n- `service`: The `telemetry.disableHighCardinalityMetrics` feature gate is deprecated (#13537)\n  The feature gate is now deprecated since metric views can be configured.\n  The feature gate will be removed in v0.134.0.\n  \n  The metric attributes removed by this feature gate are no longer emitted\n  by the Collector by default, but if needed, you can achieve the same\n  functionality by configuring the following metric views:\n  \n  ```yaml\n  service:\n    telemetry:\n      metrics:\n        level: detailed\n        views:\n          - selector:\n              meter_name: \"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc\"\n            stream:\n              attribute_keys:\n                excluded: [\"net.sock.peer.addr\", \"net.sock.peer.port\", \"net.sock.peer.name\"]\n          - selector:\n              meter_name: \"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\"\n            stream:\n              attribute_keys:\n                excluded: [\"net.host.name\", \"net.host.port\"]\n  ```\n  \n  Note that this requires setting `service::telemetry::metrics::level: detailed`.\n  If you have a strong use case for using views in combination with a different\n  level, please show your interest in\n  https://github.com/open-telemetry/opentelemetry-collector/issues/10769.\n  \n\n### 💡 Enhancements 💡\n\n- `pdata`: Generate Logs/Traces/Metrics/Profiles and p[log|trace|metric|profile]ExportResponse with pdatagen. (#13597)\n  This change brings consistency on how these structs are written and remove JSON marshaling/unmarshaling hand written logic.\n- `confighttp`: Add option to configure ForceAttemptHTTP2 to support HTTP/1 specific transport settings. (#13426)\n- `pdata`: Avoid unnecessary buffer copy when JSON marshal fails. (#13598)\n- `cmd/mdatagen`: Use a custom host implementation for lifecycle tests (#13589)\n  Use a custom noop host implementation that implements all non-deprecated, publicly-accessible interfaces implemented by the Collector service.\n- `processorhelper`: Add processor internal duration metric. (#13231)\n- `pdata`: Improve RemoveIf for slices to not reference anymore the removed memory (#13522)\n\n### 🧰 Bug fixes 🧰\n\n- `pdata`: Fix null pointer access when copying into a slice with larger cap but smaller len. (#13523)\n- `confighttp`: Fix middleware configuration field name from \"middleware\" to \"middlewares\" for consistency with configgrpc (#13444)\n- `memorylimiterextension, memorylimiterprocessor`: Memory limiter extension and processor shutdown don't throw an error if the component was not started first. (#9687)\n  The components would throw an error if they were shut down before being started.\n  With this change, they will no longer return an error, conforming to the lifecycle of components expected.\n  \n- `confighttp`: Reuse zstd Reader objects (#11824)\n\n<!-- previous-version -->\n\n## v1.37.0/v0.131.0\n\n### 🛑 Breaking changes 🛑\n\n- `confighttp`: Move `confighttp.framedSnappy` feature gate to beta. (#10584)\n\n### 💡 Enhancements 💡\n\n- `exporter/debug`: Move to alpha stability except profiles (#13487)\n- `exporterhelper`: Enable `exporter.PersistRequestContext` feature gate by default. (#13437)\n  Request context is now preserved by default when using persistent queues.\n  Note that Auth extensions context is not propagated through the persistent queue.\n  \n- `pdata`: Use pdatagen to generate marshalJSON without using gogo proto jsonpb. (#13450)\n- `otlpreceiver`: Remove usage of gogo proto which uses reflect.Value.MethodByName. Removes one source of disabling DCE. (#12747)\n- `exporterhelper`: Fix metrics split logic to consider metrics description into the size. (#13418)\n- `service`: New pipeline instrumentation now differentiates internal failures from downstream errors (#13234)\n  With the telemetry.newPipelineTelemetry feature gate enabled, the \"received\" and \"produced\"\n  metrics related to a component now distinguish between two types of errors:\n  - \"outcome = failure\" indicates that the component returned an internal error;\n  - \"outcome = refused\" indicates that the component successfully emitted data, but returned an\n    error coming from a downstream component processing that data.\n  \n- `pdata`: Remove usage of text/template from pdata, improves DCE. (#12747)\n- `architecture`: New Tier 3 platform riscv64 allowing the collector to be built and distributed for this platform. (#13462)\n\n### 🧰 Bug fixes 🧰\n\n- `exporterhelper`: Prevents the exporter for being stuck when telemetry data is bigger than batch.max_size (#12893)\n- `mdatagen`: Fix import paths for mdatagen component (#13069)\n- `otlpreceiver`: Error handler correctly fallbacks to content type (#13414)\n- `pdata/pprofiles`: Fix profiles JSON unmarshal logic for originalPayload. The bytes have to be base64 encoded. (#13483)\n- `xpdata`: Fix unmarshaling JSON for entities, add e2e tests to avoid this in the future. (#13480)\n- `service`: Downgrade dependency of prometheus exporter in OTel Go SDK (#13429)\n  This fixes the bug where collector's internal metrics are emitted with an unexpected suffix in their names when users configure the service::telemetry::metrics::readers with Prometheus\n- `service`: Revert Default internal metrics config now enables `otel_scope_` labels (#12939, #13344)\n  Reverting change temporarily due to prometheus exporter downgrade. This unfortunately re-introduces the bug that instrumentation scope attributes cause errors in Prometheus exporter. See http://github.com/open-telemetry/opentelemetry-collector/issues/12939 for details.\n- `builder`: Remove undocumented handling of `DIST_*` environment variables replacements (#13335)\n\n<!-- previous-version -->\n\n## v1.36.1/v0.130.1\n\n### 🧰 Bug fixes 🧰\n\n- `service`: Fixes bug where internal metrics are emitted with an unexpected suffix in their names when users configure `service::telemetry::metrics::readers` with Prometheus. (#13449)\n  See more details on https://github.com/open-telemetry/opentelemetry-go/issues/7039\n\n<!-- previous-version -->\n\n## v1.36.0/v0.130.0\n\n### ❗ Known Issues ❗\n\n- Due to a [bug](https://github.com/open-telemetry/opentelemetry-go/issues/7039) in the prometheus exporter, if you are configuring a prometheus exporter, the collector's internal metrics will be emitted with an unexpected suffix in its name. For example, the metric `otelcol_exporter_sent_spans__spans__total` instead of `otelcol_exporter_sent_spans_total`. The workaround is to manually configure `without_units: true` in your prometheus exporter config\n\n  ```yaml\n  service:\n    telemetry:\n      metrics:\n        readers:\n          - pull:\n              exporter:\n                prometheus:\n                  host: 0.0.0.0\n                  port: 8888\n                  without_units: true\n  ```\n\n  If you are using the collector's default Prometheus exporter for exporting internal metrics you are unaffected. \n\n### 🛑 Breaking changes 🛑\n\n- `exporter/otlp`: Remove deprecated batcher config from OTLP, use queuebatch (#13339)\n\n### 💡 Enhancements 💡\n\n- `exporterhelper`: Enable items and bytes sizers for persistent queue (#12881)\n- `exporterhelper`: Refactor persistent storage size backup to always record it. (#12890)\n- `exporterhelper`: Add support to configure a different Sizer for the batcher than the queue (#13313)\n- `yaml`: Replaced `sigs.k8s.io/yaml` with `go.yaml.in/yaml` for improved support and long-term maintainability. (#13308)\n\n### 🧰 Bug fixes 🧰\n\n- `exporterhelper`: Fix exporter.PersistRequestContext feature gate (#13342)\n- `exporterhelper`: Preserve all metrics metadata when batch splitting. (#13236)\n  Previously, when large batches of metrics were processed, the splitting logic in `metric_batch.go` could\n  cause the `name` field of some metrics to disappear. This fix ensures that all metric fields are\n  properly preserved when `metricRequest` objects are split.\n  \n- `service`: Default internal metrics config now enables `otel_scope_` labels (#12939, #13344)\n  By default, the Collector exports its internal metrics using a Prometheus\n  exporter from the opentelemetry-go repository. With this change, the Collector\n  no longer sets \"without_scope_info\" to true in its configuration.\n  \n  This means that all exported metrics will have `otel_scope_name`,\n  `otel_scope_schema_url`, and `otel_scope_version` labels corresponding to the\n  instrumentation scope metadata for that metric.\n  \n  This notably prevents an error when multiple metrics are only distinguished\n  by their instrumentation scopes and end up aliased during export.\n  \n  If this is not desired behavior, a Prometheus exporter can be explicitly\n  configured with this option enabled.\n  \n\n<!-- previous-version -->\n\n## v1.35.0/v0.129.0\n\n### 🛑 Breaking changes 🛑\n\n- `exporterhelper`: Remove deprecated sending_queue::blocking options, use sending_queue::block_on_overflow. (#13211)\n\n### 💡 Enhancements 💡\n\n- `mdatagen`: Taught mdatagen to print the `go list` stderr output on failures, and to run `go list` where the metadata file is. (#13205)\n- `service`: Support setting `sampler` and `limits` under `service::telemetry::traces` (#13201)\n  This allows users to enable sampling and set span limits on internal Collector traces using the\n  OpenTelemetry SDK declarative configuration.\n  \n- `pdata/pprofile`: Add new helper methods `FromLocationIndices` and `PutLocation` to read and modify the content of locations. (#13150)\n- `exporterhelper`: Preserve request span context and client information in the persistent queue. (#11740, #13220, #13232)\n  It allows internal collector spans and client information to propagate through the persistent queue used by \n  the exporters. The same way as it's done for the in-memory queue.\n  Currently, it is behind the exporter.PersistRequestContext feature gate, which can be enabled by adding \n  `--feature-gates=exporter.PersistRequestContext` to the collector command line. An exporter buffer stored by\n  a previous version of the collector (or by a collector with the feature gate disabled) can be read by a newer\n  collector with the feature enabled. However, the reverse is not supported: a buffer stored by a newer collector with\n  the feature enabled cannot be read by an older collector (or by a collector with the feature gate disabled).\n  \n\n### 🧰 Bug fixes 🧰\n\n- `pdata`: Fix copying of optional fields when the source is unset. (#13268)\n- `service`: Only allocate one set of internal log sampling counters (#13014)\n  The case where logs are only exported to stdout was fixed in v0.126.0;\n  this new fix also covers the case where logs are exported through OTLP.\n  \n\n<!-- previous-version -->\n\n## v1.34.0/v0.128.0\n\n### 🛑 Breaking changes 🛑\n\n- `service/telemetry`: Mark \"telemetry.disableAddressFieldForInternalTelemetry\" as stable (#13152)\n\n### 💡 Enhancements 💡\n\n- `confighttp`: Update the HTTP server span naming to use the HTTP method and route pattern instead of the path. (#12468)\n  The HTTP server span name will now be formatted as `<http.request.method> <http.route>`.\n  If a route pattern is not available, it will fall back to `<http.request.method>`.\n  \n- `service`: Use configured loggers to log errors as soon as it is available (#13081)\n- `service`: Remove stabilized featuregate useOtelWithSDKConfigurationForInternalTelemetry (#13152)\n\n### 🧰 Bug fixes 🧰\n\n- `telemetry`: Add generated resource attributes to the printed log messages. (#13110)\n  If service.name, service.version, or service.instance.id are not specified in the config, they will be generated automatically.\n  This change ensures that these attributes are also included in the printed log messages.\n  \n- `mdatagen`: Fix generation when there are no events in the metadata. (#13123)\n- `confmap`: Do not panic on assigning nil maps to non-nil maps (#13117)\n- `pdata`: Fix event_name skipped when unmarshalling LogRecord from JSON (#13127)\n\n<!-- previous-version -->\n\n## v1.33.0/v0.127.0\n\n### 🚩 Deprecations 🚩\n\n- `semconv`: Deprecating the semconv package in favour of go.opentelemetry.io/otel/semconv (#13012)\n\n### 💡 Enhancements 💡\n\n- `exporter/debug`: Display resource and scope in `normal` verbosity (#10515)\n- `service`: Add size metrics defined in Pipeline Component Telemetry RFC (#13032)\n  See [Pipeline Component Telemetry RFC](https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/rfcs/component-universal-telemetry.md) for more details:\n    - `otelcol.receiver.produced.size`\n    - `otelcol.processor.consumed.size`\n    - `otelcol.processor.produced.size`\n    - `otelcol.connector.consumed.size`\n    - `otelcol.connector.produced.size`\n    - `otelcol.exporter.consumed.size`\n  \n\n<!-- previous-version -->\n\n## v1.32.0/v0.126.0\n\n### 🛑 Breaking changes 🛑\n\n- `configauth`: Removes deprecated `configauth.Authentication` and `extensionauthtest.NewErrorClient` (#12992)\n  The following have been removed:\n  - `configauth.Authentication` use `configauth.Config` instead\n  - `extensionauthtest.NewErrorClient` use `extensionauthtest.NewErr` instead\n  \n\n### 💡 Enhancements 💡\n\n- `service`: Replace `go.opentelemetry.io/collector/semconv` usage with `go.opentelemetry.io/otel/semconv` (#12991)\n- `confmap`: Update the behavior of the confmap.enableMergeAppendOption feature gate to merge only component lists. (#12926)\n- `service`: Add item count metrics defined in Pipeline Component Telemetry RFC (#12812)\n  See [Pipeline Component Telemetry RFC](https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/rfcs/component-universal-telemetry.md) for more details:\n    - `otelcol.receiver.produced.items`\n    - `otelcol.processor.consumed.items`\n    - `otelcol.processor.produced.items`\n    - `otelcol.connector.consumed.items`\n    - `otelcol.connector.produced.items`\n    - `otelcol.exporter.consumed.items`\n  \n- `tls`: Add trusted platform module (TPM) support to TLS authentication. (#12801)\n  Now the TLS allows the use of TPM for loading private keys (e.g. in TSS2 format).\n  \n\n### 🧰 Bug fixes 🧰\n\n- `exporterhelper`: Add validation error for batch config if min_size is greater than queue_size. (#12948)\n- `telemetry`: Allocate less memory per component when OTLP exporting of logs is disabled (#13014)\n- `confmap`: Use reflect.DeepEqual to avoid panic when confmap.enableMergeAppendOption feature gate is enabled. (#12932)\n- `internal telemetry`: Add resource attributes from telemetry.resource to the logger (#12582)\n  Resource attributes from telemetry.resource were not added to the internal\n  console logs.\n  \n  Now, they are added to the logger as part of the \"resource\" field.\n  \n- `confighttp and configcompression`: Fix handling of `snappy` content-encoding in a backwards-compatible way (#10584, #12825)\n  The collector used the Snappy compression type of \"framed\" to handle the HTTP\n  content-encoding \"snappy\".  However, this encoding is typically used to indicate\n  the \"block\" compression variant of \"snappy\".  This change allows the collector to:\n  - When receiving a request with encoding 'snappy', the server endpoints will peek\n    at the first bytes of the payload to determine if it is \"framed\" or \"block\" snappy,\n    and will decompress accordingly.  This is a backwards-compatible change.\n  \n  If the feature-gate \"confighttp.framedSnappy\" is enabled, you'll see new behavior for both client and server:\n  - Client compression type \"snappy\" will now compress to the \"block\" variant of snappy\n    instead of \"framed\". Client compression type \"x-snappy-framed\" will now compress to the \"framed\" variant of snappy.\n  - Servers will accept both \"snappy\" and \"x-snappy-framed\" as valid content-encodings.\n  \n- `tlsconfig`: Disable TPM tests on MacOS/Darwin (#12964)\n\n<!-- previous-version -->\n\n## v1.31.0/v0.125.0\n\n### 🛑 Breaking changes 🛑\n\n- `service`: Lowercase values for 'otelcol.component.kind' attributes. (#12865)\n- `service`: Restrict the `telemetry.newPipelineTelemetry` feature gate to metrics. (#12856, #12933)\n  The \"off\" state of this feature gate introduced a regression, where the Collector's internal logs were missing component attributes. See issue #12870 for more details on this bug.\n  \n  On the other hand, the \"on\" state introduced an issue with the Collector's default internal metrics, because the Prometheus exporter does not currently support instrumentation scope attributes.\n  \n  To solve both of these issues, this change turns on the new scope attributes for logs and traces by default regardless of the feature gate.\n  However, the new scope attributes for metrics stay locked behind the feature gate, and will remain off by default until the Prometheus exporter is updated to support scope attributes.\n  \n  Please understand that enabling the `telemetry.newPipelineTelemetry` feature gate may break the export of Collector metrics through, depending on your configuration.\n  Having a `batch` processor in multiple pipelines is a known trigger for this.\n  \n  This comes with a breaking change, where internal logs exported through OTLP will now use instrumentation scope attributes to identify the source component instead of log attributes.\n  This does not affect the Collector's stderr output. See the changelog for v0.123.0 for a more detailed description of the gate's effects.\n  \n\n### 💡 Enhancements 💡\n\n- `mdatagen`: Add support for attributes for telemetry configuration in metadata. (#12919)\n- `configmiddleware`: Add extensionmiddleware interface. (#12603, #9591)\n- `configgrpc`: Add gRPC middleware support. (#12603, #9591)\n- `confighttp`: Add HTTP middleware support. (#12603, #9591, #7441)\n- `configmiddleware`: Add configmiddleware struct. (#12603, #9591)\n\n### 🧰 Bug fixes 🧰\n\n- `exporterhelper`: Do not ignore the `num_consumers` setting when batching is enabled. (#12244)\n- `exporterhelper`: Reject elements larger than the queue capacity (#12847)\n- `mdatagen`: Add time and plog package imports (#12907)\n- `confmap`: Maintain nil values when marshaling or unmarshaling nil slices (#11882)\n  Previously, nil slices were converted to empty lists, which are semantically different\n  than a nil slice. This change makes this conversion more consistent when encoding\n  or decoding config, and these values are now maintained.\n  \n\n<!-- previous-version -->\n\n## v1.30.0/v0.124.0\n\n### 💡 Enhancements 💡\n\n- `exporterhelper`: Add support for bytes-based batching for profiles in the exporterhelper package. (#3262)\n- `otelcol`: Enhance config validation using <validate> command to capture all validation errors that prevents the collector from starting. (#8721)\n- `exporterhelper`: Link batcher context to all batched request's span contexts. (#12212, #8122)\n\n### 🧰 Bug fixes 🧰\n\n- `confighttp`: Ensure http authentication server failures are handled by the provided error handler (#12666)\n\n<!-- previous-version -->\n\n## v1.29.0/v0.123.0\n\n### ❗ Known Issues ❗\n\n- This version increases memory usage by ~0.5 MB per component in the pipelines because a separate Zap Core logger is \n  initialized for each component. The issue is partially fixed in v0.126.0 for users who write logs to stdout, but do\n  not export logs via OTLP. See https://github.com/open-telemetry/opentelemetry-collector/issues/13014 for more details.\n\n### 🛑 Breaking changes 🛑\n\n- `service/telemetry`: Mark `telemetry.disableAddressFieldForInternalTelemetry` as beta, usage of deprecated service::telemetry::address are ignored (#25115)\n  To restore the previous behavior disable `telemetry.disableAddressFieldForInternalTelemetry` feature gate.\n- `exporterbatch`: Remove deprecated fields `min_size_items` and `max_size_items` from batch config. (#12684)\n\n### 🚩 Deprecations 🚩\n\n- `otlpexporter`: Mark BatcherConfig as deprecated, use `sending_queue::batch` instead (#12726)\n- `exporterhelper`: Deprecate `blocking` in favor of `block_on_overflow`. (#12710)\n- `exporterhelper`: Deprecate configuring exporter batching separately. Use `sending_queue::batch` instead. (#12772)\n  Moving the batching configuration to `sending_queue::batch` requires setting `sending_queue::sizer` to `items`\n  which means that `sending_queue::queue_size` needs to be also increased by the average batch size number (roughly \n  x5000 for the default batching configuration).\n  See https://github.com/open-telemetry/opentelemetry-collector/tree/main/exporter/exporterhelper#configuration\n  \n\n### 💡 Enhancements 💡\n\n- `exporterhelper`: Add support to configure batching in the sending queue. (#12746)\n- `exporterhelper`: Add support for wait_for_result, remove disabled_queue (#12742)\n  This has a side effect for users of the experimental BatchConfig with the queue disabled, since not this is | uses only NumCPU() consumers.\n- `exporterhelper`: Allow exporter memory queue to use different type of sizers. (#12708)\n- `service`: Add \"telemetry.newPipelineTelemetry\" feature gate to inject component-identifying attributes in internal telemetry (#12217)\n  With the feature gate enabled, all internal telemetry (metrics/traces/logs) will include some of\n  the following instrumentation scope attributes:\n  - `otelcol.component.kind`\n  - `otelcol.component.id`\n  - `otelcol.pipeline.id`\n  - `otelcol.signal`\n  - `otelcol.signal.output`\n  \n  These attributes are defined in the [Pipeline Component Telemetry RFC](https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/rfcs/component-universal-telemetry.md#attributes),\n  and identify the component instance from which the telemetry originates.\n  They are added automatically without changes to component code.\n  \n  These attributes were already included in internal logs as regular log attributes, starting from\n  v0.120.0. For consistency with other signals, they have been switched to scope attributes (with\n  the exception of logs emitted to standard output), and are now enabled by the feature gate.\n  \n  Please make sure that the exporter / backend endpoint you use has support for instrumentation\n  scope attributes before using this feature. If the internal telemetry is exported to another\n  Collector, a transform processor could be used to turn them into other kinds of attributes if\n  necessary.\n  \n- `exporterhelper`: Enable support to do batching using `bytes` sizer (#12751)\n- `service`: Add config key to set metric views used for internal telemetry (#10769)\n  The `service::telemetry::metrics::views` config key can now be used to explicitly set the list of\n  metric views used for internal telemetry, mirroring `meter_provider::views` in the SDK config.\n  This can be used to disable specific internal metrics, among other uses.\n  \n  This key will cause an error if used alongside other features which would normally implicitly create views, such as:\n  - not setting `service::telemetry::metrics::level` to `detailed`;\n  - enabling the `telemetry.disableHighCardinalityMetrics` feature flag.\n  \n\n### 🧰 Bug fixes 🧰\n\n- `exporterhelper`: Fix order of starting between queue and batch. (#12705)\n\n<!-- previous-version -->\n\n## v1.28.1/v0.122.1\n\n### 🧰 Bug fixes 🧰\n\n- `confmap`: Ensure slices with defaults containing struct values are correctly set. (#12661)\n  This reverts the changes made in https://github.com/open-telemetry/opentelemetry-collector/pull/11882.\n\n<!-- previous-version -->\n\n## v1.28.0/v0.122.0\n\n### 🛑 Breaking changes 🛑\n\n- `service`: Batch processor telemetry is no longer emitted at \"basic\" verbosity level (#7890)\n  According to the guidelines, basic-level telemetry should be reserved for core Collector APIs.\n  Components such as the batch processor should emit telemetry starting from the \"normal\" level\n  (which is also the default level).\n  \n  Migration: If your Collector telemetry was set to `level: basic` and you want to keep seeing\n  batch processor-related metrics, consider switching to `level: normal` instead.\n  \n\n### 💡 Enhancements 💡\n\n- `service`: Add `service.AllowNoPipelines` feature gate to allow starting the Collector without pipelines. (#12613)\n  This can be used to start with only extensions.\n- `mdatagen`: Delete generated_status.go if the component type doesn't require it. (#12346)\n- `componenttest`: Improve config struct mapstructure field tag checks (#12590)\n  `remain` tags and `omitempty` tags without a custom field name will now pass validation.\n- `service`: include component id/type in start error (#10426)\n- `mdatagen`: Add deprecation date and migration guide fields as part of component metadata (#12359)\n- `confmap`: Introduce a new feature flag to allow for merging lists instead of discarding the existing ones. (#8394, #8754, #10370)\n  You can enable this option via the command line by running following command:\n  otelcol --config=main.yaml --config=extra_config.yaml --feature-gates=-confmap.enableMergeAppendOption\n  \n- `zpagesextension`: Add expvar handler to zpages extension. (#11081)\n\n### 🧰 Bug fixes 🧰\n\n- `confmap`: Maintain nil values when marshaling or unmarshaling nil slices (#11882)\n  Previously, nil slices were converted to empty lists, which are semantically different\n  than a nil slice. This change makes this conversion more consistent when encoding\n  or decoding config, and these values are now maintained.\n  \n- `service`: do not attempt to register process metrics if they are disabled (#12098)\n\n<!-- previous-version -->\n\n## v1.27.0/v0.121.0\n\n### 🛑 Breaking changes 🛑\n\n- `confighttp`: Make the client config options `max_idle_conns`, `max_idle_conns_per_host`, `max_conns_per_host`, and `idle_conn_timeout` integers (#9478)\n  All four options can be set to `0` where they were previously set to `null`\n\n### 🚩 Deprecations 🚩\n\n- `exporterhelper`: Deprecate `min_size_items` and `max_size_items` in favor of `min_size` and `max_size`. (#12486)\n\n### 💡 Enhancements 💡\n\n- `mdatagen`: Add `converter` and `provider` module classes (#12467)\n- `pipeline`: output pipeline name with signal as signal[/name] format in logs. (#12410)\n- `memorylimiter`: Add support to configure min GC intervals for soft and hard limits. (#12450)\n- `otlpexporter`: Update the stability level for logs, it has been as stable as traces and metrics for some time. (#12423)\n- `service`: Create a new subcommand to dump the initial configuration after resolving/merging. (#11479)\n  To use the `print-initial-config` subcommand, invoke the Collector with the subcommand and corresponding feature gate: `otelcol print-initial-config --feature-gates=otelcol.printInitialConfig --config=config.yaml`.\n  Note that the feature gate enabling this flag is currently in alpha stability, and the subcommand may\n  be changed in the future.\n  \n- `memorylimiterprocessor`: Add support for profiles. (#12453)\n- `otelcol`: Converters are now available in the `components` command. (#11900, #12385)\n- `component`: Mark module as stable (#9376)\n- `confmap`: Surface YAML parsing errors when they happen at the top-level. (#12180)\n  This adds context to some instances of the error \"retrieved value (type=string) cannot be used as a Conf\", which typically happens because of invalid YAML documents\n  \n- `pprofile`: Add LinkIndex attribute to the generated Sample type (#12485)\n- `exporterhelper`: Stabilize exporter.UsePullingBasedExporterQueueBatcher and remove old batch sender (#12425)\n- `mdatagen`: Update metadata schema with new fields without enforcing them (#12359)\n\n### 🧰 Bug fixes 🧰\n\n- `service`: Fix crash at startup when converting from v0.2.0 to v0.3.0 (#12438)\n- `service`: fix bug in parsing service::telemetry configuration (#12437)\n- `exporterhelper`: Fix bug where the error logged when conversion of data fails is always nil (#12510)\n- `mdatagen`: Adds back missing import for filter when emitting resource attributes (#12455)\n\n## v1.26.0/v0.120.0\n\n### 🛑 Breaking changes 🛑\n\n- `all`: Added support for go1.24, bumped minimum version to 1.23 (#12370)\n- `mdatagen`: Removing deprecated generated funcs and a few test funcs as well. (#12304)\n- `service`: Align component logger attributes with those defined in RFC (#12217)\n  See [Pipeline Component Telemetry RFC](https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/rfcs/component-universal-telemetry.md#attributes)\n  \n\n### 💡 Enhancements 💡\n\n- `otlpreceiver`: Update stability for logs (#12335)\n- `exporterhelper`: Implement sync disabled queue used when batching is enabled. (#12245)\n- `exporterhelper`: Enable the new pull-based batcher in exporterhelper (#12291)\n- `exporterhelper`: Update queue size after the element is done exported (#12399)\n  After this change the active queue size will include elements in the process of being exported.\n- `otelcol`: Add featuregate command to display information about available features (#11998)\n  The featuregate command allows users to view detailed information about feature gates\n  including their status, stage, and description.\n  \n\n### 🧰 Bug fixes 🧰\n\n- `memorylimiter`: Logger no longer attributes to single signal, pipeline, or component. (#12217)\n- `otlpreceiver`: Logger no longer attributes to random signal when receiving multiple signals. (#12217)\n- `exporterhelper`: Fix undefined behavior access to request after send to next component. This causes random memory access. (#12281)\n- `exporterhelper`: Fix default batcher to correctly call all done callbacks exactly once (#12247)\n- `otlpreceiver`: Fix OTLP http receiver to correctly set Retry-After (#12367)\n- `otlphttpexporter`: Fix parsing logic for Retry-After in OTLP http protocol. (#12366)\n  The value of Retry-After field can be either an HTTP-date or delay-seconds and the current logic only parsed delay-seconds.\n- `cmd/builder`: Ensure unique aliases for modules with same suffix (#12201)\n\n## v1.25.0/v0.119.0\n\n### 🛑 Breaking changes 🛑\n\n- `exporterhelper`: Rename exporter span signal specific attributes (e.g. \"sent_spans\" / \"send_failed_span\") to \"items.sent\" / \"items.failed\". (#12165)\n- `cmd/mdatagen`: Remove dead field `telemetry::level` (#12144)\n- `exporterhelper`: Change exporter ID to be a Span level attribute instead on each event. (#12164)\n  This does not have an impact on the level of information emitted, but on the structure of the Span.\n- `cmd/mdatagen`: Remove `level` field from metrics definition (#12145)\n  This mechanism will be added back once a new views mechanism is implemented.\n- `service`: Value for telemetry exporter `otlp.protocol` updated from `grpc/protobuf` to `grpc`. (#12337)\n- `service`: internal metrics exported over Prometheus may differ from previous versions. (#11611)\n\n  Users who do not customize the Prometheus reader should not be impacted. The change to update the internal telemetry to use [otel-go config](https://pkg.go.dev/go.opentelemetry.io/contrib/config) can cause unexpected behaviour\n  for end users. This change is caused by the default values in `config` being different from what the Collector has used in previous versions. The\n  following changes can occur when users configure their `service::telemetry::metrics::readers`:\n  - the metric name will append a `_total` suffix if `without_type_suffix` is not configured. Set `without_type_suffix` to `true` to disable this.\n  - units will be appended to metric name if `without_units` is not configured. Set `without_units` to `true` to disable this.\n  - a `target_info` metric will be emitted if `without_scope_info` is not configured. Set `without_scope_info` to `true` to disable this.\n\n### 💡 Enhancements 💡\n\n- `configtls`: Allow users to mention their preferred curve types for ECDHE handshake (#12174)\n- `service`: remove custom code and instead use config package to instantiate meter provider. (#11611)\n- `otelcol`: Adds support for listing config providers in components command's output (#11570)\n- `general`: Reduce memory allocations when loading configuration and parsing component names (#11964)\n\n### 🧰 Bug fixes 🧰\n\n- `exporterhelper`: Fix bug that the exporter with new batcher may have been marked as non mutation. (#12239)\n  Only affects users that manually turned on `exporter.UsePullingBasedExporterQueueBatcher` featuregate.\n- `service`: Preserve URL normalization logic that was present before. (#12254)\n- `confighttp`: confighttp.ToServer now sets ErrorLog with a default logger backed by Zap (#11820)\n  \n  This change ensures that the http.Server's ErrorLog is correctly set using Zap's logger at the error level, addressing the issue of error logs being printed using a different logger.\n  \n- `exporterhelper`: Fix context propagation for DisabledBatcher (#12231)\n- `mdatagen`: apply fieldalignment to generated code (#12125)\n- `mdatagen`: Fix bug where Histograms were marked as not supporting temporal aggregation (#12168)\n- `exporterhelper`: Fix MergeSplit issue that ignores the initial message size. (#12257)\n- `service`: Include validation errors from telemetry.Config when validating the service config (#12100)\n  Previously validation errors were only printed to the console\n- `service-telemetry`: pass the missing async error channel into service telemetry settings (#11417)\n\n## v1.24.0/v0.118.0\n\n### 💡 Enhancements 💡\n\n- `exporterhelper`: Add blocking option to control queue behavior when full (#12090)\n- `debugexporter`: Add EventName to debug exporter for Logs. EventName was added as top-level field in the LogRecord from 1.5.0 of proto definition. (#11966)\n- `confighttp`: Added support for configuring compression levels. (#10467)\n  A new configuration option called CompressionParams has been added to confighttp. | This allows users to configure the compression levels for the confighttp client.\n- `exporterhelper`: Change the memory queue implementation to not pre-allocate capacity objects. (#12070)\n  This change improves memory usage of the collector under low utilization and is a prerequisite for supporting different other size limitations (number of items, bytes).\n\n### 🧰 Bug fixes 🧰\n\n- `mdatagen`: apply fieldalignment to generated code (#12121)\n- `otelcoltest`: Set `DefaultScheme` to `env` in the test `ConfigProvider` to replicate the default provider used by the Collector. (#12066)\n\n## v1.23.0/v0.117.0\n\n### 🛑 Breaking changes 🛑\n\n- `otelcol`: Remove warnings when 0.0.0.0 is used (#11713, #8510)\n\n### 🧰 Bug fixes 🧰\n\n- `internal/sharedcomponent`: Fixed bug where sharedcomponent would use too much memory remembering all the previously reported statuses (#11826)\n\n## v1.22.0/v0.116.0\n\n### 🛑 Breaking changes 🛑\n\n- `pdata/pprofile`: Remove deprecated `Profile.EndTime` and `Profile.SetEndTime` methods. (#11796)\n\n### 💡 Enhancements 💡\n\n- `xconfighttp`: Add WithOtelHTTPOptions to experimental module xconfighttp (#11770)\n\n### 🧰 Bug fixes 🧰\n\n- `exporterhelper`: Fix memory leak at exporter shutdown (#11401)\n- `sharedcomponent`: Remove race-condition and cleanup locking (#11819)\n\n## v1.21.0/v0.115.0\n\n### 🛑 Breaking changes 🛑\n\n- `otelcol`: Change all logged timestamps to ISO8601. (#10543)\n  This makes log timestamps human-readable (as opposed to epoch seconds in\n  scientific notation), but may break users trying to parse logged lines in the\n  old format.\n- `pdata/pprofile`: Upgrade pdata to opentelemetry-proto v1.4.0 (#11722)\n\n### 🚩 Deprecations 🚩\n\n- `scraperhelper`: Deprecate all Scraper helpers in scraperhelper (#11732)\n  Deprecate ScrapeFunc, ScraperOption, WithStart, WithShutdown in favor of equivalent funcs in scraper package.\n\n### 💡 Enhancements 💡\n\n- `exporterqueue`: Introduce a feature gate exporter.UsePullingBasedExporterQueueBatcher to use the new pulling model in exporter queue batching. (#8122, #10368)\n  If both queuing and batching is enabled for exporter, we now use a pulling model instead of a\n  pushing model. num_consumer in queue configuration is now used to specify the maximum number of\n  concurrent workers that are sending out the request. \n  \n- `service`: label metrics as alpha to communicate their stability (#11729)\n- `consumer`: Mark consumer as stable. (#9046)\n- `service`: Add support for ca certificates in telemetry metrics otlp grpc exporter (#11633)\n  Before this change the Certificate value in config was silently ignored.\n\n### 🧰 Bug fixes 🧰\n\n- `service`: ensure OTLP emitted logs respect severity (#11718)\n- `featuregate`: Fix an unfriendly display message `runtime error` when featuregate is used to display command line usage. (#11651)\n- `profiles`: Fix iteration over scope profiles while counting the samples. (#11688)\n\n## v1.20.0/v0.114.0\n\n### 💡 Enhancements 💡\n\n- `cmd/builder`: Allow for replacing of local Providers and Converters when building custom collector with ocb. (#11649)\n  Use the property `path` under `gomod` to replace an go module with a local folder in\n  builder-config.yaml. Ex:\n  ```\n  providers:\n    - gomod: module.url/my/custom/provider v1.2.3\n      path: /path/to/local/provider\n  ```\n  \n- `cmd/builder`: Allow configuring `confmap.Converter` components in ocb. (#11582)\n  If no converters are specified, there will be no converters added.\n  Currently, the only published converter is `expandconverter` which is \n  deprecated as of v0.107.0, but can still be added for testing purposes.\n  \n  To configure a custom converter, make sure your converter implements the converter\n  interface and is published as a go module (or replaced locally if not published).\n  You may then use the `converters` key in your OCB build manifest with a list of\n  Go modules (and replaces as necessary) to include your converter.\n  \n  Please note that converters are order-dependent. The confmap will apply converters\n  in order of which they are listed in your manifest if there is more than one.\n  \n- `all`: shorten time period before removing an unmaintained component from 6 months to 3 months (#11664)\n\n### 🧰 Bug fixes 🧰\n\n- `all`: Updates dialer timeout section documentation in confignet README (#11685)\n- `scraperhelper`: If the scraper shuts down, do not scrape first. (#11632)\n  When the scraper is shutting down, it currently will scrape at least once.\n  With this change, upon receiving a shutdown order, the receiver's scraperhelper will exit immediately.\n  \n\n## v1.19.0/v0.113.0\n\n### 🛑 Breaking changes 🛑\n\n- `internal/fanoutconsumer`: Extract internal/fanoutconsumer as a separate go module (#11441)\n- `builder`: Remove builder support to build old version, and the otelcol_version config (#11405)\n  User should remove this property from their config, to build older versions use older builders.\n- `receiver`: Make receivertest into its own module (#11462)\n- `builder`: Remove deprecated flags from Builder (#11576)\n  Here is the list of flags | --name, --description, --version, --otelcol-version, --go, --module\n- `internal/sharedcomponent`: Extract internal/sharedcomponent as a separate go module (#11442)\n\n### 💡 Enhancements 💡\n\n- `mdatagen`: Add otlp as supported distribution (#11527)\n- `batchprocessor`: Move single shard batcher creation to the constructor (#11594)\n- `service`: add support for using the otelzap bridge and emit logs using the OTel Go SDK (#10544)\n\n### 🧰 Bug fixes 🧰\n\n- `service`: ensure traces and logs emitted by the otel go SDK use the same resource information (#11578)\n- `config/configgrpc`: Patch for bug in the grpc-go NewClient that makes the way the hostname is resolved incompatible with the way proxy setting are applied. (#11537)\n- `builder`: Update builder default providers to latest stable releases (#11566)\n\n## v1.18.0/v0.112.0\n\n### 🛑 Breaking changes 🛑\n\n- `consumer/consumererror`: Extract consumer/consumererror as a separate go module (#11440)\n- `exporter/exportertest`: Put exportertest into its own module (#11461)\n- `service`: Remove stable gate component.UseLocalHostAsDefaultHost (#11412)\n\n### 🚩 Deprecations 🚩\n\n- `processortest`: Deprecated 'NewUnhealthyProcessorCreateSettings'. Use NewNopSettings instead. (#11307)\n\n### 💡 Enhancements 💡\n\n- `mdatagen`: Added generated_package_name config field to support custom generated package name. (#11231)\n- `mdatagen`: Generate documentation for components with resource attributes only (#10705)\n- `confighttp`: Adding support for lz4 compression into the project (#9128)\n- `service`: Hide profiles support behind a feature gate while it remains alpha. (#11477)\n- `exporterhelper`: Retry sender will fail fast when the context timeout is shorter than the next retry interval. (#11183)\n\n### 🧰 Bug fixes 🧰\n\n- `cmd/builder`: Fix default configuration for builder for httpprovider, httpsprovider, and yamlprovider. (#11357)\n- `processorhelper`: Fix issue where in/out parameters were not recorded when error was returned from consumer. (#11351)\n\n## v1.17.0/v0.111.0\n\n### 🛑 Breaking changes 🛑\n\n- `service/telemetry`: Change default metrics address to \"localhost:8888\" instead of \":8888\" (#11251)\n  This behavior can be disabled by disabling the feature gate 'telemetry.UseLocalHostAsDefaultMetricsAddress'.\n- `loggingexporter`: Removed the deprecated logging exporter.  Use the debug exporter instead. (#11037)\n\n### 🚩 Deprecations 🚩\n\n- `service/telemetry`: Deprecate service::telemetry::metrics::address in favor of service::telemetry::metrics::readers. (#11205)\n- `processorhelper`: Deprecate BuildProcessorMetricName as it's no longer needed since introduction of mdatagen (#11302)\n\n### 💡 Enhancements 💡\n\n- `ocb`: create docker images for OCB, per https://github.com/open-telemetry/opentelemetry-collector-releases/pull/671 (#5712)\n  Adds standard Docker images for OCB to Dockerhub and GitHub, see hub.docker.com/r/otel/opentelemetry-collector-builder\n- `confighttp`: Snappy compression to lazy read for memory efficiency (#11177)\n- `httpsprovider`: Mark the httpsprovider as stable. (#11191)\n- `httpprovider`: Mark the httpprovider as stable. (#11191)\n- `yamlprovider`: Mark the yamlprovider as stable. (#11192)\n- `confmap`: Allow using any YAML structure as a string when loading configuration including time.Time formats (#10659)\n  Previously, fields with time.Time formats could not be used as strings in configurations\n  \n\n### 🧰 Bug fixes 🧰\n\n- `processorhelper`: Fix data race condition, concurrent writes to the err variable, causes UB (Undefined Behavior) (#11350)\n- `cmd/builder`: re-adds function to properly set and view version number of OpenTelemetry Collector Builder (ocb) binaries (#11208)\n- `pdata`: Unmarshal Span and SpanLink flags from JSON (#11267)\n\n## v1.16.0/v0.110.0\n\n### 🛑 Breaking changes 🛑\n\n- `processorhelper`: Update incoming/outgoing metrics to a single metric with a `otel.signal` attributes. (#11144)\n  The following metrics were added in the previous version\n  - otelcol_processor_incoming_spans\n  - otelcol_processor_outgoing_spans\n  - otelcol_processor_incoming_metric_points\n  - otelcol_processor_outgoing_metric_points\n  - otelcol_processor_incoming_log_records\n  - otelcol_processor_outgoing_log_records\n  \n  They are being replaced with the following to more closely align with OTEP 259:\n  - otelcol_processor_incoming_items\n  - otelcol_processor_outgoing_items\n  \n- `processorhelper`: Remove deprecated `[Traces|Metrics|Logs]`Inserted funcs (#11151)\n- `config`: Mark UseLocalHostAsDefaultHostfeatureGate as stable (#11235)\n\n### 🚩 Deprecations 🚩\n\n- `processorhelper`: deprecate accepted/refused/dropped metrics (#11201)\n  The following metrics are being deprecated as they were only used in a single\n  processor:\n    - `otelcol_processor_accepted_log_records`\n    - `otelcol_processor_accepted_metric_points`\n    - `otelcol_processor_accepted_spans`\n    - `otelcol_processor_dropped_log_records`\n    - `otelcol_processor_dropped_metric_points`\n    - `otelcol_processor_dropped_spans`\n    - `otelcol_processor_refused_log_records`\n    - `otelcol_processor_refused_metric_points`\n    - `otelcol_processor_refused_spans`\n  \n\n### 💡 Enhancements 💡\n\n- `pdata`: Add support to MoveTo for Map, allow avoiding copies (#11175)\n- `mdatagen`: Add stability field to telemetry metrics, allowing the generated description to include a stability string. (#11160)\n- `confignet`: Mark module as Stable. (#9801)\n- `confmap/provider/envprovider`: Support default values when env var is empty (#5228)\n- `mdatagen`: mdatagen `validateMetrics()` support validate metrics in `telemetry.metric` (#10925)\n- `service/telemetry`: Mark useOtelWithSDKConfigurationForInternalTelemetry as stable (#7532)\n- `mdatagen`: Use cobra for the command, add version flag (#11196)\n\n### 🧰 Bug fixes 🧰\n\n- `service`: Ensure process telemetry is registered when internal telemetry is configured with readers instead of an address. (#11093)\n- `mdatagen`: Fix incorrect generation of metric tests with boolean attributes. (#11169)\n- `otelcol`: Fix the Windows Event Log configuration when running the Collector as a Windows service. (#5297, #11051)\n- `builder`: Honor build_tags in config (#11156)\n- `builder`: Fix version for providers in the default config (#11123)\n- `cmd/builder`: Temporarily disable strict versioning checks (#11129, #11152)\n  The strict versioning check may be enabled by default in a future version once all configuration providers are stabilized.\n  \n- `confmap`: Fix loading config of a component from a different source. (#11154)\n  This issue only affected loading the whole component config, loading parts of a component config from a different source was working correctly.\n  \n\n## v1.15.0/v0.109.0\n\n### 🛑 Breaking changes 🛑\n\n- `scraperhelper`: Remove deprecated `ObsReport`, `ObsReportSettings`, `NewObsReport` types/funcs (#11086)\n- `confmap`: Remove stable `confmap.strictlyTypedInput` gate (#11008)\n- `confmap`: Removes stable `confmap.unifyEnvVarExpansion` feature gate. (#11007)\n- `ballastextension`: Removes the deprecated ballastextension (#10671)\n- `service`: Removes stable `service.disableOpenCensusBridge` feature gate (#11009)\n\n### 🚩 Deprecations 🚩\n\n- `processorhelper`: These funcs are not used anywhere, marking them deprecated. (#11083)\n\n### 🚀 New components 🚀\n\n- `extension/experimental/storage`: Move `extension/experimental/storage` into a separate module (#11022)\n\n### 💡 Enhancements 💡\n\n- `configtelemetry`: Add guidelines for each level of component telemetry (#10286)\n- `service`: move `useOtelWithSDKConfigurationForInternalTelemetry` gate to beta (#11091)\n- `service`: implement a no-op tracer provider that doesn't propagate the context (#11026)\n  The no-op tracer provider supported by the SDK incurs a memory cost of propagating the context no matter\n  what. This is not needed if tracing is not enabled in the Collector. This implementation of the no-op tracer\n  provider removes the need to allocate memory when tracing is disabled.\n  \n- `envprovider`: Mark module as stable (#10982)\n- `fileprovider`: Mark module as stable (#10983)\n- `processor`: Add incoming and outgoing counts for processors using processorhelper. (#10910)\n  Any processor using the processorhelper package (this is most processors) will automatically report\n  incoming and outgoing item counts. The new metrics are:\n  - otelcol_processor_incoming_spans\n  - otelcol_processor_outgoing_spans\n  - otelcol_processor_incoming_metric_points\n  - otelcol_processor_outgoing_metric_points\n  - otelcol_processor_incoming_log_records\n  - otelcol_processor_outgoing_log_records\n  \n\n### 🧰 Bug fixes 🧰\n\n- `configgrpc`: Change the value of max_recv_msg_size_mib from uint64 to int to avoid a case where misconfiguration caused an integer overflow. (#10948)\n- `exporterqueue`: Fix a bug in persistent queue that Offer can becomes deadlocked when queue is almost full (#11015)\n\n## v1.14.1/v0.108.1\n\n### 🧰 Bug fixes 🧰\n\n- `mdatagen`: Fix a missing import in the generated test file (#10969)\n\n## v1.14.0/v0.108.0\n\n### 🛑 Breaking changes 🛑\n\n- `all`: Added support for go1.23, bumped the minimum version to 1.22 (#10869)\n- `otelcol`: Remove deprecated `ConfmapProvider` interface. (#10934)\n- `confmap`: Mark `confmap.strictlyTypedInput` as stable (#10552)\n\n### 💡 Enhancements 💡\n\n- `exporter/otlp`: Add batching option to otlp exporter (#8122)\n- `builder`: Add a --skip-new-go-module flag to skip creating a module in the output directory. (#9252)\n- `component`: Add `TelemetrySettings.LeveledMeterProvider` func to replace MetricsLevel in the near future (#10931)\n- `mdatagen`: Add `LeveledMeter` method to mdatagen (#10933)\n- `service`: Adds `level` configuration option to `service::telemetry::trace` to allow users to disable the default TracerProvider (#10892)\n  This replaces the feature gate `service.noopTracerProvider` introduced in v0.107.0\n- `componentstatus`: Add new Reporter interface to define how to report a status via a `component.Host` implementation (#10852)\n- `mdatagen`: support using a different github project in mdatagen README issues list (#10484)\n- `mdatagen`: Updates mdatagen's usage to output a complete command line example, including the metadata.yaml file. (#10886)\n- `extension`: Add ModuleInfo to extension.Settings to allow extensions to access component go module information. (#10876)\n- `confmap`: Mark module as stable (#9379)\n\n### 🧰 Bug fixes 🧰\n\n- `batchprocessor`: Update units for internal telemetry (#10652)\n- `confmap`: Fix bug where an unset env var used with a non-string field resulted in a panic (#10950)\n- `service`: Fix memory leaks during service package shutdown (#9165)\n- `mdatagen`: Update generated telemetry template to only include context import when there are async metrics. (#10883)\n- `mdatagen`: Fixed bug in which setting `SkipLifecycle` & `SkipShutdown` to true would result in a generated file with an unused import `confmaptest` (#10866)\n- `confmap`: Use string representation for field types where all primitive types are strings. (#10937)\n- `otelcol`: Preserve internal representation when unmarshaling component configs (#10552)\n\n## v1.13.0/v0.107.0\n\n### 🛑 Breaking changes 🛑\n\n- `service`: Remove OpenCensus bridge completely, mark feature gate as stable. (#10414)\n- `confmap`: Set the `confmap.unifyEnvVarExpansion` feature gate to Stable. Expansion of `$FOO` env vars is no longer supported.  Use `${FOO}` or `${env:FOO}` instead. (#10508)\n- `service`: Remove `otelcol` from Prometheus configuration. This means that any metric that isn't explicitly prefixed with `otelcol_` no longer have that prefix. (#9759)\n\n### 💡 Enhancements 💡\n\n- `mdatagen`: export ScopeName in internal/metadata package (#10845)\n  This can be used by components that need to set their scope name manually. Will save component owners from having to store a variable, which may diverge from the scope name used by the component for emitting its own telemetry.\n- `semconv`: Add v1.26.0 semantic conventions package (#10249, #10829)\n- `mdatagen`: Expose a setting on tests::host to set up your own host initialization code (#10765)\n  Some receivers require a host that has additional capabilities such as exposing exporters.\n  For those, we can expose a setting that allows them to place a different host in the generated code.\n  \n- `confmap`: Allow using any YAML structure as a string when loading configuration. (#10800)\n  Previous to this change, slices could not be used as strings in configuration.\n  \n- `ocb`: migrate build and release of ocb binaries to opentelemetry-collector-releases repository (#10710)\n  ocb binaries will now be released under open-telemetry/opentelemetry-collector-releases tagged as \"cmd/builder/vX.XXX.X\"\n- `semconv`: Add semantic conventions version v1.27.0 (#10837)\n- `client`: Mark module as stable. (#10775)\n\n### 🧰 Bug fixes 🧰\n\n- `configtelemetry`: Add 10s read header timeout on the configtelemetry Prometheus HTTP server. (#5699)\n- `service`: Allow users to disable the tracer provider via the feature gate `service.noopTracerProvider` (#10858)\n  The service is returning an instance of a SDK tracer provider regardless of whether there were any processors configured causing resources to be consumed unnecessarily.\n- `processorhelper`: Fix processor metrics not being reported initially with 0 values. (#10855)\n- `service`: Implement the `temporality_preference` setting for internal telemetry exported via OTLP (#10745)\n- `configauth`: Fix unmarshaling of authentication in HTTP servers. (#10750)\n- `confmap`: If loading an invalid YAML string through a provider, use it verbatim instead of erroring out. (#10759)\n  This makes the ${env:ENV} syntax closer to how ${ENV} worked before unifying syntaxes.\n  \n- `component`: Allow component names of up to 1024 characters in length. (#10816)\n- `confmap`: Remove original string representation if invalid. (#10787)\n\n## v0.106.1\n\n### 🧰 Bug fixes 🧰\n\n- `configauth`: Fix unmarshaling of authentication in HTTP servers. (#10750)\n\n## v0.106.0\n\n### 🛑 Breaking changes 🛑\n\n- `service`: Update all metrics to include `otelcol_` prefix to ensure consistency across OTLP and Prometheus metrics (#9759)\n  This change is marked as a breaking change as anyone that was using OTLP for metrics will\n  see the new prefix which was not present before. Prometheus generated metrics remain\n  unchanged.\n  \n- `confighttp`: Delete `ClientConfig.CustomRoundTripper` (#8627)\n  Set (*http.Client).Transport on the *http.Client returned from ToClient to configure this.\n- `confmap`: When passing configuration for a string field using any provider, use the verbatim string representation as the value. (#10605, #10405)\n  This matches the behavior of `${ENV}` syntax prior to the promotion of the `confmap.unifyEnvVarExpansion` feature gate\n  to beta. It changes the behavior of the `${env:ENV}` syntax with escaped strings.\n  \n- `component`: Adds restrictions on the character set for component.ID name. (#10673)\n- `processor/memorylimiter`: The memory limiter processor will no longer account for ballast size. (#10696)\n  If you are already using GOMEMLIMIT instead of the ballast extension this does not affect you.\n- `extension/memorylimiter`: The memory limiter extension will no longer account for ballast size. (#10696)\n  If you are already using GOMEMLIMIT instead of the ballast extension this does not affect you.\n- `service`: The service will no longer be able to get a ballast size from the deprecated ballast extension. (#10696)\n  If you are already using GOMEMLIMIT instead of the ballast extension this does not affect you.\n\n### 🚀 New components 🚀\n\n- `client`: Create a new go module `go.opentelemetry.io/collector/client` (#9804)\n  This module contains generic representations of clients connecting to different receivers.\n\n### 💡 Enhancements 💡\n\n- `exporterhelper`: Add data_type attribute to `otelcol_exporter_queue_size` metric to report the type of data being processed. (#9943)\n- `confighttp`: Add option to include query params in auth context (#4806)\n- `configgrpc`: gRPC auth errors now return gRPC status code UNAUTHENTICATED (16) (#7646)\n- `httpprovider, httpsprovider`: Validate URIs in HTTP and HTTPS providers before fetching. (#10468)\n\n### 🧰 Bug fixes 🧰\n\n- `processorhelper`: update units for internal telemetry (#10647)\n- `confmap`: Increase the amount of recursion and URI expansions allowed in a single line (#10712)\n- `exporterhelper`: There is no guarantee that after the exporterhelper sends the plog/pmetric/ptrace data downstream that the data won't be mutated in some way. (e.g by the batch_sender) This mutation could result in the proceeding call to req.ItemsCount() to provide inaccurate information to be logged. (#10033)\n- `exporterhelper`: Update units for internal telemetry (#10648)\n- `receiverhelper`: Update units for internal telemetry (#10650)\n- `scraperhelper`: Update units for internal telemetry (#10649)\n- `service`: Use Command/Version to populate service name/version attributes (#10644)\n\n## v1.12.0/v0.105.0\n\n### 🛑 Breaking changes 🛑\n\n- `service`: add `service.disableOpenCensusBridge` feature gate which is enabled by default to remove the dependency on OpenCensus (#10414)\n- `confmap`: Promote `confmap.strictlyTypedInput` feature gate to beta. (#10552)\n  This feature gate changes the following:\n  - Configurations relying on the implicit type casting behaviors listed on [#9532](https://github.com/open-telemetry/opentelemetry-collector/issues/9532) will start to fail.\n  - Configurations using URI expansion (i.e. `field: ${env:ENV}`) for string-typed fields will use the value passed in `ENV` verbatim without intermediate type casting.\n  \n\n### 💡 Enhancements 💡\n\n- `configtls`: Mark module as stable. (#9377)\n- `confmap`: Remove extra closing parenthesis in sub-config error (#10480)\n- `configgrpc`: Update the default load balancer strategy to round_robin (#10319)\n  To restore the behavior that was previously the default, set `balancer_name` to `pick_first`.\n- `cmd/builder`: Add go module info the builder generated code. (#10570)\n- `otelcol`: Add go module to components subcommand. (#10570)\n- `confmap`: Add explanation to errors related to `confmap.strictlyTypedInput` feature gate. (#9532)\n- `confmap`: Allow using `map[string]any` values in string interpolation (#10605)\n\n### 🧰 Bug fixes 🧰\n\n- `builder`: provide context when a module in the config is missing its gomod value (#10474)\n- `confmap`: Fixes issue where confmap could not escape `$$` when `confmap.unifyEnvVarExpansion` is enabled. (#10560)\n- `mdatagen`: fix generated comp test for extensions and unused imports in templates (#10477)\n- `otlpreceiver`: Fixes a bug where the otlp receiver's http response was not properly translating grpc error codes to http status codes. (#10574)\n- `exporterhelper`: Fix incorrect deduplication of otelcol_exporter_queue_size and otelcol_exporter_queue_capacity metrics if multiple exporters are used. (#10444)\n- `service/telemetry`: Add ability to set service.name for spans emitted by the Collector (#10489)\n- `internal/localhostgate`: Correctly log info message when `component.UseLocalHostAsDefaultHost` is enabled (#8510)\n\n## v1.11.0/v0.104.0\n\nThis release includes 2 very important breaking changes.\n1. The `otlpreceiver` will now use `localhost` by default instead of `0.0.0.0`. This may break the receiver in containerized environments like Kubernetes. If you depend on `0.0.0.0` disable the `component.UseLocalHostAsDefaultHost` feature gate or explicitly set the endpoint to `0.0.0.0`.\n2. Expansion of BASH-style environment variables, such as `$FOO` will no longer be supported by default. If you depend on this syntax, disable the `confmap.unifyEnvVarExpansion` feature gate, but know that the feature will be removed in the future in favor of `${env:FOO}`.\n\n### 🛑 Breaking changes 🛑\n\n- `filter`: Remove deprecated `filter.CombinedFilter` (#10348)\n- `otelcol`: By default, `otelcol.NewCommand` and `otelcol.NewCommandMustSetProvider` will set the `DefaultScheme` to `env`. (#10435)\n- `expandconverter`: By default expandconverter will now error if it is about to expand `$FOO` syntax. Update configuration to use `${env:FOO}` instead or disable the `confmap.unifyEnvVarExpansion` feature gate. (#10435)\n- `otlpreceiver`: Switch to `localhost` as the default for all endpoints. (#8510)\n  Disable the `component.UseLocalHostAsDefaultHost` feature gate to temporarily get the previous default.\n  \n\n### 💡 Enhancements 💡\n\n- `confighttp`: Add support for cookies in HTTP clients with `cookies::enabled`. (#10175)\n  The method `confighttp.ToClient` will return a client with a `cookiejar.Jar` which will reuse cookies from server responses in subsequent requests.\n- `exporter/debug`: In `normal` verbosity, display one line of text for each telemetry record (log, data point, span) (#7806)\n- `exporter/debug`: Add option `use_internal_logger` (#10226)\n- `configretry`: Mark module as stable. (#10279)\n- `debugexporter`: Print Span.TraceState() when present. (#10421)\n  Enables viewing sampling threshold information (as by OTEP 235 samplers).\n- `processorhelper`: Add \"inserted\" metrics for processors. (#10353)\n  This includes the following metrics for processors:\n  - `processor_inserted_spans`\n  - `processor_inserted_metric_points`\n  - `processor_inserted_log_records`\n  \n\n### 🧰 Bug fixes 🧰\n\n- `otlpexporter`: Update validation to support both dns:// and dns:/// (#10449)\n- `service`: Fixed a bug that caused otel-collector to fail to start with ipv6 metrics endpoint service telemetry. (#10011)\n\n## v1.10.0/v0.103.0\n\n### 🛑 Breaking changes 🛑\n\n- `exporter/debug`: Disable sampling by default (#9921)\n  To restore the behavior that was previously the default, set `sampling_thereafter` to `500`.\n\n### 💡 Enhancements 💡\n\n- `cmd/builder`: Allow setting `otelcol.CollectorSettings.ResolverSettings.DefaultScheme` via the builder's `conf_resolver.default_uri_scheme` configuration option (#10296)\n- `mdatagen`: add support for optional internal metrics (#10316)\n- `otelcol/expandconverter`: Add `confmap.unifyEnvVarExpansion` feature gate to allow enabling Collector/Configuration SIG environment variable expansion rules. (#10391)\n  When enabled, this feature gate will:\n  - Disable expansion of BASH-style env vars (`$FOO`)\n  - `${FOO}` will be expanded as if it was `${env:FOO}\n  See https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/rfcs/env-vars.md for more details.\n  \n- `confmap`: Add `confmap.unifyEnvVarExpansion` feature gate to allow enabling Collector/Configuration SIG environment variable expansion rules. (#10259)\n  When enabled, this feature gate will:\n    - Disable expansion of BASH-style env vars (`$FOO`)\n    - `${FOO}` will be expanded as if it was `${env:FOO}\n  See https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/rfcs/env-vars.md for more details.\n  \n- `confighttp`: Allow the compression list to be overridden (#10295)\n  Allows Collector administrators to control which compression algorithms to enable for HTTP-based receivers.\n- `configgrpc`: Revert the zstd compression for gRPC to the third-party library we were using previously. (#10394)\n  We switched back to our compression logic for zstd when a CVE was found on the third-party library we were using. Now that the third-party library has been fixed, we can revert to that one. For end-users, this has no practical effect. The reproducers for the CVE were tested against this patch, confirming we are not reintroducing the bugs.\n- `confmap`: Adds alpha `confmap.strictlyTypedInput` feature gate that enables strict type checks during configuration resolution (#9532)\n  When enabled, the configuration resolution system will:\n  - Stop doing most kinds of implicit type casting when resolving configuration values\n  - Use the original string representation of configuration values if the ${} syntax is used in inline position\n  \n- `confighttp`: Use `confighttp.ServerConfig` as part of zpagesextension. See [server configuration](https://github.com/open-telemetry/opentelemetry-collector/blob/main/config/confighttp/README.md#server-configuration) options. (#9368)\n\n### 🧰 Bug fixes 🧰\n\n- `exporterhelper`: Fix potential deadlock in the batch sender (#10315)\n- `expandconverter`: Fix bug where an warning was logged incorrectly. (#10392)\n- `exporterhelper`: Fix a bug when the retry and timeout logic was not applied with enabled batching. (#10166)\n- `exporterhelper`: Fix a bug where an unstarted batch_sender exporter hangs on shutdown (#10306)\n- `exporterhelper`: Fix small batch due to unfavorable goroutine scheduling in batch sender (#9952)\n- `confmap`: Fix issue where structs with only yaml tags were not marshaled correctly. (#10282)\n\n## v0.102.1\n\n**This release addresses [GHSA-c74f-6mfw-mm4v](https://github.com/open-telemetry/opentelemetry-collector/security/advisories/GHSA-c74f-6mfw-mm4v) for `configgrpc`.**\n\n### 🧰 Bug fixes 🧰\n\n- `configrpc`: Use own compressors for zstd. Before this change, the zstd compressor we used didn't respect the max message size. This addresses [GHSA-c74f-6mfw-mm4v](https://github.com/open-telemetry/opentelemetry-collector/security/advisories/GHSA-c74f-6mfw-mm4v) for `configgrpc` (#10323)\n\n## v1.9.0/v0.102.0\n\n**This release addresses [GHSA-c74f-6mfw-mm4v](https://github.com/open-telemetry/opentelemetry-collector/security/advisories/GHSA-c74f-6mfw-mm4v) for `confighttp`.**\n\n### 🛑 Breaking changes 🛑\n\n- `envprovider`: Restricts Environment Variable names.  Environment variable names must now be ASCII only and start with a letter or an underscore, and can only contain underscores, letters, or numbers. (#9531)\n- `confighttp`: Apply MaxRequestBodySize to the result of a decompressed body. This addresses [GHSA-c74f-6mfw-mm4v](https://github.com/open-telemetry/opentelemetry-collector/security/advisories/GHSA-c74f-6mfw-mm4v) for `confighttp` (#10289)\n  When using compressed payloads, the Collector would verify only the size of the compressed payload. \n  This change applies the same restriction to the decompressed content. As a security measure, a limit of 20 MiB was added, which makes this a breaking change. \n  For most clients, this shouldn't be a problem, but if you often have payloads that decompress to more than 20 MiB, you might want to either configure your\n  client to send smaller batches (recommended), or increase the limit using the MaxRequestBodySize option.\n  \n\n### 💡 Enhancements 💡\n\n- `mdatagen`: auto-generate utilities to test component telemetry (#19783)\n- `mdatagen`: support setting an AttributeSet for async instruments (#9674)\n- `mdatagen`: support using telemetry level in telemetry builder (#10234)\n  This allows components to set the minimum level needed for them to produce telemetry. By default, this is set to configtelemetry.LevelBasic. If the telemetry level is below that minimum level, then the noop meter is used for metrics.\n- `mdatagen`: add support for bucket boundaries for histograms (#10218)\n- `releases`: add documentation in how to verify the image signatures using cosign (#9610)\n\n### 🧰 Bug fixes 🧰\n\n- `batchprocessor`: ensure attributes are set on cardinality metadata metric (#9674)\n- `batchprocessor`: Fixing processor_batch_metadata_cardinality which was broken in v0.101.0 (#10231)\n- `batchprocessor`: respect telemetry level for all metrics (#10234)\n- `exporterhelper`: Fix potential deadlocks in BatcherSender shutdown (#10255)\n\n## v1.8.0/v0.101.0\n\n### 💡 Enhancements 💡\n\n- `mdatagen`: generate documentation for internal telemetry (#10170)\n- `mdatagen`: add ability to use metadata.yaml to automatically generate instruments for components (#10054)\n  The `telemetry` section in metadata.yaml is used to generate\n  instruments for components to measure telemetry about themselves.\n  \n- `confmap`: Allow Converters to write logs during startup (#10135)\n- `otelcol`: Enable logging during configuration resolution (#10056)\n\n### 🧰 Bug fixes 🧰\n\n- `mdatagen`: Run package tests when goleak is skipped (#10125)\n\n## v1.7.0/v0.100.0\n\n### 🛑 Breaking changes 🛑\n\n- `service`: The `validate` sub-command no longer validates that each pipeline's type is the same as its component types (#10031)\n\n### 💡 Enhancements 💡\n\n- `semconv`: Add support for v1.25.0 semantic convention (#10072)\n- `builder`: remove the need to go get a module to address ambiguous import paths (#10015)\n- `pmetric`: Support parsing metric.metadata from OTLP JSON. (#10026)\n\n### 🧰 Bug fixes 🧰\n\n- `exporterhelper`: Fix enabled config option for batch sender (#10076)\n\n## v1.6.0/v0.99.0\n\n### 🛑 Breaking changes 🛑\n\n- `builder`: Add strict version checking when using the builder. Add the temporary flag `--skip-strict-versioning `for skipping this check. (#9896)\n  Strict version checking will error on major and minor version mismatches \n  between the `otelcol_version` configured and the builder version or versions \n  in the go.mod. This check can be temporarily disabled by using the `--skip-strict-versioning` \n  flag. This flag will be removed in a future minor version.\n  \n- `telemetry`: Distributed internal metrics across different levels. (#7890)\n  The internal metrics levels are updated along with reported metrics:\n  - The default level is changed from `basic` to `normal`, which can be overridden with `service::telemetry::metrics::level` configuration.\n  - Batch processor metrics are updated to be reported starting from `normal` level:\n    - `processor_batch_batch_send_size` \n    - `processor_batch_metadata_cardinality`\n    - `processor_batch_timeout_trigger_send`\n    - `processor_batch_size_trigger_send`\n  - GRPC/HTTP server and client metrics are updated to be reported starting from `detailed` level:\n    - http.client.* metrics\n    - http.server.* metrics\n    - rpc.server.* metrics\n    - rpc.client.* metrics\n  \n\n### 💡 Enhancements 💡\n\n- `confighttp`: Disable concurrency in zstd compression (#8216)\n- `cmd/builder`: Allow configuring `confmap.Provider`s in the builder. (#4759)\n  If no providers are specified, the defaults are used.\n  The default providers are: env, file, http, https, and yaml.\n  \n  To configure providers, use the `providers` key in your OCB build\n  manifest with a list of Go modules for your providers.\n  The modules will work the same as other Collector components.\n  \n- `mdatagen`: enable goleak tests by default via mdatagen (#9959)\n- `cmd/mdatagen`: support excluding some metrics based on string and regexes in resource_attributes (#9661)\n- `cmd/mdatagen`: Generate config and factory tests covering their requirements. (#9940)\n  The tests are moved from cmd/builder.\n  \n- `confmap`: Add `ProviderSettings`, `ConverterSettings`, `ProviderFactories`, and `ConverterFactories` fields to `confmap.ResolverSettings` (#9516)\n  This allows configuring providers and converters, which are instantiated by `NewResolver` using the given factories.\n\n### 🧰 Bug fixes 🧰\n\n- `exporter/otlp`: Allow DNS scheme to be used in endpoint (#4274)\n- `service`: fix record sampler configuration (#9968)\n- `service`: ensure the tracer provider is configured via go.opentelemetry.io/contrib/config (#9967)\n- `otlphttpexporter`: Fixes a bug that was preventing the otlp http exporter from propagating status. (#9892)\n- `confmap`: Fix decoding negative configuration values into uints (#9060)\n\n## v1.5.0/v0.98.0\n\n### 🛑 Breaking changes 🛑\n\n- `service`: emit internal collector metrics with _ instead of / with OTLP export (#9774)\n  This is addressing an issue w/ the names of the metrics generated by the Collector for its\n  internal metrics. Note that this change only impacts users that emit telemetry using OTLP, which\n  is currently still in experimental support. The prometheus metrics already replaced `/` with `_`\n  and they will do the same with `_`.\n  \n\n### 💡 Enhancements 💡\n\n- `mdatagen`: Adds unsupported platforms to the README header (#9794)\n- `confmap`: Clarify the use of embedded structs to make unmarshaling composable (#7101)\n- `nopexporter`: Promote the nopexporter to beta (#7316)\n- `nopreceiver`: Promote the nopreceiver to beta (#7316)\n- `otlpexporter`: Checks for port in the config validation for the otlpexporter (#9505)\n- `service`: Validate pipeline type against component types (#8007)\n\n### 🧰 Bug fixes 🧰\n\n- `configtls`: Fix issue where `IncludeSystemCACertsPool` was not consistently used between `ServerConfig` and `ClientConfig`. (#9835)\n- `component`: Fix issue where the `components` command wasn't properly printing the component type. (#9856)\n- `otelcol`: Fix issue where the `validate` command wasn't properly printing valid component type. (#9866)\n- `receiver/otlp`: Fix bug where the otlp receiver did not properly respond with a retryable error code when possible for http (#9357)\n\n## v1.4.0/v0.97.0\n\n### 🛑 Breaking changes 🛑\n\n- `telemetry`: Remove telemetry.useOtelForInternalMetrics stable feature gate (#9752)\n\n### 🚀 New components 🚀\n\n- `exporter/nop`: Add the `nopexporter` to serve as a placeholder exporter in a pipeline (#7316)\n  This is primarily useful for starting the Collector with only extensions enabled\n  or to test Collector pipeline throughput.\n  \n- `receiver/nop`: Add the `nopreceiver` to serve as a placeholder receiver in a pipeline (#7316)\n  This is primarily useful for starting the Collector with only extensions enabled.\n\n### 💡 Enhancements 💡\n\n- `configtls`: Validates TLS min_version and max_version (#9475)\n  Introduces `Validate()` method in TLSSetting.\n- `configcompression`: Mark module as Stable. (#9571)\n- `cmd/mdatagen`: Use go package name for the scope name by default and add an option to provide the scope name in metadata.yaml. (#9693)\n- `cmd/mdatagen`: Generate the lifecycle tests for components by default. (#9683)\n  It's encouraged to have lifecycle tests for all components enabled, but they can be disabled if needed \n  in metadata.yaml with `skip_lifecycle: true` and `skip_shutdown: true` under `tests` section.\n  \n- `cmd/mdatagen`: optimize the mdatagen for the case like batchprocessor which use a common struct to implement consumer.Traces, consumer.Metrics, consumer.Logs in the meantime. (#9688)\n\n### 🧰 Bug fixes 🧰\n\n- `exporterhelper`: Fix persistent queue size backup on reads. (#9740)\n- `processor/batch`: Prevent starting unnecessary goroutines. (#9739)\n- `otlphttpexporter`: prevent error on empty response body when content type is application/json (#9666)\n- `confmap`: confmap honors `Unmarshal` methods on config embedded structs. (#6671)\n- `otelcol`: Respect telemetry configuration when running as a Windows service (#5300)\n\n## v1.3.0/v0.96.0\n\n### 🛑 Breaking changes 🛑\n\n- `configgrpc`: Remove deprecated `GRPCClientSettings`, `GRPCServerSettings`, and `ServerConfig.ToListenerContext`. (#9616)\n- `confighttp`: Remove deprecated `HTTPClientSettings`, `NewDefaultHTTPClientSettings`, and `CORSSettings`. (#9625)\n- `confignet`: Removes deprecated `NetAddr` and `TCPAddr` (#9614)\n\n### 💡 Enhancements 💡\n\n- `configtls`: Add `include_system_ca_certs_pool` to configtls, allowing to load system certs and additional custom certs. (#7774)\n- `otelcol`: Add `ConfigProviderSettings` to `CollectorSettings` (#4759)\n  This allows passing a custom list of `confmap.Provider`s to `otelcol.NewCommand`.\n- `pdata`: Update to OTLP v1.1.0 (#9587)\n  Introduces Span and SpanLink flags.\n- `confmap`: Update mapstructure to use a maintained fork, github.com/go-viper/mapstructure/v2. (#9634)\n  See https://github.com/mitchellh/mapstructure/issues/349 for context.\n  \n\n### 🧰 Bug fixes 🧰\n\n- `configretry`: Allow max_elapsed_time to be set to 0 for indefinite retries (#9641)\n- `client`: Make `Metadata.Get` thread safe (#9595)\n\n## v1.2.0/v0.95.0\n\n### 🛑 Breaking changes 🛑\n\n- `all`: scope name for all generated Meter/Tracer funcs now includes full package name (#9494)\n\n### 💡 Enhancements 💡\n\n- `confighttp`: Adds support for Snappy decompression of HTTP requests. (#7632)\n- `configretry`: Validate `max_elapsed_time`, ensure it is larger than `max_interval` and `initial_interval` respectively. (#9489)\n- `configopaque`: Mark module as stable (#9167)\n- `otlphttpexporter`: Add support for json content encoding when exporting telemetry (#6945)\n- `confmap/converter/expandconverter, confmap/provider/envprovider, confmap/provider/fileprovider, confmap/provider/httpprovider, confmap/provider/httpsprovider, confmap/provider/yamlprovider`: Split confmap.Converter and confmap.Provider implementation packages out of confmap. (#4759, #9460)\n\n## v1.1.0/v0.94.0\n\n### 🛑 Breaking changes 🛑\n\n- `receiver/otlp`: Update gRPC code from `codes.InvalidArgument` to `codes.Internal` when a permanent error doesn't contain a gRPC status (#9415)\n\n### 🚩 Deprecations 🚩\n\n- `configgrpc`: Deprecate GRPCClientSettings, use ClientConfig instead (#6767)\n\n### 💡 Enhancements 💡\n\n- `mdatagen`: Add a generated test that checks the config struct using `componenttest.CheckConfigStruct` (#9438)\n- `component`: Add `component.UseLocalHostAsDefaultHost` feature gate that changes default endpoints from 0.0.0.0 to localhost (#8510)\n  The only component in this repository affected by this is the OTLP receiver.\n  \n- `confighttp`: Add support of Host header (#9395)\n- `mdatagen`: Remove use of ReportFatalError in generated tests (#9439)\n\n### 🧰 Bug fixes 🧰\n\n- `service`: fix opencensus bridge configuration in periodic readers (#9361)\n- `otlpreceiver`: Fix goroutine leak when GRPC server is started but HTTP server is unsuccessful (#9165)\n- `otlpexporter`: PartialSuccess is treated as success, logged as warning. (#9243)\n\n## v0.93.0\n\n### 🛑 Breaking changes 🛑\n\n- `exporterhelper`: remove deprecated exporterhelper.RetrySettings and exporterhelper.NewDefaultRetrySettings (#9256)\n- `configopaque`: configopaque.String implements `fmt.Stringer` and `fmt.GoStringer`, outputting [REDACTED] when formatted with the %s, %q or %#v verbs` (#9213)\n  This may break applications that rely on the previous behavior of opaque strings with `fmt.Sprintf` to e.g. build URLs or headers.\n  Explicitly cast the opaque string to a string before using it in `fmt.Sprintf` to restore the previous behavior.\n  \n\n### 🚀 New components 🚀\n\n- `extension/memory_limiter`: Introduce a `memory_limiter` extension which receivers can use to reject incoming requests when collector doesn't have enough memory (#8632)\n  The extension has the same configuration interface and behavior as the existing `memory_limiter` processor, which potentially can be deprecated and removed in the future\n\n### 💡 Enhancements 💡\n\n- `configtls`: add `cipher_suites` to configtls. (#8105)\n  Users can specify a list of cipher suites to pick from. If left blank, a safe default list is used.\n  \n- `service`: mark `telemetry.useOtelForInternalMetrics` as stable (#816)\n- `exporters`: Cleanup log messages for export failures (#9219)\n  1. Ensure an error message is logged every time and only once when data is dropped/rejected due to export failure.\n  2. Update the wording. Specifically, don't use \"dropped\" term when an error is reported back to the pipeline.\n     Keep the \"dropped\" wording for failures happened after the enabled queue.\n  3. Properly report any error reported by a queue. For example, a persistent storage error must be reported as a storage error, not as \"queue overflow\".\n  \n\n### 🧰 Bug fixes 🧰\n\n- `configgrpc`: Update dependency to address a potential crash in the grpc instrumentation (#9296)\n- `otlpreceiver`: Ensure OTLP receiver handles consume errors correctly (#4335)\n  Make sure OTLP receiver returns correct status code and follows the receiver contract (gRPC)\n- `zpagesextension`: Remove mention of rpcz page from zpages extension (#9328)\n\n## v1.0.1/v0.92.0\n\n### 🛑 Breaking changes 🛑\n\n- `exporters/sending_queue`: Do not re-enqueue failed batches, rely on the retry_on_failure strategy instead. (#8382)\n  The current re-enqueuing behavior is not obvious and cannot be configured. It takes place only for persistent queue\n  and only if `retry_on_failure::enabled=true` even if `retry_on_failure` is a setting for a different backoff retry\n  strategy. This change removes the re-enqueuing behavior. Consider increasing `retry_on_failure::max_elapsed_time` \n  to reduce chances of data loss or set it to 0 to keep retrying until requests succeed.\n  \n- `confmap`: Make the option `WithErrorUnused` enabled by default when unmarshaling configuration (#7102)\n  The option `WithErrorUnused` is now enabled by default, and a new option `WithIgnoreUnused` is introduced to ignore\n  errors about unused fields.\n  \n- `status`: Deprecate `ReportComponentStatus` in favor of `ReportStatus`. This new function does not return an error. (#9148)\n\n### 🚩 Deprecations 🚩\n\n- `connectortest`: Deprecate connectortest.New[Metrics|Logs|Traces]Router in favour of connector.New[Metrics|Logs|Traces]Router (#9095)\n- `exporterhelper`: Deprecate exporterhelper.RetrySettings in favor of configretry.BackOffConfig (#9091)\n- `extension/ballast`: Deprecate `memory_ballast` extension. (#8343)\n  Use `GOMEMLIMIT` environment variable instead.\n  \n- `connector`: Deprecate [Metrics|Logs|Traces]Router in favour of [Metrics|Logs|Traces]RouterAndConsumer (#9095)\n\n### 💡 Enhancements 💡\n\n- `exporterhelper`: Add RetrySettings validation function (#9089)\n  Validate that time.Duration, multiplier values in configretry are non-negative, and randomization_factor is between 0 and 1\n  \n- `service`: Enable `telemetry.useOtelForInternalMetrics` by updating the flag to beta (#7454)\n  The metrics generated should be consistent with the metrics generated\n  previously with OpenCensus. Users can disable the behaviour\n  by setting `--feature-gates -telemetry.useOtelForInternalMetrics` at\n  collector start.\n  \n- `mdatagen`: move component from contrib to core (#9172)\n- `semconv`: Generated Semantic conventions 1.22.0. (#8686)\n- `confignet`: Add `dialer_timeout` config option. (#9066)\n- `processor/memory_limiter`: Update config validation errors (#9059)\n  - Fix names of the config fields that are validated in the error messages\n  - Move the validation from start to the initialization phrase \n  \n- `exporterhelper`: Add config Validate for TimeoutSettings (#9104)\n\n### 🧰 Bug fixes 🧰\n\n- `memorylimiterprocessor`: Fixed leaking goroutines from memorylimiterprocessor (#9099)\n- `cmd/otelcorecol`: Fix the code detecting if the collector is running as a service on Windows. (#7350)\n  Removed the `NO_WINDOWS_SERVICE` environment variable given it is not needed anymore.\n- `otlpexporter`: remove dependency of otlphttpreceiver on otlpexporter (#6454)\n\n## v0.91.0\n\n### 💡 Enhancements 💡\n\n- `statusreporting`: Automates status reporting upon the completion of component.Start(). (#7682)\n- `service`: add resource attributes as labels to otel metrics to ensures backwards compatibility with OpenCensus metrics. (#9029)\n- `semconv`: Generated Semantic conventions 1.21. (#9056)\n- `config/confighttp`: Exposes http/2 transport settings to enable health check and workaround golang http/2 issue https://github.com/golang/go/issues/59690 (#9022)\n- `cmd/builder`: running builder version on binaries installed with `go install` will output the version specified at the suffix. (#8770)\n\n### 🧰 Bug fixes 🧰\n\n- `exporterhelper`: fix missed metric aggregations (#9048)\n  This ensures that context cancellation in the exporter doesn't interfere with metric aggregation. The OTel\n  SDK currently returns if there's an error in the context used in `Add`. This means that if there's a\n  cancelled context in an export, the metrics are now recorded.\n  \n- `service`: Fix bug where MutatesData would not correctly propagate through connectors. (#9053)\n\n## v0.90.1\n\n### 🧰 Bug fixes 🧰\n\n- `exporterhelper`: Remove noisy log (#9017)\n\n## v1.0.0/v0.90.0\n\n### 🛑 Breaking changes 🛑\n\n- `service`: To remain backwards compatible w/ the metrics generated today, otel generated metrics will be generated without the `_total` suffix (#7454)\n- `service`: use WithNamespace instead of WrapRegistererWithPrefix (#8988)\n  Using this functionality in the otel prom exporter fixes a bug where the\n  target_info was prefixed as otelcol_target_info previously.\n  \n\n### 💡 Enhancements 💡\n\n- `exporter/debug`: Change default `verbosity` from `normal` to `basic` (#8844)\n  This change has currently no effect, as `basic` and `normal` verbosity share the same behavior. This might change in the future though, with the `normal` verbosity being more verbose than it currently is (see https://github.com/open-telemetry/opentelemetry-collector/issues/7806). This is why we are changing the default to `basic`, which is expected to stay at the current level of verbosity (one line per batch).\n- `exporterhelper`: Fix shutdown logic in persistent queue to not require consumers to be closed first (#8899)\n- `confighttp`: Support proxy configuration field in all exporters that support confighttp (#5761)\n\n### 🧰 Bug fixes 🧰\n\n- `exporterhelper`: Fix invalid write index updates in the persistent queue (#8115)\n\n## v1.0.0-rcv0018/v0.89.0\n\n### 💡 Enhancements 💡\n\n- `builder`: remove replace statement in builder template (#8763)\n- `service/extensions`: Allow extensions to declare dependencies on other extensions and guarantee start/stop/notification order accordingly. (#8732)\n- `exporterhelper`: Log export errors when retry is not used by the component. (#8791)\n- `cmd/builder`: Add --verbose flag to log `go` subcommands output that are ran as part of a build (#8715)\n- `exporterhelper`: Remove internal goroutine loop for persistent queue (#8868)\n- `exporterhelper`: Simplify usage of storage client, avoid unnecessary allocations (#8830)\n- `exporterhelper`: Simplify logic in boundedMemoryQueue, use channels len/cap (#8829)\n\n### 🧰 Bug fixes 🧰\n\n- `exporterhelper`: fix bug with queue size and capacity metrics (#8682)\n- `obsreporttest`: split handler for otel vs oc test path in TestTelemetry (#8758)\n- `builder`: Fix featuregate late initialization (#4967)\n- `service`: Fix connector logger zap kind key (#8878)\n\n## v1.0.0-rcv0017/v0.88.0\n\n### 💡 Enhancements 💡\n\n- `fanoutconsumer`: Enable runtime assertions to catch incorrect pdata mutations in the components claiming as non-mutating pdata. (#6794)\n  This change enables the runtime assertions to catch unintentional pdata mutations in components that are claimed\n  as non-mutating pdata. Without these assertions, runtime errors may still occur, but thrown by unrelated components, \n  making it very difficult to troubleshoot.\n  \n\n### 🧰 Bug fixes 🧰\n\n- `exporterhelper`: make enqueue failures available for otel metrics (#8673)\n- `exporterhelper`: Fix nil pointer dereference when stopping persistent queue after a start encountered an error (#8718)\n- `cmd/builder`: Fix ocb ignoring `otelcol_version` when set to v0.86.0 or later (#8692)\n\n## v1.0.0-rcv0016/v0.87.0\n\n### 💡 Enhancements 💡\n\n- `service/telemetry exporter/exporterhelper`: Enable sampling logging by default and apply it to all components. (#8134)\n  The sampled logger configuration can be disabled easily by setting the `service::telemetry::logs::sampling::enabled` to `false`.\n- `core`: Adds the ability for components to report status and for extensions to subscribe to status events by implementing an optional StatusWatcher interface. (#7682)\n\n### 🧰 Bug fixes 🧰\n\n- `telemetry`: remove workaround to ignore errors when an instrument includes a `/` (#8346)\n\n## v1.0.0-rcv0015/v0.86.0\n\n### 🚩 Deprecations 🚩\n\n- `loggingexporter`: Mark the logging exporter as deprecated, in favour of debug exporter (#7769)\n\n### 🚀 New components 🚀\n\n- `debugexporter`: Add debug exporter, which replaces the logging exporter (#7769)\n\n### 💡 Enhancements 💡\n\n- `featuregate`: List valid feature gates when failing to load invalid gate (#8505)\n- `supported platforms`: Add `linux/s390x` architecture to cross build tests in CI (#8213)\n\n### 🧰 Bug fixes 🧰\n\n- `builder`: fix setting `dist.*` keys from env (#8239)\n- `configtls`: fix incorrect use of fsnotify (#8438)\n\n## v0.85.0\n\n### 💡 Enhancements 💡\n\n- `components command`: The \"components\" command now lists the component's stability levels. (#8289)\n  Note that the format of this output is NOT stable and can change between versions.\n- `confighttp`: Add option to disable HTTP keep-alives (#8260)\n\n### 🧰 Bug fixes 🧰\n\n- `confmap`: fix bugs of unmarshalling slice values (#4001)\n- `exporterhelper`: Stop logging error messages suggesting user to enable `retry_on_failure` or `sending_queue` when they are not available. (#8369)\n\n## v0.84.0\n\n### 💡 Enhancements 💡\n\n- `loggingexporter`: Adds exemplars logging to the logging exporter when `detailed` verbosity level is set. (#7912)\n- `configgrpc`: Allow any registered gRPC load balancer name to be used. (#8262)\n- `service`: add OTLP export for internal traces (#8106)\n- `configgrpc`: Add support for :authority pseudo-header in grpc client (#8228)\n\n### 🧰 Bug fixes 🧰\n\n- `otlphttpexporter`: Fix the handling of the HTTP response to ignore responses not encoded as protobuf (#8263)\n\n## v0.83.0\n\n### 💡 Enhancements 💡\n\n- `extension`: Add optional `ConfigWatcher` interface (#6596)\n  Extensions implementing this interface will be notified of the Collector's effective config.\n- `otelcol`: Add optional `ConfmapProvider` interface for Config Providers (#6596)\n  This allows providing the Collector's configuration as a marshaled confmap.Conf object\n  from a ConfigProvider\n  \n- `service`: Add `CollectorConf` field to `service.Settings` (#6596)\n  This field is intended to be used by the Collector to pass its effective configuration to the service.\n  \n\n## v1.0.0-rcv0014/v0.82.0\n\n### 🛑 Breaking changes 🛑\n\n- `service`: Enable configuration of collector telemetry through prometheus reader (#7641)\n  These options are still experimental. To enable them, users must enable both\n  `telemetry.useOtelForInternalMetrics` and `telemetry.useOtelWithSDKConfigurationForInternalTelemetry`\n  feature gates. This change updates `metric_readers` to `readers` to align with the configuration\n  working group.\n  \n- `service`: Remove experimental `metric_readers.args` and `metric_reader.type` config options. (#7641)\n  These options were experimental and did not have any effect on the configuration of\n  the collector's telemetry. The change aligns the configuration with the latest iteration\n  of the configuration json schema, which may still change in the future.\n\n### 💡 Enhancements 💡\n\n- `service`: Add support for exporting internal metrics to the console (#7641)\n  Internal collector metrics can now be exported to the console\n  using the otel-go stdout exporter.\n  \n- `service`: Add support for `interval` and `timeout` configuration in periodic reader (#7641)\n- `service`: Add support for span processor configuration for internal traces (#8106)\n  These options are still experimental. To enable them, users must enable both\n  `telemetry.useOtelForInternalMetrics` and `telemetry.useOtelWithSDKConfigurationForInternalTelemetry`\n  feature gates.\n  \n- `service`: Add support for OTLP export for internal metrics (#7641)\n  Internal collector metrics can now be exported via OTLP\n  using the otel-go otlpgrpc and otlphttp exporters.\n  \n- `scraperhelper`: Adding optional timeout field to scrapers (#7951)\n- `otlpreceiver`: Add http url paths per signal config options to otlpreceiver (#7511)\n- `otlphttpexporter`: Add support for trailing slash in endpoint URL (#8084)\n  URLs like `http://localhost:4318/` will now be treated as if they were `http://localhost:4318`\n\n### 🧰 Bug fixes 🧰\n\n- `connector`: Fix connector validation (#7892)\n  Validation of connectors was too aggressive such that a connector that was used in any combination of unsupported roles would fail.\n  Instead, validation should pass as long as each use of the connector has a supported corresponding use.\n  \n\n## v0.81.0\n\n### 🛑 Breaking changes 🛑\n\n- `service`: Remove 'service.connectors' featuregate (#7952)\n\n### 💡 Enhancements 💡\n\n- `HTTPServerSettings`: Add zstd support to HTTPServerSettings (#7927)\n  This adds ability to decompress zstd-compressed HTTP requests to| all receivers that use HTTPServerSettings.\n- `cmd/builder`: Add \"--skip-generate\" option to make builder skip source generation (#7541)\n- `confighttp`: Add support for additional content decoders via `WithDecoder` server option (#7977)\n- `connectortest`: Add helpers to aid the construction of `connector.TracesRouter`, `connector.MetricsRouter`, and `connector.LogsRouter` instances to `connectortest`. (#7672)\n- `confighttp`: Add `response_headers` configuration option on HTTPServerSettings. It allows for additional headers to be attached to each HTTP response sent to the client (#7328)\n- `otlpreceiver, otlphttpexporter, otlpexporter, configgrpc`: Upgrade github.com/mostynb/go-grpc-compression and switch to nonclobbering imports (#7920)\n  consumers of this library should not have their grpc codecs overridden\n- `otlphttpexporter`: Treat partial success responses as errors (#6686)\n\n### 🧰 Bug fixes 🧰\n\n- `HTTPServerSettings`: Ensure requests with unsupported Content-Encoding return HTTP 400 Bad Request (#7927)\n\n## v1.0.0-rcv0013/v0.80.0\n\n### 🚩 Deprecations 🚩\n\n- `service`: Deprecate service.PipelineConfig in favor of pipelines.Config. (#7854)\n\n### 💡 Enhancements 💡\n\n- `service`: Added dry run flag to validate config file without running collector. (#4671)\n- `configtls`: Allow TLS Settings to be provided in memory in addition to filepath. (#7313)\n- `connector`: Updates the way connector nodes are built to always pass a fanoutconsumer to their factory functions. (#7672, #7673)\n- `otlp`: update otlp protos to v0.20.0 (#7839)\n- `configauth`: Split config/configauth into its own module (#7895)\n- `configgrpc, confighttp, config/internal`: Split confighttp, configgrpc, and config/internal into separate modules (#7895)\n- `confignet`: Split config/confignet into its own module (#7895)\n- `configopaque`: Split config/configopaque into its own module (#7895)\n- `configtelemetry`: Split config/configtelemetry into its own module (#7895)\n- `configtls`: Split config/configtls into its own module (#7895)\n- `configcompression`: Split config/configcompression into its own module (#7895)\n- `extension`: Splitting `extension/auth` into separate module (#7054)\n- `connector`: Split connector into its own module (#7895)\n- `extension`: split extension module into its own module (#7306)\n- `processor`: Split the processor into its own go module (#7307)\n- `confighttp`: Avoid re-creating the compressors for every request. (#7859)\n- `otlpexporter`: Treat partial success responses as errors (#6686)\n- `service/pipelines`: Add pipelines.Config to remove duplicate of the pipelines configuration (#7854)\n\n## v0.79.0\n\n### 🚩 Deprecations 🚩\n\n- `component`: Deprecate Host.GetExporters function (#7370)\n\n### 💡 Enhancements 💡\n\n- `otelcol`: Add connectors to output of the `components` command (#7809)\n- `scraperhelper`: Will start calling scrapers on component start. (#7635)\n  The change allows scrapes to perform their initial scrape on component start\n  and provide an initial delay. This means that scrapes will be delayed by `initial_delay`\n  before first scrape and then run on `collection_interval` for each consecutive interval. \n  \n- `batchprocessor`: Change multiBatcher to use sync.Map, avoid global lock on fast path (#7714)\n\n### 🧰 Bug fixes 🧰\n\n- `connectors`: When replicating data to connectors, consider whether the next pipeline will mutate data (#7776)\n\n## v0.78.2\n\n### 🧰 Bug fixes 🧰\n\n- `batchprocessor`: Fix return error for batch processor when consuming Metrics and Logs (#7711)\n\n## v0.78.1\n\n### 🧰 Bug fixes 🧰\n\n- `batchprocessor`: Fix start/stop logic for batch processor (#7708)\n\n## v1.0.0-rcv0012/v0.78.0\n\n### 💡 Enhancements 💡\n\n- `batchprocessor`: Add support for batching by metadata keys. (#4544)\n- `service`: Add feature gate `telemetry.useOtelWithSDKConfigurationForInternalTelemetry` that will add support for configuring the export of internal telemetry to additional destinations in future releases (#7641)\n- `forwardconnector`: Promote to beta (#7579)\n- `featuregate`: Promote `featuregate` to the stable module-set (#7693)\n\n### 🧰 Bug fixes 🧰\n\n- `featuregate`: Fix issue where `StageDeprecated` was not usable (#7586)\n- `exporterhelper`: Fix persistent storage behaviour with no available space on device (#7198)\n\n## v0.77.0\n\n### 🛑 Breaking changes 🛑\n\n- `exporterhelper`: Reduce the default queue size to 1000 from 5000 (#7359)\n  Affects any exporter which enables the queue by default and doesn't set its own default size.\n  For example: otlphttp.\n  \n- `featuregate`: Remove deprecated `RemovalVersion` and `WithRegisterRemovalVersion` functions. (#7587)\n\n### 💡 Enhancements 💡\n\n- `service`: Adds ResourceAttributes map to telemetry settings and thus CreateSettings. (#6599)\n- `service`: Allows users to disable high cardinality OTLP attributes behind a feature flag. (#7517)\n- `featuregate`: Finalize purpose of `toVersion`.  Allow stable gates to be explicitly set to true, but produce a warning log. (#7626)\n\n### 🧰 Bug fixes 🧰\n\n- `config/confighttp`: Ensure Auth RoundTripper follows compression/header changes (#7574)\n- `otlpreceiver`: do not reject requests having 'content-type' header with optional parameters (#7452)\n\n## v1.0.0-rcv0011/v0.76.1\n\n### 🛑 Breaking changes 🛑\n\n- `confmap`: Using an Invalid Scheme in a URI will throw an error. (#7504)\n\n### 🚩 Deprecations 🚩\n\n- `featuregate`: Deprecate Gate.RemovalVersion and WithRegisterRemovalVersion in favor of ToVersion. (#7043)\n\n### 💡 Enhancements 💡\n\n- `batchprocessor`: Support zero timeout. (#7508)\n  This allows the batchprocessor to limit request sizes without introducing delay in a pipeline, to act only as a splitter.\n- `service`: use the otel opencensus bridge when telemetry.useOtelForInternalMetrics is enabled (#7483)\n- `connector`: Mark 'service.connectors' featuregate as stable (#2336)\n- `featuregate`: Add a new Deprecated stage for feature gates, when features are abandoned. (#7043)\n- `loggingexporter`: Show more counters in not detailed verbosity (#7461)\n  The logging exporter now shows more counters when the verbosity is not detailed. The following numbers are added:\n  - Number of resource logs\n  - Number of resource spans\n  - Number of resource metrics\n  - Number of data points\n  \n- `configtls`: Reload mTLS ClientCA certificates on file change (#6524)\n- `confmap`: Add support for nested URIs. (#7117)\n- `featuregate`: Add concept of gate lifetime, [fromVersion, toVersion]. (#7043)\n\n### 🧰 Bug fixes 🧰\n\n- `obsreport`: fix issue where send_failed_requests counter was reporting an incorrect value. (#7456)\n\n## v1.0.0-rc9/v0.75.0\n\n### 🛑 Breaking changes 🛑\n\n- `featuregate`: Remove deprecated featuregate.FlagValue (#7401)\n\n### 💡 Enhancements 💡\n\n- `provider`: Added userfriendly error on incorrect type. (#7399)\n\n### 🧰 Bug fixes 🧰\n\n- `loggingexporter`: Fix display of bucket boundaries of exponential histograms to correctly reflect inclusive/exclusive bounds. (#7445)\n- `exporterhelper`: Fix a deadlock in persistent queue initialization (#7400)\n\n## v1.0.0-rc8/v0.74.0\n\n### 🛑 Breaking changes 🛑\n\n- `consumererror`: Remove deprecated funcs in consumererror (#7357)\n\n### 🚩 Deprecations 🚩\n\n- `featuregate`: Deprecate `FlagValue` in favor of `NewFlag`. (#7042)\n\n### 💡 Enhancements 💡\n\n- `service`: Enable connectors by default by moving service.connectors featuregate to beta (#7369)\n\n## v0.73.0/v1.0.0-rc7\n\n### 🛑 Breaking changes 🛑\n\n- `consumererror`: Remove `Get` prefix from methods returning failed signal data (#7048)\n- `service`: Feature gate `service.graph` is now stable and cannot be disabled. It will be removed in the next version. (#2336)\n\n### 💡 Enhancements 💡\n\n- `exporter`: split exporter into its own module (#7239)\n- `receiver`: split receiver into its own module (#7174)\n- `connectors`: Provide connectors with a mechanism to route data to specific pipelines (#7152)\n- `confmap`: Mark `confmap.expandEnabled` as stable (#7323)\n\n## v1.0.0-rc6/v0.72.0\n\n### 🛑 Breaking changes 🛑\n\n- `all`: Remove go 1.18 support, bump minimum to go 1.19 and add testing for 1.20 (#7151)\n- `pdata`: Remove deprecated `[Metrics|Traces|Logs]MoveTo` methods. (#7165)\n- `featuregate`: Remove deprecated funcs in featuregate. (#7173)\n\n### 💡 Enhancements 💡\n\n- `semconv`: Generated Semantic conventions 1.17 that now contains the `event` type. (#7170)\n- `semconv`: Generated Semantic conventions 1.18. (#7168)\n\n### 🧰 Bug fixes 🧰\n\n- `memorylimiterprocessor`: Fix incorrect parsing of cgroups when running Collector with host mount (#6826)\n- `confmap`: Clear list of old already closed closers. (#7215)\n\n## v1.0.0-rc5/v0.71.0\n\n### 🛑 Breaking changes 🛑\n\n- `pdata`: Add private method to GrpcServer interface, disallow direct implementation (#6966)\n- `featuregate`: Remove deprecated GetRegistry (#7011)\n- `pcommon`: Remove deprecated Map.Sort (#6688)\n\n### 🚩 Deprecations 🚩\n\n- `featuregate`: Deprecate Registry.List in favor of Registry.VisitAll. (#7041)\n- `featuregate`: Deprecate Apply in favor of Set (#7018)\n- `pdata`: Deprecate [Metrics|Logs|Traces].MoveTo methods. (#7091)\n- `featuregate`: Deprecate RegistryOption in favor of RegisterOption (#7012)\n- `featuregate`: Deprecate featuregate.Registry.[IsEnabled, RegisterID, MustRegister] (#6998)\n\n### 🚀 New components 🚀\n\n- `httpsprovider`: Add the httpsprovider. This component allows the collector to fetch configurations from web servers using the HTTPS protocol. (#6683)\n\n### 💡 Enhancements 💡\n\n- `exporter`: Allow configuration of fields, `RandomizationFactor` and `Multiplier`, for exponential backoff algorithm when retry on failure is enabled (#6610)\n- `connectors`: Add \"connectors\", a new type of pipeline component (#2336)\n  - Connectors connect pipelines by acting as an exporter in one or more pipelines and simultaneously\n  as a receiver of corresponding data in one or more other pipelines. For example:\n    - The `forward` connector can export data to another pipeline of the same type. This allows you\n    to merge data from multiple pipelines onto a common pipeline. Or, you can replicate data onto multiple\n    pipelines so that it may be processed in different ways and/or exported to different backends.\n    - The `count` connector can count data of any type. Regardless of the type of data that is counted, it\n    emits counts as metrics onto a metrics pipeline.\n  - Connectors are currently disabled by default but can be enabled with the `service.connectors` feature gate.\n  - See the [connectors README](https://github.com/open-telemetry/opentelemetry-collector/blob/main/connector/README.md)\n  for more details on how to use connectors.\n  \n- `service`: Enable new pipelines implementation using graphs. Controlled by the `service.graph` featuregate. (#2336)\n- `builder`: added ldflags command option (#6940)\n- `proctelemetry`: Instrument `proctelemetry.ProcessMetrics` metrics with otel-go (#6886)\n- `capabilityconsumer`: If the consumer has already the desired capability, don't wrap (#7116)\n- `confmap`: Add support to resolve embedded uris inside a string, concatenate results. (#6932)\n\n### 🧰 Bug fixes 🧰\n\n- `confmap`: Fix bug in confmap validation that allowed the usage of case-insensitive keys in the configurations, despite them failing silently. (#6876)\n- `logging`: Fix the attribute key used to identify the receiver data type in logging configuration (#7033)\n\n## v1.0.0-RC4/v0.70.0\n\n### 🛑 Breaking changes 🛑\n\n- `pdata`: Start enforcing grpc server implementation to embed UnimplementedGRPCServer, disallow client implementation (#6966)\n- `config/configgrpc`: Change configgrpc.GRPCClientSettings.Headers type to map[string]configopaque.String (#6852)\n  Use `configopaque.String(str)` and `string(opaque)` to turn a string opaque/clear.\n- `pdata`: Remove deprecated pcommon.Value.Equal (#6860)\n\n### 🚩 Deprecations 🚩\n\n- `pdata`: Deprecate pcommon.Map.Sort(). (#6688)\n- `featuregate`: Deprecate GetRegistry in favor of GlobalRegistry (#6979)\n\n### 💡 Enhancements 💡\n\n- `builder`: Add remote debug option for otel-collector to builder (#6149)\n- `connector`: Add Builder (#6867)\n- `cmd/builder`: Add support for connector configurations (#6789)\n- `exporter/otlphttp`: Retry only on status code 429/502/503/504 (#6845)\n- `featuregate`: Reduce contention in featuregate by using sync.Map instead of mutex. (#6980)\n\n### 🧰 Bug fixes 🧰\n\n- `loggingexporter`: Fix undefined symbol errors on building otelcorecol for other platforms than darwin, linux, windows. (#6924)\n- `otlpexporter`: Fix a dataloss bug in persistent storage when collector shuts down or restarts (#6771)\n\n## v0.69.1\n\n### 🧰 Bug fixes 🧰\n\n- `various modules`: Fix issue where some collector modules imported previous version of other modules (#6929)\n\n## v1.0.0-RC3/v0.69.0\n\n### 🛑 Breaking changes 🛑\n\n- `component`: Remove deprecated Exporter types (#6880)\n- `component`: Remove deprecated Extension types (#6865)\n- `component`: Remove deprecated ProcessorFactoryOptions (#6881)\n- `component`: Remove deprecated Receiver types (#6882)\n- `componenttest`: Remove deprecated funcs from componenttest (#6836)\n- `batchprocessor`: Remove deprecated batchprocessor.MetricViews and batchprocessor.OtelMetricViews (#6861)\n- `component`: Remove deprecated component.[Factories|MakeProcessorFactoryMap] and componenttest.NewNopFactories (#6835)\n- `config`: Remove deprecated config.*Settings (#6837)\n- `obsreporttest`: Remove deprecated obsreporttest.SetupTelemetryWithID (#6861)\n- `component`: Remove deprecated component [Traces|Metrics|Logs]Processor and ProcessorFactory (#6884)\n- `service`: Remove deprecated service service.ConfigService and service.ConfigServicePipeline (#6859)\n\n### 💡 Enhancements 💡\n\n- `connector`: Add MakeFactoryMap (#6889)\n- `semconv`: Add semantic conventions for specification v1.16.0 (#6714)\n\n### 🧰 Bug fixes 🧰\n\n- `config`: use [REDACTED] when marshaling to text a configopaque.String, instead of disclosing secret length. (#6868)\n\n## v1.0.0-RC2/v0.68.0\n\n### 🛑 Breaking changes 🛑\n\n- `componenttest`: Move NopFactories to otelcoltest (#6792)\n- `config/confighttp`: Change confighttp.HTTPClientSettings.Headers type to map[string]configopaque.String (#5653)\n- `config`: Remove deprecated `component.Config.[ID|SetIDName]`. (#4714)\n- `configauth`: Remove deprecated funcs/types from `configauth` (#6719)\n- `component`: Remove deprecated funcs/types from component package (#6769)\n  - `component.[Exporter|Processor|Receiver|Extension]Config`\n  - `component.Unmarshal[Exporter|Processor|Receiver|Extension]Config`\n  - `component.[Exporter|Processor|Receiver|Extension]CreateDefaultConfigFunc`\n  - `component.[Exporter|Receiver|Extension]FactoryOption`\n  - `component.New[Exporter|Receiver|Extension]Factory`\n  - `component.With[Traces|Metrics|Logs][Exporter|Receiver]`\n  - `component.Create[Traces|Metrics|Logs][Exporter|Receiver]Func`\n  - `component.CreateExtensionFunc`\n- `componenttest`: Remove deprecated componenttest.NewNop*CreateSettings (#6761)\n- `service`: Remove deprecated `service.[Collector|New|CollectorSettings|ConfigProvider]` (#5564)\n- `service`: Remove deprecated funcs `service.NewCommand` and `service.NewSvcHandler`. (#5564)\n- `obsreporttest`: Remove deprecate obsreporttest.Check* (#6720)\n- `service`: Remove deprecated `service.Config`. (#6774)\n- `servicetest`: Remove deprecated `servicetest` package. (#5564)\n\n### 🚩 Deprecations 🚩\n\n- `service`: Deprecate `service.ConfigService` in favor of `service.Config` and `service.ConfigServicePipeline` in favor of `service.PipelineConfig`. (#6787)\n- `pdata`: Deprecate `pcommon.Value.Equal` method (#6811)\n- `component`: Deprecate `Processor` related structs and functions in favor of `processor` package (#6709)\n- `component`: Deprecate component.Factories in favor of otelcol.Factories (#6723)\n- `config`: Deprecate `config.[Extension|Exporter|Connector|Receiver|Processor]Settings`. (#6718)\n- `batchprocessor`: Deprecate metric views funcs, for OC and Otel. (#6730)\n- `obsreporttest`: Deprecate obsreporttest.SetupTelemetryWithID in favor of obsreporttest.SetupTelemetry (#6720)\n\n### 🚀 New components 🚀\n\n- `forwardconnector`: Add forward connector (#6763)\n\n### 💡 Enhancements 💡\n\n- `components`: Add [receiver|processor|exporter|extension].Builder to help with creating components form a set of configs and factories (#6803)\n- `configunmarshaler`: Consolidate package into generic implementation (#6801)\n- `service`: Shutdown internal telemetry with the Service (every time config changes). (#5564)\n\n### 🧰 Bug fixes 🧰\n\n- `configgrpc`: Fix todo to add MeterProvider to grpc instrumentation (#4030)\n- `otlpreceiver`: Fix otlpreceiver transport metrics attribute (#6695)\n\n## v1.0.0-RC1/v0.67.0\n\nWe are excited to announce that the `pdata` module is now available as a\nv1.0.0 release candidate.  While breaking changes may still happen in this\nmodule before v1.0.0, we believe it is ready for final assessment and validation\nand hope to make a v1.0.0 release soon.\n\n### 🛑 Breaking changes 🛑\n\n- `overwritepropertiesconverter`: Remove deprecated package `overwritepropertiesconverter` (#6656)\n- `pdata`: Change [...Slice|Map].Sort methods to not return any value (#6660)\n- `featuregate`: remove deprecated functions (#6594)\n  - `featuregate.GetID()`\n  - `featuregate.GetDescription()`\n- `obsreport`: remove deprecated functions. (#6595)\n  - `obsreport.MustNewExporter`\n  - `obsreport.MustNewProcessor`\n  - `obsreport.MustNewReceiver`\n  - `obsreport.MustNewScraper`\n- `service`: Remove deprecated `service.State` enum values. (#6605)\n- `component`: Remove deprecated func/types from component (#6606)\n- `config`: Remove deprecated config.Pipelines and config.Pipeline (#6664)\n- `ballastextension`: Remove deprecated `ballastextension.MemoryBallast` type (#6628)\n- `component`: Remove `Validate()` from component.*Config interfaces and make it optional interface (#6544)\n- `confmap`: Splitting confmap into its own module (#6185)\n  The import path for the confmap module can now be access directly:\n  - `go.opentelemetry.io/collector/confmap`\n\n### 🚩 Deprecations 🚩\n\n- `service`: Deprecate service.[Collector|NewSvcHandler|CollectorSettings|State|NewCommand] in favor of otelcol package\" (#6608)\n  - Deprecate `service.Config` in favor of `otelcol.Config`.\n  - Deprecate `service.ConfigProvider` in favor of `otelcol.ConfigProvider`.\n  - Deprecate `service.NewConfigProvider` in favor of `otelcol.NewConfigProvider`.\n  - Deprecate `service.CollectorSettings` in favor of `otelcol.CollectorSettings`.\n  - Deprecate `service.Collector` in favor of `otelcol.Collector`.\n  - Deprecate `service.New` in favor of `otelcol.NewCollector`.\n  - Deprecate `service.State` in favor of `otelcol.State`.\n  - Deprecate `service.NewSvcHandler` in favor of `otelcol.NewSvcHandler`.\n  - Deprecate `service.NewCommand` in favor of `otelcol.NewCommand`.\n- `obsreporttest`: Deprecate obsreporttest.Check* in favor of TestTelemetry.Check (#6678)\n- `component`: Deprecate Exporter related types/funcs from component package in favor of exporter package. (#6578)\n  - `component.ExporterCreateSettings` -> `exporter.CreateSettings`\n  - `component.CreateTracesExporterFunc` -> `exporter.CreateTracesFunc`\n  - `component.CreateMetricsExporterFunc` -> `exporter.CreateMetricsFunc`\n  - `component.CreateLogsExporterFunc` -> `exporter.CreateLogsFunc`\n  - `component.ExporterFactory` -> `exporter.Factory`\n  - `component.NewExporterFactory` -> `exporter.NewFactory`\n  - `component.MakeExporterFactoryMap` -> `exporter.MakeFactoryMap`\n  - `componenttest.NewNopExporterCreateSettings` -> `exportertest.NewNopCreateSettings`\n  - `componenttest.NewNopExporterFactory` -> `exportertest.NewNopFactory`\n- `component`: Change Config to be opaque for otel collector core. (#4714)\n  - Deprecate `component.Config.ID()` in favor of `component.[*]CreateSettings.ID`.\n  - Deprecate `component.Config.SetIDName()`, no replacement needed since ID in settings is public member.\n  - Deprecate `obsreporttest.SetupTelemetry` in favor of `obsreporttest.SetupTelemetryWithID`.\n\n- `component`: Deprecate `component.Unmarshal[*]Config` in favor of `component.UnmarshalConfig` (#6613)\n- `component`: Deprecate Extension related types/funcs from component package in favor of extension package. (#6578)\n  - `component.Extension` -> `extension.Extension`\n  - `component.PipelineWatcher` -> extension.PipelineWatcher\n  - `component.ExtensionCreateSettings` -> `extension.CreateSettings`\n  - `component.CreateExtensionFunc` -> `extension.CreateFunc`\n  - `component.ExtensionFactory` -> `extension.Factory`\n  - `component.NewExtensionFactory` -> `extension.NewFactory`\n  - `component.MakeExtensionFactoryMap` -> `extension.MakeFactoryMap`\n  - `componenttest.NewNopExtensionCreateSettings` -> `extensiontest.NewNopCreateSettings`\n  - `componenttest.NewNopExtensionFactory` -> `extensiontest.NewNopFactory`\n- `component`: Deprecate `Receiver` related structs and functions in favor of `receiver` package (#6687)\n- `component`: Deprecate `component.[Exporter|Extension|Processor|Receiver]Config` in favor of `component.Config` (#6578)\n- `pdata`: Remove deprecated funcs `pdata.[Span|Trace]ID.HexString` (#6627)\n\n### 💡 Enhancements 💡\n\n- `config/configopaque`: Add new `configopaque.String` type alias for opaque strings. (#5653)\n- `service`: Added components sub command which outputs components in collector distribution. (#4671)\n- `component`: Define new component type 'connectors' (#6577)\n- `connector`: Add connector factory (#6611)\n- `connector`: Add connector types (TracesConnector, MetricsConnector, LogsConnector) (#6689)\n- `connectortest`: Add connector/connectortest package (#6711)\n- `component`: Add recursive validation check for configs (#4584)\n- `service`: Improve config error messages, split Validate functionality (#6665)\n- `extension/authextension`: Define new authextension package and use new package in collector repo (#6467)\n  - configauth.ClientAuthenticator -> auth.Client\n  - configauth.NewClientAuthenticator -> auth.NewClient\n  - configauth.ClientOption -> auth.ClientOption\n  - configauth.WithClientStart -> auth.WithClientStart\n  - configauth.WithClientShutdown -> auth.WithClientShutdown\n  - configauth.WithClientRoundTripper -> auth.WithClientRoundTripper\n  - configauth.WithPerRPCCredentials -> auth.WithClientPerRPCCredentials\n  - configauth.ServerAuthenticator -> auth.Server\n  - configauth.NewServerAuthenticator -> auth.NewServer\n  - configauth.Option -> auth.ServerOption\n  - configauth.AuthenticateFunc -> auth.ServerAuthenticateFunc\n  - configauth.WithAuthenticate -> auth.WithServerAuthenticate\n  - configauth.WithStart -> auth.WithServerStart\n  - configauth.WithShutdown -> auth.WithServerShutdown\n- `obsreport`: Instrument `obsreport.Processor` metrics with otel-go (#6607)\n- `pdata`: Add ability to clear optional fields (#6474)\n\n### 🧰 Bug fixes 🧰\n\n- `otlpexporter`: Fix nil panic from otlp exporter in case of errors during Start. (#6633)\n- `service`: Stop notification for signals before shutdown, increase channel size. (#6522)\n- `confmap`: Fix support for concatenating envvars with colon (#6580)\n- `otlpexporter`: Fix a bug that exporter persistent queue is sending duplicate data after restarting. (#6692)\n\n## v0.65.0\n\n### 🛑 Breaking changes 🛑\n\n- `featuregate`: Capitalize `featuregate.Stage` string values, remove Stage prefix. (#6490)\n- `configtelemetry`: Update values returned by `Level.String` and `Level.MarshalText` method. (#6490)\n  - All returned strings are capitalized.\n  - \"\" is returned for integers that are out of Level enum range.\n  - It also affects `Level.Marshal` output, but it's not a problem because `Unmarshal` method accepts strings in\n  all cases, e.g. \"normal\", \"Normal\" and \"NORMAL\".\n\n- `featuregate`: Make impossible to implement RegistryOption outside `featuregate` package (#6532)\n- `service/telemetry`: Remove unit suffixes from metrics exported by the otel-go prometheus exporter. (#6403)\n- `obsreport`: `obsreport.New[Receiver|Scraper|Processor|Exporter]` returns error now (#6458)\n- `configgrpc`: Remove deprecated funcs in `configgrpc`. (#6529)\n  - `configgrpc.GRPCClientSettings.ToDialOptions`\n  - `configgrpc.GRPCServerSettings.ToServerOption`\n\n- `config/configtest`: Remove deprecated `configtest` package. (#6542)\n- `config`: Remove deprecated types and funcs from config. Use `component` package. (#6511)\n  - config.ComponentID\n  - config.Type\n  - config.DataType\n  - config.Receiver\n  - config.UnmarshalReceiver\n  - config.Processor\n  - config.UnmarshalProcessor\n  - config.Exporter\n  - config.UnmarshalExporter\n  - config.Extension\n  - config.UnmarshalExtension\n\n- `featuregate`: Remove deprecated funcs and struct members from `featuregate` package (#6523)\n  - featuregate.Gate.ID\n  - featuregate.Gate.Description\n  - featuregate.Gate.Enabled\n  - featuregate.Registry.Register\n  - featuregate.Registry.MustRegister\n\n- `experimental`: Remove experimental configsource code. (#6558)\n- `component`: Update values returned by `StabilityLevel.String` method. (#6490)\n  - All returned strings are capitalized.\n  - \"Undefined\" is returned only for `StabilityLevelUndefined`.\n  - \"\" is returned for integers that are out of StabilityLevel enum range.\n\n\n### 🚩 Deprecations 🚩\n\n- `pdata`: Deprecate `pcommon.[Span|Trace]ID.HexString` methods. Call `hex.EncodeToString` explicitly instead. (#6514)\n- `obsreport`: deprecate `obsreport.MustNew[Receiver|Scraper|Processor|Exporter]` in favor of `obsreport.New[Receiver|Scraper|Processor|Exporter]` (#6458)\n  - Deprecate `obsreport.MustNewReceiver()` in favor of `obsreport.NewReceiver()`\n  - Deprecate `obsreport.MustNewScraper()` in favor of `obsreport.NewScraper()`\n  - Deprecate `obsreport.MustNewProcessor()` in favor of `obsreport.NewProcessor()`\n  - Deprecate `obsreport.MustNewExporter()` in favor of `obsreport.NewExporter()`\n\n- `component`: Deprecate `component.Receiver`, `component.Processor`, and `component.Exporter`. (#6553)\n- `featuregate`: Deprecate Get prefix funcs for `featuregate.Gate` (#6528)\n  `featuregate.Gate.GetID` -> `featuregate.Gate.ID`\n  `featuregate.Gate.GetDescription` -> `featuregate.Gate.Description`\n\n- `component`: Deprecate `component.Config.Validate` in favor of `component.ValidateConfig` (#6572)\n- `component`: Deprecate `StabilityLevelInDevelopment` enum const in favor of `StabilityLevelDevelopment`. (#6561)\n  Also rename all mentions of \"In development\" stability level to \"Development\".\n- `service`: Deprecate `service.[Starting|Running|Closing|Closed]` in favor of `service.State[Starting|Running|Closing|Closed]` (#6492)\n\n### 💡 Enhancements 💡\n\n- `component`: `component.Extension` is temporarily set to be an alias of `component.Component` which will be reverted once it's moved to the `extension` package. Change your `component.Host.GetExtensions()` implementation to return `map[ID]component.Component` instead of `map[ID]component.Extension` (#6553)\n- `pdata`: Return error from `pcommon.[Value|Map|Slice].FromRaw` when unsupported type. (#6579)\n- `batchprocessor`: instrument the `batch` processor with OpenTelemetry Go SDK (#6423)\n- `obsreport`: Instrument `obsreport.Scraper` metrics with otel-go (#6460)\n- `service/collector`: Support SIGHUP configuration reloading (#5966)\n- `component`: Split component into its own package (#6187)\n  The import path for the component module can now be access directly:\n    - `go.opentelemetry.io/collector/component`\n- `consumer`: Split consumer into its own package (#6186)\n  The import path for the consumer module can now be accessed directly:\n    - `go.opentelemetry.io/collector/consumer`\n- `featuregate`: Split featuregate into its own package (#6526)\n  The import path for the featuregate module can now be accessed directly:\n    - `go.opentelemetry.io/collector/featuregate`\n\n### 🧰 Bug fixes 🧰\n\n- `service`: Disallow duplicate references to processors within a single pipeline (#6540)\n\n## v0.64.1\n\n### 🧰 Bug fixes 🧰\n\n- `loggingexporter`: Fix logging exporter to not mutate the data (#6420)\n\n## 0.64.0\n\n### 🛑 Breaking changes 🛑\n\n- `config`: Remove already deprecates `config.Service`. (#6395)\n- `pdata`: Change output of String() method of the following enum types to more a concise form: (#6251)\n  - plog.SeverityNumber\n  - ptrace.SpanKind\n  - ptrace.StatusCode\n\n- `config`: Remove already deprecates `config.Config`. (#6394)\n- `pdata`: Remove deprecated code from pdata (#6417)\n  - `p[trace|metric|log]otlp.[Request|Response]`\n  - `p[trace|metric|log]otlp.New[Request|Response]`\n  - `p[trace|metric|log]otlp.NewRequestFrom[Traces|Metrics|Logs]`\n  - `p[trace|metric|log]otlp.NewClient`\n  - `p[trace|metric|log]New[JSON|Proto][Marshaler|Unmarshaler]`\n\n- `extension`: Splitting ballast/zpages extension into their own modules (#6191)\n  The import path for the extension modules can now be accessed directly:\n  - `go.opentelemetry.io/collector/extension/ballastextension`\n  - `go.opentelemetry.io/collector/extension/zpagesextension`\n\n  If using one of these extensions, modify your Collector builder configuration to use `gomod` directly, such as:\n  - `gomod: go.opentelemetry.io/collector/extension/ballastextension v0.64.0`\n- `processor`: Splitting batch/memorylimiter processors into their own modules (#6188, #6192, #6193)\n  The import path for the processor modules can now be access directly:\n  - `go.opentelemetry.io/collector/processor/batchprocessor`\n  - `go.opentelemetry.io/collector/processor/memorylimiter`\n\n  If using this processor, modify your Collector builder configuration to use `gomod` directly, such as:\n  - `gomod: go.opentelemetry.io/collector/processor/batchprocessor v0.64.0`\n- `otlpreceiver`: Splitting otlp receiver into its own module (#6190)\n  The import path for the OTLP receiver can now be access directly:\n  - `go.opentelemetry.io/collector/receiver/otlpreceiver`\n\n  If using this receiver, modify your Collector builder configuration to use `gomod` directly, such as:\n  - `gomod: go.opentelemetry.io/collector/receiver/otlpreceiver v0.64.0`\n\n- `confmap`: Remove unused public member `sync.Mutex` from `confmap.Resolver`. (#6489)\n  This is an exception from the deprecation rule since this is not used anywhere and it is very unlikely that is used by external users.\n\n### 🚩 Deprecations 🚩\n\n- `config`: Deprecate multiple types and funcs in `config` package (#6422)\n  - config.ComponentID => component.ID\n  - config.Type => component.Type\n  - config.DataType => component.DataType\n  - config.[Traces|Metrics|Logs]DataType => component.DataType[Traces|Metrics|Logs]\n  - config.Receiver => component.ReceiverConfig\n  - config.UnmarshalReceiver => component.UnmarshalReceiverConfig\n  - config.Processor => component.ProcessorConfig\n  - config.UnmarshalProcessor => component.UnmarshalProcessorConfig\n  - config.Exporter => component.ExporterConfig\n  - config.UnmarshalExporter => component.UnmarshalExporterConfig\n  - config.Extension => component.ExtensionConfig\n  - config.UnmarshalExtension => component.UnmarshalExtensionConfig\n\n- `obsreport`: deprecate `obsreport.New[Receiver|Scraper|Processor|Exporter]` in favor of `obsreport.MustNew[Receiver|Scraper|Processor|Exporter]` (#6458)\n- `config/configgrpc`: Provide better helpers for configgrpc, consistent with confighttp (#6441)\n  - Deprecate `GRPCClientSettings.ToDialOptions` in favor of `GRPCClientSettings.ToClientConn`.\n  - Deprecate `GRPCServerSettings.ToServerOption` in favor of `GRPCServerSettings.ToServer`.\n\n- `featuregates`: Removing Gates being configurable externally to the Registry (#6167)\n  - Deprecate `Gate.ID` in favour of `Registry.RegisterID`\n  - Deprecate `Gate.Enabled` in favour of `Gate.IsEnabled()`\n  - Deprecate `Gate.Description` in favour of `WithRegisterDescription` to be used with `Registry.RegisterID`\n  - Deprecate `Registry.Register` in favour of `Registry.RegisterID`\n  - Deprecate `Registry.MustRegister` in favour of `Registry.MustRegisterID`\n\n\n### 💡 Enhancements 💡\n\n- `service/telemetry`: Allow to configure sampling config for logs. (#4554)\n- `featuregates`: Extend feature gate definition to include support for issue links and expected deprecated version (#6167)\n- `receiver/otlp`: Add warning when using unspecified (`0.0.0.0`) address on HTTP or gRPC servers (#6151)\n- `obsreport`: Instrument `obsreport.Exporter` metrics with otel-go (#6346)\n- `config`: Add validation for empty address [telemetry::metrics::address] (#5661)\n\n### 🧰 Bug fixes 🧰\n\n- `cgroups`: split line into exactly 3 parts while parsing /proc/{pid}/cgroup (#6389)\n- `cgroups`: Use int64 for cgroup v1 parsing (#6443)\n\n## v0.63.1\n\n### 🧰 Bug fixes 🧰\n\n- `service`: Fix running collector as a windows service. (#6433)\n\n## v0.63.0\n\n### 🛑 Breaking changes 🛑\n\n- `pdata`: JSON marshaler emits enums as ints per spec requirements. This may be a breaking change if receivers were not confirming with the spec. (#6338)\n- `confmap`: Remove deprecated `confmap.Conf.UnmarshalExact` API in 0.62.0 (#6315)\n- `pdata`: Remove API deprecated in 0.62.0 (#6314)\n  - Remove deprecated `pcommon.NewValueString`\n  - Remove deprecated `pcommon.Map.PutString`\n  - Remove deprecated `plog.SeverityNumberUndefined`\n  - Remove deprecated `p[metric|log|trace]otlp.RegisterServer`\n  - Remove deprecated `pmetric.[Default]?MetricDataPointFlags`\n  - Remove deprecated `pmetric.MetricAggregationTemporality*`\n  - Remove deprecated `pmetric.MetricTypeNone`\n  - Remove deprecated `pmetric.NumberDataPointValueTypeNone`\n  - Remove deprecated `pmetric.ExemplarValueTypeNone`\n  - Remove deprecated `pmetric.[New]?Buckets`\n  - Remove deprecated `pmetric.[New]?ValueAtQuantile`\n  - Remove deprecated `pmetric.[New]?ValueAtQuantileSlice`\n  - Remove deprecated `ptrace.[New]?SpanStatus`\n\n- `exporter`: Splitting otlp, otlphttp and logging exporters into their own modules (#6343)\n  The import path for these exporters can now be access directly:\n  - `go.opentelemetry.io/collector/exporter/loggingexporter`\n  - `go.opentelemetry.io/collector/exporter/otlpexporter`\n  - `go.opentelemetry.io/collector/exporter/otlphttpexporter`\n\n  If using these exporters, modify your Collector builder configuration to use `gomod` directly, such as:\n  - `gomod: go.opentelemetry.io/collector/exporter/otlpexporter v0.63.0`\n\n### 🚩 Deprecations 🚩\n\n- `overwritepropertiesconverter`: Deprecate `overwritepropertiesconverter`, only used by non builder distributions. (#6294)\n- `pdata`: Add `Export` prefix to `p[trace|metric|log]otlp.[Request|Response]` (#6365)\n  - Deprecate `p[trace|metric|log]otlp.[Request|Response]` in favor of `p[trace|metric|log]otlp.Export[Request|Response]`\n  - Deprecate `p[trace|metric|log]otlp.New[Request|Response]` in favor of `p[trace|metric|log]otlp.NewExport[Request|Response]`\n  - Deprecate `p[trace|metric|log]otlp.NewRequestFrom[Traces|Metrics|Logs]` in favor of\n    `p[trace|metric|log]otlp.NewExportRequestFrom[Traces|Metrics|Logs]`\n\n- `pdata`: Deprecate `p[trace|metric|log]otlp.NewClient` in favor of `p[trace|metric|log]otlp.NewGRPCClient` (#6350)\n- `exporter/logging`: Deprecate 'loglevel' in favor of 'verbosity' option (#5878)\n- `pdata`: Deprecate `New[JSON|Proto][Marshaler|Unmarshaler]` in favor of exposing the underlying structs (#6340)\n\n### 💡 Enhancements 💡\n\n- `pdata`: Introduce partial success fields in ExportResponse. (#5815, #5816, #6365)\n- `obsreport`: Instrument `obsreport.Receiver` metrics with otel-go (#6222)\n- `service/telemetry`: Move logging and tracing initialization to service/telemetry (#5564)\n- `confmap`: Fail fast when a resolver has URIs with unsupported schemes. (#6274)\n- `service`: Use the same `prometheus.Registry` for the OpenCensus and OpenTelemetry Go prometheus exporters to act as a bridge for internal telemetry (#6297)\n\n### 🧰 Bug fixes 🧰\n\n- `pdata`: Because of wrong deprecation/rename in proto, services still send the fake 1000 proto id. See https://github.com/open-telemetry/opentelemetry-proto/issues/431 (#6342)\n- `confmap`: When a sub-config implements Unmarshaler, do not reinitialized it unless necessary. (#6392)\n- `pdata`: Enable enums as ints for otlp messages, switch to jsoniter for responses. (#6345)\n- `collector`: Fixed collector service not cleaning up if it failed during Start (#6352)\n\n## v0.62.1 Beta\n\n- Fix support for new line in config URI location. (#6306)\n\n## v0.62.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Delete deprecated `go.opentelemetry.io/collector/service/featuregate`. (#6178)\n- Delete deprecated `pmetric.OptionalType`. (#6178)\n- Delete deprecated `ptrace.Span[Link]?.TraceStateStruct`. (#6178)\n- Delete deprecated `pcommon.NewValueBytesEmpty`. (#6178)\n- Delete deprecated `pmetric.MetricDataType`. (#6178)\n- Delete deprecated `pmetric.Metric.DataType()`. (#6178)\n- Delete deprecated `pmetric.NumberDataPoint.[Set]?[Int|Double]Val()`. (#6178)\n- Delete deprecated `pmetric.Exemplar.[Set]?[Int|Double]Val()`. (#6178)\n- Delete deprecated `p[metric|log|trace]otlp.[Client|Server]`. (#6178)\n- Delete deprecated pdata Clone methods. (#6178)\n- Delete deprecated `pcommon.Value` getter/setter methods with `Val` suffix. (#6178)\n- Delete deprecated `StringVal` and `SetStringVal` methods. (#6178)\n- Delete deprecated `ValueTypeString` method. (#6178)\n- Change AggregationTemporality.String to simpler, easier to read. (#6117)\n- Update `pcommon.ValueType.String` output to string representation of corresponding type identifiers. The following\n  values will be returned: (#6247)\n  - ValueTypeEmpty.String() -> \"Empty\"\n  - ValueTypeStr.String() -> \"Str\"\n  - ValueTypeBool.String() -> \"Bool\"\n  - ValueTypeInt.String() -> \"Int\"\n  - ValueTypeDouble.String() -> \"Double\"\n  - ValueTypeMap.String() -> \"Map\"\n  - ValueTypeSlice.String() -> \"Slice\"\n  - ValueTypeBytes.String() -> \"Bytes\"\n- Rename output of `[MetricType|NumberDataPointValueType|ExemplarValueType].String()` for zero values from `\"None\"` to\n  `\"Empty\"` (#6270)\n\n### 🚩 Deprecations 🚩\n\n- Deprecate `p[metric|log|trace]otlp.RegisterServer` in favor of `p[metric|log|trace]otlp.RegisterGRPCServer` (#6182)\n- Deprecate `pcommon.Map.PutString` in favor of `pcommon.Map.PutStr` (#6210)\n- Deprecate `pcommon.NewValueString` in favor of `pcommon.NewValueStr` (#6209)\n- Deprecate `pmetric.MetricAggregationTemporality` enum type in favor of `pmetric.AggregationTemporality` (#6253)\n- Deprecate `confmap.Conf.UnmarshalExact` in favor of `confmap.Conf.Unmarshal(.., WithErrorUnused)` (#6231)\n- Deprecate `pmetric.[Default]?MetricDataPointFlags` favor of `pmetric.[Default]?DataPointFlags` (#6259)\n- Deprecate `ptrace.[New]?SpanStatus` favor of `ptrace.[New]?Status` (#6258)\n- Deprecate `pmetric.[New]?Buckets` in favor of `pmetric.[New]?ExponentialHistogramDataPointBuckets` (#6261)\n- Deprecate `plog.SeverityNumberUndefined` in favor of `plog.SeverityNumberUnspecified` (#6269)\n- Deprecate `pmetric.[New]?ValueAtQuantile[Slice]?` in favor of `pmetric.[New]?SummaryDataPointValueAtQuantile[Slice]?` (#6262)\n- Deprecate enum zero constants ending with `None` (#6270)\n  - Deprecate `pmetric.MetricTypeNone` in favor of `pmetric.MetricTypeEmpty`\n  - Deprecate `pmetric.NumberDataPointValueTypeNone` in favor of `pmetric.NumberDataPointValueTypeEmpty`\n  - Deprecate `pmetric.ExemplarValueTypeNone` in favor of `pmetric.ExemplarValueTypeEmpty`\n\n### 💡 Enhancements 💡\n\n- Add config marshaler (#5566)\n- Add semantic conventions for specification v1.10-v1.13 (#6213)\n- `receiver/otlp`: Make logs related to gRCPC and HTTP server startup clearer (#6174)\n- Add prometheus metric prefix to Collector's own telemetry when using OpenTelemetry for internal telemetry (#6223)\n- `exporter/logging`: Apply consistent rendering of map values (#6244)\n- Add support in the confmap.Resolver to expand embedded config URIs inside configuration. (#6276)\n\n### 🧰 Bug fixes 🧰\n\n- Fixed bug where `telemetryInitializer` is not cleaned up when `newService` errors (#6239)\n\n## v0.61.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Change `ptrace.Span[Link]?.TraceState` signature to match `ptrace.Span[Link]?.TraceStateStruct` (#6085)\n- Delete deprecated `pmetric.NewMetricDataPointFlagsImmutable` func. (#6097)\n- Delete deprecated `pmetric.*DataPoint.[Set]FlagsImmutable()` funcs. (#6097)\n- Delete deprecated `config.Unmarshalable` interface. (#6084)\n- Delete deprecated `p[metric|log|trace].MarshalerSizer` interfaces (#6083)\n- Delete deprecated `pcommon.Map.Insert*` funcs. (#6088)\n- Delete deprecated `pcommon.Map.Upsert*` funcs. (#6088)\n- Delete deprecated `pcommon.Map.Update*` funcs. (#6088)\n- Change `pcommon.NewValueBytes` signature to match `pcommon.NewValueBytesEmpty`. (#6088)\n- Delete deprecated `pcommon.Empty[Trace|Span]ID`. (#6098)\n- Delete deprecated `pcommon.[Trace|Span]ID.Bytes()`. (#6098)\n- Delete deprecated `pcommon.New[Trace|Span]ID()`. (#6098)\n- Delete deprecated `pcommon.Value.SetBytesVal`. (#6088)\n- Delete deprecated `pmetric.Metric.SetDataType`. (#6095)\n- Delete deprecated `plog.LogRecord.[Set]FlagStruct` funcs. (#6100)\n- Delete deprecated `pcommon.ImmutableByteSlice` and `pcommon.NewImmutableByteSlice`. (#6107)\n- Delete deprecated `pcommon.ImmutableFloat64Slice` and `pcommon.NewImmutableFloat64Slice`. (#6107)\n- Delete deprecated `pcommon.ImmutableUInt64Slice` and `pcommon.NewImmutableUInt64Slice`. (#6107)\n- Delete deprecated `*DataPoint.SetBucketCounts` and `*DataPoint.SetExplicitBounds`. (#6108)\n\n### 🚩 Deprecations 🚩\n\n- Deprecate `go.opentelemetry.io/collector/service/featuregate` in favor of `go.opentelemetry.io/collector/featuregate`. (#6094)\n- Deprecate `pmetric.OptionalType`, unused enum type. (#6096)\n- Deprecate `ptrace.Span[Link]?.TraceStateStruct` in favor of `ptrace.Span[Link]?.TraceState` (#6085)\n- Deprecate `pcommon.NewValueBytesEmpty` in favor of `pcommon.NewValueBytes` that now has the same signature. (#6105)\n- Deprecate `pmetric.MetricDataType` and related constants in favor of `pmetric.MetricType`. (#6127)\n- Deprecate `pmetric.Metric.DataType()` in favor of `pmetric.Metric.Type()`. (#6127)\n- Deprecate `pmetric.NumberDataPoint.[Set]?[Int|Double]Val()` in favor of `pmetric.NumberDataPoint.[Set]?[Int|Double]Value()`. (#6134)\n- Deprecate `pmetric.Exemplar.[Set]?[Int|Double]Val()` in favor of `pmetric.Exemplar.[Set]?[Int|Double]Value()`. (#6134)\n- Deprecate `p[metric|log|trace]otlp.[Client|Server]` in favor of `p[metric|log|trace]otlp.GRPC[Client|Server]` (#6165)\n- Deprecate pdata Clone methods in favor of CopyTo for consistency with other pdata structs (#6164)\n  - `pmetric.Metrics.Clone` is deprecated in favor of `pmetric.Metrics.CopyTo`\n  - `ptrace.Traces.Clone` is deprecated in favor of `pmetric.Traces.CopyTo`\n  - `plog.Logs.Clone` is deprecated in favor of `plogs.Logs.CopyTo`\n- Rename all `pcommon.Value` getter/setter methods by removing `Val` suffix. (#6092)\n  - Old methods with `Val` suffix are deprecated.\n  - `StringVal` and `SetStringVal` are deprecated in favor of `Str` and `SetStr` to avoid implementing `fmt.Stringer` interface.\n  - Therefore, `ValueTypeString` is deprecated in favour of `ValueTypeStr` for consistency.\n\n### 💡 Enhancements 💡\n\n- Add AppendEmpty and EnsureCapacity method to primitive pdata slices (#6060)\n- Expose `AsRaw` and `FromRaw` `pcommon.Value` methods (#6090)\n- Convert `ValueTypeBytes` attributes in logging exporter (#6153)\n- service.name Resource attribute is added to Collector's own telemetry, defaults to the value of `BuildInfo.Command` and can be overridden in the config (#6152)\n- Updated how `telemetryInitializer` is created so it's instanced per Collector instance rather than global to the process (#6138)\n\n## v0.60.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Replace deprecated `*DataPoint.Flags()` with `*DataPoint.[Set]FlagsImmutable()`. (#6017)\n- Remove deprecated `MetricDataPointFlagsStruct` struct and `NewMetricDataPointFlagsStruct` func. (#6017)\n- Replace deprecated `MetricDataPointFlags` with `MetricDataPointFlagsImmutable`. (#6017)\n- Replace deprecated `LogRecord.[Set]Flags()` with `LogRecord.[Set]FlagsStruct()`. (#6007)\n- Remove deprecated components helpers funcs (#6006)\n  - `exporterhelper.New[Traces|Metrics|Logs]ExporterWithContext`\n  - `processorhelper.New[Traces|Metrics|Logs]ProcessorWithCreateSettings`\n  - `component.NewExtensionFactoryWithStabilityLevel`\n- Remove deprecated `pcommon.InvalidTraceID` and `pcommon.InvalidSpanID` funcs (#6008)\n- Remove deprecated `pcommon.Map` methods: `Update`, `Upsert`, `InsertNull` (#6019)\n\n### 🚩 Deprecations 🚩\n\n- Deprecate pmetric.Metric.SetDataType, in favor of empty setters for each type. (#5979)\n- Deprecate `p[metric|log|trace].MarshalerSizer` in favor of `p[metric|log|trace].MarshalSizer`. (#6033)\n- Deprecate `pcommon.Map.Update+` in favor of `pcommon.Map.Get` + `pcommon.Value.Set+` (#6013)\n- Deprecate `pcommon.Empty[Trace|Span]ID` in favor of `pcommon.New[Trace|Span]IDEmpty` (#6008)\n- Deprecate `pcommon.[Trace|Span]ID.Bytes` in favor direct conversion. (#6008)\n- Deprecate `pcommon.New[Trace|Span]ID` in favor direct conversion. (#6008)\n- Deprecate `MetricDataPointFlagsImmutable` type. (#6017)\n- Deprecate `*DataPoint.[Set]FlagsImmutable()` funcs in favor of `*DataPoint.[Set]Flags()`. (#6017)\n- Deprecate `LogRecord.FlagsStruct()` and `LogRecord.SetFlagsStruct()` in favor of `LogRecord.Flags()` and `LogRecord.SetFlags()`. (#6007)\n- Deprecate `config.Unmarshallable` in favor of `confmap.Unmarshaler`. (#6031)\n- Primitive slice wrapper are now mutable (#5971):\n  - `pcommon.ImmutableByteSlice` is deprecated in favor of `pcommon.ByteSlice`\n  - `pcommon.ImmutableFloat64Slice` is deprecated in favor of `pcommon.Float64Slice`\n  - `pcommon.ImmutableUInt64Slice` is deprecated in favor of `pcommon.UInt64Slice`\n  - Temporarily deprecate `pcommon.NewValueBytes` that will be replaced with `pcommon.NewValueBytesEmpty` in 0.60.0\n  - Deprecate `pcommon.Map.UpsertBytes` in favor of `pcommon.Map.PutEmptyBytes` (#6064)\n  - Deprecate `pcommon.Value.SetBytesVal` in favor of `pcommon.Value.SetEmptyBytesVal`\n  - Deprecate `pcommon.New[Slice|Map]FromRaw` functions in favor of `New[Slice|Map]().FromRaw` (#6045)\n- Deprecate `pcommon.Map.Insert*` methods (#6051)\n- Deprecate `pcommon.Map.Upsert*` methods in favor of `pcommon.Map.Put*` (#6064)\n- Deprecate `ptrace.TraceState` in favor of `pcommon.TraceState`. (#6052)\n  - `ptrace.Span.TraceState` in favor of `ptrace.Span.TraceStateStruct().AsRaw()`\n  - `ptrace.Span.SetTraceState` in favor of `ptrace.Span.TraceStateStruct().FromRaw`\n  - `ptrace.SpanLink.TraceState` in favor of `ptrace.SpanLink.TraceStateStruct().AsRaw()`\n  - `ptrace.SpanLink.SetTraceState` in favor of `ptrace.SpanLink.TraceStateStruct().FromRaw`\n  - `TraceStateStruct` is a temporary name that will be replaced back to `TraceState` in the next release.\n\n### 💡 Enhancements 💡\n\n- Add `skip-get-modules` builder flag to support isolated environment executions (#6009)\n  - Skip unnecessary Go binary path validation when the builder is used with `skip-compilation` and `skip-get-modules` flags (#6026)\n- Make the otlpreceiver support to use jsoniter to unmarshal JSON payloads. (#6040)\n- Add mapstructure hook function for confmap.Unmarshaler interface (#6029)\n- Add CopyTo and MoveTo methods to primitive slices (#6044)\n- Add support to unmarshalls bytes into plogs.Logs with `jsoniter` in jsonUnmarshaler (#6021)\n- Instead of exiting, `ocb` now generates a default Collector when no build configuration is supplied (#5752)\n\n### 🧰 Bug fixes 🧰\n\n- otlpjson: Correctly skip unknown JSON value types. (#6038)\n- Fix reading resource attributes from trace JSON. (#6023)\n\n## v0.59.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove deprecated fields/funcs from `service` (#5907)\n  - Remove `ConfigProviderSettings.Location`\n  - Remove `ConfigProviderSettings.MapProviders`\n  - Remove `ConfigProviderSettings.MapConverters`\n  - Remove `featuregate.Registry.MustAppy`\n- Remove deprecated funcs from `pdata` module. (#5911)\n  - Remove `pmetric.MetricDataPointFlags.String()`\n  - Remove `pmetric.NumberDataPoint.FlagsStruct()`\n  - Remove `pmetric.HistogramDataPoint.FlagsStruct()`\n  - Remove `pmetric.ExponentialHistogramDataPoint.FlagsStruct()`\n  - Remove `pmetric.SummaryDataPoint.FlagsStruct()`\n- Remove deprecated settings from `obsreport`, `ProcessorSettings.Level` and `ExporterSettings.Level` (#5918)\n- Replace `processorhelper.New[Traces|Metrics|Logs]Exporter` with `processorhelper.New[Traces|Metrics|Logs]ProcessorWithCreateSettings` definition (#5915)\n- Replace `exporterhelper.New[Traces|Metrics|Logs]Exporter` with `exporterhelper.New[Traces|Metrics|Logs]ExporterWithContext` definition (#5914)\n- Replace ``component.NewExtensionFactory`` with `component.NewExtensionFactoryWithStabilityLevel` definition (#5917)\n- Set TLS 1.2 as default for `min_version` for TLS configuration in case this property is not defined (affects servers). (#5956)\n\n### 🚩 Deprecations 🚩\n\n- Deprecate `processorhelper.New[Traces|Metrics|Logs]ProcessorWithCreateSettings` in favor of `processorhelper.New[Traces|Metrics|Logs]Exporter` (#5915)\n- Deprecates `LogRecord.Flags()` and `LogRecord.SetFlags()` in favor of `LogRecord.FlagsStruct()` and `LogRecord.SetFlagsStruct()`. (#5972)\n- Deprecate `exporterhelper.New[Traces|Metrics|Logs]ExporterWithContext` in favor of `exporterhelper.New[Traces|Metrics|Logs]Exporter` (#5914)\n- Deprecate `component.NewExtensionFactoryWithStabilityLevel` in favor of `component.NewExtensionFactory` (#5917)\n- Deprecate `plog.SeverityNumber[UPPERCASE]` constants (#5927)\n- Deprecate `pcommon.Map.InsertNull` method (#5955)\n- Deprecate FlagsStruct types (#5933):\n  - `MetricDataPointFlagsStruct` -> `MetricDataPointFlags`\n  - `NewMetricDataPointFlagsStruct` -> `NewMetricDataPointFlags`\n- Deprecate builder distribution flags, use configuration. (#5946)\n- Enforce naming conventions for Invalid[Trace|Span]ID: (#5969)\n  - Deprecate funcs `pcommon.InvalidTraceID` and `pcommon.InvalidSpanID` in favor of vars `pcommon.EmptyTraceID` and `pcommon.EmptySpanID`\n- Deprecate `Update` and `Upsert` methods of `pcommon.Map` (#5975)\n- Deprecated the current MetricDataPointFlags API.  The new API provides functions to check and set Flags. (#5999)\n  - `NumberDataPoint.Flags` -> `NumberDataPoint.FlagsImmutable`\n  - `HistogramDataPoint.Flags` -> `HistogramDataPoint.FlagsImmutable`\n  - `ExponentialHistogramDataPoint.Flags` -> `ExponentialHistogramDataPoint.FlagsImmutable`\n  - `SummaryDataPoint.Flags` -> `SummaryDataPoint.FlagsImmutable`\n  - `MetricDataPointFlags` -> `MetricDataPointFlagsImmutable`\n  - `NewMetricDataPointFlags` -> `MetricDataPointFlagsImmutable`\n\n### 💡 Enhancements 💡\n\n- Added `MarshalerSizer` interface to `ptrace`, `plog`, and `pmetric` packages. `NewProtoMarshaler` now returns a `MarshalerSizer` (#5929)\n- Add support to unmarshalls bytes into pmetric.Metrics with `jsoniter` in jsonUnmarshaler(#5433)\n- Add httpprovider to allow loading config files stored in HTTP (#5810)\n- Added `service.telemetry.traces.propagators` configuration to set propagators for collector's internal spans. (#5572)\n- Remove unnecessary duplicate code and allocations for reading enums in JSON. (#5928)\n- Add \"dist.build_tags\" configuration option to support passing go build flags to builder. (#5659)\n- Add an AsRaw func on the flags, lots of places to encode these flags. (#5934)\n- Change pdata generated types to use type definition instead of aliases. (#5936)\n  - Improves documentation, and makes code easier to read/understand.\n- Log `InstrumentationScope` attributes in `loggingexporter` (#5976)\n- Add `UpsertEmpty`, `UpsertEmptyMap` and `UpsertEmptySlice` methods to `pcommon.Map` (#5975)\n- Add `SetEmptyMapVal` and `SetEmptySliceVal` methods to `pcommon.Value` (#5975)\n\n### 🧰 Bug fixes 🧰\n\n- Fix reading scope attributes for trace JSON, remove duplicate code. (#5930)\n- otlpjson/trace: skip unknown fields instead of error. (#5931)\n- Fix bug in setting the correct collector state after a configuration change event. (#5830)\n- Fix json trace unmarshalling for numbers (#5924):\n  - Accept both string and number for float64.\n  - Accept both string and number for int32/uint32.\n  - Read uint64 numbers without converting from int64.\n- Fix persistent storage client not closing when shutting down (#6003)\n\n## v0.58.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove the InstrumentationLibrary to Scope translation (part of transition to OTLP 0.19). (#5819)\n  - This has a side effect that when sending JSON encoded telemetry using OTLP proto <= 0.15.0, telemetry will be dropped.\n- Require the storage to be explicitly set for the (experimental) persistent queue (#5784)\n- Remove deprecated `confighttp.HTTPClientSettings.ToClientWithHost` (#5803)\n- Remove deprecated component stability helpers (#5802):\n  - `component.WithTracesExporterAndStabilityLevel`\n  - `component.WithMetricsExporterAndStabilityLevel`\n  - `component.WithLogsExporterAndStabilityLevel`\n  - `component.WithTracesReceiverAndStabilityLevel`\n  - `component.WithMetricsReceiverAndStabilityLevel`\n  - `component.WithLogsReceiverAndStabilityLevel`\n  - `component.WithTracesProcessorAndStabilityLevel`\n  - `component.WithMetricsProcessorAndStabilityLevel`\n  - `component.WithLogsProcessorAndStabilityLevel`\n- ABI breaking change: `featuregate.Registry.Apply` returns error now.\n- Update minimum go version to 1.18 (#5795)\n- Remove deprecated `Flags` API from pdata (#5814)\n- Change `confmap.Provider` to return pointer to `Retrieved` (#5839)\n\n### 🚩 Deprecations 🚩\n\n- Deprecate duplicate settings in service.ConfigProvider, embed ResolverSettings (#5843)\n- Deprecate `featuregate.Registry.MustApply` in favor of `featuregate.Registry.Apply`. (#5801)\n- Deprecate the `component.Factory.StabilityLevel(config.DataType)` in favor of Stability per component (#5762):\n  - `component.ExporterFactory.TracesExporterStability`\n  - `component.ExporterFactory.MetricsExporterStability`\n  - `component.ExporterFactory.LogsExporterStability`\n  - `component.ProcessorFactory.TracesProcessorStability`\n  - `component.ProcessorFactory.MetricsProcessorStability`\n  - `component.ProcessorFactory.LogsProcessorStability`\n  - `component.ReceiverFactory.TracesReceiverStability`\n  - `component.ReceiverFactory.MetricsReceiverStability`\n  - `component.ReceiverFactory.LogsReceiverStability`\n- Deprecate `obsreport.ProcessorSettings.Level` and `obsreport.ExporterSettings.Level`, use MetricsLevel from CreateSettings (#5824)\n- Deprecate `processorhelper.New[Traces|Metrics|Logs]Processor` in favor of `processorhelper.New[Traces|Metrics|Logs]ProcessorWithCreateSettings` (#5833)\n- Deprecate MetricDataPointFlags.String(), no other pdata flags have this method (#5868)\n- Deprecates `FlagsStruct` in favor of `Flags` (#5842)\n  - `FlagsStruct` -> `Flags`\n- Deprecate `exporterhelper.New[Traces|Metrics|Logs]Exporter` in favor of `exporterhelper.New[Traces|Metrics|Logs]ExporterWithContext` (#5834)\n\n### 💡 Enhancements 💡\n\n- Enable persistent queue in the build by default (#5828)\n- Bump to opentelemetry-proto v0.19.0. (#5823)\n- Expose `Scope.Attributes` in pdata (#5826)\n- Remove unnecessary limitation on `pcommon.Value.Equal` that slices have only primitive values. (#5865)\n- Add support to handle 404, 405 http error code as permanent errors in OTLP exporter (#5827)\n- Enforce scheme name restrictions to all `confmap.Provider` implementations. (#5861)\n\n## v0.57.2 Beta\n\nSee the changelog for v0.57.0.\n\n## v0.57.1 Beta\n\nThis was a failed release.\n\n## v0.57.0 Beta\n\nThere isn't a valid core binary for this release. Use v0.57.2 instead.\n\n### 🛑 Breaking changes 🛑\n\n- Remove deprecated funcs/types from service related to `Config` (#5755)\n- Change`confighttp.ToClient` to accept a `component.Host` (#5737)\n- Remove deprecated funcs from pdata related to mutable slices (#5754)\n- Change the following deprecated component functions to ensure a stability level is set:\n  - `component.WithTracesExporter`\n  - `component.WithMetricsExporter`\n  - `component.WithLogsExporter`\n  - `component.WithTracesReceiver`\n  - `component.WithMetricsReceiver`\n  - `component.WithLogsReceiver`\n  - `component.WithTracesProcessor`\n  - `component.WithMetricsProcessor`\n  - `component.WithLogsProcessor`\n\n### 🚩 Deprecations 🚩\n\n- Deprecated the current Flag API.  The new API provides functions to check and set Flags (#5790) (#5602):\n  - `NumberDataPoint.Flags` -> `NumberDataPoint.FlagsStruct`\n  - `NumberDataPoint.SetFlags` -> `NumberDataPoint.FlagsStruct`\n  - `HistogramDataPoint.Flags` -> `HistogramDataPoint.FlagsStruct`\n  - `HistogramDataPoint.SetFlags` -> `HistogramDataPoint.FlagsStruct`\n  - `ExponentialHistogramDataPoint.Flags` -> `ExponentialHistogramDataPoint.FlagsStruct`\n  - `ExponentialHistogramDataPoint.SetFlags` -> `ExponentialHistogramDataPoint.FlagsStruct`\n  - `SummaryDataPoint.Flags` -> `SummaryDataPoint.FlagsStruct`\n  - `SummaryDataPoint.SetFlags` -> `SummaryDataPoint.FlagsStruct`\n  - `MetricDataPointFlags` -> `MetricDataPointFlagsStruct`\n  - `NewMetricDataPointFlags` -> `NewMetricDataPointFlagsStruct`\n  - `MetricDataPointFlagsNone` -> `MetricDataPointFlagsStruct.NoRecordedValue`\n  - `MetricDataPointFlagNoRecordedValue` -> `MetricDataPointFlagsStruct.NoRecordedValue`\n  - `MetricDataPointFlag`\n- Deprecate the following component functions added to ensure a stability level is set:\n  - `component.WithTracesExporterAndStabilityLevel` -> `component.WithTracesExporter`\n  - `component.WithMetricsExporterAndStabilityLevel` -> `component.WithMetricsExporter`\n  - `component.WithLogsExporterAndStabilityLevel` -> `component.WithLogsExporter`\n  - `component.WithTracesReceiverAndStabilityLevel` -> `component.WithTracesReceiver`\n  - `component.WithMetricsReceiverAndStabilityLevel` -> `component.WithMetricsReceiver`\n  - `component.WithLogsReceiverAndStabilityLevel` -> `component.WithLogsReceiver`\n  - `component.WithTracesProcessorAndStabilityLevel` -> `component.WithTracesProcessor`\n  - `component.WithMetricsProcessorAndStabilityLevel` -> `component.WithMetricsProcessor`\n  - `component.WithLogsProcessorAndStabilityLevel` -> `component.WithLogsProcessor`\n\n### 💡 Enhancements 💡\n\n- Make the in-memory and persistent queues more consistent (#5764)\n- `ocb` now exits with an error if it fails to load the build configuration. (#5731)\n- Deprecate `HTTPClientSettings.ToClientWithHost` (#5737)\n\n### 🧰 Bug fixes 🧰\n\n- Fix bug in ocb where flags did not take precedence. (#5726)\n\n## v0.56.0 Beta\n\n### 💡 Enhancements 💡\n\n- Add `linux-ppc64le` architecture to cross build tests in CI (#5645)\n- `client`: perform case insensitive lookups in case the requested metadata value isn't found (#5646)\n- `loggingexporter`: Decouple `loglevel` field from level of logged messages (#5678)\n- Expose `pcommon.NewSliceFromRaw` function (#5679)\n- `loggingexporter`: create the exporter's logger from the service's logger (#5677)\n- Add `otelcol_exporter_queue_capacity` metrics show the collector's exporter queue capacity (#5475)\n- Add support to handle 402, 413, 414, 431 http error code as permanent errors in OTLP exporter (#5685)\n\n### 🧰 Bug fixes 🧰\n\n- Fix Collector panic when disabling telemetry metrics (#5642)\n- Fix Collector panic when featuregate value is empty (#5663)\n- Fix confighttp.compression panic due to nil request.Body. (#5628)\n\n## v0.55.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove deprecated `config.ServiceTelemetry` (#5565)\n- Remove deprecated `config.ServiceTelemetryLogs` (#5565)\n- Remove deprecated `config.ServiceTelemetryMetrics` (#5565)\n\n### 🚩 Deprecations 🚩\n\n- Deprecate `service.ConfigServiceTelemetry`, `service.ConfigServiceTelemetryLogs`, and `service.ConfigServiceTelemetryMetrics` (#5565)\n- Deprecate the following component functions to ensure a stability level is set (#5580):\n  - `component.WithTracesExporter` -> `component.WithTracesExporterAndStabilityLevel`\n  - `component.WithMetricsExporter` -> `component.WithMetricsExporterAndStabilityLevel`\n  - `component.WithLogsExporter` -> `component.WithLogsExporterAndStabilityLevel`\n  - `component.WithTracesReceiver` -> `component.WithTracesReceiverAndStabilityLevel`\n  - `component.WithMetricsReceiver` -> `component.WithMetricsReceiverAndStabilityLevel`\n  - `component.WithLogsReceiver` -> `component.WithLogsReceiverAndStabilityLevel`\n  - `component.WithTracesProcessor` -> `component.WithTracesProcessorAndStabilityLevel`\n  - `component.WithMetricsProcessor` -> `component.WithMetricsProcessorAndStabilityLevel`\n  - `component.WithLogsProcessor` -> `component.WithLogsProcessorAndStabilityLevel`\n- Deprecate `Registry.Apply` in `service.featuregate` (#5660)\n\n### 💡 Enhancements 💡\n\n- Components stability levels are now logged. By default components which haven't defined their stability levels, or which are\n  unmaintained, deprecated or in development will log a message. (#5580)\n- `exporter/logging`: Skip \"bad file descriptor\" sync errors (#5585)\n\n### 🧰 Bug fixes 🧰\n\n- Fix initialization of the OpenTelemetry MetricProvider. (#5571)\n- Set log level for `undefined` stability level to debug. (#5635)\n\n## v0.54.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove deprecated `GetLogger`. (#5504)\n- Remove deprecated `configtest.LoadConfigMap` (#5505)\n- Remove deprecated `config.Map` (#5505)\n- Remove deprecated `config.MapProvider` (#5505)\n- Remove deprecated `config.MapConverter` (#5505)\n- Remove deprecated `config.Received` (#5505)\n- Remove deprecated `config.CloseFunc` (#5505)\n- Deprecated `pcommon.Value.NewValueBytes` is brought back taking `pcommon.ImmutableByteSlice` as an argument instead of `[]byte` (#5299)\n\n### 🚩 Deprecations 🚩\n\n- Use immutable slices for primitive types slices to restrict mutations. (#5299)\n  - `Value.NewValueMBytes` func is deprecated in favor of `Value.NewValueBytes` func that takes\n    `ImmutableByteSlice` instead of `[]byte`\n  - `Value.SetMBytesVal` func is deprecated in favor of `Value.SetBytesVal` func that takes\n    `pcommon.ImmutableByteSlice` instead of []byte.\n  - `Value.BytesVal` func is deprecated in favor of `Value.BytesVal` func that returns `pcommon.ImmutableByteSlice`\n    instead of []byte.\n  - `<HistogramDataPoint|Buckets>.SetMBucketCounts` funcs are deprecated in favor of\n    `<HistogramDataPoint|Buckets>.SetBucketCounts` funcs that take `pcommon.ImmutableUInt64Slice` instead of []uint64.\n  - `<HistogramDataPoint|Buckets>.MBucketCounts` funcs are deprecated in favor of\n    `<HistogramDataPoint|Buckets>.BucketCounts` funcs that return `pcommon.ImmutableUInt64Slice` instead of []uint64.\n  - `HistogramDataPoint.SetMExplicitBounds` func is deprecated in favor of `HistogramDataPoint.SetExplicitBounds` func\n    that takes `pcommon.ImmutableFloat64Slice` instead of []float64.\n  - `HistogramDataPoint.MExplicitBounds` func func is deprecated in favor of `HistogramDataPoint.ExplicitBounds`\n    returns `pcommon.ImmutableFloat64Slice` instead of []float64.\n\n### 💡 Enhancements 💡\n\n- Deprecate `HTTPClientSettings.ToClient` in favor of `HTTPClientSettings.ToClientWithHost` (#5584)\n- Use OpenCensus `metric` package for process metrics instead of `stats` package (#5486)\n- Update OTLP to v0.18.0 (#5530)\n- Log histogram min/max fields with `logging` exporter (#5520)\n\n### 🧰 Bug fixes 🧰\n\n- Update sum field of exponential histograms to make it optional (#5530)\n- Remove redundant extension shutdown call (#5532)\n- Refactor pipelines builder, fix some issues (#5512)\n  - Unconfigured receivers are not identified, this was not a real problem in final binaries since the validation of the config catch this.\n  - Allow configurations to contain \"unused\" receivers. Receivers that are configured but not used in any pipeline, this was possible already for exporters and processors.\n  - Remove the enforcement/check that Receiver factories create the same instance for the same config.\n\n## v0.53.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove deprecated `componenterror` package. (#5420)\n- Remove deprecated `config.MapConverterFunc`. (#5419)\n- Remove `AddCollectorVersionTag`, enabled for long time already. (#5471)\n\n### 🚩 Deprecations 🚩\n\n- Move `config.Map` to its own package `confmap` which does not depend on any component concept (#5237)\n  - `config.Map` -> `confmap.ConfMap`\n  - `config.MapProvider` -> `confmap.Provider`\n  - `config.Received` -> `confmap.Received`\n  - `config.NewReceivedFromMap` -> `confmap.NewReceived`\n  - `config.CloseFunc` -> `confmap.CloseFunc`\n  - `config.ChangeEvent` -> `confmap.ChangeEvent`\n  - `config.MapConverter` -> `confmap.Converter`\n  - Package `envmapprovider` -> `envprovider`\n  - Package `filemapprovider` -> `fileprovider`\n  - Package `yamlmapprovider` -> `yamlprovider`\n  - Package `expandmapconverter` -> `expandconverter`\n  - Package `filemapprovider` -> `fileprovider`\n  - Package `overwritepropertiesmapconverter` -> `overwritepropertiesconverter`\n- Deprecate `component.ExtensionDefaultConfigFunc` in favor of `component.ExtensionCreateDefaultConfigFunc` (#5451)\n- Deprecate `confmap.Received.AsMap` in favor of `confmap.Received.AsConf` (#5465)\n- Deprecate `confmap.Conf.Set`, not used anywhere for the moment (#5485)\n\n### 💡 Enhancements 💡\n\n- Move `service.mapResolver` to `confmap.Resolver` (#5444)\n- Add `linux-arm` architecture to cross build tests in CI (#5472)\n\n### 🧰 Bug fixes 🧰\n\n- Fixes the \"service.version\" label value for internal metrics, always was \"latest\" in core/contrib distros. (#5449).\n- Send correct batch stats when SendBatchMaxSize is set (#5385)\n- TLS `MinVersion` and `MaxVersion` defaults will be handled by `crypto/tls` (#5480)\n\n## v0.52.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove `configunmarshaler.Unmarshaler` interface, per deprecation comment (#5348)\n- Remove deprecated pdata funcs/structs from v0.50.0 (#5345)\n- Remove deprecated pdata getters and setters of primitive slice values: `Value.BytesVal`, `Value.SetBytesVal`,\n  `Value.UpdateBytes`, `Value.InsertBytes`, `Value.UpsertBytes`, `<HistogramDataPoint|Buckets>.BucketCounts`,\n  `<HistogramDataPoint|Buckets>.SetBucketCounts`, `HistogramDataPoint.ExplicitBounds`,\n  `HistogramDataPoint.SetExplicitBounds` (#5347)\n- Remove deprecated featuregate funcs/structs from v0.50.0 (#5346)\n- Remove access to deprecated members of the config.Retrieved struct (#5363)\n- Replace usage of `config.MapConverterFunc` with `config.MapConverter` (#5382)\n\n### 🚩 Deprecations 🚩\n\n- Deprecate `config.Config` and `config.Service`, use `service.Config*` (#4608)\n- Deprecate `componenterror` package, move everything to `component` (#5383)\n- `pcommon.Value.NewValueBytes` is deprecated in favor of `Value.NewValueMBytes` in preparation of migration to\n  immutable slices (#5367)\n\n### 💡 Enhancements 💡\n\n- Update OTLP to v0.17.0 (#5335)\n- Add optional min/max fields to histograms (#5399)\n- User-defined Resource attributes can be specified under `service.telemetry.resource`\n  configuration key and will be included as metric labels for own telemetry.\n  If `service.instance.id` is not specified it will be auto-generated. Previously\n  `service.instance.id` was always auto-generated, so the default of the new\n  behavior matches the old behavior. (#5402)\n\n## v0.51.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove deprecated model module, everything is available in `pdata` and `semconv`. (#5281)\n  - Old versions of the module are still available, but no new versions will be released.\n- Remove deprecated LogRecord.Name field. (#5202)\n\n### 🚩 Deprecations 🚩\n\n- In preparation of migration to immutable slices for primitive type items, the following methods are renamed (#5344)\n  - `Value.BytesVal` func is deprecated in favor of `Value.MBytesVal`.\n  - `Value.SetBytesVal` func is deprecated in favor of `Value.SetMBytesVal`.\n  - `Value.UpdateBytes` func is deprecated in favor of `Value.UpdateMBytes`.\n  - `Value.InsertBytes` func is deprecated in favor of `Value.InsertMBytes`.\n  - `Value.UpsertBytes` func is deprecated in favor of `Value.UpsertMBytes`.\n  - `<HistogramDataPoint|Buckets>.BucketCounts` funcs are deprecated in favor of\n    `<HistogramDataPoint|Buckets>.MBucketCounts`.\n  - `<HistogramDataPoint|Buckets>.SetBucketCounts` funcs are deprecated in favor of\n    `<HistogramDataPoint|Buckets>.SetMBucketCounts`.\n  - `HistogramDataPoint.ExplicitBounds` func is deprecated in favor of `HistogramDataPoint.MExplicitBounds`.\n  - `HistogramDataPoint.SetExplicitBounds` func is deprecated in favor of `HistogramDataPoint.SetMExplicitBounds`.\n\n### 💡 Enhancements 💡\n\n- `pdata`: Expose `pcommon.NewSliceFromRaw` and `pcommon.Slice.AsRaw` functions (#5311)\n\n### 🧰 Bug fixes 🧰\n\n- Fix Windows Event Logs ignoring user-specified logging options (#5298)\n\n## v0.50.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove pdata deprecated funcs from 2 versions (v0.48.0) ago. (#5219)\n- Remove non pdata deprecated funcs/structs (#5220)\n- `pmetric.Exemplar.ValueType()` now returns new type `ExemplarValueType` (#5233)\n- Remove deprecated `Delete` pdata func in favor of `pdata.Remove` from (v0.47.0). (#5307)\n\n### 🚩 Deprecations 🚩\n\n- Deprecate `configunmarshaler` package, move it to internal (#5151)\n- Deprecate all API in `model/semconv`. The package is moved to a new `semconv` module (#5196)\n- Deprecate access to `config.Retrieved` fields, use the newly added funcs to interact with the internal fields (#5198)\n- Deprecate `p<signal>otlp.Request.Set<Logs|Metrics|Traces>` (#5234)\n  - `plogotlp.Request.SetLogs` func is deprecated in favor of `plogotlp.NewRequestFromLogs`\n  - `pmetricotlp.Request.SetMetrics` func is deprecated in favor of `pmetricotlp.NewRequestFromMetrics`\n  - `ptraceotlp.Request.SetTraces` func is deprecated in favor of `ptraceotlp.NewRequestFromTraces`\n- `pmetric.NumberDataPoint.ValueType()` now returns new type `NumberDataPointValueType` (#5233)\n  - `pmetric.MetricValueType` is deprecated in favor of `NumberDataPointValueType`\n  - `pmetric.MetricValueTypeNone` is deprecated in favor of `NumberDataPointValueTypeNone`\n  - `pmetric.MetricValueTypeInt` is deprecated in favor of `NumberDataPointValueTypeInt`\n  - `pmetric.MetricValueTypeDouble` is deprecated in favor of `NumberDataPointValueTypeDouble`\n- Deprecate `plog.LogRecord.SetName()` function (#5230)\n- Deprecate global `featuregate` funcs in favor of `GetRegistry` and a public `Registry` type (#5160)\n\n### 💡 Enhancements 💡\n- Add `jsoniter` Unmarshaller (#4817)\n\n- Extend config.Map.Unmarshal hook to check map key string to any TextUnmarshaler not only ComponentID (#5244)\n- Collector will no longer print error with stack trace when the collector is shutdown due to a context cancel. (#5258)\n\n### 🧰 Bug fixes 🧰\n- Fix translation from otlp.Request to pdata representation, changes to the returned pdata not all reflected to the otlp.Request (#5197)\n- `exporterhelper` now properly consumes any remaining items on stop (#5203)\n- `pdata`: Fix copying of `Value` with `ValueTypeBytes` type (#5267)\n- `pdata`: Fix copying of metric fields of primitive items slice type (#5271)\n\n## v0.49.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove deprecated structs/funcs from previous versions (#5131)\n- Do not set TraceProvider to global otel (#5138)\n- Remove deprecated funcs from otlpgrpc (#5144)\n- Add Scheme to MapProvider interface (#5068)\n- Do not set MeterProvider to global otel (#5146)\n- Make `InstrumentationLibrary<signal>ToScope` helper functions unexported (#5164)\n- Remove Log's \"ShortName\" from logging exporter output (#5172)\n- `exporter/otlp`: Retry RESOURCE_EXHAUSTED only if the server returns RetryInfo (#5147)\n\n### 🚩 Deprecations 🚩\n\n- All pdata related APIs from model (model/pdata, model/otlp and model/otlpgrpc) are deprecated in\n  favor of packages in the new pdata module separated by telemetry signal type (#5168)\n  - `model/pdata`, `model/otlp` -> `pdata/pcommon`, `pdata/plog`, `pdata/pmetric`, `pdata/ptrace`\n  - `model/otlpgrpc` -> `pdata/plog/plogotlp`, `pdata/pmetric/pmetricotlp`, `pdata/ptrace/ptraceotlp`\n- Deprecate configmapprovider package, replace with mapconverter (#5167)\n- Deprecate `service.MustNewConfigProvider` and `service.MustNewDefaultConfigProvider`in favor of `service.NewConfigProvider` (#4936)\n\n### 💡 Enhancements 💡\n\n- OTLP HTTP receiver will use HTTP/2 over TLS if client supports it (#5109)\n- Add `ObservedTimestamp` field to `pdata.LogRecord` (#5171)\n\n### 🧰 Bug fixes 🧰\n\n- Setup the correct meter provider if telemetry.useOtelForInternalMetrics featuregate enabled (#5146)\n- Fix pdata.Value.asRaw() to correctly return elements of Slice and Map type (#5153)\n- Update pdata.Slice.asRaw() to return raw representation of Slice and Map elements (#5157)\n- The codepath through the OTLP receiver for gRPC was not translating the InstrumentationLibrary* to Scope* (#5189)\n\n## v0.48.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove deprecated `consumerhelper` package (#5028)\n- Remove pdata `InternalRep` deprecated funcs (#5018)\n- Remove service/defaultcomponents deprecated package (#5019)\n- Remove deprecated UseOpenTelemetryForInternalMetrics (#5026)\n- Change outcome of `pdata.Value.MapVal()` and `pdata.Value.SliceVal()` functions misuse. In case of\n  type mismatch, they now return an invalid zero-initialized instance instead of a detached\n  collection (#5034)\n- OTLP JSON field changes following upgrade to OTLP v0.15.0:\n  - \"instrumentationLibraryLogs\" is now \"scopeLogs\"\n  - \"instrumentationLibraryMetrics\" is now \"scopeMetrics\"\n  - \"instrumentationLibrarySpans\" is now \"scopeSpans\"\n  - \"instrumentationLibrary\" is now \"scope\"\n- AsString for pdata.Value now returns the JSON-encoded string of floats. (#4934)\n\n### 🚩 Deprecations 🚩\n\n- Move MapProvider to config, split providers in their own package (#5030)\n- API related to `pdata.AttributeValue` is deprecated in favor of `pdata.Value` (#4978)\n  - `pdata.AttributeValue` struct is deprecated in favor of `pdata.Value`\n  - `pdata.AttributeValueType` type is deprecated in favor of `pdata.ValueType`\n  - `pdata.AttributeValueType...` constants are deprecated in favor of `pdata.ValueType...`\n  - `pdata.NewAttributeValue...` funcs are deprecated in favor of `pdata.NewValue...`\n- Deprecate featureflags.FlagValue.SetSlice, unnecessary public (#5053)\n- Remove \"Attribute\" part from common pdata collections names (#5001)\n  - Deprecate `pdata.AttributeMap` struct in favor of `pdata.Map`\n  - Deprecate `pdata.NewAttributeMap` func in favor of `pdata.NewMap`\n  - Deprecate `pdata.NewAttributeMapFromMap` func in favor of `pdata.NewMapFromRaw`\n  - Deprecate `pdata.AttributeValueSlice` struct in favor of `pdata.Slice`\n  - Deprecate `pdata.NewAttributeValueSlice` func in favor of `pdata.NewSlice`\n- Deprecate LogRecord.Name(), it was deprecated in the data model (#5054)\n- Rename `Array` type of `pdata.Value` to `Slice` (#5066)\n  - Deprecate `pdata.AttributeValueTypeArray` type in favor of `pdata.ValueTypeSlice`\n  - Deprecate `pdata.NewAttributeValueArray` func in favor of `pdata.NewValueSlice`\n- Deprecate global flag in `featuregates` (#5060)\n- Deprecate last funcs/structs in componenthelper (#5069)\n- Change structs in otlpgrpc to follow standard go encoding interfaces (#5062)\n  - Deprecate `UnmarshalJSON[Traces|Metrics|Logs][Request|Response]` in favor of `UnmarshalJSON`.\n  - Deprecate `[Traces|Metrics|Logs][Request|Response].Marshal` in favor of `MarshalProto`.\n  - Deprecate `UnmarshalJSON[Traces|Metrics|Logs][Request|Response]` in favor of `UnmarshalProto`.\n- Deprecating following pdata methods/types following OTLP v0.15.0 upgrade (#5076):\n      - InstrumentationLibrary is now InstrumentationScope\n      - NewInstrumentationLibrary is now NewInstrumentationScope\n      - InstrumentationLibraryLogsSlice is now ScopeLogsSlice\n      - NewInstrumentationLibraryLogsSlice is now NewScopeLogsSlice\n      - InstrumentationLibraryLogs is now ScopeLogs\n      - NewInstrumentationLibraryLogs is now NewScopeLogs\n      - InstrumentationLibraryMetricsSlice is now ScopeMetricsSlice\n      - NewInstrumentationLibraryMetricsSlice is now NewScopeMetricsSlice\n      - InstrumentationLibraryMetrics is now ScopeMetrics\n      - NewInstrumentationLibraryMetrics is now NewScopeMetrics\n      - InstrumentationLibrarySpansSlice is now ScopeSpansSlice\n      - NewInstrumentationLibrarySpansSlice is now NewScopeSpansSlice\n      - InstrumentationLibrarySpans is now ScopeSpans\n      - NewInstrumentationLibrarySpans is now NewScopeSpans\n\n### 💡 Enhancements 💡\n\n- Add semconv definitions for v1.9.0 (#5090)\n- Change outcome of `pdata.Metric.<Gauge|Sum|Histogram|ExponentialHistogram>()` functions misuse.\n  In case of type mismatch, they don't panic right away but return an invalid zero-initialized\n  instance for consistency with other OneOf field accessors (#5035)\n- Update OTLP to v0.15.0 (#5064)\n- Adding support for transition from older versions of OTLP to OTLP v0.15.0 (#5085)\n\n### 🧰 Bug fixes 🧰\n\n- Add missing files for semconv definitions v1.7.0 and v1.8.0 (#5091)\n- The `featuregates` were not configured from the \"--feature-gates\" flag on windows service (#5060)\n- Fix Semantic Convention Schema URL definition for 1.5.0 and 1.6.1 versions (#5103)\n\n## v0.47.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove `Type` funcs in pdata (#4933)\n- Remove all deprecated funcs/structs from v0.46.0 (#4995)\n\n### 🚩 Deprecations 🚩\n\n- pdata: deprecate funcs working with InternalRep (#4957)\n- Deprecate `pdata.AttributeMap.Delete` in favor of `pdata.AttributeMap.Remove` (#4914)\n- Deprecate consumerhelper, move helpers to consumer (#5006)\n\n### 💡 Enhancements 💡\n\n- Add `pdata.AttributeMap.RemoveIf`, which is a more performant way to remove multiple keys (#4914)\n- Add `pipeline` key with pipeline identifier to processor loggers (#4968)\n- Add a new yaml provider, allows providing yaml bytes (#4998)\n\n### 🧰 Bug fixes 🧰\n\n- Collector `Run` will now exit when a context cancels (#4954)\n- Add missing droppedAttributesCount to pdata generated resource (#4979)\n- Collector `Run` will now set state to `Closed` if startup fails (#4974)\n\n## v0.46.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Change otel collector to enable open telemetry metrics through feature gate instead of a constant (#4912)\n- Remove support for legacy otlp/http port. (#4916)\n- Remove deprecated funcs in pdata (#4809)\n- Remove deprecated Retrieve funcs/calls (#4922)\n- Remove deprecated NewConfigProvider funcs (#4937)\n\n### 🚩 Deprecations 🚩\n\n- Deprecated funcs `config.DefaultConfig`, `confighttp.DefaultHTTPSettings`, `exporterhelper.DefaultTimeoutSettings`,\n  `exporthelper.DefaultQueueSettings`, `exporterhelper.DefaultRetrySettings`, `testcomponents.DefaultFactories`, and\n  `scraperhelper.DefaultScraperControllerSettings` in favour for their `NewDefault` method to adhere to contribution guidelines (#4865)\n- Deprecated funcs `componenthelper.StartFunc`, `componenthelper.ShutdownFunc` in favour of `component.StartFunc` and `component.ShutdownFunc` (#4803)\n- Move helpers from extensionhelper to component (#4805)\n  - Deprecated `extensionhelper.CreateDefaultConfig` in favour of `component.ExtensionDefaultConfigFunc`\n  - Deprecated `extensionhelper.CreateServiceExtension` in favour of `component.CreateExtensionFunc`\n  - Deprecated `extensionhelper.NewFactory` in favour of `component.NewExtensionFactory`\n- Move helpers from processorhelper to component (#4889)\n  - Deprecated `processorhelper.CreateDefaultConfig` in favour of `component.ProcessorDefaultConfigFunc`\n  - Deprecated `processorhelper.WithTraces` in favour of `component.WithTracesProcessor`\n  - Deprecated `processorhelper.WithMetrics` in favour of `component.WithMetricsProcessor`\n  - Deprecated `processorhelper.WithLogs` in favour of `component.WithLogsProcessor`\n  - Deprecated `processorhelper.NewFactory` in favour of `component.NewProcessorFactory`\n- Move helpers from exporterhelper to component (#4899)\n  - Deprecated `exporterhelper.CreateDefaultConfig` in favour of `component.ExporterDefaultConfigFunc`\n  - Deprecated `exporterhelper.WithTraces` in favour of `component.WithTracesExporter`\n  - Deprecated `exporterhelper.WithMetrics` in favour of `component.WithMetricsExporter`\n  - Deprecated `exporterhelper.WithLogs` in favour of `component.WithLogsExporter`\n  - Deprecated `exporterhelper.NewFactory` in favour of `component.NewExporterFactory`\n- Move helpers from receiverhelper to component (#4891)\n  - Deprecated `receiverhelper.CreateDefaultConfig` in favour of `component.ReceiverDefaultConfigFunc`\n  - Deprecated `receiverhelper.WithTraces` in favour of `component.WithTracesReceiver`\n  - Deprecated `receiverhelper.WithMetrics` in favour of `component.WithMetricsReceiver`\n  - Deprecated `receiverhelper.WithLogs` in favour of `component.WithLogsReceiver`\n  - Deprecated `receiverhelper.NewFactory` in favour of `component.NewReceiverFactory`\n\n### 💡 Enhancements 💡\n\n- Add validation to check at least one endpoint is specified in otlphttpexporter's configuration (#4860)\n- Implement default client authenticators (#4837)\n\n## 🧰 Bug fixes 🧰\n\n- Initialized logger with collector to avoid potential race condition panic on `Shutdown` (#4827)\n- In addition to traces, now logs and metrics processors will start the memory limiter.\n  Added thread-safe logic so only the first processor can launch the `checkMemLimits` go-routine and the last processor\n  that calls shutdown to terminate it; this is done per memory limiter instance.\n  Added memory limiter factory to cache initiated object and be reused by similar config. This guarantees a single\n  running `checkMemLimits` per config (#4886)\n- Resolved race condition in collector when calling `Shutdown` (#4878)\n\n## v0.45.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove deprecated funcs in configtelemetry (#4808)\n- `otlphttp` and `otlp` exporters enable gzip compression by default (#4632)\n\n### 🚩 Deprecations 🚩\n\n- Deprecate `service/defaultcomponents` go package (#4622)\n- Deprecate `pdata.NumberDataPoint.Type()` and `pdata.Exemplar.Type()` in favor of `NumberDataPoint.ValueType()` and\n  `Exemplar.ValueType()` (#4850)\n\n### 💡 Enhancements 💡\n\n- Reject invalid queue size exporterhelper (#4799)\n- Transform configmapprovider.Retrieved interface to a struct (#4789)\n- Added feature gate summary to zpages extension (#4834)\n- Add support for reloading TLS certificates (#4737)\n\n### 🧰 Bug fixes 🧰\n\n- `confighttp`: Allow CORS requests with configured auth (#4869)\n\n## v0.44.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Updated to OTLP 0.12.0. Deprecated traces and metrics messages that existed\n  in 0.11.0 are no longer converted to the messages and fields that replaced the deprecated ones.\n  Received deprecated messages and fields will be now ignored. In OTLP/JSON in the\n  instrumentationLibraryLogs object the \"logs\" field is now named \"logRecords\" (#4724)\n- Deprecate `service.NewWindowsService`, add `service.NewSvcHandler` (#4783).\n\n### 🚩 Deprecations 🚩\n\n- Deprecate `service.NewConfigProvider`, and a new version `service.MustNewConfigProvider` (#4734).\n\n### 💡 Enhancements 💡\n\n- Invalid requests now return an appropriate unsupported (`405`) or method not allowed (`415`) response (#4735)\n- `client.Info`: Add Host property for Metadata (#4736)\n\n## v0.43.1 Beta\n\n### 🧰 Bug fixes 🧰\n\n- ExpandStringValues function support to map[string]interface{} (#4748)\n\n## v0.43.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Change configmapprovider.Provider to accept a location for retrieve (#4657)\n- Change Properties Provider to be a Converter (#4666)\n- Define a type `WatcherFunc` for onChange func instead of func pointer (#4656)\n- Remove deprecated `configtest.LoadConfig` and `configtest.LoadConfigAndValidate` (#4659)\n- Move service.ConfigMapConverterFunc to config.MapConverterFunc (#4673)\n  - Add context to config.MapConverterFunc (#4678)\n- Builder: the skip compilation should only be supplied as a CLI flag. Previously, it was possible to specify that in the YAML file, contrary to the original intention (#4645)\n- Builder: Remove deprecated config option module::core (#4693)\n- Remove deprecate flags --metrics-level and --metrics-addr (#4695)\n  - Usages of `--metrics-level={VALUE}` can be replaced by `--set=service.telemetry.metrics.level={VALUE}`;\n  - Usages of `--metrics-addr={VALUE}` can be replaced by `--set=service.telemetry.metrics.address={VALUE}`;\n- Updated confighttp `ToClient` to support passing telemetry settings for instrumenting otlphttp exporter(#4449)\n- Remove support to some arches and platforms from `ocb` (opentelemetry-collector-builder) (#4710)\n- Remove deprecated legacy path (\"v1/trace\") support for otlp http receiver (#4720)\n- Change the `service.NewDefaultConfigProvider` to accept a slice of location strings (#4727).\n\n### 🚩 Deprecations 🚩\n\n- Deprecate `configtelemetry.Level.Set()` (#4700)\n\n### 🧰 Bug fixes 🧰\n\n- Ensure Windows path (e.g: C:) is recognized as a file path (#4726)\n- Fix structured logging issue for windows service (#4686)\n\n### 💡 Enhancements 💡\n\n- Expose experimental API `configmapprovider.NewExpandConverter()` (#4672)\n- `service.NewConfigProvider`: copy slice argument, disallow changes from caller to the input slice (#4729)\n- `confighttp` and `configgrpc`: New config option `include_metadata` to persist request metadata/headers in `client.Info.Metadata` (experimental) (#4547)\n- Remove expand cases that cannot happen with config.Map (#4649)\n- Add `max_request_body_size` to confighttp.HTTPServerSettings (#4677)\n- Move `compression.go` into `confighttp.go` to internalize functions in `compression.go` file. (#4651)\n  - create `configcompression` package to manage compression methods in `confighttp` and `configgrpc`\n- Add support for cgroupv2 memory limit (#4654)\n- Enable end users to provide multiple files for config location (#4727)\n\n## v0.42.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove `configmapprovider.NewInMemory()` (#4507)\n- Disallow direct implementation of `configmapprovider.Retrieved` (#4577)\n- `configauth`: remove interceptor functions from the ServerAuthenticator interface (#4583)\n- Replace ConfigMapProvider and ConfigUnmarshaler in collector settings by one simpler ConfigProvider (#4590)\n- Remove deprecated consumererror.Combine (#4597)\n- Remove `configmapprovider.NewDefault`, `configmapprovider.NewExpand`, `configmapprovider.NewMerge` (#4600)\n  - The merge functionality is now embedded into `service.NewConfigProvider` (#4637).\n- Move `configtest.LoadConfig` and `configtest.LoadConfigAndValidate` to `servicetest` (#4606)\n- Builder: Remove deprecated `include-core` flag (#4616)\n- Collector telemetry level must now be accessed through an atomic function. (#4549)\n\n### 💡 Enhancements 💡\n\n- `confighttp`: add client-side compression support. (#4441)\n  - Each exporter should remove `compression` field if they have and should use `confighttp.HTTPClientSettings`\n- Allow more zap logger configs: `disable_caller`, `disable_stacktrace`, `output_paths`, `error_output_paths`, `initial_fields` (#1048)\n- Allow the custom zap logger encoding (#4532)\n- Collector self-metrics may now be configured through the configuration file. (#4069)\n  - CLI flags for configuring self-metrics are deprecated and will be removed\n    in a future release.\n  - `service.telemetry.metrics.level` and `service.telemetry.metrics.address`\n    should be used to configure collector self-metrics.\n- `configauth`: add helpers to create new server authenticators. (#4558)\n- Refactor `configgrpc` for compression methods (#4624)\n- Add an option to allow `config.Map` conversion in the `service.ConfigProvider` (#4634)\n- Added support to expose gRPC framework's logs as part of collector logs (#4501)\n- Builder: Enable unmarshal exact to help finding hard to find typos #4644\n\n### 🧰 Bug fixes 🧰\n\n- Fix merge config map provider to close the watchers (#4570)\n- Fix expand map provider to call close on the base provider (#4571)\n- Fix correct the value of `otelcol_exporter_send_failed_requests` (#4629)\n- `otlp` receiver: Fix legacy port cfg value override and HTTP server starting bug (#4631)\n\n## v0.41.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove reference to `defaultcomponents` in core and deprecate `include_core` flag (#4087)\n- Remove `config.NewConfigMapFrom[File|Buffer]`, add testonly version (#4502)\n- `configtls`: TLS 1.2 is the new default minimum version (#4503)\n- `confighttp`: `ToServer` now accepts a `component.Host`, in line with gRPC's counterpart (#4514)\n- CORS configuration for OTLP/HTTP receivers has been moved into a `cors:` block, instead of individual `cors_allowed_origins` and `cors_allowed_headers` settings (#4492)\n\n### 💡 Enhancements 💡\n\n- OTLP/HTTP receivers now support setting the `Access-Control-Max-Age` header for CORS caching. (#4492)\n- `client.Info` pre-populated for all receivers using common helpers like `confighttp` and `configgrpc` (#4423)\n\n### 🧰 Bug fixes 🧰\n\n- Fix handling of corrupted records by persistent buffer (experimental) (#4475)\n\n### 💡 Enhancements 💡\n\n- Extending the contribution guide to help clarify what is acceptable defaults and recommendations.\n\n## v0.40.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Package `client` refactored (#4416) and auth data included in it (#4422). Final PR to be merged in the next release (#4423)\n- Remove `pdata.AttributeMap.InitFromMap` (#4429)\n- Updated configgrpc `ToDialOptions` to support passing providers to instrumentation library (#4451)\n- Make state information propagation non-blocking on the collector (#4460)\n\n### 💡 Enhancements 💡\n\n- Add semconv 1.7.0 and 1.8.0 (#4452)\n- Added `feature-gates` CLI flag for controlling feature gate state. (#4368)\n- Add a default user-agent header to the OTLP/gRPC and OTLP/HTTP exporters containing collector build information (#3970)\n\n## v0.39.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove deprecated config (already no-op) `ballast_size_mib` in memorylimiterprocessor (#4365)\n- Remove `config.Receivers`, `config.Exporters`, `config.Processors`, and `config.Extensions`. Use map directly (#4344)\n- Remove `component.BaseProcessorFactory`, use `processorhelper.NewFactory` instead (#4175)\n- Force usage of `exporterhelper.NewFactory` to implement `component.ExporterFactory` (#4338)\n- Force usage of `receiverhelper.NewFactory` to implement `component.ReceiverFactory` (#4338)\n- Force usage of `extensionhelper.NewFactory` to implement `component.ExtensionFactory` (#4338)\n- Move `service/parserprovider` package to `config/configmapprovider` (#4206)\n  - Rename `MapProvider` interface to `Provider`\n  - Remove `MapProvider` from helper names\n- Renamed slice-valued `pdata` types and functions for consistency. (#4325)\n  - Rename `pdata.AnyValueArray` to `pdata.AttributeValueSlice`\n  - Rename `ArrayVal()` to `SliceVal()`\n  - Rename `SetArrayVal()` to `SetSliceVal()`\n- Remove `config.Pipeline.Name` (#4326)\n- Rename `config.Mapprovider` as `configmapprovider.Provider` (#4337)\n- Move `config.WatchableRetrieved` and `config.Retrieved` interfaces to `config/configmapprovider` package (#4337)\n- Remove `config.Pipeline.InputDataType` (#4343)\n- otlpexporter: Do not retry on PermissionDenied and Unauthenticated (#4349)\n- Enable configuring collector metrics through service config file. (#4069)\n  - New `service::telemetry::metrics` structure added to configuration\n  - Existing metrics configuration CLI flags are deprecated and to be\n    removed in the future.\n  - `--metrics-prefix` is no longer operative; the prefix is determined by\n    the value of `service.buildInfo.Command`.\n  - `--add-instance-id` is no longer operative; an instance ID will always be added.\n- Remove deprecated funcs `consumererror.As[Traces|Metrics|Logs]` (#4364)\n- Remove support to expand env variables in default configs (#4366)\n\n### 💡 Enhancements 💡\n\n- Supports more compression methods(`snappy` and `zstd`) for configgrpc, in addition to current `gzip` (#4088)\n- Moved the OpenTelemetry Collector Builder to core (#4307)\n\n### 🧰 Bug fixes 🧰\n\n- Fix AggregationTemporality and IsMonotonic when metric descriptors are split in the batch processor (#4389)\n\n## v0.38.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Removed `configauth.HTTPClientAuthenticator` and `configauth.GRPCClientAuthenticator` in favor of `configauth.ClientAuthenticator`. (#4255)\n- Rename `parserprovider.MapProvider` as `config.MapProvider`. (#4178)\n- Rename `parserprovider.Watchable` as `config.WatchableMapProvider`. (#4178)\n- Remove deprecated no-op flags to setup Collector's logging \"--log-level\", \"--log-profile\", \"--log-format\". (#4213)\n- Move `cmd/pdatagen` as internal package `model/internal/cmd/pdatagen`. (#4243)\n- Use directly the ComponentID in configauth. (#4238)\n- Refactor configauth, getters use the map instead of iteration. (#4234)\n- Change scraperhelper to follow the recommended append model for pdata. (#4202)\n\n### 💡 Enhancements 💡\n\n- Update proto to 0.11.0. (#4209)\n- Change pdata to use the newly added [Traces|Metrics|Logs]Data. (#4214)\n- Add ExponentialHistogram field to pdata. (#4219)\n- Make sure otlphttp exporter tests include TraceID and SpanID. (#4268)\n- Use multimod tool in release process. (#4229)\n- Change queue metrics to use opencensus metrics instead of stats, close to otel-go. (#4220)\n- Make receiver data delivery guarantees explicit (#4262)\n- Simplify unmarshal logic by adding more supported hooks. (#4237)\n- Add unmarshaler for otlpgrpc.[*]Request and otlpgrpc.[*]Response (#4215)\n\n## v0.37.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Move `configcheck.ValidateConfigFromFactories` as internal function in service package (#3876)\n- Rename `configparser.Parser` as `config.Map` (#4075)\n- Rename `component.DefaultBuildInfo()` to `component.NewDefaultBuildInfo()` (#4129)\n- Rename `consumererror.Permanent` to `consumererror.NewPermanent` (#4118)\n- Rename `config.NewID` to `config.NewComponentID` and `config.NewIDFromString` to `config.NewComponentIDFromString` (#4137)\n- Rename `config.NewIDWithName` to `config.NewComponentIDWithName` (#4151)\n- Move `extension/storage` to `extension/experimental/storage` (#4082)\n- Rename `obsreporttest.SetupRecordedMetricsTest()` to `obsreporttest.SetupTelemetry()` and `obsreporttest.TestTelemetrySettings` to `obsreporttest.TestTelemetry` (#4157)\n\n### 💡 Enhancements 💡\n\n- Add Gen dependabot into CI (#4083)\n- Update OTLP to v0.10.0 (#4045).\n- Add Flags field to NumberDataPoint, HistogramDataPoint, SummaryDataPoint (#4081).\n- Add feature gate library (#4108)\n- Add version to the internal telemetry metrics (#4140)\n\n### 🧰 Bug fixes 🧰\n\n- Fix panic when not using `service.NewCommand` (#4139)\n\n## v0.36.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove deprecated pdata.AttributeMapToMap (#3994)\n- Move ValidateConfig from configcheck to configtest (#3956)\n- Remove `mem-ballast-size-mib`, already deprecated and no-op (#4005)\n- Remove `semconv.AttributeMessageType` (#4020)\n- Remove `semconv.AttributeHTTPStatusText` (#4015)\n- Remove squash on `configtls.TLSClientSetting` and move TLS client configs under `tls` (#4063)\n- Rename TLS server config `*configtls.TLSServerSetting` from `tls_settings` to `tls` (#4063)\n- Split `service.Collector` from the `cobra.Command` (#4074)\n- Rename `memorylimiter` to `memorylimiterprocessor` (#4064)\n\n### 💡 Enhancements 💡\n\n- Create new semconv package for v1.6.1 (#3948)\n- Add AttributeValueBytes support to AsString (#4002)\n- Add AttributeValueTypeBytes support to AttributeMap.AsRaw (#4003)\n- Add MeterProvider to TelemetrySettings (#4031)\n- Add configuration to setup collector logs via config file. (#4009)\n\n## v0.35.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove the legacy gRPC port(`55680`) support in OTLP receiver (#3966)\n- Rename configparser.Parser to configparser.ConfigMap (#3964)\n- Remove obsreport.ScraperContext, embed into StartMetricsOp (#3969)\n- Remove dependency on deprecated go.opentelemetry.io/otel/oteltest (#3979)\n- Remove deprecated pdata.AttributeValueToString (#3953)\n- Remove deprecated pdata.TimestampFromTime. Closes: #3925 (#3935)\n\n### 💡 Enhancements 💡\n\n- Add TelemetryCreateSettings (#3984)\n- Only initialize collector telemetry once (#3918)\n- Add trace context info to LogRecord log (#3959)\n- Add new view for AWS ECS health check extension. (#3776)\n\n## v0.34.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Artifacts are no longer published in this repository, check [here](https://github.com/open-telemetry/opentelemetry-collector-releases) (#3941)\n- Remove deprecated `tracetranslator.AttributeValueToString` and `tracetranslator.AttributeMapToMap` (#3873)\n- Change semantic conventions for status (code, msg) as per specifications (#3872)\n- Move `fileexporter` to contrib (#3474)\n- Move `jaegerexporter` to contrib (#3474)\n- Move `kafkaexporter` to contrib (#3474)\n- Move `opencensusexporter` to contrib (#3474)\n- Move `prometheusexporter` to contrib (#3474)\n- Move `prometheusremotewriteexporter` to contrib (#3474)\n- Move `zipkinexporter` to contrib (#3474)\n- Move `attributeprocessor` to contrib (#3474)\n- Move `filterprocessor` to contrib (#3474)\n- Move `probabilisticsamplerprocessor` to contrib (#3474)\n- Move `resourceprocessor` to contrib (#3474)\n- Move `spanprocessor` to contrib (#3474)\n- Move `hostmetricsreceiver` to contrib (#3474)\n- Move `jaegerreceiver` to contrib (#3474)\n- Move `kafkareceiver` to contrib (#3474)\n- Move `opencensusreceiver` to contrib (#3474)\n- Move `prometheusreceiver` to contrib (#3474)\n- Move `zipkinreceiver` to contrib (#3474)\n- Move `bearertokenauthextension` to contrib (#3474)\n- Move `healthcheckextension` to contrib (#3474)\n- Move `oidcauthextension` to contrib (#3474)\n- Move `pprofextension` to contrib (#3474)\n- Move `translator/internaldata` to contrib (#3474)\n- Move `translator/trace/jaeger` to contrib (#3474)\n- Move `translator/trace/zipkin` to contrib (#3474)\n- Move `testbed` to contrib (#3474)\n- Move `exporter/exporterhelper/resource_to_telemetry` to contrib (#3474)\n- Move `processor/processorhelper/attraction` to contrib (#3474)\n- Move `translator/conventions` to `model/semconv` (#3901)\n\n### 🚩 Deprecations 🚩\n\n- Add `pdata.NewTimestampFromTime`, deprecate `pdata.TimestampFromTime` (#3868)\n- Add `pdata.NewAttributeMapFromMap`, deprecate `pdata.AttributeMap.InitFromMap` (#3936)\n\n## v0.33.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Rename `configloader` interface to `configunmarshaler` (#3774)\n- Remove `LabelsMap` from all the metrics points (#3706)\n- Update generated K8S attribute labels to fix capitalization (#3823)\n\n### 💡 Enhancements 💡\n\n- Collector has now full support for metrics proto v0.9.0.\n\n## v0.32.0 Beta\n\nThis release is marked as \"bad\" since the metrics pipelines will produce bad data.\n\n- See https://github.com/open-telemetry/opentelemetry-collector/issues/3824\n\n### 🛑 Breaking changes 🛑\n\n- Rename `CustomUnmarshable` interface to `Unmarshallable` (#3774)\n\n### 💡 Enhancements 💡\n\n- Change default OTLP/HTTP port number from 55681 to 4318 (#3743)\n- Update OTLP proto to v0.9.0 (#3740)\n  - Remove `SetValue`/`Value` func for `NumberDataPoint`/`Exemplar` (#3730)\n  - Remove `IntGauge`/`IntSum`from pdata (#3731)\n  - Remove `IntDataPoint` from pdata (#3735)\n  - Add support for `Bytes` attribute type (#3756)\n  - Add `SchemaUrl` field (#3759)\n  - Add `Attributes` to `NumberDataPoint`, `HistogramDataPoint`, `SummaryDataPoint` (#3761)\n- `conventions` translator: Replace with conventions generated from spec v1.5.0 (#3494)\n- `prometheus` receiver: Add `ToMetricPdata` method (#3695)\n- Make configsource `Watchable` an optional interface (#3792)\n- `obsreport` exporter: Change to accept `ExporterCreateSettings` (#3789)\n\n### 🧰 Bug fixes 🧰\n\n- `configgrpc`: Use chained interceptors in the gRPC server (#3744)\n- `prometheus` receiver: Use actual interval startTimeMs for cumulative types (#3694)\n- `jaeger` translator: Fix bug that could generate empty proto spans (#3808)\n\n## v0.31.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove Resize() from pdata slice APIs (#3675)\n- Remove the ballast allocation when `mem-ballast-size-mib` is set in command line (#3626)\n  - Use `ballast extension` to set memory ballast instead.\n- Rename `DoubleDataPoint` to `NumberDataPoint` (#3633)\n- Remove `IntHistogram` (#3676)\n\n### 💡 Enhancements 💡\n\n- Update to OTLP 0.8.0:\n  - Translate `IntHistogram` to `Histogram` in `otlp_wrappers` (#3676)\n  - Translate `IntGauge` to `Gauge` in `otlp_wrappers` (#3619)\n  - Translate `IntSum` to `Sum` in `otlp_wrappers` (#3621)\n  - Update `NumberDataPoint` to support `DoubleVal` and `IntVal` (#3689)\n  - Update `Exemplar` to use `oneOfPrimitiveValue` (#3699)\n  - Remove `IntExemplar` and `IntExemplarSlice` from `pdata` (#3705)\n  - Mark `IntGauge`/`IntSum`/`IntDataPoint` as deprecated (#3707)\n  - Remove `IntGauge`/`IntSum` from `batchprocessor` (#3718)\n  - `prometheusremotewrite` exporter: Convert to new Number metrics (#3714)\n  - `prometheus` receiver: Convert to new Number metrics (#3716)\n  - `prometheus` exporter: Convert to new Number metrics (#3709)\n  - `hostmetrics` receiver: Convert to new Number metrics (#3710)\n  - `opencensus`: Convert to new Number metrics (#3708)\n  - `scraperhelper` receiver: Convert to new Number metrics (#3717)\n  - `testbed`: Convert to new Number metrics (#3719)\n  - `exporterhelper`: Convert `resourcetolabel` to new Number metrics (#3723)\n- `configauth`: Prepare auth API to return a context (#3618)\n- `pdata`:\n  - Implement `Equal()` for map-valued `AttributeValues` (#3612)\n  - Add `[Type]Slice.Sort(func)` to sort slices (#3671)\n- `memorylimiter`:\n  - Add validation on ballast size between `memorylimiter` and `ballastextension` (#3532)\n  - Access Ballast extension via `Host.GetExtensions` (#3634)\n- `prometheusremotewrite` exporter: Add a WAL implementation without wiring up (#3597)\n- `prometheus` receiver: Add `metricGroup.toDistributionPoint` pdata conversion (#3667)\n- Use `ComponentID` as identifier instead of config (#3696)\n- `zpages`: Move config validation from factory to `Validate` (#3697)\n- Enable `tracez` z-pages from otel-go, disable opencensus (#3698)\n- Convert temporality and monotonicity for deprecated sums (#3729)\n\n### 🧰 Bug fixes 🧰\n\n- `otlpexporter`: Allow endpoint to be configured with a scheme of `http` or `https` (#3575)\n- Handle errors when reloading the collector service (#3615)\n- Do not report fatal error when `cmux.ErrServerClosed` (#3703)\n- Fix bool attribute equality in `pdata` (#3688)\n\n## v0.30.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Rename `pdata.DoubleSum` to `pdata.Sum` (#3583)\n- Rename `pdata.DoubleGauge` to `pdata.Gauge` (#3599)\n- Migrated `pdata` to a dedicated package (#3483)\n- Change Marshaler/Unmarshaler to be consistent with other interfaces (#3502)\n- Remove consumer/simple package (#3438)\n- Remove unnecessary interfaces from pdata (#3506)\n- zipkinv1 implement directly Unmarshaler interface (#3504)\n- zipkinv2 implement directly Marshaler/Unmarshaler interface (#3505)\n- Change exporterhelper to accept ExporterCreateSettings instead of just logger (#3569)\n- Use Func pattern in processorhelper, consistent with others (#3570)\n\n### 🚩 Deprecations 🚩\n\n- Deprecate Resize() from pdata slice APIs (#3573)\n\n### 💡 Enhancements 💡\n\n- Update OTLP to v0.8.0 (#3572)\n- Migrate from OpenCensus to OpenTelemetry for internal tracing (#3567)\n- Move internal/pdatagrpc to model/otlpgrpc (#3507)\n- Move internal/otlp to model/otlp (#3508)\n- Create http Server via Config, enable cors and decompression (#3513)\n- Allow users to set min and max TLS versions (#3591)\n- Support setting ballast size in percentage of total Mem in ballast extension (#3456)\n- Publish go.opentelemetry.io/collector/model as a separate module (#3530)\n- Pass a TracerProvider via construct settings to all the components (#3592)\n- Make graceful shutdown optional (#3577)\n\n### 🧰 Bug fixes 🧰\n\n- `scraperhelper`: Include the scraper name in log messages (#3487)\n- `scraperhelper`: fix case when returned pdata is empty (#3520)\n- Record the correct number of points not metrics in Kafka receiver (#3553)\n- Validate the Prometheus configuration (#3589)\n\n## v0.29.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Rename `service.Application` to `service.Collector` (#3268)\n- Provide case sensitivity in config yaml mappings by using Koanf instead of Viper (#3337)\n- Move zipkin constants to an internal package (#3431)\n- Disallow renaming metrics using metric relabel configs (#3410)\n- Move cgroup and iruntime utils from memory_limiter to internal folder (#3448)\n- Move model pdata interfaces to pdata, expose them publicly (#3455)\n\n### 💡 Enhancements 💡\n\n- Change obsreport helpers for scraper to use the same pattern as Processor/Exporter (#3327)\n- Convert `otlptext` to implement Marshaler interfaces (#3366)\n- Add encoder/decoder and marshaler/unmarshaler for OTLP protobuf (#3401)\n- Use the new marshaler/unmarshaler in `kafka` exporter (#3403)\n- Convert `zipkinv2` to to/from translator interfaces (#3409)\n- `zipkinv1`: Move to translator and encoders interfaces (#3419)\n- Use the new marshaler/unmarshaler in `kafka` receiver #3402\n- Change `oltp` receiver to use the new unmarshaler, avoid grpc-gateway dependency (#3406)\n- Use the new Marshaler in the `otlphttp` exporter (#3433)\n- Add grpc response struct for all signals instead of returning interface in `otlp` receiver/exporter (#3437)\n- `zipkinv2`: Add encoders, decoders, marshalers (#3426)\n- `scrapererror` receiver: Return concrete error type (#3360)\n- `kafka` receiver: Add metrics support (#3452)\n- `prometheus` receiver:\n  - Add store to track stale metrics (#3414)\n  - Add `up` and `scrape_xxxx` internal metrics (#3116)\n\n### 🧰 Bug fixes 🧰\n\n- `prometheus` receiver:\n  - Reject datapoints with duplicate label keys (#3408)\n  - Scrapers are not stopped when receiver is shutdown (#3450)\n- `prometheusremotewrite` exporter: Adjust default retry settings (#3416)\n- `hostmetrics` receiver: Fix missing startTimestamp for `processes` scraper (#3461)\n\n## v0.28.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove unused logstest package (#3222)\n- Introduce `AppSettings` instead of `Parameters` (#3163)\n- Remove unused testutil.TempSocketName (#3291)\n- Move BigEndian helper functions in `tracetranslator` to an internal package.(#3298)\n- Rename `configtest.LoadConfigFile` to `configtest.LoadConfigAndValidate` (#3306)\n- Replace `ExtensionCreateParams` with `ExtensionCreateSettings` (#3294)\n- Replace `ProcessorCreateParams` with `ProcessorCreateSettings`. (#3181)\n- Replace `ExporterCreateParams` with `ExporterCreateSettings` (#3164)\n- Replace `ReceiverCreateParams` with `ReceiverCreateSettings`. (#3167)\n- Change `batchprocessor` logic to limit data points rather than metrics (#3141)\n- Rename `PrwExporter` to `PRWExporter` and `NewPrwExporter` to `NewPRWExporter` (#3246)\n- Avoid exposing OpenCensus reference in public APIs (#3253)\n- Move `config.Parser` to `configparser.Parser` (#3304)\n- Remove deprecated funcs inside the obsreceiver (#3314)\n- Remove `obsreport.GRPCServerWithObservabilityEnabled`, enable observability in config (#3315)\n- Remove `obsreport.ProcessorMetricViews`, use `BuildProcessorCustomMetricName` where needed (#3316)\n- Remove \"Receive\" from `obsreport.Receiver` funcs (#3326)\n- Remove \"Export\" from `obsreport.Exporter` funcs (#3333)\n- Hide unnecessary public struct `obsreport.StartReceiveOptions` (#3353)\n- Avoid exposing internal implementation public in OC/OTEL receivers (#3355)\n- Updated configgrpc `ToDialOptions` and confighttp `ToClient` apis to take extensions configuration map (#3340)\n- Remove `GenerateSequentialTraceID` and `GenerateSequentialSpanIDin` functions in testbed (#3390)\n- Change \"grpc\" to \"GRPC\" in configauth function/type names (#3285)\n\n### 💡 Enhancements 💡\n\n- Add `doc.go` files to the consumer package and its subpackages (#3270)\n- Improve documentation of consumer package and subpackages (#3269, #3361)\n- Automate triggering of doc-update on release (#3234)\n- Enable Dependabot for Github Actions (#3312)\n- Remove the proto dependency in `goldendataset` for traces (#3322)\n- Add telemetry for dropped data due to exporter sending queue overflow (#3328)\n- Add initial implementation of `pdatagrpc` (#3231)\n- Change receiver obsreport helpers pattern to match the Processor/Exporter (#3227)\n- Add model translation and encoding interfaces (#3200)\n- Add otlpjson as a serializer implementation (#3238)\n- `prometheus` receiver:\n  - Add `createNodeAndResourcePdata` for Prometheus->OTLP pdata (#3139)\n  - Direct metricfamily Prometheus->OTLP (#3145)\n- Add `componenttest.NewNop*CreateSettings` to simplify tests (#3375)\n- Add support for markdown generation (#3100)\n- Refactor components for the Client Authentication Extensions (#3287)\n\n### 🧰 Bug fixes 🧰\n\n- Use dedicated `zapcore.Core` for Windows service (#3147)\n- Hook up start and shutdown functions in fileexporter (#3260)\n- Fix oc to pdata translation for sum non-monotonic cumulative (#3272)\n- Fix `timeseriesSignature` in prometheus receiver (#3310)\n\n## v0.27.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Change `Marshal` signatures in kafkaexporter's Marshalers to directly convert pdata to `sarama.ProducerMessage` (#3162)\n- Remove `tracetranslator.DetermineValueType`, only used internally by Zipkin (#3114)\n- Remove OpenCensus conventions, should not be used (#3113)\n- Remove Zipkin specific translation constants, move to internal (#3112)\n- Remove `tracetranslator.TagHTTPStatusCode`, use `conventions.AttributeHTTPStatusCode` (#3111)\n- Remove OpenCensus status constants and transformation (#3110)\n- Remove `tracetranslator.AttributeArrayToSlice`, not used in core or contrib (#3109)\n- Remove `internaldata.MetricsData`, same APIs as for traces (#3156)\n- Rename `config.IDFromString` to `NewIDFromString`, remove `MustIDFromString` (#3177)\n- Move consumerfanout package to internal (#3207)\n- Canonicalize enum names in pdata. Fix usage of uppercase names (#3208)\n\n### 💡 Enhancements 💡\n\n- Use `config.ComponentID` for obsreport receiver/scraper (#3098)\n- Add initial implementation of the consumerhelper (#3146)\n- Add Collector version to Prometheus Remote Write Exporter user-agent header (#3094)\n- Refactor processorhelper to use consumerhelper, split by signal type (#3180)\n- Use consumerhelper for exporterhelper, add WithCapabilities (#3186)\n- Set capabilities for all core exporters, remove unnecessary funcs (#3190)\n- Add an internal sharedcomponent to be shared by receivers with shared resources (#3198)\n- Allow users to configure the Prometheus remote write queue (#3046)\n- Mark internaldata traces translation as deprecated for external usage (#3176)\n\n### 🧰 Bug fixes 🧰\n\n- Fix Prometheus receiver metric start time and reset determination logic. (#3047)\n  - The receiver will no longer drop the first sample for `counter`, `summary`, and `histogram` metrics.\n- The Prometheus remote write exporter will no longer force `counter` metrics to have a `_total` suffix. (#2993)\n- Remove locking from jaeger receiver start and stop processes (#3070)\n- Fix batch processor metrics reorder, improve performance (#3034)\n- Fix batch processor traces reorder, improve performance (#3107)\n- Fix batch processor logs reorder, improve performance (#3125)\n- Avoid one unnecessary allocation in grpc OTLP exporter (#3122)\n- `batch` processor: Validate that batch config max size is greater than send size (#3126)\n- Add capabilities to consumer, remove from processor (#2770)\n- Remove internal protos usage in Prometheusremotewrite exporter (#3184)\n- `prometheus` receiver: Honor Prometheus external labels (#3127)\n- Validate that remote write queue settings are not negative (#3213)\n\n## v0.26.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Change `With*Unmarshallers` signatures in Kafka exporter/receiver (#2973)\n- Rename `marshall` to `marshal` in all the occurrences (#2977)\n- Remove `componenterror.ErrAlreadyStarted` and `componenterror.ErrAlreadyStopped`, components should not protect against this, Service will start/stop once.\n- Rename `ApplicationStartInfo` to `BuildInfo`\n- Rename `ApplicationStartInfo.ExeName` to `BuildInfo.Command`\n- Rename `ApplicationStartInfo.LongName` to `BuildInfo.Description`\n\n### 🚩 Deprecations 🚩\n\n- Add AppendEmpty and deprecate Append for slices (#2970)\n\n### 💡 Enhancements 💡\n\n- `kafka` exporter: Add logs support (#2943)\n- Update mdatagen to create factories of init instead of new (#2978)\n- `zipkin` receiver: Reduce the judgment of zipkin v1 version (#2990)\n- Custom authenticator logic to accept a `component.Host` which will extract the authenticator to use based on a new authenticator name property (#2767)\n- `prometheusremotewrite` exporter: Add `resource_to_telemetry_conversion` config option (#3031)\n- `logging` exporter: Extract OTLP text logging (#3082)\n- Format timestamps as strings instead of int in otlptext output (#3088)\n- Add darwin arm64 build (#3090)\n\n### 🧰 Bug fixes 🧰\n\n- Fix Jaeger receiver to honor TLS Settings (#2866)\n- `zipkin` translator: Handle missing starttime case for zipkin json v2 format spans (#2506)\n- `prometheus` exporter: Fix OTEL resource label drops (#2899)\n- `prometheusremotewrite` exporter:\n  - Enable the queue internally (#2974)\n  - Don't drop instance and job labels (#2979)\n- `jaeger` receiver: Wait for server goroutines exit on shutdown (#2985)\n- `logging` exporter: Ignore invalid handle on close (#2994)\n- Fix service zpages (#2996)\n- `batch` processor: Fix to avoid reordering and send max size (#3029)\n\n## v0.25.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Rename ForEach (in pdata) with Range to be consistent with sync.Map (#2931)\n- Rename `componenthelper.Start` to `componenthelper.StartFunc` (#2880)\n- Rename `componenthelper.Stop` to `componenthelper.StopFunc` (#2880)\n- Remove `exporterhelper.WithCustomUnmarshaler`, `processorhelper.WithCustomUnmarshaler`, `receiverhelper.WithCustomUnmarshaler`, `extensionhelper.WithCustomUnmarshaler`, implement `config.CustomUnmarshaler` interface instead (#2867)\n- Remove `component.CustomUnmarshaler` implement `config.CustomUnmarshaler` interface instead (#2867)\n- Remove `testutil.HostPortFromAddr`, users can write their own parsing helper (#2919)\n- Remove `configparser.DecodeTypeAndName`, use `config.IDFromString` (#2869)\n- Remove `config.NewViper`, users should use `config.NewParser` (#2917)\n- Remove `testutil.WaitFor`, use `testify.Eventually` helper if needed (#2920)\n- Remove testutil.WaitForPort, users can use testify.Eventually (#2926)\n- Rename `processorhelper.NewTraceProcessor` to `processorhelper.NewTracesProcessor` (#2935)\n- Rename `exporterhelper.NewTraceExporter` to `exporterhelper.NewTracesExporter` (#2937)\n- Remove InitEmptyWithCapacity, add EnsureCapacity and Clear (#2845)\n- Rename traces methods/objects to include Traces in Kafka receiver (#2966)\n\n### 💡 Enhancements 💡\n\n- Add `validatable` interface with `Validate()` to all `config.<component>` (#2898)\n  - add the empty `Validate()` implementation for all component configs\n- **Experimental**: Add a config source manager that wraps the interaction with config sources (#2857, #2903, #2948)\n- `kafka` exporter: Key jaeger messages on traceid (#2855)\n- `scraperhelper`: Don't try to count metrics if scraper returns an error (#2902)\n- Extract ConfigFactory in a ParserProvider interface (#2868)\n- `prometheus` exporter: Allows Summary metrics to be exported to Prometheus (#2900)\n- `prometheus` receiver: Optimize `dpgSignature` function (#2945)\n- `kafka` receiver: Add logs support (#2944)\n\n### 🧰 Bug fixes 🧰\n\n- `prometheus` receiver:\n  - Treat Summary and Histogram metrics without \"\\_sum\" counter as valid metric (#2812)\n  - Add `job` and `instance` as well-known labels (#2897)\n- `prometheusremotewrite` exporter:\n  - Sort Sample by Timestamp to avoid out of order errors (#2941)\n  - Remove incompatible queued retry (#2951)\n- `kafka` receiver: Fix data race with batchprocessor (#2957)\n- `jaeger` receiver: Jaeger agent should not report ErrServerClosed (#2965)\n\n## v0.24.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove legacy internal metrics for memorylimiter processor, `spans_dropped` and `trace_batches_dropped` (#2841)\n  - For `spans_dropped` use `processor/refused_spans` with `processor=memorylimiter`\n- Rename pdata._.[Start|End]Time to pdata._.[Start|End]Timestamp (#2847)\n- Rename pdata.DoubleExemplar to pdata.Exemplar (#2804)\n- Rename pdata.DoubleHistogram to pdata.Histogram (#2797)\n- Rename pdata.DoubleSummary to pdata.Summary (#2774)\n- Refactor `consumererror` package (#2768)\n  - Remove `PartialError` type in favor of signal-specific types\n  - Rename `CombineErrors()` to `Combine()`\n- Refactor `componenthelper` package (#2778)\n  - Remove `ComponentSettings` and `DefaultComponentSettings()`\n  - Rename `NewComponent()` to `New()`\n- obsReport.NewExporter accepts a settings struct (#2668)\n- Remove ErrorWaitingHost from `componenttest` (#2582)\n- Move `config.Load` to `configparser.Load` (#2796)\n- Remove `configtest.NewViperFromYamlFile()`, use `config.Parser.NewParserFromFile()` (#2806)\n- Remove `config.ViperSubExact()`, use `config.Parser.Sub()` (#2806)\n- Update LoadReceiver signature to remove unused params (#2823)\n- Move `configerror.ErrDataTypeIsNotSupported` to `componenterror.ErrDataTypeIsNotSupported` (#2886)\n- Rename`CreateTraceExporter` type to `CreateTracesExporter` in `exporterhelper` (#2779)\n- Move `fluentbit` extension to contrib (#2795)\n- Move `configmodels` to `config` (#2808)\n- Move `fluentforward` receiver to contrib (#2723)\n\n### 🚩 Deprecations 🚩\n\n- Deprecate `consumetest.New[${SIGNAL}]Nop` in favor of `consumetest.NewNop` (#2878)\n- Deprecate `consumetest.New[${SIGNAL}]Err` in favor of `consumetest.NewErr` (#2878)\n\n### 💡 Enhancements 💡\n\n- `batch` processor: - Support max batch size for logs (#2736)\n- Use `Endpoint` for health check extension (#2782)\n- Use `confignet.TCPAddr` for `pprof` and `zpages` extensions (#2829)\n- Add watcher to values retrieved via config sources (#2803)\n- Updates for cloud semantic conventions (#2809)\n  - `cloud.infrastructure_service` -> `cloud.platform`\n  - `cloud.zone` -> `cloud.availability_zone`\n- Add systemd environment file for deb/rpm packages (#2822)\n- Add validate interface in `configmodels` to force each component do configuration validation (#2802, #2856)\n- Add `aws.ecs.task.revision` to semantic conventions list (#2816)\n- Set unprivileged user to container image (#2838)\n- Add New funcs for extension, exporter, processor config settings (#2872)\n- Report metric about current size of the exporter retry queue (#2858)\n- Allow adding new signals in `ProcessorFactory` by forcing everyone to embed `BaseProcessorFactory` (#2885)\n\n### 🧰 Bug fixes 🧰\n\n- `pdata.TracesFromOtlpProtoBytes`: Fixes to handle backwards compatibility changes in proto (#2798)\n- `jaeger` receiver: Escape user input used in output (#2815)\n- `prometheus` exporter: Ensure same time is used for updated time (#2745)\n- `prometheusremotewrite` exporter: Close HTTP response body (#2875)\n\n## v0.23.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Move fanout consumers to fanoutconsumer package (#2615)\n- Rename ExporterObsReport to Exporter (#2658)\n- Rename ProcessorObsReport to Processor (#2657)\n- Remove ValidateConfig and add Validate on the Config struct (#2665)\n- Rename pdata Size to OtlpProtoSize (#2726)\n- Rename [Traces|Metrics|Logs]Consumer to [Traces|Metrics|Logs] (#2761)\n- Remove public access for `componenttest.Example*` components:\n  - Users of these structs for testing configs should use the newly added `componenttest.Nop*` (update all components name in the config `example*` -> `nop` and use `componenttest.NopComponents()`).\n  - Users of these structs for sink like behavior should use `consumertest.*Sink`.\n\n### 💡 Enhancements 💡\n\n- `hostmetrics` receiver: List labels along with respective metrics in metadata (#2662)\n- `exporter` helper: Remove obsreport.ExporterContext, always add exporter name as a tag to the metrics (#2682)\n- `jaeger` exporter: Change to not use internal data (#2698)\n- `kafka` receiver: Change to not use internal data (#2697)\n- `zipkin` receiver: Change to not use internal data (#2699)\n- `kafka` exporter: Change to not use internal data (#2696)\n- Ensure that extensions can be created and started multiple times (#2679)\n- Use otlp request in logs wrapper, hide members in the wrapper (#2692)\n- Add MetricsWrapper to disallow access to internal representation (#2693)\n- Add TracesWrapper to disallow access to internal representation (#2721)\n- Allow multiple OTLP receivers to be created (#2743)\n\n### 🧰 Bug fixes 🧰\n\n- `prometheus` exporter: Fix to work with standard labels that follow the naming convention of using periods instead of underscores (#2707)\n- Propagate name and transport for `prometheus` receiver and exporter (#2680)\n- `zipkin` receiver: Ensure shutdown correctness (#2765)\n\n## v0.22.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Rename ServiceExtension to just Extension (#2581)\n- Remove `consumerdata.TraceData` (#2551)\n- Move `consumerdata.MetricsData` to `internaldata.MetricsData` (#2512)\n- Remove custom OpenCensus sematic conventions that have equivalent in otel (#2552)\n- Move ScrapeErrors and PartialScrapeError to `scrapererror` (#2580)\n- Remove support for deprecated unmarshaler `CustomUnmarshaler`, only `Unmarshal` is supported (#2591)\n- Remove deprecated componenterror.CombineErrors (#2598)\n- Rename `pdata.TimestampUnixNanos` to `pdata.Timestamp` (#2549)\n\n### 💡 Enhancements 💡\n\n- `prometheus` exporter: Re-implement on top of `github.com/prometheus/client_golang/prometheus` and add `metric_expiration` option\n- `logging` exporter: Add support for AttributeMap (#2609)\n- Add semantic conventions for instrumentation library (#2602)\n\n### 🧰 Bug fixes 🧰\n\n- `otlp` receiver: Fix `Shutdown()` bug (#2564)\n- `batch` processor: Fix Shutdown behavior (#2537)\n- `logging` exporter: Fix handling the loop for empty attributes (#2610)\n- `prometheusremotewrite` exporter: Fix counter name check (#2613)\n\n## v0.21.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove deprecated function `IsValid` from trace/span ID (#2522)\n- Remove accessors for deprecated status code (#2521)\n\n### 💡 Enhancements 💡\n\n- `otlphttp` exporter: Add `compression` option for gzip encoding of outgoing http requests (#2502)\n- Add `ScrapeErrors` struct to `consumererror` to simplify errors usage (#2414)\n- Add `cors_allowed_headers` option to `confighttp` (#2454)\n- Add SASL/SCRAM authentication mechanism on `kafka` receiver and exporter (#2503)\n\n### 🧰 Bug fixes 🧰\n\n- `otlp` receiver: Sets the correct deprecated status code before sending data to the pipeline (#2521)\n- Fix `IsPermanent` to account for wrapped errors (#2455)\n- `otlp` exporter: Preserve original error messages (#2459)\n\n## v0.20.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Rename `samplingprocessor/probabilisticsamplerprocessor` to `probabilisticsamplerprocessor` (#2392)\n\n### 💡 Enhancements 💡\n\n- `hostmetrics` receiver: Refactor to use metrics metadata utilities (#2405, #2406, #2421)\n- Add k8s.node semantic conventions (#2425)\n\n## v0.19.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove deprecated `queued_retry` processor\n- Remove deprecated configs from `resource` processor: `type` (set \"opencensus.type\" key in \"attributes.upsert\" map instead) and `labels` (use \"attributes.upsert\" instead).\n\n### 💡 Enhancements 💡\n\n- `hostmetrics` receiver: Refactor load metrics to use generated metrics (#2375)\n- Add uptime to the servicez debug page (#2385)\n- Add new semantic conventions for AWS (#2365)\n\n### 🧰 Bug fixes 🧰\n\n- `jaeger` exporter: Improve connection state logging (#2239)\n- `pdatagen`: Fix slice of values generated code (#2403)\n- `filterset` processor: Avoid returning always nil error in strict filterset (#2399)\n\n## v0.18.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Rename host metrics according to metrics spec and rename `swap` scraper to `paging` (#2311)\n\n### 💡 Enhancements 💡\n\n- Add check for `NO_WINDOWS_SERVICE` environment variable to force interactive mode on Windows (#2272)\n- `hostmetrics` receiver: Add `disk/weighted_io_time` metric (Linux only) (#2312)\n- `opencensus` exporter: Add queue-retry (#2307)\n- `filter` processor: Filter metrics using resource attributes (#2251)\n\n### 🧰 Bug fixes 🧰\n\n- `fluentforward` receiver: Fix string conversions (#2314)\n- Fix zipkinv2 translation error tag handling (#2253)\n\n## v0.17.0 Beta\n\n### 💡 Enhancements 💡\n\n- Default config environment variable expansion (#2231)\n- `prometheusremotewrite` exporter: Add batched exports (#2249)\n- `memorylimiter` processor: Introduce soft and hard limits (#2250)\n\n### 🧰 Bug fixes 🧰\n\n- Fix nits in pdata usage (#2235)\n- Convert status to not be a pointer in the Span (#2242)\n- Report the error from `pprof.StartCPUProfile` (#2263)\n- Rename `service.Application.SignalTestComplete` to `Shutdown` (#2277)\n\n## v0.16.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Rename Push functions to be consistent across signals in `exporterhelper` (#2203)\n\n### 💡 Enhancements 💡\n\n- Change default OTLP/gRPC port number to 4317, also continue receiving on legacy port\n  55680 during transition period (#2104).\n- `kafka` exporter: Add support for exporting metrics as otlp Protobuf. (#1966)\n- Move scraper helpers to its own `scraperhelper` package (#2185)\n- Add `componenthelper` package to help build components (#2186)\n- Remove usage of custom init/stop in `scraper` and use start/shutdown from `component` (#2193)\n- Add more trace annotations, so zpages are more useful to determine failures (#2206)\n- Add support to skip TLS verification (#2202)\n- Expose non-nullable metric types (#2208)\n- Expose non-nullable elements from slices of pointers (#2200)\n\n### 🧰 Bug fixes 🧰\n\n- Change InstrumentationLibrary to be non-nullable (#2196)\n- Add support for slices to non-pointers, use non-nullable AnyValue (#2192)\n- Fix `--set` flag to work with `{}` in configs (#2162)\n\n## v0.15.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Remove legacy metrics, they were marked as legacy for ~12 months #2105\n\n### 💡 Enhancements 💡\n\n- Implement conversion between OpenCensus and OpenTelemetry Summary Metric (#2048)\n- Add ability to generate non nullable messages (#2005)\n- Implement Summary Metric in Prometheus RemoteWrite Exporter (#2083)\n- Add `resource_to_telemetry_conversion` to exporter helper expose exporter settings (#2060)\n- Add `CustomRoundTripper` function to httpclientconfig (#2085)\n- Allow for more logging options to be passed to `service` (#2132)\n- Add config parameters for `jaeger` receiver (#2068)\n- Map unset status code for `jaeger` translator as per spec (#2134)\n- Add more trace annotations to the queue-retry logic (#2136)\n- Add config settings for component telemetry (#2148)\n- Use net.SplitHostPort for IPv6 support in `prometheus` receiver (#2154)\n- Add --log-format command line option (default to \"console\") #2177.\n\n### 🧰 Bug fixes 🧰\n\n- `logging` exporter: Add Logging for Summary Datapoint (#2084)\n- `hostmetrics` receiver: use correct TCP state labels on Unix systems (#2087)\n- Fix otlp_log receiver wrong use of trace measurement (#2117)\n- Fix \"process/memory/rss\" metric units (#2112)\n- Fix \"process/cpu_seconds\" metrics (#2113)\n- Add check for nil logger in exporterhelper functions (#2141)\n- `prometheus` receiver:\n  - Upgrade Prometheus version to fix race condition (#2121)\n  - Fix the scraper/discover manager coordination (#2089)\n  - Fix panic when adjusting buckets (#2168)\n\n## v0.14.0 Beta\n\n### 🚀 New components 🚀\n\n- `otlphttp` exporter which implements OTLP over HTTP protocol.\n\n### 🛑 Breaking changes 🛑\n\n- Rename consumer.TraceConsumer to consumer.TracesConsumer #1974\n- Rename component.TraceReceiver to component.TracesReceiver #1975\n- Rename component.TraceProcessor to component.TracesProcessor #1976\n- Rename component.TraceExporter to component.TracesExporter #1975\n- Move `tailsampling` processor to contrib (#2012)\n- Remove NewAttributeValueSlice (#2028) and mark NewAttributeValue as deprecated (#2022)\n- Remove pdata.StringValue (#2021)\n- Remove pdata.InitFromAttributeMap, use CopyTo if needed (#2042)\n- Remove SetMapVal and SetArrayVal for pdata.AttributeValue (#2039)\n\n### 🚩 Deprecations 🚩\n\n- Deprecate NopExporter, add NopConsumer (#1972)\n- Deprecate SinkExporter, add SinkConsumer (#1973)\n\n### 💡 Enhancements 💡\n\n- `zipkin` exporter: Add queue retry to zipkin (#1971)\n- `prometheus` exporter: Add `send_timestamps` option (#1951)\n- `filter` processor: Add `expr` pdata.Metric filtering support (#1940, #1996)\n- `attribute` processor: Add log support (#1934)\n- `logging` exporter: Add index for histogram buckets count (#2009)\n- `otlphttp` exporter: Add correct handling of server error responses (#2016)\n- `prometheusremotewrite` exporter:\n  - Add user agent header to outgoing http request (#2000)\n  - Convert histograms to cumulative (#2049)\n  - Return permanent errors (#2053)\n  - Add external labels (#2044)\n- `hostmetrics` receiver: Use scraper controller (#1949)\n- Change Span/Trace ID to be byte array (#2001)\n- Add `simple` metrics helper to facilitate building pdata.Metrics in receivers (#1540)\n- Improve diagnostic logging for exporters (#2020)\n- Add obsreport to receiverhelper scrapers (#1961)\n- Update OTLP to 0.6.0 and use the new Span Status code (#2031)\n- Add support of partial requests for logs and metrics to the exporterhelper (#2059)\n\n### 🧰 Bug fixes 🧰\n\n- `logging` exporter: Added array serialization (#1994)\n- `zipkin` receiver: Allow receiver to parse string tags (#1893)\n- `batch` processor: Fix shutdown race (#1967)\n- Guard for nil data points (#2055)\n\n## v0.13.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Host metric `system.disk.time` renamed to `system.disk.operation_time` (#1887)\n- Use consumer for sender interface, remove unnecessary receiver address from Runner (#1941)\n- Enable sending queue by default in all exporters configured to use it (#1924)\n- Removed `groupbytraceprocessor` (#1891)\n- Remove ability to configure collection interval per scraper (#1947)\n\n### 💡 Enhancements 💡\n\n- Host Metrics receiver now reports both `system.disk.io_time` and `system.disk.operation_time` (#1887)\n- Match spans against the instrumentation library and resource attributes (#928)\n- Add `receiverhelper` for creating flexible \"scraper\" metrics receiver (#1886, #1890, #1945, #1946)\n- Migrate `tailsampling` processor to new OTLP-based internal data model and add Composite Sampler (#1894)\n- Metadata Generator: Change Metrics fields to implement an interface with new methods (#1912)\n- Add unmarshalling for `pdata.Traces` (#1948)\n- Add debug-level message on error for `jaeger` exporter (#1964)\n\n### 🧰 Bug fixes 🧰\n\n- Fix bug where the service does not correctly start/stop the log exporters (#1943)\n- Fix Queued Retry Unusable without Batch Processor (#1813) - (#1930)\n- `prometheus` receiver: Log error message when `process_start_time_seconds` gauge is missing (#1921)\n- Fix trace jaeger conversion to internal traces zero time bug (#1957)\n- Fix panic in otlp traces to zipkin (#1963)\n- Fix OTLP/HTTP receiver's path to be /v1/traces (#1979)\n\n## v0.12.0 Beta\n\n### 🚀 New components 🚀\n\n- `configauth` package with the auth settings that can be used by receivers (#1807, #1808, #1809, #1810)\n- `perfcounters` package that uses perflib for host metrics receiver (#1835, #1836, #1868, #1869, #1870)\n\n### 💡 Enhancements 💡\n\n- Remove `queued_retry` and enable `otlp` metrics receiver in default config (#1823, #1838)\n- Add `limit_percentage` and `spike_limit_percentage` options to `memorylimiter` processor (#1622)\n- `hostmetrics` receiver:\n  - Collect additional labels from partitions in the filesystems scraper (#1858)\n  - Add filters for mount point and filesystem type (#1866)\n- Add cloud.provider semantic conventions (#1865)\n- `attribute` processor: Add log support (#1783)\n- Introduce SpanID data type, not yet used in Protobuf messages ($1854, #1855)\n- Enable `otlp` trace by default in the released docker image (#1883)\n- `tailsampling` processor: Combine batches of spans into a single batch (#1864)\n- `filter` processor: Update to use pdata (#1885)\n- Allow MSI upgrades (#1914)\n\n### 🚩 Deprecations 🚩\n\n- Deprecate OpenCensus-based internal data structures (#1843)\n\n### 🧰 Bug fixes 🧰\n\n- `prometheus` receiver: Print a more informative message about 'up' metric value (#1826)\n- Use custom data type and custom JSON serialization for traceid (#1840)\n- Skip creation of redundant nil resource in translation from OC if there are no combined metrics (#1803)\n- `tailsampling` processor: Only send to next consumer once (#1735)\n- Report Windows pagefile usage in bytes (#1837)\n- Fix issue where Prometheus SD config cannot be parsed (#1877)\n\n## v0.11.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Rename service.Start() to Run() since it's a blocking call\n- Fix slice Append to accept by value the element in pdata\n- Change CreateTraceProcessor and CreateMetricsProcessor to use the same parameter order as receivers/logs processor and exporters.\n- Prevent accidental use of LogsToOtlp and LogsFromOtlp and the OTLP data structs (#1703)\n- Remove SetType from configmodels, ensure all registered factories set the type in config (#1798)\n- Move process telemetry to service/internal (#1794)\n\n### 💡 Enhancements 💡\n\n- Add map and array attribute value type support (#1656)\n- Add authentication support to kafka (#1632)\n- Implement InstrumentationLibrary translation to jaeger (#1645)\n- Add public functions to export pdata to ExportXServicesRequest Protobuf bytes (#1741)\n- Expose telemetry level in the configtelemetry (#1796)\n- Add configauth package (#1807)\n- Add config to docker image (#1792)\n\n### 🧰 Bug fixes 🧰\n\n- Use zap int argument for int values instead of conversion (#1779)\n- Add support for gzip encoded payload in OTLP/HTTP receiver (#1581)\n- Return proto status for OTLP receiver when failed (#1788)\n\n## v0.10.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- **Update OTLP to v0.5.0, incompatible metrics protocol.**\n- Remove support for propagating summary metrics in OtelCollector.\n  - This is a temporary change, and will affect mostly OpenCensus users who use metrics.\n\n### 💡 Enhancements 💡\n\n- Support zipkin proto in `kafka` receiver (#1646)\n- Prometheus Remote Write Exporter supporting Cortex (#1577, #1643)\n- Add deployment environment semantic convention (#1722)\n- Add logs support to `batch` and `resource` processors (#1723, #1729)\n\n### 🧰 Bug fixes 🧰\n\n- Identify config error when expected map is other value type (#1641)\n- Fix Kafka receiver closing ready channel multiple times (#1696)\n- Fix a panic issue while processing Zipkin spans with an empty service name (#1742)\n- Zipkin Receiver: Always set the endtime (#1750)\n\n## v0.9.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- **Remove old base factories**:\n  - `ReceiverFactoryBase` (#1583)\n  - `ProcessorFactoryBase` (#1596)\n  - `ExporterFactoryBase` (#1630)\n- Remove logs factories and merge with normal factories (#1569)\n- Remove `reconnection_delay` from OpenCensus exporter (#1516)\n- Remove `ConsumerOld` interfaces (#1631)\n\n### 🚀 New components 🚀\n\n- `prometheusremotewrite` exporter: Send metrics data in Prometheus TimeSeries format to Cortex or any Prometheus (#1544)\n- `kafka` receiver: Receive traces from Kafka (#1410)\n\n### 💡 Enhancements 💡\n\n- `kafka` exporter: Enable queueing, retry, timeout (#1455)\n- Add `Headers` field in HTTPClientSettings (#1552)\n- Change OpenCensus receiver (#1556) and exporter (#1571) to the new interfaces\n- Add semantic attribute for `telemetry.auto.version` (#1578)\n- Add uptime and RSS memory self-observability metrics (#1549)\n- Support conversion for OpenCensus `SameProcessAsParentSpan` (#1629)\n- Access application version in components (#1559)\n- Make Kafka payload encoding configurable (#1584)\n\n### 🧰 Bug fixes 🧰\n\n- Stop further processing if `filterprocessor` filters all data (#1500)\n- `processscraper`: Use same scrape time for all data points coming from same process (#1539)\n- Ensure that time conversion for 0 returns nil timestamps or Time where IsZero returns true (#1550)\n- Fix multiple exporters panic (#1563)\n- Allow `attribute` processor for external use (#1574)\n- Do not duplicate filesystem metrics for devices with many mount points (#1617)\n\n## v0.8.0 Beta\n\n### 🚀 New components 🚀\n\n- `groupbytrace` processor that waits for a trace to be completed (#1362)\n\n### 💡 Enhancements 💡\n\n- Migrate `zipkin` receiver/exporter to the new interfaces (#1484)\n- Migrate `prometheus` receiver/exporter to the new interfaces (#1477, #1515)\n- Add new FactoryUnmarshaler support to all components, deprecate old way (#1468)\n- Update `fileexporter` to write data in OTLP (#1488)\n- Add extension factory helper (#1485)\n- Host scrapers: Use same scrape time for all data points coming from same source (#1473)\n- Make logs SeverityNumber publicly available (#1496)\n- Add recently included conventions for k8s and container resources (#1519)\n- Add new config StartTimeMetricRegex to `prometheus` receiver (#1511)\n- Convert Zipkin receiver and exporter to use OTLP (#1446)\n\n### 🧰 Bug fixes 🧰\n\n- Infer OpenCensus resource type based on OpenTelemetry's semantic conventions (#1462)\n- Fix log adapter in `prometheus` receiver (#1493)\n- Avoid frequent errors for process telemetry on Windows (#1487)\n\n## v0.7.0 Beta\n\n### 🚀 New components 🚀\n\n- Receivers\n  - `fluentforward` runs a TCP server that accepts events via the [Fluent Forward protocol](https://github.com/fluent/fluentd/wiki/Forward-Protocol-Specification-v1) (#1173)\n- Exporters\n  - `kafka` exports traces to Kafka (#1439)\n- Extensions\n  - **Experimental** `fluentbit` facilitates running a FluentBit subprocess of the collector (#1381)\n\n### 💡 Enhancements 💡\n\n- Updated `golang/protobuf` from v1.3.5 to v1.4.2 (#1308)\n- Updated `opencensus-proto` from v0.2.1 to v0.3.0 (#1308)\n- Added round_robin `balancer_name` as an option to gRPC client settings (#1353)\n- `hostmetrics` receiver\n  - Switch to using perf counters to get disk io metrics on Windows (#1340)\n  - Add device filter for file system (#1379) and disk (#1378) scrapers\n  - Record process physical & virtual memory stats separately (#1403)\n  - Scrape system.disk.time on Windows (#1408)\n  - Add disk.pending_operations metric (#1428)\n  - Add network interface label to network metrics (#1377)\n- Add `exporterhelper` (#1351) and `processorhelper` (#1359) factories\n- Update OTLP to latest version (#1384)\n- Disable timeout, retry on failure and sending queue for `logging` exporter (#1400)\n- Add support for retry and sending queue for `jaeger` exporter (#1401)\n- Add batch size bytes metric to `batch` processor (#1270)\n- `otlp` receiver: Add Log Support (#1444)\n- Allow to configure read/write buffer sizes for http Client (#1447)\n- Update DB conventions to latest and add exception conventions (#1452)\n\n### 🧰 Bug fixes 🧰\n\n- Fix `resource` processor for old metrics (#1412)\n- `jaeger` receiver: Do not try to stop if failed to start. Collector service will do that (#1434)\n\n## v0.6.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- Renamed the metrics generated by `hostmetrics` receiver to match the (currently still pending) OpenTelemetry system metric conventions (#1261) (#1269)\n- Removed `vmmetrics` receiver (#1282)\n- Removed `cpu` scraper `report_per_cpu` config option (#1326)\n\n### 💡 Enhancements 💡\n\n- Added disk merged (#1267) and process count (#1268) metrics to `hostmetrics`\n- Log metric data points in `logging` exporter (#1258)\n- Changed the `batch` processor to not ignore the errors returned by the exporters (#1259)\n- Build and publish MSI (#1153) and DEB/RPM packages (#1278, #1335)\n- Added batch size metric to `batch` processor (#1241)\n- Added log support for `memorylimiter` processor (#1291) and `logging` exporter (#1298)\n- Always add tags for `observability`, other metrics may use them (#1312)\n- Added metrics support (#1313) and allow partial retries in `queued_retry` processor (#1297)\n- Update `resource` processor: introduce `attributes` config parameter to specify actions on attributes similar to `attributes` processor, old config interface is deprecated (#1315)\n- Update memory state labels for non-Linux OSs (#1325)\n- Ensure tcp connection value is provided for all states, even when count is 0 (#1329)\n- Set `batch` processor channel size to num cpus (#1330)\n- Add `send_batch_max_size` config parameter to `batch` processor enforcing hard limit on batch size (#1310)\n- Add support for including a per-RPC authentication to gRPC settings (#1250)\n\n### 🧰 Bug fixes 🧰\n\n- Fixed OTLP waitForReady, not set from config (#1254)\n- Fixed all translation diffs between OTLP and Jaeger (#1222)\n- Disabled `process` scraper for any non Linux/Windows OS (#1328)\n\n## v0.5.0 Beta\n\n### 🛑 Breaking changes 🛑\n\n- **Update OTLP to v0.4.0 (#1142)**: Collector will be incompatible with any other sender or receiver of OTLP protocol\n  of different versions\n- Make \"--new-metrics\" command line flag the default (#1148)\n- Change `endpoint` to `url` in Zipkin exporter config (#1186)\n- Change `tls_credentials` to `tls_settings` in Jaeger receiver config (#1233)\n- OTLP receiver config change for `protocols` to support mTLS (#1223)\n- Remove `export_resource_labels` flag from Zipkin exporter (#1163)\n\n### 🚀 New components 🚀\n\n- Receivers\n  - Added process scraper to the `hostmetrics` receiver (#1047)\n\n### 💡 Enhancements 💡\n\n- otlpexporter: send configured headers in request (#1130)\n- Enable Collector to be run as a Windows service (#1120)\n- Add config for HttpServer (#1196)\n- Allow cors in HTTPServerSettings (#1211)\n- Add a generic grpc server settings config, cleanup client config (#1183)\n- Rely on gRPC to batch and loadbalance between connections instead of custom logic (#1212)\n- Allow to tune the read/write buffers for gRPC clients (#1213)\n- Allow to tune the read/write buffers for gRPC server (#1218)\n\n### 🧰 Bug fixes 🧰\n\n- Handle overlapping metrics from different jobs in prometheus exporter (#1096)\n- Fix handling of SpanKind INTERNAL in OTLP OC translation (#1143)\n- Unify zipkin v1 and v2 annotation/tag parsing logic (#1002)\n- mTLS: Add support to configure client CA and enforce ClientAuth (#1185)\n- Fixed untyped Prometheus receiver bug (#1194)\n- Do not embed ProtocolServerSettings in gRPC (#1210)\n- Add Context to the missing CreateMetricsReceiver method (#1216)\n\n## v0.4.0 Beta\n\nReleased 2020-06-16\n\n### 🛑 Breaking changes 🛑\n\n- `isEnabled` configuration option removed (#909)\n- `thrift_tchannel` protocol moved from `jaeger` receiver to `jaeger_legacy` in contrib (#636)\n\n### ⚠️ Major changes ⚠️\n\n- Switch from `localhost` to `0.0.0.0` by default for all receivers (#1006)\n- Internal API Changes (only impacts contributors)\n  - Add context to `Start` and `Stop` methods in the component (#790)\n  - Rename `AttributeValue` and `AttributeMap` method names (#781)\n    (other breaking changes in the internal trace data types)\n  - Change entire repo to use the new vanityurl go.opentelemetry.io/collector (#977)\n\n### 🚀 New components 🚀\n\n- Receivers\n  - `hostmetrics` receiver with CPU (#862), disk (#921), load (#974), filesystem (#926), memory (#911), network (#930), and virtual memory (#989) support\n- Processors\n  - `batch` for batching received metrics (#1060)\n  - `filter` for filtering (dropping) received metrics (#1001)\n\n### 💡 Enhancements 💡\n\n- `otlp` receiver implement HTTP X-Protobuf (#1021)\n- Exporters: Support mTLS in gRPC exporters (#927)\n- Extensions: Add `zpages` for service (servicez, pipelinez, extensions) (#894)\n\n### 🧰 Bug fixes 🧰\n\n- Add missing logging for metrics at `debug` level (#1108)\n- Fix setting internal status code in `jaeger` receivers (#1105)\n- `zipkin` export fails on span without timestamp when used with `queued_retry` (#1068)\n- Fix `zipkin` receiver status code conversion (#996)\n- Remove extra send/receive annotations with using `zipkin` v1 (#960)\n- Fix resource attribute mutation bug when exporting in `jaeger` proto (#907)\n- Fix metric/spans count, add tests for nil entries in the slices (#787)\n\n### 🧩 Components 🧩\n\n#### Traces\n\n| Receivers  |   Processors   | Exporters  |\n|:----------:|:--------------:|:----------:|\n|   Jaeger   |   Attributes   |    File    |\n| OpenCensus |     Batch      |   Jaeger   |\n|    OTLP    | Memory Limiter |  Logging   |\n|   Zipkin   |  Queued Retry  | OpenCensus |\n|            |    Resource    |    OTLP    |\n|            |    Sampling    |   Zipkin   |\n|            |      Span      |            |\n\n#### Metrics\n\n|  Receivers  |   Processors   | Exporters  |\n|:-----------:|:--------------:|:----------:|\n| HostMetrics |     Batch      |    File    |\n| OpenCensus  |     Filter     |  Logging   |\n|    OTLP     | Memory Limiter | OpenCensus |\n| Prometheus  |                |    OTLP    |\n| VM Metrics  |                | Prometheus |\n\n#### Extensions\n\n- Health Check\n- Performance Profiler\n- zPages\n\n## v0.3.0 Beta\n\nReleased 2020-03-30\n\n### Breaking changes\n\n- Make prometheus receiver config loading strict. #697\n  Prometheus receiver will now fail fast if the config contains unused keys in it.\n\n### Changes and fixes\n\n- Enable best effort serve by default of Prometheus Exporter (https://github.com/orijtech/prometheus-go-metrics-exporter/pull/6)\n- Fix null pointer exception in the logging exporter #743\n- Remove unnecessary condition to have at least one processor #744\n\n### Components\n\n| Receivers / Exporters |   Processors   |      Extensions      |\n|:---------------------:|:--------------:|:--------------------:|\n|        Jaeger         |   Attributes   |     Health Check     |\n|      OpenCensus       |     Batch      | Performance Profiler |\n|     OpenTelemetry     | Memory Limiter |        zPages        |\n|        Zipkin         |  Queued Retry  |                      |\n|                       |    Resource    |                      |\n|                       |    Sampling    |                      |\n|                       |      Span      |                      |\n\n## v0.2.8 Alpha\n\nAlpha v0.2.8 of OpenTelemetry Collector\n\n- Implemented OTLP receiver and exporter.\n- Added ability to pass config to the service programmatically (useful for custom builds).\n- Improved own metrics / observability.\n- Refactored component and factory interface definitions (breaking change #683)\n\n## v0.2.7 Alpha\n\nAlpha v0.2.7 of OpenTelemetry Collector\n\n- Improved error handling on shutdown\n- Partial implementation of new metrics (new obsreport package)\n- Include resource labels for Zipkin exporter\n- New `HASH` action to attribute processor\n\n## v0.2.6 Alpha\n\nAlpha v0.2.6 of OpenTelemetry Collector.\n\n- Update metrics prefix to `otelcol` and expose command line argument to modify the prefix value.\n- Extend Span processor to have include/exclude span logic.\n- Batch dropped span now emits zero when no spans are dropped.\n\n## v0.2.5 Alpha\n\nAlpha v0.2.5 of OpenTelemetry Collector.\n\n- Regexp-based filtering of spans based on service names.\n- Ability to choose strict or regexp matching for include/exclude filters.\n\n## v0.2.4 Alpha\n\nAlpha v0.2.4 of OpenTelemetry Collector.\n\n- Regexp-based filtering of span names.\n- Ability to extract attributes from span names and rename span.\n- File exporter for debugging.\n- Span processor is now enabled by default.\n\n## v0.2.3 Alpha\n\nAlpha v0.2.3 of OpenTelemetry Collector.\n\nChanges:\n21a70d6 Add a memory limiter processor (#498)\n9778b16 Refactor Jaeger Receiver config (#490)\nec4ad0c Remove workers from OpenCensus receiver implementation (#497)\n4e01fa3 Update k8s config to use opentelemetry docker image and configuration (#459)\n\n## v0.2.2 Alpha\n\nAlpha v0.2.2 of OpenTelemetry Collector.\n\nMain changes visible to users since previous release:\n\n- Improved Testbed and added more E2E tests.\n- Made component interfaces more uniform (this is a breaking change).\n\nNote: v0.2.1 never existed and is skipped since it was tainted in some dependencies.\n\n## v0.2.0 Alpha\n\nAlpha v0.2 of OpenTelemetry Collector.\n\nDocker image: omnition/opentelemetry-collector:v0.2.0 (we are working on getting this under an OpenTelemetry org)\n\nMain changes visible to users since previous release:\n\n- Rename from `service` to `collector`, the binary is now named `otelcol`\n\n- Configuration reorganized and using strict mode\n\n- Concurrency issues for pipelines transforming data addressed\n\nCommits:\n\n```terminal\n0e505d5 Refactor config: pipelines now under service (#376)\n402b80c Add Capabilities to Processor and use for Fanout cloning decision (#374)\nb27d824 Use strict mode to read config (#375)\nd769eb5 Fix concurrency handling when data is fanned out (#367)\ndc6b290 Rename all github paths from opentelemetry-service to opentelemetry-collector (#371)\nd038801 Rename otelsvc to otelcol (#365)\nc264e0e Add Include/Exclude logic for Attributes Processor (#363)\n8ce427a Pin a commit for Prometheus dependency in go.mod (#364)\n2393774 Bump Jaeger version to 1.14.0 (latest) (#349)\n63362d5 Update testbed modules (#360)\nc0e2a27 Change dashes to underscores to separate words in config files (#357)\n7609eaa Rename OpenTelemetry Service to Collector in docs and comments (#354)\nbc5b299 Add common gRPC configuration settings (#340)\nb38505c Remove network access popups on macos (#348)\nf7727d1 Fixed loop variable pointer bug in jaeger translator (#341)\n958beed Ensure that ConsumeMetricsData() is not passed empty metrics in the Prometheus receiver (#345)\n0be295f Change log statement in Prometheus receiver from info to debug. (#344)\nd205393 Add Owais to codeowners (#339)\n8fa6afe Translate OC resource labels to Jaeger process tags (#325)\n```\n\n## v0.0.2 Alpha\n\nAlpha release of OpenTelemetry Service.\n\nDocker image: omnition/opentelemetry-service:v0.0.2 (we are working on getting this under an OpenTelemetry org)\n\nMain changes visible to users since previous release:\n\n```terminal\n8fa6afe Translate OC resource labels to Jaeger process tags (#325)\n047b0f3 Allow environment variables in config (#334)\n96c24a3 Add exclude/include spans option to attributes processor (#311)\n4db0414 Allow metric processors to be specified in pipelines (#332)\nc277569 Add observability instrumentation for Prometheus receiver (#327)\nf47aa79 Add common configuration for receiver tls (#288)\na493765 Refactor extensions to new config format (#310)\n41a7afa Add Span Processor logic\n97a71b3 Use full name for the metrics and spans created for observability (#316)\nfed4ed2 Add support to record metrics for metricsexporter (#315)\n5edca32 Add include_filter configuration to prometheus receiver (#298)\n0068d0a Passthrough CORS allowed origins (#260)\n```\n\n## v0.0.1 Alpha\n\nThis is the first alpha release of OpenTelemetry Service.\n\nDocker image: omnition/opentelemetry-service:v0.0.1\n\n[v0.3.0]: https://github.com/open-telemetry/opentelemetry-collector/compare/v0.2.10...v0.3.0\n[v0.2.10]: https://github.com/open-telemetry/opentelemetry-collector/compare/v0.2.8...v0.2.10\n[v0.2.8]: https://github.com/open-telemetry/opentelemetry-collector/compare/v0.2.7...v0.2.8\n[v0.2.7]: https://github.com/open-telemetry/opentelemetry-collector/compare/v0.2.6...v0.2.7\n[v0.2.6]: https://github.com/open-telemetry/opentelemetry-collector/compare/v0.2.5...v0.2.6\n[v0.2.5]: https://github.com/open-telemetry/opentelemetry-collector/compare/v0.2.4...v0.2.5\n[v0.2.4]: https://github.com/open-telemetry/opentelemetry-collector/compare/v0.2.3...v0.2.4\n[v0.2.3]: https://github.com/open-telemetry/opentelemetry-collector/compare/v0.2.2...v0.2.3\n[v0.2.2]: https://github.com/open-telemetry/opentelemetry-collector/compare/v0.2.0...v0.2.2\n[v0.2.0]: https://github.com/open-telemetry/opentelemetry-collector/compare/v0.0.2...v0.2.0\n[v0.0.2]: https://github.com/open-telemetry/opentelemetry-collector/compare/v0.0.1...v0.0.2\n[v0.0.1]: https://github.com/open-telemetry/opentelemetry-collector/tree/v0.0.1\n"
  },
  {
    "path": "CLAUDE.md",
    "content": "@AGENTS.md\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing Guide\n\nWe'd love your help! Please join our weekly [SIG\nmeeting](https://github.com/open-telemetry/community#special-interest-groups).\n\n## Target audiences\n\nThe OpenTelemetry Collector has three main target audiences:\n\n1. *End-users*, aiming to use an OpenTelemetry Collector binary.\n1. *Component developers*, consuming the Go APIs to create components compatible with the OpenTelemetry Collector Builder.\n1. *Collector library users*, consuming other Go APIs exposed by the opentelemetry-collector repository, for example to\n   build custom distributions or other projects building on top of the Collector Go APIs.\n\nWhen the needs of these audiences conflict, end-users should be prioritized, followed by component developers, and\nfinally Collector library users.\n\n### End-users\n\nEnd-users are the target audience for our binary distributions, as made available via the\n[opentelemetry-collector-releases](https://github.com/open-telemetry/opentelemetry-collector-releases) repository, as\nwell as distributions created using the [OpenTelemetry Collector\nBuilder](https://github.com/open-telemetry/opentelemetry-collector/tree/main/cmd/builder). To them, stability in the\nbehavior is important, be it runtime, configuration, or [internal\ntelemetry](https://opentelemetry.io/docs/collector/internal-telemetry/). They are more numerous and harder to get in\ntouch with, making our changes to the Collector more disruptive to them than to other audiences. As a general rule,\nwhenever you are developing OpenTelemetry Collector components (extensions, receivers, processors, exporters,\nconnectors), you should have end-users' interests in mind. Similarly, changes to code within packages like `config` will\nhave an impact on this audience. Make sure to cause minimal disruption when doing changes here.\n\n### Component developers\n\nComponent developers create new extensions, receivers, processors, exporters, and connectors to be used with the\nOpenTelemetry Collector. They are the primary audience for the opentelemetry-collector repository's public Go API. A\nsignificant part of them will contribute to opentelemetry-collector-contrib. In addition to the end-user aspect\nmentioned above, this audience also cares about Go API compatibility of Go modules such as the ones in the `pdata`,\n`component`, `consumer`, `confmap`, `exporterhelper`, `config*` modules and others, even though such changes wouldn't cause any\nimpact to end-users. See the [Breaking changes](docs/coding-guidelines.md#breaking-changes) section\nin the coding guidelines for more information on how to perform changes affecting this audience.\n\n### Collector library users\n\nA third audience uses the OpenTelemetry Collector as a library to build their own distributions or other projects based\non the Collector. This audience is the main consumer of modules such as `service` or `otelcol`. They also share the same\nconcerns as component developers regarding Go API compatibility and are likewise interested in behavior stability. These\nare our most advanced users and are the most equipped to deal with disruptive changes.\n\n## How to structure PRs to get expedient reviews?\n\nWe recommend that PRs be smaller than 500 lines, excluding `go.mod` and `go.sum`\nchanges, to help reviewers perform thorough and timely reviews.\n\nKeep each PR isolated to the specific change it is meant to deliver. Do not bundle unrelated\ncleanup, drive-by edits, opportunistic refactors, wording tweaks, formatting changes, or other\n\"small\" improvements into the same PR unless they are strictly necessary to make the intended\nchange correct. Narrow, focused PRs are significantly easier to review and validate.\n\n### When adding a new component\n\nComponents refer to connectors, exporters, extensions, processors, and receivers. The key criteria for implementing a component is to:\n\n* Implement the `component.Component` interface\n* Provide a configuration structure which defines the configuration of the component\n* Provide the implementation that performs the component operation\n\nFor more details on components, see the [Donating New Components](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/CONTRIBUTING.md#donating-new-components) document and the tutorial [Building a Trace Receiver](https://opentelemetry.io/docs/collector/trace-receiver/) which provides a detailed example of building a component.\n\nWhen adding a new component to the OpenTelemetry Collector, ensure that any configuration structs used by the component include fields with the `configopaque.String` type for sensitive data. This ensures that the data is masked when serialized to prevent accidental exposure.\n\nWhen submitting a component to the community, consider breaking it down into separate PRs as follows:\n\n* **First PR** should include the overall structure of the new component:\n  * Readme, configuration, and factory implementation should usually use the helper\n    factory structs.\n  * This PR is usually trivial to review, so the size limit does not apply to\n    it.\n  * The component should use [`In Development` Stability](https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#development) in its README.\n* **Second PR** should include the concrete implementation of the component. If the\n  size of this PR is larger than the recommended size consider splitting it into\n  multiple PRs.\n* **Last PR** should mark the new component as `Alpha` stability and add it to the `otelcorecol`\n  binary by updating the `otelcorecol/components.go` file. The component must be enabled\n  only after sufficient testing and only when it meets [`Alpha` stability requirements.](https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#alpha)\n* Once a new component has been added to the executable, please add the component\n  to the [OpenTelemetry.io registry](https://github.com/open-telemetry/opentelemetry.io#adding-a-project-to-the-opentelemetry-registry).\n* intra-repository `replace` statements in `go.mod` files can be automatically inserted by running `make crosslink`. For more information\n  on the `crosslink` tool see the README [here](https://github.com/open-telemetry/opentelemetry-go-build-tools/tree/main/crosslink).\n\n### Refactoring Work\n\nAny refactoring work must be split in its own PR that does not include any\nbehavior changes. It is important to do this to avoid hidden changes in large\nand trivial refactoring PRs.\n\nIf you notice additional improvement opportunities while working on a change, handle them in\nfollow-up PRs instead of extending the current one beyond its original scope.\n\n## Report a bug or request a feature\n\nReporting bugs is an important contribution. Please make sure to include:\n\n* Expected and actual behavior\n* The OpenTelemetry version you are running\n* If possible, steps to reproduce\n\n### Adding Labels via Comments\n\nIn order to facilitate proper label usage and to empower Code Owners, you are able to add labels to issues via comments. To add a label through a comment, post a new comment on an issue starting with `/label`, followed by a space-separated list of your desired labels. Supported labels come from the table below, or correspond to a component defined in the [CODEOWNERS file](.github/CODEOWNERS).\n\nThe following general labels are supported:\n\n| Label                    | Label in Comment         |\n|--------------------------|--------------------------|\n| `arm64`                  | `arm64`                  |\n| `good first issue`       | `good-first-issue`       |\n| `help wanted`            | `help-wanted`            |\n| `discussion needed`      | `discussion-needed`      |\n| `os:macos`               | `os:macos`               |\n| `os:windows`             | `os:windows`             |\n| `waiting for author`     | `waiting-for-author`     |\n| `waiting-for-codeowners` | `waiting-for-codeowners` |\n| `bug`                    | `bug`                    |\n| `priority:p0`            | `priority:p0`            |\n| `priority:p1`            | `priority:p1`            |\n| `priority:p2`            | `priority:p2`            |\n| `priority:p3`            | `priority:p3`            |\n| `Stale`                  | `stale`                  |\n\nTo delete a label, prepend the label with `-`. Note that you must make a new comment to modify labels; you cannot edit an existing comment.\n\nExample label comment:\n\n```\n/label help-wanted -arm64\n```\n\n### Rerunning Failed Workflows\n\nPR authors can rerun failed GitHub Actions workflows by commenting `/rerun` on the pull request. This will automatically rerun all failed workflow runs for the PR's latest commit.\n\nExample rerun comment:\n\n```\n/rerun\n```\n\n## How to contribute\n\n### Before you start\n\nPlease read the project contribution\n[guide](https://github.com/open-telemetry/community/tree/main/guides/contributor)\nfor general practices for the OpenTelemetry project.\n\nSelect a good issue from the links below (ordered by difficulty/complexity):\n\n* [Good First Issue](https://github.com/open-telemetry/opentelemetry-collector/issues?utf8=%E2%9C%93&q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22)\n* [Help Wanted](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aissue+is%3Aopen+label%3A%22help+wanted%22)\n\nComment on the issue that you want to work on so we can assign it to you and\nclarify anything related to it.\n\nIf you would like to work on something that is not listed as an issue\n(e.g. a new feature or enhancement) please first read our [vision](docs/vision.md)\nto make sure your proposal aligns with the goals of the\nCollector, then create an issue and describe your proposal. It is best to do this\nin advance so that maintainers can decide if the proposal is a good fit for\nthis repository. This will help avoid situations when you spend significant time\non something that maintainers may decide this repo is not the right place for.\n\nIf you're new to the Collector, the [internal architecture](docs/internal-architecture.md) documentation may be helpful.\n\nFollow the instructions below to create your PR.\n\n### Fork\n\nIn the interest of keeping this repository clean and manageable, you should\nwork from a fork. To create a fork, click the 'Fork' button at the top of the\nrepository, then clone the fork locally using `git clone\ngit@github.com:USERNAME/opentelemetry-collector.git`.\n\nYou should also add this repository as an \"upstream\" repo to your local copy,\nin order to keep it up to date. You can add this as a remote like so:\n\n`git remote add upstream https://github.com/open-telemetry/opentelemetry-collector.git`\n\nVerify that the upstream exists:\n\n`git remote -v`\n\nTo update your fork, fetch the upstream repo's branches and commits, then merge\nyour `main` with upstream's `main`:\n\n```\ngit fetch upstream\ngit checkout main\ngit merge upstream/main\n```\n\nRemember to always work in a branch of your local copy, as you might otherwise\nhave to contend with conflicts in `main`.\n\nPlease also see [GitHub\nworkflow](https://github.com/open-telemetry/community/blob/main/guides/contributor/processes.md#github-workflow)\nsection of the general project contributing guide.\n\n## Required Tools\n\nWorking with the project sources requires the following tools:\n\n1. [git](https://git-scm.com/)\n2. [go](https://golang.org/) (version 1.25 and up)\n3. [make](https://www.gnu.org/software/make/)\n4. [docker](https://www.docker.com/)\n\n## Repository Setup\n\nFork the repo and checkout the upstream repo to your GOPATH by:\n\n```\n$ git clone git@github.com:open-telemetry/opentelemetry-collector.git\n```\n\nAdd your fork as an origin:\n\n```shell\n$ cd opentelemetry-collector\n$ git remote add fork git@github.com:YOUR_GITHUB_USERNAME/opentelemetry-collector.git\n```\n\nRun tests, fmt, and lint:\n\n```shell\n$ make\n```\n\nYou can run `make markdownlint` to check Markdown formatting.\n\n## Creating a PR\n\nCheckout a new branch, make modifications, build locally, and push the branch to your fork\nto open a new PR:\n\n```shell\n$ git checkout -b feature\n# edit\n$ make\n$ make fmt\n$ git commit\n$ git push fork feature\n```\n\n### Commit Messages\n\nUse descriptive commit messages. Here are [some recommendations](https://cbea.ms/git-commit/)\non how to write good commit messages.\nWhen creating PRs GitHub will automatically copy commit messages into the PR description,\nso it is a useful habit to write good commit messages before the PR is created.\nAlso, unless you actually want to tell a story with multiple commits make sure to squash\ninto a single commit before creating the PR.\n\nWhen maintainers merge PRs with multiple commits, they will be squashed and GitHub will\nconcatenate all commit messages right before you hit the \"Confirm squash and merge\"\nbutton. Maintainers must make sure to edit this concatenated message to make it right before merging.\nIn some cases, if the commit messages are lacking the easiest approach to have at\nleast something useful is copy/pasting the PR description into the commit message box\nbefore merging (but see the above paragraph about writing good commit messages in the first place).\n\n## General Notes\n\nThis project uses Go 1.25.* and [Github Actions.](https://github.com/features/actions)\n\nIt is recommended to run `make gofmt all` before submitting your PR.\n\n## Coding Guidelines\n\nSee the [Coding Guidelines](docs/coding-guidelines.md) document for more information.\n\n## Changelog\n\n### Overview\n\nThere are two Changelogs for this repository:\n\n- `CHANGELOG.md` is intended for users of the collector and lists changes that affect the behavior of the collector.\n- `CHANGELOG-API.md` is intended for developers who are importing packages from the collector codebase.\n\n### When to add a Changelog Entry\n\nAn entry into the changelog is required for the following reasons:\n\n- Changes made to the behaviour of the component\n- Changes to the configuration\n- Changes to default settings\n- New components being added\n- Changes to exported elements of a package\n\nIt is reasonable to omit an entry to the changelog under these circumstances:\n\n- Updating test to remove flakiness or improve coverage\n- Updates to the CI/CD process\n- Updates to internal packages\n\nIf there is some uncertainty with regards to if a changelog entry is needed, the recommendation is to create\nan entry to in the event that the change is important to the project consumers.\n\n### Adding a Changelog Entry\n\nThe [CHANGELOG.md](./CHANGELOG.md) and [CHANGELOG-API.md](./CHANGELOG-API.md) files in this repo is autogenerated from `.yaml` files in the `./.chloggen` directory.\n\nYour pull request should add a new `.yaml` file to this directory. The name of your file must be unique since the last release.\n\nDuring the collector release process, all `./chloggen/*.yaml` files are transcribed into `CHANGELOG.md` and `CHANGELOG-API.md` and then deleted.\n\n**Recommended Steps**\n1. Create an entry file using `make chlog-new`. This generates a file based on your current branch (e.g. `./.chloggen/my-branch.yaml`)\n2. Fill in all fields in the new file\n3. Run `make chlog-validate` to ensure the new file is valid\n4. Commit and push the file\n\nAlternatively, copy `./.chloggen/TEMPLATE.yaml`, or just create your file from scratch.\n\n## Local Testing\n\nTo manually test your changes, follow these steps to build and run the Collector\nlocally. Ensure that you execute these commands from the root of the repository:\n\n1. Build the Collector:\n\n  ```shell\n  make otelcorecol\n  ```\n\n2. Run the Collector with a local configuration file:\n\n  ```shell\n  ./bin/otelcorecol_<os>_<arch> --config ./examples/local/otel-config.yaml\n  ```\n\n  The actual name of the binary will depend on your platform, adjust accordingly\n  (e.g., `./bin/otelcorecol_darwin_arm64`).\n\n  Replace `otel-config.yaml` with the appropriate configuration file as needed.\n\n3. Verify that your changes are reflected in the Collector's behavior by testing\n   it against the provided configuration.\n\n## Membership, Roles, and Responsibilities\n\n### Membership levels\n\nSee the [OpenTelemetry membership guide](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md) for information on how to become a member of the OpenTelemetry organization and the different roles available. In addition to the roles listed there we also have a Collector-specific role: code owners.\n\n### Becoming a Code Owner\n\nA Code Owner is responsible for one or multiple packages within the Collector. That responsibility includes maintaining the component, triaging and responding to issues, and reviewing pull requests.\nMaintainers are expected to seek feedback from code owners for changes that are not trivial, but they may merge PRs without code owner approval.\n\nCode Ownership does not have to be a full-time job. If you can find a couple hours to help out on a recurring basis, please consider pursuing Code Ownership.\n\n#### Requirements\n\nIf you would like to help and become a Code Owner, you must meet the following requirements. These are more stringent requirements than those in the opentelemetry-collector-contrib repository due to the higher impact of changes in this repository:\n\n1. [Be a member of the OpenTelemetry organization](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#member).\n2. Be an existing [approver](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#approver) or [maintainer](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#maintainer) in at least one repository within the OpenTelemetry Github organization.\n3. Have made significant contributions directly to the package you want to own.\n\n#### How to become a Code Owner\n\nTo become a Code Owner, open a PR that adds you to the [.github/CODEOWNERS](.github/CODEOWNERS) file. Make sure to ping existing code owners for the package you want to own to get their approval.\n\n## Release\n\nSee [release](docs/release.md) for details.\n\n## Contributing Images\nIf you are adding any new images, please use [Excalidraw](https://excalidraw.com). It's a free and open-source web application and doesn't require any account to get started. Once you've created the design, while exporting the image, make sure to tick **\"Embed scene into exported file\"** option. This allows the image to be imported in an editable format for other contributors later.\n\n## Common Issues\n\nBuild fails due to dependency issues, e.g.\n\n```sh\ngo: github.com/golangci/golangci-lint@v1.31.0 requires\n\tgithub.com/tommy-muehle/go-mnd@v1.3.1-0.20200224220436-e6f9a994e8fa: invalid pseudo-version: git fetch --unshallow -f origin in /root/go/pkg/mod/cache/vcs/053b1e985f53e43f78db2b3feaeb7e40a2ae482c92734ba3982ca463d5bf19ce: exit status 128:\n\tfatal: git fetch-pack: expected shallow list\n ```\n\n`go env GOPROXY` should return `https://proxy.golang.org,direct`. If it does not, set it as an environment variable:\n\n`export GOPROXY=https://proxy.golang.org,direct`\n\n### Makefile Guidelines\n\nWhen adding or modifying the `Makefile`'s in this repository, consider the following design guidelines.\n\nMake targets are organized according to whether they apply to the entire repository, or only to an individual module.\nThe [Makefile](./Makefile) SHOULD contain \"repo-level\" targets. (i.e. targets that apply to the entire repo.)\nLikewise, `Makefile.Common` SHOULD contain \"module-level\" targets. (i.e. targets that apply to one module at a time.)\nEach module should have a `Makefile` at its root that includes `Makefile.Common`.\n\n#### Module-level targets\n\nModule-level targets SHOULD NOT act on nested modules. For example, running `make lint` at the root of the repo will\n_only_ evaluate code that is part of the `go.opentelemetry.io/collector` module. This excludes nested modules such as\n`go.opentelemetry.io/collector/component`.\n\nEach module-level target SHOULD have a corresponding repo-level target. For example, `make golint` will run `make lint`\nin each module. In this way, the entire repository is covered. The root `Makefile` contains some \"for each module\" targets\nthat can wrap a module-level target into a repo-level target.\n\n#### Repo-level targets\n\nWhenever reasonable, targets SHOULD be implemented as module-level targets (and wrapped with a repo-level target).\nHowever, there are many valid justifications for implementing a standalone repo-level target.\n\n1. The target naturally applies to the repo as a whole. (e.g. Building the collector.)\n2. Interaction between modules would be problematic.\n3. A necessary tool does not provide a mechanism for scoping its application. (e.g. `porto` cannot be limited to a specific module.)\n4. The \"for each module\" pattern would result in incomplete coverage of the codebase. (e.g. A target that scans all files, not just `.go` files.)\n\n#### Default targets\n\nThe default module-level target (i.e. running `make` in the context of an individual module), should run a substantial set of module-level\ntargets for an individual module. Ideally, this would include *all* module-level targets, but exceptions should be made if a particular\ntarget would result in unacceptable latency in the local development loop.\n\nThe default repo-level target (i.e. running `make` at the root of the repo) should meaningfully validate the entire repo. This should include\nrunning the default common target for each module as well as additional repo-level targets.\n\n## How to update the OTLP protocol version\n\nWhen a new OTLP version is published, the following steps are required to update this code base:\n\n1. Edit the top-level Makefile's `OPENTELEMETRY_PROTO_VERSION` variable\n2. Run `make genproto`\n3. Inspect modifications to the generated code in `pdata/internal/data/protogen`\n4. When new fields are added in the protocol, make corresponding changes in `pdata/internal/cmd/pdatagen/internal`\n5. Run `make genpdata`\n6. Inspect modifications to the generated code in `pdata/*`\n7. Run `make genproto-cleanup`, to remove temporary files\n8. Update the supported OTLP version in [README.md](./README.md).\n\n## Exceptions\n\nWhile the rules in this and other documents in this repository are what we strive to follow, we acknowledge that it may be unfeasible to apply these rules in some situations. Exceptions to the rules\non this and other documents are acceptable if consensus can be obtained from approvers in the pull request they are proposed.\nA reason for requesting the exception MUST be given in the pull request. Until unanimity is obtained, approvers and maintainers are\nencouraged to discuss the issue at hand. If a consensus (unanimity) cannot be obtained, the maintainers' group is then tasked with making a\ndecision using its regular means (voting, TC help, etc.).\n"
  },
  {
    "path": "LICENSE",
    "content": "\n                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "Makefile",
    "content": "include ./Makefile.Common\n\n# This is the code that we want to run lint, etc.\nALL_SRC := $(shell find . -name '*.go' \\\n\t\t\t\t\t\t\t-not -path './internal/tools/*' \\\n\t\t\t\t\t\t\t-not -path '*/third_party/*' \\\n\t\t\t\t\t\t\t-not -path './pdata/internal/data/protogen/*' \\\n\t\t\t\t\t\t\t-not -path './service/internal/zpages/tmplgen/*' \\\n\t\t\t\t\t\t\t-type f | sort)\n\n# All source code and documents. Used in spell check.\nALL_DOC := $(shell find . \\( -name \"*.md\" -o -name \"*.yaml\" \\) \\\n                                -type f | sort)\n\n# All Markdown files. Used in markdownlint.\nALL_MD := $(shell find . -name \"*.md\" -type f | sort)\n\n# ALL_MODULES includes ./* dirs (excludes . dir)\nALL_MODULES := $(shell find . -mindepth 2 \\\n\t\t\t\t-type f \\\n\t\t\t\t-name \"go.mod\" \\\n\t\t\t\t-not -path \"./internal/tools/*\" \\\n\t\t\t\t-exec dirname {} \\; | sort )\n\nCMD?=\n\nRUN_CONFIG?=examples/local/otel-config.yaml\nCONTRIB_PATH=$(CURDIR)/../opentelemetry-collector-contrib\nCOMP_REL_PATH=cmd/otelcorecol/components.go\nMOD_NAME=go.opentelemetry.io/collector\n\n# Function to execute a command. Note the empty line before endef to make sure each command\n# gets executed separately instead of concatenated with previous one.\n# Accepts command to execute as first parameter.\ndefine exec-command\n$(1)\n\nendef\n\n.DEFAULT_GOAL := all\n\n.PHONY: all\nall: checklicense checkdoc misspell markdownlint goimpi goporto multimod-verify golint gotest\n\nall-modules:\n\t@echo $(ALL_MODULES) | tr ' ' '\\n' | sort\n\n.PHONY: gomoddownload\ngomoddownload:\n\t@$(MAKE) for-all-target TARGET=\"moddownload\"\n\n.PHONY: gotest\ngotest:\n\t@$(MAKE) for-all-target TARGET=\"test\"\n\n.PHONY: gobenchmark\ngobenchmark:\n\t@$(MAKE) for-all-target TARGET=\"benchmark\"\n\tcat `find . -name benchmark.txt` > benchmarks.txt\n\n.PHONY: gotest-with-cover\ngotest-with-cover:\n\t@$(MAKE) for-all-target TARGET=\"test-with-cover\"\n\t$(GOCMD) tool covdata textfmt -i=./coverage/unit -o ./coverage.txt\n\n.PHONY: gotest-with-junit\ngotest-with-junit:\n\t@$(MAKE) for-all-target TARGET=\"test-with-junit\"\n\n.PHONY: goporto\ngoporto:\n\t$(GO_TOOL) porto -w --include-internal --skip-dirs \"^cmd/mdatagen/third_party$$\" ./\n\n.PHONY: for-all\nfor-all:\n\t@echo \"running $${CMD} in root\"\n\t@$${CMD}\n\t@set -e; for dir in $(GOMODULES); do \\\n\t  (cd \"$${dir}\" && \\\n\t  \techo \"running $${CMD} in $${dir}\" && \\\n\t \t$${CMD} ); \\\n\tdone\n\n.PHONY: golint\ngolint:\n\t@$(MAKE) for-all-target TARGET=\"lint\"\n\n.PHONY: gomodernize\ngomodernize:\n\t@$(MAKE) for-all-target TARGET=\"modernize\"\n\n.PHONY: goimpi\ngoimpi:\n\t@$(MAKE) for-all-target TARGET=\"impi\"\n\n.PHONY: gofmt\ngofmt:\n\t@$(MAKE) for-all-target TARGET=\"fmt\"\n\n.PHONY: gotidy\ngotidy:\n\t@$(MAKE) for-all-target TARGET=\"tidy\"\n\n.PHONY: gogenerate\ngogenerate:\n\tcd cmd/mdatagen && $(GOCMD) install .\n\t@$(MAKE) for-all-target TARGET=\"generate\"\n\t$(MAKE) fmt\n\n.PHONY: govulncheck\ngovulncheck:\n\t@$(MAKE) for-all-target TARGET=\"vulncheck\"\n\n.PHONY: addlicense\naddlicense:\n\t@ADDLICENSEOUT=`$(GO_TOOL) addlicense -s=only -y \"\" -c \"The OpenTelemetry Authors\" $(ALL_SRC) 2>&1`; \\\n\t\tif [ \"$$ADDLICENSEOUT\" ]; then \\\n\t\t\techo \"$(ADDLICENSE) FAILED => add License errors:\\n\"; \\\n\t\t\techo \"$$ADDLICENSEOUT\\n\"; \\\n\t\t\texit 1; \\\n\t\telse \\\n\t\t\techo \"Add License finished successfully\"; \\\n\t\tfi\n\n.PHONY: checklicense\nchecklicense:\n\t@licRes=$$(for f in $$(find . -type f \\( -iname '*.go' -o -iname '*.sh' \\) ! -path '**/third_party/*') ; do \\\n\t           awk '/Copyright The OpenTelemetry Authors|generated|GENERATED/ && NR<=3 { found=1; next } END { if (!found) print FILENAME }' $$f; \\\n\t\t\t   awk '/SPDX-License-Identifier: Apache-2.0|generated|GENERATED/ && NR<=4 { found=1; next } END { if (!found) print FILENAME }' $$f; \\\n\t   done); \\\n\t   if [ -n \"$${licRes}\" ]; then \\\n\t           echo \"license header checking failed:\"; echo \"$${licRes}\"; \\\n\t           exit 1; \\\n\t   fi\n\n.PHONY: misspell\nmisspell:\n\t$(GO_TOOL) misspell -error $(ALL_DOC)\n\n.PHONY: markdownlint\nmarkdownlint:\n\tnpx -y markdownlint-cli@0.48.0 -c .markdownlint.yaml --ignore-path .markdownlintignore -- $(ALL_MD)\n\n.PHONY: misspell-correction\nmisspell-correction:\n\t$(GO_TOOL) misspell -w $(ALL_DOC)\n\n.PHONY: run\nrun: otelcorecol\n\t./bin/otelcorecol_$(GOOS)_$(GOARCH) --config ${RUN_CONFIG} ${RUN_ARGS}\n\n# Append root module to all modules\nGOMODULES = $(ALL_MODULES) $(PWD)\n\n# Define a delegation target for each module\n.PHONY: $(GOMODULES)\n$(GOMODULES):\n\t@echo \"Running target '$(TARGET)' in module '$@'\"\n\t$(MAKE) -C $@ $(TARGET)\n\n# Triggers each module's delegation target\n.PHONY: for-all-target\nfor-all-target: $(GOMODULES)\n\n.PHONY: check-component\ncheck-component:\nifndef COMPONENT\n\t$(error COMPONENT variable was not defined)\nendif\n\n# Build the Collector executable.\n.PHONY: otelcorecol\notelcorecol:\n\tpushd cmd/otelcorecol && CGO_ENABLED=0 $(GOCMD) build -trimpath -o ../../bin/otelcorecol_$(GOOS)_$(GOARCH) -tags \"grpcnotrace\" ./... && popd\n\n.PHONY: genotelcorecol\ngenotelcorecol:\n\tpushd cmd/builder/ && $(GOCMD) run ./ --skip-compilation --config ../otelcorecol/builder-config.yaml --output-path ../otelcorecol && popd\n\t$(MAKE) -C cmd/otelcorecol fmt\n\n.PHONY: actionlint\nactionlint:\n\t$(GO_TOOL) actionlint -config-file .github/actionlint.yaml -color .github/workflows/*.yml .github/workflows/*.yaml\n\n.PHONY: ocb\nocb:\n\t$(MAKE) -C cmd/builder config\n\t$(MAKE) -C cmd/builder ocb\n\n# Generate structs, functions and tests for pdata package.\ngenpdata:\n\tcd internal/cmd/pdatagen && $(GOCMD) run main.go -C $(SRC_ROOT)\n\t$(MAKE) -C pdata fmt\n\tcd pdata && $(GO_TOOL) betteralign --generated_files --apply ./... || true\n\nDOCKERCMD ?= docker\nDOCKER_PROTOBUF ?= otel/build-protobuf:0.23.0\n\nPROTO_SRC_DIRS := exporter/exporterhelper/internal/queue\nPROTO_FILES := $(foreach dir,$(PROTO_SRC_DIRS),$(wildcard $(dir)/*.proto))\nPROTOC := $(DOCKERCMD) run --rm -u ${shell id -u} -v${PWD}:${PWD} -w${PWD} ${DOCKER_PROTOBUF} --proto_path=${PWD} --go_out=plugins=grpc,paths=source_relative:.\n\n.PHONY: genproto\ngenproto:\n\t@echo \"Generating Go code for proto files\"\n\t@echo \"Found proto files: $(PROTO_FILES)\"\n\t$(foreach file,$(PROTO_FILES),$(call exec-command,$(PROTOC) $(file)))\n\t$(MAKE) fmt\n\nALL_MOD_PATHS := \"\" $(ALL_MODULES:.%=%)\n\n.PHONY: prepare-contrib\nprepare-contrib:\n\t@echo Setting contrib at $(CONTRIB_PATH) to use this core checkout\n\t@$(MAKE) -j2 -C $(CONTRIB_PATH) for-all CMD=\"$(GOCMD) mod edit \\\n\t\t$(addprefix -replace ,$(join $(ALL_MOD_PATHS:%=go.opentelemetry.io/collector%=),$(ALL_MOD_PATHS:%=$(CURDIR)%)))\"\n\t@$(MAKE) -j2 -C $(CONTRIB_PATH) gotidy\n\n\t@$(MAKE) generate-contrib\n\n# Checks that the HEAD of the contrib repo checked out in CONTRIB_PATH compiles\n# against the current version of this repo.\n.PHONY: check-contrib\ncheck-contrib:\n\t@echo -e \"\\nRunning tests\"\n\t@$(MAKE) -C $(CONTRIB_PATH) gotest\n\n\t@if [ -z \"$(SKIP_RESTORE_CONTRIB)\" ]; then \\\n\t\t$(MAKE) restore-contrib; \\\n\tfi\n\n.PHONY: generate-contrib\ngenerate-contrib:\n\t@echo -e \"\\nGenerating files in contrib\"\n\t$(MAKE) -C $(CONTRIB_PATH) generate GROUP=all\n\n# Restores contrib to its original state after running check-contrib.\n.PHONY: restore-contrib\nrestore-contrib:\n\t@echo -e \"\\nRestoring contrib at $(CONTRIB_PATH) to its original state\"\n\t@$(MAKE) -C $(CONTRIB_PATH) for-all CMD=\"$(GOCMD) mod edit \\\n\t\t$(addprefix -dropreplace ,$(ALL_MOD_PATHS:%=go.opentelemetry.io/collector%))\"\n\t@$(MAKE) -C $(CONTRIB_PATH) for-all CMD=\"$(GOCMD) mod tidy\"\n\n# List of directories where certificates are stored for unit tests.\nCERT_DIRS := localhost|\"\"|config/configgrpc/testdata \\\n             localhost|\"\"|config/confighttp/testdata \\\n             example1|\"-1\"|config/configtls/testdata \\\n             example2|\"-2\"|config/configtls/testdata\ncert-domain = $(firstword $(subst |, ,$1))\ncert-suffix = $(word 2,$(subst |, ,$1))\ncert-dir = $(word 3,$(subst |, ,$1))\n\n# Generate certificates for unit tests relying on certificates.\n.PHONY: certs\ncerts:\n\t$(foreach dir, $(CERT_DIRS), $(call exec-command, @internal/buildscripts/gen-certs.sh -o $(call cert-dir,$(dir)) -s $(call cert-suffix,$(dir)) -m $(call cert-domain,$(dir))))\n\n# Generate certificates for unit tests relying on certificates without copying certs to specific test directories.\n.PHONY: certs-dryrun\ncerts-dryrun:\n\t@internal/buildscripts/gen-certs.sh -d\n\n.PHONY: checkapi\ncheckapi:\n\t$(GO_TOOL) checkapi -folder . -config .checkapi.yaml\n\n# Verify existence of READMEs for components specified as default components in the collector.\n.PHONY: checkdoc\ncheckdoc:\n\t$(GO_TOOL) checkfile --project-path $(CURDIR) --component-rel-path $(COMP_REL_PATH) --module-name $(MOD_NAME) --file-name \"README.md\"\n\n# Construct new API state snapshots\n.PHONY: apidiff-build\napidiff-build:\n\t@$(foreach pkg,$(ALL_PKGS),$(call exec-command,./internal/buildscripts/gen-apidiff.sh -p $(pkg)))\n\n# If we are running in CI, change input directory\nifeq ($(CI), true)\nAPICOMPARE_OPTS=$(COMPARE_OPTS)\nelse\nAPICOMPARE_OPTS=-d \"./internal/data/apidiff\"\nendif\n\n# Compare API state snapshots\n.PHONY: apidiff-compare\napidiff-compare:\n\t@$(foreach pkg,$(ALL_PKGS),$(call exec-command,./internal/buildscripts/compare-apidiff.sh -p $(pkg)))\n\n.PHONY: multimod-verify\nmultimod-verify:\n\t@echo \"Validating versions.yaml\"\n\t$(GO_TOOL) multimod verify\n\nMODSET?=stable\n.PHONY: multimod-prerelease\nmultimod-prerelease:\n\t$(GO_TOOL) multimod prerelease -s=true -b=false -v ./versions.yaml -m ${MODSET}\n\t$(MAKE) gotidy\n\nCOMMIT?=HEAD\nREMOTE?=git@github.com:open-telemetry/opentelemetry-collector.git\n.PHONY: push-tags\npush-tags:\n\t$(GO_TOOL) multimod verify\n\tset -e; for tag in `$(GO_TOOL) multimod tag -m ${MODSET} -c ${COMMIT} --print-tags | grep -v \"Using\" `; do \\\n\t\techo \"pushing tag $${tag}\"; \\\n\t\tgit push ${REMOTE} $${tag}; \\\n\tdone;\n\n.PHONY: check-changes\ncheck-changes:\n\t$(GO_TOOL) multimod diff -p $(PREVIOUS_VERSION) -m $(MODSET)\n\n.PHONY: prepare-release\nprepare-release:\nifndef MODSET\n\t@echo \"MODSET not defined\"\n\t@echo \"usage: make prepare-release RELEASE_CANDIDATE=<version eg 0.53.0> PREVIOUS_VERSION=<version eg 0.52.0> MODSET=beta\"\n\texit 1\nendif\nifdef PREVIOUS_VERSION\n\t@echo \"Previous version $(PREVIOUS_VERSION)\"\nelse\n\t@echo \"PREVIOUS_VERSION not defined\"\n\t@echo \"usage: make prepare-release RELEASE_CANDIDATE=<version eg 0.53.0> PREVIOUS_VERSION=<version eg 0.52.0> MODSET=beta\"\n\texit 1\nendif\nifdef RELEASE_CANDIDATE\n\t@echo \"Preparing ${MODSET} release $(RELEASE_CANDIDATE)\"\nelse\n\t@echo \"RELEASE_CANDIDATE not defined\"\n\t@echo \"usage: make prepare-release RELEASE_CANDIDATE=<version eg 0.53.0> PREVIOUS_VERSION=<version eg 0.52.0> MODSET=beta\"\n\texit 1\nendif\n\t# ensure a clean branch\n\tgit diff -s --exit-code || (echo \"local repository not clean\"; exit 1)\n\t# update files with new version\n\tsed -i.bak 's/$(PREVIOUS_VERSION)/$(RELEASE_CANDIDATE)/g' versions.yaml\n\tsed -i.bak 's/$(PREVIOUS_VERSION)/$(RELEASE_CANDIDATE)/g' ./cmd/builder/internal/builder/config.go\n\tsed -i.bak 's/$(PREVIOUS_VERSION)/$(RELEASE_CANDIDATE)/g' ./cmd/builder/test/core.builder.yaml\n\tsed -i.bak 's/$(PREVIOUS_VERSION)/$(RELEASE_CANDIDATE)/g' ./cmd/otelcorecol/builder-config.yaml\n\tsed -i.bak 's/$(PREVIOUS_VERSION)/$(RELEASE_CANDIDATE)/g' examples/k8s/otel-config.yaml\n\tfind . -name \"*.bak\" -type f -delete\n\t# commit changes before running multimod\n\tgit add .\n\tgit commit -m \"prepare release $(RELEASE_CANDIDATE)\"\n\t$(MAKE) multimod-prerelease\n\t# regenerate files\n\t$(MAKE) -C cmd/builder config\n\t$(MAKE) genotelcorecol\n\tgit add .\n\tgit commit -m \"add multimod changes $(RELEASE_CANDIDATE)\" || (echo \"no multimod changes to commit\")\n\n.PHONY: clean\nclean:\n\ttest -d bin && $(RM) bin/*\n\n.PHONY: checklinks\nchecklinks:\n\tcommand -v $(DOCKERCMD) >/dev/null 2>&1 || { echo >&2 \"$(DOCKERCMD) not installed. Install before continuing\"; exit 1; }\n\t$(DOCKERCMD) run -w /home/repo --rm \\\n\t\t--mount 'type=bind,source='$(PWD)',target=/home/repo' \\\n\t\tlycheeverse/lychee \\\n\t\t--config .github/lychee.toml \\\n\t\t--root-dir /home/repo \\\n\t\t-v \\\n\t\t--no-progress './**/*.md'\n\n# error message \"failed to sync logger:  sync /dev/stderr: inappropriate ioctl for device\"\n# is a known issue but does not affect function.\n.PHONY: crosslink\ncrosslink:\n\t@echo \"Executing crosslink\"\n\t$(GO_TOOL) crosslink --root=$(shell pwd) --prune\n\nFILENAME?=$(shell git branch --show-current)\n.PHONY: chlog-new\nchlog-new:\n\t$(GO_TOOL) chloggen new --config $(CHLOGGEN_CONFIG) --filename $(FILENAME)\n\n.PHONY: chlog-validate\nchlog-validate:\n\t$(GO_TOOL) chloggen validate --config $(CHLOGGEN_CONFIG)\n\n.PHONY: chlog-preview\nchlog-preview:\n\t$(GO_TOOL) chloggen update --config $(CHLOGGEN_CONFIG) --dry\n\n.PHONY: chlog-update\nchlog-update:\n\t$(GO_TOOL) chloggen update --config $(CHLOGGEN_CONFIG) --version $(VERSION)\n\n.PHONY: builder-integration-test\nbuilder-integration-test:\n\tcd ./cmd/builder && ./test/test.sh\n\n.PHONY: mdatagen-test\nmdatagen-test:\n\tcd cmd/mdatagen && $(GOCMD) install .\n\tcd cmd/mdatagen && $(GOCMD) generate ./...\n\tcd cmd/mdatagen && $(MAKE) fmt\n\tcd cmd/mdatagen && $(GOCMD) test ./...\n\nGITHUBGEN_ARGS ?= -skipgithub\nGITHUBGEN := $(GO_TOOL) githubgen $(GITHUBGEN_ARGS)\n\n.PHONY: generate-gh-issue-templates\ngenerate-gh-issue-templates:\n\t$(GITHUBGEN) issue-templates\n\n.PHONY: generate-codeowners\ngenerate-codeowners:\n\t$(GITHUBGEN) --default-codeowner \"open-telemetry/collector-approvers\" codeowners\n\n.PHONY: gengithub\ngengithub: generate-codeowners generate-gh-issue-templates\n\n.PHONY: gendistributions\ngendistributions:\n\t$(GITHUBGEN) distributions\n\n.PHONY: generate-chloggen-components\ngenerate-chloggen-components:\n\t$(GITHUBGEN) chloggen-components\n"
  },
  {
    "path": "Makefile.Common",
    "content": "SHELL = /bin/bash\n# ALL_PKGS is the list of all packages where ALL_SRC files reside.\nALL_PKGS := $(sort $(shell go list ./...))\n# COVER_PKGS is the list of packages to include in the coverage\nCOVER_PKGS := $(shell go list ./... | tr \"\\n\" \",\")\n\nCURR_MOD := $(shell go list -m | tr '/' '-' )\n\nGOCMD?= go\nGOOS := $(shell $(GOCMD) env GOOS)\nGOARCH := $(shell $(GOCMD) env GOARCH)\nGOTEST_TIMEOUT?=240s\n# -race is not supported on windows arm64\nGOTEST_OPT?= -timeout $(GOTEST_TIMEOUT) $(if $(and $(filter windows,$(GOOS)), $(filter arm64,$(GOARCH))),, -race)\n\n# SRC_ROOT is the top of the source tree.\nSRC_ROOT := $(shell git rev-parse --show-toplevel)\n\nTOOLS_MOD_DIR   := $(SRC_ROOT)/internal/tools\nTOOLS_MOD_FILE  := $(TOOLS_MOD_DIR)/go.mod\nGO_TOOL         := $(GOCMD) tool -modfile $(TOOLS_MOD_FILE)\nCHLOGGEN_CONFIG := .chloggen/config.yaml\n# no trailing slash\nJUNIT_OUT_DIR ?= $(TOOLS_MOD_DIR)/testresults\n\n.PHONY: test\ntest:\n    # GODEBUG=fips140=only is used to surface any FIPS-140-3 non-compliant cryptographic\n    # calls into the Go standard library. See: https://go.dev/doc/security/fips140#fips-140-3-mode\n\t# disabling fips only to unblock CI. See https://github.com/open-telemetry/opentelemetry-collector/issues/13925\n\t# GODEBUG=fips140=only $(GO_TOOL) gotestsum --packages=\"./...\" -- $(GOTEST_OPT)\n\t$(GO_TOOL) gotestsum --packages=\"./...\" -- $(GOTEST_OPT)\n\n.PHONY: test-with-cover\ntest-with-cover:\n\tmkdir -p $(PWD)/coverage/unit\n\t$(GO_TOOL) gotestsum \\\n\t\t--packages=\"./...\" -- \\\n\t\t$(GOTEST_OPT) -cover -covermode=atomic -coverpkg $(COVER_PKGS) -args -test.gocoverdir=\"$(PWD)/coverage/unit\"\n\n.PHONY: test-with-junit\ntest-with-junit:\n\tmkdir -p $(JUNIT_OUT_DIR)\n\t$(GO_TOOL) gotestsum \\\n\t\t--packages=\"./...\" --junitfile $(JUNIT_OUT_DIR)/$(CURR_MOD)-junit.xml -- \\\n\t\t$(GOTEST_OPT) ./...\n\n.PHONY: benchmark\nbenchmark:\n\tMEMBENCH=yes $(GO_TOOL) gotestsum \\\n\t\t--packages=\"$(ALL_PKGS)\" -- \\\n\t\t-bench=. -run=notests ./... | tee benchmark.txt\n\n.PHONY: fmt\nfmt: common/gofmt common/goimports common/gofumpt\n\n.PHONY: modernize\nmodernize:\n\t$(GO_TOOL) modernize \\\n\t\t-fix -test -v -any -fmtappendf -forvar -mapsloop -minmax -newexpr -omitzero -plusbuild \\\n\t\t-rangeint -reflecttypefor -slicescontains -slicessort -stditerators -stringscut \\\n\t\t-stringscutprefix -stringsseq -stringsbuilder -testingcontext -unsafefuncs -waitgroup ./...\n\n.PHONY: tidy\ntidy:\n\trm -fr go.sum\n\t$(GOCMD) mod tidy -compat=1.25.0\n\n.PHONY: lint\nlint:\n\t$(GO_TOOL) golangci-lint run\n\n.PHONY: common/gofmt\ncommon/gofmt:\n\tgofmt -w -s ./\n\n.PHONY: common/goimports\ncommon/goimports:\n\t$(GO_TOOL) goimports -w -local go.opentelemetry.io/collector ./\n\n.PHONY: common/gofumpt\ncommon/gofumpt:\n\t$(GO_TOOL) gofumpt -l -w -extra .\n\n.PHONY: vulncheck\nvulncheck:\n\t$(GO_TOOL) govulncheck ./...\n\n.PHONY: generate\ngenerate:\n\t$(GOCMD) generate ./...\n\n.PHONY: impi\nimpi:\n\t$(GO_TOOL) impi \\\n\t\t--local go.opentelemetry.io/collector \\\n\t\t--scheme stdThirdPartyLocal ./...\n\n.PHONY: moddownload\nmoddownload:\n\t$(GOCMD) mod download\n\ntimebenchmark:\n\tgo test -bench=. -benchtime=1s ./...\n"
  },
  {
    "path": "README.md",
    "content": "---\n\n<p align=\"center\">\n  <strong>\n    <a href=\"https://opentelemetry.io/docs/collector/getting-started/\">Getting Started</a>\n    &nbsp;&nbsp;&bull;&nbsp;&nbsp;\n    <a href=\"CONTRIBUTING.md\">Getting Involved</a>\n    &nbsp;&nbsp;&bull;&nbsp;&nbsp;\n    <a href=\"https://cloud-native.slack.com/archives/C01N6P7KR6W\">Getting In Touch</a>\n  </strong>\n</p>\n\n<p align=\"center\">\n  <a href=\"https://github.com/open-telemetry/opentelemetry-collector/actions/workflows/build-and-test.yml?query=branch%3Amain\">\n    <img alt=\"Build Status\" src=\"https://img.shields.io/github/actions/workflow/status/open-telemetry/opentelemetry-collector/build-and-test.yml?branch=main&style=for-the-badge\">\n  </a>\n  <a href=\"https://goreportcard.com/report/github.com/open-telemetry/opentelemetry-collector\">\n    <img alt=\"Go Report Card\" src=\"https://goreportcard.com/badge/github.com/open-telemetry/opentelemetry-collector?style=for-the-badge\">\n  </a>\n  <a href=\"https://codecov.io/gh/open-telemetry/opentelemetry-collector/branch/main/\">\n    <img alt=\"Codecov Status\" src=\"https://img.shields.io/codecov/c/github/open-telemetry/opentelemetry-collector?style=for-the-badge\">\n  </a>\n  <a href=\"https://github.com/open-telemetry/opentelemetry-collector/releases\">\n    <img alt=\"GitHub release (latest by date including pre-releases)\" src=\"https://img.shields.io/github/v/release/open-telemetry/opentelemetry-collector?include_prereleases&style=for-the-badge\">\n  </a>\n  </br>\n  <a href=\"https://www.bestpractices.dev/projects/8404\"><img src=\"https://www.bestpractices.dev/projects/8404/badge\">\n  </a>\n  <a href=\"https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:opentelemetry\">\n    <img alt=\"Fuzzing Status\" src=\"https://oss-fuzz-build-logs.storage.googleapis.com/badges/opentelemetry.svg\">\n  </a>\n</p>\n\n<p align=\"center\">\n  <strong>\n    <a href=\"docs/vision.md\">Vision</a>\n    &nbsp;&nbsp;&bull;&nbsp;&nbsp;\n    <a href=\"https://opentelemetry.io/docs/collector/configuration/\">Configuration</a>\n    &nbsp;&nbsp;&bull;&nbsp;&nbsp;\n    <a href=\"https://opentelemetry.io/docs/collector/internal-telemetry/#use-internal-telemetry-to-monitor-the-collector\">Monitoring</a>\n    &nbsp;&nbsp;&bull;&nbsp;&nbsp;\n    <a href=\"docs/security-best-practices.md\">Security</a>\n    &nbsp;&nbsp;&bull;&nbsp;&nbsp;\n    <a href=\"https://pkg.go.dev/go.opentelemetry.io/collector\">Package</a>\n  </strong>\n</p>\n\n---\n\n# <img src=\"https://opentelemetry.io/img/logos/opentelemetry-logo-nav.png\" alt=\"OpenTelemetry Icon\" width=\"45\" height=\"\"> OpenTelemetry Collector\n\nThe OpenTelemetry Collector offers a vendor-agnostic implementation on how to\nreceive, process and export telemetry data. In addition, it removes the need\nto run, operate and maintain multiple agents/collectors in order to support\nopen-source telemetry data formats (e.g. Jaeger, Prometheus, etc.) to\nmultiple open-source or commercial back-ends.\n\nObjectives:\n\n- Usable: Reasonable default configuration, supports popular protocols, runs and collects out of the box.\n- Performant: Highly stable and performant under varying loads and configurations.\n- Observable: An exemplar of an observable service.\n- Extensible: Customizable without touching the core code.\n- Unified: Single codebase, deployable as an agent or collector with support for traces, metrics and logs.\n\n## Community\n\nThe OpenTelemetry Collector SIG is present at the [#otel-collector](https://cloud-native.slack.com/archives/C01N6P7KR6W)\nchannel on the CNCF Slack and [meets once a week](https://github.com/open-telemetry/community#implementation-sigs) via\nvideo calls. Everyone is invited to join those calls, which typically serves the following purposes:\n\n- meet the humans behind the project\n- get an opinion about specific proposals\n- look for a sponsor for a proposed component after trying already via GitHub and Slack\n- get attention to a specific pull-request that got stuck and is difficult to discuss asynchronously\n\nWe rotate our video calls between three time slots, in order to\nallow everyone to join at least once every three meetings. The rotation order is as follows:\n\nTuesday:\n\n- [17:00 PT](https://dateful.com/convert/pst-pdt-pacific-time?t=1700)\n\nWednesday:\n\n- [09:00 PT](https://dateful.com/convert/pst-pdt-pacific-time?t=0900)\n- [05:00 PT](https://dateful.com/convert/pst-pdt-pacific-time?t=0500)\n\nContributors to the project are also welcome to have ad-hoc meetings for synchronous discussions about specific points.\nPost a note in #otel-collector-dev on Slack inviting others, specifying the topic to be discussed. Unless there are strong\nreasons to keep the meeting private, please make it an open invitation for other contributors to join. Try also to\nidentify who would be the other contributors interested on that topic and in which timezones they are.\n\nRemember that our source of truth is GitHub: every decision made via Slack or video calls has to be recorded in the\nrelevant GitHub issue. Ideally, the agenda items from the meeting notes would include a link to the issue or pull\nrequest where a discussion is happening already. We acknowledge that not everyone can join Slack or the synchronous\ncalls and don't want them to feel excluded.\n\n## Supported OTLP version\n\nThis code base is currently built against using OTLP protocol v1.10.0,\nconsidered Stable. [See the OpenTelemetry Protocol Stability\ndefinition\nhere.](https://github.com/open-telemetry/opentelemetry-proto?tab=readme-ov-file#stability-definition)\n\n## Stability levels\n\nSee [Stability Levels and versioning](docs/component-stability.md) for more details.\n\n## Compatibility\n\nWhen used as a library, the OpenTelemetry Collector attempts to track the currently supported versions of Go, as [defined by the Go team](https://go.dev/doc/devel/release#policy).\nRemoving support for an unsupported Go version is not considered a breaking change.\n\nSupport for Go versions on the OpenTelemetry Collector is updated as follows:\n\n1. The first release after the release of a new Go minor version `N` will add build and tests steps for the new Go minor version.\n2. The first release after the release of a new Go minor version `N` will remove support for Go version `N-2`.\n\nOfficial OpenTelemetry Collector distro binaries will be built with a release in the latest Go minor version series.\n\n## Verifying the images signatures\n\n> [!NOTE]\n> To verify a signed artifact or blob, first [install Cosign](https://docs.sigstore.dev/cosign/system_config/installation/), then follow the instructions below.\n\nWe are signing the images `otel/opentelemetry-collector` and `otel/opentelemetry-collector-contrib` using [sigstore cosign](https://github.com/sigstore/cosign) tool and to verify the signatures you can run the following command:\n\n```console\n$ cosign verify \\\n  --certificate-identity=https://github.com/open-telemetry/opentelemetry-collector-releases/.github/workflows/base-release.yaml@refs/tags/<RELEASE_TAG> \\\n  --certificate-oidc-issuer=https://token.actions.githubusercontent.com \\\n  <OTEL_COLLECTOR_IMAGE>\n```\n\nwhere:\n\n- `<RELEASE_TAG>`: is the release that you want to validate\n- `<OTEL_COLLECTOR_IMAGE>`: is the image that you want to check\n\nExample:\n\n```console\n$ cosign verify --certificate-identity=https://github.com/open-telemetry/opentelemetry-collector-releases/.github/workflows/base-release.yaml@refs/tags/v0.98.0 --certificate-oidc-issuer=https://token.actions.githubusercontent.com ghcr.io/open-telemetry/opentelemetry-collector-releases/opentelemetry-collector-contrib:0.98.0\n\nVerification for ghcr.io/open-telemetry/opentelemetry-collector-releases/opentelemetry-collector-contrib:0.98.0 --\nThe following checks were performed on each of these signatures:\n  - The cosign claims were validated\n  - Existence of the claims in the transparency log was verified offline\n  - The code-signing certificate was verified using trusted certificate authority certificates\n\n[{\"critical\":{\"identity\":{\"docker-reference\":\"ghcr.io/open-telemetry/opentelemetry-collector-releases/opentelemetry-collector-contrib\"},\"image\":{\"docker-manifest-digest\":\"sha256:5cea85bcbc734a3c0a641368e5a4ea9d31b472997e9f2feca57eeb4a147fcf1a\"},\"type\":\"cosign container image signature\"},\"optional\":{\"1.3.6.1.4.1.57264.1.1\":\"https://token.actions.githubusercontent.com\",\"1.3.6.1.4.1.57264.1.2\":\"push\",\"1.3.6.1.4.1.57264.1.3\":\"9e20bf5c142e53070ccb8320a20315fffb41469e\",\"1.3.6.1.4.1.57264.1.4\":\"Release Contrib\",\"1.3.6.1.4.1.57264.1.5\":\"open-telemetry/opentelemetry-collector-releases\",\"1.3.6.1.4.1.57264.1.6\":\"refs/tags/v0.98.0\",\"Bundle\":{\"SignedEntryTimestamp\":\"MEUCIQDdlmNeKXQrHnonwWiHLhLLwFDVDNoOBCn2sv85J9P8mgIgDQFssWJImo1hn38VlojvSCL7Qq5FMmtnGu0oLsNdOm8=\",\"Payload\":{\"body\":\"eyJhcGlWZXJzaW9uIjoiMC4wLjEiLCJraW5kIjoiaGFzaGVkcmVrb3JkIiwic3BlYyI6eyJkYXRhIjp7Imhhc2giOnsiYWxnb3JpdGhtIjoic2hhMjU2IiwidmFsdWUiOiIxMzVjY2RlN2YzZTNhYjU2NmFmYzJhYWU3MDljYmJlNmFhMDZlZWMzNDA2MWNkZjMyNmRhYzM2MmY0NWM4Yjg4In19LCJzaWduYXR1cmUiOnsiY29udGVudCI6Ik1FVUNJUURFbDV6N0diMWRVYkM5KzR4c1VvbDhMcWZNV2hiTzhkdEpwdExyMXhUNWZnSWdTdEwwN1I0ZDA5R2x0ZkV0azJVbmlJSlJhQVdrVDJNWDVtRXJNSlplc2pRPSIsInB1YmxpY0tleSI6eyJjb250ZW50IjoiTFMwdExTMUNSVWRKVGlCRFJWSlVTVVpKUTBGVVJTMHRMUzB0Q2sxSlNVaG9ha05EUW5jeVowRjNTVUpCWjBsVlNETkNjRFZTYlVSU1VpOXphMWg0YVdWUFlrcFhSbmRrUjNNNGQwTm5XVWxMYjFwSmVtb3dSVUYzVFhjS1RucEZWazFDVFVkQk1WVkZRMmhOVFdNeWJHNWpNMUoyWTIxVmRWcEhWakpOVWpSM1NFRlpSRlpSVVVSRmVGWjZZVmRrZW1SSE9YbGFVekZ3WW01U2JBcGpiVEZzV2tkc2FHUkhWWGRJYUdOT1RXcFJkMDVFUlhoTlJGRjRUMFJOTlZkb1kwNU5hbEYzVGtSRmVFMUVVWGxQUkUwMVYycEJRVTFHYTNkRmQxbElDa3R2V2tsNmFqQkRRVkZaU1V0dldrbDZhakJFUVZGalJGRm5RVVZyWlRsSE1ubHNjMjkzYVZZMmRFOVZSazlRVVhNd2NXY3hTSEV5WmpsVUx6UTJZbEFLU1ZSNE0ybFRkVXBhV0hGc1dEUldWV2Q1VlZndmNVazJhblZ2WlZSVEswaG5XVUoyYjBseVNERTFUeTltZEd0VmVtRlBRMEpwZDNkbloxbHZUVUUwUndwQk1WVmtSSGRGUWk5M1VVVkJkMGxJWjBSQlZFSm5UbFpJVTFWRlJFUkJTMEpuWjNKQ1owVkdRbEZqUkVGNlFXUkNaMDVXU0ZFMFJVWm5VVlZHTkRrMUNrdDFNRWhqTm5rek1rNUNTVTFFU21ReVpuWkxNMHBCZDBoM1dVUldVakJxUWtKbmQwWnZRVlV6T1ZCd2VqRlphMFZhWWpWeFRtcHdTMFpYYVhocE5Ga0tXa1E0ZDJkWldVZEJNVlZrUlZGRlFpOTNVamhOU0hGSFpVZG9NR1JJUW5wUGFUaDJXakpzTUdGSVZtbE1iVTUyWWxNNWRtTkhWblZNV0ZKc1lrZFdkQXBhV0ZKNVpWTTVkbU5IVm5Wa1IxWnpXbGN4YkdSSVNqVk1WMDUyWWtkNGJGa3pVblpqYVRGNVdsZDRiRmxZVG14amVUaDFXakpzTUdGSVZtbE1NMlIyQ21OdGRHMWlSemt6WTNrNWFWbFlUbXhNV0Vwc1lrZFdhR015VlhWbFYwWjBZa1ZDZVZwWFducE1NMUpvV2pOTmRtUnFRWFZQVkdkMVRVUkJOVUpuYjNJS1FtZEZSVUZaVHk5TlFVVkNRa04wYjJSSVVuZGplbTkyVEROU2RtRXlWblZNYlVacVpFZHNkbUp1VFhWYU1td3dZVWhXYVdSWVRteGpiVTUyWW01U2JBcGlibEYxV1RJNWRFMUNTVWREYVhOSFFWRlJRbWMzT0hkQlVVbEZRa2hDTVdNeVozZE9aMWxMUzNkWlFrSkJSMFIyZWtGQ1FYZFJiMDlYVlhsTlIwcHRDazVYVFhoT1JFcHNUbFJOZDA1NlFtcFpNa2swVFhwSmQxbFVTWGROZWtVeFdtMWFiVmxxVVhoT1JGazFXbFJCWkVKbmIzSkNaMFZGUVZsUEwwMUJSVVVLUWtFNVUxcFhlR3haV0U1c1NVVk9kbUp1VW5saFYwbDNVRkZaUzB0M1dVSkNRVWRFZG5wQlFrSlJVWFppTTBKc1lta3hNRnBYZUd4aVYxWXdZMjVyZGdwaU0wSnNZbTVTYkdKSFZuUmFXRko1WlZNeGFtSXllSE5hVjA0d1lqTkpkR050Vm5OYVYwWjZXbGhOZDBoM1dVdExkMWxDUWtGSFJIWjZRVUpDWjFGU0NtTnRWbTFqZVRrd1dWZGtla3d6V1hkTWFtczBUR3BCZDA5M1dVdExkMWxDUWtGSFJIWjZRVUpEUVZGMFJFTjBiMlJJVW5kamVtOTJURE5TZG1FeVZuVUtURzFHYW1SSGJIWmliazExV2pKc01HRklWbWxrV0U1c1kyMU9kbUp1VW14aWJsRjFXVEk1ZEUxSlIwbENaMjl5UW1kRlJVRlpUeTlOUVVWS1FraHZUUXBsUjJnd1pFaENlazlwT0haYU1td3dZVWhXYVV4dFRuWmlVemwyWTBkV2RVeFlVbXhpUjFaMFdsaFNlV1ZUT1haalIxWjFaRWRXYzFwWE1XeGtTRW8xQ2t4WFRuWmlSM2hzV1ROU2RtTnBNWGxhVjNoc1dWaE9iR041T0hWYU1td3dZVWhXYVV3elpIWmpiWFJ0WWtjNU0yTjVPV2xaV0U1c1RGaEtiR0pIVm1nS1l6SlZkV1ZYUm5SaVJVSjVXbGRhZWt3elVtaGFNMDEyWkdwQmRVOVVaM1ZOUkVFMFFtZHZja0puUlVWQldVOHZUVUZGUzBKRGIwMUxSR3hzVFdwQ2FRcGFhbFpxVFZSUmVWcFVWWHBOUkdOM1dUSk9hVTlFVFhsTlIwVjVUVVJOZUU1WFdtMWFiVWt3VFZSUk1rOVhWWGRJVVZsTFMzZFpRa0pCUjBSMmVrRkNDa04zVVZCRVFURnVZVmhTYjJSWFNYUmhSemw2WkVkV2EwMUdTVWREYVhOSFFWRlJRbWMzT0hkQlVYZEZVa0Y0UTJGSVVqQmpTRTAyVEhrNWJtRllVbThLWkZkSmRWa3lPWFJNTWpsM1dsYzBkR1JIVm5OYVZ6RnNaRWhLTlV3eU9YZGFWelV3V2xkNGJHSlhWakJqYm10MFdUSTVjMkpIVm1wa1J6bDVURmhLYkFwaVIxWm9ZekpXZWsxRVowZERhWE5IUVZGUlFtYzNPSGRCVVRCRlMyZDNiMDlYVlhsTlIwcHRUbGROZUU1RVNteE9WRTEzVG5wQ2Fsa3lTVFJOZWtsM0NsbFVTWGROZWtVeFdtMWFiVmxxVVhoT1JGazFXbFJCYUVKbmIzSkNaMFZGUVZsUEwwMUJSVTlDUWsxTlJWaEtiRnB1VFhaa1IwWnVZM2s1TWsxRE5EVUtUME0wZDAxQ2EwZERhWE5IUVZGUlFtYzNPSGRCVVRoRlEzZDNTazVFUVhkTmFsVjZUbXBqTWsxRVJVZERhWE5IUVZGUlFtYzNPSGRCVWtGRlNYZDNhQXBoU0ZJd1kwaE5Oa3g1T1c1aFdGSnZaRmRKZFZreU9YUk1NamwzV2xjMGRHUkhWbk5hVnpGc1pFaEtOVTFDWjBkRGFYTkhRVkZSUW1jM09IZEJVa1ZGQ2tObmQwbE9SR3MxVDFSbmQwMUVTWGRuV1hOSFEybHpSMEZSVVVKbk56aDNRVkpKUldaUmVEZGhTRkl3WTBoTk5reDVPVzVoV0ZKdlpGZEpkVmt5T1hRS1RESTVkMXBYTkhSa1IxWnpXbGN4YkdSSVNqVk1NamwzV2xjMU1GcFhlR3hpVjFZd1kyNXJkRmt5T1hOaVIxWnFaRWM1ZVV4WVNteGlSMVpvWXpKV2VncE1lVFZ1WVZoU2IyUlhTWFprTWpsNVlUSmFjMkl6WkhwTU0wcHNZa2RXYUdNeVZYUlpNamwxWkVoS2NGbHBOVFZaVnpGelVVaEtiRnB1VFhaa1IwWnVDbU41T1RKTlF6UTFUME0wZDAxRVowZERhWE5IUVZGUlFtYzNPSGRCVWsxRlMyZDNiMDlYVlhsTlIwcHRUbGROZUU1RVNteE9WRTEzVG5wQ2Fsa3lTVFFLVFhwSmQxbFVTWGROZWtVeFdtMWFiVmxxVVhoT1JGazFXbFJCVlVKbmIzSkNaMFZGUVZsUEwwMUJSVlZDUVZsTlFraENNV015WjNka1VWbExTM2RaUWdwQ1FVZEVkbnBCUWtaUlVtNUVSMVp2WkVoU2QyTjZiM1pNTW1Sd1pFZG9NVmxwTldwaU1qQjJZak5DYkdKcE1UQmFWM2hzWWxkV01HTnVhM1ppTTBKc0NtSnVVbXhpUjFaMFdsaFNlV1ZUTVdwaU1uaHpXbGRPTUdJelNYUmpiVlp6V2xkR2VscFlUWFpaVjA0d1lWYzVkV041T1hsa1Z6VjZUSHBuTWs1RVJYZ0tUbnBGTVU1cVkzWlpXRkl3V2xjeGQyUklUWFpOYWtGWFFtZHZja0puUlVWQldVOHZUVUZGVjBKQlowMUNia0l4V1cxNGNGbDZRMEpwWjFsTFMzZFpRZ3BDUVVoWFpWRkpSVUZuVWpoQ1NHOUJaVUZDTWtGT01EbE5SM0pIZUhoRmVWbDRhMlZJU214dVRuZExhVk5zTmpRemFubDBMelJsUzJOdlFYWkxaVFpQQ2tGQlFVSnFjM1JvUlVOUlFVRkJVVVJCUldOM1VsRkpaMWg2Y2xaME0xQjRkU3ROWVZKRkswUkdORzlGUldNMGVucHphSGR1VDJ4bGMwZGlla2xwYnpNS0wxWmpRMGxSUkZNelJ6QmlNemRhYUhRNGFITjJUSEozYkc1UFFXYzJWRXh1U1ZSS09HTjNkMVEzTW5sMVRVdFlUbFJCUzBKblozRm9hMnBQVUZGUlJBcEJkMDV1UVVSQ2EwRnFRWGxFUkZSYVFqQlRPVXBGYkZsSGJuTnZWVmhLYm04MU5Fc3ZUVUZUTlN0RFFVMU9lbWRqUWpWQ2JrRk5OMWhNUjBoV01HRnhDbVpaY21weFkyOXFia3RaUTAxSFRWRnFjalpUVGt0Q2NVaEtZVGwxTDBSTlQySlpNa0pKTVV0ME4yTnhOemhFT0VOcVMzQmFVblJoYnpadFVVMUVZMk1LUms5M2VYWnhWalJPVld0dlpsRTlQUW90TFMwdExVVk9SQ0JEUlZKVVNVWkpRMEZVUlMwdExTMHRDZz09In19fX0=\",\"integratedTime\":1712809120,\"logIndex\":84797936,\"logID\":\"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d\"}},\"Issuer\":\"https://token.actions.githubusercontent.com\",\"Subject\":\"https://github.com/open-telemetry/opentelemetry-collector-releases/.github/workflows/base-release.yaml@refs/tags/v0.98.0\",\"githubWorkflowName\":\"Release Contrib\",\"githubWorkflowRef\":\"refs/tags/v0.98.0\",\"githubWorkflowRepository\":\"open-telemetry/opentelemetry-collector-releases\",\"githubWorkflowSha\":\"9e20bf5c142e53070ccb8320a20315fffb41469e\",\"githubWorkflowTrigger\":\"push\"}},{\"critical\":{\"identity\":{\"docker-reference\":\"ghcr.io/open-telemetry/opentelemetry-collector-releases/opentelemetry-collector-contrib\"},\"image\":{\"docker-manifest-digest\":\"sha256:5cea85bcbc734a3c0a641368e5a4ea9d31b472997e9f2feca57eeb4a147fcf1a\"},\"type\":\"cosign container image signature\"},\"optional\":{\"1.3.6.1.4.1.57264.1.1\":\"https://token.actions.githubusercontent.com\",\"1.3.6.1.4.1.57264.1.2\":\"push\",\"1.3.6.1.4.1.57264.1.3\":\"9e20bf5c142e53070ccb8320a20315fffb41469e\",\"1.3.6.1.4.1.57264.1.4\":\"Release Contrib\",\"1.3.6.1.4.1.57264.1.5\":\"open-telemetry/opentelemetry-collector-releases\",\"1.3.6.1.4.1.57264.1.6\":\"refs/tags/v0.98.0\",\"Bundle\":{\"SignedEntryTimestamp\":\"MEUCIQD1ehDnPO6fzoPIpeQ3KFuYHHBiX7RcEbpo9B2r7JAlzwIgZ1bsuQz7gAXbNU1IEdsTQgfAnRk3xVXO16GnKXM2sAQ=\",\"Payload\":{\"body\":\"eyJhcGlWZXJzaW9uIjoiMC4wLjEiLCJraW5kIjoiaGFzaGVkcmVrb3JkIiwic3BlYyI6eyJkYXRhIjp7Imhhc2giOnsiYWxnb3JpdGhtIjoic2hhMjU2IiwidmFsdWUiOiIxMzVjY2RlN2YzZTNhYjU2NmFmYzJhYWU3MDljYmJlNmFhMDZlZWMzNDA2MWNkZjMyNmRhYzM2MmY0NWM4Yjg4In19LCJzaWduYXR1cmUiOnsiY29udGVudCI6Ik1FUUNJRU92QXl0aE5RVGNvNHFMdG9GZUVOV0toNCtEK2I5SUxyYWhoa09WMmVBM0FpQjNEL2FpUGd1T05zUlB5alhaWk1hdnlCam0vMkVxNFNUMkZJWHozTnpyYWc9PSIsInB1YmxpY0tleSI6eyJjb250ZW50IjoiTFMwdExTMUNSVWRKVGlCRFJWSlVTVVpKUTBGVVJTMHRMUzB0Q2sxSlNVaHBSRU5EUW5jMlowRjNTVUpCWjBsVlZuRlRLMnd4WXpoMWVFUktOWEppZDAxMlVuaDBSR3hXVW1nMGQwTm5XVWxMYjFwSmVtb3dSVUYzVFhjS1RucEZWazFDVFVkQk1WVkZRMmhOVFdNeWJHNWpNMUoyWTIxVmRWcEhWakpOVWpSM1NFRlpSRlpSVVVSRmVGWjZZVmRrZW1SSE9YbGFVekZ3WW01U2JBcGpiVEZzV2tkc2FHUkhWWGRJYUdOT1RXcFJkMDVFUlhoTlJGRjRUMFJSZVZkb1kwNU5hbEYzVGtSRmVFMUVVWGxQUkZGNVYycEJRVTFHYTNkRmQxbElDa3R2V2tsNmFqQkRRVkZaU1V0dldrbDZhakJFUVZGalJGRm5RVVYyWlRCdGJrRkdRVzl1TVZoUGRIVlRMMXBNT0djeE5YUlJkVmxPTmtRemVUUlBWM0FLT1ZSTFMwUlVkRkJHU2xST1ZrWlJkVTlKUWs1bVJqWk1ORTlGYkd4dlZuUndaSE5uYjB0NVZGTnlPR3hTV1c1S1JIRlBRMEpwTUhkbloxbHdUVUUwUndwQk1WVmtSSGRGUWk5M1VVVkJkMGxJWjBSQlZFSm5UbFpJVTFWRlJFUkJTMEpuWjNKQ1owVkdRbEZqUkVGNlFXUkNaMDVXU0ZFMFJVWm5VVlZDSzFkSENuVmtlRE5IZUcxS1RWUkpUVVJyYW13clJtdzFXRzkzZDBoM1dVUldVakJxUWtKbmQwWnZRVlV6T1ZCd2VqRlphMFZhWWpWeFRtcHdTMFpYYVhocE5Ga0tXa1E0ZDJkWldVZEJNVlZrUlZGRlFpOTNVamhOU0hGSFpVZG9NR1JJUW5wUGFUaDJXakpzTUdGSVZtbE1iVTUyWWxNNWRtTkhWblZNV0ZKc1lrZFdkQXBhV0ZKNVpWTTVkbU5IVm5Wa1IxWnpXbGN4YkdSSVNqVk1WMDUyWWtkNGJGa3pVblpqYVRGNVdsZDRiRmxZVG14amVUaDFXakpzTUdGSVZtbE1NMlIyQ21OdGRHMWlSemt6WTNrNWFWbFlUbXhNV0Vwc1lrZFdhR015VlhWbFYwWjBZa1ZDZVZwWFducE1NMUpvV2pOTmRtUnFRWFZQVkdkMVRVUkJOVUpuYjNJS1FtZEZSVUZaVHk5TlFVVkNRa04wYjJSSVVuZGplbTkyVEROU2RtRXlWblZNYlVacVpFZHNkbUp1VFhWYU1td3dZVWhXYVdSWVRteGpiVTUyWW01U2JBcGlibEYxV1RJNWRFMUNTVWREYVhOSFFWRlJRbWMzT0hkQlVVbEZRa2hDTVdNeVozZE9aMWxMUzNkWlFrSkJSMFIyZWtGQ1FYZFJiMDlYVlhsTlIwcHRDazVYVFhoT1JFcHNUbFJOZDA1NlFtcFpNa2swVFhwSmQxbFVTWGROZWtVeFdtMWFiVmxxVVhoT1JGazFXbFJCWkVKbmIzSkNaMFZGUVZsUEwwMUJSVVVLUWtFNVUxcFhlR3haV0U1c1NVVk9kbUp1VW5saFYwbDNVRkZaUzB0M1dVSkNRVWRFZG5wQlFrSlJVWFppTTBKc1lta3hNRnBYZUd4aVYxWXdZMjVyZGdwaU0wSnNZbTVTYkdKSFZuUmFXRko1WlZNeGFtSXllSE5hVjA0d1lqTkpkR050Vm5OYVYwWjZXbGhOZDBoM1dVdExkMWxDUWtGSFJIWjZRVUpDWjFGU0NtTnRWbTFqZVRrd1dWZGtla3d6V1hkTWFtczBUR3BCZDA5M1dVdExkMWxDUWtGSFJIWjZRVUpEUVZGMFJFTjBiMlJJVW5kamVtOTJURE5TZG1FeVZuVUtURzFHYW1SSGJIWmliazExV2pKc01HRklWbWxrV0U1c1kyMU9kbUp1VW14aWJsRjFXVEk1ZEUxSlIwbENaMjl5UW1kRlJVRlpUeTlOUVVWS1FraHZUUXBsUjJnd1pFaENlazlwT0haYU1td3dZVWhXYVV4dFRuWmlVemwyWTBkV2RVeFlVbXhpUjFaMFdsaFNlV1ZUT1haalIxWjFaRWRXYzFwWE1XeGtTRW8xQ2t4WFRuWmlSM2hzV1ROU2RtTnBNWGxhVjNoc1dWaE9iR041T0hWYU1td3dZVWhXYVV3elpIWmpiWFJ0WWtjNU0yTjVPV2xaV0U1c1RGaEtiR0pIVm1nS1l6SlZkV1ZYUm5SaVJVSjVXbGRhZWt3elVtaGFNMDEyWkdwQmRVOVVaM1ZOUkVFMFFtZHZja0puUlVWQldVOHZUVUZGUzBKRGIwMUxSR3hzVFdwQ2FRcGFhbFpxVFZSUmVWcFVWWHBOUkdOM1dUSk9hVTlFVFhsTlIwVjVUVVJOZUU1WFdtMWFiVWt3VFZSUk1rOVhWWGRJVVZsTFMzZFpRa0pCUjBSMmVrRkNDa04zVVZCRVFURnVZVmhTYjJSWFNYUmhSemw2WkVkV2EwMUdTVWREYVhOSFFWRlJRbWMzT0hkQlVYZEZVa0Y0UTJGSVVqQmpTRTAyVEhrNWJtRllVbThLWkZkSmRWa3lPWFJNTWpsM1dsYzBkR1JIVm5OYVZ6RnNaRWhLTlV3eU9YZGFWelV3V2xkNGJHSlhWakJqYm10MFdUSTVjMkpIVm1wa1J6bDVURmhLYkFwaVIxWm9ZekpXZWsxRVowZERhWE5IUVZGUlFtYzNPSGRCVVRCRlMyZDNiMDlYVlhsTlIwcHRUbGROZUU1RVNteE9WRTEzVG5wQ2Fsa3lTVFJOZWtsM0NsbFVTWGROZWtVeFdtMWFiVmxxVVhoT1JGazFXbFJCYUVKbmIzSkNaMFZGUVZsUEwwMUJSVTlDUWsxTlJWaEtiRnB1VFhaa1IwWnVZM2s1TWsxRE5EVUtUME0wZDAxQ2EwZERhWE5IUVZGUlFtYzNPSGRCVVRoRlEzZDNTazVFUVhkTmFsVjZUbXBqTWsxRVJVZERhWE5IUVZGUlFtYzNPSGRCVWtGRlNYZDNhQXBoU0ZJd1kwaE5Oa3g1T1c1aFdGSnZaRmRKZFZreU9YUk1NamwzV2xjMGRHUkhWbk5hVnpGc1pFaEtOVTFDWjBkRGFYTkhRVkZSUW1jM09IZEJVa1ZGQ2tObmQwbE9SR3MxVDFSbmQwMUVTWGRuV1hOSFEybHpSMEZSVVVKbk56aDNRVkpKUldaUmVEZGhTRkl3WTBoTk5reDVPVzVoV0ZKdlpGZEpkVmt5T1hRS1RESTVkMXBYTkhSa1IxWnpXbGN4YkdSSVNqVk1NamwzV2xjMU1GcFhlR3hpVjFZd1kyNXJkRmt5T1hOaVIxWnFaRWM1ZVV4WVNteGlSMVpvWXpKV2VncE1lVFZ1WVZoU2IyUlhTWFprTWpsNVlUSmFjMkl6WkhwTU0wcHNZa2RXYUdNeVZYUlpNamwxWkVoS2NGbHBOVFZaVnpGelVVaEtiRnB1VFhaa1IwWnVDbU41T1RKTlF6UTFUME0wZDAxRVowZERhWE5IUVZGUlFtYzNPSGRCVWsxRlMyZDNiMDlYVlhsTlIwcHRUbGROZUU1RVNteE9WRTEzVG5wQ2Fsa3lTVFFLVFhwSmQxbFVTWGROZWtVeFdtMWFiVmxxVVhoT1JGazFXbFJCVlVKbmIzSkNaMFZGUVZsUEwwMUJSVlZDUVZsTlFraENNV015WjNka1VWbExTM2RaUWdwQ1FVZEVkbnBCUWtaUlVtNUVSMVp2WkVoU2QyTjZiM1pNTW1Sd1pFZG9NVmxwTldwaU1qQjJZak5DYkdKcE1UQmFWM2hzWWxkV01HTnVhM1ppTTBKc0NtSnVVbXhpUjFaMFdsaFNlV1ZUTVdwaU1uaHpXbGRPTUdJelNYUmpiVlp6V2xkR2VscFlUWFpaVjA0d1lWYzVkV041T1hsa1Z6VjZUSHBuTWs1RVJYZ0tUbnBGTVU1cVkzWlpXRkl3V2xjeGQyUklUWFpOYWtGWFFtZHZja0puUlVWQldVOHZUVUZGVjBKQlowMUNia0l4V1cxNGNGbDZRMEpwZDFsTFMzZFpRZ3BDUVVoWFpWRkpSVUZuVWpsQ1NITkJaVkZDTTBGT01EbE5SM0pIZUhoRmVWbDRhMlZJU214dVRuZExhVk5zTmpRemFubDBMelJsUzJOdlFYWkxaVFpQQ2tGQlFVSnFjM1JvUjJKSlFVRkJVVVJCUldkM1VtZEphRUZQZUZNM2RteDRjVzVGYTBKVVRtSlZVRUpsUkZSbk0waGtlRlkyY0cxWk9FdGliREV6TjNBS1lWUnViMEZwUlVFelMyMUxVbU5uYWxBeVQzSmxORVpyVm5vNU4xaENNWGRsUzBOeWFXazFTMWx2UTB0bVkxRktSREJSZDBObldVbExiMXBKZW1vd1JRcEJkMDFFWVVGQmQxcFJTWGhCUzNwcVpHMUZTV2gzV21Kb1lVSlNlalk1Y1N0MWVrNVZSMmxhYlRWVk4xcE5aWFJMUTFSM1VFTkljRkZQVldvdlVERkJDa2R0YWt3elJucFFObTVpYkRGblNYZFNUbXN6UkhkNWMwOUJUMHhoUVVoR09IaHhZV0ZzT0U5WGNGRmFhRGh4TTJVMVNVSmFXR0ZWVkhocFlWbGFTM29LUXpWS1RGVlNWbnBMTURsd04wVjBUd290TFMwdExVVk9SQ0JEUlZKVVNVWkpRMEZVUlMwdExTMHRDZz09In19fX0=\",\"integratedTime\":1712809122,\"logIndex\":84797940,\"logID\":\"c0d23d6ad406973f9559f3ba2d1ca01f84147d8ffc5b8445c224f98b9591801d\"}},\"Issuer\":\"https://token.actions.githubusercontent.com\",\"Subject\":\"https://github.com/open-telemetry/opentelemetry-collector-releases/.github/workflows/base-release.yaml@refs/tags/v0.98.0\",\"githubWorkflowName\":\"Release Contrib\",\"githubWorkflowRef\":\"refs/tags/v0.98.0\",\"githubWorkflowRepository\":\"open-telemetry/opentelemetry-collector-releases\",\"githubWorkflowSha\":\"9e20bf5c142e53070ccb8320a20315fffb41469e\",\"githubWorkflowTrigger\":\"push\"}}]\n```\n\n> [!NOTE]\n> We started signing the images with release `v0.95.0`\n\n## Contributing\n\nSee the [Contributing Guide](CONTRIBUTING.md) for details.\n\nHere is a list of community roles with current and previous members:\n\n### Maintainers\n\n- [Alex Boten](https://github.com/codeboten), Honeycomb\n- [Bogdan Drutu](https://github.com/bogdandrutu), Snowflake\n- [Dmitrii Anoshin](https://github.com/dmitryax), Splunk\n- [Pablo Baeyens](https://github.com/mx-psi), DataDog\n\nFor more information about the maintainer role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#maintainer).\n\n### Approvers\n\n- [Andrew Wilkins](https://github.com/axw), Elastic\n- [Antoine Toulme](https://github.com/atoulme), Splunk\n- [Damien Mathieu](https://github.com/dmathieu), Elastic\n- [Evan Bradley](https://github.com/evan-bradley), Dynatrace\n- [Jade Guiton](https://github.com/jade-guiton-dd), Datadog\n- [Joshua MacDonald](https://github.com/jmacd), Microsoft\n- [Tyler Helmuth](https://github.com/TylerHelmuth), Honeycomb\n- [Yang Song](https://github.com/songy23), Datadog\n\nFor more information about the approver role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#approver).\n\nIn addition to what is described at the organization-level, the SIG Collector requires all core approvers to take part in rotating\nthe role of the [release manager](./docs/release.md#release-manager).\n\n### Triagers\n\n- [Andrzej Stencel](https://github.com/andrzej-stencel), Elastic\n- [Arthur Silva Sens](https://github.com/ArthurSens), Grafana Labs\n- [Chao Weng](https://github.com/sincejune), AppDynamics\n- [Vihas Makwana](https://github.com/VihasMakwana), Elastic\n- Actively seeking contributors to triage issues\n\nFor more information about the triager role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#triager).\n\n### Emeritus Maintainers\n\n- [Paulo Janotti](https://github.com/pjanotti)\n- [Tigran Najaryan](https://github.com/tigrannajaryan)\n\nFor more information about the emeritus role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#emeritus-maintainerapprovertriager).\n\n### Emeritus Approvers\n\n- [Anthony Mirabella](https://github.com/Aneurysm9)\n- [Daniel Jaglowski](https://github.com/djaglowski)\n- [James Bebbington](https://github.com/james-bebbington)\n- [Jay Camp](https://github.com/jrcamp)\n- [Juraci Paixão Kröhling](https://github.com/jpkrohling)\n- [Nail Islamov](https://github.com/nilebox)\n- [Owais Lone](https://github.com/owais)\n- [Rahul Patel](https://github.com/rghetia)\n- [Steven Karis](https://github.com/sjkaris)\n\nFor more information about the emeritus role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#emeritus-maintainerapprovertriager).\n\n### Emeritus Triagers\n\n- [Alolita Sharma](https://github.com/alolita)\n- [Andrew Hsu](https://github.com/andrewhsu)\n- [Punya Biswal](https://github.com/punya)\n- [Steve Flanders](https://github.com/flands)\n\nFor more information about the emeritus role, see the [community repository](https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#emeritus-maintainerapprovertriager).\n\n### Thanks to all of our contributors!\n\n<a href=\"https://github.com/open-telemetry/opentelemetry-collector/graphs/contributors\">\n  <img alt=\"Repo contributors\" src=\"https://contrib.rocks/image?repo=open-telemetry/opentelemetry-collector\" />\n</a>\n"
  },
  {
    "path": "VERSIONING.md",
    "content": "# Versioning and stability\n\nThe OpenTelemetry Collector SIG produces several artifacts for [a variety of audiences](CONTRIBUTING.md#target-audiences). This document describes the versioning and support policy for these artifacts. These policies are designed so that the following goal can be achieved:\n\n**Users are provided software artifacts of value that are stable and secure.**\n\nThe policies are divided depending on the artifact's target audience. While an artifact is supported, [critical bugs](docs/release.md#bugfix-release-criteria) and security vulnerabilities MUST be addressed. The main criteria for the length of support for an artifact is how easy it is for an artifact's target audience to adapt to disruptive changes.\n\nThese policies reflect the current consensus of the OpenTelemetry Collector SIG. They are subject to change as the project evolves.\n\n## Software artifacts for end users\n\nSoftware artifacts intended for [end users](CONTRIBUTING.md#end-users) of the OpenTelemetry Collector include \n- Binary distributions of the OpenTelemetry Collector.\n- Go modules that expose Collector components, such as receivers, processors, connectors, extensions and exporters. \n\nThese artifacts are versioned according to the [semantic versioning v2.0.0](https://semver.org/) specification.\n\n### General considerations\n\nBinary distributions produced by the Collector SIG contain components and features with varying [levels of stability](README.md#stability-levels). We abide by the following principles to relate the Collector's version to the stability of its components and features:\n\n* The Collector's core framework behavior MUST be stable in order for a Collector distribution to be v1.0.0 or higher.\n* Users can easily understand when they are opting in to use a component or feature that is not stable.\n    * The Collector MUST be configurable so that unstable components or features can be excluded ensuring that a fully stable configuration is possible.\n    * The Collector's telemetry (e.g. Collector logs) MUST provide the ability to identify usage of unstable components or features.\n\n### Long-term support after v1\n\nThe OpenTelemetry Collector SIG provides long-term support for stable binary distributions of the OpenTelemetry Collector and its components. The following policies apply to long-term support for any major version starting on v1:\n\n* A binary distribution of the OpenTelemetry Collector MUST be supported for a minimum of **one year** after the release of the next major version of said distribution.\n* Components MUST be supported for a minimum of **6 months** after the release of the next major version of said component or after the component has been marked as deprecated. If a component has been deprecated for 6 months it MAY be removed from a binary distribution of the OpenTelemetry Collector. This does not imply a major version change in the Collector distribution.\n\n## Go modules\n\nGo modules are intended to be used by [component developers](CONTRIBUTING.md#component-developers) and [Collector library users](CONTRIBUTING.md#collector-library-users) of the OpenTelemetry Collector\n\nUnless otherwise specified, the following public API expectations apply to all modules in opentelemetry-collector and opentelemetry-collector-contrib.\nAs a general rule, stability guarantees of modules versioned as `v1` or higher are aligned with [Go 1 compatibility promise](https://go.dev/doc/go1compat).\n\n### General Go API considerations\n\nOpenTelemetry authors reserve the right to introduce API changes breaking compatibility between minor versions in the following scenarios:\n* **Struct literals.** It may be necessary to add new fields to exported structs in the API. Code that uses unkeyed\n  struct literals (such as pkg.T{3, \"x\"}) to create values of these types would fail to compile after such a change.\n  However, code that uses keyed literals (pkg.T{A: 3, B: \"x\"}) will continue to compile. We therefore recommend \n  using OpenTelemetry collector structs with the keyed literals only.\n* **Methods.** As with struct fields, it may be necessary to add methods to types. Under some circumstances,\n  such as when the type is embedded in a struct along with another type, the addition of the new method may \n  break the struct by creating a conflict with an existing method of the other embedded type. We cannot protect \n  against this rare case and do not guarantee compatibility in such scenarios.\n* **Dot imports.** If a program imports a package using `import .`, additional names defined in the imported package\n  in future releases may conflict with other names defined in the program. We do not recommend the use of\n  `import .` with OpenTelemetry Collector modules.\n\nUnless otherwise specified in the documentation, the following may change in any way between minor versions:\n* **String representation**. The `String` or `Error` method of any struct is intended to be human-readable and may\n change its output in any way.\n* **Go version compatibility**. Removing support for an unsupported Go version is not considered a breaking change.\n* **OS version compatibility**. Removing support for an unsupported OS version is not considered a breaking change. Upgrading or downgrading OS version support per the [platform support](docs/platform-support.md) document is not considered a breaking change.\n* **Protocol compatibility**. Changing the default minimum version of a supported protocol (e.g. TLS) or dropping support for protocols when there are security concerns is not considered a breaking change.\n* **Dependency updates**. Updating dependencies is not considered a breaking change except when their types are part of the\npublic API or the update may change the behavior of applications in an incompatible way.\n* **Underlying type for interfaces**. If a struct exported as an interface has an experimental\nmethod, this method may change or be removed in a minor version. The method will be published in an\noptional interface under an experimental module to signal it is experimental.\n\n### Configuration structures\n\nConfiguration structures are part of the public API and backwards\ncompatibility should be maintained through any changes made to configuration structures.\n\nUnless otherwise specified in the documentation, the following may change in any way between minor versions:\n* **Adding new fields to configuration structures**. Because configuration structures are typically instantiated through \nunmarshalling a serialized representation of the structure, and not through structure literals, additive changes to \nthe set of exported fields in a configuration structure are not considered to break backward compatibility.\n* **Relaxing validation rules**. An invalid configuration struct as defined by its `Validate` method return value\nmay become valid after a change to the validation rules.\n\nThe following are explicitly considered to be breaking changes:\n* **Modifying struct tags related to serialization**. Struct tags used to configure serialization mechanisms (`yaml:`, \n`mapstructure:`, etc) are part of the structure definition and must maintain compatibility to the same extent as the \nstructure. However, changes are allowed when tag modifications produce a\nfunctionally-equivalent result when serializing or deserializing the structure.\nFor example, adding a tag to a field so it will not be emitted during serialization\nif it has a default value would not alter its value if the serialized representation\nwere again deserialized, so such a change would be permitted.\n* **Making validation rules more strict**. A valid configuration struct as defined by its `Validate` method return value\nmust continue to be valid after a change to the validation rules, except when the configuration struct would cause an error\non its intended usage (e.g. when calling a method or when passed to any method or function in any module under opentelemetry-collector).\n\n### Module versioning and schema\n\n* Versioning of this project will be idiomatic of a Go project using [Go\n  modules](https://golang.org/ref/mod#versions).\n    * [Semantic import\n      versioning](https://github.com/golang/go/wiki/Modules#semantic-import-versioning)\n      will be used.\n        * Versions will comply with [semver 2.0](https://semver.org/spec/v2.0.0.html).\n        * If a module is version `v2` or higher, the major version of the module\n          must be included as a `/vN` at the end of the module paths used in\n          `go.mod` files (e.g., `module go.opentelemetry.io/collector/v2`, `require\n          go.opentelemetry.io/collector/v2 v2.0.1`) and in the package import path\n          (e.g., `import \"go.opentelemetry.io/collector/v2/component\"`). This includes the\n          paths used in `go get` commands (e.g., `go get\n          go.opentelemetry.io/collector/v2@v2.0.1`.  Note there is both a `/v2` and a\n          `@v2.0.1` in that example. One way to think about it is that the module\n          name now includes the `/v2`, so include `/v2` whenever you are using the\n          module name).\n        * If a module is version `v0` or `v1`, do not include the major version in\n          either the module path or the import path.\n        * Semantic convention packages will contain a complete version identifier in their\n          import path to enable concurrent use of multiple convention versions in a single\n          application. This identifies the version of the specification used to generate\n          the package and is not related to the version of the module containing the package.\n    * A single module should exist, rooted at the top level of this repository,\n      that contains all packages provided for use outside this repository.\n    * Additional modules may be created in this repository to provide for\n      isolation of build-time tools, other commands or independent libraries. Such modules should be\n      versioned in sync with the `go.opentelemetry.io/collector` module.\n    * Experimental modules still under active development will be versioned with a major\n      version of `v0` to imply the stability guarantee defined by\n      [semver](https://semver.org/spec/v2.0.0.html#spec-item-4).\n\n      > Major version zero (0.y.z) is for initial development. Anything MAY\n      > change at any time. The public API SHOULD NOT be considered stable.\n* Versioning of the associated [contrib\n  repository](https://github.com/open-telemetry/opentelemetry-collector-contrib) of\n  this project will be idiomatic of a Go project using [Go\n  modules](https://golang.org/ref/mod#versions).\n    * [Semantic import\n      versioning](https://github.com/golang/go/wiki/Modules#semantic-import-versioning)\n      will be used.\n        * Versions will comply with [semver 2.0](https://semver.org/spec/v2.0.0.html).\n        * If a module is version `v2` or higher, the\n          major version of the module must be included as a `/vN` at the end of the\n          module paths used in `go.mod` files (e.g., `module\n          github.com/open-telemetry/opentelemetry-collector-contrib/processor/k8sprocessor/v2`, `require\n          github.com/open-telemetry/opentelemetry-collector-contrib/processor/k8sprocessor/v2 v2.0.1`) and in the\n          package import path (e.g., `import\n          \"github.com/open-telemetry/opentelemetry-collector-contrib/processor/k8sprocessor/v2\"`). This includes\n          the paths used in `go get` commands (e.g., `go get\n          github.com/open-telemetry/opentelemetry-collector-contrib/processor/k8sprocessor/v2@v2.0.1`.  Note there\n          is both a `/v2` and a `@v2.0.1` in that example. One way to think about\n          it is that the module name now includes the `/v2`, so include `/v2`\n          whenever you are using the module name).\n        * If a module is version `v0` or `v1`, do not include the major version\n          in either the module path or the import path.\n    * Modules will be used to encapsulate receivers, processors, exporters,\n      extensions, connectors and any other independent sets of related components.\n        * Experimental modules still under active development will be versioned with a major\n          version of `v0` to imply the stability guarantee defined by\n          [semver](https://semver.org/spec/v2.0.0.html#spec-item-4).\n\n          > Major version zero (0.y.z) is for initial development. Anything MAY\n          > change at any time. The public API SHOULD NOT be considered stable.\n\n        * Experimental modules will start their versioning at `v0.0.0` and will\n          increment their minor version when backwards incompatible changes are\n          released and increment their patch version when backwards compatible\n          changes are released.\n        * Mature modules for which we guarantee a stable public API will\n          be versioned with a major version of `v1` or greater.\n        * All stable contrib modules of the same major version with this project\n          will use the same entire version.\n            * Stable modules may be released with an incremented minor or patch\n              version even though that module's code has not been changed. Instead\n              the only change that will have been included is to have updated that\n              modules dependency on this project's stable APIs.\n    * Contrib modules will be kept up to date with this project's releases.\n* GitHub releases will be made for all releases.\n* Go modules will be made available at Go package mirrors.\n\n### Long-term support after v1\n\nThe OpenTelemetry Collector SIG provides long-term support for stable Go modules. Support for modules depend on the module's [target audiences](CONTRIBUTING.md#target-audiences). The following policies apply to long-term support for any major version starting on v1:\n\n- Modules intended for **component developers** MUST be supported for a minimum of **1 year** after the release of the next major version of said module or after the module has been marked as deprecated.\n- Modules intended for **Collector library users** MUST be supported for a minimum of **6 months** after the release of the next major version of said module or after the module has been marked as deprecated.\n"
  },
  {
    "path": "client/Makefile",
    "content": "include ../Makefile.Common\n"
  },
  {
    "path": "client/client.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package client contains generic representations of clients connecting to\n// different receivers. Components, such as processors or exporters, can make\n// use of this information to make decisions related to grouping of batches,\n// tenancy, load balancing, tagging, among others.\n//\n// The structs defined here are typically used within the context that is\n// propagated down the pipeline, with the values being produced by\n// authenticators and/or receivers, and consumed by processors and exporters.\n//\n// # Producers\n//\n// Receivers are responsible for obtaining a client.Info from the current\n// context and enhancing the client.Info with the net.Addr from the peer,\n// storing a new client.Info into the context that it passes down. For HTTP\n// requests, the net.Addr is typically the IP address of the client.\n//\n// Typically, however, receivers would delegate this processing to helpers such\n// as the confighttp or configgrpc packages: both contain interceptors that will\n// enhance the context with the client.Info, such that no actions are needed by\n// receivers that are built using confighttp.HTTPServerSettings or\n// configgrpc.GRPCServerSettings.\n//\n// Authenticators are responsible for obtaining a client.Info from the current\n// context, enhancing the client.Info with an implementation of client.AuthData,\n// and storing a new client.Info into the context that it passes down. The\n// attribute names should be documented with their return types and considered\n// part of the public API for the authenticator.\n//\n// # Consumers\n//\n// Provided that the pipeline does not contain processors that would discard or\n// rewrite the context, such as the batch processor, processors and exporters\n// have access to the client.Info via client.FromContext. Among other usages,\n// this data can be used to:\n//\n// - annotate data points with authentication data (username, tenant, ...)\n//\n// - route data points based on authentication data\n//\n// - rate limit client calls based on IP addresses\n//\n// Processors and exporters relying on the existence of data from the\n// client.Info, especially client.AuthData, should clearly document this as part\n// of the component's README file. The expected pattern for consuming data is to\n// allow users to specify the attribute name to use in the component. The\n// expected data type should also be communicated to users, who should then\n// compare this with the authenticators that are part of the pipeline. For\n// example, assuming that the OIDC authenticator pushes a \"subject\" string\n// attribute and that we have a hypothetical \"authprinter\" processor that prints\n// the \"username\" to the console, this is how an OpenTelemetry Collector\n// configuration would look like:\n//\n//\textensions:\n//\t  oidc:\n//\t    issuer_url: http://localhost:8080/auth/realms/opentelemetry\n//\t    audience: collector\n//\treceivers:\n//\t  otlp:\n//\t    protocols:\n//\t      grpc:\n//\t        auth:\n//\t          authenticator: oidc\n//\tprocessors:\n//\t  authprinter:\n//\t    attribute: subject\n//\texporters:\n//\t  debug:\n//\tservice:\n//\t  extensions: [oidc]\n//\t  pipelines:\n//\t    traces:\n//\t      receivers: [otlp]\n//\t      processors: [authprinter]\n//\t      exporters: [debug]\npackage client // import \"go.opentelemetry.io/collector/client\"\n\nimport (\n\t\"context\"\n\t\"iter\"\n\t\"maps\"\n\t\"net\"\n\t\"strings\"\n)\n\ntype ctxKey struct{}\n\n// Info contains data related to the clients connecting to receivers.\ntype Info struct {\n\t// Addr for the client connecting to this collector. Available in a\n\t// best-effort basis, and generally reliable for receivers making use of\n\t// confighttp.ToServer and configgrpc.ToServerOption.\n\tAddr net.Addr\n\n\t// Auth information from the incoming request as provided by\n\t// configauth.ServerAuthenticator implementations tied to the receiver for\n\t// this connection.\n\tAuth AuthData\n\n\t// Metadata is the request metadata from the client connecting to this connector.\n\tMetadata Metadata\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// AuthData represents the authentication data as seen by authenticators tied to\n// the receivers.\ntype AuthData interface {\n\t// GetAttribute returns the value for the given attribute. Authenticator\n\t// implementations might define different data types for different\n\t// attributes. While \"string\" is used most of the time, a key named\n\t// \"membership\" might return a list of strings.\n\tGetAttribute(string) any\n\n\t// GetAttributeNames returns the names of all attributes in this authentication data.\n\tGetAttributeNames() []string\n}\n\nconst MetadataHostName = \"Host\"\n\n// NewContext takes an existing context and derives a new context with the\n// client.Info value stored on it.\nfunc NewContext(ctx context.Context, c Info) context.Context {\n\treturn context.WithValue(ctx, ctxKey{}, c)\n}\n\n// FromContext takes a context and returns a ClientInfo from it.\n// When a ClientInfo isn't present, a new empty one is returned.\nfunc FromContext(ctx context.Context) Info {\n\tc, ok := ctx.Value(ctxKey{}).(Info)\n\tif !ok {\n\t\tc = Info{}\n\t}\n\treturn c\n}\n\n// Metadata is an immutable map, meant to contain request metadata.\ntype Metadata struct {\n\tdata map[string][]string\n}\n\n// NewMetadata creates a new Metadata object to use in Info.\nfunc NewMetadata(md map[string][]string) Metadata {\n\tc := make(map[string][]string, len(md))\n\tfor k, v := range md {\n\t\tc[strings.ToLower(k)] = v\n\t}\n\treturn Metadata{\n\t\tdata: c,\n\t}\n}\n\n// Keys returns an iterator for the metadata keys.\nfunc (m Metadata) Keys() iter.Seq[string] {\n\treturn maps.Keys(m.data)\n}\n\n// Get gets the value of the key from metadata, returning a copy.\n// The key lookup is case-insensitive.\nfunc (m Metadata) Get(key string) []string {\n\tif len(m.data) == 0 {\n\t\treturn nil\n\t}\n\n\tvals := m.data[strings.ToLower(key)]\n\tif len(vals) == 0 {\n\t\treturn nil\n\t}\n\n\tret := make([]string, len(vals))\n\tcopy(ret, vals)\n\n\treturn ret\n}\n"
  },
  {
    "path": "client/client_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package client contains generic representations of clients connecting to\n// different receivers\npackage client\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"slices\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestNewContext(t *testing.T) {\n\ttestCases := []struct {\n\t\tname string\n\t\tcl   Info\n\t}{\n\t\t{\n\t\t\tname: \"valid client\",\n\t\t\tcl: Info{\n\t\t\t\tAddr: &net.IPAddr{\n\t\t\t\t\tIP: net.IPv4(1, 2, 3, 4),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"nil client\",\n\t\t\tcl:   Info{},\n\t\t},\n\t}\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tctx := NewContext(context.Background(), tt.cl)\n\t\t\tassert.Equal(t, ctx.Value(ctxKey{}), tt.cl)\n\t\t})\n\t}\n}\n\nfunc TestFromContext(t *testing.T) {\n\ttestCases := []struct {\n\t\tname     string\n\t\tinput    context.Context\n\t\texpected Info\n\t}{\n\t\t{\n\t\t\tname: \"context with client\",\n\t\t\tinput: context.WithValue(context.Background(), ctxKey{}, Info{\n\t\t\t\tAddr: &net.IPAddr{\n\t\t\t\t\tIP: net.IPv4(1, 2, 3, 4),\n\t\t\t\t},\n\t\t\t}),\n\t\t\texpected: Info{\n\t\t\t\tAddr: &net.IPAddr{\n\t\t\t\t\tIP: net.IPv4(1, 2, 3, 4),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:     \"context without client\",\n\t\t\tinput:    context.Background(),\n\t\t\texpected: Info{},\n\t\t},\n\t\t{\n\t\t\tname:     \"context with something else in the key\",\n\t\t\tinput:    context.WithValue(context.Background(), ctxKey{}, \"unexpected!\"),\n\t\t\texpected: Info{},\n\t\t},\n\t}\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tassert.Equal(t, tt.expected, FromContext(tt.input))\n\t\t})\n\t}\n}\n\nfunc TestMetadata(t *testing.T) {\n\tsource := map[string][]string{\"test-key\": {\"test-val\"}, \"TEST-KEY-2\": {\"test-val\"}}\n\tmd := NewMetadata(source)\n\tassert.Equal(t, []string{\"test-key\", \"test-key-2\"}, slices.Sorted(md.Keys()))\n\tassert.Equal(t, []string{\"test-val\"}, md.Get(\"test-key\"))\n\tassert.Equal(t, []string{\"test-val\"}, md.Get(\"test-KEY\"))   // case insensitive lookup\n\tassert.Equal(t, []string{\"test-val\"}, md.Get(\"test-key-2\")) // case insensitive lookup\n\n\t// test if copy. In regular use, source cannot change\n\tval := md.Get(\"test-key\")\n\tsource[\"test-key\"][0] = \"abc\"\n\tassert.Equal(t, []string{\"test-val\"}, val)\n\n\tassert.Empty(t, md.Get(\"non-existent-key\"))\n}\n\nfunc TestUninstantiatedMetadata(t *testing.T) {\n\ti := Info{}\n\tassert.Empty(t, slices.Collect(i.Metadata.Keys()))\n\tassert.Empty(t, i.Metadata.Get(\"test\"))\n}\n"
  },
  {
    "path": "client/doc_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage client_test\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\"\n\n\t\"go.opentelemetry.io/collector/client\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nfunc Example_receiver() {\n\t// Your receiver get a next consumer when it's constructed\n\tnext, err := consumer.NewTraces(func(_ context.Context, _ ptrace.Traces) error {\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// You'll convert the incoming data into pipeline data\n\ttd := ptrace.NewTraces()\n\n\t// You probably have a context with client metadata from your listener or\n\t// scraper\n\tctx := context.Background()\n\n\t// Get the client from the context: if it doesn't exist, FromContext will\n\t// create one\n\tcl := client.FromContext(ctx)\n\n\t// Extract the client information based on your original context and set it\n\t// to Addr\n\t//nolint:govet\n\tcl.Addr = &net.IPAddr{\n\t\tIP: net.IPv4(1, 2, 3, 4),\n\t}\n\n\t// When you are done, propagate the context down the pipeline to the next\n\t// consumer and handle error.\n\tif err = next.ConsumeTraces(ctx, td); err != nil {\n\t\tpanic(err)\n\t}\n}\n\nfunc Example_processor() {\n\t// Your processor or exporter will receive a context, from which you get the\n\t// client information\n\tctx := context.Background()\n\tcl := client.FromContext(ctx)\n\n\t// And use the information from the client as you need\n\tfmt.Println(cl.Addr)\n}\n\nfunc Example_authenticator() {\n\t// Your configauth.AuthenticateFunc receives a context\n\tctx := context.Background()\n\n\t// Get the client from the context: if it doesn't exist, FromContext will\n\t// create one\n\tcl := client.FromContext(ctx)\n\n\t// After a successful authentication, place the data you want to propagate\n\t// as part of an AuthData implementation of your own\n\tcl.Auth = &exampleAuthData{\n\t\tusername: \"jdoe\",\n\t}\n\n\t// Your configauth.AuthenticateFunc should return this new context\n\t_ = client.NewContext(ctx, cl)\n}\n\ntype exampleAuthData struct {\n\tusername string\n}\n\nfunc (e *exampleAuthData) GetAttribute(key string) any {\n\tif key == \"username\" {\n\t\treturn e.username\n\t}\n\treturn nil\n}\n\nfunc (e *exampleAuthData) GetAttributeNames() []string {\n\treturn []string{\"username\"}\n}\n"
  },
  {
    "path": "client/go.mod",
    "content": "module go.opentelemetry.io/collector/client\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/consumer => ../consumer\n\nreplace go.opentelemetry.io/collector/pdata => ../pdata\n\nreplace go.opentelemetry.io/collector/featuregate => ../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../internal/testutil\n"
  },
  {
    "path": "client/go.sum",
    "content": "github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "client/metadata.yaml",
    "content": "type: client\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "client/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage client\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "cmd/builder/Makefile",
    "content": "include ../../Makefile.Common\n\n.PHONY: ocb\nocb:\n\tCGO_ENABLED=0 $(GOCMD) build -trimpath -o ../../bin/ocb_$(GOOS)_$(GOARCH) .\n\n# Generate the default build config from otelcorecol, by removing the\n# \"replaces\" stanza, which is assumed to be at the end of the file.\n#\n# The default config file is checked in so that `go install` will work\n# and so that non-unix builds don't need sed to be installed.\n.PHONY: config\nconfig: internal/config/default.yaml\n\tsed '-e/replaces:/,$$d' <../otelcorecol/builder-config.yaml > internal/config/default.yaml\n"
  },
  {
    "path": "cmd/builder/README.md",
    "content": "# OpenTelemetry Collector Builder (ocb)\n\nThis program generates a custom OpenTelemetry Collector binary based on a given configuration.\n\n## TL;DR\n\n```console\n$ go install go.opentelemetry.io/collector/cmd/builder@v0.129.0\n$ cat > otelcol-builder.yaml <<EOF\ndist:\n  name: otelcol-custom\n  description: Local OpenTelemetry Collector binary\n  output_path: /tmp/dist\nexporters:\n  - gomod: github.com/open-telemetry/opentelemetry-collector-contrib/exporter/alibabacloudlogserviceexporter v0.129.0\n  - gomod: go.opentelemetry.io/collector/exporter/debugexporter v0.129.0\n\nreceivers:\n  - gomod: go.opentelemetry.io/collector/receiver/otlpreceiver v0.129.0\n\nprocessors:\n  - gomod: go.opentelemetry.io/collector/processor/batchprocessor v0.129.0\n\nproviders:\n  - gomod: go.opentelemetry.io/collector/confmap/provider/envprovider v1.35.0\n  - gomod: go.opentelemetry.io/collector/confmap/provider/fileprovider v1.35.0\n  - gomod: go.opentelemetry.io/collector/confmap/provider/httpprovider v1.35.0\n  - gomod: go.opentelemetry.io/collector/confmap/provider/httpsprovider v1.35.0\n  - gomod: go.opentelemetry.io/collector/confmap/provider/yamlprovider v1.35.0\nEOF\n$ builder --config=otelcol-builder.yaml\n$ cat > /tmp/otelcol.yaml <<EOF\nreceivers:\n  otlp:\n    protocols:\n      grpc:\n        endpoint: localhost:4317\n\nexporters:\n  debug:\n\nservice:\n  pipelines:\n    traces:\n      receivers:\n      - otlp\n      exporters:\n      - debug\nEOF\n$ /tmp/dist/otelcol-custom --config=/tmp/otelcol.yaml\n```\n\n## Installation\n\nThere are three supported ways to install the builder:\n1. Via official release Docker images (recommended)\n2. Via official release binaries (recommended)\n3. Through `go install` (not recommended)\n\n### Official release Docker image\n\nYou will find the official docker images at [DockerHub](https://hub.docker.com/r/otel/opentelemetry-collector-builder).\n\nPull the image via tagged version number (e.g. `0.129.0`) or 'latest'. You may also specify platform, although Docker will handle this automatically as it is a multi-platform build.\n\n```console\ndocker pull otel/opentelemetry-collector-builder:latest\n```\n\nThe included builder configuration file/manifest should be replaced by mounting a file from your local filesystem to the docker container; the default location is `/build/builder-config.yaml`. If you mount a file at a different location inside the container, your `builder.config.yaml` must be specified as a command line argument to ocb. Additionally, the output folder must also be mounted from your local system to the docker container. This output directory must be specified in your `builder-config.yaml` file as it cannot be set via the command-line arguments.\n\nAssuming you are running this image in your working directory, have a `builder-config.yaml` file located in this folder, the `dist.output_path` item inside your `builder-config.yaml` is set to `./otelcol-dev`, and you wish to output the binary/go module files to a folder named `output`, the command would look as follows:\n\n```console\ndocker run -v \"$(pwd)/builder-config.yaml:/build/builder-config.yaml\" -v \"$(pwd)/output:/build/otelcol-dev\" otel/opentelemetry-collector-builder:latest --config=/build/builder-config.yaml\n```\n\nPlease note that a `--config` flag must be passed to specify your custom manifest.yaml/builder-config.yaml file regardless of where you mount it inside the container, otherwise a default config is used that cannot be changed.\n\nAdditional arguments may be passed to ocb on the command line as specified below, but if you wish to do this, you must make sure to pass the `--config` argument, as this is specified as an additional `CMD`, not an entrypoint.\n\n### Official release binaries\n\nThis is the recommended installation method for the binary. Download the binary for your respective platform from the [\"Releases\"](https://github.com/open-telemetry/opentelemetry-collector-releases/releases?q=cmd/builder) page.\n\n### `go install`\n\nYou need to have a `go` compiler in your PATH. Run the following command to install the latest version:\n\n```console\ngo install go.opentelemetry.io/collector/cmd/builder@latest\n```\n\nIf installing through this method the binary will be called `builder`.\n\nIn order to successfully generate and build a collector using ocb, you must use [compatible Go version](../../README.md#compatibility).\n\n## Running\n\nA build configuration file must be provided with the `--config` flag.\nYou will need to specify at least one module (extension, exporter, receiver, processor) to add to your distribution.\nTo build a default collector configuration, you can use [this](../otelcorecol/builder-config.yaml) build configuration.\n\n```console\nocb --config=builder-config.yaml\n```\n\nUse `ocb --help` to learn about which flags are available.\n\n## Debug\n\n### Debug symbols\n\nBy default, the LDflags are set to `-s -w`, which strips debugging symbols to produce a smaller OpenTelemetry Collector binary. To retain debugging symbols and DWARF debugging data in the binary, override the LDflags as shown:\n\n```console\nocb --ldflags=\"\" --config=builder-config.yaml.\n```\n\n### Debugging with Delve\n\nTo ensure the code being executed matches the written code exactly, debugging symbols must be preserved, and compiler inlining and optimizations disabled. You can achieve this in two ways:\n\n1. Set the configuration property `debug_compilation` to true.\n2. Manually override the ldflags and gcflags `ocb --ldflags=\"\" --gcflags=\"all=-N -l\" --config=builder-config.yaml.`\n\nThen install `go-delve` and run OpenTelemetry Collector with `dlv` command as the following example:\n\n```bash\n# go install github.com/go-delve/delve/cmd/dlv@latest\n# ~/go/bin/dlv --listen=:2345 --headless=true --api-version=2 --accept-multiclient --log exec .otel-collector-binary -- --config otel-collector-config.yaml\n```\n\nFinally, load the OpenTelemetry Collector as a project in the IDE, configure debug for Go\n\n## Configuration\n\nThe configuration file is composed of two main parts: `dist` and module types. All `dist` options can be specified via command line flags:\n\n```console\nocb --config=config.yaml\n```\n\nThe module types are specified at the top-level. Available options are `extensions`, `exporters`, `receivers`, `processors`, `providers`, and `converters`. They all accept a list of components, and each component is required to have at least the `gomod` entry. The telemetry provider for the Collector binary can also be specified through the `telemetry` key, which can be set to a single module, also requiring a `gomod` entry at a minimum.\n\nWhen not specified, the `import` value is inferred from the `gomod`. When not specified, the `name` is inferred from the `import`.\n\nThe `import` might specify a more specific path than what is specified in the `gomod`. For instance, your Go module might be `gitlab.com/myorg/myrepo` and the `import` might be `gitlab.com/myorg/myrepo/myexporter`.\n\nThe `name` will typically be omitted, except when multiple components have the same name. In such case, set a unique name for each module.\n\nOptionally, a list of `go mod` replace entries can be provided, in case custom overrides are needed. This is typically necessary when a processor or some of its transitive dependencies have dependency problems.\n\n```yaml\ndist:\n    module: github.com/open-telemetry/opentelemetry-collector # the module name for the new distribution, following Go mod conventions. Optional, but recommended.\n    name: otelcol-custom # the binary name. Optional.\n    description: \"Custom OpenTelemetry Collector distribution\" # a long name for the application. Optional.\n    output_path: /tmp/otelcol-distributionNNN # the path to write the output (sources and binary). Optional.\n    version: \"1.0.0\" # the version for your custom OpenTelemetry Collector. Optional.\n    go: \"/usr/bin/go\" # which Go binary to use to compile the generated sources. Optional.\n    debug_compilation: false # enabling this causes the builder to keep the debug symbols in the resulting binary. Optional.\nexporters:\n  - gomod: \"github.com/open-telemetry/opentelemetry-collector-contrib/exporter/alibabacloudlogserviceexporter v0.146.0\" # the Go module for the component. Required.\n    import: \"github.com/open-telemetry/opentelemetry-collector-contrib/exporter/alibabacloudlogserviceexporter\" # the import path for the component. Optional.\n    name: \"alibabacloudlogserviceexporter\" # package name to use in the generated sources. Optional.\n    path: \"./alibabacloudlogserviceexporter\" # in case a local version should be used for the module, the path relative to the current dir, or a full path can be specified. Optional.\ntelemetry:\n  gomod: go.opentelemetry.io/collector/service v0.146.0\n  import: go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\nreplaces:\n  # a list of \"replaces\" directives that will be part of the resulting go.mod\n  - github.com/open-telemetry/opentelemetry-collector-contrib/internal/common => github.com/open-telemetry/opentelemetry-collector-contrib/internal/common v0.128.0\n```\n\nThe builder also allows setting the scheme to use as the default URI scheme via `conf_resolver.default_uri_scheme`:\n\n```yaml\nconf_resolver:\n   default_uri_scheme: \"env\"\n```\n\nThis tells the builder to produce a Collector that uses the `env` scheme when expanding configuration that does not\nprovide a scheme, such as `${HOST}` (instead of doing `${env:HOST}`).\n\n## Steps\n\nThe builder has 3 steps:\n\n* Generate: generates the golang source code\n* Get modules: generates the go.mod file based on the imported modules in the generated golang source code\n* Compilation: builds the OpenTelemetry Collector executable\n\nEach step can be skipped independently: `--skip-generate`, `--skip-get-modules` and `--skip-compilation`.\n\nFor instance, a code generation step could execute\n\n```console\nocb --skip-compilation --config=config.yaml\n```\n\nthen commit the code in a git repo. A CI can sync the code and execute\n\n```console\nocb --skip-generate --skip-get-modules --config=config.yaml\n```\n\nto only execute the compilation step.\n\n### Strict versioning checks\n\nThe builder checks the relevant `go.mod`\nfile for the following things after `go get`ing all components and calling\n`go mod tidy`:\n\n1. The `dist::otelcol_version` field in the build configuration must have\n   matching major and minor versions as the core library version calculated by\n   the Go toolchain, considering all components.  A mismatch could happen, for\n   example, when the builder or one of the components depends on a newer release\n   of the core collector library.\n2. For each component in the build configuration, the major and minor versions\n   included in the `gomod` module specifier must match the one calculated by\n   the Go toolchain, considering all components.  A mismatch could\n   happen, for example, when the enclosing Go module uses a newer\n   release of the core collector library.\n\nThe `--skip-strict-versioning` flag disables these versioning checks.\nThis flag is available temporarily and\n**will be removed in a future minor version**.\n\n### Cgo disabled by default\n\nBy default, the OpenTelemetry Collector binary is built with `CGO_ENABLED=0` in accordance with\nhow the official OpenTelemetry Collector releases are built. This can be overridden by adding\nthe following configuration option to the `dist` section of the builder configuration file:\n\n```yaml\ndist:\n  cgo_enabled: true\n```\n"
  },
  {
    "path": "cmd/builder/RELEASE.md",
    "content": "# Releasing the OpenTelemetry Collector Builder\n\nThis project uses [`goreleaser`](https://github.com/goreleaser/goreleaser) to manage the release of new versions.\n\nTo release a new version, simply add a tag named `vX.Y.Z`, like:\n\n```\ngit tag -a v0.1.1 -m \"Release v0.1.1\"\ngit push upstream v0.1.1\n```\n\nA new GitHub workflow should be started, and at the end, a GitHub release should have been created, similar with the [\"Release v0.56.0\"](https://github.com/open-telemetry/opentelemetry-collector/releases/tag/cmd%2Fbuilder%2Fv0.56.0)."
  },
  {
    "path": "cmd/builder/go.mod",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\nmodule go.opentelemetry.io/collector/cmd/builder\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/knadh/koanf/parsers/yaml v1.1.0\n\tgithub.com/knadh/koanf/providers/env/v2 v2.0.0\n\tgithub.com/knadh/koanf/providers/file v1.2.1\n\tgithub.com/knadh/koanf/providers/fs v1.0.0\n\tgithub.com/knadh/koanf/v2 v2.3.3\n\tgithub.com/spf13/cobra v1.10.2\n\tgithub.com/spf13/pflag v1.0.10\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/multierr v1.11.0\n\tgo.uber.org/zap v1.27.1\n\tgolang.org/x/mod v0.33.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/fsnotify/fsnotify v1.9.0 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.4.0 // indirect\n\tgithub.com/inconshreveable/mousetrap v1.1.0 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/kr/pretty v0.3.1 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/rogpeppe/go-internal v1.10.0 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nretract (\n\tv0.76.0 // Depends on retracted pdata v1.0.0-rc10 module, use v0.76.1\n\tv0.69.0 // Release failed, use v0.69.1\n\tv0.57.1 // Release failed, use v0.57.2\n\tv0.57.0 // Release failed, use v0.57.2\n)\n"
  },
  {
    "path": "cmd/builder/go.sum",
    "content": "github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=\ngithub.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=\ngithub.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=\ngithub.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/parsers/yaml v1.1.0 h1:3ltfm9ljprAHt4jxgeYLlFPmUaunuCgu1yILuTXRdM4=\ngithub.com/knadh/koanf/parsers/yaml v1.1.0/go.mod h1:HHmcHXUrp9cOPcuC+2wrr44GTUB0EC+PyfN3HZD9tFg=\ngithub.com/knadh/koanf/providers/env/v2 v2.0.0 h1:Ad5H3eun722u+FvchiIcEIJZsZ2M6oxCkgZfWN5B5KY=\ngithub.com/knadh/koanf/providers/env/v2 v2.0.0/go.mod h1:1g01PE+Ve1gBfWNNw2wmULRP0tc8RJrjn5p2N/jNCIc=\ngithub.com/knadh/koanf/providers/file v1.2.1 h1:bEWbtQwYrA+W2DtdBrQWyXqJaJSG3KrP3AESOJYp9wM=\ngithub.com/knadh/koanf/providers/file v1.2.1/go.mod h1:bp1PM5f83Q+TOUu10J/0ApLBd9uIzg+n9UgthfY+nRA=\ngithub.com/knadh/koanf/providers/fs v1.0.0 h1:tvn4MrduLgdOSUqqEHULUuIcELXf6xDOpH8GUErpYaY=\ngithub.com/knadh/koanf/providers/fs v1.0.0/go.mod h1:FksHET+xXFNDozvj8ZCdom54OnZ6eGKJtC5FhZJKx/8=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=\ngithub.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=\ngithub.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=\ngithub.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=\ngithub.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=\ngithub.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=\ngolang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "cmd/builder/header.txt",
    "content": "Copyright The OpenTelemetry Authors\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n    http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License."
  },
  {
    "path": "cmd/builder/internal/.gitignore",
    "content": "# tmp folder used by tests\ntmp/\n"
  },
  {
    "path": "cmd/builder/internal/builder/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builder // import \"go.opentelemetry.io/collector/cmd/builder/internal/builder\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"slices\"\n\t\"strings\"\n\t\"time\"\n\n\t\"go.uber.org/multierr\"\n\t\"go.uber.org/zap\"\n)\n\nconst (\n\tDefaultBetaOtelColVersion   = \"v0.148.0\"\n\tDefaultStableOtelColVersion = \"v1.54.0\"\n)\n\n// errMissingGoMod indicates an empty gomod field\nvar errMissingGoMod = errors.New(\"missing gomod specification for module\")\n\n// Config holds the builder's configuration\ntype Config struct {\n\tLogger *zap.Logger\n\n\tOtelColVersion       string `mapstructure:\"-\"` // only used be the go.mod template\n\tSkipGenerate         bool   `mapstructure:\"-\"`\n\tSkipCompilation      bool   `mapstructure:\"-\"`\n\tSkipGetModules       bool   `mapstructure:\"-\"`\n\tSkipStrictVersioning bool   `mapstructure:\"-\"`\n\tLDFlags              string `mapstructure:\"-\"`\n\tLDSet                bool   `mapstructure:\"-\"` // only used to override LDFlags\n\tGCFlags              string `mapstructure:\"-\"`\n\tGCSet                bool   `mapstructure:\"-\"` // only used to override GCFlags\n\tVerbose              bool   `mapstructure:\"-\"`\n\n\tDistribution      Distribution `mapstructure:\"dist\"`\n\tExporters         []Module     `mapstructure:\"exporters\"`\n\tExtensions        []Module     `mapstructure:\"extensions\"`\n\tReceivers         []Module     `mapstructure:\"receivers\"`\n\tProcessors        []Module     `mapstructure:\"processors\"`\n\tConnectors        []Module     `mapstructure:\"connectors\"`\n\tTelemetry         Module       `mapstructure:\"telemetry\"`\n\tConfmapProviders  []Module     `mapstructure:\"providers\"`\n\tConfmapConverters []Module     `mapstructure:\"converters\"`\n\tReplaces          []string     `mapstructure:\"replaces\"`\n\tExcludes          []string     `mapstructure:\"excludes\"`\n\n\tConfResolver ConfResolver `mapstructure:\"conf_resolver\"`\n\n\tdownloadModules retry `mapstructure:\"-\"`\n}\n\ntype ConfResolver struct {\n\t// When set, will be used to set the CollectorSettings.ConfResolver.DefaultScheme value,\n\t// which determines how the Collector interprets URIs that have no scheme, such as ${ENV}.\n\t// See https://pkg.go.dev/go.opentelemetry.io/collector/confmap#ResolverSettings for more details.\n\tDefaultURIScheme string `mapstructure:\"default_uri_scheme\"`\n}\n\n// Distribution holds the parameters for the final binary\ntype Distribution struct {\n\tModule           string `mapstructure:\"module\"`\n\tName             string `mapstructure:\"name\"`\n\tGo               string `mapstructure:\"go\"`\n\tDescription      string `mapstructure:\"description\"`\n\tOutputPath       string `mapstructure:\"output_path\"`\n\tVersion          string `mapstructure:\"version\"`\n\tBuildTags        string `mapstructure:\"build_tags\"`\n\tDebugCompilation bool   `mapstructure:\"debug_compilation\"`\n\tCGoEnabled       bool   `mapstructure:\"cgo_enabled\"`\n}\n\n// Module represents a receiver, exporter, processor or extension for the distribution\ntype Module struct {\n\tName   string `mapstructure:\"name\"`   // if not specified, this is package part of the go mod (last part of the path)\n\tImport string `mapstructure:\"import\"` // if not specified, this is the path part of the go mods\n\tGoMod  string `mapstructure:\"gomod\"`  // a gomod-compatible spec for the module\n\tPath   string `mapstructure:\"path\"`   // an optional path to the local version of this module\n}\n\ntype retry struct {\n\tnumRetries int\n\twait       time.Duration\n}\n\n// NewDefaultConfig creates a new config, with default values\nfunc NewDefaultConfig() (*Config, error) {\n\tlog, err := zap.NewDevelopment()\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to obtain a logger instance: %v\", err))\n\t}\n\n\toutputDir, err := os.MkdirTemp(\"\", \"otelcol-distribution\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &Config{\n\t\tOtelColVersion: DefaultBetaOtelColVersion,\n\t\tLogger:         log,\n\t\tDistribution: Distribution{\n\t\t\tOutputPath: outputDir,\n\t\t\tModule:     \"go.opentelemetry.io/collector/cmd/builder\",\n\t\t},\n\t\t// basic retry if error from go mod command (in case of transient network error).\n\t\t// retry 3 times with 5 second spacing interval\n\t\tdownloadModules: retry{\n\t\t\tnumRetries: 3,\n\t\t\twait:       5 * time.Second,\n\t\t},\n\t\tConfmapProviders: []Module{\n\t\t\t{\n\t\t\t\tGoMod: \"go.opentelemetry.io/collector/confmap/provider/envprovider \" + DefaultStableOtelColVersion,\n\t\t\t},\n\t\t\t{\n\t\t\t\tGoMod: \"go.opentelemetry.io/collector/confmap/provider/fileprovider \" + DefaultStableOtelColVersion,\n\t\t\t},\n\t\t\t{\n\t\t\t\tGoMod: \"go.opentelemetry.io/collector/confmap/provider/httpprovider \" + DefaultStableOtelColVersion,\n\t\t\t},\n\t\t\t{\n\t\t\t\tGoMod: \"go.opentelemetry.io/collector/confmap/provider/httpsprovider \" + DefaultStableOtelColVersion,\n\t\t\t},\n\t\t\t{\n\t\t\t\tGoMod: \"go.opentelemetry.io/collector/confmap/provider/yamlprovider \" + DefaultStableOtelColVersion,\n\t\t\t},\n\t\t},\n\t}, nil\n}\n\n// Validate checks whether the current configuration is valid\nfunc (c *Config) Validate() error {\n\treturn multierr.Combine(\n\t\tvalidateModules(\"extension\", c.Extensions),\n\t\tvalidateModules(\"receiver\", c.Receivers),\n\t\tvalidateModules(\"exporter\", c.Exporters),\n\t\tvalidateModules(\"processor\", c.Processors),\n\t\tvalidateModules(\"connector\", c.Connectors),\n\t\tvalidateModules(\"provider\", c.ConfmapProviders),\n\t\tvalidateModules(\"converter\", c.ConfmapConverters),\n\t\tvalidateTelemetry(c),\n\t)\n}\n\n// SetGoPath sets go path\nfunc (c *Config) SetGoPath() error {\n\tif !c.SkipCompilation || !c.SkipGetModules {\n\t\t//nolint:gosec // #nosec G204\n\t\tif _, err := exec.Command(c.Distribution.Go, \"env\").CombinedOutput(); err != nil {\n\t\t\tpath, err := exec.LookPath(\"go\")\n\t\t\tif err != nil {\n\t\t\t\treturn ErrGoNotFound\n\t\t\t}\n\t\t\tc.Distribution.Go = path\n\t\t}\n\t\tc.Logger.Info(\"Using go\", zap.String(\"go-executable\", c.Distribution.Go))\n\t}\n\treturn nil\n}\n\n// ParseModules will parse the Modules entries and populate the missing values\nfunc (c *Config) ParseModules() error {\n\tvar err error\n\tusedNames := make(map[string]int)\n\n\tc.Extensions, err = parseModules(c.Extensions, usedNames)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Receivers, err = parseModules(c.Receivers, usedNames)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Exporters, err = parseModules(c.Exporters, usedNames)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Processors, err = parseModules(c.Processors, usedNames)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tc.Connectors, err = parseModules(c.Connectors, usedNames)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttelemetry, err := parseModules([]Module{c.Telemetry}, usedNames)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.Telemetry = telemetry[0]\n\n\tc.ConfmapProviders, err = parseModules(c.ConfmapProviders, usedNames)\n\tif err != nil {\n\t\treturn err\n\t}\n\tc.ConfmapConverters, err = parseModules(c.ConfmapConverters, usedNames)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\nfunc (c *Config) allComponents() []Module {\n\treturn slices.Concat(c.Exporters, c.Receivers, c.Processors, c.Extensions, c.Connectors, []Module{c.Telemetry}, c.ConfmapProviders, c.ConfmapConverters)\n}\n\nfunc validateModules(name string, mods []Module) error {\n\tfor i, mod := range mods {\n\t\tif mod.GoMod == \"\" {\n\t\t\treturn fmt.Errorf(\"%s module at index %v: %w\", name, i, errMissingGoMod)\n\t\t}\n\t}\n\treturn nil\n}\n\n// validateTelemetry ensures there is a valid telemetry module specified.\n// If the field is not set, it is defaulted to otelconftelemetry.\nfunc validateTelemetry(c *Config) error {\n\t// We cannot set this in createDefaultConfig, since koanf merges maps and we\n\t// would get a blend of this value and user-provided values. Once\n\t// otelconftelemetry is its own module (that is, the `Import` field is not\n\t// set), we can likely move the default to createDefaultConfig.\n\tif c.Telemetry.Name == \"\" && c.Telemetry.Import == \"\" && c.Telemetry.GoMod == \"\" && c.Telemetry.Path == \"\" {\n\t\tc.Telemetry = Module{\n\t\t\tGoMod:  \"go.opentelemetry.io/collector/service \" + DefaultBetaOtelColVersion,\n\t\t\tImport: \"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\",\n\t\t}\n\t} else if c.Telemetry.GoMod == \"\" {\n\t\treturn fmt.Errorf(\"telemetry module: %w\", errMissingGoMod)\n\t}\n\n\treturn nil\n}\n\nfunc parseModules(mods []Module, usedNames map[string]int) ([]Module, error) {\n\tvar parsedModules []Module\n\tfor _, mod := range mods {\n\t\tif mod.Import == \"\" {\n\t\t\tmod.Import = strings.Split(mod.GoMod, \" \")[0]\n\t\t}\n\n\t\tif mod.Name == \"\" {\n\t\t\tparts := strings.Split(mod.Import, \"/\")\n\t\t\tmod.Name = parts[len(parts)-1]\n\t\t}\n\n\t\toriginalModName := mod.Name\n\t\tif count, exists := usedNames[mod.Name]; exists {\n\t\t\tvar newName string\n\t\t\tfor {\n\t\t\t\tnewName = fmt.Sprintf(\"%s%d\", mod.Name, count+1)\n\t\t\t\tif _, transformedExists := usedNames[newName]; !transformedExists {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t\tcount++\n\t\t\t}\n\t\t\tmod.Name = newName\n\t\t\tusedNames[newName] = 1\n\t\t}\n\t\tusedNames[originalModName] = 1\n\n\t\t// Check if path is empty, otherwise filepath.Abs replaces it with current path \".\".\n\t\tif mod.Path != \"\" {\n\t\t\tvar err error\n\t\t\tmod.Path, err = filepath.Abs(mod.Path)\n\t\t\tif err != nil {\n\t\t\t\treturn mods, fmt.Errorf(\"module has a relative \\\"path\\\" element, but we couldn't resolve the current working dir: %w\", err)\n\t\t\t}\n\t\t\t// Check if the path exists\n\t\t\tif _, err := os.Stat(mod.Path); os.IsNotExist(err) {\n\t\t\t\treturn mods, fmt.Errorf(\"filepath does not exist: %s\", mod.Path)\n\t\t\t}\n\t\t}\n\n\t\tparsedModules = append(parsedModules, mod)\n\t}\n\n\treturn parsedModules, nil\n}\n"
  },
  {
    "path": "cmd/builder/internal/builder/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builder\n\nimport (\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/knadh/koanf/parsers/yaml\"\n\t\"github.com/knadh/koanf/v2\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest\"\n\n\t\"go.opentelemetry.io/collector/cmd/builder/internal/config\"\n)\n\nfunc TestAliases(t *testing.T) {\n\t// prepare\n\tcfg := Config{\n\t\tExtensions: []Module{\n\t\t\t{\n\t\t\t\tGoMod: \"github.com/org/repo/impl v0.1.2\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tGoMod: \"github.com/org/repo2/impl v0.1.2\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tGoMod: \"github.com/org/repo3/impl v0.1.2\",\n\t\t\t},\n\t\t},\n\t\tReceivers: []Module{\n\t\t\t{\n\t\t\t\tGoMod: \"github.com/org/repo v0.1.2\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tGoMod: \"github.com/org2/repo v0.1.2\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tGoMod: \"github.com/org/repo4/impl v0.1.2\",\n\t\t\t},\n\t\t},\n\t\tExporters: []Module{\n\t\t\t{\n\t\t\t\tGoMod: \"github.com/another/module v0.1.2\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tGoMod: \"github.com/org/repo5/impl v0.1.2\",\n\t\t\t},\n\t\t},\n\t\tProcessors: []Module{\n\t\t\t{\n\t\t\t\tGoMod: \"github.com/another/module2 v0.1.2\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tGoMod: \"github.com/another2/module v0.1.2\",\n\t\t\t},\n\t\t},\n\t\tConnectors: []Module{\n\t\t\t{\n\t\t\t\tGoMod: \"github.com/another/module3 v0.1.2\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tGoMod: \"github.com/another2/module4 v0.1.2\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tGoMod: \"github.com/another3/module v0.1.2\",\n\t\t\t},\n\t\t},\n\t\tTelemetry: Module{\n\t\t\tGoMod: \"github.com/another3/module v0.1.2\",\n\t\t},\n\t}\n\n\t// test\n\terr := cfg.ParseModules()\n\trequire.NoError(t, err)\n\n\t// verify\n\tassert.Equal(t, \"github.com/org/repo/impl v0.1.2\", cfg.Extensions[0].GoMod)\n\tassert.Equal(t, \"github.com/org/repo/impl\", cfg.Extensions[0].Import)\n\tassert.Equal(t, \"impl\", cfg.Extensions[0].Name)\n\n\tassert.Equal(t, \"github.com/org/repo2/impl v0.1.2\", cfg.Extensions[1].GoMod)\n\tassert.Equal(t, \"github.com/org/repo2/impl\", cfg.Extensions[1].Import)\n\tassert.Equal(t, \"impl2\", cfg.Extensions[1].Name)\n\n\tassert.Equal(t, \"github.com/org/repo3/impl v0.1.2\", cfg.Extensions[2].GoMod)\n\tassert.Equal(t, \"github.com/org/repo3/impl\", cfg.Extensions[2].Import)\n\tassert.Equal(t, \"impl3\", cfg.Extensions[2].Name)\n\n\tassert.Equal(t, \"github.com/org/repo v0.1.2\", cfg.Receivers[0].GoMod)\n\tassert.Equal(t, \"github.com/org/repo\", cfg.Receivers[0].Import)\n\tassert.Equal(t, \"repo\", cfg.Receivers[0].Name)\n\n\tassert.Equal(t, \"github.com/org2/repo v0.1.2\", cfg.Receivers[1].GoMod)\n\tassert.Equal(t, \"github.com/org2/repo\", cfg.Receivers[1].Import)\n\tassert.Equal(t, \"repo2\", cfg.Receivers[1].Name)\n\n\tassert.Equal(t, \"github.com/org/repo4/impl v0.1.2\", cfg.Receivers[2].GoMod)\n\tassert.Equal(t, \"github.com/org/repo4/impl\", cfg.Receivers[2].Import)\n\tassert.Equal(t, \"impl4\", cfg.Receivers[2].Name)\n\n\tassert.Equal(t, \"github.com/another/module v0.1.2\", cfg.Exporters[0].GoMod)\n\tassert.Equal(t, \"github.com/another/module\", cfg.Exporters[0].Import)\n\tassert.Equal(t, \"module\", cfg.Exporters[0].Name)\n\n\tassert.Equal(t, \"github.com/org/repo5/impl v0.1.2\", cfg.Exporters[1].GoMod)\n\tassert.Equal(t, \"github.com/org/repo5/impl\", cfg.Exporters[1].Import)\n\tassert.Equal(t, \"impl5\", cfg.Exporters[1].Name)\n\n\tassert.Equal(t, \"github.com/another/module2 v0.1.2\", cfg.Processors[0].GoMod)\n\tassert.Equal(t, \"github.com/another/module2\", cfg.Processors[0].Import)\n\tassert.Equal(t, \"module2\", cfg.Processors[0].Name)\n\n\tassert.Equal(t, \"github.com/another2/module v0.1.2\", cfg.Processors[1].GoMod)\n\tassert.Equal(t, \"github.com/another2/module\", cfg.Processors[1].Import)\n\tassert.Equal(t, \"module3\", cfg.Processors[1].Name)\n\n\tassert.Equal(t, \"github.com/another/module3 v0.1.2\", cfg.Connectors[0].GoMod)\n\tassert.Equal(t, \"github.com/another/module3\", cfg.Connectors[0].Import)\n\tassert.Equal(t, \"module32\", cfg.Connectors[0].Name)\n\n\tassert.Equal(t, \"github.com/another2/module4 v0.1.2\", cfg.Connectors[1].GoMod)\n\tassert.Equal(t, \"github.com/another2/module4\", cfg.Connectors[1].Import)\n\tassert.Equal(t, \"module4\", cfg.Connectors[1].Name)\n\n\tassert.Equal(t, \"github.com/another3/module v0.1.2\", cfg.Connectors[2].GoMod)\n\tassert.Equal(t, \"github.com/another3/module\", cfg.Connectors[2].Import)\n\tassert.Equal(t, \"module5\", cfg.Connectors[2].Name)\n\n\tassert.Equal(t, \"github.com/another3/module v0.1.2\", cfg.Telemetry.GoMod)\n\tassert.Equal(t, \"github.com/another3/module\", cfg.Telemetry.Import)\n\tassert.Equal(t, \"module6\", cfg.Telemetry.Name)\n}\n\nfunc TestParseModules(t *testing.T) {\n\t// prepare\n\tcfg := Config{\n\t\tExtensions: []Module{{\n\t\t\tGoMod: \"github.com/org/repo v0.1.2\",\n\t\t}},\n\t}\n\n\t// test\n\terr := cfg.ParseModules()\n\trequire.NoError(t, err)\n\n\t// verify\n\tassert.Equal(t, \"github.com/org/repo v0.1.2\", cfg.Extensions[0].GoMod)\n\tassert.Equal(t, \"github.com/org/repo\", cfg.Extensions[0].Import)\n\tassert.Equal(t, \"repo\", cfg.Extensions[0].Name)\n}\n\nfunc TestInvalidConverter(t *testing.T) {\n\t// Create a Config instance with invalid Converters\n\tconfig := &Config{\n\t\tConfmapConverters: []Module{\n\t\t\t{\n\t\t\t\tPath: \"./invalid/module/path\", // Invalid module path to trigger an error\n\t\t\t},\n\t\t},\n\t}\n\n\t// Call the method and expect an error\n\terr := config.ParseModules()\n\trequire.Error(t, err, \"expected an error when parsing invalid modules\")\n}\n\nfunc TestRelativePath(t *testing.T) {\n\t// prepare\n\tcfg := Config{\n\t\tExtensions: []Module{{\n\t\t\tGoMod: \"some-module\",\n\t\t\tPath:  \"./templates\",\n\t\t}},\n\t}\n\n\t// test\n\terr := cfg.ParseModules()\n\trequire.NoError(t, err)\n\n\t// verify\n\tcwd, err := os.Getwd()\n\trequire.NoError(t, err)\n\tassert.True(t, strings.HasPrefix(cfg.Extensions[0].Path, cwd))\n}\n\nfunc TestModuleFromCore(t *testing.T) {\n\t// prepare\n\tcfg := Config{\n\t\tExtensions: []Module{ // see issue-12\n\t\t\t{\n\t\t\t\tImport: \"go.opentelemetry.io/collector/receiver/otlpreceiver\",\n\t\t\t\tGoMod:  \"go.opentelemetry.io/collector v0.0.0\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tImport: \"go.opentelemetry.io/collector/receiver/otlpreceiver\",\n\t\t\t\tGoMod:  \"go.opentelemetry.io/collector v0.0.0\",\n\t\t\t},\n\t\t},\n\t}\n\n\t// test\n\terr := cfg.ParseModules()\n\trequire.NoError(t, err)\n\n\t// verify\n\tassert.True(t, strings.HasPrefix(cfg.Extensions[0].Name, \"otlpreceiver\"))\n}\n\nfunc TestMissingModule(t *testing.T) {\n\ttype invalidModuleTest struct {\n\t\tcfg Config\n\t\terr error\n\t}\n\t// prepare\n\tconfigurations := []invalidModuleTest{\n\t\t{\n\t\t\tcfg: Config{\n\t\t\t\tLogger: zap.NewNop(),\n\t\t\t\tConfmapProviders: []Module{{\n\t\t\t\t\tImport: \"invalid\",\n\t\t\t\t}},\n\t\t\t},\n\t\t\terr: errMissingGoMod,\n\t\t},\n\t\t{\n\t\t\tcfg: Config{\n\t\t\t\tLogger: zap.NewNop(),\n\t\t\t\tExtensions: []Module{{\n\t\t\t\t\tImport: \"invalid\",\n\t\t\t\t}},\n\t\t\t},\n\t\t\terr: errMissingGoMod,\n\t\t},\n\t\t{\n\t\t\tcfg: Config{\n\t\t\t\tLogger: zap.NewNop(),\n\t\t\t\tReceivers: []Module{{\n\t\t\t\t\tImport: \"invalid\",\n\t\t\t\t}},\n\t\t\t},\n\t\t\terr: errMissingGoMod,\n\t\t},\n\t\t{\n\t\t\tcfg: Config{\n\t\t\t\tLogger: zap.NewNop(),\n\t\t\t\tExporters: []Module{{\n\t\t\t\t\tImport: \"invalid\",\n\t\t\t\t}},\n\t\t\t},\n\t\t\terr: errMissingGoMod,\n\t\t},\n\t\t{\n\t\t\tcfg: Config{\n\t\t\t\tLogger: zap.NewNop(),\n\t\t\t\tProcessors: []Module{{\n\t\t\t\t\tImport: \"invalid\",\n\t\t\t\t}},\n\t\t\t},\n\t\t\terr: errMissingGoMod,\n\t\t},\n\t\t{\n\t\t\tcfg: Config{\n\t\t\t\tLogger: zap.NewNop(),\n\t\t\t\tConnectors: []Module{{\n\t\t\t\t\tImport: \"invalid\",\n\t\t\t\t}},\n\t\t\t},\n\t\t\terr: errMissingGoMod,\n\t\t},\n\t\t{\n\t\t\tcfg: Config{\n\t\t\t\tLogger: zap.NewNop(),\n\t\t\t\tConfmapConverters: []Module{{\n\t\t\t\t\tImport: \"invalid\",\n\t\t\t\t}},\n\t\t\t},\n\t\t\terr: errMissingGoMod,\n\t\t},\n\t\t{\n\t\t\tcfg: Config{\n\t\t\t\tLogger: zap.NewNop(),\n\t\t\t\tTelemetry: Module{\n\t\t\t\t\tImport: \"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\",\n\t\t\t\t},\n\t\t\t},\n\t\t\terr: errMissingGoMod,\n\t\t},\n\t}\n\n\tfor _, test := range configurations {\n\t\tassert.ErrorIs(t, test.cfg.Validate(), test.err)\n\t}\n}\n\nfunc TestNewDefaultConfig(t *testing.T) {\n\tcfg, err := NewDefaultConfig()\n\trequire.NoError(t, err)\n\tassert.Empty(t, cfg.Telemetry.GoMod)\n\trequire.NoError(t, cfg.Validate())\n\trequire.NoError(t, cfg.SetGoPath())\n\trequire.NoError(t, cfg.ParseModules())\n\tassert.NotEmpty(t, cfg.Telemetry.GoMod)\n\tassert.False(t, cfg.Distribution.DebugCompilation)\n\tassert.Empty(t, cfg.Distribution.BuildTags)\n\tassert.False(t, cfg.LDSet)\n\tassert.Empty(t, cfg.LDFlags)\n\tassert.False(t, cfg.GCSet)\n\tassert.Empty(t, cfg.GCFlags)\n}\n\nfunc TestNewBuiltinConfig(t *testing.T) {\n\tk := koanf.New(\".\")\n\n\trequire.NoError(t, k.Load(config.DefaultProvider(), yaml.Parser()))\n\n\tcfg := Config{Logger: zaptest.NewLogger(t)}\n\n\trequire.NoError(t, k.UnmarshalWithConf(\"\", &cfg, koanf.UnmarshalConf{Tag: \"mapstructure\"}))\n\trequire.NoError(t, cfg.Validate())\n\trequire.NoError(t, cfg.SetGoPath())\n\trequire.NoError(t, cfg.ParseModules())\n\n\t// Unlike the config initialized in NewDefaultConfig(), we expect\n\t// the builtin default to be practically useful, so there must be\n\t// a set of modules present.\n\tassert.NotEmpty(t, cfg.Receivers)\n\tassert.NotEmpty(t, cfg.Exporters)\n\tassert.NotEmpty(t, cfg.Extensions)\n\tassert.NotEmpty(t, cfg.Processors)\n}\n\nfunc TestSkipGoValidation(t *testing.T) {\n\tcfg := Config{\n\t\tDistribution: Distribution{\n\t\t\tGo: \"invalid/go/binary/path\",\n\t\t},\n\t\tSkipCompilation: true,\n\t\tSkipGetModules:  true,\n\t}\n\tassert.NoError(t, cfg.Validate())\n\tassert.NoError(t, cfg.SetGoPath())\n}\n\nfunc TestSkipGoInitialization(t *testing.T) {\n\tcfg := Config{\n\t\tSkipCompilation: true,\n\t\tSkipGetModules:  true,\n\t}\n\tassert.NoError(t, cfg.Validate())\n\tassert.NoError(t, cfg.SetGoPath())\n\tassert.Empty(t, cfg.Distribution.Go)\n}\n\nfunc TestBuildTagConfig(t *testing.T) {\n\tcfg := Config{\n\t\tDistribution: Distribution{\n\t\t\tBuildTags: \"customTag\",\n\t\t},\n\t\tSkipCompilation: true,\n\t\tSkipGetModules:  true,\n\t}\n\trequire.NoError(t, cfg.Validate())\n\tassert.Equal(t, \"customTag\", cfg.Distribution.BuildTags)\n}\n\nfunc TestDebugOptionSetConfig(t *testing.T) {\n\tcfg := Config{\n\t\tDistribution: Distribution{\n\t\t\tDebugCompilation: true,\n\t\t},\n\t\tSkipCompilation: true,\n\t\tSkipGetModules:  true,\n\t}\n\trequire.NoError(t, cfg.Validate())\n\tassert.True(t, cfg.Distribution.DebugCompilation)\n}\n\nfunc TestAddsDefaultProviders(t *testing.T) {\n\tcfg, err := NewDefaultConfig()\n\trequire.NoError(t, err)\n\trequire.NoError(t, cfg.ParseModules())\n\tassert.Len(t, cfg.ConfmapProviders, 5)\n}\n\nfunc TestSkipsNilFieldValidation(t *testing.T) {\n\tcfg, err := NewDefaultConfig()\n\trequire.NoError(t, err)\n\tcfg.ConfmapProviders = nil\n\tcfg.ConfmapConverters = nil\n\tassert.NoError(t, cfg.Validate())\n}\n"
  },
  {
    "path": "cmd/builder/internal/builder/main.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builder // import \"go.opentelemetry.io/collector/cmd/builder/internal/builder\"\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"text/template\"\n\t\"time\"\n\n\t\"go.uber.org/zap\"\n\t\"golang.org/x/mod/modfile\"\n\t\"golang.org/x/mod/semver\"\n)\n\nvar (\n\t// ErrGoNotFound is returned when a Go binary hasn't been found\n\tErrGoNotFound      = errors.New(\"go binary not found\")\n\tErrDepNotFound     = errors.New(\"dependency not found in go mod file\")\n\tErrVersionMismatch = errors.New(\"mismatch in go.mod and builder configuration versions\")\n\terrDownloadFailed  = errors.New(\"failed to download go modules\")\n\terrCompileFailed   = errors.New(\"failed to compile the OpenTelemetry Collector distribution\")\n\tskipStrictMsg      = \"Use --skip-strict-versioning to temporarily disable this check. This flag will be removed in a future minor version\"\n)\n\nconst otelcolPath = \"go.opentelemetry.io/collector/otelcol\"\n\nfunc runGoCommand(cfg *Config, args ...string) ([]byte, error) {\n\tif cfg.Verbose {\n\t\tcfg.Logger.Info(\"Running go subcommand.\", zap.Any(\"arguments\", args))\n\t}\n\n\t//nolint:gosec // #nosec G204 -- cfg.Distribution.Go is trusted to be a safe path and the caller is assumed to have carried out necessary input validation\n\tcmd := exec.Command(cfg.Distribution.Go, args...)\n\tcmd.Dir = cfg.Distribution.OutputPath\n\n\tcmd.Env = os.Environ()\n\tif cfg.Distribution.CGoEnabled {\n\t\tcmd.Env = append(cmd.Env, \"CGO_ENABLED=1\")\n\t} else {\n\t\tcmd.Env = append(cmd.Env, \"CGO_ENABLED=0\")\n\t}\n\n\tvar stdout, stderr bytes.Buffer\n\tcmd.Stdout = &stdout\n\tcmd.Stderr = &stderr\n\n\tif err := cmd.Run(); err != nil {\n\t\treturn nil, fmt.Errorf(\"go subcommand failed with args '%v': %w, error message: %s\", args, err, stderr.String())\n\t}\n\tif cfg.Verbose && stderr.Len() != 0 {\n\t\tcfg.Logger.Info(\"go subcommand error\", zap.String(\"message\", stderr.String()))\n\t}\n\n\treturn stdout.Bytes(), nil\n}\n\n// GenerateAndCompile will generate the source files based on the given configuration, update go mod, and will compile into a binary\nfunc GenerateAndCompile(cfg *Config) error {\n\tif err := Generate(cfg); err != nil {\n\t\treturn err\n\t}\n\n\t// run go get to update go.mod and go.sum files\n\tif err := GetModules(cfg); err != nil {\n\t\treturn err\n\t}\n\n\treturn Compile(cfg)\n}\n\n// Generate assembles a new distribution based on the given configuration\nfunc Generate(cfg *Config) error {\n\tif cfg.SkipGenerate {\n\t\tcfg.Logger.Info(\"Skipping generating source codes.\")\n\t\treturn nil\n\t}\n\n\t// if the file does not exist, try to create it\n\tif _, err := os.Stat(cfg.Distribution.OutputPath); os.IsNotExist(err) {\n\t\tif err = os.Mkdir(cfg.Distribution.OutputPath, 0o750); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create output path: %w\", err)\n\t\t}\n\t} else if err != nil {\n\t\treturn fmt.Errorf(\"failed to create output path: %w\", err)\n\t}\n\n\tfor _, tmpl := range []*template.Template{\n\t\tmainTemplate,\n\t\tmainOthersTemplate,\n\t\tmainWindowsTemplate,\n\t\tcomponentsTemplate,\n\t\tgoModTemplate,\n\t} {\n\t\tif err := processAndWrite(cfg, tmpl, tmpl.Name(), cfg); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to generate source file %q: %w\", tmpl.Name(), err)\n\t\t}\n\t}\n\n\tcfg.Logger.Info(\"Sources created\", zap.String(\"path\", cfg.Distribution.OutputPath))\n\treturn nil\n}\n\n// Compile generates a binary from the sources based on the configuration\nfunc Compile(cfg *Config) error {\n\tif cfg.SkipCompilation {\n\t\tcfg.Logger.Info(\"Generating source codes only, the distribution will not be compiled.\")\n\t\treturn nil\n\t}\n\n\tcfg.Logger.Info(\"Compiling\")\n\tldflags := \"-s -w\" // we strip the symbols by default for smaller binaries\n\tgcflags := \"\"\n\tbinaryName := outputBinaryName(cfg.Distribution.Name)\n\n\targs := []string{\"build\", \"-trimpath\", \"-o\", binaryName}\n\tif cfg.Distribution.DebugCompilation {\n\t\tcfg.Logger.Info(\"Debug compilation is enabled, the debug symbols will be left on the resulting binary\")\n\t\tldflags = cfg.LDFlags\n\t\tgcflags = \"all=-N -l\"\n\t} else {\n\t\tif cfg.LDSet {\n\t\t\tcfg.Logger.Info(\"Using custom ldflags\", zap.String(\"ldflags\", cfg.LDFlags))\n\t\t\tldflags = cfg.LDFlags\n\t\t}\n\t\tif cfg.GCSet {\n\t\t\tcfg.Logger.Info(\"Using custom gcflags\", zap.String(\"gcflags\", cfg.GCFlags))\n\t\t\tgcflags = cfg.GCFlags\n\t\t}\n\t}\n\tif cfg.Distribution.CGoEnabled {\n\t\tcfg.Logger.Info(\"Building with cgo enabled\")\n\t}\n\n\targs = append(args, \"-ldflags=\"+ldflags, \"-gcflags=\"+gcflags)\n\n\tif cfg.Distribution.BuildTags != \"\" {\n\t\targs = append(args, \"-tags\", cfg.Distribution.BuildTags)\n\t}\n\tif _, err := runGoCommand(cfg, args...); err != nil {\n\t\treturn fmt.Errorf(\"%w: %s\", errCompileFailed, err.Error())\n\t}\n\tcfg.Logger.Info(\"Compiled\", zap.String(\"binary\", fmt.Sprintf(\"%s/%s\", cfg.Distribution.OutputPath, binaryName)))\n\n\treturn nil\n}\n\nfunc outputBinaryName(name string) string {\n\tgoos, ok := os.LookupEnv(\"GOOS\")\n\tif !ok || goos == \"\" {\n\t\tgoos = runtime.GOOS\n\t}\n\n\tif !strings.EqualFold(goos, \"windows\") {\n\t\treturn name\n\t}\n\tif strings.EqualFold(filepath.Ext(name), \".exe\") {\n\t\treturn name\n\t}\n\treturn name + \".exe\"\n}\n\n// GetModules retrieves the go modules, updating go.mod and go.sum in the process\nfunc GetModules(cfg *Config) error {\n\tif cfg.SkipGetModules {\n\t\tcfg.Logger.Info(\"Generating source codes only, will not update go.mod and retrieve Go modules.\")\n\t\treturn nil\n\t}\n\n\tif _, err := runGoCommand(cfg, \"mod\", \"tidy\", \"-compat=1.25\"); err != nil {\n\t\treturn fmt.Errorf(\"failed to update go.mod: %w\", err)\n\t}\n\n\tif cfg.SkipStrictVersioning {\n\t\treturn downloadModules(cfg)\n\t}\n\n\t// Perform strict version checking.  For each component listed and the\n\t// otelcol core dependency, check that the enclosing go module matches.\n\tmodulePath, dependencyVersions, err := readGoModFile(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tcoreDepVersion, ok := dependencyVersions[otelcolPath]\n\tbetaVersion := semver.MajorMinor(DefaultBetaOtelColVersion)\n\tif !ok {\n\t\treturn fmt.Errorf(\"core collector %w: '%s'. %s\", ErrDepNotFound, otelcolPath, skipStrictMsg)\n\t}\n\tif semver.MajorMinor(coreDepVersion) != betaVersion {\n\t\treturn fmt.Errorf(\n\t\t\t\"%w: core collector version calculated by component dependencies %q does not match configured version %q. %s\",\n\t\t\tErrVersionMismatch, coreDepVersion, betaVersion, skipStrictMsg)\n\t}\n\n\tfor _, mod := range cfg.allComponents() {\n\t\tmodule, version, _ := strings.Cut(mod.GoMod, \" \")\n\t\tif module == modulePath {\n\t\t\t// No need to check the version of components that are part of the\n\t\t\t// module we're building from.\n\t\t\tcontinue\n\t\t}\n\n\t\tmoduleDepVersion, ok := dependencyVersions[module]\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"component %w: '%s'. %s\", ErrDepNotFound, module, skipStrictMsg)\n\t\t}\n\t\tif semver.MajorMinor(moduleDepVersion) != semver.MajorMinor(version) {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"%w: component %q version calculated by dependencies %q does not match configured version %q. %s\",\n\t\t\t\tErrVersionMismatch, module, moduleDepVersion, version, skipStrictMsg)\n\t\t}\n\t}\n\n\treturn downloadModules(cfg)\n}\n\nfunc downloadModules(cfg *Config) error {\n\tcfg.Logger.Info(\"Getting go modules\")\n\tfailReason := \"unknown\"\n\tfor i := 1; i <= cfg.downloadModules.numRetries; i++ {\n\t\tif _, err := runGoCommand(cfg, \"mod\", \"download\"); err != nil {\n\t\t\tfailReason = err.Error()\n\t\t\tcfg.Logger.Info(\"Failed modules download\", zap.String(\"retry\", fmt.Sprintf(\"%d/%d\", i, cfg.downloadModules.numRetries)))\n\t\t\ttime.Sleep(cfg.downloadModules.wait)\n\t\t\tcontinue\n\t\t}\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"%w: %s\", errDownloadFailed, failReason)\n}\n\nfunc processAndWrite(cfg *Config, tmpl *template.Template, outFile string, tmplParams any) error {\n\tout, err := os.Create(filepath.Clean(filepath.Join(cfg.Distribution.OutputPath, outFile)))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tdefer out.Close()\n\treturn tmpl.Execute(out, tmplParams)\n}\n\nfunc readGoModFile(cfg *Config) (string, map[string]string, error) {\n\tvar modPath string\n\tstdout, err := runGoCommand(cfg, \"mod\", \"edit\", \"-print\")\n\tif err != nil {\n\t\treturn modPath, nil, err\n\t}\n\tparsedFile, err := modfile.Parse(\"go.mod\", stdout, nil)\n\tif err != nil {\n\t\treturn modPath, nil, err\n\t}\n\tif parsedFile.Module != nil {\n\t\tmodPath = parsedFile.Module.Mod.Path\n\t}\n\tdependencies := map[string]string{}\n\tfor _, req := range parsedFile.Require {\n\t\tif req == nil {\n\t\t\tcontinue\n\t\t}\n\t\tdependencies[req.Mod.Path] = req.Mod.Version\n\t}\n\treturn modPath, dependencies, nil\n}\n"
  },
  {
    "path": "cmd/builder/internal/builder/main_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builder\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\t\"golang.org/x/mod/modfile\"\n)\n\nconst (\n\tgoModTestFile = `// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\nmodule go.opentelemetry.io/collector/cmd/builder/internal/tester\ngo 1.20\nrequire (\n\tgo.opentelemetry.io/collector/component v0.96.0\n\tgo.opentelemetry.io/collector/connector v0.94.1\n\tgo.opentelemetry.io/collector/exporter v0.94.1\n\tgo.opentelemetry.io/collector/extension v0.94.1\n\tgo.opentelemetry.io/collector/otelcol v0.94.1\n\tgo.opentelemetry.io/collector/processor v0.94.1\n\tgo.opentelemetry.io/collector/receiver v0.94.1\n\tgo.opentelemetry.io/collector v0.96.0\n)`\n\tmodulePrefix = \"go.opentelemetry.io/collector\"\n)\n\nvar replaceModules = []string{\n\t\"\",\n\t\"/component\",\n\t\"/component/componentstatus\",\n\t\"/component/componenttest\",\n\t\"/client\",\n\t\"/config/configauth\",\n\t\"/config/configcompression\",\n\t\"/config/configgrpc\",\n\t\"/config/confighttp\",\n\t\"/config/configmiddleware\",\n\t\"/config/confignet\",\n\t\"/config/configopaque\",\n\t\"/config/configoptional\",\n\t\"/config/configretry\",\n\t\"/config/configtelemetry\",\n\t\"/config/configtls\",\n\t\"/confmap\",\n\t\"/confmap/xconfmap\",\n\t\"/confmap/provider/envprovider\",\n\t\"/confmap/provider/fileprovider\",\n\t\"/confmap/provider/httpprovider\",\n\t\"/confmap/provider/httpsprovider\",\n\t\"/confmap/provider/yamlprovider\",\n\t\"/consumer\",\n\t\"/consumer/consumererror\",\n\t\"/consumer/consumererror/xconsumererror\",\n\t\"/consumer/xconsumer\",\n\t\"/consumer/consumertest\",\n\t\"/connector\",\n\t\"/connector/connectortest\",\n\t\"/connector/xconnector\",\n\t\"/exporter\",\n\t\"/exporter/debugexporter\",\n\t\"/exporter/xexporter\",\n\t\"/exporter/exportertest\",\n\t\"/exporter/exporterhelper\",\n\t\"/exporter/exporterhelper/xexporterhelper\",\n\t\"/exporter/nopexporter\",\n\t\"/exporter/otlpexporter\",\n\t\"/exporter/otlphttpexporter\",\n\t\"/extension\",\n\t\"/extension/extensionauth\",\n\t\"/extension/extensionauth/extensionauthtest\",\n\t\"/extension/extensioncapabilities\",\n\t\"/extension/extensionmiddleware\",\n\t\"/extension/extensionmiddleware/extensionmiddlewaretest\",\n\t\"/extension/extensiontest\",\n\t\"/extension/zpagesextension\",\n\t\"/extension/xextension\",\n\t\"/featuregate\",\n\t\"/internal/componentalias\",\n\t\"/internal/memorylimiter\",\n\t\"/internal/fanoutconsumer\",\n\t\"/internal/sharedcomponent\",\n\t\"/internal/telemetry\",\n\t\"/internal/testutil\",\n\t\"/otelcol\",\n\t\"/pdata\",\n\t\"/pdata/testdata\",\n\t\"/pdata/pprofile\",\n\t\"/pdata/xpdata\",\n\t\"/pipeline\",\n\t\"/pipeline/xpipeline\",\n\t\"/processor\",\n\t\"/processor/processortest\",\n\t\"/processor/batchprocessor\",\n\t\"/processor/memorylimiterprocessor\",\n\t\"/processor/processorhelper\",\n\t\"/processor/processorhelper/xprocessorhelper\",\n\t\"/processor/xprocessor\",\n\t\"/receiver\",\n\t\"/receiver/nopreceiver\",\n\t\"/receiver/otlpreceiver\",\n\t\"/receiver/receivertest\",\n\t\"/receiver/receiverhelper\",\n\t\"/receiver/xreceiver\",\n\t\"/service\",\n\t\"/service/hostcapabilities\",\n\t\"/service/telemetry/telemetrytest\",\n}\n\nfunc newTestConfig(tb testing.TB) *Config {\n\tcfg, err := NewDefaultConfig()\n\trequire.NoError(tb, err)\n\tcfg.downloadModules.wait = 0\n\tcfg.downloadModules.numRetries = 1\n\treturn cfg\n}\n\nfunc newInitializedConfig(t *testing.T) *Config {\n\tcfg := newTestConfig(t)\n\t// Validate and ParseModules will be called before the config is\n\t// given to Generate.\n\tassert.NoError(t, cfg.Validate())\n\tassert.NoError(t, cfg.ParseModules())\n\n\treturn cfg\n}\n\nfunc TestGenerateDefault(t *testing.T) {\n\trequire.NoError(t, Generate(newInitializedConfig(t)))\n}\n\nfunc TestGenerateInvalidOutputPath(t *testing.T) {\n\tcfg := newInitializedConfig(t)\n\tcfg.Distribution.OutputPath = \":/invalid\"\n\terr := Generate(cfg)\n\trequire.ErrorContains(t, err, \"failed to create output path\")\n}\n\nfunc TestOutputBinaryName(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname string\n\t\tgoos string\n\t\twant string\n\t}{\n\t\t{\n\t\t\tname: \"on windows\",\n\t\t\tgoos: \"windows\",\n\t\t\twant: \"otelcorecol.exe\",\n\t\t},\n\t\t{\n\t\t\tname: \"on other OSes\",\n\t\t\tgoos: \"linux\",\n\t\t\twant: \"otelcorecol\",\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tt.Setenv(\"GOOS\", tt.goos)\n\t\t\tassert.Equal(t, tt.want, outputBinaryName(\"otelcorecol\"))\n\t\t\tassert.Equal(t, \"otelcorecol.exe\", outputBinaryName(\"otelcorecol.exe\"))\n\t\t})\n\t}\n}\n\nfunc TestVersioning(t *testing.T) {\n\treplaces := generateReplaces()\n\ttests := []struct {\n\t\tname        string\n\t\tcfgBuilder  func() *Config\n\t\texpectedErr error\n\t}{\n\t\t{\n\t\t\tname: \"defaults\",\n\t\t\tcfgBuilder: func() *Config {\n\t\t\t\tcfg := newTestConfig(t)\n\t\t\t\tcfg.Distribution.Go = \"go\"\n\t\t\t\tcfg.Replaces = append(cfg.Replaces, replaces...)\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"only gomod file, skip generate\",\n\t\t\tcfgBuilder: func() *Config {\n\t\t\t\tcfg := newTestConfig(t)\n\t\t\t\ttempDir := t.TempDir()\n\t\t\t\terr := makeModule(tempDir, []byte(goModTestFile))\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tcfg.Distribution.OutputPath = tempDir\n\t\t\t\tcfg.SkipGenerate = true\n\t\t\t\tcfg.Distribution.Go = \"go\"\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpectedErr: ErrDepNotFound,\n\t\t},\n\t\t{\n\t\t\tname: \"old component version\",\n\t\t\tcfgBuilder: func() *Config {\n\t\t\t\tcfg := newTestConfig(t)\n\t\t\t\tcfg.Distribution.Go = \"go\"\n\t\t\t\tcfg.Exporters = []Module{\n\t\t\t\t\t{\n\t\t\t\t\t\tGoMod: \"go.opentelemetry.io/collector/exporter/otlpexporter v0.112.0\",\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tcfg.ConfmapProviders = []Module{}\n\t\t\t\tcfg.Replaces = append(cfg.Replaces, replaces...)\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpectedErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"old component version without strict mode\",\n\t\t\tcfgBuilder: func() *Config {\n\t\t\t\tcfg := newTestConfig(t)\n\t\t\t\tcfg.Distribution.Go = \"go\"\n\t\t\t\tcfg.SkipStrictVersioning = true\n\t\t\t\tcfg.Exporters = []Module{\n\t\t\t\t\t{\n\t\t\t\t\t\tGoMod: \"go.opentelemetry.io/collector/exporter/otlpexporter v0.112.0\",\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tcfg.ConfmapProviders = []Module{}\n\t\t\t\tcfg.Replaces = append(cfg.Replaces, replaces...)\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpectedErr: nil,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// X25519 curves are not supported when GODEBUG=fips140=only is set, so we\n\t\t\t// detect if it is and conditionally also add the tlsmklem=0 flag to disable\n\t\t\t// these curves. See: https://pkg.go.dev/crypto/tls#Config.CurvePreferences\n\t\t\tif strings.Contains(os.Getenv(\"GODEBUG\"), \"fips140=only\") {\n\t\t\t\tt.Setenv(\"GODEBUG\", os.Getenv(\"GODEBUG\")+\",tlsmlkem=0\")\n\t\t\t}\n\n\t\t\tcfg := tt.cfgBuilder()\n\t\t\trequire.NoError(t, cfg.Validate())\n\t\t\trequire.NoError(t, cfg.ParseModules())\n\t\t\terr := GenerateAndCompile(cfg)\n\t\t\trequire.ErrorIs(t, err, tt.expectedErr)\n\t\t})\n\t}\n}\n\nfunc TestSkipGenerate(t *testing.T) {\n\tcfg := newInitializedConfig(t)\n\tcfg.Distribution.OutputPath = t.TempDir()\n\tcfg.SkipGenerate = true\n\terr := Generate(cfg)\n\trequire.NoError(t, err)\n\toutputFile, err := os.Open(cfg.Distribution.OutputPath)\n\tdefer func() {\n\t\trequire.NoError(t, outputFile.Close())\n\t}()\n\trequire.NoError(t, err)\n\t_, err = outputFile.Readdirnames(1)\n\trequire.ErrorIs(t, err, io.EOF, \"skip generate should leave output directory empty\")\n}\n\nfunc TestGenerateAndCompile(t *testing.T) {\n\treplaces := generateReplaces()\n\ttestCases := []struct {\n\t\tname       string\n\t\tcfgBuilder func(t *testing.T) *Config\n\t}{\n\t\t{\n\t\t\tname: \"Default Configuration Compilation\",\n\t\t\tcfgBuilder: func(t *testing.T) *Config {\n\t\t\t\tcfg := newTestConfig(t)\n\t\t\t\tcfg.Distribution.OutputPath = t.TempDir()\n\t\t\t\tcfg.Replaces = append(cfg.Replaces, replaces...)\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"LDFlags Compilation\",\n\t\t\tcfgBuilder: func(t *testing.T) *Config {\n\t\t\t\tcfg := newTestConfig(t)\n\t\t\t\tcfg.Distribution.OutputPath = t.TempDir()\n\t\t\t\tcfg.Replaces = append(cfg.Replaces, replaces...)\n\t\t\t\tcfg.LDSet = true\n\t\t\t\tcfg.LDFlags = `-X \"test.gitVersion=0743dc6c6411272b98494a9b32a63378e84c34da\" -X \"test.gitTag=local-testing\" -X \"test.goVersion=go version go1.20.7 darwin/amd64\"`\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"GCFlags Compilation\",\n\t\t\tcfgBuilder: func(t *testing.T) *Config {\n\t\t\t\tcfg := newTestConfig(t)\n\t\t\t\tcfg.Distribution.OutputPath = t.TempDir()\n\t\t\t\tcfg.Replaces = append(cfg.Replaces, replaces...)\n\t\t\t\tcfg.GCSet = true\n\t\t\t\tcfg.GCFlags = `all=-N -l`\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Build Tags Compilation\",\n\t\t\tcfgBuilder: func(t *testing.T) *Config {\n\t\t\t\tcfg := newTestConfig(t)\n\t\t\t\tcfg.Distribution.OutputPath = t.TempDir()\n\t\t\t\tcfg.Replaces = append(cfg.Replaces, replaces...)\n\t\t\t\tcfg.Distribution.BuildTags = \"customTag\"\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Debug Compilation\",\n\t\t\tcfgBuilder: func(t *testing.T) *Config {\n\t\t\t\tcfg := newTestConfig(t)\n\t\t\t\tcfg.Distribution.OutputPath = t.TempDir()\n\t\t\t\tcfg.Replaces = append(cfg.Replaces, replaces...)\n\t\t\t\tcfg.Logger = zap.NewNop()\n\t\t\t\tcfg.Distribution.DebugCompilation = true\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"No providers\",\n\t\t\tcfgBuilder: func(t *testing.T) *Config {\n\t\t\t\tcfg := newTestConfig(t)\n\t\t\t\tcfg.Distribution.OutputPath = t.TempDir()\n\t\t\t\tcfg.Replaces = append(cfg.Replaces, replaces...)\n\t\t\t\tcfg.ConfmapProviders = []Module{}\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"With confmap factories\",\n\t\t\tcfgBuilder: func(t *testing.T) *Config {\n\t\t\t\tcfg := newTestConfig(t)\n\t\t\t\tcfg.Distribution.OutputPath = t.TempDir()\n\t\t\t\tcfg.Replaces = append(cfg.Replaces, replaces...)\n\t\t\t\tcfg.SkipStrictVersioning = true\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"ConfResolverDefaultURIScheme set\",\n\t\t\tcfgBuilder: func(t *testing.T) *Config {\n\t\t\t\tcfg := newTestConfig(t)\n\t\t\t\tcfg.ConfResolver = ConfResolver{\n\t\t\t\t\tDefaultURIScheme: \"env\",\n\t\t\t\t}\n\t\t\t\tcfg.Distribution.OutputPath = t.TempDir()\n\t\t\t\tcfg.Replaces = append(cfg.Replaces, replaces...)\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"CGoEnabled set to true\",\n\t\t\tcfgBuilder: func(t *testing.T) *Config {\n\t\t\t\tcfg := newTestConfig(t)\n\t\t\t\tcfg.Distribution.OutputPath = t.TempDir()\n\t\t\t\tcfg.Replaces = append(cfg.Replaces, replaces...)\n\t\t\t\tcfg.Distribution.CGoEnabled = true\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := tt.cfgBuilder(t)\n\t\t\tassert.NoError(t, cfg.Validate())\n\t\t\tassert.NoError(t, cfg.SetGoPath())\n\t\t\tassert.NoError(t, cfg.ParseModules())\n\t\t\trequire.NoError(t, GenerateAndCompile(cfg))\n\t\t})\n\t}\n}\n\n// Test that the go.mod files that other tests in this file\n// may generate have all their modules covered by our\n// \"replace\" statements created in `generateReplaces`.\n//\n// An incomplete set of replace statements in these tests\n// may cause them to fail during the release process, when\n// the local version of modules in the release branch is\n// not yet available on the Go package repository.\n// Unless the replace statements route all modules to the\n// local copy, `go get` will try to fetch the unreleased\n// version remotely and some tests will fail.\nfunc TestReplaceStatementsAreComplete(t *testing.T) {\n\tworkspaceDir := getWorkspaceDir()\n\treplaceMods := map[string]bool{}\n\n\tfor _, suffix := range replaceModules {\n\t\treplaceMods[modulePrefix+suffix] = false\n\t}\n\n\tfor _, mod := range replaceModules {\n\t\tverifyGoMod(t, workspaceDir+mod, replaceMods)\n\t}\n\n\tvar err error\n\tdir := t.TempDir()\n\tcfg, err := NewDefaultConfig()\n\trequire.NoError(t, err)\n\tcfg.Distribution.Go = \"go\"\n\tcfg.Distribution.OutputPath = dir\n\tcfg.Replaces = append(cfg.Replaces, generateReplaces()...)\n\t// Configure all components that we want to use elsewhere in these tests.\n\t// This ensures the resulting go.mod file has maximum coverage of modules\n\t// that exist in the Core repository.\n\tusedNames := make(map[string]int)\n\tcfg.Exporters, err = parseModules([]Module{\n\t\t{\n\t\t\tGoMod: \"go.opentelemetry.io/collector/exporter/debugexporter v1.9999.9999\",\n\t\t},\n\t\t{\n\t\t\tGoMod: \"go.opentelemetry.io/collector/exporter/nopexporter v1.9999.9999\",\n\t\t},\n\t\t{\n\t\t\tGoMod: \"go.opentelemetry.io/collector/exporter/otlpexporter v1.9999.9999\",\n\t\t},\n\t\t{\n\t\t\tGoMod: \"go.opentelemetry.io/collector/exporter/otlphttpexporter v1.9999.9999\",\n\t\t},\n\t}, usedNames)\n\trequire.NoError(t, err)\n\tcfg.Receivers, err = parseModules([]Module{\n\t\t{\n\t\t\tGoMod: \"go.opentelemetry.io/collector/receiver/nopreceiver v1.9999.9999\",\n\t\t},\n\t\t{\n\t\t\tGoMod: \"go.opentelemetry.io/collector/receiver/otlpreceiver v1.9999.9999\",\n\t\t},\n\t}, usedNames)\n\trequire.NoError(t, err)\n\tcfg.Extensions, err = parseModules([]Module{\n\t\t{\n\t\t\tGoMod: \"go.opentelemetry.io/collector/extension/zpagesextension v1.9999.9999\",\n\t\t},\n\t}, usedNames)\n\trequire.NoError(t, err)\n\tcfg.Processors, err = parseModules([]Module{\n\t\t{\n\t\t\tGoMod: \"go.opentelemetry.io/collector/processor/batchprocessor v1.9999.9999\",\n\t\t},\n\t\t{\n\t\t\tGoMod: \"go.opentelemetry.io/collector/processor/memorylimiterprocessor v1.9999.9999\",\n\t\t},\n\t}, usedNames)\n\trequire.NoError(t, err)\n\n\trequire.NoError(t, cfg.Validate())\n\trequire.NoError(t, cfg.ParseModules())\n\terr = GenerateAndCompile(cfg)\n\trequire.NoError(t, err)\n\n\tverifyGoMod(t, dir, replaceMods)\n\n\tfor k, v := range replaceMods {\n\t\tassert.Truef(t, v, \"Module not used: %s\", k)\n\t}\n}\n\nfunc verifyGoMod(t *testing.T, dir string, replaceMods map[string]bool) {\n\tgomodpath := path.Join(dir, \"go.mod\")\n\tgomod, err := os.ReadFile(filepath.Clean(gomodpath))\n\trequire.NoError(t, err)\n\n\tmod, err := modfile.Parse(gomodpath, gomod, nil)\n\trequire.NoError(t, err)\n\n\tfor _, req := range mod.Require {\n\t\tif !strings.HasPrefix(req.Mod.Path, modulePrefix) {\n\t\t\tcontinue\n\t\t}\n\n\t\t_, ok := replaceMods[req.Mod.Path]\n\t\tassert.Truef(t, ok, \"Module missing from replace statements list: %s\", req.Mod.Path)\n\n\t\treplaceMods[req.Mod.Path] = true\n\t}\n}\n\nfunc makeModule(dir string, fileContents []byte) error {\n\t// if the file does not exist, try to create it\n\tif _, err := os.Stat(dir); os.IsNotExist(err) {\n\t\tif err = os.Mkdir(dir, 0o750); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create output path: %w\", err)\n\t\t}\n\t} else if err != nil {\n\t\treturn fmt.Errorf(\"failed to create output path: %w\", err)\n\t}\n\n\terr := os.WriteFile(filepath.Clean(filepath.Join(dir, \"go.mod\")), fileContents, 0o600)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to write go.mod file: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc generateReplaces() []string {\n\tworkspaceDir := getWorkspaceDir()\n\tmodules := replaceModules\n\treplaces := make([]string, len(modules))\n\n\tfor i, mod := range modules {\n\t\treplaces[i] = fmt.Sprintf(\"%s%s => %s%s\", modulePrefix, mod, workspaceDir, mod)\n\t}\n\n\treturn replaces\n}\n\nfunc getWorkspaceDir() string {\n\t// This is dependent on the current file structure.\n\t// The goal is find the root of the repo so we can replace the root module.\n\t_, thisFile, _, _ := runtime.Caller(0)\n\treturn filepath.Dir(filepath.Dir(filepath.Dir(filepath.Dir(filepath.Dir(thisFile)))))\n}\n"
  },
  {
    "path": "cmd/builder/internal/builder/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builder\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "cmd/builder/internal/builder/templates/components.go.tmpl",
    "content": "// Code generated by \"go.opentelemetry.io/collector/cmd/builder\". DO NOT EDIT.\n\npackage main\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/otelcol\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t{{.Telemetry.Name}} \"{{.Telemetry.Import}}\"\n\t{{- range .Connectors}}\n\t{{.Name}} \"{{.Import}}\"\n\t{{- end}}\n\t{{- range .Exporters}}\n\t{{.Name}} \"{{.Import}}\"\n\t{{- end}}\n\t{{- range .Extensions}}\n\t{{.Name}} \"{{.Import}}\"\n\t{{- end}}\n\t{{- range .Processors}}\n\t{{.Name}} \"{{.Import}}\"\n\t{{- end}}\n\t{{- range .Receivers}}\n\t{{.Name}} \"{{.Import}}\"\n\t{{- end}}\n)\n\ntype aliasProvider interface{ DeprecatedAlias() component.Type }\n\nfunc makeModulesMap[T component.Factory](factories map[component.Type]T, modules map[component.Type]string) map[component.Type]string {\n\tfor compType, factory := range factories {\n\t\tif ap, ok := any(factory).(aliasProvider); ok {\n\t\t\talias := ap.DeprecatedAlias()\n\t\t\tif alias.String() != \"\" {\n\t\t\t\tmodules[alias] = modules[compType]\n\t\t\t}\n\t\t}\n\t}\n\treturn modules\n}\n\nfunc components() (otelcol.Factories, error) {\n\tvar err error\n\tfactories := otelcol.Factories{\n\t\tTelemetry: {{.Telemetry.Name}}.NewFactory(),\n\t}\n\n\tfactories.Extensions, err = otelcol.MakeFactoryMap[extension.Factory](\n\t\t{{- range .Extensions}}\n\t\t{{.Name}}.NewFactory(),\n\t\t{{- end}}\n\t)\n\tif err != nil {\n\t\treturn otelcol.Factories{}, err\n\t}\n\tfactories.ExtensionModules = makeModulesMap(factories.Extensions, map[component.Type]string{\n\t\t{{- range .Extensions}}\n\t\t{{.Name}}.NewFactory().Type(): \"{{.GoMod}}\",\n\t\t{{- end}}\n\t})\n\n\tfactories.Receivers, err = otelcol.MakeFactoryMap[receiver.Factory](\n\t\t{{- range .Receivers}}\n\t\t{{.Name}}.NewFactory(),\n\t\t{{- end}}\n\t)\n\tif err != nil {\n\t\treturn otelcol.Factories{}, err\n\t}\n\tfactories.ReceiverModules = makeModulesMap(factories.Receivers, map[component.Type]string{\n\t\t{{- range .Receivers}}\n\t\t{{.Name}}.NewFactory().Type(): \"{{.GoMod}}\",\n\t\t{{- end}}\n\t})\n\n\tfactories.Exporters, err = otelcol.MakeFactoryMap[exporter.Factory](\n\t\t{{- range .Exporters}}\n\t\t{{.Name}}.NewFactory(),\n\t\t{{- end}}\n\t)\n\tif err != nil {\n\t\treturn otelcol.Factories{}, err\n\t}\n\tfactories.ExporterModules = makeModulesMap(factories.Exporters, map[component.Type]string{\n\t\t{{- range .Exporters}}\n\t\t{{.Name}}.NewFactory().Type(): \"{{.GoMod}}\",\n\t\t{{- end}}\n\t})\n\n\tfactories.Processors, err = otelcol.MakeFactoryMap[processor.Factory](\n\t\t{{- range .Processors}}\n\t\t{{.Name}}.NewFactory(),\n\t\t{{- end}}\n\t)\n\tif err != nil {\n\t\treturn otelcol.Factories{}, err\n\t}\n\tfactories.ProcessorModules = makeModulesMap(factories.Processors, map[component.Type]string{\n\t\t{{- range .Processors}}\n\t\t{{.Name}}.NewFactory().Type(): \"{{.GoMod}}\",\n\t\t{{- end}}\n\t})\n\n\tfactories.Connectors, err = otelcol.MakeFactoryMap[connector.Factory](\n\t\t{{- range .Connectors}}\n\t\t{{.Name}}.NewFactory(),\n\t\t{{- end}}\n\t)\n\tif err != nil {\n\t\treturn otelcol.Factories{}, err\n\t}\n\tfactories.ConnectorModules = makeModulesMap(factories.Connectors, map[component.Type]string{\n\t\t{{- range .Connectors}}\n\t\t{{.Name}}.NewFactory().Type(): \"{{.GoMod}}\",\n\t\t{{- end}}\n\t})\n\n\treturn factories, nil\n}\n"
  },
  {
    "path": "cmd/builder/internal/builder/templates/go.mod.tmpl",
    "content": "// Code generated by \"go.opentelemetry.io/collector/cmd/builder\". DO NOT EDIT.\n\nmodule {{.Distribution.Module}}\n\ngo 1.25\n\nrequire (\n\t{{- range .ConfmapConverters}}\n\t{{if .GoMod}}{{.GoMod}}{{end}}\n\t{{- end}}\n\t{{- range .ConfmapProviders}}\n\t{{if .GoMod}}{{.GoMod}}{{end}}\n\t{{- end}}\n\t{{- range .Connectors}}\n\t{{if .GoMod}}{{.GoMod}}{{end}}\n\t{{- end}}\n\t{{- range .Extensions}}\n\t{{if .GoMod}}{{.GoMod}}{{end}}\n\t{{- end}}\n\t{{- range .Receivers}}\n\t{{if .GoMod}}{{.GoMod}}{{end}}\n\t{{- end}}\n\t{{- range .Exporters}}\n\t{{if .GoMod}}{{.GoMod}}{{end}}\n\t{{- end}}\n\t{{- range .Processors}}\n\t{{if .GoMod}}{{.GoMod}}{{end}}\n\t{{- end}}\n\t{{if .Telemetry.GoMod}}{{.Telemetry.GoMod}}{{end}}\n\tgo.opentelemetry.io/collector/otelcol {{.OtelColVersion}}\n)\n\nrequire (\n\tgithub.com/knadh/koanf/maps v0.1.1 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v0.1.0 // indirect\n)\n\n{{- range .ConfmapConverters}}\n{{if ne .Path \"\"}}replace {{.GoMod}} => {{.Path}}{{end}}\n{{- end}}\n{{- range .ConfmapProviders}}\n{{if ne .Path \"\"}}replace {{.GoMod}} => {{.Path}}{{end}}\n{{- end}}\n{{- range .Connectors}}\n{{if ne .Path \"\"}}replace {{.GoMod}} => {{.Path}}{{end}}\n{{- end}}\n{{- range .Extensions}}\n{{if ne .Path \"\"}}replace {{.GoMod}} => {{.Path}}{{end}}\n{{- end}}\n{{- range .Receivers}}\n{{if ne .Path \"\"}}replace {{.GoMod}} => {{.Path}}{{end}}\n{{- end}}\n{{- range .Exporters}}\n{{if ne .Path \"\"}}replace {{.GoMod}} => {{.Path}}{{end}}\n{{- end}}\n{{- range .Processors}}\n{{if ne .Path \"\"}}replace {{.GoMod}} => {{.Path}}{{end}}\n{{- end}}\n{{if ne .Telemetry.Path \"\"}}replace {{.Telemetry.GoMod}} => {{.Telemetry.Path}}{{end}}\n{{- range .Replaces}}\nreplace {{.}}\n{{- end}}\n{{- range .Excludes}}\nexclude {{.}}\n{{- end}}\n"
  },
  {
    "path": "cmd/builder/internal/builder/templates/main.go.tmpl",
    "content": "// Code generated by \"go.opentelemetry.io/collector/cmd/builder\". DO NOT EDIT.\n\n// Program {{ .Distribution.Name }} is an OpenTelemetry Collector binary.\npackage main\n\nimport (\n\t\"os\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t{{- range .ConfmapConverters}}\n\t{{.Name}} \"{{.Import}}\"\n\t{{- end}}\n\t{{- range .ConfmapProviders}}\n\t{{.Name}} \"{{.Import}}\"\n\t{{- end}}\n\t\"go.opentelemetry.io/collector/otelcol\"\n)\n\nfunc main() {\n\tinfo := component.BuildInfo{\n\t\tCommand:     \"{{ .Distribution.Name }}\",\n\t\tDescription: \"{{ .Distribution.Description }}\",\n\t\tVersion:     \"{{ .Distribution.Version }}\",\n\t}\n\n\tset := otelcol.CollectorSettings{\n\t\tBuildInfo: info,\n\t\tFactories: components,\n\t\tConfigProviderSettings: otelcol.ConfigProviderSettings{\n\t\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\t\tProviderFactories: []confmap.ProviderFactory{\n\t\t\t\t\t{{- range .ConfmapProviders}}\n\t\t\t\t\t{{.Name}}.NewFactory(),\n\t\t\t\t\t{{- end}}\n\t\t\t\t},\n\t\t\t\t{{- if .ConfmapConverters }}\n\t\t\t\tConverterFactories: []confmap.ConverterFactory{\n\t\t\t\t\t{{- range .ConfmapConverters}}\n\t\t\t\t\t{{.Name}}.NewFactory(),\n\t\t\t\t\t{{- end}}\n\t\t\t\t},\n\t\t\t\t{{- end }}\n\t\t\t\t{{- if .ConfResolver.DefaultURIScheme }}\n\t\t\t\tDefaultScheme: \"{{ .ConfResolver.DefaultURIScheme }}\",\n\t\t\t\t{{- end }}\n\t\t\t},\n\t\t},\n\t\tProviderModules: map[string]string{\n\t\t\t{{- range .ConfmapProviders}}\n\t\t\t{{.Name}}.NewFactory().Create(confmap.ProviderSettings{}).Scheme(): \"{{.GoMod}}\",\n\t\t\t{{- end}}\n\t\t},\n\t\tConverterModules: []string{\n\t\t\t{{- range .ConfmapConverters}}\n\t\t\t\"{{.GoMod}}\",\n\t\t\t{{- end}}\n\t\t},\n\t}\n\n\tif err := run(set); err != nil {\n\t\t// The error message is logged by cobra, so we intentionally\n\t\t// avoid logging it again here to prevent duplicate output.\n\t\tos.Exit(1)\n\t}\n}\n\nfunc runInteractive(params otelcol.CollectorSettings) error {\n\tcmd := otelcol.NewCommand(params)\n\tif err := cmd.Execute(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/builder/internal/builder/templates/main_others.go.tmpl",
    "content": "// Code generated by \"go.opentelemetry.io/collector/cmd/builder\". DO NOT EDIT.\n\n//go:build !windows\n\npackage main\n\nimport \"go.opentelemetry.io/collector/otelcol\"\n\nfunc run(params otelcol.CollectorSettings) error {\n\treturn runInteractive(params)\n}\n"
  },
  {
    "path": "cmd/builder/internal/builder/templates/main_windows.go.tmpl",
    "content": "// Code generated by \"go.opentelemetry.io/collector/cmd/builder\". DO NOT EDIT.\n\n//go:build windows\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"golang.org/x/sys/windows\"\n\t\"golang.org/x/sys/windows/svc\"\n\t\"go.opentelemetry.io/collector/otelcol\"\n)\n\nfunc run(params otelcol.CollectorSettings) error {\n\t// No need to supply service name when startup is invoked through\n\t// the Service Control Manager directly.\n\tif err := svc.Run(\"\", otelcol.NewSvcHandler(params)); err != nil {\n\t\tif errors.Is(err, windows.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {\n\t\t\t// Per https://learn.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-startservicectrldispatchera#return-value\n\t\t\t// this means that the process is not running as a service, so run interactively.\n\t\t\treturn runInteractive(params)\n\t\t}\n\n\t\treturn fmt.Errorf(\"failed to start collector server: %w\", err)\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/builder/internal/builder/templates.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builder // import \"go.opentelemetry.io/collector/cmd/builder/internal/builder\"\n\nimport (\n\t_ \"embed\"\n\t\"text/template\"\n)\n\nvar (\n\t//go:embed templates/components.go.tmpl\n\tcomponentsBytes    []byte\n\tcomponentsTemplate = parseTemplate(\"components.go\", componentsBytes)\n\n\t//go:embed templates/main.go.tmpl\n\tmainBytes    []byte\n\tmainTemplate = parseTemplate(\"main.go\", mainBytes)\n\n\t//go:embed templates/main_others.go.tmpl\n\tmainOthersBytes    []byte\n\tmainOthersTemplate = parseTemplate(\"main_others.go\", mainOthersBytes)\n\n\t//go:embed templates/main_windows.go.tmpl\n\tmainWindowsBytes    []byte\n\tmainWindowsTemplate = parseTemplate(\"main_windows.go\", mainWindowsBytes)\n\n\t//go:embed templates/go.mod.tmpl\n\tgoModBytes    []byte\n\tgoModTemplate = parseTemplate(\"go.mod\", goModBytes)\n)\n\nfunc parseTemplate(name string, bytes []byte) *template.Template {\n\treturn template.Must(template.New(name).Parse(string(bytes)))\n}\n"
  },
  {
    "path": "cmd/builder/internal/command.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/cmd/builder/internal\"\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/knadh/koanf/parsers/yaml\"\n\t\"github.com/knadh/koanf/providers/env/v2\"\n\t\"github.com/knadh/koanf/providers/file\"\n\t\"github.com/knadh/koanf/v2\"\n\t\"github.com/spf13/cobra\"\n\tflag \"github.com/spf13/pflag\"\n\t\"go.uber.org/multierr\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/cmd/builder/internal/builder\"\n\t\"go.opentelemetry.io/collector/cmd/builder/internal/config\"\n)\n\nconst (\n\tconfigFlag                 = \"config\"\n\tskipGenerateFlag           = \"skip-generate\"\n\tskipCompilationFlag        = \"skip-compilation\"\n\tskipGetModulesFlag         = \"skip-get-modules\"\n\tskipStrictVersioningFlag   = \"skip-strict-versioning\"\n\tldflagsFlag                = \"ldflags\"\n\tgcflagsFlag                = \"gcflags\"\n\tdistributionOutputPathFlag = \"output-path\"\n\tverboseFlag                = \"verbose\"\n)\n\n// Command is the main entrypoint for this application\nfunc Command() (*cobra.Command, error) {\n\tcmd := &cobra.Command{\n\t\tSilenceUsage: true, // Don't print usage on Run error.\n\t\tUse:          \"ocb\",\n\t\tLong: fmt.Sprintf(\"OpenTelemetry Collector Builder (%s)\", version) + `\n\nocb generates a custom OpenTelemetry Collector binary using the\nbuild configuration given by the \"--config\" argument. If no build\nconfiguration is provided, ocb will generate a default Collector.\n`,\n\t\tArgs: cobra.NoArgs,\n\t\tRunE: func(cmd *cobra.Command, _ []string) error {\n\t\t\tcfg, err := initConfig(cmd.Flags())\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif err = cfg.Validate(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"invalid configuration: %w\", err)\n\t\t\t}\n\n\t\t\tif err = cfg.SetGoPath(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"go not found: %w\", err)\n\t\t\t}\n\n\t\t\tif err = cfg.ParseModules(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"invalid module configuration: %w\", err)\n\t\t\t}\n\n\t\t\treturn builder.GenerateAndCompile(cfg)\n\t\t},\n\t}\n\n\tif err := initFlags(cmd.Flags()); err != nil {\n\t\treturn nil, err\n\t}\n\n\tcmd.AddCommand(initCommand())\n\tcmd.AddCommand(versionCommand())\n\n\treturn cmd, nil\n}\n\nfunc initFlags(flags *flag.FlagSet) error {\n\tflags.String(configFlag, \"\", \"build configuration file\")\n\t// the distribution parameters, which we accept as CLI flags as well\n\tflags.Bool(skipGenerateFlag, false, \"Whether builder should skip generating go code (default false)\")\n\tflags.Bool(skipCompilationFlag, false, \"Whether builder should only generate go code with no compile of the collector (default false)\")\n\tflags.Bool(skipGetModulesFlag, false, \"Whether builder should skip updating go.mod and retrieve Go module list (default false)\")\n\tflags.Bool(skipStrictVersioningFlag, true, \"Whether builder should skip strictly checking the calculated versions following dependency resolution\")\n\tflags.Bool(verboseFlag, false, \"Whether builder should print verbose output (default false)\")\n\tflags.String(ldflagsFlag, \"\", `ldflags to include in the \"go build\" command`)\n\tflags.String(gcflagsFlag, \"\", `gcflags to include in the \"go build\" command`)\n\tflags.String(distributionOutputPathFlag, \"\", \"Where to write the resulting files\")\n\treturn flags.MarkDeprecated(distributionOutputPathFlag, \"use config distribution::output_path\")\n}\n\nfunc initConfig(flags *flag.FlagSet) (*builder.Config, error) {\n\tcfg, err := builder.NewDefaultConfig()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcfg.Logger.Info(\"OpenTelemetry Collector Builder\", zap.String(\"version\", version))\n\n\tvar provider koanf.Provider\n\tcfgFile, _ := flags.GetString(configFlag)\n\tif cfgFile != \"\" {\n\t\tcfg.Logger.Info(\"Using config file\", zap.String(\"path\", cfgFile))\n\t\t// load the config file\n\t\tprovider = file.Provider(cfgFile)\n\t} else {\n\t\tcfg.Logger.Info(\"Using default build configuration\")\n\t\t// or the default if the config isn't provided\n\t\tprovider = config.DefaultProvider()\n\t}\n\n\tk := koanf.New(\".\")\n\tif err = k.Load(provider, yaml.Parser()); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load configuration file: %w\", err)\n\t}\n\n\t// handle env variables\n\tif err = k.Load(env.Provider(\".\", env.Opt{}), nil); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load environment variables: %w\", err)\n\t}\n\n\tif err = k.UnmarshalWithConf(\"\", cfg, koanf.UnmarshalConf{Tag: \"mapstructure\"}); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to unmarshal configuration: %w\", err)\n\t}\n\n\tif err = applyFlags(flags, cfg); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to apply flags configuration: %w\", err)\n\t}\n\n\treturn cfg, nil\n}\n\nfunc applyFlags(flags *flag.FlagSet, cfg *builder.Config) error {\n\tvar errs, err error\n\tcfg.SkipGenerate, err = flags.GetBool(skipGenerateFlag)\n\terrs = multierr.Append(errs, err)\n\tcfg.SkipCompilation, err = flags.GetBool(skipCompilationFlag)\n\terrs = multierr.Append(errs, err)\n\tcfg.SkipGetModules, err = flags.GetBool(skipGetModulesFlag)\n\terrs = multierr.Append(errs, err)\n\tcfg.SkipStrictVersioning, err = flags.GetBool(skipStrictVersioningFlag)\n\terrs = multierr.Append(errs, err)\n\n\tif flags.Changed(ldflagsFlag) {\n\t\tcfg.LDSet = true\n\t\tcfg.LDFlags, err = flags.GetString(ldflagsFlag)\n\t\terrs = multierr.Append(errs, err)\n\t}\n\tif flags.Changed(gcflagsFlag) {\n\t\tcfg.GCSet = true\n\t\tcfg.GCFlags, err = flags.GetString(gcflagsFlag)\n\t\terrs = multierr.Append(errs, err)\n\t}\n\n\tcfg.Verbose, err = flags.GetBool(verboseFlag)\n\terrs = multierr.Append(errs, err)\n\n\tif flags.Changed(distributionOutputPathFlag) {\n\t\tcfg.Distribution.OutputPath, err = flags.GetString(distributionOutputPathFlag)\n\t\terrs = multierr.Append(errs, err)\n\t}\n\n\treturn errs\n}\n"
  },
  {
    "path": "cmd/builder/internal/command_init.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/cmd/builder/internal\"\n\nimport (\n\t\"bytes\"\n\t\"embed\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path\"\n\t\"path/filepath\"\n\t\"text/template\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"go.opentelemetry.io/collector/cmd/builder/internal/builder\"\n)\n\nconst defaultDescription = \"Custom OpenTelemetry Collector\"\n\n//go:embed init/templates/*.tmpl\nvar templatesFS embed.FS\n\ntype metadata struct {\n\tName          string\n\tDescription   string\n\tStableVersion string\n\tBetaVersion   string\n}\n\nfunc initCommand() *cobra.Command {\n\tvar outputPath string\n\n\tcmd := &cobra.Command{\n\t\tUse:   \"init\",\n\t\tShort: \"[EXPERIMENTAL] Initializes a new custom collector repository in the provided folder\",\n\t\tLong:  `ocb init initializes a new repository in the provided folder with a manifest to start building a custom Collector. This command is experimental and very likely to change.`,\n\t\tArgs:  cobra.NoArgs,\n\t\tRunE: func(_ *cobra.Command, _ []string) error {\n\t\t\treturn run(outputPath)\n\t\t},\n\t}\n\n\tcmd.Flags().StringVar(&outputPath, \"path\", \".\", \"Output path where the collector repository will be initialized\")\n\n\treturn cmd\n}\n\nfunc run(path string) error {\n\tif path == \"\" {\n\t\treturn errors.New(\"argument must be a folder\")\n\t}\n\tpath, err := filepath.Abs(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get absolute path for %v: %w\", path, err)\n\t}\n\terr = os.MkdirAll(path, 0o750)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed creating folder %v: %w\", path, err)\n\t}\n\n\tmeta := metadata{\n\t\tName:          filepath.Base(path),\n\t\tDescription:   defaultDescription,\n\t\tStableVersion: builder.DefaultStableOtelColVersion,\n\t\tBetaVersion:   builder.DefaultBetaOtelColVersion,\n\t}\n\n\terr = writeTemplate(path, \"manifest.yaml\", meta)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed writing manifest: %w\", err)\n\t}\n\n\terr = writeTemplate(path, \".gitignore\", meta)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed writing gitignore: %w\", err)\n\t}\n\n\terr = writeTemplate(path, \"README.md\", meta)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed writing README: %w\", err)\n\t}\n\n\terr = writeTemplate(path, \"go.mod\", meta)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed writing go.mod: %w\", err)\n\t}\n\n\terr = writeTemplate(path, \"Makefile\", meta)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed writing Makefile: %w\", err)\n\t}\n\n\terr = writeTemplate(path, \"config.yaml\", meta)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed writing config.yaml: %w\", err)\n\t}\n\n\terr = os.MkdirAll(filepath.Join(path, \"build\"), 0o750)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed creating build folder: %w\", err)\n\t}\n\n\terr = runTidy(path)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed running go mod tidy: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc writeTemplate(path, fn string, m metadata) error {\n\toutputFile := filepath.Join(path, fn)\n\n\tcontent, err := executeTemplate(fn+\".tmpl\", m)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn os.WriteFile(outputFile, content, 0o600)\n}\n\nfunc executeTemplate(tmplFile string, m metadata) ([]byte, error) {\n\ttmplPath := path.Join(\"init/templates\", tmplFile)\n\ttmpl := template.Must(template.New(tmplFile).ParseFS(templatesFS, tmplPath))\n\tbuf := bytes.Buffer{}\n\n\tif err := tmpl.Execute(&buf, m); err != nil {\n\t\treturn []byte{}, fmt.Errorf(\"failed executing template: %w\", err)\n\t}\n\treturn buf.Bytes(), nil\n}\n\nfunc runTidy(path string) error {\n\tcmd := exec.Command(\"go\", \"mod\", \"tidy\")\n\tcmd.Dir = path\n\toutput, err := cmd.CombinedOutput()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"%w (%s)\", err, string(output))\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/builder/internal/command_init_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/cmd/builder/internal\"\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/knadh/koanf/parsers/yaml\"\n\t\"github.com/knadh/koanf/providers/file\"\n\t\"github.com/knadh/koanf/v2\"\n\t\"github.com/spf13/cobra\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/cmd/builder/internal/builder\"\n)\n\nfunc TestInitCommand(t *testing.T) {\n\tcmd := initCommand()\n\n\tassert.NotNil(t, cmd)\n\tassert.IsType(t, &cobra.Command{}, cmd)\n\tassert.Equal(t, \"init\", cmd.Use)\n}\n\nfunc TestRunInit(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname      string\n\t\tbuildPath func(string) string\n\n\t\twantErr string\n\t}{\n\t\t{\n\t\t\tname:      \"without a path\",\n\t\t\tbuildPath: func(string) string { return \"\" },\n\t\t\twantErr:   \"argument must be a folder\",\n\t\t},\n\t\t{\n\t\t\tname:      \"with a relative path\",\n\t\t\tbuildPath: func(string) string { return \"./tmp/init\" },\n\t\t\twantErr:   \"\",\n\t\t},\n\t\t{\n\t\t\tname:      \"with an absolute path\",\n\t\t\tbuildPath: func(dir string) string { return dir },\n\t\t\twantErr:   \"\",\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttmpdir := filepath.Join(t.TempDir(), \"init\")\n\t\t\tpath := tt.buildPath(tmpdir)\n\t\t\terr := run(path)\n\n\t\t\tif tt.wantErr == \"\" {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tvalidateCollector(t, path)\n\t\t\t} else {\n\t\t\t\trequire.ErrorContains(t, err, tt.wantErr)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc validateCollector(t *testing.T, path string) {\n\trequire.FileExists(t, filepath.Join(path, \".gitignore\"))\n\trequire.FileExists(t, filepath.Join(path, \"README.md\"))\n\trequire.FileExists(t, filepath.Join(path, \"manifest.yaml\"))\n\trequire.FileExists(t, filepath.Join(path, \"go.mod\"))\n\trequire.FileExists(t, filepath.Join(path, \"go.sum\"))\n\trequire.FileExists(t, filepath.Join(path, \"Makefile\"))\n\trequire.FileExists(t, filepath.Join(path, \"config.yaml\"))\n\n\tk := koanf.New(\".\")\n\terr := k.Load(file.Provider(filepath.Join(path, \"manifest.yaml\")), yaml.Parser())\n\trequire.NoError(t, err)\n\n\tcfg := builder.Config{}\n\terr = k.UnmarshalWithConf(\"\", &cfg, koanf.UnmarshalConf{\n\t\tTag: \"mapstructure\",\n\t})\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, \"init\", cfg.Distribution.Name)\n\tassert.Equal(t, defaultDescription, cfg.Distribution.Description)\n}\n"
  },
  {
    "path": "cmd/builder/internal/command_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"bytes\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/spf13/cobra\"\n\tflag \"github.com/spf13/pflag\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/cmd/builder/internal/builder\"\n)\n\nfunc TestCommand(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\twant    *cobra.Command\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname: \"command created\",\n\t\t\twant: &cobra.Command{\n\t\t\t\tSilenceUsage: true, // Don't print usage on Run error.\n\t\t\t\tUse:          \"ocb\",\n\t\t\t\tLong:         \"OpenTelemetry Collector Builder\",\n\t\t\t\tArgs:         cobra.NoArgs,\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot, err := Command()\n\t\t\tif !tt.wantErr {\n\t\t\t\trequire.NoErrorf(t, err, \"Command()\")\n\t\t\t\tassert.Equal(t, tt.want.Aliases, got.Aliases)\n\t\t\t\tassert.Equal(t, tt.want.Annotations, got.Annotations)\n\t\t\t\tassert.Equal(t, tt.want.ValidArgs, got.ValidArgs)\n\t\t\t\tassert.Equal(t, tt.want.ArgAliases, got.ArgAliases)\n\t\t\t\tassert.Equal(t, tt.want.Use, got.Use)\n\t\t\t\tassert.Equal(t, tt.want.SilenceUsage, got.SilenceUsage)\n\t\t\t\tassert.Equal(t, tt.want.SilenceErrors, got.SilenceErrors)\n\t\t\t\tassert.True(t, strings.HasPrefix(got.Long, tt.want.Long))\n\t\t\t\tassert.Empty(t, got.Short)\n\t\t\t\tassert.NotEqual(t, tt.want.HasFlags(), got.Flags().HasFlags())\n\t\t\t} else {\n\t\t\t\trequire.Error(t, err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCommandErrorOutputOnce(t *testing.T) {\n\tcmd, err := Command()\n\trequire.NoError(t, err)\n\n\tvar stderr bytes.Buffer\n\tcmd.SetErr(&stderr)\n\tcmd.SetArgs([]string{\"/nonexistent/path/metadata.yaml\"})\n\n\terr = cmd.Execute()\n\trequire.Error(t, err)\n\tout := stderr.String()\n\trequire.NotEmpty(t, out)\n\n\tmsg := err.Error()\n\tassert.Equal(t, 1, strings.Count(out, msg), out)\n}\n\nfunc TestApplyFlags(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tflags []string\n\t\twant  *builder.Config\n\t}{\n\t\t{\n\t\t\tname: \"Default flag values\",\n\t\t\twant: &builder.Config{\n\t\t\t\tSkipStrictVersioning: true,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:  \"All flag values\",\n\t\t\tflags: []string{\"--skip-generate=true\", \"--skip-compilation=true\", \"--skip-get-modules=true\", \"--skip-strict-versioning=true\", \"--ldflags=test\", \"--gcflags=test\", \"--verbose=true\"},\n\t\t\twant: &builder.Config{\n\t\t\t\tSkipGenerate:         true,\n\t\t\t\tSkipCompilation:      true,\n\t\t\t\tSkipGetModules:       true,\n\t\t\t\tSkipStrictVersioning: true,\n\t\t\t\tLDFlags:              \"test\",\n\t\t\t\tGCFlags:              \"test\",\n\t\t\t\tVerbose:              true,\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tflags := flag.NewFlagSet(\"version=1.0.0\", 1)\n\t\t\trequire.NoError(t, initFlags(flags))\n\t\t\trequire.NoError(t, flags.Parse(tt.flags))\n\t\t\tcfg, err := builder.NewDefaultConfig()\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, applyFlags(flags, cfg))\n\t\t\tassert.Equal(t, tt.want.SkipGenerate, cfg.SkipGenerate)\n\t\t\tassert.Equal(t, tt.want.SkipCompilation, cfg.SkipCompilation)\n\t\t\tassert.Equal(t, tt.want.SkipGetModules, cfg.SkipGetModules)\n\t\t\tassert.Equal(t, tt.want.SkipStrictVersioning, cfg.SkipStrictVersioning)\n\t\t\tassert.Equal(t, tt.want.LDFlags, cfg.LDFlags)\n\t\t\tassert.Equal(t, tt.want.Verbose, cfg.Verbose)\n\t\t})\n\t}\n}\n\nfunc TestInitConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tflags   *flag.FlagSet\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:    \"initConfig created correctly\",\n\t\t\tflags:   flag.NewFlagSet(\"version=1.0.0\", 1),\n\t\t\twantErr: false,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\trequire.NoError(t, initFlags(tt.flags))\n\t\t\t_, err := initConfig(tt.flags)\n\t\t\tif tt.wantErr {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/builder/internal/config/default.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage config // import \"go.opentelemetry.io/collector/cmd/builder/internal/config\"\n\nimport (\n\t\"embed\"\n\n\t\"github.com/knadh/koanf/providers/fs\"\n\t\"github.com/knadh/koanf/v2\"\n)\n\n//go:embed *.yaml\nvar configs embed.FS\n\n// DefaultProvider returns a koanf.Provider that provides the default build\n// configuration file. This is the same configuration that otelcorecol is\n// built with.\nfunc DefaultProvider() koanf.Provider {\n\treturn fs.Provider(configs, \"default.yaml\")\n}\n"
  },
  {
    "path": "cmd/builder/internal/config/default.yaml",
    "content": "# NOTE:\n# This builder configuration is NOT used to build any official binary.\n# To see the builder manifests used for official binaries,\n# check https://github.com/open-telemetry/opentelemetry-collector-releases\n#\n# For the OpenTelemetry Collector Core official distribution sources, check\n# https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n\ndist:\n  module: go.opentelemetry.io/collector/cmd/otelcorecol\n  name: otelcorecol\n  description: Local OpenTelemetry Collector binary, testing only.\n  version: 0.148.0-dev\n\nreceivers:\n  - gomod: go.opentelemetry.io/collector/receiver/nopreceiver v0.148.0\n  - gomod: go.opentelemetry.io/collector/receiver/otlpreceiver v0.148.0\nexporters:\n  - gomod: go.opentelemetry.io/collector/exporter/debugexporter v0.148.0\n  - gomod: go.opentelemetry.io/collector/exporter/nopexporter v0.148.0\n  - gomod: go.opentelemetry.io/collector/exporter/otlpexporter v0.148.0\n  - gomod: go.opentelemetry.io/collector/exporter/otlphttpexporter v0.148.0\nextensions:\n  - gomod: go.opentelemetry.io/collector/extension/memorylimiterextension v0.148.0\n  - gomod: go.opentelemetry.io/collector/extension/zpagesextension v0.148.0\nprocessors:\n  - gomod: go.opentelemetry.io/collector/processor/batchprocessor v0.148.0\n  - gomod: go.opentelemetry.io/collector/processor/memorylimiterprocessor v0.148.0\nconnectors:\n  - gomod: go.opentelemetry.io/collector/connector/forwardconnector v0.148.0\n\nproviders:\n  - gomod: go.opentelemetry.io/collector/confmap/provider/envprovider v1.54.0\n  - gomod: go.opentelemetry.io/collector/confmap/provider/fileprovider v1.54.0\n  - gomod: go.opentelemetry.io/collector/confmap/provider/httpprovider v1.54.0\n  - gomod: go.opentelemetry.io/collector/confmap/provider/httpsprovider v1.54.0\n  - gomod: go.opentelemetry.io/collector/confmap/provider/yamlprovider v1.54.0\n\ntelemetry:\n  gomod: go.opentelemetry.io/collector/service v0.148.0\n  import: go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\n\n"
  },
  {
    "path": "cmd/builder/internal/init/templates/.gitignore.tmpl",
    "content": "build/\n"
  },
  {
    "path": "cmd/builder/internal/init/templates/Makefile.tmpl",
    "content": "GOMODULES := $(shell find . -mindepth 2 \\\n\t\t\t\t\t\t\t -type f \\\n\t\t\t\t\t\t\t -name \"go.mod\" \\\n\t\t\t\t\t\t\t -not -path \"./internal/tools/*\" \\\n\t\t\t\t\t\t\t -exec dirname {} \\; | sort )\n\n\n.PHONY: generate\ngenerate:\n\tgo tool go.opentelemetry.io/collector/cmd/builder --verbose --config manifest.yaml\n\tcd build/collector && go mod tidy\n\n.PHONY: run\nrun: generate\n\t@cd build/collector && \\\n\t./{{.Name}} --config ../../config.yaml\n"
  },
  {
    "path": "cmd/builder/internal/init/templates/README.md.tmpl",
    "content": "# {{.Name}} Collector\n\nWelcome to your new custom OpenTelemetry Collector!\nThis Collector allows you to configure the components you wish to use, and only those.\n\nComponents can come from the ones provided by the OpenTelemetry organization in\nthe\n[opentelemetry-collector-contrib](https://github.com/open-telemetry/opentelemetry-collector-contrib)\nrepository, or from any other source, including your [custom, possibly private\ncode](https://opentelemetry.io/docs/collector/extend/custom-component/). The\nonly requirement is that they match the Go interface for that component, so the\nCollector can run them.\n\n## Important files\n\nEdit these two files to customize your Collector:\n\n* `manifest.yaml` - The manifest file configures the OpenTelemetry Collector Builder and tells it what modules it needs to enable within your custom collector.\n  See [Configure the OpenTelemetry Collector Builder](https://opentelemetry.io/docs/collector/extend/ocb/#configure-the-opentelemetry-collector-builder) for more information.\n* `config.yaml` - The Collector configuration allows you to configure your components and their pipelines. This is where you tell your Collector where it needs to export data.\n  See [Collector Configuration](https://opentelemetry.io/docs/collector/configuration/) for more information.\n\n## Running your custom Collector\n\nYou can already run your custom Collector, though it only includes the OTLP\nreceiver and exporter.\n\nUse the following make command:\n\n```\nmake run\n```\n\nThis will build your collector inside the `build/collector` folder, and then\nrun the compiled binary.\n\nWith the `make generate` command, you can also build the collector but not run it.\n\n## Next\n\nTo learn more, read the [Extend the\nCollector](https://opentelemetry.io/docs/collector/extend/) documentation,\nwhich will give you pointers to configure your new custom Collector, and to\nbuild custom components.\n"
  },
  {
    "path": "cmd/builder/internal/init/templates/config.yaml.tmpl",
    "content": "receivers:\n  otlp:\n    protocols:\n      grpc:\n        endpoint: 0.0.0.0:4317\n      http:\n        endpoint: 0.0.0.0:4318\n\nexporters:\n  otlp:\n    endpoint: https://localhost:4318\n\nservice:\n  pipelines:\n    traces:\n      receivers: [otlp]\n      exporters: [otlp]\n    metrics:\n      receivers: [otlp]\n      exporters: [otlp]\n    logs:\n        receivers: [otlp]\n        exporters: [otlp]\n"
  },
  {
    "path": "cmd/builder/internal/init/templates/go.mod.tmpl",
    "content": "module {{.Name}}\n\ngo 1.25\n\ntool go.opentelemetry.io/collector/cmd/builder\n"
  },
  {
    "path": "cmd/builder/internal/init/templates/manifest.yaml.tmpl",
    "content": "dist:\n  name: {{.Name}}\n  description: {{.Description}}\n  output_path: ./build/collector\n\nexporters:\n  - gomod: go.opentelemetry.io/collector/exporter/otlpexporter {{.BetaVersion}}\n\nreceivers:\n  - gomod: go.opentelemetry.io/collector/receiver/otlpreceiver {{.BetaVersion}}\n"
  },
  {
    "path": "cmd/builder/internal/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "cmd/builder/internal/version.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/cmd/builder/internal\"\n\nimport (\n\t\"fmt\"\n\t\"runtime/debug\"\n\n\t\"github.com/spf13/cobra\"\n)\n\nvar version = \"\"\n\nfunc init() {\n\t// the second returned value is a boolean, which is true if the binaries are built with module support.\n\tif version != \"\" {\n\t\treturn\n\t}\n\tinfo, ok := debug.ReadBuildInfo()\n\tif ok {\n\t\tversion = info.Main.Version\n\t}\n}\n\nfunc versionCommand() *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse:   \"version\",\n\t\tShort: \"Version of ocb\",\n\t\tLong:  \"Prints the version of the ocb binary\",\n\t\tRunE: func(cmd *cobra.Command, _ []string) error {\n\t\t\tcmd.Println(fmt.Sprintf(\"%s version %s\", cmd.Parent().Name(), version))\n\t\t\treturn nil\n\t\t},\n\t}\n}\n"
  },
  {
    "path": "cmd/builder/main.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage main\n\nimport (\n\t\"os\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"go.opentelemetry.io/collector/cmd/builder/internal\"\n)\n\nfunc main() {\n\tcmd, err := internal.Command()\n\tcobra.CheckErr(err)\n\n\tif err := cmd.Execute(); err != nil {\n\t\tos.Exit(1)\n\t}\n}\n"
  },
  {
    "path": "cmd/builder/metadata.yaml",
    "content": "type: builder\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: cmd\n  stability:\n    alpha: [metrics]\n  codeowners:\n    active: [ArthurSens, dmathieu]\n"
  },
  {
    "path": "cmd/builder/test/README.md",
    "content": "# Testing for the OpenTelemetry Collector Builder\n\nThis is a set of end-to-end tests for the builder. As such, it includes only positive tests, based on the manifest files in this directory. Each manifest is expected to be in a working state and should yield an OpenTelemetry Collector instance that is ready within a time interval. \"Ready\" is defined by calling its healthcheck endpoint.\n"
  },
  {
    "path": "cmd/builder/test/core.builder.yaml",
    "content": "dist:\n  name: core\n  module: go.opentelemetry.io/collector/builder/test/core\n  go: ${GOBIN}\n\nextensions:\n  - gomod: go.opentelemetry.io/collector/extension/zpagesextension v0.148.0\n\nreceivers:\n  - gomod: go.opentelemetry.io/collector/receiver/otlpreceiver v0.148.0\n\nexporters:\n  - gomod: go.opentelemetry.io/collector/exporter/debugexporter v0.148.0\n"
  },
  {
    "path": "cmd/builder/test/core.otel.yaml",
    "content": "extensions:\n  zpages:\n\nreceivers:\n  otlp:\n    protocols:\n      grpc:\n\nprocessors:\n\nexporters:\n  debug:\n\nservice:\n  extensions: [zpages]\n  pipelines:\n    traces:\n      receivers:\n        - otlp\n      processors: []\n      exporters:\n        - debug\n"
  },
  {
    "path": "cmd/builder/test/test.sh",
    "content": "#!/bin/bash\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n\nSCRIPT_DIR=$( cd -- \"$( dirname -- \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd )\nWORKSPACE_DIR=$( cd -- \"$( dirname \"$(dirname \"$(dirname -- \"${SCRIPT_DIR}\")\")\" )\" &> /dev/null && pwd )\nexport WORKSPACE_DIR\n\nGOBIN=$(go env GOBIN)\nif [[ \"$GO\" == \"\" ]]; then\n    GOBIN=$(which go)\nfi\nexport GOBIN\n\nif [[ \"$GOBIN\" == \"\" ]]; then\n    echo \"Could not determine which Go binary to use.\"\n    exit 1\nfi\n\necho \"Using ${GOBIN} to compile the distributions.\"\n\ntest_build_config() {\n    local test=\"$1\"\n    local build_config=\"$2\"\n\n    out=\"${base}/${test}\"\n    if ! mkdir -p \"${out}\"; then\n        echo \"❌ FAIL ${test}. Failed to create test directory for the test. Aborting tests.\"\n        exit 2\n    fi\n\n    echo \"Starting test '${test}' at $(date)\" >> \"${out}/test.log\"\n\n    final_build_config=$(basename \"${build_config}\")\n    go tool -modfile \"${WORKSPACE_DIR}/internal/tools/go.mod\" envsubst \\\n       -o \"${out}/${final_build_config}\" -i <(cat \"$build_config\" \"$replaces\")\n    if ! go run . --config \"${out}/${final_build_config}\" --output-path \"${out}\" > \"${out}/builder.log\" 2>&1; then\n        echo \"❌ FAIL ${test}. Failed to compile the test ${test}. Build logs:\"\n        cat \"${out}/builder.log\"\n        failed=true\n        return\n    fi\n\n    if [ ! -f \"${out}/${test}\" ]; then\n        echo \"❌ FAIL ${test}. Binary not found for ${test} at '${out}/${test}'. Build logs:\"\n        cat \"${out}/builder.log\"\n        failed=true\n        return\n    fi\n\n    # start the distribution\n    if [ ! -f \"./test/${test}.otel.yaml\" ]; then\n        echo \"❌ FAIL ${test}. Config file for ${test} not found at './test/${test}.otel.yaml'\"\n        failed=true\n        return\n    fi\n\n    \"${out}/${test}\" --config \"./test/${test}.otel.yaml\" > \"${out}/otelcol.log\" 2>&1 &\n    pid=$!\n\n    # each attempt pauses for 100ms before retrying\n    max_retries=50\n    retries=0\n    while true\n    do\n        if ! kill -0 \"${pid}\" >/dev/null 2>&1; then\n            echo \"❌ FAIL ${test}. The OpenTelemetry Collector isn't running. Startup log:\"\n            cat \"${out}/otelcol.log\"\n            failed=true\n            break\n        fi\n\n        # Since the content of the servicez page depend on which extensions are\n        # built into the collector, we depend only on the zpages extension\n        # being present and serving something.\n        if curl --fail --silent --output /dev/null http://localhost:55679/debug/servicez; then\n            echo \"✅ PASS ${test}\"\n\n            kill \"${pid}\"\n            ret=$?\n            if [ $ret -ne 0 ]; then\n                echo \"Failed to stop the running instance for test ${test}. Return code: ${ret} . Skipping tests.\"\n                exit 4\n            fi\n            break\n        fi\n\n        echo \"Server still unavailable for test '${test}'\" >> \"${out}/test.log\"\n\n        ((retries++))\n        if [ \"$retries\" -gt \"$max_retries\" ]; then\n            echo \"❌ FAIL ${test}. Server wasn't up after about 5s.\"\n            failed=true\n\n            kill \"${pid}\"\n            ret=$?\n            if [ $ret -ne 0 ]; then\n                echo \"Failed to stop the running instance for test ${test}. Return code: ${ret} . Skipping tests.\"\n                exit 8\n            fi\n            break\n        fi\n        sleep 0.1s\n    done\n\n    echo \"Stopping server for '${test}' (pid: ${pid})\" >> \"${out}/test.log\"\n\n}\n\ntest_init() {\n  out=\"${base}/init\"\n  if ! mkdir -p \"${out}\"; then\n      echo \"❌ FAIL ${test}. Failed to create test directory for the test. Aborting tests.\"\n      exit 2\n  fi\n\n  echo \"Starting init test at $(date)\" >> \"${out}/test.log\"\n\n  if ! go run . init --path \"${out}\" > \"${out}/builder.log\" 2>&1; then\n      echo \"❌ FAIL ${test}. Failed to compile the test. Build logs:\"\n      cat \"${out}/builder.log\"\n      failed=true\n      return\n  fi\n\n  go tool -modfile \"${WORKSPACE_DIR}/internal/tools/go.mod\" envsubst \\\n     -o \"${out}/manifest.yaml\" -i <(cat \"${out}/manifest.yaml\" \"$replaces\")\n\n  cd \"${out}\" || exit 1\n  make run > \"${out}/otelcol.log\" 2>&1 &\n  pid=$!\n\n  # each attempt pauses for 100ms before retrying\n  max_retries=15000\n  retries=0\n  while true\n  do\n      if ! kill -0 \"${pid}\" >/dev/null 2>&1; then\n          echo \"❌ FAIL ${test}. The OpenTelemetry Collector isn't running. Startup log:\"\n          cat \"${out}/otelcol.log\"\n          failed=true\n          break\n      fi\n\n      if cat \"${out}/otelcol.log\" | grep \"Everything is ready.\"; then\n        echo \"✅ PASS init\"\n\n        kill \"${pid}\"\n        ret=$?\n        if [ $ret -ne 0 ]; then\n            echo \"Failed to stop the running instance for test ${test}. Return code: ${ret} . Skipping tests.\"\n            exit 4\n        fi\n        break\n      fi\n\n      echo \"Server still unavailable for test '${test}'\" >> \"${out}/test.log\"\n\n      ((retries++))\n      if [ \"$retries\" -gt \"$max_retries\" ]; then\n          echo \"❌ FAIL ${test}. Server wasn't up after about 5m.\"\n          failed=true\n\n          kill \"${pid}\"\n          ret=$?\n          if [ $ret -ne 0 ]; then\n              echo \"Failed to stop the running instance for test ${test}. Return code: ${ret} . Skipping tests.\"\n              exit 8\n          fi\n          break\n      fi\n      sleep 0.1s\n  done\n\n  echo \"Stopping server for '${test}' (pid: ${pid})\" >> \"${out}/test.log\"\n}\n\ntests=\"core\"\n\nbase=$(mktemp -d)\necho \"Running the tests in ${base}\"\n\nreplaces=\"$base/replaces\"\n# Get path of all core modules, in sorted order\ncore_mods=$(cd ../.. && find . -type f -name \"go.mod\" -exec dirname {} \\; | sort)\necho \"replaces:\" >> \"$replaces\"\nfor mod_path in $core_mods; do\n    mod=${mod_path#\".\"} # remove initial dot\n    echo \"  - go.opentelemetry.io/collector$mod => \\${WORKSPACE_DIR}$mod\" >> \"$replaces\"\ndone\necho \"Wrote replace statements to $replaces\"\n\nfailed=false\n\nfor test in $tests\ndo\n    test_build_config \"$test\" \"./test/${test}.builder.yaml\"\ndone\n\ntest_init\n\nif [[ \"$failed\" == \"true\" ]]; then\n    exit 1\nfi\n"
  },
  {
    "path": "cmd/githubgen/allowlist.txt",
    "content": ""
  },
  {
    "path": "cmd/mdatagen/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "cmd/mdatagen/README.md",
    "content": "# Metadata Generator\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [alpha]: metrics   |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Acmd%2Fmdatagen%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Acmd%2Fmdatagen) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Acmd%2Fmdatagen%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Acmd%2Fmdatagen) |\n| [Code Owners](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/CONTRIBUTING.md#becoming-a-code-owner)    | [@dmitryax](https://www.github.com/dmitryax) |\n\n[alpha]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#alpha\n<!-- end autogenerated section -->\n\nEvery component's documentation should include a brief description of the component and guidance on how to use it.\nThere is also some information about the component (or metadata) that should be included to help end-users understand the current state of the component and whether it is right for their use case.\nExamples of this metadata about a component are:\n\n- its stability level\n- the distributions containing it\n- the types of pipelines it supports\n- metrics emitted in the case of a scraping receiver, a scraper, or a connector\n\nThe metadata generator defines a schema for specifying this information to ensure it is complete and well-formed.\nThe metadata generator is then able to ingest the metadata, validate it against the schema and produce documentation in a standardized format.\nAn example of how this generated documentation looks can be found in [documentation.md](https://github.com/open-telemetry/opentelemetry-collector/blob/main/cmd/mdatagen/internal/samplereceiver/documentation.md).\n\n## Using the Metadata Generator\n\nIn order for a component to benefit from the metadata generator (`mdatagen`) these requirements need to be met:\n\n1. A yaml file containing the metadata that needs to be included in the component\n2. The component should declare a `go:generate mdatagen` directive which tells `mdatagen` what to generate\n\nAs an example, here is a minimal `metadata.yaml` for the [OTLP receiver](https://github.com/open-telemetry/opentelemetry-collector/tree/main/receiver/otlpreceiver):\n\n```yaml\ntype: otlp\nstatus:\n  class: receiver\n  stability:\n    beta: [logs]\n    stable: [metrics, traces]\n```\n\nDetailed information about the schema of `metadata.yaml` can be found in [metadata-schema.yaml](./metadata-schema.yaml).\n\nThe `go:generate mdatagen` directive is usually defined in a `doc.go` file in the same package as the component, for example:\n\n```go\n//go:generate mdatagen metadata.yaml\n\npackage main\n```\n\nBelow are some more examples that can be used for reference:\n\n- The ElasticSearch receiver has an extensive [metadata.yaml](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/elasticsearchreceiver/metadata.yaml)\n- The host metrics receiver has internal subcomponents, each with their own `metadata.yaml` and `doc.go`. See [cpuscraper](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/hostmetricsreceiver/internal/scraper/cpuscraper) for example.\n\nYou can run `cd cmd/mdatagen && $(GOCMD) install .` to install the `mdatagen` tool in `GOBIN` and then run `mdatagen metadata.yaml` to generate documentation for a specific component or you can run `make generate` to generate documentation for all components.\n\n### Component Config Documentation\n\nThe metadata generator supports automatic generation of configuration schemas for components. \nThis generates JSON Schema files that enable IDE autocompletion, validation, and documentation for component configuration.\nIn the future it will also generate Go config structs and human-readable documentation for configuration options\n\nTo define a configuration schema, add a `config` section to your `metadata.yaml`:\n\n```yaml\ntype: myreceiver\nstatus:\n  class: receiver\n  stability:\n    beta: [metrics, traces]\n\nconfig:\n  type: object\n  properties:\n    endpoint:\n      type: string\n      description: The endpoint to listen on\n      default: \"localhost:4317\"\n    timeout:\n      type: string\n      format: duration\n      description: Request timeout duration\n      default: \"30s\"\n    tls:\n      $ref: go.opentelemetry.io/collector/config/configtls.server_config\n  required: [endpoint]\n```\n\nThe `config` section is based on [JSON Schema standard](https://json-schema.org/) (draft 2020-12) and supports:\n\n- **Standard JSON Schema types**: string, number, integer, boolean, object, array, null\n- **Validation constraints**: minLength, maxLength, pattern, minimum, maximum, enum, etc.\n- **References**: Internal (`$ref: definition_name`), external (`$ref: package.path.type`), or relative (`$ref: ./internal/config.type`)\n- **Reusable definitions**: Define common schemas in `$defs` and reference them with `$ref`\n- **Schema composition**: Use `allOf` for complex configurations\n\n### Metrics Builder Configuration\n\nFor receivers, scrapers, and other components that emit metrics, `mdatagen` can generate metrics builder\nconfiguration from `metadata.yaml`.\n\n```yaml\ntype: myreceiver\nstatus:\n  class: receiver\n  stability:\n    beta: [metrics]\n\nresource_attributes:\n  transport:\n    description: Transport used by the request.\n    type: string\n    enabled: true\n\nattributes:\n  status_code:\n    description: Response status code.\n    type: int\n    requirement_level: opt_in\n\nmetrics:\n  http.server.request.count:\n    enabled: true\n    description: Number of received requests.\n    unit: \"{request}\"\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n    attributes: [status_code]\n```\n\nThis lets users:\n\n- enable or disable individual metrics\n- enable or disable resource attributes\n- use `metrics_include` and `metrics_exclude` on resource attributes to only emit metrics with matching resource attribute values\n\n### Metric Reaggregation Configuration\n\nSet `reaggregation_enabled: true` to let users reduce metric cardinality by dropping selected metric\nattributes and aggregating the resulting datapoints.\n\n```yaml\nreaggregation_enabled: true\n\nattributes:\n  transport:\n    description: Transport used by the request.\n    type: string\n    requirement_level: recommended\n  status_code:\n    description: Response status code.\n    type: int\n    requirement_level: opt_in\n```\n\nThis adds two per-metric settings for metrics that declare attributes:\n\n- `attributes`: the subset of metric attributes to keep in the emitted metric stream\n- `aggregation_strategy`: how collapsed datapoints are merged, using `sum`, `avg`, `min`, or `max`\n\nDefaults:\n\n- sum metrics use `sum`; gauge metrics use `avg`\n- `required` attributes are always kept\n- `recommended` and `conditionally_required` attributes are kept by default, but users can remove them\n- `opt_in` attributes are omitted by default, so that dimension is aggregated unless the user adds it\n\nExample user configuration:\n\n```yaml\nreceivers:\n  myreceiver:\n    metrics:\n      http.server.request.count:\n        enabled: true\n        aggregation_strategy: sum\n        attributes: [transport]\n```\n\nIn this example, datapoints that only differ by `status_code` are aggregated together, while\n`transport` remains part of the output identity.\n\n### Feature Gates Documentation\n\nThe metadata generator supports automatic documentation generation for feature gates used by components. Feature gates are documented by adding a `feature_gates` section to your `metadata.yaml`:\n\n```yaml\ntype: mycomponent\nstatus:\n  class: receiver\n  stability:\n    beta: [metrics, traces]\n\nfeature_gates:\n  - id: mycomponent.newFeature\n    description: 'Enables new feature functionality that improves performance'\n    stage: alpha\n    from_version: 'v0.100.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/issues/12345'\n\n  - id: mycomponent.stableFeature\n    description: 'A feature that has reached stability'\n    stage: stable\n    from_version: 'v0.90.0'\n    to_version: 'v0.95.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/issues/11111'\n```\n\nThis will generate a \"Feature Gates\" section in the component's `documentation.md` file with a table containing:\n\n- **Feature Gate**: The gate identifier\n- **Stage**: The lifecycle stage (alpha, beta, stable, deprecated)\n- **Description**: Brief description of what the gate controls\n- **From Version**: Version when the gate was introduced\n- **To Version**: Version when stable/deprecated gates will be removed (if applicable)\n- **Reference**: Link to additional contextual information\n\nThe feature gate definitions should correspond to actual gates registered in your component code using the [Feature Gates API](../../featuregate/README.md).\n\n### Generate multiple metadata packages\n\nBy default, `mdatagen` will generate a package called `metadata` in the `internal` directory. If you want to generate a package with a different name, you can use the `generated_package_name` configuration field to provide an alternate name.\n\n```yaml\ntype: otlp\ngenerated_package_name: customname\nstatus:\n  class: receiver\n  stability:\n    beta: [logs]\n    stable: [metrics, traces]\n```\n\nThe most common scenario for this would be making major changes to a receiver's metadata without breaking what exists. In this scenario, `mdatagen` could produce separate packages for different metadata specs in the same receiver:\n\n```go\n//go:generate mdatagen metadata.yaml\n//go:generate mdatagen custom.yaml\n\npackage main\n```\n\nWith two different packages generated, the behaviour for which metadata is used can be easily controlled via featuregate or a similar mechanism.\n\n## Contributing to the Metadata Generator\n\nThe code for generating the documentation can be found in [loader.go](./internal/loader.go) and the templates for rendering the documentation can be found in [templates](./internal/templates).\nWhen making updates to the metadata generator or introducing support for new functionality:\n\n1. Ensure the [metadata-schema.yaml](./metadata-schema.yaml) and [metadata.yaml](./metadata.yaml) files reflect the changes.\n2. Run `make mdatagen-test`.\n3. Make sure all tests are passing including [generated tests](./internal/samplereceiver/internal/metadata/generated_metrics_test.go).\n4. Run `make generate`.\n"
  },
  {
    "path": "cmd/mdatagen/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage main\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "cmd/mdatagen/go.mod",
    "content": "module go.opentelemetry.io/collector/cmd/mdatagen\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/google/go-cmp v0.7.0\n\tgithub.com/spf13/cobra v1.10.2\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/config/confighttp v0.148.0\n\tgo.opentelemetry.io/collector/config/configoptional v1.54.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/confmap/provider/fileprovider v1.54.0\n\tgo.opentelemetry.io/collector/connector v0.148.0\n\tgo.opentelemetry.io/collector/connector/connectortest v0.148.0\n\tgo.opentelemetry.io/collector/connector/xconnector v0.148.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/featuregate v1.54.0\n\tgo.opentelemetry.io/collector/filter v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pdata/xpdata v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0\n\tgo.opentelemetry.io/collector/processor v1.54.0\n\tgo.opentelemetry.io/collector/processor/processortest v0.148.0\n\tgo.opentelemetry.io/collector/processor/xprocessor v0.148.0\n\tgo.opentelemetry.io/collector/receiver v1.54.0\n\tgo.opentelemetry.io/collector/receiver/receivertest v0.148.0\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0\n\tgo.opentelemetry.io/collector/scraper v0.148.0\n\tgo.opentelemetry.io/collector/scraper/scraperhelper v0.148.0\n\tgo.opentelemetry.io/collector/scraper/scrapertest v0.148.0\n\tgo.opentelemetry.io/collector/scraper/xscraper v0.148.0\n\tgo.opentelemetry.io/collector/service/hostcapabilities v0.148.0\n\tgo.opentelemetry.io/otel v1.42.0\n\tgo.opentelemetry.io/otel/metric v1.42.0\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0\n\tgo.opentelemetry.io/otel/trace v1.42.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/zap v1.27.1\n\tgo.yaml.in/yaml/v3 v3.0.4\n\tgolang.org/x/text v0.34.0\n\tgolang.org/x/tools v0.42.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect\n\tgithub.com/felixge/httpsnoop v1.0.4 // indirect\n\tgithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f // indirect\n\tgithub.com/fsnotify/fsnotify v1.9.0 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/golang/snappy v1.0.0 // indirect\n\tgithub.com/google/go-tpm v0.9.8 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/inconshreveable/mousetrap v1.1.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/klauspost/compress v1.18.4 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pierrec/lz4/v4 v4.1.26 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect\n\tgithub.com/rs/cors v1.11.1 // indirect\n\tgithub.com/spf13/pflag v1.0.10 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/client v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/component/componentstatus v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/config/configauth v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configcompression v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configmiddleware v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/confignet v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configopaque v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configtls v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionauth v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionmiddleware v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/internal/fanoutconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/receiverhelper v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/service v0.148.0 // indirect\n\tgo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgolang.org/x/crypto v0.48.0 // indirect\n\tgolang.org/x/mod v0.33.0 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sync v0.19.0 // indirect\n\tgolang.org/x/sys v0.42.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/confmap/provider/fileprovider => ../../confmap/provider/fileprovider\n\nreplace go.opentelemetry.io/collector/filter => ../../filter\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/receiver => ../../receiver\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../../receiver/receivertest\n\nretract (\n\tv0.76.2\n\tv0.76.1\n\tv0.65.0\n)\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/processor/xprocessor => ../../processor/xprocessor\n\nreplace go.opentelemetry.io/collector/processor/processortest => ../../processor/processortest\n\nreplace go.opentelemetry.io/collector/component/componentstatus => ../../component/componentstatus\n\nreplace go.opentelemetry.io/collector/processor => ../../processor\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/scraper => ../../scraper\n\nreplace go.opentelemetry.io/collector/scraper/scrapertest => ../../scraper/scrapertest\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/connector => ../../connector\n\nreplace go.opentelemetry.io/collector/connector/connectortest => ../../connector/connectortest\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/internal/fanoutconsumer => ../../internal/fanoutconsumer\n\nreplace go.opentelemetry.io/collector/connector/xconnector => ../../connector/xconnector\n\nreplace go.opentelemetry.io/collector/internal/telemetry => ../../internal/telemetry\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../../extension/extensiontest\n\nreplace go.opentelemetry.io/collector/exporter => ../../exporter\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ../../extension/extensionmiddleware\n\nreplace go.opentelemetry.io/collector/config/configmiddleware => ../../config/configmiddleware\n\nreplace go.opentelemetry.io/collector/exporter/exportertest => ../../exporter/exportertest\n\nreplace go.opentelemetry.io/collector/client => ../../client\n\nreplace go.opentelemetry.io/collector/extension => ../../extension\n\nreplace go.opentelemetry.io/collector/config/configauth => ../../config/configauth\n\nreplace go.opentelemetry.io/collector/otelcol => ../../otelcol\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest => ../../extension/extensionmiddleware/extensionmiddlewaretest\n\nreplace go.opentelemetry.io/collector/extension/xextension => ../../extension/xextension\n\nreplace go.opentelemetry.io/collector/extension/zpagesextension => ../../extension/zpagesextension\n\nreplace go.opentelemetry.io/collector/config/configretry => ../../config/configretry\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../../config/configoptional\n\nreplace go.opentelemetry.io/collector/config/configopaque => ../../config/configopaque\n\nreplace go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest => ../../extension/extensionauth/extensionauthtest\n\nreplace go.opentelemetry.io/collector/service => ../../service\n\nreplace go.opentelemetry.io/collector/extension/extensionauth => ../../extension/extensionauth\n\nreplace go.opentelemetry.io/collector/service/hostcapabilities => ../../service/hostcapabilities\n\nreplace go.opentelemetry.io/collector/config/configtls => ../../config/configtls\n\nreplace go.opentelemetry.io/collector/config/configcompression => ../../config/configcompression\n\nreplace go.opentelemetry.io/collector/exporter/xexporter => ../../exporter/xexporter\n\nreplace go.opentelemetry.io/collector/config/configtelemetry => ../../config/configtelemetry\n\nreplace go.opentelemetry.io/collector/config/confighttp => ../../config/confighttp\n\nreplace go.opentelemetry.io/collector/extension/extensioncapabilities => ../../extension/extensioncapabilities\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper => ../../exporter/exporterhelper\n\nreplace go.opentelemetry.io/collector/service/telemetry/telemetrytest => ../../service/telemetry/telemetrytest\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n\nreplace go.opentelemetry.io/collector/config/confignet => ../../config/confignet\n\nreplace go.opentelemetry.io/collector/receiver/receiverhelper => ../../receiver/receiverhelper\n\nreplace go.opentelemetry.io/collector/scraper/scraperhelper => ../../scraper/scraperhelper\n\nreplace go.opentelemetry.io/collector/scraper/xscraper => ../../scraper/xscraper\n"
  },
  {
    "path": "cmd/mdatagen/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=\ngithub.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f h1:RJ+BDPLSHQO7cSjKBqjPJSbi1qfk9WcsjQDtZiw3dZw=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f/go.mod h1:VHbbch/X4roIY22jL1s3qRbZhCiRIgUAF/PdSUcx2io=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=\ngithub.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=\ngithub.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=\ngithub.com/google/go-tpm-tools v0.4.7 h1:J3ycC8umYxM9A4eF73EofRZu4BxY0jjQnUnkhIBbvws=\ngithub.com/google/go-tpm-tools v0.4.7/go.mod h1:gSyXTZHe3fgbzb6WEGd90QucmsnT1SRdlye82gH8QjQ=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=\ngithub.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=\ngithub.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=\ngithub.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=\ngithub.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=\ngithub.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=\ngithub.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=\ngithub.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=\ngithub.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=\ngithub.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=\ngolang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=\ngolang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=\ngolang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=\ngolang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=\ngolang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=\ngolang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngolang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=\ngolang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=\ngonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=\ngonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "cmd/mdatagen/internal/cfggen/generation.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage cfggen // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/cfggen\"\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"maps\"\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/helpers\"\n)\n\n// NewCfgFns returns template functions for config generation with rootPackage and componentPackage\n// baked into closures. This way the template itself never needs to pass these context values around.\nfunc NewCfgFns(rootPackage, componentPackage string) map[string]any {\n\treturn map[string]any{\n\t\t\"extractImports\": func(cfg *ConfigMetadata) []string {\n\t\t\tif cfg == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\timports, err := ExtractImports(cfg, rootPackage, componentPackage)\n\t\t\tif err != nil {\n\t\t\t\treturn []string{}\n\t\t\t}\n\t\t\treturn imports\n\t\t},\n\t\t\"extractDefs\": func(cfg *ConfigMetadata) map[string]*ConfigMetadata {\n\t\t\tif cfg == nil {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn ExtractDefs(cfg)\n\t\t},\n\t\t\"mapGoType\": func(cfg *ConfigMetadata, propName string) string {\n\t\t\tif cfg == nil {\n\t\t\t\treturn \"any\"\n\t\t\t}\n\t\t\tgoType, err := MapGoType(cfg, propName, rootPackage, componentPackage)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\treturn goType\n\t\t},\n\t\t\"publicType\": func(ref string) string {\n\t\t\ttypeName, err := FormatTypeName(ref, rootPackage, componentPackage)\n\t\t\tif err != nil {\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\treturn typeName\n\t\t},\n\t}\n}\n\n// WithCfgFns merges config generation template functions into the given function map.\n// The rootPackage and componentPackage are captured in closures so the template doesn't need to thread them through.\nfunc WithCfgFns(fns map[string]any, rootPackage, componentPackage string) map[string]any {\n\tcfgFns := NewCfgFns(rootPackage, componentPackage)\n\tmaps.Copy(fns, cfgFns)\n\treturn fns\n}\n\nvar goBasicTypes = []string{\n\t\"rune\", \"byte\",\n\t\"uint\", \"int8\", \"uint8\", \"int16\", \"uint16\", \"int32\", \"uint32\", \"int64\", \"uint64\",\n\t\"float32\", \"float64\",\n}\n\n// MapGoType maps a ConfigMetadata to its corresponding Go type as a string.\nfunc MapGoType(md *ConfigMetadata, propName, rootPackage, componentPackage string) (string, error) {\n\tif md == nil {\n\t\treturn \"\", errors.New(\"nil ConfigMetadata\")\n\t}\n\tgoType, err := resolveGoType(md, propName, rootPackage, componentPackage)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to resolve Go type for property %q: %w\", propName, err)\n\t}\n\tif md.IsPointer {\n\t\tgoType = \"*\" + goType\n\t}\n\tif md.IsOptional {\n\t\treturn \"configoptional.Optional[\" + goType + \"]\", nil\n\t}\n\treturn goType, nil\n}\n\nfunc resolveGoType(md *ConfigMetadata, propName, rootPackage, componentPackage string) (string, error) {\n\tif md.GoType != \"\" {\n\t\tif slices.Contains(goBasicTypes, md.GoType) {\n\t\t\treturn md.GoType, nil\n\t\t}\n\t\ttypeName, err := FormatTypeName(md.GoType, rootPackage, componentPackage)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to format custom type %q: %w\", md.GoType, err)\n\t\t}\n\t\treturn typeName, nil\n\t}\n\tif md.Ref != \"\" {\n\t\ttypeName, err := FormatTypeName(md.Ref, rootPackage, componentPackage)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to format reference type %q: %w\", md.Ref, err)\n\t\t}\n\t\treturn typeName, nil\n\t}\n\n\tswitch md.Type {\n\tcase \"string\":\n\t\tswitch md.Format {\n\t\tcase \"date-time\":\n\t\t\treturn \"time.Time\", nil\n\t\tcase \"duration\":\n\t\t\treturn \"time.Duration\", nil\n\t\tdefault:\n\t\t\treturn \"string\", nil\n\t\t}\n\tcase \"integer\":\n\t\treturn \"int\", nil\n\tcase \"number\":\n\t\treturn \"float64\", nil\n\tcase \"boolean\":\n\t\treturn \"bool\", nil\n\tcase \"array\":\n\t\tif md.Items == nil {\n\t\t\treturn \"[]any\", nil\n\t\t}\n\t\titemType, err := MapGoType(md.Items, propName+\"_item\", rootPackage, componentPackage)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to map array item type: %w\", err)\n\t\t}\n\t\treturn \"[]\" + itemType, nil\n\tcase \"object\":\n\t\tif md.AdditionalProperties != nil {\n\t\t\tvalueType, err := MapGoType(md.AdditionalProperties, propName, rootPackage, componentPackage)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"failed to map additionalProperties type: %w\", err)\n\t\t\t}\n\t\t\treturn \"map[string]\" + valueType, nil\n\t\t}\n\t\tif md.Properties != nil {\n\t\t\tformatted, err := helpers.FormatIdentifier(propName, true)\n\t\t\tif err != nil {\n\t\t\t\treturn \"\", fmt.Errorf(\"failed to format embedded object type name %q: %w\", propName, err)\n\t\t\t}\n\t\t\treturn formatted, nil\n\t\t}\n\t\treturn \"map[string]any\", nil\n\tcase \"\":\n\t\treturn \"any\", nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"unsupported type: %q\", md.Type)\n\t}\n}\n\n// ExtractImports recursively scans the ConfigMetadata and collects all unique import paths needed for the generated Go code.\nfunc ExtractImports(md *ConfigMetadata, rootPackage, componentPackage string) ([]string, error) {\n\tif md == nil {\n\t\treturn nil, nil\n\t}\n\n\timports := make(map[string]bool)\n\tif err := collectImports(md, imports, rootPackage, componentPackage); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn slices.Collect(maps.Keys(imports)), nil\n}\n\nfunc collectImports(md *ConfigMetadata, imports map[string]bool, rootPackage, componentPackage string) error {\n\tif md == nil {\n\t\treturn nil\n\t}\n\n\tif md.GoType != \"\" {\n\t\tref, err := ResolveGoTypeRef(md.GoType, rootPackage, componentPackage)\n\t\tif err == nil && ref.ImportPath != \"\" {\n\t\t\timports[ref.ImportPath] = true\n\t\t}\n\t}\n\n\tif md.Ref != \"\" {\n\t\tref, err := ResolveGoTypeRef(md.Ref, rootPackage, componentPackage)\n\t\tif err == nil && ref.ImportPath != \"\" {\n\t\t\timports[ref.ImportPath] = true\n\t\t}\n\t}\n\n\tif md.Type == \"string\" && (md.Format == \"date-time\" || md.Format == \"duration\") {\n\t\timports[\"time\"] = true\n\t}\n\n\tif md.IsOptional {\n\t\timports[\"go.opentelemetry.io/collector/config/configoptional\"] = true\n\t}\n\n\tfor _, prop := range md.Properties {\n\t\tif err := collectImports(prop, imports, rootPackage, componentPackage); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif md.Items != nil {\n\t\tif err := collectImports(md.Items, imports, rootPackage, componentPackage); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, schema := range md.AllOf {\n\t\tif err := collectImports(schema, imports, rootPackage, componentPackage); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tfor _, def := range md.Defs {\n\t\tif err := collectImports(def, imports, rootPackage, componentPackage); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := collectImports(md.AdditionalProperties, imports, rootPackage, componentPackage); err != nil {\n\t\treturn err\n\t}\n\n\tif md.ContentSchema != nil {\n\t\tif err := collectImports(md.ContentSchema, imports, rootPackage, componentPackage); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// FormatTypeName resolves a reference string to a Go type expression using GoTypeRef.\nfunc FormatTypeName(ref, rootPackage, componentPackage string) (string, error) {\n\ttr, err := ResolveGoTypeRef(ref, rootPackage, componentPackage)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\treturn tr.String(), nil\n}\n\n// ExtractDefs recursively collects all definitions from the ConfigMetadata, including nested ones,\n// and returns a flat map of definition names to their corresponding ConfigMetadata.\nfunc ExtractDefs(md *ConfigMetadata) map[string]*ConfigMetadata {\n\tdefs := make(map[string]*ConfigMetadata)\n\tcollectDefs(md, defs)\n\treturn defs\n}\n\nfunc collectDefs(md *ConfigMetadata, defs map[string]*ConfigMetadata) {\n\tif md == nil {\n\t\treturn\n\t}\n\n\tfor name, def := range md.Defs {\n\t\tdefs[name] = def\n\t\tcollectDefs(def, defs)\n\t}\n\n\tfor propName, prop := range md.Properties {\n\t\t// if is embedded object\n\t\tif prop.Type == \"object\" {\n\t\t\tif len(prop.Properties) > 0 {\n\t\t\t\tdefs[propName] = prop\n\t\t\t\tcollectDefs(prop, defs)\n\t\t\t}\n\t\t\tap := md.AdditionalProperties\n\t\t\tif ap != nil && ap.Type == \"object\" && len(ap.Properties) > 0 {\n\t\t\t\tdefs[propName] = ap\n\t\t\t\tcollectDefs(ap, defs)\n\t\t\t}\n\t\t}\n\t\tif prop.Type == \"array\" {\n\t\t\tif prop.Items != nil && prop.Items.Type == \"object\" && len(prop.Items.Properties) > 0 {\n\t\t\t\tdefName := propName + \"_item\"\n\t\t\t\tdefs[defName] = prop.Items\n\t\t\t\tcollectDefs(prop.Items, defs)\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/cfggen/generation_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage cfggen\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestMapGoType_BasicTypes(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tmetadata *ConfigMetadata\n\t\tpropName string\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"string type\",\n\t\t\tmetadata: &ConfigMetadata{Type: \"string\"},\n\t\t\tpropName: \"field\",\n\t\t\texpected: \"string\",\n\t\t},\n\t\t{\n\t\t\tname:     \"integer type\",\n\t\t\tmetadata: &ConfigMetadata{Type: \"integer\"},\n\t\t\tpropName: \"field\",\n\t\t\texpected: \"int\",\n\t\t},\n\t\t{\n\t\t\tname:     \"number type\",\n\t\t\tmetadata: &ConfigMetadata{Type: \"number\"},\n\t\t\tpropName: \"field\",\n\t\t\texpected: \"float64\",\n\t\t},\n\t\t{\n\t\t\tname:     \"boolean type\",\n\t\t\tmetadata: &ConfigMetadata{Type: \"boolean\"},\n\t\t\tpropName: \"field\",\n\t\t\texpected: \"bool\",\n\t\t},\n\t\t{\n\t\t\tname:     \"empty type defaults to any\",\n\t\t\tmetadata: &ConfigMetadata{Type: \"\"},\n\t\t\tpropName: \"field\",\n\t\t\texpected: \"any\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult, err := MapGoType(tt.metadata, tt.propName, \"\", \"\")\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestMapGoType_FormattedStrings(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tformat   string\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"date-time format\",\n\t\t\tformat:   \"date-time\",\n\t\t\texpected: \"time.Time\",\n\t\t},\n\t\t{\n\t\t\tname:     \"duration format\",\n\t\t\tformat:   \"duration\",\n\t\t\texpected: \"time.Duration\",\n\t\t},\n\t\t{\n\t\t\tname:     \"no format\",\n\t\t\tformat:   \"\",\n\t\t\texpected: \"string\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tmd := &ConfigMetadata{\n\t\t\t\tType:   \"string\",\n\t\t\t\tFormat: tt.format,\n\t\t\t}\n\t\t\tresult, err := MapGoType(md, \"field\", \"\", \"\")\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestMapGoType_Arrays(t *testing.T) {\n\tcompPkg := \"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplescraper\"\n\n\ttests := []struct {\n\t\tname     string\n\t\tmetadata *ConfigMetadata\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname: \"array with string items\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType:  \"array\",\n\t\t\t\tItems: &ConfigMetadata{Type: \"string\"},\n\t\t\t},\n\t\t\texpected: \"[]string\",\n\t\t},\n\t\t{\n\t\t\tname: \"array with int items\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType:  \"array\",\n\t\t\t\tItems: &ConfigMetadata{Type: \"integer\"},\n\t\t\t},\n\t\t\texpected: \"[]int\",\n\t\t},\n\t\t{\n\t\t\tname: \"array with ref items\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType:  \"array\",\n\t\t\t\tItems: &ConfigMetadata{Ref: \"./internal/metadata.custom_type\"},\n\t\t\t},\n\t\t\texpected: \"[]metadata.CustomType\",\n\t\t},\n\t\t{\n\t\t\tname: \"array with nested object items \",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType: \"array\",\n\t\t\t\tItems: &ConfigMetadata{\n\t\t\t\t\tType: \"object\",\n\t\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\t\"name\": {Type: \"string\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"[]FieldItem\",\n\t\t},\n\t\t{\n\t\t\tname: \"array without items defaults to any\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType:  \"array\",\n\t\t\t\tItems: nil,\n\t\t\t},\n\t\t\texpected: \"[]any\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult, err := MapGoType(tt.metadata, \"field\", \"\", compPkg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestMapGoType_Objects(t *testing.T) {\n\tcompPkg := \"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplescraper\"\n\n\ttests := []struct {\n\t\tname     string\n\t\tmetadata *ConfigMetadata\n\t\tpropName string\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname: \"object with additionalProperties string\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType:                 \"object\",\n\t\t\t\tAdditionalProperties: &ConfigMetadata{Type: \"string\"},\n\t\t\t},\n\t\t\tpropName: \"field\",\n\t\t\texpected: \"map[string]string\",\n\t\t},\n\t\t{\n\t\t\tname: \"object with additionalProperties int\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType:                 \"object\",\n\t\t\t\tAdditionalProperties: &ConfigMetadata{Type: \"integer\"},\n\t\t\t},\n\t\t\tpropName: \"field\",\n\t\t\texpected: \"map[string]int\",\n\t\t},\n\t\t{\n\t\t\tname: \"object with additionalProperties ref\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType:                 \"object\",\n\t\t\t\tAdditionalProperties: &ConfigMetadata{Ref: \"./internal/metadata.custom_type\"},\n\t\t\t},\n\t\t\tpropName: \"field\",\n\t\t\texpected: \"map[string]metadata.CustomType\",\n\t\t},\n\t\t{\n\t\t\tname: \"object without additionalProperties or properties\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType: \"object\",\n\t\t\t},\n\t\t\tpropName: \"field\",\n\t\t\texpected: \"map[string]any\",\n\t\t},\n\t\t{\n\t\t\tname: \"object with properties\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"name\": {Type: \"string\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\tpropName: \"my_config\",\n\t\t\texpected: \"MyConfig\",\n\t\t},\n\t\t{\n\t\t\tname: \"map of arrays of objects\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType: \"object\",\n\t\t\t\tAdditionalProperties: &ConfigMetadata{\n\t\t\t\t\tType: \"array\",\n\t\t\t\t\tItems: &ConfigMetadata{\n\t\t\t\t\t\tType: \"object\",\n\t\t\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\t\t\"id\": {Type: \"integer\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tpropName: \"field\",\n\t\t\texpected: \"map[string][]FieldItem\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult, err := MapGoType(tt.metadata, tt.propName, \"\", compPkg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestMapGoType_CustomTypes(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tmetadata *ConfigMetadata\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname: \"custom type with basic type\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType:   \"string\",\n\t\t\t\tGoType: \"rune\",\n\t\t\t},\n\t\t\texpected: \"rune\",\n\t\t},\n\t\t{\n\t\t\tname: \"custom type with external package\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType:   \"object\",\n\t\t\t\tGoType: \"github.com/example/pkg.CustomType\",\n\t\t\t},\n\t\t\texpected: \"pkg.CustomType\",\n\t\t},\n\t\t{\n\t\t\tname: \"custom type without package\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType:   \"object\",\n\t\t\t\tGoType: \"my_custom_type\",\n\t\t\t},\n\t\t\texpected: \"MyCustomType\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult, err := MapGoType(tt.metadata, \"field\", \"\", \"\")\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestMapGoType_References(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tref      string\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"internal reference\",\n\t\t\tref:      \"my_type\",\n\t\t\texpected: \"MyType\",\n\t\t},\n\t\t{\n\t\t\tname:     \"external reference\",\n\t\t\tref:      \"go.opentelemetry.io/collector/component.Config\",\n\t\t\texpected: \"component.Config\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tmd := &ConfigMetadata{\n\t\t\t\tRef: tt.ref,\n\t\t\t}\n\t\t\tresult, err := MapGoType(md, \"field\", \"\", \"\")\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestMapGoType_Modifiers(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tmetadata *ConfigMetadata\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname: \"optional type\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType:       \"string\",\n\t\t\t\tIsOptional: true,\n\t\t\t},\n\t\t\texpected: \"configoptional.Optional[string]\",\n\t\t},\n\t\t{\n\t\t\tname: \"pointer type\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType:      \"string\",\n\t\t\t\tIsPointer: true,\n\t\t\t},\n\t\t\texpected: \"*string\",\n\t\t},\n\t\t{\n\t\t\tname: \"optional pointer\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType:       \"string\",\n\t\t\t\tIsOptional: true,\n\t\t\t\tIsPointer:  true,\n\t\t\t},\n\t\t\texpected: \"configoptional.Optional[*string]\",\n\t\t},\n\t\t{\n\t\t\tname: \"array of pointers\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType: \"array\",\n\t\t\t\tItems: &ConfigMetadata{\n\t\t\t\t\tType:      \"string\",\n\t\t\t\t\tIsPointer: true,\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"[]*string\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult, err := MapGoType(tt.metadata, \"field\", \"\", \"\")\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestMapGoType_NilInput(t *testing.T) {\n\t_, err := MapGoType(nil, \"field\", \"\", \"\")\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"nil ConfigMetadata\")\n}\n\nfunc TestMapGoType_UnsupportedType(t *testing.T) {\n\tmd := &ConfigMetadata{\n\t\tType: \"unsupported_type\",\n\t}\n\t_, err := MapGoType(md, \"field\", \"\", \"\")\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"unsupported type\")\n}\n\nfunc TestExtractImports_BasicTypes(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tmetadata *ConfigMetadata\n\t\texpected []string\n\t}{\n\t\t{\n\t\t\tname:     \"no imports for basic types\",\n\t\t\tmetadata: &ConfigMetadata{Type: \"string\"},\n\t\t\texpected: []string{},\n\t\t},\n\t\t{\n\t\t\tname: \"time import for date-time format\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType:   \"string\",\n\t\t\t\tFormat: \"date-time\",\n\t\t\t},\n\t\t\texpected: []string{\"time\"},\n\t\t},\n\t\t{\n\t\t\tname: \"time import for duration format\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType:   \"string\",\n\t\t\t\tFormat: \"duration\",\n\t\t\t},\n\t\t\texpected: []string{\"time\"},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult, err := ExtractImports(tt.metadata, \"\", \"\")\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.ElementsMatch(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestExtractImports_CustomTypes(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tmetadata *ConfigMetadata\n\t\texpected []string\n\t}{\n\t\t{\n\t\t\tname: \"external custom type\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tType:   \"object\",\n\t\t\t\tGoType: \"github.com/example/pkg.CustomType\",\n\t\t\t},\n\t\t\texpected: []string{\"github.com/example/pkg\"},\n\t\t},\n\t\t{\n\t\t\tname: \"external reference\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tRef: \"go.opentelemetry.io/collector/component.Config\",\n\t\t\t},\n\t\t\texpected: []string{\"go.opentelemetry.io/collector/component\"},\n\t\t},\n\t\t{\n\t\t\tname: \"no import for internal reference\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tRef: \"my_type\",\n\t\t\t},\n\t\t\texpected: []string{},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult, err := ExtractImports(tt.metadata, \"\", \"\")\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.ElementsMatch(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestExtractImports_LocalRef(t *testing.T) {\n\trootPkg := \"go.opentelemetry.io/collector\"\n\tcompPkg := \"go.opentelemetry.io/collector/scraper/scraperhelper\"\n\n\ttests := []struct {\n\t\tname     string\n\t\tmetadata *ConfigMetadata\n\t\texpected []string\n\t}{\n\t\t{\n\t\t\tname: \"local absolute reference\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tRef: \"/config/confighttp.client_config\",\n\t\t\t},\n\t\t\texpected: []string{\"go.opentelemetry.io/collector/config/confighttp\"},\n\t\t},\n\t\t{\n\t\t\tname: \"local relative reference\",\n\t\t\tmetadata: &ConfigMetadata{\n\t\t\t\tRef: \"./internal/metadata.custom_type\",\n\t\t\t},\n\t\t\texpected: []string{\"go.opentelemetry.io/collector/scraper/scraperhelper/internal/metadata\"},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult, err := ExtractImports(tt.metadata, rootPkg, compPkg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.ElementsMatch(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestExtractImports_Optional(t *testing.T) {\n\tmd := &ConfigMetadata{\n\t\tType:       \"string\",\n\t\tIsOptional: true,\n\t}\n\tresult, err := ExtractImports(md, \"\", \"\")\n\trequire.NoError(t, err)\n\trequire.Contains(t, result, \"go.opentelemetry.io/collector/config/configoptional\")\n}\n\nfunc TestExtractImports_Nested(t *testing.T) {\n\tmd := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"timeout\": {\n\t\t\t\tType:   \"string\",\n\t\t\t\tFormat: \"duration\",\n\t\t\t},\n\t\t\t\"nested\": {\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"timestamp\": {\n\t\t\t\t\t\tType:   \"string\",\n\t\t\t\t\t\tFormat: \"date-time\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tresult, err := ExtractImports(md, \"\", \"\")\n\trequire.NoError(t, err)\n\trequire.Contains(t, result, \"time\")\n}\n\nfunc TestExtractImports_AllOf(t *testing.T) {\n\tmd := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tAllOf: []*ConfigMetadata{\n\t\t\t{\n\t\t\t\tType:   \"string\",\n\t\t\t\tFormat: \"duration\",\n\t\t\t},\n\t\t},\n\t}\n\tresult, err := ExtractImports(md, \"\", \"\")\n\trequire.NoError(t, err)\n\trequire.Contains(t, result, \"time\")\n}\n\nfunc TestExtractImports_ArrayItems(t *testing.T) {\n\tmd := &ConfigMetadata{\n\t\tType: \"array\",\n\t\tItems: &ConfigMetadata{\n\t\t\tType:   \"string\",\n\t\t\tFormat: \"date-time\",\n\t\t},\n\t}\n\tresult, err := ExtractImports(md, \"\", \"\")\n\trequire.NoError(t, err)\n\trequire.Contains(t, result, \"time\")\n}\n\nfunc TestExtractImports_AdditionalProperties(t *testing.T) {\n\tmd := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tAdditionalProperties: &ConfigMetadata{\n\t\t\tType:   \"string\",\n\t\t\tFormat: \"duration\",\n\t\t},\n\t}\n\tresult, err := ExtractImports(md, \"\", \"\")\n\trequire.NoError(t, err)\n\trequire.Contains(t, result, \"time\")\n}\n\nfunc TestExtractImports_Defs(t *testing.T) {\n\tmd := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"CustomType\": {\n\t\t\t\tType:   \"string\",\n\t\t\t\tFormat: \"date-time\",\n\t\t\t},\n\t\t},\n\t}\n\tresult, err := ExtractImports(md, \"\", \"\")\n\trequire.NoError(t, err)\n\trequire.Contains(t, result, \"time\")\n}\n\nfunc TestExtractImports_NilInput(t *testing.T) {\n\tresult, err := ExtractImports(nil, \"\", \"\")\n\trequire.NoError(t, err)\n\trequire.Nil(t, result)\n}\n\nfunc TestFormatTypeName_InternalReferences(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tref      string\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"simple name\",\n\t\t\tref:      \"my_type\",\n\t\t\texpected: \"MyType\",\n\t\t},\n\t\t{\n\t\t\tname:     \"snake case\",\n\t\t\tref:      \"my_custom_type\",\n\t\t\texpected: \"MyCustomType\",\n\t\t},\n\t\t{\n\t\t\tname:     \"already formatted\",\n\t\t\tref:      \"MyType\",\n\t\t\texpected: \"MyType\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult, err := FormatTypeName(tt.ref, \"\", \"\")\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestFormatTypeName_ExternalReferences(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tref      string\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"full package path\",\n\t\t\tref:      \"go.opentelemetry.io/collector/component.Config\",\n\t\t\texpected: \"component.Config\",\n\t\t},\n\t\t{\n\t\t\tname:     \"nested package\",\n\t\t\tref:      \"github.com/example/pkg/subpkg.Type\",\n\t\t\texpected: \"subpkg.Type\",\n\t\t},\n\t\t{\n\t\t\tname:     \"type name needs formatting\",\n\t\t\tref:      \"github.com/example/pkg.my_type\",\n\t\t\texpected: \"pkg.MyType\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult, err := FormatTypeName(tt.ref, \"\", \"\")\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestFormatTypeName_LocalReferences(t *testing.T) {\n\trootPkg := \"go.opentelemetry.io/collector\"\n\tcompPkg := \"go.opentelemetry.io/collector/scraper/scraperhelper\"\n\n\ttests := []struct {\n\t\tname     string\n\t\tref      string\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"local absolute\",\n\t\t\tref:      \"/config/confighttp.client_config\",\n\t\t\texpected: \"confighttp.ClientConfig\",\n\t\t},\n\t\t{\n\t\t\tname:     \"local relative\",\n\t\t\tref:      \"./internal/metadata.metrics_builder\",\n\t\t\texpected: \"metadata.MetricsBuilder\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult, err := FormatTypeName(tt.ref, rootPkg, compPkg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestFormatTypeName_InvalidInput(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tref  string\n\t}{\n\t\t{\n\t\t\tname: \"empty type name after dot\",\n\t\t\tref:  \"github.com/example/pkg.\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t_, err := FormatTypeName(tt.ref, \"\", \"\")\n\t\t\trequire.Error(t, err)\n\t\t})\n\t}\n}\n\nfunc TestExtractDefs_Basic(t *testing.T) {\n\tmd := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"CustomType\": {\n\t\t\t\tType: \"string\",\n\t\t\t},\n\t\t\t\"AnotherType\": {\n\t\t\t\tType: \"integer\",\n\t\t\t},\n\t\t},\n\t}\n\n\tresult := ExtractDefs(md)\n\trequire.Len(t, result, 2)\n\trequire.Contains(t, result, \"CustomType\")\n\trequire.Contains(t, result, \"AnotherType\")\n}\n\nfunc TestExtractDefs_NestedDefs(t *testing.T) {\n\tmd := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"OuterType\": {\n\t\t\t\tType: \"object\",\n\t\t\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\t\t\"InnerType\": {\n\t\t\t\t\t\tType: \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tresult := ExtractDefs(md)\n\trequire.Len(t, result, 2)\n\trequire.Contains(t, result, \"OuterType\")\n\trequire.Contains(t, result, \"InnerType\")\n}\n\nfunc TestExtractDefs_EmbeddedObjects(t *testing.T) {\n\tmd := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"config\": {\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"name\": {Type: \"string\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tresult := ExtractDefs(md)\n\trequire.Len(t, result, 1)\n\trequire.Contains(t, result, \"config\")\n\trequire.Equal(t, \"object\", result[\"config\"].Type)\n}\n\nfunc TestExtractDefs_ArrayItems(t *testing.T) {\n\tmd := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"servers\": {\n\t\t\t\tType: \"array\",\n\t\t\t\tItems: &ConfigMetadata{\n\t\t\t\t\tType: \"object\",\n\t\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\t\"host\": {Type: \"string\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tresult := ExtractDefs(md)\n\trequire.Len(t, result, 1)\n\trequire.Contains(t, result, \"servers_item\")\n\trequire.Equal(t, \"object\", result[\"servers_item\"].Type)\n}\n\nfunc TestExtractDefs_NilInput(t *testing.T) {\n\tresult := ExtractDefs(nil)\n\trequire.Empty(t, result)\n}\n\nfunc TestExtractDefs_EmptyInput(t *testing.T) {\n\tmd := &ConfigMetadata{\n\t\tType: \"object\",\n\t}\n\tresult := ExtractDefs(md)\n\trequire.Empty(t, result)\n}\n\nfunc TestExtractDefs_AdditionalPropertiesObject(t *testing.T) {\n\tmd := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t// A property of type \"object\" with no sub-properties triggers the ap check\n\t\t\t\"extra\": {Type: \"object\"},\n\t\t},\n\t\tAdditionalProperties: &ConfigMetadata{\n\t\t\tType: \"object\",\n\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\"value\": {Type: \"integer\"},\n\t\t\t},\n\t\t},\n\t}\n\tresult := ExtractDefs(md)\n\trequire.Contains(t, result, \"extra\")\n}\n\nfunc TestNewCfgFns_ExtractImports(t *testing.T) {\n\tfns := NewCfgFns(\"go.opentelemetry.io/collector\", \"go.opentelemetry.io/collector/comp\")\n\n\textractImports := fns[\"extractImports\"].(func(*ConfigMetadata) []string)\n\n\t// nil input returns nil\n\trequire.Nil(t, extractImports(nil))\n\n\t// valid input returns imports\n\tmd := &ConfigMetadata{Type: \"string\", Format: \"duration\"}\n\tresult := extractImports(md)\n\trequire.Contains(t, result, \"time\")\n\n\t// input with unresolvable GoType: collectImports swallows the error, returns empty slice\n\terrMd := &ConfigMetadata{GoType: \"github.com/pkg.\"}\n\tresult = extractImports(errMd)\n\trequire.Empty(t, result)\n}\n\nfunc TestNewCfgFns_ExtractDefs(t *testing.T) {\n\tfns := NewCfgFns(\"\", \"\")\n\n\textractDefs := fns[\"extractDefs\"].(func(*ConfigMetadata) map[string]*ConfigMetadata)\n\n\t// nil input returns nil\n\trequire.Nil(t, extractDefs(nil))\n\n\t// valid input\n\tmd := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\"MyType\": {Type: \"string\"}},\n\t}\n\tresult := extractDefs(md)\n\trequire.Contains(t, result, \"MyType\")\n}\n\nfunc TestNewCfgFns_MapGoType(t *testing.T) {\n\tfns := NewCfgFns(\"\", \"\")\n\n\tmapGoType := fns[\"mapGoType\"].(func(*ConfigMetadata, string) string)\n\n\t// nil input returns \"any\"\n\trequire.Equal(t, \"any\", mapGoType(nil, \"field\"))\n\n\t// valid input\n\trequire.Equal(t, \"string\", mapGoType(&ConfigMetadata{Type: \"string\"}, \"field\"))\n}\n\nfunc TestNewCfgFns_PublicType(t *testing.T) {\n\tfns := NewCfgFns(\"\", \"\")\n\n\tpublicType := fns[\"publicType\"].(func(string) string)\n\n\trequire.Equal(t, \"MyType\", publicType(\"my_type\"))\n\trequire.Equal(t, \"component.Config\", publicType(\"go.opentelemetry.io/collector/component.Config\"))\n}\n\nfunc TestWithCfgFns(t *testing.T) {\n\tbase := map[string]any{\"existing\": \"value\"}\n\tresult := WithCfgFns(base, \"\", \"\")\n\n\trequire.Equal(t, \"value\", result[\"existing\"])\n\trequire.Contains(t, result, \"mapGoType\")\n\trequire.Contains(t, result, \"extractImports\")\n\trequire.Contains(t, result, \"extractDefs\")\n\trequire.Contains(t, result, \"publicType\")\n}\n\nfunc TestResolveGoType_CustomTypeFormatError(t *testing.T) {\n\t// GoType with invalid empty type name after dot triggers FormatTypeName error\n\tmd := &ConfigMetadata{GoType: \"github.com/pkg.\"}\n\t_, err := MapGoType(md, \"field\", \"\", \"\")\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"failed to format custom type\")\n}\n\nfunc TestResolveGoType_RefFormatError(t *testing.T) {\n\t// Ref with invalid empty type name after dot triggers FormatTypeName error\n\tmd := &ConfigMetadata{Ref: \"github.com/pkg.\"}\n\t_, err := MapGoType(md, \"field\", \"\", \"\")\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"failed to format reference type\")\n}\n\nfunc TestResolveGoType_ArrayItemError(t *testing.T) {\n\t// Array whose item type fails to resolve\n\tmd := &ConfigMetadata{\n\t\tType:  \"array\",\n\t\tItems: &ConfigMetadata{Type: \"unsupported_array_item\"},\n\t}\n\t_, err := MapGoType(md, \"field\", \"\", \"\")\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"failed to map array item type\")\n}\n\nfunc TestResolveGoType_AdditionalPropertiesError(t *testing.T) {\n\t// Object with additionalProperties whose type fails to resolve\n\tmd := &ConfigMetadata{\n\t\tType:                 \"object\",\n\t\tAdditionalProperties: &ConfigMetadata{Type: \"unsupported_value\"},\n\t}\n\t_, err := MapGoType(md, \"field\", \"\", \"\")\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"failed to map additionalProperties type\")\n}\n\nfunc TestResolveGoType_EmbeddedObjectNameError(t *testing.T) {\n\t// Object with properties but propName that cannot be formatted as an identifier\n\tmd := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"x\": {Type: \"string\"},\n\t\t},\n\t}\n\t_, err := MapGoType(md, \"\", \"\", \"\")\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"failed to format embedded object type name\")\n}\n\nfunc TestExtractImports_PropError(t *testing.T) {\n\t// A property with an invalid GoType propagates the error through collectImports\n\tmd := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"bad\": {GoType: \"github.com/pkg.\", Type: \"object\"},\n\t\t},\n\t}\n\t// collectImports swallows ResolveGoTypeRef errors (err == nil check), so no error expected;\n\t// this exercises the properties loop path\n\t_, err := ExtractImports(md, \"\", \"\")\n\trequire.NoError(t, err)\n}\n\nfunc TestExtractImports_ItemsPath(t *testing.T) {\n\tmd := &ConfigMetadata{\n\t\tType: \"array\",\n\t\tItems: &ConfigMetadata{\n\t\t\tType:       \"string\",\n\t\t\tIsOptional: true,\n\t\t},\n\t}\n\tresult, err := ExtractImports(md, \"\", \"\")\n\trequire.NoError(t, err)\n\trequire.Contains(t, result, \"go.opentelemetry.io/collector/config/configoptional\")\n}\n\nfunc TestExtractImports_DefsPath(t *testing.T) {\n\tmd := &ConfigMetadata{\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"T\": {\n\t\t\t\tType:       \"string\",\n\t\t\t\tIsOptional: true,\n\t\t\t},\n\t\t},\n\t}\n\tresult, err := ExtractImports(md, \"\", \"\")\n\trequire.NoError(t, err)\n\trequire.Contains(t, result, \"go.opentelemetry.io/collector/config/configoptional\")\n}\n\nfunc TestExtractImports_ContentSchema(t *testing.T) {\n\tmd := &ConfigMetadata{\n\t\tContentSchema: &ConfigMetadata{\n\t\t\tType:   \"string\",\n\t\t\tFormat: \"duration\",\n\t\t},\n\t}\n\tresult, err := ExtractImports(md, \"\", \"\")\n\trequire.NoError(t, err)\n\trequire.Contains(t, result, \"time\")\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/cfggen/loader.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage cfggen // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/cfggen\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"time\"\n\n\t\"go.yaml.in/yaml/v3\"\n\t\"golang.org/x/tools/go/packages\"\n)\n\nconst (\n\tschemaFileName = \"config.schema.yaml\"\n)\n\n// ErrNotFound indicates a schema was not found by any source.\nvar ErrNotFound = errors.New(\"schema not found\")\n\n// Loader loads configuration metadata from various sources (file, HTTP).\ntype Loader interface {\n\tLoad(ref Ref) (*ConfigMetadata, error)\n}\n\ntype schemaLoader struct {\n\tcache      map[string]*ConfigMetadata\n\tcd         string\n\trootDir    string\n\thttpClient *http.Client\n}\n\n// NewLoader creates a fully configured loader. Takes current component's directory to determine where to look for local schema files.\nfunc NewLoader(cwd string) Loader {\n\treturn &schemaLoader{\n\t\tcache:      make(map[string]*ConfigMetadata),\n\t\tcd:         cwd,\n\t\thttpClient: &http.Client{Timeout: 30 * time.Second},\n\t}\n}\n\nfunc (sl *schemaLoader) Load(ref Ref) (*ConfigMetadata, error) {\n\tif cached, ok := sl.cache[ref.CacheKey()]; ok {\n\t\treturn cached, nil\n\t}\n\n\tmetadata, err := sl.load(ref)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tsl.cache[ref.CacheKey()] = metadata\n\treturn metadata, nil\n}\n\nfunc (sl *schemaLoader) load(ref Ref) (*ConfigMetadata, error) {\n\trepoRoot, err := sl.repoRoot(sl.cd)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to determine repo root: %w\", err)\n\t}\n\n\tif ref.isLocal() {\n\t\tvar filePath string\n\t\tif strings.HasPrefix(ref.schemaID, \"/\") {\n\t\t\tfilePath = filepath.Join(repoRoot, ref.SchemaID(), schemaFileName)\n\t\t} else {\n\t\t\tfilePath = filepath.Join(sl.cd, ref.SchemaID(), schemaFileName)\n\t\t}\n\t\treturn sl.loadFromFile(filePath)\n\t}\n\n\treturn sl.loadFromHTTP(ref, filepath.Join(repoRoot, \".schemas\"))\n}\n\nfunc (sl *schemaLoader) loadFromFile(filePath string) (*ConfigMetadata, error) {\n\tbody, err := os.ReadFile(filePath) // #nosec G304\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn nil, ErrNotFound\n\t\t}\n\t\treturn nil, fmt.Errorf(\"failed to read schema from %s: %w\", filePath, err)\n\t}\n\n\tvar metadata ConfigMetadata\n\tif err := yaml.Unmarshal(body, &metadata); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse schema from %s: %w\", filePath, err)\n\t}\n\n\treturn &metadata, nil\n}\n\nfunc (sl *schemaLoader) loadFromHTTP(ref Ref, fileCacheDir string) (*ConfigMetadata, error) {\n\tversion, err := sl.refVersion(&ref)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tfilePath := filepath.Join(fileCacheDir, version, filepath.FromSlash(ref.SchemaID()), schemaFileName)\n\t// check fs cache first\n\tmetadata, err := sl.loadFromFile(filePath)\n\tif err == nil {\n\t\treturn metadata, nil\n\t}\n\tif !errors.Is(err, ErrNotFound) {\n\t\tlog.Printf(\"warning: failed to load schema from file cache at %s: %v\", filePath, err)\n\t}\n\tmetadata, err = sl.tryLoad(ref, version)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif err := sl.persistToFile(filePath, metadata); err != nil {\n\t\tlog.Printf(\"warning: failed to persist schema to file cache at %s: %v\", filePath, err)\n\t}\n\treturn metadata, nil\n}\n\nfunc (sl *schemaLoader) tryLoad(ref Ref, version string) (*ConfigMetadata, error) {\n\turl, err := ref.URL(version)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to construct URL for %s: %w\", ref.CacheKey(), err)\n\t}\n\n\tresp, err := sl.httpClient.Get(url)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to fetch schema from %s: %w\", url, err)\n\t}\n\tdefer resp.Body.Close()\n\n\tif resp.StatusCode == http.StatusNotFound {\n\t\treturn nil, ErrNotFound\n\t}\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"failed to fetch schema from %s: HTTP %d\", url, resp.StatusCode)\n\t}\n\n\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read response body from %s: %w\", url, err)\n\t}\n\n\tvar metadata ConfigMetadata\n\tif err := yaml.Unmarshal(body, &metadata); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to parse schema from %s: %w\", url, err)\n\t}\n\n\treturn &metadata, nil\n}\n\nfunc (sl *schemaLoader) persistToFile(filePath string, md *ConfigMetadata) error {\n\tif err := os.MkdirAll(filepath.Dir(filePath), 0o750); err != nil {\n\t\treturn fmt.Errorf(\"failed to create directory: %w\", err)\n\t}\n\n\tdata, err := yaml.Marshal(md)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal metadata: %w\", err)\n\t}\n\n\tif err := os.WriteFile(filePath, data, 0o600); err != nil {\n\t\treturn fmt.Errorf(\"failed to write file: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc (sl *schemaLoader) refVersion(ref *Ref) (string, error) {\n\t// Try to resolve version via packages.Load (respects replace directives)\n\tmodulePath := ref.Module()\n\tif modulePath != \"\" {\n\t\tif version := sl.resolveModuleVersion(modulePath); version != \"\" {\n\t\t\treturn version, nil\n\t\t}\n\t\t// attempt to \"go get\" the module to resolve version if not found locally\n\t\tcmd := exec.Command(\"go\", \"get\", modulePath) // #nosec G204\n\t\tcmd.Dir = sl.cd\n\n\t\tif err := cmd.Run(); err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"failed to run `go get` for module %s: %w\", modulePath, err)\n\t\t}\n\t\tif version := sl.resolveModuleVersion(modulePath); version != \"\" {\n\t\t\treturn version, nil\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"unable to resolve version for module %s after `go get`: %w\", modulePath, ErrNotFound)\n\t}\n\treturn \"\", fmt.Errorf(\"unknown module path for `%s` ref\", ref)\n}\n\nfunc (sl *schemaLoader) resolveModuleVersion(importPath string) string {\n\tcfg := &packages.Config{\n\t\tMode: packages.NeedModule,\n\t\tDir:  sl.cd,\n\t}\n\tpkgs, err := packages.Load(cfg, importPath)\n\tif err != nil || len(pkgs) == 0 {\n\t\treturn \"\"\n\t}\n\n\tpkg := pkgs[0]\n\tif pkg.Module == nil {\n\t\treturn \"\"\n\t}\n\n\treturn pkg.Module.Version\n}\n\nfunc (sl *schemaLoader) repoRoot(componentDir string) (string, error) {\n\tif sl.rootDir != \"\" {\n\t\treturn sl.rootDir, nil\n\t}\n\n\tcmd := exec.Command(\"git\", \"rev-parse\", \"--show-toplevel\")\n\tcmd.Dir = componentDir\n\toutput, err := cmd.Output()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to determine repo root: %w\", err)\n\t}\n\tsl.rootDir = strings.TrimSpace(string(output))\n\n\treturn sl.rootDir, nil\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/cfggen/loader_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage cfggen\n\nimport (\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestLoader_LoadFromFile_Success(t *testing.T) {\n\ttempDir := t.TempDir()\n\n\t// Create schema file - for a local ref\n\tschemaPath := filepath.Join(tempDir, \"internal/metadata\")\n\trequire.NoError(t, os.MkdirAll(schemaPath, 0o750))\n\tschemaFile := filepath.Join(schemaPath, schemaFileName)\n\tschemaContent := `title: \"Test Schema\"\ndescription: \"A test schema\"\ntype: object\n`\n\trequire.NoError(t, os.WriteFile(schemaFile, []byte(schemaContent), 0o600))\n\n\tloader := NewLoader(tempDir).(*schemaLoader)\n\n\t// For local refs, the loadFromFile method takes a file path\n\tresult, err := loader.loadFromFile(schemaFile)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"Test Schema\", result.Title)\n\trequire.Equal(t, \"A test schema\", result.Description)\n\trequire.Equal(t, \"object\", result.Type)\n}\n\nfunc TestLoader_LoadFromFile_NotFound(t *testing.T) {\n\ttempDir := t.TempDir()\n\tloader := NewLoader(tempDir).(*schemaLoader)\n\n\t// Try to load from non-existent file\n\tresult, err := loader.loadFromFile(filepath.Join(tempDir, \"nonexistent\", schemaFileName))\n\trequire.ErrorIs(t, err, ErrNotFound)\n\trequire.Nil(t, result)\n}\n\nfunc TestLoader_LoadFromFile_ParseError(t *testing.T) {\n\ttempDir := t.TempDir()\n\n\t// Create invalid YAML file\n\tschemaPath := filepath.Join(tempDir, \"test/path\")\n\trequire.NoError(t, os.MkdirAll(schemaPath, 0o750))\n\tschemaFile := filepath.Join(schemaPath, schemaFileName)\n\tinvalidYAML := `title: \"Test\"\n  invalid: yaml: content:\n`\n\trequire.NoError(t, os.WriteFile(schemaFile, []byte(invalidYAML), 0o600))\n\n\tloader := NewLoader(tempDir).(*schemaLoader)\n\n\tresult, err := loader.loadFromFile(schemaFile)\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"failed to parse schema\")\n\trequire.Nil(t, result)\n}\n\nfunc TestLoader_LoadFromHTTP_Success(t *testing.T) {\n\t// Create test HTTP server\n\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_, _ = w.Write([]byte(`title: \"HTTP Schema\"\ntype: string\n`))\n\t}))\n\tdefer server.Close()\n\n\t// Override namespaceToURL for testing\n\toriginalURL := namespaceToURL[\"go.opentelemetry.io/collector\"]\n\tnamespaceToURL[\"go.opentelemetry.io/collector\"] = server.URL\n\tdefer func() { namespaceToURL[\"go.opentelemetry.io/collector\"] = originalURL }()\n\n\ttempDir := t.TempDir()\n\t// Use mdatagenDir so resolveModuleVersion can find the module in go.mod\n\tloader := NewLoader(mdatagenDir(t)).(*schemaLoader)\n\tref := *NewRef(\"go.opentelemetry.io/collector/scraper/scraperhelper.controller_config\")\n\n\tresult, err := loader.loadFromHTTP(ref, filepath.Join(tempDir, \".schemas\"))\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"HTTP Schema\", result.Title)\n\trequire.Equal(t, \"string\", result.Type)\n}\n\nfunc TestLoader_LoadFromHTTP_NotFound(t *testing.T) {\n\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t}))\n\tdefer server.Close()\n\n\toriginalURL := namespaceToURL[\"go.opentelemetry.io/collector\"]\n\tnamespaceToURL[\"go.opentelemetry.io/collector\"] = server.URL\n\tdefer func() { namespaceToURL[\"go.opentelemetry.io/collector\"] = originalURL }()\n\n\ttempDir := t.TempDir()\n\tloader := NewLoader(mdatagenDir(t)).(*schemaLoader)\n\tref := *NewRef(\"go.opentelemetry.io/collector/scraper/scraperhelper.controller_config\")\n\n\tresult, err := loader.loadFromHTTP(ref, filepath.Join(tempDir, \".schemas\"))\n\trequire.ErrorIs(t, err, ErrNotFound)\n\trequire.Nil(t, result)\n}\n\nfunc TestLoader_LoadFromHTTP_ServerError(t *testing.T) {\n\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusInternalServerError)\n\t}))\n\tdefer server.Close()\n\n\toriginalURL := namespaceToURL[\"go.opentelemetry.io/collector\"]\n\tnamespaceToURL[\"go.opentelemetry.io/collector\"] = server.URL\n\tdefer func() { namespaceToURL[\"go.opentelemetry.io/collector\"] = originalURL }()\n\n\ttempDir := t.TempDir()\n\tloader := NewLoader(mdatagenDir(t)).(*schemaLoader)\n\tref := *NewRef(\"go.opentelemetry.io/collector/scraper/scraperhelper.controller_config\")\n\n\tresult, err := loader.loadFromHTTP(ref, filepath.Join(tempDir, \".schemas\"))\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"HTTP 500\")\n\trequire.Nil(t, result)\n}\n\nfunc TestLoader_TryLoad_WithVersion(t *testing.T) {\n\t// Create test HTTP server that returns different content for different versions\n\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tif strings.Contains(r.URL.Path, \"v1.0.0\") {\n\t\t\t_, _ = w.Write([]byte(`title: \"Versioned Schema\"`))\n\t\t} else {\n\t\t\t_, _ = w.Write([]byte(`title: \"Main Version Schema\"`))\n\t\t}\n\t}))\n\tdefer server.Close()\n\n\toriginalURL := namespaceToURL[\"go.opentelemetry.io/collector\"]\n\tnamespaceToURL[\"go.opentelemetry.io/collector\"] = server.URL\n\tdefer func() { namespaceToURL[\"go.opentelemetry.io/collector\"] = originalURL }()\n\n\ttempDir := t.TempDir()\n\tloader := NewLoader(tempDir).(*schemaLoader)\n\tref := *NewRef(\"go.opentelemetry.io/collector/test/path.config\")\n\n\t// Try to load with version\n\tresult, err := loader.tryLoad(ref, \"v1.0.0\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"Versioned Schema\", result.Title)\n}\n\nfunc TestLoader_PersistToFile_Success(t *testing.T) {\n\ttempDir := t.TempDir()\n\tloader := NewLoader(tempDir).(*schemaLoader)\n\n\tmetadata := &ConfigMetadata{\n\t\tTitle:       \"Persisted Schema\",\n\t\tDescription: \"Test persistence\",\n\t}\n\n\tfilePath := filepath.Join(tempDir, \"test\", \"persisted.yaml\")\n\terr := loader.persistToFile(filePath, metadata)\n\trequire.NoError(t, err)\n\n\t// Verify file was created\n\trequire.FileExists(t, filePath)\n\n\tcontent, err := os.ReadFile(filePath) // #nosec G304\n\trequire.NoError(t, err)\n\trequire.Contains(t, string(content), \"Persisted Schema\")\n\trequire.Contains(t, string(content), \"Test persistence\")\n}\n\nfunc TestLoader_Load_CacheInteraction(t *testing.T) {\n\ttempDir := t.TempDir()\n\n\tloader := NewLoader(tempDir).(*schemaLoader)\n\tref := *NewRef(\"go.opentelemetry.io/collector/test/path.config\")\n\n\texpected := &ConfigMetadata{Title: \"Pre-cached Schema\"}\n\tloader.cache[ref.CacheKey()] = expected\n\n\tresult, err := loader.Load(ref)\n\trequire.NoError(t, err)\n\trequire.Equal(t, expected, result)\n\trequire.Same(t, expected, result)\n}\n\nfunc TestLoader_Integration_MemoryCachePeristence(t *testing.T) {\n\ttempDir := t.TempDir()\n\n\tloader := &schemaLoader{\n\t\tcache:      make(map[string]*ConfigMetadata),\n\t\tcd:         tempDir,\n\t\thttpClient: &http.Client{Timeout: 30 * time.Second},\n\t}\n\n\tref := *NewRef(\"go.opentelemetry.io/collector/test/path.config\")\n\texpected := &ConfigMetadata{Title: \"Integration Test\"}\n\n\tloader.cache[ref.CacheKey()] = expected\n\n\tresult1, err := loader.Load(ref)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"Integration Test\", result1.Title)\n\n\tresult2, err := loader.Load(ref)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"Integration Test\", result2.Title)\n\n\trequire.Same(t, result1, result2)\n}\n\nfunc TestLoader_Load_CachesOnFirstLoad(t *testing.T) {\n\ttempDir := t.TempDir()\n\n\tschemaPath := filepath.Join(tempDir, \"subdir\")\n\trequire.NoError(t, os.MkdirAll(schemaPath, 0o750))\n\tschemaFile := filepath.Join(schemaPath, schemaFileName)\n\trequire.NoError(t, os.WriteFile(schemaFile, []byte(\"title: Cached\\ntype: object\\n\"), 0o600))\n\n\tloader := NewLoader(tempDir).(*schemaLoader)\n\tloader.rootDir = tempDir // bypass git\n\n\tref := Ref{schemaID: \"subdir\", kind: Local}\n\n\tresult1, err := loader.Load(ref)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"Cached\", result1.Title)\n\n\tresult2, err := loader.Load(ref)\n\trequire.NoError(t, err)\n\trequire.Same(t, result1, result2)\n}\n\nfunc TestLoader_Load_RepoRootError(t *testing.T) {\n\ttempDir := t.TempDir()\n\tloader := NewLoader(tempDir).(*schemaLoader)\n\n\tref := Ref{schemaID: \"subdir\", kind: Local}\n\t_, err := loader.load(ref)\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"failed to determine repo root\")\n}\n\nfunc TestLoader_Load_LocalAbsolutePath(t *testing.T) {\n\ttempDir := t.TempDir()\n\n\t// Create schema at <repoRoot>/somepackage/config.schema.yaml\n\tschemaDir := filepath.Join(tempDir, \"somepackage\")\n\trequire.NoError(t, os.MkdirAll(schemaDir, 0o750))\n\trequire.NoError(t, os.WriteFile(filepath.Join(schemaDir, schemaFileName), []byte(\"title: AbsoluteLocal\\ntype: object\\n\"), 0o600))\n\n\tloader := NewLoader(tempDir).(*schemaLoader)\n\tloader.rootDir = tempDir // bypass git\n\n\t// absolute local ref (starts with /)\n\tref := Ref{schemaID: \"/somepackage\", kind: Local}\n\tresult, err := loader.load(ref)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"AbsoluteLocal\", result.Title)\n}\n\nfunc TestLoader_Load_LocalRelativePath(t *testing.T) {\n\ttempDir := t.TempDir()\n\tsubDir := filepath.Join(tempDir, \"subdir\")\n\trequire.NoError(t, os.MkdirAll(subDir, 0o750))\n\trequire.NoError(t, os.WriteFile(filepath.Join(subDir, schemaFileName), []byte(\"title: RelativeLocal\\ntype: object\\n\"), 0o600))\n\n\tloader := NewLoader(tempDir).(*schemaLoader)\n\tloader.rootDir = tempDir // bypass git\n\n\t// relative local ref (does not start with /)\n\tref := Ref{schemaID: \"subdir\", kind: Local}\n\tresult, err := loader.load(ref)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"RelativeLocal\", result.Title)\n}\n\nfunc TestLoader_LoadFromFile_ReadError(t *testing.T) {\n\t// Create a directory where the file is expected — os.ReadFile on a directory fails\n\ttempDir := t.TempDir()\n\tdirPath := filepath.Join(tempDir, schemaFileName)\n\trequire.NoError(t, os.MkdirAll(dirPath, 0o750))\n\n\tloader := NewLoader(tempDir).(*schemaLoader)\n\tresult, err := loader.loadFromFile(dirPath)\n\trequire.Error(t, err)\n\trequire.Nil(t, result)\n\trequire.NotErrorIs(t, err, ErrNotFound)\n\trequire.Contains(t, err.Error(), \"failed to read schema\")\n}\n\nfunc TestLoader_LoadFromHTTP_FileCacheHit(t *testing.T) {\n\t// Test that loadFromHTTP returns from the file cache when a schema is already persisted,\n\t// without making any HTTP requests.\n\tref := *NewRef(\"go.opentelemetry.io/collector/scraper/scraperhelper.controller_config\")\n\n\t// Resolve the real module version so we can place the file at the right path.\n\tmdDir := mdatagenDir(t)\n\thelper := NewLoader(mdDir).(*schemaLoader)\n\tversion := helper.resolveModuleVersion(ref.Module())\n\tif version == \"\" {\n\t\tt.Skip(\"could not resolve module version, skipping file cache hit test\")\n\t}\n\n\ttempDir := t.TempDir()\n\tfileCacheDir := filepath.Join(tempDir, \".schemas\")\n\tfilePath := filepath.Join(fileCacheDir, version, ref.SchemaID(), schemaFileName)\n\trequire.NoError(t, os.MkdirAll(filepath.Dir(filePath), 0o750))\n\trequire.NoError(t, os.WriteFile(filePath, []byte(\"title: FileCached\\ntype: object\\n\"), 0o600))\n\n\t// Use an httpClient that always panics to confirm no HTTP call is made.\n\tloader := &schemaLoader{\n\t\tcache:      make(map[string]*ConfigMetadata),\n\t\tcd:         mdDir,\n\t\thttpClient: &http.Client{},\n\t}\n\n\tresult, err := loader.loadFromHTTP(ref, fileCacheDir)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"FileCached\", result.Title)\n}\n\nfunc TestLoader_LoadFromHTTP_PersistWarning(t *testing.T) {\n\t// Test the warning path when persistToFile fails (non-writable dir).\n\t// We create a read-only file cache dir so persistToFile fails.\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"file permission test not reliable on Windows\")\n\t}\n\n\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_, _ = w.Write([]byte(\"title: PersistFail\\ntype: object\\n\"))\n\t}))\n\tdefer server.Close()\n\n\toriginalURL := namespaceToURL[\"go.opentelemetry.io/collector\"]\n\tnamespaceToURL[\"go.opentelemetry.io/collector\"] = server.URL\n\tdefer func() { namespaceToURL[\"go.opentelemetry.io/collector\"] = originalURL }()\n\n\ttempDir := t.TempDir()\n\n\t// Make the file cache directory read-only so persistToFile fails\n\tcacheDir := filepath.Join(tempDir, \".schemas\")\n\trequire.NoError(t, os.MkdirAll(cacheDir, 0o750))\n\n\tloader := NewLoader(mdatagenDir(t)).(*schemaLoader)\n\tref := *NewRef(\"go.opentelemetry.io/collector/scraper/scraperhelper.controller_config\")\n\n\t// Should still return the result even though persist fails (warning only)\n\tresult, err := loader.loadFromHTTP(ref, cacheDir)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"PersistFail\", result.Title)\n}\n\nfunc TestLoader_LoadFromHTTP_NonNotFoundFileError(t *testing.T) {\n\t// Test the log.Printf warning path in loadFromHTTP when loadFromFile on the cached path\n\t// fails with a non-ErrNotFound error (directory placed where file is expected).\n\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_, _ = w.Write([]byte(\"title: AfterWarning\\ntype: object\\n\"))\n\t}))\n\tdefer server.Close()\n\n\toriginalURL := namespaceToURL[\"go.opentelemetry.io/collector\"]\n\tnamespaceToURL[\"go.opentelemetry.io/collector\"] = server.URL\n\tdefer func() { namespaceToURL[\"go.opentelemetry.io/collector\"] = originalURL }()\n\n\tmdDir := mdatagenDir(t)\n\tref := *NewRef(\"go.opentelemetry.io/collector/scraper/scraperhelper.controller_config\")\n\n\t// Resolve the real version so we can poison the file cache at the correct path\n\thelper := NewLoader(mdDir).(*schemaLoader)\n\tversion := helper.resolveModuleVersion(ref.Module())\n\tif version == \"\" {\n\t\tt.Skip(\"could not resolve module version, skipping non-ErrNotFound warning test\")\n\t}\n\n\ttempDir := t.TempDir()\n\tcacheDir := filepath.Join(tempDir, \".schemas\")\n\tfilePath := filepath.Join(cacheDir, version, ref.SchemaID(), schemaFileName)\n\t// Place a directory at the expected file path → loadFromFile returns a non-ErrNotFound error\n\trequire.NoError(t, os.MkdirAll(filePath, 0o750))\n\n\tloader := &schemaLoader{\n\t\tcache:      make(map[string]*ConfigMetadata),\n\t\tcd:         mdDir,\n\t\thttpClient: &http.Client{},\n\t}\n\n\tresult, err := loader.loadFromHTTP(ref, cacheDir)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"AfterWarning\", result.Title)\n}\n\nfunc TestLoader_TryLoad_URLError(t *testing.T) {\n\t// Ref with unsupported namespace → URL() returns an error\n\tloader := NewLoader(\"\").(*schemaLoader)\n\tref := *NewRef(\"unknownns/path.type\")\n\t// namespace is set so Module() returns non-empty, but Namespace() returns false\n\t// Actually NewRef sets it as external; let's manually set up a ref with no URL support\n\tref2 := Ref{namespace: \"unsupported.example.com\", schemaID: \"pkg\", defName: \"t\", kind: External}\n\t_, err := loader.tryLoad(ref2, \"v1.0.0\")\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"failed to construct URL\")\n\t_ = ref\n}\n\nfunc TestLoader_TryLoad_HTTPError(t *testing.T) {\n\t// Use a server that closes connections immediately to simulate a network error\n\t// The simplest approach: use an invalid URL\n\tloader := NewLoader(\"\").(*schemaLoader)\n\n\tref := *NewRef(\"go.opentelemetry.io/collector/test/path.config\")\n\n\t// Override the URL to point to an invalid host\n\toriginalURL := namespaceToURL[\"go.opentelemetry.io/collector\"]\n\tnamespaceToURL[\"go.opentelemetry.io/collector\"] = \"http://127.0.0.1:0\" // port 0 → connection refused\n\tdefer func() { namespaceToURL[\"go.opentelemetry.io/collector\"] = originalURL }()\n\n\t_, err := loader.tryLoad(ref, \"v1.0.0\")\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"failed to fetch schema\")\n}\n\nfunc TestLoader_TryLoad_ParseError(t *testing.T) {\n\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_, _ = w.Write([]byte(\"title: bad\\n  invalid: yaml: :\\n\"))\n\t}))\n\tdefer server.Close()\n\n\toriginalURL := namespaceToURL[\"go.opentelemetry.io/collector\"]\n\tnamespaceToURL[\"go.opentelemetry.io/collector\"] = server.URL\n\tdefer func() { namespaceToURL[\"go.opentelemetry.io/collector\"] = originalURL }()\n\n\tloader := NewLoader(\"\").(*schemaLoader)\n\tref := *NewRef(\"go.opentelemetry.io/collector/test/path.config\")\n\t_, err := loader.tryLoad(ref, \"v1.0.0\")\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"failed to parse schema\")\n}\n\nfunc TestLoader_RefVersion_UnknownModulePath(t *testing.T) {\n\ttempDir := t.TempDir()\n\tloader := NewLoader(tempDir).(*schemaLoader)\n\n\tref := Ref{namespace: \"\", schemaID: \"pkg\", defName: \"t\", kind: Internal}\n\t_, err := loader.refVersion(&ref)\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"unknown module path\")\n}\n\nfunc TestLoader_ResolveModuleVersion_NilModule(t *testing.T) {\n\tloader := NewLoader(mdatagenDir(t)).(*schemaLoader)\n\n\tversion := loader.resolveModuleVersion(\"fmt\")\n\trequire.Empty(t, version)\n}\n\nfunc TestLoader_ResolveModuleVersion_LoadError(t *testing.T) {\n\tloader := NewLoader(\"/nonexistent/path/xyz\").(*schemaLoader)\n\n\tversion := loader.resolveModuleVersion(\"somemodule/that/doesnt/exist\")\n\trequire.Empty(t, version)\n}\n\nfunc TestLoader_RepoRoot_CachedValue(t *testing.T) {\n\tloader := NewLoader(\"\").(*schemaLoader)\n\tloader.rootDir = \"/cached/root\"\n\n\troot, err := loader.repoRoot(\"/any/dir\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"/cached/root\", root)\n}\n\nfunc TestLoader_RepoRoot_GitError(t *testing.T) {\n\ttempDir := t.TempDir()\n\tloader := NewLoader(tempDir).(*schemaLoader)\n\n\t_, err := loader.repoRoot(tempDir)\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"failed to determine repo root\")\n}\n\nfunc TestLoader_PersistToFile_MkdirAllError(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"file permission test not reliable on Windows\")\n\t}\n\ttempDir := t.TempDir()\n\tt.Cleanup(func() {\n\t\t_ = os.Chmod(tempDir, 0o700) // #nosec G302 -- restore so t.TempDir cleanup can remove it\n\t})\n\n\trequire.NoError(t, os.Chmod(tempDir, 0o500)) // #nosec G302\n\n\tloader := NewLoader(tempDir).(*schemaLoader)\n\terr := loader.persistToFile(filepath.Join(tempDir, \"newdir\", \"schema.yaml\"), &ConfigMetadata{Title: \"X\"})\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"failed to create directory\")\n}\n\nfunc TestLoader_PersistToFile_WriteFileError(t *testing.T) {\n\ttempDir := t.TempDir()\n\n\tfilePath := filepath.Join(tempDir, \"schema.yaml\")\n\trequire.NoError(t, os.MkdirAll(filePath, 0o750))\n\n\tloader := NewLoader(tempDir).(*schemaLoader)\n\terr := loader.persistToFile(filePath, &ConfigMetadata{Title: \"X\"})\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"failed to write file\")\n}\n\nfunc TestLoader_TryLoad_ReadBodyError(t *testing.T) {\n\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.Header().Set(\"Content-Length\", \"1000\")\n\t\tw.WriteHeader(http.StatusOK)\n\t\thj, ok := w.(http.Hijacker)\n\t\tif !ok {\n\t\t\treturn\n\t\t}\n\t\tconn, _, _ := hj.Hijack()\n\t\t_ = conn.Close()\n\t}))\n\tdefer server.Close()\n\n\toriginalURL := namespaceToURL[\"go.opentelemetry.io/collector\"]\n\tnamespaceToURL[\"go.opentelemetry.io/collector\"] = server.URL\n\tdefer func() { namespaceToURL[\"go.opentelemetry.io/collector\"] = originalURL }()\n\n\tloader := NewLoader(\"\").(*schemaLoader)\n\tref := *NewRef(\"go.opentelemetry.io/collector/test/path.config\")\n\t_, err := loader.tryLoad(ref, \"v1.0.0\")\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"failed to read response body\")\n}\n\nfunc mdatagenDir(t *testing.T) string {\n\tt.Helper()\n\t_, file, _, ok := runtime.Caller(0)\n\trequire.True(t, ok, \"could not determine caller file\")\n\treturn filepath.Join(filepath.Dir(file), \"../..\")\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/cfggen/model.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage cfggen // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/cfggen\"\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n)\n\n// ConfigMetadata represents a JSON schema object, draft 2020-12 (limited), with additional custom fields.\ntype ConfigMetadata struct {\n\tSchema               string                     `mapstructure:\"$schema,omitempty\" json:\"$schema,omitempty\" yaml:\"$schema,omitempty\"`\n\tID                   string                     `mapstructure:\"$id,omitempty\" json:\"$id,omitempty\" yaml:\"$id,omitempty\"`\n\tTitle                string                     `mapstructure:\"title,omitempty\" json:\"title,omitempty\" yaml:\"title,omitempty\"`\n\tDescription          string                     `mapstructure:\"description,omitempty\" json:\"description,omitempty\" yaml:\"description,omitempty\"`\n\tComment              string                     `mapstructure:\"$comment,omitempty\" json:\"$comment,omitempty\" yaml:\"$comment,omitempty\"`\n\tType                 any                        `mapstructure:\"type,omitempty\" json:\"type,omitempty\" yaml:\"type,omitempty\"`\n\tRef                  string                     `mapstructure:\"$ref,omitempty\" json:\"-\" yaml:\"$ref,omitempty\"`\n\tDefault              any                        `mapstructure:\"default,omitempty\" json:\"default,omitempty\" yaml:\"default,omitempty\"`\n\tExamples             []any                      `mapstructure:\"examples,omitempty\" json:\"examples,omitempty\" yaml:\"examples,omitempty\"`\n\tDeprecated           bool                       `mapstructure:\"deprecated,omitempty\" json:\"deprecated,omitempty\" yaml:\"deprecated,omitempty\"`\n\tEnum                 []any                      `mapstructure:\"enum,omitempty\" json:\"enum,omitempty\" yaml:\"enum,omitempty\"`\n\tConst                any                        `mapstructure:\"const,omitempty\" json:\"const,omitempty\" yaml:\"const,omitempty\"`\n\tAllOf                []*ConfigMetadata          `mapstructure:\"allOf,omitempty\" json:\"allOf,omitempty\" yaml:\"allOf,omitempty\"`\n\tProperties           map[string]*ConfigMetadata `mapstructure:\"properties,omitempty\" json:\"properties,omitempty\" yaml:\"properties,omitempty\"`\n\tAdditionalProperties *ConfigMetadata            `mapstructure:\"additionalProperties,omitempty\" json:\"additionalProperties,omitempty\" yaml:\"additionalProperties,omitempty\"`\n\tRequired             []string                   `mapstructure:\"required,omitempty\" json:\"required,omitempty\" yaml:\"required,omitempty\"`\n\tMinProperties        *int                       `mapstructure:\"minProperties,omitempty\" json:\"minProperties,omitempty\" yaml:\"minProperties,omitempty\"`\n\tMaxProperties        *int                       `mapstructure:\"maxProperties,omitempty\" json:\"maxProperties,omitempty\" yaml:\"maxProperties,omitempty\"`\n\tItems                *ConfigMetadata            `mapstructure:\"items,omitempty\" json:\"items,omitempty\" yaml:\"items,omitempty\"`\n\tMinItems             *int                       `mapstructure:\"minItems,omitempty\" json:\"minItems,omitempty\" yaml:\"minItems,omitempty\"`\n\tMaxItems             *int                       `mapstructure:\"maxItems,omitempty\" json:\"maxItems,omitempty\" yaml:\"maxItems,omitempty\"`\n\tUniqueItems          bool                       `mapstructure:\"uniqueItems,omitempty\" json:\"uniqueItems,omitempty\" yaml:\"uniqueItems,omitempty\"`\n\tMaxLength            *int                       `mapstructure:\"maxLength,omitempty\" json:\"maxLength,omitempty\" yaml:\"maxLength,omitempty\"`\n\tMinLength            *int                       `mapstructure:\"minLength,omitempty\" json:\"minLength,omitempty\" yaml:\"minLength,omitempty\"`\n\tPattern              string                     `mapstructure:\"pattern,omitempty\" json:\"pattern,omitempty\" yaml:\"pattern,omitempty\"`\n\tFormat               string                     `mapstructure:\"format,omitempty\" json:\"format,omitempty\" yaml:\"format,omitempty\"`\n\tContentMediaType     string                     `mapstructure:\"contentMediaType,omitempty\" json:\"contentMediaType,omitempty\" yaml:\"contentMediaType,omitempty\"`\n\tContentEncoding      string                     `mapstructure:\"contentEncoding,omitempty\" json:\"contentEncoding,omitempty\" yaml:\"contentEncoding,omitempty\"`\n\tContentSchema        *ConfigMetadata            `mapstructure:\"contentSchema,omitempty\" json:\"contentSchema,omitempty\" yaml:\"contentSchema,omitempty\"`\n\tMultipleOf           *float64                   `mapstructure:\"multipleOf,omitempty\" json:\"multipleOf,omitempty\" yaml:\"multipleOf,omitempty\"`\n\tMaximum              *float64                   `mapstructure:\"maximum,omitempty\" json:\"maximum,omitempty\" yaml:\"maximum,omitempty\"`\n\tExclusiveMaximum     *float64                   `mapstructure:\"exclusiveMaximum,omitempty\" json:\"exclusiveMaximum,omitempty\" yaml:\"exclusiveMaximum,omitempty\"`\n\tMinimum              *float64                   `mapstructure:\"minimum,omitempty\" json:\"minimum,omitempty\" yaml:\"minimum,omitempty\"`\n\tExclusiveMinimum     *float64                   `mapstructure:\"exclusiveMinimum,omitempty\" json:\"exclusiveMinimum,omitempty\" yaml:\"exclusiveMinimum,omitempty\"`\n\tDefs                 map[string]*ConfigMetadata `mapstructure:\"$defs,omitempty\" json:\"-\" yaml:\"$defs,omitempty\"`\n\t// Additional custom fields\n\tGoType     string `mapstructure:\"x-customType,omitempty\" json:\"-\" yaml:\"x-customType,omitempty\"`\n\tIsPointer  bool   `mapstructure:\"x-pointer,omitempty\" json:\"-\" yaml:\"x-pointer,omitempty\"`\n\tIsOptional bool   `mapstructure:\"x-optional,omitempty\" json:\"-\" yaml:\"x-optional,omitempty\"`\n}\n\nfunc (md *ConfigMetadata) ToJSON() ([]byte, error) {\n\treturn json.MarshalIndent(md, \"\", \"  \")\n}\n\nfunc (md *ConfigMetadata) Validate() error {\n\tvar errs error\n\tif md.Type != \"object\" {\n\t\terrs = errors.Join(errs, fmt.Errorf(\"config type must be \\\"object\\\", got %q\", md.Type))\n\t}\n\tif len(md.Properties) == 0 && len(md.AllOf) == 0 {\n\t\terrs = errors.Join(errs, errors.New(\"config must not be empty\"))\n\t}\n\treturn errs\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/cfggen/model_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage cfggen\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestConfigMetadata_ToJSON(t *testing.T) {\n\tmd := &ConfigMetadata{\n\t\tSchema: schemaVersion,\n\t\tType:   \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"endpoint\": {Type: \"string\", Description: \"The endpoint\"},\n\t\t},\n\t}\n\n\tdata, err := md.ToJSON()\n\trequire.NoError(t, err)\n\tassert.Contains(t, string(data), `\"$schema\"`)\n\tassert.Contains(t, string(data), `\"endpoint\"`)\n\tassert.Contains(t, string(data), `\"The endpoint\"`)\n}\n\nfunc TestConfigMetadata_Validate_Valid(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tmd   *ConfigMetadata\n\t}{\n\t\t{\n\t\t\tname: \"valid with properties\",\n\t\t\tmd: &ConfigMetadata{\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"endpoint\": {Type: \"string\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"valid with allOf\",\n\t\t\tmd: &ConfigMetadata{\n\t\t\t\tType: \"object\",\n\t\t\t\tAllOf: []*ConfigMetadata{\n\t\t\t\t\t{Ref: \"some_ref\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"valid with both properties and allOf\",\n\t\t\tmd: &ConfigMetadata{\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"endpoint\": {Type: \"string\"},\n\t\t\t\t},\n\t\t\t\tAllOf: []*ConfigMetadata{\n\t\t\t\t\t{Ref: \"some_ref\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"valid with multiple properties\",\n\t\t\tmd: &ConfigMetadata{\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"endpoint\": {Type: \"string\"},\n\t\t\t\t\t\"timeout\":  {Type: \"string\", GoType: \"time.Duration\"},\n\t\t\t\t\t\"port\":     {Type: \"integer\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := tt.md.Validate()\n\t\t\tassert.NoError(t, err)\n\t\t})\n\t}\n}\n\nfunc TestConfigMetadata_Validate_InvalidType(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tmd      *ConfigMetadata\n\t\twantErr string\n\t}{\n\t\t{\n\t\t\tname: \"type is string instead of object\",\n\t\t\tmd: &ConfigMetadata{\n\t\t\t\tType: \"string\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"endpoint\": {Type: \"string\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twantErr: `config type must be \"object\", got \"string\"`,\n\t\t},\n\t\t{\n\t\t\tname: \"type is empty string\",\n\t\t\tmd: &ConfigMetadata{\n\t\t\t\tType: \"\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"endpoint\": {Type: \"string\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twantErr: `config type must be \"object\", got \"\"`,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := tt.md.Validate()\n\t\t\trequire.Error(t, err)\n\t\t\tassert.Contains(t, err.Error(), tt.wantErr)\n\t\t})\n\t}\n}\n\nfunc TestConfigMetadata_Validate_EmptyConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tmd      *ConfigMetadata\n\t\twantErr string\n\t}{\n\t\t{\n\t\t\tname: \"no properties and no allOf\",\n\t\t\tmd: &ConfigMetadata{\n\t\t\t\tType: \"object\",\n\t\t\t},\n\t\t\twantErr: \"config must not be empty\",\n\t\t},\n\t\t{\n\t\t\tname: \"empty properties map and no allOf\",\n\t\t\tmd: &ConfigMetadata{\n\t\t\t\tType:       \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{},\n\t\t\t},\n\t\t\twantErr: \"config must not be empty\",\n\t\t},\n\t\t{\n\t\t\tname: \"empty allOf slice and no properties\",\n\t\t\tmd: &ConfigMetadata{\n\t\t\t\tType:  \"object\",\n\t\t\t\tAllOf: []*ConfigMetadata{},\n\t\t\t},\n\t\t\twantErr: \"config must not be empty\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := tt.md.Validate()\n\t\t\trequire.Error(t, err)\n\t\t\tassert.Contains(t, err.Error(), tt.wantErr)\n\t\t})\n\t}\n}\n\nfunc TestConfigMetadata_Validate_MultipleErrors(t *testing.T) {\n\ttests := []struct {\n\t\tname            string\n\t\tmd              *ConfigMetadata\n\t\twantErrCount    int\n\t\twantErrContains []string\n\t}{\n\t\t{\n\t\t\tname: \"invalid type and empty config\",\n\t\t\tmd: &ConfigMetadata{\n\t\t\t\tType: \"string\",\n\t\t\t},\n\t\t\twantErrCount: 2,\n\t\t\twantErrContains: []string{\n\t\t\t\t`config type must be \"object\", got \"string\"`,\n\t\t\t\t\"config must not be empty\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"invalid type with empty properties and empty allOf\",\n\t\t\tmd: &ConfigMetadata{\n\t\t\t\tType:       \"array\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{},\n\t\t\t\tAllOf:      []*ConfigMetadata{},\n\t\t\t},\n\t\t\twantErrCount: 2,\n\t\t\twantErrContains: []string{\n\t\t\t\t`config type must be \"object\", got \"array\"`,\n\t\t\t\t\"config must not be empty\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := tt.md.Validate()\n\t\t\trequire.Error(t, err)\n\n\t\t\t// Check that error contains all expected substrings\n\t\t\tfor _, expectedErr := range tt.wantErrContains {\n\t\t\t\tassert.Contains(t, err.Error(), expectedErr)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestConfigMetadata_Validate_NilMetadata(t *testing.T) {\n\tvar md *ConfigMetadata\n\t// The current implementation panics on nil receiver\n\t// This test documents that behavior\n\tassert.Panics(t, func() {\n\t\t_ = md.Validate()\n\t}, \"Validate() should panic when called on nil ConfigMetadata\")\n}\n\nfunc TestConfigMetadata_Validate_TypeAsInterface(t *testing.T) {\n\t// Test when Type field is set as interface{} instead of string\n\t// This tests the real-world scenario where YAML/JSON unmarshaling\n\t// might produce different types\n\ttests := []struct {\n\t\tname    string\n\t\ttypeVal any\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:    \"type as string 'object'\",\n\t\t\ttypeVal: \"object\",\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname:    \"type as string 'string'\",\n\t\t\ttypeVal: \"string\",\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"type as array of strings (union type) - not supported\",\n\t\t\ttypeVal: []any{\"object\", \"null\"},\n\t\t\twantErr: true, // Current implementation doesn't handle union types, treats as invalid\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tmd := &ConfigMetadata{\n\t\t\t\tType: tt.typeVal,\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"field\": {Type: \"string\"},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\terr := md.Validate()\n\t\t\tif tt.wantErr {\n\t\t\t\tassert.Error(t, err)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestConfigMetadata_Validate_EdgeCases(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tmd      *ConfigMetadata\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname: \"single property is sufficient\",\n\t\t\tmd: &ConfigMetadata{\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"only_field\": {Type: \"string\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"single allOf entry is sufficient\",\n\t\t\tmd: &ConfigMetadata{\n\t\t\t\tType: \"object\",\n\t\t\t\tAllOf: []*ConfigMetadata{\n\t\t\t\t\t{Ref: \"base_config\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"properties with nested objects\",\n\t\t\tmd: &ConfigMetadata{\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"server\": {\n\t\t\t\t\t\tType: \"object\",\n\t\t\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\t\t\"host\": {Type: \"string\"},\n\t\t\t\t\t\t\t\"port\": {Type: \"integer\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"allOf with nil entries\",\n\t\t\tmd: &ConfigMetadata{\n\t\t\t\tType: \"object\",\n\t\t\t\tAllOf: []*ConfigMetadata{\n\t\t\t\t\tnil,\n\t\t\t\t\t{Ref: \"base_config\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\twantErr: false, // At least one non-nil entry exists\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := tt.md.Validate()\n\t\t\tif tt.wantErr {\n\t\t\t\tassert.Error(t, err)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/cfggen/namespace.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage cfggen // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/cfggen\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"maps\"\n\t\"path\"\n\t\"regexp\"\n\t\"slices\"\n\t\"strings\"\n)\n\nvar namespaceToURL = map[string]string{\n\t\"go.opentelemetry.io/collector\":                             \"https://raw.githubusercontent.com/open-telemetry/opentelemetry-collector\",\n\t\"github.com/open-telemetry/opentelemetry-collector-contrib\": \"https://raw.githubusercontent.com/open-telemetry/opentelemetry-collector-contrib\",\n}\n\nvar supportedNamespaces = slices.Collect(maps.Keys(namespaceToURL))\n\ntype RefKind int\n\nconst (\n\tExternal RefKind = iota\n\tInternal\n\tLocal\n)\n\ntype Ref struct {\n\tnamespace string\n\tschemaID  string\n\tdefName   string\n\tkind      RefKind\n}\n\nvar localRefPattern = regexp.MustCompile(`^((?:/|\\.\\.?/).*?)(?:\\.([^./]+))?$`)\n\nfunc NewRef(refPath string) *Ref {\n\tvar namespace, schemaID, defName string\n\tvar kind RefKind\n\n\tswitch {\n\tcase localRefPattern.MatchString(refPath):\n\t\tmatches := localRefPattern.FindStringSubmatch(refPath)\n\t\tschemaID = matches[1]\n\t\tdefName = matches[2]\n\t\tkind = Local\n\tcase !strings.ContainsRune(refPath, '/'):\n\t\tdefName = refPath\n\t\tkind = Internal\n\tdefault:\n\t\tnamespace = namespaceOf(refPath)\n\t\trest, _ := strings.CutPrefix(refPath, namespace)\n\t\tschemaID, defName, _ = strings.Cut(rest, \".\")\n\t\tschemaID = strings.Trim(schemaID, \"/\")\n\t\tkind = External\n\t}\n\n\treturn &Ref{\n\t\tnamespace,\n\t\tschemaID,\n\t\tdefName,\n\t\tkind,\n\t}\n}\n\nfunc WithOrigin(refPath string, origin *Ref) *Ref {\n\tref := NewRef(refPath)\n\tif origin == nil {\n\t\treturn ref\n\t}\n\n\tif origin.isExternal() {\n\t\tref.namespace = origin.namespace\n\t\tref.kind = External\n\t\tif strings.HasPrefix(ref.schemaID, \"/\") {\n\t\t\tref.schemaID = strings.Trim(ref.schemaID, \"/\")\n\t\t\treturn ref\n\t\t}\n\n\t\tref.schemaID = path.Join(origin.schemaID, ref.schemaID)\n\t\treturn ref\n\t}\n\t// check if it's a local ref with relative path, if so, resolve it against the origin schema ID\n\tif ref.isLocal() && !strings.HasPrefix(ref.schemaID, \"/\") {\n\t\tref.schemaID = path.Join(origin.schemaID, ref.schemaID)\n\t}\n\treturn ref\n}\n\nfunc namespaceOf(path string) string {\n\tif ns, ok := matchSupportedNamespace(path); ok {\n\t\treturn ns\n\t}\n\tif idx := strings.LastIndex(path, \"/\"); idx != -1 {\n\t\treturn path[:idx]\n\t}\n\treturn \"\"\n}\n\nfunc matchSupportedNamespace(path string) (string, bool) {\n\tfor _, ns := range supportedNamespaces {\n\t\tif strings.HasPrefix(path, ns) {\n\t\t\treturn ns, true\n\t\t}\n\t}\n\treturn \"\", false\n}\n\nfunc (r *Ref) Namespace() (string, bool) {\n\t_, ok := matchSupportedNamespace(r.namespace)\n\treturn r.namespace, ok\n}\n\nfunc (r *Ref) Module() string {\n\tif r.namespace != \"\" {\n\t\treturn r.namespace + \"/\" + r.schemaID\n\t}\n\treturn \"\"\n}\n\nfunc (r *Ref) SchemaID() string {\n\treturn r.schemaID\n}\n\nfunc (r *Ref) DefName() string {\n\treturn r.defName\n}\n\nfunc (r *Ref) URL(version string) (string, error) {\n\tns, ok := r.Namespace()\n\tif !ok {\n\t\treturn \"\", errors.New(\"unsupported namespace\")\n\t}\n\tbaseURL := namespaceToURL[ns]\n\treturn fmt.Sprintf(\"%s/%s/%s/%s\",\n\t\t\tbaseURL,\n\t\t\tversion,\n\t\t\tr.SchemaID(),\n\t\t\tschemaFileName),\n\t\tnil\n}\n\nfunc (r *Ref) isInternal() bool {\n\treturn r.kind == Internal\n}\n\nfunc (r *Ref) isLocal() bool {\n\treturn r.kind == Local\n}\n\nfunc (r *Ref) isExternal() bool {\n\treturn r.kind == External\n}\n\nfunc (r *Ref) Validate() error {\n\tif r.String() == \"\" {\n\t\treturn errors.New(\"empty path\")\n\t}\n\n\tif r.defName == \"\" {\n\t\treturn errors.New(\"missing definition name\")\n\t}\n\tif r.isLocal() && r.schemaID == \"\" {\n\t\treturn errors.New(\"missing schema ID in local reference\")\n\t}\n\n\treturn nil\n}\n\nfunc (r *Ref) String() string {\n\tvar sb strings.Builder\n\tif r.namespace != \"\" {\n\t\tsb.WriteString(r.namespace)\n\t}\n\tif r.schemaID != \"\" {\n\t\tif sb.Len() > 0 {\n\t\t\tsb.WriteRune('/')\n\t\t}\n\t\tsb.WriteString(r.schemaID)\n\t}\n\tif r.defName != \"\" {\n\t\tif sb.Len() > 0 {\n\t\t\tsb.WriteRune('.')\n\t\t}\n\t\tsb.WriteString(r.defName)\n\t}\n\n\treturn sb.String()\n}\n\nfunc (r *Ref) CacheKey() string {\n\treturn r.String()\n}\n\nfunc LocalizeRef(refPath, importRootPath string) string {\n\tif importRootPath == \"\" || !strings.HasPrefix(refPath, importRootPath+\"/\") {\n\t\treturn refPath\n\t}\n\treturn strings.TrimPrefix(refPath, importRootPath)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/cfggen/namespace_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage cfggen\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestNewRef(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\trefPath  string\n\t\texpected *Ref\n\t}{\n\t\t{\n\t\t\tname:    \"empty ref\",\n\t\t\trefPath: \"\",\n\t\t\texpected: &Ref{\n\t\t\t\tnamespace: \"\",\n\t\t\t\tschemaID:  \"\",\n\t\t\t\tdefName:   \"\",\n\t\t\t\tkind:      Internal,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"internal ref\",\n\t\t\trefPath: \"target_type\",\n\t\t\texpected: &Ref{\n\t\t\t\tnamespace: \"\",\n\t\t\t\tschemaID:  \"\",\n\t\t\t\tdefName:   \"target_type\",\n\t\t\t\tkind:      Internal,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"local ref with absolute path\",\n\t\t\trefPath: \"/config/configauth.config\",\n\t\t\texpected: &Ref{\n\t\t\t\tnamespace: \"\",\n\t\t\t\tschemaID:  \"/config/configauth\",\n\t\t\t\tdefName:   \"config\",\n\t\t\t\tkind:      Local,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"local ref with relative path (./)\",\n\t\t\trefPath: \"./internal/metadata.config\",\n\t\t\texpected: &Ref{\n\t\t\t\tnamespace: \"\",\n\t\t\t\tschemaID:  \"./internal/metadata\",\n\t\t\t\tdefName:   \"config\",\n\t\t\t\tkind:      Local,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"local ref with relative path (../)\",\n\t\t\trefPath: \"../other.config\",\n\t\t\texpected: &Ref{\n\t\t\t\tnamespace: \"\",\n\t\t\t\tschemaID:  \"../other\",\n\t\t\t\tdefName:   \"config\",\n\t\t\t\tkind:      Local,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"local ref without def name\",\n\t\t\trefPath: \"/config/configauth\",\n\t\t\texpected: &Ref{\n\t\t\t\tnamespace: \"\",\n\t\t\t\tschemaID:  \"/config/configauth\",\n\t\t\t\tdefName:   \"\",\n\t\t\t\tkind:      Local,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"local ref empty\",\n\t\t\trefPath: \"../\",\n\t\t\texpected: &Ref{\n\t\t\t\tnamespace: \"\",\n\t\t\t\tschemaID:  \"../\",\n\t\t\t\tdefName:   \"\",\n\t\t\t\tkind:      Local,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"local ref empty short schemaId\",\n\t\t\trefPath: \"../.test\",\n\t\t\texpected: &Ref{\n\t\t\t\tnamespace: \"\",\n\t\t\t\tschemaID:  \"../\",\n\t\t\t\tdefName:   \"test\",\n\t\t\t\tkind:      Local,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"external ref without version\",\n\t\t\trefPath: \"go.opentelemetry.io/collector/config/confighttp.client_config\",\n\t\t\texpected: &Ref{\n\t\t\t\tnamespace: \"go.opentelemetry.io/collector\",\n\t\t\t\tschemaID:  \"config/confighttp\",\n\t\t\t\tdefName:   \"client_config\",\n\t\t\t\tkind:      External,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"external ref without def name\",\n\t\t\trefPath: \"go.opentelemetry.io/collector/config/confighttp\",\n\t\t\texpected: &Ref{\n\t\t\t\tnamespace: \"go.opentelemetry.io/collector\",\n\t\t\t\tschemaID:  \"config/confighttp\",\n\t\t\t\tdefName:   \"\",\n\t\t\t\tkind:      External,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"external ref without schema ID\",\n\t\t\trefPath: \"go.opentelemetry.io/collector\",\n\t\t\texpected: &Ref{\n\t\t\t\tnamespace: \"go.opentelemetry.io/collector\",\n\t\t\t\tschemaID:  \"\",\n\t\t\t\tdefName:   \"\",\n\t\t\t\tkind:      External,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"unknown namespace\",\n\t\t\trefPath: \"com.github.example/custom.xyz\",\n\t\t\texpected: &Ref{\n\t\t\t\tnamespace: \"com.github.example\",\n\t\t\t\tschemaID:  \"custom\",\n\t\t\t\tdefName:   \"xyz\",\n\t\t\t\tkind:      External,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"ref with wrong format\",\n\t\t\trefPath: \"some/path.with.dots\",\n\t\t\texpected: &Ref{\n\t\t\t\tnamespace: \"some\",\n\t\t\t\tschemaID:  \"path\",\n\t\t\t\tdefName:   \"with.dots\",\n\t\t\t\tkind:      External,\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := NewRef(tt.refPath)\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestWithOrigin(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\trefPath  string\n\t\torigin   string\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"absolute ref resolves against namespace\",\n\t\t\trefPath:  \"/config/configauth.config\",\n\t\t\torigin:   \"go.opentelemetry.io/collector/config/confighttp\",\n\t\t\texpected: \"go.opentelemetry.io/collector/config/configauth.config\",\n\t\t},\n\t\t{\n\t\t\tname:     \"absolute ref with empty origin unchanged\",\n\t\t\trefPath:  \"/config/configauth.config\",\n\t\t\torigin:   \"\",\n\t\t\texpected: \"/config/configauth.config\",\n\t\t},\n\t\t{\n\t\t\tname:     \"relative ref resolves against module path\",\n\t\t\trefPath:  \"./internal/metadata.config\",\n\t\t\torigin:   \"go.opentelemetry.io/collector/config/confighttp\",\n\t\t\texpected: \"go.opentelemetry.io/collector/config/confighttp/internal/metadata.config\",\n\t\t},\n\t\t{\n\t\t\tname:     \"parent relative ref resolves against parent module\",\n\t\t\trefPath:  \"../configtls.tls_config\",\n\t\t\torigin:   \"go.opentelemetry.io/collector/config/confighttp\",\n\t\t\texpected: \"go.opentelemetry.io/collector/config/configtls.tls_config\",\n\t\t},\n\t\t{\n\t\t\tname:     \"external ref with same-namespace origin joins schema IDs\",\n\t\t\trefPath:  \"go.opentelemetry.io/collector/config/confighttp.client_config\",\n\t\t\torigin:   \"go.opentelemetry.io/collector/config/confighttp\",\n\t\t\texpected: \"go.opentelemetry.io/collector/config/confighttp/config/confighttp.client_config\",\n\t\t},\n\t\t{\n\t\t\tname:     \"internal ref with origin unchanged\",\n\t\t\trefPath:  \"target_type\",\n\t\t\torigin:   \"go.opentelemetry.io/collector/config/confighttp\",\n\t\t\texpected: \"go.opentelemetry.io/collector/config/confighttp.target_type\",\n\t\t},\n\t\t{\n\t\t\tname:     \"local relative ref with local absolute resolves to local absolute schema ID\",\n\t\t\trefPath:  \"./internal.timeout_config\",\n\t\t\torigin:   \"/config/confighttp\",\n\t\t\texpected: \"/config/confighttp/internal.timeout_config\",\n\t\t},\n\t\t{\n\t\t\tname:     \"local relative ref with external origin resolves to external schema ID\",\n\t\t\trefPath:  \"./internal.timeout_config\",\n\t\t\torigin:   \"go.opentelemetry.io/collector/config/confighttp\",\n\t\t\texpected: \"go.opentelemetry.io/collector/config/confighttp/internal.timeout_config\",\n\t\t},\n\t\t{\n\t\t\tname:     \"local absolute ref with local absolute origin keeps original schema ID\",\n\t\t\trefPath:  \"/config/confighttp.timeout_config\",\n\t\t\torigin:   \"/config/confignet.connection_config\",\n\t\t\texpected: \"/config/confighttp.timeout_config\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tref := WithOrigin(tt.refPath, NewRef(tt.origin))\n\t\t\trequire.Equal(t, tt.expected, ref.CacheKey())\n\t\t})\n\t}\n}\n\nfunc TestRef_Validate(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\trefPath string\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:    \"valid collector reference\",\n\t\t\trefPath: \"go.opentelemetry.io/collector/scraper/scraperhelper.controller_config\",\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname:    \"valid contrib reference\",\n\t\t\trefPath: \"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/mysqlreceiver.config\",\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname:    \"valid internal reference\",\n\t\t\trefPath: \"target_type\",\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname:    \"valid local absolute reference\",\n\t\t\trefPath: \"/config/configauth.config\",\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname:    \"empty path\",\n\t\t\trefPath: \"\",\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"missing def name\",\n\t\t\trefPath: \"/config/configauth\",\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"missing schema ID with external ref\",\n\t\t\trefPath: \"go.opentelemetry.io/collector\",\n\t\t\twantErr: true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tref := NewRef(tt.refPath)\n\t\t\terr := ref.Validate()\n\t\t\tif tt.wantErr {\n\t\t\t\trequire.Error(t, err)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestRef_URL(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\trefPath  string\n\t\tversion  string\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"collector reference\",\n\t\t\trefPath:  \"go.opentelemetry.io/collector/scraper/scraperhelper.controller_config\",\n\t\t\tversion:  \"v1.0.0\",\n\t\t\texpected: \"https://raw.githubusercontent.com/open-telemetry/opentelemetry-collector/v1.0.0/scraper/scraperhelper/config.schema.yaml\",\n\t\t},\n\t\t{\n\t\t\tname:     \"contrib reference\",\n\t\t\trefPath:  \"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/mysqlreceiver.config\",\n\t\t\tversion:  \"v0.95.0\",\n\t\t\texpected: \"https://raw.githubusercontent.com/open-telemetry/opentelemetry-collector-contrib/v0.95.0/receiver/mysqlreceiver/config.schema.yaml\",\n\t\t},\n\t\t{\n\t\t\tname:     \"main version\",\n\t\t\trefPath:  \"go.opentelemetry.io/collector/processor/batchprocessor.config\",\n\t\t\tversion:  \"main\",\n\t\t\texpected: \"https://raw.githubusercontent.com/open-telemetry/opentelemetry-collector/main/processor/batchprocessor/config.schema.yaml\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tref := NewRef(tt.refPath)\n\t\t\tresult, err := ref.URL(tt.version)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestRef_String(t *testing.T) {\n\tref := NewRef(\"go.opentelemetry.io/collector/config/confighttp.client_config\")\n\trequire.Equal(t, \"go.opentelemetry.io/collector/config/confighttp.client_config\", ref.String())\n}\n\nfunc TestRef_Module_EmptyNamespace(t *testing.T) {\n\tref := NewRef(\"target_type\")\n\trequire.Empty(t, ref.Module())\n}\n\nfunc TestRef_URL_UnsupportedNamespace(t *testing.T) {\n\tref := NewRef(\"unsupported.example.com/pkg/sub.config\")\n\t_, err := ref.URL(\"v1.0.0\")\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"unsupported namespace\")\n}\n\nfunc TestRef_Validate_LocalRefMissingSchemaID(t *testing.T) {\n\tref := &Ref{schemaID: \"\", defName: \"config\", kind: Local}\n\terr := ref.Validate()\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"missing schema ID in local reference\")\n}\n\nfunc TestNamespaceOf_FallbackLastSlash(t *testing.T) {\n\tresult := namespaceOf(\"com.example/some/path.type\")\n\trequire.Equal(t, \"com.example/some\", result)\n}\n\nfunc TestNamespaceOf_NoSlash(t *testing.T) {\n\tresult := namespaceOf(\"noslash\")\n\trequire.Empty(t, result)\n}\n\nfunc TestLocalizeRef(t *testing.T) {\n\ttests := []struct {\n\t\tname           string\n\t\trefPath        string\n\t\timportRootPath string\n\t\texpected       string\n\t}{\n\t\t{\n\t\t\tname:           \"same root collector ref becomes local absolute\",\n\t\t\trefPath:        \"go.opentelemetry.io/collector/filter.config\",\n\t\t\timportRootPath: \"go.opentelemetry.io/collector\",\n\t\t\texpected:       \"/filter.config\",\n\t\t},\n\t\t{\n\t\t\tname:           \"different root ref stays external\",\n\t\t\trefPath:        \"go.opentelemetry.io/collector/filter.config\",\n\t\t\timportRootPath: \"github.com/open-telemetry/opentelemetry-collector-contrib\",\n\t\t\texpected:       \"go.opentelemetry.io/collector/filter.config\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\trequire.Equal(t, tt.expected, LocalizeRef(tt.refPath, tt.importRootPath))\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/cfggen/resolver.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage cfggen // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/cfggen\"\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n)\n\nconst (\n\tschemaVersion = \"https://json-schema.org/draft/2020-12/schema\"\n\t// goDurationPattern matches Go duration strings (e.g., \"30s\", \"1h30m\", \"500ms\")\n\tgoDurationPattern = `^([0-9]+(\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$`\n)\n\ntype Resolver struct {\n\tpkgID  string\n\tclass  string\n\tname   string\n\tloader Loader\n}\n\nfunc NewResolver(pkgID, class, name, dir string) *Resolver {\n\tloader := NewLoader(dir)\n\n\treturn &Resolver{\n\t\tloader: loader,\n\t\tpkgID:  pkgID,\n\t\tclass:  class,\n\t\tname:   name,\n\t}\n}\n\n// ResolveSchema takes a source configuration metadata schema and resolves all references ($ref)\n// to produce a fully resolved schema. It handles both internal references (within the same schema) and external references\n// (pointing to other schemas, either locally or remotely). The resolver uses registered loaders to fetch external schemas as needed.\n//\n// Returns a new ConfigMetadata with all references resolved, or an error if resolution fails.\nfunc (r *Resolver) ResolveSchema(src *ConfigMetadata) (*ConfigMetadata, error) {\n\ttarget := &ConfigMetadata{}\n\terr := r.resolveSchema(src, src, target, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttarget.Schema = schemaVersion\n\ttarget.ID = r.pkgID\n\ttarget.Title = fmt.Sprintf(\"%s/%s\", r.class, r.name)\n\n\treturn target, nil\n}\n\n// transformDurationFormat converts JSON Schema format: duration to Go duration pattern.\n// JSON Schema duration format expects ISO 8601 (e.g., \"PT30S\"), but Go uses a different\n// format (e.g., \"30s\", \"1h30m\"). This function replaces the format with a pattern that\n// validates Go duration strings.\nfunc transformDurationFormat(md *ConfigMetadata) {\n\tif md.Type == \"string\" && md.Format == \"duration\" {\n\t\tmd.Format = \"\"\n\t\tmd.Pattern = goDurationPattern\n\t\tif md.Description != \"\" && !strings.Contains(md.Description, \"duration\") {\n\t\t\tmd.Description += \" (duration format, e.g., \\\"30s\\\", \\\"1h30m\\\")\"\n\t\t}\n\t}\n}\n\nfunc (r *Resolver) resolveSchema(root, current, target *ConfigMetadata, origin *Ref) error {\n\tif current.Ref != \"\" {\n\t\tresolved, err := r.resolveRef(root, current, origin)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to resolve $ref %q: %w\", current.Ref, err)\n\t\t}\n\n\t\t// Preserve custom extensions defined on the reference node\n\t\tcustomGoType := current.GoType\n\t\tcustomIsPointer := current.IsPointer\n\t\tcustomIsOptional := current.IsOptional\n\t\tcustomDescription := current.Description\n\t\tcustomDefault := current.Default\n\t\tcustomEnum := current.Enum\n\n\t\t// Copy the resolved node\n\t\tnewCurrent := *resolved\n\n\t\t// Restore custom extensions if they were explicitly set on the reference\n\t\tif customGoType != \"\" {\n\t\t\tnewCurrent.GoType = customGoType\n\t\t}\n\t\tif customIsPointer {\n\t\t\tnewCurrent.IsPointer = customIsPointer\n\t\t}\n\t\tif customIsOptional {\n\t\t\tnewCurrent.IsOptional = customIsOptional\n\t\t}\n\t\tif customDescription != \"\" {\n\t\t\tnewCurrent.Description = customDescription\n\t\t}\n\t\tif customDefault != nil {\n\t\t\tnewCurrent.Default = customDefault\n\t\t}\n\t\tif len(customEnum) > 0 {\n\t\t\tnewCurrent.Enum = customEnum\n\t\t}\n\n\t\tcurrent = &newCurrent\n\t}\n\n\tcurrRef := reflect.ValueOf(current).Elem()\n\ttargetRef := reflect.ValueOf(target).Elem()\n\n\tfor i := 0; i < currRef.NumField(); i++ {\n\t\tfield := currRef.Field(i)\n\t\ttargetField := targetRef.Field(i)\n\n\t\tif !targetField.CanSet() {\n\t\t\tcontinue\n\t\t}\n\n\t\tswitch field.Kind() {\n\t\tcase reflect.Ptr:\n\t\t\tif !field.IsNil() && field.Elem().Kind() == reflect.Struct {\n\t\t\t\tif field.Type() == reflect.TypeFor[*ConfigMetadata]() {\n\t\t\t\t\tnewMeta := &ConfigMetadata{}\n\t\t\t\t\tif err := r.resolveSchema(root, field.Interface().(*ConfigMetadata), newMeta, origin); err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\ttargetField.Set(reflect.ValueOf(newMeta))\n\t\t\t\t}\n\t\t\t}\n\t\tcase reflect.Map:\n\t\t\tif field.Type().Elem() == reflect.TypeFor[*ConfigMetadata]() {\n\t\t\t\tnewMap := reflect.MakeMap(field.Type())\n\t\t\t\titer := field.MapRange()\n\t\t\t\tfor iter.Next() {\n\t\t\t\t\tkey := iter.Key()\n\t\t\t\t\tvalue := iter.Value()\n\t\t\t\t\tif !value.IsNil() {\n\t\t\t\t\t\tnewMeta := &ConfigMetadata{}\n\t\t\t\t\t\tif err := r.resolveSchema(root, value.Interface().(*ConfigMetadata), newMeta, origin); err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnewMap.SetMapIndex(key, reflect.ValueOf(newMeta))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ttargetField.Set(newMap)\n\t\t\t} else {\n\t\t\t\ttargetField.Set(field)\n\t\t\t}\n\t\tcase reflect.Slice:\n\t\t\tif field.Type().Elem() == reflect.TypeFor[*ConfigMetadata]() {\n\t\t\t\tnewSlice := reflect.MakeSlice(field.Type(), field.Len(), field.Len())\n\t\t\t\tfor j := 0; j < field.Len(); j++ {\n\t\t\t\t\telem := field.Index(j)\n\t\t\t\t\tif !elem.IsNil() {\n\t\t\t\t\t\tnewMeta := &ConfigMetadata{}\n\t\t\t\t\t\tif err := r.resolveSchema(root, elem.Interface().(*ConfigMetadata), newMeta, origin); err != nil {\n\t\t\t\t\t\t\treturn err\n\t\t\t\t\t\t}\n\t\t\t\t\t\tnewSlice.Index(j).Set(reflect.ValueOf(newMeta))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\ttargetField.Set(newSlice)\n\t\t\t} else {\n\t\t\t\ttargetField.Set(field)\n\t\t\t}\n\t\tdefault:\n\t\t\ttargetField.Set(field)\n\t\t}\n\t}\n\ttransformDurationFormat(target)\n\ttarget.Defs = nil // Clear defs after resolution to avoid confusion\n\treturn nil\n}\n\n// resolveRef resolves a JSON Schema $ref, handling both internal and external references.\n// The origin parameter tracks which namespace the current schema was loaded from,\n// enabling local refs in remotely-fetched schemas to be converted to external refs.\nfunc (r *Resolver) resolveRef(root, current *ConfigMetadata, origin *Ref) (*ConfigMetadata, error) {\n\tref := WithOrigin(current.Ref, origin)\n\n\tif err := ref.Validate(); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid reference format %q: %w\", current.Ref, err)\n\t}\n\n\tif ref.isInternal() {\n\t\tif root.Defs != nil {\n\t\t\tif val, ok := root.Defs[ref.DefName()]; ok {\n\t\t\t\treturn val, nil\n\t\t\t}\n\t\t}\n\t}\n\n\tif ref.isLocal() {\n\t\treturn r.loadExternalRef(ref)\n\t}\n\n\t// check if it's in known namespace\n\tif _, ok := ref.Namespace(); ok {\n\t\treturn r.loadExternalRef(ref)\n\t}\n\n\t// fallback to type \"any\"\n\tcurrent.GoType = current.Ref\n\tcurrent.Comment = \"Uses `any` type.\"\n\treturn current, nil\n}\n\n// loadExternalRef uses SchemaLoader to load external references\nfunc (r *Resolver) loadExternalRef(ref *Ref) (*ConfigMetadata, error) {\n\tmd, err := r.loader.Load(*ref)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif md == nil {\n\t\treturn nil, fmt.Errorf(\"no loader could resolve external reference: %s\", ref)\n\t}\n\n\tif md.Defs != nil {\n\t\tif def, ok := md.Defs[ref.DefName()]; ok {\n\t\t\tresolved := &ConfigMetadata{}\n\t\t\tif err := r.resolveSchema(md, def, resolved, ref); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"failed to resolve internal references in external schema %s: %w\", ref, err)\n\t\t\t}\n\t\t\treturn resolved, nil\n\t\t}\n\t}\n\n\treturn nil, fmt.Errorf(\"type %q not found in loaded schema for reference %s\", ref.DefName(), ref)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/cfggen/resolver_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage cfggen\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestResolver_ResolveSchema_BasicMetadata(t *testing.T) {\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/receiver/otlpreceiver\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"otlp\",\n\t\tloader: NewLoader(\"\"),\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tDescription: \"OTLP receiver configuration\",\n\t\tType:        \"object\",\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.Equal(t, schemaVersion, result.Schema)\n\trequire.Equal(t, \"go.opentelemetry.io/collector/receiver/otlpreceiver\", result.ID)\n\trequire.Equal(t, \"receiver/otlp\", result.Title)\n\trequire.Equal(t, \"OTLP receiver configuration\", result.Description)\n\trequire.Equal(t, \"object\", result.Type)\n}\n\nfunc TestResolver_ResolveSchema_InternalReference(t *testing.T) {\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: NewLoader(\"\"),\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"config\": {\n\t\t\t\tRef: \"target_type\",\n\t\t\t},\n\t\t},\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"target_type\": {\n\t\t\t\tType:        \"string\",\n\t\t\t\tDescription: \"Target type description\",\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"object\", result.Type)\n\trequire.NotNil(t, result.Properties[\"config\"])\n\trequire.Equal(t, \"string\", result.Properties[\"config\"].Type)\n\trequire.Equal(t, \"Target type description\", result.Properties[\"config\"].Description)\n}\n\nfunc TestResolver_ResolveSchema_UnknownInternalReference(t *testing.T) {\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: NewLoader(\"\"),\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"config\": {\n\t\t\t\tRef: \"unknown_type\",\n\t\t\t},\n\t\t},\n\t}\n\n\t// Should use \"any\" type because the internal reference doesn't exist\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.Nil(t, result.Properties[\"config\"].Type)\n}\n\nfunc TestResolver_ResolveSchema_NestedStructures(t *testing.T) {\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: NewLoader(\"\"),\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"nested\": {\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"field1\": {\n\t\t\t\t\t\tType: \"string\",\n\t\t\t\t\t},\n\t\t\t\t\t\"field2\": {\n\t\t\t\t\t\tType: \"integer\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"object\", result.Type)\n\trequire.NotNil(t, result.Properties[\"nested\"])\n\trequire.Equal(t, \"object\", result.Properties[\"nested\"].Type)\n\trequire.NotNil(t, result.Properties[\"nested\"].Properties[\"field1\"])\n\trequire.Equal(t, \"string\", result.Properties[\"nested\"].Properties[\"field1\"].Type)\n\trequire.NotNil(t, result.Properties[\"nested\"].Properties[\"field2\"])\n\trequire.Equal(t, \"integer\", result.Properties[\"nested\"].Properties[\"field2\"].Type)\n}\n\nfunc TestResolver_ResolveSchema_AllOf(t *testing.T) {\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: NewLoader(\"\"),\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tAllOf: []*ConfigMetadata{\n\t\t\t{\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"field1\": {Type: \"string\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"field2\": {Type: \"integer\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.Len(t, result.AllOf, 2)\n\trequire.NotNil(t, result.AllOf[0].Properties[\"field1\"])\n\trequire.NotNil(t, result.AllOf[1].Properties[\"field2\"])\n}\n\nfunc TestResolver_ResolveSchema_ArrayItems(t *testing.T) {\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: NewLoader(\"\"),\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"array\",\n\t\tItems: &ConfigMetadata{\n\t\t\tType: \"object\",\n\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\"name\": {Type: \"string\"},\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"array\", result.Type)\n\trequire.NotNil(t, result.Items)\n\trequire.Equal(t, \"object\", result.Items.Type)\n\trequire.NotNil(t, result.Items.Properties[\"name\"])\n}\n\nfunc TestResolver_LoadExternalRef_Success(t *testing.T) {\n\tml := &mockLoader{\n\t\tschemas: map[string]*ConfigMetadata{\n\t\t\t\"go.opentelemetry.io/collector/scraper/scraperhelper.controller_config\": {\n\t\t\t\tType: \"object\",\n\t\t\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\t\t\"controller_config\": {\n\t\t\t\t\t\tType: \"object\",\n\t\t\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\t\t\"timeout\": {\n\t\t\t\t\t\t\t\tType: \"string\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: ml,\n\t}\n\n\tref := NewRef(\"go.opentelemetry.io/collector/scraper/scraperhelper.controller_config\")\n\tresult, err := resolver.loadExternalRef(ref)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"object\", result.Type)\n\trequire.NotNil(t, result.Properties[\"timeout\"])\n\trequire.Equal(t, \"string\", result.Properties[\"timeout\"].Type)\n}\n\nfunc TestResolver_LoadExternalRef_InvalidPath(t *testing.T) {\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: NewLoader(\"\"),\n\t}\n\n\tref := NewRef(\"invalid/path/without/namespace\")\n\tresult, err := resolver.loadExternalRef(ref)\n\trequire.Error(t, err)\n\trequire.Nil(t, result)\n}\n\nfunc TestResolver_LoadExternalRef_TypeNotFound(t *testing.T) {\n\tml := &mockLoader{\n\t\tschemas: map[string]*ConfigMetadata{\n\t\t\t\"go.opentelemetry.io/collector/scraper/scraperhelper.controller_config\": {\n\t\t\t\tType: \"object\",\n\t\t\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\t\t\"other_type\": {\n\t\t\t\t\t\tType: \"string\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: ml,\n\t}\n\n\tref := NewRef(\"go.opentelemetry.io/collector/scraper/scraperhelper.controller_config\")\n\tresult, err := resolver.loadExternalRef(ref)\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"type \\\"controller_config\\\" not found\")\n\trequire.Nil(t, result)\n}\n\nfunc TestResolver_IsExternalRef(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tref      string\n\t\texpected bool\n\t}{\n\t\t{\n\t\t\tname:     \"collector external ref - known namespace\",\n\t\t\tref:      \"go.opentelemetry.io/collector/scraper/scraperhelper.controller_config\",\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname:     \"contrib external ref - known namespace\",\n\t\t\tref:      \"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/mysqlreceiver.config\",\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname:     \"relative path - local not external\",\n\t\t\tref:      \"./internal/metadata.metrics_builder_config\",\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname:     \"internal ref - simple name\",\n\t\t\tref:      \"target_type\",\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname:     \"unsupported namespace - still external (not internal/local)\",\n\t\t\tref:      \"github.com/example/custom.config\",\n\t\t\texpected: true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tr := NewRef(tt.ref)\n\t\t\tresult := r.isExternal()\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestResolver_ResolveSchema_ExternalReference_Integration(t *testing.T) {\n\t// Use mockLoader instead of real file loading to avoid repo root dependency\n\tconfighttpSchema := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"client_config\": {\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"endpoint\": {\n\t\t\t\t\t\tType:        \"string\",\n\t\t\t\t\t\tDescription: \"HTTP endpoint\",\n\t\t\t\t\t},\n\t\t\t\t\t\"timeout\": {\n\t\t\t\t\t\tType:        \"string\",\n\t\t\t\t\t\tDescription: \"Request timeout\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tml := &mockLoader{\n\t\tschemas: map[string]*ConfigMetadata{\n\t\t\t\"go.opentelemetry.io/collector/config/confighttp.client_config\": confighttpSchema,\n\t\t},\n\t}\n\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/receiver/otlpreceiver\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"otlp\",\n\t\tloader: ml,\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"http\": {\n\t\t\t\tRef: \"go.opentelemetry.io/collector/config/confighttp.client_config\",\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"object\", result.Type)\n\trequire.NotNil(t, result.Properties[\"http\"])\n\trequire.Equal(t, \"object\", result.Properties[\"http\"].Type)\n\trequire.NotNil(t, result.Properties[\"http\"].Properties[\"endpoint\"])\n\trequire.Equal(t, \"HTTP endpoint\", result.Properties[\"http\"].Properties[\"endpoint\"].Description)\n\trequire.NotNil(t, result.Properties[\"http\"].Properties[\"timeout\"])\n\trequire.Equal(t, \"Request timeout\", result.Properties[\"http\"].Properties[\"timeout\"].Description)\n}\n\nfunc TestResolver_ResolveSchema_DurationFormat(t *testing.T) {\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: NewLoader(\"\"),\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"timeout\": {\n\t\t\t\tType:        \"string\",\n\t\t\t\tFormat:      \"duration\",\n\t\t\t\tDescription: \"Request timeout\",\n\t\t\t},\n\t\t\t\"interval\": {\n\t\t\t\tType:   \"string\",\n\t\t\t\tFormat: \"duration\",\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\n\t// Check timeout field - should have pattern instead of format\n\trequire.NotNil(t, result.Properties[\"timeout\"])\n\trequire.Equal(t, \"string\", result.Properties[\"timeout\"].Type)\n\trequire.Empty(t, result.Properties[\"timeout\"].Format, \"format should be cleared\")\n\trequire.Equal(t, `^([0-9]+(\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$`, result.Properties[\"timeout\"].Pattern)\n\trequire.Contains(t, result.Properties[\"timeout\"].Description, \"duration format\")\n\trequire.Contains(t, result.Properties[\"timeout\"].Description, \"Request timeout\")\n\n\t// Check interval field - should have pattern and auto-generated description hint\n\trequire.NotNil(t, result.Properties[\"interval\"])\n\trequire.Equal(t, \"string\", result.Properties[\"interval\"].Type)\n\trequire.Empty(t, result.Properties[\"interval\"].Format)\n\trequire.Equal(t, `^([0-9]+(\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$`, result.Properties[\"interval\"].Pattern)\n}\n\n// mockLoader is a test helper that returns pre-configured schemas keyed by cache key.\ntype mockLoader struct {\n\tschemas map[string]*ConfigMetadata\n}\n\nfunc (m *mockLoader) Load(ref Ref) (*ConfigMetadata, error) {\n\tcacheKey := ref.CacheKey()\n\tif md, ok := m.schemas[cacheKey]; ok {\n\t\treturn md, nil\n\t}\n\treturn nil, fmt.Errorf(\"schema not found for ref: %s\", cacheKey)\n}\n\nfunc TestResolver_ResolveSchema_OriginConvertsLocalRefToExternal(t *testing.T) {\n\t// confighttp schema contains a local absolute ref to /config/configauth.config\n\t// When loaded as an external ref from the collector namespace, the local ref\n\t// should be converted to go.opentelemetry.io/collector/config/configauth.config\n\tconfigauthSchema := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"config\": {\n\t\t\t\tType:        \"object\",\n\t\t\t\tDescription: \"Auth configuration\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"token\": {Type: \"string\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tconfighttpSchema := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"client_config\": {\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"endpoint\": {Type: \"string\"},\n\t\t\t\t\t\"auth\": {\n\t\t\t\t\t\t// This is the key: a local absolute ref inside an externally-loaded schema\n\t\t\t\t\t\tRef: \"/config/configauth.config\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tml := &mockLoader{\n\t\tschemas: map[string]*ConfigMetadata{\n\t\t\t// When loading the reference to confighttp.client_config, we get the whole schema with all defs\n\t\t\t\"go.opentelemetry.io/collector/config/confighttp.client_config\": confighttpSchema,\n\t\t\t// When resolving the local ref /config/configauth.config -> go.opentelemetry.io/collector/config/configauth.config\n\t\t\t\"go.opentelemetry.io/collector/config/configauth.config\": configauthSchema,\n\t\t},\n\t}\n\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/receiver/otlpreceiver\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"otlp\",\n\t\tloader: ml,\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"http\": {\n\t\t\t\tRef: \"go.opentelemetry.io/collector/config/confighttp.client_config\",\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, result.Properties[\"http\"])\n\trequire.Equal(t, \"object\", result.Properties[\"http\"].Type)\n\trequire.NotNil(t, result.Properties[\"http\"].Properties[\"endpoint\"])\n\trequire.Equal(t, \"string\", result.Properties[\"http\"].Properties[\"endpoint\"].Type)\n\t// The auth property should have been resolved through origin-aware conversion\n\trequire.NotNil(t, result.Properties[\"http\"].Properties[\"auth\"])\n\trequire.Equal(t, \"object\", result.Properties[\"http\"].Properties[\"auth\"].Type)\n\trequire.Equal(t, \"Auth configuration\", result.Properties[\"http\"].Properties[\"auth\"].Description)\n\trequire.NotNil(t, result.Properties[\"http\"].Properties[\"auth\"].Properties[\"token\"])\n}\n\nfunc TestResolver_ResolveSchema_LocalRefWithOriginConversion(t *testing.T) {\n\t// When a local ref is encountered in an externally-loaded schema, it should be converted\n\t// using the origin namespace\n\tconfigauthSchema := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"config\": {\n\t\t\t\tType:        \"object\",\n\t\t\t\tDescription: \"Auth config\",\n\t\t\t},\n\t\t},\n\t}\n\n\tconfighttpSchema := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"client_config\": {\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"auth\": {\n\t\t\t\t\t\t// This is a local absolute ref inside an externally-loaded schema\n\t\t\t\t\t\tRef: \"/config/configauth.config\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tml := &mockLoader{\n\t\tschemas: map[string]*ConfigMetadata{\n\t\t\t\"go.opentelemetry.io/collector/config/confighttp.client_config\": confighttpSchema,\n\t\t\t// After origin conversion, /config/configauth.config becomes:\n\t\t\t\"go.opentelemetry.io/collector/config/configauth.config\": configauthSchema,\n\t\t},\n\t}\n\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/receiver/otlpreceiver\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"otlp\",\n\t\tloader: ml,\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"http\": {\n\t\t\t\tRef: \"go.opentelemetry.io/collector/config/confighttp.client_config\",\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, result.Properties[\"http\"])\n\trequire.Equal(t, \"object\", result.Properties[\"http\"].Type)\n\t// auth should be resolved through origin-aware conversion\n\trequire.NotNil(t, result.Properties[\"http\"].Properties[\"auth\"])\n\trequire.Equal(t, \"object\", result.Properties[\"http\"].Properties[\"auth\"].Type)\n\trequire.Equal(t, \"Auth config\", result.Properties[\"http\"].Properties[\"auth\"].Description)\n}\n\nfunc TestResolver_ResolveSchema_NestedOriginPropagation(t *testing.T) {\n\t// Schema A (remote) → local ref → Schema B (also remote) → local ref → Schema C\n\t// Verify the origin propagates through all levels.\n\n\tschemaC := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"tls_config\": {\n\t\t\t\tType:        \"object\",\n\t\t\t\tDescription: \"TLS configuration\",\n\t\t\t},\n\t\t},\n\t}\n\n\tschemaB := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"auth_config\": {\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"tls\": {\n\t\t\t\t\t\t// Nested local ref — should also be converted using origin\n\t\t\t\t\t\tRef: \"/config/configtls.tls_config\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tschemaA := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"client_config\": {\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"auth\": {\n\t\t\t\t\t\tRef: \"/config/configauth.auth_config\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tml := &mockLoader{\n\t\tschemas: map[string]*ConfigMetadata{\n\t\t\t\"go.opentelemetry.io/collector/config/confighttp.client_config\": schemaA,\n\t\t\t\"go.opentelemetry.io/collector/config/configauth.auth_config\":   schemaB,\n\t\t\t\"go.opentelemetry.io/collector/config/configtls.tls_config\":     schemaC,\n\t\t},\n\t}\n\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/receiver/otlpreceiver\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"otlp\",\n\t\tloader: ml,\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"http\": {\n\t\t\t\tRef: \"go.opentelemetry.io/collector/config/confighttp.client_config\",\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, result.Properties[\"http\"])\n\t// auth should be resolved through origin-aware conversion\n\tauth := result.Properties[\"http\"].Properties[\"auth\"]\n\trequire.NotNil(t, auth)\n\trequire.Equal(t, \"object\", auth.Type)\n\t// tls inside auth should also be resolved through origin propagation\n\ttls := auth.Properties[\"tls\"]\n\trequire.NotNil(t, tls)\n\trequire.Equal(t, \"object\", tls.Type)\n\trequire.Equal(t, \"TLS configuration\", tls.Description)\n}\n\nfunc TestResolver_ResolveSchema_RelativeRefWithOrigin(t *testing.T) {\n\tmetadataSchema := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"metrics_config\": {\n\t\t\t\tType:        \"object\",\n\t\t\t\tDescription: \"Metrics configuration\",\n\t\t\t},\n\t\t},\n\t}\n\n\tconfighttpSchema := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"client_config\": {\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"metrics\": {\n\t\t\t\t\t\tRef: \"./internal/metadata.metrics_config\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tml := &mockLoader{\n\t\tschemas: map[string]*ConfigMetadata{\n\t\t\t\"go.opentelemetry.io/collector/config/confighttp.client_config\":                    confighttpSchema,\n\t\t\t\"go.opentelemetry.io/collector/config/confighttp/internal/metadata.metrics_config\": metadataSchema,\n\t\t},\n\t}\n\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/receiver/otlpreceiver\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"otlp\",\n\t\tloader: ml,\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"http\": {\n\t\t\t\tRef: \"go.opentelemetry.io/collector/config/confighttp.client_config\",\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, result.Properties[\"http\"])\n\tmetrics := result.Properties[\"http\"].Properties[\"metrics\"]\n\trequire.NotNil(t, metrics)\n\trequire.Equal(t, \"object\", metrics.Type)\n\trequire.Equal(t, \"Metrics configuration\", metrics.Description)\n}\n\nfunc TestResolver_ResolveSchema_ParentRelativeRefWithOrigin(t *testing.T) {\n\tconfigtlsSchema := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"tls_config\": {\n\t\t\t\tType:        \"object\",\n\t\t\t\tDescription: \"TLS settings\",\n\t\t\t},\n\t\t},\n\t}\n\n\tconfighttpSchema := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"client_config\": {\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"tls\": {\n\t\t\t\t\t\tRef: \"../configtls.tls_config\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tml := &mockLoader{\n\t\tschemas: map[string]*ConfigMetadata{\n\t\t\t\"go.opentelemetry.io/collector/config/confighttp.client_config\": confighttpSchema,\n\t\t\t\"go.opentelemetry.io/collector/config/configtls.tls_config\":     configtlsSchema,\n\t\t},\n\t}\n\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/receiver/otlpreceiver\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"otlp\",\n\t\tloader: ml,\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"http\": {\n\t\t\t\tRef: \"go.opentelemetry.io/collector/config/confighttp.client_config\",\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, result.Properties[\"http\"])\n\ttls := result.Properties[\"http\"].Properties[\"tls\"]\n\trequire.NotNil(t, tls)\n\trequire.Equal(t, \"object\", tls.Type)\n\trequire.Equal(t, \"TLS settings\", tls.Description)\n}\n\nfunc TestNewResolver(t *testing.T) {\n\tdir := t.TempDir()\n\tr := NewResolver(\"go.opentelemetry.io/collector/receiver/otlp\", \"receiver\", \"otlp\", dir)\n\trequire.NotNil(t, r)\n\trequire.Equal(t, \"go.opentelemetry.io/collector/receiver/otlp\", r.pkgID)\n\trequire.Equal(t, \"receiver\", r.class)\n\trequire.Equal(t, \"otlp\", r.name)\n\trequire.NotNil(t, r.loader)\n}\n\nfunc TestResolver_ResolveSchema_UnknownNamespaceFallback(t *testing.T) {\n\t// An external ref with an unsupported namespace should fall back to \"any\" type\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: NewLoader(\"\"),\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"custom\": {\n\t\t\t\tRef: \"github.com/example/custom.config\",\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, result.Properties[\"custom\"])\n\trequire.Equal(t, \"github.com/example/custom.config\", result.Properties[\"custom\"].GoType)\n\trequire.Contains(t, result.Properties[\"custom\"].Comment, \"any\")\n}\n\nfunc TestResolver_ResolveSchema_LoaderError(t *testing.T) {\n\tml := &mockLoader{schemas: map[string]*ConfigMetadata{}}\n\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: ml,\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"http\": {\n\t\t\t\tRef: \"go.opentelemetry.io/collector/config/confighttp.client_config\",\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.Error(t, err)\n\trequire.Nil(t, result)\n}\n\nfunc TestResolver_ResolveRef_InvalidRefFormat(t *testing.T) {\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: NewLoader(\"\"),\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"bad\": {\n\t\t\t\tRef: \"/\",\n\t\t\t},\n\t\t},\n\t}\n\t_, err := resolver.ResolveSchema(src)\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"invalid reference format\")\n}\n\nfunc TestResolver_LoadExternalRef_NilResult(t *testing.T) {\n\tml := &nilResultLoader{}\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: ml,\n\t}\n\n\tref := NewRef(\"go.opentelemetry.io/collector/config/confighttp.client_config\")\n\tresult, err := resolver.loadExternalRef(ref)\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"no loader could resolve external reference\")\n\trequire.Nil(t, result)\n}\n\n// nilResultLoader returns (nil, nil) for any ref.\ntype nilResultLoader struct{}\n\nfunc (n *nilResultLoader) Load(_ Ref) (*ConfigMetadata, error) { return nil, nil }\n\nfunc TestResolver_LoadExternalRef_InternalResolutionError(t *testing.T) {\n\tbrokenSchema := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"config\": {\n\t\t\t\tType: \"object\",\n\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\"field\": {\n\t\t\t\t\t\tRef: \"/\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tml := &mockLoader{\n\t\tschemas: map[string]*ConfigMetadata{\n\t\t\t\"go.opentelemetry.io/collector/config/confighttp.config\": brokenSchema,\n\t\t},\n\t}\n\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: ml,\n\t}\n\n\tref := NewRef(\"go.opentelemetry.io/collector/config/confighttp.config\")\n\tresult, err := resolver.loadExternalRef(ref)\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"failed to resolve internal references in external schema\")\n\trequire.Nil(t, result)\n}\n\nfunc TestResolver_ResolveSchema_LocalRef(t *testing.T) {\n\tlocalSchema := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"target\": {\n\t\t\t\tType:        \"object\",\n\t\t\t\tDescription: \"Local target\",\n\t\t\t},\n\t\t},\n\t}\n\n\tml := &mockLoader{\n\t\tschemas: map[string]*ConfigMetadata{\n\t\t\t\"/config/localtype.target\": localSchema,\n\t\t},\n\t}\n\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: ml,\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"local\": {\n\t\t\t\tRef: \"/config/localtype.target\",\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, result.Properties[\"local\"])\n\trequire.Equal(t, \"object\", result.Properties[\"local\"].Type)\n\trequire.Equal(t, \"Local target\", result.Properties[\"local\"].Description)\n}\n\nfunc TestResolver_ResolveSchema_MapValueError(t *testing.T) {\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: &mockLoader{schemas: map[string]*ConfigMetadata{}},\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"field\": {\n\t\t\t\t// Ref to an unknown external schema → loader returns error\n\t\t\t\tRef: \"go.opentelemetry.io/collector/missing/pkg.config\",\n\t\t\t},\n\t\t},\n\t}\n\n\t_, err := resolver.ResolveSchema(src)\n\trequire.Error(t, err)\n}\n\nfunc TestResolver_ResolveSchema_AllOfError(t *testing.T) {\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: &mockLoader{schemas: map[string]*ConfigMetadata{}},\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tAllOf: []*ConfigMetadata{\n\t\t\t{\n\t\t\t\tRef: \"go.opentelemetry.io/collector/missing/pkg.config\",\n\t\t\t},\n\t\t},\n\t}\n\n\t_, err := resolver.ResolveSchema(src)\n\trequire.Error(t, err)\n}\n\nfunc TestResolver_ResolveSchema_PtrFieldError(t *testing.T) {\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: &mockLoader{schemas: map[string]*ConfigMetadata{}},\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"body\": {\n\t\t\t\tType: \"string\",\n\t\t\t\tContentSchema: &ConfigMetadata{\n\t\t\t\t\tRef: \"/\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\t_, err := resolver.ResolveSchema(src)\n\trequire.Error(t, err)\n}\n\nfunc TestResolver_ResolveSchema_PointerFields(t *testing.T) {\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: NewLoader(\"\"),\n\t}\n\n\tminItems := 1\n\tmaxItems := 10\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"tags\": {\n\t\t\t\tType:     \"array\",\n\t\t\t\tItems:    &ConfigMetadata{Type: \"string\"},\n\t\t\t\tMinItems: &minItems,\n\t\t\t\tMaxItems: &maxItems,\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, result.Properties[\"tags\"])\n\trequire.Equal(t, \"array\", result.Properties[\"tags\"].Type)\n\trequire.NotNil(t, result.Properties[\"tags\"].Items)\n\trequire.Equal(t, \"string\", result.Properties[\"tags\"].Items.Type)\n}\n\nfunc TestResolver_ResolveSchema_ContentSchema(t *testing.T) {\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: NewLoader(\"\"),\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"body\": {\n\t\t\t\tType:             \"string\",\n\t\t\t\tContentMediaType: \"application/json\",\n\t\t\t\tContentSchema: &ConfigMetadata{\n\t\t\t\t\tType: \"object\",\n\t\t\t\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\t\t\t\"name\": {Type: \"string\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, result.Properties[\"body\"])\n\trequire.NotNil(t, result.Properties[\"body\"].ContentSchema)\n\trequire.Equal(t, \"object\", result.Properties[\"body\"].ContentSchema.Type)\n}\n\nfunc TestResolver_ResolveSchema_PreservesCustomExtensions(t *testing.T) {\n\t// When a node has both a $ref and custom extensions (GoType, IsPointer,\n\t// IsOptional, Description, Default, Enum), the custom extensions should\n\t// be preserved after resolution instead of being overwritten by the\n\t// resolved schema's values.\n\n\ttargetSchema := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"duration_type\": {\n\t\t\t\tType:        \"string\",\n\t\t\t\tDescription: \"A generic duration type\",\n\t\t\t},\n\t\t},\n\t}\n\n\tml := &mockLoader{\n\t\tschemas: map[string]*ConfigMetadata{\n\t\t\t\"go.opentelemetry.io/collector/config/configbase.duration_type\": targetSchema,\n\t\t},\n\t}\n\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: ml,\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"timeout\": {\n\t\t\t\tRef:         \"go.opentelemetry.io/collector/config/configbase.duration_type\",\n\t\t\t\tGoType:      \"time.Duration\",\n\t\t\t\tIsPointer:   true,\n\t\t\t\tIsOptional:  true,\n\t\t\t\tDescription: \"Request timeout for the endpoint\",\n\t\t\t\tDefault:     \"30s\",\n\t\t\t\tEnum:        []any{\"10s\", \"30s\", \"60s\"},\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, result.Properties[\"timeout\"])\n\n\ttimeout := result.Properties[\"timeout\"]\n\t// GoType should be preserved from the referencing node\n\trequire.Equal(t, \"time.Duration\", timeout.GoType)\n\t// IsPointer should be preserved\n\trequire.True(t, timeout.IsPointer)\n\t// IsOptional should be preserved\n\trequire.True(t, timeout.IsOptional)\n\t// Description should come from the referencing node, not the target\n\trequire.Equal(t, \"Request timeout for the endpoint\", timeout.Description)\n\t// Default should be preserved\n\trequire.NotNil(t, timeout.Default)\n\trequire.Equal(t, \"30s\", timeout.Default)\n\t// Enum should be preserved\n\trequire.Equal(t, []any{\"10s\", \"30s\", \"60s\"}, timeout.Enum)\n\t// Type should come from the resolved schema\n\trequire.Equal(t, \"string\", timeout.Type)\n}\n\nfunc TestResolver_ResolveSchema_RefWithoutCustomExtensions(t *testing.T) {\n\t// When a node has a $ref but NO custom extensions, the resolved schema's\n\t// values should be used as-is (no overriding).\n\n\ttargetSchema := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tDefs: map[string]*ConfigMetadata{\n\t\t\t\"base_config\": {\n\t\t\t\tType:        \"object\",\n\t\t\t\tDescription: \"Base configuration from the target schema\",\n\t\t\t\tGoType:      \"BaseConfig\",\n\t\t\t},\n\t\t},\n\t}\n\n\tml := &mockLoader{\n\t\tschemas: map[string]*ConfigMetadata{\n\t\t\t\"go.opentelemetry.io/collector/config/configbase.base_config\": targetSchema,\n\t\t},\n\t}\n\n\tresolver := &Resolver{\n\t\tpkgID:  \"go.opentelemetry.io/collector/test/component\",\n\t\tclass:  \"receiver\",\n\t\tname:   \"test\",\n\t\tloader: ml,\n\t}\n\n\tsrc := &ConfigMetadata{\n\t\tType: \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"base\": {\n\t\t\t\tRef: \"go.opentelemetry.io/collector/config/configbase.base_config\",\n\t\t\t\t// No custom extensions set\n\t\t\t},\n\t\t},\n\t}\n\n\tresult, err := resolver.ResolveSchema(src)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, result.Properties[\"base\"])\n\n\tbase := result.Properties[\"base\"]\n\t// Values should come from the resolved target\n\trequire.Equal(t, \"object\", base.Type)\n\trequire.Equal(t, \"Base configuration from the target schema\", base.Description)\n\trequire.Equal(t, \"BaseConfig\", base.GoType)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/cfggen/type_ref.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage cfggen // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/cfggen\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"path\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/helpers\"\n)\n\n// GoTypeRef represents a fully resolved Go type reference for code generation.\n// It holds the import path and exported type name needed to render a type in generated Go source code.\ntype GoTypeRef struct {\n\t// ImportPath is the full Go import path\n\t// Empty for internal (local $defs) references that need no import.\n\tImportPath string\n\t// TypeName is the exported Go type name\n\tTypeName string\n}\n\n// Qualifier returns the short package name used as a qualifier in Go source.\n// Returns \"\" for internal references (no import needed).\nfunc (r GoTypeRef) Qualifier() string {\n\tif r.ImportPath == \"\" {\n\t\treturn \"\"\n\t}\n\treturn path.Base(r.ImportPath)\n}\n\n// String returns the Go type expression as it would appear in source code,\nfunc (r GoTypeRef) String() string {\n\tif q := r.Qualifier(); q != \"\" {\n\t\treturn q + \".\" + r.TypeName\n\t}\n\treturn r.TypeName\n}\n\n// ResolveGoTypeRef converts a raw metadata reference string into a GoTypeRef.\n//\n// Parameters:\n//   - ref:              raw reference string from metadata\n//   - rootPackage:      module path from the repo-root go.mod\n//   - componentPackage: full Go import path of the component\nfunc ResolveGoTypeRef(ref, rootPackage, componentPackage string) (GoTypeRef, error) {\n\tif ref == \"\" {\n\t\treturn GoTypeRef{}, errors.New(\"empty reference string\")\n\t}\n\n\tcleanRef, _, _ := strings.Cut(ref, \"@\")\n\n\tswitch {\n\tcase strings.HasPrefix(cleanRef, \"/\"):\n\t\treturn resolveLocalAbsolute(cleanRef, rootPackage)\n\tcase strings.HasPrefix(cleanRef, \"./\") || strings.HasPrefix(cleanRef, \"../\"):\n\t\treturn resolveLocalRelative(cleanRef, componentPackage)\n\tcase strings.Contains(cleanRef, \"/\"):\n\t\treturn resolveExternal(cleanRef)\n\tdefault:\n\t\treturn resolveInternal(cleanRef)\n\t}\n}\n\nfunc resolveInternal(ref string) (GoTypeRef, error) {\n\ttypeName, err := helpers.FormatIdentifier(ref, true)\n\tif err != nil {\n\t\treturn GoTypeRef{}, fmt.Errorf(\"failed to format internal type %q: %w\", ref, err)\n\t}\n\treturn GoTypeRef{ImportPath: \"\", TypeName: typeName}, nil\n}\n\nfunc resolveExternal(ref string) (GoTypeRef, error) {\n\tsepIndex := strings.LastIndex(ref, \".\")\n\tif sepIndex == -1 || sepIndex == len(ref)-1 {\n\t\treturn GoTypeRef{}, fmt.Errorf(\"invalid external reference %q: missing type name after last dot\", ref)\n\t}\n\tpkgPath := ref[:sepIndex]\n\trawType := ref[sepIndex+1:]\n\n\ttypeName, err := helpers.FormatIdentifier(rawType, true)\n\tif err != nil {\n\t\treturn GoTypeRef{}, fmt.Errorf(\"failed to format external type %q: %w\", rawType, err)\n\t}\n\treturn GoTypeRef{ImportPath: pkgPath, TypeName: typeName}, nil\n}\n\nfunc resolveLocalAbsolute(ref, rootPackage string) (GoTypeRef, error) {\n\tsepIndex := strings.LastIndex(ref, \".\")\n\tif sepIndex == -1 || sepIndex == len(ref)-1 {\n\t\treturn GoTypeRef{}, fmt.Errorf(\"invalid local absolute reference %q: missing type name after last dot\", ref)\n\t}\n\tlocalPath := ref[:sepIndex]\n\trawType := ref[sepIndex+1:]\n\n\ttypeName, err := helpers.FormatIdentifier(rawType, true)\n\tif err != nil {\n\t\treturn GoTypeRef{}, fmt.Errorf(\"failed to format local type %q: %w\", rawType, err)\n\t}\n\n\timportPath := rootPackage + localPath\n\treturn GoTypeRef{ImportPath: importPath, TypeName: typeName}, nil\n}\n\nfunc resolveLocalRelative(ref, componentPackage string) (GoTypeRef, error) {\n\tsepIndex := strings.LastIndex(ref, \".\")\n\tif sepIndex == -1 || sepIndex == len(ref)-1 {\n\t\treturn GoTypeRef{}, fmt.Errorf(\"invalid local relative reference %q: missing type name after last dot\", ref)\n\t}\n\trelPath := ref[:sepIndex]\n\trawType := ref[sepIndex+1:]\n\n\ttypeName, err := helpers.FormatIdentifier(rawType, true)\n\tif err != nil {\n\t\treturn GoTypeRef{}, fmt.Errorf(\"failed to format local type %q: %w\", rawType, err)\n\t}\n\n\timportPath := path.Join(componentPackage, relPath)\n\treturn GoTypeRef{ImportPath: importPath, TypeName: typeName}, nil\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/cfggen/type_ref_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage cfggen\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestGoTypeRef_String(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tref      GoTypeRef\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"internal type (no import)\",\n\t\t\tref:      GoTypeRef{ImportPath: \"\", TypeName: \"Target\"},\n\t\t\texpected: \"Target\",\n\t\t},\n\t\t{\n\t\t\tname:     \"external type with package qualifier\",\n\t\t\tref:      GoTypeRef{ImportPath: \"go.opentelemetry.io/collector/config/confighttp\", TypeName: \"ClientConfig\"},\n\t\t\texpected: \"confighttp.ClientConfig\",\n\t\t},\n\t\t{\n\t\t\tname:     \"standard library type\",\n\t\t\tref:      GoTypeRef{ImportPath: \"time\", TypeName: \"Duration\"},\n\t\t\texpected: \"time.Duration\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\trequire.Equal(t, tt.expected, tt.ref.String())\n\t\t})\n\t}\n}\n\nfunc TestGoTypeRef_Qualifier(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tref      GoTypeRef\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"no import path\",\n\t\t\tref:      GoTypeRef{ImportPath: \"\"},\n\t\t\texpected: \"\",\n\t\t},\n\t\t{\n\t\t\tname:     \"nested package\",\n\t\t\tref:      GoTypeRef{ImportPath: \"go.opentelemetry.io/collector/config/confighttp\"},\n\t\t\texpected: \"confighttp\",\n\t\t},\n\t\t{\n\t\t\tname:     \"single segment\",\n\t\t\tref:      GoTypeRef{ImportPath: \"time\"},\n\t\t\texpected: \"time\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\trequire.Equal(t, tt.expected, tt.ref.Qualifier())\n\t\t})\n\t}\n}\n\nfunc TestResolveGoTypeRef_Internal(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tref      string\n\t\texpected GoTypeRef\n\t}{\n\t\t{\n\t\t\tname:     \"simple snake_case name\",\n\t\t\tref:      \"target\",\n\t\t\texpected: GoTypeRef{ImportPath: \"\", TypeName: \"Target\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"multi-word snake_case\",\n\t\t\tref:      \"my_custom_type\",\n\t\t\texpected: GoTypeRef{ImportPath: \"\", TypeName: \"MyCustomType\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"already formatted\",\n\t\t\tref:      \"MyType\",\n\t\t\texpected: GoTypeRef{ImportPath: \"\", TypeName: \"MyType\"},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult, err := ResolveGoTypeRef(tt.ref, \"\", \"\")\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestResolveGoTypeRef_External(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tref      string\n\t\texpected GoTypeRef\n\t}{\n\t\t{\n\t\t\tname: \"full module path\",\n\t\t\tref:  \"go.opentelemetry.io/collector/config/confighttp.client_config\",\n\t\t\texpected: GoTypeRef{\n\t\t\t\tImportPath: \"go.opentelemetry.io/collector/config/confighttp\",\n\t\t\t\tTypeName:   \"ClientConfig\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with version suffix\",\n\t\t\tref:  \"go.opentelemetry.io/collector/scraper/scraperhelper.controller_config@v0.146.0\",\n\t\t\texpected: GoTypeRef{\n\t\t\t\tImportPath: \"go.opentelemetry.io/collector/scraper/scraperhelper\",\n\t\t\t\tTypeName:   \"ControllerConfig\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"github package\",\n\t\t\tref:  \"github.com/example/pkg/subpkg.MyType\",\n\t\t\texpected: GoTypeRef{\n\t\t\t\tImportPath: \"github.com/example/pkg/subpkg\",\n\t\t\t\tTypeName:   \"MyType\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"type name needs formatting\",\n\t\t\tref:  \"github.com/example/pkg.my_type\",\n\t\t\texpected: GoTypeRef{\n\t\t\t\tImportPath: \"github.com/example/pkg\",\n\t\t\t\tTypeName:   \"MyType\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult, err := ResolveGoTypeRef(tt.ref, \"\", \"\")\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestResolveGoTypeRef_LocalAbsolute(t *testing.T) {\n\trootPkg := \"go.opentelemetry.io/collector\"\n\n\ttests := []struct {\n\t\tname     string\n\t\tref      string\n\t\texpected GoTypeRef\n\t}{\n\t\t{\n\t\t\tname: \"repo-relative path\",\n\t\t\tref:  \"/config/confighttp.client_config\",\n\t\t\texpected: GoTypeRef{\n\t\t\t\tImportPath: \"go.opentelemetry.io/collector/config/confighttp\",\n\t\t\t\tTypeName:   \"ClientConfig\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"nested path\",\n\t\t\tref:  \"/scraper/scraperhelper.controller_config\",\n\t\t\texpected: GoTypeRef{\n\t\t\t\tImportPath: \"go.opentelemetry.io/collector/scraper/scraperhelper\",\n\t\t\t\tTypeName:   \"ControllerConfig\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult, err := ResolveGoTypeRef(tt.ref, rootPkg, \"\")\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestResolveGoTypeRef_LocalAbsolute_DifferentRoot(t *testing.T) {\n\trootPkg := \"github.com/open-telemetry/opentelemetry-collector-contrib\"\n\n\tref := \"/receiver/hostmetricsreceiver/internal.scraper_config\"\n\tresult, err := ResolveGoTypeRef(ref, rootPkg, \"\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, GoTypeRef{\n\t\tImportPath: \"github.com/open-telemetry/opentelemetry-collector-contrib/receiver/hostmetricsreceiver/internal\",\n\t\tTypeName:   \"ScraperConfig\",\n\t}, result)\n}\n\nfunc TestResolveGoTypeRef_LocalRelative(t *testing.T) {\n\tcompPkg := \"go.opentelemetry.io/collector/scraper/scraperhelper\"\n\n\ttests := []struct {\n\t\tname     string\n\t\tref      string\n\t\texpected GoTypeRef\n\t}{\n\t\t{\n\t\t\tname: \"relative to component\",\n\t\t\tref:  \"./internal/metadata.metrics_builder\",\n\t\t\texpected: GoTypeRef{\n\t\t\t\tImportPath: \"go.opentelemetry.io/collector/scraper/scraperhelper/internal/metadata\",\n\t\t\t\tTypeName:   \"MetricsBuilder\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"parent directory reference\",\n\t\t\tref:  \"../otherpackage.some_type\",\n\t\t\texpected: GoTypeRef{\n\t\t\t\tImportPath: \"go.opentelemetry.io/collector/scraper/otherpackage\",\n\t\t\t\tTypeName:   \"SomeType\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult, err := ResolveGoTypeRef(tt.ref, \"\", compPkg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestResolveGoTypeRef_Errors(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tref  string\n\t}{\n\t\t{\n\t\t\tname: \"empty reference\",\n\t\t\tref:  \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"external missing type after dot\",\n\t\t\tref:  \"github.com/example/pkg.\",\n\t\t},\n\t\t{\n\t\t\tname: \"local absolute missing type after dot\",\n\t\t\tref:  \"/config/confighttp.\",\n\t\t},\n\t\t{\n\t\t\tname: \"local relative missing type after dot\",\n\t\t\tref:  \"./internal/metadata.\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t_, err := ResolveGoTypeRef(tt.ref, \"root\", \"comp\")\n\t\t\trequire.Error(t, err)\n\t\t})\n\t}\n}\n\nfunc TestResolveGoTypeRef_VersionStripped(t *testing.T) {\n\tref := \"go.opentelemetry.io/collector/config/confighttp.client_config@v0.146.0\"\n\tresult, err := ResolveGoTypeRef(ref, \"\", \"\")\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"go.opentelemetry.io/collector/config/confighttp\", result.ImportPath)\n\trequire.Equal(t, \"ClientConfig\", result.TypeName)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/cfggen/writer.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage cfggen // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/cfggen\"\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\nconst fileName = \"config.schema.json\"\n\n// WriteJSONSchema writes the given ConfigMetadata as a JSON Schema file\n// named \"config.schema.json\" in the specified directory.\nfunc WriteJSONSchema(dir string, md *ConfigMetadata) error {\n\tfilePath := filepath.Join(dir, fileName)\n\tdata, err := md.ToJSON()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn os.WriteFile(filePath, data, 0o600)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/cfggen/writer_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage cfggen\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestWriteJSONSchema(t *testing.T) {\n\tdir := t.TempDir()\n\tmd := &ConfigMetadata{\n\t\tSchema: schemaVersion,\n\t\tType:   \"object\",\n\t\tProperties: map[string]*ConfigMetadata{\n\t\t\t\"endpoint\": {Type: \"string\"},\n\t\t},\n\t}\n\n\terr := WriteJSONSchema(dir, md)\n\trequire.NoError(t, err)\n\n\tcontent, err := os.ReadFile(filepath.Join(dir, fileName)) // #nosec G304\n\trequire.NoError(t, err)\n\trequire.Contains(t, string(content), `\"$schema\"`)\n\trequire.Contains(t, string(content), `\"endpoint\"`)\n}\n\nfunc TestWriteJSONSchema_InvalidDir(t *testing.T) {\n\tmd := &ConfigMetadata{Type: \"object\"}\n\terr := WriteJSONSchema(\"/nonexistent/path/that/does/not/exist\", md)\n\trequire.Error(t, err)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/command.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal\"\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n\t\"go/format\"\n\t\"io/fs\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"runtime/debug\"\n\t\"slices\"\n\t\"sort\"\n\t\"strings\"\n\t\"text/template\"\n\n\t\"github.com/spf13/cobra\"\n\t\"go.yaml.in/yaml/v3\"\n\t\"golang.org/x/text/cases\"\n\t\"golang.org/x/text/language\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/cfggen\"\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/helpers\"\n)\n\nconst (\n\tstatusStart = \"<!-- status autogenerated section -->\"\n\tstatusEnd   = \"<!-- end autogenerated section -->\"\n)\n\nvar nonComponents = []string{\n\t\"cmd\",\n\t\"converter\",\n\t\"pkg\",\n\t\"provider\",\n}\n\nfunc getVersion() (string, error) {\n\t// the second returned value is a boolean, which is true if the binaries are built with module support.\n\tinfo, ok := debug.ReadBuildInfo()\n\tif !ok {\n\t\treturn \"\", errors.New(\"could not read build info\")\n\t}\n\treturn info.Main.Version, nil\n}\n\n// NewCommand constructs a new cobra.Command using the given Settings.\n// Any URIs specified in CollectorSettings.ConfigProviderSettings.ResolverSettings.URIs\n// are considered defaults and will be overwritten by config flags passed as\n// command-line arguments to the executable.\n// At least one Provider must be set.\nfunc NewCommand() (*cobra.Command, error) {\n\tver, err := getVersion()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\trootCmd := &cobra.Command{\n\t\tUse:          \"mdatagen\",\n\t\tVersion:      ver,\n\t\tSilenceUsage: true,\n\t\tArgs:         cobra.ExactArgs(1),\n\t\tRunE: func(_ *cobra.Command, args []string) error {\n\t\t\treturn run(args[0])\n\t\t},\n\t}\n\treturn rootCmd, nil\n}\n\nfunc run(ymlPath string) error {\n\tif ymlPath == \"\" {\n\t\treturn errors.New(\"argument must be metadata.yaml file\")\n\t}\n\tymlPath, err := filepath.Abs(ymlPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get absolute path for %v: %w\", ymlPath, err)\n\t}\n\n\tymlDir := filepath.Dir(ymlPath)\n\tpackageName := filepath.Base(ymlDir)\n\timportRootPath, err := helpers.RootPackage(ymlDir)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to determine import root path: %w\", err)\n\t}\n\n\traw, readErr := os.ReadFile(filepath.Clean(ymlPath))\n\tif readErr != nil {\n\t\treturn fmt.Errorf(\"failed reading %v: %w\", ymlPath, readErr)\n\t}\n\n\tif err = validateYAMLKeyOrder(raw); err != nil {\n\t\treturn fmt.Errorf(\"metadata.yaml ordering check failed: %w\", err)\n\t}\n\n\tmd, err := LoadMetadata(ymlPath)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed loading %v: %w\", ymlPath, err)\n\t}\n\n\ttmplDir := \"templates\"\n\n\tcodeDir := filepath.Join(ymlDir, \"internal\", md.GeneratedPackageName)\n\ttoGenerate := map[string]string{}\n\tif md.Status != nil {\n\t\tif !slices.Contains(nonComponents, md.Status.Class) {\n\t\t\ttoGenerate[filepath.Join(tmplDir, \"status.go.tmpl\")] = filepath.Join(codeDir, \"generated_status.go\")\n\t\t\terr = generateFile(filepath.Join(tmplDir, \"component_test.go.tmpl\"),\n\t\t\t\tfilepath.Join(ymlDir, \"generated_component_test.go\"), md, packageName, importRootPath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t} else {\n\t\t\tif _, err = os.Stat(filepath.Join(codeDir, \"generated_status.go\")); err == nil {\n\t\t\t\terr = os.Remove(filepath.Join(codeDir, \"generated_status.go\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t\tif _, err = os.Stat(filepath.Join(ymlDir, \"generated_component_test.go\")); err == nil {\n\t\t\t\terr = os.Remove(filepath.Join(ymlDir, \"generated_component_test.go\"))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\terr = generateFile(filepath.Join(tmplDir, \"package_test.go.tmpl\"),\n\t\t\tfilepath.Join(ymlDir, \"generated_package_test.go\"), md, packageName, importRootPath)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif _, err = os.Stat(filepath.Join(ymlDir, \"README.md\")); err == nil {\n\t\t\terr = inlineReplace(\n\t\t\t\tfilepath.Join(tmplDir, \"readme.md.tmpl\"),\n\t\t\t\tfilepath.Join(ymlDir, \"README.md\"),\n\t\t\t\tmd, statusStart, statusEnd, md.GeneratedPackageName, importRootPath)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(md.Telemetry.Metrics) != 0 { // if there are telemetry metrics, generate telemetry specific files\n\t\ttestDir := filepath.Join(ymlDir, \"internal\", md.GeneratedPackageName+\"test\")\n\t\tif err = os.MkdirAll(testDir, 0o700); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to create output test directory %q: %w\", codeDir, err)\n\t\t}\n\t\ttoGenerate[filepath.Join(tmplDir, \"telemetry.go.tmpl\")] = filepath.Join(codeDir, \"generated_telemetry.go\")\n\t\ttoGenerate[filepath.Join(tmplDir, \"telemetry_test.go.tmpl\")] = filepath.Join(codeDir, \"generated_telemetry_test.go\")\n\t\ttoGenerate[filepath.Join(tmplDir, \"telemetrytest.go.tmpl\")] = filepath.Join(testDir, \"generated_telemetrytest.go\")\n\t\ttoGenerate[filepath.Join(tmplDir, \"telemetrytest_test.go.tmpl\")] = filepath.Join(testDir, \"generated_telemetrytest_test.go\")\n\t} else {\n\t\tif _, err = os.Stat(filepath.Join(ymlDir, \"generated_telemetry.go\")); err == nil {\n\t\t\terr = os.Remove(filepath.Join(ymlDir, \"generated_telemetry.go\"))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif _, err = os.Stat(filepath.Join(ymlDir, \"generated_telemetry_test.go\")); err == nil {\n\t\t\terr = os.Remove(filepath.Join(ymlDir, \"generated_telemetry_test.go\"))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif _, err = os.Stat(filepath.Join(ymlDir, \"generated_telemetrytest.go\")); err == nil {\n\t\t\terr = os.Remove(filepath.Join(ymlDir, \"generated_telemetrytest.go\"))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif _, err = os.Stat(filepath.Join(ymlDir, \"generated_telemetrytest_test.go\")); err == nil {\n\t\t\terr = os.Remove(filepath.Join(ymlDir, \"generated_telemetrytest_test.go\"))\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\n\tif len(md.Metrics) != 0 || len(md.Telemetry.Metrics) != 0 || len(md.ResourceAttributes) != 0 || len(md.Events) != 0 || len(md.FeatureGates) != 0 { // if there's metrics or internal metrics or events or feature gates, generate documentation for them\n\t\ttoGenerate[filepath.Join(tmplDir, \"documentation.md.tmpl\")] = filepath.Join(ymlDir, \"documentation.md\")\n\t}\n\n\tif len(md.Metrics) > 0 || len(md.Events) > 0 || len(md.ResourceAttributes) > 0 {\n\t\ttestdataDir := filepath.Join(codeDir, \"testdata\")\n\t\tif err = os.MkdirAll(filepath.Join(codeDir, \"testdata\"), 0o700); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to create output directory %q: %w\", testdataDir, err)\n\t\t}\n\n\t\ttoGenerate[filepath.Join(tmplDir, \"testdata\", \"config.yaml.tmpl\")] = filepath.Join(testdataDir, \"config.yaml\")\n\t\ttoGenerate[filepath.Join(tmplDir, \"config.go.tmpl\")] = filepath.Join(codeDir, \"generated_config.go\")\n\t\ttoGenerate[filepath.Join(tmplDir, \"config_test.go.tmpl\")] = filepath.Join(codeDir, \"generated_config_test.go\")\n\t\ttoGenerate[filepath.Join(tmplDir, \"config.schema.yaml.tmpl\")] = filepath.Join(codeDir, \"config.schema.yaml\")\n\t}\n\n\tif len(md.ResourceAttributes) > 0 { // only generate resource files if resource attributes are configured\n\t\ttoGenerate[filepath.Join(tmplDir, \"resource.go.tmpl\")] = filepath.Join(codeDir, \"generated_resource.go\")\n\t\ttoGenerate[filepath.Join(tmplDir, \"resource_test.go.tmpl\")] = filepath.Join(codeDir, \"generated_resource_test.go\")\n\t}\n\n\tif len(md.Metrics) > 0 { // only generate metrics if metrics are present\n\t\ttoGenerate[filepath.Join(tmplDir, \"metrics.go.tmpl\")] = filepath.Join(codeDir, \"generated_metrics.go\")\n\t\ttoGenerate[filepath.Join(tmplDir, \"metrics_test.go.tmpl\")] = filepath.Join(codeDir, \"generated_metrics_test.go\")\n\t}\n\n\tif md.supportsSignal(\"logs\") &&\n\t\t(md.Status.Class == \"receiver\" || md.Status.Class == \"scraper\") {\n\t\ttoGenerate[filepath.Join(tmplDir, \"logs.go.tmpl\")] = filepath.Join(codeDir, \"generated_logs.go\")\n\t\ttoGenerate[filepath.Join(tmplDir, \"logs_test.go.tmpl\")] = filepath.Join(codeDir, \"generated_logs_test.go\")\n\t}\n\n\tif len(md.FeatureGates) > 0 { // only generate feature gates if feature gates are present\n\t\ttoGenerate[filepath.Join(tmplDir, \"feature_gates.go.tmpl\")] = filepath.Join(codeDir, \"generated_feature_gates.go\")\n\t}\n\n\tif len(md.Entities) > 0 && len(md.Metrics) > 0 { // only generate entity metrics if entities are defined\n\t\ttoGenerate[filepath.Join(tmplDir, \"entity_metrics.go.tmpl\")] = filepath.Join(codeDir, \"generated_entity_metrics.go\")\n\t\ttoGenerate[filepath.Join(tmplDir, \"entity_metrics_test.go.tmpl\")] = filepath.Join(codeDir, \"generated_entity_metrics_test.go\")\n\t}\n\n\t// If at least one file to generate, will need the codeDir\n\tif len(toGenerate) > 0 {\n\t\tif err = os.MkdirAll(codeDir, 0o700); err != nil {\n\t\t\treturn fmt.Errorf(\"unable to create output directory %q: %w\", codeDir, err)\n\t\t}\n\t}\n\n\tfor tmpl, dst := range toGenerate {\n\t\tif err := generateFile(tmpl, dst, md, md.GeneratedPackageName, importRootPath); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := generateConfigFiles(md, ymlDir, importRootPath); err != nil {\n\t\treturn fmt.Errorf(\"failed to generate config files: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc getTemplateFuncMap(md Metadata, importRootPath string) template.FuncMap {\n\treturn template.FuncMap{\n\t\t\"publicVar\": func(s string) (string, error) {\n\t\t\treturn helpers.FormatIdentifier(s, true)\n\t\t},\n\t\t\"attributeInfo\": func(an AttributeName) Attribute {\n\t\t\treturn md.Attributes[an]\n\t\t},\n\t\t\"defaultAttributes\": func(ans []AttributeName) []string {\n\t\t\tvar atts []string\n\t\t\tfor _, an := range ans {\n\t\t\t\tif md.Attributes[an].IsNotOptIn() {\n\t\t\t\t\tatts = append(atts, string(md.Attributes[an].Name()))\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn atts\n\t\t},\n\t\t\"requiredAttributes\": func(ans []AttributeName) []string {\n\t\t\tvar atts []string\n\t\t\tfor _, an := range ans {\n\t\t\t\tif md.Attributes[an].IsRequired() {\n\t\t\t\t\tatts = append(atts, string(md.Attributes[an].Name()))\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn atts\n\t\t},\n\t\t\"hasAggregatableAttributes\": func(ans []AttributeName) bool {\n\t\t\tfor _, an := range ans {\n\t\t\t\tif md.Attributes[an].RequirementLevel == AttributeRequirementLevelRecommended ||\n\t\t\t\t\tmd.Attributes[an].RequirementLevel == AttributeRequirementLevelOptIn {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t},\n\t\t\"getEventConditionalAttributes\": func(attrs map[AttributeName]Attribute) []AttributeName {\n\t\t\tseen := make(map[AttributeName]bool)\n\t\t\tused := make([]AttributeName, 0)\n\n\t\t\tfor _, event := range md.Events {\n\t\t\t\tfor _, attribute := range event.Attributes {\n\t\t\t\t\tv, exists := attrs[attribute]\n\t\t\t\t\tif exists && v.IsConditional() && !seen[attribute] {\n\t\t\t\t\t\tused = append(used, attribute)\n\t\t\t\t\t\tseen[attribute] = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tsort.Slice(used, func(i, j int) bool { return string(used[i]) < string(used[j]) })\n\n\t\t\treturn used\n\t\t},\n\t\t\"getMetricConditionalAttributes\": func(attrs map[AttributeName]Attribute) []AttributeName {\n\t\t\tseen := make(map[AttributeName]bool)\n\t\t\tused := make([]AttributeName, 0)\n\n\t\t\tfor _, event := range md.Metrics {\n\t\t\t\tfor _, attribute := range event.Attributes {\n\t\t\t\t\tv, exists := attrs[attribute]\n\t\t\t\t\tif exists && v.IsConditional() && !seen[attribute] {\n\t\t\t\t\t\tused = append(used, attribute)\n\t\t\t\t\t\tseen[attribute] = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tsort.Slice(used, func(i, j int) bool { return string(used[i]) < string(used[j]) })\n\n\t\t\treturn used\n\t\t},\n\t\t\"metricInfo\": func(mn MetricName) Metric {\n\t\t\treturn md.Metrics[mn]\n\t\t},\n\t\t\"eventInfo\": func(en EventName) Event {\n\t\t\treturn md.Events[en]\n\t\t},\n\t\t\"telemetryInfo\": func(mn MetricName) Metric {\n\t\t\treturn md.Telemetry.Metrics[mn]\n\t\t},\n\t\t\"parseImportsRequired\": func(metrics map[MetricName]Metric) bool {\n\t\t\tfor _, m := range metrics {\n\t\t\t\tif m.Data().HasMetricInputType() {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn false\n\t\t},\n\t\t\"stringsJoin\":  strings.Join,\n\t\t\"stringsSplit\": strings.Split,\n\t\t\"userLinks\": func(elems []string) []string {\n\t\t\tresult := make([]string, len(elems))\n\t\t\tfor i, elem := range elems {\n\t\t\t\tif elem == \"open-telemetry/collector-approvers\" {\n\t\t\t\t\tresult[i] = \"[@open-telemetry/collector-approvers](https://github.com/orgs/open-telemetry/teams/collector-approvers)\"\n\t\t\t\t} else {\n\t\t\t\t\tresult[i] = fmt.Sprintf(\"[@%s](https://www.github.com/%s)\", elem, elem)\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn result\n\t\t},\n\t\t\"casesTitle\":  cases.Title(language.English).String,\n\t\t\"toLowerCase\": strings.ToLower,\n\t\t\"toCamelCase\": func(s string) string {\n\t\t\treturn joinCamelCase(strings.Split(s, \"_\"), true)\n\t\t},\n\t\t\"toLowerCamelCase\": func(s string) string {\n\t\t\treturn joinCamelCase(strings.Split(s, \"_\"), false)\n\t\t},\n\t\t\"schemaRef\": func(ref string) string {\n\t\t\treturn cfggen.LocalizeRef(ref, importRootPath)\n\t\t},\n\t\t\"inc\":       func(i int) int { return i + 1 },\n\t\t\"distroURL\": distroURL,\n\t\t\"isExporter\": func() bool {\n\t\t\treturn md.Status.Class == \"exporter\"\n\t\t},\n\t\t\"isProcessor\": func() bool {\n\t\t\treturn md.Status.Class == \"processor\"\n\t\t},\n\t\t\"isReceiver\": func() bool {\n\t\t\treturn md.Status.Class == \"receiver\"\n\t\t},\n\t\t\"isExtension\": func() bool {\n\t\t\treturn md.Status.Class == \"extension\"\n\t\t},\n\t\t\"isConnector\": func() bool {\n\t\t\treturn md.Status.Class == \"connector\"\n\t\t},\n\t\t\"isScraper\": func() bool {\n\t\t\treturn md.Status.Class == \"scraper\"\n\t\t},\n\t\t\"isCommand\": func() bool {\n\t\t\treturn md.Status.Class == \"cmd\"\n\t\t},\n\t\t\"supportsLogs\":               func() bool { return md.supportsSignal(\"logs\") },\n\t\t\"supportsMetrics\":            func() bool { return md.supportsSignal(\"metrics\") },\n\t\t\"supportsTraces\":             func() bool { return md.supportsSignal(\"traces\") },\n\t\t\"supportsProfiles\":           func() bool { return md.supportsSignal(\"profiles\") },\n\t\t\"supportsLogsToLogs\":         func() bool { return md.supportsSignal(\"logs_to_logs\") },\n\t\t\"supportsLogsToMetrics\":      func() bool { return md.supportsSignal(\"logs_to_metrics\") },\n\t\t\"supportsLogsToTraces\":       func() bool { return md.supportsSignal(\"logs_to_traces\") },\n\t\t\"supportsLogsToProfiles\":     func() bool { return md.supportsSignal(\"logs_to_profiles\") },\n\t\t\"supportsMetricsToLogs\":      func() bool { return md.supportsSignal(\"metrics_to_logs\") },\n\t\t\"supportsMetricsToMetrics\":   func() bool { return md.supportsSignal(\"metrics_to_metrics\") },\n\t\t\"supportsMetricsToTraces\":    func() bool { return md.supportsSignal(\"metrics_to_traces\") },\n\t\t\"supportsMetricsToProfiles\":  func() bool { return md.supportsSignal(\"metrics_to_profiles\") },\n\t\t\"supportsTracesToLogs\":       func() bool { return md.supportsSignal(\"traces_to_logs\") },\n\t\t\"supportsTracesToMetrics\":    func() bool { return md.supportsSignal(\"traces_to_metrics\") },\n\t\t\"supportsTracesToTraces\":     func() bool { return md.supportsSignal(\"traces_to_traces\") },\n\t\t\"supportsTracesToProfiles\":   func() bool { return md.supportsSignal(\"traces_to_profiles\") },\n\t\t\"supportsProfilesToLogs\":     func() bool { return md.supportsSignal(\"profiles_to_logs\") },\n\t\t\"supportsProfilesToMetrics\":  func() bool { return md.supportsSignal(\"profiles_to_metrics\") },\n\t\t\"supportsProfilesToTraces\":   func() bool { return md.supportsSignal(\"profiles_to_traces\") },\n\t\t\"supportsProfilesToProfiles\": func() bool { return md.supportsSignal(\"profiles_to_profiles\") },\n\t\t\"expectConsumerError\": func() bool {\n\t\t\treturn md.Tests.ExpectConsumerError\n\t\t},\n\t\t// ParseFS delegates the parsing of the files to `Glob`\n\t\t// which uses the `\\` as a special character.\n\t\t// Meaning on windows based machines, the `\\` needs to be replaced\n\t\t// with a `/` for it to find the file.\n\t}\n}\n\nfunc templatize(tmplFile string, funcMap template.FuncMap) *template.Template {\n\treturn template.Must(\n\t\ttemplate.\n\t\t\tNew(filepath.Base(tmplFile)).\n\t\t\tOption(\"missingkey=error\").\n\t\t\tFuncs(funcMap).\n\t\t\tParseFS(TemplateFS, \"templates/helper.tmpl\", strings.ReplaceAll(tmplFile, \"\\\\\", \"/\")))\n}\n\nfunc executeTemplate(tmplFile string, md Metadata, goPackage, importRootPath string, fns template.FuncMap) ([]byte, error) {\n\ttmpl := templatize(tmplFile, fns)\n\tbuf := bytes.Buffer{}\n\n\tif err := tmpl.Execute(&buf, TemplateContext{Metadata: md, Package: goPackage, ImportRootPath: importRootPath}); err != nil {\n\t\treturn []byte{}, fmt.Errorf(\"failed executing template: %w\", err)\n\t}\n\treturn buf.Bytes(), nil\n}\n\nfunc generateFile(tmplFile, outputFile string, md Metadata, goPackage, importRootPath string) error {\n\treturn generateFileWithFns(tmplFile, outputFile, md, goPackage, importRootPath, getTemplateFuncMap(md, importRootPath))\n}\n\nfunc inlineReplace(tmplFile, outputFile string, md Metadata, start, end, goPackage, importRootPath string) error {\n\tvar readmeContents []byte\n\tvar err error\n\tif readmeContents, err = os.ReadFile(filepath.Clean(outputFile)); err != nil {\n\t\treturn err\n\t}\n\n\tre := regexp.MustCompile(fmt.Sprintf(\"%s[\\\\s\\\\S]*%s\", start, end))\n\tif !re.Match(readmeContents) {\n\t\treturn nil\n\t}\n\n\tif md.GithubProject == \"\" {\n\t\tmd.GithubProject = \"open-telemetry/opentelemetry-collector-contrib\"\n\t}\n\n\tbuf, err := executeTemplate(tmplFile, md, goPackage, importRootPath, getTemplateFuncMap(md, importRootPath))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ts := re.ReplaceAllString(string(readmeContents), string(buf))\n\tif err := os.WriteFile(outputFile, []byte(s), 0o600); err != nil {\n\t\treturn fmt.Errorf(\"failed writing %q: %w\", outputFile, err)\n\t}\n\n\treturn nil\n}\n\nfunc generateFileWithFns(tmplFile, outputFile string, md Metadata, goPackage, importRootPath string, fns template.FuncMap) error {\n\tif err := os.Remove(outputFile); err != nil && !errors.Is(err, fs.ErrNotExist) {\n\t\treturn fmt.Errorf(\"unable to remove generated file %q: %w\", outputFile, err)\n\t}\n\n\tresult, err := executeTemplate(tmplFile, md, goPackage, importRootPath, fns)\n\tif err != nil {\n\t\treturn err\n\t}\n\tvar formatErr error\n\tif strings.HasSuffix(outputFile, \".go\") {\n\t\tif formatted, err := format.Source(result); err == nil {\n\t\t\tresult = formatted\n\t\t} else {\n\t\t\tformatErr = fmt.Errorf(\"failed formatting %s:%w\", outputFile, err)\n\t\t}\n\t}\n\n\tif err := os.WriteFile(outputFile, result, 0o600); err != nil {\n\t\treturn fmt.Errorf(\"failed writing %q: %w\", outputFile, err)\n\t}\n\n\treturn formatErr\n}\n\nfunc validateMappingKeysSorted(root *yaml.Node, path ...string) error {\n\t// unwrap doc\n\tn := root\n\tif n.Kind == yaml.DocumentNode && len(n.Content) > 0 {\n\t\tn = n.Content[0]\n\t}\n\t// follow path\n\tfor _, seg := range path {\n\t\tif n.Kind != yaml.MappingNode {\n\t\t\treturn nil\n\t\t}\n\t\tvar next *yaml.Node\n\t\tfor i := 0; i < len(n.Content); i += 2 {\n\t\t\tif n.Content[i].Value == seg {\n\t\t\t\tnext = n.Content[i+1]\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif next == nil {\n\t\t\treturn nil\n\t\t}\n\t\tn = next\n\t}\n\tif n.Kind != yaml.MappingNode {\n\t\treturn nil\n\t}\n\n\t// collect keys\n\tkeys := make([]string, 0, len(n.Content)/2)\n\tfor i := 0; i < len(n.Content); i += 2 {\n\t\tkeys = append(keys, n.Content[i].Value)\n\t}\n\n\tif !slices.IsSorted(keys) {\n\t\treturn fmt.Errorf(\"%v keys are not sorted: %v\", path, keys)\n\t}\n\treturn nil\n}\n\n// ValidateYAMLKeyOrder checks the sections we care about.\nfunc validateYAMLKeyOrder(raw []byte) error {\n\tvar doc yaml.Node\n\tif err := yaml.Unmarshal(raw, &doc); err != nil {\n\t\treturn err\n\t}\n\tfor _, p := range [][]string{\n\t\t{\"resource_attributes\"},\n\t\t{\"entities\"},\n\t\t{\"attributes\"},\n\t\t{\"metrics\"},\n\t\t{\"events\"},\n\t\t{\"telemetry\", \"metrics\"},\n\t} {\n\t\tif err := validateMappingKeysSorted(&doc, p...); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc generateConfigFiles(md Metadata, mdDir, _ string) error {\n\tif md.Config != nil {\n\t\tresolver := cfggen.NewResolver(md.PackageName, md.Status.Class, md.Type, mdDir)\n\t\tresolvedSchema, err := resolver.ResolveSchema(md.Config)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to resolve config schema: %w\", err)\n\t\t}\n\n\t\terr = cfggen.WriteJSONSchema(mdDir, resolvedSchema)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to write config schema: %w\", err)\n\t\t}\n\n\t\tif err := generateConfigGoStruct(md, mdDir); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to generate config Go struct: %w\", err)\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc generateConfigGoStruct(md Metadata, outputDir string) error {\n\trootPkg, err := helpers.RootPackage(outputDir)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"unable to determine root package: %w\", err)\n\t}\n\n\tpackageName := filepath.Base(outputDir)\n\ttmplFile := filepath.Join(\"templates\", \"config_from_cfggen.go.tmpl\")\n\tdstFile := filepath.Join(outputDir, \"generated_config.go\")\n\n\tfns := cfggen.WithCfgFns(getTemplateFuncMap(md, rootPkg), rootPkg, md.PackageName)\n\treturn generateFileWithFns(tmplFile, dstFile, md, packageName, rootPkg, fns)\n}\n\nfunc joinCamelCase(parts []string, exported bool) string {\n\tcaser := cases.Title(language.English).String\n\tvar result strings.Builder\n\tfor i, part := range parts {\n\t\tif i == 0 && !exported {\n\t\t\tfmt.Fprintf(&result, \"%s\", strings.ToLower(part))\n\t\t} else {\n\t\t\tfmt.Fprintf(&result, \"%s\", caser(part))\n\t\t}\n\t}\n\treturn result.String()\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/command_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"go/parser\"\n\t\"go/token\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/cfggen\"\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc TestNewCommand(t *testing.T) {\n\tcmd, err := NewCommand()\n\trequire.NoError(t, err)\n\n\tassert.NotNil(t, cmd)\n\tassert.IsType(t, &cobra.Command{}, cmd)\n\tassert.Equal(t, \"mdatagen\", cmd.Use)\n\tassert.True(t, cmd.SilenceUsage)\n}\n\nfunc TestCommandNoArgs(t *testing.T) {\n\tcmd, err := NewCommand()\n\trequire.NoError(t, err)\n\n\tcmd.SetArgs([]string{})\n\terr = cmd.Execute()\n\n\trequire.Error(t, err)\n}\n\nfunc TestCommandErrorOutputOnce(t *testing.T) {\n\tcmd, err := NewCommand()\n\trequire.NoError(t, err)\n\n\tvar stderr bytes.Buffer\n\tcmd.SetErr(&stderr)\n\tcmd.SetArgs([]string{\"/nonexistent/path/metadata.yaml\"})\n\n\terr = cmd.Execute()\n\trequire.Error(t, err)\n\tout := stderr.String()\n\trequire.NotEmpty(t, out)\n\n\tmsg := err.Error()\n\tassert.Equal(t, 1, strings.Count(out, msg), out)\n}\n\nfunc TestRunContents(t *testing.T) {\n\ttests := []struct {\n\t\tyml                  string\n\t\twantMetricsGenerated bool\n\t\t// TODO: we should add one more flag for logs builder\n\t\twantEventsGenerated             bool\n\t\twantMetricsContext              bool\n\t\twantLogsGenerated               bool\n\t\twantConfigGenerated             bool\n\t\twantTelemetryGenerated          bool\n\t\twantResourceAttributesGenerated bool\n\t\twantReadmeGenerated             bool\n\t\twantStatusGenerated             bool\n\t\twantComponentTestGenerated      bool\n\t\twantGoleakIgnore                bool\n\t\twantGoleakSkip                  bool\n\t\twantGoleakSetup                 bool\n\t\twantGoleakTeardown              bool\n\t\twantFeatureGatesGenerated       bool\n\t\twantConfigSchemaGenerated       bool\n\t\twantMetricsSchemaYamlGenerated  bool\n\t\twantErr                         bool\n\t\twantOrderErr                    bool\n\t\twantRunErr                      bool\n\t\twantAttributes                  []string\n\t}{\n\t\t{\n\t\t\tyml:     \"invalid.yaml\",\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tyml:          \"unsorted_rattr.yaml\",\n\t\t\twantOrderErr: true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"basic_connector.yaml\",\n\t\t\twantErr:                    false,\n\t\t\twantStatusGenerated:        true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantComponentTestGenerated: true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"basic_receiver.yaml\",\n\t\t\twantErr:                    false,\n\t\t\twantStatusGenerated:        true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantComponentTestGenerated: true,\n\t\t\twantLogsGenerated:          true,\n\t\t},\n\t\t{\n\t\t\tyml:                 \"basic_pkg.yaml\",\n\t\t\twantErr:             false,\n\t\t\twantStatusGenerated: false,\n\t\t\twantReadmeGenerated: true,\n\t\t},\n\t\t{\n\t\t\tyml:                            \"metrics_and_type.yaml\",\n\t\t\twantMetricsGenerated:           true,\n\t\t\twantConfigGenerated:            true,\n\t\t\twantStatusGenerated:            true,\n\t\t\twantReadmeGenerated:            true,\n\t\t\twantComponentTestGenerated:     true,\n\t\t\twantMetricsSchemaYamlGenerated: true,\n\t\t},\n\t\t{\n\t\t\tyml:                             \"resource_attributes_only.yaml\",\n\t\t\twantConfigGenerated:             true,\n\t\t\twantStatusGenerated:             true,\n\t\t\twantResourceAttributesGenerated: true,\n\t\t\twantReadmeGenerated:             true,\n\t\t\twantComponentTestGenerated:      true,\n\t\t\twantLogsGenerated:               true,\n\t\t\twantMetricsSchemaYamlGenerated:  true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"status_only.yaml\",\n\t\t\twantStatusGenerated:        true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantComponentTestGenerated: true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"with_tests_receiver.yaml\",\n\t\t\twantStatusGenerated:        true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantComponentTestGenerated: true,\n\t\t\twantLogsGenerated:          true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"with_tests_exporter.yaml\",\n\t\t\twantStatusGenerated:        true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantComponentTestGenerated: true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"with_tests_processor.yaml\",\n\t\t\twantStatusGenerated:        true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantComponentTestGenerated: true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"with_tests_extension.yaml\",\n\t\t\twantStatusGenerated:        true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantComponentTestGenerated: true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"with_tests_connector.yaml\",\n\t\t\twantStatusGenerated:        true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantComponentTestGenerated: true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"with_tests_profiles_connector.yaml\",\n\t\t\twantStatusGenerated:        true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantComponentTestGenerated: true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"with_goleak_ignores.yaml\",\n\t\t\twantStatusGenerated:        true,\n\t\t\twantGoleakIgnore:           true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantComponentTestGenerated: true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"with_goleak_skip.yaml\",\n\t\t\twantStatusGenerated:        true,\n\t\t\twantGoleakSkip:             true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantComponentTestGenerated: true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"with_goleak_setup.yaml\",\n\t\t\twantStatusGenerated:        true,\n\t\t\twantGoleakSetup:            true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantComponentTestGenerated: true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"with_goleak_teardown.yaml\",\n\t\t\twantStatusGenerated:        true,\n\t\t\twantGoleakTeardown:         true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantComponentTestGenerated: true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"with_telemetry.yaml\",\n\t\t\twantStatusGenerated:        true,\n\t\t\twantTelemetryGenerated:     true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantComponentTestGenerated: true,\n\t\t\twantAttributes:             []string{\"name\"},\n\t\t\twantLogsGenerated:          true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"invalid_telemetry_missing_value_type_for_histogram.yaml\",\n\t\t\twantErr:                    true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantComponentTestGenerated: true,\n\t\t},\n\t\t{\n\t\t\tyml:                            \"async_metric.yaml\",\n\t\t\twantMetricsGenerated:           true,\n\t\t\twantConfigGenerated:            true,\n\t\t\twantStatusGenerated:            true,\n\t\t\twantReadmeGenerated:            true,\n\t\t\twantComponentTestGenerated:     true,\n\t\t\twantMetricsSchemaYamlGenerated: true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"custom_generated_package_name.yaml\",\n\t\t\twantStatusGenerated:        true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantComponentTestGenerated: true,\n\t\t\twantLogsGenerated:          true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"feature_gates.yaml\",\n\t\t\twantStatusGenerated:        true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantComponentTestGenerated: true,\n\t\t\twantFeatureGatesGenerated:  true,\n\t\t},\n\t\t{\n\t\t\tyml:                            \"with_conditional_attribute.yaml\",\n\t\t\twantStatusGenerated:            true,\n\t\t\twantReadmeGenerated:            true,\n\t\t\twantMetricsGenerated:           true,\n\t\t\twantLogsGenerated:              true,\n\t\t\twantConfigGenerated:            true,\n\t\t\twantComponentTestGenerated:     true,\n\t\t\twantMetricsSchemaYamlGenerated: true,\n\t\t},\n\t\t{\n\t\t\tyml:                            \"events/basic_event.yaml\",\n\t\t\twantStatusGenerated:            true,\n\t\t\twantReadmeGenerated:            true,\n\t\t\twantComponentTestGenerated:     true,\n\t\t\twantConfigGenerated:            true,\n\t\t\twantEventsGenerated:            true,\n\t\t\twantLogsGenerated:              true,\n\t\t\twantMetricsSchemaYamlGenerated: true,\n\t\t},\n\t\t{\n\t\t\tyml:                        \"with_config.yaml\",\n\t\t\twantStatusGenerated:        true,\n\t\t\twantReadmeGenerated:        true,\n\t\t\twantLogsGenerated:          true,\n\t\t\twantComponentTestGenerated: true,\n\t\t\twantConfigSchemaGenerated:  true,\n\t\t},\n\t\t{\n\t\t\tyml:        \"with_invalid_config_ref.yaml\",\n\t\t\twantRunErr: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.yml, func(t *testing.T) {\n\t\t\ttmpdir := filepath.Join(t.TempDir(), \"shortname\")\n\t\t\terr := os.MkdirAll(tmpdir, 0o750)\n\t\t\trequire.NoError(t, err)\n\t\t\tymlContent, err := os.ReadFile(filepath.Join(\"testdata\", tt.yml))\n\t\t\trequire.NoError(t, err)\n\t\t\tmetadataFile := filepath.Join(tmpdir, \"metadata.yaml\")\n\t\t\trequire.NoError(t, os.WriteFile(metadataFile, ymlContent, 0o600))\n\t\t\trequire.NoError(t, os.WriteFile(filepath.Join(tmpdir, \"empty.go\"), []byte(\"package shortname\"), 0o600))\n\t\t\trequire.NoError(t, os.WriteFile(filepath.Join(tmpdir, \"go.mod\"), []byte(\"module shortname\"), 0o600))\n\t\t\trequire.NoError(t, os.WriteFile(filepath.Join(tmpdir, \"README.md\"), []byte(`\n<!-- status autogenerated section -->\nfoo\n<!-- end autogenerated section -->`), 0o600))\n\t\t\tmd, err := LoadMetadata(metadataFile)\n\t\t\tif tt.wantErr {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\tgeneratedPackageDir := filepath.Join(\"internal\", md.GeneratedPackageName)\n\t\t\trequire.NoError(t, os.MkdirAll(filepath.Join(tmpdir, generatedPackageDir), 0o700))\n\t\t\trequire.NoError(t, os.WriteFile(filepath.Join(tmpdir, generatedPackageDir, \"generated_status.go\"), []byte(\"status\"), 0o600))\n\t\t\trequire.NoError(t, os.WriteFile(filepath.Join(tmpdir, generatedPackageDir, \"generated_telemetry_test.go\"), []byte(\"test\"), 0o600))\n\t\t\trequire.NoError(t, os.WriteFile(filepath.Join(tmpdir, generatedPackageDir, \"generated_component_test.go\"), []byte(\"test\"), 0o600))\n\n\t\t\terr = run(metadataFile)\n\t\t\tif tt.wantOrderErr {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\trequire.Contains(t, err.Error(), \"metadata.yaml ordering check failed\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif tt.wantRunErr {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\trequire.Contains(t, err.Error(), \"failed to generate config files\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\n\t\t\t// Documentation is generated when any of these features are present\n\t\t\twantDocumentationGenerated := tt.wantFeatureGatesGenerated || tt.wantMetricsGenerated || tt.wantTelemetryGenerated || tt.wantResourceAttributesGenerated || tt.wantEventsGenerated\n\n\t\t\tvar contents []byte\n\t\t\tif tt.wantMetricsGenerated {\n\t\t\t\trequire.FileExists(t, filepath.Join(tmpdir, generatedPackageDir, \"generated_metrics.go\"))\n\t\t\t\trequire.FileExists(t, filepath.Join(tmpdir, generatedPackageDir, \"generated_metrics_test.go\"))\n\t\t\t\trequire.FileExists(t, filepath.Join(tmpdir, \"documentation.md\"))\n\t\t\t\tif len(tt.wantAttributes) > 0 {\n\t\t\t\t\tcontents, err = os.ReadFile(filepath.Clean(filepath.Join(tmpdir, \"documentation.md\")))\n\t\t\t\t\trequire.NoError(t, err)\n\t\t\t\t\tfor _, attr := range tt.wantAttributes {\n\t\t\t\t\t\trequire.Contains(t, string(contents), attr)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcontents, err = os.ReadFile(filepath.Clean(filepath.Join(tmpdir, generatedPackageDir, \"generated_metrics.go\")))\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tif tt.wantMetricsContext {\n\t\t\t\t\trequire.Contains(t, string(contents), \"\\\"context\\\"\")\n\t\t\t\t} else {\n\t\t\t\t\trequire.NotContains(t, string(contents), \"\\\"context\\\"\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trequire.NoFileExists(t, filepath.Join(tmpdir, generatedPackageDir, \"generated_metrics.go\"))\n\t\t\t\trequire.NoFileExists(t, filepath.Join(tmpdir, generatedPackageDir, \"generated_metrics_test.go\"))\n\t\t\t}\n\n\t\t\tif tt.wantLogsGenerated {\n\t\t\t\trequire.FileExists(t, filepath.Join(tmpdir, generatedPackageDir, \"generated_logs.go\"))\n\t\t\t\trequire.FileExists(t, filepath.Join(tmpdir, generatedPackageDir, \"generated_logs_test.go\"))\n\t\t\t} else {\n\t\t\t\trequire.NoFileExists(t, filepath.Join(tmpdir, generatedPackageDir, \"generated_logs.go\"))\n\t\t\t\trequire.NoFileExists(t, filepath.Join(tmpdir, generatedPackageDir, \"generated_logs_test.go\"))\n\t\t\t}\n\n\t\t\tif tt.wantConfigGenerated {\n\t\t\t\trequire.FileExists(t, filepath.Join(tmpdir, generatedPackageDir, \"generated_config.go\"))\n\t\t\t\trequire.FileExists(t, filepath.Join(tmpdir, generatedPackageDir, \"generated_config_test.go\"))\n\t\t\t} else {\n\t\t\t\trequire.NoFileExists(t, filepath.Join(tmpdir, generatedPackageDir, \"generated_config.go\"))\n\t\t\t\trequire.NoFileExists(t, filepath.Join(tmpdir, generatedPackageDir, \"generated_config_test.go\"))\n\t\t\t}\n\n\t\t\tif tt.wantTelemetryGenerated {\n\t\t\t\trequire.FileExists(t, filepath.Join(tmpdir, generatedPackageDir, \"generated_telemetry.go\"))\n\t\t\t\trequire.FileExists(t, filepath.Join(tmpdir, generatedPackageDir, \"generated_telemetry_test.go\"))\n\t\t\t\trequire.FileExists(t, filepath.Join(tmpdir, \"documentation.md\"))\n\t\t\t\tcontents, err = os.ReadFile(filepath.Clean(filepath.Join(tmpdir, generatedPackageDir, \"generated_telemetry.go\")))\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tif tt.wantMetricsContext {\n\t\t\t\t\trequire.Contains(t, string(contents), \"\\\"context\\\"\")\n\t\t\t\t} else {\n\t\t\t\t\trequire.NotContains(t, string(contents), \"\\\"context\\\"\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trequire.NoFileExists(t, filepath.Join(tmpdir, generatedPackageDir, \"generated_telemetry.go\"))\n\t\t\t}\n\n\t\t\tif wantDocumentationGenerated {\n\t\t\t\trequire.FileExists(t, filepath.Join(tmpdir, \"documentation.md\"))\n\t\t\t} else {\n\t\t\t\trequire.NoFileExists(t, filepath.Join(tmpdir, \"documentation.md\"))\n\t\t\t}\n\n\t\t\tif tt.wantStatusGenerated {\n\t\t\t\trequire.FileExists(t, filepath.Join(tmpdir, generatedPackageDir, \"generated_status.go\"))\n\t\t\t} else {\n\t\t\t\trequire.NoFileExists(t, filepath.Join(tmpdir, generatedPackageDir, \"generated_status.go\"))\n\t\t\t}\n\n\t\t\tcontents, err = os.ReadFile(filepath.Clean(filepath.Join(tmpdir, \"README.md\")))\n\t\t\trequire.NoError(t, err)\n\t\t\tif tt.wantReadmeGenerated {\n\t\t\t\trequire.NotContains(t, string(contents), \"foo\")\n\t\t\t} else {\n\t\t\t\trequire.Contains(t, string(contents), \"foo\")\n\t\t\t}\n\n\t\t\tif tt.wantComponentTestGenerated {\n\t\t\t\trequire.FileExists(t, filepath.Join(tmpdir, \"generated_component_test.go\"))\n\t\t\t\tcontents, err = os.ReadFile(filepath.Clean(filepath.Join(tmpdir, \"generated_component_test.go\")))\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.Contains(t, string(contents), \"func Test\")\n\t\t\t\t_, err = parser.ParseFile(token.NewFileSet(), \"\", contents, parser.DeclarationErrors)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.NoFileExists(t, filepath.Join(tmpdir, \"generated_component_test.go\"))\n\t\t\t}\n\n\t\t\trequire.FileExists(t, filepath.Join(tmpdir, \"generated_package_test.go\"))\n\t\t\tcontents, err = os.ReadFile(filepath.Clean(filepath.Join(tmpdir, \"generated_package_test.go\")))\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Contains(t, string(contents), \"func TestMain\")\n\t\t\t_, err = parser.ParseFile(token.NewFileSet(), \"\", contents, parser.DeclarationErrors)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tif tt.wantGoleakSkip {\n\t\t\t\trequire.Contains(t, string(contents), \"skipping goleak test\")\n\t\t\t} else {\n\t\t\t\trequire.NotContains(t, string(contents), \"skipping goleak test\")\n\t\t\t}\n\n\t\t\tif tt.wantGoleakIgnore {\n\t\t\t\trequire.Contains(t, string(contents), \"IgnoreTopFunction\")\n\t\t\t\trequire.Contains(t, string(contents), \"IgnoreAnyFunction\")\n\t\t\t} else {\n\t\t\t\trequire.NotContains(t, string(contents), \"IgnoreTopFunction\")\n\t\t\t\trequire.NotContains(t, string(contents), \"IgnoreAnyFunction\")\n\t\t\t}\n\n\t\t\tif tt.wantGoleakSetup {\n\t\t\t\trequire.Contains(t, string(contents), \"setupFunc\")\n\t\t\t} else {\n\t\t\t\trequire.NotContains(t, string(contents), \"setupFunc\")\n\t\t\t}\n\n\t\t\tif tt.wantGoleakTeardown {\n\t\t\t\trequire.Contains(t, string(contents), \"teardownFunc\")\n\t\t\t} else {\n\t\t\t\trequire.NotContains(t, string(contents), \"teardownFunc\")\n\t\t\t}\n\n\t\t\tif tt.wantConfigSchemaGenerated {\n\t\t\t\trequire.FileExists(t, filepath.Join(tmpdir, \"config.schema.json\"))\n\t\t\t} else {\n\t\t\t\trequire.NoFileExists(t, filepath.Join(tmpdir, \"config.schema.json\"))\n\t\t\t}\n\n\t\t\tschemaYamlPath := filepath.Join(tmpdir, generatedPackageDir, \"config.schema.yaml\")\n\t\t\tif tt.wantMetricsSchemaYamlGenerated {\n\t\t\t\trequire.FileExists(t, schemaYamlPath)\n\t\t\t\tcontents, err = os.ReadFile(filepath.Clean(schemaYamlPath))\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.Contains(t, string(contents), \"# Code generated by mdatagen. DO NOT EDIT.\")\n\t\t\t\trequire.Contains(t, string(contents), \"$defs:\")\n\t\t\t\tif tt.wantMetricsGenerated {\n\t\t\t\t\trequire.Contains(t, string(contents), \"metrics_config:\")\n\t\t\t\t\trequire.Contains(t, string(contents), \"metrics_builder_config:\")\n\t\t\t\t}\n\t\t\t\tif tt.wantEventsGenerated {\n\t\t\t\t\trequire.Contains(t, string(contents), \"events_config:\")\n\t\t\t\t\trequire.Contains(t, string(contents), \"logs_builder_config:\")\n\t\t\t\t}\n\t\t\t\tif tt.wantResourceAttributesGenerated {\n\t\t\t\t\trequire.Contains(t, string(contents), \"resource_attributes_config:\")\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\trequire.NoFileExists(t, schemaYamlPath)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGenerateConfigFiles(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tmd      Metadata\n\t\twantErr bool\n\t\twantGen bool\n\t}{\n\t\t{\n\t\t\tname: \"nil config skips generation\",\n\t\t\tmd: Metadata{\n\t\t\t\tType: \"test\",\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tClass: \"receiver\",\n\t\t\t\t},\n\t\t\t\tConfig: nil,\n\t\t\t},\n\t\t\twantGen: false,\n\t\t},\n\t\t{\n\t\t\tname: \"valid config generates schema file\",\n\t\t\tmd: Metadata{\n\t\t\t\tType:        \"test\",\n\t\t\t\tPackageName: \"shortname\",\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tClass: \"receiver\",\n\t\t\t\t},\n\t\t\t\tConfig: &cfggen.ConfigMetadata{\n\t\t\t\t\tType: \"object\",\n\t\t\t\t},\n\t\t\t},\n\t\t\twantGen: true,\n\t\t},\n\t\t{\n\t\t\tname: \"invalid ref in config causes resolve error\",\n\t\t\tmd: Metadata{\n\t\t\t\tType:        \"test\",\n\t\t\t\tPackageName: \"shortname\",\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tClass: \"receiver\",\n\t\t\t\t},\n\t\t\t\t// A local ref without a definition name fails Validate() inside ResolveSchema\n\t\t\t\tConfig: &cfggen.ConfigMetadata{\n\t\t\t\t\tRef: \"/config/configauth\",\n\t\t\t\t},\n\t\t\t},\n\t\t\twantErr: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\troot := t.TempDir()\n\n\t\t\ttmpdir := filepath.Join(root, \"shortname\")\n\t\t\trequire.NoError(t, os.MkdirAll(tmpdir, 0o700))\n\n\t\t\trequire.NoError(t, os.WriteFile(filepath.Join(root, \"go.mod\"), []byte(\"module testmodule\\n\"), 0o600))\n\t\t\terr := generateConfigFiles(tt.md, tmpdir, \"testmodule\")\n\t\t\tif tt.wantErr {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\tif tt.wantGen {\n\t\t\t\trequire.FileExists(t, filepath.Join(tmpdir, \"config.schema.json\"))\n\t\t\t} else {\n\t\t\t\trequire.NoFileExists(t, filepath.Join(tmpdir, \"config.schema.json\"))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGenerateConfigGoStruct_RootPackageError(t *testing.T) {\n\t// tmpdir has no go.mod in any ancestor, so helpers.RootPackage fails\n\tmd := Metadata{\n\t\tType:        \"test\",\n\t\tPackageName: \"shortname\",\n\t\tStatus:      &Status{Class: \"receiver\"},\n\t\tConfig:      &cfggen.ConfigMetadata{Type: \"object\"},\n\t}\n\terr := generateConfigGoStruct(md, t.TempDir())\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"unable to determine root package\")\n}\n\nfunc TestGenerateConfigFiles_GoStructError(t *testing.T) {\n\t// generateConfigGoStruct fails because tmpdir has no go.mod in any ancestor\n\tmd := Metadata{\n\t\tType:        \"test\",\n\t\tPackageName: \"shortname\",\n\t\tStatus:      &Status{Class: \"receiver\"},\n\t\tConfig:      &cfggen.ConfigMetadata{Type: \"object\"},\n\t}\n\terr := generateConfigFiles(md, t.TempDir(), \"testmodule\")\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"failed to generate config Go struct\")\n}\n\nfunc TestGenerateConfigFiles_WriteError(t *testing.T) {\n\tmd := Metadata{\n\t\tType:        \"test\",\n\t\tPackageName: \"shortname\",\n\t\tStatus: &Status{\n\t\t\tClass: \"receiver\",\n\t\t},\n\t\tConfig: &cfggen.ConfigMetadata{\n\t\t\tType: \"object\",\n\t\t},\n\t}\n\terr := generateConfigFiles(md, \"/nonexistent/path/that/does/not/exist\", \"testmodule\")\n\trequire.Error(t, err)\n\trequire.Contains(t, err.Error(), \"failed to write config schema\")\n}\n\nfunc TestRun(t *testing.T) {\n\ttype args struct {\n\t\tymlPath string\n\t}\n\ttests := []struct {\n\t\tname    string\n\t\targs    args\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:    \"no argument\",\n\t\t\targs:    args{\"\"},\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"no such file\",\n\t\t\targs:    args{\"/no/such/file\"},\n\t\t\twantErr: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := run(tt.args.ymlPath)\n\t\t\tif !tt.wantErr {\n\t\t\t\trequire.NoError(t, err, \"run()\")\n\t\t\t} else {\n\t\t\t\trequire.Error(t, err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestInlineReplace(t *testing.T) {\n\ttests := []struct {\n\t\tname           string\n\t\tmarkdown       string\n\t\toutputFile     string\n\t\tcomponentClass string\n\t\twarnings       []string\n\t\tstability      map[component.StabilityLevel][]string\n\t\tdeprecation    map[string]DeprecationInfo\n\t\tdistros        []string\n\t\tcodeowners     *Codeowners\n\t\tgithubProject  string\n\t}{\n\t\t{\n\t\t\tname: \"readme with empty status\",\n\t\t\tmarkdown: `# Some component\n\n<!-- status autogenerated section -->\n<!-- end autogenerated section -->\n\nSome info about a component\n`,\n\t\t\toutputFile:     \"readme_with_status.md\",\n\t\t\tcomponentClass: \"receiver\",\n\t\t\tdistros:        []string{\"contrib\"},\n\t\t\tgithubProject:  \"open-telemetry/opentelemetry-collector\",\n\t\t},\n\t\t{\n\t\t\tname: \"readme with status for extension\",\n\t\t\tmarkdown: `# Some component\n\n<!-- status autogenerated section -->\n<!-- end autogenerated section -->\n\nSome info about a component\n`,\n\t\t\toutputFile:     \"readme_with_status_extension.md\",\n\t\t\tcomponentClass: \"extension\",\n\t\t\tdistros:        []string{\"contrib\"},\n\t\t},\n\t\t{\n\t\t\tname: \"readme with status for converter\",\n\t\t\tmarkdown: `# Some component\n\n<!-- status autogenerated section -->\n<!-- end autogenerated section -->\n\nSome info about a component\n`,\n\t\t\toutputFile:     \"readme_with_status_converter.md\",\n\t\t\tcomponentClass: \"converter\",\n\t\t\tdistros:        []string{\"contrib\"},\n\t\t},\n\t\t{\n\t\t\tname: \"readme with status for provider\",\n\t\t\tmarkdown: `# Some component\n\n<!-- status autogenerated section -->\n<!-- end autogenerated section -->\n\nSome info about a component\n`,\n\t\t\toutputFile:     \"readme_with_status_provider.md\",\n\t\t\tcomponentClass: \"provider\",\n\t\t\tdistros:        []string{\"contrib\"},\n\t\t},\n\t\t{\n\t\t\tname: \"readme with status with codeowners and seeking new\",\n\t\t\tmarkdown: `# Some component\n\n<!-- status autogenerated section -->\n<!-- end autogenerated section -->\n\nSome info about a component\n`,\n\t\t\toutputFile:     \"readme_with_status_codeowners_and_seeking_new.md\",\n\t\t\tcomponentClass: \"receiver\",\n\t\t\tdistros:        []string{\"contrib\"},\n\t\t\tcodeowners: &Codeowners{\n\t\t\t\tActive:     []string{\"foo\"},\n\t\t\t\tSeekingNew: true,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"readme with status with codeowners and emeritus\",\n\t\t\tmarkdown: `# Some component\n\n<!-- status autogenerated section -->\n<!-- end autogenerated section -->\n\nSome info about a component\n`,\n\t\t\toutputFile:     \"readme_with_status_codeowners_and_emeritus.md\",\n\t\t\tcomponentClass: \"receiver\",\n\t\t\tdistros:        []string{\"contrib\"},\n\t\t\tcodeowners: &Codeowners{\n\t\t\t\tActive:   []string{\"foo\"},\n\t\t\t\tEmeritus: []string{\"bar\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"readme with status with codeowners\",\n\t\t\tmarkdown: `# Some component\n\n<!-- status autogenerated section -->\n<!-- end autogenerated section -->\n\nSome info about a component\n`,\n\t\t\toutputFile:     \"readme_with_status_codeowners.md\",\n\t\t\tcomponentClass: \"receiver\",\n\t\t\tdistros:        []string{\"contrib\"},\n\t\t\tcodeowners: &Codeowners{\n\t\t\t\tActive: []string{\"open-telemetry/collector-approvers\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"readme with status table\",\n\t\t\tmarkdown: `# Some component\n\n<!-- status autogenerated section -->\n| Status                   |           |\n| ------------------------ |-----------|\n<!-- end autogenerated section -->\n\nSome info about a component\n`,\n\t\t\toutputFile:     \"readme_with_status.md\",\n\t\t\tcomponentClass: \"receiver\",\n\t\t\tdistros:        []string{\"contrib\"},\n\t\t\tgithubProject:  \"open-telemetry/opentelemetry-collector\",\n\t\t},\n\t\t{\n\t\t\tname: \"readme with no status\",\n\t\t\tmarkdown: `# Some component\n\nSome info about a component\n`,\n\t\t\toutputFile: \"readme_without_status.md\",\n\t\t\tdistros:    []string{\"contrib\"},\n\t\t},\n\t\t{\n\t\t\tname: \"component with warnings\",\n\t\t\tmarkdown: `# Some component\n\n<!-- status autogenerated section -->\n<!-- end autogenerated section -->\n\nSome info about a component\n### warnings\nSome warning there.\n`,\n\t\t\toutputFile: \"readme_with_warnings.md\",\n\t\t\twarnings:   []string{\"warning1\"},\n\t\t\tdistros:    []string{\"contrib\"},\n\t\t},\n\t\t{\n\t\t\tname: \"readme with multiple signals\",\n\t\t\tmarkdown: `# Some component\n\n<!-- status autogenerated section -->\n<!-- end autogenerated section -->\n\nSome info about a component\n`,\n\t\t\toutputFile: \"readme_with_multiple_signals.md\",\n\t\t\tstability: map[component.StabilityLevel][]string{\n\t\t\t\tcomponent.StabilityLevelBeta:  {\"metrics\"},\n\t\t\t\tcomponent.StabilityLevelAlpha: {\"logs\"},\n\t\t\t},\n\t\t\tdistros: []string{\"contrib\"},\n\t\t},\n\t\t{\n\t\t\tname: \"readme with multiple signals and deprecation\",\n\t\t\tmarkdown: `# Some component\n\n<!-- status autogenerated section -->\n<!-- end autogenerated section -->\n\nSome info about a component\n`,\n\t\t\toutputFile: \"readme_with_multiple_signals_and_deprecation.md\",\n\t\t\tstability: map[component.StabilityLevel][]string{\n\t\t\t\tcomponent.StabilityLevelBeta:       {\"metrics\"},\n\t\t\t\tcomponent.StabilityLevelAlpha:      {\"logs\"},\n\t\t\t\tcomponent.StabilityLevelDeprecated: {\"traces\"},\n\t\t\t},\n\t\t\tdeprecation: DeprecationMap{\n\t\t\t\t\"traces\": DeprecationInfo{\n\t\t\t\t\tDate:      \"2025-02-05\",\n\t\t\t\t\tMigration: \"no migration needed\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tdistros: []string{\"contrib\"},\n\t\t},\n\t\t{\n\t\t\tname: \"readme with cmd class\",\n\t\t\tmarkdown: `# Some component\n\n<!-- status autogenerated section -->\n<!-- end autogenerated section -->\n\nSome info about a component\n`,\n\t\t\toutputFile: \"readme_with_cmd_class.md\",\n\t\t\tstability: map[component.StabilityLevel][]string{\n\t\t\t\tcomponent.StabilityLevelBeta:  {\"metrics\"},\n\t\t\t\tcomponent.StabilityLevelAlpha: {\"logs\"},\n\t\t\t},\n\t\t\tcomponentClass: \"cmd\",\n\t\t\tdistros:        []string{},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tstability := map[component.StabilityLevel][]string{component.StabilityLevelBeta: {\"metrics\"}}\n\t\t\tif len(tt.stability) > 0 {\n\t\t\t\tstability = tt.stability\n\t\t\t}\n\t\t\tmd := Metadata{\n\t\t\t\tGithubProject:   tt.githubProject,\n\t\t\t\tType:            \"foo\",\n\t\t\t\tShortFolderName: \"foo\",\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tDisableCodeCov: true,\n\t\t\t\t\tStability:      stability,\n\t\t\t\t\tDistributions:  tt.distros,\n\t\t\t\t\tClass:          tt.componentClass,\n\t\t\t\t\tWarnings:       tt.warnings,\n\t\t\t\t\tCodeowners:     tt.codeowners,\n\t\t\t\t\tDeprecation:    tt.deprecation,\n\t\t\t\t},\n\t\t\t}\n\t\t\ttmpdir := t.TempDir()\n\n\t\t\treadmeFile := filepath.Join(tmpdir, \"README.md\")\n\t\t\trequire.NoError(t, os.WriteFile(readmeFile, []byte(tt.markdown), 0o600))\n\n\t\t\terr := inlineReplace(\"templates/readme.md.tmpl\", readmeFile, md, statusStart, statusEnd, \"metadata\", \"go.opentelemetry.io/collector\")\n\t\t\trequire.NoError(t, err)\n\n\t\t\trequire.FileExists(t, filepath.Join(tmpdir, \"README.md\"))\n\t\t\tgot, err := os.ReadFile(filepath.Clean(filepath.Join(tmpdir, \"README.md\")))\n\t\t\trequire.NoError(t, err)\n\t\t\tgot = bytes.ReplaceAll(got, []byte(\"\\r\\n\"), []byte(\"\\n\"))\n\t\t\texpected, err := os.ReadFile(filepath.Join(\"testdata\", tt.outputFile))\n\t\t\trequire.NoError(t, err)\n\t\t\texpected = bytes.ReplaceAll(expected, []byte(\"\\r\\n\"), []byte(\"\\n\"))\n\t\t\tfmt.Println(string(got))\n\t\t\tfmt.Println(string(expected))\n\t\t\trequire.Equal(t, string(expected), string(got))\n\t\t})\n\t}\n}\n\nfunc TestGenerateStatusMetadata(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\toutput   string\n\t\tmd       Metadata\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname: \"foo component with beta status\",\n\t\t\tmd: Metadata{\n\t\t\t\tType: \"foo\",\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tStability: map[component.StabilityLevel][]string{\n\t\t\t\t\t\tcomponent.StabilityLevelBeta: {\"metrics\"},\n\t\t\t\t\t},\n\t\t\t\t\tDistributions: []string{\"contrib\"},\n\t\t\t\t\tClass:         \"receiver\",\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"foo\")\n\tScopeName = \"\"\n)\n\nconst (\n\tMetricsStability = component.StabilityLevelBeta\n)\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"foo component with alpha status\",\n\t\t\tmd: Metadata{\n\t\t\t\tType: \"foo\",\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tStability: map[component.StabilityLevel][]string{\n\t\t\t\t\t\tcomponent.StabilityLevelAlpha: {\"metrics\"},\n\t\t\t\t\t},\n\t\t\t\t\tDistributions: []string{\"contrib\"},\n\t\t\t\t\tClass:         \"receiver\",\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"foo\")\n\tScopeName = \"\"\n)\n\nconst (\n\tMetricsStability = component.StabilityLevelAlpha\n)\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"foo component with deprecated type\",\n\t\t\tmd: Metadata{\n\t\t\t\tType:           \"foo\",\n\t\t\t\tDeprecatedType: \"old_foo\",\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tStability: map[component.StabilityLevel][]string{\n\t\t\t\t\t\tcomponent.StabilityLevelBeta: {\"metrics\"},\n\t\t\t\t\t},\n\t\t\t\t\tDistributions: []string{\"contrib\"},\n\t\t\t\t\tClass:         \"receiver\",\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType           = component.MustNewType(\"foo\")\n\tDeprecatedType = component.MustNewType(\"old_foo\")\n\tScopeName      = \"\"\n)\n\nconst (\n\tMetricsStability = component.StabilityLevelBeta\n)\n`,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttmpdir := t.TempDir()\n\t\t\terr := generateFile(\"templates/status.go.tmpl\",\n\t\t\t\tfilepath.Join(tmpdir, \"generated_status.go\"), tt.md, \"metadata\", \"go.opentelemetry.io/collector\")\n\t\t\trequire.NoError(t, err)\n\t\t\tactual, err := os.ReadFile(filepath.Clean(filepath.Join(tmpdir, \"generated_status.go\")))\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, string(actual))\n\t\t})\n\t}\n}\n\nfunc TestGenerateTelemetryMetadata(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\toutput   string\n\t\tmd       Metadata\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname: \"foo component with beta status\",\n\t\t\tmd: Metadata{\n\t\t\t\tType: \"foo\",\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tStability: map[component.StabilityLevel][]string{\n\t\t\t\t\t\tcomponent.StabilityLevelBeta: {\"metrics\"},\n\t\t\t\t\t},\n\t\t\t\t\tDistributions: []string{\"contrib\"},\n\t\t\t\t\tClass:         \"receiver\",\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc Meter(settings component.TelemetrySettings) metric.Meter {\n\treturn settings.MeterProvider.Meter(\"\")\n}\n\nfunc Tracer(settings component.TelemetrySettings) trace.Tracer {\n\treturn settings.TracerProvider.Tracer(\"\")\n}\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"foo component with alpha status\",\n\t\t\tmd: Metadata{\n\t\t\t\tType: \"foo\",\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tStability: map[component.StabilityLevel][]string{\n\t\t\t\t\t\tcomponent.StabilityLevelAlpha: {\"metrics\"},\n\t\t\t\t\t},\n\t\t\t\t\tDistributions: []string{\"contrib\"},\n\t\t\t\t\tClass:         \"receiver\",\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc Meter(settings component.TelemetrySettings) metric.Meter {\n\treturn settings.MeterProvider.Meter(\"\")\n}\n\nfunc Tracer(settings component.TelemetrySettings) trace.Tracer {\n\treturn settings.TracerProvider.Tracer(\"\")\n}\n`,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttmpdir := t.TempDir()\n\t\t\terr := generateFile(\"templates/telemetry.go.tmpl\",\n\t\t\t\tfilepath.Join(tmpdir, \"generated_telemetry.go\"), tt.md, \"metadata\", \"go.opentelemetry.io/collector\")\n\t\t\trequire.NoError(t, err)\n\t\t\tactual, err := os.ReadFile(filepath.Clean(filepath.Join(tmpdir, \"generated_telemetry.go\")))\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, string(actual))\n\t\t})\n\t}\n}\n\nfunc TestGenerateConfigSchema_LocalizesSameRootRefs(t *testing.T) {\n\tenabled := true\n\tmd := Metadata{\n\t\tType: \"foo\",\n\t\tResourceAttributes: map[AttributeName]Attribute{\n\t\t\t\"resource.attr\": {\n\t\t\t\tDescription: \"resource attr\",\n\t\t\t\tEnabledPtr:  &enabled,\n\t\t\t\tFullName:    \"resource.attr\",\n\t\t\t},\n\t\t},\n\t\tEvents: map[EventName]Event{\n\t\t\t\"default.event\": {\n\t\t\t\tSignal: Signal{\n\t\t\t\t\tEnabled:     true,\n\t\t\t\t\tDescription: \"event description\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\ttmpdir := t.TempDir()\n\toutputFile := filepath.Join(tmpdir, \"config.schema.yaml\")\n\terr := generateFile(\"templates/config.schema.yaml.tmpl\", outputFile, md, \"metadata\", \"go.opentelemetry.io/collector\")\n\trequire.NoError(t, err)\n\n\tactual, err := os.ReadFile(filepath.Clean(outputFile))\n\trequire.NoError(t, err)\n\trequire.Contains(t, string(actual), \"$ref: /filter.config\")\n\trequire.NotContains(t, string(actual), \"$ref: go.opentelemetry.io/collector/filter.config\")\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/embedded_templates.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal\"\n\nimport \"embed\"\n\n// TemplateFS ensures that the files needed\n// to generate metadata as an embedded filesystem since\n// `go get` doesn't require these files to be downloaded.\n//\n//go:embed templates/*.tmpl templates/testdata/*.tmpl\nvar TemplateFS embed.FS\n"
  },
  {
    "path": "cmd/mdatagen/internal/embedded_templates_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"io/fs\"\n\t\"path\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestEnsureTemplatesLoaded(t *testing.T) {\n\tt.Parallel()\n\n\tconst (\n\t\trootDir = \"templates\"\n\t)\n\n\tvar (\n\t\ttemplateFiles = map[string]struct{}{\n\t\t\tpath.Join(rootDir, \"component_test.go.tmpl\"):       {},\n\t\t\tpath.Join(rootDir, \"documentation.md.tmpl\"):        {},\n\t\t\tpath.Join(rootDir, \"metrics.go.tmpl\"):              {},\n\t\t\tpath.Join(rootDir, \"metrics_test.go.tmpl\"):         {},\n\t\t\tpath.Join(rootDir, \"logs.go.tmpl\"):                 {},\n\t\t\tpath.Join(rootDir, \"logs_test.go.tmpl\"):            {},\n\t\t\tpath.Join(rootDir, \"resource.go.tmpl\"):             {},\n\t\t\tpath.Join(rootDir, \"resource_test.go.tmpl\"):        {},\n\t\t\tpath.Join(rootDir, \"config.go.tmpl\"):               {},\n\t\t\tpath.Join(rootDir, \"config_test.go.tmpl\"):          {},\n\t\t\tpath.Join(rootDir, \"config.schema.yaml.tmpl\"):      {},\n\t\t\tpath.Join(rootDir, \"package_test.go.tmpl\"):         {},\n\t\t\tpath.Join(rootDir, \"readme.md.tmpl\"):               {},\n\t\t\tpath.Join(rootDir, \"status.go.tmpl\"):               {},\n\t\t\tpath.Join(rootDir, \"telemetry.go.tmpl\"):            {},\n\t\t\tpath.Join(rootDir, \"telemetry_test.go.tmpl\"):       {},\n\t\t\tpath.Join(rootDir, \"testdata\", \"config.yaml.tmpl\"): {},\n\t\t\tpath.Join(rootDir, \"telemetrytest.go.tmpl\"):        {},\n\t\t\tpath.Join(rootDir, \"telemetrytest_test.go.tmpl\"):   {},\n\t\t\tpath.Join(rootDir, \"helper.tmpl\"):                  {},\n\t\t\tpath.Join(rootDir, \"feature_gates.md.tmpl\"):        {},\n\t\t\tpath.Join(rootDir, \"feature_gates.go.tmpl\"):        {},\n\t\t\tpath.Join(rootDir, \"config_from_cfggen.go.tmpl\"):   {},\n\t\t\tpath.Join(rootDir, \"entity_metrics.go.tmpl\"):       {},\n\t\t\tpath.Join(rootDir, \"entity_metrics_test.go.tmpl\"):  {},\n\t\t}\n\t\tcount = 0\n\t)\n\trequire.NoError(t, fs.WalkDir(TemplateFS, \".\", func(path string, d fs.DirEntry, _ error) error {\n\t\tif d != nil && d.IsDir() {\n\t\t\treturn nil\n\t\t}\n\t\tcount++\n\t\tassert.Contains(t, templateFiles, path)\n\t\treturn nil\n\t}))\n\tassert.Equal(t, len(templateFiles), count, \"Must match the expected number of calls\")\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/event.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal\"\n\nimport (\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/helpers\"\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\ntype (\n\tEventName string\n)\n\nfunc (ln EventName) Render() (string, error) {\n\treturn helpers.FormatIdentifier(string(ln), true)\n}\n\nfunc (ln EventName) RenderUnexported() (string, error) {\n\treturn helpers.FormatIdentifier(string(ln), false)\n}\n\ntype Event struct {\n\tSignal `mapstructure:\",squash\"`\n}\n\nfunc (l *Event) validate() error {\n\tvar errs error\n\tif l.Description == \"\" {\n\t\terrs = errors.Join(errs, errors.New(`missing event description`))\n\t}\n\treturn errs\n}\n\nfunc (l *Event) Unmarshal(parser *confmap.Conf) error {\n\tif !parser.IsSet(\"enabled\") {\n\t\treturn errors.New(\"missing required field: `enabled`\")\n\t}\n\treturn parser.Unmarshal(l)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/event_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestEventNameRender(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname               EventName\n\t\tsuccess            bool\n\t\texpectedExported   string\n\t\texpectedUnExported string\n\t}{\n\t\t{\"\", false, \"\", \"\"},\n\t\t{\"otel.val\", true, \"OtelVal\", \"otelVal\"},\n\t\t{\"otel_val_2\", true, \"OtelVal2\", \"otelVal2\"},\n\t} {\n\t\texported, err := tt.name.Render()\n\t\tif tt.success {\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tt.expectedExported, exported)\n\t\t} else {\n\t\t\trequire.Error(t, err)\n\t\t}\n\n\t\tunexported, err := tt.name.RenderUnexported()\n\t\tif tt.success {\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tt.expectedUnExported, unexported)\n\t\t} else {\n\t\t\trequire.Error(t, err)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/helpers/lint.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage helpers // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/helpers\"\n\nimport (\n\t\"errors\"\n\t\"strings\"\n\t\"unicode\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/third_party/golint\"\n)\n\n// FormatIdentifier variable in a go-safe way\nfunc FormatIdentifier(s string, exported bool) (string, error) {\n\tif s == \"\" {\n\t\treturn \"\", errors.New(\"string cannot be empty\")\n\t}\n\t// Convert various characters to . for strings.Title to operate on.\n\treplace := strings.NewReplacer(\"_\", \".\", \"-\", \".\", \"<\", \".\", \">\", \".\", \"/\", \".\", \":\", \".\")\n\tstr := replace.Replace(s)\n\tstr = strings.Title(str) //nolint:staticcheck // SA1019\n\tstr = strings.ReplaceAll(str, \".\", \"\")\n\n\tvar word string\n\tvar output string\n\n\t// Fixup acronyms to make lint happy.\n\tfor idx, r := range str {\n\t\tif idx == 0 {\n\t\t\tif exported {\n\t\t\t\tr = unicode.ToUpper(r)\n\t\t\t} else {\n\t\t\t\tr = unicode.ToLower(r)\n\t\t\t}\n\t\t}\n\n\t\tif unicode.IsUpper(r) || unicode.IsNumber(r) {\n\t\t\t// If the current word is an acronym and it's either exported or it's not the\n\t\t\t// beginning of an unexported variable then upper case it.\n\t\t\tif golint.Acronyms[strings.ToUpper(word)] && (exported || output != \"\") {\n\t\t\t\toutput += strings.ToUpper(word)\n\t\t\t\tword = string(r)\n\t\t\t} else {\n\t\t\t\toutput += word\n\t\t\t\tword = string(r)\n\t\t\t}\n\t\t} else {\n\t\t\tword += string(r)\n\t\t}\n\t}\n\n\tif golint.Acronyms[strings.ToUpper(word)] && output != \"\" {\n\t\toutput += strings.ToUpper(word)\n\t} else {\n\t\toutput += word\n\t}\n\n\t// Remove white spaces\n\toutput = strings.Join(strings.Fields(output), \"\")\n\n\treturn output, nil\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/helpers/lint_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage helpers\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestFormatIdentifier(t *testing.T) {\n\ttests := []struct {\n\t\tinput    string\n\t\twant     string\n\t\texported bool\n\t\twantErr  string\n\t}{\n\t\t// Unexported.\n\t\t{input: \"max.cpu\", want: \"maxCPU\"},\n\t\t{input: \"max.foo\", want: \"maxFoo\"},\n\t\t{input: \"cpu.utilization\", want: \"cpuUtilization\"},\n\t\t{input: \"cpu\", want: \"cpu\"},\n\t\t{input: \"max.ip.addr\", want: \"maxIPAddr\"},\n\t\t{input: \"some_metric\", want: \"someMetric\"},\n\t\t{input: \"some-metric\", want: \"someMetric\"},\n\t\t{input: \"Upper.Case\", want: \"upperCase\"},\n\t\t{input: \"max.ip6\", want: \"maxIP6\"},\n\t\t{input: \"max.ip6.idle\", want: \"maxIP6Idle\"},\n\t\t{input: \"node_netstat_IpExt_OutOctets\", want: \"nodeNetstatIPExtOutOctets\"},\n\n\t\t// Exported.\n\t\t{input: \"cpu.state\", want: \"CPUState\", exported: true},\n\n\t\t// Errors\n\t\t{input: \"\", want: \"\", wantErr: \"string cannot be empty\"},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.input, func(t *testing.T) {\n\t\t\tgot, err := FormatIdentifier(tt.input, tt.exported)\n\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\trequire.EqualError(t, err, tt.wantErr)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.Equal(t, tt.want, got)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/helpers/packages.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage helpers // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/helpers\"\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n)\n\n// RootPackage determines the root Go module path by finding the highest go.mod above componentDir\n// and running \"go list -m\" in that directory. This is used to resolve local absolute references\n// (e.g., \"/config/confighttp.client_config\") into full Go import paths.\nfunc RootPackage(componentDir string) (string, error) {\n\trootModDir, err := rootModuleDir(componentDir)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tcmd := exec.Command(\"go\", \"list\", \"-m\")\n\tcmd.Dir = rootModDir\n\toutput, err := cmd.Output()\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to resolve root module path: %w\", err)\n\t}\n\treturn strings.TrimSpace(string(output)), nil\n}\n\nfunc rootModuleDir(componentDir string) (string, error) {\n\tabsDir, err := filepath.Abs(componentDir)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"failed to get absolute path: %w\", err)\n\t}\n\n\tvar found string\n\tdir := absDir\n\tfor {\n\t\tif _, err := os.Stat(filepath.Join(dir, \"go.mod\")); err == nil {\n\t\t\tfound = dir\n\t\t}\n\t\tparent := filepath.Dir(dir)\n\t\tif parent == dir {\n\t\t\tbreak\n\t\t}\n\t\tdir = parent\n\t}\n\n\tif found == \"\" {\n\t\treturn \"\", fmt.Errorf(\"no go.mod found in any parent of %s\", componentDir)\n\t}\n\treturn found, nil\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/helpers/packages_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage helpers\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestRootModuleDir(t *testing.T) {\n\tt.Run(\"finds_go_mod_in_parent\", func(t *testing.T) {\n\t\ttmp := t.TempDir()\n\t\tsubDir := filepath.Join(tmp, \"sub\")\n\t\trequire.NoError(t, os.MkdirAll(subDir, 0o700))\n\n\t\trequire.NoError(t, os.WriteFile(filepath.Join(tmp, \"go.mod\"), []byte(\"module example.com/root\\n\"), 0o600))\n\n\t\tdir, err := rootModuleDir(subDir)\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, tmp, dir)\n\t})\n\n\tt.Run(\"finds_go_mod_in_intermediate_directory\", func(t *testing.T) {\n\t\ttmp := t.TempDir()\n\t\tprojectDir := filepath.Join(tmp, \"project\")\n\t\tcomponentDir := filepath.Join(projectDir, \"receiver\", \"foo\")\n\t\trequire.NoError(t, os.MkdirAll(componentDir, 0o700))\n\n\t\t// No go.mod at tmp root; go.mod is in project/ subdirectory\n\t\trequire.NoError(t, os.WriteFile(filepath.Join(projectDir, \"go.mod\"), []byte(\"module example.com/project\\n\"), 0o600))\n\n\t\tdir, err := rootModuleDir(componentDir)\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, projectDir, dir)\n\t})\n\n\tt.Run(\"prefers_highest_go_mod\", func(t *testing.T) {\n\t\ttmp := t.TempDir()\n\t\tcomponentDir := filepath.Join(tmp, \"project\", \"receiver\", \"foo\")\n\t\trequire.NoError(t, os.MkdirAll(componentDir, 0o700))\n\n\t\t// go.mod at both levels\n\t\trequire.NoError(t, os.WriteFile(filepath.Join(tmp, \"go.mod\"), []byte(\"module example.com/root\\n\"), 0o600))\n\t\trequire.NoError(t, os.WriteFile(filepath.Join(tmp, \"project\", \"go.mod\"), []byte(\"module example.com/project\\n\"), 0o600))\n\n\t\tdir, err := rootModuleDir(componentDir)\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, tmp, dir)\n\t})\n\n\tt.Run(\"error_when_no_go_mod_found\", func(t *testing.T) {\n\t\ttmp := t.TempDir()\n\t\tsubDir := filepath.Join(tmp, \"sub\")\n\t\trequire.NoError(t, os.MkdirAll(subDir, 0o700))\n\n\t\t_, err := rootModuleDir(subDir)\n\t\trequire.Error(t, err)\n\t\tassert.Contains(t, err.Error(), \"no go.mod found\")\n\t})\n}\n\nfunc TestRootPackage(t *testing.T) {\n\tt.Run(\"returns_correct_module_path\", func(t *testing.T) {\n\t\twd, err := os.Getwd()\n\t\trequire.NoError(t, err)\n\n\t\tpkg, err := RootPackage(wd)\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, \"go.opentelemetry.io/collector\", pkg)\n\t})\n\n\tt.Run(\"error_for_nonexistent_directory\", func(t *testing.T) {\n\t\t_, err := RootPackage(\"/nonexistent/path/that/does/not/exist\")\n\t\trequire.Error(t, err)\n\t})\n\n\tt.Run(\"resolves_module_from_synthetic_go_mod\", func(t *testing.T) {\n\t\ttmp := t.TempDir()\n\t\tsubDir := filepath.Join(tmp, \"pkg\", \"foo\")\n\t\trequire.NoError(t, os.MkdirAll(subDir, 0o700))\n\n\t\trequire.NoError(t, os.WriteFile(\n\t\t\tfilepath.Join(tmp, \"go.mod\"),\n\t\t\t[]byte(\"module example.com/my-project\\n\\ngo 1.21\\n\"),\n\t\t\t0o600,\n\t\t))\n\n\t\tpkg, err := RootPackage(subDir)\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, \"example.com/my-project\", pkg)\n\t})\n\n\tt.Run(\"monorepo_go_mod_not_at_top_level\", func(t *testing.T) {\n\t\ttmp := t.TempDir()\n\t\tprojectDir := filepath.Join(tmp, \"collector\")\n\t\tcomponentDir := filepath.Join(projectDir, \"receiver\", \"foo\")\n\t\trequire.NoError(t, os.MkdirAll(componentDir, 0o700))\n\n\t\t// No go.mod at top level; only in collector/ subdirectory\n\t\trequire.NoError(t, os.WriteFile(\n\t\t\tfilepath.Join(projectDir, \"go.mod\"),\n\t\t\t[]byte(\"module go.opentelemetry.io/collector\\n\\ngo 1.21\\n\"),\n\t\t\t0o600,\n\t\t))\n\n\t\tpkg, err := RootPackage(componentDir)\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, \"go.opentelemetry.io/collector\", pkg)\n\t})\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/loader.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/confmap/provider/fileprovider\"\n)\n\nfunc setAttributeDefaultFields(attrs map[AttributeName]Attribute) {\n\tfor k, v := range attrs {\n\t\tv.FullName = k\n\t\tif v.RequirementLevel == \"\" {\n\t\t\tv.RequirementLevel = AttributeRequirementLevelRecommended\n\t\t}\n\t\tattrs[k] = v\n\t}\n}\n\ntype TemplateContext struct {\n\tMetadata\n\t// Package name for generated code.\n\tPackage string\n\t// ImportRootPath is the repo-local import prefix used to localize same-tree schema references.\n\tImportRootPath string\n}\n\nfunc LoadMetadata(filePath string) (Metadata, error) {\n\tcp, err := fileprovider.NewFactory().Create(confmaptest.NewNopProviderSettings()).Retrieve(context.Background(), \"file:\"+filePath, nil)\n\tif err != nil {\n\t\treturn Metadata{}, err\n\t}\n\n\tconf, err := cp.AsConf()\n\tif err != nil {\n\t\treturn Metadata{}, err\n\t}\n\n\tmd := Metadata{ShortFolderName: shortFolderName(filePath), Tests: Tests{Host: \"newMdatagenNopHost()\"}}\n\terr = conf.Unmarshal(&md)\n\tif err != nil {\n\t\treturn md, err\n\t}\n\tpackageName, err := packageName(filepath.Dir(filePath))\n\tif err != nil {\n\t\treturn md, fmt.Errorf(\"unable to determine package name: %w\", err)\n\t}\n\tmd.PackageName = packageName\n\n\tif md.ScopeName == \"\" {\n\t\tmd.ScopeName = packageName\n\t}\n\tif md.GeneratedPackageName == \"\" {\n\t\tmd.GeneratedPackageName = \"metadata\"\n\t}\n\n\tif err := md.Validate(); err != nil {\n\t\treturn md, err\n\t}\n\n\tsetAttributeDefaultFields(md.Attributes)\n\tsetAttributeDefaultFields(md.ResourceAttributes)\n\n\treturn md, nil\n}\n\nvar componentTypes = []string{\n\t\"connector\",\n\t\"exporter\",\n\t\"extension\",\n\t\"processor\",\n\t\"scraper\",\n\t\"receiver\",\n}\n\nfunc shortFolderName(filePath string) string {\n\tparentFolder := filepath.Base(filepath.Dir(filePath))\n\tfor _, cType := range componentTypes {\n\t\tif before, ok := strings.CutSuffix(parentFolder, cType); ok {\n\t\t\treturn before\n\t\t}\n\t}\n\treturn parentFolder\n}\n\nfunc packageName(filePath string) (string, error) {\n\tcmd := exec.Command(\"go\", \"list\", \"-f\", \"{{.ImportPath}}\")\n\tcmd.Dir = filePath\n\toutput, err := cmd.Output()\n\tif err != nil {\n\t\tvar ee *exec.ExitError\n\t\tif errors.As(err, &ee) {\n\t\t\treturn \"\", fmt.Errorf(\"unable to determine package name: %v failed: (stderr) %v\", cmd.Args, string(ee.Stderr))\n\t\t}\n\n\t\treturn \"\", fmt.Errorf(\"unable to determine package name: %v failed: %v %w\", cmd.Args, string(output), err)\n\t}\n\treturn strings.TrimSpace(string(output)), nil\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/loader_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/cfggen\"\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\nfunc boolPtr(b bool) *bool {\n\treturn &b\n}\n\nfunc TestTwoPackagesInDirectory(t *testing.T) {\n\tcontents, err := os.ReadFile(\"testdata/twopackages.yaml\")\n\trequire.NoError(t, err)\n\ttempDir := t.TempDir()\n\tmetadataPath := filepath.Join(tempDir, \"metadata.yaml\")\n\t// we create a trivial module and packages to avoid having invalid go checked into our test directory.\n\trequire.NoError(t, os.WriteFile(filepath.Join(tempDir, \"go.mod\"), []byte(\"module twopackages\"), 0o600))\n\trequire.NoError(t, os.WriteFile(filepath.Join(tempDir, \"package1.go\"), []byte(\"package package1\"), 0o600))\n\trequire.NoError(t, os.WriteFile(filepath.Join(tempDir, \"package2.go\"), []byte(\"package package2\"), 0o600))\n\trequire.NoError(t, os.WriteFile(metadataPath, contents, 0o600))\n\n\t_, err = LoadMetadata(metadataPath)\n\trequire.Error(t, err)\n\trequire.ErrorContains(t, err, \"unable to determine package name: [go list -f {{.ImportPath}}] failed: (stderr) found packages package1 (package1.go) and package2 (package2.go)\")\n}\n\nfunc TestLoadMetadata(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\twant    Metadata\n\t\twantErr string\n\t}{\n\t\t{\n\t\t\tname: \"samplereceiver/metadata.yaml\",\n\t\t\twant: Metadata{\n\t\t\t\tGithubProject:        \"open-telemetry/opentelemetry-collector\",\n\t\t\t\tGeneratedPackageName: \"metadata\",\n\t\t\t\tType:                 \"sample\",\n\t\t\t\tDisplayName:          \"Sample Receiver\",\n\t\t\t\tDescription:          \"This receiver is used for testing purposes to check the output of mdatagen.\",\n\t\t\t\tSemConvVersion:       \"1.38.0\",\n\t\t\t\tPackageName:          \"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplereceiver\",\n\t\t\t\tReaggregationEnabled: true,\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tDisableCodeCov: true,\n\t\t\t\t\tClass:          \"receiver\",\n\t\t\t\t\tStability: map[component.StabilityLevel][]string{\n\t\t\t\t\t\tcomponent.StabilityLevelDevelopment: {\"logs\"},\n\t\t\t\t\t\tcomponent.StabilityLevelBeta:        {\"traces\"},\n\t\t\t\t\t\tcomponent.StabilityLevelStable:      {\"metrics\"},\n\t\t\t\t\t\tcomponent.StabilityLevelDeprecated:  {\"profiles\"},\n\t\t\t\t\t},\n\t\t\t\t\tDistributions: []string{},\n\t\t\t\t\tDeprecation: DeprecationMap{\n\t\t\t\t\t\t\"profiles\": DeprecationInfo{\n\t\t\t\t\t\t\tDate:      \"2025-02-05\",\n\t\t\t\t\t\t\tMigration: \"no migration needed\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tCodeowners: &Codeowners{\n\t\t\t\t\t\tActive: []string{\"dmitryax\"},\n\t\t\t\t\t},\n\t\t\t\t\tWarnings:             []string{\"Any additional information that should be brought to the consumer's attention\"},\n\t\t\t\t\tUnsupportedPlatforms: []string{\"freebsd\", \"illumos\"},\n\t\t\t\t},\n\t\t\t\tConfig: &cfggen.ConfigMetadata{\n\t\t\t\t\tType: \"object\",\n\t\t\t\t\tAllOf: []*cfggen.ConfigMetadata{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tRef: \"./internal/metadata.metrics_builder_config\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tProperties: map[string]*cfggen.ConfigMetadata{\n\t\t\t\t\t\t\"endpoint\": {\n\t\t\t\t\t\t\tDescription: \"The endpoint to scrape metrics from.\",\n\t\t\t\t\t\t\tType:        \"string\",\n\t\t\t\t\t\t\tDefault:     \"localhost:12345\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"timeout\": {\n\t\t\t\t\t\t\tDescription: \"Timeout for scraping metrics.\",\n\t\t\t\t\t\t\tType:        \"string\",\n\t\t\t\t\t\t\tFormat:      \"duration\",\n\t\t\t\t\t\t\tDefault:     \"10s\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tRequired: []string{\"endpoint\"},\n\t\t\t\t},\n\t\t\t\tResourceAttributes: map[AttributeName]Attribute{\n\t\t\t\t\t\"string.resource.attr\": {\n\t\t\t\t\t\tDescription: \"Resource attribute with any string value.\",\n\t\t\t\t\t\tEnabledPtr:  boolPtr(true),\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeStr,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"string.resource.attr\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelRecommended,\n\t\t\t\t\t},\n\t\t\t\t\t\"string.enum.resource.attr\": {\n\t\t\t\t\t\tDescription: \"Resource attribute with a known set of string values.\",\n\t\t\t\t\t\tEnabledPtr:  boolPtr(true),\n\t\t\t\t\t\tEnum:        []string{\"one\", \"two\"},\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeStr,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"string.enum.resource.attr\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelRecommended,\n\t\t\t\t\t},\n\t\t\t\t\t\"optional.resource.attr\": {\n\t\t\t\t\t\tDescription: \"Explicitly disabled ResourceAttribute.\",\n\t\t\t\t\t\tEnabledPtr:  boolPtr(false),\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeStr,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"optional.resource.attr\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelRecommended,\n\t\t\t\t\t},\n\t\t\t\t\t\"slice.resource.attr\": {\n\t\t\t\t\t\tDescription: \"Resource attribute with a slice value.\",\n\t\t\t\t\t\tEnabledPtr:  boolPtr(true),\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeSlice,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"slice.resource.attr\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelRecommended,\n\t\t\t\t\t},\n\t\t\t\t\t\"map.resource.attr\": {\n\t\t\t\t\t\tDescription: \"Resource attribute with a map value.\",\n\t\t\t\t\t\tEnabledPtr:  boolPtr(true),\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeMap,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"map.resource.attr\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelRecommended,\n\t\t\t\t\t},\n\t\t\t\t\t\"string.resource.attr_disable_warning\": {\n\t\t\t\t\t\tDescription: \"Resource attribute with any string value.\",\n\t\t\t\t\t\tWarnings: Warnings{\n\t\t\t\t\t\t\tIfEnabledNotSet: \"This resource_attribute will be disabled by default soon.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tEnabledPtr: boolPtr(true),\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeStr,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"string.resource.attr_disable_warning\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelRecommended,\n\t\t\t\t\t},\n\t\t\t\t\t\"string.resource.attr_remove_warning\": {\n\t\t\t\t\t\tDescription: \"Resource attribute with any string value.\",\n\t\t\t\t\t\tWarnings: Warnings{\n\t\t\t\t\t\t\tIfConfigured: \"This resource_attribute is deprecated and will be removed soon.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tEnabledPtr: boolPtr(false),\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeStr,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"string.resource.attr_remove_warning\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelRecommended,\n\t\t\t\t\t},\n\t\t\t\t\t\"string.resource.attr_to_be_removed\": {\n\t\t\t\t\t\tDescription: \"Resource attribute with any string value.\",\n\t\t\t\t\t\tWarnings: Warnings{\n\t\t\t\t\t\t\tIfEnabled: \"This resource_attribute is deprecated and will be removed soon.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tEnabledPtr: boolPtr(true),\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeStr,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"string.resource.attr_to_be_removed\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelRecommended,\n\t\t\t\t\t},\n\t\t\t\t},\n\n\t\t\t\tAttributes: map[AttributeName]Attribute{\n\t\t\t\t\t\"enum_attr\": {\n\t\t\t\t\t\tDescription:  \"Attribute with a known set of string values.\",\n\t\t\t\t\t\tNameOverride: \"\",\n\t\t\t\t\t\tEnum:         []string{\"red\", \"green\", \"blue\"},\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeStr,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"enum_attr\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelRecommended,\n\t\t\t\t\t},\n\t\t\t\t\t\"string_attr\": {\n\t\t\t\t\t\tDescription:  \"Attribute with any string value.\",\n\t\t\t\t\t\tNameOverride: \"\",\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeStr,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"string_attr\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelRecommended,\n\t\t\t\t\t},\n\t\t\t\t\t\"overridden_int_attr\": {\n\t\t\t\t\t\tDescription:  \"Integer attribute with overridden name.\",\n\t\t\t\t\t\tNameOverride: \"state\",\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeInt,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"overridden_int_attr\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelRecommended,\n\t\t\t\t\t},\n\t\t\t\t\t\"boolean_attr\": {\n\t\t\t\t\t\tDescription: \"Attribute with a boolean value.\",\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeBool,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"boolean_attr\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelRecommended,\n\t\t\t\t\t},\n\t\t\t\t\t\"boolean_attr2\": {\n\t\t\t\t\t\tDescription: \"Another attribute with a boolean value.\",\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeBool,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"boolean_attr2\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelRecommended,\n\t\t\t\t\t},\n\t\t\t\t\t\"slice_attr\": {\n\t\t\t\t\t\tDescription: \"Attribute with a slice value.\",\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeSlice,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"slice_attr\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelRecommended,\n\t\t\t\t\t},\n\t\t\t\t\t\"map_attr\": {\n\t\t\t\t\t\tDescription: \"Attribute with a map value.\",\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeMap,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"map_attr\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelRecommended,\n\t\t\t\t\t},\n\t\t\t\t\t\"conditional_int_attr\": {\n\t\t\t\t\t\tDescription: \"A conditional attribute with an integer value\",\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeInt,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"conditional_int_attr\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelConditionallyRequired,\n\t\t\t\t\t},\n\t\t\t\t\t\"conditional_string_attr\": {\n\t\t\t\t\t\tDescription: \"A conditional attribute with any string value\",\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeStr,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"conditional_string_attr\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelConditionallyRequired,\n\t\t\t\t\t},\n\t\t\t\t\t\"opt_in_bool_attr\": {\n\t\t\t\t\t\tDescription: \"An opt-in attribute with a boolean value\",\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeBool,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"opt_in_bool_attr\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelOptIn,\n\t\t\t\t\t},\n\t\t\t\t\t\"required_string_attr\": {\n\t\t\t\t\t\tDescription: \"A required attribute with a string value\",\n\t\t\t\t\t\tType: ValueType{\n\t\t\t\t\t\t\tValueType: pcommon.ValueTypeStr,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tFullName:         \"required_string_attr\",\n\t\t\t\t\t\tRequirementLevel: AttributeRequirementLevelRequired,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tMetrics: map[MetricName]Metric{\n\t\t\t\t\t\"default.metric\": {\n\t\t\t\t\t\tSignal: Signal{\n\t\t\t\t\t\t\tEnabled:               true,\n\t\t\t\t\t\t\tDescription:           \"Monotonic cumulative sum int metric enabled by default.\",\n\t\t\t\t\t\t\tExtendedDocumentation: \"The metric will be become optional soon.\",\n\t\t\t\t\t\t\tStability:             component.StabilityLevelDeprecated,\n\t\t\t\t\t\t\tWarnings: Warnings{\n\t\t\t\t\t\t\t\tIfEnabledNotSet: \"This metric will be disabled by default soon.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tAttributes: []AttributeName{\"string_attr\", \"overridden_int_attr\", \"enum_attr\", \"slice_attr\", \"map_attr\", \"conditional_int_attr\", \"conditional_string_attr\", \"opt_in_bool_attr\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tUnit: strPtr(\"s\"),\n\t\t\t\t\t\tSum: &Sum{\n\t\t\t\t\t\t\tMetricValueType:        MetricValueType{pmetric.NumberDataPointValueTypeInt},\n\t\t\t\t\t\t\tAggregationTemporality: AggregationTemporality{Aggregation: pmetric.AggregationTemporalityCumulative},\n\t\t\t\t\t\t\tMono:                   Mono{Monotonic: true},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tDeprecated: &Deprecated{\n\t\t\t\t\t\t\tSince: \"1.0.0\",\n\t\t\t\t\t\t\tNote:  \"This metric will be removed\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t\"reaggregate.metric\": {\n\t\t\t\t\t\tSignal: Signal{\n\t\t\t\t\t\t\tEnabled:     true,\n\t\t\t\t\t\t\tDescription: \"Metric for testing spatial reaggregation\",\n\t\t\t\t\t\t\tStability:   component.StabilityLevelBeta,\n\t\t\t\t\t\t\tAttributes:  []AttributeName{\"string_attr\", \"boolean_attr\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tUnit: strPtr(\"1\"),\n\t\t\t\t\t\tGauge: &Gauge{\n\t\t\t\t\t\t\tMetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeDouble},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t\"reaggregate.metric.with_required\": {\n\t\t\t\t\t\tSignal: Signal{\n\t\t\t\t\t\t\tEnabled:     true,\n\t\t\t\t\t\t\tDescription: \"Metric for testing spatial reaggregation with required attributes\",\n\t\t\t\t\t\t\tStability:   component.StabilityLevelBeta,\n\t\t\t\t\t\t\tAttributes:  []AttributeName{\"required_string_attr\", \"string_attr\", \"boolean_attr\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tUnit: strPtr(\"1\"),\n\t\t\t\t\t\tGauge: &Gauge{\n\t\t\t\t\t\t\tMetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeDouble},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t\"system.cpu.time\": {\n\t\t\t\t\t\tSignal: Signal{\n\t\t\t\t\t\t\tEnabled:               true,\n\t\t\t\t\t\t\tStability:             component.StabilityLevelBeta,\n\t\t\t\t\t\t\tSemanticConvention:    &SemanticConvention{SemanticConventionRef: \"https://github.com/open-telemetry/semantic-conventions/blob/v1.38.0/docs/system/system-metrics.md#metric-systemcputime\"},\n\t\t\t\t\t\t\tDescription:           \"Monotonic cumulative sum int metric enabled by default.\",\n\t\t\t\t\t\t\tExtendedDocumentation: \"The metric will be become optional soon.\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tUnit: strPtr(\"s\"),\n\t\t\t\t\t\tSum: &Sum{\n\t\t\t\t\t\t\tMetricValueType:        MetricValueType{pmetric.NumberDataPointValueTypeInt},\n\t\t\t\t\t\t\tAggregationTemporality: AggregationTemporality{Aggregation: pmetric.AggregationTemporalityCumulative},\n\t\t\t\t\t\t\tMono:                   Mono{Monotonic: true},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t\"optional.metric\": {\n\t\t\t\t\t\tSignal: Signal{\n\t\t\t\t\t\t\tEnabled:     false,\n\t\t\t\t\t\t\tDescription: \"[DEPRECATED] Gauge double metric disabled by default.\",\n\t\t\t\t\t\t\tStability:   component.StabilityLevelDeprecated,\n\t\t\t\t\t\t\tWarnings: Warnings{\n\t\t\t\t\t\t\t\tIfConfigured: \"This metric is deprecated and will be removed soon.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tAttributes: []AttributeName{\"string_attr\", \"boolean_attr\", \"boolean_attr2\", \"conditional_string_attr\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tDeprecated: &Deprecated{\n\t\t\t\t\t\t\tSince: \"1.0.0\",\n\t\t\t\t\t\t\tNote:  \"This metric will be removed\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tUnit: strPtr(\"1\"),\n\t\t\t\t\t\tGauge: &Gauge{\n\t\t\t\t\t\t\tMetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeDouble},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t\"optional.metric.empty_unit\": {\n\t\t\t\t\t\tSignal: Signal{\n\t\t\t\t\t\t\tEnabled:     false,\n\t\t\t\t\t\t\tDescription: \"[DEPRECATED] Gauge double metric disabled by default.\",\n\t\t\t\t\t\t\tStability:   component.StabilityLevelDeprecated,\n\t\t\t\t\t\t\tWarnings: Warnings{\n\t\t\t\t\t\t\t\tIfConfigured: \"This metric is deprecated and will be removed soon.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tAttributes: []AttributeName{\"string_attr\", \"boolean_attr\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tDeprecated: &Deprecated{\n\t\t\t\t\t\t\tSince: \"1.0.0\",\n\t\t\t\t\t\t\tNote:  \"This metric will be removed\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tUnit: strPtr(\"\"),\n\t\t\t\t\t\tGauge: &Gauge{\n\t\t\t\t\t\t\tMetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeDouble},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\n\t\t\t\t\t\"default.metric.to_be_removed\": {\n\t\t\t\t\t\tSignal: Signal{\n\t\t\t\t\t\t\tEnabled:               true,\n\t\t\t\t\t\t\tDescription:           \"[DEPRECATED] Non-monotonic delta sum double metric enabled by default.\",\n\t\t\t\t\t\t\tExtendedDocumentation: \"The metric will be removed soon.\",\n\t\t\t\t\t\t\tStability:             component.StabilityLevelDeprecated,\n\t\t\t\t\t\t\tWarnings: Warnings{\n\t\t\t\t\t\t\t\tIfEnabled: \"This metric is deprecated and will be removed soon.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tDeprecated: &Deprecated{\n\t\t\t\t\t\t\tSince: \"1.0.0\",\n\t\t\t\t\t\t\tNote:  \"This metric will be removed\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\tUnit: strPtr(\"s\"),\n\t\t\t\t\t\tSum: &Sum{\n\t\t\t\t\t\t\tMetricValueType:        MetricValueType{pmetric.NumberDataPointValueTypeDouble},\n\t\t\t\t\t\t\tAggregationTemporality: AggregationTemporality{Aggregation: pmetric.AggregationTemporalityDelta},\n\t\t\t\t\t\t\tMono:                   Mono{Monotonic: false},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t\"metric.input_type\": {\n\t\t\t\t\t\tSignal: Signal{\n\t\t\t\t\t\t\tEnabled:     true,\n\t\t\t\t\t\t\tDescription: \"Monotonic cumulative sum int metric with string input_type enabled by default.\",\n\t\t\t\t\t\t\tStability:   component.StabilityLevelDevelopment,\n\t\t\t\t\t\t\tAttributes:  []AttributeName{\"string_attr\", \"overridden_int_attr\", \"enum_attr\", \"slice_attr\", \"map_attr\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tUnit: strPtr(\"s\"),\n\t\t\t\t\t\tSum: &Sum{\n\t\t\t\t\t\t\tMetricValueType:        MetricValueType{pmetric.NumberDataPointValueTypeInt},\n\t\t\t\t\t\t\tMetricInputType:        MetricInputType{InputType: \"string\"},\n\t\t\t\t\t\t\tAggregationTemporality: AggregationTemporality{Aggregation: pmetric.AggregationTemporalityCumulative},\n\t\t\t\t\t\t\tMono:                   Mono{Monotonic: true},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tEvents: map[EventName]Event{\n\t\t\t\t\t\"default.event\": {\n\t\t\t\t\t\tSignal: Signal{\n\t\t\t\t\t\t\tEnabled:     true,\n\t\t\t\t\t\t\tDescription: \"Example event enabled by default.\",\n\t\t\t\t\t\t\tWarnings: Warnings{\n\t\t\t\t\t\t\t\tIfEnabledNotSet: \"This event will be disabled by default soon.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tAttributes: []AttributeName{\"string_attr\", \"overridden_int_attr\", \"enum_attr\", \"slice_attr\", \"map_attr\", \"conditional_int_attr\", \"conditional_string_attr\", \"opt_in_bool_attr\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t\"default.event.to_be_renamed\": {\n\t\t\t\t\t\tSignal: Signal{\n\t\t\t\t\t\t\tEnabled:               false,\n\t\t\t\t\t\t\tDescription:           \"[DEPRECATED] Example event disabled by default.\",\n\t\t\t\t\t\t\tExtendedDocumentation: \"The event will be renamed soon.\",\n\t\t\t\t\t\t\tWarnings: Warnings{\n\t\t\t\t\t\t\t\tIfConfigured: \"This event is deprecated and will be renamed soon.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tAttributes: []AttributeName{\"string_attr\", \"boolean_attr\", \"boolean_attr2\", \"conditional_string_attr\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t\"default.event.to_be_removed\": {\n\t\t\t\t\t\tSignal: Signal{\n\t\t\t\t\t\t\tEnabled:               true,\n\t\t\t\t\t\t\tDescription:           \"[DEPRECATED] Example to-be-removed event enabled by default.\",\n\t\t\t\t\t\t\tExtendedDocumentation: \"The event will be removed soon.\",\n\t\t\t\t\t\t\tWarnings: Warnings{\n\t\t\t\t\t\t\t\tIfEnabled: \"This event is deprecated and will be removed soon.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tAttributes: []AttributeName{\"string_attr\", \"overridden_int_attr\", \"enum_attr\", \"slice_attr\", \"map_attr\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tTelemetry: Telemetry{\n\t\t\t\t\tMetrics: map[MetricName]Metric{\n\t\t\t\t\t\t\"batch_size_trigger_send\": {\n\t\t\t\t\t\t\tSignal: Signal{\n\t\t\t\t\t\t\t\tEnabled:     true,\n\t\t\t\t\t\t\t\tStability:   component.StabilityLevelDeprecated,\n\t\t\t\t\t\t\t\tDescription: \"Number of times the batch was sent due to a size trigger\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tDeprecated: &Deprecated{\n\t\t\t\t\t\t\t\tSince: \"1.5.0\",\n\t\t\t\t\t\t\t\tNote:  \"This metric will be removed in favor of batch_send_trigger_size\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tUnit: strPtr(\"{time}\"),\n\t\t\t\t\t\t\tSum: &Sum{\n\t\t\t\t\t\t\t\tMetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeInt},\n\t\t\t\t\t\t\t\tMono:            Mono{Monotonic: true},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"request_duration\": {\n\t\t\t\t\t\t\tSignal: Signal{\n\t\t\t\t\t\t\t\tEnabled:     true,\n\t\t\t\t\t\t\t\tStability:   component.StabilityLevelAlpha,\n\t\t\t\t\t\t\t\tDescription: \"Duration of request\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tUnit: strPtr(\"s\"),\n\t\t\t\t\t\t\tHistogram: &Histogram{\n\t\t\t\t\t\t\t\tMetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeDouble},\n\t\t\t\t\t\t\t\tBoundaries:      []float64{1, 10, 100},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"process_runtime_total_alloc_bytes\": {\n\t\t\t\t\t\t\tSignal: Signal{\n\t\t\t\t\t\t\t\tEnabled:     true,\n\t\t\t\t\t\t\t\tStability:   component.StabilityLevelStable,\n\t\t\t\t\t\t\t\tDescription: \"Cumulative bytes allocated for heap objects (see 'go doc runtime.MemStats.TotalAlloc')\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tUnit: strPtr(\"By\"),\n\t\t\t\t\t\t\tSum: &Sum{\n\t\t\t\t\t\t\t\tMono: Mono{true},\n\t\t\t\t\t\t\t\tMetricValueType: MetricValueType{\n\t\t\t\t\t\t\t\t\tValueType: pmetric.NumberDataPointValueTypeInt,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tAsync: true,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"queue_length\": {\n\t\t\t\t\t\t\tSignal: Signal{\n\t\t\t\t\t\t\t\tEnabled:               true,\n\t\t\t\t\t\t\t\tStability:             component.StabilityLevelAlpha,\n\t\t\t\t\t\t\t\tDescription:           \"This metric is optional and therefore not initialized in NewTelemetryBuilder.\",\n\t\t\t\t\t\t\t\tExtendedDocumentation: \"For example this metric only exists if feature A is enabled.\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tUnit:     strPtr(\"{item}\"),\n\t\t\t\t\t\t\tOptional: true,\n\t\t\t\t\t\t\tGauge: &Gauge{\n\t\t\t\t\t\t\t\tMetricValueType: MetricValueType{\n\t\t\t\t\t\t\t\t\tValueType: pmetric.NumberDataPointValueTypeInt,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\tAsync: true,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"queue_capacity\": {\n\t\t\t\t\t\t\tSignal: Signal{\n\t\t\t\t\t\t\t\tEnabled:     true,\n\t\t\t\t\t\t\t\tDescription: \"Queue capacity - sync gauge example.\",\n\t\t\t\t\t\t\t\tStability:   component.StabilityLevelDevelopment,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tUnit: strPtr(\"{item}\"),\n\t\t\t\t\t\t\tGauge: &Gauge{\n\t\t\t\t\t\t\t\tMetricValueType: MetricValueType{\n\t\t\t\t\t\t\t\t\tValueType: pmetric.NumberDataPointValueTypeInt,\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tScopeName:       \"go.opentelemetry.io/collector/internal/receiver/samplereceiver\",\n\t\t\t\tShortFolderName: \"sample\",\n\t\t\t\tTests:           Tests{Host: \"newMdatagenNopHost()\"},\n\t\t\t\tFeatureGates: []FeatureGate{\n\t\t\t\t\t{\n\t\t\t\t\t\tID:           \"receiver.sample.featuregate.example\",\n\t\t\t\t\t\tDescription:  \"This is an example feature gate for testing mdatagen code generation.\",\n\t\t\t\t\t\tStage:        \"alpha\",\n\t\t\t\t\t\tFromVersion:  \"v0.100.0\",\n\t\t\t\t\t\tReferenceURL: \"https://github.com/open-telemetry/opentelemetry-collector/issues/12345\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"testdata/parent.yaml\",\n\t\t\twant: Metadata{\n\t\t\t\tType:                 \"subcomponent\",\n\t\t\t\tParent:               \"parentComponent\",\n\t\t\t\tGeneratedPackageName: \"metadata\",\n\t\t\t\tScopeName:            \"go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata\",\n\t\t\t\tPackageName:          \"go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata\",\n\t\t\t\tShortFolderName:      \"testdata\",\n\t\t\t\tTests:                Tests{Host: \"newMdatagenNopHost()\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"testdata/generated_package_name.yaml\",\n\t\t\twant: Metadata{\n\t\t\t\tType:                 \"custom\",\n\t\t\t\tGeneratedPackageName: \"customname\",\n\t\t\t\tScopeName:            \"go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata\",\n\t\t\t\tPackageName:          \"go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata\",\n\t\t\t\tShortFolderName:      \"testdata\",\n\t\t\t\tTests:                Tests{Host: \"newMdatagenNopHost()\"},\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tClass: \"receiver\",\n\t\t\t\t\tStability: map[component.StabilityLevel][]string{\n\t\t\t\t\t\tcomponent.StabilityLevelDevelopment: {\"logs\"},\n\t\t\t\t\t\tcomponent.StabilityLevelBeta:        {\"traces\"},\n\t\t\t\t\t\tcomponent.StabilityLevelStable:      {\"metrics\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"testdata/empty_test_config.yaml\",\n\t\t\twant: Metadata{\n\t\t\t\tType:                 \"test\",\n\t\t\t\tGeneratedPackageName: \"metadata\",\n\t\t\t\tScopeName:            \"go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata\",\n\t\t\t\tPackageName:          \"go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata\",\n\t\t\t\tShortFolderName:      \"testdata\",\n\t\t\t\tTests:                Tests{Host: \"newMdatagenNopHost()\"},\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tClass: \"receiver\",\n\t\t\t\t\tStability: map[component.StabilityLevel][]string{\n\t\t\t\t\t\tcomponent.StabilityLevelBeta: {\"logs\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/invalid_type_rattr.yaml\",\n\t\t\twant:    Metadata{},\n\t\t\twantErr: \"decoding failed due to the following error(s):\\n\\n'resource_attributes[string.resource.attr].type' invalid type: \\\"invalidtype\\\"\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/no_enabled.yaml\",\n\t\t\twant:    Metadata{},\n\t\t\twantErr: \"decoding failed due to the following error(s):\\n\\n'metrics[system.cpu.time]' missing required field: `enabled`\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/events/no_enabled.yaml\",\n\t\t\twant:    Metadata{},\n\t\t\twantErr: \"decoding failed due to the following error(s):\\n\\n'events[system.event]' missing required field: `enabled`\",\n\t\t},\n\t\t{\n\t\t\tname: \"testdata/no_value_type.yaml\",\n\t\t\twant: Metadata{},\n\t\t\twantErr: \"decoding failed due to the following error(s):\\n\\n'metrics[system.cpu.time]' decoding failed due to the following error(s):\\n\\n\" +\n\t\t\t\t\"'sum' missing required field: `value_type`\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/unknown_value_type.yaml\",\n\t\t\twantErr: \"decoding failed due to the following error(s):\\n\\n'metrics[system.cpu.time]' decoding failed due to the following error(s):\\n\\n'sum' decoding failed due to the following error(s):\\n\\n'value_type' invalid value_type: \\\"unknown\\\"\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/invalid_aggregation.yaml\",\n\t\t\twant:    Metadata{},\n\t\t\twantErr: \"decoding failed due to the following error(s):\\n\\n'metrics[default.metric]' decoding failed due to the following error(s):\\n\\n'sum' decoding failed due to the following error(s):\\n\\n'aggregation_temporality' invalid aggregation: \\\"invalidaggregation\\\"\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/invalid_type_attr.yaml\",\n\t\t\twant:    Metadata{},\n\t\t\twantErr: \"decoding failed due to the following error(s):\\n\\n'attributes[used_attr].type' invalid type: \\\"invalidtype\\\"\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/invalid_metric_stability.yaml\",\n\t\t\twant:    Metadata{},\n\t\t\twantErr: \"decoding failed due to the following error(s):\\n\\n'metrics[default.metric]' decoding failed due to the following error(s):\\n\\n'stability' unsupported stability level: \\\"development42\\\"\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/invalid_metric_semconvref.yaml\",\n\t\t\twant:    Metadata{},\n\t\t\twantErr: \"metric \\\"default.metric\\\": invalid semantic-conventions URL: want https://github.com/open-telemetry/semantic-conventions/blob/v1.37.2/*#metric-defaultmetric, got \\\"https://github.com/open-telemetry/semantic-conventions/blob/v1.38.0/docs/system/system-metrics.md#metric-systemcputime\\\"\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/no_metric_stability.yaml\",\n\t\t\twant:    Metadata{},\n\t\t\twantErr: \"metric \\\"default.metric\\\": missing required field: `stability.level`\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/undeprecated_with_deprecation.yaml\",\n\t\t\twant:    Metadata{},\n\t\t\twantErr: \"`stability` must be `deprecated` when specifying a `deprecated` field\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/invalid_config.yaml\",\n\t\t\twant:    Metadata{},\n\t\t\twantErr: \"config type must be \\\"object\\\", got \\\"string\\\"\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/~~this file doesn't exist~~.yaml\",\n\t\t\twantErr: \"unable to read the file file:testdata/~~this file doesn't exist~~.yaml\",\n\t\t},\n\t\t{\n\t\t\tname: \"testdata/display_name.yaml\",\n\t\t\twant: Metadata{\n\t\t\t\tType:                 \"test\",\n\t\t\t\tDisplayName:          \"Test Receiver\",\n\t\t\t\tGeneratedPackageName: \"metadata\",\n\t\t\t\tScopeName:            \"go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata\",\n\t\t\t\tPackageName:          \"go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata\",\n\t\t\t\tShortFolderName:      \"testdata\",\n\t\t\t\tTests:                Tests{Host: \"newMdatagenNopHost()\"},\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tClass: \"receiver\",\n\t\t\t\t\tStability: map[component.StabilityLevel][]string{\n\t\t\t\t\t\tcomponent.StabilityLevelBeta: {\"logs\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"testdata/no_display_name.yaml\",\n\t\t\twant: Metadata{\n\t\t\t\tType:                 \"nodisplayname\",\n\t\t\t\tDisplayName:          \"\",\n\t\t\t\tGeneratedPackageName: \"metadata\",\n\t\t\t\tScopeName:            \"go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata\",\n\t\t\t\tPackageName:          \"go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata\",\n\t\t\t\tShortFolderName:      \"testdata\",\n\t\t\t\tTests:                Tests{Host: \"newMdatagenNopHost()\"},\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tClass: \"receiver\",\n\t\t\t\t\tStability: map[component.StabilityLevel][]string{\n\t\t\t\t\t\tcomponent.StabilityLevelBeta: {\"logs\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"testdata/with_description.yaml\",\n\t\t\twant: Metadata{\n\t\t\t\tType:                 \"testdesc\",\n\t\t\t\tDisplayName:          \"Test Component\",\n\t\t\t\tDescription:          \"This is a test component with a description.\",\n\t\t\t\tGeneratedPackageName: \"metadata\",\n\t\t\t\tScopeName:            \"go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata\",\n\t\t\t\tPackageName:          \"go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata\",\n\t\t\t\tShortFolderName:      \"testdata\",\n\t\t\t\tTests:                Tests{Host: \"newMdatagenNopHost()\"},\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tClass: \"receiver\",\n\t\t\t\t\tStability: map[component.StabilityLevel][]string{\n\t\t\t\t\t\tcomponent.StabilityLevelBeta: {\"logs\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"testdata/with_underscore_in_semconv_ref_anchor_tag.yaml\",\n\t\t\twant: Metadata{\n\t\t\t\tType:                 \"metricreceiver\",\n\t\t\t\tGeneratedPackageName: \"metadata\",\n\t\t\t\tSemConvVersion:       \"1.38.0\",\n\t\t\t\tScopeName:            \"go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata\",\n\t\t\t\tPackageName:          \"go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata\",\n\t\t\t\tShortFolderName:      \"testdata\",\n\t\t\t\tTests:                Tests{Host: \"newMdatagenNopHost()\"},\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tClass: \"receiver\",\n\t\t\t\t\tStability: map[component.StabilityLevel][]string{\n\t\t\t\t\t\tcomponent.StabilityLevelDevelopment: {\"logs\"},\n\t\t\t\t\t\tcomponent.StabilityLevelBeta:        {\"traces\"},\n\t\t\t\t\t\tcomponent.StabilityLevelStable:      {\"metrics\"},\n\t\t\t\t\t},\n\t\t\t\t\tDistributions: []string{\"contrib\"},\n\t\t\t\t\tWarnings:      []string{\"Any additional information that should be brought to the consumer's attention\"},\n\t\t\t\t},\n\t\t\t\tMetrics: map[MetricName]Metric{\n\t\t\t\t\t\"system.disk.io_time\": {\n\t\t\t\t\t\tSignal: Signal{\n\t\t\t\t\t\t\tEnabled:     true,\n\t\t\t\t\t\t\tDescription: \"Time disk spent activated..\",\n\t\t\t\t\t\t\tStability:   component.StabilityLevelDevelopment,\n\t\t\t\t\t\t\tSemanticConvention: &SemanticConvention{\n\t\t\t\t\t\t\t\tSemanticConventionRef: \"https://github.com/open-telemetry/semantic-conventions/blob/v1.38.0/docs/system/system-metrics.md#metric-systemdiskio_time\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tUnit: strPtr(\"s\"),\n\t\t\t\t\t\tSum: &Sum{\n\t\t\t\t\t\t\tAggregationTemporality: AggregationTemporality{Aggregation: pmetric.AggregationTemporalityCumulative},\n\t\t\t\t\t\t\tMono:                   Mono{Monotonic: true},\n\t\t\t\t\t\t\tMetricValueType:        MetricValueType{ValueType: pmetric.NumberDataPointValueTypeDouble},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot, err := LoadMetadata(tt.name)\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\trequire.ErrorContains(t, err, tt.wantErr)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.Equal(t, tt.want, got)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc strPtr(s string) *string {\n\treturn &s\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/metadata.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"slices\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/cfggen\"\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/helpers\"\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/filter\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\ntype Metadata struct {\n\t// Type of the component.\n\tType string `mapstructure:\"type\"`\n\t// DeprecatedType of the component.\n\tDeprecatedType string `mapstructure:\"deprecated_type\"`\n\t// DisplayName is a human-readable display name for the component.\n\tDisplayName string `mapstructure:\"display_name\"`\n\t// Description is a brief description of the component.\n\tDescription string `mapstructure:\"description\"`\n\t// Type of the parent component (applicable to subcomponents).\n\tParent string `mapstructure:\"parent\"`\n\t// Status information for the component.\n\tStatus *Status `mapstructure:\"status\"`\n\t// Spatial Re-aggregation featuregate.\n\tReaggregationEnabled bool `mapstructure:\"reaggregation_enabled\"`\n\t// The name of the package that will be generated.\n\tGeneratedPackageName string `mapstructure:\"generated_package_name\"`\n\t// Telemetry information for the component.\n\tTelemetry Telemetry `mapstructure:\"telemetry\"`\n\t// SemConvVersion is a version number of OpenTelemetry semantic conventions applied to the scraped metrics.\n\tSemConvVersion string `mapstructure:\"sem_conv_version\"`\n\t// ResourceAttributes that can be emitted by the component.\n\tResourceAttributes map[AttributeName]Attribute `mapstructure:\"resource_attributes\"`\n\t// Entities organizes resource attributes into logical entities.\n\tEntities []Entity `mapstructure:\"entities\"`\n\t// Attributes emitted by one or more metrics.\n\tAttributes map[AttributeName]Attribute `mapstructure:\"attributes\"`\n\t// Metrics that can be emitted by the component.\n\tMetrics map[MetricName]Metric `mapstructure:\"metrics\"`\n\t// Events that can be emitted by the component.\n\tEvents map[EventName]Event `mapstructure:\"events\"`\n\t// GithubProject is the project where the component README lives in the format of org/repo, defaults to open-telemetry/opentelemetry-collector-contrib\n\tGithubProject string `mapstructure:\"github_project\"`\n\t// ScopeName of the metrics emitted by the component.\n\tScopeName string `mapstructure:\"scope_name\"`\n\t// ShortFolderName is the shortened folder name of the component, removing class if present\n\tShortFolderName string `mapstructure:\"-\"`\n\t// Tests is the set of tests generated with the component\n\tTests Tests `mapstructure:\"tests\"`\n\t// PackageName is the name of the package where the component is defined.\n\tPackageName string `mapstructure:\"package_name\"`\n\t// FeatureGates that are managed by the component.\n\tFeatureGates []FeatureGate `mapstructure:\"feature_gates\"`\n\t// Config is the configuration schema for the component.\n\tConfig *cfggen.ConfigMetadata `mapstructure:\"config\"`\n}\n\ntype Deprecated struct {\n\tSince string `mapstructure:\"since\"`\n\tNote  string `mapstructure:\"note\"`\n}\n\nfunc (d *Deprecated) validate() error {\n\tif strings.TrimSpace(d.Since) == \"\" {\n\t\treturn errors.New(\"deprecated.since must be set\")\n\t}\n\n\t// NOTE: note is optional, but if present, it must not be empty\n\tif d.Note != \"\" && strings.TrimSpace(d.Note) == \"\" {\n\t\treturn errors.New(\"deprecated.note must not be empty\")\n\t}\n\n\treturn nil\n}\n\nfunc (md Metadata) GetCodeCovComponentID() string {\n\tif md.Status.CodeCovComponentID != \"\" {\n\t\treturn md.Status.CodeCovComponentID\n\t}\n\n\treturn strings.ReplaceAll(md.Status.Class+\"_\"+strings.ReplaceAll(md.Type, \"_\", \"\"), \"/\", \"_\")\n}\n\nfunc (md Metadata) HasEntities() bool {\n\treturn len(md.Entities) > 0\n}\n\nfunc (md *Metadata) Validate() error {\n\tvar errs error\n\tif err := md.validateType(); err != nil {\n\t\terrs = errors.Join(errs, err)\n\t}\n\n\tif md.Parent != \"\" {\n\t\tif md.Status != nil {\n\t\t\t// status is not required for subcomponents.\n\t\t\terrs = errors.Join(errs, errors.New(\"status must be empty for subcomponents\"))\n\t\t}\n\t} else {\n\t\terrs = errors.Join(errs, md.Status.Validate())\n\t}\n\n\tif err := md.validateResourceAttributes(); err != nil {\n\t\terrs = errors.Join(errs, err)\n\t}\n\n\tif err := md.validateEntities(); err != nil {\n\t\terrs = errors.Join(errs, err)\n\t}\n\n\tif err := md.validateMetricsAndEvents(); err != nil {\n\t\terrs = errors.Join(errs, err)\n\t}\n\n\tif err := md.validateFeatureGates(); err != nil {\n\t\terrs = errors.Join(errs, err)\n\t}\n\n\tif err := md.validateConfig(); err != nil {\n\t\terrs = errors.Join(errs, err)\n\t}\n\n\treturn errs\n}\n\n// typeRegexp is used to validate the type of a component.\n// A type must start with an ASCII alphabetic character and\n// can only contain ASCII alphanumeric characters and '_'.\n// We allow '/' for subcomponents.\n// This must be kept in sync with the regex in component/config.go.\nvar typeRegexp = regexp.MustCompile(`^[a-zA-Z][0-9a-zA-Z_]{0,62}$`)\n\nfunc (md *Metadata) validateType() error {\n\tif md.Type == \"\" {\n\t\treturn errors.New(\"missing type\")\n\t}\n\n\tif md.Parent != \"\" {\n\t\t// subcomponents are allowed to have a '/' in their type.\n\t\treturn nil\n\t}\n\n\tif !typeRegexp.MatchString(md.Type) {\n\t\treturn fmt.Errorf(\"invalid character(s) in type %q\", md.Type)\n\t}\n\treturn nil\n}\n\nfunc (md *Metadata) validateResourceAttributes() error {\n\tvar errs error\n\tfor name, attr := range md.ResourceAttributes {\n\t\tif attr.Description == \"\" {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(\"empty description for resource attribute: %v\", name))\n\t\t}\n\t\tempty := ValueType{ValueType: pcommon.ValueTypeEmpty}\n\t\tif attr.Type == empty {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(\"empty type for resource attribute: %v\", name))\n\t\t}\n\t\tif attr.EnabledPtr == nil {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(\"enabled field is required for resource attribute: %v\", name))\n\t\t}\n\t}\n\treturn errs\n}\n\nfunc (md *Metadata) validateEntities() error {\n\tvar errs error\n\tusedAttrs := make(map[AttributeName]string)\n\tseenTypes := make(map[string]bool)\n\n\t// First pass: collect entity types and validate basic entity properties\n\tfor _, entity := range md.Entities {\n\t\tif entity.Type == \"\" {\n\t\t\terrs = errors.Join(errs, errors.New(\"entity type cannot be empty\"))\n\t\t\tcontinue\n\t\t}\n\t\tif seenTypes[entity.Type] {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`duplicate entity type: %v`, entity.Type))\n\t\t}\n\t\tseenTypes[entity.Type] = true\n\n\t\tif entity.Brief == \"\" {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`entity \"%v\": brief is required`, entity.Type))\n\t\t}\n\t\tif len(entity.Identity) == 0 {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`entity \"%v\": identity is required`, entity.Type))\n\t\t}\n\t\tfor _, ref := range entity.Identity {\n\t\t\tif _, ok := md.ResourceAttributes[ref.Ref]; !ok {\n\t\t\t\terrs = errors.Join(errs, fmt.Errorf(`entity \"%v\": identity refers to undefined resource attribute: %v`, entity.Type, ref.Ref))\n\t\t\t}\n\t\t\tif otherEntity, used := usedAttrs[ref.Ref]; used {\n\t\t\t\terrs = errors.Join(errs, fmt.Errorf(`entity \"%v\": attribute %v is already used by entity \"%v\"`, entity.Type, ref.Ref, otherEntity))\n\t\t\t} else {\n\t\t\t\tusedAttrs[ref.Ref] = entity.Type\n\t\t\t}\n\t\t}\n\t\tfor _, ref := range entity.Description {\n\t\t\tif _, ok := md.ResourceAttributes[ref.Ref]; !ok {\n\t\t\t\terrs = errors.Join(errs, fmt.Errorf(`entity \"%v\": description refers to undefined resource attribute: %v`, entity.Type, ref.Ref))\n\t\t\t}\n\t\t\tif otherEntity, used := usedAttrs[ref.Ref]; used {\n\t\t\t\terrs = errors.Join(errs, fmt.Errorf(`entity \"%v\": attribute %v is already used by entity \"%v\"`, entity.Type, ref.Ref, otherEntity))\n\t\t\t} else {\n\t\t\t\tusedAttrs[ref.Ref] = entity.Type\n\t\t\t}\n\t\t}\n\t\tfor _, ref := range entity.ExtraAttributes {\n\t\t\tif _, ok := md.ResourceAttributes[ref.Ref]; !ok {\n\t\t\t\terrs = errors.Join(errs, fmt.Errorf(`entity \"%v\": extra_attributes refers to undefined resource attribute: %v`, entity.Type, ref.Ref))\n\t\t\t}\n\t\t}\n\t}\n\n\t// Second pass: validate relationships\n\tseenRelationships := make(map[string]string)\n\tfor _, entity := range md.Entities {\n\t\tfor _, rel := range entity.Relationships {\n\t\t\tif rel.Type == \"\" {\n\t\t\t\terrs = errors.Join(errs, fmt.Errorf(`entity \"%v\": relationship type cannot be empty`, entity.Type))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif rel.Target == \"\" {\n\t\t\t\terrs = errors.Join(errs, fmt.Errorf(`entity \"%v\": relationship target cannot be empty`, entity.Type))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif !seenTypes[rel.Target] {\n\t\t\t\terrs = errors.Join(errs, fmt.Errorf(`entity \"%v\": relationship target \"%v\" does not exist`, entity.Type, rel.Target))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif seenRelationships[rel.Target] == entity.Type || seenRelationships[entity.Type] == rel.Target {\n\t\t\t\terrs = errors.Join(errs, fmt.Errorf(`entity \"%v\": duplicate relationship to target \"%v\" (only one relationship allowed between two entities)`, entity.Type, rel.Target))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tseenRelationships[rel.Target] = entity.Type\n\t\t\tseenRelationships[entity.Type] = rel.Target\n\t\t}\n\t}\n\treturn errs\n}\n\nfunc (md *Metadata) validateMetricsAndEvents() error {\n\tvar errs error\n\tusedAttrs := map[AttributeName]bool{}\n\terrs = errors.Join(errs,\n\t\tvalidateMetrics(md.Metrics, md.Attributes, usedAttrs, md.SemConvVersion),\n\t\tvalidateMetrics(md.Telemetry.Metrics, md.Attributes, usedAttrs, md.SemConvVersion),\n\t\tvalidateEvents(md.Events, md.Attributes, usedAttrs),\n\t\tmd.validateAttributes(usedAttrs),\n\t\tmd.validateEntityAssociations())\n\treturn errs\n}\n\nfunc (md *Metadata) validateAttributes(usedAttrs map[AttributeName]bool) error {\n\tvar errs error\n\tunusedAttrs := make([]AttributeName, 0, len(md.Attributes))\n\tfor attrName, attr := range md.Attributes {\n\t\tif attr.Description == \"\" {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`missing attribute description for: %v`, attrName))\n\t\t}\n\t\tempty := ValueType{ValueType: pcommon.ValueTypeEmpty}\n\t\tif attr.Type == empty {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(\"empty type for attribute: %v\", attrName))\n\t\t}\n\t\tif attr.EnabledPtr != nil {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(\"enabled field is not allowed for regular attribute: %v\", attrName))\n\t\t}\n\t\tif !usedAttrs[attrName] {\n\t\t\tunusedAttrs = append(unusedAttrs, attrName)\n\t\t}\n\t}\n\tif len(unusedAttrs) > 0 {\n\t\terrs = errors.Join(errs, fmt.Errorf(\"unused attributes: %v\", unusedAttrs))\n\t}\n\treturn errs\n}\n\n// validateEntityAssociations checks that if entities are defined, then each metric and event must be associated with an entity.\nfunc (md *Metadata) validateEntityAssociations() error {\n\tvar errs error\n\trequireEntityAssociation := len(md.Entities) > 0\n\tentityTypes := make(map[string]bool)\n\tfor _, entity := range md.Entities {\n\t\tentityTypes[entity.Type] = true\n\t}\n\n\tfor metricName, metric := range md.Metrics {\n\t\tif requireEntityAssociation && metric.Entity == \"\" {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`metric \"%v\": entity is required when entities are defined`, metricName))\n\t\t}\n\t\tif metric.Entity != \"\" && !entityTypes[metric.Entity] {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`metric \"%v\": entity refers to undefined entity type: %v`, metricName, metric.Entity))\n\t\t}\n\t}\n\n\tfor eventName, event := range md.Events {\n\t\tif requireEntityAssociation && event.Entity == \"\" {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`event \"%v\": entity is required when entities are defined`, eventName))\n\t\t}\n\t\tif event.Entity != \"\" && !entityTypes[event.Entity] {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`event \"%v\": entity refers to undefined entity type: %v`, eventName, event.Entity))\n\t\t}\n\t}\n\n\treturn errs\n}\n\nfunc (md *Metadata) supportsSignal(signal string) bool {\n\tif md.Status == nil {\n\t\treturn false\n\t}\n\n\tfor _, signals := range md.Status.Stability {\n\t\tif slices.Contains(signals, signal) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n\nfunc validateMetrics(metrics map[MetricName]Metric, attributes map[AttributeName]Attribute, usedAttrs map[AttributeName]bool, semConvVersion string) error {\n\tvar errs error\n\tfor mn, m := range metrics {\n\t\tif err := m.validate(mn, semConvVersion); err != nil {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`metric \"%v\": %w`, mn, err))\n\t\t\tcontinue\n\t\t}\n\t\tunknownAttrs := make([]AttributeName, 0, len(m.Attributes))\n\t\tfor _, attr := range m.Attributes {\n\t\t\tif _, ok := attributes[attr]; ok {\n\t\t\t\tusedAttrs[attr] = true\n\t\t\t} else {\n\t\t\t\tunknownAttrs = append(unknownAttrs, attr)\n\t\t\t}\n\t\t}\n\t\tif len(unknownAttrs) > 0 {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`metric \"%v\" refers to undefined attributes: %v`, mn, unknownAttrs))\n\t\t}\n\t}\n\treturn errs\n}\n\nfunc validateEvents(events map[EventName]Event, attributes map[AttributeName]Attribute, usedAttrs map[AttributeName]bool) error {\n\tvar errs error\n\tfor en, e := range events {\n\t\tif err := e.validate(); err != nil {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`event \"%v\": %w`, en, err))\n\t\t\tcontinue\n\t\t}\n\t\tunknownAttrs := make([]AttributeName, 0, len(e.Attributes))\n\t\tfor _, attr := range e.Attributes {\n\t\t\tif _, ok := attributes[attr]; ok {\n\t\t\t\tusedAttrs[attr] = true\n\t\t\t} else {\n\t\t\t\tunknownAttrs = append(unknownAttrs, attr)\n\t\t\t}\n\t\t}\n\t\tif len(unknownAttrs) > 0 {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`event \"%v\" refers to undefined attributes: %v`, en, unknownAttrs))\n\t\t}\n\t}\n\treturn errs\n}\n\nfunc (md *Metadata) validateFeatureGates() error {\n\tvar errs error\n\tseen := make(map[FeatureGateID]bool)\n\tidRegexp := regexp.MustCompile(`^[0-9a-zA-Z.]*$`)\n\n\t// Validate that feature gates are sorted by ID\n\tif !slices.IsSortedFunc(md.FeatureGates, func(a, b FeatureGate) int {\n\t\treturn strings.Compare(string(a.ID), string(b.ID))\n\t}) {\n\t\terrs = errors.Join(errs, errors.New(\"feature gates must be sorted by ID\"))\n\t}\n\n\tfor i, gate := range md.FeatureGates {\n\t\t// Validate gate ID is not empty\n\t\tif string(gate.ID) == \"\" {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(\"feature gate at index %d: ID cannot be empty\", i))\n\t\t\tcontinue\n\t\t}\n\n\t\t// Validate ID follows the allowed character pattern\n\t\tif !idRegexp.MatchString(string(gate.ID)) {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`feature gate \"%v\": ID contains invalid characters, must match ^[0-9a-zA-Z.]*$`, gate.ID))\n\t\t}\n\n\t\t// Check for duplicate IDs\n\t\tif seen[gate.ID] {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`feature gate \"%v\": duplicate ID`, gate.ID))\n\t\t\tcontinue\n\t\t}\n\t\tseen[gate.ID] = true\n\n\t\t// Validate gate has required fields\n\t\tif gate.Description == \"\" {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`feature gate \"%v\": description is required`, gate.ID))\n\t\t}\n\n\t\t// Validate that each feature gate has a reference link\n\t\tif gate.ReferenceURL == \"\" {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`feature gate \"%v\": reference_url is required`, gate.ID))\n\t\t}\n\n\t\t// Validate stage is one of the allowed values\n\t\tvalidStages := map[FeatureGateStage]bool{\n\t\t\tFeatureGateStageAlpha:      true,\n\t\t\tFeatureGateStageBeta:       true,\n\t\t\tFeatureGateStageStable:     true,\n\t\t\tFeatureGateStageDeprecated: true,\n\t\t}\n\t\tif !validStages[gate.Stage] {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`feature gate \"%v\": invalid stage \"%v\", must be one of: alpha, beta, stable, deprecated`, gate.ID, gate.Stage))\n\t\t}\n\n\t\t// Validate from_version is required\n\t\tif gate.FromVersion == \"\" {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`feature gate \"%v\": from_version is required`, gate.ID))\n\t\t} else if !strings.HasPrefix(gate.FromVersion, \"v\") {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`feature gate \"%v\": from_version \"%v\" must start with 'v'`, gate.ID, gate.FromVersion))\n\t\t}\n\t\tif gate.ToVersion != \"\" && !strings.HasPrefix(gate.ToVersion, \"v\") {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`feature gate \"%v\": to_version \"%v\" must start with 'v'`, gate.ID, gate.ToVersion))\n\t\t}\n\n\t\t// Validate that stable/deprecated gates should have to_version\n\t\tif (gate.Stage == FeatureGateStageStable || gate.Stage == FeatureGateStageDeprecated) && gate.ToVersion == \"\" {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(`feature gate \"%v\": to_version is required for %v stage gates`, gate.ID, gate.Stage))\n\t\t}\n\t}\n\treturn errs\n}\n\nfunc (md *Metadata) validateConfig() error {\n\tif md.Config != nil {\n\t\treturn md.Config.Validate()\n\t}\n\treturn nil\n}\n\ntype AttributeName string\n\n// AttributeRequirementLevel defines the requirement level of an attribute.\ntype AttributeRequirementLevel string\n\nconst (\n\t// AttributeRequirementLevelRequired means the attribute is always included and cannot be excluded.\n\tAttributeRequirementLevelRequired AttributeRequirementLevel = \"required\"\n\t// AttributeRequirementLevelConditionallyRequired means the attribute is included by default when certain conditions are met.\n\tAttributeRequirementLevelConditionallyRequired AttributeRequirementLevel = \"conditionally_required\"\n\t// AttributeRequirementLevelRecommended means the attribute is included by default but can be disabled via configuration.\n\tAttributeRequirementLevelRecommended AttributeRequirementLevel = \"recommended\"\n\t// AttributeRequirementLevelOptIn means the attribute is not included unless explicitly enabled in user config.\n\tAttributeRequirementLevelOptIn AttributeRequirementLevel = \"opt_in\"\n)\n\n// String returns capitalized display name of the requirement level for documentation.\nfunc (rl AttributeRequirementLevel) String() string {\n\tswitch rl {\n\tcase AttributeRequirementLevelRequired:\n\t\treturn \"Required\"\n\tcase AttributeRequirementLevelConditionallyRequired:\n\t\treturn \"Conditionally Required\"\n\tcase AttributeRequirementLevelRecommended:\n\t\treturn \"Recommended\"\n\tcase AttributeRequirementLevelOptIn:\n\t\treturn \"Opt-In\"\n\t}\n\treturn \"\"\n}\n\nfunc (mn AttributeName) Render() (string, error) {\n\treturn helpers.FormatIdentifier(string(mn), true)\n}\n\nfunc (mn AttributeName) RenderUnexported() (string, error) {\n\treturn helpers.FormatIdentifier(string(mn), false)\n}\n\n// ValueType defines an attribute value type.\ntype ValueType struct {\n\t// ValueType is type of the attribute value.\n\tValueType pcommon.ValueType\n}\n\n// UnmarshalText implements the encoding.TextUnmarshaler interface.\nfunc (mvt *ValueType) UnmarshalText(text []byte) error {\n\tswitch vtStr := string(text); vtStr {\n\tcase \"string\":\n\t\tmvt.ValueType = pcommon.ValueTypeStr\n\tcase \"int\":\n\t\tmvt.ValueType = pcommon.ValueTypeInt\n\tcase \"double\":\n\t\tmvt.ValueType = pcommon.ValueTypeDouble\n\tcase \"bool\":\n\t\tmvt.ValueType = pcommon.ValueTypeBool\n\tcase \"bytes\":\n\t\tmvt.ValueType = pcommon.ValueTypeBytes\n\tcase \"slice\":\n\t\tmvt.ValueType = pcommon.ValueTypeSlice\n\tcase \"map\":\n\t\tmvt.ValueType = pcommon.ValueTypeMap\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid type: %q\", vtStr)\n\t}\n\treturn nil\n}\n\n// String returns capitalized name of the ValueType.\nfunc (mvt ValueType) String() string {\n\treturn strings.Title(strings.ToLower(mvt.ValueType.String())) //nolint:staticcheck // SA1019\n}\n\n// Primitive returns name of primitive type for the ValueType.\nfunc (mvt ValueType) Primitive() string {\n\tswitch mvt.ValueType {\n\tcase pcommon.ValueTypeStr:\n\t\treturn \"string\"\n\tcase pcommon.ValueTypeInt:\n\t\treturn \"int64\"\n\tcase pcommon.ValueTypeDouble:\n\t\treturn \"float64\"\n\tcase pcommon.ValueTypeBool:\n\t\treturn \"bool\"\n\tcase pcommon.ValueTypeBytes:\n\t\treturn \"[]byte\"\n\tcase pcommon.ValueTypeSlice:\n\t\treturn \"[]any\"\n\tcase pcommon.ValueTypeMap:\n\t\treturn \"map[string]any\"\n\tcase pcommon.ValueTypeEmpty:\n\t\treturn \"\"\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\ntype SemanticConvention struct {\n\tSemanticConventionRef string `mapstructure:\"ref\"`\n}\n\ntype Warnings struct {\n\t// A warning that will be displayed if the field is enabled in user config.\n\tIfEnabled string `mapstructure:\"if_enabled\"`\n\t// A warning that will be displayed if `enabled` field is not set explicitly in user config.\n\tIfEnabledNotSet string `mapstructure:\"if_enabled_not_set\"`\n\t// A warning that will be displayed if the field is configured by user in any way.\n\tIfConfigured string `mapstructure:\"if_configured\"`\n}\n\ntype Attribute struct {\n\t// Description describes the purpose of the attribute.\n\tDescription string `mapstructure:\"description\"`\n\t// NameOverride can be used to override the attribute name.\n\tNameOverride string `mapstructure:\"name_override\"`\n\t// EnabledPtr defines whether the attribute is enabled by default.\n\tEnabledPtr *bool `mapstructure:\"enabled\"`\n\t// Include can be used to filter attributes.\n\tInclude []filter.Config `mapstructure:\"include\"`\n\t// Include can be used to filter attributes.\n\tExclude []filter.Config `mapstructure:\"exclude\"`\n\t// Enum can optionally describe the set of values to which the attribute can belong.\n\tEnum []string `mapstructure:\"enum\"`\n\t// Type is an attribute type.\n\tType ValueType `mapstructure:\"type\"`\n\t// FullName is the attribute name populated from the map key.\n\tFullName AttributeName `mapstructure:\"-\"`\n\t// Warnings that will be shown to user under specified conditions.\n\tWarnings Warnings `mapstructure:\"warnings\"`\n\t// RequirementLevel defines the requirement level of the attribute.\n\tRequirementLevel AttributeRequirementLevel `mapstructure:\"requirement_level\"`\n}\n\n// IsConditional returns true if the attribute is conditionally required.\nfunc (a Attribute) IsConditional() bool {\n\treturn a.RequirementLevel == AttributeRequirementLevelConditionallyRequired\n}\n\n// IsRequired returns true if the attribute is required.\nfunc (a Attribute) IsRequired() bool {\n\treturn a.RequirementLevel == AttributeRequirementLevelRequired\n}\n\n// IsNotOptIn returns true if the attribute is any requirement_level above\n// opt_in\nfunc (a Attribute) IsNotOptIn() bool {\n\treturn a.RequirementLevel != AttributeRequirementLevelOptIn\n}\n\n// UnmarshalText implements the encoding.TextUnmarshaler interface.\nfunc (rl *AttributeRequirementLevel) UnmarshalText(text []byte) error {\n\tswitch string(text) {\n\tcase \"required\":\n\t\t*rl = AttributeRequirementLevelRequired\n\tcase \"conditionally_required\":\n\t\t*rl = AttributeRequirementLevelConditionallyRequired\n\tcase \"recommended\":\n\t\t*rl = AttributeRequirementLevelRecommended\n\tcase \"opt_in\":\n\t\t*rl = AttributeRequirementLevelOptIn\n\tcase \"\":\n\t\t*rl = AttributeRequirementLevelRecommended\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid requirement_level %q\", string(text))\n\t}\n\treturn nil\n}\n\n// Enabled returns the boolean value of EnabledPtr.\n// This method is needed to differentiate between different types of attributes:\n// - Resource attributes: EnabledPtr is always set (non-nil) due to validation\n// - Regular attributes: EnabledPtr is always nil due to validation\n// Panics if EnabledPtr is nil, indicating incorrect template usage.\nfunc (a Attribute) Enabled() bool {\n\tif a.EnabledPtr == nil {\n\t\tpanic(\"Enabled() must not be called on regular attributes, only on resource attributes\")\n\t}\n\treturn *a.EnabledPtr\n}\n\n// Name returns actual name of the attribute that is set on the metric after applying NameOverride.\nfunc (a Attribute) Name() AttributeName {\n\tif a.NameOverride != \"\" {\n\t\treturn AttributeName(a.NameOverride)\n\t}\n\treturn a.FullName\n}\n\nfunc (a Attribute) TestValue() string {\n\tif a.Enum != nil {\n\t\treturn fmt.Sprintf(`%q`, a.Enum[0])\n\t}\n\tswitch a.Type.ValueType {\n\tcase pcommon.ValueTypeEmpty:\n\t\treturn \"\"\n\tcase pcommon.ValueTypeStr:\n\t\treturn fmt.Sprintf(`\"%s-val\"`, a.FullName)\n\tcase pcommon.ValueTypeInt:\n\t\treturn strconv.Itoa(len(a.FullName))\n\tcase pcommon.ValueTypeDouble:\n\t\treturn fmt.Sprintf(\"%f\", 0.1+float64(len(a.FullName)))\n\tcase pcommon.ValueTypeBool:\n\t\treturn strconv.FormatBool(len(a.FullName)%2 == 0)\n\tcase pcommon.ValueTypeMap:\n\t\treturn fmt.Sprintf(`map[string]any{\"key1\": \"%s-val1\", \"key2\": \"%s-val2\"}`, a.FullName, a.FullName)\n\tcase pcommon.ValueTypeSlice:\n\t\treturn fmt.Sprintf(`[]any{\"%s-item1\", \"%s-item2\"}`, a.FullName, a.FullName)\n\tcase pcommon.ValueTypeBytes:\n\t\treturn fmt.Sprintf(`[]byte(\"%s-val\")`, a.FullName)\n\t}\n\treturn \"\"\n}\n\nfunc (a Attribute) TestValueTwo() string {\n\tif a.Enum != nil {\n\t\treturn fmt.Sprintf(`%q`, a.Enum[1])\n\t}\n\tswitch a.Type.ValueType {\n\tcase pcommon.ValueTypeEmpty:\n\t\treturn \"\"\n\tcase pcommon.ValueTypeStr:\n\t\treturn fmt.Sprintf(`\"%s-val-2\"`, a.FullName)\n\tcase pcommon.ValueTypeInt:\n\t\treturn strconv.Itoa(len(a.FullName) + 1)\n\tcase pcommon.ValueTypeDouble:\n\t\treturn fmt.Sprintf(\"%f\", 1.1+float64(len(a.FullName)))\n\tcase pcommon.ValueTypeBool:\n\t\treturn strconv.FormatBool(len(a.FullName)%2 == 1)\n\tcase pcommon.ValueTypeMap:\n\t\treturn fmt.Sprintf(`map[string]any{\"key3\": \"%s-val3\", \"key4\": \"%s-val4\"}`, a.FullName, a.FullName)\n\tcase pcommon.ValueTypeSlice:\n\t\treturn fmt.Sprintf(`[]any{\"%s-item3\", \"%s-item4\"}`, a.FullName, a.FullName)\n\tcase pcommon.ValueTypeBytes:\n\t\treturn fmt.Sprintf(`[]byte(\"%s-val-2\")`, a.FullName)\n\t}\n\treturn \"\"\n}\n\ntype Signal struct {\n\t// Enabled defines whether the signal is enabled by default.\n\tEnabled bool `mapstructure:\"enabled\"`\n\n\t// Warnings that will be shown to user under specified conditions.\n\tWarnings Warnings `mapstructure:\"warnings\"`\n\n\t// Description of the signal.\n\tDescription string `mapstructure:\"description\"`\n\n\t// The semantic convention reference of the signal.\n\tSemanticConvention *SemanticConvention `mapstructure:\"semantic_convention\"`\n\n\t// The stability level of the signal.\n\tStability component.StabilityLevel `mapstructure:\"stability\"`\n\n\t// Extended documentation of the signal. If specified, this will be appended to the description used in generated documentation.\n\tExtendedDocumentation string `mapstructure:\"extended_documentation\"`\n\n\t// Attributes is the list of attributes that the signal emits.\n\tAttributes []AttributeName `mapstructure:\"attributes\"`\n\n\t// Entity is the type of entity this signal is associated with.\n\t// Required when entities are defined.\n\tEntity string `mapstructure:\"entity\"`\n}\n\nfunc (s Signal) HasConditionalAttributes(attrs map[AttributeName]Attribute) bool {\n\tfor _, attr := range s.Attributes {\n\t\tif v, exists := attrs[attr]; exists && v.IsConditional() {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\ntype Entity struct {\n\t// Type is the type of the entity.\n\tType string `mapstructure:\"type\"`\n\t// Brief is a brief description of the entity.\n\tBrief string `mapstructure:\"brief\"`\n\t// Stability is the stability level of the entity.\n\tStability component.StabilityLevel `mapstructure:\"stability\"`\n\t// Identity contains references to resource attributes that uniquely identify the entity.\n\tIdentity []EntityAttributeRef `mapstructure:\"identity\"`\n\t// Description contains references to resource attributes that describe the entity.\n\tDescription []EntityAttributeRef `mapstructure:\"description\"`\n\t// ExtraAttributes contains references to resource attributes that are contextually\n\t// relevant to the entity but are not part of its identity or description\n\t// (e.g. k8s.namespace.name on a pod entity).\n\tExtraAttributes []EntityAttributeRef `mapstructure:\"extra_attributes\"`\n\t// Relationships defines how this entity relates to other entities (optional).\n\t// Relationships should be defined only on one end. It is recommended to define\n\t// relationships on entities with lower lifespan (higher churn).\n\tRelationships []EntityRelationship `mapstructure:\"relationships\"`\n}\n\ntype EntityAttributeRef struct {\n\t// Ref is the reference to a resource attribute.\n\tRef AttributeName `mapstructure:\"ref\"`\n}\n\ntype EntityRelationship struct {\n\t// Type is the relationship type (e.g., \"parent\", \"child\", \"peer\").\n\tType string `mapstructure:\"type\"`\n\t// Target is the entity type this entity relates to.\n\tTarget string `mapstructure:\"target\"`\n}\n\n// FeatureGateID represents the identifier for a feature gate.\ntype FeatureGateID string\n\n// FeatureGateStage represents the lifecycle stage of a feature gate.\ntype FeatureGateStage string\n\nconst (\n\tFeatureGateStageAlpha      FeatureGateStage = \"alpha\"\n\tFeatureGateStageBeta       FeatureGateStage = \"beta\"\n\tFeatureGateStageStable     FeatureGateStage = \"stable\"\n\tFeatureGateStageDeprecated FeatureGateStage = \"deprecated\"\n)\n\n// FeatureGate represents a feature gate definition in metadata.\ntype FeatureGate struct {\n\t// ID is the unique identifier for the feature gate.\n\tID FeatureGateID `mapstructure:\"id\"`\n\t// Description of the feature gate.\n\tDescription string `mapstructure:\"description\"`\n\t// Stage is the lifecycle stage of the feature gate.\n\tStage FeatureGateStage `mapstructure:\"stage\"`\n\t// FromVersion is the version when the feature gate was introduced.\n\tFromVersion string `mapstructure:\"from_version\"`\n\t// ToVersion is the version when the feature gate reached stable stage.\n\tToVersion string `mapstructure:\"to_version\"`\n\t// ReferenceURL is the URL with contextual information about the feature gate.\n\tReferenceURL string `mapstructure:\"reference_url\"`\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/metadata_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/cfggen\"\n)\n\nfunc TestValidate(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\twantErr string\n\t}{\n\t\t{\n\t\t\tname:    \"testdata/no_type.yaml\",\n\t\t\twantErr: \"missing type\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/no_status.yaml\",\n\t\t\twantErr: \"missing status\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/no_class.yaml\",\n\t\t\twantErr: \"missing class\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/invalid_class.yaml\",\n\t\t\twantErr: \"invalid class: incorrectclass\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/no_stability.yaml\",\n\t\t\twantErr: \"missing stability\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/no_deprecation_info.yaml\",\n\t\t\twantErr: \"deprecated component missing deprecation date and migration guide for traces\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/no_deprecation_date_info.yaml\",\n\t\t\twantErr: \"deprecated component missing date in YYYY-MM-DD format: traces\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/no_deprecation_migration_info.yaml\",\n\t\t\twantErr: \"deprecated component missing migration guide: traces\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/deprecation_info_invalid_date.yaml\",\n\t\t\twantErr: \"deprecated component missing valid date in YYYY-MM-DD format: traces\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/invalid_stability.yaml\",\n\t\t\twantErr: \"decoding failed due to the following error(s):\\n\\n'status.stability' unsupported stability level: \\\"incorrectstability\\\"\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/no_stability_component.yaml\",\n\t\t\twantErr: \"missing component for stability: Beta\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/invalid_stability_component.yaml\",\n\t\t\twantErr: \"invalid component: incorrectcomponent\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/no_description_rattr.yaml\",\n\t\t\twantErr: \"empty description for resource attribute: string.resource.attr\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/no_type_rattr.yaml\",\n\t\t\twantErr: \"empty type for resource attribute: string.resource.attr\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/no_metric_description.yaml\",\n\t\t\twantErr: \"metric \\\"default.metric\\\": missing metric description\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/events/no_description.yaml\",\n\t\t\twantErr: \"event \\\"default.event\\\": missing event description\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/no_metric_unit.yaml\",\n\t\t\twantErr: \"metric \\\"default.metric\\\": missing metric unit\",\n\t\t},\n\t\t{\n\t\t\tname: \"testdata/no_metric_type.yaml\",\n\t\t\twantErr: \"metric \\\"system.cpu.time\\\": missing metric type key, \" +\n\t\t\t\t\"one of the following has to be specified: sum, gauge, histogram\",\n\t\t},\n\t\t{\n\t\t\tname: \"testdata/two_metric_types.yaml\",\n\t\t\twantErr: \"metric \\\"system.cpu.time\\\": more than one metric type keys, \" +\n\t\t\t\t\"only one of the following has to be specified: sum, gauge, histogram\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/invalid_input_type.yaml\",\n\t\t\twantErr: \"metric \\\"system.cpu.time\\\": invalid `input_type` value \\\"double\\\", must be \\\"\\\" or \\\"string\\\"\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/unknown_metric_attribute.yaml\",\n\t\t\twantErr: \"metric \\\"system.cpu.time\\\" refers to undefined attributes: [missing]\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/events/unknown_attribute.yaml\",\n\t\t\twantErr: \"event \\\"system.event\\\" refers to undefined attributes: [missing]\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/unused_attribute.yaml\",\n\t\t\twantErr: \"unused attributes: [unused_attr]\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/no_description_attr.yaml\",\n\t\t\twantErr: \"missing attribute description for: string_attr\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/no_type_attr.yaml\",\n\t\t\twantErr: \"empty type for attribute: used_attr\",\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/entity_undefined_id_attribute.yaml\",\n\t\t\twantErr: `entity \"host\": identity refers to undefined resource attribute: host.missing`,\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/entity_undefined_description_attribute.yaml\",\n\t\t\twantErr: `entity \"host\": description refers to undefined resource attribute: host.missing`,\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/entity_empty_id_attributes.yaml\",\n\t\t\twantErr: `entity \"host\": identity is required`,\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/entity_duplicate_attributes.yaml\",\n\t\t\twantErr: `attribute host.name is already used by entity`,\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/entity_duplicate_types.yaml\",\n\t\t\twantErr: `duplicate entity type: host`,\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/invalid_entity_stability.yaml\",\n\t\t\twantErr: `unsupported stability level: \"stable42\"`,\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/entity_relationships_bidirectional.yaml\",\n\t\t\twantErr: `duplicate relationship to target \"k8s.replicaset\" (only one relationship allowed between two entities)`,\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/entity_relationships_empty_type.yaml\",\n\t\t\twantErr: `entity \"k8s.pod\": relationship type cannot be empty`,\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/entity_relationships_empty_target.yaml\",\n\t\t\twantErr: `entity \"k8s.pod\": relationship target cannot be empty`,\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/entity_relationships_undefined_target.yaml\",\n\t\t\twantErr: `entity \"k8s.pod\": relationship target \"k8s.replicaset\" does not exist`,\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/entity_metric_missing_association.yaml\",\n\t\t\twantErr: `metric \"host.cpu.time\": entity is required when entities are defined`,\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/entity_event_missing_association.yaml\",\n\t\t\twantErr: `event \"host.restart\": entity is required when entities are defined`,\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/entity_undefined_reference.yaml\",\n\t\t\twantErr: `metric \"host.cpu.time\": entity refers to undefined entity type: undefined_entity`,\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/entity_single_metric_missing_association.yaml\",\n\t\t\twantErr: `metric \"host.cpu.time\": entity is required when entities are defined`,\n\t\t},\n\t\t{\n\t\t\tname:    \"testdata/entity_metrics_events_valid.yaml\",\n\t\t\twantErr: \"\",\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t_, err := LoadMetadata(tt.name)\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\trequire.ErrorContains(t, err, tt.wantErr)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestSupportsSignal(t *testing.T) {\n\tmd := Metadata{}\n\tassert.False(t, md.supportsSignal(\"logs\"))\n}\n\nfunc TestCodeCovID(t *testing.T) {\n\ttests := []struct {\n\t\tmd   Metadata\n\t\twant string\n\t}{\n\t\t{\n\t\t\tmd: Metadata{\n\t\t\t\tType: \"aes\",\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tClass:              \"provider\",\n\t\t\t\t\tCodeCovComponentID: \"my_custom_id\",\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: \"my_custom_id\",\n\t\t},\n\t\t{\n\t\t\tmd: Metadata{\n\t\t\t\tType: \"count\",\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tClass: \"connector\",\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: \"connector_count\",\n\t\t},\n\t\t{\n\t\t\tmd: Metadata{\n\t\t\t\tType: \"file\",\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tClass: \"exporter\",\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: \"exporter_file\",\n\t\t},\n\t\t{\n\t\t\tmd: Metadata{\n\t\t\t\tType: \"file_log_thing\",\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tClass: \"exporter\",\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: \"exporter_filelogthing\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.md.Type, func(t *testing.T) {\n\t\t\tgot := tt.md.GetCodeCovComponentID()\n\t\t\tassert.Equal(t, tt.want, got)\n\t\t})\n\t}\n}\n\nfunc TestAttributeRequirementLevel(t *testing.T) {\n\ttests := []struct {\n\t\tname             string\n\t\trequirementLevel AttributeRequirementLevel\n\t\twantConditional  bool\n\t}{\n\t\t{\n\t\t\tname:             \"required\",\n\t\t\trequirementLevel: AttributeRequirementLevelRequired,\n\t\t\twantConditional:  false,\n\t\t},\n\t\t{\n\t\t\tname:             \"conditionally_required\",\n\t\t\trequirementLevel: AttributeRequirementLevelConditionallyRequired,\n\t\t\twantConditional:  true,\n\t\t},\n\t\t{\n\t\t\tname:             \"recommended\",\n\t\t\trequirementLevel: AttributeRequirementLevelRecommended,\n\t\t\twantConditional:  false,\n\t\t},\n\t\t{\n\t\t\tname:             \"opt_in\",\n\t\t\trequirementLevel: AttributeRequirementLevelOptIn,\n\t\t\twantConditional:  false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tattr := Attribute{RequirementLevel: tt.requirementLevel}\n\t\t\tassert.Equal(t, tt.wantConditional, attr.IsConditional())\n\t\t})\n\t}\n}\n\nfunc TestAttributeRequirementLevelUnmarshalText(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tinput   string\n\t\twant    AttributeRequirementLevel\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:  \"required\",\n\t\t\tinput: \"required\",\n\t\t\twant:  AttributeRequirementLevelRequired,\n\t\t},\n\t\t{\n\t\t\tname:  \"conditionally_required\",\n\t\t\tinput: \"conditionally_required\",\n\t\t\twant:  AttributeRequirementLevelConditionallyRequired,\n\t\t},\n\t\t{\n\t\t\tname:  \"recommended\",\n\t\t\tinput: \"recommended\",\n\t\t\twant:  AttributeRequirementLevelRecommended,\n\t\t},\n\t\t{\n\t\t\tname:  \"opt_in\",\n\t\t\tinput: \"opt_in\",\n\t\t\twant:  AttributeRequirementLevelOptIn,\n\t\t},\n\t\t{\n\t\t\tname:  \"empty defaults to recommended\",\n\t\t\tinput: \"\",\n\t\t\twant:  AttributeRequirementLevelRecommended,\n\t\t},\n\t\t{\n\t\t\tname:    \"invalid value\",\n\t\t\tinput:   \"invalid\",\n\t\t\twantErr: true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvar rl AttributeRequirementLevel\n\t\t\terr := rl.UnmarshalText([]byte(tt.input))\n\t\t\tif tt.wantErr {\n\t\t\t\tassert.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tt.want, rl)\n\t\t})\n\t}\n}\n\nfunc TestValidateFeatureGates(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tfeatureGate FeatureGate\n\t\twantErr     string\n\t}{\n\t\t{\n\t\t\tname: \"valid alpha gate\",\n\t\t\tfeatureGate: FeatureGate{\n\t\t\t\tID:           \"component.feature\",\n\t\t\t\tDescription:  \"Test feature gate\",\n\t\t\t\tStage:        FeatureGateStageAlpha,\n\t\t\t\tFromVersion:  \"v0.100.0\",\n\t\t\t\tReferenceURL: \"https://example.com\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"valid stable gate with to_version\",\n\t\t\tfeatureGate: FeatureGate{\n\t\t\t\tID:           \"component.stable\",\n\t\t\t\tDescription:  \"Stable feature gate\",\n\t\t\t\tStage:        FeatureGateStageStable,\n\t\t\t\tFromVersion:  \"v0.90.0\",\n\t\t\t\tToVersion:    \"v0.95.0\",\n\t\t\t\tReferenceURL: \"https://example.com\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"empty description\",\n\t\t\tfeatureGate: FeatureGate{\n\t\t\t\tID:          \"component.feature\",\n\t\t\t\tStage:       FeatureGateStageAlpha,\n\t\t\t\tFromVersion: \"v0.100.0\",\n\t\t\t},\n\t\t\twantErr: `description is required`,\n\t\t},\n\t\t{\n\t\t\tname: \"invalid stage\",\n\t\t\tfeatureGate: FeatureGate{\n\t\t\t\tID:          \"component.feature\",\n\t\t\t\tDescription: \"Test feature\",\n\t\t\t\tStage:       \"invalid\",\n\t\t\t\tFromVersion: \"v0.100.0\",\n\t\t\t},\n\t\t\twantErr: `invalid stage \"invalid\"`,\n\t\t},\n\t\t{\n\t\t\tname: \"missing from_version\",\n\t\t\tfeatureGate: FeatureGate{\n\t\t\t\tID:          \"component.feature\",\n\t\t\t\tDescription: \"Test feature\",\n\t\t\t\tStage:       FeatureGateStageAlpha,\n\t\t\t},\n\t\t\twantErr: `from_version is required`,\n\t\t},\n\t\t{\n\t\t\tname: \"from_version without v prefix\",\n\t\t\tfeatureGate: FeatureGate{\n\t\t\t\tID:          \"component.feature\",\n\t\t\t\tDescription: \"Test feature\",\n\t\t\t\tStage:       FeatureGateStageAlpha,\n\t\t\t\tFromVersion: \"0.100.0\",\n\t\t\t},\n\t\t\twantErr: `from_version \"0.100.0\" must start with 'v'`,\n\t\t},\n\t\t{\n\t\t\tname: \"to_version without v prefix\",\n\t\t\tfeatureGate: FeatureGate{\n\t\t\t\tID:          \"component.feature\",\n\t\t\t\tDescription: \"Test feature\",\n\t\t\t\tStage:       FeatureGateStageStable,\n\t\t\t\tFromVersion: \"v0.90.0\",\n\t\t\t\tToVersion:   \"0.95.0\",\n\t\t\t},\n\t\t\twantErr: `to_version \"0.95.0\" must start with 'v'`,\n\t\t},\n\t\t{\n\t\t\tname: \"stable gate missing to_version\",\n\t\t\tfeatureGate: FeatureGate{\n\t\t\t\tID:          \"component.feature\",\n\t\t\t\tDescription: \"Test feature\",\n\t\t\t\tStage:       FeatureGateStageStable,\n\t\t\t\tFromVersion: \"v0.90.0\",\n\t\t\t},\n\t\t\twantErr: `to_version is required for stable stage gates`,\n\t\t},\n\t\t{\n\t\t\tname: \"deprecated gate missing to_version\",\n\t\t\tfeatureGate: FeatureGate{\n\t\t\t\tID:          \"component.feature\",\n\t\t\t\tDescription: \"Test feature\",\n\t\t\t\tStage:       FeatureGateStageDeprecated,\n\t\t\t\tFromVersion: \"v0.90.0\",\n\t\t\t},\n\t\t\twantErr: `to_version is required for deprecated stage gates`,\n\t\t},\n\t\t{\n\t\t\tname: \"missing reference_url\",\n\t\t\tfeatureGate: FeatureGate{\n\t\t\t\tID:          \"component.feature\",\n\t\t\t\tDescription: \"Test feature\",\n\t\t\t\tStage:       FeatureGateStageAlpha,\n\t\t\t\tFromVersion: \"v0.100.0\",\n\t\t\t},\n\t\t\twantErr: `reference_url is required`,\n\t\t},\n\t\t{\n\t\t\tname: \"invalid characters in ID\",\n\t\t\tfeatureGate: FeatureGate{\n\t\t\t\tID:           \"component.feature@invalid\",\n\t\t\t\tDescription:  \"Test feature\",\n\t\t\t\tStage:        FeatureGateStageAlpha,\n\t\t\t\tFromVersion:  \"v0.100.0\",\n\t\t\t\tReferenceURL: \"https://example.com\",\n\t\t\t},\n\t\t\twantErr: `ID contains invalid characters`,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tmd := &Metadata{\n\t\t\t\tFeatureGates: []FeatureGate{tt.featureGate},\n\t\t\t}\n\t\t\terr := md.validateFeatureGates()\n\t\t\tif tt.wantErr != \"\" {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\tassert.ErrorContains(t, err, tt.wantErr)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestValidateFeatureGatesEmptyID(t *testing.T) {\n\tmd := &Metadata{\n\t\tFeatureGates: []FeatureGate{\n\t\t\t{\n\t\t\t\tDescription: \"Test\",\n\t\t\t\tStage:       FeatureGateStageAlpha,\n\t\t\t},\n\t\t},\n\t}\n\terr := md.validateFeatureGates()\n\trequire.Error(t, err)\n\tassert.ErrorContains(t, err, \"ID cannot be empty\")\n}\n\nfunc TestValidateFeatureGatesDuplicateID(t *testing.T) {\n\tmd := &Metadata{\n\t\tFeatureGates: []FeatureGate{\n\t\t\t{\n\t\t\t\tID:          \"component.feature\",\n\t\t\t\tDescription: \"Test feature\",\n\t\t\t\tStage:       FeatureGateStageAlpha,\n\t\t\t},\n\t\t\t{\n\t\t\t\tID:          \"component.feature\",\n\t\t\t\tDescription: \"Duplicate feature\",\n\t\t\t\tStage:       FeatureGateStageAlpha,\n\t\t\t},\n\t\t},\n\t}\n\terr := md.validateFeatureGates()\n\trequire.Error(t, err)\n\tassert.ErrorContains(t, err, \"duplicate ID\")\n}\n\nfunc TestValidateFeatureGatesNotSorted(t *testing.T) {\n\tmd := &Metadata{\n\t\tFeatureGates: []FeatureGate{\n\t\t\t{\n\t\t\t\tID:           \"component.zebra\",\n\t\t\t\tDescription:  \"Test feature\",\n\t\t\t\tStage:        FeatureGateStageAlpha,\n\t\t\t\tReferenceURL: \"https://example.com\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tID:           \"component.alpha\",\n\t\t\t\tDescription:  \"Another feature\",\n\t\t\t\tStage:        FeatureGateStageAlpha,\n\t\t\t\tReferenceURL: \"https://example.com\",\n\t\t\t},\n\t\t},\n\t}\n\terr := md.validateFeatureGates()\n\trequire.Error(t, err)\n\tassert.ErrorContains(t, err, \"feature gates must be sorted by ID\")\n}\n\nfunc TestValidateConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tconfig  *cfggen.ConfigMetadata\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname: \"valid config\",\n\t\t\tconfig: &cfggen.ConfigMetadata{\n\t\t\t\tType: \"object\",\n\t\t\t\tAllOf: []*cfggen.ConfigMetadata{\n\t\t\t\t\t{\n\t\t\t\t\t\tRef: \"component.config\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname:    \"no config defined\",\n\t\t\tconfig:  nil,\n\t\t\twantErr: false,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tmd := &Metadata{\n\t\t\t\tType: \"test\",\n\t\t\t\tStatus: &Status{\n\t\t\t\t\tClass: \"exporter\",\n\t\t\t\t\tStability: StabilityMap{\n\t\t\t\t\t\t6: {\"traces\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tConfig: tt.config,\n\t\t\t}\n\t\t\terr := md.Validate()\n\t\t\tif tt.wantErr {\n\t\t\t\trequire.Error(t, err)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/metric.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"golang.org/x/text/cases\"\n\t\"golang.org/x/text/language\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/helpers\"\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\nvar reNonAlnum = regexp.MustCompile(`[^a-z0-9_]+`)\n\ntype MetricName string\n\nfunc (mn MetricName) Render() (string, error) {\n\treturn helpers.FormatIdentifier(string(mn), true)\n}\n\nfunc (mn MetricName) RenderUnexported() (string, error) {\n\treturn helpers.FormatIdentifier(string(mn), false)\n}\n\ntype Metric struct {\n\tSignal `mapstructure:\",squash\"`\n\n\t// Optional can be used to specify metrics that may\n\t// or may not be present in all cases, depending on configuration.\n\tOptional bool `mapstructure:\"optional\"`\n\n\t// Unit of the metric.\n\tUnit *string `mapstructure:\"unit\"`\n\n\t// Sum stores metadata for sum metric type\n\tSum *Sum `mapstructure:\"sum,omitempty\"`\n\t// Gauge stores metadata for gauge metric type\n\tGauge *Gauge `mapstructure:\"gauge,omitempty\"`\n\t// Histogram stores metadata for histogram metric type\n\tHistogram *Histogram `mapstructure:\"histogram,omitempty\"`\n\n\t// Override the default prefix for the metric name.\n\tPrefix string `mapstructure:\"prefix\"`\n\n\t// Deprecation metadata for deprecated metrics\n\tDeprecated *Deprecated `mapstructure:\"deprecated,omitempty\"`\n}\n\nfunc (m *Metric) validate(metricName MetricName, semConvVersion string) error {\n\tvar errs error\n\n\tif m.Deprecated != nil {\n\t\tif m.Stability != component.StabilityLevelDeprecated {\n\t\t\terrs = errors.Join(errs, errors.New(\"`stability` must be `deprecated` when specifying a `deprecated` field\"))\n\t\t}\n\n\t\tif err := m.Deprecated.validate(); err != nil {\n\t\t\terrs = errors.Join(errs, err)\n\t\t}\n\t}\n\n\tif m.Sum == nil && m.Gauge == nil && m.Histogram == nil {\n\t\terrs = errors.Join(errs, errors.New(\"missing metric type key, \"+\n\t\t\t\"one of the following has to be specified: sum, gauge, histogram\"))\n\t}\n\tif (m.Sum != nil && m.Gauge != nil) || (m.Sum != nil && m.Histogram != nil) || (m.Gauge != nil && m.Histogram != nil) {\n\t\terrs = errors.Join(errs, errors.New(\"more than one metric type keys, \"+\n\t\t\t\"only one of the following has to be specified: sum, gauge, histogram\"))\n\t}\n\tif m.Stability == component.StabilityLevelUndefined {\n\t\terrs = errors.Join(errs, errors.New(\"missing required field: `stability.level`\"))\n\t}\n\tif m.Description == \"\" {\n\t\terrs = errors.Join(errs, errors.New(`missing metric description`))\n\t}\n\tif m.Unit == nil {\n\t\terrs = errors.Join(errs, errors.New(`missing metric unit`))\n\t}\n\tif m.Sum != nil {\n\t\terrs = errors.Join(errs, m.Sum.Validate())\n\t}\n\tif m.Gauge != nil {\n\t\terrs = errors.Join(errs, m.Gauge.Validate())\n\t}\n\tif m.SemanticConvention != nil {\n\t\tif err := validateSemConvMetricURL(m.SemanticConvention.SemanticConventionRef, semConvVersion, string(metricName)); err != nil {\n\t\t\terrs = errors.Join(errs, err)\n\t\t}\n\t}\n\treturn errs\n}\n\nfunc metricAnchor(metricName string) string {\n\tm := strings.ToLower(strings.TrimSpace(metricName))\n\tm = reNonAlnum.ReplaceAllString(m, \"\")\n\treturn \"metric-\" + m\n}\n\n// validateSemConvMetricURL verifies the URL matches exactly:\n// https://github.com/open-telemetry/semantic-conventions/blob/<semConvVersion>/*#metric-<metricName>\nfunc validateSemConvMetricURL(rawURL, semConvVersion, metricName string) error {\n\tif strings.TrimSpace(rawURL) == \"\" {\n\t\treturn errors.New(\"url is empty\")\n\t}\n\tif strings.TrimSpace(semConvVersion) == \"\" {\n\t\treturn errors.New(\"semConvVersion is empty\")\n\t}\n\tif strings.TrimSpace(metricName) == \"\" {\n\t\treturn errors.New(\"metricName is empty\")\n\t}\n\tsemConvVersion = \"v\" + semConvVersion\n\n\tanchor := metricAnchor(metricName)\n\t// Build a strict regex that enforces https, repo, blob, given version, any doc path, and exact anchor.\n\tpattern := fmt.Sprintf(`^https://github\\.com/open-telemetry/semantic-conventions/blob/%s/[^#\\s]+#%s$`,\n\t\tsemConvVersion,\n\t\tanchor,\n\t)\n\tre := regexp.MustCompile(pattern)\n\tif !re.MatchString(rawURL) {\n\t\treturn fmt.Errorf(\n\t\t\t\"invalid semantic-conventions URL: want https://github.com/open-telemetry/semantic-conventions/blob/%s/*#%s, got %q\",\n\t\t\tsemConvVersion, anchor, rawURL)\n\t}\n\treturn nil\n}\n\nfunc (m *Metric) Unmarshal(parser *confmap.Conf) error {\n\tif !parser.IsSet(\"enabled\") {\n\t\treturn errors.New(\"missing required field: `enabled`\")\n\t}\n\tif !parser.IsSet(\"stability\") {\n\t\treturn errors.New(\"missing required field: `stability`\")\n\t}\n\treturn parser.Unmarshal(m)\n}\n\nfunc (m Metric) Data() MetricData {\n\tif m.Sum != nil {\n\t\treturn m.Sum\n\t}\n\tif m.Gauge != nil {\n\t\treturn m.Gauge\n\t}\n\tif m.Histogram != nil {\n\t\treturn m.Histogram\n\t}\n\treturn nil\n}\n\n// MetricData is generic interface for all metric datatypes.\ntype MetricData interface {\n\tType() string\n\tHasMonotonic() bool\n\tHasAggregated() bool\n\tHasMetricInputType() bool\n\tInstrument() string\n\tIsAsync() bool\n}\n\n// AggregationTemporality defines a metric aggregation type.\ntype AggregationTemporality struct {\n\t// Aggregation describes if the aggregator reports delta changes\n\t// since last report time, or cumulative changes since a fixed start time.\n\tAggregation pmetric.AggregationTemporality\n}\n\n// UnmarshalText implements the encoding.TextUnmarshaler interface.\nfunc (agg *AggregationTemporality) UnmarshalText(text []byte) error {\n\tswitch vtStr := string(text); vtStr {\n\tcase \"cumulative\":\n\t\tagg.Aggregation = pmetric.AggregationTemporalityCumulative\n\tcase \"delta\":\n\t\tagg.Aggregation = pmetric.AggregationTemporalityDelta\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation: %q\", vtStr)\n\t}\n\treturn nil\n}\n\n// String returns string representation of the aggregation temporality.\nfunc (agg *AggregationTemporality) String() string {\n\treturn agg.Aggregation.String()\n}\n\n// Mono defines the metric monotonicity.\ntype Mono struct {\n\t// Monotonic is true if the sum is monotonic.\n\tMonotonic bool `mapstructure:\"monotonic\"`\n}\n\n// MetricInputType defines the metric input value type\ntype MetricInputType struct {\n\t// InputType is the type the metric needs to be parsed from, options are \"string\"\n\tInputType string `mapstructure:\"input_type\"`\n}\n\nfunc (mit MetricInputType) HasMetricInputType() bool {\n\treturn mit.InputType != \"\"\n}\n\n// String returns name of the datapoint type.\nfunc (mit MetricInputType) String() string {\n\treturn mit.InputType\n}\n\nfunc (mit MetricInputType) Validate() error {\n\tif mit.InputType != \"\" && mit.InputType != \"string\" {\n\t\treturn fmt.Errorf(\"invalid `input_type` value \\\"%v\\\", must be \\\"\\\" or \\\"string\\\"\", mit.InputType)\n\t}\n\treturn nil\n}\n\n// MetricValueType defines the metric number type.\ntype MetricValueType struct {\n\t// ValueType is type of the metric number, options are \"double\", \"int\".\n\tValueType pmetric.NumberDataPointValueType\n}\n\nfunc (mvt *MetricValueType) Unmarshal(parser *confmap.Conf) error {\n\tif !parser.IsSet(\"value_type\") {\n\t\treturn errors.New(\"missing required field: `value_type`\")\n\t}\n\treturn nil\n}\n\n// UnmarshalText implements the encoding.TextUnmarshaler interface.\nfunc (mvt *MetricValueType) UnmarshalText(text []byte) error {\n\tswitch vtStr := string(text); vtStr {\n\tcase \"int\":\n\t\tmvt.ValueType = pmetric.NumberDataPointValueTypeInt\n\tcase \"double\":\n\t\tmvt.ValueType = pmetric.NumberDataPointValueTypeDouble\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid value_type: %q\", vtStr)\n\t}\n\treturn nil\n}\n\n// String returns name of the datapoint type.\nfunc (mvt MetricValueType) String() string {\n\treturn mvt.ValueType.String()\n}\n\n// BasicType returns name of a golang basic type for the datapoint type.\nfunc (mvt MetricValueType) BasicType() string {\n\tswitch mvt.ValueType {\n\tcase pmetric.NumberDataPointValueTypeInt:\n\t\treturn \"int64\"\n\tcase pmetric.NumberDataPointValueTypeDouble:\n\t\treturn \"float64\"\n\tcase pmetric.NumberDataPointValueTypeEmpty:\n\t\treturn \"\"\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\nvar _ MetricData = (*Gauge)(nil)\n\ntype Gauge struct {\n\tMetricValueType `mapstructure:\"value_type\"`\n\tMetricInputType `mapstructure:\",squash\"`\n\tAsync           bool `mapstructure:\"async,omitempty\"`\n}\n\n// Unmarshal is a custom unmarshaler for gauge. Needed mostly to avoid MetricValueType.Unmarshal inheritance.\nfunc (d *Gauge) Unmarshal(parser *confmap.Conf) error {\n\tif err := d.MetricValueType.Unmarshal(parser); err != nil {\n\t\treturn err\n\t}\n\treturn parser.Unmarshal(d, confmap.WithIgnoreUnused())\n}\n\nfunc (d *Gauge) Type() string {\n\treturn \"Gauge\"\n}\n\nfunc (d *Gauge) HasMonotonic() bool {\n\treturn false\n}\n\nfunc (d *Gauge) HasAggregated() bool {\n\treturn false\n}\n\nfunc (d *Gauge) Instrument() string {\n\tinstrumentName := cases.Title(language.English).String(d.BasicType())\n\n\tif d.Async {\n\t\tinstrumentName += \"Observable\"\n\t}\n\n\tinstrumentName += \"Gauge\"\n\treturn instrumentName\n}\n\nfunc (d *Gauge) IsAsync() bool {\n\treturn d.Async\n}\n\nvar _ MetricData = (*Sum)(nil)\n\ntype Sum struct {\n\tAggregationTemporality `mapstructure:\"aggregation_temporality\"`\n\tMono                   `mapstructure:\",squash\"`\n\tMetricValueType        `mapstructure:\"value_type\"`\n\tMetricInputType        `mapstructure:\",squash\"`\n\tAsync                  bool `mapstructure:\"async,omitempty\"`\n}\n\n// Unmarshal is a custom unmarshaler for sum. Needed mostly to avoid MetricValueType.Unmarshal inheritance.\nfunc (d *Sum) Unmarshal(parser *confmap.Conf) error {\n\tif err := d.MetricValueType.Unmarshal(parser); err != nil {\n\t\treturn err\n\t}\n\treturn parser.Unmarshal(d, confmap.WithIgnoreUnused())\n}\n\n// TODO: Currently, this func will not be called because of https://github.com/open-telemetry/opentelemetry-collector/issues/6671. Uncomment function and\n// add a test case to Test_LoadMetadata for file no_monotonic.yaml once the issue is solved.\n//\n// Unmarshal is a custom unmarshaler for Mono.\n// func (m *Mono) Unmarshal(parser *confmap.Conf) error {\n// \tif !parser.IsSet(\"monotonic\") {\n// \t\treturn errors.New(\"missing required field: `monotonic`\")\n// \t}\n// \treturn parser.Unmarshal(m)\n// }\n\nfunc (d *Sum) Type() string {\n\treturn \"Sum\"\n}\n\nfunc (d *Sum) HasMonotonic() bool {\n\treturn true\n}\n\nfunc (d *Sum) HasAggregated() bool {\n\treturn true\n}\n\nfunc (d *Sum) Instrument() string {\n\tinstrumentName := cases.Title(language.English).String(d.BasicType())\n\n\tif d.Async {\n\t\tinstrumentName += \"Observable\"\n\t}\n\tif !d.Monotonic {\n\t\tinstrumentName += \"UpDown\"\n\t}\n\tinstrumentName += \"Counter\"\n\treturn instrumentName\n}\n\nfunc (d *Sum) IsAsync() bool {\n\treturn d.Async\n}\n\nvar _ MetricData = (*Histogram)(nil)\n\ntype Histogram struct {\n\tAggregationTemporality `mapstructure:\"aggregation_temporality\"`\n\tMono                   `mapstructure:\",squash\"`\n\tMetricValueType        `mapstructure:\"value_type\"`\n\tMetricInputType        `mapstructure:\",squash\"`\n\tAsync                  bool      `mapstructure:\"async,omitempty\"`\n\tBoundaries             []float64 `mapstructure:\"bucket_boundaries\"`\n}\n\nfunc (d *Histogram) Type() string {\n\treturn \"Histogram\"\n}\n\nfunc (d *Histogram) HasMonotonic() bool {\n\treturn false\n}\n\nfunc (d *Histogram) HasAggregated() bool {\n\treturn true\n}\n\nfunc (d *Histogram) Instrument() string {\n\tinstrumentName := cases.Title(language.English).String(d.BasicType())\n\treturn instrumentName + d.Type()\n}\n\n// Unmarshal is a custom unmarshaler for histogram. Needed mostly to avoid MetricValueType.Unmarshal inheritance.\nfunc (d *Histogram) Unmarshal(parser *confmap.Conf) error {\n\tif err := d.MetricValueType.Unmarshal(parser); err != nil {\n\t\treturn err\n\t}\n\treturn parser.Unmarshal(d, confmap.WithIgnoreUnused())\n}\n\nfunc (d *Histogram) IsAsync() bool {\n\treturn d.Async\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/metric_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\nfunc TestMetricData(t *testing.T) {\n\tfor _, arg := range []struct {\n\t\tmetricData        MetricData\n\t\twantType          string\n\t\twantHasAggregated bool\n\t\twantHasMonotonic  bool\n\t\twantInstrument    string\n\t\twantAsync         bool\n\t}{\n\t\t{&Gauge{}, \"Gauge\", false, false, \"Gauge\", false},\n\t\t{&Gauge{Async: true}, \"Gauge\", false, false, \"ObservableGauge\", true},\n\t\t{&Gauge{MetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeInt}, Async: true}, \"Gauge\", false, false, \"Int64ObservableGauge\", true},\n\t\t{&Gauge{MetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeDouble}, Async: true}, \"Gauge\", false, false, \"Float64ObservableGauge\", true},\n\t\t{&Sum{}, \"Sum\", true, true, \"UpDownCounter\", false},\n\t\t{&Sum{Mono: Mono{true}}, \"Sum\", true, true, \"Counter\", false},\n\t\t{&Sum{Async: true}, \"Sum\", true, true, \"ObservableUpDownCounter\", true},\n\t\t{&Sum{MetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeInt}, Async: true}, \"Sum\", true, true, \"Int64ObservableUpDownCounter\", true},\n\t\t{&Sum{MetricValueType: MetricValueType{pmetric.NumberDataPointValueTypeDouble}, Async: true}, \"Sum\", true, true, \"Float64ObservableUpDownCounter\", true},\n\t\t{&Histogram{}, \"Histogram\", true, false, \"Histogram\", false},\n\t} {\n\t\tassert.Equal(t, arg.wantType, arg.metricData.Type())\n\t\tassert.Equal(t, arg.wantHasAggregated, arg.metricData.HasAggregated())\n\t\tassert.Equal(t, arg.wantHasMonotonic, arg.metricData.HasMonotonic())\n\t\tassert.Equal(t, arg.wantInstrument, arg.metricData.Instrument())\n\t\tassert.Equal(t, arg.wantAsync, arg.metricData.IsAsync())\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Generate a test metrics builder from a sample metrics set covering all configuration options.\n//go:generate mdatagen metadata.yaml\n\npackage sampleconnector // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/sampleconnector\"\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# sample\n\n## Default Metrics\n\nThe following metrics are emitted by default. Each of them can be disabled by applying the following configuration:\n\n```yaml\nmetrics:\n  <metric_name>:\n    enabled: false\n```\n\n### default.metric\n\nMonotonic cumulative sum int metric enabled by default.\n\nThe metric will be become optional soon.\n\n| Unit | Metric Type | Value Type | Aggregation Temporality | Monotonic | Stability |\n| ---- | ----------- | ---------- | ----------------------- | --------- | --------- |\n| s | Sum | Int | Cumulative | true | Development |\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | Recommended |\n| state | Integer attribute with overridden name. | Any Int | Recommended |\n| enum_attr | Attribute with a known set of string values. | Str: ``red``, ``green``, ``blue`` | Recommended |\n| slice_attr | Attribute with a slice value. | Any Slice | Recommended |\n| map_attr | Attribute with a map value. | Any Map | Recommended |\n\n### default.metric.to_be_removed\n\n[DEPRECATED] Non-monotonic delta sum double metric enabled by default.\n\nThe metric will be removed soon.\n\n| Unit | Metric Type | Value Type | Aggregation Temporality | Monotonic | Stability |\n| ---- | ----------- | ---------- | ----------------------- | --------- | --------- |\n| s | Sum | Double | Delta | false | Deprecated since 1.0.0 |\n\n**Deprecation note**: This metric will be removed\n\n### metric.input_type\n\nMonotonic cumulative sum int metric with string input_type enabled by default.\n\n| Unit | Metric Type | Value Type | Aggregation Temporality | Monotonic | Stability |\n| ---- | ----------- | ---------- | ----------------------- | --------- | --------- |\n| s | Sum | Int | Cumulative | true | Development |\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | Recommended |\n| state | Integer attribute with overridden name. | Any Int | Recommended |\n| enum_attr | Attribute with a known set of string values. | Str: ``red``, ``green``, ``blue`` | Recommended |\n| slice_attr | Attribute with a slice value. | Any Slice | Recommended |\n| map_attr | Attribute with a map value. | Any Map | Recommended |\n\n### reaggregate.metric\n\nMetric for testing spatial reaggregation\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| 1 | Gauge | Double | Beta |\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | Recommended |\n| boolean_attr | Attribute with a boolean value. | Any Bool | Recommended |\n\n## Optional Metrics\n\nThe following metrics are not emitted by default. Each of them can be enabled by applying the following configuration:\n\n```yaml\nmetrics:\n  <metric_name>:\n    enabled: true\n```\n\n### optional.metric\n\n[DEPRECATED] Gauge double metric disabled by default.\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| 1 | Gauge | Double | Deprecated since 1.0.0 |\n\n**Deprecation note**: This metric will be removed\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | Recommended |\n| boolean_attr | Attribute with a boolean value. | Any Bool | Recommended |\n| boolean_attr2 | Another attribute with a boolean value. | Any Bool | Recommended |\n\n### optional.metric.empty_unit\n\n[DEPRECATED] Gauge double metric disabled by default.\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n|  | Gauge | Double | Deprecated since 1.0.0 |\n\n**Deprecation note**: This metric will be removed\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | Recommended |\n| boolean_attr | Attribute with a boolean value. | Any Bool | Recommended |\n\n## Resource Attributes\n\n| Name | Description | Values | Enabled |\n| ---- | ----------- | ------ | ------- |\n| map.resource.attr | Resource attribute with a map value. | Any Map | true |\n| optional.resource.attr | Explicitly disabled ResourceAttribute. | Any Str | false |\n| slice.resource.attr | Resource attribute with a slice value. | Any Slice | true |\n| string.enum.resource.attr | Resource attribute with a known set of string values. | Str: ``one``, ``two`` | true |\n| string.resource.attr | Resource attribute with any string value. | Any Str | true |\n| string.resource.attr_disable_warning | Resource attribute with any string value. | Any Str | true |\n| string.resource.attr_remove_warning | Resource attribute with any string value. | Any Str | false |\n| string.resource.attr_to_be_removed | Resource attribute with any string value. | Any Str | true |\n\n## Entities\n\nThe following entities are defined for this component:\n\n### test.entity\n\nA test entity.\n\n**Stability:** Stable\n\n**Identifying Attributes:**\n- `string.resource.attr`\n\n**Descriptive Attributes:**\n- `map.resource.attr`\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage sampleconnector // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/sampleconnector\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/sampleconnector/internal/metadata\"\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/xconnector\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n)\n\n// NewFactory returns a connector.Factory for sample connector.\nfunc NewFactory() connector.Factory {\n\treturn xconnector.NewFactory(\n\t\tmetadata.Type,\n\t\tfunc() component.Config { return &struct{}{} },\n\t\txconnector.WithMetricsToMetrics(createMetricsToMetricsConnector, metadata.MetricsToMetricsStability),\n\t\txconnector.WithProfilesToProfiles(createProfilesToProfilesConnector, metadata.ProfilesToProfilesStability),\n\t)\n}\n\nfunc createMetricsToMetricsConnector(context.Context, connector.Settings, component.Config, consumer.Metrics) (connector.Metrics, error) {\n\treturn nopInstance, nil\n}\n\nfunc createProfilesToProfilesConnector(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (xconnector.Profiles, error) {\n\treturn nopInstance, nil\n}\n\nvar nopInstance = &nopConnector{}\n\ntype nopConnector struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n}\n\nfunc (n nopConnector) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: false}\n}\n\nfunc (n nopConnector) ConsumeMetrics(context.Context, pmetric.Metrics) error {\n\treturn nil\n}\n\nfunc (n nopConnector) ConsumeProfiles(context.Context, pprofile.Profiles) error {\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n//go:build !freebsd && !illumos\n\npackage sampleconnector\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/connectortest\"\n\t\"go.opentelemetry.io/collector/connector/xconnector\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n)\n\nvar typ = component.MustNewType(\"sample\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct {\n\t\tcreateFn func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error)\n\t\tname     string\n\t}{\n\n\t\t{\n\t\t\tname: \"metrics_to_metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewMetricsRouter(map[pipeline.ID]consumer.Metrics{pipeline.NewID(pipeline.SignalMetrics): consumertest.NewNop()})\n\t\t\t\treturn factory.CreateMetricsToMetrics(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"profiles_to_profiles\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := xconnector.NewProfilesRouter(map[pipeline.ID]xconsumer.Profiles{pipeline.NewID(xpipeline.SignalProfiles): consumertest.NewNop()})\n\t\t\t\treturn factory.(xconnector.Factory).CreateProfilesToProfiles(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name+\"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), connectortest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\tt.Run(tt.name+\"-lifecycle\", func(t *testing.T) {\n\t\t\tfirstConnector, err := tt.createFn(context.Background(), connectortest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := newMdatagenNopHost()\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, firstConnector.Start(context.Background(), host))\n\t\t\trequire.NoError(t, firstConnector.Shutdown(context.Background()))\n\t\t\tsecondConnector, err := tt.createFn(context.Background(), connectortest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, secondConnector.Start(context.Background(), host))\n\t\t\trequire.NoError(t, secondConnector.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage sampleconnector\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/internal/metadata/config.schema.yaml",
    "content": "# Code generated by mdatagen. DO NOT EDIT.\n$defs:\n  metrics_config:\n    description: MetricsConfig provides config for sample metrics.\n    type: object\n    properties:\n      default.metric:\n        description: \"DefaultMetricMetricConfig provides config for the default.metric metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          aggregation_strategy:\n            type: string\n            enum:\n              - \"sum\"\n              - \"avg\"\n              - \"min\"\n              - \"max\"\n            default: \"sum\"\n          attributes:\n            type: array\n            items:\n              type: string\n              enum:\n                - \"string_attr\"\n                - \"state\"\n                - \"enum_attr\"\n                - \"slice_attr\"\n                - \"map_attr\"\n            default:\n              - \"string_attr\"\n              - \"state\"\n              - \"enum_attr\"\n              - \"slice_attr\"\n              - \"map_attr\"\n      default.metric.to_be_removed:\n        description: \"DefaultMetricToBeRemovedMetricConfig provides config for the default.metric.to_be_removed metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n      metric.input_type:\n        description: \"MetricInputTypeMetricConfig provides config for the metric.input_type metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          aggregation_strategy:\n            type: string\n            enum:\n              - \"sum\"\n              - \"avg\"\n              - \"min\"\n              - \"max\"\n            default: \"sum\"\n          attributes:\n            type: array\n            items:\n              type: string\n              enum:\n                - \"string_attr\"\n                - \"state\"\n                - \"enum_attr\"\n                - \"slice_attr\"\n                - \"map_attr\"\n            default:\n              - \"string_attr\"\n              - \"state\"\n              - \"enum_attr\"\n              - \"slice_attr\"\n              - \"map_attr\"\n      optional.metric:\n        description: \"OptionalMetricMetricConfig provides config for the optional.metric metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: false\n          aggregation_strategy:\n            type: string\n            enum:\n              - \"sum\"\n              - \"avg\"\n              - \"min\"\n              - \"max\"\n            default: \"avg\"\n          attributes:\n            type: array\n            items:\n              type: string\n              enum:\n                - \"string_attr\"\n                - \"boolean_attr\"\n                - \"boolean_attr2\"\n            default:\n              - \"string_attr\"\n              - \"boolean_attr\"\n              - \"boolean_attr2\"\n      optional.metric.empty_unit:\n        description: \"OptionalMetricEmptyUnitMetricConfig provides config for the optional.metric.empty_unit metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: false\n          aggregation_strategy:\n            type: string\n            enum:\n              - \"sum\"\n              - \"avg\"\n              - \"min\"\n              - \"max\"\n            default: \"avg\"\n          attributes:\n            type: array\n            items:\n              type: string\n              enum:\n                - \"string_attr\"\n                - \"boolean_attr\"\n            default:\n              - \"string_attr\"\n              - \"boolean_attr\"\n      reaggregate.metric:\n        description: \"ReaggregateMetricMetricConfig provides config for the reaggregate.metric metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          aggregation_strategy:\n            type: string\n            enum:\n              - \"sum\"\n              - \"avg\"\n              - \"min\"\n              - \"max\"\n            default: \"avg\"\n          attributes:\n            type: array\n            items:\n              type: string\n              enum:\n                - \"string_attr\"\n                - \"boolean_attr\"\n            default:\n              - \"string_attr\"\n              - \"boolean_attr\"\n  resource_attributes_config:\n    description: ResourceAttributesConfig provides config for sample resource attributes.\n    type: object\n    properties:\n      map.resource.attr:\n        description: ResourceAttributeConfig provides common config for a map.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      optional.resource.attr:\n        description: ResourceAttributeConfig provides common config for a optional.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: false\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      slice.resource.attr:\n        description: ResourceAttributeConfig provides common config for a slice.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      string.enum.resource.attr:\n        description: ResourceAttributeConfig provides common config for a string.enum.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      string.resource.attr:\n        description: ResourceAttributeConfig provides common config for a string.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      string.resource.attr_disable_warning:\n        description: ResourceAttributeConfig provides common config for a string.resource.attr_disable_warning resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      string.resource.attr_remove_warning:\n        description: ResourceAttributeConfig provides common config for a string.resource.attr_remove_warning resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: false\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      string.resource.attr_to_be_removed:\n        description: ResourceAttributeConfig provides common config for a string.resource.attr_to_be_removed resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n  metrics_builder_config:\n    description: MetricsBuilderConfig is a configuration for sample metrics builder.\n    type: object\n    properties:\n      metrics:\n        $ref: metrics_config\n      resource_attributes:\n        $ref: resource_attributes_config\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/internal/metadata/generated_config.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/filter\"\n)\n\n// DefaultMetricMetricAttributeKey specifies the key of an attribute for the default.metric metric.\ntype DefaultMetricMetricAttributeKey string\n\nconst (\n\tDefaultMetricMetricAttributeKeyStringAttr        DefaultMetricMetricAttributeKey = \"string_attr\"\n\tDefaultMetricMetricAttributeKeyOverriddenIntAttr DefaultMetricMetricAttributeKey = \"state\"\n\tDefaultMetricMetricAttributeKeyEnumAttr          DefaultMetricMetricAttributeKey = \"enum_attr\"\n\tDefaultMetricMetricAttributeKeySliceAttr         DefaultMetricMetricAttributeKey = \"slice_attr\"\n\tDefaultMetricMetricAttributeKeyMapAttr           DefaultMetricMetricAttributeKey = \"map_attr\"\n)\n\n// DefaultMetricMetricConfig provides config for the default.metric metric.\ntype DefaultMetricMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n\n\tAggregationStrategy string                            `mapstructure:\"aggregation_strategy\"`\n\tEnabledAttributes   []DefaultMetricMetricAttributeKey `mapstructure:\"attributes\"`\n}\n\nfunc (ms *DefaultMetricMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\nfunc (ms *DefaultMetricMetricConfig) Validate() error {\n\tfor _, val := range ms.EnabledAttributes {\n\t\tswitch val {\n\t\tcase DefaultMetricMetricAttributeKeyStringAttr, DefaultMetricMetricAttributeKeyOverriddenIntAttr, DefaultMetricMetricAttributeKeyEnumAttr, DefaultMetricMetricAttributeKeySliceAttr, DefaultMetricMetricAttributeKeyMapAttr:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"metric default.metric doesn't have an attribute %v, valid attributes: [string_attr, state, enum_attr, slice_attr, map_attr]\", val)\n\t\t}\n\t}\n\n\tswitch ms.AggregationStrategy {\n\tcase AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax:\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation strategy %q, valid strategies: [%s, %s, %s, %s]\", ms.AggregationStrategy, AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax)\n\t}\n\n\treturn nil\n}\n\n// DefaultMetricToBeRemovedMetricConfig provides config for the default.metric.to_be_removed metric.\ntype DefaultMetricToBeRemovedMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n}\n\nfunc (ms *DefaultMetricToBeRemovedMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\n// MetricInputTypeMetricAttributeKey specifies the key of an attribute for the metric.input_type metric.\ntype MetricInputTypeMetricAttributeKey string\n\nconst (\n\tMetricInputTypeMetricAttributeKeyStringAttr        MetricInputTypeMetricAttributeKey = \"string_attr\"\n\tMetricInputTypeMetricAttributeKeyOverriddenIntAttr MetricInputTypeMetricAttributeKey = \"state\"\n\tMetricInputTypeMetricAttributeKeyEnumAttr          MetricInputTypeMetricAttributeKey = \"enum_attr\"\n\tMetricInputTypeMetricAttributeKeySliceAttr         MetricInputTypeMetricAttributeKey = \"slice_attr\"\n\tMetricInputTypeMetricAttributeKeyMapAttr           MetricInputTypeMetricAttributeKey = \"map_attr\"\n)\n\n// MetricInputTypeMetricConfig provides config for the metric.input_type metric.\ntype MetricInputTypeMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n\n\tAggregationStrategy string                              `mapstructure:\"aggregation_strategy\"`\n\tEnabledAttributes   []MetricInputTypeMetricAttributeKey `mapstructure:\"attributes\"`\n}\n\nfunc (ms *MetricInputTypeMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\nfunc (ms *MetricInputTypeMetricConfig) Validate() error {\n\tfor _, val := range ms.EnabledAttributes {\n\t\tswitch val {\n\t\tcase MetricInputTypeMetricAttributeKeyStringAttr, MetricInputTypeMetricAttributeKeyOverriddenIntAttr, MetricInputTypeMetricAttributeKeyEnumAttr, MetricInputTypeMetricAttributeKeySliceAttr, MetricInputTypeMetricAttributeKeyMapAttr:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"metric metric.input_type doesn't have an attribute %v, valid attributes: [string_attr, state, enum_attr, slice_attr, map_attr]\", val)\n\t\t}\n\t}\n\n\tswitch ms.AggregationStrategy {\n\tcase AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax:\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation strategy %q, valid strategies: [%s, %s, %s, %s]\", ms.AggregationStrategy, AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax)\n\t}\n\n\treturn nil\n}\n\n// OptionalMetricMetricAttributeKey specifies the key of an attribute for the optional.metric metric.\ntype OptionalMetricMetricAttributeKey string\n\nconst (\n\tOptionalMetricMetricAttributeKeyStringAttr   OptionalMetricMetricAttributeKey = \"string_attr\"\n\tOptionalMetricMetricAttributeKeyBooleanAttr  OptionalMetricMetricAttributeKey = \"boolean_attr\"\n\tOptionalMetricMetricAttributeKeyBooleanAttr2 OptionalMetricMetricAttributeKey = \"boolean_attr2\"\n)\n\n// OptionalMetricMetricConfig provides config for the optional.metric metric.\ntype OptionalMetricMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n\n\tAggregationStrategy string                             `mapstructure:\"aggregation_strategy\"`\n\tEnabledAttributes   []OptionalMetricMetricAttributeKey `mapstructure:\"attributes\"`\n}\n\nfunc (ms *OptionalMetricMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\nfunc (ms *OptionalMetricMetricConfig) Validate() error {\n\tfor _, val := range ms.EnabledAttributes {\n\t\tswitch val {\n\t\tcase OptionalMetricMetricAttributeKeyStringAttr, OptionalMetricMetricAttributeKeyBooleanAttr, OptionalMetricMetricAttributeKeyBooleanAttr2:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"metric optional.metric doesn't have an attribute %v, valid attributes: [string_attr, boolean_attr, boolean_attr2]\", val)\n\t\t}\n\t}\n\n\tswitch ms.AggregationStrategy {\n\tcase AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax:\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation strategy %q, valid strategies: [%s, %s, %s, %s]\", ms.AggregationStrategy, AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax)\n\t}\n\n\treturn nil\n}\n\n// OptionalMetricEmptyUnitMetricAttributeKey specifies the key of an attribute for the optional.metric.empty_unit metric.\ntype OptionalMetricEmptyUnitMetricAttributeKey string\n\nconst (\n\tOptionalMetricEmptyUnitMetricAttributeKeyStringAttr  OptionalMetricEmptyUnitMetricAttributeKey = \"string_attr\"\n\tOptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr OptionalMetricEmptyUnitMetricAttributeKey = \"boolean_attr\"\n)\n\n// OptionalMetricEmptyUnitMetricConfig provides config for the optional.metric.empty_unit metric.\ntype OptionalMetricEmptyUnitMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n\n\tAggregationStrategy string                                      `mapstructure:\"aggregation_strategy\"`\n\tEnabledAttributes   []OptionalMetricEmptyUnitMetricAttributeKey `mapstructure:\"attributes\"`\n}\n\nfunc (ms *OptionalMetricEmptyUnitMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\nfunc (ms *OptionalMetricEmptyUnitMetricConfig) Validate() error {\n\tfor _, val := range ms.EnabledAttributes {\n\t\tswitch val {\n\t\tcase OptionalMetricEmptyUnitMetricAttributeKeyStringAttr, OptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"metric optional.metric.empty_unit doesn't have an attribute %v, valid attributes: [string_attr, boolean_attr]\", val)\n\t\t}\n\t}\n\n\tswitch ms.AggregationStrategy {\n\tcase AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax:\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation strategy %q, valid strategies: [%s, %s, %s, %s]\", ms.AggregationStrategy, AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax)\n\t}\n\n\treturn nil\n}\n\n// ReaggregateMetricMetricAttributeKey specifies the key of an attribute for the reaggregate.metric metric.\ntype ReaggregateMetricMetricAttributeKey string\n\nconst (\n\tReaggregateMetricMetricAttributeKeyStringAttr  ReaggregateMetricMetricAttributeKey = \"string_attr\"\n\tReaggregateMetricMetricAttributeKeyBooleanAttr ReaggregateMetricMetricAttributeKey = \"boolean_attr\"\n)\n\n// ReaggregateMetricMetricConfig provides config for the reaggregate.metric metric.\ntype ReaggregateMetricMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n\n\tAggregationStrategy string                                `mapstructure:\"aggregation_strategy\"`\n\tEnabledAttributes   []ReaggregateMetricMetricAttributeKey `mapstructure:\"attributes\"`\n}\n\nfunc (ms *ReaggregateMetricMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\nfunc (ms *ReaggregateMetricMetricConfig) Validate() error {\n\tfor _, val := range ms.EnabledAttributes {\n\t\tswitch val {\n\t\tcase ReaggregateMetricMetricAttributeKeyStringAttr, ReaggregateMetricMetricAttributeKeyBooleanAttr:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"metric reaggregate.metric doesn't have an attribute %v, valid attributes: [string_attr, boolean_attr]\", val)\n\t\t}\n\t}\n\n\tswitch ms.AggregationStrategy {\n\tcase AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax:\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation strategy %q, valid strategies: [%s, %s, %s, %s]\", ms.AggregationStrategy, AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax)\n\t}\n\n\treturn nil\n}\n\n// MetricsConfig provides config for sample metrics.\ntype MetricsConfig struct {\n\tDefaultMetric            DefaultMetricMetricConfig            `mapstructure:\"default.metric\"`\n\tDefaultMetricToBeRemoved DefaultMetricToBeRemovedMetricConfig `mapstructure:\"default.metric.to_be_removed\"`\n\tMetricInputType          MetricInputTypeMetricConfig          `mapstructure:\"metric.input_type\"`\n\tOptionalMetric           OptionalMetricMetricConfig           `mapstructure:\"optional.metric\"`\n\tOptionalMetricEmptyUnit  OptionalMetricEmptyUnitMetricConfig  `mapstructure:\"optional.metric.empty_unit\"`\n\tReaggregateMetric        ReaggregateMetricMetricConfig        `mapstructure:\"reaggregate.metric\"`\n}\n\nfunc DefaultMetricsConfig() MetricsConfig {\n\treturn MetricsConfig{\n\t\tDefaultMetric: DefaultMetricMetricConfig{\n\t\t\tEnabled:             true,\n\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\tEnabledAttributes:   []DefaultMetricMetricAttributeKey{DefaultMetricMetricAttributeKeyStringAttr, DefaultMetricMetricAttributeKeyOverriddenIntAttr, DefaultMetricMetricAttributeKeyEnumAttr, DefaultMetricMetricAttributeKeySliceAttr, DefaultMetricMetricAttributeKeyMapAttr},\n\t\t},\n\t\tDefaultMetricToBeRemoved: DefaultMetricToBeRemovedMetricConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tMetricInputType: MetricInputTypeMetricConfig{\n\t\t\tEnabled:             true,\n\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\tEnabledAttributes:   []MetricInputTypeMetricAttributeKey{MetricInputTypeMetricAttributeKeyStringAttr, MetricInputTypeMetricAttributeKeyOverriddenIntAttr, MetricInputTypeMetricAttributeKeyEnumAttr, MetricInputTypeMetricAttributeKeySliceAttr, MetricInputTypeMetricAttributeKeyMapAttr},\n\t\t},\n\t\tOptionalMetric: OptionalMetricMetricConfig{\n\t\t\tEnabled:             false,\n\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\tEnabledAttributes:   []OptionalMetricMetricAttributeKey{OptionalMetricMetricAttributeKeyStringAttr, OptionalMetricMetricAttributeKeyBooleanAttr, OptionalMetricMetricAttributeKeyBooleanAttr2},\n\t\t},\n\t\tOptionalMetricEmptyUnit: OptionalMetricEmptyUnitMetricConfig{\n\t\t\tEnabled:             false,\n\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\tEnabledAttributes:   []OptionalMetricEmptyUnitMetricAttributeKey{OptionalMetricEmptyUnitMetricAttributeKeyStringAttr, OptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr},\n\t\t},\n\t\tReaggregateMetric: ReaggregateMetricMetricConfig{\n\t\t\tEnabled:             true,\n\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\tEnabledAttributes:   []ReaggregateMetricMetricAttributeKey{ReaggregateMetricMetricAttributeKeyStringAttr, ReaggregateMetricMetricAttributeKeyBooleanAttr},\n\t\t},\n\t}\n}\n\n// ResourceAttributeConfig provides common config for a particular resource attribute.\ntype ResourceAttributeConfig struct {\n\tEnabled bool `mapstructure:\"enabled\"`\n\t// Experimental: MetricsInclude defines a list of filters for attribute values.\n\t// If the list is not empty, only metrics with matching resource attribute values will be emitted.\n\tMetricsInclude []filter.Config `mapstructure:\"metrics_include\"`\n\t// Experimental: MetricsExclude defines a list of filters for attribute values.\n\t// If the list is not empty, metrics with matching resource attribute values will not be emitted.\n\t// MetricsInclude has higher priority than MetricsExclude.\n\tMetricsExclude []filter.Config `mapstructure:\"metrics_exclude\"`\n\n\tenabledSetByUser bool\n}\n\nfunc (rac *ResourceAttributeConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\terr := parser.Unmarshal(rac)\n\tif err != nil {\n\t\treturn err\n\t}\n\trac.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\n// ResourceAttributesConfig provides config for sample resource attributes.\ntype ResourceAttributesConfig struct {\n\tMapResourceAttr                  ResourceAttributeConfig `mapstructure:\"map.resource.attr\"`\n\tOptionalResourceAttr             ResourceAttributeConfig `mapstructure:\"optional.resource.attr\"`\n\tSliceResourceAttr                ResourceAttributeConfig `mapstructure:\"slice.resource.attr\"`\n\tStringEnumResourceAttr           ResourceAttributeConfig `mapstructure:\"string.enum.resource.attr\"`\n\tStringResourceAttr               ResourceAttributeConfig `mapstructure:\"string.resource.attr\"`\n\tStringResourceAttrDisableWarning ResourceAttributeConfig `mapstructure:\"string.resource.attr_disable_warning\"`\n\tStringResourceAttrRemoveWarning  ResourceAttributeConfig `mapstructure:\"string.resource.attr_remove_warning\"`\n\tStringResourceAttrToBeRemoved    ResourceAttributeConfig `mapstructure:\"string.resource.attr_to_be_removed\"`\n}\n\nfunc DefaultResourceAttributesConfig() ResourceAttributesConfig {\n\treturn ResourceAttributesConfig{\n\t\tMapResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tOptionalResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: false,\n\t\t},\n\t\tSliceResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringEnumResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringResourceAttrRemoveWarning: ResourceAttributeConfig{\n\t\t\tEnabled: false,\n\t\t},\n\t\tStringResourceAttrToBeRemoved: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t}\n}\n\n// MetricsBuilderConfig is a configuration for sample metrics builder.\ntype MetricsBuilderConfig struct {\n\tMetrics            MetricsConfig            `mapstructure:\"metrics\"`\n\tResourceAttributes ResourceAttributesConfig `mapstructure:\"resource_attributes\"`\n}\n\nfunc DefaultMetricsBuilderConfig() MetricsBuilderConfig {\n\treturn MetricsBuilderConfig{\n\t\tMetrics:            DefaultMetricsConfig(),\n\t\tResourceAttributes: DefaultResourceAttributesConfig(),\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/internal/metadata/generated_config_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n\t\"github.com/google/go-cmp/cmp/cmpopts\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n)\n\nfunc TestMetricsBuilderConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant MetricsBuilderConfig\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\twant: DefaultMetricsBuilderConfig(),\n\t\t},\n\t\t{\n\t\t\tname: \"all_set\",\n\t\t\twant: MetricsBuilderConfig{\n\t\t\t\tMetrics: MetricsConfig{\n\t\t\t\t\tDefaultMetric: DefaultMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             true,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\t\t\t\tEnabledAttributes:   []DefaultMetricMetricAttributeKey{DefaultMetricMetricAttributeKeyStringAttr, DefaultMetricMetricAttributeKeyOverriddenIntAttr, DefaultMetricMetricAttributeKeyEnumAttr, DefaultMetricMetricAttributeKeySliceAttr, DefaultMetricMetricAttributeKeyMapAttr},\n\t\t\t\t\t},\n\t\t\t\t\tDefaultMetricToBeRemoved: DefaultMetricToBeRemovedMetricConfig{\n\t\t\t\t\t\tEnabled: true,\n\t\t\t\t\t},\n\t\t\t\t\tMetricInputType: MetricInputTypeMetricConfig{\n\t\t\t\t\t\tEnabled:             true,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\t\t\t\tEnabledAttributes:   []MetricInputTypeMetricAttributeKey{MetricInputTypeMetricAttributeKeyStringAttr, MetricInputTypeMetricAttributeKeyOverriddenIntAttr, MetricInputTypeMetricAttributeKeyEnumAttr, MetricInputTypeMetricAttributeKeySliceAttr, MetricInputTypeMetricAttributeKeyMapAttr},\n\t\t\t\t\t},\n\t\t\t\t\tOptionalMetric: OptionalMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             true,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []OptionalMetricMetricAttributeKey{OptionalMetricMetricAttributeKeyStringAttr, OptionalMetricMetricAttributeKeyBooleanAttr, OptionalMetricMetricAttributeKeyBooleanAttr2},\n\t\t\t\t\t},\n\t\t\t\t\tOptionalMetricEmptyUnit: OptionalMetricEmptyUnitMetricConfig{\n\t\t\t\t\t\tEnabled:             true,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []OptionalMetricEmptyUnitMetricAttributeKey{OptionalMetricEmptyUnitMetricAttributeKeyStringAttr, OptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr},\n\t\t\t\t\t},\n\t\t\t\t\tReaggregateMetric: ReaggregateMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             true,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []ReaggregateMetricMetricAttributeKey{ReaggregateMetricMetricAttributeKeyStringAttr, ReaggregateMetricMetricAttributeKeyBooleanAttr},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tResourceAttributes: ResourceAttributesConfig{\n\t\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: true},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"none_set\",\n\t\t\twant: MetricsBuilderConfig{\n\t\t\t\tMetrics: MetricsConfig{\n\t\t\t\t\tDefaultMetric: DefaultMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             false,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\t\t\t\tEnabledAttributes:   []DefaultMetricMetricAttributeKey{DefaultMetricMetricAttributeKeyStringAttr, DefaultMetricMetricAttributeKeyOverriddenIntAttr, DefaultMetricMetricAttributeKeyEnumAttr, DefaultMetricMetricAttributeKeySliceAttr, DefaultMetricMetricAttributeKeyMapAttr},\n\t\t\t\t\t},\n\t\t\t\t\tDefaultMetricToBeRemoved: DefaultMetricToBeRemovedMetricConfig{\n\t\t\t\t\t\tEnabled: false,\n\t\t\t\t\t},\n\t\t\t\t\tMetricInputType: MetricInputTypeMetricConfig{\n\t\t\t\t\t\tEnabled:             false,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\t\t\t\tEnabledAttributes:   []MetricInputTypeMetricAttributeKey{MetricInputTypeMetricAttributeKeyStringAttr, MetricInputTypeMetricAttributeKeyOverriddenIntAttr, MetricInputTypeMetricAttributeKeyEnumAttr, MetricInputTypeMetricAttributeKeySliceAttr, MetricInputTypeMetricAttributeKeyMapAttr},\n\t\t\t\t\t},\n\t\t\t\t\tOptionalMetric: OptionalMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             false,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []OptionalMetricMetricAttributeKey{OptionalMetricMetricAttributeKeyStringAttr, OptionalMetricMetricAttributeKeyBooleanAttr, OptionalMetricMetricAttributeKeyBooleanAttr2},\n\t\t\t\t\t},\n\t\t\t\t\tOptionalMetricEmptyUnit: OptionalMetricEmptyUnitMetricConfig{\n\t\t\t\t\t\tEnabled:             false,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []OptionalMetricEmptyUnitMetricAttributeKey{OptionalMetricEmptyUnitMetricAttributeKeyStringAttr, OptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr},\n\t\t\t\t\t},\n\t\t\t\t\tReaggregateMetric: ReaggregateMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             false,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []ReaggregateMetricMetricAttributeKey{ReaggregateMetricMetricAttributeKeyStringAttr, ReaggregateMetricMetricAttributeKeyBooleanAttr},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tResourceAttributes: ResourceAttributesConfig{\n\t\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: false},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := loadMetricsBuilderConfig(t, tt.name)\n\t\t\tdiff := cmp.Diff(tt.want, cfg, cmpopts.IgnoreUnexported(DefaultMetricMetricConfig{}, DefaultMetricToBeRemovedMetricConfig{}, MetricInputTypeMetricConfig{}, OptionalMetricMetricConfig{}, OptionalMetricEmptyUnitMetricConfig{}, ReaggregateMetricMetricConfig{}, ResourceAttributeConfig{}))\n\t\t\trequire.Emptyf(t, diff, \"Config mismatch (-expected +actual):\\n%s\", diff)\n\t\t})\n\t}\n}\n\nfunc loadMetricsBuilderConfig(t *testing.T, name string) MetricsBuilderConfig {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tsub, err := cm.Sub(name)\n\trequire.NoError(t, err)\n\tcfg := DefaultMetricsBuilderConfig()\n\trequire.NoError(t, sub.Unmarshal(&cfg, confmap.WithIgnoreUnused()))\n\treturn cfg\n}\n\nfunc TestResourceAttributesConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant ResourceAttributesConfig\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\twant: DefaultResourceAttributesConfig(),\n\t\t},\n\t\t{\n\t\t\tname: \"all_set\",\n\t\t\twant: ResourceAttributesConfig{\n\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: true},\n\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: true},\n\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: true},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"none_set\",\n\t\t\twant: ResourceAttributesConfig{\n\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: false},\n\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: false},\n\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: false},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := loadResourceAttributesConfig(t, tt.name)\n\t\t\tdiff := cmp.Diff(tt.want, cfg, cmpopts.IgnoreUnexported(ResourceAttributeConfig{}))\n\t\t\trequire.Emptyf(t, diff, \"Config mismatch (-expected +actual):\\n%s\", diff)\n\t\t})\n\t}\n}\n\nfunc loadResourceAttributesConfig(t *testing.T, name string) ResourceAttributesConfig {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tsub, err := cm.Sub(name)\n\trequire.NoError(t, err)\n\tsub, err = sub.Sub(\"resource_attributes\")\n\trequire.NoError(t, err)\n\tcfg := DefaultResourceAttributesConfig()\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\treturn cfg\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/internal/metadata/generated_entity_metrics.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/entity\"\n)\n\n// TestEntityEntity represents a test.entity entity.\n// Create one with NewTestEntityEntity and pass it to EmitForEntity.\ntype TestEntityEntity struct {\n\tstringResourceAttr string\n\tmapResourceAttr    map[string]any\n}\n\n// NewTestEntityEntity creates a new TestEntityEntity.\n// Identity attributes are required and must be provided at construction time.\nfunc NewTestEntityEntity(stringResourceAttr string) *TestEntityEntity {\n\treturn &TestEntityEntity{\n\t\tstringResourceAttr: stringResourceAttr,\n\t}\n}\n\n// Description attribute setters for test.entity.\n\n// SetMapResourceAttr sets the map.resource.attr description attribute.\nfunc (e *TestEntityEntity) SetMapResourceAttr(val map[string]any) {\n\te.mapResourceAttr = val\n}\n\n// copyToResource populates res with the entity's attributes according to cfg.\n// If all identity attributes are enabled, an entity ref is produced; otherwise\n// the enabled attributes are written directly as plain resource attributes.\nfunc (e *TestEntityEntity) copyToResource(cfg ResourceAttributesConfig, res pcommon.Resource) {\n\tif cfg.StringResourceAttr.Enabled {\n\t\tent := entity.ResourceEntities(res).PutEmpty(\"test.entity\")\n\t\tent.IdentifyingAttributes().PutStr(\"string.resource.attr\", e.stringResourceAttr)\n\t\tif cfg.MapResourceAttr.Enabled {\n\t\t\tent.DescriptiveAttributes().PutEmpty(\"map.resource.attr\").SetEmptyMap().FromRaw(e.mapResourceAttr)\n\t\t}\n\t} else {\n\t\tif cfg.StringResourceAttr.Enabled {\n\t\t\tres.Attributes().PutStr(\"string.resource.attr\", e.stringResourceAttr)\n\t\t}\n\t\tif cfg.MapResourceAttr.Enabled {\n\t\t\tres.Attributes().PutEmptyMap(\"map.resource.attr\").FromRaw(e.mapResourceAttr)\n\t\t}\n\t}\n}\n\n// TestEntityMetricsBuilder records metrics for the test.entity entity.\n// Obtain one via MetricsBuilder.ForTestEntity().\ntype TestEntityMetricsBuilder struct {\n\tmb     *MetricsBuilder\n\tentity *TestEntityEntity\n}\n\n// RecordDefaultMetricDataPoint records a data point for the default.metric metric.\nfunc (eb *TestEntityMetricsBuilder) RecordDefaultMetricDataPoint(ts pcommon.Timestamp, val int64, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue AttributeEnumAttr, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any) {\n\teb.mb.metricDefaultMetric.recordDataPoint(eb.mb.startTime, ts, val, stringAttrAttributeValue, overriddenIntAttrAttributeValue, enumAttrAttributeValue.String(), sliceAttrAttributeValue, mapAttrAttributeValue)\n}\n\n// RecordDefaultMetricToBeRemovedDataPoint records a data point for the default.metric.to_be_removed metric.\nfunc (eb *TestEntityMetricsBuilder) RecordDefaultMetricToBeRemovedDataPoint(ts pcommon.Timestamp, val float64) {\n\teb.mb.metricDefaultMetricToBeRemoved.recordDataPoint(eb.mb.startTime, ts, val)\n}\n\n// RecordMetricInputTypeDataPoint records a data point for the metric.input_type metric.\nfunc (eb *TestEntityMetricsBuilder) RecordMetricInputTypeDataPoint(ts pcommon.Timestamp, inputVal string, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue AttributeEnumAttr, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MetricInputType, value was %s: %w\", inputVal, err)\n\t}\n\teb.mb.metricMetricInputType.recordDataPoint(eb.mb.startTime, ts, val, stringAttrAttributeValue, overriddenIntAttrAttributeValue, enumAttrAttributeValue.String(), sliceAttrAttributeValue, mapAttrAttributeValue)\n\treturn nil\n}\n\n// RecordOptionalMetricDataPoint records a data point for the optional.metric metric.\nfunc (eb *TestEntityMetricsBuilder) RecordOptionalMetricDataPoint(ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool, booleanAttr2AttributeValue bool) {\n\teb.mb.metricOptionalMetric.recordDataPoint(eb.mb.startTime, ts, val, stringAttrAttributeValue, booleanAttrAttributeValue, booleanAttr2AttributeValue)\n}\n\n// RecordOptionalMetricEmptyUnitDataPoint records a data point for the optional.metric.empty_unit metric.\nfunc (eb *TestEntityMetricsBuilder) RecordOptionalMetricEmptyUnitDataPoint(ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\teb.mb.metricOptionalMetricEmptyUnit.recordDataPoint(eb.mb.startTime, ts, val, stringAttrAttributeValue, booleanAttrAttributeValue)\n}\n\n// RecordReaggregateMetricDataPoint records a data point for the reaggregate.metric metric.\nfunc (eb *TestEntityMetricsBuilder) RecordReaggregateMetricDataPoint(ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\teb.mb.metricReaggregateMetric.recordDataPoint(eb.mb.startTime, ts, val, stringAttrAttributeValue, booleanAttrAttributeValue)\n}\n\n// Emit emits all pending metrics for the entity. Resource attributes are filtered by config:\n// disabled identity attributes suppress the entity (other enabled attributes are added directly\n// to the resource); disabled descriptive/extra attributes are omitted entirely.\nfunc (eb *TestEntityMetricsBuilder) Emit() {\n\tres := pcommon.NewResource()\n\tcfg := eb.mb.config.ResourceAttributes\n\teb.entity.copyToResource(cfg, res)\n\teb.mb.EmitForResource(withResourceMoved(res))\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/internal/metadata/generated_entity_metrics_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/connector/connectortest\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/entity\"\n)\n\nfunc TestEntityBuilders(t *testing.T) {\n\tstart := pcommon.Timestamp(1_000_000_000)\n\tts := pcommon.Timestamp(1_000_001_000)\n\tsettings := connectortest.NewNopSettings(connectortest.NopType)\n\tmb := NewMetricsBuilder(DefaultMetricsBuilderConfig(), settings, WithStartTime(start))\n\n\tt.Run(\"test.entity\", func(t *testing.T) {\n\t\te := NewTestEntityEntity(\"string.resource.attr-val\")\n\t\trequire.NotNil(t, e)\n\t\te.SetMapResourceAttr(map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"})\n\n\t\teb := mb.ForTestEntity(e)\n\t\teb.RecordDefaultMetricDataPoint(ts, 1, \"string_attr-val\", 19, AttributeEnumAttrRed, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"})\n\t\teb.RecordDefaultMetricToBeRemovedDataPoint(ts, 1)\n\t\teb.RecordMetricInputTypeDataPoint(ts, \"1\", \"string_attr-val\", 19, AttributeEnumAttrRed, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"})\n\t\teb.RecordOptionalMetricDataPoint(ts, 1, \"string_attr-val\", true, false)\n\t\teb.RecordOptionalMetricEmptyUnitDataPoint(ts, 1, \"string_attr-val\", true)\n\t\teb.RecordReaggregateMetricDataPoint(ts, 1, \"string_attr-val\", true)\n\t\teb.Emit()\n\t\tmetrics := mb.Emit()\n\n\t\trequire.Equal(t, 1, metrics.ResourceMetrics().Len())\n\t\trm := metrics.ResourceMetrics().At(0)\n\t\tentityVal, ok := entity.ResourceEntities(rm.Resource()).Get(\"test.entity\")\n\t\trequire.True(t, ok)\n\t\tstringResourceAttrAttrVal, ok := entityVal.IdentifyingAttributes().Get(\"string.resource.attr\")\n\t\trequire.True(t, ok)\n\t\tassert.Equal(t, \"string.resource.attr-val\", stringResourceAttrAttrVal.Str())\n\t\tmapResourceAttrAttrVal, ok := entityVal.DescriptiveAttributes().Get(\"map.resource.attr\")\n\t\trequire.True(t, ok)\n\t\tassert.Equal(t, map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"}, mapResourceAttrAttrVal.Map().AsRaw())\n\n\t\trequire.Equal(t, 1, rm.ScopeMetrics().Len())\n\t\tms := rm.ScopeMetrics().At(0).Metrics()\n\t\tassert.Equal(t, 4, ms.Len())\n\t})\n\tt.Run(\"test.entity/disabled_identity_attr\", func(t *testing.T) {\n\t\t// When an identity attribute is disabled, the entity is not produced but\n\t\t// other enabled attributes are still added to the resource directly.\n\t\tcfg := DefaultMetricsBuilderConfig()\n\t\tcfg.ResourceAttributes.StringResourceAttr.Enabled = false\n\t\tmb := NewMetricsBuilder(cfg, settings, WithStartTime(start))\n\n\t\te := NewTestEntityEntity(\"string.resource.attr-val\")\n\t\te.SetMapResourceAttr(map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"})\n\n\t\teb := mb.ForTestEntity(e)\n\t\teb.RecordDefaultMetricDataPoint(ts, 1, \"string_attr-val\", 19, AttributeEnumAttrRed, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"})\n\t\teb.RecordDefaultMetricToBeRemovedDataPoint(ts, 1)\n\t\teb.RecordMetricInputTypeDataPoint(ts, \"1\", \"string_attr-val\", 19, AttributeEnumAttrRed, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"})\n\t\teb.RecordOptionalMetricDataPoint(ts, 1, \"string_attr-val\", true, false)\n\t\teb.RecordOptionalMetricEmptyUnitDataPoint(ts, 1, \"string_attr-val\", true)\n\t\teb.RecordReaggregateMetricDataPoint(ts, 1, \"string_attr-val\", true)\n\t\teb.Emit()\n\t\tmetrics := mb.Emit()\n\n\t\trequire.Equal(t, 1, metrics.ResourceMetrics().Len())\n\t\trm := metrics.ResourceMetrics().At(0)\n\t\t// Entity must not be present since its identity attribute is disabled.\n\t\t_, ok := entity.ResourceEntities(rm.Resource()).Get(\"test.entity\")\n\t\tassert.False(t, ok)\n\t\t// Enabled descriptive attributes should still be on the resource directly.\n\t\t_, ok = rm.Resource().Attributes().Get(\"map.resource.attr\")\n\t\tassert.True(t, ok)\n\t})\n\tt.Run(\"test.entity/disabled_descriptive_attr\", func(t *testing.T) {\n\t\t// When a descriptive attribute is disabled, the entity is still produced\n\t\t// with its identity but the disabled attribute is not added.\n\t\tcfg := DefaultMetricsBuilderConfig()\n\t\tcfg.ResourceAttributes.MapResourceAttr.Enabled = false\n\t\tmb := NewMetricsBuilder(cfg, settings, WithStartTime(start))\n\n\t\te := NewTestEntityEntity(\"string.resource.attr-val\")\n\t\te.SetMapResourceAttr(map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"})\n\n\t\teb := mb.ForTestEntity(e)\n\t\teb.RecordDefaultMetricDataPoint(ts, 1, \"string_attr-val\", 19, AttributeEnumAttrRed, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"})\n\t\teb.RecordDefaultMetricToBeRemovedDataPoint(ts, 1)\n\t\teb.RecordMetricInputTypeDataPoint(ts, \"1\", \"string_attr-val\", 19, AttributeEnumAttrRed, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"})\n\t\teb.RecordOptionalMetricDataPoint(ts, 1, \"string_attr-val\", true, false)\n\t\teb.RecordOptionalMetricEmptyUnitDataPoint(ts, 1, \"string_attr-val\", true)\n\t\teb.RecordReaggregateMetricDataPoint(ts, 1, \"string_attr-val\", true)\n\t\teb.Emit()\n\t\tmetrics := mb.Emit()\n\n\t\trequire.Equal(t, 1, metrics.ResourceMetrics().Len())\n\t\trm := metrics.ResourceMetrics().At(0)\n\t\t// Entity must still be produced since identity attributes are enabled.\n\t\tentityVal, ok := entity.ResourceEntities(rm.Resource()).Get(\"test.entity\")\n\t\trequire.True(t, ok)\n\t\tstringResourceAttrAttrVal, ok := entityVal.IdentifyingAttributes().Get(\"string.resource.attr\")\n\t\trequire.True(t, ok)\n\t\tassert.Equal(t, \"string.resource.attr-val\", stringResourceAttrAttrVal.Str())\n\t\t// Disabled descriptive/extra attributes must not be present.\n\t\t_, ok = entityVal.DescriptiveAttributes().Get(\"map.resource.attr\")\n\t\tassert.False(t, ok)\n\t})\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/internal/metadata/generated_metrics.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"fmt\"\n\t\"slices\"\n\t\"strconv\"\n\t\"time\"\n\n\tconventions \"go.opentelemetry.io/otel/semconv/v1.9.0\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/filter\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\nconst (\n\tAggregationStrategySum = \"sum\"\n\tAggregationStrategyAvg = \"avg\"\n\tAggregationStrategyMin = \"min\"\n\tAggregationStrategyMax = \"max\"\n)\n\n// AttributeEnumAttr specifies the value enum_attr attribute.\ntype AttributeEnumAttr int\n\nconst (\n\t_ AttributeEnumAttr = iota\n\tAttributeEnumAttrRed\n\tAttributeEnumAttrGreen\n\tAttributeEnumAttrBlue\n)\n\n// String returns the string representation of the AttributeEnumAttr.\nfunc (av AttributeEnumAttr) String() string {\n\tswitch av {\n\tcase AttributeEnumAttrRed:\n\t\treturn \"red\"\n\tcase AttributeEnumAttrGreen:\n\t\treturn \"green\"\n\tcase AttributeEnumAttrBlue:\n\t\treturn \"blue\"\n\t}\n\treturn \"\"\n}\n\n// MapAttributeEnumAttr is a helper map of string to AttributeEnumAttr attribute value.\nvar MapAttributeEnumAttr = map[string]AttributeEnumAttr{\n\t\"red\":   AttributeEnumAttrRed,\n\t\"green\": AttributeEnumAttrGreen,\n\t\"blue\":  AttributeEnumAttrBlue,\n}\n\nvar MetricsInfo = metricsInfo{\n\tDefaultMetric: metricInfo{\n\t\tName: \"default.metric\",\n\t},\n\tDefaultMetricToBeRemoved: metricInfo{\n\t\tName: \"default.metric.to_be_removed\",\n\t},\n\tMetricInputType: metricInfo{\n\t\tName: \"metric.input_type\",\n\t},\n\tOptionalMetric: metricInfo{\n\t\tName: \"optional.metric\",\n\t},\n\tOptionalMetricEmptyUnit: metricInfo{\n\t\tName: \"optional.metric.empty_unit\",\n\t},\n\tReaggregateMetric: metricInfo{\n\t\tName: \"reaggregate.metric\",\n\t},\n}\n\ntype metricsInfo struct {\n\tDefaultMetric            metricInfo\n\tDefaultMetricToBeRemoved metricInfo\n\tMetricInputType          metricInfo\n\tOptionalMetric           metricInfo\n\tOptionalMetricEmptyUnit  metricInfo\n\tReaggregateMetric        metricInfo\n}\n\ntype metricInfo struct {\n\tName string\n}\n\ntype metricDefaultMetric struct {\n\tdata          pmetric.Metric            // data buffer for generated metric.\n\tconfig        DefaultMetricMetricConfig // metric config provided by user.\n\tcapacity      int                       // max observed number of data points added to the metric.\n\taggDataPoints []int64                   // slice containing number of aggregated datapoints at each index\n}\n\n// init fills default.metric metric with initial data.\nfunc (m *metricDefaultMetric) init() {\n\tm.data.SetName(\"default.metric\")\n\tm.data.SetDescription(\"Monotonic cumulative sum int metric enabled by default.\")\n\tm.data.SetUnit(\"s\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(true)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n\tm.data.Sum().DataPoints().EnsureCapacity(m.capacity)\n\tm.aggDataPoints = m.aggDataPoints[:0]\n}\n\nfunc (m *metricDefaultMetric) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val int64, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue string, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\n\tdp := pmetric.NewNumberDataPoint()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tif slices.Contains(m.config.EnabledAttributes, DefaultMetricMetricAttributeKeyStringAttr) {\n\t\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, DefaultMetricMetricAttributeKeyOverriddenIntAttr) {\n\t\tdp.Attributes().PutInt(\"state\", overriddenIntAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, DefaultMetricMetricAttributeKeyEnumAttr) {\n\t\tdp.Attributes().PutStr(\"enum_attr\", enumAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, DefaultMetricMetricAttributeKeySliceAttr) {\n\t\tdp.Attributes().PutEmptySlice(\"slice_attr\").FromRaw(sliceAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, DefaultMetricMetricAttributeKeyMapAttr) {\n\t\tdp.Attributes().PutEmptyMap(\"map_attr\").FromRaw(mapAttrAttributeValue)\n\t}\n\n\tvar s string\n\tdps := m.data.Sum().DataPoints()\n\tfor i := 0; i < dps.Len(); i++ {\n\t\tdpi := dps.At(i)\n\t\tif dp.Attributes().Equal(dpi.Attributes()) && dp.StartTimestamp() == dpi.StartTimestamp() && dp.Timestamp() == dpi.Timestamp() {\n\t\t\tswitch s = m.config.AggregationStrategy; s {\n\t\t\tcase AggregationStrategySum, AggregationStrategyAvg:\n\t\t\t\tdpi.SetIntValue(dpi.IntValue() + val)\n\t\t\t\tm.aggDataPoints[i] += 1\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMin:\n\t\t\t\tif dpi.IntValue() > val {\n\t\t\t\t\tdpi.SetIntValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMax:\n\t\t\t\tif dpi.IntValue() < val {\n\t\t\t\t\tdpi.SetIntValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdp.SetIntValue(val)\n\tm.aggDataPoints = append(m.aggDataPoints, 1)\n\tdp.MoveTo(dps.AppendEmpty())\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricDefaultMetric) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricDefaultMetric) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tif m.config.AggregationStrategy == AggregationStrategyAvg {\n\t\t\tfor i, aggCount := range m.aggDataPoints {\n\t\t\t\tm.data.Sum().DataPoints().At(i).SetIntValue(m.data.Sum().DataPoints().At(i).IntValue() / aggCount)\n\t\t\t}\n\t\t}\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricDefaultMetric(cfg DefaultMetricMetricConfig) metricDefaultMetric {\n\tm := metricDefaultMetric{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricDefaultMetricToBeRemoved struct {\n\tdata     pmetric.Metric                       // data buffer for generated metric.\n\tconfig   DefaultMetricToBeRemovedMetricConfig // metric config provided by user.\n\tcapacity int                                  // max observed number of data points added to the metric.\n}\n\n// init fills default.metric.to_be_removed metric with initial data.\nfunc (m *metricDefaultMetricToBeRemoved) init() {\n\tm.data.SetName(\"default.metric.to_be_removed\")\n\tm.data.SetDescription(\"[DEPRECATED] Non-monotonic delta sum double metric enabled by default.\")\n\tm.data.SetUnit(\"s\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(false)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityDelta)\n}\n\nfunc (m *metricDefaultMetricToBeRemoved) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val float64) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\tdp := m.data.Sum().DataPoints().AppendEmpty()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tdp.SetDoubleValue(val)\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricDefaultMetricToBeRemoved) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricDefaultMetricToBeRemoved) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricDefaultMetricToBeRemoved(cfg DefaultMetricToBeRemovedMetricConfig) metricDefaultMetricToBeRemoved {\n\tm := metricDefaultMetricToBeRemoved{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricMetricInputType struct {\n\tdata          pmetric.Metric              // data buffer for generated metric.\n\tconfig        MetricInputTypeMetricConfig // metric config provided by user.\n\tcapacity      int                         // max observed number of data points added to the metric.\n\taggDataPoints []int64                     // slice containing number of aggregated datapoints at each index\n}\n\n// init fills metric.input_type metric with initial data.\nfunc (m *metricMetricInputType) init() {\n\tm.data.SetName(\"metric.input_type\")\n\tm.data.SetDescription(\"Monotonic cumulative sum int metric with string input_type enabled by default.\")\n\tm.data.SetUnit(\"s\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(true)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n\tm.data.Sum().DataPoints().EnsureCapacity(m.capacity)\n\tm.aggDataPoints = m.aggDataPoints[:0]\n}\n\nfunc (m *metricMetricInputType) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val int64, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue string, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\n\tdp := pmetric.NewNumberDataPoint()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tif slices.Contains(m.config.EnabledAttributes, MetricInputTypeMetricAttributeKeyStringAttr) {\n\t\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, MetricInputTypeMetricAttributeKeyOverriddenIntAttr) {\n\t\tdp.Attributes().PutInt(\"state\", overriddenIntAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, MetricInputTypeMetricAttributeKeyEnumAttr) {\n\t\tdp.Attributes().PutStr(\"enum_attr\", enumAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, MetricInputTypeMetricAttributeKeySliceAttr) {\n\t\tdp.Attributes().PutEmptySlice(\"slice_attr\").FromRaw(sliceAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, MetricInputTypeMetricAttributeKeyMapAttr) {\n\t\tdp.Attributes().PutEmptyMap(\"map_attr\").FromRaw(mapAttrAttributeValue)\n\t}\n\n\tvar s string\n\tdps := m.data.Sum().DataPoints()\n\tfor i := 0; i < dps.Len(); i++ {\n\t\tdpi := dps.At(i)\n\t\tif dp.Attributes().Equal(dpi.Attributes()) && dp.StartTimestamp() == dpi.StartTimestamp() && dp.Timestamp() == dpi.Timestamp() {\n\t\t\tswitch s = m.config.AggregationStrategy; s {\n\t\t\tcase AggregationStrategySum, AggregationStrategyAvg:\n\t\t\t\tdpi.SetIntValue(dpi.IntValue() + val)\n\t\t\t\tm.aggDataPoints[i] += 1\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMin:\n\t\t\t\tif dpi.IntValue() > val {\n\t\t\t\t\tdpi.SetIntValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMax:\n\t\t\t\tif dpi.IntValue() < val {\n\t\t\t\t\tdpi.SetIntValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdp.SetIntValue(val)\n\tm.aggDataPoints = append(m.aggDataPoints, 1)\n\tdp.MoveTo(dps.AppendEmpty())\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricMetricInputType) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricMetricInputType) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tif m.config.AggregationStrategy == AggregationStrategyAvg {\n\t\t\tfor i, aggCount := range m.aggDataPoints {\n\t\t\t\tm.data.Sum().DataPoints().At(i).SetIntValue(m.data.Sum().DataPoints().At(i).IntValue() / aggCount)\n\t\t\t}\n\t\t}\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricMetricInputType(cfg MetricInputTypeMetricConfig) metricMetricInputType {\n\tm := metricMetricInputType{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricOptionalMetric struct {\n\tdata          pmetric.Metric             // data buffer for generated metric.\n\tconfig        OptionalMetricMetricConfig // metric config provided by user.\n\tcapacity      int                        // max observed number of data points added to the metric.\n\taggDataPoints []float64                  // slice containing number of aggregated datapoints at each index\n}\n\n// init fills optional.metric metric with initial data.\nfunc (m *metricOptionalMetric) init() {\n\tm.data.SetName(\"optional.metric\")\n\tm.data.SetDescription(\"[DEPRECATED] Gauge double metric disabled by default.\")\n\tm.data.SetUnit(\"1\")\n\tm.data.SetEmptyGauge()\n\tm.data.Gauge().DataPoints().EnsureCapacity(m.capacity)\n\tm.aggDataPoints = m.aggDataPoints[:0]\n}\n\nfunc (m *metricOptionalMetric) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool, booleanAttr2AttributeValue bool) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\n\tdp := pmetric.NewNumberDataPoint()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tif slices.Contains(m.config.EnabledAttributes, OptionalMetricMetricAttributeKeyStringAttr) {\n\t\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, OptionalMetricMetricAttributeKeyBooleanAttr) {\n\t\tdp.Attributes().PutBool(\"boolean_attr\", booleanAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, OptionalMetricMetricAttributeKeyBooleanAttr2) {\n\t\tdp.Attributes().PutBool(\"boolean_attr2\", booleanAttr2AttributeValue)\n\t}\n\n\tvar s string\n\tdps := m.data.Gauge().DataPoints()\n\tfor i := 0; i < dps.Len(); i++ {\n\t\tdpi := dps.At(i)\n\t\tif dp.Attributes().Equal(dpi.Attributes()) && dp.StartTimestamp() == dpi.StartTimestamp() && dp.Timestamp() == dpi.Timestamp() {\n\t\t\tswitch s = m.config.AggregationStrategy; s {\n\t\t\tcase AggregationStrategySum, AggregationStrategyAvg:\n\t\t\t\tdpi.SetDoubleValue(dpi.DoubleValue() + val)\n\t\t\t\tm.aggDataPoints[i] += 1\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMin:\n\t\t\t\tif dpi.DoubleValue() > val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMax:\n\t\t\t\tif dpi.DoubleValue() < val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdp.SetDoubleValue(val)\n\tm.aggDataPoints = append(m.aggDataPoints, 1)\n\tdp.MoveTo(dps.AppendEmpty())\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricOptionalMetric) updateCapacity() {\n\tif m.data.Gauge().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Gauge().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricOptionalMetric) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 {\n\t\tif m.config.AggregationStrategy == AggregationStrategyAvg {\n\t\t\tfor i, aggCount := range m.aggDataPoints {\n\t\t\t\tm.data.Gauge().DataPoints().At(i).SetDoubleValue(m.data.Gauge().DataPoints().At(i).DoubleValue() / aggCount)\n\t\t\t}\n\t\t}\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricOptionalMetric(cfg OptionalMetricMetricConfig) metricOptionalMetric {\n\tm := metricOptionalMetric{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricOptionalMetricEmptyUnit struct {\n\tdata          pmetric.Metric                      // data buffer for generated metric.\n\tconfig        OptionalMetricEmptyUnitMetricConfig // metric config provided by user.\n\tcapacity      int                                 // max observed number of data points added to the metric.\n\taggDataPoints []float64                           // slice containing number of aggregated datapoints at each index\n}\n\n// init fills optional.metric.empty_unit metric with initial data.\nfunc (m *metricOptionalMetricEmptyUnit) init() {\n\tm.data.SetName(\"optional.metric.empty_unit\")\n\tm.data.SetDescription(\"[DEPRECATED] Gauge double metric disabled by default.\")\n\tm.data.SetUnit(\"\")\n\tm.data.SetEmptyGauge()\n\tm.data.Gauge().DataPoints().EnsureCapacity(m.capacity)\n\tm.aggDataPoints = m.aggDataPoints[:0]\n}\n\nfunc (m *metricOptionalMetricEmptyUnit) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\n\tdp := pmetric.NewNumberDataPoint()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tif slices.Contains(m.config.EnabledAttributes, OptionalMetricEmptyUnitMetricAttributeKeyStringAttr) {\n\t\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, OptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr) {\n\t\tdp.Attributes().PutBool(\"boolean_attr\", booleanAttrAttributeValue)\n\t}\n\n\tvar s string\n\tdps := m.data.Gauge().DataPoints()\n\tfor i := 0; i < dps.Len(); i++ {\n\t\tdpi := dps.At(i)\n\t\tif dp.Attributes().Equal(dpi.Attributes()) && dp.StartTimestamp() == dpi.StartTimestamp() && dp.Timestamp() == dpi.Timestamp() {\n\t\t\tswitch s = m.config.AggregationStrategy; s {\n\t\t\tcase AggregationStrategySum, AggregationStrategyAvg:\n\t\t\t\tdpi.SetDoubleValue(dpi.DoubleValue() + val)\n\t\t\t\tm.aggDataPoints[i] += 1\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMin:\n\t\t\t\tif dpi.DoubleValue() > val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMax:\n\t\t\t\tif dpi.DoubleValue() < val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdp.SetDoubleValue(val)\n\tm.aggDataPoints = append(m.aggDataPoints, 1)\n\tdp.MoveTo(dps.AppendEmpty())\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricOptionalMetricEmptyUnit) updateCapacity() {\n\tif m.data.Gauge().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Gauge().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricOptionalMetricEmptyUnit) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 {\n\t\tif m.config.AggregationStrategy == AggregationStrategyAvg {\n\t\t\tfor i, aggCount := range m.aggDataPoints {\n\t\t\t\tm.data.Gauge().DataPoints().At(i).SetDoubleValue(m.data.Gauge().DataPoints().At(i).DoubleValue() / aggCount)\n\t\t\t}\n\t\t}\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricOptionalMetricEmptyUnit(cfg OptionalMetricEmptyUnitMetricConfig) metricOptionalMetricEmptyUnit {\n\tm := metricOptionalMetricEmptyUnit{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricReaggregateMetric struct {\n\tdata          pmetric.Metric                // data buffer for generated metric.\n\tconfig        ReaggregateMetricMetricConfig // metric config provided by user.\n\tcapacity      int                           // max observed number of data points added to the metric.\n\taggDataPoints []float64                     // slice containing number of aggregated datapoints at each index\n}\n\n// init fills reaggregate.metric metric with initial data.\nfunc (m *metricReaggregateMetric) init() {\n\tm.data.SetName(\"reaggregate.metric\")\n\tm.data.SetDescription(\"Metric for testing spatial reaggregation\")\n\tm.data.SetUnit(\"1\")\n\tm.data.SetEmptyGauge()\n\tm.data.Gauge().DataPoints().EnsureCapacity(m.capacity)\n\tm.aggDataPoints = m.aggDataPoints[:0]\n}\n\nfunc (m *metricReaggregateMetric) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\n\tdp := pmetric.NewNumberDataPoint()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tif slices.Contains(m.config.EnabledAttributes, ReaggregateMetricMetricAttributeKeyStringAttr) {\n\t\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, ReaggregateMetricMetricAttributeKeyBooleanAttr) {\n\t\tdp.Attributes().PutBool(\"boolean_attr\", booleanAttrAttributeValue)\n\t}\n\n\tvar s string\n\tdps := m.data.Gauge().DataPoints()\n\tfor i := 0; i < dps.Len(); i++ {\n\t\tdpi := dps.At(i)\n\t\tif dp.Attributes().Equal(dpi.Attributes()) && dp.StartTimestamp() == dpi.StartTimestamp() && dp.Timestamp() == dpi.Timestamp() {\n\t\t\tswitch s = m.config.AggregationStrategy; s {\n\t\t\tcase AggregationStrategySum, AggregationStrategyAvg:\n\t\t\t\tdpi.SetDoubleValue(dpi.DoubleValue() + val)\n\t\t\t\tm.aggDataPoints[i] += 1\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMin:\n\t\t\t\tif dpi.DoubleValue() > val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMax:\n\t\t\t\tif dpi.DoubleValue() < val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdp.SetDoubleValue(val)\n\tm.aggDataPoints = append(m.aggDataPoints, 1)\n\tdp.MoveTo(dps.AppendEmpty())\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricReaggregateMetric) updateCapacity() {\n\tif m.data.Gauge().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Gauge().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricReaggregateMetric) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 {\n\t\tif m.config.AggregationStrategy == AggregationStrategyAvg {\n\t\t\tfor i, aggCount := range m.aggDataPoints {\n\t\t\t\tm.data.Gauge().DataPoints().At(i).SetDoubleValue(m.data.Gauge().DataPoints().At(i).DoubleValue() / aggCount)\n\t\t\t}\n\t\t}\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricReaggregateMetric(cfg ReaggregateMetricMetricConfig) metricReaggregateMetric {\n\tm := metricReaggregateMetric{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\n// MetricsBuilder provides an interface for scrapers to report metrics while taking care of all the transformations\n// required to produce metric representation defined in metadata and user config.\ntype MetricsBuilder struct {\n\tconfig                         MetricsBuilderConfig // config of the metrics builder.\n\tstartTime                      pcommon.Timestamp    // start time that will be applied to all recorded data points.\n\tmetricsCapacity                int                  // maximum observed number of metrics per resource.\n\tmetricsBuffer                  pmetric.Metrics      // accumulates metrics data before emitting.\n\tbuildInfo                      component.BuildInfo  // contains version information.\n\tresourceAttributeIncludeFilter map[string]filter.Filter\n\tresourceAttributeExcludeFilter map[string]filter.Filter\n\tmetricDefaultMetric            metricDefaultMetric\n\tmetricDefaultMetricToBeRemoved metricDefaultMetricToBeRemoved\n\tmetricMetricInputType          metricMetricInputType\n\tmetricOptionalMetric           metricOptionalMetric\n\tmetricOptionalMetricEmptyUnit  metricOptionalMetricEmptyUnit\n\tmetricReaggregateMetric        metricReaggregateMetric\n}\n\n// MetricBuilderOption applies changes to default metrics builder.\ntype MetricBuilderOption interface {\n\tapply(*MetricsBuilder)\n}\n\ntype metricBuilderOptionFunc func(mb *MetricsBuilder)\n\nfunc (mbof metricBuilderOptionFunc) apply(mb *MetricsBuilder) {\n\tmbof(mb)\n}\n\n// WithStartTime sets startTime on the metrics builder.\nfunc WithStartTime(startTime pcommon.Timestamp) MetricBuilderOption {\n\treturn metricBuilderOptionFunc(func(mb *MetricsBuilder) {\n\t\tmb.startTime = startTime\n\t})\n}\nfunc NewMetricsBuilder(mbc MetricsBuilderConfig, settings connector.Settings, options ...MetricBuilderOption) *MetricsBuilder {\n\tif !mbc.Metrics.DefaultMetric.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] Please set `enabled` field explicitly for `default.metric`: This metric will be disabled by default soon.\")\n\t}\n\tif mbc.Metrics.DefaultMetricToBeRemoved.Enabled {\n\t\tsettings.Logger.Warn(\"[WARNING] `default.metric.to_be_removed` should not be enabled: This metric is deprecated and will be removed soon.\")\n\t}\n\tif mbc.Metrics.OptionalMetric.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] `optional.metric` should not be configured: This metric is deprecated and will be removed soon.\")\n\t}\n\tif mbc.Metrics.OptionalMetricEmptyUnit.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] `optional.metric.empty_unit` should not be configured: This metric is deprecated and will be removed soon.\")\n\t}\n\tif !mbc.ResourceAttributes.StringResourceAttrDisableWarning.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] Please set `enabled` field explicitly for `string.resource.attr_disable_warning`: This resource_attribute will be disabled by default soon.\")\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrRemoveWarning.enabledSetByUser || mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsInclude != nil || mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsExclude != nil {\n\t\tsettings.Logger.Warn(\"[WARNING] `string.resource.attr_remove_warning` should not be configured: This resource_attribute is deprecated and will be removed soon.\")\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrToBeRemoved.Enabled {\n\t\tsettings.Logger.Warn(\"[WARNING] `string.resource.attr_to_be_removed` should not be enabled: This resource_attribute is deprecated and will be removed soon.\")\n\t}\n\tmb := &MetricsBuilder{\n\t\tconfig:                         mbc,\n\t\tstartTime:                      pcommon.NewTimestampFromTime(time.Now()),\n\t\tmetricsBuffer:                  pmetric.NewMetrics(),\n\t\tbuildInfo:                      settings.BuildInfo,\n\t\tmetricDefaultMetric:            newMetricDefaultMetric(mbc.Metrics.DefaultMetric),\n\t\tmetricDefaultMetricToBeRemoved: newMetricDefaultMetricToBeRemoved(mbc.Metrics.DefaultMetricToBeRemoved),\n\t\tmetricMetricInputType:          newMetricMetricInputType(mbc.Metrics.MetricInputType),\n\t\tmetricOptionalMetric:           newMetricOptionalMetric(mbc.Metrics.OptionalMetric),\n\t\tmetricOptionalMetricEmptyUnit:  newMetricOptionalMetricEmptyUnit(mbc.Metrics.OptionalMetricEmptyUnit),\n\t\tmetricReaggregateMetric:        newMetricReaggregateMetric(mbc.Metrics.ReaggregateMetric),\n\t\tresourceAttributeIncludeFilter: make(map[string]filter.Filter),\n\t\tresourceAttributeExcludeFilter: make(map[string]filter.Filter),\n\t}\n\tif mbc.ResourceAttributes.MapResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"map.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.MapResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.MapResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"map.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.MapResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.OptionalResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"optional.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.OptionalResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.OptionalResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"optional.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.OptionalResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.SliceResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"slice.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.SliceResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.SliceResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"slice.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.SliceResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringEnumResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.enum.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.StringEnumResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringEnumResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.enum.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.StringEnumResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrDisableWarning.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.resource.attr_disable_warning\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrDisableWarning.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrDisableWarning.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.resource.attr_disable_warning\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrDisableWarning.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.resource.attr_remove_warning\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.resource.attr_remove_warning\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrToBeRemoved.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.resource.attr_to_be_removed\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrToBeRemoved.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrToBeRemoved.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.resource.attr_to_be_removed\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrToBeRemoved.MetricsExclude)\n\t}\n\n\tfor _, op := range options {\n\t\top.apply(mb)\n\t}\n\treturn mb\n}\n\n// NewResourceBuilder returns a new resource builder that should be used to build a resource associated with for the emitted metrics.\nfunc (mb *MetricsBuilder) NewResourceBuilder() *ResourceBuilder {\n\treturn NewResourceBuilder(mb.config.ResourceAttributes)\n}\n\n// updateCapacity updates max length of metrics and resource attributes that will be used for the slice capacity.\nfunc (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n}\n\n// ResourceMetricsOption applies changes to provided resource metrics.\ntype ResourceMetricsOption interface {\n\tapply(pmetric.ResourceMetrics)\n}\n\ntype resourceMetricsOptionFunc func(pmetric.ResourceMetrics)\n\nfunc (rmof resourceMetricsOptionFunc) apply(rm pmetric.ResourceMetrics) {\n\trmof(rm)\n}\n\n// WithResource sets the provided resource on the emitted ResourceMetrics.\n// It's recommended to use ResourceBuilder to create the resource.\nfunc WithResource(res pcommon.Resource) ResourceMetricsOption {\n\treturn resourceMetricsOptionFunc(func(rm pmetric.ResourceMetrics) {\n\t\tres.CopyTo(rm.Resource())\n\t})\n}\n\nfunc withResourceMoved(res pcommon.Resource) ResourceMetricsOption {\n\treturn resourceMetricsOptionFunc(func(rm pmetric.ResourceMetrics) {\n\t\tres.MoveTo(rm.Resource())\n\t})\n}\n\n// WithStartTimeOverride overrides start time for all the resource metrics data points.\n// This option should be only used if different start time has to be set on metrics coming from different resources.\nfunc WithStartTimeOverride(start pcommon.Timestamp) ResourceMetricsOption {\n\treturn resourceMetricsOptionFunc(func(rm pmetric.ResourceMetrics) {\n\t\tvar dps pmetric.NumberDataPointSlice\n\t\tmetrics := rm.ScopeMetrics().At(0).Metrics()\n\t\tfor i := 0; i < metrics.Len(); i++ {\n\t\t\tswitch metrics.At(i).Type() {\n\t\t\tcase pmetric.MetricTypeGauge:\n\t\t\t\tdps = metrics.At(i).Gauge().DataPoints()\n\t\t\tcase pmetric.MetricTypeSum:\n\t\t\t\tdps = metrics.At(i).Sum().DataPoints()\n\t\t\t}\n\t\t\tfor j := 0; j < dps.Len(); j++ {\n\t\t\t\tdps.At(j).SetStartTimestamp(start)\n\t\t\t}\n\t\t}\n\t})\n}\n\n// ForTestEntity returns a TestEntityMetricsBuilder that restricts metric recording\n// to metrics belonging to the test.entity entity.\nfunc (mb *MetricsBuilder) ForTestEntity(e *TestEntityEntity) *TestEntityMetricsBuilder {\n\treturn &TestEntityMetricsBuilder{mb: mb, entity: e}\n}\n\n// EmitForResource saves all the generated metrics under a new resource and updates the internal state to be ready for\n// recording another set of data points as part of another resource. This function can be helpful when one scraper\n// needs to emit metrics from several resources. Otherwise calling this function is not required,\n// just `Emit` function can be called instead.\n// Resource attributes should be provided as ResourceMetricsOption arguments.\n//\n// Deprecated: Use the For<EntityType> methods to get entity-scoped builders and call Emit() on them instead.\nfunc (mb *MetricsBuilder) EmitForResource(options ...ResourceMetricsOption) {\n\trm := pmetric.NewResourceMetrics()\n\trm.SetSchemaUrl(conventions.SchemaURL)\n\tils := rm.ScopeMetrics().AppendEmpty()\n\tils.Scope().SetName(ScopeName)\n\tils.Scope().SetVersion(mb.buildInfo.Version)\n\tils.Metrics().EnsureCapacity(mb.metricsCapacity)\n\tmb.metricDefaultMetric.emit(ils.Metrics())\n\tmb.metricDefaultMetricToBeRemoved.emit(ils.Metrics())\n\tmb.metricMetricInputType.emit(ils.Metrics())\n\tmb.metricOptionalMetric.emit(ils.Metrics())\n\tmb.metricOptionalMetricEmptyUnit.emit(ils.Metrics())\n\tmb.metricReaggregateMetric.emit(ils.Metrics())\n\n\tfor _, op := range options {\n\t\top.apply(rm)\n\t}\n\tfor attr, filter := range mb.resourceAttributeIncludeFilter {\n\t\tif val, ok := rm.Resource().Attributes().Get(attr); ok && !filter.Matches(val.AsString()) {\n\t\t\treturn\n\t\t}\n\t}\n\tfor attr, filter := range mb.resourceAttributeExcludeFilter {\n\t\tif val, ok := rm.Resource().Attributes().Get(attr); ok && filter.Matches(val.AsString()) {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif ils.Metrics().Len() > 0 {\n\t\tmb.updateCapacity(rm)\n\t\trm.MoveTo(mb.metricsBuffer.ResourceMetrics().AppendEmpty())\n\t}\n}\n\n// Emit returns all the metrics accumulated by the metrics builder and updates the internal state to be ready for\n// recording another set of metrics. This function will be responsible for applying all the transformations required to\n// produce metric representation defined in metadata and user config, e.g. delta or cumulative.\nfunc (mb *MetricsBuilder) Emit(options ...ResourceMetricsOption) pmetric.Metrics {\n\tmb.EmitForResource(options...)\n\tmetrics := mb.metricsBuffer\n\tmb.metricsBuffer = pmetric.NewMetrics()\n\treturn metrics\n}\n\n// RecordDefaultMetricDataPoint adds a data point to default.metric metric.\n//\n// Deprecated: Use mb.ForTestEntity(entity).RecordDefaultMetricDataPoint(...) instead.\nfunc (mb *MetricsBuilder) RecordDefaultMetricDataPoint(ts pcommon.Timestamp, val int64, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue AttributeEnumAttr, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any) {\n\tmb.metricDefaultMetric.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, overriddenIntAttrAttributeValue, enumAttrAttributeValue.String(), sliceAttrAttributeValue, mapAttrAttributeValue)\n}\n\n// RecordDefaultMetricToBeRemovedDataPoint adds a data point to default.metric.to_be_removed metric.\n//\n// Deprecated: Use mb.ForTestEntity(entity).RecordDefaultMetricToBeRemovedDataPoint(...) instead.\nfunc (mb *MetricsBuilder) RecordDefaultMetricToBeRemovedDataPoint(ts pcommon.Timestamp, val float64) {\n\tmb.metricDefaultMetricToBeRemoved.recordDataPoint(mb.startTime, ts, val)\n}\n\n// RecordMetricInputTypeDataPoint adds a data point to metric.input_type metric.\n//\n// Deprecated: Use mb.ForTestEntity(entity).RecordMetricInputTypeDataPoint(...) instead.\nfunc (mb *MetricsBuilder) RecordMetricInputTypeDataPoint(ts pcommon.Timestamp, inputVal string, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue AttributeEnumAttr, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MetricInputType, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMetricInputType.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, overriddenIntAttrAttributeValue, enumAttrAttributeValue.String(), sliceAttrAttributeValue, mapAttrAttributeValue)\n\treturn nil\n}\n\n// RecordOptionalMetricDataPoint adds a data point to optional.metric metric.\n//\n// Deprecated: Use mb.ForTestEntity(entity).RecordOptionalMetricDataPoint(...) instead.\nfunc (mb *MetricsBuilder) RecordOptionalMetricDataPoint(ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool, booleanAttr2AttributeValue bool) {\n\tmb.metricOptionalMetric.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, booleanAttrAttributeValue, booleanAttr2AttributeValue)\n}\n\n// RecordOptionalMetricEmptyUnitDataPoint adds a data point to optional.metric.empty_unit metric.\n//\n// Deprecated: Use mb.ForTestEntity(entity).RecordOptionalMetricEmptyUnitDataPoint(...) instead.\nfunc (mb *MetricsBuilder) RecordOptionalMetricEmptyUnitDataPoint(ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\tmb.metricOptionalMetricEmptyUnit.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, booleanAttrAttributeValue)\n}\n\n// RecordReaggregateMetricDataPoint adds a data point to reaggregate.metric metric.\n//\n// Deprecated: Use mb.ForTestEntity(entity).RecordReaggregateMetricDataPoint(...) instead.\nfunc (mb *MetricsBuilder) RecordReaggregateMetricDataPoint(ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\tmb.metricReaggregateMetric.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, booleanAttrAttributeValue)\n}\n\n// Reset resets metrics builder to its initial state. It should be used when external metrics source is restarted,\n// and metrics builder should update its startTime and reset it's internal state accordingly.\nfunc (mb *MetricsBuilder) Reset(options ...MetricBuilderOption) {\n\tmb.startTime = pcommon.NewTimestampFromTime(time.Now())\n\tfor _, op := range options {\n\t\top.apply(mb)\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/internal/metadata/generated_metrics_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/connector/connectortest\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\ntype testDataSet int\n\nconst (\n\ttestDataSetDefault testDataSet = iota\n\ttestDataSetAll\n\ttestDataSetNone\n\ttestDataSetReag\n)\n\nfunc TestMetricsBuilder(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tmetricsSet  testDataSet\n\t\tresAttrsSet testDataSet\n\t\texpectEmpty bool\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t},\n\t\t{\n\t\t\tname:        \"all_set\",\n\t\t\tmetricsSet:  testDataSetAll,\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t},\n\t\t{\n\t\t\tname:        \"reaggregate_set\",\n\t\t\tmetricsSet:  testDataSetReag,\n\t\t\tresAttrsSet: testDataSetReag,\n\t\t},\n\t\t{\n\t\t\tname:        \"none_set\",\n\t\t\tmetricsSet:  testDataSetNone,\n\t\t\tresAttrsSet: testDataSetNone,\n\t\t\texpectEmpty: true,\n\t\t},\n\t\t{\n\t\t\tname:        \"filter_set_include\",\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t},\n\t\t{\n\t\t\tname:        \"filter_set_exclude\",\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t\texpectEmpty: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tstart := pcommon.Timestamp(1_000_000_000)\n\t\t\tts := pcommon.Timestamp(1_000_001_000)\n\t\t\tobservedZapCore, observedLogs := observer.New(zap.WarnLevel)\n\t\t\tsettings := connectortest.NewNopSettings(connectortest.NopType)\n\t\t\tsettings.Logger = zap.New(observedZapCore)\n\t\t\tmb := NewMetricsBuilder(loadMetricsBuilderConfig(t, tt.name), settings, WithStartTime(start))\n\t\t\taggMap := make(map[string]string) // contains the aggregation strategies for each metric name\n\t\t\taggMap[\"DefaultMetric\"] = mb.metricDefaultMetric.config.AggregationStrategy\n\t\t\taggMap[\"MetricInputType\"] = mb.metricMetricInputType.config.AggregationStrategy\n\t\t\taggMap[\"OptionalMetric\"] = mb.metricOptionalMetric.config.AggregationStrategy\n\t\t\taggMap[\"OptionalMetricEmptyUnit\"] = mb.metricOptionalMetricEmptyUnit.config.AggregationStrategy\n\t\t\taggMap[\"ReaggregateMetric\"] = mb.metricReaggregateMetric.config.AggregationStrategy\n\n\t\t\texpectedWarnings := 0\n\t\t\tif tt.metricsSet == testDataSetDefault {\n\t\t\t\tassert.Equal(t, \"[WARNING] Please set `enabled` field explicitly for `default.metric`: This metric will be disabled by default soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetDefault || tt.metricsSet == testDataSetAll {\n\t\t\t\tassert.Equal(t, \"[WARNING] `default.metric.to_be_removed` should not be enabled: This metric is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetAll || tt.metricsSet == testDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `optional.metric` should not be configured: This metric is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetAll || tt.metricsSet == testDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `optional.metric.empty_unit` should not be configured: This metric is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.resAttrsSet == testDataSetDefault {\n\t\t\t\tassert.Equal(t, \"[WARNING] Please set `enabled` field explicitly for `string.resource.attr_disable_warning`: This resource_attribute will be disabled by default soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.resAttrsSet == testDataSetAll || tt.resAttrsSet == testDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `string.resource.attr_remove_warning` should not be configured: This resource_attribute is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.resAttrsSet == testDataSetDefault || tt.resAttrsSet == testDataSetAll {\n\t\t\t\tassert.Equal(t, \"[WARNING] `string.resource.attr_to_be_removed` should not be enabled: This resource_attribute is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.metricsSet != testDataSetReag {\n\t\t\t\tassert.Equal(t, expectedWarnings, observedLogs.Len())\n\t\t\t}\n\n\t\t\tdefaultMetricsCount := 0\n\t\t\tallMetricsCount := 0\n\t\t\tebTestEntity := mb.ForTestEntity(NewTestEntityEntity(\"string.resource.attr-val\"))\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tebTestEntity.RecordDefaultMetricDataPoint(ts, 1, \"string_attr-val\", 19, AttributeEnumAttrRed, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"})\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tebTestEntity.RecordDefaultMetricDataPoint(ts, 3, \"string_attr-val-2\", 20, AttributeEnumAttrGreen, []any{\"slice_attr-item3\", \"slice_attr-item4\"}, map[string]any{\"key3\": \"map_attr-val3\", \"key4\": \"map_attr-val4\"})\n\t\t\t}\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tebTestEntity.RecordDefaultMetricToBeRemovedDataPoint(ts, 1)\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tebTestEntity.RecordMetricInputTypeDataPoint(ts, \"1\", \"string_attr-val\", 19, AttributeEnumAttrRed, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"})\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tebTestEntity.RecordMetricInputTypeDataPoint(ts, \"3\", \"string_attr-val-2\", 20, AttributeEnumAttrGreen, []any{\"slice_attr-item3\", \"slice_attr-item4\"}, map[string]any{\"key3\": \"map_attr-val3\", \"key4\": \"map_attr-val4\"})\n\t\t\t}\n\n\t\t\tallMetricsCount++\n\t\t\tebTestEntity.RecordOptionalMetricDataPoint(ts, 1, \"string_attr-val\", true, false)\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tebTestEntity.RecordOptionalMetricDataPoint(ts, 3, \"string_attr-val-2\", false, true)\n\t\t\t}\n\n\t\t\tallMetricsCount++\n\t\t\tebTestEntity.RecordOptionalMetricEmptyUnitDataPoint(ts, 1, \"string_attr-val\", true)\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tebTestEntity.RecordOptionalMetricEmptyUnitDataPoint(ts, 3, \"string_attr-val-2\", false)\n\t\t\t}\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tebTestEntity.RecordReaggregateMetricDataPoint(ts, 1, \"string_attr-val\", true)\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tebTestEntity.RecordReaggregateMetricDataPoint(ts, 3, \"string_attr-val-2\", false)\n\t\t\t}\n\t\t\tebTestEntity.Emit()\n\n\t\t\trb := mb.NewResourceBuilder()\n\t\t\trb.SetMapResourceAttr(map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"})\n\t\t\trb.SetOptionalResourceAttr(\"optional.resource.attr-val\")\n\t\t\trb.SetSliceResourceAttr([]any{\"slice.resource.attr-item1\", \"slice.resource.attr-item2\"})\n\t\t\trb.SetStringEnumResourceAttrOne()\n\t\t\trb.SetStringResourceAttr(\"string.resource.attr-val\")\n\t\t\trb.SetStringResourceAttrDisableWarning(\"string.resource.attr_disable_warning-val\")\n\t\t\trb.SetStringResourceAttrRemoveWarning(\"string.resource.attr_remove_warning-val\")\n\t\t\trb.SetStringResourceAttrToBeRemoved(\"string.resource.attr_to_be_removed-val\")\n\t\t\tres := rb.Emit()\n\t\t\tmetrics := mb.Emit(WithResource(res))\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tassert.Empty(t, mb.metricDefaultMetric.aggDataPoints)\n\t\t\t\tassert.Empty(t, mb.metricMetricInputType.aggDataPoints)\n\t\t\t\tassert.Empty(t, mb.metricOptionalMetric.aggDataPoints)\n\t\t\t\tassert.Empty(t, mb.metricOptionalMetricEmptyUnit.aggDataPoints)\n\t\t\t\tassert.Empty(t, mb.metricReaggregateMetric.aggDataPoints)\n\t\t\t}\n\n\t\t\tif tt.expectEmpty {\n\t\t\t\tassert.Equal(t, 0, metrics.ResourceMetrics().Len())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar allMetricsList []pmetric.Metric\n\t\t\ttotalMetricsCount := 0\n\t\t\tfor ri := 0; ri < metrics.ResourceMetrics().Len(); ri++ {\n\t\t\t\trm := metrics.ResourceMetrics().At(ri)\n\t\t\t\tassert.Equal(t, 1, rm.ScopeMetrics().Len())\n\t\t\t\tms := rm.ScopeMetrics().At(0).Metrics()\n\t\t\t\ttotalMetricsCount += ms.Len()\n\t\t\t\tfor mi := 0; mi < ms.Len(); mi++ {\n\t\t\t\t\tallMetricsList = append(allMetricsList, ms.At(mi))\n\t\t\t\t}\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetDefault {\n\t\t\t\tassert.Equal(t, defaultMetricsCount, totalMetricsCount)\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetAll {\n\t\t\t\tassert.Equal(t, allMetricsCount, totalMetricsCount)\n\t\t\t}\n\t\t\tvalidatedMetrics := make(map[string]bool)\n\t\t\tfor _, mi := range allMetricsList {\n\t\t\t\tswitch mi.Name() {\n\t\t\t\tcase \"default.metric\":\n\t\t\t\t\tif tt.name != \"reaggregate_set\" {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"default.metric\"], \"Found a duplicate in the metrics slice: default.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"default.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Monotonic cumulative sum int metric enabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\t\tassert.True(t, mi.Sum().IsMonotonic())\n\t\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, mi.Sum().AggregationTemporality())\n\t\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t\t\tstringAttrAttrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"string_attr-val\", stringAttrAttrVal.Str())\n\t\t\t\t\t\toverriddenIntAttrAttrVal, ok := dp.Attributes().Get(\"state\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.EqualValues(t, 19, overriddenIntAttrAttrVal.Int())\n\t\t\t\t\t\tenumAttrAttrVal, ok := dp.Attributes().Get(\"enum_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"red\", enumAttrAttrVal.Str())\n\t\t\t\t\t\tsliceAttrAttrVal, ok := dp.Attributes().Get(\"slice_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, sliceAttrAttrVal.Slice().AsRaw())\n\t\t\t\t\t\tmapAttrAttrVal, ok := dp.Attributes().Get(\"map_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"}, mapAttrAttrVal.Map().AsRaw())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"default.metric\"], \"Found a duplicate in the metrics slice: default.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"default.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Monotonic cumulative sum int metric enabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\t\tassert.True(t, mi.Sum().IsMonotonic())\n\t\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, mi.Sum().AggregationTemporality())\n\t\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\t\tswitch aggMap[\"default.metric\"] {\n\t\t\t\t\t\tcase \"sum\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(4), dp.IntValue())\n\t\t\t\t\t\tcase \"avg\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(2), dp.IntValue())\n\t\t\t\t\t\tcase \"min\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t\t\tcase \"max\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(3), dp.IntValue())\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"state\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"enum_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"slice_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"map_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t}\n\t\t\t\tcase \"default.metric.to_be_removed\":\n\t\t\t\t\tassert.False(t, validatedMetrics[\"default.metric.to_be_removed\"], \"Found a duplicate in the metrics slice: default.metric.to_be_removed\")\n\t\t\t\t\tvalidatedMetrics[\"default.metric.to_be_removed\"] = true\n\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Non-monotonic delta sum double metric enabled by default.\", mi.Description())\n\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\tassert.False(t, mi.Sum().IsMonotonic())\n\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityDelta, mi.Sum().AggregationTemporality())\n\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\tcase \"metric.input_type\":\n\t\t\t\t\tif tt.name != \"reaggregate_set\" {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"metric.input_type\"], \"Found a duplicate in the metrics slice: metric.input_type\")\n\t\t\t\t\t\tvalidatedMetrics[\"metric.input_type\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Monotonic cumulative sum int metric with string input_type enabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\t\tassert.True(t, mi.Sum().IsMonotonic())\n\t\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, mi.Sum().AggregationTemporality())\n\t\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t\t\tstringAttrAttrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"string_attr-val\", stringAttrAttrVal.Str())\n\t\t\t\t\t\toverriddenIntAttrAttrVal, ok := dp.Attributes().Get(\"state\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.EqualValues(t, 19, overriddenIntAttrAttrVal.Int())\n\t\t\t\t\t\tenumAttrAttrVal, ok := dp.Attributes().Get(\"enum_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"red\", enumAttrAttrVal.Str())\n\t\t\t\t\t\tsliceAttrAttrVal, ok := dp.Attributes().Get(\"slice_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, sliceAttrAttrVal.Slice().AsRaw())\n\t\t\t\t\t\tmapAttrAttrVal, ok := dp.Attributes().Get(\"map_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"}, mapAttrAttrVal.Map().AsRaw())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"metric.input_type\"], \"Found a duplicate in the metrics slice: metric.input_type\")\n\t\t\t\t\t\tvalidatedMetrics[\"metric.input_type\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Monotonic cumulative sum int metric with string input_type enabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\t\tassert.True(t, mi.Sum().IsMonotonic())\n\t\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, mi.Sum().AggregationTemporality())\n\t\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\t\tswitch aggMap[\"metric.input_type\"] {\n\t\t\t\t\t\tcase \"sum\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(4), dp.IntValue())\n\t\t\t\t\t\tcase \"avg\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(2), dp.IntValue())\n\t\t\t\t\t\tcase \"min\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t\t\tcase \"max\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(3), dp.IntValue())\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"state\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"enum_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"slice_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"map_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t}\n\t\t\t\tcase \"optional.metric\":\n\t\t\t\t\tif tt.name != \"reaggregate_set\" {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"optional.metric\"], \"Found a duplicate in the metrics slice: optional.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"optional.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Gauge double metric disabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"1\", mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tstringAttrAttrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"string_attr-val\", stringAttrAttrVal.Str())\n\t\t\t\t\t\tbooleanAttrAttrVal, ok := dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.True(t, booleanAttrAttrVal.Bool())\n\t\t\t\t\t\tbooleanAttr2AttrVal, ok := dp.Attributes().Get(\"boolean_attr2\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.False(t, booleanAttr2AttrVal.Bool())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"optional.metric\"], \"Found a duplicate in the metrics slice: optional.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"optional.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Gauge double metric disabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"1\", mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tswitch aggMap[\"optional.metric\"] {\n\t\t\t\t\t\tcase \"sum\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(4), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"avg\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(2), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"min\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"max\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(3), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"boolean_attr2\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t}\n\t\t\t\tcase \"optional.metric.empty_unit\":\n\t\t\t\t\tif tt.name != \"reaggregate_set\" {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"optional.metric.empty_unit\"], \"Found a duplicate in the metrics slice: optional.metric.empty_unit\")\n\t\t\t\t\t\tvalidatedMetrics[\"optional.metric.empty_unit\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Gauge double metric disabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Empty(t, mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tstringAttrAttrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"string_attr-val\", stringAttrAttrVal.Str())\n\t\t\t\t\t\tbooleanAttrAttrVal, ok := dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.True(t, booleanAttrAttrVal.Bool())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"optional.metric.empty_unit\"], \"Found a duplicate in the metrics slice: optional.metric.empty_unit\")\n\t\t\t\t\t\tvalidatedMetrics[\"optional.metric.empty_unit\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Gauge double metric disabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Empty(t, mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tswitch aggMap[\"optional.metric.empty_unit\"] {\n\t\t\t\t\t\tcase \"sum\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(4), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"avg\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(2), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"min\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"max\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(3), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t}\n\t\t\t\tcase \"reaggregate.metric\":\n\t\t\t\t\tif tt.name != \"reaggregate_set\" {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"reaggregate.metric\"], \"Found a duplicate in the metrics slice: reaggregate.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"reaggregate.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Metric for testing spatial reaggregation\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"1\", mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tstringAttrAttrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"string_attr-val\", stringAttrAttrVal.Str())\n\t\t\t\t\t\tbooleanAttrAttrVal, ok := dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.True(t, booleanAttrAttrVal.Bool())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"reaggregate.metric\"], \"Found a duplicate in the metrics slice: reaggregate.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"reaggregate.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Metric for testing spatial reaggregation\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"1\", mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tswitch aggMap[\"reaggregate.metric\"] {\n\t\t\t\t\t\tcase \"sum\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(4), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"avg\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(2), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"min\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"max\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(3), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/internal/metadata/generated_resource.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ResourceBuilder is a helper struct to build resources predefined in metadata.yaml.\n// The ResourceBuilder is not thread-safe and must not to be used in multiple goroutines.\ntype ResourceBuilder struct {\n\tconfig ResourceAttributesConfig\n\tres    pcommon.Resource\n}\n\n// NewResourceBuilder creates a new ResourceBuilder. This method should be called on the start of the application.\nfunc NewResourceBuilder(rac ResourceAttributesConfig) *ResourceBuilder {\n\treturn &ResourceBuilder{\n\t\tconfig: rac,\n\t\tres:    pcommon.NewResource(),\n\t}\n}\n\n// SetMapResourceAttr sets provided value as \"map.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetMapResourceAttr(val map[string]any) {\n\tif rb.config.MapResourceAttr.Enabled {\n\t\trb.res.Attributes().PutEmptyMap(\"map.resource.attr\").FromRaw(val)\n\t}\n}\n\n// SetOptionalResourceAttr sets provided value as \"optional.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetOptionalResourceAttr(val string) {\n\tif rb.config.OptionalResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"optional.resource.attr\", val)\n\t}\n}\n\n// SetSliceResourceAttr sets provided value as \"slice.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetSliceResourceAttr(val []any) {\n\tif rb.config.SliceResourceAttr.Enabled {\n\t\trb.res.Attributes().PutEmptySlice(\"slice.resource.attr\").FromRaw(val)\n\t}\n}\n\n// SetStringEnumResourceAttrOne sets \"string.enum.resource.attr=one\" attribute.\nfunc (rb *ResourceBuilder) SetStringEnumResourceAttrOne() {\n\tif rb.config.StringEnumResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.enum.resource.attr\", \"one\")\n\t}\n}\n\n// SetStringEnumResourceAttrTwo sets \"string.enum.resource.attr=two\" attribute.\nfunc (rb *ResourceBuilder) SetStringEnumResourceAttrTwo() {\n\tif rb.config.StringEnumResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.enum.resource.attr\", \"two\")\n\t}\n}\n\n// SetStringResourceAttr sets provided value as \"string.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttr(val string) {\n\tif rb.config.StringResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr\", val)\n\t}\n}\n\n// SetStringResourceAttrDisableWarning sets provided value as \"string.resource.attr_disable_warning\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttrDisableWarning(val string) {\n\tif rb.config.StringResourceAttrDisableWarning.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr_disable_warning\", val)\n\t}\n}\n\n// SetStringResourceAttrRemoveWarning sets provided value as \"string.resource.attr_remove_warning\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttrRemoveWarning(val string) {\n\tif rb.config.StringResourceAttrRemoveWarning.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr_remove_warning\", val)\n\t}\n}\n\n// SetStringResourceAttrToBeRemoved sets provided value as \"string.resource.attr_to_be_removed\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttrToBeRemoved(val string) {\n\tif rb.config.StringResourceAttrToBeRemoved.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr_to_be_removed\", val)\n\t}\n}\n\n// Emit returns the built resource and resets the internal builder state.\nfunc (rb *ResourceBuilder) Emit() pcommon.Resource {\n\tr := rb.res\n\trb.res = pcommon.NewResource()\n\treturn r\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/internal/metadata/generated_resource_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestResourceBuilder(t *testing.T) {\n\tfor _, tt := range []string{\"default\", \"all_set\", \"none_set\"} {\n\t\tt.Run(tt, func(t *testing.T) {\n\t\t\tcfg := loadResourceAttributesConfig(t, tt)\n\t\t\trb := NewResourceBuilder(cfg)\n\t\t\trb.SetMapResourceAttr(map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"})\n\t\t\trb.SetOptionalResourceAttr(\"optional.resource.attr-val\")\n\t\t\trb.SetSliceResourceAttr([]any{\"slice.resource.attr-item1\", \"slice.resource.attr-item2\"})\n\t\t\trb.SetStringEnumResourceAttrOne()\n\t\t\trb.SetStringResourceAttr(\"string.resource.attr-val\")\n\t\t\trb.SetStringResourceAttrDisableWarning(\"string.resource.attr_disable_warning-val\")\n\t\t\trb.SetStringResourceAttrRemoveWarning(\"string.resource.attr_remove_warning-val\")\n\t\t\trb.SetStringResourceAttrToBeRemoved(\"string.resource.attr_to_be_removed-val\")\n\n\t\t\tres := rb.Emit()\n\t\t\tassert.Equal(t, 0, rb.Emit().Attributes().Len()) // Second call should return empty Resource\n\n\t\t\tswitch tt {\n\t\t\tcase \"default\":\n\t\t\t\tassert.Equal(t, 6, res.Attributes().Len())\n\t\t\tcase \"all_set\":\n\t\t\t\tassert.Equal(t, 8, res.Attributes().Len())\n\t\t\tcase \"none_set\":\n\t\t\t\tassert.Equal(t, 0, res.Attributes().Len())\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tassert.Failf(t, \"unexpected test case: %s\", tt)\n\t\t\t}\n\t\t\tmapResourceAttrAttrVal, ok := res.Attributes().Get(\"map.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"}, mapResourceAttrAttrVal.Map().AsRaw())\n\t\t\t}\n\t\t\toptionalResourceAttrAttrVal, ok := res.Attributes().Get(\"optional.resource.attr\")\n\t\t\tassert.Equal(t, tt == \"all_set\", ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"optional.resource.attr-val\", optionalResourceAttrAttrVal.Str())\n\t\t\t}\n\t\t\tsliceResourceAttrAttrVal, ok := res.Attributes().Get(\"slice.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, []any{\"slice.resource.attr-item1\", \"slice.resource.attr-item2\"}, sliceResourceAttrAttrVal.Slice().AsRaw())\n\t\t\t}\n\t\t\tstringEnumResourceAttrAttrVal, ok := res.Attributes().Get(\"string.enum.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"one\", stringEnumResourceAttrAttrVal.Str())\n\t\t\t}\n\t\t\tstringResourceAttrAttrVal, ok := res.Attributes().Get(\"string.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr-val\", stringResourceAttrAttrVal.Str())\n\t\t\t}\n\t\t\tstringResourceAttrDisableWarningAttrVal, ok := res.Attributes().Get(\"string.resource.attr_disable_warning\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr_disable_warning-val\", stringResourceAttrDisableWarningAttrVal.Str())\n\t\t\t}\n\t\t\tstringResourceAttrRemoveWarningAttrVal, ok := res.Attributes().Get(\"string.resource.attr_remove_warning\")\n\t\t\tassert.Equal(t, tt == \"all_set\", ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr_remove_warning-val\", stringResourceAttrRemoveWarningAttrVal.Str())\n\t\t\t}\n\t\t\tstringResourceAttrToBeRemovedAttrVal, ok := res.Attributes().Get(\"string.resource.attr_to_be_removed\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr_to_be_removed-val\", stringResourceAttrToBeRemovedAttrVal.Str())\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"sample\")\n\tScopeName = \"go.opentelemetry.io/collector/cmd/mdatagen/internal/sampleconnector\"\n)\n\nconst (\n\tMetricsToMetricsStability   = component.StabilityLevelDevelopment\n\tProfilesToProfilesStability = component.StabilityLevelDevelopment\n)\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/internal/metadata/testdata/config.yaml",
    "content": "default:\nall_set:\n  metrics:\n    default.metric:\n      enabled: true\n      attributes: [\"string_attr\",\"state\",\"enum_attr\",\"slice_attr\",\"map_attr\"]\n    default.metric.to_be_removed:\n      enabled: true\n    metric.input_type:\n      enabled: true\n      attributes: [\"string_attr\",\"state\",\"enum_attr\",\"slice_attr\",\"map_attr\"]\n    optional.metric:\n      enabled: true\n      attributes: [\"string_attr\",\"boolean_attr\",\"boolean_attr2\"]\n    optional.metric.empty_unit:\n      enabled: true\n      attributes: [\"string_attr\",\"boolean_attr\"]\n    reaggregate.metric:\n      enabled: true\n      attributes: [\"string_attr\",\"boolean_attr\"]\n  resource_attributes:\n    map.resource.attr:\n      enabled: true\n    optional.resource.attr:\n      enabled: true\n    slice.resource.attr:\n      enabled: true\n    string.enum.resource.attr:\n      enabled: true\n    string.resource.attr:\n      enabled: true\n    string.resource.attr_disable_warning:\n      enabled: true\n    string.resource.attr_remove_warning:\n      enabled: true\n    string.resource.attr_to_be_removed:\n      enabled: true\nreaggregate_set:\n  metrics:\n    default.metric:\n      enabled: true\n      attributes: []\n    default.metric.to_be_removed:\n      enabled: true\n    metric.input_type:\n      enabled: true\n      attributes: []\n    optional.metric:\n      enabled: true\n      attributes: []\n    optional.metric.empty_unit:\n      enabled: true\n      attributes: []\n    reaggregate.metric:\n      enabled: true\n      attributes: []\n  resource_attributes:\n    map.resource.attr:\n      enabled: true\n    optional.resource.attr:\n      enabled: true\n    slice.resource.attr:\n      enabled: true\n    string.enum.resource.attr:\n      enabled: true\n    string.resource.attr:\n      enabled: true\n    string.resource.attr_disable_warning:\n      enabled: true\n    string.resource.attr_remove_warning:\n      enabled: true\n    string.resource.attr_to_be_removed:\n      enabled: true\nnone_set:\n  metrics:\n    default.metric:\n      enabled: false\n      attributes: [\"string_attr\",\"state\",\"enum_attr\",\"slice_attr\",\"map_attr\"]\n    default.metric.to_be_removed:\n      enabled: false\n    metric.input_type:\n      enabled: false\n      attributes: [\"string_attr\",\"state\",\"enum_attr\",\"slice_attr\",\"map_attr\"]\n    optional.metric:\n      enabled: false\n      attributes: [\"string_attr\",\"boolean_attr\",\"boolean_attr2\"]\n    optional.metric.empty_unit:\n      enabled: false\n      attributes: [\"string_attr\",\"boolean_attr\"]\n    reaggregate.metric:\n      enabled: false\n      attributes: [\"string_attr\",\"boolean_attr\"]\n  resource_attributes:\n    map.resource.attr:\n      enabled: false\n    optional.resource.attr:\n      enabled: false\n    slice.resource.attr:\n      enabled: false\n    string.enum.resource.attr:\n      enabled: false\n    string.resource.attr:\n      enabled: false\n    string.resource.attr_disable_warning:\n      enabled: false\n    string.resource.attr_remove_warning:\n      enabled: false\n    string.resource.attr_to_be_removed:\n      enabled: false\nfilter_set_include:\n  resource_attributes:\n    map.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    optional.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    slice.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    string.enum.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    string.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    string.resource.attr_disable_warning:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    string.resource.attr_remove_warning:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    string.resource.attr_to_be_removed:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\nfilter_set_exclude:\n  resource_attributes:\n    map.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - regexp: \".*\"\n    optional.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - strict: \"optional.resource.attr-val\"\n    slice.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - regexp: \".*\"\n    string.enum.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - strict: \"one\"\n    string.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - strict: \"string.resource.attr-val\"\n    string.resource.attr_disable_warning:\n      enabled: true\n      metrics_exclude:\n        - strict: \"string.resource.attr_disable_warning-val\"\n    string.resource.attr_remove_warning:\n      enabled: true\n      metrics_exclude:\n        - strict: \"string.resource.attr_remove_warning-val\"\n    string.resource.attr_to_be_removed:\n      enabled: true\n      metrics_exclude:\n        - strict: \"string.resource.attr_to_be_removed-val\"\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/metadata.yaml",
    "content": "# Sample metadata file with all available configurations for a connector.\n\ntype: sample\ndisplay_name: Sample Connector\ndescription: This connector is used for testing purposes to check the output of mdatagen.\ngithub_project: open-telemetry/opentelemetry-collector\nreaggregation_enabled: true\n\nsem_conv_version: 1.9.0\n\nstatus:\n  disable_codecov_badge: true\n  class: connector\n  stability:\n    development: [metrics_to_metrics, profiles_to_profiles]\n  distributions: []\n  unsupported_platforms: [freebsd, illumos]\n  codeowners:\n    active: []\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nresource_attributes:\n  map.resource.attr:\n    description: Resource attribute with a map value.\n    type: map\n    enabled: true\n\n  optional.resource.attr:\n    description: Explicitly disabled ResourceAttribute.\n    type: string\n    enabled: false\n\n  slice.resource.attr:\n    description: Resource attribute with a slice value.\n    type: slice\n    enabled: true\n\n  string.enum.resource.attr:\n    description: Resource attribute with a known set of string values.\n    type: string\n    enum: [one, two]\n    enabled: true\n\n  string.resource.attr:\n    description: Resource attribute with any string value.\n    type: string\n    enabled: true\n\n  string.resource.attr_disable_warning:\n    description: Resource attribute with any string value.\n    type: string\n    enabled: true\n    warnings:\n      if_enabled_not_set: This resource_attribute will be disabled by default soon.\n\n  string.resource.attr_remove_warning:\n    description: Resource attribute with any string value.\n    type: string\n    enabled: false\n    warnings:\n      if_configured: This resource_attribute is deprecated and will be removed soon.\n\n  string.resource.attr_to_be_removed:\n    description: Resource attribute with any string value.\n    type: string\n    enabled: true\n    warnings:\n      if_enabled: This resource_attribute is deprecated and will be removed soon.\n\nentities:\n  - type: test.entity\n    brief: A test entity.\n    stability: stable\n    identity:\n      - ref: string.resource.attr\n    description:\n      - ref: map.resource.attr\n\nattributes:\n  boolean_attr:\n    description: Attribute with a boolean value.\n    type: bool\n\n  # This 2nd boolean attribute allows us to test both values for boolean attributes,\n  # as test values are based on the parity of the attribute name length.\n  boolean_attr2:\n    description: Another attribute with a boolean value.\n    type: bool\n\n  enum_attr:\n    description: Attribute with a known set of string values.\n    type: string\n    enum: [red, green, blue]\n\n  map_attr:\n    description: Attribute with a map value.\n    type: map\n\n  overridden_int_attr:\n    name_override: state\n    description: Integer attribute with overridden name.\n    type: int\n\n  slice_attr:\n    description: Attribute with a slice value.\n    type: slice\n\n  string_attr:\n    description: Attribute with any string value.\n    type: string\n\nmetrics:\n  default.metric:\n    enabled: true\n    description: Monotonic cumulative sum int metric enabled by default.\n    extended_documentation: The metric will be become optional soon.\n    stability: development\n    unit: s\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n    attributes:\n      [string_attr, overridden_int_attr, enum_attr, slice_attr, map_attr]\n    entity: test.entity\n    warnings:\n      if_enabled_not_set: This metric will be disabled by default soon.\n\n  default.metric.to_be_removed:\n    enabled: true\n    description: \"[DEPRECATED] Non-monotonic delta sum double metric enabled by default.\"\n    extended_documentation: The metric will be removed soon.\n    stability: deprecated\n    deprecated:\n      since: \"1.0.0\"\n      note: \"This metric will be removed\"\n    unit: s\n    sum:\n      value_type: double\n      monotonic: false\n      aggregation_temporality: delta\n    entity: test.entity\n    warnings:\n      if_enabled: This metric is deprecated and will be removed soon.\n\n  metric.input_type:\n    enabled: true\n    description: Monotonic cumulative sum int metric with string input_type enabled by default.\n    stability: development\n    unit: s\n    sum:\n      value_type: int\n      input_type: string\n      monotonic: true\n      aggregation_temporality: cumulative\n    attributes:\n      [string_attr, overridden_int_attr, enum_attr, slice_attr, map_attr]\n    entity: test.entity\n\n  optional.metric:\n    enabled: false\n    description: \"[DEPRECATED] Gauge double metric disabled by default.\"\n    stability: deprecated\n    deprecated:\n       since: \"1.0.0\"\n       note: \"This metric will be removed\"\n    unit: \"1\"\n    gauge:\n      value_type: double\n    attributes: [string_attr, boolean_attr, boolean_attr2]\n    entity: test.entity\n    warnings:\n      if_configured: This metric is deprecated and will be removed soon.\n\n  optional.metric.empty_unit:\n    enabled: false\n    description: \"[DEPRECATED] Gauge double metric disabled by default.\"\n    stability: deprecated\n    deprecated:\n      since: \"1.0.0\"\n      note: \"This metric will be removed\"\n    unit: \"\"\n    gauge:\n      value_type: double\n    attributes: [string_attr, boolean_attr]\n    entity: test.entity\n    warnings:\n      if_configured: This metric is deprecated and will be removed soon.\n\n  reaggregate.metric:\n    enabled: true\n    description: Metric for testing spatial reaggregation\n    unit: \"1\"\n    stability: beta\n    gauge:\n      value_type: double\n    attributes: [string_attr, boolean_attr]\n    entity: test.entity\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleconnector/metrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage sampleconnector\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/sampleconnector/internal/metadata\"\n\t\"go.opentelemetry.io/collector/connector/connectortest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\n// TestGeneratedMetrics verifies that the internal/metadata API is generated correctly.\nfunc TestGeneratedMetrics(t *testing.T) {\n\tmb := metadata.NewMetricsBuilder(metadata.DefaultMetricsBuilderConfig(), connectortest.NewNopSettings(metadata.Type))\n\tm := mb.Emit()\n\trequire.Equal(t, 0, m.ResourceMetrics().Len())\n}\n\nfunc TestNopConnector(t *testing.T) {\n\tconnector, err := createMetricsToMetricsConnector(context.Background(), connectortest.NewNopSettings(metadata.Type), newMdatagenNopHost(), new(consumertest.MetricsSink))\n\trequire.NoError(t, err)\n\trequire.False(t, connector.Capabilities().MutatesData)\n\trequire.NoError(t, connector.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleentityreceiver/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Generate a sample entity-based metrics builder\n//go:generate mdatagen metadata.yaml\n\npackage sampleentityreceiver // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/sampleentityreceiver\"\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleentityreceiver/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# sampleentity\n\n## Default Metrics\n\nThe following metrics are emitted by default. Each of them can be disabled by applying the following configuration:\n\n```yaml\nmetrics:\n  <metric_name>:\n    enabled: false\n```\n\n### k8s.pod.cpu_time\n\nCPU time consumed by the pod\n\n| Unit | Metric Type | Value Type | Aggregation Temporality | Monotonic | Stability |\n| ---- | ----------- | ---------- | ----------------------- | --------- | --------- |\n| s | Sum | Double | Cumulative | true | Development |\n\n### k8s.pod.phase\n\nCurrent phase of the pod\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| 1 | Gauge | Int | Development |\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n| phase | The phase of the pod (Pending, Running, Succeeded, Failed, Unknown) | Str: ``Pending``, ``Running``, ``Succeeded``, ``Failed``, ``Unknown`` | Recommended |\n\n### k8s.replicaset.desired\n\nNumber of desired replicas\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| {replicas} | Gauge | Int | Development |\n\n## Resource Attributes\n\n| Name | Description | Values | Enabled |\n| ---- | ----------- | ------ | ------- |\n| k8s.namespace.name | The name of the Kubernetes Namespace | Any Str | true |\n| k8s.pod.name | The name of the Kubernetes Pod | Any Str | true |\n| k8s.pod.uid | The UID of the Kubernetes Pod | Any Str | true |\n| k8s.replicaset.name | The name of the Kubernetes ReplicaSet | Any Str | true |\n| k8s.replicaset.uid | The UID of the Kubernetes ReplicaSet | Any Str | true |\n\n## Entities\n\nThe following entities are defined for this component:\n\n### k8s.replicaset\n\nA Kubernetes ReplicaSet\n\n**Stability:** Development\n\n**Identifying Attributes:**\n- `k8s.replicaset.uid`\n\n**Descriptive Attributes:**\n- `k8s.replicaset.name`\n\n### k8s.pod\n\nA Kubernetes Pod\n\n**Stability:** Development\n\n**Identifying Attributes:**\n- `k8s.pod.uid`\n\n**Descriptive Attributes:**\n- `k8s.pod.name`\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleentityreceiver/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage sampleentityreceiver // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/sampleentityreceiver\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/sampleentityreceiver/internal/metadata\"\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n)\n\n// NewFactory returns a receiver.Factory for sample entity receiver.\nfunc NewFactory() xreceiver.Factory {\n\treturn xreceiver.NewFactory(\n\t\tmetadata.Type,\n\t\tfunc() component.Config { return &struct{}{} },\n\t\txreceiver.WithMetrics(createMetrics, metadata.MetricsStability),\n\t)\n}\n\nfunc createMetrics(context.Context, receiver.Settings, component.Config, consumer.Metrics) (receiver.Metrics, error) {\n\treturn nopInstance, nil\n}\n\nvar nopInstance = &nopReceiver{}\n\ntype nopReceiver struct {\n\tcomponent.StartFunc\n}\n\nfunc (nopReceiver) Shutdown(context.Context) error {\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleentityreceiver/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage sampleentityreceiver\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\nvar typ = component.MustNewType(\"sampleentity\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct {\n\t\tcreateFn func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error)\n\t\tname     string\n\t}{\n\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name+\"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\tt.Run(tt.name+\"-lifecycle\", func(t *testing.T) {\n\t\t\tfirstRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := newMdatagenNopHost()\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, firstRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, firstRcvr.Shutdown(context.Background()))\n\t\t\tsecondRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, secondRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, secondRcvr.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleentityreceiver/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage sampleentityreceiver\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleentityreceiver/internal/metadata/config.schema.yaml",
    "content": "# Code generated by mdatagen. DO NOT EDIT.\n$defs:\n  metrics_config:\n    description: MetricsConfig provides config for sampleentity metrics.\n    type: object\n    properties:\n      k8s.pod.cpu_time:\n        description: \"K8sPodCPUTimeMetricConfig provides config for the k8s.pod.cpu_time metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n      k8s.pod.phase:\n        description: \"K8sPodPhaseMetricConfig provides config for the k8s.pod.phase metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n      k8s.replicaset.desired:\n        description: \"K8sReplicasetDesiredMetricConfig provides config for the k8s.replicaset.desired metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n  resource_attributes_config:\n    description: ResourceAttributesConfig provides config for sampleentity resource attributes.\n    type: object\n    properties:\n      k8s.namespace.name:\n        description: ResourceAttributeConfig provides common config for a k8s.namespace.name resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      k8s.pod.name:\n        description: ResourceAttributeConfig provides common config for a k8s.pod.name resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      k8s.pod.uid:\n        description: ResourceAttributeConfig provides common config for a k8s.pod.uid resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      k8s.replicaset.name:\n        description: ResourceAttributeConfig provides common config for a k8s.replicaset.name resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      k8s.replicaset.uid:\n        description: ResourceAttributeConfig provides common config for a k8s.replicaset.uid resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n  metrics_builder_config:\n    description: MetricsBuilderConfig is a configuration for sampleentity metrics builder.\n    type: object\n    properties:\n      metrics:\n        $ref: metrics_config\n      resource_attributes:\n        $ref: resource_attributes_config\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleentityreceiver/internal/metadata/generated_config.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/filter\"\n)\n\n// MetricConfig provides common config for a particular metric.\ntype MetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n}\n\nfunc (ms *MetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\n// MetricsConfig provides config for sampleentity metrics.\ntype MetricsConfig struct {\n\tK8sPodCPUTime        MetricConfig `mapstructure:\"k8s.pod.cpu_time\"`\n\tK8sPodPhase          MetricConfig `mapstructure:\"k8s.pod.phase\"`\n\tK8sReplicasetDesired MetricConfig `mapstructure:\"k8s.replicaset.desired\"`\n}\n\nfunc DefaultMetricsConfig() MetricsConfig {\n\treturn MetricsConfig{\n\t\tK8sPodCPUTime: MetricConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tK8sPodPhase: MetricConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tK8sReplicasetDesired: MetricConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t}\n}\n\n// ResourceAttributeConfig provides common config for a particular resource attribute.\ntype ResourceAttributeConfig struct {\n\tEnabled bool `mapstructure:\"enabled\"`\n\t// Experimental: MetricsInclude defines a list of filters for attribute values.\n\t// If the list is not empty, only metrics with matching resource attribute values will be emitted.\n\tMetricsInclude []filter.Config `mapstructure:\"metrics_include\"`\n\t// Experimental: MetricsExclude defines a list of filters for attribute values.\n\t// If the list is not empty, metrics with matching resource attribute values will not be emitted.\n\t// MetricsInclude has higher priority than MetricsExclude.\n\tMetricsExclude []filter.Config `mapstructure:\"metrics_exclude\"`\n\n\tenabledSetByUser bool\n}\n\nfunc (rac *ResourceAttributeConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\terr := parser.Unmarshal(rac)\n\tif err != nil {\n\t\treturn err\n\t}\n\trac.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\n// ResourceAttributesConfig provides config for sampleentity resource attributes.\ntype ResourceAttributesConfig struct {\n\tK8sNamespaceName  ResourceAttributeConfig `mapstructure:\"k8s.namespace.name\"`\n\tK8sPodName        ResourceAttributeConfig `mapstructure:\"k8s.pod.name\"`\n\tK8sPodUID         ResourceAttributeConfig `mapstructure:\"k8s.pod.uid\"`\n\tK8sReplicasetName ResourceAttributeConfig `mapstructure:\"k8s.replicaset.name\"`\n\tK8sReplicasetUID  ResourceAttributeConfig `mapstructure:\"k8s.replicaset.uid\"`\n}\n\nfunc DefaultResourceAttributesConfig() ResourceAttributesConfig {\n\treturn ResourceAttributesConfig{\n\t\tK8sNamespaceName: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tK8sPodName: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tK8sPodUID: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tK8sReplicasetName: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tK8sReplicasetUID: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t}\n}\n\n// MetricsBuilderConfig is a configuration for sampleentity metrics builder.\ntype MetricsBuilderConfig struct {\n\tMetrics            MetricsConfig            `mapstructure:\"metrics\"`\n\tResourceAttributes ResourceAttributesConfig `mapstructure:\"resource_attributes\"`\n}\n\nfunc DefaultMetricsBuilderConfig() MetricsBuilderConfig {\n\treturn MetricsBuilderConfig{\n\t\tMetrics:            DefaultMetricsConfig(),\n\t\tResourceAttributes: DefaultResourceAttributesConfig(),\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleentityreceiver/internal/metadata/generated_config_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n\t\"github.com/google/go-cmp/cmp/cmpopts\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n)\n\nfunc TestMetricsBuilderConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant MetricsBuilderConfig\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\twant: DefaultMetricsBuilderConfig(),\n\t\t},\n\t\t{\n\t\t\tname: \"all_set\",\n\t\t\twant: MetricsBuilderConfig{\n\t\t\t\tMetrics: MetricsConfig{\n\t\t\t\t\tK8sPodCPUTime: MetricConfig{\n\t\t\t\t\t\tEnabled: true,\n\t\t\t\t\t},\n\t\t\t\t\tK8sPodPhase: MetricConfig{\n\t\t\t\t\t\tEnabled: true,\n\t\t\t\t\t},\n\t\t\t\t\tK8sReplicasetDesired: MetricConfig{\n\t\t\t\t\t\tEnabled: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tResourceAttributes: ResourceAttributesConfig{\n\t\t\t\t\tK8sNamespaceName:  ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tK8sPodName:        ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tK8sPodUID:         ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tK8sReplicasetName: ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tK8sReplicasetUID:  ResourceAttributeConfig{Enabled: true},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"none_set\",\n\t\t\twant: MetricsBuilderConfig{\n\t\t\t\tMetrics: MetricsConfig{\n\t\t\t\t\tK8sPodCPUTime: MetricConfig{\n\t\t\t\t\t\tEnabled: false,\n\t\t\t\t\t},\n\t\t\t\t\tK8sPodPhase: MetricConfig{\n\t\t\t\t\t\tEnabled: false,\n\t\t\t\t\t},\n\t\t\t\t\tK8sReplicasetDesired: MetricConfig{\n\t\t\t\t\t\tEnabled: false,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tResourceAttributes: ResourceAttributesConfig{\n\t\t\t\t\tK8sNamespaceName:  ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tK8sPodName:        ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tK8sPodUID:         ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tK8sReplicasetName: ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tK8sReplicasetUID:  ResourceAttributeConfig{Enabled: false},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := loadMetricsBuilderConfig(t, tt.name)\n\t\t\tdiff := cmp.Diff(tt.want, cfg, cmpopts.IgnoreUnexported(MetricConfig{}, ResourceAttributeConfig{}))\n\t\t\trequire.Emptyf(t, diff, \"Config mismatch (-expected +actual):\\n%s\", diff)\n\t\t})\n\t}\n}\n\nfunc loadMetricsBuilderConfig(t *testing.T, name string) MetricsBuilderConfig {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tsub, err := cm.Sub(name)\n\trequire.NoError(t, err)\n\tcfg := DefaultMetricsBuilderConfig()\n\trequire.NoError(t, sub.Unmarshal(&cfg, confmap.WithIgnoreUnused()))\n\treturn cfg\n}\n\nfunc TestResourceAttributesConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant ResourceAttributesConfig\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\twant: DefaultResourceAttributesConfig(),\n\t\t},\n\t\t{\n\t\t\tname: \"all_set\",\n\t\t\twant: ResourceAttributesConfig{\n\t\t\t\tK8sNamespaceName:  ResourceAttributeConfig{Enabled: true},\n\t\t\t\tK8sPodName:        ResourceAttributeConfig{Enabled: true},\n\t\t\t\tK8sPodUID:         ResourceAttributeConfig{Enabled: true},\n\t\t\t\tK8sReplicasetName: ResourceAttributeConfig{Enabled: true},\n\t\t\t\tK8sReplicasetUID:  ResourceAttributeConfig{Enabled: true},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"none_set\",\n\t\t\twant: ResourceAttributesConfig{\n\t\t\t\tK8sNamespaceName:  ResourceAttributeConfig{Enabled: false},\n\t\t\t\tK8sPodName:        ResourceAttributeConfig{Enabled: false},\n\t\t\t\tK8sPodUID:         ResourceAttributeConfig{Enabled: false},\n\t\t\t\tK8sReplicasetName: ResourceAttributeConfig{Enabled: false},\n\t\t\t\tK8sReplicasetUID:  ResourceAttributeConfig{Enabled: false},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := loadResourceAttributesConfig(t, tt.name)\n\t\t\tdiff := cmp.Diff(tt.want, cfg, cmpopts.IgnoreUnexported(ResourceAttributeConfig{}))\n\t\t\trequire.Emptyf(t, diff, \"Config mismatch (-expected +actual):\\n%s\", diff)\n\t\t})\n\t}\n}\n\nfunc loadResourceAttributesConfig(t *testing.T, name string) ResourceAttributesConfig {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tsub, err := cm.Sub(name)\n\trequire.NoError(t, err)\n\tsub, err = sub.Sub(\"resource_attributes\")\n\trequire.NoError(t, err)\n\tcfg := DefaultResourceAttributesConfig()\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\treturn cfg\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleentityreceiver/internal/metadata/generated_entity_metrics.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/entity\"\n)\n\n// K8sReplicasetEntity represents a k8s.replicaset entity.\n// Create one with NewK8sReplicasetEntity and pass it to EmitForEntity.\ntype K8sReplicasetEntity struct {\n\tk8sReplicasetUID  string\n\tk8sReplicasetName string\n}\n\n// NewK8sReplicasetEntity creates a new K8sReplicasetEntity.\n// Identity attributes are required and must be provided at construction time.\nfunc NewK8sReplicasetEntity(k8sReplicasetUID string) *K8sReplicasetEntity {\n\treturn &K8sReplicasetEntity{\n\t\tk8sReplicasetUID: k8sReplicasetUID,\n\t}\n}\n\n// Description attribute setters for k8s.replicaset.\n\n// SetK8sReplicasetName sets the k8s.replicaset.name description attribute.\nfunc (e *K8sReplicasetEntity) SetK8sReplicasetName(val string) {\n\te.k8sReplicasetName = val\n}\n\n// copyToResource populates res with the entity's attributes according to cfg.\n// If all identity attributes are enabled, an entity ref is produced; otherwise\n// the enabled attributes are written directly as plain resource attributes.\nfunc (e *K8sReplicasetEntity) copyToResource(cfg ResourceAttributesConfig, res pcommon.Resource) {\n\tif cfg.K8sReplicasetUID.Enabled {\n\t\tent := entity.ResourceEntities(res).PutEmpty(\"k8s.replicaset\")\n\t\tent.IdentifyingAttributes().PutStr(\"k8s.replicaset.uid\", e.k8sReplicasetUID)\n\t\tif cfg.K8sReplicasetName.Enabled {\n\t\t\tent.DescriptiveAttributes().PutStr(\"k8s.replicaset.name\", e.k8sReplicasetName)\n\t\t}\n\t} else {\n\t\tif cfg.K8sReplicasetUID.Enabled {\n\t\t\tres.Attributes().PutStr(\"k8s.replicaset.uid\", e.k8sReplicasetUID)\n\t\t}\n\t\tif cfg.K8sReplicasetName.Enabled {\n\t\t\tres.Attributes().PutStr(\"k8s.replicaset.name\", e.k8sReplicasetName)\n\t\t}\n\t}\n}\n\n// K8sPodEntity represents a k8s.pod entity.\n// Create one with NewK8sPodEntity and pass it to EmitForEntity.\ntype K8sPodEntity struct {\n\tk8sPodUID                 string\n\tk8sPodName                string\n\tk8sNamespaceName          string\n\tcontrolledByK8sReplicaset *K8sReplicasetEntity\n}\n\n// NewK8sPodEntity creates a new K8sPodEntity.\n// Identity attributes are required and must be provided at construction time.\nfunc NewK8sPodEntity(k8sPodUID string) *K8sPodEntity {\n\treturn &K8sPodEntity{\n\t\tk8sPodUID: k8sPodUID,\n\t}\n}\n\n// Description attribute setters for k8s.pod.\n\n// SetK8sPodName sets the k8s.pod.name description attribute.\nfunc (e *K8sPodEntity) SetK8sPodName(val string) {\n\te.k8sPodName = val\n}\n\n// Extra attribute setters for k8s.pod.\n// These attributes are contextually relevant but are not part of the entity's identity or description.\n\n// SetK8sNamespaceName sets the k8s.namespace.name extra attribute on the resource.\nfunc (e *K8sPodEntity) SetK8sNamespaceName(val string) {\n\te.k8sNamespaceName = val\n}\n\n// Relationship setters for k8s.pod.\n\n// SetControlledByK8sReplicaset sets the controlled_by relationship to a k8s.replicaset entity.\n// The related entity will be emitted alongside this entity's metrics.\nfunc (e *K8sPodEntity) SetControlledByK8sReplicaset(target *K8sReplicasetEntity) {\n\te.controlledByK8sReplicaset = target\n}\n\n// copyToResource populates res with the entity's attributes according to cfg.\n// If all identity attributes are enabled, an entity ref is produced; otherwise\n// the enabled attributes are written directly as plain resource attributes.\nfunc (e *K8sPodEntity) copyToResource(cfg ResourceAttributesConfig, res pcommon.Resource) {\n\tif cfg.K8sPodUID.Enabled {\n\t\tent := entity.ResourceEntities(res).PutEmpty(\"k8s.pod\")\n\t\tent.IdentifyingAttributes().PutStr(\"k8s.pod.uid\", e.k8sPodUID)\n\t\tif cfg.K8sPodName.Enabled {\n\t\t\tent.DescriptiveAttributes().PutStr(\"k8s.pod.name\", e.k8sPodName)\n\t\t}\n\t\tif cfg.K8sNamespaceName.Enabled {\n\t\t\tres.Attributes().PutStr(\"k8s.namespace.name\", e.k8sNamespaceName)\n\t\t}\n\t} else {\n\t\tif cfg.K8sPodUID.Enabled {\n\t\t\tres.Attributes().PutStr(\"k8s.pod.uid\", e.k8sPodUID)\n\t\t}\n\t\tif cfg.K8sPodName.Enabled {\n\t\t\tres.Attributes().PutStr(\"k8s.pod.name\", e.k8sPodName)\n\t\t}\n\t\tif cfg.K8sNamespaceName.Enabled {\n\t\t\tres.Attributes().PutStr(\"k8s.namespace.name\", e.k8sNamespaceName)\n\t\t}\n\t}\n}\n\n// K8sReplicasetMetricsBuilder records metrics for the k8s.replicaset entity.\n// Obtain one via MetricsBuilder.ForK8sReplicaset().\ntype K8sReplicasetMetricsBuilder struct {\n\tmb     *MetricsBuilder\n\tentity *K8sReplicasetEntity\n}\n\n// RecordK8sReplicasetDesiredDataPoint records a data point for the k8s.replicaset.desired metric.\nfunc (eb *K8sReplicasetMetricsBuilder) RecordK8sReplicasetDesiredDataPoint(ts pcommon.Timestamp, val int64) {\n\teb.mb.metricK8sReplicasetDesired.recordDataPoint(eb.mb.startTime, ts, val)\n}\n\n// Emit emits all pending metrics for the entity. Resource attributes are filtered by config:\n// disabled identity attributes suppress the entity (other enabled attributes are added directly\n// to the resource); disabled descriptive/extra attributes are omitted entirely.\nfunc (eb *K8sReplicasetMetricsBuilder) Emit() {\n\tres := pcommon.NewResource()\n\tcfg := eb.mb.config.ResourceAttributes\n\teb.entity.copyToResource(cfg, res)\n\teb.mb.EmitForResource(withResourceMoved(res))\n}\n\n// K8sPodMetricsBuilder records metrics for the k8s.pod entity.\n// Obtain one via MetricsBuilder.ForK8sPod().\ntype K8sPodMetricsBuilder struct {\n\tmb     *MetricsBuilder\n\tentity *K8sPodEntity\n}\n\n// RecordK8sPodCPUTimeDataPoint records a data point for the k8s.pod.cpu_time metric.\nfunc (eb *K8sPodMetricsBuilder) RecordK8sPodCPUTimeDataPoint(ts pcommon.Timestamp, val float64) {\n\teb.mb.metricK8sPodCPUTime.recordDataPoint(eb.mb.startTime, ts, val)\n}\n\n// RecordK8sPodPhaseDataPoint records a data point for the k8s.pod.phase metric.\nfunc (eb *K8sPodMetricsBuilder) RecordK8sPodPhaseDataPoint(ts pcommon.Timestamp, val int64, phaseAttributeValue AttributePhase) {\n\teb.mb.metricK8sPodPhase.recordDataPoint(eb.mb.startTime, ts, val, phaseAttributeValue.String())\n}\n\n// Emit emits all pending metrics for the entity. Resource attributes are filtered by config:\n// disabled identity attributes suppress the entity (other enabled attributes are added directly\n// to the resource); disabled descriptive/extra attributes are omitted entirely.\nfunc (eb *K8sPodMetricsBuilder) Emit() {\n\tres := pcommon.NewResource()\n\tcfg := eb.mb.config.ResourceAttributes\n\teb.entity.copyToResource(cfg, res)\n\tif eb.entity.controlledByK8sReplicaset != nil {\n\t\teb.entity.controlledByK8sReplicaset.copyToResource(cfg, res)\n\t}\n\teb.mb.EmitForResource(withResourceMoved(res))\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleentityreceiver/internal/metadata/generated_entity_metrics_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/entity\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\nfunc TestEntityBuilders(t *testing.T) {\n\tstart := pcommon.Timestamp(1_000_000_000)\n\tts := pcommon.Timestamp(1_000_001_000)\n\tsettings := receivertest.NewNopSettings(receivertest.NopType)\n\tmb := NewMetricsBuilder(DefaultMetricsBuilderConfig(), settings, WithStartTime(start))\n\n\tt.Run(\"k8s.replicaset\", func(t *testing.T) {\n\t\te := NewK8sReplicasetEntity(\"k8s.replicaset.uid-val\")\n\t\trequire.NotNil(t, e)\n\t\te.SetK8sReplicasetName(\"k8s.replicaset.name-val\")\n\n\t\teb := mb.ForK8sReplicaset(e)\n\t\teb.RecordK8sReplicasetDesiredDataPoint(ts, 1)\n\t\teb.Emit()\n\t\tmetrics := mb.Emit()\n\n\t\trequire.Equal(t, 1, metrics.ResourceMetrics().Len())\n\t\trm := metrics.ResourceMetrics().At(0)\n\t\tentityVal, ok := entity.ResourceEntities(rm.Resource()).Get(\"k8s.replicaset\")\n\t\trequire.True(t, ok)\n\t\tk8sReplicasetUIDAttrVal, ok := entityVal.IdentifyingAttributes().Get(\"k8s.replicaset.uid\")\n\t\trequire.True(t, ok)\n\t\tassert.Equal(t, \"k8s.replicaset.uid-val\", k8sReplicasetUIDAttrVal.Str())\n\t\tk8sReplicasetNameAttrVal, ok := entityVal.DescriptiveAttributes().Get(\"k8s.replicaset.name\")\n\t\trequire.True(t, ok)\n\t\tassert.Equal(t, \"k8s.replicaset.name-val\", k8sReplicasetNameAttrVal.Str())\n\n\t\trequire.Equal(t, 1, rm.ScopeMetrics().Len())\n\t\tms := rm.ScopeMetrics().At(0).Metrics()\n\t\tassert.Equal(t, 1, ms.Len())\n\t})\n\tt.Run(\"k8s.replicaset/disabled_identity_attr\", func(t *testing.T) {\n\t\t// When an identity attribute is disabled, the entity is not produced but\n\t\t// other enabled attributes are still added to the resource directly.\n\t\tcfg := DefaultMetricsBuilderConfig()\n\t\tcfg.ResourceAttributes.K8sReplicasetUID.Enabled = false\n\t\tmb := NewMetricsBuilder(cfg, settings, WithStartTime(start))\n\n\t\te := NewK8sReplicasetEntity(\"k8s.replicaset.uid-val\")\n\t\te.SetK8sReplicasetName(\"k8s.replicaset.name-val\")\n\n\t\teb := mb.ForK8sReplicaset(e)\n\t\teb.RecordK8sReplicasetDesiredDataPoint(ts, 1)\n\t\teb.Emit()\n\t\tmetrics := mb.Emit()\n\n\t\trequire.Equal(t, 1, metrics.ResourceMetrics().Len())\n\t\trm := metrics.ResourceMetrics().At(0)\n\t\t// Entity must not be present since its identity attribute is disabled.\n\t\t_, ok := entity.ResourceEntities(rm.Resource()).Get(\"k8s.replicaset\")\n\t\tassert.False(t, ok)\n\t\t// Enabled descriptive attributes should still be on the resource directly.\n\t\t_, ok = rm.Resource().Attributes().Get(\"k8s.replicaset.name\")\n\t\tassert.True(t, ok)\n\t})\n\tt.Run(\"k8s.replicaset/disabled_descriptive_attr\", func(t *testing.T) {\n\t\t// When a descriptive attribute is disabled, the entity is still produced\n\t\t// with its identity but the disabled attribute is not added.\n\t\tcfg := DefaultMetricsBuilderConfig()\n\t\tcfg.ResourceAttributes.K8sReplicasetName.Enabled = false\n\t\tmb := NewMetricsBuilder(cfg, settings, WithStartTime(start))\n\n\t\te := NewK8sReplicasetEntity(\"k8s.replicaset.uid-val\")\n\t\te.SetK8sReplicasetName(\"k8s.replicaset.name-val\")\n\n\t\teb := mb.ForK8sReplicaset(e)\n\t\teb.RecordK8sReplicasetDesiredDataPoint(ts, 1)\n\t\teb.Emit()\n\t\tmetrics := mb.Emit()\n\n\t\trequire.Equal(t, 1, metrics.ResourceMetrics().Len())\n\t\trm := metrics.ResourceMetrics().At(0)\n\t\t// Entity must still be produced since identity attributes are enabled.\n\t\tentityVal, ok := entity.ResourceEntities(rm.Resource()).Get(\"k8s.replicaset\")\n\t\trequire.True(t, ok)\n\t\tk8sReplicasetUIDAttrVal, ok := entityVal.IdentifyingAttributes().Get(\"k8s.replicaset.uid\")\n\t\trequire.True(t, ok)\n\t\tassert.Equal(t, \"k8s.replicaset.uid-val\", k8sReplicasetUIDAttrVal.Str())\n\t\t// Disabled descriptive/extra attributes must not be present.\n\t\t_, ok = entityVal.DescriptiveAttributes().Get(\"k8s.replicaset.name\")\n\t\tassert.False(t, ok)\n\t})\n\n\tt.Run(\"k8s.pod\", func(t *testing.T) {\n\t\te := NewK8sPodEntity(\"k8s.pod.uid-val\")\n\t\trequire.NotNil(t, e)\n\t\te.SetK8sPodName(\"k8s.pod.name-val\")\n\t\te.SetK8sNamespaceName(\"k8s.namespace.name-val\")\n\t\trelatedK8sReplicaset := NewK8sReplicasetEntity(\"k8s.replicaset.uid-val\")\n\t\te.SetControlledByK8sReplicaset(relatedK8sReplicaset)\n\n\t\teb := mb.ForK8sPod(e)\n\t\teb.RecordK8sPodCPUTimeDataPoint(ts, 1)\n\t\teb.RecordK8sPodPhaseDataPoint(ts, 1, AttributePhasePending)\n\t\teb.Emit()\n\t\tmetrics := mb.Emit()\n\n\t\trequire.Equal(t, 1, metrics.ResourceMetrics().Len())\n\t\trm := metrics.ResourceMetrics().At(0)\n\t\tentityVal, ok := entity.ResourceEntities(rm.Resource()).Get(\"k8s.pod\")\n\t\trequire.True(t, ok)\n\t\tk8sPodUIDAttrVal, ok := entityVal.IdentifyingAttributes().Get(\"k8s.pod.uid\")\n\t\trequire.True(t, ok)\n\t\tassert.Equal(t, \"k8s.pod.uid-val\", k8sPodUIDAttrVal.Str())\n\t\tk8sPodNameAttrVal, ok := entityVal.DescriptiveAttributes().Get(\"k8s.pod.name\")\n\t\trequire.True(t, ok)\n\t\tassert.Equal(t, \"k8s.pod.name-val\", k8sPodNameAttrVal.Str())\n\t\t_, ok = entityVal.DescriptiveAttributes().Get(\"k8s.namespace.name\")\n\t\tassert.False(t, ok)\n\t\tk8sNamespaceNameAttrVal, ok := rm.Resource().Attributes().Get(\"k8s.namespace.name\")\n\t\trequire.True(t, ok)\n\t\tassert.Equal(t, \"k8s.namespace.name-val\", k8sNamespaceNameAttrVal.Str())\n\n\t\trequire.Equal(t, 1, rm.ScopeMetrics().Len())\n\t\tms := rm.ScopeMetrics().At(0).Metrics()\n\t\tassert.Equal(t, 2, ms.Len())\n\t})\n\tt.Run(\"k8s.pod/disabled_identity_attr\", func(t *testing.T) {\n\t\t// When an identity attribute is disabled, the entity is not produced but\n\t\t// other enabled attributes are still added to the resource directly.\n\t\tcfg := DefaultMetricsBuilderConfig()\n\t\tcfg.ResourceAttributes.K8sPodUID.Enabled = false\n\t\tmb := NewMetricsBuilder(cfg, settings, WithStartTime(start))\n\n\t\te := NewK8sPodEntity(\"k8s.pod.uid-val\")\n\t\te.SetK8sPodName(\"k8s.pod.name-val\")\n\n\t\teb := mb.ForK8sPod(e)\n\t\teb.RecordK8sPodCPUTimeDataPoint(ts, 1)\n\t\teb.RecordK8sPodPhaseDataPoint(ts, 1, AttributePhasePending)\n\t\teb.Emit()\n\t\tmetrics := mb.Emit()\n\n\t\trequire.Equal(t, 1, metrics.ResourceMetrics().Len())\n\t\trm := metrics.ResourceMetrics().At(0)\n\t\t// Entity must not be present since its identity attribute is disabled.\n\t\t_, ok := entity.ResourceEntities(rm.Resource()).Get(\"k8s.pod\")\n\t\tassert.False(t, ok)\n\t\t// Enabled descriptive attributes should still be on the resource directly.\n\t\t_, ok = rm.Resource().Attributes().Get(\"k8s.pod.name\")\n\t\tassert.True(t, ok)\n\t})\n\tt.Run(\"k8s.pod/disabled_descriptive_attr\", func(t *testing.T) {\n\t\t// When a descriptive attribute is disabled, the entity is still produced\n\t\t// with its identity but the disabled attribute is not added.\n\t\tcfg := DefaultMetricsBuilderConfig()\n\t\tcfg.ResourceAttributes.K8sPodName.Enabled = false\n\t\tcfg.ResourceAttributes.K8sNamespaceName.Enabled = false\n\t\tmb := NewMetricsBuilder(cfg, settings, WithStartTime(start))\n\n\t\te := NewK8sPodEntity(\"k8s.pod.uid-val\")\n\t\te.SetK8sPodName(\"k8s.pod.name-val\")\n\t\te.SetK8sNamespaceName(\"k8s.namespace.name-val\")\n\n\t\teb := mb.ForK8sPod(e)\n\t\teb.RecordK8sPodCPUTimeDataPoint(ts, 1)\n\t\teb.RecordK8sPodPhaseDataPoint(ts, 1, AttributePhasePending)\n\t\teb.Emit()\n\t\tmetrics := mb.Emit()\n\n\t\trequire.Equal(t, 1, metrics.ResourceMetrics().Len())\n\t\trm := metrics.ResourceMetrics().At(0)\n\t\t// Entity must still be produced since identity attributes are enabled.\n\t\tentityVal, ok := entity.ResourceEntities(rm.Resource()).Get(\"k8s.pod\")\n\t\trequire.True(t, ok)\n\t\tk8sPodUIDAttrVal, ok := entityVal.IdentifyingAttributes().Get(\"k8s.pod.uid\")\n\t\trequire.True(t, ok)\n\t\tassert.Equal(t, \"k8s.pod.uid-val\", k8sPodUIDAttrVal.Str())\n\t\t// Disabled descriptive/extra attributes must not be present.\n\t\t_, ok = entityVal.DescriptiveAttributes().Get(\"k8s.pod.name\")\n\t\tassert.False(t, ok)\n\t\t_, ok = entityVal.DescriptiveAttributes().Get(\"k8s.namespace.name\")\n\t\tassert.False(t, ok)\n\t})\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleentityreceiver/internal/metadata/generated_metrics.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"time\"\n\n\tconventions \"go.opentelemetry.io/otel/semconv/v1.38.0\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/filter\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/receiver\"\n)\n\n// AttributePhase specifies the value phase attribute.\ntype AttributePhase int\n\nconst (\n\t_ AttributePhase = iota\n\tAttributePhasePending\n\tAttributePhaseRunning\n\tAttributePhaseSucceeded\n\tAttributePhaseFailed\n\tAttributePhaseUnknown\n)\n\n// String returns the string representation of the AttributePhase.\nfunc (av AttributePhase) String() string {\n\tswitch av {\n\tcase AttributePhasePending:\n\t\treturn \"Pending\"\n\tcase AttributePhaseRunning:\n\t\treturn \"Running\"\n\tcase AttributePhaseSucceeded:\n\t\treturn \"Succeeded\"\n\tcase AttributePhaseFailed:\n\t\treturn \"Failed\"\n\tcase AttributePhaseUnknown:\n\t\treturn \"Unknown\"\n\t}\n\treturn \"\"\n}\n\n// MapAttributePhase is a helper map of string to AttributePhase attribute value.\nvar MapAttributePhase = map[string]AttributePhase{\n\t\"Pending\":   AttributePhasePending,\n\t\"Running\":   AttributePhaseRunning,\n\t\"Succeeded\": AttributePhaseSucceeded,\n\t\"Failed\":    AttributePhaseFailed,\n\t\"Unknown\":   AttributePhaseUnknown,\n}\n\nvar MetricsInfo = metricsInfo{\n\tK8sPodCPUTime: metricInfo{\n\t\tName: \"k8s.pod.cpu_time\",\n\t},\n\tK8sPodPhase: metricInfo{\n\t\tName: \"k8s.pod.phase\",\n\t},\n\tK8sReplicasetDesired: metricInfo{\n\t\tName: \"k8s.replicaset.desired\",\n\t},\n}\n\ntype metricsInfo struct {\n\tK8sPodCPUTime        metricInfo\n\tK8sPodPhase          metricInfo\n\tK8sReplicasetDesired metricInfo\n}\n\ntype metricInfo struct {\n\tName string\n}\n\ntype metricK8sPodCPUTime struct {\n\tdata     pmetric.Metric // data buffer for generated metric.\n\tconfig   MetricConfig   // metric config provided by user.\n\tcapacity int            // max observed number of data points added to the metric.\n}\n\n// init fills k8s.pod.cpu_time metric with initial data.\nfunc (m *metricK8sPodCPUTime) init() {\n\tm.data.SetName(\"k8s.pod.cpu_time\")\n\tm.data.SetDescription(\"CPU time consumed by the pod\")\n\tm.data.SetUnit(\"s\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(true)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n}\n\nfunc (m *metricK8sPodCPUTime) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val float64) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\tdp := m.data.Sum().DataPoints().AppendEmpty()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tdp.SetDoubleValue(val)\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricK8sPodCPUTime) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricK8sPodCPUTime) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricK8sPodCPUTime(cfg MetricConfig) metricK8sPodCPUTime {\n\tm := metricK8sPodCPUTime{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricK8sPodPhase struct {\n\tdata     pmetric.Metric // data buffer for generated metric.\n\tconfig   MetricConfig   // metric config provided by user.\n\tcapacity int            // max observed number of data points added to the metric.\n}\n\n// init fills k8s.pod.phase metric with initial data.\nfunc (m *metricK8sPodPhase) init() {\n\tm.data.SetName(\"k8s.pod.phase\")\n\tm.data.SetDescription(\"Current phase of the pod\")\n\tm.data.SetUnit(\"1\")\n\tm.data.SetEmptyGauge()\n\tm.data.Gauge().DataPoints().EnsureCapacity(m.capacity)\n}\n\nfunc (m *metricK8sPodPhase) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val int64, phaseAttributeValue string) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\tdp := m.data.Gauge().DataPoints().AppendEmpty()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tdp.SetIntValue(val)\n\tdp.Attributes().PutStr(\"phase\", phaseAttributeValue)\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricK8sPodPhase) updateCapacity() {\n\tif m.data.Gauge().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Gauge().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricK8sPodPhase) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricK8sPodPhase(cfg MetricConfig) metricK8sPodPhase {\n\tm := metricK8sPodPhase{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricK8sReplicasetDesired struct {\n\tdata     pmetric.Metric // data buffer for generated metric.\n\tconfig   MetricConfig   // metric config provided by user.\n\tcapacity int            // max observed number of data points added to the metric.\n}\n\n// init fills k8s.replicaset.desired metric with initial data.\nfunc (m *metricK8sReplicasetDesired) init() {\n\tm.data.SetName(\"k8s.replicaset.desired\")\n\tm.data.SetDescription(\"Number of desired replicas\")\n\tm.data.SetUnit(\"{replicas}\")\n\tm.data.SetEmptyGauge()\n}\n\nfunc (m *metricK8sReplicasetDesired) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val int64) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\tdp := m.data.Gauge().DataPoints().AppendEmpty()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tdp.SetIntValue(val)\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricK8sReplicasetDesired) updateCapacity() {\n\tif m.data.Gauge().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Gauge().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricK8sReplicasetDesired) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricK8sReplicasetDesired(cfg MetricConfig) metricK8sReplicasetDesired {\n\tm := metricK8sReplicasetDesired{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\n// MetricsBuilder provides an interface for scrapers to report metrics while taking care of all the transformations\n// required to produce metric representation defined in metadata and user config.\ntype MetricsBuilder struct {\n\tconfig                         MetricsBuilderConfig // config of the metrics builder.\n\tstartTime                      pcommon.Timestamp    // start time that will be applied to all recorded data points.\n\tmetricsCapacity                int                  // maximum observed number of metrics per resource.\n\tmetricsBuffer                  pmetric.Metrics      // accumulates metrics data before emitting.\n\tbuildInfo                      component.BuildInfo  // contains version information.\n\tresourceAttributeIncludeFilter map[string]filter.Filter\n\tresourceAttributeExcludeFilter map[string]filter.Filter\n\tmetricK8sPodCPUTime            metricK8sPodCPUTime\n\tmetricK8sPodPhase              metricK8sPodPhase\n\tmetricK8sReplicasetDesired     metricK8sReplicasetDesired\n}\n\n// MetricBuilderOption applies changes to default metrics builder.\ntype MetricBuilderOption interface {\n\tapply(*MetricsBuilder)\n}\n\ntype metricBuilderOptionFunc func(mb *MetricsBuilder)\n\nfunc (mbof metricBuilderOptionFunc) apply(mb *MetricsBuilder) {\n\tmbof(mb)\n}\n\n// WithStartTime sets startTime on the metrics builder.\nfunc WithStartTime(startTime pcommon.Timestamp) MetricBuilderOption {\n\treturn metricBuilderOptionFunc(func(mb *MetricsBuilder) {\n\t\tmb.startTime = startTime\n\t})\n}\nfunc NewMetricsBuilder(mbc MetricsBuilderConfig, settings receiver.Settings, options ...MetricBuilderOption) *MetricsBuilder {\n\tmb := &MetricsBuilder{\n\t\tconfig:                         mbc,\n\t\tstartTime:                      pcommon.NewTimestampFromTime(time.Now()),\n\t\tmetricsBuffer:                  pmetric.NewMetrics(),\n\t\tbuildInfo:                      settings.BuildInfo,\n\t\tmetricK8sPodCPUTime:            newMetricK8sPodCPUTime(mbc.Metrics.K8sPodCPUTime),\n\t\tmetricK8sPodPhase:              newMetricK8sPodPhase(mbc.Metrics.K8sPodPhase),\n\t\tmetricK8sReplicasetDesired:     newMetricK8sReplicasetDesired(mbc.Metrics.K8sReplicasetDesired),\n\t\tresourceAttributeIncludeFilter: make(map[string]filter.Filter),\n\t\tresourceAttributeExcludeFilter: make(map[string]filter.Filter),\n\t}\n\tif mbc.ResourceAttributes.K8sNamespaceName.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"k8s.namespace.name\"] = filter.CreateFilter(mbc.ResourceAttributes.K8sNamespaceName.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.K8sNamespaceName.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"k8s.namespace.name\"] = filter.CreateFilter(mbc.ResourceAttributes.K8sNamespaceName.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.K8sPodName.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"k8s.pod.name\"] = filter.CreateFilter(mbc.ResourceAttributes.K8sPodName.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.K8sPodName.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"k8s.pod.name\"] = filter.CreateFilter(mbc.ResourceAttributes.K8sPodName.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.K8sPodUID.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"k8s.pod.uid\"] = filter.CreateFilter(mbc.ResourceAttributes.K8sPodUID.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.K8sPodUID.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"k8s.pod.uid\"] = filter.CreateFilter(mbc.ResourceAttributes.K8sPodUID.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.K8sReplicasetName.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"k8s.replicaset.name\"] = filter.CreateFilter(mbc.ResourceAttributes.K8sReplicasetName.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.K8sReplicasetName.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"k8s.replicaset.name\"] = filter.CreateFilter(mbc.ResourceAttributes.K8sReplicasetName.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.K8sReplicasetUID.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"k8s.replicaset.uid\"] = filter.CreateFilter(mbc.ResourceAttributes.K8sReplicasetUID.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.K8sReplicasetUID.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"k8s.replicaset.uid\"] = filter.CreateFilter(mbc.ResourceAttributes.K8sReplicasetUID.MetricsExclude)\n\t}\n\n\tfor _, op := range options {\n\t\top.apply(mb)\n\t}\n\treturn mb\n}\n\n// NewResourceBuilder returns a new resource builder that should be used to build a resource associated with for the emitted metrics.\nfunc (mb *MetricsBuilder) NewResourceBuilder() *ResourceBuilder {\n\treturn NewResourceBuilder(mb.config.ResourceAttributes)\n}\n\n// updateCapacity updates max length of metrics and resource attributes that will be used for the slice capacity.\nfunc (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n}\n\n// ResourceMetricsOption applies changes to provided resource metrics.\ntype ResourceMetricsOption interface {\n\tapply(pmetric.ResourceMetrics)\n}\n\ntype resourceMetricsOptionFunc func(pmetric.ResourceMetrics)\n\nfunc (rmof resourceMetricsOptionFunc) apply(rm pmetric.ResourceMetrics) {\n\trmof(rm)\n}\n\n// WithResource sets the provided resource on the emitted ResourceMetrics.\n// It's recommended to use ResourceBuilder to create the resource.\nfunc WithResource(res pcommon.Resource) ResourceMetricsOption {\n\treturn resourceMetricsOptionFunc(func(rm pmetric.ResourceMetrics) {\n\t\tres.CopyTo(rm.Resource())\n\t})\n}\n\nfunc withResourceMoved(res pcommon.Resource) ResourceMetricsOption {\n\treturn resourceMetricsOptionFunc(func(rm pmetric.ResourceMetrics) {\n\t\tres.MoveTo(rm.Resource())\n\t})\n}\n\n// WithStartTimeOverride overrides start time for all the resource metrics data points.\n// This option should be only used if different start time has to be set on metrics coming from different resources.\nfunc WithStartTimeOverride(start pcommon.Timestamp) ResourceMetricsOption {\n\treturn resourceMetricsOptionFunc(func(rm pmetric.ResourceMetrics) {\n\t\tvar dps pmetric.NumberDataPointSlice\n\t\tmetrics := rm.ScopeMetrics().At(0).Metrics()\n\t\tfor i := 0; i < metrics.Len(); i++ {\n\t\t\tswitch metrics.At(i).Type() {\n\t\t\tcase pmetric.MetricTypeGauge:\n\t\t\t\tdps = metrics.At(i).Gauge().DataPoints()\n\t\t\tcase pmetric.MetricTypeSum:\n\t\t\t\tdps = metrics.At(i).Sum().DataPoints()\n\t\t\t}\n\t\t\tfor j := 0; j < dps.Len(); j++ {\n\t\t\t\tdps.At(j).SetStartTimestamp(start)\n\t\t\t}\n\t\t}\n\t})\n}\n\n// ForK8sReplicaset returns a K8sReplicasetMetricsBuilder that restricts metric recording\n// to metrics belonging to the k8s.replicaset entity.\nfunc (mb *MetricsBuilder) ForK8sReplicaset(e *K8sReplicasetEntity) *K8sReplicasetMetricsBuilder {\n\treturn &K8sReplicasetMetricsBuilder{mb: mb, entity: e}\n}\n\n// ForK8sPod returns a K8sPodMetricsBuilder that restricts metric recording\n// to metrics belonging to the k8s.pod entity.\nfunc (mb *MetricsBuilder) ForK8sPod(e *K8sPodEntity) *K8sPodMetricsBuilder {\n\treturn &K8sPodMetricsBuilder{mb: mb, entity: e}\n}\n\n// EmitForResource saves all the generated metrics under a new resource and updates the internal state to be ready for\n// recording another set of data points as part of another resource. This function can be helpful when one scraper\n// needs to emit metrics from several resources. Otherwise calling this function is not required,\n// just `Emit` function can be called instead.\n// Resource attributes should be provided as ResourceMetricsOption arguments.\n//\n// Deprecated: Use the For<EntityType> methods to get entity-scoped builders and call Emit() on them instead.\nfunc (mb *MetricsBuilder) EmitForResource(options ...ResourceMetricsOption) {\n\trm := pmetric.NewResourceMetrics()\n\trm.SetSchemaUrl(conventions.SchemaURL)\n\tils := rm.ScopeMetrics().AppendEmpty()\n\tils.Scope().SetName(ScopeName)\n\tils.Scope().SetVersion(mb.buildInfo.Version)\n\tils.Metrics().EnsureCapacity(mb.metricsCapacity)\n\tmb.metricK8sPodCPUTime.emit(ils.Metrics())\n\tmb.metricK8sPodPhase.emit(ils.Metrics())\n\tmb.metricK8sReplicasetDesired.emit(ils.Metrics())\n\n\tfor _, op := range options {\n\t\top.apply(rm)\n\t}\n\tfor attr, filter := range mb.resourceAttributeIncludeFilter {\n\t\tif val, ok := rm.Resource().Attributes().Get(attr); ok && !filter.Matches(val.AsString()) {\n\t\t\treturn\n\t\t}\n\t}\n\tfor attr, filter := range mb.resourceAttributeExcludeFilter {\n\t\tif val, ok := rm.Resource().Attributes().Get(attr); ok && filter.Matches(val.AsString()) {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif ils.Metrics().Len() > 0 {\n\t\tmb.updateCapacity(rm)\n\t\trm.MoveTo(mb.metricsBuffer.ResourceMetrics().AppendEmpty())\n\t}\n}\n\n// Emit returns all the metrics accumulated by the metrics builder and updates the internal state to be ready for\n// recording another set of metrics. This function will be responsible for applying all the transformations required to\n// produce metric representation defined in metadata and user config, e.g. delta or cumulative.\nfunc (mb *MetricsBuilder) Emit(options ...ResourceMetricsOption) pmetric.Metrics {\n\tmb.EmitForResource(options...)\n\tmetrics := mb.metricsBuffer\n\tmb.metricsBuffer = pmetric.NewMetrics()\n\treturn metrics\n}\n\n// RecordK8sPodCPUTimeDataPoint adds a data point to k8s.pod.cpu_time metric.\n//\n// Deprecated: Use mb.ForK8sPod(entity).RecordK8sPodCPUTimeDataPoint(...) instead.\nfunc (mb *MetricsBuilder) RecordK8sPodCPUTimeDataPoint(ts pcommon.Timestamp, val float64) {\n\tmb.metricK8sPodCPUTime.recordDataPoint(mb.startTime, ts, val)\n}\n\n// RecordK8sPodPhaseDataPoint adds a data point to k8s.pod.phase metric.\n//\n// Deprecated: Use mb.ForK8sPod(entity).RecordK8sPodPhaseDataPoint(...) instead.\nfunc (mb *MetricsBuilder) RecordK8sPodPhaseDataPoint(ts pcommon.Timestamp, val int64, phaseAttributeValue AttributePhase) {\n\tmb.metricK8sPodPhase.recordDataPoint(mb.startTime, ts, val, phaseAttributeValue.String())\n}\n\n// RecordK8sReplicasetDesiredDataPoint adds a data point to k8s.replicaset.desired metric.\n//\n// Deprecated: Use mb.ForK8sReplicaset(entity).RecordK8sReplicasetDesiredDataPoint(...) instead.\nfunc (mb *MetricsBuilder) RecordK8sReplicasetDesiredDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricK8sReplicasetDesired.recordDataPoint(mb.startTime, ts, val)\n}\n\n// Reset resets metrics builder to its initial state. It should be used when external metrics source is restarted,\n// and metrics builder should update its startTime and reset it's internal state accordingly.\nfunc (mb *MetricsBuilder) Reset(options ...MetricBuilderOption) {\n\tmb.startTime = pcommon.NewTimestampFromTime(time.Now())\n\tfor _, op := range options {\n\t\top.apply(mb)\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleentityreceiver/internal/metadata/generated_metrics_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\ntype testDataSet int\n\nconst (\n\ttestDataSetDefault testDataSet = iota\n\ttestDataSetAll\n\ttestDataSetNone\n)\n\nfunc TestMetricsBuilder(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tmetricsSet  testDataSet\n\t\tresAttrsSet testDataSet\n\t\texpectEmpty bool\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t},\n\t\t{\n\t\t\tname:        \"all_set\",\n\t\t\tmetricsSet:  testDataSetAll,\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t},\n\t\t{\n\t\t\tname:        \"none_set\",\n\t\t\tmetricsSet:  testDataSetNone,\n\t\t\tresAttrsSet: testDataSetNone,\n\t\t\texpectEmpty: true,\n\t\t},\n\t\t{\n\t\t\tname:        \"filter_set_include\",\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t},\n\t\t{\n\t\t\tname:        \"filter_set_exclude\",\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t\texpectEmpty: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tstart := pcommon.Timestamp(1_000_000_000)\n\t\t\tts := pcommon.Timestamp(1_000_001_000)\n\t\t\tobservedZapCore, observedLogs := observer.New(zap.WarnLevel)\n\t\t\tsettings := receivertest.NewNopSettings(receivertest.NopType)\n\t\t\tsettings.Logger = zap.New(observedZapCore)\n\t\t\tmb := NewMetricsBuilder(loadMetricsBuilderConfig(t, tt.name), settings, WithStartTime(start))\n\n\t\t\texpectedWarnings := 0\n\t\t\tassert.Equal(t, expectedWarnings, observedLogs.Len())\n\n\t\t\tdefaultMetricsCount := 0\n\t\t\tallMetricsCount := 0\n\t\t\tebK8sReplicaset := mb.ForK8sReplicaset(NewK8sReplicasetEntity(\"k8s.replicaset.uid-val\"))\n\t\t\tebK8sPod := mb.ForK8sPod(NewK8sPodEntity(\"k8s.pod.uid-val\"))\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tebK8sPod.RecordK8sPodCPUTimeDataPoint(ts, 1)\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tebK8sPod.RecordK8sPodPhaseDataPoint(ts, 1, AttributePhasePending)\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tebK8sReplicaset.RecordK8sReplicasetDesiredDataPoint(ts, 1)\n\t\t\tebK8sReplicaset.Emit()\n\t\t\tebK8sPod.Emit()\n\n\t\t\trb := mb.NewResourceBuilder()\n\t\t\trb.SetK8sNamespaceName(\"k8s.namespace.name-val\")\n\t\t\trb.SetK8sPodName(\"k8s.pod.name-val\")\n\t\t\trb.SetK8sPodUID(\"k8s.pod.uid-val\")\n\t\t\trb.SetK8sReplicasetName(\"k8s.replicaset.name-val\")\n\t\t\trb.SetK8sReplicasetUID(\"k8s.replicaset.uid-val\")\n\t\t\tres := rb.Emit()\n\t\t\tmetrics := mb.Emit(WithResource(res))\n\n\t\t\tif tt.expectEmpty {\n\t\t\t\tassert.Equal(t, 0, metrics.ResourceMetrics().Len())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar allMetricsList []pmetric.Metric\n\t\t\ttotalMetricsCount := 0\n\t\t\tfor ri := 0; ri < metrics.ResourceMetrics().Len(); ri++ {\n\t\t\t\trm := metrics.ResourceMetrics().At(ri)\n\t\t\t\tassert.Equal(t, 1, rm.ScopeMetrics().Len())\n\t\t\t\tms := rm.ScopeMetrics().At(0).Metrics()\n\t\t\t\ttotalMetricsCount += ms.Len()\n\t\t\t\tfor mi := 0; mi < ms.Len(); mi++ {\n\t\t\t\t\tallMetricsList = append(allMetricsList, ms.At(mi))\n\t\t\t\t}\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetDefault {\n\t\t\t\tassert.Equal(t, defaultMetricsCount, totalMetricsCount)\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetAll {\n\t\t\t\tassert.Equal(t, allMetricsCount, totalMetricsCount)\n\t\t\t}\n\t\t\tvalidatedMetrics := make(map[string]bool)\n\t\t\tfor _, mi := range allMetricsList {\n\t\t\t\tswitch mi.Name() {\n\t\t\t\tcase \"k8s.pod.cpu_time\":\n\t\t\t\t\tassert.False(t, validatedMetrics[\"k8s.pod.cpu_time\"], \"Found a duplicate in the metrics slice: k8s.pod.cpu_time\")\n\t\t\t\t\tvalidatedMetrics[\"k8s.pod.cpu_time\"] = true\n\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\tassert.Equal(t, \"CPU time consumed by the pod\", mi.Description())\n\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\tassert.True(t, mi.Sum().IsMonotonic())\n\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, mi.Sum().AggregationTemporality())\n\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\tcase \"k8s.pod.phase\":\n\t\t\t\t\tassert.False(t, validatedMetrics[\"k8s.pod.phase\"], \"Found a duplicate in the metrics slice: k8s.pod.phase\")\n\t\t\t\t\tvalidatedMetrics[\"k8s.pod.phase\"] = true\n\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\tassert.Equal(t, \"Current phase of the pod\", mi.Description())\n\t\t\t\t\tassert.Equal(t, \"1\", mi.Unit())\n\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t\tphaseAttrVal, ok := dp.Attributes().Get(\"phase\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, \"Pending\", phaseAttrVal.Str())\n\t\t\t\tcase \"k8s.replicaset.desired\":\n\t\t\t\t\tassert.False(t, validatedMetrics[\"k8s.replicaset.desired\"], \"Found a duplicate in the metrics slice: k8s.replicaset.desired\")\n\t\t\t\t\tvalidatedMetrics[\"k8s.replicaset.desired\"] = true\n\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\tassert.Equal(t, \"Number of desired replicas\", mi.Description())\n\t\t\t\t\tassert.Equal(t, \"{replicas}\", mi.Unit())\n\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleentityreceiver/internal/metadata/generated_resource.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ResourceBuilder is a helper struct to build resources predefined in metadata.yaml.\n// The ResourceBuilder is not thread-safe and must not to be used in multiple goroutines.\ntype ResourceBuilder struct {\n\tconfig ResourceAttributesConfig\n\tres    pcommon.Resource\n}\n\n// NewResourceBuilder creates a new ResourceBuilder. This method should be called on the start of the application.\nfunc NewResourceBuilder(rac ResourceAttributesConfig) *ResourceBuilder {\n\treturn &ResourceBuilder{\n\t\tconfig: rac,\n\t\tres:    pcommon.NewResource(),\n\t}\n}\n\n// SetK8sNamespaceName sets provided value as \"k8s.namespace.name\" attribute.\nfunc (rb *ResourceBuilder) SetK8sNamespaceName(val string) {\n\tif rb.config.K8sNamespaceName.Enabled {\n\t\trb.res.Attributes().PutStr(\"k8s.namespace.name\", val)\n\t}\n}\n\n// SetK8sPodName sets provided value as \"k8s.pod.name\" attribute.\nfunc (rb *ResourceBuilder) SetK8sPodName(val string) {\n\tif rb.config.K8sPodName.Enabled {\n\t\trb.res.Attributes().PutStr(\"k8s.pod.name\", val)\n\t}\n}\n\n// SetK8sPodUID sets provided value as \"k8s.pod.uid\" attribute.\nfunc (rb *ResourceBuilder) SetK8sPodUID(val string) {\n\tif rb.config.K8sPodUID.Enabled {\n\t\trb.res.Attributes().PutStr(\"k8s.pod.uid\", val)\n\t}\n}\n\n// SetK8sReplicasetName sets provided value as \"k8s.replicaset.name\" attribute.\nfunc (rb *ResourceBuilder) SetK8sReplicasetName(val string) {\n\tif rb.config.K8sReplicasetName.Enabled {\n\t\trb.res.Attributes().PutStr(\"k8s.replicaset.name\", val)\n\t}\n}\n\n// SetK8sReplicasetUID sets provided value as \"k8s.replicaset.uid\" attribute.\nfunc (rb *ResourceBuilder) SetK8sReplicasetUID(val string) {\n\tif rb.config.K8sReplicasetUID.Enabled {\n\t\trb.res.Attributes().PutStr(\"k8s.replicaset.uid\", val)\n\t}\n}\n\n// Emit returns the built resource and resets the internal builder state.\nfunc (rb *ResourceBuilder) Emit() pcommon.Resource {\n\tr := rb.res\n\trb.res = pcommon.NewResource()\n\treturn r\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleentityreceiver/internal/metadata/generated_resource_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestResourceBuilder(t *testing.T) {\n\tfor _, tt := range []string{\"default\", \"all_set\", \"none_set\"} {\n\t\tt.Run(tt, func(t *testing.T) {\n\t\t\tcfg := loadResourceAttributesConfig(t, tt)\n\t\t\trb := NewResourceBuilder(cfg)\n\t\t\trb.SetK8sNamespaceName(\"k8s.namespace.name-val\")\n\t\t\trb.SetK8sPodName(\"k8s.pod.name-val\")\n\t\t\trb.SetK8sPodUID(\"k8s.pod.uid-val\")\n\t\t\trb.SetK8sReplicasetName(\"k8s.replicaset.name-val\")\n\t\t\trb.SetK8sReplicasetUID(\"k8s.replicaset.uid-val\")\n\n\t\t\tres := rb.Emit()\n\t\t\tassert.Equal(t, 0, rb.Emit().Attributes().Len()) // Second call should return empty Resource\n\n\t\t\tswitch tt {\n\t\t\tcase \"default\":\n\t\t\t\tassert.Equal(t, 5, res.Attributes().Len())\n\t\t\tcase \"all_set\":\n\t\t\t\tassert.Equal(t, 5, res.Attributes().Len())\n\t\t\tcase \"none_set\":\n\t\t\t\tassert.Equal(t, 0, res.Attributes().Len())\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tassert.Failf(t, \"unexpected test case: %s\", tt)\n\t\t\t}\n\t\t\tk8sNamespaceNameAttrVal, ok := res.Attributes().Get(\"k8s.namespace.name\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"k8s.namespace.name-val\", k8sNamespaceNameAttrVal.Str())\n\t\t\t}\n\t\t\tk8sPodNameAttrVal, ok := res.Attributes().Get(\"k8s.pod.name\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"k8s.pod.name-val\", k8sPodNameAttrVal.Str())\n\t\t\t}\n\t\t\tk8sPodUIDAttrVal, ok := res.Attributes().Get(\"k8s.pod.uid\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"k8s.pod.uid-val\", k8sPodUIDAttrVal.Str())\n\t\t\t}\n\t\t\tk8sReplicasetNameAttrVal, ok := res.Attributes().Get(\"k8s.replicaset.name\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"k8s.replicaset.name-val\", k8sReplicasetNameAttrVal.Str())\n\t\t\t}\n\t\t\tk8sReplicasetUIDAttrVal, ok := res.Attributes().Get(\"k8s.replicaset.uid\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"k8s.replicaset.uid-val\", k8sReplicasetUIDAttrVal.Str())\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleentityreceiver/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"sampleentity\")\n\tScopeName = \"go.opentelemetry.io/collector/internal/receiver/sampleentityreceiver\"\n)\n\nconst (\n\tMetricsStability = component.StabilityLevelDevelopment\n)\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleentityreceiver/internal/metadata/testdata/config.yaml",
    "content": "default:\nall_set:\n  metrics:\n    k8s.pod.cpu_time:\n      enabled: true\n    k8s.pod.phase:\n      enabled: true\n    k8s.replicaset.desired:\n      enabled: true\n  resource_attributes:\n    k8s.namespace.name:\n      enabled: true\n    k8s.pod.name:\n      enabled: true\n    k8s.pod.uid:\n      enabled: true\n    k8s.replicaset.name:\n      enabled: true\n    k8s.replicaset.uid:\n      enabled: true\nnone_set:\n  metrics:\n    k8s.pod.cpu_time:\n      enabled: false\n    k8s.pod.phase:\n      enabled: false\n    k8s.replicaset.desired:\n      enabled: false\n  resource_attributes:\n    k8s.namespace.name:\n      enabled: false\n    k8s.pod.name:\n      enabled: false\n    k8s.pod.uid:\n      enabled: false\n    k8s.replicaset.name:\n      enabled: false\n    k8s.replicaset.uid:\n      enabled: false\nfilter_set_include:\n  resource_attributes:\n    k8s.namespace.name:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    k8s.pod.name:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    k8s.pod.uid:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    k8s.replicaset.name:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    k8s.replicaset.uid:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\nfilter_set_exclude:\n  resource_attributes:\n    k8s.namespace.name:\n      enabled: true\n      metrics_exclude:\n        - strict: \"k8s.namespace.name-val\"\n    k8s.pod.name:\n      enabled: true\n      metrics_exclude:\n        - strict: \"k8s.pod.name-val\"\n    k8s.pod.uid:\n      enabled: true\n      metrics_exclude:\n        - strict: \"k8s.pod.uid-val\"\n    k8s.replicaset.name:\n      enabled: true\n      metrics_exclude:\n        - strict: \"k8s.replicaset.name-val\"\n    k8s.replicaset.uid:\n      enabled: true\n      metrics_exclude:\n        - strict: \"k8s.replicaset.uid-val\"\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleentityreceiver/metadata.yaml",
    "content": "# Sample metadata file with entities for testing entity-based builder API\n\ntype: sampleentity\ndisplay_name: Sample Entity Receiver\ndescription: This receiver demonstrates entity-based metrics builder API.\nscope_name: go.opentelemetry.io/collector/internal/receiver/sampleentityreceiver\nsem_conv_version: 1.38.0\n\nstatus:\n  class: receiver\n  stability:\n    development: [metrics]\n  codeowners:\n    active: [dmitryax]\n\nresource_attributes:\n  k8s.namespace.name:\n    description: The name of the Kubernetes Namespace\n    type: string\n    enabled: true\n\n  k8s.pod.name:\n    description: The name of the Kubernetes Pod\n    type: string\n    enabled: true\n\n  k8s.pod.uid:\n    description: The UID of the Kubernetes Pod\n    type: string\n    enabled: true\n\n  k8s.replicaset.name:\n    description: The name of the Kubernetes ReplicaSet\n    type: string\n    enabled: true\n\n  k8s.replicaset.uid:\n    description: The UID of the Kubernetes ReplicaSet\n    type: string\n    enabled: true\n\nentities:\n  - type: k8s.replicaset\n    brief: A Kubernetes ReplicaSet\n    stability: development\n    identity:\n      - ref: k8s.replicaset.uid\n    description:\n      - ref: k8s.replicaset.name\n\n  - type: k8s.pod\n    brief: A Kubernetes Pod\n    stability: development\n    identity:\n      - ref: k8s.pod.uid\n    description:\n      - ref: k8s.pod.name\n    extra_attributes:\n      - ref: k8s.namespace.name\n    relationships:\n      - type: controlled_by\n        target: k8s.replicaset\n\nattributes:\n  phase:\n    description: The phase of the pod (Pending, Running, Succeeded, Failed, Unknown)\n    type: string\n    enum: [Pending, Running, Succeeded, Failed, Unknown]\n\nmetrics:\n  k8s.pod.cpu_time:\n    enabled: true\n    description: CPU time consumed by the pod\n    unit: s\n    sum:\n      value_type: double\n      monotonic: true\n      aggregation_temporality: cumulative\n    attributes: []\n    entity: k8s.pod\n    stability: development\n\n  k8s.pod.phase:\n    enabled: true\n    description: Current phase of the pod\n    unit: \"1\"\n    gauge:\n      value_type: int\n    attributes: [phase]\n    entity: k8s.pod\n    stability: development\n\n  k8s.replicaset.desired:\n    enabled: true\n    description: Number of desired replicas\n    unit: \"{replicas}\"\n    gauge:\n      value_type: int\n    attributes: []\n    entity: k8s.replicaset\n    stability: development\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/README.md",
    "content": "<!-- status autogenerated section -->\n# Sample Factory Receiver\n\nThis receiver is used for testing purposes to check the output of mdatagen.\n\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [deprecated]: profiles   |\n|               | [development]: logs   |\n|               | [beta]: traces   |\n|               | [stable]: metrics   |\n| Deprecation of profiles | [Date]: 2025-02-05   |\n|                      | [Migration Note]: no migration needed   |\n| Unsupported Platforms | freebsd, illumos |\n| Distributions | [] |\n| Warnings      | [Any additional information that should be brought to the consumer's attention](#warnings) |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Areceiver%2Fsamplefactory%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Areceiver%2Fsamplefactory) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Areceiver%2Fsamplefactory%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Areceiver%2Fsamplefactory) |\n| [Code Owners](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/CONTRIBUTING.md#becoming-a-code-owner)    | [@dmitryax](https://www.github.com/dmitryax) |\n\n[deprecated]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#deprecated\n[development]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#development\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[stable]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stable\n[Date]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#deprecation-information\n[Migration Note]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#deprecation-information\n<!-- end autogenerated section -->\n\n## Warnings\n\nThis is where warnings are described.\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Generate a test metrics builder from a sample metrics set covering all configuration options.\n//go:generate mdatagen metadata.yaml\n\npackage samplefactoryreceiver // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplefactoryreceiver\"\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# sample\n\n## Default Metrics\n\nThe following metrics are emitted by default. Each of them can be disabled by applying the following configuration:\n\n```yaml\nmetrics:\n  <metric_name>:\n    enabled: false\n```\n\n### default.metric\n\nMonotonic cumulative sum int metric enabled by default.\n\nThe metric will be become optional soon.\n\n| Unit | Metric Type | Value Type | Aggregation Temporality | Monotonic |\n| ---- | ----------- | ---------- | ----------------------- | --------- |\n| s | Sum | Int | Cumulative | true |\n\n#### Attributes\n\n| Name | Description | Values | Optional |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | false |\n| state | Integer attribute with overridden name. | Any Int | false |\n| enum_attr | Attribute with a known set of string values. | Str: ``red``, ``green``, ``blue`` | false |\n| slice_attr | Attribute with a slice value. | Any Slice | false |\n| map_attr | Attribute with a map value. | Any Map | false |\n| optional_int_attr | An optional attribute with an integer value | Any Int | true |\n| optional_string_attr | An optional attribute with any string value | Any Str | true |\n\n### default.metric.to_be_removed\n\n[DEPRECATED] Non-monotonic delta sum double metric enabled by default.\n\nThe metric will be removed soon.\n\n| Unit | Metric Type | Value Type | Aggregation Temporality | Monotonic |\n| ---- | ----------- | ---------- | ----------------------- | --------- |\n| s | Sum | Double | Delta | false |\n\n### metric.input_type\n\nMonotonic cumulative sum int metric with string input_type enabled by default.\n\n| Unit | Metric Type | Value Type | Aggregation Temporality | Monotonic |\n| ---- | ----------- | ---------- | ----------------------- | --------- |\n| s | Sum | Int | Cumulative | true |\n\n#### Attributes\n\n| Name | Description | Values | Optional |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | false |\n| state | Integer attribute with overridden name. | Any Int | false |\n| enum_attr | Attribute with a known set of string values. | Str: ``red``, ``green``, ``blue`` | false |\n| slice_attr | Attribute with a slice value. | Any Slice | false |\n| map_attr | Attribute with a map value. | Any Map | false |\n\n## Optional Metrics\n\nThe following metrics are not emitted by default. Each of them can be enabled by applying the following configuration:\n\n```yaml\nmetrics:\n  <metric_name>:\n    enabled: true\n```\n\n### optional.metric\n\n[DEPRECATED] Gauge double metric disabled by default.\n\n| Unit | Metric Type | Value Type |\n| ---- | ----------- | ---------- |\n| 1 | Gauge | Double |\n\n#### Attributes\n\n| Name | Description | Values | Optional |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | false |\n| boolean_attr | Attribute with a boolean value. | Any Bool | false |\n| boolean_attr2 | Another attribute with a boolean value. | Any Bool | false |\n| optional_string_attr | An optional attribute with any string value | Any Str | true |\n\n### optional.metric.empty_unit\n\n[DEPRECATED] Gauge double metric disabled by default.\n\n| Unit | Metric Type | Value Type |\n| ---- | ----------- | ---------- |\n|  | Gauge | Double |\n\n#### Attributes\n\n| Name | Description | Values | Optional |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | false |\n| boolean_attr | Attribute with a boolean value. | Any Bool | false |\n\n## Default Events\n\nThe following events are emitted by default. Each of them can be disabled by applying the following configuration:\n\n```yaml\nevents:\n  <event_name>:\n    enabled: false\n```\n\n### default.event\n\nExample event enabled by default.\n\n#### Attributes\n\n| Name | Description | Values |\n| ---- | ----------- | ------ |\n| string_attr | Attribute with any string value. | Any Str |\n| state | Integer attribute with overridden name. | Any Int |\n| enum_attr | Attribute with a known set of string values. | Str: ``red``, ``green``, ``blue`` |\n| slice_attr | Attribute with a slice value. | Any Slice |\n| map_attr | Attribute with a map value. | Any Map |\n| optional_int_attr | An optional attribute with an integer value | Any Int |\n| optional_string_attr | An optional attribute with any string value | Any Str |\n\n### default.event.to_be_removed\n\n[DEPRECATED] Example to-be-removed event enabled by default.\n\nThe event will be removed soon.\n\n#### Attributes\n\n| Name | Description | Values |\n| ---- | ----------- | ------ |\n| string_attr | Attribute with any string value. | Any Str |\n| state | Integer attribute with overridden name. | Any Int |\n| enum_attr | Attribute with a known set of string values. | Str: ``red``, ``green``, ``blue`` |\n| slice_attr | Attribute with a slice value. | Any Slice |\n| map_attr | Attribute with a map value. | Any Map |\n\n## Optional Events\n\nThe following events are not emitted by default. Each of them can be enabled by applying the following configuration:\n\n```yaml\nevents:\n  <event_name>:\n    enabled: true\n```\n\n### default.event.to_be_renamed\n\n[DEPRECATED] Example event disabled by default.\n\nThe event will be renamed soon.\n\n#### Attributes\n\n| Name | Description | Values |\n| ---- | ----------- | ------ |\n| string_attr | Attribute with any string value. | Any Str |\n| boolean_attr | Attribute with a boolean value. | Any Bool |\n| boolean_attr2 | Another attribute with a boolean value. | Any Bool |\n| optional_string_attr | An optional attribute with any string value | Any Str |\n\n## Resource Attributes\n\n| Name | Description | Values | Enabled |\n| ---- | ----------- | ------ | ------- |\n| map.resource.attr | Resource attribute with a map value. | Any Map | true |\n| optional.resource.attr | Explicitly disabled ResourceAttribute. | Any Str | false |\n| slice.resource.attr | Resource attribute with a slice value. | Any Slice | true |\n| string.enum.resource.attr | Resource attribute with a known set of string values. | Str: ``one``, ``two`` | true |\n| string.resource.attr | Resource attribute with any string value. | Any Str | true |\n| string.resource.attr_disable_warning | Resource attribute with any string value. | Any Str | true |\n| string.resource.attr_remove_warning | Resource attribute with any string value. | Any Str | false |\n| string.resource.attr_to_be_removed | Resource attribute with any string value. | Any Str | true |\n\n## Internal Telemetry\n\nThe following telemetry is emitted by this component.\n\n### otelcol_batch_size_trigger_send\n\nNumber of times the batch was sent due to a size trigger [deprecated since v0.110.0]\n\n| Unit | Metric Type | Value Type | Monotonic |\n| ---- | ----------- | ---------- | --------- |\n| {times} | Sum | Int | true |\n\n### otelcol_process_runtime_total_alloc_bytes\n\nCumulative bytes allocated for heap objects (see 'go doc runtime.MemStats.TotalAlloc')\n\n| Unit | Metric Type | Value Type | Monotonic |\n| ---- | ----------- | ---------- | --------- |\n| By | Sum | Int | true |\n\n### otelcol_queue_capacity\n\nQueue capacity - sync gauge example.\n\n| Unit | Metric Type | Value Type |\n| ---- | ----------- | ---------- |\n| {items} | Gauge | Int |\n\n### otelcol_queue_length\n\nThis metric is optional and therefore not initialized in NewTelemetryBuilder. [alpha]\n\nFor example this metric only exists if feature A is enabled.\n\n| Unit | Metric Type | Value Type |\n| ---- | ----------- | ---------- |\n| {items} | Gauge | Int |\n\n### otelcol_request_duration\n\nDuration of request [alpha]\n\n| Unit | Metric Type | Value Type |\n| ---- | ----------- | ---------- |\n| s | Histogram | Double |\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage samplefactoryreceiver // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplefactoryreceiver\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/otel/metric\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplefactoryreceiver/internal/metadata\"\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n\t\"go.opentelemetry.io/collector/service/hostcapabilities\"\n)\n\n// NewFactory returns a receiver.Factory for sample receiver.\nfunc NewFactory() xreceiver.Factory {\n\treturn xreceiver.NewFactory(\n\t\tmetadata.Type,\n\t\tfunc() component.Config { return &struct{}{} },\n\t\txreceiver.WithTraces(createTraces, metadata.TracesStability),\n\t\txreceiver.WithMetrics(createMetrics, metadata.MetricsStability),\n\t\txreceiver.WithLogs(createLogs, metadata.LogsStability),\n\t\txreceiver.WithProfiles(createProfiles, metadata.ProfilesStability),\n\t)\n}\n\nfunc createTraces(context.Context, receiver.Settings, component.Config, consumer.Traces) (receiver.Traces, error) {\n\treturn nopInstance, nil\n}\n\nfunc createMetrics(ctx context.Context, set receiver.Settings, _ component.Config, _ consumer.Metrics) (receiver.Metrics, error) {\n\ttelemetryBuilder, err := metadata.NewTelemetryBuilder(set.TelemetrySettings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = telemetryBuilder.RegisterProcessRuntimeTotalAllocBytesCallback(func(_ context.Context, observer metric.Int64Observer) error {\n\t\tobserver.Observe(2)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttelemetryBuilder.BatchSizeTriggerSend.Add(ctx, 1)\n\treturn nopReceiver{telemetryBuilder: telemetryBuilder}, nil\n}\n\nfunc createLogs(context.Context, receiver.Settings, component.Config, consumer.Logs) (receiver.Logs, error) {\n\treturn nopInstance, nil\n}\n\nfunc createProfiles(context.Context, receiver.Settings, component.Config, xconsumer.Profiles) (xreceiver.Profiles, error) {\n\treturn nopInstance, nil\n}\n\nvar nopInstance = &nopReceiver{}\n\ntype nopReceiver struct {\n\tcomponent.StartFunc\n\ttelemetryBuilder *metadata.TelemetryBuilder\n}\n\nfunc (r nopReceiver) Start(_ context.Context, host component.Host) error {\n\tif _, ok := host.(hostcapabilities.ComponentFactory); !ok {\n\t\treturn errors.New(\"host does not implement hostcapabilities.ComponentFactory\")\n\t}\n\n\treturn nil\n}\n\n// Shutdown shuts down the component.\nfunc (r nopReceiver) Shutdown(context.Context) error {\n\tif r.telemetryBuilder != nil {\n\t\tr.telemetryBuilder.Shutdown()\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n//go:build !freebsd && !illumos\n\npackage samplefactoryreceiver\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n)\n\nvar typ = component.MustNewType(\"sample\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct {\n\t\tcreateFn func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error)\n\t\tname     string\n\t}{\n\n\t\t{\n\t\t\tname: \"logs\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateLogs(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"traces\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateTraces(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"profiles\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.(xreceiver.Factory).CreateProfiles(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name+\"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\tt.Run(tt.name+\"-lifecycle\", func(t *testing.T) {\n\t\t\tfirstRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := newMdatagenNopHost()\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, firstRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, firstRcvr.Shutdown(context.Background()))\n\t\t\tsecondRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, secondRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, secondRcvr.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage samplefactoryreceiver\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/internal/metadata/generated_config.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/filter\"\n)\n\n// MetricConfig provides common config for a particular metric.\ntype MetricConfig struct {\n\tEnabled bool `mapstructure:\"enabled\"`\n\n\tenabledSetByUser bool\n}\n\nfunc (ms *MetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\n// MetricsConfig provides config for sample metrics.\ntype MetricsConfig struct {\n\tDefaultMetric            MetricConfig `mapstructure:\"default.metric\"`\n\tDefaultMetricToBeRemoved MetricConfig `mapstructure:\"default.metric.to_be_removed\"`\n\tMetricInputType          MetricConfig `mapstructure:\"metric.input_type\"`\n\tOptionalMetric           MetricConfig `mapstructure:\"optional.metric\"`\n\tOptionalMetricEmptyUnit  MetricConfig `mapstructure:\"optional.metric.empty_unit\"`\n}\n\nfunc DefaultMetricsConfig() MetricsConfig {\n\treturn MetricsConfig{\n\t\tDefaultMetric: MetricConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tDefaultMetricToBeRemoved: MetricConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tMetricInputType: MetricConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tOptionalMetric: MetricConfig{\n\t\t\tEnabled: false,\n\t\t},\n\t\tOptionalMetricEmptyUnit: MetricConfig{\n\t\t\tEnabled: false,\n\t\t},\n\t}\n}\n\n// EventConfig provides common config for a particular event.\ntype EventConfig struct {\n\tEnabled bool `mapstructure:\"enabled\"`\n\n\tenabledSetByUser bool\n}\n\nfunc (ec *EventConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\terr := parser.Unmarshal(ec)\n\tif err != nil {\n\t\treturn err\n\t}\n\tec.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\n// EventsConfig provides config for sample events.\ntype EventsConfig struct {\n\tDefaultEvent            EventConfig `mapstructure:\"default.event\"`\n\tDefaultEventToBeRemoved EventConfig `mapstructure:\"default.event.to_be_removed\"`\n\tDefaultEventToBeRenamed EventConfig `mapstructure:\"default.event.to_be_renamed\"`\n}\n\nfunc DefaultEventsConfig() EventsConfig {\n\treturn EventsConfig{\n\t\tDefaultEvent: EventConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tDefaultEventToBeRemoved: EventConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tDefaultEventToBeRenamed: EventConfig{\n\t\t\tEnabled: false,\n\t\t},\n\t}\n}\n\n// ResourceAttributeConfig provides common config for a particular resource attribute.\ntype ResourceAttributeConfig struct {\n\tEnabled bool `mapstructure:\"enabled\"`\n\t// Experimental: MetricsInclude defines a list of filters for attribute values.\n\t// If the list is not empty, only metrics with matching resource attribute values will be emitted.\n\tMetricsInclude []filter.Config `mapstructure:\"metrics_include\"`\n\t// Experimental: MetricsExclude defines a list of filters for attribute values.\n\t// If the list is not empty, metrics with matching resource attribute values will not be emitted.\n\t// MetricsInclude has higher priority than MetricsExclude.\n\tMetricsExclude []filter.Config `mapstructure:\"metrics_exclude\"`\n\t// Experimental: EventsInclude defines a list of filters for attribute values.\n\t// If the list is not empty, only events with matching resource attribute values will be emitted.\n\tEventsInclude []filter.Config `mapstructure:\"events_include\"`\n\t// Experimental: EventsExclude defines a list of filters for attribute values.\n\t// If the list is not empty, events with matching resource attribute values will not be emitted.\n\t// EventsInclude has higher priority than EventsExclude.\n\tEventsExclude []filter.Config `mapstructure:\"events_exclude\"`\n\n\tenabledSetByUser bool\n}\n\nfunc (rac *ResourceAttributeConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\terr := parser.Unmarshal(rac)\n\tif err != nil {\n\t\treturn err\n\t}\n\trac.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\n// ResourceAttributesConfig provides config for sample resource attributes.\ntype ResourceAttributesConfig struct {\n\tMapResourceAttr                  ResourceAttributeConfig `mapstructure:\"map.resource.attr\"`\n\tOptionalResourceAttr             ResourceAttributeConfig `mapstructure:\"optional.resource.attr\"`\n\tSliceResourceAttr                ResourceAttributeConfig `mapstructure:\"slice.resource.attr\"`\n\tStringEnumResourceAttr           ResourceAttributeConfig `mapstructure:\"string.enum.resource.attr\"`\n\tStringResourceAttr               ResourceAttributeConfig `mapstructure:\"string.resource.attr\"`\n\tStringResourceAttrDisableWarning ResourceAttributeConfig `mapstructure:\"string.resource.attr_disable_warning\"`\n\tStringResourceAttrRemoveWarning  ResourceAttributeConfig `mapstructure:\"string.resource.attr_remove_warning\"`\n\tStringResourceAttrToBeRemoved    ResourceAttributeConfig `mapstructure:\"string.resource.attr_to_be_removed\"`\n}\n\nfunc DefaultResourceAttributesConfig() ResourceAttributesConfig {\n\treturn ResourceAttributesConfig{\n\t\tMapResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tOptionalResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: false,\n\t\t},\n\t\tSliceResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringEnumResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringResourceAttrRemoveWarning: ResourceAttributeConfig{\n\t\t\tEnabled: false,\n\t\t},\n\t\tStringResourceAttrToBeRemoved: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t}\n}\n\n// MetricsBuilderConfig is a configuration for sample metrics builder.\ntype MetricsBuilderConfig struct {\n\tMetrics            MetricsConfig            `mapstructure:\"metrics\"`\n\tResourceAttributes ResourceAttributesConfig `mapstructure:\"resource_attributes\"`\n}\n\nfunc DefaultMetricsBuilderConfig() MetricsBuilderConfig {\n\treturn MetricsBuilderConfig{\n\t\tMetrics:            DefaultMetricsConfig(),\n\t\tResourceAttributes: DefaultResourceAttributesConfig(),\n\t}\n}\n\n// LogsBuilderConfig is a configuration for sample logs builder.\ntype LogsBuilderConfig struct {\n\tEvents             EventsConfig             `mapstructure:\"events\"`\n\tResourceAttributes ResourceAttributesConfig `mapstructure:\"resource_attributes\"`\n}\n\nfunc DefaultLogsBuilderConfig() LogsBuilderConfig {\n\treturn LogsBuilderConfig{\n\t\tEvents:             DefaultEventsConfig(),\n\t\tResourceAttributes: DefaultResourceAttributesConfig(),\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/internal/metadata/generated_config_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n\t\"github.com/google/go-cmp/cmp/cmpopts\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n)\n\nfunc TestMetricsBuilderConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant MetricsBuilderConfig\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\twant: DefaultMetricsBuilderConfig(),\n\t\t},\n\t\t{\n\t\t\tname: \"all_set\",\n\t\t\twant: MetricsBuilderConfig{\n\t\t\t\tMetrics: MetricsConfig{\n\t\t\t\t\tDefaultMetric:            MetricConfig{Enabled: true},\n\t\t\t\t\tDefaultMetricToBeRemoved: MetricConfig{Enabled: true},\n\t\t\t\t\tMetricInputType:          MetricConfig{Enabled: true},\n\t\t\t\t\tOptionalMetric:           MetricConfig{Enabled: true},\n\t\t\t\t\tOptionalMetricEmptyUnit:  MetricConfig{Enabled: true},\n\t\t\t\t},\n\t\t\t\tResourceAttributes: ResourceAttributesConfig{\n\t\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: true},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"none_set\",\n\t\t\twant: MetricsBuilderConfig{\n\t\t\t\tMetrics: MetricsConfig{\n\t\t\t\t\tDefaultMetric:            MetricConfig{Enabled: false},\n\t\t\t\t\tDefaultMetricToBeRemoved: MetricConfig{Enabled: false},\n\t\t\t\t\tMetricInputType:          MetricConfig{Enabled: false},\n\t\t\t\t\tOptionalMetric:           MetricConfig{Enabled: false},\n\t\t\t\t\tOptionalMetricEmptyUnit:  MetricConfig{Enabled: false},\n\t\t\t\t},\n\t\t\t\tResourceAttributes: ResourceAttributesConfig{\n\t\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: false},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := loadMetricsBuilderConfig(t, tt.name)\n\t\t\tdiff := cmp.Diff(tt.want, cfg, cmpopts.IgnoreUnexported(MetricConfig{}, ResourceAttributeConfig{}))\n\t\t\trequire.Emptyf(t, diff, \"Config mismatch (-expected +actual):\\n%s\", diff)\n\t\t})\n\t}\n}\n\nfunc loadMetricsBuilderConfig(t *testing.T, name string) MetricsBuilderConfig {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tsub, err := cm.Sub(name)\n\trequire.NoError(t, err)\n\tcfg := DefaultMetricsBuilderConfig()\n\trequire.NoError(t, sub.Unmarshal(&cfg, confmap.WithIgnoreUnused()))\n\treturn cfg\n}\n\nfunc loadLogsBuilderConfig(t *testing.T, name string) LogsBuilderConfig {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tsub, err := cm.Sub(name)\n\trequire.NoError(t, err)\n\tcfg := DefaultLogsBuilderConfig()\n\trequire.NoError(t, sub.Unmarshal(&cfg, confmap.WithIgnoreUnused()))\n\treturn cfg\n}\n\nfunc TestResourceAttributesConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant ResourceAttributesConfig\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\twant: DefaultResourceAttributesConfig(),\n\t\t},\n\t\t{\n\t\t\tname: \"all_set\",\n\t\t\twant: ResourceAttributesConfig{\n\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: true},\n\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: true},\n\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: true},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"none_set\",\n\t\t\twant: ResourceAttributesConfig{\n\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: false},\n\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: false},\n\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: false},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := loadResourceAttributesConfig(t, tt.name)\n\t\t\tdiff := cmp.Diff(tt.want, cfg, cmpopts.IgnoreUnexported(ResourceAttributeConfig{}))\n\t\t\trequire.Emptyf(t, diff, \"Config mismatch (-expected +actual):\\n%s\", diff)\n\t\t})\n\t}\n}\n\nfunc loadResourceAttributesConfig(t *testing.T, name string) ResourceAttributesConfig {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tsub, err := cm.Sub(name)\n\trequire.NoError(t, err)\n\tsub, err = sub.Sub(\"resource_attributes\")\n\trequire.NoError(t, err)\n\tcfg := DefaultResourceAttributesConfig()\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\treturn cfg\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/internal/metadata/generated_logs.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\tconventions \"go.opentelemetry.io/otel/semconv/v1.9.0\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/receiver\"\n)\n\n// LogsBuilder provides an interface for scrapers to report logs while taking care of all the transformations\n// required to produce log representation defined in metadata and user config.\ntype LogsBuilder struct {\n\tlogsBuffer       plog.Logs\n\tlogRecordsBuffer plog.LogRecordSlice\n\tbuildInfo        component.BuildInfo // contains version information.\n}\n\n// LogBuilderOption applies changes to default logs builder.\ntype LogBuilderOption interface {\n\tapply(*LogsBuilder)\n}\n\nfunc NewLogsBuilder(settings receiver.Settings) *LogsBuilder {\n\tlb := &LogsBuilder{\n\t\tlogsBuffer:       plog.NewLogs(),\n\t\tlogRecordsBuffer: plog.NewLogRecordSlice(),\n\t\tbuildInfo:        settings.BuildInfo,\n\t}\n\n\treturn lb\n}\n\n// ResourceLogsOption applies changes to provided resource logs.\ntype ResourceLogsOption interface {\n\tapply(plog.ResourceLogs)\n}\n\ntype resourceLogsOptionFunc func(plog.ResourceLogs)\n\nfunc (rlof resourceLogsOptionFunc) apply(rl plog.ResourceLogs) {\n\trlof(rl)\n}\n\n// WithLogsResource sets the provided resource on the emitted ResourceLogs.\n// It's recommended to use ResourceBuilder to create the resource.\nfunc WithLogsResource(res pcommon.Resource) ResourceLogsOption {\n\treturn resourceLogsOptionFunc(func(rl plog.ResourceLogs) {\n\t\tres.CopyTo(rl.Resource())\n\t})\n}\n\n// AppendLogRecord adds a log record to the logs builder.\nfunc (lb *LogsBuilder) AppendLogRecord(lr plog.LogRecord) {\n\tlr.MoveTo(lb.logRecordsBuffer.AppendEmpty())\n}\n\n// EmitForResource saves all the generated logs under a new resource and updates the internal state to be ready for\n// recording another set of log records as part of another resource. This function can be helpful when one scraper\n// needs to emit logs from several resources. Otherwise calling this function is not required,\n// just `Emit` function can be called instead.\n// Resource attributes should be provided as ResourceLogsOption arguments.\nfunc (lb *LogsBuilder) EmitForResource(options ...ResourceLogsOption) {\n\trl := plog.NewResourceLogs()\n\trl.SetSchemaUrl(conventions.SchemaURL)\n\tils := rl.ScopeLogs().AppendEmpty()\n\tils.Scope().SetName(ScopeName)\n\tils.Scope().SetVersion(lb.buildInfo.Version)\n\n\tfor _, op := range options {\n\t\top.apply(rl)\n\t}\n\n\tif lb.logRecordsBuffer.Len() > 0 {\n\t\tlb.logRecordsBuffer.MoveAndAppendTo(ils.LogRecords())\n\t\tlb.logRecordsBuffer = plog.NewLogRecordSlice()\n\t}\n\n\tif ils.LogRecords().Len() > 0 {\n\t\trl.MoveTo(lb.logsBuffer.ResourceLogs().AppendEmpty())\n\t}\n}\n\n// Emit returns all the logs accumulated by the logs builder and updates the internal state to be ready for\n// recording another set of logs. This function will be responsible for applying all the transformations required to\n// produce logs representation defined in metadata and user config.\nfunc (lb *LogsBuilder) Emit(options ...ResourceLogsOption) plog.Logs {\n\tlb.EmitForResource(options...)\n\tlogs := lb.logsBuffer\n\tlb.logsBuffer = plog.NewLogs()\n\treturn logs\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/internal/metadata/generated_logs_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\nfunc TestLogsBuilderAppendLogRecord(t *testing.T) {\n\tobservedZapCore, _ := observer.New(zap.WarnLevel)\n\tsettings := receivertest.NewNopSettings(receivertest.NopType)\n\tsettings.Logger = zap.New(observedZapCore)\n\tlb := NewLogsBuilder(settings)\n\n\tres := pcommon.NewResource()\n\n\t// append the first log record\n\tlr := plog.NewLogRecord()\n\tlr.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\tlr.Attributes().PutStr(\"type\", \"log\")\n\tlr.Body().SetStr(\"the first log record\")\n\n\t// append the second log record\n\tlr2 := plog.NewLogRecord()\n\tlr2.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\tlr2.Attributes().PutStr(\"type\", \"event\")\n\tlr2.Body().SetStr(\"the second log record\")\n\n\tlb.AppendLogRecord(lr)\n\tlb.AppendLogRecord(lr2)\n\n\tlogs := lb.Emit(WithLogsResource(res))\n\tassert.Equal(t, 1, logs.ResourceLogs().Len())\n\n\trl := logs.ResourceLogs().At(0)\n\tassert.Equal(t, 1, rl.ScopeLogs().Len())\n\n\tsl := rl.ScopeLogs().At(0)\n\tassert.Equal(t, ScopeName, sl.Scope().Name())\n\tassert.Equal(t, lb.buildInfo.Version, sl.Scope().Version())\n\n\tassert.Equal(t, 2, sl.LogRecords().Len())\n\n\tattrVal, ok := sl.LogRecords().At(0).Attributes().Get(\"type\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"log\", attrVal.Str())\n\n\tassert.Equal(t, pcommon.ValueTypeStr, sl.LogRecords().At(0).Body().Type())\n\tassert.Equal(t, \"the first log record\", sl.LogRecords().At(0).Body().Str())\n\n\tattrVal, ok = sl.LogRecords().At(1).Attributes().Get(\"type\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"event\", attrVal.Str())\n\n\tassert.Equal(t, pcommon.ValueTypeStr, sl.LogRecords().At(1).Body().Type())\n\tassert.Equal(t, \"the second log record\", sl.LogRecords().At(1).Body().Str())\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/internal/metadata/generated_metrics.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"time\"\n\n\tconventions \"go.opentelemetry.io/otel/semconv/v1.9.0\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/filter\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/receiver\"\n)\n\n// AttributeEnumAttr specifies the value enum_attr attribute.\ntype AttributeEnumAttr int\n\nconst (\n\t_ AttributeEnumAttr = iota\n\tAttributeEnumAttrRed\n\tAttributeEnumAttrGreen\n\tAttributeEnumAttrBlue\n)\n\n// String returns the string representation of the AttributeEnumAttr.\nfunc (av AttributeEnumAttr) String() string {\n\tswitch av {\n\tcase AttributeEnumAttrRed:\n\t\treturn \"red\"\n\tcase AttributeEnumAttrGreen:\n\t\treturn \"green\"\n\tcase AttributeEnumAttrBlue:\n\t\treturn \"blue\"\n\t}\n\treturn \"\"\n}\n\n// MapAttributeEnumAttr is a helper map of string to AttributeEnumAttr attribute value.\nvar MapAttributeEnumAttr = map[string]AttributeEnumAttr{\n\t\"red\":   AttributeEnumAttrRed,\n\t\"green\": AttributeEnumAttrGreen,\n\t\"blue\":  AttributeEnumAttrBlue,\n}\n\nvar MetricsInfo = metricsInfo{\n\tDefaultMetric: metricInfo{\n\t\tName: \"default.metric\",\n\t},\n\tDefaultMetricToBeRemoved: metricInfo{\n\t\tName: \"default.metric.to_be_removed\",\n\t},\n\tMetricInputType: metricInfo{\n\t\tName: \"metric.input_type\",\n\t},\n\tOptionalMetric: metricInfo{\n\t\tName: \"optional.metric\",\n\t},\n\tOptionalMetricEmptyUnit: metricInfo{\n\t\tName: \"optional.metric.empty_unit\",\n\t},\n}\n\ntype metricsInfo struct {\n\tDefaultMetric            metricInfo\n\tDefaultMetricToBeRemoved metricInfo\n\tMetricInputType          metricInfo\n\tOptionalMetric           metricInfo\n\tOptionalMetricEmptyUnit  metricInfo\n}\n\ntype metricInfo struct {\n\tName string\n}\n\ntype MetricAttributeOption interface {\n\tapply(pmetric.NumberDataPoint)\n}\n\ntype metricAttributeOptionFunc func(pmetric.NumberDataPoint)\n\nfunc (maof metricAttributeOptionFunc) apply(dp pmetric.NumberDataPoint) {\n\tmaof(dp)\n}\n\nfunc WithOptionalIntAttrMetricAttribute(optionalIntAttrAttributeValue int64) MetricAttributeOption {\n\treturn metricAttributeOptionFunc(func(dp pmetric.NumberDataPoint) {\n\t\tdp.Attributes().PutInt(\"optional_int_attr\", optionalIntAttrAttributeValue)\n\t})\n}\n\nfunc WithOptionalStringAttrMetricAttribute(optionalStringAttrAttributeValue string) MetricAttributeOption {\n\treturn metricAttributeOptionFunc(func(dp pmetric.NumberDataPoint) {\n\t\tdp.Attributes().PutStr(\"optional_string_attr\", optionalStringAttrAttributeValue)\n\t})\n}\n\ntype metricDefaultMetric struct {\n\tdata     pmetric.Metric // data buffer for generated metric.\n\tconfig   MetricConfig   // metric config provided by user.\n\tcapacity int            // max observed number of data points added to the metric.\n}\n\n// init fills default.metric metric with initial data.\nfunc (m *metricDefaultMetric) init() {\n\tm.data.SetName(\"default.metric\")\n\tm.data.SetDescription(\"Monotonic cumulative sum int metric enabled by default.\")\n\tm.data.SetUnit(\"s\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(true)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n\tm.data.Sum().DataPoints().EnsureCapacity(m.capacity)\n}\n\nfunc (m *metricDefaultMetric) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val int64, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue string, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any, options ...MetricAttributeOption) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\tdp := m.data.Sum().DataPoints().AppendEmpty()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tdp.SetIntValue(val)\n\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\tdp.Attributes().PutInt(\"state\", overriddenIntAttrAttributeValue)\n\tdp.Attributes().PutStr(\"enum_attr\", enumAttrAttributeValue)\n\tdp.Attributes().PutEmptySlice(\"slice_attr\").FromRaw(sliceAttrAttributeValue)\n\tdp.Attributes().PutEmptyMap(\"map_attr\").FromRaw(mapAttrAttributeValue)\n\tfor _, op := range options {\n\t\top.apply(dp)\n\t}\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricDefaultMetric) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricDefaultMetric) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricDefaultMetric(cfg MetricConfig) metricDefaultMetric {\n\tm := metricDefaultMetric{config: cfg}\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricDefaultMetricToBeRemoved struct {\n\tdata     pmetric.Metric // data buffer for generated metric.\n\tconfig   MetricConfig   // metric config provided by user.\n\tcapacity int            // max observed number of data points added to the metric.\n}\n\n// init fills default.metric.to_be_removed metric with initial data.\nfunc (m *metricDefaultMetricToBeRemoved) init() {\n\tm.data.SetName(\"default.metric.to_be_removed\")\n\tm.data.SetDescription(\"[DEPRECATED] Non-monotonic delta sum double metric enabled by default.\")\n\tm.data.SetUnit(\"s\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(false)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityDelta)\n}\n\nfunc (m *metricDefaultMetricToBeRemoved) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val float64) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\tdp := m.data.Sum().DataPoints().AppendEmpty()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tdp.SetDoubleValue(val)\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricDefaultMetricToBeRemoved) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricDefaultMetricToBeRemoved) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricDefaultMetricToBeRemoved(cfg MetricConfig) metricDefaultMetricToBeRemoved {\n\tm := metricDefaultMetricToBeRemoved{config: cfg}\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricMetricInputType struct {\n\tdata     pmetric.Metric // data buffer for generated metric.\n\tconfig   MetricConfig   // metric config provided by user.\n\tcapacity int            // max observed number of data points added to the metric.\n}\n\n// init fills metric.input_type metric with initial data.\nfunc (m *metricMetricInputType) init() {\n\tm.data.SetName(\"metric.input_type\")\n\tm.data.SetDescription(\"Monotonic cumulative sum int metric with string input_type enabled by default.\")\n\tm.data.SetUnit(\"s\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(true)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n\tm.data.Sum().DataPoints().EnsureCapacity(m.capacity)\n}\n\nfunc (m *metricMetricInputType) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val int64, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue string, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\tdp := m.data.Sum().DataPoints().AppendEmpty()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tdp.SetIntValue(val)\n\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\tdp.Attributes().PutInt(\"state\", overriddenIntAttrAttributeValue)\n\tdp.Attributes().PutStr(\"enum_attr\", enumAttrAttributeValue)\n\tdp.Attributes().PutEmptySlice(\"slice_attr\").FromRaw(sliceAttrAttributeValue)\n\tdp.Attributes().PutEmptyMap(\"map_attr\").FromRaw(mapAttrAttributeValue)\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricMetricInputType) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricMetricInputType) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricMetricInputType(cfg MetricConfig) metricMetricInputType {\n\tm := metricMetricInputType{config: cfg}\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricOptionalMetric struct {\n\tdata     pmetric.Metric // data buffer for generated metric.\n\tconfig   MetricConfig   // metric config provided by user.\n\tcapacity int            // max observed number of data points added to the metric.\n}\n\n// init fills optional.metric metric with initial data.\nfunc (m *metricOptionalMetric) init() {\n\tm.data.SetName(\"optional.metric\")\n\tm.data.SetDescription(\"[DEPRECATED] Gauge double metric disabled by default.\")\n\tm.data.SetUnit(\"1\")\n\tm.data.SetEmptyGauge()\n\tm.data.Gauge().DataPoints().EnsureCapacity(m.capacity)\n}\n\nfunc (m *metricOptionalMetric) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool, booleanAttr2AttributeValue bool, options ...MetricAttributeOption) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\tdp := m.data.Gauge().DataPoints().AppendEmpty()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tdp.SetDoubleValue(val)\n\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\tdp.Attributes().PutBool(\"boolean_attr\", booleanAttrAttributeValue)\n\tdp.Attributes().PutBool(\"boolean_attr2\", booleanAttr2AttributeValue)\n\tfor _, op := range options {\n\t\top.apply(dp)\n\t}\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricOptionalMetric) updateCapacity() {\n\tif m.data.Gauge().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Gauge().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricOptionalMetric) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricOptionalMetric(cfg MetricConfig) metricOptionalMetric {\n\tm := metricOptionalMetric{config: cfg}\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricOptionalMetricEmptyUnit struct {\n\tdata     pmetric.Metric // data buffer for generated metric.\n\tconfig   MetricConfig   // metric config provided by user.\n\tcapacity int            // max observed number of data points added to the metric.\n}\n\n// init fills optional.metric.empty_unit metric with initial data.\nfunc (m *metricOptionalMetricEmptyUnit) init() {\n\tm.data.SetName(\"optional.metric.empty_unit\")\n\tm.data.SetDescription(\"[DEPRECATED] Gauge double metric disabled by default.\")\n\tm.data.SetUnit(\"\")\n\tm.data.SetEmptyGauge()\n\tm.data.Gauge().DataPoints().EnsureCapacity(m.capacity)\n}\n\nfunc (m *metricOptionalMetricEmptyUnit) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\tdp := m.data.Gauge().DataPoints().AppendEmpty()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tdp.SetDoubleValue(val)\n\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\tdp.Attributes().PutBool(\"boolean_attr\", booleanAttrAttributeValue)\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricOptionalMetricEmptyUnit) updateCapacity() {\n\tif m.data.Gauge().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Gauge().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricOptionalMetricEmptyUnit) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricOptionalMetricEmptyUnit(cfg MetricConfig) metricOptionalMetricEmptyUnit {\n\tm := metricOptionalMetricEmptyUnit{config: cfg}\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\n// MetricsBuilder provides an interface for scrapers to report metrics while taking care of all the transformations\n// required to produce metric representation defined in metadata and user config.\ntype MetricsBuilder struct {\n\tconfig                         MetricsBuilderConfig // config of the metrics builder.\n\tstartTime                      pcommon.Timestamp    // start time that will be applied to all recorded data points.\n\tmetricsCapacity                int                  // maximum observed number of metrics per resource.\n\tmetricsBuffer                  pmetric.Metrics      // accumulates metrics data before emitting.\n\tbuildInfo                      component.BuildInfo  // contains version information.\n\tresourceAttributeIncludeFilter map[string]filter.Filter\n\tresourceAttributeExcludeFilter map[string]filter.Filter\n\tmetricDefaultMetric            metricDefaultMetric\n\tmetricDefaultMetricToBeRemoved metricDefaultMetricToBeRemoved\n\tmetricMetricInputType          metricMetricInputType\n\tmetricOptionalMetric           metricOptionalMetric\n\tmetricOptionalMetricEmptyUnit  metricOptionalMetricEmptyUnit\n}\n\n// MetricBuilderOption applies changes to default metrics builder.\ntype MetricBuilderOption interface {\n\tapply(*MetricsBuilder)\n}\n\ntype metricBuilderOptionFunc func(mb *MetricsBuilder)\n\nfunc (mbof metricBuilderOptionFunc) apply(mb *MetricsBuilder) {\n\tmbof(mb)\n}\n\n// WithStartTime sets startTime on the metrics builder.\nfunc WithStartTime(startTime pcommon.Timestamp) MetricBuilderOption {\n\treturn metricBuilderOptionFunc(func(mb *MetricsBuilder) {\n\t\tmb.startTime = startTime\n\t})\n}\nfunc NewMetricsBuilder(mbc MetricsBuilderConfig, settings receiver.Settings, options ...MetricBuilderOption) *MetricsBuilder {\n\tif !mbc.Metrics.DefaultMetric.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] Please set `enabled` field explicitly for `default.metric`: This metric will be disabled by default soon.\")\n\t}\n\tif mbc.Metrics.DefaultMetricToBeRemoved.Enabled {\n\t\tsettings.Logger.Warn(\"[WARNING] `default.metric.to_be_removed` should not be enabled: This metric is deprecated and will be removed soon.\")\n\t}\n\tif mbc.Metrics.OptionalMetric.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] `optional.metric` should not be configured: This metric is deprecated and will be removed soon.\")\n\t}\n\tif mbc.Metrics.OptionalMetricEmptyUnit.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] `optional.metric.empty_unit` should not be configured: This metric is deprecated and will be removed soon.\")\n\t}\n\tif !mbc.ResourceAttributes.StringResourceAttrDisableWarning.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] Please set `enabled` field explicitly for `string.resource.attr_disable_warning`: This resource_attribute will be disabled by default soon.\")\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrRemoveWarning.enabledSetByUser || mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsInclude != nil || mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsExclude != nil {\n\t\tsettings.Logger.Warn(\"[WARNING] `string.resource.attr_remove_warning` should not be configured: This resource_attribute is deprecated and will be removed soon.\")\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrToBeRemoved.Enabled {\n\t\tsettings.Logger.Warn(\"[WARNING] `string.resource.attr_to_be_removed` should not be enabled: This resource_attribute is deprecated and will be removed soon.\")\n\t}\n\tmb := &MetricsBuilder{\n\t\tconfig:                         mbc,\n\t\tstartTime:                      pcommon.NewTimestampFromTime(time.Now()),\n\t\tmetricsBuffer:                  pmetric.NewMetrics(),\n\t\tbuildInfo:                      settings.BuildInfo,\n\t\tmetricDefaultMetric:            newMetricDefaultMetric(mbc.Metrics.DefaultMetric),\n\t\tmetricDefaultMetricToBeRemoved: newMetricDefaultMetricToBeRemoved(mbc.Metrics.DefaultMetricToBeRemoved),\n\t\tmetricMetricInputType:          newMetricMetricInputType(mbc.Metrics.MetricInputType),\n\t\tmetricOptionalMetric:           newMetricOptionalMetric(mbc.Metrics.OptionalMetric),\n\t\tmetricOptionalMetricEmptyUnit:  newMetricOptionalMetricEmptyUnit(mbc.Metrics.OptionalMetricEmptyUnit),\n\t\tresourceAttributeIncludeFilter: make(map[string]filter.Filter),\n\t\tresourceAttributeExcludeFilter: make(map[string]filter.Filter),\n\t}\n\tif mbc.ResourceAttributes.MapResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"map.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.MapResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.MapResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"map.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.MapResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.OptionalResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"optional.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.OptionalResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.OptionalResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"optional.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.OptionalResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.SliceResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"slice.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.SliceResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.SliceResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"slice.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.SliceResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringEnumResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.enum.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.StringEnumResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringEnumResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.enum.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.StringEnumResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrDisableWarning.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.resource.attr_disable_warning\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrDisableWarning.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrDisableWarning.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.resource.attr_disable_warning\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrDisableWarning.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.resource.attr_remove_warning\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.resource.attr_remove_warning\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrToBeRemoved.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.resource.attr_to_be_removed\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrToBeRemoved.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrToBeRemoved.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.resource.attr_to_be_removed\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrToBeRemoved.MetricsExclude)\n\t}\n\n\tfor _, op := range options {\n\t\top.apply(mb)\n\t}\n\treturn mb\n}\n\n// NewResourceBuilder returns a new resource builder that should be used to build a resource associated with for the emitted metrics.\nfunc (mb *MetricsBuilder) NewResourceBuilder() *ResourceBuilder {\n\treturn NewResourceBuilder(mb.config.ResourceAttributes)\n}\n\n// updateCapacity updates max length of metrics and resource attributes that will be used for the slice capacity.\nfunc (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n}\n\n// ResourceMetricsOption applies changes to provided resource metrics.\ntype ResourceMetricsOption interface {\n\tapply(pmetric.ResourceMetrics)\n}\n\ntype resourceMetricsOptionFunc func(pmetric.ResourceMetrics)\n\nfunc (rmof resourceMetricsOptionFunc) apply(rm pmetric.ResourceMetrics) {\n\trmof(rm)\n}\n\n// WithResource sets the provided resource on the emitted ResourceMetrics.\n// It's recommended to use ResourceBuilder to create the resource.\nfunc WithResource(res pcommon.Resource) ResourceMetricsOption {\n\treturn resourceMetricsOptionFunc(func(rm pmetric.ResourceMetrics) {\n\t\tres.CopyTo(rm.Resource())\n\t})\n}\n\n// WithStartTimeOverride overrides start time for all the resource metrics data points.\n// This option should be only used if different start time has to be set on metrics coming from different resources.\nfunc WithStartTimeOverride(start pcommon.Timestamp) ResourceMetricsOption {\n\treturn resourceMetricsOptionFunc(func(rm pmetric.ResourceMetrics) {\n\t\tvar dps pmetric.NumberDataPointSlice\n\t\tmetrics := rm.ScopeMetrics().At(0).Metrics()\n\t\tfor i := 0; i < metrics.Len(); i++ {\n\t\t\tswitch metrics.At(i).Type() {\n\t\t\tcase pmetric.MetricTypeGauge:\n\t\t\t\tdps = metrics.At(i).Gauge().DataPoints()\n\t\t\tcase pmetric.MetricTypeSum:\n\t\t\t\tdps = metrics.At(i).Sum().DataPoints()\n\t\t\t}\n\t\t\tfor j := 0; j < dps.Len(); j++ {\n\t\t\t\tdps.At(j).SetStartTimestamp(start)\n\t\t\t}\n\t\t}\n\t})\n}\n\n// EmitForResource saves all the generated metrics under a new resource and updates the internal state to be ready for\n// recording another set of data points as part of another resource. This function can be helpful when one scraper\n// needs to emit metrics from several resources. Otherwise calling this function is not required,\n// just `Emit` function can be called instead.\n// Resource attributes should be provided as ResourceMetricsOption arguments.\nfunc (mb *MetricsBuilder) EmitForResource(options ...ResourceMetricsOption) {\n\trm := pmetric.NewResourceMetrics()\n\trm.SetSchemaUrl(conventions.SchemaURL)\n\tils := rm.ScopeMetrics().AppendEmpty()\n\tils.Scope().SetName(ScopeName)\n\tils.Scope().SetVersion(mb.buildInfo.Version)\n\tils.Metrics().EnsureCapacity(mb.metricsCapacity)\n\tmb.metricDefaultMetric.emit(ils.Metrics())\n\tmb.metricDefaultMetricToBeRemoved.emit(ils.Metrics())\n\tmb.metricMetricInputType.emit(ils.Metrics())\n\tmb.metricOptionalMetric.emit(ils.Metrics())\n\tmb.metricOptionalMetricEmptyUnit.emit(ils.Metrics())\n\n\tfor _, op := range options {\n\t\top.apply(rm)\n\t}\n\tfor attr, filter := range mb.resourceAttributeIncludeFilter {\n\t\tif val, ok := rm.Resource().Attributes().Get(attr); ok && !filter.Matches(val.AsString()) {\n\t\t\treturn\n\t\t}\n\t}\n\tfor attr, filter := range mb.resourceAttributeExcludeFilter {\n\t\tif val, ok := rm.Resource().Attributes().Get(attr); ok && filter.Matches(val.AsString()) {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif ils.Metrics().Len() > 0 {\n\t\tmb.updateCapacity(rm)\n\t\trm.MoveTo(mb.metricsBuffer.ResourceMetrics().AppendEmpty())\n\t}\n}\n\n// Emit returns all the metrics accumulated by the metrics builder and updates the internal state to be ready for\n// recording another set of metrics. This function will be responsible for applying all the transformations required to\n// produce metric representation defined in metadata and user config, e.g. delta or cumulative.\nfunc (mb *MetricsBuilder) Emit(options ...ResourceMetricsOption) pmetric.Metrics {\n\tmb.EmitForResource(options...)\n\tmetrics := mb.metricsBuffer\n\tmb.metricsBuffer = pmetric.NewMetrics()\n\treturn metrics\n}\n\n// RecordDefaultMetricDataPoint adds a data point to default.metric metric.\nfunc (mb *MetricsBuilder) RecordDefaultMetricDataPoint(ts pcommon.Timestamp, val int64, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue AttributeEnumAttr, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any, options ...MetricAttributeOption) {\n\tmb.metricDefaultMetric.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, overriddenIntAttrAttributeValue, enumAttrAttributeValue.String(), sliceAttrAttributeValue, mapAttrAttributeValue, options...)\n}\n\n// RecordDefaultMetricToBeRemovedDataPoint adds a data point to default.metric.to_be_removed metric.\nfunc (mb *MetricsBuilder) RecordDefaultMetricToBeRemovedDataPoint(ts pcommon.Timestamp, val float64) {\n\tmb.metricDefaultMetricToBeRemoved.recordDataPoint(mb.startTime, ts, val)\n}\n\n// RecordMetricInputTypeDataPoint adds a data point to metric.input_type metric.\nfunc (mb *MetricsBuilder) RecordMetricInputTypeDataPoint(ts pcommon.Timestamp, inputVal string, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue AttributeEnumAttr, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MetricInputType, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMetricInputType.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, overriddenIntAttrAttributeValue, enumAttrAttributeValue.String(), sliceAttrAttributeValue, mapAttrAttributeValue)\n\treturn nil\n}\n\n// RecordOptionalMetricDataPoint adds a data point to optional.metric metric.\nfunc (mb *MetricsBuilder) RecordOptionalMetricDataPoint(ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool, booleanAttr2AttributeValue bool, options ...MetricAttributeOption) {\n\tmb.metricOptionalMetric.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, booleanAttrAttributeValue, booleanAttr2AttributeValue, options...)\n}\n\n// RecordOptionalMetricEmptyUnitDataPoint adds a data point to optional.metric.empty_unit metric.\nfunc (mb *MetricsBuilder) RecordOptionalMetricEmptyUnitDataPoint(ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\tmb.metricOptionalMetricEmptyUnit.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, booleanAttrAttributeValue)\n}\n\n// Reset resets metrics builder to its initial state. It should be used when external metrics source is restarted,\n// and metrics builder should update its startTime and reset it's internal state accordingly.\nfunc (mb *MetricsBuilder) Reset(options ...MetricBuilderOption) {\n\tmb.startTime = pcommon.NewTimestampFromTime(time.Now())\n\tfor _, op := range options {\n\t\top.apply(mb)\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/internal/metadata/generated_metrics_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\ntype testDataSet int\n\nconst (\n\ttestDataSetDefault testDataSet = iota\n\ttestDataSetAll\n\ttestDataSetNone\n)\n\nfunc TestMetricsBuilder(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tmetricsSet  testDataSet\n\t\tresAttrsSet testDataSet\n\t\texpectEmpty bool\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t},\n\t\t{\n\t\t\tname:        \"all_set\",\n\t\t\tmetricsSet:  testDataSetAll,\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t},\n\t\t{\n\t\t\tname:        \"none_set\",\n\t\t\tmetricsSet:  testDataSetNone,\n\t\t\tresAttrsSet: testDataSetNone,\n\t\t\texpectEmpty: true,\n\t\t},\n\t\t{\n\t\t\tname:        \"filter_set_include\",\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t},\n\t\t{\n\t\t\tname:        \"filter_set_exclude\",\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t\texpectEmpty: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tstart := pcommon.Timestamp(1_000_000_000)\n\t\t\tts := pcommon.Timestamp(1_000_001_000)\n\t\t\tobservedZapCore, observedLogs := observer.New(zap.WarnLevel)\n\t\t\tsettings := receivertest.NewNopSettings(receivertest.NopType)\n\t\t\tsettings.Logger = zap.New(observedZapCore)\n\t\t\tmb := NewMetricsBuilder(loadMetricsBuilderConfig(t, tt.name), settings, WithStartTime(start))\n\n\t\t\texpectedWarnings := 0\n\t\t\tif tt.metricsSet == testDataSetDefault {\n\t\t\t\tassert.Equal(t, \"[WARNING] Please set `enabled` field explicitly for `default.metric`: This metric will be disabled by default soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetDefault || tt.metricsSet == testDataSetAll {\n\t\t\t\tassert.Equal(t, \"[WARNING] `default.metric.to_be_removed` should not be enabled: This metric is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetAll || tt.metricsSet == testDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `optional.metric` should not be configured: This metric is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetAll || tt.metricsSet == testDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `optional.metric.empty_unit` should not be configured: This metric is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.resAttrsSet == testDataSetDefault {\n\t\t\t\tassert.Equal(t, \"[WARNING] Please set `enabled` field explicitly for `string.resource.attr_disable_warning`: This resource_attribute will be disabled by default soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.resAttrsSet == testDataSetAll || tt.resAttrsSet == testDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `string.resource.attr_remove_warning` should not be configured: This resource_attribute is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.resAttrsSet == testDataSetDefault || tt.resAttrsSet == testDataSetAll {\n\t\t\t\tassert.Equal(t, \"[WARNING] `string.resource.attr_to_be_removed` should not be enabled: This resource_attribute is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\n\t\t\tassert.Equal(t, expectedWarnings, observedLogs.Len())\n\n\t\t\tdefaultMetricsCount := 0\n\t\t\tallMetricsCount := 0\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordDefaultMetricDataPoint(ts, 1, \"string_attr-val\", 19, AttributeEnumAttrRed, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"}, WithOptionalIntAttrMetricAttribute(17), WithOptionalStringAttrMetricAttribute(\"optional_string_attr-val\"))\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordDefaultMetricToBeRemovedDataPoint(ts, 1)\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordMetricInputTypeDataPoint(ts, \"1\", \"string_attr-val\", 19, AttributeEnumAttrRed, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"})\n\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordOptionalMetricDataPoint(ts, 1, \"string_attr-val\", true, false, WithOptionalStringAttrMetricAttribute(\"optional_string_attr-val\"))\n\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordOptionalMetricEmptyUnitDataPoint(ts, 1, \"string_attr-val\", true)\n\n\t\t\trb := mb.NewResourceBuilder()\n\t\t\trb.SetMapResourceAttr(map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"})\n\t\t\trb.SetOptionalResourceAttr(\"optional.resource.attr-val\")\n\t\t\trb.SetSliceResourceAttr([]any{\"slice.resource.attr-item1\", \"slice.resource.attr-item2\"})\n\t\t\trb.SetStringEnumResourceAttrOne()\n\t\t\trb.SetStringResourceAttr(\"string.resource.attr-val\")\n\t\t\trb.SetStringResourceAttrDisableWarning(\"string.resource.attr_disable_warning-val\")\n\t\t\trb.SetStringResourceAttrRemoveWarning(\"string.resource.attr_remove_warning-val\")\n\t\t\trb.SetStringResourceAttrToBeRemoved(\"string.resource.attr_to_be_removed-val\")\n\t\t\tres := rb.Emit()\n\t\t\tmetrics := mb.Emit(WithResource(res))\n\n\t\t\tif tt.expectEmpty {\n\t\t\t\tassert.Equal(t, 0, metrics.ResourceMetrics().Len())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tassert.Equal(t, 1, metrics.ResourceMetrics().Len())\n\t\t\trm := metrics.ResourceMetrics().At(0)\n\t\t\tassert.Equal(t, res, rm.Resource())\n\t\t\tassert.Equal(t, 1, rm.ScopeMetrics().Len())\n\t\t\tms := rm.ScopeMetrics().At(0).Metrics()\n\t\t\tif tt.metricsSet == testDataSetDefault {\n\t\t\t\tassert.Equal(t, defaultMetricsCount, ms.Len())\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetAll {\n\t\t\t\tassert.Equal(t, allMetricsCount, ms.Len())\n\t\t\t}\n\t\t\tvalidatedMetrics := make(map[string]bool)\n\t\t\tfor i := 0; i < ms.Len(); i++ {\n\t\t\t\tswitch ms.At(i).Name() {\n\t\t\t\tcase \"default.metric\":\n\t\t\t\t\tassert.False(t, validatedMetrics[\"default.metric\"], \"Found a duplicate in the metrics slice: default.metric\")\n\t\t\t\t\tvalidatedMetrics[\"default.metric\"] = true\n\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, ms.At(i).Type())\n\t\t\t\t\tassert.Equal(t, 1, ms.At(i).Sum().DataPoints().Len())\n\t\t\t\t\tassert.Equal(t, \"Monotonic cumulative sum int metric enabled by default.\", ms.At(i).Description())\n\t\t\t\t\tassert.Equal(t, \"s\", ms.At(i).Unit())\n\t\t\t\t\tassert.True(t, ms.At(i).Sum().IsMonotonic())\n\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, ms.At(i).Sum().AggregationTemporality())\n\t\t\t\t\tdp := ms.At(i).Sum().DataPoints().At(0)\n\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t\tattrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, \"string_attr-val\", attrVal.Str())\n\t\t\t\t\tattrVal, ok = dp.Attributes().Get(\"state\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.EqualValues(t, 19, attrVal.Int())\n\t\t\t\t\tattrVal, ok = dp.Attributes().Get(\"enum_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, \"red\", attrVal.Str())\n\t\t\t\t\tattrVal, ok = dp.Attributes().Get(\"slice_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, attrVal.Slice().AsRaw())\n\t\t\t\t\tattrVal, ok = dp.Attributes().Get(\"map_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"}, attrVal.Map().AsRaw())\n\t\t\t\t\tattrVal, ok = dp.Attributes().Get(\"optional_int_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.EqualValues(t, 17, attrVal.Int())\n\t\t\t\t\tattrVal, ok = dp.Attributes().Get(\"optional_string_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, \"optional_string_attr-val\", attrVal.Str())\n\t\t\t\tcase \"default.metric.to_be_removed\":\n\t\t\t\t\tassert.False(t, validatedMetrics[\"default.metric.to_be_removed\"], \"Found a duplicate in the metrics slice: default.metric.to_be_removed\")\n\t\t\t\t\tvalidatedMetrics[\"default.metric.to_be_removed\"] = true\n\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, ms.At(i).Type())\n\t\t\t\t\tassert.Equal(t, 1, ms.At(i).Sum().DataPoints().Len())\n\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Non-monotonic delta sum double metric enabled by default.\", ms.At(i).Description())\n\t\t\t\t\tassert.Equal(t, \"s\", ms.At(i).Unit())\n\t\t\t\t\tassert.False(t, ms.At(i).Sum().IsMonotonic())\n\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityDelta, ms.At(i).Sum().AggregationTemporality())\n\t\t\t\t\tdp := ms.At(i).Sum().DataPoints().At(0)\n\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\tcase \"metric.input_type\":\n\t\t\t\t\tassert.False(t, validatedMetrics[\"metric.input_type\"], \"Found a duplicate in the metrics slice: metric.input_type\")\n\t\t\t\t\tvalidatedMetrics[\"metric.input_type\"] = true\n\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, ms.At(i).Type())\n\t\t\t\t\tassert.Equal(t, 1, ms.At(i).Sum().DataPoints().Len())\n\t\t\t\t\tassert.Equal(t, \"Monotonic cumulative sum int metric with string input_type enabled by default.\", ms.At(i).Description())\n\t\t\t\t\tassert.Equal(t, \"s\", ms.At(i).Unit())\n\t\t\t\t\tassert.True(t, ms.At(i).Sum().IsMonotonic())\n\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, ms.At(i).Sum().AggregationTemporality())\n\t\t\t\t\tdp := ms.At(i).Sum().DataPoints().At(0)\n\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t\tattrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, \"string_attr-val\", attrVal.Str())\n\t\t\t\t\tattrVal, ok = dp.Attributes().Get(\"state\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.EqualValues(t, 19, attrVal.Int())\n\t\t\t\t\tattrVal, ok = dp.Attributes().Get(\"enum_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, \"red\", attrVal.Str())\n\t\t\t\t\tattrVal, ok = dp.Attributes().Get(\"slice_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, attrVal.Slice().AsRaw())\n\t\t\t\t\tattrVal, ok = dp.Attributes().Get(\"map_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"}, attrVal.Map().AsRaw())\n\t\t\t\tcase \"optional.metric\":\n\t\t\t\t\tassert.False(t, validatedMetrics[\"optional.metric\"], \"Found a duplicate in the metrics slice: optional.metric\")\n\t\t\t\t\tvalidatedMetrics[\"optional.metric\"] = true\n\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, ms.At(i).Type())\n\t\t\t\t\tassert.Equal(t, 1, ms.At(i).Gauge().DataPoints().Len())\n\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Gauge double metric disabled by default.\", ms.At(i).Description())\n\t\t\t\t\tassert.Equal(t, \"1\", ms.At(i).Unit())\n\t\t\t\t\tdp := ms.At(i).Gauge().DataPoints().At(0)\n\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\tattrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, \"string_attr-val\", attrVal.Str())\n\t\t\t\t\tattrVal, ok = dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.True(t, attrVal.Bool())\n\t\t\t\t\tattrVal, ok = dp.Attributes().Get(\"boolean_attr2\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.False(t, attrVal.Bool())\n\t\t\t\t\tattrVal, ok = dp.Attributes().Get(\"optional_string_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, \"optional_string_attr-val\", attrVal.Str())\n\t\t\t\tcase \"optional.metric.empty_unit\":\n\t\t\t\t\tassert.False(t, validatedMetrics[\"optional.metric.empty_unit\"], \"Found a duplicate in the metrics slice: optional.metric.empty_unit\")\n\t\t\t\t\tvalidatedMetrics[\"optional.metric.empty_unit\"] = true\n\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, ms.At(i).Type())\n\t\t\t\t\tassert.Equal(t, 1, ms.At(i).Gauge().DataPoints().Len())\n\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Gauge double metric disabled by default.\", ms.At(i).Description())\n\t\t\t\t\tassert.Empty(t, ms.At(i).Unit())\n\t\t\t\t\tdp := ms.At(i).Gauge().DataPoints().At(0)\n\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\tattrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, \"string_attr-val\", attrVal.Str())\n\t\t\t\t\tattrVal, ok = dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.True(t, attrVal.Bool())\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/internal/metadata/generated_resource.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ResourceBuilder is a helper struct to build resources predefined in metadata.yaml.\n// The ResourceBuilder is not thread-safe and must not to be used in multiple goroutines.\ntype ResourceBuilder struct {\n\tconfig ResourceAttributesConfig\n\tres    pcommon.Resource\n}\n\n// NewResourceBuilder creates a new ResourceBuilder. This method should be called on the start of the application.\nfunc NewResourceBuilder(rac ResourceAttributesConfig) *ResourceBuilder {\n\treturn &ResourceBuilder{\n\t\tconfig: rac,\n\t\tres:    pcommon.NewResource(),\n\t}\n}\n\n// SetMapResourceAttr sets provided value as \"map.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetMapResourceAttr(val map[string]any) {\n\tif rb.config.MapResourceAttr.Enabled {\n\t\trb.res.Attributes().PutEmptyMap(\"map.resource.attr\").FromRaw(val)\n\t}\n}\n\n// SetOptionalResourceAttr sets provided value as \"optional.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetOptionalResourceAttr(val string) {\n\tif rb.config.OptionalResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"optional.resource.attr\", val)\n\t}\n}\n\n// SetSliceResourceAttr sets provided value as \"slice.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetSliceResourceAttr(val []any) {\n\tif rb.config.SliceResourceAttr.Enabled {\n\t\trb.res.Attributes().PutEmptySlice(\"slice.resource.attr\").FromRaw(val)\n\t}\n}\n\n// SetStringEnumResourceAttrOne sets \"string.enum.resource.attr=one\" attribute.\nfunc (rb *ResourceBuilder) SetStringEnumResourceAttrOne() {\n\tif rb.config.StringEnumResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.enum.resource.attr\", \"one\")\n\t}\n}\n\n// SetStringEnumResourceAttrTwo sets \"string.enum.resource.attr=two\" attribute.\nfunc (rb *ResourceBuilder) SetStringEnumResourceAttrTwo() {\n\tif rb.config.StringEnumResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.enum.resource.attr\", \"two\")\n\t}\n}\n\n// SetStringResourceAttr sets provided value as \"string.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttr(val string) {\n\tif rb.config.StringResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr\", val)\n\t}\n}\n\n// SetStringResourceAttrDisableWarning sets provided value as \"string.resource.attr_disable_warning\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttrDisableWarning(val string) {\n\tif rb.config.StringResourceAttrDisableWarning.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr_disable_warning\", val)\n\t}\n}\n\n// SetStringResourceAttrRemoveWarning sets provided value as \"string.resource.attr_remove_warning\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttrRemoveWarning(val string) {\n\tif rb.config.StringResourceAttrRemoveWarning.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr_remove_warning\", val)\n\t}\n}\n\n// SetStringResourceAttrToBeRemoved sets provided value as \"string.resource.attr_to_be_removed\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttrToBeRemoved(val string) {\n\tif rb.config.StringResourceAttrToBeRemoved.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr_to_be_removed\", val)\n\t}\n}\n\n// Emit returns the built resource and resets the internal builder state.\nfunc (rb *ResourceBuilder) Emit() pcommon.Resource {\n\tr := rb.res\n\trb.res = pcommon.NewResource()\n\treturn r\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/internal/metadata/generated_resource_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestResourceBuilder(t *testing.T) {\n\tfor _, tt := range []string{\"default\", \"all_set\", \"none_set\"} {\n\t\tt.Run(tt, func(t *testing.T) {\n\t\t\tcfg := loadResourceAttributesConfig(t, tt)\n\t\t\trb := NewResourceBuilder(cfg)\n\t\t\trb.SetMapResourceAttr(map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"})\n\t\t\trb.SetOptionalResourceAttr(\"optional.resource.attr-val\")\n\t\t\trb.SetSliceResourceAttr([]any{\"slice.resource.attr-item1\", \"slice.resource.attr-item2\"})\n\t\t\trb.SetStringEnumResourceAttrOne()\n\t\t\trb.SetStringResourceAttr(\"string.resource.attr-val\")\n\t\t\trb.SetStringResourceAttrDisableWarning(\"string.resource.attr_disable_warning-val\")\n\t\t\trb.SetStringResourceAttrRemoveWarning(\"string.resource.attr_remove_warning-val\")\n\t\t\trb.SetStringResourceAttrToBeRemoved(\"string.resource.attr_to_be_removed-val\")\n\n\t\t\tres := rb.Emit()\n\t\t\tassert.Equal(t, 0, rb.Emit().Attributes().Len()) // Second call should return empty Resource\n\n\t\t\tswitch tt {\n\t\t\tcase \"default\":\n\t\t\t\tassert.Equal(t, 6, res.Attributes().Len())\n\t\t\tcase \"all_set\":\n\t\t\t\tassert.Equal(t, 8, res.Attributes().Len())\n\t\t\tcase \"none_set\":\n\t\t\t\tassert.Equal(t, 0, res.Attributes().Len())\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tassert.Failf(t, \"unexpected test case: %s\", tt)\n\t\t\t}\n\n\t\t\tval, ok := res.Attributes().Get(\"map.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"}, val.Map().AsRaw())\n\t\t\t}\n\t\t\tval, ok = res.Attributes().Get(\"optional.resource.attr\")\n\t\t\tassert.Equal(t, tt == \"all_set\", ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"optional.resource.attr-val\", val.Str())\n\t\t\t}\n\t\t\tval, ok = res.Attributes().Get(\"slice.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, []any{\"slice.resource.attr-item1\", \"slice.resource.attr-item2\"}, val.Slice().AsRaw())\n\t\t\t}\n\t\t\tval, ok = res.Attributes().Get(\"string.enum.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"one\", val.Str())\n\t\t\t}\n\t\t\tval, ok = res.Attributes().Get(\"string.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr-val\", val.Str())\n\t\t\t}\n\t\t\tval, ok = res.Attributes().Get(\"string.resource.attr_disable_warning\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr_disable_warning-val\", val.Str())\n\t\t\t}\n\t\t\tval, ok = res.Attributes().Get(\"string.resource.attr_remove_warning\")\n\t\t\tassert.Equal(t, tt == \"all_set\", ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr_remove_warning-val\", val.Str())\n\t\t\t}\n\t\t\tval, ok = res.Attributes().Get(\"string.resource.attr_to_be_removed\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr_to_be_removed-val\", val.Str())\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"sample\")\n\tScopeName = \"go.opentelemetry.io/collector/internal/receiver/samplefactoryreceiver\"\n)\n\nconst (\n\tProfilesStability = component.StabilityLevelDeprecated\n\tLogsStability     = component.StabilityLevelDevelopment\n\tTracesStability   = component.StabilityLevelBeta\n\tMetricsStability  = component.StabilityLevelStable\n)\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/internal/metadata/generated_telemetry.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/metric/embedded\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc Meter(settings component.TelemetrySettings) metric.Meter {\n\treturn settings.MeterProvider.Meter(\"go.opentelemetry.io/collector/internal/receiver/samplefactoryreceiver\")\n}\n\nfunc Tracer(settings component.TelemetrySettings) trace.Tracer {\n\treturn settings.TracerProvider.Tracer(\"go.opentelemetry.io/collector/internal/receiver/samplefactoryreceiver\")\n}\n\n// TelemetryBuilder provides an interface for components to report telemetry\n// as defined in metadata and user config.\ntype TelemetryBuilder struct {\n\tmeter                         metric.Meter\n\tmu                            sync.Mutex\n\tregistrations                 []metric.Registration\n\tBatchSizeTriggerSend          metric.Int64Counter\n\tProcessRuntimeTotalAllocBytes metric.Int64ObservableCounter\n\tQueueCapacity                 metric.Int64Gauge\n\tQueueLength                   metric.Int64ObservableGauge\n\tRequestDuration               metric.Float64Histogram\n}\n\n// TelemetryBuilderOption applies changes to default builder.\ntype TelemetryBuilderOption interface {\n\tapply(*TelemetryBuilder)\n}\n\ntype telemetryBuilderOptionFunc func(mb *TelemetryBuilder)\n\nfunc (tbof telemetryBuilderOptionFunc) apply(mb *TelemetryBuilder) {\n\ttbof(mb)\n}\n\n// RegisterProcessRuntimeTotalAllocBytesCallback sets callback for observable ProcessRuntimeTotalAllocBytes metric.\nfunc (builder *TelemetryBuilder) RegisterProcessRuntimeTotalAllocBytesCallback(cb metric.Int64Callback) error {\n\treg, err := builder.meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {\n\t\tcb(ctx, &observerInt64{inst: builder.ProcessRuntimeTotalAllocBytes, obs: o})\n\t\treturn nil\n\t}, builder.ProcessRuntimeTotalAllocBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tbuilder.registrations = append(builder.registrations, reg)\n\treturn nil\n}\n\n// RegisterQueueLengthCallback sets callback for observable QueueLength metric.\nfunc (builder *TelemetryBuilder) RegisterQueueLengthCallback(cb metric.Int64Callback) error {\n\treg, err := builder.meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {\n\t\tcb(ctx, &observerInt64{inst: builder.QueueLength, obs: o})\n\t\treturn nil\n\t}, builder.QueueLength)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tbuilder.registrations = append(builder.registrations, reg)\n\treturn nil\n}\n\ntype observerInt64 struct {\n\tembedded.Int64Observer\n\tinst metric.Int64Observable\n\tobs  metric.Observer\n}\n\nfunc (oi *observerInt64) Observe(value int64, opts ...metric.ObserveOption) {\n\toi.obs.ObserveInt64(oi.inst, value, opts...)\n}\n\n// Shutdown unregister all registered callbacks for async instruments.\nfunc (builder *TelemetryBuilder) Shutdown() {\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tfor _, reg := range builder.registrations {\n\t\treg.Unregister()\n\t}\n}\n\n// NewTelemetryBuilder provides a struct with methods to update all internal telemetry\n// for a component\nfunc NewTelemetryBuilder(settings component.TelemetrySettings, options ...TelemetryBuilderOption) (*TelemetryBuilder, error) {\n\tbuilder := TelemetryBuilder{}\n\tfor _, op := range options {\n\t\top.apply(&builder)\n\t}\n\tbuilder.meter = Meter(settings)\n\tvar err, errs error\n\tbuilder.BatchSizeTriggerSend, err = builder.meter.Int64Counter(\n\t\t\"otelcol_batch_size_trigger_send\",\n\t\tmetric.WithDescription(\"Number of times the batch was sent due to a size trigger [deprecated since v0.110.0]\"),\n\t\tmetric.WithUnit(\"{times}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessRuntimeTotalAllocBytes, err = builder.meter.Int64ObservableCounter(\n\t\t\"otelcol_process_runtime_total_alloc_bytes\",\n\t\tmetric.WithDescription(\"Cumulative bytes allocated for heap objects (see 'go doc runtime.MemStats.TotalAlloc')\"),\n\t\tmetric.WithUnit(\"By\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.QueueCapacity, err = builder.meter.Int64Gauge(\n\t\t\"otelcol_queue_capacity\",\n\t\tmetric.WithDescription(\"Queue capacity - sync gauge example.\"),\n\t\tmetric.WithUnit(\"{items}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.QueueLength, err = builder.meter.Int64ObservableGauge(\n\t\t\"otelcol_queue_length\",\n\t\tmetric.WithDescription(\"This metric is optional and therefore not initialized in NewTelemetryBuilder. [Alpha]\"),\n\t\tmetric.WithUnit(\"{items}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.RequestDuration, err = builder.meter.Float64Histogram(\n\t\t\"otelcol_request_duration\",\n\t\tmetric.WithDescription(\"Duration of request [Alpha]\"),\n\t\tmetric.WithUnit(\"s\"),\n\t\tmetric.WithExplicitBucketBoundaries([]float64{1, 10, 100}...),\n\t)\n\terrs = errors.Join(errs, err)\n\treturn &builder, errs\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/internal/metadata/generated_telemetry_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/metric\"\n\tembeddedmetric \"go.opentelemetry.io/otel/metric/embedded\"\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\t\"go.opentelemetry.io/otel/trace\"\n\tembeddedtrace \"go.opentelemetry.io/otel/trace/embedded\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\ntype mockMeter struct {\n\tnoopmetric.Meter\n\tname string\n}\ntype mockMeterProvider struct {\n\tembeddedmetric.MeterProvider\n}\n\nfunc (m mockMeterProvider) Meter(name string, opts ...metric.MeterOption) metric.Meter {\n\treturn mockMeter{name: name}\n}\n\ntype mockTracer struct {\n\tnooptrace.Tracer\n\tname string\n}\n\ntype mockTracerProvider struct {\n\tembeddedtrace.TracerProvider\n}\n\nfunc (m mockTracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer {\n\treturn mockTracer{name: name}\n}\n\nfunc TestProviders(t *testing.T) {\n\tset := component.TelemetrySettings{\n\t\tMeterProvider:  mockMeterProvider{},\n\t\tTracerProvider: mockTracerProvider{},\n\t}\n\n\tmeter := Meter(set)\n\tif m, ok := meter.(mockMeter); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/internal/receiver/samplefactoryreceiver\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockMeter\")\n\t}\n\n\ttracer := Tracer(set)\n\tif m, ok := tracer.(mockTracer); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/internal/receiver/samplefactoryreceiver\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockTracer\")\n\t}\n}\n\nfunc TestNewTelemetryBuilder(t *testing.T) {\n\tset := componenttest.NewNopTelemetrySettings()\n\tapplied := false\n\t_, err := NewTelemetryBuilder(set, telemetryBuilderOptionFunc(func(b *TelemetryBuilder) {\n\t\tapplied = true\n\t}))\n\trequire.NoError(t, err)\n\trequire.True(t, applied)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/internal/metadata/testdata/config.yaml",
    "content": "default:\nall_set:\n  metrics:\n    default.metric:\n      enabled: true\n    default.metric.to_be_removed:\n      enabled: true\n    metric.input_type:\n      enabled: true\n    optional.metric:\n      enabled: true\n    optional.metric.empty_unit:\n      enabled: true\n  events:\n    default.event:\n      enabled: true\n    default.event.to_be_removed:\n      enabled: true\n    default.event.to_be_renamed:\n      enabled: true\n  resource_attributes:\n    map.resource.attr:\n      enabled: true\n    optional.resource.attr:\n      enabled: true\n    slice.resource.attr:\n      enabled: true\n    string.enum.resource.attr:\n      enabled: true\n    string.resource.attr:\n      enabled: true\n    string.resource.attr_disable_warning:\n      enabled: true\n    string.resource.attr_remove_warning:\n      enabled: true\n    string.resource.attr_to_be_removed:\n      enabled: true\nnone_set:\n  metrics:\n    default.metric:\n      enabled: false\n    default.metric.to_be_removed:\n      enabled: false\n    metric.input_type:\n      enabled: false\n    optional.metric:\n      enabled: false\n    optional.metric.empty_unit:\n      enabled: false\n  events:\n    default.event:\n      enabled: false\n    default.event.to_be_removed:\n      enabled: false\n    default.event.to_be_renamed:\n      enabled: false\n  resource_attributes:\n    map.resource.attr:\n      enabled: false\n    optional.resource.attr:\n      enabled: false\n    slice.resource.attr:\n      enabled: false\n    string.enum.resource.attr:\n      enabled: false\n    string.resource.attr:\n      enabled: false\n    string.resource.attr_disable_warning:\n      enabled: false\n    string.resource.attr_remove_warning:\n      enabled: false\n    string.resource.attr_to_be_removed:\n      enabled: false\nfilter_set_include:\n  resource_attributes:\n    map.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n      events_include:\n        - regexp: \".*\"\n    optional.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n      events_include:\n        - regexp: \".*\"\n    slice.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n      events_include:\n        - regexp: \".*\"\n    string.enum.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n      events_include:\n        - regexp: \".*\"\n    string.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n      events_include:\n        - regexp: \".*\"\n    string.resource.attr_disable_warning:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n      events_include:\n        - regexp: \".*\"\n    string.resource.attr_remove_warning:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n      events_include:\n        - regexp: \".*\"\n    string.resource.attr_to_be_removed:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n      events_include:\n        - regexp: \".*\"\nfilter_set_exclude:\n  resource_attributes:\n    map.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - regexp: \".*\"\n      events_exclude:\n        - regexp: \".*\"\n    optional.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - strict: \"optional.resource.attr-val\"\n      events_exclude:\n        - strict: \"optional.resource.attr-val\"\n    slice.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - regexp: \".*\"\n      events_exclude:\n        - regexp: \".*\"\n    string.enum.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - strict: \"one\"\n      events_exclude:\n        - strict: \"one\"\n    string.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - strict: \"string.resource.attr-val\"\n      events_exclude:\n        - strict: \"string.resource.attr-val\"\n    string.resource.attr_disable_warning:\n      enabled: true\n      metrics_exclude:\n        - strict: \"string.resource.attr_disable_warning-val\"\n      events_exclude:\n        - strict: \"string.resource.attr_disable_warning-val\"\n    string.resource.attr_remove_warning:\n      enabled: true\n      metrics_exclude:\n        - strict: \"string.resource.attr_remove_warning-val\"\n      events_exclude:\n        - strict: \"string.resource.attr_remove_warning-val\"\n    string.resource.attr_to_be_removed:\n      enabled: true\n      metrics_exclude:\n        - strict: \"string.resource.attr_to_be_removed-val\"\n      events_exclude:\n        - strict: \"string.resource.attr_to_be_removed-val\"\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplefactoryreceiver/metadata.yaml",
    "content": "# Sample metadata file with all available configurations for a receiver.\n\ntype: sample\ndisplay_name: Sample Factory Receiver\ndescription: This receiver is used for testing purposes to check the output of mdatagen.\nscope_name: go.opentelemetry.io/collector/internal/receiver/samplefactoryreceiver\ngithub_project: open-telemetry/opentelemetry-collector\n\nsem_conv_version: 1.9.0\n\nstatus:\n  disable_codecov_badge: true\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n    deprecated: [profiles]\n  deprecation:\n    profiles:\n      migration: \"no migration needed\"\n      date: \"2025-02-05\"\n  distributions: []\n  unsupported_platforms: [freebsd, illumos]\n  codeowners:\n    active: [dmitryax]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleprocessor/README.md",
    "content": "<!-- status autogenerated section -->\n# Sample Processor\n\nThis processor is used for testing purposes to check the output of mdatagen.\n\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [development]: logs, profiles   |\n|               | [beta]: traces   |\n|               | [stable]: metrics   |\n| Unsupported Platforms | freebsd, illumos |\n| Distributions | [] |\n| Warnings      | [Any additional information that should be brought to the consumer's attention](#warnings) |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Aprocessor%2Fsample%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Aprocessor%2Fsample) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Aprocessor%2Fsample%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Aprocessor%2Fsample) |\n| [Code Owners](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/CONTRIBUTING.md#becoming-a-code-owner)    |  |\n\n[development]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#development\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[stable]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stable\n<!-- end autogenerated section -->\n\n## Warnings\n\nThis is where warnings are described.\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleprocessor/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Generate a test metrics builder from a sample metrics set covering all configuration options.\n//go:generate mdatagen metadata.yaml\n\npackage sampleprocessor // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/sampleprocessor\"\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleprocessor/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# sample\n\n## Resource Attributes\n\n| Name | Description | Values | Enabled |\n| ---- | ----------- | ------ | ------- |\n| map.resource.attr | Resource attribute with a map value. | Any Map | true |\n| optional.resource.attr | Explicitly disabled ResourceAttribute. | Any Str | false |\n| slice.resource.attr | Resource attribute with a slice value. | Any Slice | true |\n| string.enum.resource.attr | Resource attribute with a known set of string values. | Str: ``one``, ``two`` | true |\n| string.resource.attr | Resource attribute with any string value. | Any Str | true |\n| string.resource.attr_disable_warning | Resource attribute with any string value. | Any Str | true |\n| string.resource.attr_remove_warning | Resource attribute with any string value. | Any Str | false |\n| string.resource.attr_to_be_removed | Resource attribute with any string value. | Any Str | true |\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleprocessor/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage sampleprocessor // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/sampleprocessor\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/sampleprocessor/internal/metadata\"\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/xprocessor\"\n)\n\n// NewFactory returns a receiver.Factory for sample receiver.\nfunc NewFactory() processor.Factory {\n\treturn xprocessor.NewFactory(\n\t\tmetadata.Type,\n\t\tfunc() component.Config { return &struct{}{} },\n\t\txprocessor.WithTraces(createTracesProcessor, metadata.TracesStability),\n\t\txprocessor.WithMetrics(createMetricsProcessor, metadata.MetricsStability),\n\t\txprocessor.WithLogs(createLogsProcessor, metadata.LogsStability),\n\t\txprocessor.WithProfiles(createProfilesProcessor, metadata.ProfilesStability),\n\t)\n}\n\nfunc createTracesProcessor(context.Context, processor.Settings, component.Config, consumer.Traces) (processor.Traces, error) {\n\treturn nopInstance, nil\n}\n\nfunc createMetricsProcessor(context.Context, processor.Settings, component.Config, consumer.Metrics) (processor.Metrics, error) {\n\treturn nopInstance, nil\n}\n\nfunc createLogsProcessor(context.Context, processor.Settings, component.Config, consumer.Logs) (processor.Logs, error) {\n\treturn nopInstance, nil\n}\n\nfunc createProfilesProcessor(context.Context, processor.Settings, component.Config, xconsumer.Profiles) (xprocessor.Profiles, error) {\n\treturn nopInstance, nil\n}\n\nvar nopInstance = &nopProcessor{}\n\ntype nopProcessor struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n}\n\nfunc (n nopProcessor) ConsumeTraces(context.Context, ptrace.Traces) error {\n\treturn nil\n}\n\nfunc (n nopProcessor) ConsumeLogs(context.Context, plog.Logs) error {\n\treturn nil\n}\n\nfunc (n nopProcessor) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: true}\n}\n\nfunc (n nopProcessor) ConsumeMetrics(context.Context, pmetric.Metrics) error {\n\treturn nil\n}\n\nfunc (n nopProcessor) ConsumeProfiles(context.Context, pprofile.Profiles) error {\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleprocessor/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n//go:build !freebsd && !illumos\n\npackage sampleprocessor\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n\t\"go.opentelemetry.io/collector/processor/xprocessor\"\n)\n\nvar typ = component.MustNewType(\"sample\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct {\n\t\tcreateFn func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error)\n\t\tname     string\n\t}{\n\n\t\t{\n\t\t\tname: \"logs\",\n\t\t\tcreateFn: func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateLogs(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"traces\",\n\t\t\tcreateFn: func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateTraces(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"profiles\",\n\t\t\tcreateFn: func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.(xprocessor.Factory).CreateProfiles(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name+\"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), processortest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\tt.Run(tt.name+\"-lifecycle\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), processortest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := newMdatagenNopHost()\n\t\t\terr = c.Start(context.Background(), host)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NotPanics(t, func() {\n\t\t\t\tswitch tt.name {\n\t\t\t\tcase \"logs\":\n\t\t\t\t\te, ok := c.(processor.Logs)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tlogs := generateLifecycleTestLogs()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tlogs.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeLogs(context.Background(), logs)\n\t\t\t\tcase \"metrics\":\n\t\t\t\t\te, ok := c.(processor.Metrics)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tmetrics := generateLifecycleTestMetrics()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tmetrics.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeMetrics(context.Background(), metrics)\n\t\t\t\tcase \"traces\":\n\t\t\t\t\te, ok := c.(processor.Traces)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\ttraces := generateLifecycleTestTraces()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\ttraces.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeTraces(context.Background(), traces)\n\t\t\t\t}\n\t\t\t})\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t}\n}\n\nfunc generateLifecycleTestLogs() plog.Logs {\n\tlogs := plog.NewLogs()\n\trl := logs.ResourceLogs().AppendEmpty()\n\trl.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tl := rl.ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\tl.Body().SetStr(\"test log message\")\n\tl.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn logs\n}\n\nfunc generateLifecycleTestMetrics() pmetric.Metrics {\n\tmetrics := pmetric.NewMetrics()\n\trm := metrics.ResourceMetrics().AppendEmpty()\n\trm.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tm := rm.ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\tm.SetName(\"test_metric\")\n\tdp := m.SetEmptyGauge().DataPoints().AppendEmpty()\n\tdp.Attributes().PutStr(\"test_attr\", \"value_1\")\n\tdp.SetIntValue(123)\n\tdp.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn metrics\n}\n\nfunc generateLifecycleTestTraces() ptrace.Traces {\n\ttraces := ptrace.NewTraces()\n\trs := traces.ResourceSpans().AppendEmpty()\n\trs.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tspan := rs.ScopeSpans().AppendEmpty().Spans().AppendEmpty()\n\tspan.Attributes().PutStr(\"test_attr\", \"value_1\")\n\tspan.SetName(\"test_span\")\n\tspan.SetStartTimestamp(pcommon.NewTimestampFromTime(time.Now().Add(-1 * time.Second)))\n\tspan.SetEndTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn traces\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleprocessor/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage sampleprocessor\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleprocessor/internal/metadata/config.schema.yaml",
    "content": "# Code generated by mdatagen. DO NOT EDIT.\n$defs:\n  resource_attributes_config:\n    description: ResourceAttributesConfig provides config for sample resource attributes.\n    type: object\n    properties:\n      map.resource.attr:\n        description: ResourceAttributeConfig provides common config for a map.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n      optional.resource.attr:\n        description: ResourceAttributeConfig provides common config for a optional.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: false\n      slice.resource.attr:\n        description: ResourceAttributeConfig provides common config for a slice.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n      string.enum.resource.attr:\n        description: ResourceAttributeConfig provides common config for a string.enum.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n      string.resource.attr:\n        description: ResourceAttributeConfig provides common config for a string.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n      string.resource.attr_disable_warning:\n        description: ResourceAttributeConfig provides common config for a string.resource.attr_disable_warning resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n      string.resource.attr_remove_warning:\n        description: ResourceAttributeConfig provides common config for a string.resource.attr_remove_warning resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: false\n      string.resource.attr_to_be_removed:\n        description: ResourceAttributeConfig provides common config for a string.resource.attr_to_be_removed resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleprocessor/internal/metadata/generated_config.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\n// ResourceAttributeConfig provides common config for a particular resource attribute.\ntype ResourceAttributeConfig struct {\n\tEnabled bool `mapstructure:\"enabled\"`\n\n\tenabledSetByUser bool\n}\n\nfunc (rac *ResourceAttributeConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\terr := parser.Unmarshal(rac)\n\tif err != nil {\n\t\treturn err\n\t}\n\trac.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\n// ResourceAttributesConfig provides config for sample resource attributes.\ntype ResourceAttributesConfig struct {\n\tMapResourceAttr                  ResourceAttributeConfig `mapstructure:\"map.resource.attr\"`\n\tOptionalResourceAttr             ResourceAttributeConfig `mapstructure:\"optional.resource.attr\"`\n\tSliceResourceAttr                ResourceAttributeConfig `mapstructure:\"slice.resource.attr\"`\n\tStringEnumResourceAttr           ResourceAttributeConfig `mapstructure:\"string.enum.resource.attr\"`\n\tStringResourceAttr               ResourceAttributeConfig `mapstructure:\"string.resource.attr\"`\n\tStringResourceAttrDisableWarning ResourceAttributeConfig `mapstructure:\"string.resource.attr_disable_warning\"`\n\tStringResourceAttrRemoveWarning  ResourceAttributeConfig `mapstructure:\"string.resource.attr_remove_warning\"`\n\tStringResourceAttrToBeRemoved    ResourceAttributeConfig `mapstructure:\"string.resource.attr_to_be_removed\"`\n}\n\nfunc DefaultResourceAttributesConfig() ResourceAttributesConfig {\n\treturn ResourceAttributesConfig{\n\t\tMapResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tOptionalResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: false,\n\t\t},\n\t\tSliceResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringEnumResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringResourceAttrRemoveWarning: ResourceAttributeConfig{\n\t\t\tEnabled: false,\n\t\t},\n\t\tStringResourceAttrToBeRemoved: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleprocessor/internal/metadata/generated_config_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n\t\"github.com/google/go-cmp/cmp/cmpopts\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n)\n\nfunc TestResourceAttributesConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant ResourceAttributesConfig\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\twant: DefaultResourceAttributesConfig(),\n\t\t},\n\t\t{\n\t\t\tname: \"all_set\",\n\t\t\twant: ResourceAttributesConfig{\n\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: true},\n\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: true},\n\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: true},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"none_set\",\n\t\t\twant: ResourceAttributesConfig{\n\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: false},\n\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: false},\n\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: false},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := loadResourceAttributesConfig(t, tt.name)\n\t\t\tdiff := cmp.Diff(tt.want, cfg, cmpopts.IgnoreUnexported(ResourceAttributeConfig{}))\n\t\t\trequire.Emptyf(t, diff, \"Config mismatch (-expected +actual):\\n%s\", diff)\n\t\t})\n\t}\n}\n\nfunc loadResourceAttributesConfig(t *testing.T, name string) ResourceAttributesConfig {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tsub, err := cm.Sub(name)\n\trequire.NoError(t, err)\n\tsub, err = sub.Sub(\"resource_attributes\")\n\trequire.NoError(t, err)\n\tcfg := DefaultResourceAttributesConfig()\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\treturn cfg\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleprocessor/internal/metadata/generated_resource.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ResourceBuilder is a helper struct to build resources predefined in metadata.yaml.\n// The ResourceBuilder is not thread-safe and must not to be used in multiple goroutines.\ntype ResourceBuilder struct {\n\tconfig ResourceAttributesConfig\n\tres    pcommon.Resource\n}\n\n// NewResourceBuilder creates a new ResourceBuilder. This method should be called on the start of the application.\nfunc NewResourceBuilder(rac ResourceAttributesConfig) *ResourceBuilder {\n\treturn &ResourceBuilder{\n\t\tconfig: rac,\n\t\tres:    pcommon.NewResource(),\n\t}\n}\n\n// SetMapResourceAttr sets provided value as \"map.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetMapResourceAttr(val map[string]any) {\n\tif rb.config.MapResourceAttr.Enabled {\n\t\trb.res.Attributes().PutEmptyMap(\"map.resource.attr\").FromRaw(val)\n\t}\n}\n\n// SetOptionalResourceAttr sets provided value as \"optional.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetOptionalResourceAttr(val string) {\n\tif rb.config.OptionalResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"optional.resource.attr\", val)\n\t}\n}\n\n// SetSliceResourceAttr sets provided value as \"slice.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetSliceResourceAttr(val []any) {\n\tif rb.config.SliceResourceAttr.Enabled {\n\t\trb.res.Attributes().PutEmptySlice(\"slice.resource.attr\").FromRaw(val)\n\t}\n}\n\n// SetStringEnumResourceAttrOne sets \"string.enum.resource.attr=one\" attribute.\nfunc (rb *ResourceBuilder) SetStringEnumResourceAttrOne() {\n\tif rb.config.StringEnumResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.enum.resource.attr\", \"one\")\n\t}\n}\n\n// SetStringEnumResourceAttrTwo sets \"string.enum.resource.attr=two\" attribute.\nfunc (rb *ResourceBuilder) SetStringEnumResourceAttrTwo() {\n\tif rb.config.StringEnumResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.enum.resource.attr\", \"two\")\n\t}\n}\n\n// SetStringResourceAttr sets provided value as \"string.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttr(val string) {\n\tif rb.config.StringResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr\", val)\n\t}\n}\n\n// SetStringResourceAttrDisableWarning sets provided value as \"string.resource.attr_disable_warning\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttrDisableWarning(val string) {\n\tif rb.config.StringResourceAttrDisableWarning.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr_disable_warning\", val)\n\t}\n}\n\n// SetStringResourceAttrRemoveWarning sets provided value as \"string.resource.attr_remove_warning\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttrRemoveWarning(val string) {\n\tif rb.config.StringResourceAttrRemoveWarning.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr_remove_warning\", val)\n\t}\n}\n\n// SetStringResourceAttrToBeRemoved sets provided value as \"string.resource.attr_to_be_removed\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttrToBeRemoved(val string) {\n\tif rb.config.StringResourceAttrToBeRemoved.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr_to_be_removed\", val)\n\t}\n}\n\n// Emit returns the built resource and resets the internal builder state.\nfunc (rb *ResourceBuilder) Emit() pcommon.Resource {\n\tr := rb.res\n\trb.res = pcommon.NewResource()\n\treturn r\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleprocessor/internal/metadata/generated_resource_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestResourceBuilder(t *testing.T) {\n\tfor _, tt := range []string{\"default\", \"all_set\", \"none_set\"} {\n\t\tt.Run(tt, func(t *testing.T) {\n\t\t\tcfg := loadResourceAttributesConfig(t, tt)\n\t\t\trb := NewResourceBuilder(cfg)\n\t\t\trb.SetMapResourceAttr(map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"})\n\t\t\trb.SetOptionalResourceAttr(\"optional.resource.attr-val\")\n\t\t\trb.SetSliceResourceAttr([]any{\"slice.resource.attr-item1\", \"slice.resource.attr-item2\"})\n\t\t\trb.SetStringEnumResourceAttrOne()\n\t\t\trb.SetStringResourceAttr(\"string.resource.attr-val\")\n\t\t\trb.SetStringResourceAttrDisableWarning(\"string.resource.attr_disable_warning-val\")\n\t\t\trb.SetStringResourceAttrRemoveWarning(\"string.resource.attr_remove_warning-val\")\n\t\t\trb.SetStringResourceAttrToBeRemoved(\"string.resource.attr_to_be_removed-val\")\n\n\t\t\tres := rb.Emit()\n\t\t\tassert.Equal(t, 0, rb.Emit().Attributes().Len()) // Second call should return empty Resource\n\n\t\t\tswitch tt {\n\t\t\tcase \"default\":\n\t\t\t\tassert.Equal(t, 6, res.Attributes().Len())\n\t\t\tcase \"all_set\":\n\t\t\t\tassert.Equal(t, 8, res.Attributes().Len())\n\t\t\tcase \"none_set\":\n\t\t\t\tassert.Equal(t, 0, res.Attributes().Len())\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tassert.Failf(t, \"unexpected test case: %s\", tt)\n\t\t\t}\n\t\t\tmapResourceAttrAttrVal, ok := res.Attributes().Get(\"map.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"}, mapResourceAttrAttrVal.Map().AsRaw())\n\t\t\t}\n\t\t\toptionalResourceAttrAttrVal, ok := res.Attributes().Get(\"optional.resource.attr\")\n\t\t\tassert.Equal(t, tt == \"all_set\", ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"optional.resource.attr-val\", optionalResourceAttrAttrVal.Str())\n\t\t\t}\n\t\t\tsliceResourceAttrAttrVal, ok := res.Attributes().Get(\"slice.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, []any{\"slice.resource.attr-item1\", \"slice.resource.attr-item2\"}, sliceResourceAttrAttrVal.Slice().AsRaw())\n\t\t\t}\n\t\t\tstringEnumResourceAttrAttrVal, ok := res.Attributes().Get(\"string.enum.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"one\", stringEnumResourceAttrAttrVal.Str())\n\t\t\t}\n\t\t\tstringResourceAttrAttrVal, ok := res.Attributes().Get(\"string.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr-val\", stringResourceAttrAttrVal.Str())\n\t\t\t}\n\t\t\tstringResourceAttrDisableWarningAttrVal, ok := res.Attributes().Get(\"string.resource.attr_disable_warning\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr_disable_warning-val\", stringResourceAttrDisableWarningAttrVal.Str())\n\t\t\t}\n\t\t\tstringResourceAttrRemoveWarningAttrVal, ok := res.Attributes().Get(\"string.resource.attr_remove_warning\")\n\t\t\tassert.Equal(t, tt == \"all_set\", ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr_remove_warning-val\", stringResourceAttrRemoveWarningAttrVal.Str())\n\t\t\t}\n\t\t\tstringResourceAttrToBeRemovedAttrVal, ok := res.Attributes().Get(\"string.resource.attr_to_be_removed\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr_to_be_removed-val\", stringResourceAttrToBeRemovedAttrVal.Str())\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleprocessor/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"sample\")\n\tScopeName = \"go.opentelemetry.io/collector/internal/receiver/samplereceiver\"\n)\n\nconst (\n\tLogsStability     = component.StabilityLevelDevelopment\n\tProfilesStability = component.StabilityLevelDevelopment\n\tTracesStability   = component.StabilityLevelBeta\n\tMetricsStability  = component.StabilityLevelStable\n)\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleprocessor/internal/metadata/testdata/config.yaml",
    "content": "default:\nall_set:\n  resource_attributes:\n    map.resource.attr:\n      enabled: true\n    optional.resource.attr:\n      enabled: true\n    slice.resource.attr:\n      enabled: true\n    string.enum.resource.attr:\n      enabled: true\n    string.resource.attr:\n      enabled: true\n    string.resource.attr_disable_warning:\n      enabled: true\n    string.resource.attr_remove_warning:\n      enabled: true\n    string.resource.attr_to_be_removed:\n      enabled: true\nreaggregate_set:\n  resource_attributes:\n    map.resource.attr:\n      enabled: true\n    optional.resource.attr:\n      enabled: true\n    slice.resource.attr:\n      enabled: true\n    string.enum.resource.attr:\n      enabled: true\n    string.resource.attr:\n      enabled: true\n    string.resource.attr_disable_warning:\n      enabled: true\n    string.resource.attr_remove_warning:\n      enabled: true\n    string.resource.attr_to_be_removed:\n      enabled: true\nnone_set:\n  resource_attributes:\n    map.resource.attr:\n      enabled: false\n    optional.resource.attr:\n      enabled: false\n    slice.resource.attr:\n      enabled: false\n    string.enum.resource.attr:\n      enabled: false\n    string.resource.attr:\n      enabled: false\n    string.resource.attr_disable_warning:\n      enabled: false\n    string.resource.attr_remove_warning:\n      enabled: false\n    string.resource.attr_to_be_removed:\n      enabled: false\n"
  },
  {
    "path": "cmd/mdatagen/internal/sampleprocessor/metadata.yaml",
    "content": "# Sample metadata file with all available configurations for a processor.\n\ntype: sample\ndisplay_name: Sample Processor\ndescription: This processor is used for testing purposes to check the output of mdatagen.\nreaggregation_enabled: true\nscope_name: go.opentelemetry.io/collector/internal/receiver/samplereceiver\ngithub_project: open-telemetry/opentelemetry-collector\n\nsem_conv_version: 1.9.0\n\nstatus:\n  disable_codecov_badge: true\n  class: processor\n  stability:\n    development: [logs, profiles]\n    beta: [traces]\n    stable: [metrics]\n  distributions: []\n  unsupported_platforms: [freebsd, illumos]\n  codeowners:\n    active: []\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nresource_attributes:\n  map.resource.attr:\n    description: Resource attribute with a map value.\n    type: map\n    enabled: true\n\n  optional.resource.attr:\n    description: Explicitly disabled ResourceAttribute.\n    type: string\n    enabled: false\n\n  slice.resource.attr:\n    description: Resource attribute with a slice value.\n    type: slice\n    enabled: true\n\n  string.enum.resource.attr:\n    description: Resource attribute with a known set of string values.\n    type: string\n    enum: [one, two]\n    enabled: true\n\n  string.resource.attr:\n    description: Resource attribute with any string value.\n    type: string\n    enabled: true\n\n  string.resource.attr_disable_warning:\n    description: Resource attribute with any string value.\n    type: string\n    enabled: true\n    warnings:\n      if_enabled_not_set: This resource_attribute will be disabled by default soon.\n\n  string.resource.attr_remove_warning:\n    description: Resource attribute with any string value.\n    type: string\n    enabled: false\n    warnings:\n      if_configured: This resource_attribute is deprecated and will be removed soon.\n\n  string.resource.attr_to_be_removed:\n    description: Resource attribute with any string value.\n    type: string\n    enabled: true\n    warnings:\n      if_enabled: This resource_attribute is deprecated and will be removed soon.\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/README.md",
    "content": "<!-- status autogenerated section -->\n# Sample Receiver\n\nThis receiver is used for testing purposes to check the output of mdatagen.\n\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [deprecated]: profiles   |\n|               | [development]: logs   |\n|               | [beta]: traces   |\n|               | [stable]: metrics   |\n| Deprecation of profiles | [Date]: 2025-02-05   |\n|                      | [Migration Note]: no migration needed   |\n| Unsupported Platforms | freebsd, illumos |\n| Distributions | [] |\n| Warnings      | [Any additional information that should be brought to the consumer's attention](#warnings) |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Areceiver%2Fsample%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Areceiver%2Fsample) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Areceiver%2Fsample%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Areceiver%2Fsample) |\n| [Code Owners](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/CONTRIBUTING.md#becoming-a-code-owner)    | [@dmitryax](https://www.github.com/dmitryax) |\n\n[deprecated]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#deprecated\n[development]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#development\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[stable]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stable\n[Date]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#deprecation-information\n[Migration Note]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#deprecation-information\n<!-- end autogenerated section -->\n\n## Warnings\n\nThis is where warnings are described.\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/config.schema.json",
    "content": "{\n  \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n  \"$id\": \"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplereceiver\",\n  \"title\": \"receiver/sample\",\n  \"type\": \"object\",\n  \"allOf\": [\n    {\n      \"description\": \"MetricsBuilderConfig is a configuration for sample metrics builder.\",\n      \"type\": \"object\",\n      \"properties\": {\n        \"metrics\": {\n          \"description\": \"MetricsConfig provides config for sample metrics.\",\n          \"type\": \"object\",\n          \"properties\": {\n            \"default.metric\": {\n              \"description\": \"DefaultMetricMetricConfig provides config for the default.metric metric.\",\n              \"type\": \"object\",\n              \"properties\": {\n                \"aggregation_strategy\": {\n                  \"type\": \"string\",\n                  \"default\": \"sum\",\n                  \"enum\": [\n                    \"sum\",\n                    \"avg\",\n                    \"min\",\n                    \"max\"\n                  ]\n                },\n                \"attributes\": {\n                  \"type\": \"array\",\n                  \"default\": [\n                    \"string_attr\",\n                    \"state\",\n                    \"enum_attr\",\n                    \"slice_attr\",\n                    \"map_attr\",\n                    \"conditional_int_attr\",\n                    \"conditional_string_attr\"\n                  ],\n                  \"items\": {\n                    \"type\": \"string\",\n                    \"enum\": [\n                      \"string_attr\",\n                      \"state\",\n                      \"enum_attr\",\n                      \"slice_attr\",\n                      \"map_attr\",\n                      \"conditional_int_attr\",\n                      \"conditional_string_attr\",\n                      \"opt_in_bool_attr\"\n                    ]\n                  }\n                },\n                \"enabled\": {\n                  \"type\": \"boolean\",\n                  \"default\": true\n                }\n              }\n            },\n            \"default.metric.to_be_removed\": {\n              \"description\": \"DefaultMetricToBeRemovedMetricConfig provides config for the default.metric.to_be_removed metric.\",\n              \"type\": \"object\",\n              \"properties\": {\n                \"enabled\": {\n                  \"type\": \"boolean\",\n                  \"default\": true\n                }\n              }\n            },\n            \"metric.input_type\": {\n              \"description\": \"MetricInputTypeMetricConfig provides config for the metric.input_type metric.\",\n              \"type\": \"object\",\n              \"properties\": {\n                \"aggregation_strategy\": {\n                  \"type\": \"string\",\n                  \"default\": \"sum\",\n                  \"enum\": [\n                    \"sum\",\n                    \"avg\",\n                    \"min\",\n                    \"max\"\n                  ]\n                },\n                \"attributes\": {\n                  \"type\": \"array\",\n                  \"default\": [\n                    \"string_attr\",\n                    \"state\",\n                    \"enum_attr\",\n                    \"slice_attr\",\n                    \"map_attr\"\n                  ],\n                  \"items\": {\n                    \"type\": \"string\",\n                    \"enum\": [\n                      \"string_attr\",\n                      \"state\",\n                      \"enum_attr\",\n                      \"slice_attr\",\n                      \"map_attr\"\n                    ]\n                  }\n                },\n                \"enabled\": {\n                  \"type\": \"boolean\",\n                  \"default\": true\n                }\n              }\n            },\n            \"optional.metric\": {\n              \"description\": \"OptionalMetricMetricConfig provides config for the optional.metric metric.\",\n              \"type\": \"object\",\n              \"properties\": {\n                \"aggregation_strategy\": {\n                  \"type\": \"string\",\n                  \"default\": \"avg\",\n                  \"enum\": [\n                    \"sum\",\n                    \"avg\",\n                    \"min\",\n                    \"max\"\n                  ]\n                },\n                \"attributes\": {\n                  \"type\": \"array\",\n                  \"default\": [\n                    \"string_attr\",\n                    \"boolean_attr\",\n                    \"boolean_attr2\",\n                    \"conditional_string_attr\"\n                  ],\n                  \"items\": {\n                    \"type\": \"string\",\n                    \"enum\": [\n                      \"string_attr\",\n                      \"boolean_attr\",\n                      \"boolean_attr2\",\n                      \"conditional_string_attr\"\n                    ]\n                  }\n                },\n                \"enabled\": {\n                  \"type\": \"boolean\",\n                  \"default\": false\n                }\n              }\n            },\n            \"optional.metric.empty_unit\": {\n              \"description\": \"OptionalMetricEmptyUnitMetricConfig provides config for the optional.metric.empty_unit metric.\",\n              \"type\": \"object\",\n              \"properties\": {\n                \"aggregation_strategy\": {\n                  \"type\": \"string\",\n                  \"default\": \"avg\",\n                  \"enum\": [\n                    \"sum\",\n                    \"avg\",\n                    \"min\",\n                    \"max\"\n                  ]\n                },\n                \"attributes\": {\n                  \"type\": \"array\",\n                  \"default\": [\n                    \"string_attr\",\n                    \"boolean_attr\"\n                  ],\n                  \"items\": {\n                    \"type\": \"string\",\n                    \"enum\": [\n                      \"string_attr\",\n                      \"boolean_attr\"\n                    ]\n                  }\n                },\n                \"enabled\": {\n                  \"type\": \"boolean\",\n                  \"default\": false\n                }\n              }\n            },\n            \"reaggregate.metric\": {\n              \"description\": \"ReaggregateMetricMetricConfig provides config for the reaggregate.metric metric.\",\n              \"type\": \"object\",\n              \"properties\": {\n                \"aggregation_strategy\": {\n                  \"type\": \"string\",\n                  \"default\": \"avg\",\n                  \"enum\": [\n                    \"sum\",\n                    \"avg\",\n                    \"min\",\n                    \"max\"\n                  ]\n                },\n                \"attributes\": {\n                  \"type\": \"array\",\n                  \"default\": [\n                    \"string_attr\",\n                    \"boolean_attr\"\n                  ],\n                  \"items\": {\n                    \"type\": \"string\",\n                    \"enum\": [\n                      \"string_attr\",\n                      \"boolean_attr\"\n                    ]\n                  }\n                },\n                \"enabled\": {\n                  \"type\": \"boolean\",\n                  \"default\": true\n                }\n              }\n            },\n            \"reaggregate.metric.with_required\": {\n              \"description\": \"ReaggregateMetricWithRequiredMetricConfig provides config for the reaggregate.metric.with_required metric.\",\n              \"type\": \"object\",\n              \"properties\": {\n                \"aggregation_strategy\": {\n                  \"type\": \"string\",\n                  \"default\": \"avg\",\n                  \"enum\": [\n                    \"sum\",\n                    \"avg\",\n                    \"min\",\n                    \"max\"\n                  ]\n                },\n                \"attributes\": {\n                  \"type\": \"array\",\n                  \"default\": [\n                    \"required_string_attr\",\n                    \"string_attr\",\n                    \"boolean_attr\"\n                  ],\n                  \"items\": {\n                    \"type\": \"string\",\n                    \"enum\": [\n                      \"required_string_attr\",\n                      \"string_attr\",\n                      \"boolean_attr\"\n                    ]\n                  }\n                },\n                \"enabled\": {\n                  \"type\": \"boolean\",\n                  \"default\": true\n                }\n              }\n            },\n            \"system.cpu.time\": {\n              \"description\": \"SystemCPUTimeMetricConfig provides config for the system.cpu.time metric.\",\n              \"type\": \"object\",\n              \"properties\": {\n                \"enabled\": {\n                  \"type\": \"boolean\",\n                  \"default\": true\n                }\n              }\n            }\n          }\n        },\n        \"resource_attributes\": {\n          \"description\": \"ResourceAttributesConfig provides config for sample resource attributes.\",\n          \"type\": \"object\",\n          \"properties\": {\n            \"map.resource.attr\": {\n              \"description\": \"ResourceAttributeConfig provides common config for a map.resource.attr resource attribute.\",\n              \"type\": \"object\",\n              \"properties\": {\n                \"enabled\": {\n                  \"type\": \"boolean\",\n                  \"default\": true\n                },\n                \"events_exclude\": {\n                  \"description\": \"Experimental: EventsExclude defines a list of filters for attribute values. If the list is not empty, events with matching resource attribute values will not be emitted. EventsInclude has higher priority than EventsExclude.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"events_include\": {\n                  \"description\": \"Experimental: EventsInclude defines a list of filters for attribute values. If the list is not empty, only events with matching resource attribute values will be emitted.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"metrics_exclude\": {\n                  \"description\": \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"metrics_include\": {\n                  \"description\": \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                }\n              }\n            },\n            \"optional.resource.attr\": {\n              \"description\": \"ResourceAttributeConfig provides common config for a optional.resource.attr resource attribute.\",\n              \"type\": \"object\",\n              \"properties\": {\n                \"enabled\": {\n                  \"type\": \"boolean\",\n                  \"default\": false\n                },\n                \"events_exclude\": {\n                  \"description\": \"Experimental: EventsExclude defines a list of filters for attribute values. If the list is not empty, events with matching resource attribute values will not be emitted. EventsInclude has higher priority than EventsExclude.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"events_include\": {\n                  \"description\": \"Experimental: EventsInclude defines a list of filters for attribute values. If the list is not empty, only events with matching resource attribute values will be emitted.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"metrics_exclude\": {\n                  \"description\": \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"metrics_include\": {\n                  \"description\": \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                }\n              }\n            },\n            \"slice.resource.attr\": {\n              \"description\": \"ResourceAttributeConfig provides common config for a slice.resource.attr resource attribute.\",\n              \"type\": \"object\",\n              \"properties\": {\n                \"enabled\": {\n                  \"type\": \"boolean\",\n                  \"default\": true\n                },\n                \"events_exclude\": {\n                  \"description\": \"Experimental: EventsExclude defines a list of filters for attribute values. If the list is not empty, events with matching resource attribute values will not be emitted. EventsInclude has higher priority than EventsExclude.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"events_include\": {\n                  \"description\": \"Experimental: EventsInclude defines a list of filters for attribute values. If the list is not empty, only events with matching resource attribute values will be emitted.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"metrics_exclude\": {\n                  \"description\": \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"metrics_include\": {\n                  \"description\": \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                }\n              }\n            },\n            \"string.enum.resource.attr\": {\n              \"description\": \"ResourceAttributeConfig provides common config for a string.enum.resource.attr resource attribute.\",\n              \"type\": \"object\",\n              \"properties\": {\n                \"enabled\": {\n                  \"type\": \"boolean\",\n                  \"default\": true\n                },\n                \"events_exclude\": {\n                  \"description\": \"Experimental: EventsExclude defines a list of filters for attribute values. If the list is not empty, events with matching resource attribute values will not be emitted. EventsInclude has higher priority than EventsExclude.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"events_include\": {\n                  \"description\": \"Experimental: EventsInclude defines a list of filters for attribute values. If the list is not empty, only events with matching resource attribute values will be emitted.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"metrics_exclude\": {\n                  \"description\": \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"metrics_include\": {\n                  \"description\": \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                }\n              }\n            },\n            \"string.resource.attr\": {\n              \"description\": \"ResourceAttributeConfig provides common config for a string.resource.attr resource attribute.\",\n              \"type\": \"object\",\n              \"properties\": {\n                \"enabled\": {\n                  \"type\": \"boolean\",\n                  \"default\": true\n                },\n                \"events_exclude\": {\n                  \"description\": \"Experimental: EventsExclude defines a list of filters for attribute values. If the list is not empty, events with matching resource attribute values will not be emitted. EventsInclude has higher priority than EventsExclude.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"events_include\": {\n                  \"description\": \"Experimental: EventsInclude defines a list of filters for attribute values. If the list is not empty, only events with matching resource attribute values will be emitted.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"metrics_exclude\": {\n                  \"description\": \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"metrics_include\": {\n                  \"description\": \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                }\n              }\n            },\n            \"string.resource.attr_disable_warning\": {\n              \"description\": \"ResourceAttributeConfig provides common config for a string.resource.attr_disable_warning resource attribute.\",\n              \"type\": \"object\",\n              \"properties\": {\n                \"enabled\": {\n                  \"type\": \"boolean\",\n                  \"default\": true\n                },\n                \"events_exclude\": {\n                  \"description\": \"Experimental: EventsExclude defines a list of filters for attribute values. If the list is not empty, events with matching resource attribute values will not be emitted. EventsInclude has higher priority than EventsExclude.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"events_include\": {\n                  \"description\": \"Experimental: EventsInclude defines a list of filters for attribute values. If the list is not empty, only events with matching resource attribute values will be emitted.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"metrics_exclude\": {\n                  \"description\": \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"metrics_include\": {\n                  \"description\": \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                }\n              }\n            },\n            \"string.resource.attr_remove_warning\": {\n              \"description\": \"ResourceAttributeConfig provides common config for a string.resource.attr_remove_warning resource attribute.\",\n              \"type\": \"object\",\n              \"properties\": {\n                \"enabled\": {\n                  \"type\": \"boolean\",\n                  \"default\": false\n                },\n                \"events_exclude\": {\n                  \"description\": \"Experimental: EventsExclude defines a list of filters for attribute values. If the list is not empty, events with matching resource attribute values will not be emitted. EventsInclude has higher priority than EventsExclude.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"events_include\": {\n                  \"description\": \"Experimental: EventsInclude defines a list of filters for attribute values. If the list is not empty, only events with matching resource attribute values will be emitted.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"metrics_exclude\": {\n                  \"description\": \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"metrics_include\": {\n                  \"description\": \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                }\n              }\n            },\n            \"string.resource.attr_to_be_removed\": {\n              \"description\": \"ResourceAttributeConfig provides common config for a string.resource.attr_to_be_removed resource attribute.\",\n              \"type\": \"object\",\n              \"properties\": {\n                \"enabled\": {\n                  \"type\": \"boolean\",\n                  \"default\": true\n                },\n                \"events_exclude\": {\n                  \"description\": \"Experimental: EventsExclude defines a list of filters for attribute values. If the list is not empty, events with matching resource attribute values will not be emitted. EventsInclude has higher priority than EventsExclude.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"events_include\": {\n                  \"description\": \"Experimental: EventsInclude defines a list of filters for attribute values. If the list is not empty, only events with matching resource attribute values will be emitted.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"metrics_exclude\": {\n                  \"description\": \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                },\n                \"metrics_include\": {\n                  \"description\": \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\",\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"description\": \"Config configures the matching behavior of a Filter.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"regexp\": {\n                        \"type\": \"string\"\n                      },\n                      \"strict\": {\n                        \"type\": \"string\"\n                      }\n                    }\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  ],\n  \"properties\": {\n    \"endpoint\": {\n      \"description\": \"The endpoint to scrape metrics from.\",\n      \"type\": \"string\",\n      \"default\": \"localhost:12345\"\n    },\n    \"timeout\": {\n      \"description\": \"Timeout for scraping metrics. (duration format, e.g., \\\"30s\\\", \\\"1h30m\\\")\",\n      \"type\": \"string\",\n      \"default\": \"10s\",\n      \"pattern\": \"^([0-9]+(\\\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$\"\n    }\n  },\n  \"required\": [\n    \"endpoint\"\n  ]\n}"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Generate a test metrics builder from a sample metrics set covering all configuration options.\n//go:generate mdatagen metadata.yaml\n\npackage samplereceiver // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplereceiver\"\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# sample\n\n## Default Metrics\n\nThe following metrics are emitted by default. Each of them can be disabled by applying the following configuration:\n\n```yaml\nmetrics:\n  <metric_name>:\n    enabled: false\n```\n\n### default.metric\n\nMonotonic cumulative sum int metric enabled by default.\n\nThe metric will be become optional soon.\n\n| Unit | Metric Type | Value Type | Aggregation Temporality | Monotonic | Stability |\n| ---- | ----------- | ---------- | ----------------------- | --------- | --------- |\n| s | Sum | Int | Cumulative | true | Deprecated since 1.0.0 |\n\n**Deprecation note**: This metric will be removed\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | Recommended |\n| state | Integer attribute with overridden name. | Any Int | Recommended |\n| enum_attr | Attribute with a known set of string values. | Str: ``red``, ``green``, ``blue`` | Recommended |\n| slice_attr | Attribute with a slice value. | Any Slice | Recommended |\n| map_attr | Attribute with a map value. | Any Map | Recommended |\n| conditional_int_attr | A conditional attribute with an integer value | Any Int | Conditionally Required |\n| conditional_string_attr | A conditional attribute with any string value | Any Str | Conditionally Required |\n| opt_in_bool_attr | An opt-in attribute with a boolean value | Any Bool | Opt-In |\n\n### default.metric.to_be_removed\n\n[DEPRECATED] Non-monotonic delta sum double metric enabled by default.\n\nThe metric will be removed soon.\n\n| Unit | Metric Type | Value Type | Aggregation Temporality | Monotonic | Stability |\n| ---- | ----------- | ---------- | ----------------------- | --------- | --------- |\n| s | Sum | Double | Delta | false | Deprecated since 1.0.0 |\n\n**Deprecation note**: This metric will be removed\n\n### metric.input_type\n\nMonotonic cumulative sum int metric with string input_type enabled by default.\n\n| Unit | Metric Type | Value Type | Aggregation Temporality | Monotonic | Stability |\n| ---- | ----------- | ---------- | ----------------------- | --------- | --------- |\n| s | Sum | Int | Cumulative | true | Development |\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | Recommended |\n| state | Integer attribute with overridden name. | Any Int | Recommended |\n| enum_attr | Attribute with a known set of string values. | Str: ``red``, ``green``, ``blue`` | Recommended |\n| slice_attr | Attribute with a slice value. | Any Slice | Recommended |\n| map_attr | Attribute with a map value. | Any Map | Recommended |\n\n### reaggregate.metric\n\nMetric for testing spatial reaggregation\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| 1 | Gauge | Double | Beta |\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | Recommended |\n| boolean_attr | Attribute with a boolean value. | Any Bool | Recommended |\n\n### reaggregate.metric.with_required\n\nMetric for testing spatial reaggregation with required attributes\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| 1 | Gauge | Double | Beta |\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n| required_string_attr | A required attribute with a string value | Any Str | Required |\n| string_attr | Attribute with any string value. | Any Str | Recommended |\n| boolean_attr | Attribute with a boolean value. | Any Bool | Recommended |\n\n### system.cpu.time\n\nMonotonic cumulative sum int metric enabled by default.\n\nThe metric will be become optional soon.\n\n| Unit | Metric Type | Value Type | Aggregation Temporality | Monotonic | Stability | Semantic Convention |\n| ---- | ----------- | ---------- | ----------------------- | --------- | --------- | ------------------- |\n| s | Sum | Int | Cumulative | true | Beta | [system.cpu.time](https://github.com/open-telemetry/semantic-conventions/blob/v1.38.0/docs/system/system-metrics.md#metric-systemcputime) |\n\n## Optional Metrics\n\nThe following metrics are not emitted by default. Each of them can be enabled by applying the following configuration:\n\n```yaml\nmetrics:\n  <metric_name>:\n    enabled: true\n```\n\n### optional.metric\n\n[DEPRECATED] Gauge double metric disabled by default.\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| 1 | Gauge | Double | Deprecated since 1.0.0 |\n\n**Deprecation note**: This metric will be removed\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | Recommended |\n| boolean_attr | Attribute with a boolean value. | Any Bool | Recommended |\n| boolean_attr2 | Another attribute with a boolean value. | Any Bool | Recommended |\n| conditional_string_attr | A conditional attribute with any string value | Any Str | Conditionally Required |\n\n### optional.metric.empty_unit\n\n[DEPRECATED] Gauge double metric disabled by default.\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n|  | Gauge | Double | Deprecated since 1.0.0 |\n\n**Deprecation note**: This metric will be removed\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | Recommended |\n| boolean_attr | Attribute with a boolean value. | Any Bool | Recommended |\n\n## Default Events\n\nThe following events are emitted by default. Each of them can be disabled by applying the following configuration:\n\n```yaml\nevents:\n  <event_name>:\n    enabled: false\n```\n\n### default.event\n\nExample event enabled by default.\n\n#### Attributes\n\n| Name | Description | Values |\n| ---- | ----------- | ------ |\n| string_attr | Attribute with any string value. | Any Str |\n| state | Integer attribute with overridden name. | Any Int |\n| enum_attr | Attribute with a known set of string values. | Str: ``red``, ``green``, ``blue`` |\n| slice_attr | Attribute with a slice value. | Any Slice |\n| map_attr | Attribute with a map value. | Any Map |\n| conditional_int_attr | A conditional attribute with an integer value | Any Int |\n| conditional_string_attr | A conditional attribute with any string value | Any Str |\n| opt_in_bool_attr | An opt-in attribute with a boolean value | Any Bool |\n\n### default.event.to_be_removed\n\n[DEPRECATED] Example to-be-removed event enabled by default.\n\nThe event will be removed soon.\n\n#### Attributes\n\n| Name | Description | Values |\n| ---- | ----------- | ------ |\n| string_attr | Attribute with any string value. | Any Str |\n| state | Integer attribute with overridden name. | Any Int |\n| enum_attr | Attribute with a known set of string values. | Str: ``red``, ``green``, ``blue`` |\n| slice_attr | Attribute with a slice value. | Any Slice |\n| map_attr | Attribute with a map value. | Any Map |\n\n## Optional Events\n\nThe following events are not emitted by default. Each of them can be enabled by applying the following configuration:\n\n```yaml\nevents:\n  <event_name>:\n    enabled: true\n```\n\n### default.event.to_be_renamed\n\n[DEPRECATED] Example event disabled by default.\n\nThe event will be renamed soon.\n\n#### Attributes\n\n| Name | Description | Values |\n| ---- | ----------- | ------ |\n| string_attr | Attribute with any string value. | Any Str |\n| boolean_attr | Attribute with a boolean value. | Any Bool |\n| boolean_attr2 | Another attribute with a boolean value. | Any Bool |\n| conditional_string_attr | A conditional attribute with any string value | Any Str |\n\n## Resource Attributes\n\n| Name | Description | Values | Enabled |\n| ---- | ----------- | ------ | ------- |\n| map.resource.attr | Resource attribute with a map value. | Any Map | true |\n| optional.resource.attr | Explicitly disabled ResourceAttribute. | Any Str | false |\n| slice.resource.attr | Resource attribute with a slice value. | Any Slice | true |\n| string.enum.resource.attr | Resource attribute with a known set of string values. | Str: ``one``, ``two`` | true |\n| string.resource.attr | Resource attribute with any string value. | Any Str | true |\n| string.resource.attr_disable_warning | Resource attribute with any string value. | Any Str | true |\n| string.resource.attr_remove_warning | Resource attribute with any string value. | Any Str | false |\n| string.resource.attr_to_be_removed | Resource attribute with any string value. | Any Str | true |\n\n## Internal Telemetry\n\nThe following telemetry is emitted by this component.\n\n### otelcol_batch_size_trigger_send\n\nNumber of times the batch was sent due to a size trigger\n\n> **Deprecated since 1.5.0**\n> This metric will be removed in favor of batch_send_trigger_size\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {time} | Sum | Int | true | Deprecated since 1.5.0 |\n\n**Deprecation note**: This metric will be removed in favor of batch_send_trigger_size\n\n### otelcol_process_runtime_total_alloc_bytes\n\nCumulative bytes allocated for heap objects (see 'go doc runtime.MemStats.TotalAlloc')\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| By | Sum | Int | true | Stable |\n\n### otelcol_queue_capacity\n\nQueue capacity - sync gauge example.\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| {item} | Gauge | Int | Development |\n\n### otelcol_queue_length\n\nThis metric is optional and therefore not initialized in NewTelemetryBuilder.\n\nFor example this metric only exists if feature A is enabled.\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| {item} | Gauge | Int | Alpha |\n\n### otelcol_request_duration\n\nDuration of request\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| s | Histogram | Double | Alpha |\n\n## Feature Gates\n\nThis component has the following feature gates:\n\n| Feature Gate | Stage | Description | From Version | To Version | Reference |\n| ------------ | ----- | ----------- | ------------ | ---------- | --------- |\n| `receiver.sample.featuregate.example` | alpha | This is an example feature gate for testing mdatagen code generation. | v0.100.0 | N/A | [Link](https://github.com/open-telemetry/opentelemetry-collector/issues/12345) |\n\nFor more information about feature gates, see the [Feature Gates](https://github.com/open-telemetry/opentelemetry-collector/blob/main/featuregate/README.md) documentation.\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage samplereceiver // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplereceiver\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/otel/metric\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplereceiver/internal/metadata\"\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n)\n\n// NewFactory returns a receiver.Factory for sample receiver.\nfunc NewFactory() xreceiver.Factory {\n\treturn xreceiver.NewFactory(\n\t\tmetadata.Type,\n\t\tfunc() component.Config { return &struct{}{} },\n\t\txreceiver.WithTraces(createTraces, metadata.TracesStability),\n\t\txreceiver.WithMetrics(createMetrics, metadata.MetricsStability),\n\t\txreceiver.WithLogs(createLogs, metadata.LogsStability),\n\t\txreceiver.WithProfiles(createProfiles, metadata.ProfilesStability),\n\t)\n}\n\nfunc createTraces(context.Context, receiver.Settings, component.Config, consumer.Traces) (receiver.Traces, error) {\n\treturn nopInstance, nil\n}\n\nfunc createMetrics(ctx context.Context, set receiver.Settings, _ component.Config, _ consumer.Metrics) (receiver.Metrics, error) {\n\ttelemetryBuilder, err := metadata.NewTelemetryBuilder(set.TelemetrySettings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = telemetryBuilder.RegisterProcessRuntimeTotalAllocBytesCallback(func(_ context.Context, observer metric.Int64Observer) error {\n\t\tobserver.Observe(2)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttelemetryBuilder.BatchSizeTriggerSend.Add(ctx, 1)\n\treturn nopReceiver{telemetryBuilder: telemetryBuilder}, nil\n}\n\nfunc createLogs(context.Context, receiver.Settings, component.Config, consumer.Logs) (receiver.Logs, error) {\n\treturn nopInstance, nil\n}\n\nfunc createProfiles(context.Context, receiver.Settings, component.Config, xconsumer.Profiles) (xreceiver.Profiles, error) {\n\treturn nopInstance, nil\n}\n\nvar nopInstance = &nopReceiver{}\n\ntype nopReceiver struct {\n\tcomponent.StartFunc\n\ttelemetryBuilder *metadata.TelemetryBuilder\n}\n\nfunc (r nopReceiver) initOptionalMetric() {\n\t_ = r.telemetryBuilder.RegisterQueueLengthCallback(func(_ context.Context, observer metric.Int64Observer) error {\n\t\tobserver.Observe(3)\n\t\treturn nil\n\t})\n}\n\n// Shutdown shuts down the component.\nfunc (r nopReceiver) Shutdown(context.Context) error {\n\tif r.telemetryBuilder != nil {\n\t\tr.telemetryBuilder.Shutdown()\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n//go:build !freebsd && !illumos\n\npackage samplereceiver\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n)\n\nvar typ = component.MustNewType(\"sample\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct {\n\t\tcreateFn func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error)\n\t\tname     string\n\t}{\n\n\t\t{\n\t\t\tname: \"logs\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateLogs(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"traces\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateTraces(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"profiles\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.(xreceiver.Factory).CreateProfiles(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name+\"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\tt.Run(tt.name+\"-lifecycle\", func(t *testing.T) {\n\t\t\tfirstRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := newMdatagenNopHost()\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, firstRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, firstRcvr.Shutdown(context.Background()))\n\t\t\tsecondRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, secondRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, secondRcvr.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/generated_config.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage samplereceiver\n\nimport (\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplereceiver/internal/metadata\"\n)\n\n// Config defines the configuration for Sample Receiver component.\ntype Config struct {\n\tmetadata.MetricsBuilderConfig `mapstructure:\",squash\"`\n\t// The endpoint to scrape metrics from.\n\tEndpoint string `mapstructure:\"endpoint\"`\n\t// Timeout for scraping metrics.\n\tTimeout time.Duration `mapstructure:\"timeout\"`\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage samplereceiver\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/internal/metadata/config.schema.yaml",
    "content": "# Code generated by mdatagen. DO NOT EDIT.\n$defs:\n  metrics_config:\n    description: MetricsConfig provides config for sample metrics.\n    type: object\n    properties:\n      default.metric:\n        description: \"DefaultMetricMetricConfig provides config for the default.metric metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          aggregation_strategy:\n            type: string\n            enum:\n              - \"sum\"\n              - \"avg\"\n              - \"min\"\n              - \"max\"\n            default: \"sum\"\n          attributes:\n            type: array\n            items:\n              type: string\n              enum:\n                - \"string_attr\"\n                - \"state\"\n                - \"enum_attr\"\n                - \"slice_attr\"\n                - \"map_attr\"\n                - \"conditional_int_attr\"\n                - \"conditional_string_attr\"\n                - \"opt_in_bool_attr\"\n            default:\n              - \"string_attr\"\n              - \"state\"\n              - \"enum_attr\"\n              - \"slice_attr\"\n              - \"map_attr\"\n              - \"conditional_int_attr\"\n              - \"conditional_string_attr\"\n      default.metric.to_be_removed:\n        description: \"DefaultMetricToBeRemovedMetricConfig provides config for the default.metric.to_be_removed metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n      metric.input_type:\n        description: \"MetricInputTypeMetricConfig provides config for the metric.input_type metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          aggregation_strategy:\n            type: string\n            enum:\n              - \"sum\"\n              - \"avg\"\n              - \"min\"\n              - \"max\"\n            default: \"sum\"\n          attributes:\n            type: array\n            items:\n              type: string\n              enum:\n                - \"string_attr\"\n                - \"state\"\n                - \"enum_attr\"\n                - \"slice_attr\"\n                - \"map_attr\"\n            default:\n              - \"string_attr\"\n              - \"state\"\n              - \"enum_attr\"\n              - \"slice_attr\"\n              - \"map_attr\"\n      optional.metric:\n        description: \"OptionalMetricMetricConfig provides config for the optional.metric metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: false\n          aggregation_strategy:\n            type: string\n            enum:\n              - \"sum\"\n              - \"avg\"\n              - \"min\"\n              - \"max\"\n            default: \"avg\"\n          attributes:\n            type: array\n            items:\n              type: string\n              enum:\n                - \"string_attr\"\n                - \"boolean_attr\"\n                - \"boolean_attr2\"\n                - \"conditional_string_attr\"\n            default:\n              - \"string_attr\"\n              - \"boolean_attr\"\n              - \"boolean_attr2\"\n              - \"conditional_string_attr\"\n      optional.metric.empty_unit:\n        description: \"OptionalMetricEmptyUnitMetricConfig provides config for the optional.metric.empty_unit metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: false\n          aggregation_strategy:\n            type: string\n            enum:\n              - \"sum\"\n              - \"avg\"\n              - \"min\"\n              - \"max\"\n            default: \"avg\"\n          attributes:\n            type: array\n            items:\n              type: string\n              enum:\n                - \"string_attr\"\n                - \"boolean_attr\"\n            default:\n              - \"string_attr\"\n              - \"boolean_attr\"\n      reaggregate.metric:\n        description: \"ReaggregateMetricMetricConfig provides config for the reaggregate.metric metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          aggregation_strategy:\n            type: string\n            enum:\n              - \"sum\"\n              - \"avg\"\n              - \"min\"\n              - \"max\"\n            default: \"avg\"\n          attributes:\n            type: array\n            items:\n              type: string\n              enum:\n                - \"string_attr\"\n                - \"boolean_attr\"\n            default:\n              - \"string_attr\"\n              - \"boolean_attr\"\n      reaggregate.metric.with_required:\n        description: \"ReaggregateMetricWithRequiredMetricConfig provides config for the reaggregate.metric.with_required metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          aggregation_strategy:\n            type: string\n            enum:\n              - \"sum\"\n              - \"avg\"\n              - \"min\"\n              - \"max\"\n            default: \"avg\"\n          attributes:\n            type: array\n            items:\n              type: string\n              enum:\n                - \"required_string_attr\"\n                - \"string_attr\"\n                - \"boolean_attr\"\n            default:\n              - \"required_string_attr\"\n              - \"string_attr\"\n              - \"boolean_attr\"\n      system.cpu.time:\n        description: \"SystemCPUTimeMetricConfig provides config for the system.cpu.time metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n  events_config:\n    description: EventsConfig provides config for sample events.\n    type: object\n    properties:\n      default.event:\n        description: EventConfig provides common config for a  default.event event.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n      default.event.to_be_removed:\n        description: EventConfig provides common config for a  default.event.to_be_removed event.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n      default.event.to_be_renamed:\n        description: EventConfig provides common config for a  default.event.to_be_renamed event.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: false\n  resource_attributes_config:\n    description: ResourceAttributesConfig provides config for sample resource attributes.\n    type: object\n    properties:\n      map.resource.attr:\n        description: ResourceAttributeConfig provides common config for a map.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n          events_include:\n            description: \"Experimental: EventsInclude defines a list of filters for attribute values. If the list is not empty, only events with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          events_exclude:\n            description: \"Experimental: EventsExclude defines a list of filters for attribute values. If the list is not empty, events with matching resource attribute values will not be emitted. EventsInclude has higher priority than EventsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      optional.resource.attr:\n        description: ResourceAttributeConfig provides common config for a optional.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: false\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n          events_include:\n            description: \"Experimental: EventsInclude defines a list of filters for attribute values. If the list is not empty, only events with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          events_exclude:\n            description: \"Experimental: EventsExclude defines a list of filters for attribute values. If the list is not empty, events with matching resource attribute values will not be emitted. EventsInclude has higher priority than EventsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      slice.resource.attr:\n        description: ResourceAttributeConfig provides common config for a slice.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n          events_include:\n            description: \"Experimental: EventsInclude defines a list of filters for attribute values. If the list is not empty, only events with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          events_exclude:\n            description: \"Experimental: EventsExclude defines a list of filters for attribute values. If the list is not empty, events with matching resource attribute values will not be emitted. EventsInclude has higher priority than EventsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      string.enum.resource.attr:\n        description: ResourceAttributeConfig provides common config for a string.enum.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n          events_include:\n            description: \"Experimental: EventsInclude defines a list of filters for attribute values. If the list is not empty, only events with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          events_exclude:\n            description: \"Experimental: EventsExclude defines a list of filters for attribute values. If the list is not empty, events with matching resource attribute values will not be emitted. EventsInclude has higher priority than EventsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      string.resource.attr:\n        description: ResourceAttributeConfig provides common config for a string.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n          events_include:\n            description: \"Experimental: EventsInclude defines a list of filters for attribute values. If the list is not empty, only events with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          events_exclude:\n            description: \"Experimental: EventsExclude defines a list of filters for attribute values. If the list is not empty, events with matching resource attribute values will not be emitted. EventsInclude has higher priority than EventsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      string.resource.attr_disable_warning:\n        description: ResourceAttributeConfig provides common config for a string.resource.attr_disable_warning resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n          events_include:\n            description: \"Experimental: EventsInclude defines a list of filters for attribute values. If the list is not empty, only events with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          events_exclude:\n            description: \"Experimental: EventsExclude defines a list of filters for attribute values. If the list is not empty, events with matching resource attribute values will not be emitted. EventsInclude has higher priority than EventsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      string.resource.attr_remove_warning:\n        description: ResourceAttributeConfig provides common config for a string.resource.attr_remove_warning resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: false\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n          events_include:\n            description: \"Experimental: EventsInclude defines a list of filters for attribute values. If the list is not empty, only events with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          events_exclude:\n            description: \"Experimental: EventsExclude defines a list of filters for attribute values. If the list is not empty, events with matching resource attribute values will not be emitted. EventsInclude has higher priority than EventsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      string.resource.attr_to_be_removed:\n        description: ResourceAttributeConfig provides common config for a string.resource.attr_to_be_removed resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n          events_include:\n            description: \"Experimental: EventsInclude defines a list of filters for attribute values. If the list is not empty, only events with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          events_exclude:\n            description: \"Experimental: EventsExclude defines a list of filters for attribute values. If the list is not empty, events with matching resource attribute values will not be emitted. EventsInclude has higher priority than EventsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n  metrics_builder_config:\n    description: MetricsBuilderConfig is a configuration for sample metrics builder.\n    type: object\n    properties:\n      metrics:\n        $ref: metrics_config\n      resource_attributes:\n        $ref: resource_attributes_config\n  logs_builder_config:\n    description: LogsBuilderConfig is a configuration for sample logs builder.\n    type: object\n    properties:\n      events:\n        $ref: events_config\n      resource_attributes:\n        $ref: resource_attributes_config\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_config.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"fmt\"\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/filter\"\n)\n\n// DefaultMetricMetricAttributeKey specifies the key of an attribute for the default.metric metric.\ntype DefaultMetricMetricAttributeKey string\n\nconst (\n\tDefaultMetricMetricAttributeKeyStringAttr            DefaultMetricMetricAttributeKey = \"string_attr\"\n\tDefaultMetricMetricAttributeKeyOverriddenIntAttr     DefaultMetricMetricAttributeKey = \"state\"\n\tDefaultMetricMetricAttributeKeyEnumAttr              DefaultMetricMetricAttributeKey = \"enum_attr\"\n\tDefaultMetricMetricAttributeKeySliceAttr             DefaultMetricMetricAttributeKey = \"slice_attr\"\n\tDefaultMetricMetricAttributeKeyMapAttr               DefaultMetricMetricAttributeKey = \"map_attr\"\n\tDefaultMetricMetricAttributeKeyConditionalIntAttr    DefaultMetricMetricAttributeKey = \"conditional_int_attr\"\n\tDefaultMetricMetricAttributeKeyConditionalStringAttr DefaultMetricMetricAttributeKey = \"conditional_string_attr\"\n\tDefaultMetricMetricAttributeKeyOptInBoolAttr         DefaultMetricMetricAttributeKey = \"opt_in_bool_attr\"\n)\n\n// DefaultMetricMetricConfig provides config for the default.metric metric.\ntype DefaultMetricMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n\n\tAggregationStrategy string                            `mapstructure:\"aggregation_strategy\"`\n\tEnabledAttributes   []DefaultMetricMetricAttributeKey `mapstructure:\"attributes\"`\n}\n\nfunc (ms *DefaultMetricMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\nfunc (ms *DefaultMetricMetricConfig) Validate() error {\n\tfor _, val := range ms.EnabledAttributes {\n\t\tswitch val {\n\t\tcase DefaultMetricMetricAttributeKeyStringAttr, DefaultMetricMetricAttributeKeyOverriddenIntAttr, DefaultMetricMetricAttributeKeyEnumAttr, DefaultMetricMetricAttributeKeySliceAttr, DefaultMetricMetricAttributeKeyMapAttr, DefaultMetricMetricAttributeKeyConditionalIntAttr, DefaultMetricMetricAttributeKeyConditionalStringAttr, DefaultMetricMetricAttributeKeyOptInBoolAttr:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"metric default.metric doesn't have an attribute %v, valid attributes: [string_attr, state, enum_attr, slice_attr, map_attr, conditional_int_attr, conditional_string_attr, opt_in_bool_attr]\", val)\n\t\t}\n\t}\n\n\tswitch ms.AggregationStrategy {\n\tcase AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax:\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation strategy %q, valid strategies: [%s, %s, %s, %s]\", ms.AggregationStrategy, AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax)\n\t}\n\n\treturn nil\n}\n\n// DefaultMetricToBeRemovedMetricConfig provides config for the default.metric.to_be_removed metric.\ntype DefaultMetricToBeRemovedMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n}\n\nfunc (ms *DefaultMetricToBeRemovedMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\n// MetricInputTypeMetricAttributeKey specifies the key of an attribute for the metric.input_type metric.\ntype MetricInputTypeMetricAttributeKey string\n\nconst (\n\tMetricInputTypeMetricAttributeKeyStringAttr        MetricInputTypeMetricAttributeKey = \"string_attr\"\n\tMetricInputTypeMetricAttributeKeyOverriddenIntAttr MetricInputTypeMetricAttributeKey = \"state\"\n\tMetricInputTypeMetricAttributeKeyEnumAttr          MetricInputTypeMetricAttributeKey = \"enum_attr\"\n\tMetricInputTypeMetricAttributeKeySliceAttr         MetricInputTypeMetricAttributeKey = \"slice_attr\"\n\tMetricInputTypeMetricAttributeKeyMapAttr           MetricInputTypeMetricAttributeKey = \"map_attr\"\n)\n\n// MetricInputTypeMetricConfig provides config for the metric.input_type metric.\ntype MetricInputTypeMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n\n\tAggregationStrategy string                              `mapstructure:\"aggregation_strategy\"`\n\tEnabledAttributes   []MetricInputTypeMetricAttributeKey `mapstructure:\"attributes\"`\n}\n\nfunc (ms *MetricInputTypeMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\nfunc (ms *MetricInputTypeMetricConfig) Validate() error {\n\tfor _, val := range ms.EnabledAttributes {\n\t\tswitch val {\n\t\tcase MetricInputTypeMetricAttributeKeyStringAttr, MetricInputTypeMetricAttributeKeyOverriddenIntAttr, MetricInputTypeMetricAttributeKeyEnumAttr, MetricInputTypeMetricAttributeKeySliceAttr, MetricInputTypeMetricAttributeKeyMapAttr:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"metric metric.input_type doesn't have an attribute %v, valid attributes: [string_attr, state, enum_attr, slice_attr, map_attr]\", val)\n\t\t}\n\t}\n\n\tswitch ms.AggregationStrategy {\n\tcase AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax:\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation strategy %q, valid strategies: [%s, %s, %s, %s]\", ms.AggregationStrategy, AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax)\n\t}\n\n\treturn nil\n}\n\n// OptionalMetricMetricAttributeKey specifies the key of an attribute for the optional.metric metric.\ntype OptionalMetricMetricAttributeKey string\n\nconst (\n\tOptionalMetricMetricAttributeKeyStringAttr            OptionalMetricMetricAttributeKey = \"string_attr\"\n\tOptionalMetricMetricAttributeKeyBooleanAttr           OptionalMetricMetricAttributeKey = \"boolean_attr\"\n\tOptionalMetricMetricAttributeKeyBooleanAttr2          OptionalMetricMetricAttributeKey = \"boolean_attr2\"\n\tOptionalMetricMetricAttributeKeyConditionalStringAttr OptionalMetricMetricAttributeKey = \"conditional_string_attr\"\n)\n\n// OptionalMetricMetricConfig provides config for the optional.metric metric.\ntype OptionalMetricMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n\n\tAggregationStrategy string                             `mapstructure:\"aggregation_strategy\"`\n\tEnabledAttributes   []OptionalMetricMetricAttributeKey `mapstructure:\"attributes\"`\n}\n\nfunc (ms *OptionalMetricMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\nfunc (ms *OptionalMetricMetricConfig) Validate() error {\n\tfor _, val := range ms.EnabledAttributes {\n\t\tswitch val {\n\t\tcase OptionalMetricMetricAttributeKeyStringAttr, OptionalMetricMetricAttributeKeyBooleanAttr, OptionalMetricMetricAttributeKeyBooleanAttr2, OptionalMetricMetricAttributeKeyConditionalStringAttr:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"metric optional.metric doesn't have an attribute %v, valid attributes: [string_attr, boolean_attr, boolean_attr2, conditional_string_attr]\", val)\n\t\t}\n\t}\n\n\tswitch ms.AggregationStrategy {\n\tcase AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax:\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation strategy %q, valid strategies: [%s, %s, %s, %s]\", ms.AggregationStrategy, AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax)\n\t}\n\n\treturn nil\n}\n\n// OptionalMetricEmptyUnitMetricAttributeKey specifies the key of an attribute for the optional.metric.empty_unit metric.\ntype OptionalMetricEmptyUnitMetricAttributeKey string\n\nconst (\n\tOptionalMetricEmptyUnitMetricAttributeKeyStringAttr  OptionalMetricEmptyUnitMetricAttributeKey = \"string_attr\"\n\tOptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr OptionalMetricEmptyUnitMetricAttributeKey = \"boolean_attr\"\n)\n\n// OptionalMetricEmptyUnitMetricConfig provides config for the optional.metric.empty_unit metric.\ntype OptionalMetricEmptyUnitMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n\n\tAggregationStrategy string                                      `mapstructure:\"aggregation_strategy\"`\n\tEnabledAttributes   []OptionalMetricEmptyUnitMetricAttributeKey `mapstructure:\"attributes\"`\n}\n\nfunc (ms *OptionalMetricEmptyUnitMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\nfunc (ms *OptionalMetricEmptyUnitMetricConfig) Validate() error {\n\tfor _, val := range ms.EnabledAttributes {\n\t\tswitch val {\n\t\tcase OptionalMetricEmptyUnitMetricAttributeKeyStringAttr, OptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"metric optional.metric.empty_unit doesn't have an attribute %v, valid attributes: [string_attr, boolean_attr]\", val)\n\t\t}\n\t}\n\n\tswitch ms.AggregationStrategy {\n\tcase AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax:\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation strategy %q, valid strategies: [%s, %s, %s, %s]\", ms.AggregationStrategy, AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax)\n\t}\n\n\treturn nil\n}\n\n// ReaggregateMetricMetricAttributeKey specifies the key of an attribute for the reaggregate.metric metric.\ntype ReaggregateMetricMetricAttributeKey string\n\nconst (\n\tReaggregateMetricMetricAttributeKeyStringAttr  ReaggregateMetricMetricAttributeKey = \"string_attr\"\n\tReaggregateMetricMetricAttributeKeyBooleanAttr ReaggregateMetricMetricAttributeKey = \"boolean_attr\"\n)\n\n// ReaggregateMetricMetricConfig provides config for the reaggregate.metric metric.\ntype ReaggregateMetricMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n\n\tAggregationStrategy string                                `mapstructure:\"aggregation_strategy\"`\n\tEnabledAttributes   []ReaggregateMetricMetricAttributeKey `mapstructure:\"attributes\"`\n}\n\nfunc (ms *ReaggregateMetricMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\nfunc (ms *ReaggregateMetricMetricConfig) Validate() error {\n\tfor _, val := range ms.EnabledAttributes {\n\t\tswitch val {\n\t\tcase ReaggregateMetricMetricAttributeKeyStringAttr, ReaggregateMetricMetricAttributeKeyBooleanAttr:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"metric reaggregate.metric doesn't have an attribute %v, valid attributes: [string_attr, boolean_attr]\", val)\n\t\t}\n\t}\n\n\tswitch ms.AggregationStrategy {\n\tcase AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax:\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation strategy %q, valid strategies: [%s, %s, %s, %s]\", ms.AggregationStrategy, AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax)\n\t}\n\n\treturn nil\n}\n\n// ReaggregateMetricWithRequiredMetricAttributeKey specifies the key of an attribute for the reaggregate.metric.with_required metric.\ntype ReaggregateMetricWithRequiredMetricAttributeKey string\n\nconst (\n\tReaggregateMetricWithRequiredMetricAttributeKeyRequiredStringAttr ReaggregateMetricWithRequiredMetricAttributeKey = \"required_string_attr\"\n\tReaggregateMetricWithRequiredMetricAttributeKeyStringAttr         ReaggregateMetricWithRequiredMetricAttributeKey = \"string_attr\"\n\tReaggregateMetricWithRequiredMetricAttributeKeyBooleanAttr        ReaggregateMetricWithRequiredMetricAttributeKey = \"boolean_attr\"\n)\n\n// ReaggregateMetricWithRequiredMetricConfig provides config for the reaggregate.metric.with_required metric.\ntype ReaggregateMetricWithRequiredMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n\n\tAggregationStrategy string                                            `mapstructure:\"aggregation_strategy\"`\n\tEnabledAttributes   []ReaggregateMetricWithRequiredMetricAttributeKey `mapstructure:\"attributes\"`\n}\n\nfunc (ms *ReaggregateMetricWithRequiredMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\nfunc (ms *ReaggregateMetricWithRequiredMetricConfig) Validate() error {\n\tfor _, val := range ms.EnabledAttributes {\n\t\tswitch val {\n\t\tcase ReaggregateMetricWithRequiredMetricAttributeKeyRequiredStringAttr, ReaggregateMetricWithRequiredMetricAttributeKeyStringAttr, ReaggregateMetricWithRequiredMetricAttributeKeyBooleanAttr:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"metric reaggregate.metric.with_required doesn't have an attribute %v, valid attributes: [required_string_attr, string_attr, boolean_attr]\", val)\n\t\t}\n\t}\n\tif !slices.Contains(ms.EnabledAttributes, ReaggregateMetricWithRequiredMetricAttributeKeyRequiredStringAttr) {\n\t\treturn fmt.Errorf(\"required_string_attr is a required attribute for reaggregate.metric.with_required metric and must be included\")\n\t}\n\n\tswitch ms.AggregationStrategy {\n\tcase AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax:\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation strategy %q, valid strategies: [%s, %s, %s, %s]\", ms.AggregationStrategy, AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax)\n\t}\n\n\treturn nil\n}\n\n// SystemCPUTimeMetricConfig provides config for the system.cpu.time metric.\ntype SystemCPUTimeMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n}\n\nfunc (ms *SystemCPUTimeMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\n// MetricsConfig provides config for sample metrics.\ntype MetricsConfig struct {\n\tDefaultMetric                 DefaultMetricMetricConfig                 `mapstructure:\"default.metric\"`\n\tDefaultMetricToBeRemoved      DefaultMetricToBeRemovedMetricConfig      `mapstructure:\"default.metric.to_be_removed\"`\n\tMetricInputType               MetricInputTypeMetricConfig               `mapstructure:\"metric.input_type\"`\n\tOptionalMetric                OptionalMetricMetricConfig                `mapstructure:\"optional.metric\"`\n\tOptionalMetricEmptyUnit       OptionalMetricEmptyUnitMetricConfig       `mapstructure:\"optional.metric.empty_unit\"`\n\tReaggregateMetric             ReaggregateMetricMetricConfig             `mapstructure:\"reaggregate.metric\"`\n\tReaggregateMetricWithRequired ReaggregateMetricWithRequiredMetricConfig `mapstructure:\"reaggregate.metric.with_required\"`\n\tSystemCPUTime                 SystemCPUTimeMetricConfig                 `mapstructure:\"system.cpu.time\"`\n}\n\nfunc DefaultMetricsConfig() MetricsConfig {\n\treturn MetricsConfig{\n\t\tDefaultMetric: DefaultMetricMetricConfig{\n\t\t\tEnabled:             true,\n\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\tEnabledAttributes:   []DefaultMetricMetricAttributeKey{DefaultMetricMetricAttributeKeyStringAttr, DefaultMetricMetricAttributeKeyOverriddenIntAttr, DefaultMetricMetricAttributeKeyEnumAttr, DefaultMetricMetricAttributeKeySliceAttr, DefaultMetricMetricAttributeKeyMapAttr, DefaultMetricMetricAttributeKeyConditionalIntAttr, DefaultMetricMetricAttributeKeyConditionalStringAttr},\n\t\t},\n\t\tDefaultMetricToBeRemoved: DefaultMetricToBeRemovedMetricConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tMetricInputType: MetricInputTypeMetricConfig{\n\t\t\tEnabled:             true,\n\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\tEnabledAttributes:   []MetricInputTypeMetricAttributeKey{MetricInputTypeMetricAttributeKeyStringAttr, MetricInputTypeMetricAttributeKeyOverriddenIntAttr, MetricInputTypeMetricAttributeKeyEnumAttr, MetricInputTypeMetricAttributeKeySliceAttr, MetricInputTypeMetricAttributeKeyMapAttr},\n\t\t},\n\t\tOptionalMetric: OptionalMetricMetricConfig{\n\t\t\tEnabled:             false,\n\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\tEnabledAttributes:   []OptionalMetricMetricAttributeKey{OptionalMetricMetricAttributeKeyStringAttr, OptionalMetricMetricAttributeKeyBooleanAttr, OptionalMetricMetricAttributeKeyBooleanAttr2, OptionalMetricMetricAttributeKeyConditionalStringAttr},\n\t\t},\n\t\tOptionalMetricEmptyUnit: OptionalMetricEmptyUnitMetricConfig{\n\t\t\tEnabled:             false,\n\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\tEnabledAttributes:   []OptionalMetricEmptyUnitMetricAttributeKey{OptionalMetricEmptyUnitMetricAttributeKeyStringAttr, OptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr},\n\t\t},\n\t\tReaggregateMetric: ReaggregateMetricMetricConfig{\n\t\t\tEnabled:             true,\n\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\tEnabledAttributes:   []ReaggregateMetricMetricAttributeKey{ReaggregateMetricMetricAttributeKeyStringAttr, ReaggregateMetricMetricAttributeKeyBooleanAttr},\n\t\t},\n\t\tReaggregateMetricWithRequired: ReaggregateMetricWithRequiredMetricConfig{\n\t\t\tEnabled:             true,\n\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\tEnabledAttributes:   []ReaggregateMetricWithRequiredMetricAttributeKey{ReaggregateMetricWithRequiredMetricAttributeKeyRequiredStringAttr, ReaggregateMetricWithRequiredMetricAttributeKeyStringAttr, ReaggregateMetricWithRequiredMetricAttributeKeyBooleanAttr},\n\t\t},\n\t\tSystemCPUTime: SystemCPUTimeMetricConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t}\n}\n\n// EventConfig provides common config for a particular event.\ntype EventConfig struct {\n\tEnabled bool `mapstructure:\"enabled\"`\n\n\tenabledSetByUser bool\n}\n\nfunc (ec *EventConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\terr := parser.Unmarshal(ec)\n\tif err != nil {\n\t\treturn err\n\t}\n\tec.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\n// EventsConfig provides config for sample events.\ntype EventsConfig struct {\n\tDefaultEvent            EventConfig `mapstructure:\"default.event\"`\n\tDefaultEventToBeRemoved EventConfig `mapstructure:\"default.event.to_be_removed\"`\n\tDefaultEventToBeRenamed EventConfig `mapstructure:\"default.event.to_be_renamed\"`\n}\n\nfunc DefaultEventsConfig() EventsConfig {\n\treturn EventsConfig{\n\t\tDefaultEvent: EventConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tDefaultEventToBeRemoved: EventConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tDefaultEventToBeRenamed: EventConfig{\n\t\t\tEnabled: false,\n\t\t},\n\t}\n}\n\n// ResourceAttributeConfig provides common config for a particular resource attribute.\ntype ResourceAttributeConfig struct {\n\tEnabled bool `mapstructure:\"enabled\"`\n\t// Experimental: MetricsInclude defines a list of filters for attribute values.\n\t// If the list is not empty, only metrics with matching resource attribute values will be emitted.\n\tMetricsInclude []filter.Config `mapstructure:\"metrics_include\"`\n\t// Experimental: MetricsExclude defines a list of filters for attribute values.\n\t// If the list is not empty, metrics with matching resource attribute values will not be emitted.\n\t// MetricsInclude has higher priority than MetricsExclude.\n\tMetricsExclude []filter.Config `mapstructure:\"metrics_exclude\"`\n\t// Experimental: EventsInclude defines a list of filters for attribute values.\n\t// If the list is not empty, only events with matching resource attribute values will be emitted.\n\tEventsInclude []filter.Config `mapstructure:\"events_include\"`\n\t// Experimental: EventsExclude defines a list of filters for attribute values.\n\t// If the list is not empty, events with matching resource attribute values will not be emitted.\n\t// EventsInclude has higher priority than EventsExclude.\n\tEventsExclude []filter.Config `mapstructure:\"events_exclude\"`\n\n\tenabledSetByUser bool\n}\n\nfunc (rac *ResourceAttributeConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\terr := parser.Unmarshal(rac)\n\tif err != nil {\n\t\treturn err\n\t}\n\trac.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\n// ResourceAttributesConfig provides config for sample resource attributes.\ntype ResourceAttributesConfig struct {\n\tMapResourceAttr                  ResourceAttributeConfig `mapstructure:\"map.resource.attr\"`\n\tOptionalResourceAttr             ResourceAttributeConfig `mapstructure:\"optional.resource.attr\"`\n\tSliceResourceAttr                ResourceAttributeConfig `mapstructure:\"slice.resource.attr\"`\n\tStringEnumResourceAttr           ResourceAttributeConfig `mapstructure:\"string.enum.resource.attr\"`\n\tStringResourceAttr               ResourceAttributeConfig `mapstructure:\"string.resource.attr\"`\n\tStringResourceAttrDisableWarning ResourceAttributeConfig `mapstructure:\"string.resource.attr_disable_warning\"`\n\tStringResourceAttrRemoveWarning  ResourceAttributeConfig `mapstructure:\"string.resource.attr_remove_warning\"`\n\tStringResourceAttrToBeRemoved    ResourceAttributeConfig `mapstructure:\"string.resource.attr_to_be_removed\"`\n}\n\nfunc DefaultResourceAttributesConfig() ResourceAttributesConfig {\n\treturn ResourceAttributesConfig{\n\t\tMapResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tOptionalResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: false,\n\t\t},\n\t\tSliceResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringEnumResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringResourceAttrRemoveWarning: ResourceAttributeConfig{\n\t\t\tEnabled: false,\n\t\t},\n\t\tStringResourceAttrToBeRemoved: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t}\n}\n\n// MetricsBuilderConfig is a configuration for sample metrics builder.\ntype MetricsBuilderConfig struct {\n\tMetrics            MetricsConfig            `mapstructure:\"metrics\"`\n\tResourceAttributes ResourceAttributesConfig `mapstructure:\"resource_attributes\"`\n}\n\nfunc DefaultMetricsBuilderConfig() MetricsBuilderConfig {\n\treturn MetricsBuilderConfig{\n\t\tMetrics:            DefaultMetricsConfig(),\n\t\tResourceAttributes: DefaultResourceAttributesConfig(),\n\t}\n}\n\n// LogsBuilderConfig is a configuration for sample logs builder.\ntype LogsBuilderConfig struct {\n\tEvents             EventsConfig             `mapstructure:\"events\"`\n\tResourceAttributes ResourceAttributesConfig `mapstructure:\"resource_attributes\"`\n}\n\nfunc DefaultLogsBuilderConfig() LogsBuilderConfig {\n\treturn LogsBuilderConfig{\n\t\tEvents:             DefaultEventsConfig(),\n\t\tResourceAttributes: DefaultResourceAttributesConfig(),\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_config_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n\t\"github.com/google/go-cmp/cmp/cmpopts\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n)\n\nfunc TestMetricsBuilderConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant MetricsBuilderConfig\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\twant: DefaultMetricsBuilderConfig(),\n\t\t},\n\t\t{\n\t\t\tname: \"all_set\",\n\t\t\twant: MetricsBuilderConfig{\n\t\t\t\tMetrics: MetricsConfig{\n\t\t\t\t\tDefaultMetric: DefaultMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             true,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\t\t\t\tEnabledAttributes:   []DefaultMetricMetricAttributeKey{DefaultMetricMetricAttributeKeyStringAttr, DefaultMetricMetricAttributeKeyOverriddenIntAttr, DefaultMetricMetricAttributeKeyEnumAttr, DefaultMetricMetricAttributeKeySliceAttr, DefaultMetricMetricAttributeKeyMapAttr, DefaultMetricMetricAttributeKeyConditionalIntAttr, DefaultMetricMetricAttributeKeyConditionalStringAttr, DefaultMetricMetricAttributeKeyOptInBoolAttr},\n\t\t\t\t\t},\n\t\t\t\t\tDefaultMetricToBeRemoved: DefaultMetricToBeRemovedMetricConfig{\n\t\t\t\t\t\tEnabled: true,\n\t\t\t\t\t},\n\t\t\t\t\tMetricInputType: MetricInputTypeMetricConfig{\n\t\t\t\t\t\tEnabled:             true,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\t\t\t\tEnabledAttributes:   []MetricInputTypeMetricAttributeKey{MetricInputTypeMetricAttributeKeyStringAttr, MetricInputTypeMetricAttributeKeyOverriddenIntAttr, MetricInputTypeMetricAttributeKeyEnumAttr, MetricInputTypeMetricAttributeKeySliceAttr, MetricInputTypeMetricAttributeKeyMapAttr},\n\t\t\t\t\t},\n\t\t\t\t\tOptionalMetric: OptionalMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             true,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []OptionalMetricMetricAttributeKey{OptionalMetricMetricAttributeKeyStringAttr, OptionalMetricMetricAttributeKeyBooleanAttr, OptionalMetricMetricAttributeKeyBooleanAttr2, OptionalMetricMetricAttributeKeyConditionalStringAttr},\n\t\t\t\t\t},\n\t\t\t\t\tOptionalMetricEmptyUnit: OptionalMetricEmptyUnitMetricConfig{\n\t\t\t\t\t\tEnabled:             true,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []OptionalMetricEmptyUnitMetricAttributeKey{OptionalMetricEmptyUnitMetricAttributeKeyStringAttr, OptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr},\n\t\t\t\t\t},\n\t\t\t\t\tReaggregateMetric: ReaggregateMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             true,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []ReaggregateMetricMetricAttributeKey{ReaggregateMetricMetricAttributeKeyStringAttr, ReaggregateMetricMetricAttributeKeyBooleanAttr},\n\t\t\t\t\t},\n\t\t\t\t\tReaggregateMetricWithRequired: ReaggregateMetricWithRequiredMetricConfig{\n\t\t\t\t\t\tEnabled:             true,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []ReaggregateMetricWithRequiredMetricAttributeKey{ReaggregateMetricWithRequiredMetricAttributeKeyRequiredStringAttr, ReaggregateMetricWithRequiredMetricAttributeKeyStringAttr, ReaggregateMetricWithRequiredMetricAttributeKeyBooleanAttr},\n\t\t\t\t\t},\n\t\t\t\t\tSystemCPUTime: SystemCPUTimeMetricConfig{\n\t\t\t\t\t\tEnabled: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tResourceAttributes: ResourceAttributesConfig{\n\t\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: true},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"none_set\",\n\t\t\twant: MetricsBuilderConfig{\n\t\t\t\tMetrics: MetricsConfig{\n\t\t\t\t\tDefaultMetric: DefaultMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             false,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\t\t\t\tEnabledAttributes:   []DefaultMetricMetricAttributeKey{DefaultMetricMetricAttributeKeyStringAttr, DefaultMetricMetricAttributeKeyOverriddenIntAttr, DefaultMetricMetricAttributeKeyEnumAttr, DefaultMetricMetricAttributeKeySliceAttr, DefaultMetricMetricAttributeKeyMapAttr, DefaultMetricMetricAttributeKeyConditionalIntAttr, DefaultMetricMetricAttributeKeyConditionalStringAttr, DefaultMetricMetricAttributeKeyOptInBoolAttr},\n\t\t\t\t\t},\n\t\t\t\t\tDefaultMetricToBeRemoved: DefaultMetricToBeRemovedMetricConfig{\n\t\t\t\t\t\tEnabled: false,\n\t\t\t\t\t},\n\t\t\t\t\tMetricInputType: MetricInputTypeMetricConfig{\n\t\t\t\t\t\tEnabled:             false,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\t\t\t\tEnabledAttributes:   []MetricInputTypeMetricAttributeKey{MetricInputTypeMetricAttributeKeyStringAttr, MetricInputTypeMetricAttributeKeyOverriddenIntAttr, MetricInputTypeMetricAttributeKeyEnumAttr, MetricInputTypeMetricAttributeKeySliceAttr, MetricInputTypeMetricAttributeKeyMapAttr},\n\t\t\t\t\t},\n\t\t\t\t\tOptionalMetric: OptionalMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             false,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []OptionalMetricMetricAttributeKey{OptionalMetricMetricAttributeKeyStringAttr, OptionalMetricMetricAttributeKeyBooleanAttr, OptionalMetricMetricAttributeKeyBooleanAttr2, OptionalMetricMetricAttributeKeyConditionalStringAttr},\n\t\t\t\t\t},\n\t\t\t\t\tOptionalMetricEmptyUnit: OptionalMetricEmptyUnitMetricConfig{\n\t\t\t\t\t\tEnabled:             false,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []OptionalMetricEmptyUnitMetricAttributeKey{OptionalMetricEmptyUnitMetricAttributeKeyStringAttr, OptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr},\n\t\t\t\t\t},\n\t\t\t\t\tReaggregateMetric: ReaggregateMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             false,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []ReaggregateMetricMetricAttributeKey{ReaggregateMetricMetricAttributeKeyStringAttr, ReaggregateMetricMetricAttributeKeyBooleanAttr},\n\t\t\t\t\t},\n\t\t\t\t\tReaggregateMetricWithRequired: ReaggregateMetricWithRequiredMetricConfig{\n\t\t\t\t\t\tEnabled:             false,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []ReaggregateMetricWithRequiredMetricAttributeKey{ReaggregateMetricWithRequiredMetricAttributeKeyRequiredStringAttr, ReaggregateMetricWithRequiredMetricAttributeKeyStringAttr, ReaggregateMetricWithRequiredMetricAttributeKeyBooleanAttr},\n\t\t\t\t\t},\n\t\t\t\t\tSystemCPUTime: SystemCPUTimeMetricConfig{\n\t\t\t\t\t\tEnabled: false,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tResourceAttributes: ResourceAttributesConfig{\n\t\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: false},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := loadMetricsBuilderConfig(t, tt.name)\n\t\t\tdiff := cmp.Diff(tt.want, cfg, cmpopts.IgnoreUnexported(DefaultMetricMetricConfig{}, DefaultMetricToBeRemovedMetricConfig{}, MetricInputTypeMetricConfig{}, OptionalMetricMetricConfig{}, OptionalMetricEmptyUnitMetricConfig{}, ReaggregateMetricMetricConfig{}, ReaggregateMetricWithRequiredMetricConfig{}, SystemCPUTimeMetricConfig{}, ResourceAttributeConfig{}))\n\t\t\trequire.Emptyf(t, diff, \"Config mismatch (-expected +actual):\\n%s\", diff)\n\t\t})\n\t}\n}\n\nfunc loadMetricsBuilderConfig(t *testing.T, name string) MetricsBuilderConfig {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tsub, err := cm.Sub(name)\n\trequire.NoError(t, err)\n\tcfg := DefaultMetricsBuilderConfig()\n\trequire.NoError(t, sub.Unmarshal(&cfg, confmap.WithIgnoreUnused()))\n\treturn cfg\n}\n\nfunc loadLogsBuilderConfig(t *testing.T, name string) LogsBuilderConfig {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tsub, err := cm.Sub(name)\n\trequire.NoError(t, err)\n\tcfg := DefaultLogsBuilderConfig()\n\trequire.NoError(t, sub.Unmarshal(&cfg, confmap.WithIgnoreUnused()))\n\treturn cfg\n}\n\nfunc TestResourceAttributesConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant ResourceAttributesConfig\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\twant: DefaultResourceAttributesConfig(),\n\t\t},\n\t\t{\n\t\t\tname: \"all_set\",\n\t\t\twant: ResourceAttributesConfig{\n\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: true},\n\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: true},\n\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: true},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"none_set\",\n\t\t\twant: ResourceAttributesConfig{\n\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: false},\n\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: false},\n\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: false},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := loadResourceAttributesConfig(t, tt.name)\n\t\t\tdiff := cmp.Diff(tt.want, cfg, cmpopts.IgnoreUnexported(ResourceAttributeConfig{}))\n\t\t\trequire.Emptyf(t, diff, \"Config mismatch (-expected +actual):\\n%s\", diff)\n\t\t})\n\t}\n}\n\nfunc loadResourceAttributesConfig(t *testing.T, name string) ResourceAttributesConfig {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tsub, err := cm.Sub(name)\n\trequire.NoError(t, err)\n\tsub, err = sub.Sub(\"resource_attributes\")\n\trequire.NoError(t, err)\n\tcfg := DefaultResourceAttributesConfig()\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\treturn cfg\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_feature_gates.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\nvar ReceiverSampleFeaturegateExampleFeatureGate = featuregate.GlobalRegistry().MustRegister(\n\t\"receiver.sample.featuregate.example\",\n\tfeaturegate.StageAlpha,\n\tfeaturegate.WithRegisterDescription(\"This is an example feature gate for testing mdatagen code generation.\"),\n\tfeaturegate.WithRegisterReferenceURL(\"https://github.com/open-telemetry/opentelemetry-collector/issues/12345\"),\n\tfeaturegate.WithRegisterFromVersion(\"v0.100.0\"),\n)\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_logs.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"context\"\n\n\tconventions \"go.opentelemetry.io/otel/semconv/v1.38.0\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/filter\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/receiver\"\n)\n\ntype EventAttributeOption interface {\n\tapply(plog.LogRecord)\n}\n\ntype eventAttributeOptionFunc func(plog.LogRecord)\n\nfunc (eaof eventAttributeOptionFunc) apply(lr plog.LogRecord) {\n\teaof(lr)\n}\n\nfunc WithConditionalIntAttrEventAttribute(conditionalIntAttrAttributeValue int64) EventAttributeOption {\n\treturn eventAttributeOptionFunc(func(dp plog.LogRecord) {\n\t\tdp.Attributes().PutInt(\"conditional_int_attr\", conditionalIntAttrAttributeValue)\n\t})\n}\n\nfunc WithConditionalStringAttrEventAttribute(conditionalStringAttrAttributeValue string) EventAttributeOption {\n\treturn eventAttributeOptionFunc(func(dp plog.LogRecord) {\n\t\tdp.Attributes().PutStr(\"conditional_string_attr\", conditionalStringAttrAttributeValue)\n\t})\n}\n\ntype eventDefaultEvent struct {\n\tdata   plog.LogRecordSlice // data buffer for generated log records.\n\tconfig EventConfig         // event config provided by user.\n}\n\nfunc (e *eventDefaultEvent) recordEvent(ctx context.Context, timestamp pcommon.Timestamp, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue string, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any, optInBoolAttrAttributeValue bool, options ...EventAttributeOption) {\n\tif !e.config.Enabled {\n\t\treturn\n\t}\n\tdp := e.data.AppendEmpty()\n\tdp.SetEventName(\"default.event\")\n\tdp.SetTimestamp(timestamp)\n\n\tif span := trace.SpanContextFromContext(ctx); span.IsValid() {\n\t\tdp.SetTraceID(pcommon.TraceID(span.TraceID()))\n\t\tdp.SetSpanID(pcommon.SpanID(span.SpanID()))\n\t}\n\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\tdp.Attributes().PutInt(\"state\", overriddenIntAttrAttributeValue)\n\tdp.Attributes().PutStr(\"enum_attr\", enumAttrAttributeValue)\n\tdp.Attributes().PutEmptySlice(\"slice_attr\").FromRaw(sliceAttrAttributeValue)\n\tdp.Attributes().PutEmptyMap(\"map_attr\").FromRaw(mapAttrAttributeValue)\n\tdp.Attributes().PutBool(\"opt_in_bool_attr\", optInBoolAttrAttributeValue)\n\n\tfor _, op := range options {\n\t\top.apply(dp)\n\t}\n}\n\n// emit appends recorded event data to a events slice and prepares it for recording another set of log records.\nfunc (e *eventDefaultEvent) emit(lrs plog.LogRecordSlice) {\n\tif e.config.Enabled && e.data.Len() > 0 {\n\t\te.data.MoveAndAppendTo(lrs)\n\t}\n}\n\nfunc newEventDefaultEvent(cfg EventConfig) eventDefaultEvent {\n\te := eventDefaultEvent{config: cfg}\n\tif cfg.Enabled {\n\t\te.data = plog.NewLogRecordSlice()\n\t}\n\treturn e\n}\n\ntype eventDefaultEventToBeRemoved struct {\n\tdata   plog.LogRecordSlice // data buffer for generated log records.\n\tconfig EventConfig         // event config provided by user.\n}\n\nfunc (e *eventDefaultEventToBeRemoved) recordEvent(ctx context.Context, timestamp pcommon.Timestamp, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue string, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any) {\n\tif !e.config.Enabled {\n\t\treturn\n\t}\n\tdp := e.data.AppendEmpty()\n\tdp.SetEventName(\"default.event.to_be_removed\")\n\tdp.SetTimestamp(timestamp)\n\n\tif span := trace.SpanContextFromContext(ctx); span.IsValid() {\n\t\tdp.SetTraceID(pcommon.TraceID(span.TraceID()))\n\t\tdp.SetSpanID(pcommon.SpanID(span.SpanID()))\n\t}\n\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\tdp.Attributes().PutInt(\"state\", overriddenIntAttrAttributeValue)\n\tdp.Attributes().PutStr(\"enum_attr\", enumAttrAttributeValue)\n\tdp.Attributes().PutEmptySlice(\"slice_attr\").FromRaw(sliceAttrAttributeValue)\n\tdp.Attributes().PutEmptyMap(\"map_attr\").FromRaw(mapAttrAttributeValue)\n\n}\n\n// emit appends recorded event data to a events slice and prepares it for recording another set of log records.\nfunc (e *eventDefaultEventToBeRemoved) emit(lrs plog.LogRecordSlice) {\n\tif e.config.Enabled && e.data.Len() > 0 {\n\t\te.data.MoveAndAppendTo(lrs)\n\t}\n}\n\nfunc newEventDefaultEventToBeRemoved(cfg EventConfig) eventDefaultEventToBeRemoved {\n\te := eventDefaultEventToBeRemoved{config: cfg}\n\tif cfg.Enabled {\n\t\te.data = plog.NewLogRecordSlice()\n\t}\n\treturn e\n}\n\ntype eventDefaultEventToBeRenamed struct {\n\tdata   plog.LogRecordSlice // data buffer for generated log records.\n\tconfig EventConfig         // event config provided by user.\n}\n\nfunc (e *eventDefaultEventToBeRenamed) recordEvent(ctx context.Context, timestamp pcommon.Timestamp, stringAttrAttributeValue string, booleanAttrAttributeValue bool, booleanAttr2AttributeValue bool, options ...EventAttributeOption) {\n\tif !e.config.Enabled {\n\t\treturn\n\t}\n\tdp := e.data.AppendEmpty()\n\tdp.SetEventName(\"default.event.to_be_renamed\")\n\tdp.SetTimestamp(timestamp)\n\n\tif span := trace.SpanContextFromContext(ctx); span.IsValid() {\n\t\tdp.SetTraceID(pcommon.TraceID(span.TraceID()))\n\t\tdp.SetSpanID(pcommon.SpanID(span.SpanID()))\n\t}\n\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\tdp.Attributes().PutBool(\"boolean_attr\", booleanAttrAttributeValue)\n\tdp.Attributes().PutBool(\"boolean_attr2\", booleanAttr2AttributeValue)\n\n\tfor _, op := range options {\n\t\top.apply(dp)\n\t}\n}\n\n// emit appends recorded event data to a events slice and prepares it for recording another set of log records.\nfunc (e *eventDefaultEventToBeRenamed) emit(lrs plog.LogRecordSlice) {\n\tif e.config.Enabled && e.data.Len() > 0 {\n\t\te.data.MoveAndAppendTo(lrs)\n\t}\n}\n\nfunc newEventDefaultEventToBeRenamed(cfg EventConfig) eventDefaultEventToBeRenamed {\n\te := eventDefaultEventToBeRenamed{config: cfg}\n\tif cfg.Enabled {\n\t\te.data = plog.NewLogRecordSlice()\n\t}\n\treturn e\n}\n\n// LogsBuilder provides an interface for scrapers to report logs while taking care of all the transformations\n// required to produce log representation defined in metadata and user config.\ntype LogsBuilder struct {\n\tconfig                         LogsBuilderConfig // config of the logs builder.\n\tlogsBuffer                     plog.Logs\n\tlogRecordsBuffer               plog.LogRecordSlice\n\tbuildInfo                      component.BuildInfo // contains version information.\n\tresourceAttributeIncludeFilter map[string]filter.Filter\n\tresourceAttributeExcludeFilter map[string]filter.Filter\n\teventDefaultEvent              eventDefaultEvent\n\teventDefaultEventToBeRemoved   eventDefaultEventToBeRemoved\n\teventDefaultEventToBeRenamed   eventDefaultEventToBeRenamed\n}\n\n// LogBuilderOption applies changes to default logs builder.\ntype LogBuilderOption interface {\n\tapply(*LogsBuilder)\n}\n\nfunc NewLogsBuilder(lbc LogsBuilderConfig, settings receiver.Settings) *LogsBuilder {\n\tif !lbc.Events.DefaultEvent.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] Please set `enabled` field explicitly for `default.event`: This event will be disabled by default soon.\")\n\t}\n\tif lbc.Events.DefaultEventToBeRemoved.Enabled {\n\t\tsettings.Logger.Warn(\"[WARNING] `default.event.to_be_removed` should not be enabled: This event is deprecated and will be removed soon.\")\n\t}\n\tif lbc.Events.DefaultEventToBeRenamed.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] `default.event.to_be_renamed` should not be configured: This event is deprecated and will be renamed soon.\")\n\t}\n\tif !lbc.ResourceAttributes.StringResourceAttrDisableWarning.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] Please set `enabled` field explicitly for `string.resource.attr_disable_warning`: This resource_attribute will be disabled by default soon.\")\n\t}\n\tif lbc.ResourceAttributes.StringResourceAttrRemoveWarning.enabledSetByUser || lbc.ResourceAttributes.StringResourceAttrRemoveWarning.EventsInclude != nil || lbc.ResourceAttributes.StringResourceAttrRemoveWarning.EventsExclude != nil {\n\t\tsettings.Logger.Warn(\"[WARNING] `string.resource.attr_remove_warning` should not be configured: This resource_attribute is deprecated and will be removed soon.\")\n\t}\n\tif lbc.ResourceAttributes.StringResourceAttrToBeRemoved.Enabled {\n\t\tsettings.Logger.Warn(\"[WARNING] `string.resource.attr_to_be_removed` should not be enabled: This resource_attribute is deprecated and will be removed soon.\")\n\t}\n\tlb := &LogsBuilder{\n\t\tconfig:                         lbc,\n\t\tlogsBuffer:                     plog.NewLogs(),\n\t\tlogRecordsBuffer:               plog.NewLogRecordSlice(),\n\t\tbuildInfo:                      settings.BuildInfo,\n\t\teventDefaultEvent:              newEventDefaultEvent(lbc.Events.DefaultEvent),\n\t\teventDefaultEventToBeRemoved:   newEventDefaultEventToBeRemoved(lbc.Events.DefaultEventToBeRemoved),\n\t\teventDefaultEventToBeRenamed:   newEventDefaultEventToBeRenamed(lbc.Events.DefaultEventToBeRenamed),\n\t\tresourceAttributeIncludeFilter: make(map[string]filter.Filter),\n\t\tresourceAttributeExcludeFilter: make(map[string]filter.Filter),\n\t}\n\tif lbc.ResourceAttributes.MapResourceAttr.EventsInclude != nil {\n\t\tlb.resourceAttributeIncludeFilter[\"map.resource.attr\"] = filter.CreateFilter(lbc.ResourceAttributes.MapResourceAttr.EventsInclude)\n\t}\n\tif lbc.ResourceAttributes.MapResourceAttr.EventsExclude != nil {\n\t\tlb.resourceAttributeExcludeFilter[\"map.resource.attr\"] = filter.CreateFilter(lbc.ResourceAttributes.MapResourceAttr.EventsExclude)\n\t}\n\tif lbc.ResourceAttributes.OptionalResourceAttr.EventsInclude != nil {\n\t\tlb.resourceAttributeIncludeFilter[\"optional.resource.attr\"] = filter.CreateFilter(lbc.ResourceAttributes.OptionalResourceAttr.EventsInclude)\n\t}\n\tif lbc.ResourceAttributes.OptionalResourceAttr.EventsExclude != nil {\n\t\tlb.resourceAttributeExcludeFilter[\"optional.resource.attr\"] = filter.CreateFilter(lbc.ResourceAttributes.OptionalResourceAttr.EventsExclude)\n\t}\n\tif lbc.ResourceAttributes.SliceResourceAttr.EventsInclude != nil {\n\t\tlb.resourceAttributeIncludeFilter[\"slice.resource.attr\"] = filter.CreateFilter(lbc.ResourceAttributes.SliceResourceAttr.EventsInclude)\n\t}\n\tif lbc.ResourceAttributes.SliceResourceAttr.EventsExclude != nil {\n\t\tlb.resourceAttributeExcludeFilter[\"slice.resource.attr\"] = filter.CreateFilter(lbc.ResourceAttributes.SliceResourceAttr.EventsExclude)\n\t}\n\tif lbc.ResourceAttributes.StringEnumResourceAttr.EventsInclude != nil {\n\t\tlb.resourceAttributeIncludeFilter[\"string.enum.resource.attr\"] = filter.CreateFilter(lbc.ResourceAttributes.StringEnumResourceAttr.EventsInclude)\n\t}\n\tif lbc.ResourceAttributes.StringEnumResourceAttr.EventsExclude != nil {\n\t\tlb.resourceAttributeExcludeFilter[\"string.enum.resource.attr\"] = filter.CreateFilter(lbc.ResourceAttributes.StringEnumResourceAttr.EventsExclude)\n\t}\n\tif lbc.ResourceAttributes.StringResourceAttr.EventsInclude != nil {\n\t\tlb.resourceAttributeIncludeFilter[\"string.resource.attr\"] = filter.CreateFilter(lbc.ResourceAttributes.StringResourceAttr.EventsInclude)\n\t}\n\tif lbc.ResourceAttributes.StringResourceAttr.EventsExclude != nil {\n\t\tlb.resourceAttributeExcludeFilter[\"string.resource.attr\"] = filter.CreateFilter(lbc.ResourceAttributes.StringResourceAttr.EventsExclude)\n\t}\n\tif lbc.ResourceAttributes.StringResourceAttrDisableWarning.EventsInclude != nil {\n\t\tlb.resourceAttributeIncludeFilter[\"string.resource.attr_disable_warning\"] = filter.CreateFilter(lbc.ResourceAttributes.StringResourceAttrDisableWarning.EventsInclude)\n\t}\n\tif lbc.ResourceAttributes.StringResourceAttrDisableWarning.EventsExclude != nil {\n\t\tlb.resourceAttributeExcludeFilter[\"string.resource.attr_disable_warning\"] = filter.CreateFilter(lbc.ResourceAttributes.StringResourceAttrDisableWarning.EventsExclude)\n\t}\n\tif lbc.ResourceAttributes.StringResourceAttrRemoveWarning.EventsInclude != nil {\n\t\tlb.resourceAttributeIncludeFilter[\"string.resource.attr_remove_warning\"] = filter.CreateFilter(lbc.ResourceAttributes.StringResourceAttrRemoveWarning.EventsInclude)\n\t}\n\tif lbc.ResourceAttributes.StringResourceAttrRemoveWarning.EventsExclude != nil {\n\t\tlb.resourceAttributeExcludeFilter[\"string.resource.attr_remove_warning\"] = filter.CreateFilter(lbc.ResourceAttributes.StringResourceAttrRemoveWarning.EventsExclude)\n\t}\n\tif lbc.ResourceAttributes.StringResourceAttrToBeRemoved.EventsInclude != nil {\n\t\tlb.resourceAttributeIncludeFilter[\"string.resource.attr_to_be_removed\"] = filter.CreateFilter(lbc.ResourceAttributes.StringResourceAttrToBeRemoved.EventsInclude)\n\t}\n\tif lbc.ResourceAttributes.StringResourceAttrToBeRemoved.EventsExclude != nil {\n\t\tlb.resourceAttributeExcludeFilter[\"string.resource.attr_to_be_removed\"] = filter.CreateFilter(lbc.ResourceAttributes.StringResourceAttrToBeRemoved.EventsExclude)\n\t}\n\n\treturn lb\n}\n\n// NewResourceBuilder returns a new resource builder that should be used to build a resource associated with for the emitted logs.\nfunc (lb *LogsBuilder) NewResourceBuilder() *ResourceBuilder {\n\treturn NewResourceBuilder(lb.config.ResourceAttributes)\n}\n\n// ResourceLogsOption applies changes to provided resource logs.\ntype ResourceLogsOption interface {\n\tapply(plog.ResourceLogs)\n}\n\ntype resourceLogsOptionFunc func(plog.ResourceLogs)\n\nfunc (rlof resourceLogsOptionFunc) apply(rl plog.ResourceLogs) {\n\trlof(rl)\n}\n\n// WithLogsResource sets the provided resource on the emitted ResourceLogs.\n// It's recommended to use ResourceBuilder to create the resource.\nfunc WithLogsResource(res pcommon.Resource) ResourceLogsOption {\n\treturn resourceLogsOptionFunc(func(rl plog.ResourceLogs) {\n\t\tres.CopyTo(rl.Resource())\n\t})\n}\n\n// AppendLogRecord adds a log record to the logs builder.\nfunc (lb *LogsBuilder) AppendLogRecord(lr plog.LogRecord) {\n\tlr.MoveTo(lb.logRecordsBuffer.AppendEmpty())\n}\n\n// EmitForResource saves all the generated logs under a new resource and updates the internal state to be ready for\n// recording another set of log records as part of another resource. This function can be helpful when one scraper\n// needs to emit logs from several resources. Otherwise calling this function is not required,\n// just `Emit` function can be called instead.\n// Resource attributes should be provided as ResourceLogsOption arguments.\nfunc (lb *LogsBuilder) EmitForResource(options ...ResourceLogsOption) {\n\trl := plog.NewResourceLogs()\n\trl.SetSchemaUrl(conventions.SchemaURL)\n\tils := rl.ScopeLogs().AppendEmpty()\n\tils.Scope().SetName(ScopeName)\n\tils.Scope().SetVersion(lb.buildInfo.Version)\n\tlb.eventDefaultEvent.emit(ils.LogRecords())\n\tlb.eventDefaultEventToBeRemoved.emit(ils.LogRecords())\n\tlb.eventDefaultEventToBeRenamed.emit(ils.LogRecords())\n\n\tfor _, op := range options {\n\t\top.apply(rl)\n\t}\n\n\tif lb.logRecordsBuffer.Len() > 0 {\n\t\tlb.logRecordsBuffer.MoveAndAppendTo(ils.LogRecords())\n\t\tlb.logRecordsBuffer = plog.NewLogRecordSlice()\n\t}\n\n\tfor attr, filter := range lb.resourceAttributeIncludeFilter {\n\t\tif val, ok := rl.Resource().Attributes().Get(attr); ok && !filter.Matches(val.AsString()) {\n\t\t\treturn\n\t\t}\n\t}\n\tfor attr, filter := range lb.resourceAttributeExcludeFilter {\n\t\tif val, ok := rl.Resource().Attributes().Get(attr); ok && filter.Matches(val.AsString()) {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif ils.LogRecords().Len() > 0 {\n\t\trl.MoveTo(lb.logsBuffer.ResourceLogs().AppendEmpty())\n\t}\n}\n\n// Emit returns all the logs accumulated by the logs builder and updates the internal state to be ready for\n// recording another set of logs. This function will be responsible for applying all the transformations required to\n// produce logs representation defined in metadata and user config.\nfunc (lb *LogsBuilder) Emit(options ...ResourceLogsOption) plog.Logs {\n\tlb.EmitForResource(options...)\n\tlogs := lb.logsBuffer\n\tlb.logsBuffer = plog.NewLogs()\n\treturn logs\n}\n\n// RecordDefaultEventEvent adds a log record of default.event event.\nfunc (lb *LogsBuilder) RecordDefaultEventEvent(ctx context.Context, timestamp pcommon.Timestamp, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue AttributeEnumAttr, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any, optInBoolAttrAttributeValue bool, options ...EventAttributeOption) {\n\tlb.eventDefaultEvent.recordEvent(ctx, timestamp, stringAttrAttributeValue, overriddenIntAttrAttributeValue, enumAttrAttributeValue.String(), sliceAttrAttributeValue, mapAttrAttributeValue, optInBoolAttrAttributeValue, options...)\n}\n\n// RecordDefaultEventToBeRemovedEvent adds a log record of default.event.to_be_removed event.\nfunc (lb *LogsBuilder) RecordDefaultEventToBeRemovedEvent(ctx context.Context, timestamp pcommon.Timestamp, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue AttributeEnumAttr, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any) {\n\tlb.eventDefaultEventToBeRemoved.recordEvent(ctx, timestamp, stringAttrAttributeValue, overriddenIntAttrAttributeValue, enumAttrAttributeValue.String(), sliceAttrAttributeValue, mapAttrAttributeValue)\n}\n\n// RecordDefaultEventToBeRenamedEvent adds a log record of default.event.to_be_renamed event.\nfunc (lb *LogsBuilder) RecordDefaultEventToBeRenamedEvent(ctx context.Context, timestamp pcommon.Timestamp, stringAttrAttributeValue string, booleanAttrAttributeValue bool, booleanAttr2AttributeValue bool, options ...EventAttributeOption) {\n\tlb.eventDefaultEventToBeRenamed.recordEvent(ctx, timestamp, stringAttrAttributeValue, booleanAttrAttributeValue, booleanAttr2AttributeValue, options...)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_logs_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.opentelemetry.io/otel/trace\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\ntype eventsTestDataSet int\n\nconst (\n\teventTestDataSetDefault eventsTestDataSet = iota\n\teventTestDataSetAll\n\teventTestDataSetNone\n)\n\nfunc TestLogsBuilderAppendLogRecord(t *testing.T) {\n\tobservedZapCore, _ := observer.New(zap.WarnLevel)\n\tsettings := receivertest.NewNopSettings(receivertest.NopType)\n\tsettings.Logger = zap.New(observedZapCore)\n\tlb := NewLogsBuilder(loadLogsBuilderConfig(t, \"all_set\"), settings)\n\n\trb := lb.NewResourceBuilder()\n\trb.SetMapResourceAttr(map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"})\n\trb.SetOptionalResourceAttr(\"optional.resource.attr-val\")\n\trb.SetSliceResourceAttr([]any{\"slice.resource.attr-item1\", \"slice.resource.attr-item2\"})\n\trb.SetStringEnumResourceAttrOne()\n\trb.SetStringResourceAttr(\"string.resource.attr-val\")\n\trb.SetStringResourceAttrDisableWarning(\"string.resource.attr_disable_warning-val\")\n\trb.SetStringResourceAttrRemoveWarning(\"string.resource.attr_remove_warning-val\")\n\trb.SetStringResourceAttrToBeRemoved(\"string.resource.attr_to_be_removed-val\")\n\tres := rb.Emit()\n\n\t// append the first log record\n\tlr := plog.NewLogRecord()\n\tlr.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\tlr.Attributes().PutStr(\"type\", \"log\")\n\tlr.Body().SetStr(\"the first log record\")\n\n\t// append the second log record\n\tlr2 := plog.NewLogRecord()\n\tlr2.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\tlr2.Attributes().PutStr(\"type\", \"event\")\n\tlr2.Body().SetStr(\"the second log record\")\n\n\tlb.AppendLogRecord(lr)\n\tlb.AppendLogRecord(lr2)\n\n\tlogs := lb.Emit(WithLogsResource(res))\n\tassert.Equal(t, 1, logs.ResourceLogs().Len())\n\n\trl := logs.ResourceLogs().At(0)\n\tassert.Equal(t, 1, rl.ScopeLogs().Len())\n\n\tsl := rl.ScopeLogs().At(0)\n\tassert.Equal(t, ScopeName, sl.Scope().Name())\n\tassert.Equal(t, lb.buildInfo.Version, sl.Scope().Version())\n\n\tassert.Equal(t, 2, sl.LogRecords().Len())\n\n\tattrVal, ok := sl.LogRecords().At(0).Attributes().Get(\"type\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"log\", attrVal.Str())\n\n\tassert.Equal(t, pcommon.ValueTypeStr, sl.LogRecords().At(0).Body().Type())\n\tassert.Equal(t, \"the first log record\", sl.LogRecords().At(0).Body().Str())\n\n\tattrVal, ok = sl.LogRecords().At(1).Attributes().Get(\"type\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"event\", attrVal.Str())\n\n\tassert.Equal(t, pcommon.ValueTypeStr, sl.LogRecords().At(1).Body().Type())\n\tassert.Equal(t, \"the second log record\", sl.LogRecords().At(1).Body().Str())\n}\nfunc TestLogsBuilder(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\teventsSet   eventsTestDataSet\n\t\tresAttrsSet eventsTestDataSet\n\t\texpectEmpty bool\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t},\n\t\t{\n\t\t\tname:        \"all_set\",\n\t\t\teventsSet:   eventTestDataSetAll,\n\t\t\tresAttrsSet: eventTestDataSetAll,\n\t\t},\n\t\t{\n\t\t\tname:        \"none_set\",\n\t\t\teventsSet:   eventTestDataSetNone,\n\t\t\tresAttrsSet: eventTestDataSetNone,\n\t\t\texpectEmpty: true,\n\t\t},\n\t\t{\n\t\t\tname:        \"filter_set_include\",\n\t\t\tresAttrsSet: eventTestDataSetAll,\n\t\t},\n\t\t{\n\t\t\tname:        \"filter_set_exclude\",\n\t\t\tresAttrsSet: eventTestDataSetAll,\n\t\t\texpectEmpty: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttimestamp := pcommon.Timestamp(1_000_001_000)\n\t\t\ttraceID := [16]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}\n\t\t\tspanID := [8]byte{0, 1, 2, 3, 4, 5, 6, 7}\n\t\t\tctx := trace.ContextWithSpanContext(context.Background(), trace.NewSpanContext(trace.SpanContextConfig{\n\t\t\t\tTraceID:    trace.TraceID(traceID),\n\t\t\t\tSpanID:     trace.SpanID(spanID),\n\t\t\t\tTraceFlags: trace.FlagsSampled,\n\t\t\t}))\n\t\t\tobservedZapCore, observedLogs := observer.New(zap.WarnLevel)\n\t\t\tsettings := receivertest.NewNopSettings(receivertest.NopType)\n\t\t\tsettings.Logger = zap.New(observedZapCore)\n\t\t\tlb := NewLogsBuilder(loadLogsBuilderConfig(t, tt.name), settings)\n\n\t\t\texpectedWarnings := 0\n\t\t\tif tt.eventsSet == eventTestDataSetDefault {\n\t\t\t\tassert.Equal(t, \"[WARNING] Please set `enabled` field explicitly for `default.event`: This event will be disabled by default soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.eventsSet == eventTestDataSetDefault || tt.eventsSet == eventTestDataSetAll {\n\t\t\t\tassert.Equal(t, \"[WARNING] `default.event.to_be_removed` should not be enabled: This event is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.eventsSet == eventTestDataSetAll || tt.eventsSet == eventTestDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `default.event.to_be_renamed` should not be configured: This event is deprecated and will be renamed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.resAttrsSet == eventTestDataSetDefault {\n\t\t\t\tassert.Equal(t, \"[WARNING] Please set `enabled` field explicitly for `string.resource.attr_disable_warning`: This resource_attribute will be disabled by default soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.resAttrsSet == eventTestDataSetAll || tt.resAttrsSet == eventTestDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `string.resource.attr_remove_warning` should not be configured: This resource_attribute is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.resAttrsSet == eventTestDataSetDefault || tt.resAttrsSet == eventTestDataSetAll {\n\t\t\t\tassert.Equal(t, \"[WARNING] `string.resource.attr_to_be_removed` should not be enabled: This resource_attribute is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\n\t\t\tassert.Equal(t, expectedWarnings, observedLogs.Len())\n\n\t\t\tdefaultEventsCount := 0\n\t\t\tallEventsCount := 0\n\t\t\tdefaultEventsCount++\n\t\t\tallEventsCount++\n\t\t\tlb.RecordDefaultEventEvent(ctx, timestamp, \"string_attr-val\", 19, AttributeEnumAttrRed, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"}, true, WithConditionalIntAttrEventAttribute(20), WithConditionalStringAttrEventAttribute(\"conditional_string_attr-val\"))\n\t\t\tdefaultEventsCount++\n\t\t\tallEventsCount++\n\t\t\tlb.RecordDefaultEventToBeRemovedEvent(ctx, timestamp, \"string_attr-val\", 19, AttributeEnumAttrRed, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"})\n\n\t\t\tallEventsCount++\n\t\t\tlb.RecordDefaultEventToBeRenamedEvent(ctx, timestamp, \"string_attr-val\", true, false, WithConditionalStringAttrEventAttribute(\"conditional_string_attr-val\"))\n\n\t\t\trb := lb.NewResourceBuilder()\n\t\t\trb.SetMapResourceAttr(map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"})\n\t\t\trb.SetOptionalResourceAttr(\"optional.resource.attr-val\")\n\t\t\trb.SetSliceResourceAttr([]any{\"slice.resource.attr-item1\", \"slice.resource.attr-item2\"})\n\t\t\trb.SetStringEnumResourceAttrOne()\n\t\t\trb.SetStringResourceAttr(\"string.resource.attr-val\")\n\t\t\trb.SetStringResourceAttrDisableWarning(\"string.resource.attr_disable_warning-val\")\n\t\t\trb.SetStringResourceAttrRemoveWarning(\"string.resource.attr_remove_warning-val\")\n\t\t\trb.SetStringResourceAttrToBeRemoved(\"string.resource.attr_to_be_removed-val\")\n\t\t\tres := rb.Emit()\n\t\t\tlogs := lb.Emit(WithLogsResource(res))\n\n\t\t\tif tt.expectEmpty || ((tt.name == \"default\" || tt.name == \"filter_set_include\") && defaultEventsCount == 0) {\n\t\t\t\tassert.Equal(t, 0, logs.ResourceLogs().Len())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tassert.Equal(t, 1, logs.ResourceLogs().Len())\n\t\t\trl := logs.ResourceLogs().At(0)\n\t\t\tassert.Equal(t, res, rl.Resource())\n\t\t\tassert.Equal(t, 1, rl.ScopeLogs().Len())\n\t\t\tlrs := rl.ScopeLogs().At(0).LogRecords()\n\t\t\tif tt.eventsSet == eventTestDataSetDefault {\n\t\t\t\tassert.Equal(t, defaultEventsCount, lrs.Len())\n\t\t\t}\n\t\t\tif tt.eventsSet == eventTestDataSetAll {\n\t\t\t\tassert.Equal(t, allEventsCount, lrs.Len())\n\t\t\t}\n\t\t\tvalidatedEvents := make(map[string]bool)\n\t\t\tfor i := 0; i < lrs.Len(); i++ {\n\t\t\t\tswitch lrs.At(i).EventName() {\n\t\t\t\tcase \"default.event\":\n\t\t\t\t\tassert.False(t, validatedEvents[\"default.event\"], \"Found a duplicate in the events slice: default.event\")\n\t\t\t\t\tvalidatedEvents[\"default.event\"] = true\n\t\t\t\t\tlr := lrs.At(i)\n\t\t\t\t\tassert.Equal(t, timestamp, lr.Timestamp())\n\t\t\t\t\tassert.Equal(t, pcommon.TraceID(traceID), lr.TraceID())\n\t\t\t\t\tassert.Equal(t, pcommon.SpanID(spanID), lr.SpanID())\n\t\t\t\t\tattrVal, ok := lr.Attributes().Get(\"string_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, \"string_attr-val\", attrVal.Str())\n\t\t\t\t\tattrVal, ok = lr.Attributes().Get(\"state\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.EqualValues(t, 19, attrVal.Int())\n\t\t\t\t\tattrVal, ok = lr.Attributes().Get(\"enum_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, \"red\", attrVal.Str())\n\t\t\t\t\tattrVal, ok = lr.Attributes().Get(\"slice_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, attrVal.Slice().AsRaw())\n\t\t\t\t\tattrVal, ok = lr.Attributes().Get(\"map_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"}, attrVal.Map().AsRaw())\n\t\t\t\t\tattrVal, ok = lr.Attributes().Get(\"conditional_int_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.EqualValues(t, 20, attrVal.Int())\n\t\t\t\t\tattrVal, ok = lr.Attributes().Get(\"conditional_string_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, \"conditional_string_attr-val\", attrVal.Str())\n\t\t\t\t\tattrVal, ok = lr.Attributes().Get(\"opt_in_bool_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.True(t, attrVal.Bool())\n\t\t\t\tcase \"default.event.to_be_removed\":\n\t\t\t\t\tassert.False(t, validatedEvents[\"default.event.to_be_removed\"], \"Found a duplicate in the events slice: default.event.to_be_removed\")\n\t\t\t\t\tvalidatedEvents[\"default.event.to_be_removed\"] = true\n\t\t\t\t\tlr := lrs.At(i)\n\t\t\t\t\tassert.Equal(t, timestamp, lr.Timestamp())\n\t\t\t\t\tassert.Equal(t, pcommon.TraceID(traceID), lr.TraceID())\n\t\t\t\t\tassert.Equal(t, pcommon.SpanID(spanID), lr.SpanID())\n\t\t\t\t\tattrVal, ok := lr.Attributes().Get(\"string_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, \"string_attr-val\", attrVal.Str())\n\t\t\t\t\tattrVal, ok = lr.Attributes().Get(\"state\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.EqualValues(t, 19, attrVal.Int())\n\t\t\t\t\tattrVal, ok = lr.Attributes().Get(\"enum_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, \"red\", attrVal.Str())\n\t\t\t\t\tattrVal, ok = lr.Attributes().Get(\"slice_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, attrVal.Slice().AsRaw())\n\t\t\t\t\tattrVal, ok = lr.Attributes().Get(\"map_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"}, attrVal.Map().AsRaw())\n\t\t\t\tcase \"default.event.to_be_renamed\":\n\t\t\t\t\tassert.False(t, validatedEvents[\"default.event.to_be_renamed\"], \"Found a duplicate in the events slice: default.event.to_be_renamed\")\n\t\t\t\t\tvalidatedEvents[\"default.event.to_be_renamed\"] = true\n\t\t\t\t\tlr := lrs.At(i)\n\t\t\t\t\tassert.Equal(t, timestamp, lr.Timestamp())\n\t\t\t\t\tassert.Equal(t, pcommon.TraceID(traceID), lr.TraceID())\n\t\t\t\t\tassert.Equal(t, pcommon.SpanID(spanID), lr.SpanID())\n\t\t\t\t\tattrVal, ok := lr.Attributes().Get(\"string_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, \"string_attr-val\", attrVal.Str())\n\t\t\t\t\tattrVal, ok = lr.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.True(t, attrVal.Bool())\n\t\t\t\t\tattrVal, ok = lr.Attributes().Get(\"boolean_attr2\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.False(t, attrVal.Bool())\n\t\t\t\t\tattrVal, ok = lr.Attributes().Get(\"conditional_string_attr\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\tassert.Equal(t, \"conditional_string_attr-val\", attrVal.Str())\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_metrics.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"fmt\"\n\t\"slices\"\n\t\"strconv\"\n\t\"time\"\n\n\tconventions \"go.opentelemetry.io/otel/semconv/v1.38.0\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/filter\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/receiver\"\n)\n\nconst (\n\tAggregationStrategySum = \"sum\"\n\tAggregationStrategyAvg = \"avg\"\n\tAggregationStrategyMin = \"min\"\n\tAggregationStrategyMax = \"max\"\n)\n\n// AttributeEnumAttr specifies the value enum_attr attribute.\ntype AttributeEnumAttr int\n\nconst (\n\t_ AttributeEnumAttr = iota\n\tAttributeEnumAttrRed\n\tAttributeEnumAttrGreen\n\tAttributeEnumAttrBlue\n)\n\n// String returns the string representation of the AttributeEnumAttr.\nfunc (av AttributeEnumAttr) String() string {\n\tswitch av {\n\tcase AttributeEnumAttrRed:\n\t\treturn \"red\"\n\tcase AttributeEnumAttrGreen:\n\t\treturn \"green\"\n\tcase AttributeEnumAttrBlue:\n\t\treturn \"blue\"\n\t}\n\treturn \"\"\n}\n\n// MapAttributeEnumAttr is a helper map of string to AttributeEnumAttr attribute value.\nvar MapAttributeEnumAttr = map[string]AttributeEnumAttr{\n\t\"red\":   AttributeEnumAttrRed,\n\t\"green\": AttributeEnumAttrGreen,\n\t\"blue\":  AttributeEnumAttrBlue,\n}\n\nvar MetricsInfo = metricsInfo{\n\tDefaultMetric: metricInfo{\n\t\tName: \"default.metric\",\n\t},\n\tDefaultMetricToBeRemoved: metricInfo{\n\t\tName: \"default.metric.to_be_removed\",\n\t},\n\tMetricInputType: metricInfo{\n\t\tName: \"metric.input_type\",\n\t},\n\tOptionalMetric: metricInfo{\n\t\tName: \"optional.metric\",\n\t},\n\tOptionalMetricEmptyUnit: metricInfo{\n\t\tName: \"optional.metric.empty_unit\",\n\t},\n\tReaggregateMetric: metricInfo{\n\t\tName: \"reaggregate.metric\",\n\t},\n\tReaggregateMetricWithRequired: metricInfo{\n\t\tName: \"reaggregate.metric.with_required\",\n\t},\n\tSystemCPUTime: metricInfo{\n\t\tName: \"system.cpu.time\",\n\t},\n}\n\ntype metricsInfo struct {\n\tDefaultMetric                 metricInfo\n\tDefaultMetricToBeRemoved      metricInfo\n\tMetricInputType               metricInfo\n\tOptionalMetric                metricInfo\n\tOptionalMetricEmptyUnit       metricInfo\n\tReaggregateMetric             metricInfo\n\tReaggregateMetricWithRequired metricInfo\n\tSystemCPUTime                 metricInfo\n}\n\ntype metricInfo struct {\n\tName string\n}\n\ntype MetricAttributeOption interface {\n\tapply(pmetric.NumberDataPoint)\n}\n\ntype metricAttributeOptionFunc func(pmetric.NumberDataPoint)\n\nfunc (maof metricAttributeOptionFunc) apply(dp pmetric.NumberDataPoint) {\n\tmaof(dp)\n}\n\nfunc WithConditionalIntAttrMetricAttribute(conditionalIntAttrAttributeValue int64) MetricAttributeOption {\n\treturn metricAttributeOptionFunc(func(dp pmetric.NumberDataPoint) {\n\t\tdp.Attributes().PutInt(\"conditional_int_attr\", conditionalIntAttrAttributeValue)\n\t})\n}\n\nfunc WithConditionalStringAttrMetricAttribute(conditionalStringAttrAttributeValue string) MetricAttributeOption {\n\treturn metricAttributeOptionFunc(func(dp pmetric.NumberDataPoint) {\n\t\tdp.Attributes().PutStr(\"conditional_string_attr\", conditionalStringAttrAttributeValue)\n\t})\n}\n\ntype metricDefaultMetric struct {\n\tdata          pmetric.Metric            // data buffer for generated metric.\n\tconfig        DefaultMetricMetricConfig // metric config provided by user.\n\tcapacity      int                       // max observed number of data points added to the metric.\n\taggDataPoints []int64                   // slice containing number of aggregated datapoints at each index\n}\n\n// init fills default.metric metric with initial data.\nfunc (m *metricDefaultMetric) init() {\n\tm.data.SetName(\"default.metric\")\n\tm.data.SetDescription(\"Monotonic cumulative sum int metric enabled by default.\")\n\tm.data.SetUnit(\"s\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(true)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n\tm.data.Sum().DataPoints().EnsureCapacity(m.capacity)\n\tm.aggDataPoints = m.aggDataPoints[:0]\n}\n\nfunc (m *metricDefaultMetric) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val int64, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue string, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any, optInBoolAttrAttributeValue bool, options ...MetricAttributeOption) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\n\tdp := pmetric.NewNumberDataPoint()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tif slices.Contains(m.config.EnabledAttributes, DefaultMetricMetricAttributeKeyStringAttr) {\n\t\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, DefaultMetricMetricAttributeKeyOverriddenIntAttr) {\n\t\tdp.Attributes().PutInt(\"state\", overriddenIntAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, DefaultMetricMetricAttributeKeyEnumAttr) {\n\t\tdp.Attributes().PutStr(\"enum_attr\", enumAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, DefaultMetricMetricAttributeKeySliceAttr) {\n\t\tdp.Attributes().PutEmptySlice(\"slice_attr\").FromRaw(sliceAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, DefaultMetricMetricAttributeKeyMapAttr) {\n\t\tdp.Attributes().PutEmptyMap(\"map_attr\").FromRaw(mapAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, DefaultMetricMetricAttributeKeyOptInBoolAttr) {\n\t\tdp.Attributes().PutBool(\"opt_in_bool_attr\", optInBoolAttrAttributeValue)\n\t}\n\tfor _, op := range options {\n\t\top.apply(dp)\n\t}\n\n\tvar s string\n\tdps := m.data.Sum().DataPoints()\n\tfor i := 0; i < dps.Len(); i++ {\n\t\tdpi := dps.At(i)\n\t\tif dp.Attributes().Equal(dpi.Attributes()) && dp.StartTimestamp() == dpi.StartTimestamp() && dp.Timestamp() == dpi.Timestamp() {\n\t\t\tswitch s = m.config.AggregationStrategy; s {\n\t\t\tcase AggregationStrategySum, AggregationStrategyAvg:\n\t\t\t\tdpi.SetIntValue(dpi.IntValue() + val)\n\t\t\t\tm.aggDataPoints[i] += 1\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMin:\n\t\t\t\tif dpi.IntValue() > val {\n\t\t\t\t\tdpi.SetIntValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMax:\n\t\t\t\tif dpi.IntValue() < val {\n\t\t\t\t\tdpi.SetIntValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdp.SetIntValue(val)\n\tm.aggDataPoints = append(m.aggDataPoints, 1)\n\tdp.MoveTo(dps.AppendEmpty())\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricDefaultMetric) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricDefaultMetric) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tif m.config.AggregationStrategy == AggregationStrategyAvg {\n\t\t\tfor i, aggCount := range m.aggDataPoints {\n\t\t\t\tm.data.Sum().DataPoints().At(i).SetIntValue(m.data.Sum().DataPoints().At(i).IntValue() / aggCount)\n\t\t\t}\n\t\t}\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricDefaultMetric(cfg DefaultMetricMetricConfig) metricDefaultMetric {\n\tm := metricDefaultMetric{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricDefaultMetricToBeRemoved struct {\n\tdata     pmetric.Metric                       // data buffer for generated metric.\n\tconfig   DefaultMetricToBeRemovedMetricConfig // metric config provided by user.\n\tcapacity int                                  // max observed number of data points added to the metric.\n}\n\n// init fills default.metric.to_be_removed metric with initial data.\nfunc (m *metricDefaultMetricToBeRemoved) init() {\n\tm.data.SetName(\"default.metric.to_be_removed\")\n\tm.data.SetDescription(\"[DEPRECATED] Non-monotonic delta sum double metric enabled by default.\")\n\tm.data.SetUnit(\"s\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(false)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityDelta)\n}\n\nfunc (m *metricDefaultMetricToBeRemoved) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val float64) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\tdp := m.data.Sum().DataPoints().AppendEmpty()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tdp.SetDoubleValue(val)\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricDefaultMetricToBeRemoved) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricDefaultMetricToBeRemoved) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricDefaultMetricToBeRemoved(cfg DefaultMetricToBeRemovedMetricConfig) metricDefaultMetricToBeRemoved {\n\tm := metricDefaultMetricToBeRemoved{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricMetricInputType struct {\n\tdata          pmetric.Metric              // data buffer for generated metric.\n\tconfig        MetricInputTypeMetricConfig // metric config provided by user.\n\tcapacity      int                         // max observed number of data points added to the metric.\n\taggDataPoints []int64                     // slice containing number of aggregated datapoints at each index\n}\n\n// init fills metric.input_type metric with initial data.\nfunc (m *metricMetricInputType) init() {\n\tm.data.SetName(\"metric.input_type\")\n\tm.data.SetDescription(\"Monotonic cumulative sum int metric with string input_type enabled by default.\")\n\tm.data.SetUnit(\"s\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(true)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n\tm.data.Sum().DataPoints().EnsureCapacity(m.capacity)\n\tm.aggDataPoints = m.aggDataPoints[:0]\n}\n\nfunc (m *metricMetricInputType) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val int64, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue string, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\n\tdp := pmetric.NewNumberDataPoint()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tif slices.Contains(m.config.EnabledAttributes, MetricInputTypeMetricAttributeKeyStringAttr) {\n\t\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, MetricInputTypeMetricAttributeKeyOverriddenIntAttr) {\n\t\tdp.Attributes().PutInt(\"state\", overriddenIntAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, MetricInputTypeMetricAttributeKeyEnumAttr) {\n\t\tdp.Attributes().PutStr(\"enum_attr\", enumAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, MetricInputTypeMetricAttributeKeySliceAttr) {\n\t\tdp.Attributes().PutEmptySlice(\"slice_attr\").FromRaw(sliceAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, MetricInputTypeMetricAttributeKeyMapAttr) {\n\t\tdp.Attributes().PutEmptyMap(\"map_attr\").FromRaw(mapAttrAttributeValue)\n\t}\n\n\tvar s string\n\tdps := m.data.Sum().DataPoints()\n\tfor i := 0; i < dps.Len(); i++ {\n\t\tdpi := dps.At(i)\n\t\tif dp.Attributes().Equal(dpi.Attributes()) && dp.StartTimestamp() == dpi.StartTimestamp() && dp.Timestamp() == dpi.Timestamp() {\n\t\t\tswitch s = m.config.AggregationStrategy; s {\n\t\t\tcase AggregationStrategySum, AggregationStrategyAvg:\n\t\t\t\tdpi.SetIntValue(dpi.IntValue() + val)\n\t\t\t\tm.aggDataPoints[i] += 1\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMin:\n\t\t\t\tif dpi.IntValue() > val {\n\t\t\t\t\tdpi.SetIntValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMax:\n\t\t\t\tif dpi.IntValue() < val {\n\t\t\t\t\tdpi.SetIntValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdp.SetIntValue(val)\n\tm.aggDataPoints = append(m.aggDataPoints, 1)\n\tdp.MoveTo(dps.AppendEmpty())\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricMetricInputType) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricMetricInputType) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tif m.config.AggregationStrategy == AggregationStrategyAvg {\n\t\t\tfor i, aggCount := range m.aggDataPoints {\n\t\t\t\tm.data.Sum().DataPoints().At(i).SetIntValue(m.data.Sum().DataPoints().At(i).IntValue() / aggCount)\n\t\t\t}\n\t\t}\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricMetricInputType(cfg MetricInputTypeMetricConfig) metricMetricInputType {\n\tm := metricMetricInputType{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricOptionalMetric struct {\n\tdata          pmetric.Metric             // data buffer for generated metric.\n\tconfig        OptionalMetricMetricConfig // metric config provided by user.\n\tcapacity      int                        // max observed number of data points added to the metric.\n\taggDataPoints []float64                  // slice containing number of aggregated datapoints at each index\n}\n\n// init fills optional.metric metric with initial data.\nfunc (m *metricOptionalMetric) init() {\n\tm.data.SetName(\"optional.metric\")\n\tm.data.SetDescription(\"[DEPRECATED] Gauge double metric disabled by default.\")\n\tm.data.SetUnit(\"1\")\n\tm.data.SetEmptyGauge()\n\tm.data.Gauge().DataPoints().EnsureCapacity(m.capacity)\n\tm.aggDataPoints = m.aggDataPoints[:0]\n}\n\nfunc (m *metricOptionalMetric) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool, booleanAttr2AttributeValue bool, options ...MetricAttributeOption) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\n\tdp := pmetric.NewNumberDataPoint()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tif slices.Contains(m.config.EnabledAttributes, OptionalMetricMetricAttributeKeyStringAttr) {\n\t\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, OptionalMetricMetricAttributeKeyBooleanAttr) {\n\t\tdp.Attributes().PutBool(\"boolean_attr\", booleanAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, OptionalMetricMetricAttributeKeyBooleanAttr2) {\n\t\tdp.Attributes().PutBool(\"boolean_attr2\", booleanAttr2AttributeValue)\n\t}\n\tfor _, op := range options {\n\t\top.apply(dp)\n\t}\n\n\tvar s string\n\tdps := m.data.Gauge().DataPoints()\n\tfor i := 0; i < dps.Len(); i++ {\n\t\tdpi := dps.At(i)\n\t\tif dp.Attributes().Equal(dpi.Attributes()) && dp.StartTimestamp() == dpi.StartTimestamp() && dp.Timestamp() == dpi.Timestamp() {\n\t\t\tswitch s = m.config.AggregationStrategy; s {\n\t\t\tcase AggregationStrategySum, AggregationStrategyAvg:\n\t\t\t\tdpi.SetDoubleValue(dpi.DoubleValue() + val)\n\t\t\t\tm.aggDataPoints[i] += 1\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMin:\n\t\t\t\tif dpi.DoubleValue() > val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMax:\n\t\t\t\tif dpi.DoubleValue() < val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdp.SetDoubleValue(val)\n\tm.aggDataPoints = append(m.aggDataPoints, 1)\n\tdp.MoveTo(dps.AppendEmpty())\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricOptionalMetric) updateCapacity() {\n\tif m.data.Gauge().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Gauge().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricOptionalMetric) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 {\n\t\tif m.config.AggregationStrategy == AggregationStrategyAvg {\n\t\t\tfor i, aggCount := range m.aggDataPoints {\n\t\t\t\tm.data.Gauge().DataPoints().At(i).SetDoubleValue(m.data.Gauge().DataPoints().At(i).DoubleValue() / aggCount)\n\t\t\t}\n\t\t}\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricOptionalMetric(cfg OptionalMetricMetricConfig) metricOptionalMetric {\n\tm := metricOptionalMetric{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricOptionalMetricEmptyUnit struct {\n\tdata          pmetric.Metric                      // data buffer for generated metric.\n\tconfig        OptionalMetricEmptyUnitMetricConfig // metric config provided by user.\n\tcapacity      int                                 // max observed number of data points added to the metric.\n\taggDataPoints []float64                           // slice containing number of aggregated datapoints at each index\n}\n\n// init fills optional.metric.empty_unit metric with initial data.\nfunc (m *metricOptionalMetricEmptyUnit) init() {\n\tm.data.SetName(\"optional.metric.empty_unit\")\n\tm.data.SetDescription(\"[DEPRECATED] Gauge double metric disabled by default.\")\n\tm.data.SetUnit(\"\")\n\tm.data.SetEmptyGauge()\n\tm.data.Gauge().DataPoints().EnsureCapacity(m.capacity)\n\tm.aggDataPoints = m.aggDataPoints[:0]\n}\n\nfunc (m *metricOptionalMetricEmptyUnit) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\n\tdp := pmetric.NewNumberDataPoint()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tif slices.Contains(m.config.EnabledAttributes, OptionalMetricEmptyUnitMetricAttributeKeyStringAttr) {\n\t\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, OptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr) {\n\t\tdp.Attributes().PutBool(\"boolean_attr\", booleanAttrAttributeValue)\n\t}\n\n\tvar s string\n\tdps := m.data.Gauge().DataPoints()\n\tfor i := 0; i < dps.Len(); i++ {\n\t\tdpi := dps.At(i)\n\t\tif dp.Attributes().Equal(dpi.Attributes()) && dp.StartTimestamp() == dpi.StartTimestamp() && dp.Timestamp() == dpi.Timestamp() {\n\t\t\tswitch s = m.config.AggregationStrategy; s {\n\t\t\tcase AggregationStrategySum, AggregationStrategyAvg:\n\t\t\t\tdpi.SetDoubleValue(dpi.DoubleValue() + val)\n\t\t\t\tm.aggDataPoints[i] += 1\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMin:\n\t\t\t\tif dpi.DoubleValue() > val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMax:\n\t\t\t\tif dpi.DoubleValue() < val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdp.SetDoubleValue(val)\n\tm.aggDataPoints = append(m.aggDataPoints, 1)\n\tdp.MoveTo(dps.AppendEmpty())\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricOptionalMetricEmptyUnit) updateCapacity() {\n\tif m.data.Gauge().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Gauge().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricOptionalMetricEmptyUnit) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 {\n\t\tif m.config.AggregationStrategy == AggregationStrategyAvg {\n\t\t\tfor i, aggCount := range m.aggDataPoints {\n\t\t\t\tm.data.Gauge().DataPoints().At(i).SetDoubleValue(m.data.Gauge().DataPoints().At(i).DoubleValue() / aggCount)\n\t\t\t}\n\t\t}\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricOptionalMetricEmptyUnit(cfg OptionalMetricEmptyUnitMetricConfig) metricOptionalMetricEmptyUnit {\n\tm := metricOptionalMetricEmptyUnit{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricReaggregateMetric struct {\n\tdata          pmetric.Metric                // data buffer for generated metric.\n\tconfig        ReaggregateMetricMetricConfig // metric config provided by user.\n\tcapacity      int                           // max observed number of data points added to the metric.\n\taggDataPoints []float64                     // slice containing number of aggregated datapoints at each index\n}\n\n// init fills reaggregate.metric metric with initial data.\nfunc (m *metricReaggregateMetric) init() {\n\tm.data.SetName(\"reaggregate.metric\")\n\tm.data.SetDescription(\"Metric for testing spatial reaggregation\")\n\tm.data.SetUnit(\"1\")\n\tm.data.SetEmptyGauge()\n\tm.data.Gauge().DataPoints().EnsureCapacity(m.capacity)\n\tm.aggDataPoints = m.aggDataPoints[:0]\n}\n\nfunc (m *metricReaggregateMetric) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\n\tdp := pmetric.NewNumberDataPoint()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tif slices.Contains(m.config.EnabledAttributes, ReaggregateMetricMetricAttributeKeyStringAttr) {\n\t\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, ReaggregateMetricMetricAttributeKeyBooleanAttr) {\n\t\tdp.Attributes().PutBool(\"boolean_attr\", booleanAttrAttributeValue)\n\t}\n\n\tvar s string\n\tdps := m.data.Gauge().DataPoints()\n\tfor i := 0; i < dps.Len(); i++ {\n\t\tdpi := dps.At(i)\n\t\tif dp.Attributes().Equal(dpi.Attributes()) && dp.StartTimestamp() == dpi.StartTimestamp() && dp.Timestamp() == dpi.Timestamp() {\n\t\t\tswitch s = m.config.AggregationStrategy; s {\n\t\t\tcase AggregationStrategySum, AggregationStrategyAvg:\n\t\t\t\tdpi.SetDoubleValue(dpi.DoubleValue() + val)\n\t\t\t\tm.aggDataPoints[i] += 1\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMin:\n\t\t\t\tif dpi.DoubleValue() > val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMax:\n\t\t\t\tif dpi.DoubleValue() < val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdp.SetDoubleValue(val)\n\tm.aggDataPoints = append(m.aggDataPoints, 1)\n\tdp.MoveTo(dps.AppendEmpty())\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricReaggregateMetric) updateCapacity() {\n\tif m.data.Gauge().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Gauge().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricReaggregateMetric) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 {\n\t\tif m.config.AggregationStrategy == AggregationStrategyAvg {\n\t\t\tfor i, aggCount := range m.aggDataPoints {\n\t\t\t\tm.data.Gauge().DataPoints().At(i).SetDoubleValue(m.data.Gauge().DataPoints().At(i).DoubleValue() / aggCount)\n\t\t\t}\n\t\t}\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricReaggregateMetric(cfg ReaggregateMetricMetricConfig) metricReaggregateMetric {\n\tm := metricReaggregateMetric{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricReaggregateMetricWithRequired struct {\n\tdata          pmetric.Metric                            // data buffer for generated metric.\n\tconfig        ReaggregateMetricWithRequiredMetricConfig // metric config provided by user.\n\tcapacity      int                                       // max observed number of data points added to the metric.\n\taggDataPoints []float64                                 // slice containing number of aggregated datapoints at each index\n}\n\n// init fills reaggregate.metric.with_required metric with initial data.\nfunc (m *metricReaggregateMetricWithRequired) init() {\n\tm.data.SetName(\"reaggregate.metric.with_required\")\n\tm.data.SetDescription(\"Metric for testing spatial reaggregation with required attributes\")\n\tm.data.SetUnit(\"1\")\n\tm.data.SetEmptyGauge()\n\tm.data.Gauge().DataPoints().EnsureCapacity(m.capacity)\n\tm.aggDataPoints = m.aggDataPoints[:0]\n}\n\nfunc (m *metricReaggregateMetricWithRequired) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val float64, requiredStringAttrAttributeValue string, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\n\tdp := pmetric.NewNumberDataPoint()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tif slices.Contains(m.config.EnabledAttributes, ReaggregateMetricWithRequiredMetricAttributeKeyRequiredStringAttr) {\n\t\tdp.Attributes().PutStr(\"required_string_attr\", requiredStringAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, ReaggregateMetricWithRequiredMetricAttributeKeyStringAttr) {\n\t\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, ReaggregateMetricWithRequiredMetricAttributeKeyBooleanAttr) {\n\t\tdp.Attributes().PutBool(\"boolean_attr\", booleanAttrAttributeValue)\n\t}\n\n\tvar s string\n\tdps := m.data.Gauge().DataPoints()\n\tfor i := 0; i < dps.Len(); i++ {\n\t\tdpi := dps.At(i)\n\t\tif dp.Attributes().Equal(dpi.Attributes()) && dp.StartTimestamp() == dpi.StartTimestamp() && dp.Timestamp() == dpi.Timestamp() {\n\t\t\tswitch s = m.config.AggregationStrategy; s {\n\t\t\tcase AggregationStrategySum, AggregationStrategyAvg:\n\t\t\t\tdpi.SetDoubleValue(dpi.DoubleValue() + val)\n\t\t\t\tm.aggDataPoints[i] += 1\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMin:\n\t\t\t\tif dpi.DoubleValue() > val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMax:\n\t\t\t\tif dpi.DoubleValue() < val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdp.SetDoubleValue(val)\n\tm.aggDataPoints = append(m.aggDataPoints, 1)\n\tdp.MoveTo(dps.AppendEmpty())\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricReaggregateMetricWithRequired) updateCapacity() {\n\tif m.data.Gauge().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Gauge().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricReaggregateMetricWithRequired) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 {\n\t\tif m.config.AggregationStrategy == AggregationStrategyAvg {\n\t\t\tfor i, aggCount := range m.aggDataPoints {\n\t\t\t\tm.data.Gauge().DataPoints().At(i).SetDoubleValue(m.data.Gauge().DataPoints().At(i).DoubleValue() / aggCount)\n\t\t\t}\n\t\t}\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricReaggregateMetricWithRequired(cfg ReaggregateMetricWithRequiredMetricConfig) metricReaggregateMetricWithRequired {\n\tm := metricReaggregateMetricWithRequired{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricSystemCPUTime struct {\n\tdata     pmetric.Metric            // data buffer for generated metric.\n\tconfig   SystemCPUTimeMetricConfig // metric config provided by user.\n\tcapacity int                       // max observed number of data points added to the metric.\n}\n\n// init fills system.cpu.time metric with initial data.\nfunc (m *metricSystemCPUTime) init() {\n\tm.data.SetName(\"system.cpu.time\")\n\tm.data.SetDescription(\"Monotonic cumulative sum int metric enabled by default.\")\n\tm.data.SetUnit(\"s\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(true)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n}\n\nfunc (m *metricSystemCPUTime) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val int64) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\tdp := m.data.Sum().DataPoints().AppendEmpty()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tdp.SetIntValue(val)\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricSystemCPUTime) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricSystemCPUTime) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricSystemCPUTime(cfg SystemCPUTimeMetricConfig) metricSystemCPUTime {\n\tm := metricSystemCPUTime{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\n// MetricsBuilder provides an interface for scrapers to report metrics while taking care of all the transformations\n// required to produce metric representation defined in metadata and user config.\ntype MetricsBuilder struct {\n\tconfig                              MetricsBuilderConfig // config of the metrics builder.\n\tstartTime                           pcommon.Timestamp    // start time that will be applied to all recorded data points.\n\tmetricsCapacity                     int                  // maximum observed number of metrics per resource.\n\tmetricsBuffer                       pmetric.Metrics      // accumulates metrics data before emitting.\n\tbuildInfo                           component.BuildInfo  // contains version information.\n\tresourceAttributeIncludeFilter      map[string]filter.Filter\n\tresourceAttributeExcludeFilter      map[string]filter.Filter\n\tmetricDefaultMetric                 metricDefaultMetric\n\tmetricDefaultMetricToBeRemoved      metricDefaultMetricToBeRemoved\n\tmetricMetricInputType               metricMetricInputType\n\tmetricOptionalMetric                metricOptionalMetric\n\tmetricOptionalMetricEmptyUnit       metricOptionalMetricEmptyUnit\n\tmetricReaggregateMetric             metricReaggregateMetric\n\tmetricReaggregateMetricWithRequired metricReaggregateMetricWithRequired\n\tmetricSystemCPUTime                 metricSystemCPUTime\n}\n\n// MetricBuilderOption applies changes to default metrics builder.\ntype MetricBuilderOption interface {\n\tapply(*MetricsBuilder)\n}\n\ntype metricBuilderOptionFunc func(mb *MetricsBuilder)\n\nfunc (mbof metricBuilderOptionFunc) apply(mb *MetricsBuilder) {\n\tmbof(mb)\n}\n\n// WithStartTime sets startTime on the metrics builder.\nfunc WithStartTime(startTime pcommon.Timestamp) MetricBuilderOption {\n\treturn metricBuilderOptionFunc(func(mb *MetricsBuilder) {\n\t\tmb.startTime = startTime\n\t})\n}\nfunc NewMetricsBuilder(mbc MetricsBuilderConfig, settings receiver.Settings, options ...MetricBuilderOption) *MetricsBuilder {\n\tif !mbc.Metrics.DefaultMetric.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] Please set `enabled` field explicitly for `default.metric`: This metric will be disabled by default soon.\")\n\t}\n\tif mbc.Metrics.DefaultMetricToBeRemoved.Enabled {\n\t\tsettings.Logger.Warn(\"[WARNING] `default.metric.to_be_removed` should not be enabled: This metric is deprecated and will be removed soon.\")\n\t}\n\tif mbc.Metrics.OptionalMetric.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] `optional.metric` should not be configured: This metric is deprecated and will be removed soon.\")\n\t}\n\tif mbc.Metrics.OptionalMetricEmptyUnit.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] `optional.metric.empty_unit` should not be configured: This metric is deprecated and will be removed soon.\")\n\t}\n\tif !mbc.ResourceAttributes.StringResourceAttrDisableWarning.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] Please set `enabled` field explicitly for `string.resource.attr_disable_warning`: This resource_attribute will be disabled by default soon.\")\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrRemoveWarning.enabledSetByUser || mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsInclude != nil || mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsExclude != nil {\n\t\tsettings.Logger.Warn(\"[WARNING] `string.resource.attr_remove_warning` should not be configured: This resource_attribute is deprecated and will be removed soon.\")\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrToBeRemoved.Enabled {\n\t\tsettings.Logger.Warn(\"[WARNING] `string.resource.attr_to_be_removed` should not be enabled: This resource_attribute is deprecated and will be removed soon.\")\n\t}\n\tmb := &MetricsBuilder{\n\t\tconfig:                              mbc,\n\t\tstartTime:                           pcommon.NewTimestampFromTime(time.Now()),\n\t\tmetricsBuffer:                       pmetric.NewMetrics(),\n\t\tbuildInfo:                           settings.BuildInfo,\n\t\tmetricDefaultMetric:                 newMetricDefaultMetric(mbc.Metrics.DefaultMetric),\n\t\tmetricDefaultMetricToBeRemoved:      newMetricDefaultMetricToBeRemoved(mbc.Metrics.DefaultMetricToBeRemoved),\n\t\tmetricMetricInputType:               newMetricMetricInputType(mbc.Metrics.MetricInputType),\n\t\tmetricOptionalMetric:                newMetricOptionalMetric(mbc.Metrics.OptionalMetric),\n\t\tmetricOptionalMetricEmptyUnit:       newMetricOptionalMetricEmptyUnit(mbc.Metrics.OptionalMetricEmptyUnit),\n\t\tmetricReaggregateMetric:             newMetricReaggregateMetric(mbc.Metrics.ReaggregateMetric),\n\t\tmetricReaggregateMetricWithRequired: newMetricReaggregateMetricWithRequired(mbc.Metrics.ReaggregateMetricWithRequired),\n\t\tmetricSystemCPUTime:                 newMetricSystemCPUTime(mbc.Metrics.SystemCPUTime),\n\t\tresourceAttributeIncludeFilter:      make(map[string]filter.Filter),\n\t\tresourceAttributeExcludeFilter:      make(map[string]filter.Filter),\n\t}\n\tif mbc.ResourceAttributes.MapResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"map.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.MapResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.MapResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"map.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.MapResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.OptionalResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"optional.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.OptionalResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.OptionalResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"optional.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.OptionalResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.SliceResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"slice.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.SliceResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.SliceResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"slice.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.SliceResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringEnumResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.enum.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.StringEnumResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringEnumResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.enum.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.StringEnumResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrDisableWarning.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.resource.attr_disable_warning\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrDisableWarning.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrDisableWarning.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.resource.attr_disable_warning\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrDisableWarning.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.resource.attr_remove_warning\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.resource.attr_remove_warning\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrToBeRemoved.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.resource.attr_to_be_removed\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrToBeRemoved.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrToBeRemoved.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.resource.attr_to_be_removed\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrToBeRemoved.MetricsExclude)\n\t}\n\n\tfor _, op := range options {\n\t\top.apply(mb)\n\t}\n\treturn mb\n}\n\n// NewResourceBuilder returns a new resource builder that should be used to build a resource associated with for the emitted metrics.\nfunc (mb *MetricsBuilder) NewResourceBuilder() *ResourceBuilder {\n\treturn NewResourceBuilder(mb.config.ResourceAttributes)\n}\n\n// updateCapacity updates max length of metrics and resource attributes that will be used for the slice capacity.\nfunc (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n}\n\n// ResourceMetricsOption applies changes to provided resource metrics.\ntype ResourceMetricsOption interface {\n\tapply(pmetric.ResourceMetrics)\n}\n\ntype resourceMetricsOptionFunc func(pmetric.ResourceMetrics)\n\nfunc (rmof resourceMetricsOptionFunc) apply(rm pmetric.ResourceMetrics) {\n\trmof(rm)\n}\n\n// WithResource sets the provided resource on the emitted ResourceMetrics.\n// It's recommended to use ResourceBuilder to create the resource.\nfunc WithResource(res pcommon.Resource) ResourceMetricsOption {\n\treturn resourceMetricsOptionFunc(func(rm pmetric.ResourceMetrics) {\n\t\tres.CopyTo(rm.Resource())\n\t})\n}\n\n// WithStartTimeOverride overrides start time for all the resource metrics data points.\n// This option should be only used if different start time has to be set on metrics coming from different resources.\nfunc WithStartTimeOverride(start pcommon.Timestamp) ResourceMetricsOption {\n\treturn resourceMetricsOptionFunc(func(rm pmetric.ResourceMetrics) {\n\t\tvar dps pmetric.NumberDataPointSlice\n\t\tmetrics := rm.ScopeMetrics().At(0).Metrics()\n\t\tfor i := 0; i < metrics.Len(); i++ {\n\t\t\tswitch metrics.At(i).Type() {\n\t\t\tcase pmetric.MetricTypeGauge:\n\t\t\t\tdps = metrics.At(i).Gauge().DataPoints()\n\t\t\tcase pmetric.MetricTypeSum:\n\t\t\t\tdps = metrics.At(i).Sum().DataPoints()\n\t\t\t}\n\t\t\tfor j := 0; j < dps.Len(); j++ {\n\t\t\t\tdps.At(j).SetStartTimestamp(start)\n\t\t\t}\n\t\t}\n\t})\n}\n\n// EmitForResource saves all the generated metrics under a new resource and updates the internal state to be ready for\n// recording another set of data points as part of another resource. This function can be helpful when one scraper\n// needs to emit metrics from several resources. Otherwise calling this function is not required,\n// just `Emit` function can be called instead.\n// Resource attributes should be provided as ResourceMetricsOption arguments.\nfunc (mb *MetricsBuilder) EmitForResource(options ...ResourceMetricsOption) {\n\trm := pmetric.NewResourceMetrics()\n\trm.SetSchemaUrl(conventions.SchemaURL)\n\tils := rm.ScopeMetrics().AppendEmpty()\n\tils.Scope().SetName(ScopeName)\n\tils.Scope().SetVersion(mb.buildInfo.Version)\n\tils.Metrics().EnsureCapacity(mb.metricsCapacity)\n\tmb.metricDefaultMetric.emit(ils.Metrics())\n\tmb.metricDefaultMetricToBeRemoved.emit(ils.Metrics())\n\tmb.metricMetricInputType.emit(ils.Metrics())\n\tmb.metricOptionalMetric.emit(ils.Metrics())\n\tmb.metricOptionalMetricEmptyUnit.emit(ils.Metrics())\n\tmb.metricReaggregateMetric.emit(ils.Metrics())\n\tmb.metricReaggregateMetricWithRequired.emit(ils.Metrics())\n\tmb.metricSystemCPUTime.emit(ils.Metrics())\n\n\tfor _, op := range options {\n\t\top.apply(rm)\n\t}\n\tfor attr, filter := range mb.resourceAttributeIncludeFilter {\n\t\tif val, ok := rm.Resource().Attributes().Get(attr); ok && !filter.Matches(val.AsString()) {\n\t\t\treturn\n\t\t}\n\t}\n\tfor attr, filter := range mb.resourceAttributeExcludeFilter {\n\t\tif val, ok := rm.Resource().Attributes().Get(attr); ok && filter.Matches(val.AsString()) {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif ils.Metrics().Len() > 0 {\n\t\tmb.updateCapacity(rm)\n\t\trm.MoveTo(mb.metricsBuffer.ResourceMetrics().AppendEmpty())\n\t}\n}\n\n// Emit returns all the metrics accumulated by the metrics builder and updates the internal state to be ready for\n// recording another set of metrics. This function will be responsible for applying all the transformations required to\n// produce metric representation defined in metadata and user config, e.g. delta or cumulative.\nfunc (mb *MetricsBuilder) Emit(options ...ResourceMetricsOption) pmetric.Metrics {\n\tmb.EmitForResource(options...)\n\tmetrics := mb.metricsBuffer\n\tmb.metricsBuffer = pmetric.NewMetrics()\n\treturn metrics\n}\n\n// RecordDefaultMetricDataPoint adds a data point to default.metric metric.\nfunc (mb *MetricsBuilder) RecordDefaultMetricDataPoint(ts pcommon.Timestamp, val int64, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue AttributeEnumAttr, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any, optInBoolAttrAttributeValue bool, options ...MetricAttributeOption) {\n\tmb.metricDefaultMetric.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, overriddenIntAttrAttributeValue, enumAttrAttributeValue.String(), sliceAttrAttributeValue, mapAttrAttributeValue, optInBoolAttrAttributeValue, options...)\n}\n\n// RecordDefaultMetricToBeRemovedDataPoint adds a data point to default.metric.to_be_removed metric.\nfunc (mb *MetricsBuilder) RecordDefaultMetricToBeRemovedDataPoint(ts pcommon.Timestamp, val float64) {\n\tmb.metricDefaultMetricToBeRemoved.recordDataPoint(mb.startTime, ts, val)\n}\n\n// RecordMetricInputTypeDataPoint adds a data point to metric.input_type metric.\nfunc (mb *MetricsBuilder) RecordMetricInputTypeDataPoint(ts pcommon.Timestamp, inputVal string, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue AttributeEnumAttr, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MetricInputType, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMetricInputType.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, overriddenIntAttrAttributeValue, enumAttrAttributeValue.String(), sliceAttrAttributeValue, mapAttrAttributeValue)\n\treturn nil\n}\n\n// RecordOptionalMetricDataPoint adds a data point to optional.metric metric.\nfunc (mb *MetricsBuilder) RecordOptionalMetricDataPoint(ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool, booleanAttr2AttributeValue bool, options ...MetricAttributeOption) {\n\tmb.metricOptionalMetric.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, booleanAttrAttributeValue, booleanAttr2AttributeValue, options...)\n}\n\n// RecordOptionalMetricEmptyUnitDataPoint adds a data point to optional.metric.empty_unit metric.\nfunc (mb *MetricsBuilder) RecordOptionalMetricEmptyUnitDataPoint(ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\tmb.metricOptionalMetricEmptyUnit.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, booleanAttrAttributeValue)\n}\n\n// RecordReaggregateMetricDataPoint adds a data point to reaggregate.metric metric.\nfunc (mb *MetricsBuilder) RecordReaggregateMetricDataPoint(ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\tmb.metricReaggregateMetric.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, booleanAttrAttributeValue)\n}\n\n// RecordReaggregateMetricWithRequiredDataPoint adds a data point to reaggregate.metric.with_required metric.\nfunc (mb *MetricsBuilder) RecordReaggregateMetricWithRequiredDataPoint(ts pcommon.Timestamp, val float64, requiredStringAttrAttributeValue string, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\tmb.metricReaggregateMetricWithRequired.recordDataPoint(mb.startTime, ts, val, requiredStringAttrAttributeValue, stringAttrAttributeValue, booleanAttrAttributeValue)\n}\n\n// RecordSystemCPUTimeDataPoint adds a data point to system.cpu.time metric.\nfunc (mb *MetricsBuilder) RecordSystemCPUTimeDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricSystemCPUTime.recordDataPoint(mb.startTime, ts, val)\n}\n\n// Reset resets metrics builder to its initial state. It should be used when external metrics source is restarted,\n// and metrics builder should update its startTime and reset it's internal state accordingly.\nfunc (mb *MetricsBuilder) Reset(options ...MetricBuilderOption) {\n\tmb.startTime = pcommon.NewTimestampFromTime(time.Now())\n\tfor _, op := range options {\n\t\top.apply(mb)\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_metrics_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\ntype testDataSet int\n\nconst (\n\ttestDataSetDefault testDataSet = iota\n\ttestDataSetAll\n\ttestDataSetNone\n\ttestDataSetReag\n)\n\nfunc TestMetricsBuilder(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tmetricsSet  testDataSet\n\t\tresAttrsSet testDataSet\n\t\texpectEmpty bool\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t},\n\t\t{\n\t\t\tname:        \"all_set\",\n\t\t\tmetricsSet:  testDataSetAll,\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t},\n\t\t{\n\t\t\tname:        \"reaggregate_set\",\n\t\t\tmetricsSet:  testDataSetReag,\n\t\t\tresAttrsSet: testDataSetReag,\n\t\t},\n\t\t{\n\t\t\tname:        \"none_set\",\n\t\t\tmetricsSet:  testDataSetNone,\n\t\t\tresAttrsSet: testDataSetNone,\n\t\t\texpectEmpty: true,\n\t\t},\n\t\t{\n\t\t\tname:        \"filter_set_include\",\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t},\n\t\t{\n\t\t\tname:        \"filter_set_exclude\",\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t\texpectEmpty: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tstart := pcommon.Timestamp(1_000_000_000)\n\t\t\tts := pcommon.Timestamp(1_000_001_000)\n\t\t\tobservedZapCore, observedLogs := observer.New(zap.WarnLevel)\n\t\t\tsettings := receivertest.NewNopSettings(receivertest.NopType)\n\t\t\tsettings.Logger = zap.New(observedZapCore)\n\t\t\tmb := NewMetricsBuilder(loadMetricsBuilderConfig(t, tt.name), settings, WithStartTime(start))\n\t\t\taggMap := make(map[string]string) // contains the aggregation strategies for each metric name\n\t\t\taggMap[\"DefaultMetric\"] = mb.metricDefaultMetric.config.AggregationStrategy\n\t\t\taggMap[\"MetricInputType\"] = mb.metricMetricInputType.config.AggregationStrategy\n\t\t\taggMap[\"OptionalMetric\"] = mb.metricOptionalMetric.config.AggregationStrategy\n\t\t\taggMap[\"OptionalMetricEmptyUnit\"] = mb.metricOptionalMetricEmptyUnit.config.AggregationStrategy\n\t\t\taggMap[\"ReaggregateMetric\"] = mb.metricReaggregateMetric.config.AggregationStrategy\n\t\t\taggMap[\"ReaggregateMetricWithRequired\"] = mb.metricReaggregateMetricWithRequired.config.AggregationStrategy\n\n\t\t\texpectedWarnings := 0\n\t\t\tif tt.metricsSet == testDataSetDefault {\n\t\t\t\tassert.Equal(t, \"[WARNING] Please set `enabled` field explicitly for `default.metric`: This metric will be disabled by default soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetDefault || tt.metricsSet == testDataSetAll {\n\t\t\t\tassert.Equal(t, \"[WARNING] `default.metric.to_be_removed` should not be enabled: This metric is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetAll || tt.metricsSet == testDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `optional.metric` should not be configured: This metric is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetAll || tt.metricsSet == testDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `optional.metric.empty_unit` should not be configured: This metric is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.resAttrsSet == testDataSetDefault {\n\t\t\t\tassert.Equal(t, \"[WARNING] Please set `enabled` field explicitly for `string.resource.attr_disable_warning`: This resource_attribute will be disabled by default soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.resAttrsSet == testDataSetAll || tt.resAttrsSet == testDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `string.resource.attr_remove_warning` should not be configured: This resource_attribute is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.resAttrsSet == testDataSetDefault || tt.resAttrsSet == testDataSetAll {\n\t\t\t\tassert.Equal(t, \"[WARNING] `string.resource.attr_to_be_removed` should not be enabled: This resource_attribute is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.metricsSet != testDataSetReag {\n\t\t\t\tassert.Equal(t, expectedWarnings, observedLogs.Len())\n\t\t\t}\n\n\t\t\tdefaultMetricsCount := 0\n\t\t\tallMetricsCount := 0\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordDefaultMetricDataPoint(ts, 1, \"string_attr-val\", 19, AttributeEnumAttrRed, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"}, true, WithConditionalIntAttrMetricAttribute(20), WithConditionalStringAttrMetricAttribute(\"conditional_string_attr-val\"))\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tmb.RecordDefaultMetricDataPoint(ts, 3, \"string_attr-val-2\", 20, AttributeEnumAttrGreen, []any{\"slice_attr-item3\", \"slice_attr-item4\"}, map[string]any{\"key3\": \"map_attr-val3\", \"key4\": \"map_attr-val4\"}, false, WithConditionalIntAttrMetricAttribute(20), WithConditionalStringAttrMetricAttribute(\"conditional_string_attr-val\"))\n\t\t\t}\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordDefaultMetricToBeRemovedDataPoint(ts, 1)\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordMetricInputTypeDataPoint(ts, \"1\", \"string_attr-val\", 19, AttributeEnumAttrRed, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"})\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tmb.RecordMetricInputTypeDataPoint(ts, \"3\", \"string_attr-val-2\", 20, AttributeEnumAttrGreen, []any{\"slice_attr-item3\", \"slice_attr-item4\"}, map[string]any{\"key3\": \"map_attr-val3\", \"key4\": \"map_attr-val4\"})\n\t\t\t}\n\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordOptionalMetricDataPoint(ts, 1, \"string_attr-val\", true, false, WithConditionalStringAttrMetricAttribute(\"conditional_string_attr-val\"))\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tmb.RecordOptionalMetricDataPoint(ts, 3, \"string_attr-val-2\", false, true, WithConditionalStringAttrMetricAttribute(\"conditional_string_attr-val\"))\n\t\t\t}\n\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordOptionalMetricEmptyUnitDataPoint(ts, 1, \"string_attr-val\", true)\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tmb.RecordOptionalMetricEmptyUnitDataPoint(ts, 3, \"string_attr-val-2\", false)\n\t\t\t}\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordReaggregateMetricDataPoint(ts, 1, \"string_attr-val\", true)\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tmb.RecordReaggregateMetricDataPoint(ts, 3, \"string_attr-val-2\", false)\n\t\t\t}\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordReaggregateMetricWithRequiredDataPoint(ts, 1, \"required_string_attr-val\", \"string_attr-val\", true)\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tmb.RecordReaggregateMetricWithRequiredDataPoint(ts, 3, \"required_string_attr-val\", \"string_attr-val-2\", false)\n\t\t\t}\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordSystemCPUTimeDataPoint(ts, 1)\n\n\t\t\trb := mb.NewResourceBuilder()\n\t\t\trb.SetMapResourceAttr(map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"})\n\t\t\trb.SetOptionalResourceAttr(\"optional.resource.attr-val\")\n\t\t\trb.SetSliceResourceAttr([]any{\"slice.resource.attr-item1\", \"slice.resource.attr-item2\"})\n\t\t\trb.SetStringEnumResourceAttrOne()\n\t\t\trb.SetStringResourceAttr(\"string.resource.attr-val\")\n\t\t\trb.SetStringResourceAttrDisableWarning(\"string.resource.attr_disable_warning-val\")\n\t\t\trb.SetStringResourceAttrRemoveWarning(\"string.resource.attr_remove_warning-val\")\n\t\t\trb.SetStringResourceAttrToBeRemoved(\"string.resource.attr_to_be_removed-val\")\n\t\t\tres := rb.Emit()\n\t\t\tmetrics := mb.Emit(WithResource(res))\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tassert.Empty(t, mb.metricDefaultMetric.aggDataPoints)\n\t\t\t\tassert.Empty(t, mb.metricMetricInputType.aggDataPoints)\n\t\t\t\tassert.Empty(t, mb.metricOptionalMetric.aggDataPoints)\n\t\t\t\tassert.Empty(t, mb.metricOptionalMetricEmptyUnit.aggDataPoints)\n\t\t\t\tassert.Empty(t, mb.metricReaggregateMetric.aggDataPoints)\n\t\t\t\tassert.Empty(t, mb.metricReaggregateMetricWithRequired.aggDataPoints)\n\t\t\t}\n\n\t\t\tif tt.expectEmpty {\n\t\t\t\tassert.Equal(t, 0, metrics.ResourceMetrics().Len())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar allMetricsList []pmetric.Metric\n\t\t\ttotalMetricsCount := 0\n\t\t\tfor ri := 0; ri < metrics.ResourceMetrics().Len(); ri++ {\n\t\t\t\trm := metrics.ResourceMetrics().At(ri)\n\t\t\t\tassert.Equal(t, 1, rm.ScopeMetrics().Len())\n\t\t\t\tms := rm.ScopeMetrics().At(0).Metrics()\n\t\t\t\ttotalMetricsCount += ms.Len()\n\t\t\t\tfor mi := 0; mi < ms.Len(); mi++ {\n\t\t\t\t\tallMetricsList = append(allMetricsList, ms.At(mi))\n\t\t\t\t}\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetDefault {\n\t\t\t\tassert.Equal(t, defaultMetricsCount, totalMetricsCount)\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetAll {\n\t\t\t\tassert.Equal(t, allMetricsCount, totalMetricsCount)\n\t\t\t}\n\t\t\tvalidatedMetrics := make(map[string]bool)\n\t\t\tfor _, mi := range allMetricsList {\n\t\t\t\tswitch mi.Name() {\n\t\t\t\tcase \"default.metric\":\n\t\t\t\t\tif tt.name != \"reaggregate_set\" {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"default.metric\"], \"Found a duplicate in the metrics slice: default.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"default.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Monotonic cumulative sum int metric enabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\t\tassert.True(t, mi.Sum().IsMonotonic())\n\t\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, mi.Sum().AggregationTemporality())\n\t\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t\t\tstringAttrAttrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"string_attr-val\", stringAttrAttrVal.Str())\n\t\t\t\t\t\toverriddenIntAttrAttrVal, ok := dp.Attributes().Get(\"state\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.EqualValues(t, 19, overriddenIntAttrAttrVal.Int())\n\t\t\t\t\t\tenumAttrAttrVal, ok := dp.Attributes().Get(\"enum_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"red\", enumAttrAttrVal.Str())\n\t\t\t\t\t\tsliceAttrAttrVal, ok := dp.Attributes().Get(\"slice_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, sliceAttrAttrVal.Slice().AsRaw())\n\t\t\t\t\t\tmapAttrAttrVal, ok := dp.Attributes().Get(\"map_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"}, mapAttrAttrVal.Map().AsRaw())\n\t\t\t\t\t\tconditionalIntAttrAttrVal, ok := dp.Attributes().Get(\"conditional_int_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.EqualValues(t, 20, conditionalIntAttrAttrVal.Int())\n\t\t\t\t\t\tconditionalStringAttrAttrVal, ok := dp.Attributes().Get(\"conditional_string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"conditional_string_attr-val\", conditionalStringAttrAttrVal.Str())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"default.metric\"], \"Found a duplicate in the metrics slice: default.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"default.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Monotonic cumulative sum int metric enabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\t\tassert.True(t, mi.Sum().IsMonotonic())\n\t\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, mi.Sum().AggregationTemporality())\n\t\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\t\tswitch aggMap[\"default.metric\"] {\n\t\t\t\t\t\tcase \"sum\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(4), dp.IntValue())\n\t\t\t\t\t\tcase \"avg\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(2), dp.IntValue())\n\t\t\t\t\t\tcase \"min\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t\t\tcase \"max\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(3), dp.IntValue())\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"state\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"enum_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"slice_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"map_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"opt_in_bool_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t}\n\t\t\t\tcase \"default.metric.to_be_removed\":\n\t\t\t\t\tassert.False(t, validatedMetrics[\"default.metric.to_be_removed\"], \"Found a duplicate in the metrics slice: default.metric.to_be_removed\")\n\t\t\t\t\tvalidatedMetrics[\"default.metric.to_be_removed\"] = true\n\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Non-monotonic delta sum double metric enabled by default.\", mi.Description())\n\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\tassert.False(t, mi.Sum().IsMonotonic())\n\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityDelta, mi.Sum().AggregationTemporality())\n\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\tcase \"metric.input_type\":\n\t\t\t\t\tif tt.name != \"reaggregate_set\" {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"metric.input_type\"], \"Found a duplicate in the metrics slice: metric.input_type\")\n\t\t\t\t\t\tvalidatedMetrics[\"metric.input_type\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Monotonic cumulative sum int metric with string input_type enabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\t\tassert.True(t, mi.Sum().IsMonotonic())\n\t\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, mi.Sum().AggregationTemporality())\n\t\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t\t\tstringAttrAttrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"string_attr-val\", stringAttrAttrVal.Str())\n\t\t\t\t\t\toverriddenIntAttrAttrVal, ok := dp.Attributes().Get(\"state\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.EqualValues(t, 19, overriddenIntAttrAttrVal.Int())\n\t\t\t\t\t\tenumAttrAttrVal, ok := dp.Attributes().Get(\"enum_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"red\", enumAttrAttrVal.Str())\n\t\t\t\t\t\tsliceAttrAttrVal, ok := dp.Attributes().Get(\"slice_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, sliceAttrAttrVal.Slice().AsRaw())\n\t\t\t\t\t\tmapAttrAttrVal, ok := dp.Attributes().Get(\"map_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"}, mapAttrAttrVal.Map().AsRaw())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"metric.input_type\"], \"Found a duplicate in the metrics slice: metric.input_type\")\n\t\t\t\t\t\tvalidatedMetrics[\"metric.input_type\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Monotonic cumulative sum int metric with string input_type enabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\t\tassert.True(t, mi.Sum().IsMonotonic())\n\t\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, mi.Sum().AggregationTemporality())\n\t\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\t\tswitch aggMap[\"metric.input_type\"] {\n\t\t\t\t\t\tcase \"sum\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(4), dp.IntValue())\n\t\t\t\t\t\tcase \"avg\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(2), dp.IntValue())\n\t\t\t\t\t\tcase \"min\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t\t\tcase \"max\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(3), dp.IntValue())\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"state\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"enum_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"slice_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"map_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t}\n\t\t\t\tcase \"optional.metric\":\n\t\t\t\t\tif tt.name != \"reaggregate_set\" {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"optional.metric\"], \"Found a duplicate in the metrics slice: optional.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"optional.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Gauge double metric disabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"1\", mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tstringAttrAttrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"string_attr-val\", stringAttrAttrVal.Str())\n\t\t\t\t\t\tbooleanAttrAttrVal, ok := dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.True(t, booleanAttrAttrVal.Bool())\n\t\t\t\t\t\tbooleanAttr2AttrVal, ok := dp.Attributes().Get(\"boolean_attr2\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.False(t, booleanAttr2AttrVal.Bool())\n\t\t\t\t\t\tconditionalStringAttrAttrVal, ok := dp.Attributes().Get(\"conditional_string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"conditional_string_attr-val\", conditionalStringAttrAttrVal.Str())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"optional.metric\"], \"Found a duplicate in the metrics slice: optional.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"optional.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Gauge double metric disabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"1\", mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tswitch aggMap[\"optional.metric\"] {\n\t\t\t\t\t\tcase \"sum\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(4), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"avg\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(2), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"min\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"max\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(3), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"boolean_attr2\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t}\n\t\t\t\tcase \"optional.metric.empty_unit\":\n\t\t\t\t\tif tt.name != \"reaggregate_set\" {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"optional.metric.empty_unit\"], \"Found a duplicate in the metrics slice: optional.metric.empty_unit\")\n\t\t\t\t\t\tvalidatedMetrics[\"optional.metric.empty_unit\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Gauge double metric disabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Empty(t, mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tstringAttrAttrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"string_attr-val\", stringAttrAttrVal.Str())\n\t\t\t\t\t\tbooleanAttrAttrVal, ok := dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.True(t, booleanAttrAttrVal.Bool())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"optional.metric.empty_unit\"], \"Found a duplicate in the metrics slice: optional.metric.empty_unit\")\n\t\t\t\t\t\tvalidatedMetrics[\"optional.metric.empty_unit\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Gauge double metric disabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Empty(t, mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tswitch aggMap[\"optional.metric.empty_unit\"] {\n\t\t\t\t\t\tcase \"sum\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(4), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"avg\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(2), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"min\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"max\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(3), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t}\n\t\t\t\tcase \"reaggregate.metric\":\n\t\t\t\t\tif tt.name != \"reaggregate_set\" {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"reaggregate.metric\"], \"Found a duplicate in the metrics slice: reaggregate.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"reaggregate.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Metric for testing spatial reaggregation\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"1\", mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tstringAttrAttrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"string_attr-val\", stringAttrAttrVal.Str())\n\t\t\t\t\t\tbooleanAttrAttrVal, ok := dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.True(t, booleanAttrAttrVal.Bool())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"reaggregate.metric\"], \"Found a duplicate in the metrics slice: reaggregate.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"reaggregate.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Metric for testing spatial reaggregation\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"1\", mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tswitch aggMap[\"reaggregate.metric\"] {\n\t\t\t\t\t\tcase \"sum\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(4), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"avg\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(2), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"min\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"max\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(3), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t}\n\t\t\t\tcase \"reaggregate.metric.with_required\":\n\t\t\t\t\tif tt.name != \"reaggregate_set\" {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"reaggregate.metric.with_required\"], \"Found a duplicate in the metrics slice: reaggregate.metric.with_required\")\n\t\t\t\t\t\tvalidatedMetrics[\"reaggregate.metric.with_required\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Metric for testing spatial reaggregation with required attributes\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"1\", mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\trequiredStringAttrAttrVal, ok := dp.Attributes().Get(\"required_string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"required_string_attr-val\", requiredStringAttrAttrVal.Str())\n\t\t\t\t\t\tstringAttrAttrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"string_attr-val\", stringAttrAttrVal.Str())\n\t\t\t\t\t\tbooleanAttrAttrVal, ok := dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.True(t, booleanAttrAttrVal.Bool())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"reaggregate.metric.with_required\"], \"Found a duplicate in the metrics slice: reaggregate.metric.with_required\")\n\t\t\t\t\t\tvalidatedMetrics[\"reaggregate.metric.with_required\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Metric for testing spatial reaggregation with required attributes\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"1\", mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tswitch aggMap[\"reaggregate.metric.with_required\"] {\n\t\t\t\t\t\tcase \"sum\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(4), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"avg\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(2), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"min\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"max\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(3), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_, ok := dp.Attributes().Get(\"required_string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t}\n\t\t\t\tcase \"system.cpu.time\":\n\t\t\t\t\tassert.False(t, validatedMetrics[\"system.cpu.time\"], \"Found a duplicate in the metrics slice: system.cpu.time\")\n\t\t\t\t\tvalidatedMetrics[\"system.cpu.time\"] = true\n\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\tassert.Equal(t, \"Monotonic cumulative sum int metric enabled by default.\", mi.Description())\n\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\tassert.True(t, mi.Sum().IsMonotonic())\n\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, mi.Sum().AggregationTemporality())\n\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_resource.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ResourceBuilder is a helper struct to build resources predefined in metadata.yaml.\n// The ResourceBuilder is not thread-safe and must not to be used in multiple goroutines.\ntype ResourceBuilder struct {\n\tconfig ResourceAttributesConfig\n\tres    pcommon.Resource\n}\n\n// NewResourceBuilder creates a new ResourceBuilder. This method should be called on the start of the application.\nfunc NewResourceBuilder(rac ResourceAttributesConfig) *ResourceBuilder {\n\treturn &ResourceBuilder{\n\t\tconfig: rac,\n\t\tres:    pcommon.NewResource(),\n\t}\n}\n\n// SetMapResourceAttr sets provided value as \"map.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetMapResourceAttr(val map[string]any) {\n\tif rb.config.MapResourceAttr.Enabled {\n\t\trb.res.Attributes().PutEmptyMap(\"map.resource.attr\").FromRaw(val)\n\t}\n}\n\n// SetOptionalResourceAttr sets provided value as \"optional.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetOptionalResourceAttr(val string) {\n\tif rb.config.OptionalResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"optional.resource.attr\", val)\n\t}\n}\n\n// SetSliceResourceAttr sets provided value as \"slice.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetSliceResourceAttr(val []any) {\n\tif rb.config.SliceResourceAttr.Enabled {\n\t\trb.res.Attributes().PutEmptySlice(\"slice.resource.attr\").FromRaw(val)\n\t}\n}\n\n// SetStringEnumResourceAttrOne sets \"string.enum.resource.attr=one\" attribute.\nfunc (rb *ResourceBuilder) SetStringEnumResourceAttrOne() {\n\tif rb.config.StringEnumResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.enum.resource.attr\", \"one\")\n\t}\n}\n\n// SetStringEnumResourceAttrTwo sets \"string.enum.resource.attr=two\" attribute.\nfunc (rb *ResourceBuilder) SetStringEnumResourceAttrTwo() {\n\tif rb.config.StringEnumResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.enum.resource.attr\", \"two\")\n\t}\n}\n\n// SetStringResourceAttr sets provided value as \"string.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttr(val string) {\n\tif rb.config.StringResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr\", val)\n\t}\n}\n\n// SetStringResourceAttrDisableWarning sets provided value as \"string.resource.attr_disable_warning\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttrDisableWarning(val string) {\n\tif rb.config.StringResourceAttrDisableWarning.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr_disable_warning\", val)\n\t}\n}\n\n// SetStringResourceAttrRemoveWarning sets provided value as \"string.resource.attr_remove_warning\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttrRemoveWarning(val string) {\n\tif rb.config.StringResourceAttrRemoveWarning.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr_remove_warning\", val)\n\t}\n}\n\n// SetStringResourceAttrToBeRemoved sets provided value as \"string.resource.attr_to_be_removed\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttrToBeRemoved(val string) {\n\tif rb.config.StringResourceAttrToBeRemoved.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr_to_be_removed\", val)\n\t}\n}\n\n// Emit returns the built resource and resets the internal builder state.\nfunc (rb *ResourceBuilder) Emit() pcommon.Resource {\n\tr := rb.res\n\trb.res = pcommon.NewResource()\n\treturn r\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_resource_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestResourceBuilder(t *testing.T) {\n\tfor _, tt := range []string{\"default\", \"all_set\", \"none_set\"} {\n\t\tt.Run(tt, func(t *testing.T) {\n\t\t\tcfg := loadResourceAttributesConfig(t, tt)\n\t\t\trb := NewResourceBuilder(cfg)\n\t\t\trb.SetMapResourceAttr(map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"})\n\t\t\trb.SetOptionalResourceAttr(\"optional.resource.attr-val\")\n\t\t\trb.SetSliceResourceAttr([]any{\"slice.resource.attr-item1\", \"slice.resource.attr-item2\"})\n\t\t\trb.SetStringEnumResourceAttrOne()\n\t\t\trb.SetStringResourceAttr(\"string.resource.attr-val\")\n\t\t\trb.SetStringResourceAttrDisableWarning(\"string.resource.attr_disable_warning-val\")\n\t\t\trb.SetStringResourceAttrRemoveWarning(\"string.resource.attr_remove_warning-val\")\n\t\t\trb.SetStringResourceAttrToBeRemoved(\"string.resource.attr_to_be_removed-val\")\n\n\t\t\tres := rb.Emit()\n\t\t\tassert.Equal(t, 0, rb.Emit().Attributes().Len()) // Second call should return empty Resource\n\n\t\t\tswitch tt {\n\t\t\tcase \"default\":\n\t\t\t\tassert.Equal(t, 6, res.Attributes().Len())\n\t\t\tcase \"all_set\":\n\t\t\t\tassert.Equal(t, 8, res.Attributes().Len())\n\t\t\tcase \"none_set\":\n\t\t\t\tassert.Equal(t, 0, res.Attributes().Len())\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tassert.Failf(t, \"unexpected test case: %s\", tt)\n\t\t\t}\n\t\t\tmapResourceAttrAttrVal, ok := res.Attributes().Get(\"map.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"}, mapResourceAttrAttrVal.Map().AsRaw())\n\t\t\t}\n\t\t\toptionalResourceAttrAttrVal, ok := res.Attributes().Get(\"optional.resource.attr\")\n\t\t\tassert.Equal(t, tt == \"all_set\", ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"optional.resource.attr-val\", optionalResourceAttrAttrVal.Str())\n\t\t\t}\n\t\t\tsliceResourceAttrAttrVal, ok := res.Attributes().Get(\"slice.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, []any{\"slice.resource.attr-item1\", \"slice.resource.attr-item2\"}, sliceResourceAttrAttrVal.Slice().AsRaw())\n\t\t\t}\n\t\t\tstringEnumResourceAttrAttrVal, ok := res.Attributes().Get(\"string.enum.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"one\", stringEnumResourceAttrAttrVal.Str())\n\t\t\t}\n\t\t\tstringResourceAttrAttrVal, ok := res.Attributes().Get(\"string.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr-val\", stringResourceAttrAttrVal.Str())\n\t\t\t}\n\t\t\tstringResourceAttrDisableWarningAttrVal, ok := res.Attributes().Get(\"string.resource.attr_disable_warning\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr_disable_warning-val\", stringResourceAttrDisableWarningAttrVal.Str())\n\t\t\t}\n\t\t\tstringResourceAttrRemoveWarningAttrVal, ok := res.Attributes().Get(\"string.resource.attr_remove_warning\")\n\t\t\tassert.Equal(t, tt == \"all_set\", ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr_remove_warning-val\", stringResourceAttrRemoveWarningAttrVal.Str())\n\t\t\t}\n\t\t\tstringResourceAttrToBeRemovedAttrVal, ok := res.Attributes().Get(\"string.resource.attr_to_be_removed\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr_to_be_removed-val\", stringResourceAttrToBeRemovedAttrVal.Str())\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"sample\")\n\tScopeName = \"go.opentelemetry.io/collector/internal/receiver/samplereceiver\"\n)\n\nconst (\n\tProfilesStability = component.StabilityLevelDeprecated\n\tLogsStability     = component.StabilityLevelDevelopment\n\tTracesStability   = component.StabilityLevelBeta\n\tMetricsStability  = component.StabilityLevelStable\n)\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_telemetry.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/metric/embedded\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc Meter(settings component.TelemetrySettings) metric.Meter {\n\treturn settings.MeterProvider.Meter(\"go.opentelemetry.io/collector/internal/receiver/samplereceiver\")\n}\n\nfunc Tracer(settings component.TelemetrySettings) trace.Tracer {\n\treturn settings.TracerProvider.Tracer(\"go.opentelemetry.io/collector/internal/receiver/samplereceiver\")\n}\n\n// TelemetryBuilder provides an interface for components to report telemetry\n// as defined in metadata and user config.\ntype TelemetryBuilder struct {\n\tmeter                         metric.Meter\n\tmu                            sync.Mutex\n\tregistrations                 []metric.Registration\n\tBatchSizeTriggerSend          metric.Int64Counter\n\tProcessRuntimeTotalAllocBytes metric.Int64ObservableCounter\n\tQueueCapacity                 metric.Int64Gauge\n\tQueueLength                   metric.Int64ObservableGauge\n\tRequestDuration               metric.Float64Histogram\n}\n\n// TelemetryBuilderOption applies changes to default builder.\ntype TelemetryBuilderOption interface {\n\tapply(*TelemetryBuilder)\n}\n\ntype telemetryBuilderOptionFunc func(mb *TelemetryBuilder)\n\nfunc (tbof telemetryBuilderOptionFunc) apply(mb *TelemetryBuilder) {\n\ttbof(mb)\n}\n\n// RegisterProcessRuntimeTotalAllocBytesCallback sets callback for observable ProcessRuntimeTotalAllocBytes metric.\nfunc (builder *TelemetryBuilder) RegisterProcessRuntimeTotalAllocBytesCallback(cb metric.Int64Callback) error {\n\treg, err := builder.meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {\n\t\tcb(ctx, &observerInt64{inst: builder.ProcessRuntimeTotalAllocBytes, obs: o})\n\t\treturn nil\n\t}, builder.ProcessRuntimeTotalAllocBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tbuilder.registrations = append(builder.registrations, reg)\n\treturn nil\n}\n\n// RegisterQueueLengthCallback sets callback for observable QueueLength metric.\nfunc (builder *TelemetryBuilder) RegisterQueueLengthCallback(cb metric.Int64Callback) error {\n\treg, err := builder.meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {\n\t\tcb(ctx, &observerInt64{inst: builder.QueueLength, obs: o})\n\t\treturn nil\n\t}, builder.QueueLength)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tbuilder.registrations = append(builder.registrations, reg)\n\treturn nil\n}\n\ntype observerInt64 struct {\n\tembedded.Int64Observer\n\tinst metric.Int64Observable\n\tobs  metric.Observer\n}\n\nfunc (oi *observerInt64) Observe(value int64, opts ...metric.ObserveOption) {\n\toi.obs.ObserveInt64(oi.inst, value, opts...)\n}\n\n// Shutdown unregister all registered callbacks for async instruments.\nfunc (builder *TelemetryBuilder) Shutdown() {\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tfor _, reg := range builder.registrations {\n\t\treg.Unregister()\n\t}\n}\n\n// NewTelemetryBuilder provides a struct with methods to update all internal telemetry\n// for a component\nfunc NewTelemetryBuilder(settings component.TelemetrySettings, options ...TelemetryBuilderOption) (*TelemetryBuilder, error) {\n\tbuilder := TelemetryBuilder{}\n\tfor _, op := range options {\n\t\top.apply(&builder)\n\t}\n\tbuilder.meter = Meter(settings)\n\tvar err, errs error\n\tbuilder.BatchSizeTriggerSend, err = builder.meter.Int64Counter(\n\t\t\"otelcol_batch_size_trigger_send\",\n\t\tmetric.WithDescription(\"Number of times the batch was sent due to a size trigger [Deprecated]\"),\n\t\tmetric.WithUnit(\"{time}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessRuntimeTotalAllocBytes, err = builder.meter.Int64ObservableCounter(\n\t\t\"otelcol_process_runtime_total_alloc_bytes\",\n\t\tmetric.WithDescription(\"Cumulative bytes allocated for heap objects (see 'go doc runtime.MemStats.TotalAlloc') [Stable]\"),\n\t\tmetric.WithUnit(\"By\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.QueueCapacity, err = builder.meter.Int64Gauge(\n\t\t\"otelcol_queue_capacity\",\n\t\tmetric.WithDescription(\"Queue capacity - sync gauge example. [Development]\"),\n\t\tmetric.WithUnit(\"{item}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.QueueLength, err = builder.meter.Int64ObservableGauge(\n\t\t\"otelcol_queue_length\",\n\t\tmetric.WithDescription(\"This metric is optional and therefore not initialized in NewTelemetryBuilder. [Alpha]\"),\n\t\tmetric.WithUnit(\"{item}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.RequestDuration, err = builder.meter.Float64Histogram(\n\t\t\"otelcol_request_duration\",\n\t\tmetric.WithDescription(\"Duration of request [Alpha]\"),\n\t\tmetric.WithUnit(\"s\"),\n\t\tmetric.WithExplicitBucketBoundaries([]float64{1, 10, 100}...),\n\t)\n\terrs = errors.Join(errs, err)\n\treturn &builder, errs\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/internal/metadata/generated_telemetry_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/metric\"\n\tembeddedmetric \"go.opentelemetry.io/otel/metric/embedded\"\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\t\"go.opentelemetry.io/otel/trace\"\n\tembeddedtrace \"go.opentelemetry.io/otel/trace/embedded\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\ntype mockMeter struct {\n\tnoopmetric.Meter\n\tname string\n}\ntype mockMeterProvider struct {\n\tembeddedmetric.MeterProvider\n}\n\nfunc (m mockMeterProvider) Meter(name string, opts ...metric.MeterOption) metric.Meter {\n\treturn mockMeter{name: name}\n}\n\ntype mockTracer struct {\n\tnooptrace.Tracer\n\tname string\n}\n\ntype mockTracerProvider struct {\n\tembeddedtrace.TracerProvider\n}\n\nfunc (m mockTracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer {\n\treturn mockTracer{name: name}\n}\n\nfunc TestProviders(t *testing.T) {\n\tset := component.TelemetrySettings{\n\t\tMeterProvider:  mockMeterProvider{},\n\t\tTracerProvider: mockTracerProvider{},\n\t}\n\n\tmeter := Meter(set)\n\tif m, ok := meter.(mockMeter); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/internal/receiver/samplereceiver\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockMeter\")\n\t}\n\n\ttracer := Tracer(set)\n\tif m, ok := tracer.(mockTracer); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/internal/receiver/samplereceiver\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockTracer\")\n\t}\n}\n\nfunc TestNewTelemetryBuilder(t *testing.T) {\n\tset := componenttest.NewNopTelemetrySettings()\n\tapplied := false\n\t_, err := NewTelemetryBuilder(set, telemetryBuilderOptionFunc(func(b *TelemetryBuilder) {\n\t\tapplied = true\n\t}))\n\trequire.NoError(t, err)\n\trequire.True(t, applied)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/internal/metadata/testdata/config.yaml",
    "content": "default:\nall_set:\n  metrics:\n    default.metric:\n      enabled: true\n      attributes: [\"string_attr\",\"state\",\"enum_attr\",\"slice_attr\",\"map_attr\",\"conditional_int_attr\",\"conditional_string_attr\",\"opt_in_bool_attr\"]\n    default.metric.to_be_removed:\n      enabled: true\n    metric.input_type:\n      enabled: true\n      attributes: [\"string_attr\",\"state\",\"enum_attr\",\"slice_attr\",\"map_attr\"]\n    optional.metric:\n      enabled: true\n      attributes: [\"string_attr\",\"boolean_attr\",\"boolean_attr2\",\"conditional_string_attr\"]\n    optional.metric.empty_unit:\n      enabled: true\n      attributes: [\"string_attr\",\"boolean_attr\"]\n    reaggregate.metric:\n      enabled: true\n      attributes: [\"string_attr\",\"boolean_attr\"]\n    reaggregate.metric.with_required:\n      enabled: true\n      attributes: [\"required_string_attr\",\"string_attr\",\"boolean_attr\"]\n    system.cpu.time:\n      enabled: true\n  events:\n    default.event:\n      enabled: true\n    default.event.to_be_removed:\n      enabled: true\n    default.event.to_be_renamed:\n      enabled: true\n  resource_attributes:\n    map.resource.attr:\n      enabled: true\n    optional.resource.attr:\n      enabled: true\n    slice.resource.attr:\n      enabled: true\n    string.enum.resource.attr:\n      enabled: true\n    string.resource.attr:\n      enabled: true\n    string.resource.attr_disable_warning:\n      enabled: true\n    string.resource.attr_remove_warning:\n      enabled: true\n    string.resource.attr_to_be_removed:\n      enabled: true\nreaggregate_set:\n  metrics:\n    default.metric:\n      enabled: true\n      attributes: []\n    default.metric.to_be_removed:\n      enabled: true\n    metric.input_type:\n      enabled: true\n      attributes: []\n    optional.metric:\n      enabled: true\n      attributes: []\n    optional.metric.empty_unit:\n      enabled: true\n      attributes: []\n    reaggregate.metric:\n      enabled: true\n      attributes: []\n    reaggregate.metric.with_required:\n      enabled: true\n      attributes: [\"required_string_attr\"]\n    system.cpu.time:\n      enabled: true\n  events:\n    default.event:\n      enabled: true\n    default.event.to_be_removed:\n      enabled: true\n    default.event.to_be_renamed:\n      enabled: true\n  resource_attributes:\n    map.resource.attr:\n      enabled: true\n    optional.resource.attr:\n      enabled: true\n    slice.resource.attr:\n      enabled: true\n    string.enum.resource.attr:\n      enabled: true\n    string.resource.attr:\n      enabled: true\n    string.resource.attr_disable_warning:\n      enabled: true\n    string.resource.attr_remove_warning:\n      enabled: true\n    string.resource.attr_to_be_removed:\n      enabled: true\nnone_set:\n  metrics:\n    default.metric:\n      enabled: false\n      attributes: [\"string_attr\",\"state\",\"enum_attr\",\"slice_attr\",\"map_attr\",\"conditional_int_attr\",\"conditional_string_attr\",\"opt_in_bool_attr\"]\n    default.metric.to_be_removed:\n      enabled: false\n    metric.input_type:\n      enabled: false\n      attributes: [\"string_attr\",\"state\",\"enum_attr\",\"slice_attr\",\"map_attr\"]\n    optional.metric:\n      enabled: false\n      attributes: [\"string_attr\",\"boolean_attr\",\"boolean_attr2\",\"conditional_string_attr\"]\n    optional.metric.empty_unit:\n      enabled: false\n      attributes: [\"string_attr\",\"boolean_attr\"]\n    reaggregate.metric:\n      enabled: false\n      attributes: [\"string_attr\",\"boolean_attr\"]\n    reaggregate.metric.with_required:\n      enabled: false\n      attributes: [\"required_string_attr\",\"string_attr\",\"boolean_attr\"]\n    system.cpu.time:\n      enabled: false\n  events:\n    default.event:\n      enabled: false\n    default.event.to_be_removed:\n      enabled: false\n    default.event.to_be_renamed:\n      enabled: false\n  resource_attributes:\n    map.resource.attr:\n      enabled: false\n    optional.resource.attr:\n      enabled: false\n    slice.resource.attr:\n      enabled: false\n    string.enum.resource.attr:\n      enabled: false\n    string.resource.attr:\n      enabled: false\n    string.resource.attr_disable_warning:\n      enabled: false\n    string.resource.attr_remove_warning:\n      enabled: false\n    string.resource.attr_to_be_removed:\n      enabled: false\nfilter_set_include:\n  resource_attributes:\n    map.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n      events_include:\n        - regexp: \".*\"\n    optional.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n      events_include:\n        - regexp: \".*\"\n    slice.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n      events_include:\n        - regexp: \".*\"\n    string.enum.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n      events_include:\n        - regexp: \".*\"\n    string.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n      events_include:\n        - regexp: \".*\"\n    string.resource.attr_disable_warning:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n      events_include:\n        - regexp: \".*\"\n    string.resource.attr_remove_warning:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n      events_include:\n        - regexp: \".*\"\n    string.resource.attr_to_be_removed:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n      events_include:\n        - regexp: \".*\"\nfilter_set_exclude:\n  resource_attributes:\n    map.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - regexp: \".*\"\n      events_exclude:\n        - regexp: \".*\"\n    optional.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - strict: \"optional.resource.attr-val\"\n      events_exclude:\n        - strict: \"optional.resource.attr-val\"\n    slice.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - regexp: \".*\"\n      events_exclude:\n        - regexp: \".*\"\n    string.enum.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - strict: \"one\"\n      events_exclude:\n        - strict: \"one\"\n    string.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - strict: \"string.resource.attr-val\"\n      events_exclude:\n        - strict: \"string.resource.attr-val\"\n    string.resource.attr_disable_warning:\n      enabled: true\n      metrics_exclude:\n        - strict: \"string.resource.attr_disable_warning-val\"\n      events_exclude:\n        - strict: \"string.resource.attr_disable_warning-val\"\n    string.resource.attr_remove_warning:\n      enabled: true\n      metrics_exclude:\n        - strict: \"string.resource.attr_remove_warning-val\"\n      events_exclude:\n        - strict: \"string.resource.attr_remove_warning-val\"\n    string.resource.attr_to_be_removed:\n      enabled: true\n      metrics_exclude:\n        - strict: \"string.resource.attr_to_be_removed-val\"\n      events_exclude:\n        - strict: \"string.resource.attr_to_be_removed-val\"\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/internal/metadatatest/generated_telemetrytest.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\nfunc NewSettings(tt *componenttest.Telemetry) receiver.Settings {\n\tset := receivertest.NewNopSettings(receivertest.NopType)\n\tset.ID = component.NewID(component.MustNewType(\"sample\"))\n\tset.TelemetrySettings = tt.NewTelemetrySettings()\n\treturn set\n}\n\nfunc AssertEqualBatchSizeTriggerSend(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_batch_size_trigger_send\",\n\t\tDescription: \"Number of times the batch was sent due to a size trigger [Deprecated]\",\n\t\tUnit:        \"{time}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_batch_size_trigger_send\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessRuntimeTotalAllocBytes(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_process_runtime_total_alloc_bytes\",\n\t\tDescription: \"Cumulative bytes allocated for heap objects (see 'go doc runtime.MemStats.TotalAlloc') [Stable]\",\n\t\tUnit:        \"By\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_process_runtime_total_alloc_bytes\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualQueueCapacity(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_queue_capacity\",\n\t\tDescription: \"Queue capacity - sync gauge example. [Development]\",\n\t\tUnit:        \"{item}\",\n\t\tData: metricdata.Gauge[int64]{\n\t\t\tDataPoints: dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_queue_capacity\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualQueueLength(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_queue_length\",\n\t\tDescription: \"This metric is optional and therefore not initialized in NewTelemetryBuilder. [Alpha]\",\n\t\tUnit:        \"{item}\",\n\t\tData: metricdata.Gauge[int64]{\n\t\t\tDataPoints: dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_queue_length\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualRequestDuration(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.HistogramDataPoint[float64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_request_duration\",\n\t\tDescription: \"Duration of request [Alpha]\",\n\t\tUnit:        \"s\",\n\t\tData: metricdata.Histogram[float64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_request_duration\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/internal/metadatatest/generated_telemetrytest_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplereceiver/internal/metadata\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\nfunc TestSetupTelemetry(t *testing.T) {\n\ttestTel := componenttest.NewTelemetry()\n\ttb, err := metadata.NewTelemetryBuilder(testTel.NewTelemetrySettings())\n\trequire.NoError(t, err)\n\tdefer tb.Shutdown()\n\trequire.NoError(t, tb.RegisterProcessRuntimeTotalAllocBytesCallback(func(_ context.Context, observer metric.Int64Observer) error {\n\t\tobserver.Observe(1)\n\t\treturn nil\n\t}))\n\trequire.NoError(t, tb.RegisterQueueLengthCallback(func(_ context.Context, observer metric.Int64Observer) error {\n\t\tobserver.Observe(1)\n\t\treturn nil\n\t}))\n\ttb.BatchSizeTriggerSend.Add(context.Background(), 1)\n\ttb.QueueCapacity.Record(context.Background(), 1)\n\ttb.RequestDuration.Record(context.Background(), 1)\n\tAssertEqualBatchSizeTriggerSend(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessRuntimeTotalAllocBytes(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualQueueCapacity(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualQueueLength(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualRequestDuration(t, testTel,\n\t\t[]metricdata.HistogramDataPoint[float64]{{}}, metricdatatest.IgnoreValue(),\n\t\tmetricdatatest.IgnoreTimestamp())\n\n\trequire.NoError(t, testTel.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/metadata.yaml",
    "content": "# Sample metadata file with all available configurations for a receiver.\n\ntype: sample\ndisplay_name: Sample Receiver\ndescription: This receiver is used for testing purposes to check the output of mdatagen.\nreaggregation_enabled: true\nscope_name: go.opentelemetry.io/collector/internal/receiver/samplereceiver\ngithub_project: open-telemetry/opentelemetry-collector\n\nsem_conv_version: 1.38.0\n\nfeature_gates:\n  - id: receiver.sample.featuregate.example\n    description: This is an example feature gate for testing mdatagen code generation.\n    stage: alpha\n    from_version: v0.100.0\n    reference_url: https://github.com/open-telemetry/opentelemetry-collector/issues/12345\n\nstatus:\n  disable_codecov_badge: true\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n    deprecated: [profiles]\n  deprecation:\n    profiles:\n      migration: \"no migration needed\"\n      date: \"2025-02-05\"\n  distributions: []\n  unsupported_platforms: [freebsd, illumos]\n  codeowners:\n    active: [dmitryax]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nconfig:\n  type: object\n  allOf:\n    - $ref: ./internal/metadata.metrics_builder_config\n  properties:\n    endpoint:\n      description: The endpoint to scrape metrics from.\n      type: string\n      default: \"localhost:12345\"\n    timeout:\n      description: Timeout for scraping metrics.\n      type: string\n      format: duration\n      default: 10s\n  required: [endpoint]\n\nresource_attributes:\n  map.resource.attr:\n    description: Resource attribute with a map value.\n    type: map\n    enabled: true\n\n  optional.resource.attr:\n    description: Explicitly disabled ResourceAttribute.\n    type: string\n    enabled: false\n\n  slice.resource.attr:\n    description: Resource attribute with a slice value.\n    type: slice\n    enabled: true\n\n  string.enum.resource.attr:\n    description: Resource attribute with a known set of string values.\n    type: string\n    enum: [one, two]\n    enabled: true\n\n  string.resource.attr:\n    description: Resource attribute with any string value.\n    type: string\n    enabled: true\n\n  string.resource.attr_disable_warning:\n    description: Resource attribute with any string value.\n    type: string\n    enabled: true\n    warnings:\n      if_enabled_not_set: This resource_attribute will be disabled by default soon.\n\n  string.resource.attr_remove_warning:\n    description: Resource attribute with any string value.\n    type: string\n    enabled: false\n    warnings:\n      if_configured: This resource_attribute is deprecated and will be removed soon.\n\n  string.resource.attr_to_be_removed:\n    description: Resource attribute with any string value.\n    type: string\n    enabled: true\n    warnings:\n      if_enabled: This resource_attribute is deprecated and will be removed soon.\n\nattributes:\n  boolean_attr:\n    description: Attribute with a boolean value.\n    type: bool\n\n  # This 2nd boolean attribute allows us to test both values for boolean attributes,\n  # as test values are based on the parity of the attribute name length.\n  boolean_attr2:\n    description: Another attribute with a boolean value.\n    type: bool\n\n  conditional_int_attr:\n    description: A conditional attribute with an integer value\n    type: int\n    requirement_level: conditionally_required\n\n  conditional_string_attr:\n    description: A conditional attribute with any string value\n    type: string\n    requirement_level: conditionally_required\n\n  enum_attr:\n    description: Attribute with a known set of string values.\n    type: string\n    enum: [red, green, blue]\n\n  map_attr:\n    description: Attribute with a map value.\n    type: map\n\n  opt_in_bool_attr:\n    description: An opt-in attribute with a boolean value\n    type: bool\n    requirement_level: opt_in\n\n  overridden_int_attr:\n    name_override: state\n    description: Integer attribute with overridden name.\n    type: int\n\n  required_string_attr:\n    description: A required attribute with a string value\n    type: string\n    requirement_level: required\n\n  slice_attr:\n    description: Attribute with a slice value.\n    type: slice\n\n  string_attr:\n    description: Attribute with any string value.\n    type: string\n\nevents:\n  default.event:\n    enabled: true\n    description: Example event enabled by default.\n    attributes:\n      [\n        string_attr,\n        overridden_int_attr,\n        enum_attr,\n        slice_attr,\n        map_attr,\n        conditional_int_attr,\n        conditional_string_attr,\n        opt_in_bool_attr,\n      ]\n    warnings:\n      if_enabled_not_set: This event will be disabled by default soon.\n\n  default.event.to_be_removed:\n    enabled: true\n    description: \"[DEPRECATED] Example to-be-removed event enabled by default.\"\n    extended_documentation: The event will be removed soon.\n    warnings:\n      if_enabled: This event is deprecated and will be removed soon.\n    attributes:\n      [string_attr, overridden_int_attr, enum_attr, slice_attr, map_attr]\n\n  default.event.to_be_renamed:\n    enabled: false\n    description: \"[DEPRECATED] Example event disabled by default.\"\n    extended_documentation: The event will be renamed soon.\n    attributes: [string_attr, boolean_attr, boolean_attr2, conditional_string_attr]\n    warnings:\n      if_configured: This event is deprecated and will be renamed soon.\n\nmetrics:\n  default.metric:\n    enabled: true\n    description: Monotonic cumulative sum int metric enabled by default.\n    extended_documentation: The metric will be become optional soon.\n    stability: deprecated\n    deprecated:\n      since: \"1.0.0\"\n      note: \"This metric will be removed\"\n    unit: s\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n    attributes:\n      [\n        string_attr,\n        overridden_int_attr,\n        enum_attr,\n        slice_attr,\n        map_attr,\n        conditional_int_attr,\n        conditional_string_attr,\n        opt_in_bool_attr,\n      ]\n    warnings:\n      if_enabled_not_set: This metric will be disabled by default soon.\n\n  default.metric.to_be_removed:\n    enabled: true\n    description: \"[DEPRECATED] Non-monotonic delta sum double metric enabled by default.\"\n    extended_documentation: The metric will be removed soon.\n    stability: deprecated\n    deprecated:\n      since: \"1.0.0\"\n      note: \"This metric will be removed\"\n    unit: s\n    sum:\n      value_type: double\n      monotonic: false\n      aggregation_temporality: delta\n    warnings:\n      if_enabled: This metric is deprecated and will be removed soon.\n\n  metric.input_type:\n    enabled: true\n    description: Monotonic cumulative sum int metric with string input_type enabled by default.\n    stability: development\n    unit: s\n    sum:\n      value_type: int\n      input_type: string\n      monotonic: true\n      aggregation_temporality: cumulative\n    attributes:\n      [string_attr, overridden_int_attr, enum_attr, slice_attr, map_attr]\n\n  optional.metric:\n    enabled: false\n    description: \"[DEPRECATED] Gauge double metric disabled by default.\"\n    stability: deprecated\n    deprecated:\n      since: \"1.0.0\"\n      note: \"This metric will be removed\"\n    unit: \"1\"\n    gauge:\n      value_type: double\n    attributes: [string_attr, boolean_attr, boolean_attr2, conditional_string_attr]\n    warnings:\n      if_configured: This metric is deprecated and will be removed soon.\n\n  optional.metric.empty_unit:\n    enabled: false\n    description: \"[DEPRECATED] Gauge double metric disabled by default.\"\n    stability: deprecated\n    deprecated:\n      since: \"1.0.0\"\n      note: \"This metric will be removed\"\n    unit: \"\"\n    gauge:\n      value_type: double\n    attributes: [string_attr, boolean_attr]\n    warnings:\n      if_configured: This metric is deprecated and will be removed soon.\n\n  reaggregate.metric:\n    enabled: true\n    description: Metric for testing spatial reaggregation\n    unit: \"1\"\n    stability: beta\n    gauge:\n      value_type: double\n    attributes: [string_attr, boolean_attr]\n\n  reaggregate.metric.with_required:\n    enabled: true\n    description: Metric for testing spatial reaggregation with required attributes\n    unit: \"1\"\n    stability: beta\n    gauge:\n      value_type: double\n    attributes: [required_string_attr, string_attr, boolean_attr]\n\n  system.cpu.time:\n    enabled: true\n    stability: beta\n    description: Monotonic cumulative sum int metric enabled by default.\n    extended_documentation: The metric will be become optional soon.\n    unit: s\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n    semantic_convention:\n      ref: https://github.com/open-telemetry/semantic-conventions/blob/v1.38.0/docs/system/system-metrics.md#metric-systemcputime\n\ntelemetry:\n  metrics:\n    batch_size_trigger_send:\n      enabled: true\n      stability: deprecated\n      deprecated:\n        since: \"1.5.0\"\n        note: \"This metric will be removed in favor of batch_send_trigger_size\"\n      description: Number of times the batch was sent due to a size trigger\n      unit: \"{time}\"\n      sum:\n        value_type: int\n        monotonic: true\n    process_runtime_total_alloc_bytes:\n      enabled: true\n      stability: stable\n      description: Cumulative bytes allocated for heap objects (see 'go doc runtime.MemStats.TotalAlloc')\n      unit: By\n      sum:\n        async: true\n        value_type: int\n        monotonic: true\n    queue_capacity:\n      enabled: true\n      description: Queue capacity - sync gauge example.\n      stability: development\n      unit: \"{item}\"\n      gauge:\n        value_type: int\n    queue_length:\n      enabled: true\n      stability: alpha\n      description: This metric is optional and therefore not initialized in NewTelemetryBuilder.\n      extended_documentation: For example this metric only exists if feature A is enabled.\n      unit: \"{item}\"\n      optional: true\n      gauge:\n        async: true\n        value_type: int\n    request_duration:\n      enabled: true\n      stability: alpha\n      description: Duration of request\n      unit: s\n      histogram:\n        value_type: double\n        bucket_boundaries: [1, 10, 100]\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplereceiver/metrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage samplereceiver\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplereceiver/internal/metadata\"\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplereceiver/internal/metadatatest\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\n// TestGeneratedMetrics verifies that the internal/metadata API is generated correctly.\nfunc TestGeneratedMetrics(t *testing.T) {\n\tmb := metadata.NewMetricsBuilder(metadata.DefaultMetricsBuilderConfig(), receivertest.NewNopSettings(metadata.Type))\n\tm := mb.Emit()\n\trequire.Equal(t, 0, m.ResourceMetrics().Len())\n}\n\nfunc TestComponentTelemetry(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tfactory := NewFactory()\n\treceiver, err := factory.CreateMetrics(context.Background(), metadatatest.NewSettings(tt), newMdatagenNopHost(), new(consumertest.MetricsSink))\n\trequire.NoError(t, err)\n\tmetadatatest.AssertEqualBatchSizeTriggerSend(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue: 1,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\tmetadatatest.AssertEqualProcessRuntimeTotalAllocBytes(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue: 2,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\trcv, ok := receiver.(nopReceiver)\n\trequire.True(t, ok)\n\trcv.initOptionalMetric()\n\tmetadatatest.AssertEqualQueueLength(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue: 3,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\trequire.NoError(t, tt.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/README.md",
    "content": "<!-- status autogenerated section -->\n# Sample Scraper\n\nThis scraper is used for testing purposes to check the output of mdatagen.\n\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [development]: logs, profiles   |\n|               | [stable]: metrics   |\n| Unsupported Platforms | freebsd, illumos |\n| Distributions | [] |\n| Warnings      | [Any additional information that should be brought to the consumer's attention](#warnings) |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Ascraper%2Fsample%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Ascraper%2Fsample) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Ascraper%2Fsample%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Ascraper%2Fsample) |\n| [Code Owners](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/CONTRIBUTING.md#becoming-a-code-owner)    | [@dmitryax](https://www.github.com/dmitryax) |\n\n[development]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#development\n[stable]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stable\n<!-- end autogenerated section -->\n\n## Warnings\n\nThis is where warnings are described.\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/config.schema.json",
    "content": "{\n  \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n  \"$id\": \"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplescraper\",\n  \"title\": \"scraper/sample\",\n  \"description\": \"Configuration for the Sample Scraper.\",\n  \"type\": \"object\",\n  \"allOf\": [\n    {\n      \"description\": \"ControllerConfig defines common settings for a scraper controller configuration. Scraper controller receivers can embed this struct, instead of receiver.Settings, and extend it with more fields if needed.\",\n      \"type\": \"object\",\n      \"properties\": {\n        \"collection_interval\": {\n          \"description\": \"CollectionInterval sets how frequently the scraper should be called and used as the context timeout to ensure that scrapers don't exceed the interval. (duration format, e.g., \\\"30s\\\", \\\"1h30m\\\")\",\n          \"type\": \"string\",\n          \"pattern\": \"^([0-9]+(\\\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$\"\n        },\n        \"initial_delay\": {\n          \"description\": \"InitialDelay sets the initial start delay for the scraper, any non positive value is assumed to be immediately. (duration format, e.g., \\\"30s\\\", \\\"1h30m\\\")\",\n          \"type\": \"string\",\n          \"pattern\": \"^([0-9]+(\\\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$\"\n        },\n        \"timeout\": {\n          \"description\": \"Timeout is an optional value used to set scraper's context deadline. (duration format, e.g., \\\"30s\\\", \\\"1h30m\\\")\",\n          \"type\": \"string\",\n          \"pattern\": \"^([0-9]+(\\\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$\"\n        }\n      }\n    }\n  ],\n  \"properties\": {\n    \"targets\": {\n      \"description\": \"Targets configuration for the scraper.\",\n      \"type\": \"array\",\n      \"items\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"http_client\": {\n            \"description\": \"ClientConfig defines settings for creating an HTTP client.\",\n            \"type\": \"object\",\n            \"properties\": {\n              \"auth\": {\n                \"description\": \"Auth configuration for outgoing HTTP calls.\",\n                \"type\": \"object\",\n                \"properties\": {\n                  \"authenticator\": {\n                    \"description\": \"AuthenticatorID specifies the name of the extension to use in order to authenticate the incoming data point.\",\n                    \"type\": \"string\"\n                  }\n                }\n              },\n              \"compression\": {\n                \"description\": \"The compression key for supported compression types within collector.\",\n                \"type\": \"string\"\n              },\n              \"compression_params\": {\n                \"description\": \"Advanced configuration options for the Compression\",\n                \"type\": \"object\",\n                \"properties\": {\n                  \"level\": {\n                    \"type\": \"integer\"\n                  }\n                }\n              },\n              \"cookies\": {\n                \"description\": \"Cookies configures the cookie management of the HTTP client.\"\n              },\n              \"disable_keep_alives\": {\n                \"description\": \"DisableKeepAlives, if true, disables HTTP keep-alives and will only use the connection to the server for a single HTTP request. WARNING: enabling this option can result in significant overhead establishing a new HTTP(S) connection for every request. Before enabling this option please consider whether changes to idle connection settings can achieve your goal.\",\n                \"type\": \"boolean\"\n              },\n              \"endpoint\": {\n                \"description\": \"The target URL to send data to (e.g.: http://some.url:9411/v1/traces).\",\n                \"type\": \"string\"\n              },\n              \"force_attempt_http2\": {\n                \"description\": \"Enabling ForceAttemptHTTP2 forces the HTTP transport to use the HTTP/2 protocol. By default, this is set to true. NOTE: HTTP/2 does not support settings such as MaxConnsPerHost, MaxIdleConnsPerHost and MaxIdleConns.\",\n                \"type\": \"boolean\"\n              },\n              \"headers\": {\n                \"description\": \"Additional headers attached to each HTTP request sent by the client. Existing header values are overwritten if collision happens. Header values are opaque since they may be sensitive.\",\n                \"type\": \"array\",\n                \"items\": {\n                  \"description\": \"Pair is an element of a MapList, and consists of a name and an opaque value.\",\n                  \"type\": \"object\",\n                  \"properties\": {\n                    \"name\": {\n                      \"type\": \"string\"\n                    },\n                    \"value\": {\n                      \"description\": \"String alias that is marshaled and printed in an opaque way. To recover the original value, cast it to a string.\",\n                      \"type\": \"string\"\n                    }\n                  }\n                }\n              },\n              \"http2_ping_timeout\": {\n                \"description\": \"HTTP2PingTimeout if there's no response to the ping within the configured value, the connection will be closed. If not set or set to 0, it defaults to 15s. (duration format, e.g., \\\"30s\\\", \\\"1h30m\\\")\",\n                \"type\": \"string\",\n                \"pattern\": \"^([0-9]+(\\\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$\"\n              },\n              \"http2_read_idle_timeout\": {\n                \"description\": \"This is needed in case you run into https://github.com/golang/go/issues/59690 https://github.com/golang/go/issues/36026 HTTP2ReadIdleTimeout if the connection has been idle for the configured value send a ping frame for health check 0s means no health check will be performed. (duration format, e.g., \\\"30s\\\", \\\"1h30m\\\")\",\n                \"type\": \"string\",\n                \"pattern\": \"^([0-9]+(\\\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$\"\n              },\n              \"idle_conn_timeout\": {\n                \"description\": \"IdleConnTimeout is the maximum amount of time a connection will remain open before closing itself. By default, it is set to 90 seconds. (duration format, e.g., \\\"30s\\\", \\\"1h30m\\\")\",\n                \"type\": \"string\",\n                \"pattern\": \"^([0-9]+(\\\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$\"\n              },\n              \"max_conns_per_host\": {\n                \"description\": \"MaxConnsPerHost limits the total number of connections per host, including connections in the dialing, active, and idle states. Default is 0 (unlimited).\",\n                \"type\": \"integer\"\n              },\n              \"max_idle_conns\": {\n                \"description\": \"MaxIdleConns is used to set a limit to the maximum idle HTTP connections the client can keep open. By default, it is set to 100. Zero means no limit.\",\n                \"type\": \"integer\"\n              },\n              \"max_idle_conns_per_host\": {\n                \"description\": \"MaxIdleConnsPerHost is used to set a limit to the maximum idle HTTP connections the host can keep open. If zero, [net/http.DefaultMaxIdleConnsPerHost] is used.\",\n                \"type\": \"integer\"\n              },\n              \"middlewares\": {\n                \"description\": \"Middlewares are used to add custom functionality to the HTTP client. Middleware handlers are called in the order they appear in this list, with the first middleware becoming the outermost handler.\",\n                \"type\": \"array\",\n                \"items\": {\n                  \"description\": \"Middleware defines the extension ID for a middleware component.\",\n                  \"type\": \"object\",\n                  \"properties\": {\n                    \"id\": {\n                      \"description\": \"ID specifies the name of the extension to use.\",\n                      \"type\": \"string\"\n                    }\n                  }\n                }\n              },\n              \"proxy_url\": {\n                \"description\": \"ProxyURL setting for the collector\",\n                \"type\": \"string\"\n              },\n              \"read_buffer_size\": {\n                \"description\": \"ReadBufferSize for HTTP client. See http.Transport.ReadBufferSize. Default is 0.\",\n                \"type\": \"integer\"\n              },\n              \"timeout\": {\n                \"description\": \"Timeout parameter configures `http.Client.Timeout`. Default is 0 (unlimited). (duration format, e.g., \\\"30s\\\", \\\"1h30m\\\")\",\n                \"type\": \"string\",\n                \"pattern\": \"^([0-9]+(\\\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$\"\n              },\n              \"tls\": {\n                \"description\": \"TLS struct exposes TLS client configuration.\",\n                \"type\": \"object\",\n                \"allOf\": [\n                  {\n                    \"description\": \"Config exposes the common client and server TLS configurations. Note: Since there isn't anything specific to a server connection. Components with server connections should use Config.\",\n                    \"type\": \"object\",\n                    \"properties\": {\n                      \"ca_file\": {\n                        \"description\": \"Path to the CA cert. For a client this verifies the server certificate. For a server this verifies client certificates. If empty uses system root CA. (optional)\",\n                        \"type\": \"string\"\n                      },\n                      \"ca_pem\": {\n                        \"description\": \"In memory PEM encoded cert. (optional)\",\n                        \"type\": \"string\"\n                      },\n                      \"cert_file\": {\n                        \"description\": \"Path to the TLS cert to use for TLS required connections. (optional)\",\n                        \"type\": \"string\"\n                      },\n                      \"cert_pem\": {\n                        \"description\": \"In memory PEM encoded TLS cert to use for TLS required connections. (optional)\",\n                        \"type\": \"string\"\n                      },\n                      \"cipher_suites\": {\n                        \"description\": \"CipherSuites is a list of TLS cipher suites that the TLS transport can use. If left blank, a safe default list is used. See https://go.dev/src/crypto/tls/cipher_suites.go for a list of supported cipher suites.\",\n                        \"type\": \"array\",\n                        \"items\": {\n                          \"type\": \"string\"\n                        }\n                      },\n                      \"curve_preferences\": {\n                        \"description\": \"contains the elliptic curves that will be used in an ECDHE handshake, in preference order Defaults to empty list and \\\"crypto/tls\\\" defaults are used, internally.\",\n                        \"type\": \"array\",\n                        \"items\": {\n                          \"type\": \"string\"\n                        }\n                      },\n                      \"include_system_ca_certs_pool\": {\n                        \"description\": \"If true, load system CA certificates pool in addition to the certificates configured in this struct.\",\n                        \"type\": \"boolean\"\n                      },\n                      \"key_file\": {\n                        \"description\": \"Path to the TLS key to use for TLS required connections. (optional)\",\n                        \"type\": \"string\"\n                      },\n                      \"key_pem\": {\n                        \"description\": \"In memory PEM encoded TLS key to use for TLS required connections. (optional)\",\n                        \"type\": \"string\"\n                      },\n                      \"max_version\": {\n                        \"description\": \"MaxVersion sets the maximum TLS version that is acceptable. If not set, refer to crypto/tls for defaults. (optional)\",\n                        \"type\": \"string\"\n                      },\n                      \"min_version\": {\n                        \"description\": \"MinVersion sets the minimum TLS version that is acceptable. If not set, TLS 1.2 will be used. (optional)\",\n                        \"type\": \"string\"\n                      },\n                      \"reload_interval\": {\n                        \"description\": \"ReloadInterval specifies the duration after which the certificate will be reloaded If not set, it will never be reloaded (optional)\",\n                        \"type\": \"string\",\n                        \"pattern\": \"^([0-9]+(\\\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$\"\n                      },\n                      \"tpm\": {\n                        \"description\": \"Trusted platform module configuration\",\n                        \"type\": \"object\",\n                        \"properties\": {\n                          \"auth\": {\n                            \"type\": \"string\"\n                          },\n                          \"enabled\": {\n                            \"type\": \"boolean\"\n                          },\n                          \"owner_auth\": {\n                            \"type\": \"string\"\n                          },\n                          \"path\": {\n                            \"description\": \"The path to the TPM device or Unix domain socket. For instance /dev/tpm0 or /dev/tpmrm0.\",\n                            \"type\": \"string\"\n                          }\n                        }\n                      }\n                    }\n                  }\n                ],\n                \"properties\": {\n                  \"insecure\": {\n                    \"description\": \"In gRPC and HTTP when set to true, this is used to disable the client transport security. See https://godoc.org/google.golang.org/grpc#WithInsecure for gRPC. Please refer to https://godoc.org/crypto/tls#Config for more information. (optional, default false)\",\n                    \"type\": \"boolean\"\n                  },\n                  \"insecure_skip_verify\": {\n                    \"description\": \"InsecureSkipVerify will enable TLS but not verify the certificate.\",\n                    \"type\": \"boolean\"\n                  },\n                  \"server_name_override\": {\n                    \"description\": \"ServerName requested by client for virtual hosting. This sets the ServerName in the TLSConfig. Please refer to https://godoc.org/crypto/tls#Config for more information. (optional)\",\n                    \"type\": \"string\"\n                  }\n                }\n              },\n              \"write_buffer_size\": {\n                \"description\": \"WriteBufferSize for HTTP client. See http.Transport.WriteBufferSize. Default is 0.\",\n                \"type\": \"integer\"\n              }\n            }\n          },\n          \"interval\": {\n            \"type\": \"string\",\n            \"pattern\": \"^([0-9]+(\\\\.[0-9]+)?(ns|us|µs|ms|s|m|h))+$\"\n          }\n        }\n      }\n    }\n  }\n}"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Generate a test metrics builder from a sample metrics set covering all configuration options.\n//go:generate mdatagen metadata.yaml\n\npackage samplescraper // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplescraper\"\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# sample\n\n## Default Metrics\n\nThe following metrics are emitted by default. Each of them can be disabled by applying the following configuration:\n\n```yaml\nmetrics:\n  <metric_name>:\n    enabled: false\n```\n\n### default.metric\n\nMonotonic cumulative sum int metric enabled by default.\n\nThe metric will be become optional soon.\n\n| Unit | Metric Type | Value Type | Aggregation Temporality | Monotonic | Stability |\n| ---- | ----------- | ---------- | ----------------------- | --------- | --------- |\n| s | Sum | Int | Cumulative | true | Development |\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | Recommended |\n| state | Integer attribute with overridden name. | Any Int | Recommended |\n| enum_attr | Attribute with a known set of string values. | Str: ``red``, ``green``, ``blue`` | Recommended |\n| slice_attr | Attribute with a slice value. | Any Slice | Recommended |\n| map_attr | Attribute with a map value. | Any Map | Recommended |\n\n### default.metric.to_be_removed\n\n[DEPRECATED] Non-monotonic delta sum double metric enabled by default.\n\nThe metric will be removed soon.\n\n| Unit | Metric Type | Value Type | Aggregation Temporality | Monotonic | Stability |\n| ---- | ----------- | ---------- | ----------------------- | --------- | --------- |\n| s | Sum | Double | Delta | false | Deprecated since 1.0.0 |\n\n**Deprecation note**: This metric will be removed\n\n### metric.input_type\n\nMonotonic cumulative sum int metric with string input_type enabled by default.\n\n| Unit | Metric Type | Value Type | Aggregation Temporality | Monotonic | Stability |\n| ---- | ----------- | ---------- | ----------------------- | --------- | --------- |\n| s | Sum | Int | Cumulative | true | Development |\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | Recommended |\n| state | Integer attribute with overridden name. | Any Int | Recommended |\n| enum_attr | Attribute with a known set of string values. | Str: ``red``, ``green``, ``blue`` | Recommended |\n| slice_attr | Attribute with a slice value. | Any Slice | Recommended |\n| map_attr | Attribute with a map value. | Any Map | Recommended |\n\n### reaggregate.metric\n\nMetric for testing spatial reaggregation\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| 1 | Gauge | Double | Beta |\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | Recommended |\n| boolean_attr | Attribute with a boolean value. | Any Bool | Recommended |\n\n### system.cpu.time\n\nMonotonic cumulative sum int metric enabled by default.\n\nThe metric will be become optional soon.\n\n| Unit | Metric Type | Value Type | Aggregation Temporality | Monotonic | Stability | Semantic Convention |\n| ---- | ----------- | ---------- | ----------------------- | --------- | --------- | ------------------- |\n| s | Sum | Int | Cumulative | true | Beta | [system.cpu.time](https://github.com/open-telemetry/semantic-conventions/blob/v1.38.0/docs/system/system-metrics.md#metric-systemcputime) |\n\n## Optional Metrics\n\nThe following metrics are not emitted by default. Each of them can be enabled by applying the following configuration:\n\n```yaml\nmetrics:\n  <metric_name>:\n    enabled: true\n```\n\n### optional.metric\n\n[DEPRECATED] Gauge double metric disabled by default.\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| 1 | Gauge | Double | Deprecated since 1.0.0 |\n\n**Deprecation note**: This metric will be removed\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | Recommended |\n| boolean_attr | Attribute with a boolean value. | Any Bool | Recommended |\n| boolean_attr2 | Another attribute with a boolean value. | Any Bool | Recommended |\n\n### optional.metric.empty_unit\n\n[DEPRECATED] Gauge double metric disabled by default.\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n|  | Gauge | Double | Deprecated since 1.0.0 |\n\n**Deprecation note**: This metric will be removed\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n| string_attr | Attribute with any string value. | Any Str | Recommended |\n| boolean_attr | Attribute with a boolean value. | Any Bool | Recommended |\n\n## Resource Attributes\n\n| Name | Description | Values | Enabled |\n| ---- | ----------- | ------ | ------- |\n| map.resource.attr | Resource attribute with a map value. | Any Map | true |\n| optional.resource.attr | Explicitly disabled ResourceAttribute. | Any Str | false |\n| slice.resource.attr | Resource attribute with a slice value. | Any Slice | true |\n| string.enum.resource.attr | Resource attribute with a known set of string values. | Str: ``one``, ``two`` | true |\n| string.resource.attr | Resource attribute with any string value. | Any Str | true |\n| string.resource.attr_disable_warning | Resource attribute with any string value. | Any Str | true |\n| string.resource.attr_remove_warning | Resource attribute with any string value. | Any Str | false |\n| string.resource.attr_to_be_removed | Resource attribute with any string value. | Any Str | true |\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage samplescraper // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplescraper\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplescraper/internal/metadata\"\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/scraper\"\n\t\"go.opentelemetry.io/collector/scraper/xscraper\"\n)\n\n// NewFactory returns a receiver.Factory for sample receiver.\nfunc NewFactory() scraper.Factory {\n\treturn xscraper.NewFactory(\n\t\tmetadata.Type,\n\t\tfunc() component.Config { return &struct{}{} },\n\t\txscraper.WithMetrics(createMetrics, metadata.MetricsStability),\n\t\txscraper.WithLogs(createLogs, metadata.LogsStability),\n\t\txscraper.WithProfiles(createProfiles, metadata.ProfilesStability),\n\t)\n}\n\nfunc createMetrics(context.Context, scraper.Settings, component.Config) (scraper.Metrics, error) {\n\treturn scraper.NewMetrics(func(context.Context) (pmetric.Metrics, error) {\n\t\treturn pmetric.NewMetrics(), nil\n\t})\n}\n\nfunc createLogs(context.Context, scraper.Settings, component.Config) (scraper.Logs, error) {\n\treturn scraper.NewLogs(func(context.Context) (plog.Logs, error) { return plog.Logs{}, nil })\n}\n\nfunc createProfiles(context.Context, scraper.Settings, component.Config) (xscraper.Profiles, error) {\n\treturn xscraper.NewProfiles(func(context.Context) (pprofile.Profiles, error) { return pprofile.Profiles{}, nil })\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n//go:build !freebsd && !illumos\n\npackage samplescraper\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/scraper\"\n\t\"go.opentelemetry.io/collector/scraper/scrapertest\"\n\t\"go.opentelemetry.io/collector/scraper/xscraper\"\n)\n\nvar typ = component.MustNewType(\"sample\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct {\n\t\tcreateFn func(ctx context.Context, set scraper.Settings, cfg component.Config) (component.Component, error)\n\t\tname     string\n\t}{\n\n\t\t{\n\t\t\tname: \"logs\",\n\t\t\tcreateFn: func(ctx context.Context, set scraper.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateLogs(ctx, set, cfg)\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set scraper.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg)\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"profiles\",\n\t\t\tcreateFn: func(ctx context.Context, set scraper.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.(xscraper.Factory).CreateProfiles(ctx, set, cfg)\n\t\t\t},\n\t\t},\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name+\"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), scrapertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\tt.Run(tt.name+\"-lifecycle\", func(t *testing.T) {\n\t\t\tfirstRcvr, err := tt.createFn(context.Background(), scrapertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := newMdatagenNopHost()\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, firstRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, firstRcvr.Shutdown(context.Background()))\n\t\t\tsecondRcvr, err := tt.createFn(context.Background(), scrapertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, secondRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, secondRcvr.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/generated_config.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage samplescraper\n\nimport (\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper\"\n)\n\ntype TargetsItem struct {\n\tHTTPClient confighttp.ClientConfig                `mapstructure:\"http_client\"`\n\tInterval   configoptional.Optional[time.Duration] `mapstructure:\"interval\"`\n}\n\n// Configuration for the Sample Scraper.\ntype Config struct {\n\tscraperhelper.ControllerConfig `mapstructure:\",squash\"`\n\t// Targets configuration for the scraper.\n\tTargets *[]TargetsItem `mapstructure:\"targets\"`\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage samplescraper\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/internal/metadata/config.schema.yaml",
    "content": "# Code generated by mdatagen. DO NOT EDIT.\n$defs:\n  metrics_config:\n    description: MetricsConfig provides config for sample metrics.\n    type: object\n    properties:\n      default.metric:\n        description: \"DefaultMetricMetricConfig provides config for the default.metric metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          aggregation_strategy:\n            type: string\n            enum:\n              - \"sum\"\n              - \"avg\"\n              - \"min\"\n              - \"max\"\n            default: \"sum\"\n          attributes:\n            type: array\n            items:\n              type: string\n              enum:\n                - \"string_attr\"\n                - \"state\"\n                - \"enum_attr\"\n                - \"slice_attr\"\n                - \"map_attr\"\n            default:\n              - \"string_attr\"\n              - \"state\"\n              - \"enum_attr\"\n              - \"slice_attr\"\n              - \"map_attr\"\n      default.metric.to_be_removed:\n        description: \"DefaultMetricToBeRemovedMetricConfig provides config for the default.metric.to_be_removed metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n      metric.input_type:\n        description: \"MetricInputTypeMetricConfig provides config for the metric.input_type metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          aggregation_strategy:\n            type: string\n            enum:\n              - \"sum\"\n              - \"avg\"\n              - \"min\"\n              - \"max\"\n            default: \"sum\"\n          attributes:\n            type: array\n            items:\n              type: string\n              enum:\n                - \"string_attr\"\n                - \"state\"\n                - \"enum_attr\"\n                - \"slice_attr\"\n                - \"map_attr\"\n            default:\n              - \"string_attr\"\n              - \"state\"\n              - \"enum_attr\"\n              - \"slice_attr\"\n              - \"map_attr\"\n      optional.metric:\n        description: \"OptionalMetricMetricConfig provides config for the optional.metric metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: false\n          aggregation_strategy:\n            type: string\n            enum:\n              - \"sum\"\n              - \"avg\"\n              - \"min\"\n              - \"max\"\n            default: \"avg\"\n          attributes:\n            type: array\n            items:\n              type: string\n              enum:\n                - \"string_attr\"\n                - \"boolean_attr\"\n                - \"boolean_attr2\"\n            default:\n              - \"string_attr\"\n              - \"boolean_attr\"\n              - \"boolean_attr2\"\n      optional.metric.empty_unit:\n        description: \"OptionalMetricEmptyUnitMetricConfig provides config for the optional.metric.empty_unit metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: false\n          aggregation_strategy:\n            type: string\n            enum:\n              - \"sum\"\n              - \"avg\"\n              - \"min\"\n              - \"max\"\n            default: \"avg\"\n          attributes:\n            type: array\n            items:\n              type: string\n              enum:\n                - \"string_attr\"\n                - \"boolean_attr\"\n            default:\n              - \"string_attr\"\n              - \"boolean_attr\"\n      reaggregate.metric:\n        description: \"ReaggregateMetricMetricConfig provides config for the reaggregate.metric metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          aggregation_strategy:\n            type: string\n            enum:\n              - \"sum\"\n              - \"avg\"\n              - \"min\"\n              - \"max\"\n            default: \"avg\"\n          attributes:\n            type: array\n            items:\n              type: string\n              enum:\n                - \"string_attr\"\n                - \"boolean_attr\"\n            default:\n              - \"string_attr\"\n              - \"boolean_attr\"\n      system.cpu.time:\n        description: \"SystemCPUTimeMetricConfig provides config for the system.cpu.time metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n  resource_attributes_config:\n    description: ResourceAttributesConfig provides config for sample resource attributes.\n    type: object\n    properties:\n      map.resource.attr:\n        description: ResourceAttributeConfig provides common config for a map.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      optional.resource.attr:\n        description: ResourceAttributeConfig provides common config for a optional.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: false\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      slice.resource.attr:\n        description: ResourceAttributeConfig provides common config for a slice.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      string.enum.resource.attr:\n        description: ResourceAttributeConfig provides common config for a string.enum.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      string.resource.attr:\n        description: ResourceAttributeConfig provides common config for a string.resource.attr resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      string.resource.attr_disable_warning:\n        description: ResourceAttributeConfig provides common config for a string.resource.attr_disable_warning resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      string.resource.attr_remove_warning:\n        description: ResourceAttributeConfig provides common config for a string.resource.attr_remove_warning resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: false\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n      string.resource.attr_to_be_removed:\n        description: ResourceAttributeConfig provides common config for a string.resource.attr_to_be_removed resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: true\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: /filter.config\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: /filter.config\n  metrics_builder_config:\n    description: MetricsBuilderConfig is a configuration for sample metrics builder.\n    type: object\n    properties:\n      metrics:\n        $ref: metrics_config\n      resource_attributes:\n        $ref: resource_attributes_config\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/internal/metadata/generated_config.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/filter\"\n)\n\n// DefaultMetricMetricAttributeKey specifies the key of an attribute for the default.metric metric.\ntype DefaultMetricMetricAttributeKey string\n\nconst (\n\tDefaultMetricMetricAttributeKeyStringAttr        DefaultMetricMetricAttributeKey = \"string_attr\"\n\tDefaultMetricMetricAttributeKeyOverriddenIntAttr DefaultMetricMetricAttributeKey = \"state\"\n\tDefaultMetricMetricAttributeKeyEnumAttr          DefaultMetricMetricAttributeKey = \"enum_attr\"\n\tDefaultMetricMetricAttributeKeySliceAttr         DefaultMetricMetricAttributeKey = \"slice_attr\"\n\tDefaultMetricMetricAttributeKeyMapAttr           DefaultMetricMetricAttributeKey = \"map_attr\"\n)\n\n// DefaultMetricMetricConfig provides config for the default.metric metric.\ntype DefaultMetricMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n\n\tAggregationStrategy string                            `mapstructure:\"aggregation_strategy\"`\n\tEnabledAttributes   []DefaultMetricMetricAttributeKey `mapstructure:\"attributes\"`\n}\n\nfunc (ms *DefaultMetricMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\nfunc (ms *DefaultMetricMetricConfig) Validate() error {\n\tfor _, val := range ms.EnabledAttributes {\n\t\tswitch val {\n\t\tcase DefaultMetricMetricAttributeKeyStringAttr, DefaultMetricMetricAttributeKeyOverriddenIntAttr, DefaultMetricMetricAttributeKeyEnumAttr, DefaultMetricMetricAttributeKeySliceAttr, DefaultMetricMetricAttributeKeyMapAttr:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"metric default.metric doesn't have an attribute %v, valid attributes: [string_attr, state, enum_attr, slice_attr, map_attr]\", val)\n\t\t}\n\t}\n\n\tswitch ms.AggregationStrategy {\n\tcase AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax:\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation strategy %q, valid strategies: [%s, %s, %s, %s]\", ms.AggregationStrategy, AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax)\n\t}\n\n\treturn nil\n}\n\n// DefaultMetricToBeRemovedMetricConfig provides config for the default.metric.to_be_removed metric.\ntype DefaultMetricToBeRemovedMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n}\n\nfunc (ms *DefaultMetricToBeRemovedMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\n// MetricInputTypeMetricAttributeKey specifies the key of an attribute for the metric.input_type metric.\ntype MetricInputTypeMetricAttributeKey string\n\nconst (\n\tMetricInputTypeMetricAttributeKeyStringAttr        MetricInputTypeMetricAttributeKey = \"string_attr\"\n\tMetricInputTypeMetricAttributeKeyOverriddenIntAttr MetricInputTypeMetricAttributeKey = \"state\"\n\tMetricInputTypeMetricAttributeKeyEnumAttr          MetricInputTypeMetricAttributeKey = \"enum_attr\"\n\tMetricInputTypeMetricAttributeKeySliceAttr         MetricInputTypeMetricAttributeKey = \"slice_attr\"\n\tMetricInputTypeMetricAttributeKeyMapAttr           MetricInputTypeMetricAttributeKey = \"map_attr\"\n)\n\n// MetricInputTypeMetricConfig provides config for the metric.input_type metric.\ntype MetricInputTypeMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n\n\tAggregationStrategy string                              `mapstructure:\"aggregation_strategy\"`\n\tEnabledAttributes   []MetricInputTypeMetricAttributeKey `mapstructure:\"attributes\"`\n}\n\nfunc (ms *MetricInputTypeMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\nfunc (ms *MetricInputTypeMetricConfig) Validate() error {\n\tfor _, val := range ms.EnabledAttributes {\n\t\tswitch val {\n\t\tcase MetricInputTypeMetricAttributeKeyStringAttr, MetricInputTypeMetricAttributeKeyOverriddenIntAttr, MetricInputTypeMetricAttributeKeyEnumAttr, MetricInputTypeMetricAttributeKeySliceAttr, MetricInputTypeMetricAttributeKeyMapAttr:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"metric metric.input_type doesn't have an attribute %v, valid attributes: [string_attr, state, enum_attr, slice_attr, map_attr]\", val)\n\t\t}\n\t}\n\n\tswitch ms.AggregationStrategy {\n\tcase AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax:\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation strategy %q, valid strategies: [%s, %s, %s, %s]\", ms.AggregationStrategy, AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax)\n\t}\n\n\treturn nil\n}\n\n// OptionalMetricMetricAttributeKey specifies the key of an attribute for the optional.metric metric.\ntype OptionalMetricMetricAttributeKey string\n\nconst (\n\tOptionalMetricMetricAttributeKeyStringAttr   OptionalMetricMetricAttributeKey = \"string_attr\"\n\tOptionalMetricMetricAttributeKeyBooleanAttr  OptionalMetricMetricAttributeKey = \"boolean_attr\"\n\tOptionalMetricMetricAttributeKeyBooleanAttr2 OptionalMetricMetricAttributeKey = \"boolean_attr2\"\n)\n\n// OptionalMetricMetricConfig provides config for the optional.metric metric.\ntype OptionalMetricMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n\n\tAggregationStrategy string                             `mapstructure:\"aggregation_strategy\"`\n\tEnabledAttributes   []OptionalMetricMetricAttributeKey `mapstructure:\"attributes\"`\n}\n\nfunc (ms *OptionalMetricMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\nfunc (ms *OptionalMetricMetricConfig) Validate() error {\n\tfor _, val := range ms.EnabledAttributes {\n\t\tswitch val {\n\t\tcase OptionalMetricMetricAttributeKeyStringAttr, OptionalMetricMetricAttributeKeyBooleanAttr, OptionalMetricMetricAttributeKeyBooleanAttr2:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"metric optional.metric doesn't have an attribute %v, valid attributes: [string_attr, boolean_attr, boolean_attr2]\", val)\n\t\t}\n\t}\n\n\tswitch ms.AggregationStrategy {\n\tcase AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax:\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation strategy %q, valid strategies: [%s, %s, %s, %s]\", ms.AggregationStrategy, AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax)\n\t}\n\n\treturn nil\n}\n\n// OptionalMetricEmptyUnitMetricAttributeKey specifies the key of an attribute for the optional.metric.empty_unit metric.\ntype OptionalMetricEmptyUnitMetricAttributeKey string\n\nconst (\n\tOptionalMetricEmptyUnitMetricAttributeKeyStringAttr  OptionalMetricEmptyUnitMetricAttributeKey = \"string_attr\"\n\tOptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr OptionalMetricEmptyUnitMetricAttributeKey = \"boolean_attr\"\n)\n\n// OptionalMetricEmptyUnitMetricConfig provides config for the optional.metric.empty_unit metric.\ntype OptionalMetricEmptyUnitMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n\n\tAggregationStrategy string                                      `mapstructure:\"aggregation_strategy\"`\n\tEnabledAttributes   []OptionalMetricEmptyUnitMetricAttributeKey `mapstructure:\"attributes\"`\n}\n\nfunc (ms *OptionalMetricEmptyUnitMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\nfunc (ms *OptionalMetricEmptyUnitMetricConfig) Validate() error {\n\tfor _, val := range ms.EnabledAttributes {\n\t\tswitch val {\n\t\tcase OptionalMetricEmptyUnitMetricAttributeKeyStringAttr, OptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"metric optional.metric.empty_unit doesn't have an attribute %v, valid attributes: [string_attr, boolean_attr]\", val)\n\t\t}\n\t}\n\n\tswitch ms.AggregationStrategy {\n\tcase AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax:\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation strategy %q, valid strategies: [%s, %s, %s, %s]\", ms.AggregationStrategy, AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax)\n\t}\n\n\treturn nil\n}\n\n// ReaggregateMetricMetricAttributeKey specifies the key of an attribute for the reaggregate.metric metric.\ntype ReaggregateMetricMetricAttributeKey string\n\nconst (\n\tReaggregateMetricMetricAttributeKeyStringAttr  ReaggregateMetricMetricAttributeKey = \"string_attr\"\n\tReaggregateMetricMetricAttributeKeyBooleanAttr ReaggregateMetricMetricAttributeKey = \"boolean_attr\"\n)\n\n// ReaggregateMetricMetricConfig provides config for the reaggregate.metric metric.\ntype ReaggregateMetricMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n\n\tAggregationStrategy string                                `mapstructure:\"aggregation_strategy\"`\n\tEnabledAttributes   []ReaggregateMetricMetricAttributeKey `mapstructure:\"attributes\"`\n}\n\nfunc (ms *ReaggregateMetricMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\nfunc (ms *ReaggregateMetricMetricConfig) Validate() error {\n\tfor _, val := range ms.EnabledAttributes {\n\t\tswitch val {\n\t\tcase ReaggregateMetricMetricAttributeKeyStringAttr, ReaggregateMetricMetricAttributeKeyBooleanAttr:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"metric reaggregate.metric doesn't have an attribute %v, valid attributes: [string_attr, boolean_attr]\", val)\n\t\t}\n\t}\n\n\tswitch ms.AggregationStrategy {\n\tcase AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax:\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation strategy %q, valid strategies: [%s, %s, %s, %s]\", ms.AggregationStrategy, AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax)\n\t}\n\n\treturn nil\n}\n\n// SystemCPUTimeMetricConfig provides config for the system.cpu.time metric.\ntype SystemCPUTimeMetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n}\n\nfunc (ms *SystemCPUTimeMetricConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal(ms)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tms.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\n// MetricsConfig provides config for sample metrics.\ntype MetricsConfig struct {\n\tDefaultMetric            DefaultMetricMetricConfig            `mapstructure:\"default.metric\"`\n\tDefaultMetricToBeRemoved DefaultMetricToBeRemovedMetricConfig `mapstructure:\"default.metric.to_be_removed\"`\n\tMetricInputType          MetricInputTypeMetricConfig          `mapstructure:\"metric.input_type\"`\n\tOptionalMetric           OptionalMetricMetricConfig           `mapstructure:\"optional.metric\"`\n\tOptionalMetricEmptyUnit  OptionalMetricEmptyUnitMetricConfig  `mapstructure:\"optional.metric.empty_unit\"`\n\tReaggregateMetric        ReaggregateMetricMetricConfig        `mapstructure:\"reaggregate.metric\"`\n\tSystemCPUTime            SystemCPUTimeMetricConfig            `mapstructure:\"system.cpu.time\"`\n}\n\nfunc DefaultMetricsConfig() MetricsConfig {\n\treturn MetricsConfig{\n\t\tDefaultMetric: DefaultMetricMetricConfig{\n\t\t\tEnabled:             true,\n\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\tEnabledAttributes:   []DefaultMetricMetricAttributeKey{DefaultMetricMetricAttributeKeyStringAttr, DefaultMetricMetricAttributeKeyOverriddenIntAttr, DefaultMetricMetricAttributeKeyEnumAttr, DefaultMetricMetricAttributeKeySliceAttr, DefaultMetricMetricAttributeKeyMapAttr},\n\t\t},\n\t\tDefaultMetricToBeRemoved: DefaultMetricToBeRemovedMetricConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tMetricInputType: MetricInputTypeMetricConfig{\n\t\t\tEnabled:             true,\n\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\tEnabledAttributes:   []MetricInputTypeMetricAttributeKey{MetricInputTypeMetricAttributeKeyStringAttr, MetricInputTypeMetricAttributeKeyOverriddenIntAttr, MetricInputTypeMetricAttributeKeyEnumAttr, MetricInputTypeMetricAttributeKeySliceAttr, MetricInputTypeMetricAttributeKeyMapAttr},\n\t\t},\n\t\tOptionalMetric: OptionalMetricMetricConfig{\n\t\t\tEnabled:             false,\n\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\tEnabledAttributes:   []OptionalMetricMetricAttributeKey{OptionalMetricMetricAttributeKeyStringAttr, OptionalMetricMetricAttributeKeyBooleanAttr, OptionalMetricMetricAttributeKeyBooleanAttr2},\n\t\t},\n\t\tOptionalMetricEmptyUnit: OptionalMetricEmptyUnitMetricConfig{\n\t\t\tEnabled:             false,\n\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\tEnabledAttributes:   []OptionalMetricEmptyUnitMetricAttributeKey{OptionalMetricEmptyUnitMetricAttributeKeyStringAttr, OptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr},\n\t\t},\n\t\tReaggregateMetric: ReaggregateMetricMetricConfig{\n\t\t\tEnabled:             true,\n\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\tEnabledAttributes:   []ReaggregateMetricMetricAttributeKey{ReaggregateMetricMetricAttributeKeyStringAttr, ReaggregateMetricMetricAttributeKeyBooleanAttr},\n\t\t},\n\t\tSystemCPUTime: SystemCPUTimeMetricConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t}\n}\n\n// ResourceAttributeConfig provides common config for a particular resource attribute.\ntype ResourceAttributeConfig struct {\n\tEnabled bool `mapstructure:\"enabled\"`\n\t// Experimental: MetricsInclude defines a list of filters for attribute values.\n\t// If the list is not empty, only metrics with matching resource attribute values will be emitted.\n\tMetricsInclude []filter.Config `mapstructure:\"metrics_include\"`\n\t// Experimental: MetricsExclude defines a list of filters for attribute values.\n\t// If the list is not empty, metrics with matching resource attribute values will not be emitted.\n\t// MetricsInclude has higher priority than MetricsExclude.\n\tMetricsExclude []filter.Config `mapstructure:\"metrics_exclude\"`\n\n\tenabledSetByUser bool\n}\n\nfunc (rac *ResourceAttributeConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\terr := parser.Unmarshal(rac)\n\tif err != nil {\n\t\treturn err\n\t}\n\trac.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\n// ResourceAttributesConfig provides config for sample resource attributes.\ntype ResourceAttributesConfig struct {\n\tMapResourceAttr                  ResourceAttributeConfig `mapstructure:\"map.resource.attr\"`\n\tOptionalResourceAttr             ResourceAttributeConfig `mapstructure:\"optional.resource.attr\"`\n\tSliceResourceAttr                ResourceAttributeConfig `mapstructure:\"slice.resource.attr\"`\n\tStringEnumResourceAttr           ResourceAttributeConfig `mapstructure:\"string.enum.resource.attr\"`\n\tStringResourceAttr               ResourceAttributeConfig `mapstructure:\"string.resource.attr\"`\n\tStringResourceAttrDisableWarning ResourceAttributeConfig `mapstructure:\"string.resource.attr_disable_warning\"`\n\tStringResourceAttrRemoveWarning  ResourceAttributeConfig `mapstructure:\"string.resource.attr_remove_warning\"`\n\tStringResourceAttrToBeRemoved    ResourceAttributeConfig `mapstructure:\"string.resource.attr_to_be_removed\"`\n}\n\nfunc DefaultResourceAttributesConfig() ResourceAttributesConfig {\n\treturn ResourceAttributesConfig{\n\t\tMapResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tOptionalResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: false,\n\t\t},\n\t\tSliceResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringEnumResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringResourceAttr: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t\tStringResourceAttrRemoveWarning: ResourceAttributeConfig{\n\t\t\tEnabled: false,\n\t\t},\n\t\tStringResourceAttrToBeRemoved: ResourceAttributeConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t}\n}\n\n// MetricsBuilderConfig is a configuration for sample metrics builder.\ntype MetricsBuilderConfig struct {\n\tMetrics            MetricsConfig            `mapstructure:\"metrics\"`\n\tResourceAttributes ResourceAttributesConfig `mapstructure:\"resource_attributes\"`\n}\n\nfunc DefaultMetricsBuilderConfig() MetricsBuilderConfig {\n\treturn MetricsBuilderConfig{\n\t\tMetrics:            DefaultMetricsConfig(),\n\t\tResourceAttributes: DefaultResourceAttributesConfig(),\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/internal/metadata/generated_config_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n\t\"github.com/google/go-cmp/cmp/cmpopts\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n)\n\nfunc TestMetricsBuilderConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant MetricsBuilderConfig\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\twant: DefaultMetricsBuilderConfig(),\n\t\t},\n\t\t{\n\t\t\tname: \"all_set\",\n\t\t\twant: MetricsBuilderConfig{\n\t\t\t\tMetrics: MetricsConfig{\n\t\t\t\t\tDefaultMetric: DefaultMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             true,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\t\t\t\tEnabledAttributes:   []DefaultMetricMetricAttributeKey{DefaultMetricMetricAttributeKeyStringAttr, DefaultMetricMetricAttributeKeyOverriddenIntAttr, DefaultMetricMetricAttributeKeyEnumAttr, DefaultMetricMetricAttributeKeySliceAttr, DefaultMetricMetricAttributeKeyMapAttr},\n\t\t\t\t\t},\n\t\t\t\t\tDefaultMetricToBeRemoved: DefaultMetricToBeRemovedMetricConfig{\n\t\t\t\t\t\tEnabled: true,\n\t\t\t\t\t},\n\t\t\t\t\tMetricInputType: MetricInputTypeMetricConfig{\n\t\t\t\t\t\tEnabled:             true,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\t\t\t\tEnabledAttributes:   []MetricInputTypeMetricAttributeKey{MetricInputTypeMetricAttributeKeyStringAttr, MetricInputTypeMetricAttributeKeyOverriddenIntAttr, MetricInputTypeMetricAttributeKeyEnumAttr, MetricInputTypeMetricAttributeKeySliceAttr, MetricInputTypeMetricAttributeKeyMapAttr},\n\t\t\t\t\t},\n\t\t\t\t\tOptionalMetric: OptionalMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             true,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []OptionalMetricMetricAttributeKey{OptionalMetricMetricAttributeKeyStringAttr, OptionalMetricMetricAttributeKeyBooleanAttr, OptionalMetricMetricAttributeKeyBooleanAttr2},\n\t\t\t\t\t},\n\t\t\t\t\tOptionalMetricEmptyUnit: OptionalMetricEmptyUnitMetricConfig{\n\t\t\t\t\t\tEnabled:             true,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []OptionalMetricEmptyUnitMetricAttributeKey{OptionalMetricEmptyUnitMetricAttributeKeyStringAttr, OptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr},\n\t\t\t\t\t},\n\t\t\t\t\tReaggregateMetric: ReaggregateMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             true,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []ReaggregateMetricMetricAttributeKey{ReaggregateMetricMetricAttributeKeyStringAttr, ReaggregateMetricMetricAttributeKeyBooleanAttr},\n\t\t\t\t\t},\n\t\t\t\t\tSystemCPUTime: SystemCPUTimeMetricConfig{\n\t\t\t\t\t\tEnabled: true,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tResourceAttributes: ResourceAttributesConfig{\n\t\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: true},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"none_set\",\n\t\t\twant: MetricsBuilderConfig{\n\t\t\t\tMetrics: MetricsConfig{\n\t\t\t\t\tDefaultMetric: DefaultMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             false,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\t\t\t\tEnabledAttributes:   []DefaultMetricMetricAttributeKey{DefaultMetricMetricAttributeKeyStringAttr, DefaultMetricMetricAttributeKeyOverriddenIntAttr, DefaultMetricMetricAttributeKeyEnumAttr, DefaultMetricMetricAttributeKeySliceAttr, DefaultMetricMetricAttributeKeyMapAttr},\n\t\t\t\t\t},\n\t\t\t\t\tDefaultMetricToBeRemoved: DefaultMetricToBeRemovedMetricConfig{\n\t\t\t\t\t\tEnabled: false,\n\t\t\t\t\t},\n\t\t\t\t\tMetricInputType: MetricInputTypeMetricConfig{\n\t\t\t\t\t\tEnabled:             false,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategySum,\n\t\t\t\t\t\tEnabledAttributes:   []MetricInputTypeMetricAttributeKey{MetricInputTypeMetricAttributeKeyStringAttr, MetricInputTypeMetricAttributeKeyOverriddenIntAttr, MetricInputTypeMetricAttributeKeyEnumAttr, MetricInputTypeMetricAttributeKeySliceAttr, MetricInputTypeMetricAttributeKeyMapAttr},\n\t\t\t\t\t},\n\t\t\t\t\tOptionalMetric: OptionalMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             false,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []OptionalMetricMetricAttributeKey{OptionalMetricMetricAttributeKeyStringAttr, OptionalMetricMetricAttributeKeyBooleanAttr, OptionalMetricMetricAttributeKeyBooleanAttr2},\n\t\t\t\t\t},\n\t\t\t\t\tOptionalMetricEmptyUnit: OptionalMetricEmptyUnitMetricConfig{\n\t\t\t\t\t\tEnabled:             false,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []OptionalMetricEmptyUnitMetricAttributeKey{OptionalMetricEmptyUnitMetricAttributeKeyStringAttr, OptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr},\n\t\t\t\t\t},\n\t\t\t\t\tReaggregateMetric: ReaggregateMetricMetricConfig{\n\t\t\t\t\t\tEnabled:             false,\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategyAvg,\n\t\t\t\t\t\tEnabledAttributes:   []ReaggregateMetricMetricAttributeKey{ReaggregateMetricMetricAttributeKeyStringAttr, ReaggregateMetricMetricAttributeKeyBooleanAttr},\n\t\t\t\t\t},\n\t\t\t\t\tSystemCPUTime: SystemCPUTimeMetricConfig{\n\t\t\t\t\t\tEnabled: false,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tResourceAttributes: ResourceAttributesConfig{\n\t\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: false},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := loadMetricsBuilderConfig(t, tt.name)\n\t\t\tdiff := cmp.Diff(tt.want, cfg, cmpopts.IgnoreUnexported(DefaultMetricMetricConfig{}, DefaultMetricToBeRemovedMetricConfig{}, MetricInputTypeMetricConfig{}, OptionalMetricMetricConfig{}, OptionalMetricEmptyUnitMetricConfig{}, ReaggregateMetricMetricConfig{}, SystemCPUTimeMetricConfig{}, ResourceAttributeConfig{}))\n\t\t\trequire.Emptyf(t, diff, \"Config mismatch (-expected +actual):\\n%s\", diff)\n\t\t})\n\t}\n}\n\nfunc loadMetricsBuilderConfig(t *testing.T, name string) MetricsBuilderConfig {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tsub, err := cm.Sub(name)\n\trequire.NoError(t, err)\n\tcfg := DefaultMetricsBuilderConfig()\n\trequire.NoError(t, sub.Unmarshal(&cfg, confmap.WithIgnoreUnused()))\n\treturn cfg\n}\n\nfunc TestResourceAttributesConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant ResourceAttributesConfig\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\twant: DefaultResourceAttributesConfig(),\n\t\t},\n\t\t{\n\t\t\tname: \"all_set\",\n\t\t\twant: ResourceAttributesConfig{\n\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: true},\n\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: true},\n\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: true},\n\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: true},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"none_set\",\n\t\t\twant: ResourceAttributesConfig{\n\t\t\t\tMapResourceAttr:                  ResourceAttributeConfig{Enabled: false},\n\t\t\t\tOptionalResourceAttr:             ResourceAttributeConfig{Enabled: false},\n\t\t\t\tSliceResourceAttr:                ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringEnumResourceAttr:           ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttr:               ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttrDisableWarning: ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttrRemoveWarning:  ResourceAttributeConfig{Enabled: false},\n\t\t\t\tStringResourceAttrToBeRemoved:    ResourceAttributeConfig{Enabled: false},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := loadResourceAttributesConfig(t, tt.name)\n\t\t\tdiff := cmp.Diff(tt.want, cfg, cmpopts.IgnoreUnexported(ResourceAttributeConfig{}))\n\t\t\trequire.Emptyf(t, diff, \"Config mismatch (-expected +actual):\\n%s\", diff)\n\t\t})\n\t}\n}\n\nfunc loadResourceAttributesConfig(t *testing.T, name string) ResourceAttributesConfig {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tsub, err := cm.Sub(name)\n\trequire.NoError(t, err)\n\tsub, err = sub.Sub(\"resource_attributes\")\n\trequire.NoError(t, err)\n\tcfg := DefaultResourceAttributesConfig()\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\treturn cfg\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/internal/metadata/generated_logs.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\tconventions \"go.opentelemetry.io/otel/semconv/v1.38.0\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/scraper\"\n)\n\n// LogsBuilder provides an interface for scrapers to report logs while taking care of all the transformations\n// required to produce log representation defined in metadata and user config.\ntype LogsBuilder struct {\n\tlogsBuffer       plog.Logs\n\tlogRecordsBuffer plog.LogRecordSlice\n\tbuildInfo        component.BuildInfo // contains version information.\n}\n\n// LogBuilderOption applies changes to default logs builder.\ntype LogBuilderOption interface {\n\tapply(*LogsBuilder)\n}\n\nfunc NewLogsBuilder(settings scraper.Settings) *LogsBuilder {\n\tlb := &LogsBuilder{\n\t\tlogsBuffer:       plog.NewLogs(),\n\t\tlogRecordsBuffer: plog.NewLogRecordSlice(),\n\t\tbuildInfo:        settings.BuildInfo,\n\t}\n\n\treturn lb\n}\n\n// NewResourceBuilder returns a new resource builder that should be used to build a resource associated with for the emitted logs.\nfunc (lb *LogsBuilder) NewResourceBuilder() *ResourceBuilder {\n\treturn NewResourceBuilder(ResourceAttributesConfig{})\n}\n\n// ResourceLogsOption applies changes to provided resource logs.\ntype ResourceLogsOption interface {\n\tapply(plog.ResourceLogs)\n}\n\ntype resourceLogsOptionFunc func(plog.ResourceLogs)\n\nfunc (rlof resourceLogsOptionFunc) apply(rl plog.ResourceLogs) {\n\trlof(rl)\n}\n\n// WithLogsResource sets the provided resource on the emitted ResourceLogs.\n// It's recommended to use ResourceBuilder to create the resource.\nfunc WithLogsResource(res pcommon.Resource) ResourceLogsOption {\n\treturn resourceLogsOptionFunc(func(rl plog.ResourceLogs) {\n\t\tres.CopyTo(rl.Resource())\n\t})\n}\n\n// AppendLogRecord adds a log record to the logs builder.\nfunc (lb *LogsBuilder) AppendLogRecord(lr plog.LogRecord) {\n\tlr.MoveTo(lb.logRecordsBuffer.AppendEmpty())\n}\n\n// EmitForResource saves all the generated logs under a new resource and updates the internal state to be ready for\n// recording another set of log records as part of another resource. This function can be helpful when one scraper\n// needs to emit logs from several resources. Otherwise calling this function is not required,\n// just `Emit` function can be called instead.\n// Resource attributes should be provided as ResourceLogsOption arguments.\nfunc (lb *LogsBuilder) EmitForResource(options ...ResourceLogsOption) {\n\trl := plog.NewResourceLogs()\n\trl.SetSchemaUrl(conventions.SchemaURL)\n\tils := rl.ScopeLogs().AppendEmpty()\n\tils.Scope().SetName(ScopeName)\n\tils.Scope().SetVersion(lb.buildInfo.Version)\n\n\tfor _, op := range options {\n\t\top.apply(rl)\n\t}\n\n\tif lb.logRecordsBuffer.Len() > 0 {\n\t\tlb.logRecordsBuffer.MoveAndAppendTo(ils.LogRecords())\n\t\tlb.logRecordsBuffer = plog.NewLogRecordSlice()\n\t}\n\n\tif ils.LogRecords().Len() > 0 {\n\t\trl.MoveTo(lb.logsBuffer.ResourceLogs().AppendEmpty())\n\t}\n}\n\n// Emit returns all the logs accumulated by the logs builder and updates the internal state to be ready for\n// recording another set of logs. This function will be responsible for applying all the transformations required to\n// produce logs representation defined in metadata and user config.\nfunc (lb *LogsBuilder) Emit(options ...ResourceLogsOption) plog.Logs {\n\tlb.EmitForResource(options...)\n\tlogs := lb.logsBuffer\n\tlb.logsBuffer = plog.NewLogs()\n\treturn logs\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/internal/metadata/generated_logs_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/scraper/scrapertest\"\n)\n\nfunc TestLogsBuilderAppendLogRecord(t *testing.T) {\n\tobservedZapCore, _ := observer.New(zap.WarnLevel)\n\tsettings := scrapertest.NewNopSettings(scrapertest.NopType)\n\tsettings.Logger = zap.New(observedZapCore)\n\tlb := NewLogsBuilder(settings)\n\n\trb := lb.NewResourceBuilder()\n\trb.SetMapResourceAttr(map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"})\n\trb.SetOptionalResourceAttr(\"optional.resource.attr-val\")\n\trb.SetSliceResourceAttr([]any{\"slice.resource.attr-item1\", \"slice.resource.attr-item2\"})\n\trb.SetStringEnumResourceAttrOne()\n\trb.SetStringResourceAttr(\"string.resource.attr-val\")\n\trb.SetStringResourceAttrDisableWarning(\"string.resource.attr_disable_warning-val\")\n\trb.SetStringResourceAttrRemoveWarning(\"string.resource.attr_remove_warning-val\")\n\trb.SetStringResourceAttrToBeRemoved(\"string.resource.attr_to_be_removed-val\")\n\tres := rb.Emit()\n\n\t// append the first log record\n\tlr := plog.NewLogRecord()\n\tlr.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\tlr.Attributes().PutStr(\"type\", \"log\")\n\tlr.Body().SetStr(\"the first log record\")\n\n\t// append the second log record\n\tlr2 := plog.NewLogRecord()\n\tlr2.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\tlr2.Attributes().PutStr(\"type\", \"event\")\n\tlr2.Body().SetStr(\"the second log record\")\n\n\tlb.AppendLogRecord(lr)\n\tlb.AppendLogRecord(lr2)\n\n\tlogs := lb.Emit(WithLogsResource(res))\n\tassert.Equal(t, 1, logs.ResourceLogs().Len())\n\n\trl := logs.ResourceLogs().At(0)\n\tassert.Equal(t, 1, rl.ScopeLogs().Len())\n\n\tsl := rl.ScopeLogs().At(0)\n\tassert.Equal(t, ScopeName, sl.Scope().Name())\n\tassert.Equal(t, lb.buildInfo.Version, sl.Scope().Version())\n\n\tassert.Equal(t, 2, sl.LogRecords().Len())\n\n\tattrVal, ok := sl.LogRecords().At(0).Attributes().Get(\"type\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"log\", attrVal.Str())\n\n\tassert.Equal(t, pcommon.ValueTypeStr, sl.LogRecords().At(0).Body().Type())\n\tassert.Equal(t, \"the first log record\", sl.LogRecords().At(0).Body().Str())\n\n\tattrVal, ok = sl.LogRecords().At(1).Attributes().Get(\"type\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"event\", attrVal.Str())\n\n\tassert.Equal(t, pcommon.ValueTypeStr, sl.LogRecords().At(1).Body().Type())\n\tassert.Equal(t, \"the second log record\", sl.LogRecords().At(1).Body().Str())\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/internal/metadata/generated_metrics.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"fmt\"\n\t\"slices\"\n\t\"strconv\"\n\t\"time\"\n\n\tconventions \"go.opentelemetry.io/otel/semconv/v1.38.0\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/filter\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/scraper\"\n)\n\nconst (\n\tAggregationStrategySum = \"sum\"\n\tAggregationStrategyAvg = \"avg\"\n\tAggregationStrategyMin = \"min\"\n\tAggregationStrategyMax = \"max\"\n)\n\n// AttributeEnumAttr specifies the value enum_attr attribute.\ntype AttributeEnumAttr int\n\nconst (\n\t_ AttributeEnumAttr = iota\n\tAttributeEnumAttrRed\n\tAttributeEnumAttrGreen\n\tAttributeEnumAttrBlue\n)\n\n// String returns the string representation of the AttributeEnumAttr.\nfunc (av AttributeEnumAttr) String() string {\n\tswitch av {\n\tcase AttributeEnumAttrRed:\n\t\treturn \"red\"\n\tcase AttributeEnumAttrGreen:\n\t\treturn \"green\"\n\tcase AttributeEnumAttrBlue:\n\t\treturn \"blue\"\n\t}\n\treturn \"\"\n}\n\n// MapAttributeEnumAttr is a helper map of string to AttributeEnumAttr attribute value.\nvar MapAttributeEnumAttr = map[string]AttributeEnumAttr{\n\t\"red\":   AttributeEnumAttrRed,\n\t\"green\": AttributeEnumAttrGreen,\n\t\"blue\":  AttributeEnumAttrBlue,\n}\n\nvar MetricsInfo = metricsInfo{\n\tDefaultMetric: metricInfo{\n\t\tName: \"default.metric\",\n\t},\n\tDefaultMetricToBeRemoved: metricInfo{\n\t\tName: \"default.metric.to_be_removed\",\n\t},\n\tMetricInputType: metricInfo{\n\t\tName: \"metric.input_type\",\n\t},\n\tOptionalMetric: metricInfo{\n\t\tName: \"optional.metric\",\n\t},\n\tOptionalMetricEmptyUnit: metricInfo{\n\t\tName: \"optional.metric.empty_unit\",\n\t},\n\tReaggregateMetric: metricInfo{\n\t\tName: \"reaggregate.metric\",\n\t},\n\tSystemCPUTime: metricInfo{\n\t\tName: \"system.cpu.time\",\n\t},\n}\n\ntype metricsInfo struct {\n\tDefaultMetric            metricInfo\n\tDefaultMetricToBeRemoved metricInfo\n\tMetricInputType          metricInfo\n\tOptionalMetric           metricInfo\n\tOptionalMetricEmptyUnit  metricInfo\n\tReaggregateMetric        metricInfo\n\tSystemCPUTime            metricInfo\n}\n\ntype metricInfo struct {\n\tName string\n}\n\ntype metricDefaultMetric struct {\n\tdata          pmetric.Metric            // data buffer for generated metric.\n\tconfig        DefaultMetricMetricConfig // metric config provided by user.\n\tcapacity      int                       // max observed number of data points added to the metric.\n\taggDataPoints []int64                   // slice containing number of aggregated datapoints at each index\n}\n\n// init fills default.metric metric with initial data.\nfunc (m *metricDefaultMetric) init() {\n\tm.data.SetName(\"default.metric\")\n\tm.data.SetDescription(\"Monotonic cumulative sum int metric enabled by default.\")\n\tm.data.SetUnit(\"s\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(true)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n\tm.data.Sum().DataPoints().EnsureCapacity(m.capacity)\n\tm.aggDataPoints = m.aggDataPoints[:0]\n}\n\nfunc (m *metricDefaultMetric) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val int64, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue string, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\n\tdp := pmetric.NewNumberDataPoint()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tif slices.Contains(m.config.EnabledAttributes, DefaultMetricMetricAttributeKeyStringAttr) {\n\t\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, DefaultMetricMetricAttributeKeyOverriddenIntAttr) {\n\t\tdp.Attributes().PutInt(\"state\", overriddenIntAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, DefaultMetricMetricAttributeKeyEnumAttr) {\n\t\tdp.Attributes().PutStr(\"enum_attr\", enumAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, DefaultMetricMetricAttributeKeySliceAttr) {\n\t\tdp.Attributes().PutEmptySlice(\"slice_attr\").FromRaw(sliceAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, DefaultMetricMetricAttributeKeyMapAttr) {\n\t\tdp.Attributes().PutEmptyMap(\"map_attr\").FromRaw(mapAttrAttributeValue)\n\t}\n\n\tvar s string\n\tdps := m.data.Sum().DataPoints()\n\tfor i := 0; i < dps.Len(); i++ {\n\t\tdpi := dps.At(i)\n\t\tif dp.Attributes().Equal(dpi.Attributes()) && dp.StartTimestamp() == dpi.StartTimestamp() && dp.Timestamp() == dpi.Timestamp() {\n\t\t\tswitch s = m.config.AggregationStrategy; s {\n\t\t\tcase AggregationStrategySum, AggregationStrategyAvg:\n\t\t\t\tdpi.SetIntValue(dpi.IntValue() + val)\n\t\t\t\tm.aggDataPoints[i] += 1\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMin:\n\t\t\t\tif dpi.IntValue() > val {\n\t\t\t\t\tdpi.SetIntValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMax:\n\t\t\t\tif dpi.IntValue() < val {\n\t\t\t\t\tdpi.SetIntValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdp.SetIntValue(val)\n\tm.aggDataPoints = append(m.aggDataPoints, 1)\n\tdp.MoveTo(dps.AppendEmpty())\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricDefaultMetric) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricDefaultMetric) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tif m.config.AggregationStrategy == AggregationStrategyAvg {\n\t\t\tfor i, aggCount := range m.aggDataPoints {\n\t\t\t\tm.data.Sum().DataPoints().At(i).SetIntValue(m.data.Sum().DataPoints().At(i).IntValue() / aggCount)\n\t\t\t}\n\t\t}\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricDefaultMetric(cfg DefaultMetricMetricConfig) metricDefaultMetric {\n\tm := metricDefaultMetric{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricDefaultMetricToBeRemoved struct {\n\tdata     pmetric.Metric                       // data buffer for generated metric.\n\tconfig   DefaultMetricToBeRemovedMetricConfig // metric config provided by user.\n\tcapacity int                                  // max observed number of data points added to the metric.\n}\n\n// init fills default.metric.to_be_removed metric with initial data.\nfunc (m *metricDefaultMetricToBeRemoved) init() {\n\tm.data.SetName(\"default.metric.to_be_removed\")\n\tm.data.SetDescription(\"[DEPRECATED] Non-monotonic delta sum double metric enabled by default.\")\n\tm.data.SetUnit(\"s\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(false)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityDelta)\n}\n\nfunc (m *metricDefaultMetricToBeRemoved) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val float64) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\tdp := m.data.Sum().DataPoints().AppendEmpty()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tdp.SetDoubleValue(val)\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricDefaultMetricToBeRemoved) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricDefaultMetricToBeRemoved) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricDefaultMetricToBeRemoved(cfg DefaultMetricToBeRemovedMetricConfig) metricDefaultMetricToBeRemoved {\n\tm := metricDefaultMetricToBeRemoved{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricMetricInputType struct {\n\tdata          pmetric.Metric              // data buffer for generated metric.\n\tconfig        MetricInputTypeMetricConfig // metric config provided by user.\n\tcapacity      int                         // max observed number of data points added to the metric.\n\taggDataPoints []int64                     // slice containing number of aggregated datapoints at each index\n}\n\n// init fills metric.input_type metric with initial data.\nfunc (m *metricMetricInputType) init() {\n\tm.data.SetName(\"metric.input_type\")\n\tm.data.SetDescription(\"Monotonic cumulative sum int metric with string input_type enabled by default.\")\n\tm.data.SetUnit(\"s\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(true)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n\tm.data.Sum().DataPoints().EnsureCapacity(m.capacity)\n\tm.aggDataPoints = m.aggDataPoints[:0]\n}\n\nfunc (m *metricMetricInputType) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val int64, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue string, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\n\tdp := pmetric.NewNumberDataPoint()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tif slices.Contains(m.config.EnabledAttributes, MetricInputTypeMetricAttributeKeyStringAttr) {\n\t\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, MetricInputTypeMetricAttributeKeyOverriddenIntAttr) {\n\t\tdp.Attributes().PutInt(\"state\", overriddenIntAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, MetricInputTypeMetricAttributeKeyEnumAttr) {\n\t\tdp.Attributes().PutStr(\"enum_attr\", enumAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, MetricInputTypeMetricAttributeKeySliceAttr) {\n\t\tdp.Attributes().PutEmptySlice(\"slice_attr\").FromRaw(sliceAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, MetricInputTypeMetricAttributeKeyMapAttr) {\n\t\tdp.Attributes().PutEmptyMap(\"map_attr\").FromRaw(mapAttrAttributeValue)\n\t}\n\n\tvar s string\n\tdps := m.data.Sum().DataPoints()\n\tfor i := 0; i < dps.Len(); i++ {\n\t\tdpi := dps.At(i)\n\t\tif dp.Attributes().Equal(dpi.Attributes()) && dp.StartTimestamp() == dpi.StartTimestamp() && dp.Timestamp() == dpi.Timestamp() {\n\t\t\tswitch s = m.config.AggregationStrategy; s {\n\t\t\tcase AggregationStrategySum, AggregationStrategyAvg:\n\t\t\t\tdpi.SetIntValue(dpi.IntValue() + val)\n\t\t\t\tm.aggDataPoints[i] += 1\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMin:\n\t\t\t\tif dpi.IntValue() > val {\n\t\t\t\t\tdpi.SetIntValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMax:\n\t\t\t\tif dpi.IntValue() < val {\n\t\t\t\t\tdpi.SetIntValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdp.SetIntValue(val)\n\tm.aggDataPoints = append(m.aggDataPoints, 1)\n\tdp.MoveTo(dps.AppendEmpty())\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricMetricInputType) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricMetricInputType) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tif m.config.AggregationStrategy == AggregationStrategyAvg {\n\t\t\tfor i, aggCount := range m.aggDataPoints {\n\t\t\t\tm.data.Sum().DataPoints().At(i).SetIntValue(m.data.Sum().DataPoints().At(i).IntValue() / aggCount)\n\t\t\t}\n\t\t}\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricMetricInputType(cfg MetricInputTypeMetricConfig) metricMetricInputType {\n\tm := metricMetricInputType{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricOptionalMetric struct {\n\tdata          pmetric.Metric             // data buffer for generated metric.\n\tconfig        OptionalMetricMetricConfig // metric config provided by user.\n\tcapacity      int                        // max observed number of data points added to the metric.\n\taggDataPoints []float64                  // slice containing number of aggregated datapoints at each index\n}\n\n// init fills optional.metric metric with initial data.\nfunc (m *metricOptionalMetric) init() {\n\tm.data.SetName(\"optional.metric\")\n\tm.data.SetDescription(\"[DEPRECATED] Gauge double metric disabled by default.\")\n\tm.data.SetUnit(\"1\")\n\tm.data.SetEmptyGauge()\n\tm.data.Gauge().DataPoints().EnsureCapacity(m.capacity)\n\tm.aggDataPoints = m.aggDataPoints[:0]\n}\n\nfunc (m *metricOptionalMetric) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool, booleanAttr2AttributeValue bool) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\n\tdp := pmetric.NewNumberDataPoint()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tif slices.Contains(m.config.EnabledAttributes, OptionalMetricMetricAttributeKeyStringAttr) {\n\t\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, OptionalMetricMetricAttributeKeyBooleanAttr) {\n\t\tdp.Attributes().PutBool(\"boolean_attr\", booleanAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, OptionalMetricMetricAttributeKeyBooleanAttr2) {\n\t\tdp.Attributes().PutBool(\"boolean_attr2\", booleanAttr2AttributeValue)\n\t}\n\n\tvar s string\n\tdps := m.data.Gauge().DataPoints()\n\tfor i := 0; i < dps.Len(); i++ {\n\t\tdpi := dps.At(i)\n\t\tif dp.Attributes().Equal(dpi.Attributes()) && dp.StartTimestamp() == dpi.StartTimestamp() && dp.Timestamp() == dpi.Timestamp() {\n\t\t\tswitch s = m.config.AggregationStrategy; s {\n\t\t\tcase AggregationStrategySum, AggregationStrategyAvg:\n\t\t\t\tdpi.SetDoubleValue(dpi.DoubleValue() + val)\n\t\t\t\tm.aggDataPoints[i] += 1\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMin:\n\t\t\t\tif dpi.DoubleValue() > val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMax:\n\t\t\t\tif dpi.DoubleValue() < val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdp.SetDoubleValue(val)\n\tm.aggDataPoints = append(m.aggDataPoints, 1)\n\tdp.MoveTo(dps.AppendEmpty())\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricOptionalMetric) updateCapacity() {\n\tif m.data.Gauge().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Gauge().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricOptionalMetric) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 {\n\t\tif m.config.AggregationStrategy == AggregationStrategyAvg {\n\t\t\tfor i, aggCount := range m.aggDataPoints {\n\t\t\t\tm.data.Gauge().DataPoints().At(i).SetDoubleValue(m.data.Gauge().DataPoints().At(i).DoubleValue() / aggCount)\n\t\t\t}\n\t\t}\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricOptionalMetric(cfg OptionalMetricMetricConfig) metricOptionalMetric {\n\tm := metricOptionalMetric{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricOptionalMetricEmptyUnit struct {\n\tdata          pmetric.Metric                      // data buffer for generated metric.\n\tconfig        OptionalMetricEmptyUnitMetricConfig // metric config provided by user.\n\tcapacity      int                                 // max observed number of data points added to the metric.\n\taggDataPoints []float64                           // slice containing number of aggregated datapoints at each index\n}\n\n// init fills optional.metric.empty_unit metric with initial data.\nfunc (m *metricOptionalMetricEmptyUnit) init() {\n\tm.data.SetName(\"optional.metric.empty_unit\")\n\tm.data.SetDescription(\"[DEPRECATED] Gauge double metric disabled by default.\")\n\tm.data.SetUnit(\"\")\n\tm.data.SetEmptyGauge()\n\tm.data.Gauge().DataPoints().EnsureCapacity(m.capacity)\n\tm.aggDataPoints = m.aggDataPoints[:0]\n}\n\nfunc (m *metricOptionalMetricEmptyUnit) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\n\tdp := pmetric.NewNumberDataPoint()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tif slices.Contains(m.config.EnabledAttributes, OptionalMetricEmptyUnitMetricAttributeKeyStringAttr) {\n\t\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, OptionalMetricEmptyUnitMetricAttributeKeyBooleanAttr) {\n\t\tdp.Attributes().PutBool(\"boolean_attr\", booleanAttrAttributeValue)\n\t}\n\n\tvar s string\n\tdps := m.data.Gauge().DataPoints()\n\tfor i := 0; i < dps.Len(); i++ {\n\t\tdpi := dps.At(i)\n\t\tif dp.Attributes().Equal(dpi.Attributes()) && dp.StartTimestamp() == dpi.StartTimestamp() && dp.Timestamp() == dpi.Timestamp() {\n\t\t\tswitch s = m.config.AggregationStrategy; s {\n\t\t\tcase AggregationStrategySum, AggregationStrategyAvg:\n\t\t\t\tdpi.SetDoubleValue(dpi.DoubleValue() + val)\n\t\t\t\tm.aggDataPoints[i] += 1\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMin:\n\t\t\t\tif dpi.DoubleValue() > val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMax:\n\t\t\t\tif dpi.DoubleValue() < val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdp.SetDoubleValue(val)\n\tm.aggDataPoints = append(m.aggDataPoints, 1)\n\tdp.MoveTo(dps.AppendEmpty())\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricOptionalMetricEmptyUnit) updateCapacity() {\n\tif m.data.Gauge().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Gauge().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricOptionalMetricEmptyUnit) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 {\n\t\tif m.config.AggregationStrategy == AggregationStrategyAvg {\n\t\t\tfor i, aggCount := range m.aggDataPoints {\n\t\t\t\tm.data.Gauge().DataPoints().At(i).SetDoubleValue(m.data.Gauge().DataPoints().At(i).DoubleValue() / aggCount)\n\t\t\t}\n\t\t}\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricOptionalMetricEmptyUnit(cfg OptionalMetricEmptyUnitMetricConfig) metricOptionalMetricEmptyUnit {\n\tm := metricOptionalMetricEmptyUnit{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricReaggregateMetric struct {\n\tdata          pmetric.Metric                // data buffer for generated metric.\n\tconfig        ReaggregateMetricMetricConfig // metric config provided by user.\n\tcapacity      int                           // max observed number of data points added to the metric.\n\taggDataPoints []float64                     // slice containing number of aggregated datapoints at each index\n}\n\n// init fills reaggregate.metric metric with initial data.\nfunc (m *metricReaggregateMetric) init() {\n\tm.data.SetName(\"reaggregate.metric\")\n\tm.data.SetDescription(\"Metric for testing spatial reaggregation\")\n\tm.data.SetUnit(\"1\")\n\tm.data.SetEmptyGauge()\n\tm.data.Gauge().DataPoints().EnsureCapacity(m.capacity)\n\tm.aggDataPoints = m.aggDataPoints[:0]\n}\n\nfunc (m *metricReaggregateMetric) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\n\tdp := pmetric.NewNumberDataPoint()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tif slices.Contains(m.config.EnabledAttributes, ReaggregateMetricMetricAttributeKeyStringAttr) {\n\t\tdp.Attributes().PutStr(\"string_attr\", stringAttrAttributeValue)\n\t}\n\tif slices.Contains(m.config.EnabledAttributes, ReaggregateMetricMetricAttributeKeyBooleanAttr) {\n\t\tdp.Attributes().PutBool(\"boolean_attr\", booleanAttrAttributeValue)\n\t}\n\n\tvar s string\n\tdps := m.data.Gauge().DataPoints()\n\tfor i := 0; i < dps.Len(); i++ {\n\t\tdpi := dps.At(i)\n\t\tif dp.Attributes().Equal(dpi.Attributes()) && dp.StartTimestamp() == dpi.StartTimestamp() && dp.Timestamp() == dpi.Timestamp() {\n\t\t\tswitch s = m.config.AggregationStrategy; s {\n\t\t\tcase AggregationStrategySum, AggregationStrategyAvg:\n\t\t\t\tdpi.SetDoubleValue(dpi.DoubleValue() + val)\n\t\t\t\tm.aggDataPoints[i] += 1\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMin:\n\t\t\t\tif dpi.DoubleValue() > val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMax:\n\t\t\t\tif dpi.DoubleValue() < val {\n\t\t\t\t\tdpi.SetDoubleValue(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdp.SetDoubleValue(val)\n\tm.aggDataPoints = append(m.aggDataPoints, 1)\n\tdp.MoveTo(dps.AppendEmpty())\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricReaggregateMetric) updateCapacity() {\n\tif m.data.Gauge().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Gauge().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricReaggregateMetric) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Gauge().DataPoints().Len() > 0 {\n\t\tif m.config.AggregationStrategy == AggregationStrategyAvg {\n\t\t\tfor i, aggCount := range m.aggDataPoints {\n\t\t\t\tm.data.Gauge().DataPoints().At(i).SetDoubleValue(m.data.Gauge().DataPoints().At(i).DoubleValue() / aggCount)\n\t\t\t}\n\t\t}\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricReaggregateMetric(cfg ReaggregateMetricMetricConfig) metricReaggregateMetric {\n\tm := metricReaggregateMetric{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\ntype metricSystemCPUTime struct {\n\tdata     pmetric.Metric            // data buffer for generated metric.\n\tconfig   SystemCPUTimeMetricConfig // metric config provided by user.\n\tcapacity int                       // max observed number of data points added to the metric.\n}\n\n// init fills system.cpu.time metric with initial data.\nfunc (m *metricSystemCPUTime) init() {\n\tm.data.SetName(\"system.cpu.time\")\n\tm.data.SetDescription(\"Monotonic cumulative sum int metric enabled by default.\")\n\tm.data.SetUnit(\"s\")\n\tm.data.SetEmptySum()\n\tm.data.Sum().SetIsMonotonic(true)\n\tm.data.Sum().SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n}\n\nfunc (m *metricSystemCPUTime) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val int64) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\tdp := m.data.Sum().DataPoints().AppendEmpty()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tdp.SetIntValue(val)\n}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metricSystemCPUTime) updateCapacity() {\n\tif m.data.Sum().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.Sum().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metricSystemCPUTime) emit(metrics pmetric.MetricSlice) {\n\tif m.config.Enabled && m.data.Sum().DataPoints().Len() > 0 {\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetricSystemCPUTime(cfg SystemCPUTimeMetricConfig) metricSystemCPUTime {\n\tm := metricSystemCPUTime{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\n// MetricsBuilder provides an interface for scrapers to report metrics while taking care of all the transformations\n// required to produce metric representation defined in metadata and user config.\ntype MetricsBuilder struct {\n\tconfig                         MetricsBuilderConfig // config of the metrics builder.\n\tstartTime                      pcommon.Timestamp    // start time that will be applied to all recorded data points.\n\tmetricsCapacity                int                  // maximum observed number of metrics per resource.\n\tmetricsBuffer                  pmetric.Metrics      // accumulates metrics data before emitting.\n\tbuildInfo                      component.BuildInfo  // contains version information.\n\tresourceAttributeIncludeFilter map[string]filter.Filter\n\tresourceAttributeExcludeFilter map[string]filter.Filter\n\tmetricDefaultMetric            metricDefaultMetric\n\tmetricDefaultMetricToBeRemoved metricDefaultMetricToBeRemoved\n\tmetricMetricInputType          metricMetricInputType\n\tmetricOptionalMetric           metricOptionalMetric\n\tmetricOptionalMetricEmptyUnit  metricOptionalMetricEmptyUnit\n\tmetricReaggregateMetric        metricReaggregateMetric\n\tmetricSystemCPUTime            metricSystemCPUTime\n}\n\n// MetricBuilderOption applies changes to default metrics builder.\ntype MetricBuilderOption interface {\n\tapply(*MetricsBuilder)\n}\n\ntype metricBuilderOptionFunc func(mb *MetricsBuilder)\n\nfunc (mbof metricBuilderOptionFunc) apply(mb *MetricsBuilder) {\n\tmbof(mb)\n}\n\n// WithStartTime sets startTime on the metrics builder.\nfunc WithStartTime(startTime pcommon.Timestamp) MetricBuilderOption {\n\treturn metricBuilderOptionFunc(func(mb *MetricsBuilder) {\n\t\tmb.startTime = startTime\n\t})\n}\nfunc NewMetricsBuilder(mbc MetricsBuilderConfig, settings scraper.Settings, options ...MetricBuilderOption) *MetricsBuilder {\n\tif !mbc.Metrics.DefaultMetric.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] Please set `enabled` field explicitly for `default.metric`: This metric will be disabled by default soon.\")\n\t}\n\tif mbc.Metrics.DefaultMetricToBeRemoved.Enabled {\n\t\tsettings.Logger.Warn(\"[WARNING] `default.metric.to_be_removed` should not be enabled: This metric is deprecated and will be removed soon.\")\n\t}\n\tif mbc.Metrics.OptionalMetric.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] `optional.metric` should not be configured: This metric is deprecated and will be removed soon.\")\n\t}\n\tif mbc.Metrics.OptionalMetricEmptyUnit.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] `optional.metric.empty_unit` should not be configured: This metric is deprecated and will be removed soon.\")\n\t}\n\tif !mbc.ResourceAttributes.StringResourceAttrDisableWarning.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] Please set `enabled` field explicitly for `string.resource.attr_disable_warning`: This resource_attribute will be disabled by default soon.\")\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrRemoveWarning.enabledSetByUser || mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsInclude != nil || mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsExclude != nil {\n\t\tsettings.Logger.Warn(\"[WARNING] `string.resource.attr_remove_warning` should not be configured: This resource_attribute is deprecated and will be removed soon.\")\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrToBeRemoved.Enabled {\n\t\tsettings.Logger.Warn(\"[WARNING] `string.resource.attr_to_be_removed` should not be enabled: This resource_attribute is deprecated and will be removed soon.\")\n\t}\n\tmb := &MetricsBuilder{\n\t\tconfig:                         mbc,\n\t\tstartTime:                      pcommon.NewTimestampFromTime(time.Now()),\n\t\tmetricsBuffer:                  pmetric.NewMetrics(),\n\t\tbuildInfo:                      settings.BuildInfo,\n\t\tmetricDefaultMetric:            newMetricDefaultMetric(mbc.Metrics.DefaultMetric),\n\t\tmetricDefaultMetricToBeRemoved: newMetricDefaultMetricToBeRemoved(mbc.Metrics.DefaultMetricToBeRemoved),\n\t\tmetricMetricInputType:          newMetricMetricInputType(mbc.Metrics.MetricInputType),\n\t\tmetricOptionalMetric:           newMetricOptionalMetric(mbc.Metrics.OptionalMetric),\n\t\tmetricOptionalMetricEmptyUnit:  newMetricOptionalMetricEmptyUnit(mbc.Metrics.OptionalMetricEmptyUnit),\n\t\tmetricReaggregateMetric:        newMetricReaggregateMetric(mbc.Metrics.ReaggregateMetric),\n\t\tmetricSystemCPUTime:            newMetricSystemCPUTime(mbc.Metrics.SystemCPUTime),\n\t\tresourceAttributeIncludeFilter: make(map[string]filter.Filter),\n\t\tresourceAttributeExcludeFilter: make(map[string]filter.Filter),\n\t}\n\tif mbc.ResourceAttributes.MapResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"map.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.MapResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.MapResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"map.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.MapResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.OptionalResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"optional.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.OptionalResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.OptionalResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"optional.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.OptionalResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.SliceResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"slice.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.SliceResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.SliceResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"slice.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.SliceResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringEnumResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.enum.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.StringEnumResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringEnumResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.enum.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.StringEnumResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttr.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttr.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttr.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.resource.attr\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttr.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrDisableWarning.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.resource.attr_disable_warning\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrDisableWarning.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrDisableWarning.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.resource.attr_disable_warning\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrDisableWarning.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.resource.attr_remove_warning\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.resource.attr_remove_warning\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrRemoveWarning.MetricsExclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrToBeRemoved.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"string.resource.attr_to_be_removed\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrToBeRemoved.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.StringResourceAttrToBeRemoved.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"string.resource.attr_to_be_removed\"] = filter.CreateFilter(mbc.ResourceAttributes.StringResourceAttrToBeRemoved.MetricsExclude)\n\t}\n\n\tfor _, op := range options {\n\t\top.apply(mb)\n\t}\n\treturn mb\n}\n\n// NewResourceBuilder returns a new resource builder that should be used to build a resource associated with for the emitted metrics.\nfunc (mb *MetricsBuilder) NewResourceBuilder() *ResourceBuilder {\n\treturn NewResourceBuilder(mb.config.ResourceAttributes)\n}\n\n// updateCapacity updates max length of metrics and resource attributes that will be used for the slice capacity.\nfunc (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n}\n\n// ResourceMetricsOption applies changes to provided resource metrics.\ntype ResourceMetricsOption interface {\n\tapply(pmetric.ResourceMetrics)\n}\n\ntype resourceMetricsOptionFunc func(pmetric.ResourceMetrics)\n\nfunc (rmof resourceMetricsOptionFunc) apply(rm pmetric.ResourceMetrics) {\n\trmof(rm)\n}\n\n// WithResource sets the provided resource on the emitted ResourceMetrics.\n// It's recommended to use ResourceBuilder to create the resource.\nfunc WithResource(res pcommon.Resource) ResourceMetricsOption {\n\treturn resourceMetricsOptionFunc(func(rm pmetric.ResourceMetrics) {\n\t\tres.CopyTo(rm.Resource())\n\t})\n}\n\n// WithStartTimeOverride overrides start time for all the resource metrics data points.\n// This option should be only used if different start time has to be set on metrics coming from different resources.\nfunc WithStartTimeOverride(start pcommon.Timestamp) ResourceMetricsOption {\n\treturn resourceMetricsOptionFunc(func(rm pmetric.ResourceMetrics) {\n\t\tvar dps pmetric.NumberDataPointSlice\n\t\tmetrics := rm.ScopeMetrics().At(0).Metrics()\n\t\tfor i := 0; i < metrics.Len(); i++ {\n\t\t\tswitch metrics.At(i).Type() {\n\t\t\tcase pmetric.MetricTypeGauge:\n\t\t\t\tdps = metrics.At(i).Gauge().DataPoints()\n\t\t\tcase pmetric.MetricTypeSum:\n\t\t\t\tdps = metrics.At(i).Sum().DataPoints()\n\t\t\t}\n\t\t\tfor j := 0; j < dps.Len(); j++ {\n\t\t\t\tdps.At(j).SetStartTimestamp(start)\n\t\t\t}\n\t\t}\n\t})\n}\n\n// EmitForResource saves all the generated metrics under a new resource and updates the internal state to be ready for\n// recording another set of data points as part of another resource. This function can be helpful when one scraper\n// needs to emit metrics from several resources. Otherwise calling this function is not required,\n// just `Emit` function can be called instead.\n// Resource attributes should be provided as ResourceMetricsOption arguments.\nfunc (mb *MetricsBuilder) EmitForResource(options ...ResourceMetricsOption) {\n\trm := pmetric.NewResourceMetrics()\n\trm.SetSchemaUrl(conventions.SchemaURL)\n\tils := rm.ScopeMetrics().AppendEmpty()\n\tils.Scope().SetName(ScopeName)\n\tils.Scope().SetVersion(mb.buildInfo.Version)\n\tils.Metrics().EnsureCapacity(mb.metricsCapacity)\n\tmb.metricDefaultMetric.emit(ils.Metrics())\n\tmb.metricDefaultMetricToBeRemoved.emit(ils.Metrics())\n\tmb.metricMetricInputType.emit(ils.Metrics())\n\tmb.metricOptionalMetric.emit(ils.Metrics())\n\tmb.metricOptionalMetricEmptyUnit.emit(ils.Metrics())\n\tmb.metricReaggregateMetric.emit(ils.Metrics())\n\tmb.metricSystemCPUTime.emit(ils.Metrics())\n\n\tfor _, op := range options {\n\t\top.apply(rm)\n\t}\n\tfor attr, filter := range mb.resourceAttributeIncludeFilter {\n\t\tif val, ok := rm.Resource().Attributes().Get(attr); ok && !filter.Matches(val.AsString()) {\n\t\t\treturn\n\t\t}\n\t}\n\tfor attr, filter := range mb.resourceAttributeExcludeFilter {\n\t\tif val, ok := rm.Resource().Attributes().Get(attr); ok && filter.Matches(val.AsString()) {\n\t\t\treturn\n\t\t}\n\t}\n\n\tif ils.Metrics().Len() > 0 {\n\t\tmb.updateCapacity(rm)\n\t\trm.MoveTo(mb.metricsBuffer.ResourceMetrics().AppendEmpty())\n\t}\n}\n\n// Emit returns all the metrics accumulated by the metrics builder and updates the internal state to be ready for\n// recording another set of metrics. This function will be responsible for applying all the transformations required to\n// produce metric representation defined in metadata and user config, e.g. delta or cumulative.\nfunc (mb *MetricsBuilder) Emit(options ...ResourceMetricsOption) pmetric.Metrics {\n\tmb.EmitForResource(options...)\n\tmetrics := mb.metricsBuffer\n\tmb.metricsBuffer = pmetric.NewMetrics()\n\treturn metrics\n}\n\n// RecordDefaultMetricDataPoint adds a data point to default.metric metric.\nfunc (mb *MetricsBuilder) RecordDefaultMetricDataPoint(ts pcommon.Timestamp, val int64, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue AttributeEnumAttr, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any) {\n\tmb.metricDefaultMetric.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, overriddenIntAttrAttributeValue, enumAttrAttributeValue.String(), sliceAttrAttributeValue, mapAttrAttributeValue)\n}\n\n// RecordDefaultMetricToBeRemovedDataPoint adds a data point to default.metric.to_be_removed metric.\nfunc (mb *MetricsBuilder) RecordDefaultMetricToBeRemovedDataPoint(ts pcommon.Timestamp, val float64) {\n\tmb.metricDefaultMetricToBeRemoved.recordDataPoint(mb.startTime, ts, val)\n}\n\n// RecordMetricInputTypeDataPoint adds a data point to metric.input_type metric.\nfunc (mb *MetricsBuilder) RecordMetricInputTypeDataPoint(ts pcommon.Timestamp, inputVal string, stringAttrAttributeValue string, overriddenIntAttrAttributeValue int64, enumAttrAttributeValue AttributeEnumAttr, sliceAttrAttributeValue []any, mapAttrAttributeValue map[string]any) error {\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse int64 for MetricInputType, value was %s: %w\", inputVal, err)\n\t}\n\tmb.metricMetricInputType.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, overriddenIntAttrAttributeValue, enumAttrAttributeValue.String(), sliceAttrAttributeValue, mapAttrAttributeValue)\n\treturn nil\n}\n\n// RecordOptionalMetricDataPoint adds a data point to optional.metric metric.\nfunc (mb *MetricsBuilder) RecordOptionalMetricDataPoint(ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool, booleanAttr2AttributeValue bool) {\n\tmb.metricOptionalMetric.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, booleanAttrAttributeValue, booleanAttr2AttributeValue)\n}\n\n// RecordOptionalMetricEmptyUnitDataPoint adds a data point to optional.metric.empty_unit metric.\nfunc (mb *MetricsBuilder) RecordOptionalMetricEmptyUnitDataPoint(ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\tmb.metricOptionalMetricEmptyUnit.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, booleanAttrAttributeValue)\n}\n\n// RecordReaggregateMetricDataPoint adds a data point to reaggregate.metric metric.\nfunc (mb *MetricsBuilder) RecordReaggregateMetricDataPoint(ts pcommon.Timestamp, val float64, stringAttrAttributeValue string, booleanAttrAttributeValue bool) {\n\tmb.metricReaggregateMetric.recordDataPoint(mb.startTime, ts, val, stringAttrAttributeValue, booleanAttrAttributeValue)\n}\n\n// RecordSystemCPUTimeDataPoint adds a data point to system.cpu.time metric.\nfunc (mb *MetricsBuilder) RecordSystemCPUTimeDataPoint(ts pcommon.Timestamp, val int64) {\n\tmb.metricSystemCPUTime.recordDataPoint(mb.startTime, ts, val)\n}\n\n// Reset resets metrics builder to its initial state. It should be used when external metrics source is restarted,\n// and metrics builder should update its startTime and reset it's internal state accordingly.\nfunc (mb *MetricsBuilder) Reset(options ...MetricBuilderOption) {\n\tmb.startTime = pcommon.NewTimestampFromTime(time.Now())\n\tfor _, op := range options {\n\t\top.apply(mb)\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/internal/metadata/generated_metrics_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/scraper/scrapertest\"\n)\n\ntype testDataSet int\n\nconst (\n\ttestDataSetDefault testDataSet = iota\n\ttestDataSetAll\n\ttestDataSetNone\n\ttestDataSetReag\n)\n\nfunc TestMetricsBuilder(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tmetricsSet  testDataSet\n\t\tresAttrsSet testDataSet\n\t\texpectEmpty bool\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t},\n\t\t{\n\t\t\tname:        \"all_set\",\n\t\t\tmetricsSet:  testDataSetAll,\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t},\n\t\t{\n\t\t\tname:        \"reaggregate_set\",\n\t\t\tmetricsSet:  testDataSetReag,\n\t\t\tresAttrsSet: testDataSetReag,\n\t\t},\n\t\t{\n\t\t\tname:        \"none_set\",\n\t\t\tmetricsSet:  testDataSetNone,\n\t\t\tresAttrsSet: testDataSetNone,\n\t\t\texpectEmpty: true,\n\t\t},\n\t\t{\n\t\t\tname:        \"filter_set_include\",\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t},\n\t\t{\n\t\t\tname:        \"filter_set_exclude\",\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t\texpectEmpty: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tstart := pcommon.Timestamp(1_000_000_000)\n\t\t\tts := pcommon.Timestamp(1_000_001_000)\n\t\t\tobservedZapCore, observedLogs := observer.New(zap.WarnLevel)\n\t\t\tsettings := scrapertest.NewNopSettings(scrapertest.NopType)\n\t\t\tsettings.Logger = zap.New(observedZapCore)\n\t\t\tmb := NewMetricsBuilder(loadMetricsBuilderConfig(t, tt.name), settings, WithStartTime(start))\n\t\t\taggMap := make(map[string]string) // contains the aggregation strategies for each metric name\n\t\t\taggMap[\"DefaultMetric\"] = mb.metricDefaultMetric.config.AggregationStrategy\n\t\t\taggMap[\"MetricInputType\"] = mb.metricMetricInputType.config.AggregationStrategy\n\t\t\taggMap[\"OptionalMetric\"] = mb.metricOptionalMetric.config.AggregationStrategy\n\t\t\taggMap[\"OptionalMetricEmptyUnit\"] = mb.metricOptionalMetricEmptyUnit.config.AggregationStrategy\n\t\t\taggMap[\"ReaggregateMetric\"] = mb.metricReaggregateMetric.config.AggregationStrategy\n\n\t\t\texpectedWarnings := 0\n\t\t\tif tt.metricsSet == testDataSetDefault {\n\t\t\t\tassert.Equal(t, \"[WARNING] Please set `enabled` field explicitly for `default.metric`: This metric will be disabled by default soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetDefault || tt.metricsSet == testDataSetAll {\n\t\t\t\tassert.Equal(t, \"[WARNING] `default.metric.to_be_removed` should not be enabled: This metric is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetAll || tt.metricsSet == testDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `optional.metric` should not be configured: This metric is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetAll || tt.metricsSet == testDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `optional.metric.empty_unit` should not be configured: This metric is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.resAttrsSet == testDataSetDefault {\n\t\t\t\tassert.Equal(t, \"[WARNING] Please set `enabled` field explicitly for `string.resource.attr_disable_warning`: This resource_attribute will be disabled by default soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.resAttrsSet == testDataSetAll || tt.resAttrsSet == testDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `string.resource.attr_remove_warning` should not be configured: This resource_attribute is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.resAttrsSet == testDataSetDefault || tt.resAttrsSet == testDataSetAll {\n\t\t\t\tassert.Equal(t, \"[WARNING] `string.resource.attr_to_be_removed` should not be enabled: This resource_attribute is deprecated and will be removed soon.\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\tif tt.metricsSet != testDataSetReag {\n\t\t\t\tassert.Equal(t, expectedWarnings, observedLogs.Len())\n\t\t\t}\n\n\t\t\tdefaultMetricsCount := 0\n\t\t\tallMetricsCount := 0\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordDefaultMetricDataPoint(ts, 1, \"string_attr-val\", 19, AttributeEnumAttrRed, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"})\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tmb.RecordDefaultMetricDataPoint(ts, 3, \"string_attr-val-2\", 20, AttributeEnumAttrGreen, []any{\"slice_attr-item3\", \"slice_attr-item4\"}, map[string]any{\"key3\": \"map_attr-val3\", \"key4\": \"map_attr-val4\"})\n\t\t\t}\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordDefaultMetricToBeRemovedDataPoint(ts, 1)\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordMetricInputTypeDataPoint(ts, \"1\", \"string_attr-val\", 19, AttributeEnumAttrRed, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"})\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tmb.RecordMetricInputTypeDataPoint(ts, \"3\", \"string_attr-val-2\", 20, AttributeEnumAttrGreen, []any{\"slice_attr-item3\", \"slice_attr-item4\"}, map[string]any{\"key3\": \"map_attr-val3\", \"key4\": \"map_attr-val4\"})\n\t\t\t}\n\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordOptionalMetricDataPoint(ts, 1, \"string_attr-val\", true, false)\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tmb.RecordOptionalMetricDataPoint(ts, 3, \"string_attr-val-2\", false, true)\n\t\t\t}\n\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordOptionalMetricEmptyUnitDataPoint(ts, 1, \"string_attr-val\", true)\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tmb.RecordOptionalMetricEmptyUnitDataPoint(ts, 3, \"string_attr-val-2\", false)\n\t\t\t}\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordReaggregateMetricDataPoint(ts, 1, \"string_attr-val\", true)\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tmb.RecordReaggregateMetricDataPoint(ts, 3, \"string_attr-val-2\", false)\n\t\t\t}\n\n\t\t\tdefaultMetricsCount++\n\t\t\tallMetricsCount++\n\t\t\tmb.RecordSystemCPUTimeDataPoint(ts, 1)\n\n\t\t\trb := mb.NewResourceBuilder()\n\t\t\trb.SetMapResourceAttr(map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"})\n\t\t\trb.SetOptionalResourceAttr(\"optional.resource.attr-val\")\n\t\t\trb.SetSliceResourceAttr([]any{\"slice.resource.attr-item1\", \"slice.resource.attr-item2\"})\n\t\t\trb.SetStringEnumResourceAttrOne()\n\t\t\trb.SetStringResourceAttr(\"string.resource.attr-val\")\n\t\t\trb.SetStringResourceAttrDisableWarning(\"string.resource.attr_disable_warning-val\")\n\t\t\trb.SetStringResourceAttrRemoveWarning(\"string.resource.attr_remove_warning-val\")\n\t\t\trb.SetStringResourceAttrToBeRemoved(\"string.resource.attr_to_be_removed-val\")\n\t\t\tres := rb.Emit()\n\t\t\tmetrics := mb.Emit(WithResource(res))\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\tassert.Empty(t, mb.metricDefaultMetric.aggDataPoints)\n\t\t\t\tassert.Empty(t, mb.metricMetricInputType.aggDataPoints)\n\t\t\t\tassert.Empty(t, mb.metricOptionalMetric.aggDataPoints)\n\t\t\t\tassert.Empty(t, mb.metricOptionalMetricEmptyUnit.aggDataPoints)\n\t\t\t\tassert.Empty(t, mb.metricReaggregateMetric.aggDataPoints)\n\t\t\t}\n\n\t\t\tif tt.expectEmpty {\n\t\t\t\tassert.Equal(t, 0, metrics.ResourceMetrics().Len())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar allMetricsList []pmetric.Metric\n\t\t\ttotalMetricsCount := 0\n\t\t\tfor ri := 0; ri < metrics.ResourceMetrics().Len(); ri++ {\n\t\t\t\trm := metrics.ResourceMetrics().At(ri)\n\t\t\t\tassert.Equal(t, 1, rm.ScopeMetrics().Len())\n\t\t\t\tms := rm.ScopeMetrics().At(0).Metrics()\n\t\t\t\ttotalMetricsCount += ms.Len()\n\t\t\t\tfor mi := 0; mi < ms.Len(); mi++ {\n\t\t\t\t\tallMetricsList = append(allMetricsList, ms.At(mi))\n\t\t\t\t}\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetDefault {\n\t\t\t\tassert.Equal(t, defaultMetricsCount, totalMetricsCount)\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetAll {\n\t\t\t\tassert.Equal(t, allMetricsCount, totalMetricsCount)\n\t\t\t}\n\t\t\tvalidatedMetrics := make(map[string]bool)\n\t\t\tfor _, mi := range allMetricsList {\n\t\t\t\tswitch mi.Name() {\n\t\t\t\tcase \"default.metric\":\n\t\t\t\t\tif tt.name != \"reaggregate_set\" {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"default.metric\"], \"Found a duplicate in the metrics slice: default.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"default.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Monotonic cumulative sum int metric enabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\t\tassert.True(t, mi.Sum().IsMonotonic())\n\t\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, mi.Sum().AggregationTemporality())\n\t\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t\t\tstringAttrAttrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"string_attr-val\", stringAttrAttrVal.Str())\n\t\t\t\t\t\toverriddenIntAttrAttrVal, ok := dp.Attributes().Get(\"state\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.EqualValues(t, 19, overriddenIntAttrAttrVal.Int())\n\t\t\t\t\t\tenumAttrAttrVal, ok := dp.Attributes().Get(\"enum_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"red\", enumAttrAttrVal.Str())\n\t\t\t\t\t\tsliceAttrAttrVal, ok := dp.Attributes().Get(\"slice_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, sliceAttrAttrVal.Slice().AsRaw())\n\t\t\t\t\t\tmapAttrAttrVal, ok := dp.Attributes().Get(\"map_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"}, mapAttrAttrVal.Map().AsRaw())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"default.metric\"], \"Found a duplicate in the metrics slice: default.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"default.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Monotonic cumulative sum int metric enabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\t\tassert.True(t, mi.Sum().IsMonotonic())\n\t\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, mi.Sum().AggregationTemporality())\n\t\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\t\tswitch aggMap[\"default.metric\"] {\n\t\t\t\t\t\tcase \"sum\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(4), dp.IntValue())\n\t\t\t\t\t\tcase \"avg\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(2), dp.IntValue())\n\t\t\t\t\t\tcase \"min\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t\t\tcase \"max\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(3), dp.IntValue())\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"state\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"enum_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"slice_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"map_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t}\n\t\t\t\tcase \"default.metric.to_be_removed\":\n\t\t\t\t\tassert.False(t, validatedMetrics[\"default.metric.to_be_removed\"], \"Found a duplicate in the metrics slice: default.metric.to_be_removed\")\n\t\t\t\t\tvalidatedMetrics[\"default.metric.to_be_removed\"] = true\n\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Non-monotonic delta sum double metric enabled by default.\", mi.Description())\n\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\tassert.False(t, mi.Sum().IsMonotonic())\n\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityDelta, mi.Sum().AggregationTemporality())\n\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\tcase \"metric.input_type\":\n\t\t\t\t\tif tt.name != \"reaggregate_set\" {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"metric.input_type\"], \"Found a duplicate in the metrics slice: metric.input_type\")\n\t\t\t\t\t\tvalidatedMetrics[\"metric.input_type\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Monotonic cumulative sum int metric with string input_type enabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\t\tassert.True(t, mi.Sum().IsMonotonic())\n\t\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, mi.Sum().AggregationTemporality())\n\t\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t\t\tstringAttrAttrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"string_attr-val\", stringAttrAttrVal.Str())\n\t\t\t\t\t\toverriddenIntAttrAttrVal, ok := dp.Attributes().Get(\"state\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.EqualValues(t, 19, overriddenIntAttrAttrVal.Int())\n\t\t\t\t\t\tenumAttrAttrVal, ok := dp.Attributes().Get(\"enum_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"red\", enumAttrAttrVal.Str())\n\t\t\t\t\t\tsliceAttrAttrVal, ok := dp.Attributes().Get(\"slice_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, []any{\"slice_attr-item1\", \"slice_attr-item2\"}, sliceAttrAttrVal.Slice().AsRaw())\n\t\t\t\t\t\tmapAttrAttrVal, ok := dp.Attributes().Get(\"map_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, map[string]any{\"key1\": \"map_attr-val1\", \"key2\": \"map_attr-val2\"}, mapAttrAttrVal.Map().AsRaw())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"metric.input_type\"], \"Found a duplicate in the metrics slice: metric.input_type\")\n\t\t\t\t\t\tvalidatedMetrics[\"metric.input_type\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Monotonic cumulative sum int metric with string input_type enabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\t\tassert.True(t, mi.Sum().IsMonotonic())\n\t\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, mi.Sum().AggregationTemporality())\n\t\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\t\tswitch aggMap[\"metric.input_type\"] {\n\t\t\t\t\t\tcase \"sum\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(4), dp.IntValue())\n\t\t\t\t\t\tcase \"avg\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(2), dp.IntValue())\n\t\t\t\t\t\tcase \"min\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t\t\tcase \"max\":\n\t\t\t\t\t\t\tassert.Equal(t, int64(3), dp.IntValue())\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"state\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"enum_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"slice_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"map_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t}\n\t\t\t\tcase \"optional.metric\":\n\t\t\t\t\tif tt.name != \"reaggregate_set\" {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"optional.metric\"], \"Found a duplicate in the metrics slice: optional.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"optional.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Gauge double metric disabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"1\", mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tstringAttrAttrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"string_attr-val\", stringAttrAttrVal.Str())\n\t\t\t\t\t\tbooleanAttrAttrVal, ok := dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.True(t, booleanAttrAttrVal.Bool())\n\t\t\t\t\t\tbooleanAttr2AttrVal, ok := dp.Attributes().Get(\"boolean_attr2\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.False(t, booleanAttr2AttrVal.Bool())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"optional.metric\"], \"Found a duplicate in the metrics slice: optional.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"optional.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Gauge double metric disabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"1\", mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tswitch aggMap[\"optional.metric\"] {\n\t\t\t\t\t\tcase \"sum\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(4), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"avg\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(2), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"min\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"max\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(3), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"boolean_attr2\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t}\n\t\t\t\tcase \"optional.metric.empty_unit\":\n\t\t\t\t\tif tt.name != \"reaggregate_set\" {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"optional.metric.empty_unit\"], \"Found a duplicate in the metrics slice: optional.metric.empty_unit\")\n\t\t\t\t\t\tvalidatedMetrics[\"optional.metric.empty_unit\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Gauge double metric disabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Empty(t, mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tstringAttrAttrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"string_attr-val\", stringAttrAttrVal.Str())\n\t\t\t\t\t\tbooleanAttrAttrVal, ok := dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.True(t, booleanAttrAttrVal.Bool())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"optional.metric.empty_unit\"], \"Found a duplicate in the metrics slice: optional.metric.empty_unit\")\n\t\t\t\t\t\tvalidatedMetrics[\"optional.metric.empty_unit\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"[DEPRECATED] Gauge double metric disabled by default.\", mi.Description())\n\t\t\t\t\t\tassert.Empty(t, mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tswitch aggMap[\"optional.metric.empty_unit\"] {\n\t\t\t\t\t\tcase \"sum\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(4), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"avg\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(2), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"min\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"max\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(3), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t}\n\t\t\t\tcase \"reaggregate.metric\":\n\t\t\t\t\tif tt.name != \"reaggregate_set\" {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"reaggregate.metric\"], \"Found a duplicate in the metrics slice: reaggregate.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"reaggregate.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Metric for testing spatial reaggregation\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"1\", mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tstringAttrAttrVal, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.Equal(t, \"string_attr-val\", stringAttrAttrVal.Str())\n\t\t\t\t\t\tbooleanAttrAttrVal, ok := dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\tassert.True(t, booleanAttrAttrVal.Bool())\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"reaggregate.metric\"], \"Found a duplicate in the metrics slice: reaggregate.metric\")\n\t\t\t\t\t\tvalidatedMetrics[\"reaggregate.metric\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeGauge, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.Gauge().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"Metric for testing spatial reaggregation\", mi.Description())\n\t\t\t\t\t\tassert.Equal(t, \"1\", mi.Unit())\n\t\t\t\t\t\tdp := mi.Gauge().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeDouble, dp.ValueType())\n\t\t\t\t\t\tswitch aggMap[\"reaggregate.metric\"] {\n\t\t\t\t\t\tcase \"sum\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(4), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"avg\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(2), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"min\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(1), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\tcase \"max\":\n\t\t\t\t\t\t\tassert.InDelta(t, float64(3), dp.DoubleValue(), 0.01)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_, ok := dp.Attributes().Get(\"string_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t_, ok = dp.Attributes().Get(\"boolean_attr\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t}\n\t\t\t\tcase \"system.cpu.time\":\n\t\t\t\t\tassert.False(t, validatedMetrics[\"system.cpu.time\"], \"Found a duplicate in the metrics slice: system.cpu.time\")\n\t\t\t\t\tvalidatedMetrics[\"system.cpu.time\"] = true\n\t\t\t\t\tassert.Equal(t, pmetric.MetricTypeSum, mi.Type())\n\t\t\t\t\tassert.Equal(t, 1, mi.Sum().DataPoints().Len())\n\t\t\t\t\tassert.Equal(t, \"Monotonic cumulative sum int metric enabled by default.\", mi.Description())\n\t\t\t\t\tassert.Equal(t, \"s\", mi.Unit())\n\t\t\t\t\tassert.True(t, mi.Sum().IsMonotonic())\n\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, mi.Sum().AggregationTemporality())\n\t\t\t\t\tdp := mi.Sum().DataPoints().At(0)\n\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\tassert.Equal(t, int64(1), dp.IntValue())\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/internal/metadata/generated_resource.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ResourceBuilder is a helper struct to build resources predefined in metadata.yaml.\n// The ResourceBuilder is not thread-safe and must not to be used in multiple goroutines.\ntype ResourceBuilder struct {\n\tconfig ResourceAttributesConfig\n\tres    pcommon.Resource\n}\n\n// NewResourceBuilder creates a new ResourceBuilder. This method should be called on the start of the application.\nfunc NewResourceBuilder(rac ResourceAttributesConfig) *ResourceBuilder {\n\treturn &ResourceBuilder{\n\t\tconfig: rac,\n\t\tres:    pcommon.NewResource(),\n\t}\n}\n\n// SetMapResourceAttr sets provided value as \"map.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetMapResourceAttr(val map[string]any) {\n\tif rb.config.MapResourceAttr.Enabled {\n\t\trb.res.Attributes().PutEmptyMap(\"map.resource.attr\").FromRaw(val)\n\t}\n}\n\n// SetOptionalResourceAttr sets provided value as \"optional.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetOptionalResourceAttr(val string) {\n\tif rb.config.OptionalResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"optional.resource.attr\", val)\n\t}\n}\n\n// SetSliceResourceAttr sets provided value as \"slice.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetSliceResourceAttr(val []any) {\n\tif rb.config.SliceResourceAttr.Enabled {\n\t\trb.res.Attributes().PutEmptySlice(\"slice.resource.attr\").FromRaw(val)\n\t}\n}\n\n// SetStringEnumResourceAttrOne sets \"string.enum.resource.attr=one\" attribute.\nfunc (rb *ResourceBuilder) SetStringEnumResourceAttrOne() {\n\tif rb.config.StringEnumResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.enum.resource.attr\", \"one\")\n\t}\n}\n\n// SetStringEnumResourceAttrTwo sets \"string.enum.resource.attr=two\" attribute.\nfunc (rb *ResourceBuilder) SetStringEnumResourceAttrTwo() {\n\tif rb.config.StringEnumResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.enum.resource.attr\", \"two\")\n\t}\n}\n\n// SetStringResourceAttr sets provided value as \"string.resource.attr\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttr(val string) {\n\tif rb.config.StringResourceAttr.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr\", val)\n\t}\n}\n\n// SetStringResourceAttrDisableWarning sets provided value as \"string.resource.attr_disable_warning\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttrDisableWarning(val string) {\n\tif rb.config.StringResourceAttrDisableWarning.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr_disable_warning\", val)\n\t}\n}\n\n// SetStringResourceAttrRemoveWarning sets provided value as \"string.resource.attr_remove_warning\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttrRemoveWarning(val string) {\n\tif rb.config.StringResourceAttrRemoveWarning.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr_remove_warning\", val)\n\t}\n}\n\n// SetStringResourceAttrToBeRemoved sets provided value as \"string.resource.attr_to_be_removed\" attribute.\nfunc (rb *ResourceBuilder) SetStringResourceAttrToBeRemoved(val string) {\n\tif rb.config.StringResourceAttrToBeRemoved.Enabled {\n\t\trb.res.Attributes().PutStr(\"string.resource.attr_to_be_removed\", val)\n\t}\n}\n\n// Emit returns the built resource and resets the internal builder state.\nfunc (rb *ResourceBuilder) Emit() pcommon.Resource {\n\tr := rb.res\n\trb.res = pcommon.NewResource()\n\treturn r\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/internal/metadata/generated_resource_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestResourceBuilder(t *testing.T) {\n\tfor _, tt := range []string{\"default\", \"all_set\", \"none_set\"} {\n\t\tt.Run(tt, func(t *testing.T) {\n\t\t\tcfg := loadResourceAttributesConfig(t, tt)\n\t\t\trb := NewResourceBuilder(cfg)\n\t\t\trb.SetMapResourceAttr(map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"})\n\t\t\trb.SetOptionalResourceAttr(\"optional.resource.attr-val\")\n\t\t\trb.SetSliceResourceAttr([]any{\"slice.resource.attr-item1\", \"slice.resource.attr-item2\"})\n\t\t\trb.SetStringEnumResourceAttrOne()\n\t\t\trb.SetStringResourceAttr(\"string.resource.attr-val\")\n\t\t\trb.SetStringResourceAttrDisableWarning(\"string.resource.attr_disable_warning-val\")\n\t\t\trb.SetStringResourceAttrRemoveWarning(\"string.resource.attr_remove_warning-val\")\n\t\t\trb.SetStringResourceAttrToBeRemoved(\"string.resource.attr_to_be_removed-val\")\n\n\t\t\tres := rb.Emit()\n\t\t\tassert.Equal(t, 0, rb.Emit().Attributes().Len()) // Second call should return empty Resource\n\n\t\t\tswitch tt {\n\t\t\tcase \"default\":\n\t\t\t\tassert.Equal(t, 6, res.Attributes().Len())\n\t\t\tcase \"all_set\":\n\t\t\t\tassert.Equal(t, 8, res.Attributes().Len())\n\t\t\tcase \"none_set\":\n\t\t\t\tassert.Equal(t, 0, res.Attributes().Len())\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tassert.Failf(t, \"unexpected test case: %s\", tt)\n\t\t\t}\n\t\t\tmapResourceAttrAttrVal, ok := res.Attributes().Get(\"map.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, map[string]any{\"key1\": \"map.resource.attr-val1\", \"key2\": \"map.resource.attr-val2\"}, mapResourceAttrAttrVal.Map().AsRaw())\n\t\t\t}\n\t\t\toptionalResourceAttrAttrVal, ok := res.Attributes().Get(\"optional.resource.attr\")\n\t\t\tassert.Equal(t, tt == \"all_set\", ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"optional.resource.attr-val\", optionalResourceAttrAttrVal.Str())\n\t\t\t}\n\t\t\tsliceResourceAttrAttrVal, ok := res.Attributes().Get(\"slice.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, []any{\"slice.resource.attr-item1\", \"slice.resource.attr-item2\"}, sliceResourceAttrAttrVal.Slice().AsRaw())\n\t\t\t}\n\t\t\tstringEnumResourceAttrAttrVal, ok := res.Attributes().Get(\"string.enum.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"one\", stringEnumResourceAttrAttrVal.Str())\n\t\t\t}\n\t\t\tstringResourceAttrAttrVal, ok := res.Attributes().Get(\"string.resource.attr\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr-val\", stringResourceAttrAttrVal.Str())\n\t\t\t}\n\t\t\tstringResourceAttrDisableWarningAttrVal, ok := res.Attributes().Get(\"string.resource.attr_disable_warning\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr_disable_warning-val\", stringResourceAttrDisableWarningAttrVal.Str())\n\t\t\t}\n\t\t\tstringResourceAttrRemoveWarningAttrVal, ok := res.Attributes().Get(\"string.resource.attr_remove_warning\")\n\t\t\tassert.Equal(t, tt == \"all_set\", ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr_remove_warning-val\", stringResourceAttrRemoveWarningAttrVal.Str())\n\t\t\t}\n\t\t\tstringResourceAttrToBeRemovedAttrVal, ok := res.Attributes().Get(\"string.resource.attr_to_be_removed\")\n\t\t\tassert.True(t, ok)\n\t\t\tif ok {\n\t\t\t\tassert.Equal(t, \"string.resource.attr_to_be_removed-val\", stringResourceAttrToBeRemovedAttrVal.Str())\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"sample\")\n\tScopeName = \"go.opentelemetry.io/collector/cmd/mdatagen/internal/samplescraper\"\n)\n\nconst (\n\tLogsStability     = component.StabilityLevelDevelopment\n\tProfilesStability = component.StabilityLevelDevelopment\n\tMetricsStability  = component.StabilityLevelStable\n)\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/internal/metadata/testdata/config.yaml",
    "content": "default:\nall_set:\n  metrics:\n    default.metric:\n      enabled: true\n      attributes: [\"string_attr\",\"state\",\"enum_attr\",\"slice_attr\",\"map_attr\"]\n    default.metric.to_be_removed:\n      enabled: true\n    metric.input_type:\n      enabled: true\n      attributes: [\"string_attr\",\"state\",\"enum_attr\",\"slice_attr\",\"map_attr\"]\n    optional.metric:\n      enabled: true\n      attributes: [\"string_attr\",\"boolean_attr\",\"boolean_attr2\"]\n    optional.metric.empty_unit:\n      enabled: true\n      attributes: [\"string_attr\",\"boolean_attr\"]\n    reaggregate.metric:\n      enabled: true\n      attributes: [\"string_attr\",\"boolean_attr\"]\n    system.cpu.time:\n      enabled: true\n  resource_attributes:\n    map.resource.attr:\n      enabled: true\n    optional.resource.attr:\n      enabled: true\n    slice.resource.attr:\n      enabled: true\n    string.enum.resource.attr:\n      enabled: true\n    string.resource.attr:\n      enabled: true\n    string.resource.attr_disable_warning:\n      enabled: true\n    string.resource.attr_remove_warning:\n      enabled: true\n    string.resource.attr_to_be_removed:\n      enabled: true\nreaggregate_set:\n  metrics:\n    default.metric:\n      enabled: true\n      attributes: []\n    default.metric.to_be_removed:\n      enabled: true\n    metric.input_type:\n      enabled: true\n      attributes: []\n    optional.metric:\n      enabled: true\n      attributes: []\n    optional.metric.empty_unit:\n      enabled: true\n      attributes: []\n    reaggregate.metric:\n      enabled: true\n      attributes: []\n    system.cpu.time:\n      enabled: true\n  resource_attributes:\n    map.resource.attr:\n      enabled: true\n    optional.resource.attr:\n      enabled: true\n    slice.resource.attr:\n      enabled: true\n    string.enum.resource.attr:\n      enabled: true\n    string.resource.attr:\n      enabled: true\n    string.resource.attr_disable_warning:\n      enabled: true\n    string.resource.attr_remove_warning:\n      enabled: true\n    string.resource.attr_to_be_removed:\n      enabled: true\nnone_set:\n  metrics:\n    default.metric:\n      enabled: false\n      attributes: [\"string_attr\",\"state\",\"enum_attr\",\"slice_attr\",\"map_attr\"]\n    default.metric.to_be_removed:\n      enabled: false\n    metric.input_type:\n      enabled: false\n      attributes: [\"string_attr\",\"state\",\"enum_attr\",\"slice_attr\",\"map_attr\"]\n    optional.metric:\n      enabled: false\n      attributes: [\"string_attr\",\"boolean_attr\",\"boolean_attr2\"]\n    optional.metric.empty_unit:\n      enabled: false\n      attributes: [\"string_attr\",\"boolean_attr\"]\n    reaggregate.metric:\n      enabled: false\n      attributes: [\"string_attr\",\"boolean_attr\"]\n    system.cpu.time:\n      enabled: false\n  resource_attributes:\n    map.resource.attr:\n      enabled: false\n    optional.resource.attr:\n      enabled: false\n    slice.resource.attr:\n      enabled: false\n    string.enum.resource.attr:\n      enabled: false\n    string.resource.attr:\n      enabled: false\n    string.resource.attr_disable_warning:\n      enabled: false\n    string.resource.attr_remove_warning:\n      enabled: false\n    string.resource.attr_to_be_removed:\n      enabled: false\nfilter_set_include:\n  resource_attributes:\n    map.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    optional.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    slice.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    string.enum.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    string.resource.attr:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    string.resource.attr_disable_warning:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    string.resource.attr_remove_warning:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\n    string.resource.attr_to_be_removed:\n      enabled: true\n      metrics_include:\n        - regexp: \".*\"\nfilter_set_exclude:\n  resource_attributes:\n    map.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - regexp: \".*\"\n    optional.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - strict: \"optional.resource.attr-val\"\n    slice.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - regexp: \".*\"\n    string.enum.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - strict: \"one\"\n    string.resource.attr:\n      enabled: true\n      metrics_exclude:\n        - strict: \"string.resource.attr-val\"\n    string.resource.attr_disable_warning:\n      enabled: true\n      metrics_exclude:\n        - strict: \"string.resource.attr_disable_warning-val\"\n    string.resource.attr_remove_warning:\n      enabled: true\n      metrics_exclude:\n        - strict: \"string.resource.attr_remove_warning-val\"\n    string.resource.attr_to_be_removed:\n      enabled: true\n      metrics_exclude:\n        - strict: \"string.resource.attr_to_be_removed-val\"\n"
  },
  {
    "path": "cmd/mdatagen/internal/samplescraper/metadata.yaml",
    "content": "# Sample metadata file with all available configurations for a scraper.\n\ntype: sample\ndisplay_name: Sample Scraper\ndescription: This scraper is used for testing purposes to check the output of mdatagen.\nreaggregation_enabled: true\ngithub_project: open-telemetry/opentelemetry-collector\n\nsem_conv_version: 1.38.0\n\nstatus:\n  disable_codecov_badge: true\n  class: scraper\n  stability:\n    stable: [metrics]\n    development: [logs, profiles]\n  distributions: []\n  unsupported_platforms: [freebsd, illumos]\n  codeowners:\n    active: [dmitryax]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nconfig:\n  type: object\n  description: Configuration for the Sample Scraper.\n  allOf:\n    - $ref: /scraper/scraperhelper.controller_config\n  $defs:\n  properties:\n    targets:\n      description: Targets configuration for the scraper.\n      x-pointer: true\n      type: array\n      items:\n        type: object\n        properties:\n          http_client:\n            $ref: /config/confighttp.client_config\n          interval:\n            type: string\n            format: duration\n            x-optional: true\n\nresource_attributes:\n  map.resource.attr:\n    description: Resource attribute with a map value.\n    type: map\n    enabled: true\n\n  optional.resource.attr:\n    description: Explicitly disabled ResourceAttribute.\n    type: string\n    enabled: false\n\n  slice.resource.attr:\n    description: Resource attribute with a slice value.\n    type: slice\n    enabled: true\n\n  string.enum.resource.attr:\n    description: Resource attribute with a known set of string values.\n    type: string\n    enum: [one, two]\n    enabled: true\n\n  string.resource.attr:\n    description: Resource attribute with any string value.\n    type: string\n    enabled: true\n\n  string.resource.attr_disable_warning:\n    description: Resource attribute with any string value.\n    type: string\n    enabled: true\n    warnings:\n      if_enabled_not_set: This resource_attribute will be disabled by default soon.\n\n  string.resource.attr_remove_warning:\n    description: Resource attribute with any string value.\n    type: string\n    enabled: false\n    warnings:\n      if_configured: This resource_attribute is deprecated and will be removed soon.\n\n  string.resource.attr_to_be_removed:\n    description: Resource attribute with any string value.\n    type: string\n    enabled: true\n    warnings:\n      if_enabled: This resource_attribute is deprecated and will be removed soon.\n\nattributes:\n  boolean_attr:\n    description: Attribute with a boolean value.\n    type: bool\n\n  # This 2nd boolean attribute allows us to test both values for boolean attributes,\n  # as test values are based on the parity of the attribute name length.\n  boolean_attr2:\n    description: Another attribute with a boolean value.\n    type: bool\n\n  enum_attr:\n    description: Attribute with a known set of string values.\n    type: string\n    enum: [red, green, blue]\n\n  map_attr:\n    description: Attribute with a map value.\n    type: map\n\n  overridden_int_attr:\n    name_override: state\n    description: Integer attribute with overridden name.\n    type: int\n\n  slice_attr:\n    description: Attribute with a slice value.\n    type: slice\n\n  string_attr:\n    description: Attribute with any string value.\n    type: string\n\nmetrics:\n  default.metric:\n    enabled: true\n    description: Monotonic cumulative sum int metric enabled by default.\n    extended_documentation: The metric will be become optional soon.\n    stability: development\n    unit: s\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n    attributes:\n      [string_attr, overridden_int_attr, enum_attr, slice_attr, map_attr]\n    warnings:\n      if_enabled_not_set: This metric will be disabled by default soon.\n\n  default.metric.to_be_removed:\n    enabled: true\n    description: \"[DEPRECATED] Non-monotonic delta sum double metric enabled by default.\"\n    extended_documentation: The metric will be removed soon.\n    stability: deprecated\n    deprecated:\n      since: \"1.0.0\"\n      note: \"This metric will be removed\"\n    unit: s\n    sum:\n      value_type: double\n      monotonic: false\n      aggregation_temporality: delta\n    warnings:\n      if_enabled: This metric is deprecated and will be removed soon.\n\n  metric.input_type:\n    enabled: true\n    stability: development\n    description: Monotonic cumulative sum int metric with string input_type enabled by default.\n    unit: s\n    sum:\n      value_type: int\n      input_type: string\n      monotonic: true\n      aggregation_temporality: cumulative\n    attributes:\n      [string_attr, overridden_int_attr, enum_attr, slice_attr, map_attr]\n\n  optional.metric:\n    enabled: false\n    description: \"[DEPRECATED] Gauge double metric disabled by default.\"\n    stability: deprecated\n    deprecated:\n      since: \"1.0.0\"\n      note: \"This metric will be removed\"\n    unit: \"1\"\n    gauge:\n      value_type: double\n    attributes: [string_attr, boolean_attr, boolean_attr2]\n    warnings:\n      if_configured: This metric is deprecated and will be removed soon.\n\n  optional.metric.empty_unit:\n    enabled: false\n    description: \"[DEPRECATED] Gauge double metric disabled by default.\"\n    stability: deprecated\n    deprecated:\n      since: \"1.0.0\"\n      note: \"This metric will be removed\"\n    unit: \"\"\n    gauge:\n      value_type: double\n    attributes: [string_attr, boolean_attr]\n    warnings:\n      if_configured: This metric is deprecated and will be removed soon.\n\n  reaggregate.metric:\n    enabled: true\n    description: Metric for testing spatial reaggregation\n    unit: \"1\"\n    stability: beta\n    gauge:\n      value_type: double\n    attributes: [string_attr, boolean_attr]\n\n  system.cpu.time:\n    enabled: true\n    stability: beta\n    description: Monotonic cumulative sum int metric enabled by default.\n    extended_documentation: The metric will be become optional soon.\n    unit: s\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n    semantic_convention:\n      ref: https://github.com/open-telemetry/semantic-conventions/blob/v1.38.0/docs/system/system-metrics.md#metric-systemcputime\n"
  },
  {
    "path": "cmd/mdatagen/internal/status.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"slices\"\n\t\"sort\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\n// distroURL returns the collection of distributions that can be referenced in the metadata.yaml files.\n// The rules below apply to every distribution added to this list:\n// - The distribution is open source and maintained by the OpenTelemetry project.\n// - The link must point to a publicly accessible repository.\nfunc distroURL(name string) string {\n\tswitch name {\n\tcase \"core\":\n\t\treturn \"https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\"\n\tcase \"contrib\":\n\t\treturn \"https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\"\n\tcase \"k8s\":\n\t\treturn \"https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\"\n\tcase \"otlp\":\n\t\treturn \"https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-otlp\"\n\tdefault:\n\t\treturn \"\"\n\t}\n}\n\ntype Codeowners struct {\n\t// Active codeowners\n\tActive []string `mapstructure:\"active\"`\n\t// Emeritus codeowners\n\tEmeritus []string `mapstructure:\"emeritus\"`\n\t// Whether new codeowners are being sought\n\tSeekingNew bool `mapstructure:\"seeking_new\"`\n}\n\ntype Status struct {\n\tStability            StabilityMap   `mapstructure:\"stability\"`\n\tDistributions        []string       `mapstructure:\"distributions\"`\n\tClass                string         `mapstructure:\"class\"`\n\tWarnings             []string       `mapstructure:\"warnings\"`\n\tCodeowners           *Codeowners    `mapstructure:\"codeowners\"`\n\tUnsupportedPlatforms []string       `mapstructure:\"unsupported_platforms\"`\n\tDeprecation          DeprecationMap `mapstructure:\"deprecation\"`\n\tCodeCovComponentID   string         `mapstructure:\"codecov_component_id\"`\n\tDisableCodeCov       bool           `mapstructure:\"disable_codecov_badge\"`\n}\n\ntype DeprecationMap map[string]DeprecationInfo\n\ntype DeprecationInfo struct {\n\tDate      string `mapstructure:\"date\"`\n\tMigration string `mapstructure:\"migration\"`\n}\n\nvar validClasses = []string{\n\t\"cmd\",\n\t\"connector\",\n\t\"converter\",\n\t\"exporter\",\n\t\"extension\",\n\t\"pkg\",\n\t\"processor\",\n\t\"provider\",\n\t\"receiver\",\n\t\"scraper\",\n}\n\nvar validStabilityKeys = []string{\n\t\"converter\",\n\t\"extension\",\n\t\"logs\",\n\t\"logs_to_traces\",\n\t\"logs_to_metrics\",\n\t\"logs_to_logs\",\n\t\"logs_to_profiles\",\n\t\"metrics\",\n\t\"metrics_to_traces\",\n\t\"metrics_to_metrics\",\n\t\"metrics_to_logs\",\n\t\"metrics_to_profiles\",\n\t\"profiles\",\n\t\"profiles_to_profiles\",\n\t\"profiles_to_traces\",\n\t\"profiles_to_metrics\",\n\t\"profiles_to_logs\",\n\t\"provider\",\n\t\"traces_to_traces\",\n\t\"traces_to_metrics\",\n\t\"traces_to_logs\",\n\t\"traces_to_profiles\",\n\t\"traces\",\n}\n\nfunc (s *Status) SortedDistributions() []string {\n\tsorted := s.Distributions\n\tsort.Slice(sorted, func(i, j int) bool {\n\t\tif s.Distributions[i] == \"core\" {\n\t\t\treturn true\n\t\t}\n\t\tif s.Distributions[i] == \"contrib\" {\n\t\t\treturn s.Distributions[j] != \"core\"\n\t\t}\n\t\tif s.Distributions[j] == \"core\" {\n\t\t\treturn false\n\t\t}\n\t\tif s.Distributions[j] == \"contrib\" {\n\t\t\treturn s.Distributions[i] == \"core\"\n\t\t}\n\t\treturn s.Distributions[i] < s.Distributions[j]\n\t})\n\treturn sorted\n}\n\nfunc (s *Status) Validate() error {\n\tvar errs error\n\tif s == nil {\n\t\treturn errors.New(\"missing status\")\n\t}\n\tif err := s.validateClass(); err != nil {\n\t\terrs = errors.Join(errs, err)\n\t}\n\n\tif err := s.Stability.Validate(); err != nil {\n\t\terrs = errors.Join(errs, err)\n\t}\n\tif err := s.Deprecation.Validate(s.Stability); err != nil {\n\t\terrs = errors.Join(errs, err)\n\t}\n\treturn errs\n}\n\nfunc (s *Status) validateClass() error {\n\tif s.Class == \"\" {\n\t\treturn errors.New(\"missing class\")\n\t}\n\tif !slices.Contains(validClasses, s.Class) {\n\t\treturn fmt.Errorf(\"invalid class: %v\", s.Class)\n\t}\n\treturn nil\n}\n\ntype StabilityMap map[component.StabilityLevel][]string\n\nfunc (ms StabilityMap) Validate() error {\n\tvar errs error\n\tif len(ms) == 0 {\n\t\treturn errors.New(\"missing stability\")\n\t}\n\tfor stability, cmps := range ms {\n\t\tif len(cmps) == 0 {\n\t\t\terrs = errors.Join(errs, fmt.Errorf(\"missing component for stability: %v\", stability))\n\t\t}\n\t\tfor _, c := range cmps {\n\t\t\tif !slices.Contains(validStabilityKeys, c) {\n\t\t\t\terrs = errors.Join(errs, fmt.Errorf(\"invalid component: %v\", c))\n\t\t\t}\n\t\t}\n\t}\n\treturn errs\n}\n\nfunc (dm DeprecationMap) Validate(ms StabilityMap) error {\n\tvar errs error\n\tfor stability, cmps := range ms {\n\t\tif stability != component.StabilityLevelDeprecated {\n\t\t\tcontinue\n\t\t}\n\t\tfor _, c := range cmps {\n\t\t\tdepInfo, found := dm[c]\n\t\t\tif !found {\n\t\t\t\terrs = errors.Join(errs, fmt.Errorf(\"deprecated component missing deprecation date and migration guide for %v\", c))\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif depInfo.Migration == \"\" {\n\t\t\t\terrs = errors.Join(errs, fmt.Errorf(\"deprecated component missing migration guide: %v\", c))\n\t\t\t}\n\t\t\tif depInfo.Date == \"\" {\n\t\t\t\terrs = errors.Join(errs, fmt.Errorf(\"deprecated component missing date in YYYY-MM-DD format: %v\", c))\n\t\t\t} else {\n\t\t\t\t_, err := time.Parse(\"2006-01-02\", depInfo.Date)\n\t\t\t\tif err != nil {\n\t\t\t\t\terrs = errors.Join(errs, fmt.Errorf(\"deprecated component missing valid date in YYYY-MM-DD format: %v\", c))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn errs\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/status_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestDistroURL(t *testing.T) {\n\ttests := []struct {\n\t\tinput  string\n\t\toutput string\n\t}{\n\t\t{\n\t\t\tinput:  \"core\",\n\t\t\toutput: \"https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\",\n\t\t},\n\t\t{\n\t\t\tinput:  \"contrib\",\n\t\t\toutput: \"https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\",\n\t\t},\n\t\t{\n\t\t\tinput:  \"k8s\",\n\t\t\toutput: \"https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\",\n\t\t},\n\t\t{\n\t\t\tinput:  \"otlp\",\n\t\t\toutput: \"https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-otlp\",\n\t\t},\n\t\t{\n\t\t\tinput:  \"not_found\",\n\t\t\toutput: \"\",\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.input, func(t *testing.T) {\n\t\t\tassert.Equal(t, test.output, distroURL(test.input))\n\t\t})\n\t}\n}\n\nfunc TestSortedDistributions(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\ts      Status\n\t\tresult []string\n\t}{\n\t\t{\n\t\t\t\"all combined\",\n\t\t\tStatus{Distributions: []string{\"arm\", \"contrib\", \"core\", \"foo\", \"bar\"}},\n\t\t\t[]string{\"core\", \"contrib\", \"arm\", \"bar\", \"foo\"},\n\t\t},\n\t\t{\n\t\t\t\"core only\",\n\t\t\tStatus{Distributions: []string{\"core\"}},\n\t\t\t[]string{\"core\"},\n\t\t},\n\t\t{\n\t\t\t\"core and contrib only\",\n\t\t\tStatus{Distributions: []string{\"core\", \"contrib\"}},\n\t\t\t[]string{\"core\", \"contrib\"},\n\t\t},\n\t\t{\n\t\t\t\"core and contrib reversed\",\n\t\t\tStatus{Distributions: []string{\"contrib\", \"core\"}},\n\t\t\t[]string{\"core\", \"contrib\"},\n\t\t},\n\t\t{\n\t\t\t\"neither core nor contrib\",\n\t\t\tStatus{Distributions: []string{\"foo\", \"bar\"}},\n\t\t\t[]string{\"bar\", \"foo\"},\n\t\t},\n\t\t{\n\t\t\t\"no core, contrib, something else\",\n\t\t\tStatus{Distributions: []string{\"foo\", \"contrib\", \"bar\"}},\n\t\t\t[]string{\"contrib\", \"bar\", \"foo\"},\n\t\t},\n\t\t{\n\t\t\t\"core, no contrib, something else\",\n\t\t\tStatus{Distributions: []string{\"foo\", \"core\", \"bar\"}},\n\t\t\t[]string{\"core\", \"bar\", \"foo\"},\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tassert.Equal(t, test.result, test.s.SortedDistributions())\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/telemetry.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal\"\n\ntype Telemetry struct {\n\tMetrics map[MetricName]Metric `mapstructure:\"metrics\"`\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/component_test.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\n{{- if len .Status.UnsupportedPlatforms }}\n//go:build {{ range $i, $v := .Status.UnsupportedPlatforms }}{{ if $i }} && {{ end }}!{{ . }}{{ end }}\n{{- end }}\n\npackage {{ .Package }}\n\nimport (\n\t{{- if not (and .Tests.SkipLifecycle .Tests.SkipShutdown) }}\n\t\"context\"\n\t{{- end }}\n\t\"testing\"\n\t{{- if and (not (and .Tests.SkipLifecycle .Tests.SkipShutdown)) (or isExporter isProcessor) }}\n\t\"time\"\n\t{{- end }}\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t{{- if not (and .Tests.SkipLifecycle .Tests.SkipShutdown) }}\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t{{- if isExporter }}\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t{{- if supportsProfiles }}\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n\t{{- end }}\n\t{{- end }}\n\t{{- if isProcessor }}\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n\t{{- if supportsProfiles }}\n\t\"go.opentelemetry.io/collector/processor/xprocessor\"\n\t{{- end }}\n\t{{- end }}\n\t{{- if isReceiver }}\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n\t{{- if supportsProfiles }}\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n\t{{- end }}\n\t{{- end }}\n\t{{- if isScraper }}\n\t\"go.opentelemetry.io/collector/scraper\"\n\t\"go.opentelemetry.io/collector/scraper/scrapertest\"\n\t{{- if supportsProfiles }}\n\t\"go.opentelemetry.io/collector/scraper/xscraper\"\n\t{{- end }}\n\t{{- end }}\n\t{{- if isExtension }}\n\t\"go.opentelemetry.io/collector/extension/extensiontest\"\n\t{{- end }}\n\t{{- if isConnector }}\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/connectortest\"\n\t{{- if supportsProfiles }}\n\t\"go.opentelemetry.io/collector/connector/xconnector\"\n\t{{- end }}\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t{{- if supportsProfiles }}\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\t{{- end }}\n\t{{- end }}\n\t{{- if or isExporter isProcessor }}\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t{{- end }}\n\t{{- end }}\n)\n\nvar typ = component.MustNewType(\"{{ .Type }}\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\n{{ if not (and .Tests.SkipLifecycle .Tests.SkipShutdown) -}}\n{{ if isExporter -}}\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct{\n\t\tcreateFn func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error)\n\t\tname string\n\t}{\n{{ if supportsLogs }}\n\t\t{\n\t\t\tname: \"logs\",\n\t\t\tcreateFn: func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateLogs(ctx, set, cfg)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsMetrics }}\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsTraces }}\n\t\t{\n\t\t\tname: \"traces\",\n\t\t\tcreateFn: func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateTraces(ctx, set, cfg)\n\t\t\t},\n\t\t},\n{{ end }}\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\t{{- if not .Tests.SkipShutdown }}\n\t\tt.Run(tt.name + \"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), exportertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\t{{- end }}\n\n\t\t{{- if not .Tests.SkipLifecycle }}\n\t\tt.Run(tt.name + \"-lifecycle\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), exportertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := {{ .Tests.Host }}\n\t\t\terr = c.Start(context.Background(), host)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NotPanics(t, func() {\n\t\t\t\tswitch tt.name {\n\t\t\t\tcase \"logs\":\n\t\t\t\t\te, ok := c.(exporter.Logs)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tlogs := generateLifecycleTestLogs()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tlogs.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeLogs(context.Background(), logs)\n\t\t\t\tcase \"metrics\":\n\t\t\t\t\te, ok := c.(exporter.Metrics)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tmetrics := generateLifecycleTestMetrics()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tmetrics.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeMetrics(context.Background(), metrics)\n\t\t\t\tcase \"traces\":\n\t\t\t\t\te, ok := c.(exporter.Traces)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\ttraces := generateLifecycleTestTraces()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\ttraces.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeTraces(context.Background(), traces)\n\t\t\t\t}\n\t\t\t})\n\t\t\t{{ if not expectConsumerError }}\n\t\t\trequire.NoError(t, err)\n\t\t\t{{ end }}\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\t{{- end }}\n\t}\n}\n{{ end }}\n\n{{ if isProcessor }}\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct{\n\t\tcreateFn func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error)\n\t\tname string\n\t}{\n{{ if supportsLogs }}\n\t\t{\n\t\t\tname: \"logs\",\n\t\t\tcreateFn: func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateLogs(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsMetrics }}\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsTraces }}\n\t\t{\n\t\t\tname: \"traces\",\n\t\t\tcreateFn: func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateTraces(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsProfiles }}\n\t\t{\n\t\t\tname: \"profiles\",\n\t\t\tcreateFn: func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.(xprocessor.Factory).CreateProfiles(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n{{ end }}\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\t{{- if not .Tests.SkipShutdown }}\n\t\tt.Run(tt.name + \"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), processortest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\t{{- end }}\n\n\t\t{{- if not .Tests.SkipLifecycle }}\n\t\tt.Run(tt.name + \"-lifecycle\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), processortest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := {{ .Tests.Host }}\n\t\t\terr = c.Start(context.Background(), host)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NotPanics(t, func() {\n\t\t\t\tswitch tt.name {\n\t\t\t\tcase \"logs\":\n\t\t\t\t\te, ok := c.(processor.Logs)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tlogs := generateLifecycleTestLogs()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tlogs.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeLogs(context.Background(), logs)\n\t\t\t\tcase \"metrics\":\n\t\t\t\t\te, ok := c.(processor.Metrics)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tmetrics := generateLifecycleTestMetrics()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tmetrics.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeMetrics(context.Background(), metrics)\n\t\t\t\tcase \"traces\":\n\t\t\t\t\te, ok := c.(processor.Traces)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\ttraces := generateLifecycleTestTraces()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\ttraces.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeTraces(context.Background(), traces)\n\t\t\t\t}\n\t\t\t})\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\t{{- end }}\n\t}\n}\n{{ end }}\n\n{{ if isReceiver }}\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct{\n\t\tcreateFn func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error)\n\t\tname string\n\t}{\n{{ if supportsLogs }}\n\t\t{\n\t\t\tname: \"logs\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateLogs(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsMetrics }}\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsTraces }}\n\t\t{\n\t\t\tname: \"traces\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateTraces(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsProfiles }}\n\t\t{\n\t\t\tname: \"profiles\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.(xreceiver.Factory).CreateProfiles(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n{{ end }}\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\t{{- if not .Tests.SkipShutdown }}\n\t\tt.Run(tt.name + \"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\t{{- end }}\n\n\t\t{{- if not .Tests.SkipLifecycle }}\n\t\tt.Run(tt.name + \"-lifecycle\", func(t *testing.T) {\n\t\t\tfirstRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := {{ .Tests.Host }}\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, firstRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, firstRcvr.Shutdown(context.Background()))\n\t\t\tsecondRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, secondRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, secondRcvr.Shutdown(context.Background()))\n\t\t})\n\t\t{{- end }}\n\t}\n}\n{{ end }}\n\n{{ if isScraper }}\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct{\n\t\tcreateFn func(ctx context.Context, set scraper.Settings, cfg component.Config) (component.Component, error)\n\t\tname string\n\t}{\n{{ if supportsLogs }}\n\t\t{\n\t\t\tname: \"logs\",\n\t\t\tcreateFn: func(ctx context.Context, set scraper.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateLogs(ctx, set, cfg)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsMetrics }}\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set scraper.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsTraces }}\n\t\t{\n\t\t\tname: \"traces\",\n\t\t\tcreateFn: func(ctx context.Context, set scraper.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateTraces(ctx, set, cfg)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsProfiles }}\n\t\t{\n\t\t\tname: \"profiles\",\n\t\t\tcreateFn: func(ctx context.Context, set scraper.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.(xscraper.Factory).CreateProfiles(ctx, set, cfg)\n\t\t\t},\n\t\t},\n{{ end }}\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\t{{- if not .Tests.SkipShutdown }}\n\t\tt.Run(tt.name + \"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), scrapertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\t{{- end }}\n\n\t\t{{- if not .Tests.SkipLifecycle }}\n\t\tt.Run(tt.name + \"-lifecycle\", func(t *testing.T) {\n\t\t\tfirstRcvr, err := tt.createFn(context.Background(), scrapertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := {{ .Tests.Host }}\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, firstRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, firstRcvr.Shutdown(context.Background()))\n\t\t\tsecondRcvr, err := tt.createFn(context.Background(), scrapertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, secondRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, secondRcvr.Shutdown(context.Background()))\n\t\t})\n\t\t{{- end }}\n\t}\n}\n{{ end }}\n\n{{ if isExtension }}\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\t{{- if not .Tests.SkipShutdown }}\n\tt.Run(\"shutdown\", func(t *testing.T) {\n\t\te, err := factory.Create(context.Background(), extensiontest.NewNopSettings(typ), cfg)\n\t\trequire.NoError(t, err)\n\t\terr = e.Shutdown(context.Background())\n\t\trequire.NoError(t, err)\n\t})\n\t{{- end }}\n\n\t{{- if not .Tests.SkipLifecycle }}\n\tt.Run(\"lifecycle\", func(t *testing.T) {\n\t\tfirstExt, err := factory.Create(context.Background(), extensiontest.NewNopSettings(typ), cfg)\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, firstExt.Start(context.Background(), {{ .Tests.Host }}))\n\t\trequire.NoError(t, firstExt.Shutdown(context.Background()))\n\n\t\tsecondExt, err := factory.Create(context.Background(), extensiontest.NewNopSettings(typ), cfg)\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, secondExt.Start(context.Background(), {{ .Tests.Host }}))\n\t\trequire.NoError(t, secondExt.Shutdown(context.Background()))\n\t})\n\t{{- end }}\n}\n{{ end }}\n\n{{ if isConnector }}\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct{\n\t\tcreateFn func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error)\n\t\tname string\n\t}{\n{{ if supportsLogsToLogs }}\n\t\t{\n\t\t\tname: \"logs_to_logs\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewLogsRouter(map[pipeline.ID]consumer.Logs{pipeline.NewID(pipeline.SignalLogs): consumertest.NewNop()})\n\t\t\t\treturn factory.CreateLogsToLogs(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsLogsToMetrics }}\n\t\t{\n\t\t\tname: \"logs_to_metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewMetricsRouter(map[pipeline.ID]consumer.Metrics{pipeline.NewID(pipeline.SignalMetrics): consumertest.NewNop()})\n\t\t\t\treturn factory.CreateLogsToMetrics(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsLogsToTraces }}\n\t\t{\n\t\t\tname: \"logs_to_traces\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewTracesRouter(map[pipeline.ID]consumer.Traces{pipeline.NewID(pipeline.SignalTraces): consumertest.NewNop()})\n\t\t\t\treturn factory.CreateLogsToTraces(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsLogsToProfiles }}\n\t\t{\n\t\t\tname: \"logs_to_profiles\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewTracesRouter(map[pipeline.ID]xconsumer.Profiles{pipeline.NewID(xpipeline.SignalProfiles): consumertest.NewNop()})\n\t\t\t\treturn factory.(xconnector.Factory).CreateLogsToProfiles(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsMetricsToLogs }}\n\t\t{\n\t\t\tname: \"metrics_to_logs\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewLogsRouter(map[pipeline.ID]consumer.Logs{pipeline.NewID(pipeline.SignalLogs): consumertest.NewNop()})\n\t\t\t\treturn factory.CreateMetricsToLogs(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsMetricsToMetrics }}\n\t\t{\n\t\t\tname: \"metrics_to_metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewMetricsRouter(map[pipeline.ID]consumer.Metrics{pipeline.NewID(pipeline.SignalMetrics): consumertest.NewNop()})\n\t\t\t\treturn factory.CreateMetricsToMetrics(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsMetricsToTraces }}\n\t\t{\n\t\t\tname: \"metrics_to_traces\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewTracesRouter(map[pipeline.ID]consumer.Traces{pipeline.NewID(pipeline.SignalTraces): consumertest.NewNop()})\n\t\t\t\treturn factory.CreateMetricsToTraces(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsMetricsToProfiles }}\n\t\t{\n\t\t\tname: \"metrics_to_profiles\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewTracesRouter(map[pipeline.ID]xconsumer.Profiles{pipeline.NewID(xpipeline.SignalProfiles): consumertest.NewNop()})\n\t\t\t\treturn factory.(xconnector.Factory).CreateMetricsToTraces(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsTracesToLogs }}\n\t\t{\n\t\t\tname: \"traces_to_logs\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewLogsRouter(map[pipeline.ID]consumer.Logs{pipeline.NewID(pipeline.SignalLogs): consumertest.NewNop()})\n\t\t\t\treturn factory.CreateTracesToLogs(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsTracesToMetrics }}\n\t\t{\n\t\t\tname: \"traces_to_metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewMetricsRouter(map[pipeline.ID]consumer.Metrics{pipeline.NewID(pipeline.SignalMetrics): consumertest.NewNop()})\n\t\t\t\treturn factory.CreateTracesToMetrics(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsTracesToTraces }}\n\t\t{\n\t\t\tname: \"traces_to_traces\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewTracesRouter(map[pipeline.ID]consumer.Traces{pipeline.NewID(pipeline.SignalTraces): consumertest.NewNop()})\n\t\t\t\treturn factory.CreateTracesToTraces(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsTracesToProfiles }}\n\t\t{\n\t\t\tname: \"traces_to_profiles\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewTracesRouter(map[pipeline.ID]xconsumer.Profiles{pipeline.NewID(xpipeline.SignalProfiles): consumertest.NewNop()})\n\t\t\t\treturn factory.(xconnector.Factory).CreateTracesToProfiles(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsProfilesToLogs }}\n\t\t{\n\t\t\tname: \"profiles_to_logs\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewLogsRouter(map[pipeline.ID]consumer.Logs{pipeline.NewID(pipeline.SignalLogs): consumertest.NewNop()})\n\t\t\t\treturn factory.(xconnector.Factory).CreateProfilesToLogs(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsProfilesToMetrics }}\n\t\t{\n\t\t\tname: \"profiles_to_metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewMetricsRouter(map[pipeline.ID]consumer.Metrics{pipeline.NewID(pipeline.SignalMetrics): consumertest.NewNop()})\n\t\t\t\treturn factory.(xconnector.Factory).CreateProfilesToMetrics(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsProfilesToTraces }}\n\t\t{\n\t\t\tname: \"profiles_to_traces\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewTracesRouter(map[pipeline.ID]consumer.Traces{pipeline.NewID(pipeline.SignalTraces): consumertest.NewNop()})\n\t\t\t\treturn factory.(xconnector.Factory).CreateProfilesToTraces(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n{{ end }}\n{{ if supportsProfilesToProfiles }}\n\t\t{\n\t\t\tname: \"profiles_to_profiles\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := xconnector.NewProfilesRouter(map[pipeline.ID]xconsumer.Profiles{pipeline.NewID(xpipeline.SignalProfiles): consumertest.NewNop()})\n\t\t\t\treturn factory.(xconnector.Factory).CreateProfilesToProfiles(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n{{ end }}\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\t{{- if not .Tests.SkipShutdown }}\n\t\tt.Run(tt.name + \"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), connectortest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\t{{- end }}\n\n\t\t{{- if not .Tests.SkipLifecycle }}\n\t\tt.Run(tt.name + \"-lifecycle\", func(t *testing.T) {\n\t\t\tfirstConnector, err := tt.createFn(context.Background(), connectortest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := {{ .Tests.Host }}\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, firstConnector.Start(context.Background(), host))\n\t\t\trequire.NoError(t, firstConnector.Shutdown(context.Background()))\n\t\t\tsecondConnector, err := tt.createFn(context.Background(), connectortest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, secondConnector.Start(context.Background(), host))\n\t\t\trequire.NoError(t, secondConnector.Shutdown(context.Background()))\n\t\t})\n\t\t{{- end }}\n\t}\n}\n{{ end }}\n\n{{ if or isExporter isProcessor -}}\nfunc generateLifecycleTestLogs() plog.Logs {\n\tlogs := plog.NewLogs()\n\trl := logs.ResourceLogs().AppendEmpty()\n\trl.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tl := rl.ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\tl.Body().SetStr(\"test log message\")\n\tl.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn logs\n}\n\nfunc generateLifecycleTestMetrics() pmetric.Metrics {\n\tmetrics := pmetric.NewMetrics()\n\trm := metrics.ResourceMetrics().AppendEmpty()\n\trm.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tm := rm.ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\tm.SetName(\"test_metric\")\n\tdp := m.SetEmptyGauge().DataPoints().AppendEmpty()\n\tdp.Attributes().PutStr(\"test_attr\", \"value_1\")\n\tdp.SetIntValue(123)\n\tdp.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn metrics\n}\n\nfunc generateLifecycleTestTraces() ptrace.Traces {\n\ttraces := ptrace.NewTraces()\n\trs := traces.ResourceSpans().AppendEmpty()\n\trs.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tspan := rs.ScopeSpans().AppendEmpty().Spans().AppendEmpty()\n\tspan.Attributes().PutStr(\"test_attr\", \"value_1\")\n\tspan.SetName(\"test_span\")\n\tspan.SetStartTimestamp(pcommon.NewTimestampFromTime(time.Now().Add(-1 * time.Second)))\n\tspan.SetEndTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn traces\n}\n{{- end }}\n{{- end }}\n\n{{- if not .Tests.SkipLifecycle }}\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n{{- end }}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/config.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ .Package }}\n\n{{ $reag := .ReaggregationEnabled }}\n{{- $hasReagMetrics := false }}\n{{- range $name, $metric := .Metrics }}{{- if and $reag (hasAggregatableAttributes $metric.Attributes) }}{{- $hasReagMetrics = true }}{{- end }}{{- end }}\n\nimport (\n\t{{- if $hasReagMetrics }}\n\t\"fmt\"\n\t\"slices\"\n\t{{- end }}\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t{{ if and .Metrics .ResourceAttributes -}}\n\t\"go.opentelemetry.io/collector/filter\"\n\t{{- end }}\n)\n{{ if .Metrics -}}\n\n{{- if not $reag }}\n// MetricConfig provides common config for a particular metric.\ntype MetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n}\n\nfunc (ms *MetricConfig) Unmarshal(parser *confmap.Conf) error {\n\t{{- template \"metricUnmarshal\" \"ms\" }}\n}\n{{- else }}\n\n{{- range $name, $metric := .Metrics }}\n{{- if hasAggregatableAttributes $metric.Attributes }}\n// {{ $name.Render }}MetricAttributeKey specifies the key of an attribute for the {{ $name }} metric.\ntype {{ $name.Render }}MetricAttributeKey string\n\nconst (\n\t{{- range $metric.Attributes }}\n\t{{ $name.Render }}MetricAttributeKey{{ .Render }} {{ $name.Render }}MetricAttributeKey = \"{{ (attributeInfo .).Name }}\"\n\t{{- end }}\n)\n{{- end }}\n\n// {{ $name.Render }}MetricConfig provides config for the {{ $name }} metric.\ntype {{ $name.Render }}MetricConfig struct {\n\tEnabled          bool `mapstructure:\"enabled\"`\n\tenabledSetByUser bool\n\t{{- if hasAggregatableAttributes $metric.Attributes }}\n\n\tAggregationStrategy string                                 `mapstructure:\"aggregation_strategy\"`\n\tEnabledAttributes   []{{ $name.Render }}MetricAttributeKey `mapstructure:\"attributes\"`\n\t{{- end }}\n}\n\nfunc (ms *{{ $name.Render }}MetricConfig) Unmarshal(parser *confmap.Conf) error {\n\t{{- template \"metricUnmarshal\" \"ms\" }}\n}\n\n{{ if hasAggregatableAttributes $metric.Attributes -}}\nfunc (ms *{{ $name.Render }}MetricConfig) Validate() error {\n\tfor _, val := range ms.EnabledAttributes {\n\t\tswitch val {\n\t\tcase {{ range $index, $element := $metric.Attributes -}}{{ if $index }}, {{ end }}{{ $name.Render }}MetricAttributeKey{{ $element.Render }}{{ end }}:\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"metric {{ $name }} doesn't have an attribute %v, valid attributes: [{{ range $index, $element := $metric.Attributes -}}{{ if $index }}, {{ end }}{{ (attributeInfo $element).Name }}{{ end }}]\", val)\n\t\t}\n\t}\n\n\t{{- range $element := $metric.Attributes }}\n\t{{- if (attributeInfo $element).IsRequired }}\n\tif !slices.Contains(ms.EnabledAttributes, {{ $name.Render }}MetricAttributeKey{{ $element.Render }}) {\n\t\treturn fmt.Errorf(\"{{ (attributeInfo $element).Name }} is a required attribute for {{ $name }} metric and must be included\")\n\t}\n\t{{- end }}\n\t{{- end }}\n\n\tswitch ms.AggregationStrategy {\n\tcase AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax:\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid aggregation strategy %q, valid strategies: [%s, %s, %s, %s]\", ms.AggregationStrategy, AggregationStrategySum, AggregationStrategyAvg, AggregationStrategyMin, AggregationStrategyMax)\n\t}\n\n\treturn nil\n}\n{{- end }}\n{{- end }}\n{{- end }}\n\n// MetricsConfig provides config for {{ .Type }} metrics.\ntype MetricsConfig struct {\n\t{{- range $name, $metric := .Metrics }}\n\t{{ $name.Render }} {{ if $reag }}{{ $name.Render }}{{ end }}MetricConfig `mapstructure:\"{{ $name }}\"`\n\t{{- end }}\n}\n\nfunc DefaultMetricsConfig() MetricsConfig {\n\treturn MetricsConfig{\n\t\t{{- range $name, $metric := .Metrics }}\n\t\t{{- $metricReag := and $reag (hasAggregatableAttributes $metric.Attributes) }}\n\t\t{{ $name.Render }}: {{ if $reag }}{{ $name.Render }}{{ end }}MetricConfig{\n\t\t\tEnabled: {{ $metric.Enabled }},\n\t\t\t{{- if $metricReag }}\n\t\t\tAggregationStrategy: AggregationStrategy{{ if eq $metric.Data.Type \"Sum\" }}Sum{{ else }}Avg{{ end }},\n\t\t\tEnabledAttributes:   []{{ $name.Render }}MetricAttributeKey{ {{- range $element := $metric.Attributes -}}{{- if (attributeInfo $element).IsNotOptIn }}{{ $name.Render }}MetricAttributeKey{{ $element.Render }}, {{ end }}{{- end -}} },\n\t\t\t{{- end }}\n\t\t},\n\t\t{{- end }}\n\t}\n}\n{{- end }}\n\n{{ if .Events }}\n// EventConfig provides common config for a particular event.\ntype EventConfig struct {\n\tEnabled bool `mapstructure:\"enabled\"`\n\n\tenabledSetByUser bool\n}\n\nfunc (ec *EventConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\terr := parser.Unmarshal(ec)\n\tif err != nil {\n\t\treturn err\n\t}\n\tec.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\n// EventsConfig provides config for {{ .Type }} events.\ntype EventsConfig struct {\n\t{{- range $name, $event := .Events }}\n\t{{ $name.Render }} EventConfig `mapstructure:\"{{ $name }}\"`\n\t{{- end }}\n}\n\nfunc DefaultEventsConfig() EventsConfig {\n\treturn EventsConfig{\n\t\t{{- range $name, $event := .Events }}\n\t\t{{ $name.Render }}: EventConfig{\n\t\t\tEnabled: {{ $event.Enabled }},\n\t\t},\n\t\t{{- end }}\n\t}\n}\n{{- end }}\n\n{{ if .ResourceAttributes -}}\n// ResourceAttributeConfig provides common config for a particular resource attribute.\ntype ResourceAttributeConfig struct {\n\tEnabled bool `mapstructure:\"enabled\"`\n\t{{- if .Metrics }}\n\t// Experimental: MetricsInclude defines a list of filters for attribute values.\n\t// If the list is not empty, only metrics with matching resource attribute values will be emitted.\n\tMetricsInclude []filter.Config `mapstructure:\"metrics_include\"`\n\t// Experimental: MetricsExclude defines a list of filters for attribute values.\n\t// If the list is not empty, metrics with matching resource attribute values will not be emitted.\n\t// MetricsInclude has higher priority than MetricsExclude.\n\tMetricsExclude []filter.Config `mapstructure:\"metrics_exclude\"`\n\t{{- end }}\n\t{{- if .Events }}\n\t// Experimental: EventsInclude defines a list of filters for attribute values.\n\t// If the list is not empty, only events with matching resource attribute values will be emitted.\n\tEventsInclude []filter.Config `mapstructure:\"events_include\"`\n\t// Experimental: EventsExclude defines a list of filters for attribute values.\n\t// If the list is not empty, events with matching resource attribute values will not be emitted.\n\t// EventsInclude has higher priority than EventsExclude.\n\tEventsExclude []filter.Config `mapstructure:\"events_exclude\"`\n\t{{- end }}\n\n\tenabledSetByUser bool\n}\n\nfunc (rac *ResourceAttributeConfig) Unmarshal(parser *confmap.Conf) error {\n\tif parser == nil {\n\t\treturn nil\n\t}\n\terr := parser.Unmarshal(rac)\n\tif err != nil {\n\t\treturn err\n\t}\n\trac.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n}\n\n// ResourceAttributesConfig provides config for {{ .Type }} resource attributes.\ntype ResourceAttributesConfig struct {\n\t{{- range $name, $attr := .ResourceAttributes }}\n\t{{ $name.Render }} ResourceAttributeConfig `mapstructure:\"{{ $name }}\"`\n\t{{- end }}\n}\n\nfunc DefaultResourceAttributesConfig() ResourceAttributesConfig {\n\treturn ResourceAttributesConfig{\n\t\t{{- range $name, $attr := .ResourceAttributes }}\n\t\t{{ $name.Render }}: ResourceAttributeConfig {\n\t\t\tEnabled: {{ $attr.Enabled }},\n\t\t},\n\t\t{{- end }}\n\t}\n}\n{{- end }}\n\n{{ if .Metrics -}}\n// MetricsBuilderConfig is a configuration for {{ .Type }} metrics builder.\ntype MetricsBuilderConfig struct {\n\tMetrics MetricsConfig `mapstructure:\"metrics\"`\n\t{{- if .ResourceAttributes }}\n\tResourceAttributes ResourceAttributesConfig `mapstructure:\"resource_attributes\"`\n\t{{- end }}\n}\n\nfunc DefaultMetricsBuilderConfig() MetricsBuilderConfig {\n\treturn MetricsBuilderConfig {\n\t\tMetrics: DefaultMetricsConfig(),\n\t\t{{- if .ResourceAttributes }}\n\t\tResourceAttributes: DefaultResourceAttributesConfig(),\n\t\t{{- end }}\n\t}\n}\n{{- end }}\n\n{{ if .Events -}}\n// LogsBuilderConfig is a configuration for {{ .Type }} logs builder.\ntype LogsBuilderConfig struct {\n\tEvents EventsConfig `mapstructure:\"events\"`\n\t{{- if .ResourceAttributes }}\n\tResourceAttributes ResourceAttributesConfig `mapstructure:\"resource_attributes\"`\n\t{{- end }}\n}\n\nfunc DefaultLogsBuilderConfig() LogsBuilderConfig {\n\treturn LogsBuilderConfig {\n\t\tEvents: DefaultEventsConfig(),\n\t\t{{- if .ResourceAttributes }}\n\t\tResourceAttributes: DefaultResourceAttributesConfig(),\n\t\t{{- end }}\n\t}\n}\n{{- end }}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/config.schema.yaml.tmpl",
    "content": "# Code generated by mdatagen. DO NOT EDIT.\n{{- $reag := .ReaggregationEnabled }}\n$defs:\n{{- if .Metrics }}\n  metrics_config:\n    description: MetricsConfig provides config for {{ .Type }} metrics.\n    type: object\n    properties:\n      {{- range $name, $metric := .Metrics }}\n      {{- $metricReag := and $reag (hasAggregatableAttributes $metric.Attributes) }}\n      {{ $name }}:\n        description: \"{{ $name.Render }}MetricConfig provides config for the {{ $name }} metric.\"\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: {{ $metric.Enabled }}\n          {{- if $metricReag }}\n          aggregation_strategy:\n            type: string\n            enum:\n              - \"sum\"\n              - \"avg\"\n              - \"min\"\n              - \"max\"\n            {{- if eq $metric.Data.Type \"Sum\" }}\n            default: \"sum\"\n            {{- else }}\n            default: \"avg\"\n            {{- end }}\n          attributes:\n            type: array\n            items:\n              type: string\n              enum:\n              {{- range $metric.Attributes }}\n                - \"{{ (attributeInfo .).Name }}\"\n              {{- end }}\n            default:\n            {{- range $metric.Attributes }}\n            {{- if (attributeInfo .).IsNotOptIn }}\n              - \"{{ (attributeInfo .).Name }}\"\n            {{- end }}\n            {{- end }}\n          {{- end }}\n      {{- end }}\n{{- end }}\n{{- if .Events }}\n  events_config:\n    description: EventsConfig provides config for {{ .Type }} events.\n    type: object\n    properties:\n      {{- range $name, $event := .Events }}\n      {{ $name }}:\n        description: EventConfig provides common config for a  {{ $name }} event.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: {{ $event.Enabled }}\n      {{- end }}\n{{- end }}\n{{- if .ResourceAttributes }}\n  resource_attributes_config:\n    description: ResourceAttributesConfig provides config for {{ .Type }} resource attributes.\n    type: object\n    properties:\n    {{- range $name, $attr := .ResourceAttributes }}\n      {{ $name  }}:\n        description: ResourceAttributeConfig provides common config for a {{ $name }} resource attribute.\n        type: object\n        properties:\n          enabled:\n            type: boolean\n            default: {{ $attr.Enabled }}\n        {{- if $.Metrics }}\n          metrics_include:\n            description: \"Experimental: MetricsInclude defines a list of filters for attribute values. If the list is not empty, only metrics with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: {{ schemaRef \"go.opentelemetry.io/collector/filter.config\" }}\n          metrics_exclude:\n            description: \"Experimental: MetricsExclude defines a list of filters for attribute values. If the list is not empty, metrics with matching resource attribute values will not be emitted. MetricsInclude has higher priority than MetricsExclude.\"\n            type: array\n            items:\n              $ref: {{ schemaRef \"go.opentelemetry.io/collector/filter.config\" }}\n        {{- end }}\n        {{- if $.Events }}\n          events_include:\n            description: \"Experimental: EventsInclude defines a list of filters for attribute values. If the list is not empty, only events with matching resource attribute values will be emitted.\"\n            type: array\n            items:\n              $ref: {{ schemaRef \"go.opentelemetry.io/collector/filter.config\" }}\n          events_exclude:\n            description: \"Experimental: EventsExclude defines a list of filters for attribute values. If the list is not empty, events with matching resource attribute values will not be emitted. EventsInclude has higher priority than EventsExclude.\"\n            type: array\n            items:\n              $ref: {{ schemaRef \"go.opentelemetry.io/collector/filter.config\" }}\n        {{- end }}\n    {{- end }}\n{{- end }}\n{{- if .Metrics }}\n  metrics_builder_config:\n    description: MetricsBuilderConfig is a configuration for {{ .Type }} metrics builder.\n    type: object\n    properties:\n      metrics:\n        $ref: metrics_config\n    {{- if .ResourceAttributes }}\n      resource_attributes:\n        $ref: resource_attributes_config\n    {{- end }}\n{{- end }}\n{{- if .Events }}\n  logs_builder_config:\n    description: LogsBuilderConfig is a configuration for {{ .Type }} logs builder.\n    type: object\n    properties:\n      events:\n        $ref: events_config\n    {{- if .ResourceAttributes }}\n      resource_attributes:\n        $ref: resource_attributes_config\n    {{- end }}\n{{- end }}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/config_from_cfggen.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ .Package }}\n\n{{ $imports := extractImports .Metadata.Config }}\n{{- if $imports }}\nimport (\n{{- range $imports }}\n\t\"{{ . }}\"\n{{- end }}\n)\n{{- end }}\n\n{{ define \"struct\" }}\n    {{- if .AllOf }}\n    {{- range .AllOf }}\n        {{- if .Description }}\n    // {{ .Description }}\n        {{- end }}\n    \t{{ .Ref | publicType }} `mapstructure:\",squash\"`\n    {{- end }}\n    {{- end }}\n    {{- range $propName, $prop := .Properties }}\n        {{- if $prop.Description }}\n    // {{ $prop.Description }}\n        {{- end }}\n    \t{{ $propName | publicVar }} {{ mapGoType $prop $propName }} `mapstructure:\"{{ $propName }}\"`\n    {{- end }}\n{{ end }}\n\n{{- $defs := extractDefs .Metadata.Config }}\n{{ range $defName, $def := $defs }}\n    {{- if $def.Description }}\n// {{ $defName | publicVar }} {{ $def.Description }}\n    {{- end }}\ntype {{ $defName | publicVar }} struct {\n{{ template \"struct\" $def }}\n}\n{{ end }}\n\n{{- if .Metadata.Config.Description }}\n// {{ .Metadata.Config.Description }}\n{{- else }}\n// Config defines the configuration for {{ .Metadata.DisplayName }} component.\n{{- end }}\ntype Config struct {\n{{ template \"struct\" .Metadata.Config }}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/config_test.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ .Package }}\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/google/go-cmp/cmp\"\n\t\"github.com/google/go-cmp/cmp/cmpopts\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n)\n\n{{ $reag := .ReaggregationEnabled }}\n\n{{ if .Metrics }}\nfunc TestMetricsBuilderConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant MetricsBuilderConfig\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\twant: DefaultMetricsBuilderConfig(),\n\t\t},\n\t\t{\n\t\t\tname: \"all_set\",\n\t\t\twant: MetricsBuilderConfig{\n\t\t\t\tMetrics: MetricsConfig{\n\t\t\t\t\t{{- range $name, $metric := .Metrics }}\n\t\t\t\t\t{{- $metricReag := and $reag (hasAggregatableAttributes $metric.Attributes) }}\n\t\t\t\t\t{{ $name.Render }}: {{ if $reag }}{{ $name.Render }}{{ end }}MetricConfig{\n\t\t\t\t\t\tEnabled: true,\n\t\t\t\t\t\t{{- if $metricReag }}\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategy{{ if eq $metric.Data.Type \"Sum\" }}Sum{{ else }}Avg{{ end }},\n\t\t\t\t\t\tEnabledAttributes:   []{{ $name.Render }}MetricAttributeKey{ {{- range $index, $element := $metric.Attributes -}}{{ if $index }}, {{ end }}{{ $name.Render }}MetricAttributeKey{{ $element.Render }}{{ end -}} },\n\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t},\n\t\t\t\t\t{{- end }}\n\t\t\t\t},\n\t\t\t\t{{- if .ResourceAttributes }}\n\t\t\t\tResourceAttributes: ResourceAttributesConfig{\n\t\t\t\t\t{{- range $name, $_ := .ResourceAttributes }}\n\t\t\t\t\t{{ $name.Render }}: ResourceAttributeConfig{Enabled: true},\n\t\t\t\t\t{{- end }}\n\t\t\t\t},\n\t\t\t\t{{- end }}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"none_set\",\n\t\t\twant: MetricsBuilderConfig{\n\t\t\t\tMetrics: MetricsConfig{\n\t\t\t\t\t{{- range $name, $metric := .Metrics }}\n\t\t\t\t\t{{- $metricReag := and $reag (hasAggregatableAttributes $metric.Attributes) }}\n\t\t\t\t\t{{ $name.Render }}: {{ if $reag }}{{ $name.Render }}{{ end }}MetricConfig{\n\t\t\t\t\t\tEnabled: false,\n\t\t\t\t\t\t{{- if $metricReag }}\n\t\t\t\t\t\tAggregationStrategy: AggregationStrategy{{ if eq $metric.Data.Type \"Sum\" }}Sum{{ else }}Avg{{ end }},\n\t\t\t\t\t\tEnabledAttributes:   []{{ $name.Render }}MetricAttributeKey{ {{- range $index, $element := $metric.Attributes -}}{{ if $index }}, {{ end }}{{ $name.Render }}MetricAttributeKey{{ $element.Render }}{{ end -}} },\n\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t},\n\t\t\t\t\t{{- end }}\n\t\t\t\t},\n\t\t\t\t{{- if .ResourceAttributes }}\n\t\t\t\tResourceAttributes: ResourceAttributesConfig{\n\t\t\t\t\t{{- range $name, $_ := .ResourceAttributes }}\n\t\t\t\t\t{{ $name.Render }}: ResourceAttributeConfig{Enabled: false},\n\t\t\t\t\t{{- end }}\n\t\t\t\t},\n\t\t\t\t{{- end }}\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := loadMetricsBuilderConfig(t, tt.name)\n\t\t\tdiff := cmp.Diff(tt.want, cfg, cmpopts.IgnoreUnexported(\n\t\t\t\t{{- if $reag }}\n\t\t\t\t{{- range $name, $metric := .Metrics }}{{ $name.Render }}MetricConfig{}, {{ end }}\n\t\t\t\t{{- else }}MetricConfig{},{{ end }}\n\t\t\t\t{{- if .ResourceAttributes }}ResourceAttributeConfig{},{{ end }}\n\t\t\t))\n\t\t\trequire.Emptyf(t, diff, \"Config mismatch (-expected +actual):\\n%s\", diff)\n\t\t})\n\t}\n}\n\nfunc loadMetricsBuilderConfig(t *testing.T, name string) MetricsBuilderConfig {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tsub, err := cm.Sub(name)\n\trequire.NoError(t, err)\n\tcfg := DefaultMetricsBuilderConfig()\n\trequire.NoError(t, sub.Unmarshal(&cfg, confmap.WithIgnoreUnused()))\n\treturn cfg\n}\n{{- end }}\n\n{{ if .Events }}\nfunc loadLogsBuilderConfig(t *testing.T, name string) LogsBuilderConfig {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tsub, err := cm.Sub(name)\n\trequire.NoError(t, err)\n\tcfg := DefaultLogsBuilderConfig()\n\trequire.NoError(t, sub.Unmarshal(&cfg, confmap.WithIgnoreUnused()))\n\treturn cfg\n}\n{{- end }}\n\n{{ if .ResourceAttributes -}}\nfunc TestResourceAttributesConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\twant ResourceAttributesConfig\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\twant: DefaultResourceAttributesConfig(),\n\t\t},\n\t\t{\n\t\t\tname: \"all_set\",\n\t\t\twant: ResourceAttributesConfig{\n\t\t\t\t{{- range $name, $_ := .ResourceAttributes }}\n\t\t\t\t{{ $name.Render }}: ResourceAttributeConfig{Enabled: true},\n\t\t\t\t{{- end }}\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"none_set\",\n\t\t\twant: ResourceAttributesConfig{\n\t\t\t\t{{- range $name, $_ := .ResourceAttributes }}\n\t\t\t\t{{ $name.Render }}: ResourceAttributeConfig{Enabled: false},\n\t\t\t\t{{- end }}\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := loadResourceAttributesConfig(t, tt.name)\n\t\t\tdiff := cmp.Diff(tt.want, cfg, cmpopts.IgnoreUnexported(ResourceAttributeConfig{}))\n\t\t\trequire.Emptyf(t, diff, \"Config mismatch (-expected +actual):\\n%s\", diff)\n\t\t})\n\t}\n}\n\nfunc loadResourceAttributesConfig(t *testing.T, name string) ResourceAttributesConfig {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tsub, err := cm.Sub(name)\n\trequire.NoError(t, err)\n\tsub, err = sub.Sub(\"resource_attributes\")\n\trequire.NoError(t, err)\n\tcfg := DefaultResourceAttributesConfig()\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\treturn cfg\n}\n{{- end }}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/documentation.md.tmpl",
    "content": "{{- define \"metric-documentation\" -}}\n{{- $metricName := . }}\n{{- $metric := $metricName | metricInfo -}}\n\n### {{ $metricName }}\n\n{{ $metric.Description }}\n\n{{- if $metric.ExtendedDocumentation }}\n\n{{ $metric.ExtendedDocumentation }}\n\n{{- end }}\n\n| Unit | Metric Type | Value Type |{{ if $metric.Data.HasAggregated }} Aggregation Temporality |{{ end }}{{ if $metric.Data.HasMonotonic }} Monotonic |{{ end }}{{ if $metric.Stability }} Stability |{{ end }}{{ if $metric.SemanticConvention }} Semantic Convention |{{ end }}\n| ---- | ----------- | ---------- |{{ if $metric.Data.HasAggregated }} ----------------------- |{{ end }}{{ if $metric.Data.HasMonotonic }} --------- |{{ end }}{{ if $metric.Stability }} --------- |{{ end }}{{ if $metric.SemanticConvention }} ------------------- |{{ end }}\n| {{ $metric.Unit }} | {{ $metric.Data.Type }} | {{ $metric.Data.MetricValueType }} |\n{{- if $metric.Data.HasAggregated }} {{ $metric.Data.AggregationTemporality }} |{{ end }}\n{{- if $metric.Data.HasMonotonic }} {{ $metric.Data.Monotonic }} |{{ end }}\n{{- if $metric.Stability }} {{ $metric.Stability }}{{ if $metric.Deprecated }} since {{ $metric.Deprecated.Since }}{{ end }} |{{ end }}\n{{- if $metric.SemanticConvention }} [{{ $metricName }}]({{ $metric.SemanticConvention.SemanticConventionRef }}) |{{ end }}\n{{- if $metric.Deprecated }}{{ if $metric.Deprecated.Note }}\n\n**Deprecation note**: {{ $metric.Deprecated.Note }}\n{{- end }}{{ end }}\n\n{{- if $metric.Attributes }}\n\n#### Attributes\n\n| Name | Description | Values | Requirement Level |\n| ---- | ----------- | ------ | -------- |\n{{- range $metric.Attributes }}\n{{- $attribute := . | attributeInfo }}\n| {{ $attribute.Name }} | {{ $attribute.Description }} |\n{{- if $attribute.Enum }} {{ $attribute.Type }}: ``{{ stringsJoin $attribute.Enum \"``, ``\" }}``{{ else }} Any {{ $attribute.Type }}{{ end }} | {{ $attribute.RequirementLevel }} |\n{{- end }}\n\n{{- end }}\n\n{{- end -}}\n\n{{- define \"event-documentation\" -}}\n{{- $eventName := . }}\n{{- $event := $eventName | eventInfo -}}\n\n### {{ $eventName }}\n\n{{ $event.Description }}\n\n{{- if $event.ExtendedDocumentation }}\n\n{{ $event.ExtendedDocumentation }}\n\n{{- end }}\n\n{{- if $event.Attributes }}\n\n#### Attributes\n\n| Name | Description | Values |\n| ---- | ----------- | ------ |\n{{- range $event.Attributes }}\n{{- $attribute := . | attributeInfo }}\n| {{ $attribute.Name }} | {{ $attribute.Description }} |\n{{- if $attribute.Enum }} {{ $attribute.Type }}: ``{{ stringsJoin $attribute.Enum \"``, ``\" }}``{{ else }} Any {{ $attribute.Type }}{{ end }} |\n{{- end }}\n\n{{- end }}\n\n{{- end -}}\n\n{{- define \"telemetry-documentation\" -}}\n{{- $metricName := . }}\n{{- $metric := $metricName | telemetryInfo -}}\n\n### {{ if $metric.Prefix -}}{{ $metric.Prefix }}{{- else -}}otelcol_{{- end -}}{{ $metricName }}\n\n{{ $metric.Description }}\n{{- if $metric.Deprecated }}\n\n> **Deprecated since {{ $metric.Deprecated.Since}}**\n{{- if $metric.Deprecated.Note }}\n> {{ $metric.Deprecated.Note }}\n{{- end }}\n{{- end }}\n\n{{- if $metric.ExtendedDocumentation }}\n\n{{ $metric.ExtendedDocumentation }}\n\n{{- end }}\n\n| Unit | Metric Type | Value Type |{{ if $metric.Data.HasMonotonic }} Monotonic |{{ end }}{{ if $metric.Stability }} Stability |{{ end }}{{ if $metric.SemanticConvention }} Semantic Convention |{{ end }}\n| ---- | ----------- | ---------- |{{ if $metric.Data.HasMonotonic }} --------- |{{ end }}{{ if $metric.Stability }} --------- |{{ end }}{{ if $metric.SemanticConvention }} ------------------- |{{ end }}\n| {{ $metric.Unit }} | {{ $metric.Data.Type }} | {{ $metric.Data.MetricValueType }} |\n{{- if $metric.Data.HasMonotonic }} {{ $metric.Data.Monotonic }} |{{ end }}\n{{- if $metric.Stability }} {{ $metric.Stability }}{{ if $metric.Deprecated }} since {{ $metric.Deprecated.Since }}{{ end }} |{{ end }}\n{{- if $metric.SemanticConvention }} [{{ $metricName }}]({{ $metric.SemanticConvention.SemanticConventionRef }}) |{{ end }}\n{{- if $metric.Deprecated }}{{ if $metric.Deprecated.Note }}\n\n**Deprecation note**: {{ $metric.Deprecated.Note }}\n{{- end }}{{ end }}\n\n{{- if $metric.Attributes }}\n\n#### Attributes\n\n| Name | Description | Values |\n| ---- | ----------- | ------ |\n{{- range $metric.Attributes }}\n{{- $attribute := . | attributeInfo }}\n| {{ $attribute.Name }} | {{ $attribute.Description }} |\n{{- if $attribute.Enum }} {{ $attribute.Type }}: ``{{ stringsJoin $attribute.Enum \"``, ``\" }}``{{ else }} Any {{ $attribute.Type }}{{ end }} |\n{{- end }}\n\n{{- end }}\n\n{{- end -}}\n\n[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# {{ .Type }}\n\n{{- if .Parent }}\n\n**Parent Component:** {{ .Parent }}\n{{- end }}\n\n{{- if .Metrics }}\n\n## Default Metrics\n\nThe following metrics are emitted by default. Each of them can be disabled by applying the following configuration:\n\n```yaml\nmetrics:\n  <metric_name>:\n    enabled: false\n```\n\n{{- end }}\n\n{{- range $metricName, $metric := .Metrics }}\n{{- if $metric.Enabled }}\n\n{{ template \"metric-documentation\" $metricName }}\n\n{{- end }}\n{{- end }}\n\n{{- $optionalMetricSeen := false }}\n{{- range $metricName, $metric := .Metrics }}\n{{- if not $metric.Enabled }}\n{{- if not $optionalMetricSeen }}\n\n## Optional Metrics\n\nThe following metrics are not emitted by default. Each of them can be enabled by applying the following configuration:\n\n```yaml\nmetrics:\n  <metric_name>:\n    enabled: true\n```\n\n{{- end }}\n{{- $optionalMetricSeen = true }}\n\n{{ template \"metric-documentation\" $metricName }}\n\n{{- end }}\n{{- end }}\n\n{{- if .Events }}\n\n## Default Events\n\nThe following events are emitted by default. Each of them can be disabled by applying the following configuration:\n\n```yaml\nevents:\n  <event_name>:\n    enabled: false\n```\n\n{{- range $eventName, $event := .Events }}\n{{- if $event.Enabled }}\n\n{{ template \"event-documentation\" $eventName }}\n\n{{- end }}\n{{- end }}\n{{- end }}\n\n{{- $optionalEventSeen := false }}\n{{- range $eventName, $event := .Events }}\n{{- if not $event.Enabled }}\n{{- if not $optionalEventSeen }}\n\n## Optional Events\n\nThe following events are not emitted by default. Each of them can be enabled by applying the following configuration:\n\n```yaml\nevents:\n  <event_name>:\n    enabled: true\n```\n\n{{- end }}\n{{- $optionalEventSeen = true }}\n\n{{ template \"event-documentation\" $eventName }}\n\n{{- end }}\n{{- end }}\n\n{{- if .ResourceAttributes }}\n\n## Resource Attributes\n\n| Name | Description | Values | Enabled |\n| ---- | ----------- | ------ | ------- |\n{{- range $attributeName, $attribute := .ResourceAttributes }}\n| {{ $attributeName }} | {{ $attribute.Description }} |\n{{- if $attribute.Enum }} {{ $attribute.Type }}: ``{{ stringsJoin $attribute.Enum \"``, ``\" }}``{{ else }} Any {{ $attribute.Type }}{{ end }} | {{ $attribute.Enabled }} |\n{{- end }}\n\n{{- end }}\n\n{{- if .Entities }}\n\n## Entities\n\nThe following entities are defined for this component:\n\n{{- range $entity := .Entities }}\n\n### {{ $entity.Type }}\n\n{{ $entity.Brief }}\n\n{{- if $entity.Stability }}\n\n**Stability:** {{ $entity.Stability }}\n{{- end }}\n\n{{- if $entity.Identity }}\n\n**Identifying Attributes:**\n{{- range $entity.Identity }}\n- `{{ .Ref }}`\n{{- end }}\n{{- end }}\n\n{{- if $entity.Description }}\n\n**Descriptive Attributes:**\n{{- range $entity.Description }}\n- `{{ .Ref }}`\n{{- end }}\n{{- end }}\n\n{{- end }}\n\n{{- end }}\n\n{{- if .Telemetry.Metrics }}\n\n## Internal Telemetry\n\nThe following telemetry is emitted by this component.\n\n{{- range $metricName, $metric := .Telemetry.Metrics }}\n{{- if $metric.Enabled }}\n\n{{ template \"telemetry-documentation\" $metricName }}\n\n{{- end }}\n{{- end }}\n\n{{- end }}\n\n{{- if .FeatureGates }}\n\n## Feature Gates\n\nThis component has the following feature gates:\n\n| Feature Gate | Stage | Description | From Version | To Version | Reference |\n| ------------ | ----- | ----------- | ------------ | ---------- | --------- |\n{{- range .FeatureGates }}\n| `{{ .ID }}` | {{ .Stage }} | {{ .Description }} | {{ if .FromVersion }}{{ .FromVersion }}{{ else }}N/A{{ end }} | {{ if .ToVersion }}{{ .ToVersion }}{{ else }}N/A{{ end }} | {{ if .ReferenceURL }}[Link]({{ .ReferenceURL }}){{ else }}N/A{{ end }} |\n{{- end }}\n\nFor more information about feature gates, see the [Feature Gates](https://github.com/open-telemetry/opentelemetry-collector/blob/main/featuregate/README.md) documentation.\n\n{{- end }}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/entity_metrics.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ .Package }}\n\nimport (\n\t{{- if .Metrics | parseImportsRequired }}\n\t\"fmt\"\n\t\"strconv\"\n\t{{- end }}\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/entity\"\n)\n\n{{ $resourceAttributes := .ResourceAttributes }}\n{{ $metrics := .Metrics }}\n\n{{ range $ent := .Entities }}\n{{ $entityType := $ent.Type }}\n{{ $entityStructType := printf \"%sEntity\" (publicVar $entityType) }}\n\n// {{ $entityStructType }} represents a {{ $entityType }} entity.\n// Create one with New{{ $entityStructType }} and pass it to EmitForEntity.\ntype {{ $entityStructType }} struct {\n\t{{- range $idAttr := $ent.Identity }}\n\t{{- $attr := index $resourceAttributes $idAttr.Ref }}\n\t{{ $idAttr.Ref.RenderUnexported }} {{ $attr.Type.Primitive }}\n\t{{- end }}\n\t{{- range $descAttr := $ent.Description }}\n\t{{- $attr := index $resourceAttributes $descAttr.Ref }}\n\t{{ $descAttr.Ref.RenderUnexported }} {{ $attr.Type.Primitive }}\n\t{{- end }}\n\t{{- range $extraAttr := $ent.ExtraAttributes }}\n\t{{- $attr := index $resourceAttributes $extraAttr.Ref }}\n\t{{ $extraAttr.Ref.RenderUnexported }} {{ $attr.Type.Primitive }}\n\t{{- end }}\n\t{{- range $rel := $ent.Relationships }}\n\t{{ toLowerCamelCase $rel.Type }}{{ publicVar $rel.Target }} *{{ publicVar $rel.Target }}Entity\n\t{{- end }}\n}\n\n// New{{ $entityStructType }} creates a new {{ $entityStructType }}.\n// Identity attributes are required and must be provided at construction time.\nfunc New{{ $entityStructType }}(\n\t{{- range $i, $idAttr := $ent.Identity -}}\n\t{{- if $i }}, {{ end -}}\n\t{{- $attr := index $resourceAttributes $idAttr.Ref -}}\n\t{{ $idAttr.Ref.RenderUnexported }} {{ $attr.Type.Primitive }}\n\t{{- end -}}\n) *{{ $entityStructType }} {\n\treturn &{{ $entityStructType }}{\n\t\t{{- range $idAttr := $ent.Identity }}\n\t\t{{ $idAttr.Ref.RenderUnexported }}: {{ $idAttr.Ref.RenderUnexported }},\n\t\t{{- end }}\n\t}\n}\n\n{{- if $ent.Description }}\n\n// Description attribute setters for {{ $entityType }}.\n{{- range $descAttr := $ent.Description }}\n{{- $attr := index $resourceAttributes $descAttr.Ref }}\n\n// Set{{ publicVar $descAttr.Ref.Render }} sets the {{ $descAttr.Ref }} description attribute.\nfunc (e *{{ $entityStructType }}) Set{{ publicVar $descAttr.Ref.Render }}(val {{ $attr.Type.Primitive }}) {\n\te.{{ $descAttr.Ref.RenderUnexported }} = val\n}\n{{- end }}\n{{- end }}\n\n{{- if $ent.ExtraAttributes }}\n\n// Extra attribute setters for {{ $entityType }}.\n// These attributes are contextually relevant but are not part of the entity's identity or description.\n{{- range $extraAttr := $ent.ExtraAttributes }}\n{{- $attr := index $resourceAttributes $extraAttr.Ref }}\n\n// Set{{ publicVar $extraAttr.Ref.Render }} sets the {{ $extraAttr.Ref }} extra attribute on the resource.\nfunc (e *{{ $entityStructType }}) Set{{ publicVar $extraAttr.Ref.Render }}(val {{ $attr.Type.Primitive }}) {\n\te.{{ $extraAttr.Ref.RenderUnexported }} = val\n}\n{{- end }}\n{{- end }}\n\n{{- if $ent.Relationships }}\n\n// Relationship setters for {{ $entityType }}.\n{{- range $rel := $ent.Relationships }}\n{{ $relMethod := printf \"Set%s%s\" (publicVar $rel.Type) (publicVar $rel.Target) }}\n\n// {{ $relMethod }} sets the {{ $rel.Type }} relationship to a {{ $rel.Target }} entity.\n// The related entity will be emitted alongside this entity's metrics.\nfunc (e *{{ $entityStructType }}) {{ $relMethod }}(target *{{ publicVar $rel.Target }}Entity) {\n\te.{{ toLowerCamelCase $rel.Type }}{{ publicVar $rel.Target }} = target\n}\n{{- end }}\n{{- end }}\n\n// copyToResource populates res with the entity's attributes according to cfg.\n// If all identity attributes are enabled, an entity ref is produced; otherwise\n// the enabled attributes are written directly as plain resource attributes.\nfunc (e *{{ $entityStructType }}) copyToResource(cfg ResourceAttributesConfig, res pcommon.Resource) {\n\tif {{ range $i, $idAttr := $ent.Identity }}{{ if $i }} && {{ end }}cfg.{{ publicVar $idAttr.Ref.Render }}.Enabled{{ end }} {\n\t\tent := entity.ResourceEntities(res).PutEmpty(\"{{ $entityType }}\")\n\t\t{{- range $idAttr := $ent.Identity }}\n\t\t{{- $attr := index $resourceAttributes $idAttr.Ref }}\n\t\t{{- if eq $attr.Type.ValueType.String \"Str\" }}\n\t\tent.IdentifyingAttributes().PutStr(\"{{ $idAttr.Ref }}\", e.{{ $idAttr.Ref.RenderUnexported }})\n\t\t{{- else if or (eq $attr.Type.ValueType.String \"Map\") (eq $attr.Type.ValueType.String \"Slice\") (eq $attr.Type.ValueType.String \"Bytes\") }}\n\t\tent.IdentifyingAttributes().PutEmpty(\"{{ $idAttr.Ref }}\").SetEmpty{{ $attr.Type.ValueType }}().FromRaw(e.{{ $idAttr.Ref.RenderUnexported }})\n\t\t{{- else }}\n\t\tent.IdentifyingAttributes().PutEmpty(\"{{ $idAttr.Ref }}\").Set{{ $attr.Type.ValueType }}(e.{{ $idAttr.Ref.RenderUnexported }})\n\t\t{{- end }}\n\t\t{{- end }}\n\n\t\t{{- range $descAttr := $ent.Description }}\n\t\t{{- $attr := index $resourceAttributes $descAttr.Ref }}\n\t\tif cfg.{{ publicVar $descAttr.Ref.Render }}.Enabled {\n\t\t\t{{- if eq $attr.Type.ValueType.String \"Str\" }}\n\t\t\tent.DescriptiveAttributes().PutStr(\"{{ $descAttr.Ref }}\", e.{{ $descAttr.Ref.RenderUnexported }})\n\t\t\t{{- else if or (eq $attr.Type.ValueType.String \"Map\") (eq $attr.Type.ValueType.String \"Slice\") (eq $attr.Type.ValueType.String \"Bytes\") }}\n\t\t\tent.DescriptiveAttributes().PutEmpty(\"{{ $descAttr.Ref }}\").SetEmpty{{ $attr.Type.ValueType }}().FromRaw(e.{{ $descAttr.Ref.RenderUnexported }})\n\t\t\t{{- else }}\n\t\t\tent.DescriptiveAttributes().PutEmpty(\"{{ $descAttr.Ref }}\").Set{{ $attr.Type.ValueType }}(e.{{ $descAttr.Ref.RenderUnexported }})\n\t\t\t{{- end }}\n\t\t}\n\t\t{{- end }}\n\n\t\t{{- range $extraAttr := $ent.ExtraAttributes }}\n\t\t{{- $attr := index $resourceAttributes $extraAttr.Ref }}\n\t\tif cfg.{{ publicVar $extraAttr.Ref.Render }}.Enabled {\n\t\t\t{{- if eq $attr.Type.ValueType.String \"Str\" }}\n\t\t\tres.Attributes().PutStr(\"{{ $extraAttr.Ref }}\", e.{{ $extraAttr.Ref.RenderUnexported }})\n\t\t\t{{- else if or (eq $attr.Type.ValueType.String \"Map\") (eq $attr.Type.ValueType.String \"Slice\") (eq $attr.Type.ValueType.String \"Bytes\") }}\n\t\t\tres.Attributes().PutEmpty(\"{{ $extraAttr.Ref }}\").SetEmpty{{ $attr.Type.ValueType }}().FromRaw(e.{{ $extraAttr.Ref.RenderUnexported }})\n\t\t\t{{- else }}\n\t\t\tres.Attributes().PutEmpty(\"{{ $extraAttr.Ref }}\").Set{{ $attr.Type.ValueType }}(e.{{ $extraAttr.Ref.RenderUnexported }})\n\t\t\t{{- end }}\n\t\t}\n\t\t{{- end }}\n\t} else {\n\t\t{{- range $idAttr := $ent.Identity }}\n\t\t{{- $attr := index $resourceAttributes $idAttr.Ref }}\n\t\tif cfg.{{ publicVar $idAttr.Ref.Render }}.Enabled {\n\t\t\t{{- if or (eq $attr.Type.String \"Bytes\") (eq $attr.Type.String \"Slice\") (eq $attr.Type.String \"Map\") }}\n\t\t\tres.Attributes().PutEmpty{{ $attr.Type }}(\"{{ $idAttr.Ref }}\").FromRaw(e.{{ $idAttr.Ref.RenderUnexported }})\n\t\t\t{{- else }}\n\t\t\tres.Attributes().Put{{ $attr.Type }}(\"{{ $idAttr.Ref }}\", e.{{ $idAttr.Ref.RenderUnexported }})\n\t\t\t{{- end }}\n\t\t}\n\t\t{{- end }}\n\t\t{{- range $descAttr := $ent.Description }}\n\t\t{{- $attr := index $resourceAttributes $descAttr.Ref }}\n\t\tif cfg.{{ publicVar $descAttr.Ref.Render }}.Enabled {\n\t\t\t{{- if or (eq $attr.Type.String \"Bytes\") (eq $attr.Type.String \"Slice\") (eq $attr.Type.String \"Map\") }}\n\t\t\tres.Attributes().PutEmpty{{ $attr.Type }}(\"{{ $descAttr.Ref }}\").FromRaw(e.{{ $descAttr.Ref.RenderUnexported }})\n\t\t\t{{- else }}\n\t\t\tres.Attributes().Put{{ $attr.Type }}(\"{{ $descAttr.Ref }}\", e.{{ $descAttr.Ref.RenderUnexported }})\n\t\t\t{{- end }}\n\t\t}\n\t\t{{- end }}\n\t\t{{- range $extraAttr := $ent.ExtraAttributes }}\n\t\t{{- $attr := index $resourceAttributes $extraAttr.Ref }}\n\t\tif cfg.{{ publicVar $extraAttr.Ref.Render }}.Enabled {\n\t\t\t{{- if or (eq $attr.Type.String \"Bytes\") (eq $attr.Type.String \"Slice\") (eq $attr.Type.String \"Map\") }}\n\t\t\tres.Attributes().PutEmpty{{ $attr.Type }}(\"{{ $extraAttr.Ref }}\").FromRaw(e.{{ $extraAttr.Ref.RenderUnexported }})\n\t\t\t{{- else }}\n\t\t\tres.Attributes().Put{{ $attr.Type }}(\"{{ $extraAttr.Ref }}\", e.{{ $extraAttr.Ref.RenderUnexported }})\n\t\t\t{{- end }}\n\t\t}\n\t\t{{- end }}\n\t}\n}\n\n{{ end }}\n\n{{ range $ent := .Entities }}\n{{ $entityType := $ent.Type }}\n{{ $entityStructType := printf \"%sEntity\" (publicVar $entityType) }}\n{{ $builderType := printf \"%sMetricsBuilder\" (publicVar $entityType) }}\n\n// {{ $builderType }} records metrics for the {{ $entityType }} entity.\n// Obtain one via MetricsBuilder.For{{ publicVar $entityType }}().\ntype {{ $builderType }} struct {\n\tmb     *MetricsBuilder\n\tentity *{{ $entityStructType }}\n}\n\n{{- range $name, $metric := $metrics }}\n{{- if eq $metric.Entity $entityType }}\n\n{{/* TODO: Consolidate with the root-level Record*DataPoint methods in metrics.go.tmpl. */}}\n// Record{{ $name.Render }}DataPoint records a data point for the {{ $name }} metric.\nfunc (eb *{{ $builderType }}) Record{{ $name.Render }}DataPoint(ts pcommon.Timestamp\n\t{{- if $metric.Data.HasMetricInputType }}, inputVal {{ $metric.Data.MetricInputType.String }}\n\t{{- else }}, val {{ $metric.Data.MetricValueType.BasicType }}\n\t{{- end }}\n\t{{- range $metric.Attributes -}}\n\t{{- if not (attributeInfo .).IsConditional -}}\n\t, {{ .RenderUnexported }}AttributeValue {{ if (attributeInfo .).Enum }}Attribute{{ .Render }}{{ else }}{{ (attributeInfo .).Type.Primitive }}{{ end }}\n\t{{- end -}}\n\t{{- end -}}\n\t{{- if $metric.HasConditionalAttributes $.Attributes -}}\n\t, options ...MetricAttributeOption\n\t{{- end -}}\n\t)\n\t{{- if $metric.Data.HasMetricInputType }} error{{ end }} {\n\t{{- if $metric.Data.HasMetricInputType }}\n\t{{- if eq $metric.Data.MetricValueType.BasicType \"float64\" }}\n\tval, err := strconv.ParseFloat(inputVal, 64)\n\t{{- else if eq $metric.Data.MetricValueType.BasicType \"int64\" }}\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\t{{- end }}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse {{ $metric.Data.MetricValueType.BasicType }} for {{ $name.Render }}, value was %s: %w\", inputVal, err)\n\t}\n\t{{- end }}\n\teb.mb.metric{{ $name.Render }}.recordDataPoint(eb.mb.startTime, ts, val\n\t\t{{- range $metric.Attributes -}}\n\t\t{{- if not (attributeInfo .).IsConditional -}}\n\t\t, {{ .RenderUnexported }}AttributeValue{{ if (attributeInfo .).Enum }}.String(){{ end }}\n\t\t{{- end -}}\n\t\t{{- end -}}\n\t\t{{- if $metric.HasConditionalAttributes $.Attributes -}}\n\t\t, options...\n\t\t{{- end -}}\n\t\t)\n\t{{- if $metric.Data.HasMetricInputType }}\n\treturn nil\n\t{{- end }}\n}\n{{- end }}\n{{- end }}\n\n// Emit emits all pending metrics for the entity. Resource attributes are filtered by config:\n// disabled identity attributes suppress the entity (other enabled attributes are added directly\n// to the resource); disabled descriptive/extra attributes are omitted entirely.\nfunc (eb *{{ $builderType }}) Emit() {\n\tres := pcommon.NewResource()\n\tcfg := eb.mb.config.ResourceAttributes\n\teb.entity.copyToResource(cfg, res)\n\t{{- range $rel := $ent.Relationships }}\n\tif eb.entity.{{ toLowerCamelCase $rel.Type }}{{ publicVar $rel.Target }} != nil {\n\t\teb.entity.{{ toLowerCamelCase $rel.Type }}{{ publicVar $rel.Target }}.copyToResource(cfg, res)\n\t}\n\t{{- end }}\n\teb.mb.EmitForResource(withResourceMoved(res))\n}\n\n{{- end }}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/entity_metrics_test.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ .Package }}\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/entity\"\n\t\"go.opentelemetry.io/collector/{{ .Status.Class }}/{{ .Status.Class }}test\"\n)\n\n{{ $resourceAttributes := .ResourceAttributes }}\n\nfunc TestEntityBuilders(t *testing.T) {\n\tstart := pcommon.Timestamp(1_000_000_000)\n\tts := pcommon.Timestamp(1_000_001_000)\n\tsettings := {{ .Status.Class }}test.NewNopSettings({{ .Status.Class }}test.NopType)\n\tmb := NewMetricsBuilder(DefaultMetricsBuilderConfig(), settings, WithStartTime(start))\n\n\t{{- range $ent := .Entities }}\n\t{{ $entityType := $ent.Type }}\n\t{{ $entityStructType := printf \"%sEntity\" (publicVar $entityType) }}\n\n\tt.Run(\"{{ $entityType }}\", func(t *testing.T) {\n\t\te := New{{ $entityStructType }}(\n\t\t\t{{- range $i, $idAttr := $ent.Identity -}}\n\t\t\t{{- $attr := index $resourceAttributes $idAttr.Ref -}}\n\t\t\t{{- if $i }}, {{ end -}}{{ $attr.TestValue }}\n\t\t\t{{- end -}}\n\t\t)\n\t\trequire.NotNil(t, e)\n\n\t\t{{- if $ent.Description }}\n\t\t{{- range $descAttr := $ent.Description }}\n\t\t{{- $attr := index $resourceAttributes $descAttr.Ref }}\n\t\te.Set{{ publicVar $descAttr.Ref.Render }}({{ $attr.TestValue }})\n\t\t{{- end }}\n\t\t{{- end }}\n\n\t\t{{- if $ent.ExtraAttributes }}\n\t\t{{- range $extraAttr := $ent.ExtraAttributes }}\n\t\t{{- $attr := index $resourceAttributes $extraAttr.Ref }}\n\t\te.Set{{ publicVar $extraAttr.Ref.Render }}({{ $attr.TestValue }})\n\t\t{{- end }}\n\t\t{{- end }}\n\n\t\t{{- if $ent.Relationships }}\n\t\t{{- range $rel := $ent.Relationships }}\n\t\t{{- range $other := $.Entities }}\n\t\t{{- if eq $other.Type $rel.Target }}\n\t\trelated{{ publicVar $rel.Target }} := New{{ publicVar $rel.Target }}Entity(\n\t\t\t{{- range $i, $idAttr := $other.Identity -}}\n\t\t\t{{- $attr := index $resourceAttributes $idAttr.Ref -}}\n\t\t\t{{- if $i }}, {{ end -}}{{ $attr.TestValue }}\n\t\t\t{{- end -}}\n\t\t)\n\t\te.Set{{ publicVar $rel.Type }}{{ publicVar $rel.Target }}(related{{ publicVar $rel.Target }})\n\t\t{{- end }}\n\t\t{{- end }}\n\t\t{{- end }}\n\t\t{{- end }}\n\n\t\teb := mb.For{{ publicVar $entityType }}(e)\n\t\t{{- range $name, $metric := $.Metrics }}\n\t\t{{- if eq $metric.Entity $entityType }}\n\t\teb.Record{{ $name.Render }}DataPoint(ts, {{ if $metric.Data.HasMetricInputType }}\"1\"{{ else }}1{{ end }}\n\t\t{{- range $metric.Attributes -}}\n\t\t{{- if not (attributeInfo .).IsConditional -}}\n\t\t\t, {{- template \"getAttributeValue\" . -}}\n\t\t{{- end -}}\n\t\t{{- end -}}\n\t\t)\n\t\t{{- end }}\n\t\t{{- end }}\n\t\teb.Emit()\n\t\tmetrics := mb.Emit()\n\n\t\t{{- $count := 0 }}\n\t\t{{- range $name, $metric := $.Metrics }}\n\t\t{{- if and (eq $metric.Entity $entityType) $metric.Enabled }}\n\t\t{{- $count = inc $count }}\n\t\t{{- end }}\n\t\t{{- end }}\n\t\t{{- if gt $count 0 }}\n\n\t\trequire.Equal(t, 1, metrics.ResourceMetrics().Len())\n\t\trm := metrics.ResourceMetrics().At(0)\n\n\t\t{{- range $idAttr := $ent.Identity }}\n\t\t{{- $attr := index $resourceAttributes $idAttr.Ref }}\n\t\tentityVal, ok := entity.ResourceEntities(rm.Resource()).Get(\"{{ $entityType }}\")\n\t\trequire.True(t, ok)\n\t\t{{ $idAttr.Ref.RenderUnexported }}AttrVal, ok := entityVal.IdentifyingAttributes().Get(\"{{ $idAttr.Ref }}\")\n\t\trequire.True(t, ok)\n\t\t{{- template \"assertResourceAttributeValue\" $attr }}\n\t\t{{- end }}\n\n\t\t{{- range $descAttr := $ent.Description }}\n\t\t{{- $attr := index $resourceAttributes $descAttr.Ref }}\n\t\t{{- if $attr.Enabled }}\n\t\t{{ $descAttr.Ref.RenderUnexported }}AttrVal, ok := entityVal.DescriptiveAttributes().Get(\"{{ $descAttr.Ref }}\")\n\t\trequire.True(t, ok)\n\t\t{{- template \"assertResourceAttributeValue\" $attr }}\n\t\t{{- else }}\n\t\t_, ok = entityVal.DescriptiveAttributes().Get(\"{{ $descAttr.Ref }}\")\n\t\tassert.False(t, ok)\n\t\t{{- end }}\n\t\t{{- end }}\n\n\t\t{{- range $extraAttr := $ent.ExtraAttributes }}\n\t\t{{- $attr := index $resourceAttributes $extraAttr.Ref }}\n\t\t_, ok = entityVal.DescriptiveAttributes().Get(\"{{ $extraAttr.Ref }}\")\n\t\tassert.False(t, ok)\n\t\t{{- if $attr.Enabled }}\n\t\t{{ $extraAttr.Ref.RenderUnexported }}AttrVal, ok := rm.Resource().Attributes().Get(\"{{ $extraAttr.Ref }}\")\n\t\trequire.True(t, ok)\n\t\t{{- template \"assertResourceAttributeValue\" $attr }}\n\t\t{{- else }}\n\t\t_, ok = rm.Resource().Attributes().Get(\"{{ $extraAttr.Ref }}\")\n\t\tassert.False(t, ok)\n\t\t{{- end }}\n\t\t{{- end }}\n\n\t\trequire.Equal(t, 1, rm.ScopeMetrics().Len())\n\t\tms := rm.ScopeMetrics().At(0).Metrics()\n\t\tassert.Equal(t, {{ $count }}, ms.Len())\n\t\t{{- else }}\n\t\t// All metrics for this entity are disabled by default.\n\t\tassert.Equal(t, 0, metrics.ResourceMetrics().Len())\n\t\t{{- end }}\n\t})\n\n\t{{- if gt $count 0 }}\n\tt.Run(\"{{ $entityType }}/disabled_identity_attr\", func(t *testing.T) {\n\t\t// When an identity attribute is disabled, the entity is not produced but\n\t\t// other enabled attributes are still added to the resource directly.\n\t\tcfg := DefaultMetricsBuilderConfig()\n\t\t{{- range $idAttr := $ent.Identity }}\n\t\tcfg.ResourceAttributes.{{ publicVar $idAttr.Ref.Render }}.Enabled = false\n\t\t{{- end }}\n\t\tmb := NewMetricsBuilder(cfg, settings, WithStartTime(start))\n\n\t\te := New{{ $entityStructType }}(\n\t\t\t{{- range $i, $idAttr := $ent.Identity -}}\n\t\t\t{{- $attr := index $resourceAttributes $idAttr.Ref -}}\n\t\t\t{{- if $i }}, {{ end -}}{{ $attr.TestValue }}\n\t\t\t{{- end -}}\n\t\t)\n\t\t{{- if $ent.Description }}\n\t\t{{- range $descAttr := $ent.Description }}\n\t\t{{- $attr := index $resourceAttributes $descAttr.Ref }}\n\t\te.Set{{ publicVar $descAttr.Ref.Render }}({{ $attr.TestValue }})\n\t\t{{- end }}\n\t\t{{- end }}\n\n\t\teb := mb.For{{ publicVar $entityType }}(e)\n\t\t{{- range $name, $metric := $.Metrics }}\n\t\t{{- if eq $metric.Entity $entityType }}\n\t\teb.Record{{ $name.Render }}DataPoint(ts, {{ if $metric.Data.HasMetricInputType }}\"1\"{{ else }}1{{ end }}\n\t\t{{- range $metric.Attributes -}}\n\t\t{{- if not (attributeInfo .).IsConditional -}}\n\t\t\t, {{- template \"getAttributeValue\" . -}}\n\t\t{{- end -}}\n\t\t{{- end -}}\n\t\t)\n\t\t{{- end }}\n\t\t{{- end }}\n\t\teb.Emit()\n\t\tmetrics := mb.Emit()\n\n\t\trequire.Equal(t, 1, metrics.ResourceMetrics().Len())\n\t\trm := metrics.ResourceMetrics().At(0)\n\t\t// Entity must not be present since its identity attribute is disabled.\n\t\t_, ok := entity.ResourceEntities(rm.Resource()).Get(\"{{ $entityType }}\")\n\t\tassert.False(t, ok)\n\t\t// Enabled descriptive attributes should still be on the resource directly.\n\t\t{{- range $descAttr := $ent.Description }}\n\t\t{{- $attr := index $resourceAttributes $descAttr.Ref }}\n\t\t{{- if $attr.Enabled }}\n\t\t_, ok = rm.Resource().Attributes().Get(\"{{ $descAttr.Ref }}\")\n\t\tassert.True(t, ok)\n\t\t{{- end }}\n\t\t{{- end }}\n\t})\n\n\t{{- if or $ent.Description $ent.ExtraAttributes }}\n\tt.Run(\"{{ $entityType }}/disabled_descriptive_attr\", func(t *testing.T) {\n\t\t// When a descriptive attribute is disabled, the entity is still produced\n\t\t// with its identity but the disabled attribute is not added.\n\t\tcfg := DefaultMetricsBuilderConfig()\n\t\t{{- range $descAttr := $ent.Description }}\n\t\tcfg.ResourceAttributes.{{ publicVar $descAttr.Ref.Render }}.Enabled = false\n\t\t{{- end }}\n\t\t{{- range $extraAttr := $ent.ExtraAttributes }}\n\t\tcfg.ResourceAttributes.{{ publicVar $extraAttr.Ref.Render }}.Enabled = false\n\t\t{{- end }}\n\t\tmb := NewMetricsBuilder(cfg, settings, WithStartTime(start))\n\n\t\te := New{{ $entityStructType }}(\n\t\t\t{{- range $i, $idAttr := $ent.Identity -}}\n\t\t\t{{- $attr := index $resourceAttributes $idAttr.Ref -}}\n\t\t\t{{- if $i }}, {{ end -}}{{ $attr.TestValue }}\n\t\t\t{{- end -}}\n\t\t)\n\t\t{{- if $ent.Description }}\n\t\t{{- range $descAttr := $ent.Description }}\n\t\t{{- $attr := index $resourceAttributes $descAttr.Ref }}\n\t\te.Set{{ publicVar $descAttr.Ref.Render }}({{ $attr.TestValue }})\n\t\t{{- end }}\n\t\t{{- end }}\n\t\t{{- if $ent.ExtraAttributes }}\n\t\t{{- range $extraAttr := $ent.ExtraAttributes }}\n\t\t{{- $attr := index $resourceAttributes $extraAttr.Ref }}\n\t\te.Set{{ publicVar $extraAttr.Ref.Render }}({{ $attr.TestValue }})\n\t\t{{- end }}\n\t\t{{- end }}\n\n\t\teb := mb.For{{ publicVar $entityType }}(e)\n\t\t{{- range $name, $metric := $.Metrics }}\n\t\t{{- if eq $metric.Entity $entityType }}\n\t\teb.Record{{ $name.Render }}DataPoint(ts, {{ if $metric.Data.HasMetricInputType }}\"1\"{{ else }}1{{ end }}\n\t\t{{- range $metric.Attributes -}}\n\t\t{{- if not (attributeInfo .).IsConditional -}}\n\t\t\t, {{- template \"getAttributeValue\" . -}}\n\t\t{{- end -}}\n\t\t{{- end -}}\n\t\t)\n\t\t{{- end }}\n\t\t{{- end }}\n\t\teb.Emit()\n\t\tmetrics := mb.Emit()\n\n\t\trequire.Equal(t, 1, metrics.ResourceMetrics().Len())\n\t\trm := metrics.ResourceMetrics().At(0)\n\t\t// Entity must still be produced since identity attributes are enabled.\n\t\tentityVal, ok := entity.ResourceEntities(rm.Resource()).Get(\"{{ $entityType }}\")\n\t\trequire.True(t, ok)\n\t\t{{- range $idAttr := $ent.Identity }}\n\t\t{{- $attr := index $resourceAttributes $idAttr.Ref }}\n\t\t{{ $idAttr.Ref.RenderUnexported }}AttrVal, ok := entityVal.IdentifyingAttributes().Get(\"{{ $idAttr.Ref }}\")\n\t\trequire.True(t, ok)\n\t\t{{- template \"assertResourceAttributeValue\" $attr }}\n\t\t{{- end }}\n\t\t// Disabled descriptive/extra attributes must not be present.\n\t\t{{- range $descAttr := $ent.Description }}\n\t\t_, ok = entityVal.DescriptiveAttributes().Get(\"{{ $descAttr.Ref }}\")\n\t\tassert.False(t, ok)\n\t\t{{- end }}\n\t\t{{- range $extraAttr := $ent.ExtraAttributes }}\n\t\t_, ok = entityVal.DescriptiveAttributes().Get(\"{{ $extraAttr.Ref }}\")\n\t\tassert.False(t, ok)\n\t\t{{- end }}\n\t})\n\t{{- end }}\n\t{{- end }}\n\t{{- end }}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/feature_gates.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ .Package }}\n\nimport (\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\n{{- range $idx, $gate := .FeatureGates }}\n\nvar {{ printf \"%s\" $gate.ID | publicVar }}FeatureGate = featuregate.GlobalRegistry().MustRegister(\n\t\"{{ $gate.ID }}\",\n\tfeaturegate.Stage{{ printf \"%s\" $gate.Stage | casesTitle }},\n\tfeaturegate.WithRegisterDescription(\"{{ $gate.Description }}\"),\n\tfeaturegate.WithRegisterReferenceURL(\"{{ $gate.ReferenceURL }}\"),\n\tfeaturegate.WithRegisterFromVersion(\"{{ $gate.FromVersion }}\"),\n\t{{- if $gate.ToVersion }}\n\tfeaturegate.WithRegisterToVersion(\"{{ $gate.ToVersion }}\"),\n\t{{- end }}\n)\n{{- end }}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/feature_gates.md.tmpl",
    "content": "{{- if len .FeatureGates }}\n\n## Feature Gates\n\nThis component has the following feature gates:\n\n| Feature Gate | Stage | Description | From Version | To Version | Reference |\n| ------------ | ----- | ----------- | ------------ | ---------- | --------- |\n{{- range .FeatureGates }}\n| `{{ .ID }}` | {{ .Stage }} | {{ .Description }} | {{ if .FromVersion }}{{ .FromVersion }}{{ else }}N/A{{ end }} | {{ if .ToVersion }}{{ .ToVersion }}{{ else }}N/A{{ end }} | {{ if .ReferenceURL }}[Link]({{ .ReferenceURL }}){{ else }}N/A{{ end }} |\n{{- end }}\n\nFor more information about feature gates, see the [Feature Gates](https://github.com/open-telemetry/opentelemetry-collector/blob/main/featuregate/README.md) documentation.\n\n{{- end }}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/helper.tmpl",
    "content": "{{- define \"putAttribute\" -}}\n\t{{- if eq (attributeInfo .).Type.Primitive \"[]byte\" }}\n\tdp.Attributes().PutEmptyBytes(\"{{ (attributeInfo .).Name }}\").FromRaw({{ .RenderUnexported }}AttributeValue)\n\t{{- else if eq (attributeInfo .).Type.Primitive \"[]any\" }}\n\tdp.Attributes().PutEmptySlice(\"{{ (attributeInfo .).Name }}\").FromRaw({{ .RenderUnexported }}AttributeValue)\n\t{{- else if eq (attributeInfo .).Type.Primitive \"map[string]any\" }}\n\tdp.Attributes().PutEmptyMap(\"{{ (attributeInfo .).Name }}\").FromRaw({{ .RenderUnexported }}AttributeValue)\n\t{{- else }}\n\tdp.Attributes().Put{{ (attributeInfo .).Type }}(\"{{ (attributeInfo .).Name }}\", {{ .RenderUnexported }}AttributeValue)\n\t{{- end }}\n{{- end -}}\n\n{{- define \"putMetricAttribute\" -}}\n\tif slices.Contains(m.config.EnabledAttributes, \"{{ (attributeInfo .).Name }}\") {\n\t\t{{- if eq (attributeInfo .).Type.Primitive \"[]byte\" }}\n\t\tdp.Attributes().PutEmptyBytes(\"{{ (attributeInfo .).Name }}\").FromRaw({{ .RenderUnexported }}AttributeValue)\n\t\t{{- else if eq (attributeInfo .).Type.Primitive \"[]any\" }}\n\t\tdp.Attributes().PutEmptySlice(\"{{ (attributeInfo .).Name }}\").FromRaw({{ .RenderUnexported }}AttributeValue)\n\t\t{{- else if eq (attributeInfo .).Type.Primitive \"map[string]any\" }}\n\t\tdp.Attributes().PutEmptyMap(\"{{ (attributeInfo .).Name }}\").FromRaw({{ .RenderUnexported }}AttributeValue)\n\t\t{{- else }}\n\t\tdp.Attributes().Put{{ (attributeInfo .).Type }}(\"{{ (attributeInfo .).Name }}\", {{ .RenderUnexported }}AttributeValue)\n\t\t{{- end }}\n\t}\n{{- end -}}\n\n{{- define \"getAttributeValue\" -}}\n{{ if (attributeInfo .).Enum }}Attribute{{ .Render }}{{ (index (attributeInfo .).Enum 0) | publicVar }}{{ else }}{{ (attributeInfo .).TestValue }}{{ end }}\n{{- end -}}\n\n{{- define \"getAttributeValueTwo\" -}}\n{{ if (attributeInfo .).Enum }}Attribute{{ .Render }}{{ if gt (len (attributeInfo .).Enum) 1}}{{ (index (attributeInfo .).Enum 1) | publicVar}}{{ else }}{{ (index (attributeInfo .).Enum 0) | publicVar}}{{ end }}{{ else }}{{ (attributeInfo .).TestValueTwo }}{{ end }}\n{{- end -}}\n\n{{- define \"assertResourceAttributeValue\" -}}\n{{- if eq .Type.String \"Bool\"}}\nassert.{{- if eq .TestValue \"true\" }}True{{ else }}False{{- end }}(t, {{ .FullName.RenderUnexported }}AttrVal.{{ .Type }}())\n{{- else if eq .Type.String \"Int\"}}\nassert.EqualValues(t, {{ .TestValue }}, {{ .FullName.RenderUnexported }}AttrVal.{{ .Type }}())\n{{- else }}\nassert.Equal(t, {{ .TestValue }}, {{ .FullName.RenderUnexported }}AttrVal.{{ .Type }}()\n{{- if or (eq .Type.String \"Bytes\") (eq .Type.String \"Slice\") (eq .Type.String \"Map\") -}}\n.AsRaw()\n{{- end -}}\n)\n{{- end }}\n{{- end -}}\n\n{{- define \"assertMetricAttributeValue\" -}}\n{{- if eq (attributeInfo .).Type.String \"Bool\"}}\nassert.{{- if eq (attributeInfo .).TestValue \"true\" }}True{{ else }}False{{- end }}(t, {{ .RenderUnexported }}AttrVal.{{ (attributeInfo .).Type }}())\n{{- else if eq (attributeInfo .).Type.String \"Int\"}}\nassert.EqualValues(t, {{ (attributeInfo .).TestValue }}, {{ .RenderUnexported }}AttrVal.{{ (attributeInfo .).Type }}())\n{{- else }}\nassert.Equal(t, {{ (attributeInfo .).TestValue }}, {{ .RenderUnexported }}AttrVal.{{ (attributeInfo .).Type }}()\n{{- if or (eq (attributeInfo .).Type.String \"Bytes\") (eq (attributeInfo .).Type.String \"Slice\") (eq (attributeInfo .).Type.String \"Map\") -}}\n.AsRaw()\n{{- end -}}\n)\n{{- end }}\n{{- end -}}\n\n{{- define \"metricUnmarshal\" }}\n\tif parser == nil {\n\t\treturn nil\n\t}\n\n\terr := parser.Unmarshal({{ . }})\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t{{ . }}.enabledSetByUser = parser.IsSet(\"enabled\")\n\treturn nil\n{{- end }}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/logs.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ .Package }}\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t{{- if or isReceiver isScraper }}\n\t\"go.opentelemetry.io/collector/{{ .Status.Class }}\"\n\t{{- end }}\n\t{{- if .SemConvVersion }}\n\tconventions \"go.opentelemetry.io/otel/semconv/v{{ .SemConvVersion }}\"\n\t{{- end }}\n\t{{- if .Events }}\n\t\"context\"\n\t\"go.opentelemetry.io/otel/trace\"\n\t\"go.opentelemetry.io/collector/filter\"\n\t{{- end }}\n)\n\n\n{{ if getEventConditionalAttributes .Attributes }}\ntype EventAttributeOption interface {\n\tapply(plog.LogRecord)\n}\n\ntype eventAttributeOptionFunc func(plog.LogRecord)\n\nfunc (eaof eventAttributeOptionFunc) apply(lr plog.LogRecord) {\n\teaof(lr)\n}\n\n{{ range getEventConditionalAttributes .Attributes }}\nfunc With{{ .Render }}EventAttribute({{ .RenderUnexported }}AttributeValue {{ (attributeInfo .).Type.Primitive }}) EventAttributeOption {\n\treturn eventAttributeOptionFunc(func(dp plog.LogRecord) {\n\t\t{{- template \"putAttribute\" . }}\n\t})\n}\n{{ end }}\n{{ end }}\n\n{{ range $name, $event := .Events -}}\ntype event{{ $name.Render }} struct {\n\tdata     plog.LogRecordSlice // data buffer for generated log records.\n\tconfig   EventConfig         // event config provided by user.\n}\n\nfunc (e *event{{ $name.Render }}) recordEvent(ctx context.Context, timestamp pcommon.Timestamp\n{{- range $event.Attributes -}}{{- if not (attributeInfo .).IsConditional -}}, {{ .RenderUnexported }}AttributeValue {{ (attributeInfo .).Type.Primitive }}{{ end }}{{end}}{{- if $event.HasConditionalAttributes $.Attributes -}}, options ...EventAttributeOption{{- end -}}) {\n\tif !e.config.Enabled {\n\t\treturn\n\t}\n\tdp := e.data.AppendEmpty()\n\tdp.SetEventName(\"{{ $name }}\")\n\tdp.SetTimestamp(timestamp)\n\n\tif span := trace.SpanContextFromContext(ctx); span.IsValid() {\n\t\tdp.SetTraceID(pcommon.TraceID(span.TraceID()))\n\t\tdp.SetSpanID(pcommon.SpanID(span.SpanID()))\n\t}\n\n\t{{- range $event.Attributes }}\n\t{{- if not (attributeInfo .).IsConditional -}}\n\t{{- template \"putAttribute\" . }}\n\t{{- end }}\n\t{{- end }}\n\n\t{{ if $event.HasConditionalAttributes $.Attributes }}\n\tfor _, op := range options {\n\t\top.apply(dp)\n\t}\n\t{{- end }}\n}\n\n// emit appends recorded event data to a events slice and prepares it for recording another set of log records.\nfunc (e *event{{ $name.Render }}) emit(lrs plog.LogRecordSlice) {\n\tif e.config.Enabled && e.data.Len() > 0 {\n\t\te.data.MoveAndAppendTo(lrs)\n\t}\n}\n\nfunc newEvent{{ $name.Render }}(cfg EventConfig) event{{ $name.Render }} {\n\te := event{{ $name.Render }}{config: cfg}\n\tif cfg.Enabled {\n\t\te.data = plog.NewLogRecordSlice()\n\t}\n\treturn e\n}\n\n{{ end -}}\n\n// LogsBuilder provides an interface for scrapers to report logs while taking care of all the transformations\n// required to produce log representation defined in metadata and user config.\ntype LogsBuilder struct {\n\t{{- if .Events }}\n\tconfig              LogsBuilderConfig    // config of the logs builder.\n\t{{- end }}\n\tlogsBuffer          plog.Logs\n\tlogRecordsBuffer    plog.LogRecordSlice\n\tbuildInfo           component.BuildInfo  // contains version information.\n\t{{- if and .Events .ResourceAttributes }}\n\tresourceAttributeIncludeFilter map[string]filter.Filter\n\tresourceAttributeExcludeFilter map[string]filter.Filter\n\t{{- end }}\n\t{{- range $name, $event := .Events }}\n\tevent{{ $name.Render }} event{{ $name.Render }}\n\t{{- end }}\n}\n\n// LogBuilderOption applies changes to default logs builder.\ntype LogBuilderOption interface {\n\tapply(*LogsBuilder)\n}\n\n{{- if or isReceiver isScraper }}\nfunc NewLogsBuilder({{ if .Events }}lbc LogsBuilderConfig, {{ end }}settings {{ .Status.Class }}.Settings) *LogsBuilder {\n\t{{- range $name, $event := .Events }}\n\t{{- if $event.Warnings.IfEnabled }}\n\tif lbc.Events.{{ $name.Render }}.Enabled {\n\t\tsettings.Logger.Warn(\"[WARNING] `{{ $name }}` should not be enabled: {{ $event.Warnings.IfEnabled }}\")\n\t}\n\t{{- end }}\n\t{{- if $event.Warnings.IfEnabledNotSet }}\n\tif !lbc.Events.{{ $name.Render }}.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] Please set `enabled` field explicitly for `{{ $name }}`: {{ $event.Warnings.IfEnabledNotSet }}\")\n\t}\n\t{{- end }}\n\t{{- if $event.Warnings.IfConfigured }}\n\tif lbc.Events.{{ $name.Render }}.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] `{{ $name }}` should not be configured: {{ $event.Warnings.IfConfigured }}\")\n\t}\n\t{{- end }}\n\t{{- end }}\n\t{{- if .Events }}\n\t{{- range $name, $attr := .ResourceAttributes }}\n\t{{- if $attr.Warnings.IfEnabled }}\n\tif lbc.ResourceAttributes.{{ $name.Render }}.Enabled {\n\t\tsettings.Logger.Warn(\"[WARNING] `{{ $name }}` should not be enabled: {{ $attr.Warnings.IfEnabled }}\")\n\t}\n\t{{- end }}\n\t{{- if $attr.Warnings.IfEnabledNotSet }}\n\tif !lbc.ResourceAttributes.{{ $name.Render }}.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] Please set `enabled` field explicitly for `{{ $name }}`: {{ $attr.Warnings.IfEnabledNotSet }}\")\n\t}\n\t{{- end }}\n\t{{- if $attr.Warnings.IfConfigured }}\n\tif lbc.ResourceAttributes.{{ $name.Render }}.enabledSetByUser || lbc.ResourceAttributes.{{ $name.Render }}.EventsInclude != nil || lbc.ResourceAttributes.{{ $name.Render }}.EventsExclude != nil {\n\t\tsettings.Logger.Warn(\"[WARNING] `{{ $name }}` should not be configured: {{ $attr.Warnings.IfConfigured }}\")\n\t}\n\t{{- end }}\n\t{{- end }}\n\t{{- end }}\n\tlb := &LogsBuilder{\n\t\t{{- if .Events }}\n\t\tconfig:        lbc,\n\t\t{{- end }}\n\t\tlogsBuffer:     plog.NewLogs(),\n\t\tlogRecordsBuffer: plog.NewLogRecordSlice(),\n\t\tbuildInfo:      settings.BuildInfo,\n\t\t{{- range $name, $event := .Events }}\n\t\tevent{{ $name.Render }}: newEvent{{ $name.Render }}(lbc.Events.{{ $name.Render }}),\n\t\t{{- end }}\n\t\t{{ if and .Events .ResourceAttributes -}}\n\t\tresourceAttributeIncludeFilter: make(map[string]filter.Filter),\n\t\tresourceAttributeExcludeFilter: make(map[string]filter.Filter),\n\t\t{{- end }}\n\t}\n\t{{- if .Events }}\n\t{{- range $name, $attr := .ResourceAttributes }}\n\tif lbc.ResourceAttributes.{{ $name.Render }}.EventsInclude != nil {\n\t\tlb.resourceAttributeIncludeFilter[\"{{ $name }}\"] = filter.CreateFilter(lbc.ResourceAttributes.{{ $name.Render }}.EventsInclude)\n\t}\n\tif lbc.ResourceAttributes.{{ $name.Render }}.EventsExclude != nil {\n\t\tlb.resourceAttributeExcludeFilter[\"{{ $name }}\"] = filter.CreateFilter(lbc.ResourceAttributes.{{ $name.Render }}.EventsExclude)\n\t}\n\t{{- end }}\n\t{{- end }}\n\n\treturn lb\n}\n{{- end }}\n\n{{- if .ResourceAttributes }}\n// NewResourceBuilder returns a new resource builder that should be used to build a resource associated with for the emitted logs.\nfunc (lb *LogsBuilder) NewResourceBuilder() *ResourceBuilder {\n\treturn NewResourceBuilder({{ if .Events }}lb.config.ResourceAttributes{{ else }}ResourceAttributesConfig{}{{ end }})\n}\n{{- end }}\n\n// ResourceLogsOption applies changes to provided resource logs.\ntype ResourceLogsOption interface {\n\tapply(plog.ResourceLogs)\n}\n\ntype resourceLogsOptionFunc func(plog.ResourceLogs)\n\nfunc (rlof resourceLogsOptionFunc) apply(rl plog.ResourceLogs) {\n\trlof(rl)\n}\n\n// WithLogsResource sets the provided resource on the emitted ResourceLogs.\n// It's recommended to use ResourceBuilder to create the resource.\nfunc WithLogsResource(res pcommon.Resource) ResourceLogsOption {\n\treturn resourceLogsOptionFunc(func(rl plog.ResourceLogs) {\n\t\tres.CopyTo(rl.Resource())\n\t})\n}\n\n// AppendLogRecord adds a log record to the logs builder.\nfunc (lb *LogsBuilder) AppendLogRecord(lr plog.LogRecord) {\n\tlr.MoveTo(lb.logRecordsBuffer.AppendEmpty())\n}\n\n// EmitForResource saves all the generated logs under a new resource and updates the internal state to be ready for\n// recording another set of log records as part of another resource. This function can be helpful when one scraper\n// needs to emit logs from several resources. Otherwise calling this function is not required,\n// just `Emit` function can be called instead.\n// Resource attributes should be provided as ResourceLogsOption arguments.\nfunc (lb *LogsBuilder) EmitForResource(options ...ResourceLogsOption) {\n\trl := plog.NewResourceLogs()\n\t{{- if .SemConvVersion }}\n\trl.SetSchemaUrl(conventions.SchemaURL)\n\t{{- end }}\n\tils := rl.ScopeLogs().AppendEmpty()\n\tils.Scope().SetName(ScopeName)\n\tils.Scope().SetVersion(lb.buildInfo.Version)\n\n\t{{- range $name, $event := .Events }}\n\tlb.event{{- $name.Render }}.emit(ils.LogRecords())\n\t{{- end }}\n\n\tfor _, op := range options {\n\t\top.apply(rl)\n\t}\n\n\tif lb.logRecordsBuffer.Len() > 0 {\n\t\tlb.logRecordsBuffer.MoveAndAppendTo(ils.LogRecords())\n\t\tlb.logRecordsBuffer = plog.NewLogRecordSlice()\n\t}\n\n\t{{ if and .Events .ResourceAttributes -}}\n\tfor attr, filter := range lb.resourceAttributeIncludeFilter {\n\t\tif val, ok := rl.Resource().Attributes().Get(attr); ok && !filter.Matches(val.AsString()) {\n\t\t\treturn\n\t\t}\n\t}\n\tfor attr, filter := range lb.resourceAttributeExcludeFilter {\n\t\tif val, ok := rl.Resource().Attributes().Get(attr); ok && filter.Matches(val.AsString()) {\n\t\t\treturn\n\t\t}\n\t}\n\t{{- end }}\n\n\tif ils.LogRecords().Len() > 0 {\n\t\trl.MoveTo(lb.logsBuffer.ResourceLogs().AppendEmpty())\n\t}\n}\n\n// Emit returns all the logs accumulated by the logs builder and updates the internal state to be ready for\n// recording another set of logs. This function will be responsible for applying all the transformations required to\n// produce logs representation defined in metadata and user config.\nfunc (lb *LogsBuilder) Emit(options ...ResourceLogsOption) plog.Logs {\n\tlb.EmitForResource(options...)\n\tlogs := lb.logsBuffer\n\tlb.logsBuffer = plog.NewLogs()\n\treturn logs\n}\n\n{{ range $name, $event := .Events -}}\n// Record{{ $name.Render }}Event adds a log record of {{ $name }} event.\nfunc (lb *LogsBuilder) Record{{ $name.Render }}Event(ctx context.Context, timestamp pcommon.Timestamp\n\t{{- range $event.Attributes -}}\n\t{{- if not (attributeInfo .).IsConditional -}}\n\t, {{ .RenderUnexported }}AttributeValue {{ if (attributeInfo .).Enum }}Attribute{{ .Render }}{{ else }}{{ (attributeInfo .).Type.Primitive }}{{ end }}\n\t{{- end -}}\n\t{{- end -}}\n\t{{- if $event.HasConditionalAttributes $.Attributes -}}\n\t, options... EventAttributeOption\n\t{{- end -}}) {\n\tlb.event{{ $name.Render }}.recordEvent(ctx, timestamp\n\t\t{{- range $event.Attributes -}}\n\t\t{{- if not (attributeInfo .).IsConditional -}}\n\t\t, {{ .RenderUnexported }}AttributeValue{{ if (attributeInfo .).Enum }}.String(){{ end }}\n\t\t{{- end -}}\n\t\t{{- end -}}\n\t\t{{- if $event.HasConditionalAttributes $.Attributes -}}\n\t\t, options...\n\t\t{{- end -}})\n}\n{{ end }}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/logs_test.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ .Package }}\n\nimport (\n\t\"time\"\n\t\"testing\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t{{- if or isReceiver isScraper }}\n\t\"go.opentelemetry.io/collector/{{ .Status.Class }}/{{ .Status.Class }}test\"\n\t{{- end }}\n\t{{- if .Events }}\n\t\"context\"\n\t\"go.opentelemetry.io/otel/trace\"\n\t{{- end }}\n)\n\n{{- if .Events }}\ntype eventsTestDataSet int\n\nconst (\n\teventTestDataSetDefault eventsTestDataSet = iota\n\teventTestDataSetAll\n\teventTestDataSetNone\n)\n{{- end }}\n\nfunc TestLogsBuilderAppendLogRecord(t *testing.T) {\n\tobservedZapCore, _ := observer.New(zap.WarnLevel)\n\t{{- if or isReceiver isScraper }}\n\tsettings := {{ .Status.Class }}test.NewNopSettings({{ .Status.Class }}test.NopType)\n\t{{- end }}\n\tsettings.Logger = zap.New(observedZapCore)\n\tlb := NewLogsBuilder({{ if .Events }}loadLogsBuilderConfig(t, \"all_set\"), {{ end }}settings)\n\n\t{{ if .ResourceAttributes }}\n\trb := lb.NewResourceBuilder()\n\t{{- range $name, $attr := .ResourceAttributes }}\n\t{{- if $attr.Enum }}\n\trb.Set{{ $attr.Name.Render }}{{ index $attr.Enum 0 | publicVar }}()\n\t{{- else }}\n\trb.Set{{ $attr.Name.Render }}({{ $attr.TestValue }})\n\t{{- end }}\n\t{{- end }}\n\tres := rb.Emit()\n\t{{- else }}\n\tres := pcommon.NewResource()\n\t{{- end }}\n\n\t// append the first log record\n\tlr := plog.NewLogRecord()\n\tlr.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\tlr.Attributes().PutStr(\"type\", \"log\")\n\tlr.Body().SetStr(\"the first log record\")\n\n\t// append the second log record\n\tlr2 := plog.NewLogRecord()\n\tlr2.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\tlr2.Attributes().PutStr(\"type\", \"event\")\n\tlr2.Body().SetStr(\"the second log record\")\n\n\tlb.AppendLogRecord(lr)\n\tlb.AppendLogRecord(lr2)\n\n\tlogs := lb.Emit(WithLogsResource(res))\n\tassert.Equal(t, 1, logs.ResourceLogs().Len())\n\n\trl := logs.ResourceLogs().At(0)\n\tassert.Equal(t, 1, rl.ScopeLogs().Len())\n\n\tsl := rl.ScopeLogs().At(0)\n\tassert.Equal(t, ScopeName,sl.Scope().Name())\n\tassert.Equal(t, lb.buildInfo.Version, sl.Scope().Version())\n\n\tassert.Equal(t, 2, sl.LogRecords().Len())\n\n\tattrVal, ok := sl.LogRecords().At(0).Attributes().Get(\"type\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"log\", attrVal.Str())\n\n\tassert.Equal(t, pcommon.ValueTypeStr, sl.LogRecords().At(0).Body().Type())\n\tassert.Equal(t, \"the first log record\", sl.LogRecords().At(0).Body().Str())\n\n\tattrVal, ok = sl.LogRecords().At(1).Attributes().Get(\"type\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"event\", attrVal.Str())\n\n\tassert.Equal(t, pcommon.ValueTypeStr, sl.LogRecords().At(1).Body().Type())\n\tassert.Equal(t, \"the second log record\", sl.LogRecords().At(1).Body().Str())\n}\n\n{{- if .Events }}\nfunc TestLogsBuilder(t *testing.T) {\n\ttests := []struct {\n\t\tname               string\n\t\teventsSet          eventsTestDataSet\n\t\tresAttrsSet        eventsTestDataSet\n\t\texpectEmpty        bool\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t},\n\t\t{\n\t\t\tname:        \"all_set\",\n\t\t\teventsSet:   eventTestDataSetAll,\n\t\t\tresAttrsSet: eventTestDataSetAll,\n\t\t},\n\t\t{\n\t\t\tname:        \"none_set\",\n\t\t\teventsSet:   eventTestDataSetNone,\n\t\t\tresAttrsSet: eventTestDataSetNone,\n\t\t\texpectEmpty: true,\n\t\t},\n\t\t{{- if .ResourceAttributes }}\n\t\t{\n\t\t\tname:        \"filter_set_include\",\n\t\t\tresAttrsSet: eventTestDataSetAll,\n\t\t},\n\t\t{\n\t\t\tname:        \"filter_set_exclude\",\n\t\t\tresAttrsSet: eventTestDataSetAll,\n\t\t\texpectEmpty: true,\n\t\t},\n\t\t{{- end }}\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttimestamp := pcommon.Timestamp(1_000_001_000)\n\t\t\ttraceID := [16]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}\n\t\t\tspanID := [8]byte{0, 1, 2, 3, 4, 5, 6, 7}\n\t\t\tctx := trace.ContextWithSpanContext(context.Background(), trace.NewSpanContext(trace.SpanContextConfig{\n\t\t\t\tTraceID:    trace.TraceID(traceID),\n\t\t\t\tSpanID:     trace.SpanID(spanID),\n\t\t\t\tTraceFlags: trace.FlagsSampled,\n\t\t\t}))\n\t\t\tobservedZapCore, observedLogs := observer.New(zap.WarnLevel)\n\t\t\t{{- if or isReceiver isScraper }}\n\t\t\tsettings := {{ .Status.Class }}test.NewNopSettings({{ .Status.Class }}test.NopType)\n\t\t\t{{- end }}\n\t\t\tsettings.Logger = zap.New(observedZapCore)\n\t\t\tlb := NewLogsBuilder(loadLogsBuilderConfig(t, tt.name), settings)\n\n\t\t\texpectedWarnings := 0\n\t\t\t{{- range $name, $event := .Events }}\n\t\t\t{{- if and $event.Enabled $event.Warnings.IfEnabled }}\n\t\t\tif tt.eventsSet == eventTestDataSetDefault || tt.eventsSet == eventTestDataSetAll {\n\t\t\t\tassert.Equal(t, \"[WARNING] `{{ $name }}` should not be enabled: {{ $event.Warnings.IfEnabled }}\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\t{{- end }}\n\t\t\t{{- if $event.Warnings.IfEnabledNotSet }}\n\t\t\tif tt.eventsSet == eventTestDataSetDefault {\n\t\t\t\tassert.Equal(t, \"[WARNING] Please set `enabled` field explicitly for `{{ $name }}`: {{ $event.Warnings.IfEnabledNotSet }}\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\t{{- end }}\n\t\t\t{{- if $event.Warnings.IfConfigured }}\n\t\t\tif tt.eventsSet == eventTestDataSetAll || tt.eventsSet == eventTestDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `{{ $name }}` should not be configured: {{ $event.Warnings.IfConfigured }}\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\t{{- end }}\n\t\t\t{{- end }}\n\t\t\t{{- range $name, $attr := .ResourceAttributes }}\n\t\t\t{{- if and $attr.Enabled $attr.Warnings.IfEnabled }}\n\t\t\tif tt.resAttrsSet == eventTestDataSetDefault || tt.resAttrsSet == eventTestDataSetAll {\n\t\t\t\tassert.Equal(t, \"[WARNING] `{{ $name }}` should not be enabled: {{ $attr.Warnings.IfEnabled }}\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\t{{- end }}\n\t\t\t{{- if $attr.Warnings.IfEnabledNotSet }}\n\t\t\tif tt.resAttrsSet == eventTestDataSetDefault {\n\t\t\t\tassert.Equal(t, \"[WARNING] Please set `enabled` field explicitly for `{{ $name }}`: {{ $attr.Warnings.IfEnabledNotSet }}\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\t{{- end }}\n\t\t\t{{- if $attr.Warnings.IfConfigured }}\n\t\t\tif tt.resAttrsSet == eventTestDataSetAll || tt.resAttrsSet == eventTestDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `{{ $name }}` should not be configured: {{ $attr.Warnings.IfConfigured }}\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\t{{- end }}\n\t\t\t{{- end }}\n\n\n\t\t\tassert.Equal(t, expectedWarnings, observedLogs.Len())\n\n\t\t\tdefaultEventsCount := 0\n\t\t\tallEventsCount := 0\n\t\t\t{{- range $name, $event := .Events }}\n\t\t\t\t{{ if $event.Enabled }}defaultEventsCount++{{ end }}\n\t\t\t\tallEventsCount++\n\t\t\t\tlb.Record{{ $name.Render }}Event(ctx, timestamp\n\t\t\t\t{{- range $event.Attributes -}}\n\t\t\t\t{{- if not (attributeInfo .).IsConditional -}}\n\t\t\t\t\t, {{- template \"getAttributeValue\" . -}}\n\t\t\t\t{{- end -}}\n\t\t\t\t{{- end -}}\n\t\t\t\t{{- range $event.Attributes -}}\n\t\t\t\t{{- if (attributeInfo .).IsConditional -}}\n\t\t\t\t\t, With{{ .Render }}EventAttribute({{- template \"getAttributeValue\" . -}})\n\t\t\t\t{{- end -}}\n\t\t\t\t{{- end -}}\n\t\t\t\t)\n\t\t\t{{- end }}\n\n\t\t\t{{ if .ResourceAttributes }}\n\t\t\trb := lb.NewResourceBuilder()\n\t\t\t{{- range $name, $attr := .ResourceAttributes }}\n\t\t\t{{- if $attr.Enum }}\n\t\t\trb.Set{{ $attr.Name.Render }}{{ index $attr.Enum 0 | publicVar }}()\n\t\t\t{{- else }}\n\t\t\trb.Set{{ $attr.Name.Render }}({{ $attr.TestValue }})\n\t\t\t{{- end }}\n\t\t\t{{- end }}\n\t\t\tres := rb.Emit()\n\t\t\t{{- else }}\n\t\t\tres := pcommon.NewResource()\n\t\t\t{{- end }}\n\t\t\tlogs := lb.Emit(WithLogsResource(res))\n\n\t\t\tif tt.expectEmpty || ((tt.name == \"default\" || tt.name == \"filter_set_include\") && defaultEventsCount == 0) {\n\t\t\t\tassert.Equal(t, 0, logs.ResourceLogs().Len())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tassert.Equal(t, 1, logs.ResourceLogs().Len())\n\t\t\trl := logs.ResourceLogs().At(0)\n\t\t\tassert.Equal(t, res, rl.Resource())\n\t\t\tassert.Equal(t, 1, rl.ScopeLogs().Len())\n\t\t\tlrs := rl.ScopeLogs().At(0).LogRecords()\n\t\t\tif tt.eventsSet == eventTestDataSetDefault {\n\t\t\t\tassert.Equal(t, defaultEventsCount, lrs.Len())\n\t\t\t}\n\t\t\tif tt.eventsSet == eventTestDataSetAll {\n\t\t\t\tassert.Equal(t, allEventsCount, lrs.Len())\n\t\t\t}\n\t\t\tvalidatedEvents := make(map[string]bool)\n\t\t\tfor i := 0; i < lrs.Len(); i++ {\n\t\t\t\tswitch lrs.At(i).EventName() {\n\t\t\t\t{{- range $name, $event := .Events }}\n\t\t\t\tcase \"{{ $name }}\":\n\t\t\t\t\tassert.False(t, validatedEvents[\"{{ $name }}\"], \"Found a duplicate in the events slice: {{ $name }}\")\n\t\t\t\t\tvalidatedEvents[\"{{ $name }}\"] = true\n\t\t\t\t\tlr := lrs.At(i)\n\t\t\t\t\tassert.Equal(t, timestamp, lr.Timestamp())\n\t\t\t\t\tassert.Equal(t, pcommon.TraceID(traceID), lr.TraceID())\n\t\t\t\t\tassert.Equal(t, pcommon.SpanID(spanID), lr.SpanID())\n\n\t\t\t\t\t{{- range $i, $attr := $event.Attributes }}\n\t\t\t\t\tattrVal, ok {{ if eq $i 0 }}:{{ end }}= lr.Attributes().Get(\"{{ (attributeInfo $attr).Name }}\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t{{- if eq (attributeInfo $attr).Type.String \"Bool\"}}\n\t\t\t\t\tassert.{{- if eq (attributeInfo $attr).TestValue \"true\" }}True{{ else }}False{{- end }}(t, attrVal.{{ (attributeInfo $attr).Type }}()\n\t\t\t\t\t{{- else if eq (attributeInfo $attr).Type.String \"Int\"}}\n\t\t\t\t\tassert.EqualValues(t, {{ (attributeInfo $attr).TestValue }}, attrVal.{{ (attributeInfo $attr).Type }}()\n\t\t\t\t\t{{- else }}\n\t\t\t\t\tassert.Equal(t, {{ (attributeInfo $attr).TestValue }}, attrVal.{{ (attributeInfo $attr).Type }}()\n\t\t\t\t\t{{- end }}\n\t\t\t\t\t{{- if or (eq (attributeInfo $attr).Type.String \"Slice\") (eq (attributeInfo $attr).Type.String \"Map\")}}.AsRaw(){{ end }})\n\t\t\t\t\t{{- end }}\n\t\t\t\t{{- end }}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n{{- end }}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/metrics.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ .Package }}\n\n{{ $reag := .ReaggregationEnabled }}\n{{- $hasReagMetrics := false }}\n{{- range $name, $metric := .Metrics }}{{- if and $reag (hasAggregatableAttributes $metric.Attributes) }}{{- $hasReagMetrics = true }}{{- end }}{{- end }}\n\nimport (\n\t{{- if .Metrics | parseImportsRequired }}\n\t\"strconv\"\n\t\"fmt\"\n\t{{- end }}\n\t\"time\"\n\t{{- if $hasReagMetrics }}\n\t\"slices\"\n\t{{- end }}\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t{{- if or isReceiver isScraper isConnector }}\n\t\"go.opentelemetry.io/collector/{{ .Status.Class }}\"\n\t{{- end }}\n\t{{- if .SemConvVersion }}\n\tconventions \"go.opentelemetry.io/otel/semconv/v{{ .SemConvVersion }}\"\n\t{{- end }}\n\t{{ if .ResourceAttributes -}}\n\t\"go.opentelemetry.io/collector/filter\"\n\t{{- end }}\n)\n\n{{- if $reag }}\nconst (\n\tAggregationStrategySum = \"sum\"\n\tAggregationStrategyAvg = \"avg\"\n\tAggregationStrategyMin = \"min\"\n\tAggregationStrategyMax = \"max\"\n)\n{{- end }}\n\n{{ range $name, $info := .Attributes }}\n{{- if $info.Enum }}\n// Attribute{{ $name.Render }} specifies the value {{ $name }} attribute.\ntype Attribute{{ $name.Render }} int\n\nconst (\n\t_ Attribute{{ $name.Render }} = iota\n\t{{- range $info.Enum }}\n\tAttribute{{ $name.Render }}{{ . | publicVar }}\n\t{{- end }}\n)\n\n// String returns the string representation of the Attribute{{ $name.Render }}.\nfunc (av Attribute{{ $name.Render }}) String() string {\n\tswitch av {\n\t{{- range $info.Enum }}\n\tcase Attribute{{ $name.Render }}{{ . | publicVar }}:\n\t\treturn \"{{ . }}\"\n\t{{- end }}\n\t}\n\treturn \"\"\n}\n\n// MapAttribute{{ $name.Render }} is a helper map of string to Attribute{{ $name.Render }} attribute value.\nvar MapAttribute{{ $name.Render }} = map[string]Attribute{{ $name.Render }}{\n\t{{- range $info.Enum }}\n\t\"{{ . }}\": Attribute{{ $name.Render }}{{ . | publicVar }},\n\t{{- end }}\n}\n{{- end }}\n{{- end }}\n\nvar MetricsInfo = metricsInfo{\n\t{{- range $name, $metric := .Metrics }}\n\t{{ $name.Render }}: metricInfo{\n\t\tName: \"{{ $name }}\",\n\t},\n\t{{- end }}\n}\n\ntype metricsInfo struct {\n\t{{- range $name, $metric := .Metrics }}\n\t{{ $name.Render }} metricInfo\n\t{{- end }}\n}\n\ntype metricInfo struct {\n\tName string\n}\n\n{{ if getMetricConditionalAttributes .Attributes }}\ntype MetricAttributeOption interface {\n\tapply(pmetric.NumberDataPoint)\n}\n\ntype metricAttributeOptionFunc func(pmetric.NumberDataPoint)\n\nfunc (maof metricAttributeOptionFunc) apply(dp pmetric.NumberDataPoint) {\n\tmaof(dp)\n}\n\n{{ range getMetricConditionalAttributes .Attributes }}\nfunc With{{ .Render }}MetricAttribute({{ .RenderUnexported }}AttributeValue {{ (attributeInfo .).Type.Primitive }}) MetricAttributeOption {\n\treturn metricAttributeOptionFunc(func(dp pmetric.NumberDataPoint) {\n\t\t{{- template \"putAttribute\" . }}\n\t})\n}\n{{ end }}\n{{ end }}\n\n{{ range $name, $metric := .Metrics }}\n{{- $metricReag := and $reag (hasAggregatableAttributes $metric.Attributes) -}}\ntype metric{{ $name.Render }} struct {\n\tdata                     pmetric.Metric // data buffer for generated metric.\n\tconfig                   {{ if $reag }}{{ $name.Render }}{{ end }}MetricConfig // metric config provided by user.\n\tcapacity                 int // max observed number of data points added to the metric.\n\t{{- if $metricReag }}\n\taggDataPoints            []{{ $metric.Data.MetricValueType.BasicType }} // slice containing number of aggregated datapoints at each index\n\t{{- end }}\n}\n\n// init fills {{ $name }} metric with initial data.\nfunc (m *metric{{ $name.Render }}) init() {\n\tm.data.SetName(\"{{ $name }}\")\n\tm.data.SetDescription(\"{{ $metric.Description }}\")\n\tm.data.SetUnit(\"{{ $metric.Unit }}\")\n\tm.data.SetEmpty{{ $metric.Data.Type }}()\n\t{{- if $metric.Data.HasMonotonic }}\n\tm.data.{{ $metric.Data.Type }}().SetIsMonotonic({{ $metric.Data.Monotonic }})\n\t{{- end }}\n\t{{- if $metric.Data.HasAggregated }}\n\tm.data.{{ $metric.Data.Type }}().SetAggregationTemporality(pmetric.AggregationTemporality{{ $metric.Data.AggregationTemporality }})\n\t{{- end }}\n\t{{- if $metric.Attributes }}\n\tm.data.{{ $metric.Data.Type }}().DataPoints().EnsureCapacity(m.capacity)\n\t{{- end }}\n\t{{- if $metricReag }}\n\tm.aggDataPoints = m.aggDataPoints[:0]\n\t{{- end }}\n}\n\n{{/* This function changed in a major way, so instead of gating individual lines of code the original is being included */}}\n{{- if $metricReag }}\nfunc (m *metric{{ $name.Render }}) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val {{ $metric.Data.MetricValueType.BasicType }}\n{{- range $metric.Attributes -}}{{- if not (attributeInfo .).IsConditional -}}, {{ .RenderUnexported }}AttributeValue {{ (attributeInfo .).Type.Primitive }}{{ end }}{{ end }}{{- if $metric.HasConditionalAttributes $.Attributes -}}, options ...MetricAttributeOption{{- end -}}) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\n\tdp := pmetric.NewNumberDataPoint()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\t{{- range $metric.Attributes }}\n\t{{- if not (attributeInfo .).IsConditional }}\n\tif slices.Contains(m.config.EnabledAttributes, {{ $name.Render }}MetricAttributeKey{{ .Render }}) {\n\t\t{{- template \"putAttribute\" . }}\n\t}\n\t{{- end }}\n\t{{- end }}\n\n\t{{- if $metric.HasConditionalAttributes $.Attributes }}\n\tfor _, op := range options {\n\t\top.apply(dp)\n\t}\n\t{{- end }}\n\n\tvar s string\n\tdps := m.data.{{ $metric.Data.Type }}().DataPoints()\n\tfor i := 0; i < dps.Len(); i++ {\n\t\tdpi := dps.At(i)\n\t\tif dp.Attributes().Equal(dpi.Attributes()) && dp.StartTimestamp() == dpi.StartTimestamp() && dp.Timestamp() == dpi.Timestamp() {\n\t\t\tswitch s = m.config.AggregationStrategy; s {\n\t\t\tcase AggregationStrategySum, AggregationStrategyAvg:\n\t\t\t\tdpi.Set{{ $metric.Data.MetricValueType }}Value(dpi.{{ $metric.Data.MetricValueType }}Value() + val)\n\t\t\t\tm.aggDataPoints[i] += 1\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMin:\n\t\t\t\tif dpi.{{ $metric.Data.MetricValueType }}Value() > val {\n\t\t\t\t\tdpi.Set{{ $metric.Data.MetricValueType }}Value(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\tcase AggregationStrategyMax:\n\t\t\t\tif dpi.{{ $metric.Data.MetricValueType }}Value() < val {\n\t\t\t\t\tdpi.Set{{ $metric.Data.MetricValueType }}Value(val)\n\t\t\t\t}\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n\n\tdp.Set{{ $metric.Data.MetricValueType }}Value(val)\n\tm.aggDataPoints = append(m.aggDataPoints, 1)\n\tdp.MoveTo(dps.AppendEmpty())\n}\n{{- else }}\nfunc (m *metric{{ $name.Render }}) recordDataPoint(start pcommon.Timestamp, ts pcommon.Timestamp, val {{ $metric.Data.MetricValueType.BasicType }}\n{{- range $metric.Attributes -}}{{- if not (attributeInfo .).IsConditional -}}, {{ .RenderUnexported }}AttributeValue {{ (attributeInfo .).Type.Primitive }}{{ end }}{{ end }}{{- if $metric.HasConditionalAttributes $.Attributes -}}, options ...MetricAttributeOption{{- end -}}) {\n\tif !m.config.Enabled {\n\t\treturn\n\t}\n\tdp := m.data.{{ $metric.Data.Type }}().DataPoints().AppendEmpty()\n\tdp.SetStartTimestamp(start)\n\tdp.SetTimestamp(ts)\n\tdp.Set{{ $metric.Data.MetricValueType }}Value(val)\n\t{{- range $metric.Attributes }}\n\t{{- if not (attributeInfo .).IsConditional -}}\n\t{{- template \"putAttribute\" . -}}\n\t{{- end }}\n\t{{- end }}\n\n\t{{- if $metric.HasConditionalAttributes $.Attributes }}\n\tfor _, op := range options {\n\t\top.apply(dp)\n\t}\n\t{{- end }}\n}\n{{- end }}\n\n// updateCapacity saves max length of data point slices that will be used for the slice capacity.\nfunc (m *metric{{ $name.Render }}) updateCapacity() {\n\tif m.data.{{ $metric.Data.Type }}().DataPoints().Len() > m.capacity {\n\t\tm.capacity = m.data.{{ $metric.Data.Type }}().DataPoints().Len()\n\t}\n}\n\n// emit appends recorded metric data to a metrics slice and prepares it for recording another set of data points.\nfunc (m *metric{{ $name.Render }}) emit(metrics pmetric.MetricSlice) {\n\t{{- if $metricReag }}\n\tif m.config.Enabled && m.data.{{ $metric.Data.Type }}().DataPoints().Len() > 0 {\n\t\tif m.config.AggregationStrategy == AggregationStrategyAvg {\n\t\t\tfor i, aggCount := range m.aggDataPoints {\n\t\t\t\tm.data.{{ $metric.Data.Type }}().DataPoints().At(i).Set{{ $metric.Data.MetricValueType }}Value(m.data.{{ $metric.Data.Type }}().DataPoints().At(i).{{ $metric.Data.MetricValueType }}Value() / aggCount)\n\t\t\t}\n\t\t}\n\t{{- else }}\n\tif m.config.Enabled && m.data.{{ $metric.Data.Type }}().DataPoints().Len() > 0 {\n\t{{- end }}\n\t\tm.updateCapacity()\n\t\tm.data.MoveTo(metrics.AppendEmpty())\n\t\tm.init()\n\t}\n}\n\nfunc newMetric{{ $name.Render }}(cfg {{ if $reag }}{{ $name.Render }}{{ end }}MetricConfig) metric{{ $name.Render }} {\n\tm := metric{{ $name.Render }}{config: cfg}\n\n\tif cfg.Enabled {\n\t\tm.data = pmetric.NewMetric()\n\t\tm.init()\n\t}\n\treturn m\n}\n\n{{ end -}}\n\n// MetricsBuilder provides an interface for scrapers to report metrics while taking care of all the transformations\n// required to produce metric representation defined in metadata and user config.\ntype MetricsBuilder struct {\n\tconfig          MetricsBuilderConfig // config of the metrics builder.\n\tstartTime       pcommon.Timestamp    // start time that will be applied to all recorded data points.\n\tmetricsCapacity int                  // maximum observed number of metrics per resource.\n\tmetricsBuffer   pmetric.Metrics      // accumulates metrics data before emitting.\n\tbuildInfo       component.BuildInfo  // contains version information.\n\t{{- if .ResourceAttributes }}\n\tresourceAttributeIncludeFilter map[string]filter.Filter\n\tresourceAttributeExcludeFilter map[string]filter.Filter\n\t{{- end }}\n\t{{- range $name, $metric := .Metrics }}\n\tmetric{{ $name.Render }} metric{{ $name.Render }}\n\t{{- end }}\n}\n\n// MetricBuilderOption applies changes to default metrics builder.\ntype MetricBuilderOption interface {\n\tapply(*MetricsBuilder)\n}\n\ntype metricBuilderOptionFunc func(mb *MetricsBuilder)\n\nfunc (mbof metricBuilderOptionFunc) apply(mb *MetricsBuilder) {\n\tmbof(mb)\n}\n\n// WithStartTime sets startTime on the metrics builder.\nfunc WithStartTime(startTime pcommon.Timestamp) MetricBuilderOption {\n\treturn metricBuilderOptionFunc(func(mb *MetricsBuilder) {\n\t\tmb.startTime = startTime\n\t})\n}\n\n{{- if or isReceiver isScraper isConnector }}\nfunc NewMetricsBuilder(mbc MetricsBuilderConfig, settings {{ .Status.Class }}.Settings, options ...MetricBuilderOption) *MetricsBuilder {\n\t{{- range $name, $metric := .Metrics }}\n\t{{- if $metric.Warnings.IfEnabled }}\n\tif mbc.Metrics.{{ $name.Render }}.Enabled {\n\t\tsettings.Logger.Warn(\"[WARNING] `{{ $name }}` should not be enabled: {{ $metric.Warnings.IfEnabled }}\")\n\t}\n\t{{- end }}\n\t{{- if $metric.Warnings.IfEnabledNotSet }}\n\tif !mbc.Metrics.{{ $name.Render }}.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] Please set `enabled` field explicitly for `{{ $name }}`: {{ $metric.Warnings.IfEnabledNotSet }}\")\n\t}\n\t{{- end }}\n\t{{- if $metric.Warnings.IfConfigured }}\n\tif mbc.Metrics.{{ $name.Render }}.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] `{{ $name }}` should not be configured: {{ $metric.Warnings.IfConfigured }}\")\n\t}\n\t{{- end }}\n\t{{- end }}\n\t{{- range $name, $attr := .ResourceAttributes }}\n\t{{- if $attr.Warnings.IfEnabled }}\n\tif mbc.ResourceAttributes.{{ $name.Render }}.Enabled {\n\t\tsettings.Logger.Warn(\"[WARNING] `{{ $name }}` should not be enabled: {{ $attr.Warnings.IfEnabled }}\")\n\t}\n\t{{- end }}\n\t{{- if $attr.Warnings.IfEnabledNotSet }}\n\tif !mbc.ResourceAttributes.{{ $name.Render }}.enabledSetByUser {\n\t\tsettings.Logger.Warn(\"[WARNING] Please set `enabled` field explicitly for `{{ $name }}`: {{ $attr.Warnings.IfEnabledNotSet }}\")\n\t}\n\t{{- end }}\n\t{{- if $attr.Warnings.IfConfigured }}\n\tif mbc.ResourceAttributes.{{ $name.Render }}.enabledSetByUser || mbc.ResourceAttributes.{{ $name.Render }}.MetricsInclude != nil || mbc.ResourceAttributes.{{ $name.Render }}.MetricsExclude != nil {\n\t\tsettings.Logger.Warn(\"[WARNING] `{{ $name }}` should not be configured: {{ $attr.Warnings.IfConfigured }}\")\n\t}\n\t{{- end }}\n\t{{- end }}\n\tmb := &MetricsBuilder{\n\t\tconfig:        mbc,\n\t\tstartTime:     pcommon.NewTimestampFromTime(time.Now()),\n\t\tmetricsBuffer: pmetric.NewMetrics(),\n\t\tbuildInfo:     settings.BuildInfo,\n\t\t{{- range $name, $metric := .Metrics }}\n\t\tmetric{{ $name.Render }}: newMetric{{ $name.Render }}(mbc.Metrics.{{ $name.Render }}),\n\t\t{{- end }}\n\t\t{{ if .ResourceAttributes -}}\n\t\tresourceAttributeIncludeFilter: make(map[string]filter.Filter),\n\t\tresourceAttributeExcludeFilter: make(map[string]filter.Filter),\n\t\t{{- end }}\n\t}\n\t{{- range $name, $attr := .ResourceAttributes }}\n\tif mbc.ResourceAttributes.{{ $name.Render }}.MetricsInclude != nil {\n\t\tmb.resourceAttributeIncludeFilter[\"{{ $name }}\"] = filter.CreateFilter(mbc.ResourceAttributes.{{ $name.Render }}.MetricsInclude)\n\t}\n\tif mbc.ResourceAttributes.{{ $name.Render }}.MetricsExclude != nil {\n\t\tmb.resourceAttributeExcludeFilter[\"{{ $name }}\"] = filter.CreateFilter(mbc.ResourceAttributes.{{ $name.Render }}.MetricsExclude)\n\t}\n\t{{- end }}\n\n\tfor _, op := range options {\n\t\top.apply(mb)\n\t}\n\treturn mb\n}\n{{- end }}\n\n{{- if .ResourceAttributes }}\n// NewResourceBuilder returns a new resource builder that should be used to build a resource associated with for the emitted metrics.\nfunc (mb *MetricsBuilder) NewResourceBuilder() *ResourceBuilder {\n\treturn NewResourceBuilder(mb.config.ResourceAttributes)\n}\n{{- end }}\n\n// updateCapacity updates max length of metrics and resource attributes that will be used for the slice capacity.\nfunc (mb *MetricsBuilder) updateCapacity(rm pmetric.ResourceMetrics) {\n\tif mb.metricsCapacity < rm.ScopeMetrics().At(0).Metrics().Len() {\n\t\tmb.metricsCapacity = rm.ScopeMetrics().At(0).Metrics().Len()\n\t}\n}\n\n// ResourceMetricsOption applies changes to provided resource metrics.\ntype ResourceMetricsOption interface {\n\tapply(pmetric.ResourceMetrics)\n}\n\ntype resourceMetricsOptionFunc func(pmetric.ResourceMetrics)\n\nfunc (rmof resourceMetricsOptionFunc) apply(rm pmetric.ResourceMetrics) {\n\trmof(rm)\n}\n\n// WithResource sets the provided resource on the emitted ResourceMetrics.\n// It's recommended to use ResourceBuilder to create the resource.\nfunc WithResource(res pcommon.Resource) ResourceMetricsOption {\n\treturn resourceMetricsOptionFunc(func(rm pmetric.ResourceMetrics) {\n\t\tres.CopyTo(rm.Resource())\n\t})\n}\n\n{{ if .HasEntities -}}\nfunc withResourceMoved(res pcommon.Resource) ResourceMetricsOption {\n\treturn resourceMetricsOptionFunc(func(rm pmetric.ResourceMetrics) {\n\t\tres.MoveTo(rm.Resource())\n\t})\n}\n{{- end }}\n\n// WithStartTimeOverride overrides start time for all the resource metrics data points.\n// This option should be only used if different start time has to be set on metrics coming from different resources.\nfunc WithStartTimeOverride(start pcommon.Timestamp) ResourceMetricsOption {\n\treturn resourceMetricsOptionFunc(func(rm pmetric.ResourceMetrics) {\n\t\tvar dps pmetric.NumberDataPointSlice\n\t\tmetrics := rm.ScopeMetrics().At(0).Metrics()\n\t\tfor i := 0; i < metrics.Len(); i++ {\n\t\t\tswitch metrics.At(i).Type() {\n\t\t\tcase pmetric.MetricTypeGauge:\n\t\t\t\tdps = metrics.At(i).Gauge().DataPoints()\n\t\t\tcase pmetric.MetricTypeSum:\n\t\t\t\tdps = metrics.At(i).Sum().DataPoints()\n\t\t\t}\n\t\t\tfor j := 0; j < dps.Len(); j++ {\n\t\t\t\tdps.At(j).SetStartTimestamp(start)\n\t\t\t}\n\t\t}\n\t})\n}\n\n{{ range $ent := .Entities }}\n{{ $entityType := $ent.Type }}\n{{ $entityStructType := printf \"%sEntity\" (publicVar $entityType) }}\n{{ $builderType := printf \"%sMetricsBuilder\" (publicVar $entityType) }}\n\n// For{{ publicVar $entityType }} returns a {{ $builderType }} that restricts metric recording\n// to metrics belonging to the {{ $entityType }} entity.\nfunc (mb *MetricsBuilder) For{{ publicVar $entityType }}(e *{{ $entityStructType }}) *{{ $builderType }} {\n\treturn &{{ $builderType }}{mb: mb, entity: e}\n}\n{{ end }}\n\n// EmitForResource saves all the generated metrics under a new resource and updates the internal state to be ready for\n// recording another set of data points as part of another resource. This function can be helpful when one scraper\n// needs to emit metrics from several resources. Otherwise calling this function is not required,\n// just `Emit` function can be called instead.\n// Resource attributes should be provided as ResourceMetricsOption arguments.\n{{- if .HasEntities }}\n//\n// Deprecated: Use the For<EntityType> methods to get entity-scoped builders and call Emit() on them instead.\n{{- end }}\nfunc (mb *MetricsBuilder) EmitForResource(options ...ResourceMetricsOption) {\n\trm := pmetric.NewResourceMetrics()\n\t{{- if .SemConvVersion }}\n\trm.SetSchemaUrl(conventions.SchemaURL)\n\t{{- end }}\n\tils := rm.ScopeMetrics().AppendEmpty()\n\tils.Scope().SetName(ScopeName)\n\tils.Scope().SetVersion(mb.buildInfo.Version)\n\tils.Metrics().EnsureCapacity(mb.metricsCapacity)\n\t{{- range $name, $metric := .Metrics }}\n\tmb.metric{{- $name.Render }}.emit(ils.Metrics())\n\t{{- end }}\n\n\tfor _, op := range options {\n\t\top.apply(rm)\n\t}\n\t{{ if .ResourceAttributes -}}\n\tfor attr, filter := range mb.resourceAttributeIncludeFilter {\n\t\tif val, ok := rm.Resource().Attributes().Get(attr); ok && !filter.Matches(val.AsString()) {\n\t\t\treturn\n\t\t}\n\t}\n\tfor attr, filter := range mb.resourceAttributeExcludeFilter {\n\t\tif val, ok := rm.Resource().Attributes().Get(attr); ok && filter.Matches(val.AsString()) {\n\t\t\treturn\n\t\t}\n\t}\n\t{{- end }}\n\n\tif ils.Metrics().Len() > 0 {\n\t\tmb.updateCapacity(rm)\n\t\trm.MoveTo(mb.metricsBuffer.ResourceMetrics().AppendEmpty())\n\t}\n}\n\n// Emit returns all the metrics accumulated by the metrics builder and updates the internal state to be ready for\n// recording another set of metrics. This function will be responsible for applying all the transformations required to\n// produce metric representation defined in metadata and user config, e.g. delta or cumulative.\nfunc (mb *MetricsBuilder) Emit(options ...ResourceMetricsOption) pmetric.Metrics {\n\tmb.EmitForResource(options...)\n\tmetrics := mb.metricsBuffer\n\tmb.metricsBuffer = pmetric.NewMetrics()\n\treturn metrics\n}\n\n{{ range $name, $metric := .Metrics -}}\n// Record{{ $name.Render }}DataPoint adds a data point to {{ $name }} metric.\n{{- if $metric.Entity }}\n//\n// Deprecated: Use mb.For{{ publicVar $metric.Entity }}(entity).Record{{ $name.Render }}DataPoint(...) instead.\n{{- end }}\nfunc (mb *MetricsBuilder) Record{{ $name.Render }}DataPoint(ts pcommon.Timestamp\n\t{{- if $metric.Data.HasMetricInputType }}, inputVal {{ $metric.Data.MetricInputType.String }}\n\t{{- else }}, val {{ $metric.Data.MetricValueType.BasicType }}\n\t{{- end }}\n\t{{- range $metric.Attributes -}}\n\t{{- if not (attributeInfo .).IsConditional -}}\n\t, {{ .RenderUnexported }}AttributeValue {{ if (attributeInfo .).Enum }}Attribute{{ .Render }}{{ else }}{{ (attributeInfo .).Type.Primitive }}{{ end }}\n\t{{- end -}}\n\t{{- end -}}\n\t{{- if $metric.HasConditionalAttributes $.Attributes -}}\n\t, options... MetricAttributeOption\n\t{{- end -}}\n\t)\n\t{{- if $metric.Data.HasMetricInputType }} error{{ end }} {\n\t{{- if $metric.Data.HasMetricInputType }}\n\t{{- if eq $metric.Data.MetricValueType.BasicType \"float64\" }}\n\tval, err := strconv.ParseFloat(inputVal, 64)\n\t{{- else if eq $metric.Data.MetricValueType.BasicType \"int64\" }}\n\tval, err := strconv.ParseInt(inputVal, 10, 64)\n\t{{- end }}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to parse {{ $metric.Data.MetricValueType.BasicType }} for {{ $name.Render }}, value was %s: %w\", inputVal, err)\n\t}\n\t{{- end }}\n\tmb.metric{{ $name.Render }}.recordDataPoint(mb.startTime, ts, val\n\t\t{{- range $metric.Attributes -}}\n\t\t{{- if not (attributeInfo .).IsConditional -}}\n\t\t, {{ .RenderUnexported }}AttributeValue{{ if (attributeInfo .).Enum }}.String(){{ end }}\n\t\t{{- end -}}\n\t\t{{- end -}}\n\t\t{{- if $metric.HasConditionalAttributes $.Attributes -}}\n\t\t, options...\n\t\t{{- end -}}\n\t\t)\n\t{{- if $metric.Data.HasMetricInputType }}\n\treturn nil\n\t{{- end }}\n}\n{{ end }}\n\n// Reset resets metrics builder to its initial state. It should be used when external metrics source is restarted,\n// and metrics builder should update its startTime and reset it's internal state accordingly.\nfunc (mb *MetricsBuilder) Reset(options ...MetricBuilderOption) {\n\tmb.startTime = pcommon.NewTimestampFromTime(time.Now())\n\tfor _, op := range options {\n\t\top.apply(mb)\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/metrics_test.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ .Package }}\n\n{{ $reag := .ReaggregationEnabled }}\n{{- $hasReagMetrics := false }}\n{{- range $name, $metric := .Metrics }}{{- if and $reag (hasAggregatableAttributes $metric.Attributes) }}{{- $hasReagMetrics = true }}{{- end }}{{- end }}\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t{{- if or isReceiver isScraper isConnector }}\n\t\"go.opentelemetry.io/collector/{{ .Status.Class }}/{{ .Status.Class }}test\"\n\t{{- end }}\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n)\n\ntype testDataSet int\n\nconst (\n\ttestDataSetDefault testDataSet = iota\n\ttestDataSetAll\n\ttestDataSetNone\n\t{{- if $reag }}\n\ttestDataSetReag\n\t{{- end }}\n)\n\nfunc TestMetricsBuilder(t *testing.T) {\n\ttests := []struct {\n\t\tname               string\n\t\tmetricsSet         testDataSet\n\t\tresAttrsSet        testDataSet\n\t\texpectEmpty        bool\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t},\n\t\t{\n\t\t\tname:        \"all_set\",\n\t\t\tmetricsSet:  testDataSetAll,\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t},\n\t\t{{- if $reag }}\n\t\t{\n\t\t\tname: \"reaggregate_set\",\n\t\t\tmetricsSet: testDataSetReag,\n\t\t\tresAttrsSet: testDataSetReag,\n\t\t},\n\t\t{{- end }}\n\t\t{\n\t\t\tname:        \"none_set\",\n\t\t\tmetricsSet:  testDataSetNone,\n\t\t\tresAttrsSet: testDataSetNone,\n\t\t\texpectEmpty: true,\n\t\t},\n\t\t{{- if .ResourceAttributes }}\n\t\t{\n\t\t\tname:        \"filter_set_include\",\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t},\n\t\t{\n\t\t\tname:        \"filter_set_exclude\",\n\t\t\tresAttrsSet: testDataSetAll,\n\t\t\texpectEmpty: true,\n\t\t},\n\t\t{{- end }}\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tstart := pcommon.Timestamp(1_000_000_000)\n\t\t\tts := pcommon.Timestamp(1_000_001_000)\n\t\t\tobservedZapCore, observedLogs := observer.New(zap.WarnLevel)\n\t\t\t{{- if or isReceiver isScraper isConnector }}\n\t\t\tsettings := {{ .Status.Class }}test.NewNopSettings({{ .Status.Class }}test.NopType)\n\t\t\t{{- end }}\n\t\t\tsettings.Logger = zap.New(observedZapCore)\n\t\t\tmb := NewMetricsBuilder(loadMetricsBuilderConfig(t, tt.name), settings, WithStartTime(start))\n\n\t\t\t{{- if $hasReagMetrics }}\n\t\t\taggMap := make(map[string]string) // contains the aggregation strategies for each metric name\n\t\t\t{{- range $name, $metric := .Metrics }}\n\t\t\t{{- if hasAggregatableAttributes $metric.Attributes }}\n\t\t\taggMap[\"{{ $name.Render }}\"] = mb.metric{{ $name.Render }}.config.AggregationStrategy\n\t\t\t{{- end }}\n\t\t\t{{- end }}\n\t\t\t{{- end }}\n\n\t\t\texpectedWarnings := 0\n\t\t\t{{- range $name, $metric := .Metrics }}\n\t\t\t{{- if and $metric.Enabled $metric.Warnings.IfEnabled }}\n\t\t\tif tt.metricsSet == testDataSetDefault || tt.metricsSet == testDataSetAll {\n\t\t\t\tassert.Equal(t, \"[WARNING] `{{ $name }}` should not be enabled: {{ $metric.Warnings.IfEnabled }}\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\t{{- end }}\n\t\t\t{{- if $metric.Warnings.IfEnabledNotSet }}\n\t\t\tif tt.metricsSet == testDataSetDefault {\n\t\t\t\tassert.Equal(t, \"[WARNING] Please set `enabled` field explicitly for `{{ $name }}`: {{ $metric.Warnings.IfEnabledNotSet }}\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\t{{- end }}\n\t\t\t{{- if $metric.Warnings.IfConfigured }}\n\t\t\tif tt.metricsSet == testDataSetAll || tt.metricsSet == testDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `{{ $name }}` should not be configured: {{ $metric.Warnings.IfConfigured }}\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\t{{- end }}\n\t\t\t{{- end }}\n\t\t\t{{- range $name, $attr := .ResourceAttributes }}\n\t\t\t{{- if and $attr.Enabled $attr.Warnings.IfEnabled }}\n\t\t\tif tt.resAttrsSet == testDataSetDefault || tt.resAttrsSet == testDataSetAll {\n\t\t\t\tassert.Equal(t, \"[WARNING] `{{ $name }}` should not be enabled: {{ $attr.Warnings.IfEnabled }}\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\t{{- end }}\n\t\t\t{{- if $attr.Warnings.IfEnabledNotSet }}\n\t\t\tif tt.resAttrsSet == testDataSetDefault {\n\t\t\t\tassert.Equal(t, \"[WARNING] Please set `enabled` field explicitly for `{{ $name }}`: {{ $attr.Warnings.IfEnabledNotSet }}\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\t{{- end }}\n\t\t\t{{- if $attr.Warnings.IfConfigured }}\n\t\t\tif tt.resAttrsSet == testDataSetAll || tt.resAttrsSet == testDataSetNone {\n\t\t\t\tassert.Equal(t, \"[WARNING] `{{ $name }}` should not be configured: {{ $attr.Warnings.IfConfigured }}\", observedLogs.All()[expectedWarnings].Message)\n\t\t\t\texpectedWarnings++\n\t\t\t}\n\t\t\t{{- end }}\n\t\t\t{{- end }}\n\n\t\t\t{{- if $reag }}\n\t\t\tif tt.metricsSet != testDataSetReag {\n\t\t\t\tassert.Equal(t, expectedWarnings, observedLogs.Len())\n\t\t\t}\n\t\t\t{{- else }}\n\t\t\tassert.Equal(t, expectedWarnings, observedLogs.Len())\n\t\t\t{{- end }}\n\n\t\t\tdefaultMetricsCount := 0\n\t\t\tallMetricsCount := 0\n\n\t\t\t{{- range $ent := .Entities }}\n\t\t\teb{{ publicVar $ent.Type }} := mb.For{{ publicVar $ent.Type }}(New{{ publicVar $ent.Type }}Entity(\n\t\t\t\t{{- range $i, $idAttr := $ent.Identity -}}\n\t\t\t\t{{- $attr := index $.ResourceAttributes $idAttr.Ref -}}\n\t\t\t\t{{- if $i }}, {{ end -}}{{ $attr.TestValue }}\n\t\t\t\t{{- end -}}\n\t\t\t))\n\t\t\t{{- end }}\n\n\t\t\t{{- range $name, $metric := .Metrics }}\n\n\t\t\t{{ if $metric.Enabled }}defaultMetricsCount++{{ end }}\n\t\t\tallMetricsCount++\n\t\t\t{{ if $metric.Entity }}eb{{ publicVar $metric.Entity }}{{ else }}mb{{ end }}.Record{{ $name.Render }}DataPoint(ts, {{ if $metric.Data.HasMetricInputType }}\"1\"{{ else }}1{{ end }}\n\t\t\t{{- range $metric.Attributes -}}\n\t\t\t{{- if not (attributeInfo .).IsConditional -}}\n\t\t\t\t, {{- template \"getAttributeValue\" . -}}\n\t\t\t{{- end -}}\n\t\t\t{{- end -}}\n\t\t\t{{- range $metric.Attributes -}}\n\t\t\t{{- if (attributeInfo .).IsConditional -}}\n\t\t\t\t, With{{ .Render }}MetricAttribute({{- template \"getAttributeValue\" . -}})\n\t\t\t{{- end -}}\n\t\t\t{{- end -}}\n\t\t\t)\n\t\t\t{{- if and $reag (hasAggregatableAttributes $metric.Attributes) }}\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\t{{ if $metric.Entity }}eb{{ publicVar $metric.Entity }}{{ else }}mb{{ end }}.Record{{ $name.Render }}DataPoint(ts, {{ if $metric.Data.HasMetricInputType }}\"3\"{{ else }}3{{ end }}\n\t\t\t\t{{- range $metric.Attributes -}}\n\t\t\t\t{{- if not (attributeInfo .).IsConditional -}}\n\t\t\t\t\t{{- if (attributeInfo .).IsRequired -}}\n\t\t\t\t\t, {{- template \"getAttributeValue\" . -}}\n\t\t\t\t\t{{- else -}}\n\t\t\t\t\t, {{- template \"getAttributeValueTwo\" . -}}\n\t\t\t\t\t{{- end -}}\n\t\t\t\t{{- end -}}\n\t\t\t\t{{- end -}}\n\t\t\t\t{{- range $metric.Attributes -}}\n\t\t\t\t{{- if (attributeInfo .).IsConditional -}}\n\t\t\t\t\t, With{{ .Render }}MetricAttribute({{- template \"getAttributeValue\" . -}})\n\t\t\t\t{{- end -}}\n\t\t\t\t{{- end -}}\n\t\t\t\t)\n\t\t\t}\n\t\t\t{{- end }}\n\t\t\t{{- end }}\n\n\t\t\t{{- range $ent := .Entities }}\n\t\t\teb{{ publicVar $ent.Type }}.Emit()\n\t\t\t{{- end }}\n\n\t\t\t{{ if .ResourceAttributes }}\n\t\t\trb := mb.NewResourceBuilder()\n\t\t\t{{- range $name, $attr := .ResourceAttributes }}\n\t\t\t{{- if $attr.Enum }}\n\t\t\trb.Set{{ $attr.Name.Render }}{{ index $attr.Enum 0 | publicVar }}()\n\t\t\t{{- else }}\n\t\t\trb.Set{{ $attr.Name.Render }}({{ $attr.TestValue }})\n\t\t\t{{- end }}\n\t\t\t{{- end }}\n\t\t\tres := rb.Emit()\n\t\t\t{{- else }}\n\t\t\tres := pcommon.NewResource()\n\t\t\t{{- end }}\n\t\t\tmetrics := mb.Emit(WithResource(res))\n\t\t\t{{- if $reag }}\n\t\t\tif tt.name == \"reaggregate_set\" {\n\t\t\t\t{{- range $name, $metric := .Metrics }}\n\t\t\t\t{{- if hasAggregatableAttributes $metric.Attributes }}\n\t\t\t\tassert.Empty(t, mb.metric{{ $name.Render }}.aggDataPoints)\n\t\t\t\t{{- end }}\n\t\t\t\t{{- end }}\n\t\t\t}\n\t\t\t{{- end }}\n\n\t\t\tif tt.expectEmpty {\n\t\t\t\tassert.Equal(t, 0, metrics.ResourceMetrics().Len())\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tvar allMetricsList []pmetric.Metric\n\t\t\ttotalMetricsCount := 0\n\t\t\tfor ri := 0; ri < metrics.ResourceMetrics().Len(); ri++ {\n\t\t\t\trm := metrics.ResourceMetrics().At(ri)\n\t\t\t\tassert.Equal(t, 1, rm.ScopeMetrics().Len())\n\t\t\t\tms := rm.ScopeMetrics().At(0).Metrics()\n\t\t\t\ttotalMetricsCount += ms.Len()\n\t\t\t\tfor mi := 0; mi < ms.Len(); mi++ {\n\t\t\t\t\tallMetricsList = append(allMetricsList, ms.At(mi))\n\t\t\t\t}\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetDefault {\n\t\t\t\tassert.Equal(t, defaultMetricsCount, totalMetricsCount)\n\t\t\t}\n\t\t\tif tt.metricsSet == testDataSetAll {\n\t\t\t\tassert.Equal(t, allMetricsCount, totalMetricsCount)\n\t\t\t}\n\t\t\tvalidatedMetrics := make(map[string]bool)\n\t\t\tfor _, mi := range allMetricsList {\n\t\t\t\tswitch mi.Name() {\n\t\t\t\t{{- range $name, $metric := .Metrics }}\n\t\t\t\tcase \"{{ $name }}\":\n\t\t\t\t\t{{- if and $reag (hasAggregatableAttributes $metric.Attributes) }}\n\t\t\t\t\tif tt.name != \"reaggregate_set\" {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"{{ $name }}\"], \"Found a duplicate in the metrics slice: {{ $name }}\")\n\t\t\t\t\t\tvalidatedMetrics[\"{{ $name }}\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricType{{ $metric.Data.Type }}, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.{{ $metric.Data.Type }}().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"{{ $metric.Description }}\", mi.Description())\n\t\t\t\t\t\t{{- if len $metric.Unit}}\n\t\t\t\t\t\tassert.Equal(t, \"{{ $metric.Unit }}\", mi.Unit())\n\t\t\t\t\t\t{{- else }}\n\t\t\t\t\t\tassert.Empty(t, mi.Unit())\n\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\t{{- if $metric.Data.HasMonotonic }}\n\t\t\t\t\t\tassert.{{- if $metric.Data.Monotonic }}True{{ else }}False{{ end }}(t, mi.{{ $metric.Data.Type }}().IsMonotonic())\n\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\t{{- if $metric.Data.HasAggregated }}\n\t\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporality{{ $metric.Data.AggregationTemporality }}, mi.{{ $metric.Data.Type }}().AggregationTemporality())\n\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\tdp := mi.{{ $metric.Data.Type }}().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueType{{ $metric.Data.MetricValueType }}, dp.ValueType())\n\t\t\t\t\t\t{{- if eq $metric.Data.MetricValueType.BasicType \"float64\" }}\n\t\t\t\t\t\tassert.InDelta(t, {{ $metric.Data.MetricValueType.BasicType }}(1), dp.{{ $metric.Data.MetricValueType }}Value(), 0.01)\n\t\t\t\t\t\t{{- else }}\n\t\t\t\t\t\tassert.Equal(t, {{ $metric.Data.MetricValueType.BasicType }}(1), dp.{{ $metric.Data.MetricValueType }}Value())\n\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\t{{- range $i, $attr := $metric.Attributes }}\n\t\t\t\t\t\t{{- if ne (attributeInfo $attr).RequirementLevel.String \"Opt-In\" }}\n\t\t\t\t\t\t{{ $attr.RenderUnexported }}AttrVal, ok := dp.Attributes().Get(\"{{ (attributeInfo $attr).Name }}\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\t{{- template \"assertMetricAttributeValue\" $attr }}\n\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.False(t, validatedMetrics[\"{{ $name }}\"], \"Found a duplicate in the metrics slice: {{ $name }}\")\n\t\t\t\t\t\tvalidatedMetrics[\"{{ $name }}\"] = true\n\t\t\t\t\t\tassert.Equal(t, pmetric.MetricType{{ $metric.Data.Type }}, mi.Type())\n\t\t\t\t\t\tassert.Equal(t, 1, mi.{{ $metric.Data.Type }}().DataPoints().Len())\n\t\t\t\t\t\tassert.Equal(t, \"{{ $metric.Description }}\", mi.Description())\n\t\t\t\t\t\t{{- if len $metric.Unit}}\n\t\t\t\t\t\tassert.Equal(t, \"{{ $metric.Unit }}\", mi.Unit())\n\t\t\t\t\t\t{{- else }}\n\t\t\t\t\t\tassert.Empty(t, mi.Unit())\n\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\t{{- if $metric.Data.HasMonotonic }}\n\t\t\t\t\t\tassert.{{- if $metric.Data.Monotonic }}True{{ else }}False{{ end }}(t, mi.{{ $metric.Data.Type }}().IsMonotonic())\n\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\t{{- if $metric.Data.HasAggregated }}\n\t\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporality{{ $metric.Data.AggregationTemporality }}, mi.{{ $metric.Data.Type }}().AggregationTemporality())\n\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\tdp := mi.{{ $metric.Data.Type }}().DataPoints().At(0)\n\t\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueType{{ $metric.Data.MetricValueType }}, dp.ValueType())\n\t\t\t\t\t\tswitch aggMap[\"{{ $name }}\"] {\n\t\t\t\t\t\tcase \"sum\":\n\t\t\t\t\t\t\t{{- if eq $metric.Data.MetricValueType.BasicType \"float64\" }}\n\t\t\t\t\t\t\tassert.InDelta(t, {{ $metric.Data.MetricValueType.BasicType }}(4), dp.{{ $metric.Data.MetricValueType }}Value(), 0.01)\n\t\t\t\t\t\t\t{{- else }}\n\t\t\t\t\t\t\tassert.Equal(t, {{ $metric.Data.MetricValueType.BasicType }}(4), dp.{{ $metric.Data.MetricValueType }}Value())\n\t\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\tcase \"avg\":\n\t\t\t\t\t\t\t{{- if eq $metric.Data.MetricValueType.BasicType \"float64\" }}\n\t\t\t\t\t\t\tassert.InDelta(t, {{ $metric.Data.MetricValueType.BasicType }}(2), dp.{{ $metric.Data.MetricValueType }}Value(), 0.01)\n\t\t\t\t\t\t\t{{- else }}\n\t\t\t\t\t\t\tassert.Equal(t, {{ $metric.Data.MetricValueType.BasicType }}(2), dp.{{ $metric.Data.MetricValueType }}Value())\n\t\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\tcase \"min\":\n\t\t\t\t\t\t\t{{- if eq $metric.Data.MetricValueType.BasicType \"float64\" }}\n\t\t\t\t\t\t\tassert.InDelta(t, {{ $metric.Data.MetricValueType.BasicType }}(1), dp.{{ $metric.Data.MetricValueType }}Value(), 0.01)\n\t\t\t\t\t\t\t{{- else }}\n\t\t\t\t\t\t\tassert.Equal(t, {{ $metric.Data.MetricValueType.BasicType }}(1), dp.{{ $metric.Data.MetricValueType }}Value())\n\t\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\tcase \"max\":\n\t\t\t\t\t\t\t{{- if eq $metric.Data.MetricValueType.BasicType \"float64\" }}\n\t\t\t\t\t\t\tassert.InDelta(t, {{ $metric.Data.MetricValueType.BasicType }}(3), dp.{{ $metric.Data.MetricValueType }}Value(), 0.01)\n\t\t\t\t\t\t\t{{- else }}\n\t\t\t\t\t\t\tassert.Equal(t, {{ $metric.Data.MetricValueType.BasicType }}(3), dp.{{ $metric.Data.MetricValueType }}Value())\n\t\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\t}\n\t\t\t\t\t\t{{- range $i, $attr := $metric.Attributes }}\n\t\t\t\t\t\t{{- if eq (attributeInfo $attr).RequirementLevel.String \"Required\" }}\n\t\t\t\t\t\t_, ok {{ if eq $i 0 }}:{{ end }}= dp.Attributes().Get(\"{{ (attributeInfo $attr).Name }}\")\n\t\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t\t{{- else if eq (attributeInfo $attr).RequirementLevel.String \"Conditionally Required\" }}\n\t\t\t\t\t\t{{- else }}\n\t\t\t\t\t\t_, ok {{ if eq $i 0 }}:{{ end }}= dp.Attributes().Get(\"{{ (attributeInfo $attr).Name }}\")\n\t\t\t\t\t\tassert.False(t, ok)\n\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t\t{{- end }}\n\t\t\t\t\t}\n\t\t\t\t\t{{- else }}\n\t\t\t\t\tassert.False(t, validatedMetrics[\"{{ $name }}\"], \"Found a duplicate in the metrics slice: {{ $name }}\")\n\t\t\t\t\tvalidatedMetrics[\"{{ $name }}\"] = true\n\t\t\t\t\tassert.Equal(t, pmetric.MetricType{{ $metric.Data.Type }}, mi.Type())\n\t\t\t\t\tassert.Equal(t, 1, mi.{{ $metric.Data.Type }}().DataPoints().Len())\n\t\t\t\t\tassert.Equal(t, \"{{ $metric.Description }}\", mi.Description())\n\t\t\t\t\t{{- if len $metric.Unit}}\n\t\t\t\t\tassert.Equal(t, \"{{ $metric.Unit }}\", mi.Unit())\n\t\t\t\t\t{{- else }}\n\t\t\t\t\tassert.Empty(t, mi.Unit())\n\t\t\t\t\t{{- end }}\n\t\t\t\t\t{{- if $metric.Data.HasMonotonic }}\n\t\t\t\t\tassert.{{- if $metric.Data.Monotonic }}True{{ else }}False{{ end }}(t, mi.{{ $metric.Data.Type }}().IsMonotonic())\n\t\t\t\t\t{{- end }}\n\t\t\t\t\t{{- if $metric.Data.HasAggregated }}\n\t\t\t\t\tassert.Equal(t, pmetric.AggregationTemporality{{ $metric.Data.AggregationTemporality }}, mi.{{ $metric.Data.Type }}().AggregationTemporality())\n\t\t\t\t\t{{- end }}\n\t\t\t\t\tdp := mi.{{ $metric.Data.Type }}().DataPoints().At(0)\n\t\t\t\t\tassert.Equal(t, start, dp.StartTimestamp())\n\t\t\t\t\tassert.Equal(t, ts, dp.Timestamp())\n\t\t\t\t\tassert.Equal(t, pmetric.NumberDataPointValueType{{ $metric.Data.MetricValueType }}, dp.ValueType())\n\t\t\t\t\t{{- if eq $metric.Data.MetricValueType.BasicType \"float64\" }}\n\t\t\t\t\tassert.InDelta(t, {{ $metric.Data.MetricValueType.BasicType }}(1), dp.{{ $metric.Data.MetricValueType }}Value(), 0.01)\n\t\t\t\t\t{{- else }}\n\t\t\t\t\tassert.Equal(t, {{ $metric.Data.MetricValueType.BasicType }}(1), dp.{{ $metric.Data.MetricValueType }}Value())\n\t\t\t\t\t{{- end }}\n\n\t\t\t\t\t{{- range $i, $attr := $metric.Attributes }}\n\t\t\t\t\t{{ $attr.RenderUnexported }}AttrVal, ok := dp.Attributes().Get(\"{{ (attributeInfo $attr).Name }}\")\n\t\t\t\t\tassert.True(t, ok)\n\t\t\t\t\t{{- template \"assertMetricAttributeValue\" $attr }}\n\t\t\t\t\t{{- end }}\n\t\t\t\t\t{{- end }}\n\t\t\t\t\t{{- end }}\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/package_test.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ if isCommand -}}main{{ else }}{{ .Package }}{{- end }}\n\nimport (\n\t{{- if .Tests.GoLeak.Skip }}\n\t\"os\"\n\t{{- end }}\n\t\"testing\"\n\n\t{{- if not .Tests.GoLeak.Skip }}\n\t\"go.uber.org/goleak\"\n\t{{- end }}\n)\n\nfunc TestMain(m *testing.M) {\n\t{{- if .Tests.GoLeak.Setup }}\n\t{{.Tests.GoLeak.Setup}}\n\t{{- end }}\n\t{{- if .Tests.GoLeak.Skip }}\n\t// skipping goleak test as per metadata.yml configuration\n\tos.Exit(m.Run())\n\t{{- else }}\n\tgoleak.VerifyTestMain(m {{- range $val := .Tests.GoLeak.Ignore.Top}}, goleak.IgnoreTopFunction(\"{{$val}}\"){{end}}{{- range $val := .Tests.GoLeak.Ignore.Any}}, goleak.IgnoreAnyFunction(\"{{$val}}\"){{end}} )\n\t{{- end }}\n\t{{- if .Tests.GoLeak.Teardown }}\n\t{{.Tests.GoLeak.Teardown}}\n\t{{- end }}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/readme.md.tmpl",
    "content": "<!-- status autogenerated section -->\n{{- if .DisplayName }}\n# {{ .DisplayName }}\n{{- end }}\n{{- if .Description }}\n\n{{ .Description }}\n{{ end -}}\n{{- if len .Status.Stability }}\n| Status        |           |\n| ------------- |-----------|\n{{- $class := .Status.Class }}\n{{- $shortName := .ShortFolderName }}\n{{- if ne $class \"connector\" }}\n{{- $idx := 0 }}\n{{- range $stability, $value := .Status.Stability }}\n| {{ if not $idx }}Stability{{ else }}         {{ end }}     | [{{ toLowerCase $stability.String }}]{{ if and (ne $class \"extension\") (ne $class \"converter\") (ne $class \"provider\") }}: {{ stringsJoin $value \", \" }} {{ end }}  |\n{{- $idx = inc $idx }}\n{{- end }}\n{{- if .Status.Deprecation }}\n{{- range $deprecation, $value := .Status.Deprecation }}\n| Deprecation of {{ toLowerCase $deprecation }} | [Date]: {{ $value.Date }}{{ if and (ne $class \"extension\") (ne $class \"converter\") (ne $class \"provider\") }} {{ end }}  |\n|                      | [Migration Note]: {{ $value.Migration }}{{ if ne $class \"extension\" }} {{ end }}  |\n{{- end }}\n{{- end }}\n{{- end}}\n{{- if .Status.UnsupportedPlatforms }}\n| Unsupported Platforms | {{ stringsJoin .Status.UnsupportedPlatforms \", \" }} |\n{{- end }}\n{{- if and (ne $class \"cmd\") (ne $class \"pkg\")  }}\n| Distributions | [{{ stringsJoin .Status.SortedDistributions \"], [\" }}] |\n{{- end }}\n{{- if .Status.Warnings }}\n| Warnings      | [{{ stringsJoin .Status.Warnings \", \" }}](#warnings) |\n{{- end }}\n{{- if ne $class \"\" }}\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/{{ .GithubProject }}?query=is%3Aissue%20is%3Aopen%20label%3A{{ $class }}%2F{{ $shortName }}%20&label=open&color=orange&logo=opentelemetry)](https://github.com/{{ .GithubProject }}/issues?q=is%3Aopen+is%3Aissue+label%3A{{ $class }}%2F{{ $shortName }}) [![Closed issues](https://img.shields.io/github/issues-search/{{ .GithubProject }}?query=is%3Aissue%20is%3Aclosed%20label%3A{{ $class }}%2F{{ $shortName }}%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/{{ .GithubProject }}/issues?q=is%3Aclosed+is%3Aissue+label%3A{{ $class }}%2F{{ $shortName }}) |\n{{- if not .Status.DisableCodeCov }}\n| Code coverage | [![codecov](https://codecov.io/github/{{ .GithubProject }}/graph/main/badge.svg?component={{ .GetCodeCovComponentID }})](https://app.codecov.io/gh/{{ .GithubProject}}/tree/main/?components%5B0%5D={{ .GetCodeCovComponentID }}&displayType=list) |\n{{- end }}\n{{- end }}\n{{- if .Status.Codeowners }}\n{{- $codeowners := userLinks .Status.Codeowners.Active }}\n{{- $emeritus := userLinks .Status.Codeowners.Emeritus }}\n| [Code Owners](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/CONTRIBUTING.md#becoming-a-code-owner)    | {{ stringsJoin $codeowners \", \" }} {{ if .Status.Codeowners.SeekingNew }}\\| Seeking more code owners! {{ end }}|\n{{- if $emeritus }}\n| Emeritus      | {{ stringsJoin $emeritus \", \" }} |\n{{- end }}\n{{- end }}\n{{range $stability, $val := .Status.Stability}}\n[{{ toLowerCase $stability.String }}]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#{{ toLowerCase $stability.String }}\n{{- end }}\n{{- if .Status.Deprecation }}\n[Date]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#deprecation-information\n[Migration Note]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#deprecation-information\n{{- end }}\n{{- range .Status.SortedDistributions }}\n[{{.}}]: {{ distroURL . }}\n{{- end }}\n{{- if eq $class \"connector\"}}\n\n## Supported Pipeline Types\n\n| [Exporter Pipeline Type] | [Receiver Pipeline Type] | [Stability Level] |\n| ------------------------ | ------------------------ | ----------------- |\n{{- range $stability, $pipelines := .Status.Stability }}\n{{- range $pipeline := $pipelines }}\n{{- $parts := stringsSplit $pipeline \"_to_\"  }}\n| {{index $parts 0}} | {{index $parts 1}} | [{{ toLowerCase $stability.String }}] |\n{{- end }}\n{{- end }}\n\n[Exporter Pipeline Type]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/connector/README.md#exporter-pipeline-type\n[Receiver Pipeline Type]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/connector/README.md#receiver-pipeline-type\n[Stability Level]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stability-levels\n{{- end }}\n{{- end }}\n<!-- end autogenerated section -->"
  },
  {
    "path": "cmd/mdatagen/internal/templates/resource.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ .Package }}\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ResourceBuilder is a helper struct to build resources predefined in metadata.yaml.\n// The ResourceBuilder is not thread-safe and must not to be used in multiple goroutines.\ntype ResourceBuilder struct {\n\tconfig ResourceAttributesConfig\n\tres\tpcommon.Resource\n}\n\n// NewResourceBuilder creates a new ResourceBuilder. This method should be called on the start of the application.\nfunc NewResourceBuilder(rac ResourceAttributesConfig) *ResourceBuilder {\n\treturn &ResourceBuilder{\n\t\tconfig: rac,\n\t\tres: pcommon.NewResource(),\n\t}\n}\n\n{{- range $name, $attr := .ResourceAttributes }}\n{{- range $attr.Enum }}\n// Set{{ $name.Render }}{{ . | publicVar }} sets \"{{ $name }}={{ . }}\" attribute.\nfunc (rb *ResourceBuilder) Set{{ $name.Render }}{{ . | publicVar }}() {\n\tif rb.config.{{ $name.Render }}.Enabled {\n\t\trb.res.Attributes().PutStr(\"{{ $name }}\", \"{{ . }}\")\n\t}\n}\n{{- else }}\n// Set{{ $name.Render }} sets provided value as \"{{ $name }}\" attribute.\nfunc (rb *ResourceBuilder) Set{{ $name.Render }}(val {{ $attr.Type.Primitive }}) {\n\tif rb.config.{{ $name.Render }}.Enabled {\n\t\t{{- if or (eq $attr.Type.String \"Bytes\") (eq $attr.Type.String \"Slice\") (eq $attr.Type.String \"Map\") }}\n\t\trb.res.Attributes().PutEmpty{{ $attr.Type }}(\"{{ $name }}\").FromRaw(val)\n\t\t{{- else }}\n\t\trb.res.Attributes().Put{{ $attr.Type }}(\"{{ $name }}\", val)\n\t\t{{- end }}\n\t}\n}\n{{- end }}\n{{ end }}\n\n\n// Emit returns the built resource and resets the internal builder state.\nfunc (rb *ResourceBuilder) Emit() pcommon.Resource {\n\tr := rb.res\n\trb.res = pcommon.NewResource()\n\treturn r\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/resource_test.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ .Package }}\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n{{- $enabledAttrCount := 0 }}\n{{- range $_, $attr := .ResourceAttributes }}\n{{- if $attr.Enabled }}\n{{- $enabledAttrCount = inc $enabledAttrCount }}\n{{- end }}\n{{- end }}\n\nfunc TestResourceBuilder(t *testing.T) {\n\tfor _, tt := range []string{\"default\", \"all_set\", \"none_set\"} {\n\t\tt.Run(tt, func(t *testing.T) {\n\t\t\tcfg := loadResourceAttributesConfig(t, tt)\n\t\t\trb := NewResourceBuilder(cfg)\n\t\t\t{{- range $name, $attr := .ResourceAttributes }}\n\t\t\t{{- if $attr.Enum }}\n\t\t\trb.Set{{ $name.Render }}{{ index $attr.Enum 0 | publicVar }}()\n\t\t\t{{- else }}\n\t\t\trb.Set{{ $name.Render }}({{ $attr.TestValue }})\n\t\t\t{{- end }}\n\t\t\t{{- end }}\n\n\t\t\tres := rb.Emit()\n\t\t\tassert.Equal(t, 0, rb.Emit().Attributes().Len()) // Second call should return empty Resource\n\n\t\t\tswitch tt {\n\t\t\tcase \"default\":\n\t\t\t\tassert.Equal(t, {{ $enabledAttrCount }}, res.Attributes().Len())\n\t\t\tcase \"all_set\":\n\t\t\t\tassert.Equal(t, {{ len .ResourceAttributes }}, res.Attributes().Len())\n\t\t\tcase \"none_set\":\n\t\t\t\tassert.Equal(t, 0, res.Attributes().Len())\n\t\t\t\treturn\n\t\t\tdefault:\n\t\t\t\tassert.Failf(t, \"unexpected test case: %s\", tt)\n\t\t\t}\n\n\t\t\t{{- range $name, $attr := .ResourceAttributes }}\n\t\t\t{{ $name.RenderUnexported }}AttrVal, ok := res.Attributes().Get(\"{{ $name }}\")\n\t\t\t{{- if $attr.Enabled }}\n\t\t\tassert.True(t, ok)\n\t\t\t{{- else }}\n\t\t\tassert.Equal(t, tt == \"all_set\", ok)\n\t\t\t{{- end }}\n\t\t\tif ok {\n\t\t\t\t{{- template \"assertResourceAttributeValue\" $attr }}\n\t\t\t}\n\t\t\t{{- end }}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/status.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ .Package }}\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType           = component.MustNewType(\"{{ .Type }}\")\n{{-\tif .DeprecatedType }}\n\tDeprecatedType = component.MustNewType(\"{{ .DeprecatedType }}\")\n{{- end }}\n\tScopeName      = \"{{ .ScopeName }}\"\n)\n\nconst (\n\t{{- range $stability, $signals := .Status.Stability }}\n\t{{- range $signal := $signals }}\n\t{{ toCamelCase $signal }}Stability = component.StabilityLevel{{ casesTitle $stability.String }}\n\t{{- end }}\n\t{{- end }}\n)\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/telemetry.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ .Package }}\n\nimport (\n\t{{- if .Telemetry.Metrics }}\n\t{{- range $_, $metric := .Telemetry.Metrics }}\n\t{{- if $metric.Data.Async }}\n\t\"context\"\n\t{{- break}}\n\t{{- end }}\n\t{{- end }}\n\t\"errors\"\n\t\"sync\"\n\t{{- end }}\n\n\t\"go.opentelemetry.io/otel/metric\"\n\t{{- if .Telemetry.Metrics }}\n\t{{- range $_, $metric := .Telemetry.Metrics }}\n\t{{- if $metric.Data.Async }}\n\t\"go.opentelemetry.io/otel/metric/embedded\"\n\t{{- break}}\n\t{{- end }}\n\t{{- end }}\n\t{{- end }}\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc Meter(settings component.TelemetrySettings) metric.Meter {\n\treturn settings.MeterProvider.Meter(\"{{ .ScopeName }}\")\n}\n\nfunc Tracer(settings component.TelemetrySettings) trace.Tracer {\n\treturn settings.TracerProvider.Tracer(\"{{ .ScopeName }}\")\n}\n{{- if .Telemetry.Metrics }}\n\n// TelemetryBuilder provides an interface for components to report telemetry\n// as defined in metadata and user config.\ntype TelemetryBuilder struct {\n\tmeter metric.Meter\n\tmu sync.Mutex\n\tregistrations []metric.Registration\n\t{{- range $name, $metric := .Telemetry.Metrics }}\n\t{{ $name.Render }} metric.{{ $metric.Data.Instrument }}\n\t{{- if and ($metric.Data.Async) (not $metric.Optional) }}\n\t{{- end }}\n\t{{- end }}\n}\n\n// TelemetryBuilderOption applies changes to default builder.\ntype TelemetryBuilderOption interface {\n\tapply(*TelemetryBuilder)\n}\n\ntype telemetryBuilderOptionFunc func(mb *TelemetryBuilder)\n\nfunc (tbof telemetryBuilderOptionFunc) apply(mb *TelemetryBuilder) {\n\ttbof(mb)\n}\n\n{{- range $name, $metric := .Telemetry.Metrics }}\n\t{{ if $metric.Data.Async -}}\n// Register{{ $name.Render }}Callback sets callback for observable {{ $name.Render }} metric.\nfunc (builder *TelemetryBuilder) Register{{ $name.Render }}Callback(cb metric.{{ casesTitle $metric.Data.BasicType }}Callback) error {\n\treg, err := builder.meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {\n\t\t\tcb(ctx, &observer{{ casesTitle $metric.Data.BasicType }}{inst : builder.{{ $name.Render }}, obs: o})\n\t\t\treturn nil\n\t\t}, builder.{{ $name.Render }})\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tbuilder.registrations = append(builder.registrations, reg)\n\treturn nil\n}\n\t{{- end }}\n\n{{- end }}\n\n{{- range $name, $metric := .Telemetry.Metrics }}\n{{- if $metric.Data.Async }}\n\t{{ if eq $metric.Data.BasicType \"int64\" -}}\ntype observerInt64 struct {\n\tembedded.Int64Observer\n\tinst metric.Int64Observable\n\tobs metric.Observer\n}\n\nfunc (oi *observerInt64) Observe(value int64, opts ...metric.ObserveOption) {\n\toi.obs.ObserveInt64(oi.inst, value, opts...)\n}\n\t\t{{ break }}\n\t{{- end }}\n{{- end }}\n{{- end }}\n\n{{- range $name, $metric := .Telemetry.Metrics }}\n{{- if $metric.Data.Async }}\n{{ if eq $metric.Data.BasicType \"float64\" -}}\ntype observerFloat64 struct {\n\tembedded.Float64Observer\n\tinst metric.Float64Observable\n\tobs metric.Observer\n}\n\nfunc (oi *observerFloat64) Observe(value float64, opts ...metric.ObserveOption) {\n\toi.obs.ObserveFloat64(oi.inst, value, opts...)\n}\n{{ break }}\n{{- end }}\n{{- end }}\n{{- end }}\n\n// Shutdown unregister all registered callbacks for async instruments.\nfunc (builder *TelemetryBuilder) Shutdown() {\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tfor _, reg := range builder.registrations {\n\t\treg.Unregister()\n\t}\n}\n\n// NewTelemetryBuilder provides a struct with methods to update all internal telemetry\n// for a component\nfunc NewTelemetryBuilder(settings component.TelemetrySettings, options ...TelemetryBuilderOption) (*TelemetryBuilder, error) {\n\tbuilder := TelemetryBuilder{}\n\tfor _, op := range options {\n\t\top.apply(&builder)\n\t}\n\tbuilder.meter = Meter(settings)\n\tvar err, errs error\n\n\t{{- range $name, $metric := .Telemetry.Metrics }}\n\tbuilder.{{ $name.Render }}, err = builder.meter.{{ $metric.Data.Instrument }}(\n\t\t{{ if $metric.Prefix -}}\n\t\t\"{{ $metric.Prefix }}{{ $name }}\",\n\t\t{{ else -}}\n\t\t\"otelcol_{{ $name }}\",\n\t\t{{ end -}}\n\t\tmetric.WithDescription(\"{{ $metric.Description }} [{{ $metric.Stability }}]\"),\n\t\tmetric.WithUnit(\"{{ $metric.Unit }}\"),\n\t\t{{ if eq $metric.Data.Type \"Histogram\" -}}\n\t\t{{- if $metric.Data.Boundaries -}}metric.WithExplicitBucketBoundaries([]float64{ {{- range $metric.Data.Boundaries }} {{.}}, {{- end }} }...),{{- end }}\n\t\t{{- end }}\n\t)\n\terrs = errors.Join(errs, err)\n\t{{- end }}\n\treturn &builder, errs\n}\n\n{{- end }}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/telemetry_test.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ .Package }}\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/metric\"\n\tembeddedmetric \"go.opentelemetry.io/otel/metric/embedded\"\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\t\"go.opentelemetry.io/otel/trace\"\n\tembeddedtrace \"go.opentelemetry.io/otel/trace/embedded\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\ntype mockMeter struct {\n\tnoopmetric.Meter\n\tname string\n}\ntype mockMeterProvider struct {\n\tembeddedmetric.MeterProvider\n}\n\nfunc (m mockMeterProvider) Meter(name string, opts ...metric.MeterOption) metric.Meter {\n\treturn mockMeter{name: name}\n}\n\ntype mockTracer struct {\n\tnooptrace.Tracer\n\tname string\n}\n\ntype mockTracerProvider struct {\n\tembeddedtrace.TracerProvider\n}\n\nfunc (m mockTracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer {\n\treturn mockTracer{name: name}\n}\n\nfunc TestProviders(t *testing.T) {\n\tset := component.TelemetrySettings{\n\t\tMeterProvider: mockMeterProvider{},\n\t\tTracerProvider: mockTracerProvider{},\n\t}\n\n\tmeter := Meter(set)\n\tif m, ok := meter.(mockMeter); ok {\n\t\trequire.Equal(t, \"{{ .ScopeName }}\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockMeter\")\n\t}\n\n\ttracer := Tracer(set)\n\tif m, ok := tracer.(mockTracer); ok {\n\t\trequire.Equal(t, \"{{ .ScopeName }}\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockTracer\")\n\t}\n}\n{{- if .Telemetry.Metrics }}\n\nfunc TestNewTelemetryBuilder(t *testing.T) {\n\tset := componenttest.NewNopTelemetrySettings()\n\tapplied := false\n\t_, err := NewTelemetryBuilder(set, telemetryBuilderOptionFunc(func(b *TelemetryBuilder) {\n\t\tapplied = true\n\t}))\n\trequire.NoError(t, err)\n\trequire.True(t, applied)\n}\n\n{{- end }}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/telemetrytest.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ .Package }}test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t{{- if or isConnector isExporter isExtension isProcessor isReceiver isScraper }}\n\t\"go.opentelemetry.io/collector/component\"\n\t{{- end }}\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t{{- if or isConnector isExporter isExtension isProcessor isReceiver isScraper }}\n\t\"go.opentelemetry.io/collector/{{ .Status.Class }}\"\n\t\"go.opentelemetry.io/collector/{{ .Status.Class }}/{{ .Status.Class }}test\"\n\t{{- end }}\n)\n\n{{ if or isConnector isExporter isExtension isProcessor isReceiver isScraper }}\nfunc NewSettings(tt *componenttest.Telemetry) {{ .Status.Class }}.Settings {\nset := {{ .Status.Class }}test.NewNopSettings({{ .Status.Class }}test.NopType)\nset.ID = component.NewID(component.MustNewType(\"{{ .Type }}\"))\nset.TelemetrySettings = tt.NewTelemetrySettings()\nreturn set\n}\n{{- end }}\n\n{{ range $name, $metric := .Telemetry.Metrics }}\n\nfunc AssertEqual{{ $name.Render }}(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.{{- if eq $metric.Data.Type \"Histogram\" }} {{$metric.Data.Type}} {{- end }}DataPoint[{{ $metric.Data.BasicType }}], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\t{{ if $metric.Prefix -}}\n\t\tName:        \"{{ $metric.Prefix }}{{ $name }}\",\n\t\t{{ else -}}\n\t\tName:        \"otelcol_{{ $name }}\",\n\t\t{{ end -}}\n\t\tDescription: \"{{ $metric.Description }} [{{ $metric.Stability }}]\",\n\t\tUnit:        \"{{ $metric.Unit }}\",\n\t\tData:        metricdata.{{ $metric.Data.Type }}[{{ $metric.Data.BasicType }}]{\n\t\t\t{{- if $metric.Data.HasAggregated }}\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\t{{- end }}\n\t\t\t{{- if $metric.Data.HasMonotonic }}\n\t\t\tIsMonotonic: {{ $metric.Data.Monotonic }},\n\t\t\t{{- end }}\n\t\t\tDataPoints: dps,\n\t\t},\n\t}\n\t{{ if $metric.Prefix -}}\n\tgot, err := tt.GetMetric(\"{{ $metric.Prefix }}{{ $name }}\")\n\t{{ else -}}\n\tgot, err := tt.GetMetric(\"otelcol_{{ $name }}\")\n\t{{ end -}}\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\n{{- end }}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/telemetrytest_test.go.tmpl",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage {{ .Package }}test\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t{{- if .Telemetry.Metrics }}\n\t{{- range $_, $metric := .Telemetry.Metrics }}\n\t{{- if $metric.Data.Async }}\n\t\"go.opentelemetry.io/otel/metric\"\n\t{{- break}}\n\t{{- end }}\n\t{{- end }}\n\t{{- end }}\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"{{ .PackageName }}/internal/{{ .GeneratedPackageName }}\"\n)\n\nfunc TestSetupTelemetry(t *testing.T) {\n\ttestTel := componenttest.NewTelemetry()\n\ttb, err := {{ .Package }}.NewTelemetryBuilder(testTel.NewTelemetrySettings())\n\trequire.NoError(t, err)\n\tdefer tb.Shutdown()\n\n\t{{- range $name, $metric := .Telemetry.Metrics }}\n\t{{- if $metric.Data.Async }}\n\trequire.NoError(t, tb.Register{{ $name.Render }}Callback(func(_ context.Context, observer metric.{{ casesTitle $metric.Data.BasicType }}Observer) error {\n\t\tobserver.Observe(1)\n\t\treturn nil\n\t}))\n\t{{- end }}\n\t{{- end }}\n\n\t{{- range $name, $metric := .Telemetry.Metrics }}\n\t{{- if not $metric.Data.Async }}\n\t{{- if eq $metric.Data.Type \"Sum\" }}\n\ttb.{{ $name.Render }}.Add(context.Background(), 1)\n\t{{- else }}\n\ttb.{{ $name.Render }}.Record(context.Background(), 1)\n\t{{- end }}\n\t{{- end }}\n\t{{- end }}\n\n\t{{- range $name, $metric := .Telemetry.Metrics }}\n\tAssertEqual{{ $name.Render }}(t, testTel,\n\t\t{{ if eq $metric.Data.Type \"Gauge\" -}}\n\t\t[]metricdata.DataPoint[{{ $metric.Gauge.MetricValueType.BasicType }}]{{\"{{Value: 1}}\"}},\n\t\t{{- else if eq $metric.Data.Type \"Sum\" -}}\n\t\t[]metricdata.DataPoint[{{ $metric.Sum.MetricValueType.BasicType }}]{{\"{{Value: 1}}\"}},\n\t\t{{- else if eq $metric.Data.Type \"Histogram\" -}}\n\t\t[]metricdata.HistogramDataPoint[{{ $metric.Histogram.MetricValueType.BasicType }}]{{\"{{}}\"}}, metricdatatest.IgnoreValue(),\n\t\t{{- end }}\n\t\tmetricdatatest.IgnoreTimestamp())\n\t{{- end }}\n\n\trequire.NoError(t, testTel.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/templates/testdata/config.yaml.tmpl",
    "content": "{{- $reag := .ReaggregationEnabled -}}\ndefault:\nall_set:\n{{- if $reag }}\n  {{- if .Metrics }}\n  metrics:\n    {{- range $name, $metric := .Metrics }}\n    {{- $metricReag := and $reag (hasAggregatableAttributes $metric.Attributes) }}\n    {{ $name }}:\n      enabled: true\n      {{- if $metricReag }}\n      attributes: [{{- range $index, $element := $metric.Attributes -}}{{ if $index }},{{ end }}\"{{ (attributeInfo $element).Name }}\"{{ end -}}]\n      {{- end }}\n    {{- end }}\n  {{- end }}\n  {{- if .Events }}\n  events:\n    {{- range $name, $_ := .Events }}\n    {{ $name }}:\n      enabled: true\n    {{- end }}\n  {{- end }}\n  {{- if .ResourceAttributes }}\n  resource_attributes:\n    {{- range $name, $_ := .ResourceAttributes }}\n    {{ $name }}:\n      enabled: true\n    {{- end }}\n  {{- end }}\nreaggregate_set:\n{{- end }}\n  {{- if .Metrics }}\n  metrics:\n    {{- range $name, $metric := .Metrics }}\n    {{- $metricReag := and $reag (hasAggregatableAttributes $metric.Attributes) }}\n    {{ $name }}:\n      enabled: true\n      {{- if $metricReag }}\n      attributes: [{{- range $index, $attr := requiredAttributes $metric.Attributes -}}{{ if $index }},{{ end }}\"{{ $attr }}\"{{- end -}}]\n      {{- end }}\n    {{- end }}\n  {{- end }}\n  {{- if .Events }}\n  events:\n    {{- range $name, $_ := .Events }}\n    {{ $name }}:\n      enabled: true\n    {{- end }}\n  {{- end }}\n  {{- if .ResourceAttributes }}\n  resource_attributes:\n    {{- range $name, $_ := .ResourceAttributes }}\n    {{ $name }}:\n      enabled: true\n    {{- end }}\n  {{- end }}\nnone_set:\n  {{- if .Metrics }}\n  metrics:\n    {{- range $name, $metric := .Metrics }}\n    {{- $metricReag := and $reag (hasAggregatableAttributes $metric.Attributes) }}\n    {{ $name }}:\n      enabled: false\n      {{- if $metricReag }}\n      attributes: [{{- range $index, $element := $metric.Attributes -}}{{ if $index }},{{ end }}\"{{ (attributeInfo $element).Name }}\"{{ end -}}]\n      {{- end }}\n    {{- end }}\n  {{- end }}\n  {{- if .Events }}\n  events:\n    {{- range $name, $_ := .Events }}\n    {{ $name }}:\n      enabled: false\n    {{- end }}\n  {{- end }}\n  {{- if .ResourceAttributes }}\n  resource_attributes:\n    {{- range $name, $_ := .ResourceAttributes }}\n    {{ $name }}:\n      enabled: false\n    {{- end }}\n  {{- end }}\n{{- if and (or .Metrics .Events) .ResourceAttributes }}\nfilter_set_include:\n  resource_attributes:\n    {{- range $name, $attr := .ResourceAttributes }}\n    {{ $name }}:\n      enabled: true\n      {{- if $.Metrics }}\n      metrics_include:\n        - regexp: \".*\"\n      {{- end }}\n      {{- if $.Events }}\n      events_include:\n        - regexp: \".*\"\n      {{- end }}\n    {{- end }}\nfilter_set_exclude:\n  resource_attributes:\n    {{- range $name, $attr := .ResourceAttributes }}\n    {{ $name }}:\n      enabled: true\n      {{- if $.Metrics }}\n      metrics_exclude:\n        {{- if eq $attr.Type.String \"Str\" }}\n        - strict: {{ $attr.TestValue }}\n        {{- else }}\n        - regexp: \".*\"\n        {{- end }}\n      {{- end }}\n      {{- if $.Events }}\n      events_exclude:\n        {{- if eq $attr.Type.String \"Str\" }}\n        - strict: {{ $attr.TestValue }}\n        {{- else }}\n        - regexp: \".*\"\n        {{- end }}\n      {{- end }}\n    {{- end }}\n{{- end }}\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/async_metric.yaml",
    "content": "type: metricreceiver\n\nstatus:\n  class: receiver\n  stability:\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nmetrics:\n  metric:\n    enabled: true\n    description: Description.\n    stability: development\n    unit: s\n    gauge:\n      value_type: double\n      async: true\n\ntests:\n  skip_lifecycle: true\n  skip_shutdown: true\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/basic_connector.yaml",
    "content": "type: test\n\nstatus:\n  class: connector\n  stability:\n    beta: [traces_to_traces]"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/basic_pkg.yaml",
    "content": "type: test\n\nstatus:\n  class: pkg\n  stability:\n    beta: [logs]"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/basic_receiver.yaml",
    "content": "type: test\n\nstatus:\n  class: receiver\n  stability:\n    beta: [logs]"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/custom_generated_package_name.yaml",
    "content": "type: metricreceiver\n\ngenerated_package_name: custom\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\ntests:\n  skip_lifecycle: true\n  skip_shutdown: true\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/deprecation_info_invalid_date.yaml",
    "content": "type: file\nstatus:\n  class: receiver\n  stability:\n    beta: [logs]\n    stable: [metrics]\n    deprecated: [traces]\n  deprecation:\n    traces:\n      date: \"05-09-2007\"\n      migration: \"no migration needed\"\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/display_name.yaml",
    "content": "type: test\ndisplay_name: Test Receiver\n\nstatus:\n  class: receiver\n  stability:\n    beta: [logs]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# sample\n\n## Resource Attributes\n\n| Name | Description | Values | Enabled |\n| ---- | ----------- | ------ | ------- |\n| host.id | The unique host identifier | Any Str | true |\n| host.name | The hostname | Any Str | true |\n| process.pid | The process identifier | Any Int | true |\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/empty.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testdata\n\n// this file allows `go list -f` to run in tests and get the scope name.\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/empty_test_config.yaml",
    "content": "type: test\n\nstatus:\n  class: receiver\n  stability:\n    beta: [logs]\n\ntests:\n  config:\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/entity_duplicate_attributes.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    stable: [metrics]\n\nresource_attributes:\n  host.id:\n    description: The host identifier\n    type: string\n    enabled: true\n  host.name:\n    description: The hostname\n    type: string\n    enabled: true\n  process.pid:\n    description: The process identifier\n    type: int\n    enabled: true\n\nentities:\n  - type: host\n    brief: A host instance.\n    stability: stable\n    identity:\n      - ref: host.id\n    description:\n      - ref: host.name\n  - type: process\n    brief: A process instance.\n    stability: stable\n    identity:\n      - ref: process.pid\n    description:\n      - ref: host.name\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/entity_duplicate_types.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    stable: [metrics]\n\nresource_attributes:\n  host.id:\n    description: The host identifier\n    type: string\n    enabled: true\n  host.name:\n    description: The hostname\n    type: string\n    enabled: true\n\nentities:\n  - type: host\n    brief: A host instance.\n    stability: stable\n    identity:\n      - ref: host.id\n  - type: host\n    brief: Another host instance.\n    stability: stable\n    identity:\n      - ref: host.name\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/entity_empty_id_attributes.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    stable: [metrics]\n\nresource_attributes:\n  host.name:\n    description: The hostname\n    type: string\n    enabled: true\n\nentities:\n  - type: host\n    brief: A host instance.\n    stability: stable\n    identity: []\n    description:\n      - ref: host.name\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/entity_event_missing_association.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    stable: [metrics]\n\nresource_attributes:\n  host.id:\n    description: The unique host identifier\n    type: string\n    enabled: true\n  process.pid:\n    description: The process identifier\n    type: int\n    enabled: true\n\nentities:\n  - type: host\n    brief: A host instance.\n    stability: stable\n    identity:\n      - ref: host.id\n  - type: process\n    brief: A process instance.\n    stability: stable\n    identity:\n      - ref: process.pid\n\nattributes:\n  test.attr:\n    description: Test attribute\n    type: string\n\nevents:\n  host.restart:\n    enabled: true\n    description: Host restart event\n    attributes: [test.attr]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/entity_metric_missing_association.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    stable: [metrics]\n\nresource_attributes:\n  host.id:\n    description: The unique host identifier\n    type: string\n    enabled: true\n  process.pid:\n    description: The process identifier\n    type: int\n    enabled: true\n\nentities:\n  - type: host\n    brief: A host instance.\n    stability: stable\n    identity:\n      - ref: host.id\n  - type: process\n    brief: A process instance.\n    stability: stable\n    identity:\n      - ref: process.pid\n\nattributes:\n  test.attr:\n    description: Test attribute\n    type: string\n\nmetrics:\n  host.cpu.time:\n    enabled: true\n    description: Host CPU time\n    unit: s\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n    stability: stable\n    attributes: [test.attr]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/entity_metrics_events_valid.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    stable: [metrics]\n\nresource_attributes:\n  host.id:\n    description: The unique host identifier\n    type: string\n    enabled: true\n  host.name:\n    description: The hostname\n    type: string\n    enabled: true\n  process.pid:\n    description: The process identifier\n    type: int\n    enabled: true\n\nentities:\n  - type: host\n    brief: A host instance.\n    stability: stable\n    identity:\n      - ref: host.id\n    description:\n      - ref: host.name\n  - type: process\n    brief: A process instance.\n    stability: stable\n    identity:\n      - ref: process.pid\n\nattributes:\n  test.attr:\n    description: Test attribute\n    type: string\n\nmetrics:\n  host.cpu.time:\n    enabled: true\n    description: Host CPU time\n    unit: s\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n    stability: stable\n    entity: host\n    attributes: [test.attr]\n\n  process.cpu.time:\n    enabled: true\n    description: Process CPU time\n    unit: s\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n    stability: stable\n    entity: process\n    attributes: [test.attr]\n\nevents:\n  host.restart:\n    enabled: true\n    description: Host restart event\n    entity: host\n    attributes: [test.attr]\n\n  process.start:\n    enabled: true\n    description: Process start event\n    entity: process\n    attributes: [test.attr]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/entity_relationships_bidirectional.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    stable: [metrics]\n\nresource_attributes:\n  k8s.replicaset.uid:\n    description: The unique identifier of the Kubernetes ReplicaSet\n    type: string\n    enabled: true\n  k8s.pod.uid:\n    description: The unique identifier of the Kubernetes pod\n    type: string\n    enabled: true\n\nentities:\n  - type: k8s.replicaset\n    brief: A Kubernetes ReplicaSet\n    stability: stable\n    identity:\n      - ref: k8s.replicaset.uid\n    relationships:\n      - type: controls\n        target: k8s.pod\n  - type: k8s.pod\n    brief: A Kubernetes pod\n    stability: stable\n    identity:\n      - ref: k8s.pod.uid\n    relationships:\n      - type: controlled_by\n        target: k8s.replicaset\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/entity_relationships_empty_target.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    stable: [metrics]\n\nresource_attributes:\n  k8s.replicaset.uid:\n    description: The unique identifier of the Kubernetes ReplicaSet\n    type: string\n    enabled: true\n  k8s.pod.uid:\n    description: The unique identifier of the Kubernetes pod\n    type: string\n    enabled: true\n\nentities:\n  - type: k8s.replicaset\n    brief: A Kubernetes ReplicaSet\n    stability: stable\n    identity:\n      - ref: k8s.replicaset.uid\n  - type: k8s.pod\n    brief: A Kubernetes pod\n    stability: stable\n    identity:\n      - ref: k8s.pod.uid\n    relationships:\n      - type: controlled_by\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/entity_relationships_empty_type.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    stable: [metrics]\n\nresource_attributes:\n  k8s.replicaset.uid:\n    description: The unique identifier of the Kubernetes ReplicaSet\n    type: string\n    enabled: true\n  k8s.pod.uid:\n    description: The unique identifier of the Kubernetes pod\n    type: string\n    enabled: true\n\nentities:\n  - type: k8s.replicaset\n    brief: A Kubernetes ReplicaSet\n    stability: stable\n    identity:\n      - ref: k8s.replicaset.uid\n  - type: k8s.pod\n    brief: A Kubernetes pod\n    stability: stable\n    identity:\n      - ref: k8s.pod.uid\n    relationships:\n      - target: k8s.replicaset\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/entity_relationships_undefined_target.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    stable: [metrics]\n\nresource_attributes:\n  k8s.pod.uid:\n    description: The unique identifier of the Kubernetes pod\n    type: string\n    enabled: true\n\nentities:\n  - type: k8s.pod\n    brief: A Kubernetes pod\n    stability: stable\n    identity:\n      - ref: k8s.pod.uid\n    relationships:\n      - type: controlled_by\n        target: k8s.replicaset\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/entity_relationships_valid.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    stable: [metrics]\n\nresource_attributes:\n  k8s.replicaset.uid:\n    description: The unique identifier of the Kubernetes ReplicaSet\n    type: string\n    enabled: true\n  k8s.replicaset.name:\n    description: The name of the Kubernetes ReplicaSet\n    type: string\n    enabled: true\n  k8s.pod.uid:\n    description: The unique identifier of the Kubernetes pod\n    type: string\n    enabled: true\n  k8s.pod.name:\n    description: The name of the Kubernetes pod\n    type: string\n    enabled: true\n\nentities:\n  - type: k8s.replicaset\n    brief: A Kubernetes ReplicaSet\n    stability: stable\n    identity:\n      - ref: k8s.replicaset.uid\n    description:\n      - ref: k8s.replicaset.name\n  - type: k8s.pod\n    brief: A Kubernetes pod\n    stability: stable\n    identity:\n      - ref: k8s.pod.uid\n    description:\n      - ref: k8s.pod.name\n    relationships:\n      - type: controlled_by\n        target: k8s.replicaset\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/entity_single_metric_missing_association.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    stable: [metrics]\n\nresource_attributes:\n  host.id:\n    description: The unique host identifier\n    type: string\n    enabled: true\n\nentities:\n  - type: host\n    brief: A host instance.\n    stability: stable\n    identity:\n      - ref: host.id\n\nattributes:\n  test.attr:\n    description: Test attribute\n    type: string\n\nmetrics:\n  host.cpu.time:\n    enabled: true\n    description: Host CPU time\n    unit: s\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n    stability: stable\n    attributes: [test.attr]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/entity_undefined_description_attribute.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    stable: [metrics]\n\nresource_attributes:\n  host.id:\n    description: The host identifier\n    type: string\n    enabled: true\n\nentities:\n  - type: host\n    brief: A host instance.\n    stability: stable\n    identity:\n      - ref: host.id\n    description:\n      - ref: host.missing\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/entity_undefined_id_attribute.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    stable: [metrics]\n\nresource_attributes:\n  host.name:\n    description: The hostname\n    type: string\n    enabled: true\n\nentities:\n  - type: host\n    brief: A host instance.\n    stability: stable\n    identity:\n      - ref: host.missing\n    description:\n      - ref: host.name\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/entity_undefined_reference.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    stable: [metrics]\n\nresource_attributes:\n  host.id:\n    description: The unique host identifier\n    type: string\n    enabled: true\n\nentities:\n  - type: host\n    brief: A host instance.\n    stability: stable\n    identity:\n      - ref: host.id\n\nattributes:\n  test.attr:\n    description: Test attribute\n    type: string\n\nmetrics:\n  host.cpu.time:\n    enabled: true\n    description: Host CPU time\n    unit: s\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n    stability: stable\n    entity: undefined_entity\n    attributes: [test.attr]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/entity_valid.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    stable: [metrics]\n\nresource_attributes:\n  host.id:\n    description: The unique host identifier\n    type: string\n    enabled: true\n  host.name:\n    description: The hostname\n    type: string\n    enabled: true\n  process.pid:\n    description: The process identifier\n    type: int\n    enabled: true\n\nentities:\n  - type: host\n    brief: A host instance.\n    stability: stable\n    identity:\n      - ref: host.id\n    description:\n      - ref: host.name\n  - type: process\n    brief: A process instance.\n    stability: stable\n    identity:\n      - ref: process.pid\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/events/basic_event.yaml",
    "content": "type: receiver\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nevents:\n  event:\n    enabled: true\n    description: Description.\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/events/empty.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage events\n\n// this file allows `go list -f` to run in tests and get the scope name.\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/events/no_description.yaml",
    "content": "type: file\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nevents:\n  default.event:\n    enabled: true\n    extended_documentation: The event will be renamed soon.\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/events/no_enabled.yaml",
    "content": "type: receiver\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n\nevents:\n  system.event:\n    description: The system event collected by opentelemetry collector.\n    attributes:\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/events/unknown_attribute.yaml",
    "content": "type: receiver\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n\nevents:\n  system.event:\n    enabled: true\n    description: The system event collected by opentelemetry collector.\n    attributes: [missing]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/feature_gates.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    beta: [metrics]\n\nfeature_gates:\n  - id: sample.feature.gate\n    description: 'This is a sample feature gate for testing purposes'\n    stage: alpha\n    from_version: 'v0.100.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/issues/12345'\n\n  - id: stable.feature.gate\n    description: 'This is a stable feature gate'\n    stage: stable\n    from_version: 'v0.90.0'\n    to_version: 'v0.95.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/issues/11111'\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage testdata\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\nvar typ = component.MustNewType(\"sample\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct {\n\t\tcreateFn func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error)\n\t\tname     string\n\t}{\n\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name+\"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\tt.Run(tt.name+\"-lifecycle\", func(t *testing.T) {\n\t\t\tfirstRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := newMdatagenNopHost()\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, firstRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, firstRcvr.Shutdown(context.Background()))\n\t\t\tsecondRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, secondRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, secondRcvr.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/generated_package_name.yaml",
    "content": "type: custom\n\ngenerated_package_name: customname\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage testdata\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"sample\")\n\tScopeName = \"go.opentelemetry.io/collector/cmd/mdatagen/internal/testdata\"\n)\n\nconst (\n\tMetricsStability = component.StabilityLevelBeta\n)\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/invalid.yaml",
    "content": "invalid"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/invalid_aggregation.yaml",
    "content": "type: metricreceiver\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nmetrics:\n  default.metric:\n    enabled: true\n    description: Monotonic cumulative sum int metric enabled by default.\n    extended_documentation: The metric will be become optional soon.\n    stability: development\n    unit: s\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: invalidaggregation\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/invalid_class.yaml",
    "content": "type: test\n\nstatus:\n  class: incorrectclass\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/invalid_config.yaml",
    "content": "type: receiver\n\nstatus:\n  class: receiver\n  stability:\n    beta: [logs]\n  distributions: [contrib]\n\nconfig:\n  type: string\n  properties:\n    endpoint:\n      type: string\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/invalid_entity_stability.yaml",
    "content": "type: sample\nstatus:\n  class: receiver\n  stability:\n    stable: [metrics]\n\nresource_attributes:\n  host.id:\n    description: The unique host identifier\n    type: string\n    enabled: true\n  host.name:\n    description: The hostname\n    type: string\n    enabled: true\n  process.pid:\n    description: The process identifier\n    type: int\n    enabled: true\n\nentities:\n  - type: host\n    brief: A host instance.\n    stability: stable42\n    identity:\n      - ref: host.id\n    description:\n      - ref: host.name\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/invalid_input_type.yaml",
    "content": "type: metricreceiver\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n\nmetrics:\n  system.cpu.time:\n    enabled: true\n    description: Total CPU seconds broken down by different states.\n    stability: development\n    unit: s\n    sum:\n      value_type: double\n      monotonic: true\n      aggregation_temporality: cumulative\n      input_type: double\n    attributes:\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/invalid_metric_semconvref.yaml",
    "content": "type: metricreceiver\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nsem_conv_version: 1.37.2\n\nmetrics:\n  default.metric:\n    enabled: true\n    description: Monotonic cumulative sum int metric enabled by default.\n    extended_documentation: The metric will be become optional soon.\n    stability: development\n    semantic_convention:\n      ref: https://github.com/open-telemetry/semantic-conventions/blob/v1.38.0/docs/system/system-metrics.md#metric-systemcputime\n    unit: s\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/invalid_metric_stability.yaml",
    "content": "type: metricreceiver\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nmetrics:\n  default.metric:\n    enabled: true\n    description: Monotonic cumulative sum int metric enabled by default.\n    extended_documentation: The metric will be become optional soon.\n    stability: development42\n    unit: s\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/invalid_stability.yaml",
    "content": "type: file\nstatus:\n  class: receiver\n  stability:\n    incorrectstability: [logs]\n    beta: [traces]\n    stable: [metrics]"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/invalid_stability_component.yaml",
    "content": "type: file\nstatus:\n  class: receiver\n  stability:\n    development: [incorrectcomponent]\n    beta: [traces]\n    stable: [metrics]"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/invalid_telemetry_missing_value_type_for_histogram.yaml",
    "content": "type: metric\n\nstatus:\n  class: receiver\n  stability:\n    beta: [traces, logs, metrics]\ntelemetry:\n  metrics:\n    sampling_decision_latency:\n      description: Latency (in microseconds) of a given sampling policy\n      unit: µs\n      enabled: true\n      histogram:\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/invalid_type_attr.yaml",
    "content": "type: metricreceiver\n\nsem_conv_version: 1.9.0\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n\nattributes:\n  used_attr:\n    description: Used attribute.\n    type: invalidtype\n\nmetrics:\n  metric:\n    enabled: true\n    description: Metric.\n    unit: \"1\"\n    gauge:\n      value_type: double\n    attributes: [used_attr]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/invalid_type_rattr.yaml",
    "content": "type: file\n\nsem_conv_version: 1.9.0\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nresource_attributes:\n  string.resource.attr:\n    description: Resource attribute with any string value.\n    type: invalidtype\n    enabled: true\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/metrics_and_type.yaml",
    "content": "type: metricreceiver\n\nstatus:\n  class: receiver\n  stability:\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nmetrics:\n  metric:\n    enabled: true\n    description: Description.\n    stability: development\n    unit: s\n    gauge:\n      value_type: double\n\ntests:\n  skip_lifecycle: true\n  skip_shutdown: true\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_aggregation.yaml",
    "content": "type: file\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\n\nmetrics:\n  default.metric:\n    enabled: true\n    description: Monotonic cumulative sum int metric enabled by default.\n    extended_documentation: The metric will be become optional soon.\n    stability: development\n    unit: s\n    sum:\n      value_type: int\n      monotonic: false\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_class.yaml",
    "content": "type: test\n\nstatus:\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_deprecation_date_info.yaml",
    "content": "type: file\nstatus:\n  class: receiver\n  stability:\n    beta: [logs]\n    stable: [metrics]\n    deprecated: [traces]\n  deprecation:\n    traces:\n      migration: \"no migration needed\"\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_deprecation_info.yaml",
    "content": "type: file\nstatus:\n  class: receiver\n  stability:\n    beta: [logs]\n    stable: [metrics]\n    deprecated: [traces]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_deprecation_migration_info.yaml",
    "content": "type: file\nstatus:\n  class: receiver\n  stability:\n    beta: [logs]\n    stable: [metrics]\n    deprecated: [traces]\n  deprecation:\n    traces:\n      date: \"2006-05-09\"\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_description_attr.yaml",
    "content": "# Sample metric metadata file with all available configurations.\n\ntype: file\n\nsem_conv_version: 1.9.0\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nattributes:\n  string_attr:\n    type: string\n\nmetrics:\n  default.metric:\n    enabled: true\n    description: Monotonic cumulative sum int metric enabled by default.\n    extended_documentation: The metric will be become optional soon.\n    stability: development\n    unit: s\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n    attributes: [string_attr]\n    warnings:\n      if_enabled_not_set: This metric will be disabled by default soon.\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_description_rattr.yaml",
    "content": "type: file\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n\nresource_attributes:\n  string.resource.attr:\n    type: string\n    enabled: true\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_display_name.yaml",
    "content": "type: nodisplayname\n\nstatus:\n  class: receiver\n  stability:\n    beta: [logs]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_enabled.yaml",
    "content": "type: metricreceiver\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n\nmetrics:\n  system.cpu.time:\n    description: Total CPU seconds broken down by different states.\n    stability: development\n    unit: s\n    sum:\n      value_type: double\n      monotonic: true\n      aggregation_temporality: cumulative\n    attributes:\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_metric_description.yaml",
    "content": "type: file\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\n\nmetrics:\n  default.metric:\n    enabled: true\n    extended_documentation: The metric will be become optional soon.\n    stability: development\n    unit: s\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_metric_stability.yaml",
    "content": "type: metricreceiver\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nmetrics:\n  default.metric:\n    enabled: true\n    description: Monotonic cumulative sum int metric enabled by default.\n    extended_documentation: The metric will be become optional soon.\n    stability: ~\n    unit: s\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_metric_type.yaml",
    "content": "type: metricreceiver\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\nmetrics:\n  system.cpu.time:\n    enabled: true\n    description: Total CPU seconds broken down by different states.\n    stability: development\n    unit: s\n    attributes:\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_metric_unit.yaml",
    "content": "type: file\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\n\nmetrics:\n  default.metric:\n    enabled: true\n    description: Monotonic cumulative sum int metric enabled by default.\n    extended_documentation: The metric will be become optional soon.\n    stability: development\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_monotonic.yaml",
    "content": "type: file\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\n\nmetrics:\n  default.metric:\n    enabled: true\n    description: Monotonic cumulative sum int metric enabled by default.\n    extended_documentation: The metric will be become optional soon.\n    stability: development\n    unit: s\n    sum:\n      value_type: int\n      aggregation_temporality: cumulative\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_stability.yaml",
    "content": "type: test\n\nstatus:\n  class: receiver"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_stability_component.yaml",
    "content": "type: file\nstatus:\n  class: receiver\n  stability:\n    beta:\n    stable: [metrics]"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_status.yaml",
    "content": "type: test"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_type.yaml",
    "content": "status:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_type_attr.yaml",
    "content": "type: metricreceiver\n\nsem_conv_version: 1.9.0\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n\nattributes:\n  used_attr:\n    description: Used attribute.\n\nmetrics:\n  metric:\n    enabled: true\n    description: Metric.\n    stability: development\n    unit: \"1\"\n    gauge:\n      value_type: double\n    attributes: [used_attr]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_type_rattr.yaml",
    "content": "type: file\n\nsem_conv_version: 1.9.0\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nresource_attributes:\n  string.resource.attr:\n    description: Resource attribute with any string value.\n    enabled: true"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/no_value_type.yaml",
    "content": "type: metricreceiver\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\n\nmetrics:\n  system.cpu.time:\n    enabled: true\n    description: Total CPU seconds broken down by different states.\n    stability: development\n    unit: s\n    sum:\n      monotonic: true\n      aggregation_temporality: cumulative\n    attributes:\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/parent.yaml",
    "content": "type: subcomponent\n\nparent: parentComponent"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/readme_with_cmd_class.md",
    "content": "# Some component\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [alpha]: logs   |\n|               | [beta]: metrics   |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aopen%20label%3Acmd%2Ffoo%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aopen+is%3Aissue+label%3Acmd%2Ffoo) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aclosed%20label%3Acmd%2Ffoo%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aclosed+is%3Aissue+label%3Acmd%2Ffoo) |\n\n[alpha]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#alpha\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n<!-- end autogenerated section -->\n\nSome info about a component\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/readme_with_multiple_signals.md",
    "content": "# Some component\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [alpha]: logs   |\n|               | [beta]: metrics   |\n| Distributions | [contrib] |\n\n[alpha]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#alpha\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n<!-- end autogenerated section -->\n\nSome info about a component\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/readme_with_multiple_signals_and_deprecation.md",
    "content": "# Some component\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [deprecated]: traces   |\n|               | [alpha]: logs   |\n|               | [beta]: metrics   |\n| Deprecation of traces | [Date]: 2025-02-05   |\n|                      | [Migration Note]: no migration needed   |\n| Distributions | [contrib] |\n\n[deprecated]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#deprecated\n[alpha]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#alpha\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[Date]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#deprecation-information\n[Migration Note]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#deprecation-information\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n<!-- end autogenerated section -->\n\nSome info about a component\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/readme_with_status.md",
    "content": "# Some component\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [beta]: metrics   |\n| Distributions | [contrib] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Areceiver%2Ffoo%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Areceiver%2Ffoo) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Areceiver%2Ffoo%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Areceiver%2Ffoo) |\n\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n<!-- end autogenerated section -->\n\nSome info about a component\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/readme_with_status_codeowners.md",
    "content": "# Some component\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [beta]: metrics   |\n| Distributions | [contrib] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aopen%20label%3Areceiver%2Ffoo%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aopen+is%3Aissue+label%3Areceiver%2Ffoo) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aclosed%20label%3Areceiver%2Ffoo%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aclosed+is%3Aissue+label%3Areceiver%2Ffoo) |\n| [Code Owners](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/CONTRIBUTING.md#becoming-a-code-owner)    | [@open-telemetry/collector-approvers](https://github.com/orgs/open-telemetry/teams/collector-approvers) |\n\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n<!-- end autogenerated section -->\n\nSome info about a component\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/readme_with_status_codeowners_and_emeritus.md",
    "content": "# Some component\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [beta]: metrics   |\n| Distributions | [contrib] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aopen%20label%3Areceiver%2Ffoo%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aopen+is%3Aissue+label%3Areceiver%2Ffoo) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aclosed%20label%3Areceiver%2Ffoo%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aclosed+is%3Aissue+label%3Areceiver%2Ffoo) |\n| [Code Owners](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/CONTRIBUTING.md#becoming-a-code-owner)    | [@foo](https://www.github.com/foo) |\n| Emeritus      | [@bar](https://www.github.com/bar) |\n\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n<!-- end autogenerated section -->\n\nSome info about a component\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/readme_with_status_codeowners_and_seeking_new.md",
    "content": "# Some component\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [beta]: metrics   |\n| Distributions | [contrib] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aopen%20label%3Areceiver%2Ffoo%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aopen+is%3Aissue+label%3Areceiver%2Ffoo) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aclosed%20label%3Areceiver%2Ffoo%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aclosed+is%3Aissue+label%3Areceiver%2Ffoo) |\n| [Code Owners](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/CONTRIBUTING.md#becoming-a-code-owner)    | [@foo](https://www.github.com/foo) \\| Seeking more code owners! |\n\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n<!-- end autogenerated section -->\n\nSome info about a component\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/readme_with_status_converter.md",
    "content": "# Some component\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [beta]  |\n| Distributions | [contrib] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aopen%20label%3Aconverter%2Ffoo%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aopen+is%3Aissue+label%3Aconverter%2Ffoo) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aclosed%20label%3Aconverter%2Ffoo%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aclosed+is%3Aissue+label%3Aconverter%2Ffoo) |\n\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n<!-- end autogenerated section -->\n\nSome info about a component\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/readme_with_status_extension.md",
    "content": "# Some component\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [beta]  |\n| Distributions | [contrib] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aopen%20label%3Aextension%2Ffoo%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aopen+is%3Aissue+label%3Aextension%2Ffoo) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aclosed%20label%3Aextension%2Ffoo%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aclosed+is%3Aissue+label%3Aextension%2Ffoo) |\n\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n<!-- end autogenerated section -->\n\nSome info about a component\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/readme_with_status_provider.md",
    "content": "# Some component\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [beta]  |\n| Distributions | [contrib] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aopen%20label%3Aprovider%2Ffoo%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aopen+is%3Aissue+label%3Aprovider%2Ffoo) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector-contrib?query=is%3Aissue%20is%3Aclosed%20label%3Aprovider%2Ffoo%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues?q=is%3Aclosed+is%3Aissue+label%3Aprovider%2Ffoo) |\n\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n<!-- end autogenerated section -->\n\nSome info about a component\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/readme_with_warnings.md",
    "content": "# Some component\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [beta]: metrics   |\n| Distributions | [contrib] |\n| Warnings      | [warning1](#warnings) |\n\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n<!-- end autogenerated section -->\n\nSome info about a component\n### warnings\nSome warning there.\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/readme_without_status.md",
    "content": "# Some component\n\nSome info about a component\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/resource_attributes_only.yaml",
    "content": "type: test\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nresource_attributes:\n  res.attr1:\n    description: Resource attribute 1.\n    type: string\n    enabled: true\n\ntests:\n  skip_lifecycle: true\n  skip_shutdown: true\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/status_only.yaml",
    "content": "type: metricreceiver\nstatus:\n  class: exporter\n  stability:\n    beta: [traces, metrics, logs]\n  distributions: [contrib]\n\ntests:\n  skip_lifecycle: true\n  skip_shutdown: true\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/two_metric_types.yaml",
    "content": "type: metricreceiver\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n\nmetrics:\n  system.cpu.time:\n    enabled: true\n    description: Total CPU seconds broken down by different states.\n    stability: development\n    unit: s\n    gauge:\n      value_type: double\n    sum:\n      value_type: double\n      monotonic: true\n      aggregation_temporality: cumulative\n    attributes:\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/twopackages.yaml",
    "content": "type: sample\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  class: receiver\n  stability:\n    beta: [traces]"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/undeprecated_with_deprecation.yaml",
    "content": "type: metricreceiver\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nmetrics:\n  default.metric:\n    enabled: true\n    description: Monotonic cumulative sum int metric enabled by default.\n    extended_documentation: The metric will be become optional soon.\n    stability: development\n    deprecated:\n      note: this should not happen\n    unit: s\n    sum:\n      value_type: int\n      monotonic: true\n      aggregation_temporality: cumulative\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/unknown_metric_attribute.yaml",
    "content": "type: metricreceiver\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n\nmetrics:\n  system.cpu.time:\n    enabled: true\n    description: Total CPU seconds broken down by different states.\n    stability: development\n    unit: s\n    sum:\n      value_type: double\n      monotonic: true\n      aggregation_temporality: cumulative\n    attributes: [missing]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/unknown_value_type.yaml",
    "content": "type: metricreceiver\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n\nmetrics:\n  system.cpu.time:\n    enabled: true\n    description: Total CPU seconds broken down by different states.\n    stability: development\n    unit: s\n    sum:\n      value_type: unknown\n      monotonic: true\n      aggregation_temporality: cumulative\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/unsorted_rattr.yaml",
    "content": "type: sample\n\nstatus:\n  class: receiver\n  stability:\n    beta: [logs]\n\nresource_attributes:\n  cloud.region:\n    description: region\n    enabled: true\n    type: string\n  cloud.availability_zone:\n    description: az\n    enabled: true\n    type: string\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/unused_attribute.yaml",
    "content": "type: metricreceiver\n\nsem_conv_version: 1.9.0\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n\nattributes:\n  used_attr_in_metrics_section:\n    description: Used attribute.\n    type: string\n  used_attr_in_telemetry_section:\n    description: Used attribute.\n    type: string\n\n  unused_attr:\n    name_override: state\n    description: Unused attribute.\n    type: string\n\nmetrics:\n  metric:\n    enabled: true\n    description: Metric.\n    stability: development\n    unit: \"1\"\n    gauge:\n      value_type: double\n    attributes: [used_attr_in_metrics_section]\n\ntelemetry:\n  metrics:\n    metric:\n      enabled: true\n      description: Metric.\n      stability: development\n      unit: \"1\"\n      gauge:\n        value_type: double\n      attributes: [used_attr_in_telemetry_section]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/with_conditional_attribute.yaml",
    "content": "type: receiver\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n\nattributes:\n  conditional_int_attr:\n    description: Conditional int attr.\n    type: string\n    requirement_level: conditionally_required\n\n  opt_in_string_attr:\n    description: Opt-in string attr.\n    type: string\n    requirement_level: opt_in\n\nmetrics:\n  metric:\n    enabled: true\n    description: Metric.\n    stability: development\n    unit: \"1\"\n    gauge:\n      value_type: double\n    attributes: [conditional_int_attr, opt_in_string_attr]\n\nevents:\n  event:\n    enabled: true\n    description: Event.\n    attributes: [conditional_int_attr, opt_in_string_attr]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/with_config.yaml",
    "content": "type: receiver\n\nstatus:\n  class: receiver\n  stability:\n    beta: [logs]\n  distributions: [contrib]\n\nconfig:\n  type: object\n  properties:\n    endpoint:\n      description: The endpoint to connect to.\n      type: string\n      default: \"localhost:4317\"\n    timeout:\n      description: Timeout for requests.\n      type: string\n      format: duration\n      default: 10s\n  required: [endpoint]\n\ntests:\n  skip_lifecycle: true\n  skip_shutdown: true\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/with_description.yaml",
    "content": "type: testdesc\ndisplay_name: Test Component\ndescription: This is a test component with a description.\n\nstatus:\n  class: receiver\n  stability:\n    beta: [logs]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/with_goleak_ignores.yaml",
    "content": "type: foobar\n\nstatus:\n  disable_codecov_badge: true\n  class: connector\n  stability:\n    beta: [traces_to_metrics, traces_to_traces, traces_to_logs, metrics_to_logs, metrics_to_metrics, metrics_to_traces, logs_to_logs, logs_to_metrics, logs_to_traces]\n\ntests:\n  goleak:\n    ignore:\n      top:\n        - \"testfunc1\"\n      any:\n        - \"testfunc2\"\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/with_goleak_setup.yaml",
    "content": "type: foobar\n\nstatus:\n  disable_codecov_badge: true\n  class: connector\n  stability:\n    beta: [traces_to_metrics, traces_to_traces, traces_to_logs, metrics_to_logs, metrics_to_metrics, metrics_to_traces, logs_to_logs, logs_to_metrics, logs_to_traces]\n\ntests:\n  goleak:\n    setup: \"setupFunc()\"\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/with_goleak_skip.yaml",
    "content": "type: foobar\n\nstatus:\n  disable_codecov_badge: true\n  class: connector\n  stability:\n    beta: [traces_to_metrics, traces_to_traces, traces_to_logs, metrics_to_logs, metrics_to_metrics, metrics_to_traces, logs_to_logs, logs_to_metrics, logs_to_traces]\n\ntests:\n  goleak:\n    skip: true\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/with_goleak_teardown.yaml",
    "content": "type: foobar\n\nstatus:\n  disable_codecov_badge: true\n  class: connector\n  stability:\n    beta: [traces_to_metrics, traces_to_traces, traces_to_logs, metrics_to_logs, metrics_to_metrics, metrics_to_traces, logs_to_logs, logs_to_metrics, logs_to_traces]\n\ntests:\n  goleak:\n    teardown: \"teardownFunc()\"\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/with_invalid_config_ref.yaml",
    "content": "type: receiver\n\nstatus:\n  class: receiver\n  stability:\n    beta: [logs]\n  distributions: [contrib]\n\n# config has a local $ref without a definition name, which passes LoadMetadata\n# validation but causes generateConfigFiles to return an error during schema resolution.\nconfig:\n  type: object\n  properties:\n    sub:\n      $ref: \"/config/configauth\"\n\ntests:\n  skip_lifecycle: true\n  skip_shutdown: true\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/with_stability_from.yaml",
    "content": "type: test\nstatus:\n  class: receiver\n  stability:\n    Beta: [metrics]\nmetrics:\n  test.metric:\n    enabled: true\n    description: Test metric with stability from field\n    unit: \"1\"\n    stability:\n      level: beta\n      from: \"1.0.0\"\n    sum:\n      value_type: int\n      aggregation_temporality: cumulative\n      monotonic: true\n\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/with_telemetry.yaml",
    "content": "type: metric\n\nstatus:\n  class: receiver\n  stability:\n    beta: [traces, logs, metrics]\nattributes:\n  name:\n    description: Name of sampling decision\n    type: string\ntelemetry:\n  metrics:\n    sampling_decision_latency:\n      description: Latency (in microseconds) of a given sampling policy\n      unit: µs\n      enabled: true\n      stability: alpha\n      histogram:\n        value_type: int\n      attributes: [name]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/with_tests_connector.yaml",
    "content": "type: foobar\n\nstatus:\n  disable_codecov_badge: true\n  class: connector\n  stability:\n    beta: [traces_to_metrics, traces_to_traces, traces_to_logs, metrics_to_logs, metrics_to_metrics, metrics_to_traces, logs_to_logs, logs_to_metrics, logs_to_traces]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/with_tests_exporter.yaml",
    "content": "type: metric\n\nstatus:\n  class: exporter\n  stability:\n    beta: [traces, logs, metrics]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/with_tests_extension.yaml",
    "content": "type: metric\n\nstatus:\n  class: extension\n  stability:\n    beta: [extension]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/with_tests_processor.yaml",
    "content": "type: metric\n\nstatus:\n  class: processor\n  stability:\n    beta: [traces, logs, metrics]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/with_tests_profiles_connector.yaml",
    "content": "type: foobar\n\nstatus:\n  disable_codecov_badge: true\n  class: connector\n  stability:\n    beta: [traces_to_profiles, metrics_to_profiles, logs_to_profiles, profiles_to_traces, profiles_to_metrics, profiles_to_logs, profiles_to_profiles]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/with_tests_receiver.yaml",
    "content": "type: metric\n\nstatus:\n  class: receiver\n  stability:\n    beta: [traces, logs, metrics]\n"
  },
  {
    "path": "cmd/mdatagen/internal/testdata/with_underscore_in_semconv_ref_anchor_tag.yaml",
    "content": "type: metricreceiver\n\nstatus:\n  class: receiver\n  stability:\n    development: [logs]\n    beta: [traces]\n    stable: [metrics]\n  distributions: [contrib]\n  warnings:\n    - Any additional information that should be brought to the consumer's attention\n\nsem_conv_version: 1.38.0\n\nmetrics:\n  system.disk.io_time:\n    enabled: true\n    description: Time disk spent activated..\n    stability: development\n    semantic_convention:\n      ref: https://github.com/open-telemetry/semantic-conventions/blob/v1.38.0/docs/system/system-metrics.md#metric-systemdiskio_time\n    unit: s\n    sum:\n      value_type: double\n      monotonic: true\n      aggregation_temporality: cumulative\n\n"
  },
  {
    "path": "cmd/mdatagen/internal/tests.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/cmd/mdatagen/internal\"\n\ntype Ignore struct {\n\tTop []string `mapstructure:\"top\"`\n\tAny []string `mapstructure:\"any\"`\n}\n\ntype GoLeak struct {\n\tSkip     bool   `mapstructure:\"skip\"`\n\tIgnore   Ignore `mapstructure:\"ignore\"`\n\tSetup    string `mapstructure:\"setup\"`\n\tTeardown string `mapstructure:\"teardown\"`\n}\n\ntype Tests struct {\n\tConfig              any    `mapstructure:\"config\"`\n\tSkipLifecycle       bool   `mapstructure:\"skip_lifecycle\"`\n\tSkipShutdown        bool   `mapstructure:\"skip_shutdown\"`\n\tGoLeak              GoLeak `mapstructure:\"goleak\"`\n\tExpectConsumerError bool   `mapstructure:\"expect_consumer_error\"`\n\tHost                string `mapstructure:\"host\"`\n}\n"
  },
  {
    "path": "cmd/mdatagen/main.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage main\n\n//go:generate mdatagen metadata.yaml\n\nimport (\n\t\"os\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"go.opentelemetry.io/collector/cmd/mdatagen/internal\"\n)\n\nfunc main() {\n\tcmd, err := internal.NewCommand()\n\tcobra.CheckErr(err)\n\n\tif err := cmd.Execute(); err != nil {\n\t\tos.Exit(1)\n\t}\n}\n"
  },
  {
    "path": "cmd/mdatagen/metadata-schema.yaml",
    "content": "# Required: The type of the component - Usually the name. The type and class combined uniquely identify the component (eg. receiver/otlp) or subcomponent (eg. receiver/hostmetricsreceiver/cpu)\ntype:\n\n# Optional: A deprecated type that is still available as an alias.\ndeprecated_type: string\n\n# Optional: Human-readable display name for the component. Used as the title in generated README files.\ndisplay_name: string\n\n# Optional: Brief description of the component that will be included in the generated README.\ndescription: string\n\n# Required for subcomponents: The type of the parent component.\nparent: string\n\n# Optional: Scope name for the telemetry generated by the component. If not set, name of the go package will be used.\nscope_name: string\n\n# Optional: The name of the package that mdatagen generates. If not set, the name \"metadata\" will be used.\ngenerated_package_name: string\n\n# Optional: Enables per-metric reaggregation config generation for metrics with attributes.\n# When enabled, generated metrics config includes `aggregation_strategy` and `attributes`\n# fields that let users reduce metric cardinality by choosing which dimensions are kept.\nreaggregation_enabled: bool\n\n# Required for components (Optional for subcomponents): A high-level view of the development status and use of this component\nstatus:\n  # Required: The class of the component (For example receiver)\n  class: <receiver|processor|exporter|connector|extension|cmd|pkg|scraper|converter|provider>\n  # Required: The stability of the component - See https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stability-levels\n  stability:\n    development: [<metrics|traces|logs|traces_to_metrics|metrics_to_metrics|logs_to_metrics|extension,converter,provider>]\n    alpha: [<metrics|traces|logs|traces_to_metrics|metrics_to_metrics|logs_to_metrics|extension,converter,provider>]\n    beta: [<metrics|traces|logs|traces_to_metrics|metrics_to_metrics|logs_to_metrics|extension,converter,provider>]\n    stable: [<metrics|traces|logs|traces_to_metrics|metrics_to_metrics|logs_to_metrics|extension,converter,provider>]\n    deprecated: [<metrics|traces|logs|traces_to_metrics|metrics_to_metrics|logs_to_metrics|extension,converter,provider>]\n    unmaintained: [<metrics|traces|logs|traces_to_metrics|metrics_to_metrics|logs_to_metrics|extension,converter,provider>]\n  # Required for deprecated components: The deprecation information for the deprecated components - See https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#deprecation-information\n  deprecation:\n    <component>:\n      date: string\n      migration: string\n  # Optional: The distributions that this component is bundled with (For example core or contrib). See statusdata.go for a list of common distros.\n  distributions: [string]\n  # Optional: A list of warnings that should be brought to the attention of users looking to use this component\n  warnings: [string]\n  # Optional: Metadata related to codeowners of the component\n  codeowners:\n    active: [string]\n    emeritus: [string]\n  unsupported_platforms: [<linux|windows>]\n\n# Optional: OTel Semantic Conventions version that will be associated with the scraped metrics.\n# This attribute should be set for metrics compliant with OTel Semantic Conventions.\nsem_conv_version: 1.9.0\n\n# Optional: JSON Schema based definition for the component's configuration structure.\n# This section defines the schema that could be used to generate:\n# - JSON Schema files that can be used for validation and documentation. (current)\n# - Go structs representing the configuration with appropriate types and validation tags. (future)\n# - Configuration reference documentation in the generated README files. (future)\nconfig:\n  # Optional: Description of the configuration schema.\n  description: string\n  # Optional: Additional comments for developers (not included in JSON output).\n  $comment: string\n  # Required: The type of the configuration object. Typically \"object\" for component configs.\n  type: <string|number|integer|boolean|object|array|null>\n  # Optional: Map of configuration properties that define the component's configuration fields.\n  properties:\n    <property.name>:\n      # Optional: Description of this configuration property.\n      description: string\n      # Optional: The JSON Schema type of this property.\n      type: <string|number|integer|boolean|object|array|null>\n      # Optional: Reference to another schema definition. Can be:\n      # - Internal reference: name of a type in $defs (e.g., \"endpoint_config\")\n      # - External reference: full package path with type (e.g., \"go.opentelemetry.io/collector/config/confighttp.client_config\")\n      # - Relative reference: local path (e.g., \"./internal/metadata.config\")\n      $ref: string\n      # Optional: Default value for this property if not specified.\n      default: any\n      # Optional: Example values for this property.\n      examples: [any]\n      # Optional: Indicates if this property is deprecated.\n      deprecated: bool\n      # Optional: For string types - allowed values.\n      enum: [string]\n      # Optional: Constant value - property must have exactly this value.\n      const: any\n      # Optional: For string types - regular expression pattern that the value must match.\n      pattern: string\n      # Optional: For string types - format specification (e.g., \"uri\", \"email\", \"date-time\", \"duration\").\n      format: string\n      # Optional: For string types - minimum length.\n      minLength: int\n      # Optional: For string types - maximum length.\n      maxLength: int\n      # Optional: For number/integer types - minimum value (inclusive).\n      minimum: number\n      # Optional: For number/integer types - maximum value (inclusive).\n      maximum: number\n      # Optional: For number/integer types - exclusive minimum value.\n      exclusiveMinimum: number\n      # Optional: For number/integer types - exclusive maximum value.\n      exclusiveMaximum: number\n      # Optional: For number types - value must be a multiple of this number.\n      multipleOf: number\n      # Optional: For object types - properties of the nested object.\n      properties: {} # Recursively follows same structure\n      # Optional: For object types - whether additional properties beyond those defined are allowed.\n      # Can be true, false, or an object schema defining the type of additional properties.\n      additionalProperties: <bool|object>\n      # Optional: For object types - minimum number of properties required.\n      minProperties: int\n      # Optional: For object types - maximum number of properties allowed.\n      maxProperties: int\n      # Optional: For array types - schema for array items.\n      items:\n        # Same structure as property definition\n        type: string\n        # ... other item properties\n      # Optional: For array types - minimum number of items.\n      minItems: int\n      # Optional: For array types - maximum number of items.\n      maxItems: int\n      # Optional: For array types - whether all items must be unique.\n      uniqueItems: bool\n      # Optional: All of these schemas must be satisfied (schema composition).\n      allOf:\n        - type: object\n          properties: {}\n      # Custom extension fields (not part of JSON Schema standard, used by mdatagen):\n      # Optional: Custom Go type name to use instead of generated type.\n      x-customType: string\n      # Optional: Whether this field should be a pointer in Go code.\n      x-pointer: bool\n      # Optional: Whether this field is optional in Go code (will use pointer or optional type).\n      x-optional: bool\n  # Optional: List of required property names. Properties in this list must be present in the config.\n  required: [string]\n  # Optional: Map of reusable schema definitions that can be referenced via $ref.\n  # These definitions are not directly part of the config but can be reused multiple times.\n  $defs:\n    <definition.name>:\n      # Same structure as property definition\n      type: object\n      properties: {}\n      # ... other schema properties\n\n# Optional: map of resource attribute definitions with the key being the attribute name.\nresource_attributes:\n  <attribute.name>:\n    # Required: whether the resource attribute is added the emitted metrics by default.\n    enabled: bool\n    # Required: description of the attribute.\n    description:\n    # Optional: array of attribute values if they are static values (currently, only string type is supported).\n    enum: [string]\n    # Required: attribute value type.\n    type: <string|int|double|bool|bytes|slice|map>\n    # Optional: warnings that will be shown to user under specified conditions.\n    warnings:\n      # A warning that will be displayed if the resource_attribute is enabled in user config.\n      # Should be used for deprecated default resource_attributes that will be removed soon.\n      if_enabled:\n      # A warning that will be displayed if `enabled` field is not set explicitly in user config.\n      # Should be used for resource_attributes that will be turned from default to optional or vice versa.\n      if_enabled_not_set:\n      # A warning that will be displayed if the resource_attribute is configured by user in any way.\n      # Should be used for deprecated optional resource_attributes that will be removed soon.\n      if_configured:\n\n# Optional: array of entity definitions. Entities organize resource attributes into logical entities\n# with identity and description attributes.\nentities:\n  - # Required: the type of the entity.\n    type: string\n    # Required: a brief description of the entity.\n    brief: string\n    # Optional: the stability level of the entity.\n    stability: <development|alpha|beta|release_candidate|stable>\n    # Required: array of references to resource attributes that uniquely identify this entity.\n    # All referenced attributes must be defined in the resource_attributes section.\n    identity:\n      - ref: string\n    # Optional: array of references to resource attributes that describe this entity.\n    # All referenced attributes must be defined in the resource_attributes section.\n    description:\n      - ref: string\n    # Optional: array of relationships to other entities. Relationships should be defined on only\n    # one end to avoid bidirectional definitions. It is recommended to define relationships on\n    # entities with lower lifespan (higher churn). For example, a pod should define its relationship\n    # to a replicaset, rather than the replicaset defining its relationship to pods.\n    relationships:\n      - # Required: the type of the relationship (e.g., \"controlled_by\", \"parent\", \"peer\").\n        type: string\n        # Required: the target entity type this entity relates to. Must reference an entity\n        # defined in the same metadata.yaml file.\n        target: string\n\n# Optional: map of attribute definitions with the key being the attribute name and value\n# being described below.\nattributes:\n  <attribute.name>:\n    # Optional: this field can be used to override the actual attribute name defined by the key.\n    # It should be used if multiple metrics have different attributes with the same name.\n    name_override:\n    # Required: description of the attribute.\n    description:\n    # Optional: array of attribute values if they are static values (currently, only string type is supported).\n    enum: [string]\n    # Required: attribute value type.\n    type: <string|int|double|bool|bytes|slice|map>\n    # Optional: indicates requirement level of the attribute.\n    # - required: the attribute is always included and cannot be excluded.\n    # - conditionally_required: the attribute is included by default when certain conditions are met.\n    # - recommended (default behavior): the attribute is included by default but can be disabled via configuration.\n    # - opt_in: the attribute is not included unless explicitly enabled in user config.\n    requirement_level: <required|conditionally_required|recommended|opt_in>\n\n# Optional: map of metric names with the key being the metric name and value\n# being described below.\nmetrics:\n  <metric.name>:\n    # Required: whether the metric is collected by default.\n    enabled: bool\n    # Required: metric description.\n    description:\n    # Optional: extended documentation of the metric.\n    extended_documentation:\n    # Optional: warnings that will be shown to user under specified conditions.\n    warnings:\n      # A warning that will be displayed if the metric is enabled in user config.\n      # Should be used for deprecated default metrics that will be removed soon.\n      if_enabled:\n      # A warning that will be displayed if `enabled` field is not set explicitly in user config.\n      # Should be used for metrics that will be turned from default to optional or vice versa.\n      if_enabled_not_set:\n      # A warning that will be displayed if the metrics is configured by user in any way.\n      # Should be used for deprecated optional metrics that will be removed soon.\n      if_configured:\n    # Required: metric unit as defined by https://ucum.org/ucum.html.\n    unit:\n    # Required: metric type with its settings.\n    <sum|gauge>:\n      # Required for sum and gauge metrics: type of number data point values.\n      value_type: <int|double>\n      # Required for sum metric: whether the metric is monotonic (no negative delta values).\n      monotonic: bool\n      # Required for sum metric: whether reported values incorporate previous measurements\n      # (cumulative) or not (delta).\n      aggregation_temporality: <delta|cumulative>\n       # Optional: Indicates the type the metric needs to be parsed from. If set, the generated\n       # functions will parse the value from string to value_type.\n      input_type: string\n    # Optional: array of attributes that were defined in the attributes section that are emitted by this metric.\n    attributes: [string]\n    # Optional: the entity type this metric is associated with.\n    # Required when entities are defined in the entities section.\n    # Must reference an entity type defined in the entities section.\n    entity: string\n    # Required: the metric stability\n    stability: <development|alpha|beta|stable|deprecated>\n    # Deprecation information for the metric. Required when stability is `deprecated`.\n    deprecated:\n      # Required: version when the metric was deprecated\n      since:\n      # Required: migration note\n      note:\n    # Optional: the reference to a semantic convention\n    semantic_convention:\n      ref:\n\n# Optional: map of event names with the key being the event name and value\n# being described below.\nevents:\n  <event.name>:\n    # Required: whether the event is collected by default.\n    enabled: bool\n    # Required: event description.\n    description:\n    # Optional: extended documentation of the event.\n    extended_documentation:\n    # Optional: warnings that will be shown to user under specified conditions.\n    warnings:\n      # A warning that will be displayed if the event is enabled in user config.\n      # Should be used for deprecated default events that will be removed soon.\n      if_enabled:\n      # A warning that will be displayed if `enabled` field is not set explicitly in user config.\n      if_enabled_not_set:\n      # A warning that will be displayed if the event is configured by user in any way.\n      if_configured:\n    # Optional: array of attributes that were defined in the attributes section that are emitted by this event.\n    attributes: [string]\n    # Optional: the entity type this event is associated with.\n    # Required when entities are defined in the entities section.\n    # Must reference an entity type defined in the entities section.\n    entity: string\n\n# Lifecycle tests generated for this component.\ntests:\n  config: # {} by default, specific testing configuration for lifecycle tests.\n  # Skip lifecycle tests for this component. Not recommended for components that are not in development.\n  skip_lifecycle: false # false by default\n  # Skip shutdown tests for this component. Not recommended for components that are not in development.\n  skip_shutdown: false # false by default\n  # Whether it's expected that the Consume[Logs|Metrics|Traces] method will return an error with the given configuration.\n  expect_consumer_error: true # false by default\n  goleak: # {} by default generates a package_test to enable check for leaks\n    skip: false # set to true if goleak tests should be skipped\n    setup: string # Optional: supports configuring a setup function that runs before goleak checks\n    teardown: string # Optional: supports configuring a teardown function that runs before goleak checks\n    ignore:\n      top: [string] # Optional: array of strings representing functions that should be ignore via IgnoreTopFunction\n      any: [string] # Optional: array of strings representing functions that should be ignore via IgnoreAnyFunction\n\n\n# Optional: map of metric names with the key being the metric name and value\n# being described below.\ntelemetry:\n  metrics:\n    <metric.name>:\n      # Required: whether the metric is collected by default.\n      enabled: bool\n      # Required: metric description.\n      description:\n      # Optional: the stability of the metric. Set to alpha by default.\n      stability:\n        # Optional: the stability level of the metric. Set to alpha by default.\n        level: [alpha|stable|deprecated]\n        # Optional: the version current stability was introduced\n        from:\n      # Deprecation information for the metric. Required when stability is `deprecated`.\n      deprecated:\n        # Required: version when the metric was deprecated\n        since:\n        # Required: migration note\n        note:\n      # Optional: extended documentation of the metric.\n      extended_documentation:\n      # Optional: whether or not this metric is optional. Optional metrics may only be initialized\n      # if certain features are enabled or configured.\n      optional: bool\n      # Optional: warnings that will be shown to user under specified conditions.\n      warnings:\n        # A warning that will be displayed if the metric is enabled in user config.\n        # Should be used for deprecated default metrics that will be removed soon.\n        if_enabled:\n        # A warning that will be displayed if `enabled` field is not set explicitly in user config.\n        # Should be used for metrics that will be turned from default to optional or vice versa.\n        if_enabled_not_set:\n        # A warning that will be displayed if the metrics is configured by user in any way.\n        # Should be used for deprecated optional metrics that will be removed soon.\n        if_configured:\n      # Required: metric unit as defined by https://ucum.org/ucum.html.\n      unit:\n      # Required: metric type with its settings.\n      <sum|gauge|histogram>:\n        # Optional: Whether this metric is asynchronous. If async, a mechanism is required to be able to\n        # pass in options to the callbacks that are called when the metric is observed.\n        async: bool\n        # Required: type of number data point values.\n        value_type: <int|double>\n        # Required for sum metric: whether the metric is monotonic (no negative delta values).\n        monotonic: bool\n        # Bucket boundaries are only available to set for histogram metrics.\n        bucket_boundaries: [double]\n      # Optional: array of attributes that were defined in the attributes section that are emitted by this metric.\n      # Note: Only the following attribute types are supported: <string|int|double|bool>\n      attributes: [string]\n\n# Optional: list of feature gate definitions.\nfeature_gates:\n  - # Required: unique identifier for the feature gate.\n    id: <gate.id>\n    # Required: description of the feature gate.\n    description: string\n    # Required: lifecycle stage of the feature gate.\n    stage: <alpha|beta|stable|deprecated>\n    # Required: version when the feature gate was introduced.\n    from_version: string\n    # Required for stable/deprecated gates: version when the feature gate reached stable stage.\n    to_version: string\n    # Required: URL with contextual information about the feature gate.\n    reference_url: string\n"
  },
  {
    "path": "cmd/mdatagen/metadata.yaml",
    "content": "type: mdatagen\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: cmd\n  stability:\n    alpha: [metrics]\n  codeowners:\n    active: [dmitryax]\n"
  },
  {
    "path": "cmd/mdatagen/third_party/golint/LICENSE",
    "content": "Copyright (c) 2013 The Go Authors. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n   * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n   * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n   * Neither the name of Google Inc. nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "cmd/mdatagen/third_party/golint/golint.go",
    "content": "// Copyright (c) 2013 The Go Authors. All rights reserved.\n//\n// Use of this source code is governed by a BSD-style\n// license that can be found in the LICENSE file or at\n// https://developers.google.com/open-source/licenses/bsd.\n\npackage golint // import \"go.opentelemetry.io/collector/cmd/mdatagen/third_party/golint\"\n\n// See https://github.com/golang/lint/blob/d0100b6bd8b389f0385611eb39152c4d7c3a7905/lint.go#L771\n\n// Acronyms is a list of known acronyms that should not be formatted when linting.\nvar Acronyms = map[string]bool{\n\t\"ACL\":   true,\n\t\"API\":   true,\n\t\"ASCII\": true,\n\t\"CPU\":   true,\n\t\"CSS\":   true,\n\t\"DNS\":   true,\n\t\"EOF\":   true,\n\t\"GUID\":  true,\n\t\"HTML\":  true,\n\t\"HTTP\":  true,\n\t\"HTTPS\": true,\n\t\"ID\":    true,\n\t\"IP\":    true,\n\t\"JSON\":  true,\n\t\"LHS\":   true,\n\t\"QPS\":   true,\n\t\"RAM\":   true,\n\t\"RHS\":   true,\n\t\"RPC\":   true,\n\t\"SLA\":   true,\n\t\"SMTP\":  true,\n\t\"SQL\":   true,\n\t\"SSH\":   true,\n\t\"TCP\":   true,\n\t\"TLS\":   true,\n\t\"TTL\":   true,\n\t\"UDP\":   true,\n\t\"UI\":    true,\n\t\"UID\":   true,\n\t\"UUID\":  true,\n\t\"URI\":   true,\n\t\"URL\":   true,\n\t\"UTF8\":  true,\n\t\"VM\":    true,\n\t\"XML\":   true,\n\t\"XMPP\":  true,\n\t\"XSRF\":  true,\n\t\"XSS\":   true,\n}\n"
  },
  {
    "path": "cmd/otelcorecol/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "cmd/otelcorecol/README.md",
    "content": "# `otelcorecol` test binary\n\nThis folder contains the sources for the `otelcorecol` test binary. This binary is intended for internal **TEST PURPOSES ONLY**. The source files in this folder are **NOT** the ones used to build any official OpenTelemetry Collector releases.\nCheck [open-telemetry/opentelemetry-collector-releases](https://github.com/open-telemetry/opentelemetry-collector-releases) for the official releases. Check the [**`otelcol` folder**](https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol) on that repository for the official Collector core manifest.\n"
  },
  {
    "path": "cmd/otelcorecol/builder-config.yaml",
    "content": "# NOTE:\n# This builder configuration is NOT used to build any official binary.\n# To see the builder manifests used for official binaries,\n# check https://github.com/open-telemetry/opentelemetry-collector-releases\n#\n# For the OpenTelemetry Collector Core official distribution sources, check\n# https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n\ndist:\n  module: go.opentelemetry.io/collector/cmd/otelcorecol\n  name: otelcorecol\n  description: Local OpenTelemetry Collector binary, testing only.\n  version: 0.148.0-dev\n\nreceivers:\n  - gomod: go.opentelemetry.io/collector/receiver/nopreceiver v0.148.0\n  - gomod: go.opentelemetry.io/collector/receiver/otlpreceiver v0.148.0\nexporters:\n  - gomod: go.opentelemetry.io/collector/exporter/debugexporter v0.148.0\n  - gomod: go.opentelemetry.io/collector/exporter/nopexporter v0.148.0\n  - gomod: go.opentelemetry.io/collector/exporter/otlpexporter v0.148.0\n  - gomod: go.opentelemetry.io/collector/exporter/otlphttpexporter v0.148.0\nextensions:\n  - gomod: go.opentelemetry.io/collector/extension/memorylimiterextension v0.148.0\n  - gomod: go.opentelemetry.io/collector/extension/zpagesextension v0.148.0\nprocessors:\n  - gomod: go.opentelemetry.io/collector/processor/batchprocessor v0.148.0\n  - gomod: go.opentelemetry.io/collector/processor/memorylimiterprocessor v0.148.0\nconnectors:\n  - gomod: go.opentelemetry.io/collector/connector/forwardconnector v0.148.0\n\nproviders:\n  - gomod: go.opentelemetry.io/collector/confmap/provider/envprovider v1.54.0\n  - gomod: go.opentelemetry.io/collector/confmap/provider/fileprovider v1.54.0\n  - gomod: go.opentelemetry.io/collector/confmap/provider/httpprovider v1.54.0\n  - gomod: go.opentelemetry.io/collector/confmap/provider/httpsprovider v1.54.0\n  - gomod: go.opentelemetry.io/collector/confmap/provider/yamlprovider v1.54.0\n\ntelemetry:\n  gomod: go.opentelemetry.io/collector/service v0.148.0\n  import: go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\n\nreplaces:\n  - go.opentelemetry.io/collector => ../../\n  - go.opentelemetry.io/collector/client => ../../client\n  - go.opentelemetry.io/collector/component => ../../component\n  - go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n  - go.opentelemetry.io/collector/component/componentstatus => ../../component/componentstatus\n  - go.opentelemetry.io/collector/config/configauth => ../../config/configauth\n  - go.opentelemetry.io/collector/config/configcompression => ../../config/configcompression\n  - go.opentelemetry.io/collector/config/configgrpc => ../../config/configgrpc\n  - go.opentelemetry.io/collector/config/confighttp => ../../config/confighttp\n  - go.opentelemetry.io/collector/config/configmiddleware => ../../config/configmiddleware\n  - go.opentelemetry.io/collector/config/confignet => ../../config/confignet\n  - go.opentelemetry.io/collector/config/configopaque => ../../config/configopaque\n  - go.opentelemetry.io/collector/config/configoptional => ../../config/configoptional\n  - go.opentelemetry.io/collector/config/configretry => ../../config/configretry\n  - go.opentelemetry.io/collector/config/configtelemetry => ../../config/configtelemetry\n  - go.opentelemetry.io/collector/config/configtls => ../../config/configtls\n  - go.opentelemetry.io/collector/confmap => ../../confmap\n  - go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n  - go.opentelemetry.io/collector/confmap/provider/envprovider => ../../confmap/provider/envprovider\n  - go.opentelemetry.io/collector/confmap/provider/fileprovider => ../../confmap/provider/fileprovider\n  - go.opentelemetry.io/collector/confmap/provider/httpprovider => ../../confmap/provider/httpprovider\n  - go.opentelemetry.io/collector/confmap/provider/httpsprovider => ../../confmap/provider/httpsprovider\n  - go.opentelemetry.io/collector/confmap/provider/yamlprovider => ../../confmap/provider/yamlprovider\n  - go.opentelemetry.io/collector/consumer => ../../consumer\n  - go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n  - go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n  - go.opentelemetry.io/collector/consumer/consumererror/xconsumererror => ../../consumer/consumererror/xconsumererror\n  - go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n  - go.opentelemetry.io/collector/connector => ../../connector\n  - go.opentelemetry.io/collector/connector/connectortest => ../../connector/connectortest\n  - go.opentelemetry.io/collector/connector/xconnector => ../../connector/xconnector\n  - go.opentelemetry.io/collector/connector/forwardconnector => ../../connector/forwardconnector\n  - go.opentelemetry.io/collector/exporter => ../../exporter\n  - go.opentelemetry.io/collector/exporter/debugexporter => ../../exporter/debugexporter\n  - go.opentelemetry.io/collector/exporter/exportertest => ../../exporter/exportertest\n  - go.opentelemetry.io/collector/exporter/xexporter => ../../exporter/xexporter\n  - go.opentelemetry.io/collector/exporter/exporterhelper => ../../exporter/exporterhelper\n  - go.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper => ../../exporter/exporterhelper/xexporterhelper\n  - go.opentelemetry.io/collector/exporter/nopexporter => ../../exporter/nopexporter\n  - go.opentelemetry.io/collector/exporter/otlpexporter => ../../exporter/otlpexporter\n  - go.opentelemetry.io/collector/exporter/otlphttpexporter => ../../exporter/otlphttpexporter\n  - go.opentelemetry.io/collector/extension => ../../extension\n  - go.opentelemetry.io/collector/extension/extensionauth => ../../extension/extensionauth\n  - go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest => ../../extension/extensionauth/extensionauthtest\n  - go.opentelemetry.io/collector/extension/extensioncapabilities => ../../extension/extensioncapabilities\n  - go.opentelemetry.io/collector/extension/extensionmiddleware => ../../extension/extensionmiddleware\n  - go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest => ../../extension/extensionmiddleware/extensionmiddlewaretest\n  - go.opentelemetry.io/collector/extension/extensiontest => ../../extension/extensiontest\n  - go.opentelemetry.io/collector/extension/memorylimiterextension => ../../extension/memorylimiterextension\n  - go.opentelemetry.io/collector/extension/xextension => ../../extension/xextension\n  - go.opentelemetry.io/collector/extension/zpagesextension => ../../extension/zpagesextension\n  - go.opentelemetry.io/collector/featuregate => ../../featuregate\n  - go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n  - go.opentelemetry.io/collector/internal/memorylimiter => ../../internal/memorylimiter\n  - go.opentelemetry.io/collector/internal/fanoutconsumer => ../../internal/fanoutconsumer\n  - go.opentelemetry.io/collector/internal/telemetry => ../../internal/telemetry\n  - go.opentelemetry.io/collector/internal/sharedcomponent => ../../internal/sharedcomponent\n  - go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n  - go.opentelemetry.io/collector/otelcol => ../../otelcol\n  - go.opentelemetry.io/collector/pdata => ../../pdata\n  - go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n  - go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n  - go.opentelemetry.io/collector/pdata/xpdata => ../../pdata/xpdata\n  - go.opentelemetry.io/collector/pipeline => ../../pipeline\n  - go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n  - go.opentelemetry.io/collector/processor => ../../processor\n  - go.opentelemetry.io/collector/processor/processortest => ../../processor/processortest\n  - go.opentelemetry.io/collector/processor/batchprocessor => ../../processor/batchprocessor\n  - go.opentelemetry.io/collector/processor/memorylimiterprocessor => ../../processor/memorylimiterprocessor\n  - go.opentelemetry.io/collector/processor/xprocessor => ../../processor/xprocessor\n  - go.opentelemetry.io/collector/processor/processorhelper/xprocessorhelper => ../../processor/processorhelper/xprocessorhelper\n  - go.opentelemetry.io/collector/processor/processorhelper => ../../processor/processorhelper\n  - go.opentelemetry.io/collector/receiver => ../../receiver\n  - go.opentelemetry.io/collector/receiver/nopreceiver => ../../receiver/nopreceiver\n  - go.opentelemetry.io/collector/receiver/receiverhelper => ../../receiver/receiverhelper\n  - go.opentelemetry.io/collector/receiver/otlpreceiver => ../../receiver/otlpreceiver\n  - go.opentelemetry.io/collector/receiver/receivertest => ../../receiver/receivertest\n  - go.opentelemetry.io/collector/receiver/xreceiver => ../../receiver/xreceiver\n  - go.opentelemetry.io/collector/service => ../../service\n  - go.opentelemetry.io/collector/service/hostcapabilities => ../../service/hostcapabilities\n  - go.opentelemetry.io/collector/service/telemetry/telemetrytest => ../../service/telemetry/telemetrytest\n"
  },
  {
    "path": "cmd/otelcorecol/components.go",
    "content": "// Code generated by \"go.opentelemetry.io/collector/cmd/builder\". DO NOT EDIT.\n\npackage main\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector\"\n\tforwardconnector \"go.opentelemetry.io/collector/connector/forwardconnector\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\tdebugexporter \"go.opentelemetry.io/collector/exporter/debugexporter\"\n\tnopexporter \"go.opentelemetry.io/collector/exporter/nopexporter\"\n\totlpexporter \"go.opentelemetry.io/collector/exporter/otlpexporter\"\n\totlphttpexporter \"go.opentelemetry.io/collector/exporter/otlphttpexporter\"\n\t\"go.opentelemetry.io/collector/extension\"\n\tmemorylimiterextension \"go.opentelemetry.io/collector/extension/memorylimiterextension\"\n\tzpagesextension \"go.opentelemetry.io/collector/extension/zpagesextension\"\n\t\"go.opentelemetry.io/collector/otelcol\"\n\t\"go.opentelemetry.io/collector/processor\"\n\tbatchprocessor \"go.opentelemetry.io/collector/processor/batchprocessor\"\n\tmemorylimiterprocessor \"go.opentelemetry.io/collector/processor/memorylimiterprocessor\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\tnopreceiver \"go.opentelemetry.io/collector/receiver/nopreceiver\"\n\totlpreceiver \"go.opentelemetry.io/collector/receiver/otlpreceiver\"\n\totelconftelemetry \"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\"\n)\n\ntype aliasProvider interface{ DeprecatedAlias() component.Type }\n\nfunc makeModulesMap[T component.Factory](factories map[component.Type]T, modules map[component.Type]string) map[component.Type]string {\n\tfor compType, factory := range factories {\n\t\tif ap, ok := any(factory).(aliasProvider); ok {\n\t\t\talias := ap.DeprecatedAlias()\n\t\t\tif alias.String() != \"\" {\n\t\t\t\tmodules[alias] = modules[compType]\n\t\t\t}\n\t\t}\n\t}\n\treturn modules\n}\n\nfunc components() (otelcol.Factories, error) {\n\tvar err error\n\tfactories := otelcol.Factories{\n\t\tTelemetry: otelconftelemetry.NewFactory(),\n\t}\n\n\tfactories.Extensions, err = otelcol.MakeFactoryMap[extension.Factory](\n\t\tmemorylimiterextension.NewFactory(),\n\t\tzpagesextension.NewFactory(),\n\t)\n\tif err != nil {\n\t\treturn otelcol.Factories{}, err\n\t}\n\tfactories.ExtensionModules = makeModulesMap(factories.Extensions, map[component.Type]string{\n\t\tmemorylimiterextension.NewFactory().Type(): \"go.opentelemetry.io/collector/extension/memorylimiterextension v0.148.0\",\n\t\tzpagesextension.NewFactory().Type():        \"go.opentelemetry.io/collector/extension/zpagesextension v0.148.0\",\n\t})\n\n\tfactories.Receivers, err = otelcol.MakeFactoryMap[receiver.Factory](\n\t\tnopreceiver.NewFactory(),\n\t\totlpreceiver.NewFactory(),\n\t)\n\tif err != nil {\n\t\treturn otelcol.Factories{}, err\n\t}\n\tfactories.ReceiverModules = makeModulesMap(factories.Receivers, map[component.Type]string{\n\t\tnopreceiver.NewFactory().Type():  \"go.opentelemetry.io/collector/receiver/nopreceiver v0.148.0\",\n\t\totlpreceiver.NewFactory().Type(): \"go.opentelemetry.io/collector/receiver/otlpreceiver v0.148.0\",\n\t})\n\n\tfactories.Exporters, err = otelcol.MakeFactoryMap[exporter.Factory](\n\t\tdebugexporter.NewFactory(),\n\t\tnopexporter.NewFactory(),\n\t\totlpexporter.NewFactory(),\n\t\totlphttpexporter.NewFactory(),\n\t)\n\tif err != nil {\n\t\treturn otelcol.Factories{}, err\n\t}\n\tfactories.ExporterModules = makeModulesMap(factories.Exporters, map[component.Type]string{\n\t\tdebugexporter.NewFactory().Type():    \"go.opentelemetry.io/collector/exporter/debugexporter v0.148.0\",\n\t\tnopexporter.NewFactory().Type():      \"go.opentelemetry.io/collector/exporter/nopexporter v0.148.0\",\n\t\totlpexporter.NewFactory().Type():     \"go.opentelemetry.io/collector/exporter/otlpexporter v0.148.0\",\n\t\totlphttpexporter.NewFactory().Type(): \"go.opentelemetry.io/collector/exporter/otlphttpexporter v0.148.0\",\n\t})\n\n\tfactories.Processors, err = otelcol.MakeFactoryMap[processor.Factory](\n\t\tbatchprocessor.NewFactory(),\n\t\tmemorylimiterprocessor.NewFactory(),\n\t)\n\tif err != nil {\n\t\treturn otelcol.Factories{}, err\n\t}\n\tfactories.ProcessorModules = makeModulesMap(factories.Processors, map[component.Type]string{\n\t\tbatchprocessor.NewFactory().Type():         \"go.opentelemetry.io/collector/processor/batchprocessor v0.148.0\",\n\t\tmemorylimiterprocessor.NewFactory().Type(): \"go.opentelemetry.io/collector/processor/memorylimiterprocessor v0.148.0\",\n\t})\n\n\tfactories.Connectors, err = otelcol.MakeFactoryMap[connector.Factory](\n\t\tforwardconnector.NewFactory(),\n\t)\n\tif err != nil {\n\t\treturn otelcol.Factories{}, err\n\t}\n\tfactories.ConnectorModules = makeModulesMap(factories.Connectors, map[component.Type]string{\n\t\tforwardconnector.NewFactory().Type(): \"go.opentelemetry.io/collector/connector/forwardconnector v0.148.0\",\n\t})\n\n\treturn factories, nil\n}\n"
  },
  {
    "path": "cmd/otelcorecol/go.mod",
    "content": "// Code generated by \"go.opentelemetry.io/collector/cmd/builder\". DO NOT EDIT.\n\nmodule go.opentelemetry.io/collector/cmd/otelcorecol\n\ngo 1.25.0\n\nrequire (\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/confmap/provider/envprovider v1.54.0\n\tgo.opentelemetry.io/collector/confmap/provider/fileprovider v1.54.0\n\tgo.opentelemetry.io/collector/confmap/provider/httpprovider v1.54.0\n\tgo.opentelemetry.io/collector/confmap/provider/httpsprovider v1.54.0\n\tgo.opentelemetry.io/collector/confmap/provider/yamlprovider v1.54.0\n\tgo.opentelemetry.io/collector/connector v0.148.0\n\tgo.opentelemetry.io/collector/connector/forwardconnector v0.148.0\n\tgo.opentelemetry.io/collector/exporter v1.54.0\n\tgo.opentelemetry.io/collector/exporter/debugexporter v0.148.0\n\tgo.opentelemetry.io/collector/exporter/nopexporter v0.148.0\n\tgo.opentelemetry.io/collector/exporter/otlpexporter v0.148.0\n\tgo.opentelemetry.io/collector/exporter/otlphttpexporter v0.148.0\n\tgo.opentelemetry.io/collector/extension v1.54.0\n\tgo.opentelemetry.io/collector/extension/memorylimiterextension v0.148.0\n\tgo.opentelemetry.io/collector/extension/zpagesextension v0.148.0\n\tgo.opentelemetry.io/collector/otelcol v0.148.0\n\tgo.opentelemetry.io/collector/processor v1.54.0\n\tgo.opentelemetry.io/collector/processor/batchprocessor v0.148.0\n\tgo.opentelemetry.io/collector/processor/memorylimiterprocessor v0.148.0\n\tgo.opentelemetry.io/collector/receiver v1.54.0\n\tgo.opentelemetry.io/collector/receiver/nopreceiver v0.148.0\n\tgo.opentelemetry.io/collector/receiver/otlpreceiver v0.148.0\n\tgo.opentelemetry.io/collector/service v0.148.0\n\tgolang.org/x/sys v0.42.0\n)\n\nrequire (\n\tgithub.com/beorn7/perks v1.0.1 // indirect\n\tgithub.com/cenkalti/backoff/v5 v5.0.3 // indirect\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect\n\tgithub.com/ebitengine/purego v0.10.0 // indirect\n\tgithub.com/felixge/httpsnoop v1.0.4 // indirect\n\tgithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f // indirect\n\tgithub.com/fsnotify/fsnotify v1.9.0 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-ole/go-ole v1.2.6 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/golang/snappy v1.0.0 // indirect\n\tgithub.com/google/go-tpm v0.9.8 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/hashicorp/golang-lru/v2 v2.0.7 // indirect\n\tgithub.com/inconshreveable/mousetrap v1.1.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/klauspost/compress v1.18.4 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/mostynb/go-grpc-compression v1.2.3 // indirect\n\tgithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect\n\tgithub.com/pierrec/lz4/v4 v4.1.26 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect\n\tgithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect\n\tgithub.com/prometheus/client_golang v1.23.2 // indirect\n\tgithub.com/prometheus/client_model v0.6.2 // indirect\n\tgithub.com/prometheus/common v0.67.5 // indirect\n\tgithub.com/prometheus/otlptranslator v1.0.0 // indirect\n\tgithub.com/prometheus/procfs v0.20.1 // indirect\n\tgithub.com/rs/cors v1.11.1 // indirect\n\tgithub.com/shirou/gopsutil/v4 v4.26.2 // indirect\n\tgithub.com/spf13/cobra v1.10.2 // indirect\n\tgithub.com/spf13/pflag v1.0.10 // indirect\n\tgithub.com/stretchr/testify v1.11.1 // indirect\n\tgithub.com/tklauser/go-sysconf v0.3.16 // indirect\n\tgithub.com/tklauser/numcpus v0.11.0 // indirect\n\tgithub.com/yusufpapurcu/wmi v1.2.4 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/client v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/component/componentstatus v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/config/configauth v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configcompression v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configgrpc v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/config/confighttp v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/config/configmiddleware v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/confignet v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configopaque v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configoptional v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configretry v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configtelemetry v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/config/configtls v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/connector/connectortest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/connector/xconnector v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumererror/xconsumererror v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/exporter/exporterhelper v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/exporter/exportertest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/exporter/xexporter v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionauth v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensioncapabilities v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionmiddleware v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensiontest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension/xextension v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/internal/fanoutconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/internal/memorylimiter v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/internal/sharedcomponent v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/internal/telemetry v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/xpdata v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/processor/processorhelper v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/processor/processorhelper/xprocessorhelper v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/processor/processortest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/processor/xprocessor v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/receiverhelper v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/receivertest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/service/hostcapabilities v0.148.0 // indirect\n\tgo.opentelemetry.io/contrib/bridges/otelzap v0.17.0 // indirect\n\tgo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 // indirect\n\tgo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect\n\tgo.opentelemetry.io/contrib/otelconf v0.22.0 // indirect\n\tgo.opentelemetry.io/contrib/propagators/b3 v1.42.0 // indirect\n\tgo.opentelemetry.io/contrib/zpages v0.67.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/prometheus v0.64.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/log v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/log v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.opentelemetry.io/proto/otlp v1.10.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v2 v2.4.3 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/crypto v0.48.0 // indirect\n\tgolang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgonum.org/v1/gonum v0.17.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector => ../../\n\nreplace go.opentelemetry.io/collector/client => ../../client\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/component/componentstatus => ../../component/componentstatus\n\nreplace go.opentelemetry.io/collector/config/configauth => ../../config/configauth\n\nreplace go.opentelemetry.io/collector/config/configcompression => ../../config/configcompression\n\nreplace go.opentelemetry.io/collector/config/configgrpc => ../../config/configgrpc\n\nreplace go.opentelemetry.io/collector/config/confighttp => ../../config/confighttp\n\nreplace go.opentelemetry.io/collector/config/configmiddleware => ../../config/configmiddleware\n\nreplace go.opentelemetry.io/collector/config/confignet => ../../config/confignet\n\nreplace go.opentelemetry.io/collector/config/configopaque => ../../config/configopaque\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../../config/configoptional\n\nreplace go.opentelemetry.io/collector/config/configretry => ../../config/configretry\n\nreplace go.opentelemetry.io/collector/config/configtelemetry => ../../config/configtelemetry\n\nreplace go.opentelemetry.io/collector/config/configtls => ../../config/configtls\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/confmap/provider/envprovider => ../../confmap/provider/envprovider\n\nreplace go.opentelemetry.io/collector/confmap/provider/fileprovider => ../../confmap/provider/fileprovider\n\nreplace go.opentelemetry.io/collector/confmap/provider/httpprovider => ../../confmap/provider/httpprovider\n\nreplace go.opentelemetry.io/collector/confmap/provider/httpsprovider => ../../confmap/provider/httpsprovider\n\nreplace go.opentelemetry.io/collector/confmap/provider/yamlprovider => ../../confmap/provider/yamlprovider\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/consumer/consumererror/xconsumererror => ../../consumer/consumererror/xconsumererror\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/connector => ../../connector\n\nreplace go.opentelemetry.io/collector/connector/connectortest => ../../connector/connectortest\n\nreplace go.opentelemetry.io/collector/connector/xconnector => ../../connector/xconnector\n\nreplace go.opentelemetry.io/collector/connector/forwardconnector => ../../connector/forwardconnector\n\nreplace go.opentelemetry.io/collector/exporter => ../../exporter\n\nreplace go.opentelemetry.io/collector/exporter/debugexporter => ../../exporter/debugexporter\n\nreplace go.opentelemetry.io/collector/exporter/exportertest => ../../exporter/exportertest\n\nreplace go.opentelemetry.io/collector/exporter/xexporter => ../../exporter/xexporter\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper => ../../exporter/exporterhelper\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper => ../../exporter/exporterhelper/xexporterhelper\n\nreplace go.opentelemetry.io/collector/exporter/nopexporter => ../../exporter/nopexporter\n\nreplace go.opentelemetry.io/collector/exporter/otlpexporter => ../../exporter/otlpexporter\n\nreplace go.opentelemetry.io/collector/exporter/otlphttpexporter => ../../exporter/otlphttpexporter\n\nreplace go.opentelemetry.io/collector/extension => ../../extension\n\nreplace go.opentelemetry.io/collector/extension/extensionauth => ../../extension/extensionauth\n\nreplace go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest => ../../extension/extensionauth/extensionauthtest\n\nreplace go.opentelemetry.io/collector/extension/extensioncapabilities => ../../extension/extensioncapabilities\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ../../extension/extensionmiddleware\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest => ../../extension/extensionmiddleware/extensionmiddlewaretest\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../../extension/extensiontest\n\nreplace go.opentelemetry.io/collector/extension/memorylimiterextension => ../../extension/memorylimiterextension\n\nreplace go.opentelemetry.io/collector/extension/xextension => ../../extension/xextension\n\nreplace go.opentelemetry.io/collector/extension/zpagesextension => ../../extension/zpagesextension\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n\nreplace go.opentelemetry.io/collector/internal/memorylimiter => ../../internal/memorylimiter\n\nreplace go.opentelemetry.io/collector/internal/fanoutconsumer => ../../internal/fanoutconsumer\n\nreplace go.opentelemetry.io/collector/internal/telemetry => ../../internal/telemetry\n\nreplace go.opentelemetry.io/collector/internal/sharedcomponent => ../../internal/sharedcomponent\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/otelcol => ../../otelcol\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/processor => ../../processor\n\nreplace go.opentelemetry.io/collector/processor/processortest => ../../processor/processortest\n\nreplace go.opentelemetry.io/collector/processor/batchprocessor => ../../processor/batchprocessor\n\nreplace go.opentelemetry.io/collector/processor/memorylimiterprocessor => ../../processor/memorylimiterprocessor\n\nreplace go.opentelemetry.io/collector/processor/xprocessor => ../../processor/xprocessor\n\nreplace go.opentelemetry.io/collector/processor/processorhelper/xprocessorhelper => ../../processor/processorhelper/xprocessorhelper\n\nreplace go.opentelemetry.io/collector/processor/processorhelper => ../../processor/processorhelper\n\nreplace go.opentelemetry.io/collector/receiver => ../../receiver\n\nreplace go.opentelemetry.io/collector/receiver/nopreceiver => ../../receiver/nopreceiver\n\nreplace go.opentelemetry.io/collector/receiver/receiverhelper => ../../receiver/receiverhelper\n\nreplace go.opentelemetry.io/collector/receiver/otlpreceiver => ../../receiver/otlpreceiver\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../../receiver/receivertest\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/service => ../../service\n\nreplace go.opentelemetry.io/collector/service/hostcapabilities => ../../service/hostcapabilities\n\nreplace go.opentelemetry.io/collector/service/telemetry/telemetrytest => ../../service/telemetry/telemetrytest\n"
  },
  {
    "path": "cmd/otelcorecol/go.sum",
    "content": "github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=\ngithub.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=\ngithub.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=\ngithub.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=\ngithub.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=\ngithub.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=\ngithub.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f h1:RJ+BDPLSHQO7cSjKBqjPJSbi1qfk9WcsjQDtZiw3dZw=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f/go.mod h1:VHbbch/X4roIY22jL1s3qRbZhCiRIgUAF/PdSUcx2io=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=\ngithub.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=\ngithub.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=\ngithub.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=\ngithub.com/google/go-tpm-tools v0.4.7 h1:J3ycC8umYxM9A4eF73EofRZu4BxY0jjQnUnkhIBbvws=\ngithub.com/google/go-tpm-tools v0.4.7/go.mod h1:gSyXTZHe3fgbzb6WEGd90QucmsnT1SRdlye82gH8QjQ=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=\ngithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=\ngithub.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=\ngithub.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=\ngithub.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=\ngithub.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=\ngithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3 h1:PwQumkgq4/acIiZhtifTV5OUqqiP82UAl0h87xj/l9k=\ngithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/mostynb/go-grpc-compression v1.2.3 h1:42/BKWMy0KEJGSdWvzqIyOZ95YcR9mLPqKctH7Uo//I=\ngithub.com/mostynb/go-grpc-compression v1.2.3/go.mod h1:AghIxF3P57umzqM9yz795+y1Vjs47Km/Y2FE6ouQ7Lg=\ngithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=\ngithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=\ngithub.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=\ngithub.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=\ngithub.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=\ngithub.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=\ngithub.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=\ngithub.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=\ngithub.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=\ngithub.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=\ngithub.com/prometheus/otlptranslator v1.0.0 h1:s0LJW/iN9dkIH+EnhiD3BlkkP5QVIUVEoIwkU+A6qos=\ngithub.com/prometheus/otlptranslator v1.0.0/go.mod h1:vRYWnXvI6aWGpsdY/mOT/cbeVRBlPWtBNDb7kGR3uKM=\ngithub.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc=\ngithub.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=\ngithub.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=\ngithub.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=\ngithub.com/shirou/gopsutil/v4 v4.26.2 h1:X8i6sicvUFih4BmYIGT1m2wwgw2VG9YgrDTi7cIRGUI=\ngithub.com/shirou/gopsutil/v4 v4.26.2/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=\ngithub.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=\ngithub.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=\ngithub.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=\ngithub.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngithub.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYICU0nA=\ngithub.com/tklauser/go-sysconf v0.3.16/go.mod h1:/qNL9xxDhc7tx3HSRsLWNnuzbVfh3e7gh/BmM179nYI=\ngithub.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9RXw=\ngithub.com/tklauser/numcpus v0.11.0/go.mod h1:z+LwcLq54uWZTX0u/bGobaV34u6V7KNlTZejzM6/3MQ=\ngithub.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=\ngithub.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/contrib/bridges/otelzap v0.17.0 h1:oCltVHJcblcth2z9B9dRTeZIZTe2Sf9Ad9h8bcc+s8M=\ngo.opentelemetry.io/contrib/bridges/otelzap v0.17.0/go.mod h1:G/VE1A/hRn6mEWdfC8rMvSdQVGM64KUPi4XilLkwcQw=\ngo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 h1:yI1/OhfEPy7J9eoa6Sj051C7n5dvpj0QX8g4sRchg04=\ngo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0/go.mod h1:NoUCKYWK+3ecatC4HjkRktREheMeEtrXoQxrqYFeHSc=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=\ngo.opentelemetry.io/contrib/otelconf v0.22.0 h1:+kpcfczGOFM85zDZyqQCzWefhovegfn24D0WwmQz0n4=\ngo.opentelemetry.io/contrib/otelconf v0.22.0/go.mod h1:ojdbOukO+JRDJQmJY2PRIZEg0UYVzcOuZR59hp7xffc=\ngo.opentelemetry.io/contrib/propagators/b3 v1.42.0 h1:B2Pew5ufEtgkjLF+tSkXjgYZXQr9m7aCm1wLKB0URbU=\ngo.opentelemetry.io/contrib/propagators/b3 v1.42.0/go.mod h1:iPgUcSEF5DORW6+yNbdw/YevUy+QqJ508ncjhrRSCjc=\ngo.opentelemetry.io/contrib/zpages v0.67.0 h1:cIUwWSVDovuLEbDIKreptjdxMuIhGiqwq0uL8YNaq1c=\ngo.opentelemetry.io/contrib/zpages v0.67.0/go.mod h1:vK8fsYHgPYg4Z/XDbFSEvItSGZDbjWTvjBOu8+AiDhc=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0 h1:deI9UQMoGFgrg5iLPgzueqFPHevDl+28YKfSpPTI6rY=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0/go.mod h1:PFx9NgpNUKXdf7J4Q3agRxMs3Y07QhTCVipKmLsMKnU=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0 h1:icqq3Z34UrEFk2u+HMhTtRsvo7Ues+eiJVjaJt62njs=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0/go.mod h1:W2m8P+d5Wn5kipj4/xmbt9uMqezEKfBjzVJadfABSBE=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0 h1:MdKucPl/HbzckWWEisiNqMPhRrAOQX8r4jTuGr636gk=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0/go.mod h1:RolT8tWtfHcjajEH5wFIZ4Dgh5jpPdFXYV9pTAk/qjc=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0 h1:H7O6RlGOMTizyl3R08Kn5pdM06bnH8oscSj7o11tmLA=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0/go.mod h1:mBFWu/WOVDkWWsR7Tx7h6EpQB8wsv7P0Yrh0Pb7othc=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 h1:THuZiwpQZuHPul65w4WcwEnkX2QIuMT+UFoOrygtoJw=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0/go.mod h1:J2pvYM5NGHofZ2/Ru6zw/TNWnEQp5crgyDeSrYpXkAw=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0 h1:zWWrB1U6nqhS/k6zYB74CjRpuiitRtLLi68VcgmOEto=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0/go.mod h1:2qXPNBX1OVRC0IwOnfo1ljoid+RD0QK3443EaqVlsOU=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 h1:uLXP+3mghfMf7XmV4PkGfFhFKuNWoCvvx5wP/wOXo0o=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0/go.mod h1:v0Tj04armyT59mnURNUJf7RCKcKzq+lgJs6QSjHjaTc=\ngo.opentelemetry.io/otel/exporters/prometheus v0.64.0 h1:g0LRDXMX/G1SEZtK8zl8Chm4K6GBwRkjPKE36LxiTYs=\ngo.opentelemetry.io/otel/exporters/prometheus v0.64.0/go.mod h1:UrgcjnarfdlBDP3GjDIJWe6HTprwSazNjwsI+Ru6hro=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0 h1:KJVjPD3rcPb98rIs3HznyJlrfx9ge5oJvxxlGR+P/7s=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0/go.mod h1:K3kRa2ckmHWQaTWQdPRHc7qGXASuVuoEQXzrvlA98Ws=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0 h1:lSZHgNHfbmQTPfuTmWVkEu8J8qXaQwuV30pjCcAUvP8=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0/go.mod h1:so9ounLcuoRDu033MW/E0AD4hhUjVqswrMF5FoZlBcw=\ngo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0 h1:s/1iRkCKDfhlh1JF26knRneorus8aOwVIDhvYx9WoDw=\ngo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0/go.mod h1:UI3wi0FXg1Pofb8ZBiBLhtMzgoTm1TYkMvn71fAqDzs=\ngo.opentelemetry.io/otel/log v0.18.0 h1:XgeQIIBjZZrliksMEbcwMZefoOSMI1hdjiLEiiB0bAg=\ngo.opentelemetry.io/otel/log v0.18.0/go.mod h1:KEV1kad0NofR3ycsiDH4Yjcoj0+8206I6Ox2QYFSNgI=\ngo.opentelemetry.io/otel/log/logtest v0.18.0 h1:2QeyoKJdIgK2LJhG1yn78o/zmpXx1EditeyRDREqVS8=\ngo.opentelemetry.io/otel/log/logtest v0.18.0/go.mod h1:v1vh3PYR9zIa5MK6HwkH2lMrLBg/Y9Of6Qc+krlesX0=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/log v0.18.0 h1:n8OyZr7t7otkeTnPTbDNom6rW16TBYGtvyy2Gk6buQw=\ngo.opentelemetry.io/otel/sdk/log v0.18.0/go.mod h1:C0+wxkTwKpOCZLrlJ3pewPiiQwpzycPI/u6W0Z9fuYk=\ngo.opentelemetry.io/otel/sdk/log/logtest v0.18.0 h1:l3mYuPsuBx6UKE47BVcPrZoZ0q/KER57vbj2qkgDLXA=\ngo.opentelemetry.io/otel/sdk/log/logtest v0.18.0/go.mod h1:7cHtiVJpZebB3wybTa4NG+FUo5NPe3PROz1FqB0+qdw=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=\ngo.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=\ngo.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=\ngolang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=\ngolang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa h1:Zt3DZoOFFYkKhDT3v7Lm9FDMEV06GpzjG2jrqW+QTE0=\ngolang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=\ngolang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=\ngonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=\ngoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 h1:tu/dtnW1o3wfaxCOjSLn5IRX4YDcJrtlpzYkhHhGaC4=\ngoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171/go.mod h1:M5krXqk4GhBKvB596udGL3UyjL4I1+cTbK0orROM9ng=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "cmd/otelcorecol/main.go",
    "content": "// Code generated by \"go.opentelemetry.io/collector/cmd/builder\". DO NOT EDIT.\n\n// Program otelcorecol is an OpenTelemetry Collector binary.\npackage main\n\nimport (\n\t\"os\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\tenvprovider \"go.opentelemetry.io/collector/confmap/provider/envprovider\"\n\tfileprovider \"go.opentelemetry.io/collector/confmap/provider/fileprovider\"\n\thttpprovider \"go.opentelemetry.io/collector/confmap/provider/httpprovider\"\n\thttpsprovider \"go.opentelemetry.io/collector/confmap/provider/httpsprovider\"\n\tyamlprovider \"go.opentelemetry.io/collector/confmap/provider/yamlprovider\"\n\t\"go.opentelemetry.io/collector/otelcol\"\n)\n\nfunc main() {\n\tinfo := component.BuildInfo{\n\t\tCommand:     \"otelcorecol\",\n\t\tDescription: \"Local OpenTelemetry Collector binary, testing only.\",\n\t\tVersion:     \"0.148.0-dev\",\n\t}\n\n\tset := otelcol.CollectorSettings{\n\t\tBuildInfo: info,\n\t\tFactories: components,\n\t\tConfigProviderSettings: otelcol.ConfigProviderSettings{\n\t\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\t\tProviderFactories: []confmap.ProviderFactory{\n\t\t\t\t\tenvprovider.NewFactory(),\n\t\t\t\t\tfileprovider.NewFactory(),\n\t\t\t\t\thttpprovider.NewFactory(),\n\t\t\t\t\thttpsprovider.NewFactory(),\n\t\t\t\t\tyamlprovider.NewFactory(),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\tProviderModules: map[string]string{\n\t\t\tenvprovider.NewFactory().Create(confmap.ProviderSettings{}).Scheme():   \"go.opentelemetry.io/collector/confmap/provider/envprovider v1.54.0\",\n\t\t\tfileprovider.NewFactory().Create(confmap.ProviderSettings{}).Scheme():  \"go.opentelemetry.io/collector/confmap/provider/fileprovider v1.54.0\",\n\t\t\thttpprovider.NewFactory().Create(confmap.ProviderSettings{}).Scheme():  \"go.opentelemetry.io/collector/confmap/provider/httpprovider v1.54.0\",\n\t\t\thttpsprovider.NewFactory().Create(confmap.ProviderSettings{}).Scheme(): \"go.opentelemetry.io/collector/confmap/provider/httpsprovider v1.54.0\",\n\t\t\tyamlprovider.NewFactory().Create(confmap.ProviderSettings{}).Scheme():  \"go.opentelemetry.io/collector/confmap/provider/yamlprovider v1.54.0\",\n\t\t},\n\t\tConverterModules: []string{},\n\t}\n\n\tif err := run(set); err != nil {\n\t\t// The error message is logged by cobra, so we intentionally\n\t\t// avoid logging it again here to prevent duplicate output.\n\t\tos.Exit(1)\n\t}\n}\n\nfunc runInteractive(params otelcol.CollectorSettings) error {\n\tcmd := otelcol.NewCommand(params)\n\tif err := cmd.Execute(); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "cmd/otelcorecol/main_others.go",
    "content": "// Code generated by \"go.opentelemetry.io/collector/cmd/builder\". DO NOT EDIT.\n\n//go:build !windows\n\npackage main\n\nimport \"go.opentelemetry.io/collector/otelcol\"\n\nfunc run(params otelcol.CollectorSettings) error {\n\treturn runInteractive(params)\n}\n"
  },
  {
    "path": "cmd/otelcorecol/main_windows.go",
    "content": "// Code generated by \"go.opentelemetry.io/collector/cmd/builder\". DO NOT EDIT.\n\n//go:build windows\n\npackage main\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"golang.org/x/sys/windows\"\n\t\"golang.org/x/sys/windows/svc\"\n\n\t\"go.opentelemetry.io/collector/otelcol\"\n)\n\nfunc run(params otelcol.CollectorSettings) error {\n\t// No need to supply service name when startup is invoked through\n\t// the Service Control Manager directly.\n\tif err := svc.Run(\"\", otelcol.NewSvcHandler(params)); err != nil {\n\t\tif errors.Is(err, windows.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT) {\n\t\t\t// Per https://learn.microsoft.com/en-us/windows/win32/api/winsvc/nf-winsvc-startservicectrldispatchera#return-value\n\t\t\t// this means that the process is not running as a service, so run interactively.\n\t\t\treturn runInteractive(params)\n\t\t}\n\n\t\treturn fmt.Errorf(\"failed to start collector server: %w\", err)\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "component/Makefile",
    "content": "include ../Makefile.Common\n"
  },
  {
    "path": "component/build_info.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage component // import \"go.opentelemetry.io/collector/component\"\n\n// BuildInfo is the information that is logged at the application start and\n// passed into each component. This information can be overridden in custom build.\ntype BuildInfo struct {\n\t// Command is the executable file name, e.g. \"otelcol\".\n\tCommand string\n\n\t// Description is the full name of the collector, e.g. \"OpenTelemetry Collector\".\n\tDescription string\n\n\t// Version string.\n\tVersion string\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// NewDefaultBuildInfo returns a default BuildInfo.\nfunc NewDefaultBuildInfo() BuildInfo {\n\treturn BuildInfo{\n\t\tCommand:     \"otelcol\",\n\t\tDescription: \"OpenTelemetry Collector\",\n\t\tVersion:     \"latest\",\n\t}\n}\n"
  },
  {
    "path": "component/component.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package component outlines the abstraction of components within the OpenTelemetry Collector. It provides details on the component\n// lifecycle as well as defining the interface that components must fulfill.\npackage component // import \"go.opentelemetry.io/collector/component\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n)\n\n// Component is either a receiver, exporter, processor, connector, or an extension.\n//\n// A component's lifecycle has the following phases:\n//\n//  1. Creation: The component is created using its respective factory, via a Create* call.\n//  2. Start: The component's Start method is called.\n//  3. Running: The component is up and running.\n//  4. Shutdown: The component's Shutdown method is called and the lifecycle is complete.\n//\n// Once the lifecycle is complete it may be repeated, in which case a new component\n// is created, starts, runs and is shutdown again.\ntype Component interface {\n\t// Start tells the component to start. Host parameter can be used for communicating\n\t// with the host after Start() has already returned. If an error is returned by\n\t// Start() then the collector startup will be aborted.\n\t// If this is an exporter component it may prepare for exporting\n\t// by connecting to the endpoint.\n\t//\n\t// If the component needs to perform a long-running starting operation, then\n\t// it is recommended that Start() returns quickly and the long-running\n\t// operation is performed in the background. Background operations should\n\t// create their own context using context.WithCancel(context.Background())\n\t// rather than using the passed context, which is intended only for the\n\t// startup operation itself. The component should cancel this context in its\n\t// Shutdown() method.\n\t//\n\t// Note: as of today, the context passed to Start() lives for the entire\n\t// lifetime of the collector, but this may change in the future to include a\n\t// startup timeout.\n\tStart(ctx context.Context, host Host) error\n\n\t// Shutdown is invoked during service shutdown. After Shutdown() is called, if the component\n\t// accepted data in any way, it should not accept it anymore.\n\t//\n\t// This method must be safe to call:\n\t//   - without Start() having been called\n\t//   - if the component is in a shutdown state already\n\t//\n\t// If there are any background operations running by the component they must be aborted before\n\t// this function returns. Remember that if you started any long-running background operations from\n\t// the Start() method, those operations must be also cancelled. If there are any buffers in the\n\t// component, they should be flushed with the data being sent immediately to the next component.\n\t//\n\t// The component's lifecycle is completed once the Shutdown() method returns. No other\n\t// methods of the component are called after that. If necessary a new component with\n\t// the same or different configuration may be created and started (this may happen\n\t// for example if we want to restart the component).\n\tShutdown(ctx context.Context) error\n}\n\n// StartFunc specifies the function invoked when the component.Component is being started.\ntype StartFunc func(context.Context, Host) error\n\n// Start starts the component.\nfunc (f StartFunc) Start(ctx context.Context, host Host) error {\n\tif f == nil {\n\t\treturn nil\n\t}\n\treturn f(ctx, host)\n}\n\n// ShutdownFunc specifies the function invoked when the component.Component is being shutdown.\ntype ShutdownFunc func(context.Context) error\n\n// Shutdown shuts down the component.\nfunc (f ShutdownFunc) Shutdown(ctx context.Context) error {\n\tif f == nil {\n\t\treturn nil\n\t}\n\treturn f(ctx)\n}\n\n// Kind represents component kinds.\ntype Kind struct {\n\tname string\n}\n\nvar (\n\tKindReceiver  = Kind{name: \"Receiver\"}\n\tKindProcessor = Kind{name: \"Processor\"}\n\tKindExporter  = Kind{name: \"Exporter\"}\n\tKindExtension = Kind{name: \"Extension\"}\n\tKindConnector = Kind{name: \"Connector\"}\n)\n\nfunc (k Kind) String() string {\n\treturn k.name\n}\n\n// StabilityLevel represents the stability level of the component created by the factory.\n// The stability level is used to determine if the component should be used in production\n// or not. For more details see:\n// https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stability-levels\ntype StabilityLevel int\n\nconst (\n\tStabilityLevelUndefined StabilityLevel = iota // skip 0, start types from 1.\n\tStabilityLevelUnmaintained\n\tStabilityLevelDeprecated\n\tStabilityLevelDevelopment\n\tStabilityLevelAlpha\n\tStabilityLevelBeta\n\tStabilityLevelStable\n)\n\nfunc (sl *StabilityLevel) UnmarshalText(in []byte) error {\n\tstr := strings.ToLower(string(in))\n\tswitch str {\n\tcase \"undefined\":\n\t\t*sl = StabilityLevelUndefined\n\tcase \"unmaintained\":\n\t\t*sl = StabilityLevelUnmaintained\n\tcase \"deprecated\":\n\t\t*sl = StabilityLevelDeprecated\n\tcase \"development\":\n\t\t*sl = StabilityLevelDevelopment\n\tcase \"alpha\":\n\t\t*sl = StabilityLevelAlpha\n\tcase \"beta\":\n\t\t*sl = StabilityLevelBeta\n\tcase \"stable\":\n\t\t*sl = StabilityLevelStable\n\tdefault:\n\t\treturn fmt.Errorf(\"unsupported stability level: %q\", string(in))\n\t}\n\treturn nil\n}\n\nfunc (sl StabilityLevel) String() string {\n\tswitch sl {\n\tcase StabilityLevelUndefined:\n\t\treturn \"Undefined\"\n\tcase StabilityLevelUnmaintained:\n\t\treturn \"Unmaintained\"\n\tcase StabilityLevelDeprecated:\n\t\treturn \"Deprecated\"\n\tcase StabilityLevelDevelopment:\n\t\treturn \"Development\"\n\tcase StabilityLevelAlpha:\n\t\treturn \"Alpha\"\n\tcase StabilityLevelBeta:\n\t\treturn \"Beta\"\n\tcase StabilityLevelStable:\n\t\treturn \"Stable\"\n\t}\n\treturn \"\"\n}\n\nfunc (sl StabilityLevel) LogMessage() string {\n\tswitch sl {\n\tcase StabilityLevelUnmaintained:\n\t\treturn \"Unmaintained component. Actively looking for contributors. Component will become deprecated after 3 months of remaining unmaintained.\"\n\tcase StabilityLevelDeprecated:\n\t\treturn \"Deprecated component. Will be removed in future releases.\"\n\tcase StabilityLevelDevelopment:\n\t\treturn \"Development component. May change in the future.\"\n\tcase StabilityLevelAlpha:\n\t\treturn \"Alpha component. May change in the future.\"\n\tcase StabilityLevelBeta:\n\t\treturn \"Beta component. May change in the future.\"\n\tcase StabilityLevelStable:\n\t\treturn \"Stable component.\"\n\tdefault:\n\t\treturn \"Stability level of component is undefined\"\n\t}\n}\n\n// Factory is implemented by all Component factories.\ntype Factory interface {\n\t// Type gets the type of the component created by this factory.\n\tType() Type\n\n\t// CreateDefaultConfig creates the default configuration for the Component.\n\t// This method can be called multiple times depending on the pipeline\n\t// configuration and should not cause side effects that prevent the creation\n\t// of multiple instances of the Component.\n\t// The object returned by this method needs to pass the checks implemented by\n\t// 'componenttest.CheckConfigStruct'. It is recommended to have these checks in the\n\t// tests of any implementation of the Factory interface.\n\tCreateDefaultConfig() Config\n}\n\n// CreateDefaultConfigFunc is the equivalent of Factory.CreateDefaultConfig().\ntype CreateDefaultConfigFunc func() Config\n\n// CreateDefaultConfig implements Factory.CreateDefaultConfig().\nfunc (f CreateDefaultConfigFunc) CreateDefaultConfig() Config {\n\treturn f()\n}\n"
  },
  {
    "path": "component/component_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage component\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestKindString(t *testing.T) {\n\tassert.Empty(t, Kind{}.String())\n\tassert.Equal(t, \"Receiver\", KindReceiver.String())\n\tassert.Equal(t, \"Processor\", KindProcessor.String())\n\tassert.Equal(t, \"Exporter\", KindExporter.String())\n\tassert.Equal(t, \"Extension\", KindExtension.String())\n\tassert.Equal(t, \"Connector\", KindConnector.String())\n}\n\nfunc TestStabilityLevelUnmarshal(t *testing.T) {\n\ttests := []struct {\n\t\tinput       string\n\t\toutput      StabilityLevel\n\t\texpectedErr string\n\t}{\n\t\t{\n\t\t\tinput:  \"Undefined\",\n\t\t\toutput: StabilityLevelUndefined,\n\t\t},\n\t\t{\n\t\t\tinput:  \"UnmaintaineD\",\n\t\t\toutput: StabilityLevelUnmaintained,\n\t\t},\n\t\t{\n\t\t\tinput:  \"DepreCated\",\n\t\t\toutput: StabilityLevelDeprecated,\n\t\t},\n\t\t{\n\t\t\tinput:  \"Development\",\n\t\t\toutput: StabilityLevelDevelopment,\n\t\t},\n\t\t{\n\t\t\tinput:  \"alpha\",\n\t\t\toutput: StabilityLevelAlpha,\n\t\t},\n\t\t{\n\t\t\tinput:  \"BETA\",\n\t\t\toutput: StabilityLevelBeta,\n\t\t},\n\t\t{\n\t\t\tinput:  \"sTABLe\",\n\t\t\toutput: StabilityLevelStable,\n\t\t},\n\t\t{\n\t\t\tinput:       \"notfound\",\n\t\t\texpectedErr: \"unsupported stability level: \\\"notfound\\\"\",\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.input, func(t *testing.T) {\n\t\t\tvar sl StabilityLevel\n\t\t\terr := sl.UnmarshalText([]byte(test.input))\n\t\t\tif test.expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, test.expectedErr)\n\t\t\t} else {\n\t\t\t\tassert.Equal(t, test.output, sl)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestStabilityLevelString(t *testing.T) {\n\tassert.Equal(t, \"Undefined\", StabilityLevelUndefined.String())\n\tassert.Equal(t, \"Unmaintained\", StabilityLevelUnmaintained.String())\n\tassert.Equal(t, \"Deprecated\", StabilityLevelDeprecated.String())\n\tassert.Equal(t, \"Development\", StabilityLevelDevelopment.String())\n\tassert.Equal(t, \"Alpha\", StabilityLevelAlpha.String())\n\tassert.Equal(t, \"Beta\", StabilityLevelBeta.String())\n\tassert.Equal(t, \"Stable\", StabilityLevelStable.String())\n\tassert.Empty(t, StabilityLevel(100).String())\n}\n\nfunc TestStabilityLevelLogMessage(t *testing.T) {\n\tassert.Equal(t, \"Stability level of component is undefined\", StabilityLevelUndefined.LogMessage())\n\tassert.Equal(t, \"Unmaintained component. Actively looking for contributors. Component will become deprecated after 3 months of remaining unmaintained.\", StabilityLevelUnmaintained.LogMessage())\n\tassert.Equal(t, \"Deprecated component. Will be removed in future releases.\", StabilityLevelDeprecated.LogMessage())\n\tassert.Equal(t, \"Development component. May change in the future.\", StabilityLevelDevelopment.LogMessage())\n\tassert.Equal(t, \"Alpha component. May change in the future.\", StabilityLevelAlpha.LogMessage())\n\tassert.Equal(t, \"Beta component. May change in the future.\", StabilityLevelBeta.LogMessage())\n\tassert.Equal(t, \"Stable component.\", StabilityLevelStable.LogMessage())\n\tassert.Equal(t, \"Stability level of component is undefined\", StabilityLevel(100).LogMessage())\n}\n"
  },
  {
    "path": "component/componentstatus/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "component/componentstatus/go.mod",
    "content": "module go.opentelemetry.io/collector/component/componentstatus\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n"
  },
  {
    "path": "component/componentstatus/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "component/componentstatus/instance.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componentstatus // import \"go.opentelemetry.io/collector/component/componentstatus\"\n\nimport (\n\t\"slices\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\n// pipelineDelim is the delimiter for internal representation of pipeline\n// component IDs.\nconst pipelineDelim = byte(0x20)\n\n// InstanceID uniquely identifies a component instance\n//\n// TODO: consider moving this struct to a new package/module like `extension/statuswatcher`\n// https://github.com/open-telemetry/opentelemetry-collector/issues/10764\ntype InstanceID struct {\n\tcomponentID component.ID\n\tkind        component.Kind\n\tpipelineIDs string // IDs encoded as a string so InstanceID is Comparable.\n}\n\n// NewInstanceID returns an ID that uniquely identifies a component.\nfunc NewInstanceID(componentID component.ID, kind component.Kind, pipelineIDs ...pipeline.ID) *InstanceID {\n\tinstanceID := &InstanceID{\n\t\tcomponentID: componentID,\n\t\tkind:        kind,\n\t}\n\tinstanceID.addPipelines(pipelineIDs)\n\treturn instanceID\n}\n\n// ComponentID returns the ComponentID associated with this instance.\nfunc (id *InstanceID) ComponentID() component.ID {\n\treturn id.componentID\n}\n\n// Kind returns the component Kind associated with this instance.\nfunc (id *InstanceID) Kind() component.Kind {\n\treturn id.kind\n}\n\n// AllPipelineIDs calls f for each pipeline this instance is associated with. If\n// f returns false it will stop iteration.\nfunc (id *InstanceID) AllPipelineIDs(f func(pipeline.ID) bool) {\n\tvar bs []byte\n\tfor _, b := range []byte(id.pipelineIDs) {\n\t\tif b != pipelineDelim {\n\t\t\tbs = append(bs, b)\n\t\t\tcontinue\n\t\t}\n\t\tpipelineID := pipeline.ID{}\n\t\terr := pipelineID.UnmarshalText(bs)\n\t\tbs = bs[:0]\n\t\tif err != nil {\n\t\t\tcontinue\n\t\t}\n\t\tif !f(pipelineID) {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n// WithPipelines returns a new InstanceID updated to include the given\n// pipelineIDs.\nfunc (id *InstanceID) WithPipelines(pipelineIDs ...pipeline.ID) *InstanceID {\n\tinstanceID := &InstanceID{\n\t\tcomponentID: id.componentID,\n\t\tkind:        id.kind,\n\t\tpipelineIDs: id.pipelineIDs,\n\t}\n\tinstanceID.addPipelines(pipelineIDs)\n\treturn instanceID\n}\n\nfunc (id *InstanceID) addPipelines(pipelineIDs []pipeline.ID) {\n\tdelim := string(pipelineDelim)\n\tstrIDs := strings.Split(id.pipelineIDs, delim)\n\tfor _, pID := range pipelineIDs {\n\t\tstrIDs = append(strIDs, pID.String())\n\t}\n\tsort.Strings(strIDs)\n\tstrIDs = slices.Compact(strIDs)\n\tid.pipelineIDs = strings.Join(strIDs, delim) + delim\n}\n"
  },
  {
    "path": "component/componentstatus/instance_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componentstatus\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\nfunc TestInstanceID(t *testing.T) {\n\ttraces := component.MustNewID(\"traces\")\n\ttracesA := pipeline.NewIDWithName(pipeline.SignalTraces, \"a\")\n\ttracesB := pipeline.NewIDWithName(pipeline.SignalTraces, \"b\")\n\ttracesC := pipeline.NewIDWithName(pipeline.SignalTraces, \"c\")\n\n\tidTracesA := NewInstanceID(traces, component.KindReceiver, tracesA)\n\tidTracesAll := NewInstanceID(traces, component.KindReceiver, tracesA, tracesB, tracesC)\n\tassert.NotEqual(t, idTracesA, idTracesAll)\n\n\tassertHasPipelines := func(t *testing.T, instanceID *InstanceID, expectedPipelineIDs []pipeline.ID) {\n\t\tvar pipelineIDs []pipeline.ID\n\t\tinstanceID.AllPipelineIDs(func(id pipeline.ID) bool {\n\t\t\tpipelineIDs = append(pipelineIDs, id)\n\t\t\treturn true\n\t\t})\n\t\tassert.Equal(t, expectedPipelineIDs, pipelineIDs)\n\t}\n\n\tfor _, tc := range []struct {\n\t\tname        string\n\t\tid1         *InstanceID\n\t\tid2         *InstanceID\n\t\tpipelineIDs []pipeline.ID\n\t}{\n\t\t{\n\t\t\tname:        \"equal instances\",\n\t\t\tid1:         idTracesA,\n\t\t\tid2:         NewInstanceID(traces, component.KindReceiver, tracesA),\n\t\t\tpipelineIDs: []pipeline.ID{tracesA},\n\t\t},\n\t\t{\n\t\t\tname:        \"equal instances - out of order\",\n\t\t\tid1:         idTracesAll,\n\t\t\tid2:         NewInstanceID(traces, component.KindReceiver, tracesC, tracesB, tracesA),\n\t\t\tpipelineIDs: []pipeline.ID{tracesA, tracesB, tracesC},\n\t\t},\n\t\t{\n\t\t\tname:        \"with pipelines\",\n\t\t\tid1:         idTracesAll,\n\t\t\tid2:         idTracesA.WithPipelines(tracesB, tracesC),\n\t\t\tpipelineIDs: []pipeline.ID{tracesA, tracesB, tracesC},\n\t\t},\n\t\t{\n\t\t\tname:        \"with pipelines - out of order\",\n\t\t\tid1:         idTracesAll,\n\t\t\tid2:         idTracesA.WithPipelines(tracesC, tracesB),\n\t\t\tpipelineIDs: []pipeline.ID{tracesA, tracesB, tracesC},\n\t\t},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tassert.Equal(t, tc.id1, tc.id2)\n\t\t\tassertHasPipelines(t, tc.id1, tc.pipelineIDs)\n\t\t\tassertHasPipelines(t, tc.id2, tc.pipelineIDs)\n\t\t})\n\t}\n}\n\nfunc TestAllPipelineIDs(t *testing.T) {\n\tinstanceID := NewInstanceID(\n\t\tcomponent.MustNewID(\"traces\"),\n\t\tcomponent.KindReceiver,\n\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"a\"),\n\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"b\"),\n\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"c\"),\n\t)\n\n\tcount := 0\n\tinstanceID.AllPipelineIDs(func(pipeline.ID) bool {\n\t\tcount++\n\t\treturn true\n\t})\n\tassert.Equal(t, 3, count)\n\n\tcount = 0\n\tinstanceID.AllPipelineIDs(func(pipeline.ID) bool {\n\t\tcount++\n\t\treturn false\n\t})\n\tassert.Equal(t, 1, count)\n}\n"
  },
  {
    "path": "component/componentstatus/metadata.yaml",
    "content": "type: component/componentstatus\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "component/componentstatus/status.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package componentstatus is an experimental module that defines how components should\n// report health statues, how collector hosts should facilitate component status reporting,\n// and how extensions should watch for new component statuses.\n//\n// This package is currently under development and is exempt from the Collector SIG's\n// breaking change policy.\npackage componentstatus // import \"go.opentelemetry.io/collector/component/componentstatus\"\n\nimport (\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// Reporter is an extra interface for `component.Host` implementations.\n// A Reporter defines how to report a `componentstatus.Event`.\ntype Reporter interface {\n\t// Report allows a component to report runtime changes in status. The service\n\t// will automatically report status for a component during startup and shutdown. Components can\n\t// use this method to report status after start and before shutdown. For more details about\n\t// component status reporting see: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-status.md\n\tReport(*Event)\n}\n\n// Watcher is an extra interface for Extension hosted by the OpenTelemetry\n// Collector that is to be implemented by extensions interested in changes to component\n// status.\n//\n// TODO: consider moving this interface to a new package/module like `extension/statuswatcher`\n// https://github.com/open-telemetry/opentelemetry-collector/issues/10764\ntype Watcher interface {\n\t// ComponentStatusChanged notifies about a change in the source component status.\n\t// Extensions that implement this interface must be ready that the ComponentStatusChanged\n\t// may be called before, after or concurrently with calls to Component.Start() and Component.Shutdown().\n\t// The function may be called concurrently with itself.\n\tComponentStatusChanged(source *InstanceID, event *Event)\n}\n\ntype Status int32\n\n// Enumeration of possible component statuses\nconst (\n\t// StatusNone indicates absence of component status.\n\tStatusNone Status = iota\n\t// StatusStarting indicates the component is starting.\n\tStatusStarting\n\t// StatusOK indicates the component is running without issues.\n\tStatusOK\n\t// StatusRecoverableError indicates that the component has experienced a transient error and may recover.\n\tStatusRecoverableError\n\t// StatusPermanentError indicates that the component has detected a condition at runtime that will need human intervention to fix. The collector will continue to run in a degraded mode.\n\tStatusPermanentError\n\t// StatusFatalError indicates that the collector has experienced a fatal runtime error and will shut down.\n\tStatusFatalError\n\t// StatusStopping indicates that the component is in the process of shutting down.\n\tStatusStopping\n\t// StatusStopped indicates that the component has completed shutdown.\n\tStatusStopped\n)\n\n// String returns a string representation of a Status\nfunc (s Status) String() string {\n\tswitch s {\n\tcase StatusStarting:\n\t\treturn \"StatusStarting\"\n\tcase StatusOK:\n\t\treturn \"StatusOK\"\n\tcase StatusRecoverableError:\n\t\treturn \"StatusRecoverableError\"\n\tcase StatusPermanentError:\n\t\treturn \"StatusPermanentError\"\n\tcase StatusFatalError:\n\t\treturn \"StatusFatalError\"\n\tcase StatusStopping:\n\t\treturn \"StatusStopping\"\n\tcase StatusStopped:\n\t\treturn \"StatusStopped\"\n\t}\n\treturn \"StatusNone\"\n}\n\n// Event contains a status, a timestamp, optional error information, and additional attributes\ntype Event struct {\n\t// attributes provides additional context or metadata for the event.\n\tattributes pcommon.Map\n\n\tstatus Status\n\terr    error\n\t// TODO: consider if a timestamp is necessary in the default Event struct or is needed only for the healthcheckv2 extension\n\t// https://github.com/open-telemetry/opentelemetry-collector/issues/10763\n\ttimestamp time.Time\n}\n\n// Status returns the Status (enum) associated with the Event\nfunc (ev *Event) Status() Status {\n\treturn ev.status\n}\n\n// Err returns the error associated with the Event.\nfunc (ev *Event) Err() error {\n\treturn ev.err\n}\n\n// Attributes returns the attributes (pcommon.Map) associated with the Event.\nfunc (ev *Event) Attributes() pcommon.Map {\n\treturn ev.attributes\n}\n\n// Timestamp returns the timestamp associated with the Event\nfunc (ev *Event) Timestamp() time.Time {\n\treturn ev.timestamp\n}\n\n// EventBuilderOption is a sealed interface wrapping options for [NewEvent].\ntype EventBuilderOption interface {\n\tapplyOption(*Event)\n}\n\ntype eventOptionFunc func(*Event)\n\nfunc (f eventOptionFunc) applyOption(event *Event) {\n\tf(event)\n}\n\n// NewEvent creates and returns an Event with the specified options and sets the timestamp\n// time.Now(). To set an error on the event for an error status use the\n// WithError with one of the dedicated status (e.g. StatusRecoverableError, StatusPermanentError, StatusFatalError)\nfunc NewEvent(st Status, opts ...EventBuilderOption) *Event {\n\tevent := &Event{\n\t\ttimestamp:  time.Now(),\n\t\tattributes: pcommon.NewMap(),\n\t\tstatus:     st,\n\t}\n\n\tfor _, opt := range opts {\n\t\topt.applyOption(event)\n\t}\n\n\treturn event\n}\n\n// WithAttributes sets the Event attributes.\nfunc WithAttributes(attributes pcommon.Map) EventBuilderOption {\n\treturn eventOptionFunc(func(e *Event) {\n\t\te.attributes = attributes\n\t})\n}\n\n// WithError sets the Event error.\nfunc WithError(err error) EventBuilderOption {\n\treturn eventOptionFunc(func(e *Event) {\n\t\te.err = err\n\t})\n}\n\n// NewRecoverableErrorEvent wraps a transient error\n// passed as argument as a Event with a status StatusRecoverableError\n// and a timestamp set to time.Now().\nfunc NewRecoverableErrorEvent(err error) *Event {\n\treturn NewEvent(StatusRecoverableError, WithError(err))\n}\n\n// NewPermanentErrorEvent wraps an error requiring human intervention to fix\n// passed as argument as a Event with a status StatusPermanentError\n// and a timestamp set to time.Now().\nfunc NewPermanentErrorEvent(err error) *Event {\n\treturn NewEvent(StatusPermanentError, WithError(err))\n}\n\n// NewFatalErrorEvent wraps the fatal runtime error passed as argument as a Event\n// with a status StatusFatalError and a timestamp set to time.Now().\nfunc NewFatalErrorEvent(err error) *Event {\n\treturn NewEvent(StatusFatalError, WithError(err))\n}\n\n// StatusIsError returns true for error statuses (e.g. StatusRecoverableError,\n// StatusPermanentError, or StatusFatalError)\nfunc StatusIsError(status Status) bool {\n\treturn status == StatusRecoverableError ||\n\t\tstatus == StatusPermanentError ||\n\t\tstatus == StatusFatalError\n}\n\n// ReportStatus is a helper function that handles checking if the component.Host has implemented Reporter.\n// If it has, the Event is reported. Otherwise, nothing happens.\nfunc ReportStatus(host component.Host, e *Event) {\n\tstatusReporter, ok := host.(Reporter)\n\tif ok {\n\t\tstatusReporter.Report(e)\n\t}\n}\n"
  },
  {
    "path": "component/componentstatus/status_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\npackage componentstatus\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestNewStatusEvent(t *testing.T) {\n\tstatuses := []Status{\n\t\tStatusStarting,\n\t\tStatusOK,\n\t\tStatusRecoverableError,\n\t\tStatusPermanentError,\n\t\tStatusFatalError,\n\t\tStatusStopping,\n\t\tStatusStopped,\n\t}\n\n\tfor _, status := range statuses {\n\t\tt.Run(fmt.Sprintf(\"%s without error\", status), func(t *testing.T) {\n\t\t\tev := NewEvent(status)\n\t\t\trequire.Equal(t, status, ev.Status())\n\t\t\trequire.NoError(t, ev.Err())\n\t\t\trequire.False(t, ev.Timestamp().IsZero())\n\t\t\trequire.Equal(t, pcommon.NewMap(), ev.Attributes())\n\t\t})\n\t\tt.Run(fmt.Sprintf(\"%s without error and attributes\", status), func(t *testing.T) {\n\t\t\teventAttrs := pcommon.NewMap()\n\t\t\trequire.NoError(t, eventAttrs.FromRaw(map[string]any{\"test\": \"a\"}))\n\t\t\tev := NewEvent(status, WithAttributes(eventAttrs))\n\t\t\trequire.Equal(t, status, ev.Status())\n\t\t\trequire.NoError(t, ev.Err())\n\t\t\trequire.False(t, ev.Timestamp().IsZero())\n\t\t\trequire.Equal(t, eventAttrs, ev.Attributes())\n\t\t})\n\t}\n}\n\nfunc TestStatusEventsWithError(t *testing.T) {\n\tstatusConstructorMap := map[Status]func(error) *Event{\n\t\tStatusRecoverableError: NewRecoverableErrorEvent,\n\t\tStatusPermanentError:   NewPermanentErrorEvent,\n\t\tStatusFatalError:       NewFatalErrorEvent,\n\t}\n\n\tfor status, newEvent := range statusConstructorMap {\n\t\tt.Run(fmt.Sprintf(\"error status constructor for: %s\", status), func(t *testing.T) {\n\t\t\tev := newEvent(assert.AnError)\n\t\t\trequire.Equal(t, status, ev.Status())\n\t\t\trequire.Equal(t, assert.AnError, ev.Err())\n\t\t\trequire.False(t, ev.Timestamp().IsZero())\n\t\t})\n\t}\n}\n\nfunc TestStatusIsError(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tstatus  Status\n\t\tisError bool\n\t}{\n\t\t{\n\t\t\tstatus:  StatusStarting,\n\t\t\tisError: false,\n\t\t},\n\t\t{\n\t\t\tstatus:  StatusOK,\n\t\t\tisError: false,\n\t\t},\n\t\t{\n\t\t\tstatus:  StatusRecoverableError,\n\t\t\tisError: true,\n\t\t},\n\t\t{\n\t\t\tstatus:  StatusPermanentError,\n\t\t\tisError: true,\n\t\t},\n\t\t{\n\t\t\tstatus:  StatusFatalError,\n\t\t\tisError: true,\n\t\t},\n\t\t{\n\t\t\tstatus:  StatusStopping,\n\t\t\tisError: false,\n\t\t},\n\t\t{\n\t\t\tstatus:  StatusStopped,\n\t\t\tisError: false,\n\t\t},\n\t} {\n\t\tname := fmt.Sprintf(\"StatusIsError(%s) is %t\", tc.status, tc.isError)\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tassert.Equal(t, tc.isError, StatusIsError(tc.status))\n\t\t})\n\t}\n}\n\nfunc Test_ReportStatus(t *testing.T) {\n\tt.Run(\"Reporter implemented\", func(t *testing.T) {\n\t\tr := &reporter{}\n\t\tReportStatus(r, NewEvent(StatusOK))\n\t\trequire.True(t, r.reportStatusCalled)\n\t})\n\n\tt.Run(\"Reporter not implemented\", func(t *testing.T) {\n\t\th := &host{}\n\t\tReportStatus(h, NewEvent(StatusOK))\n\t\trequire.False(t, h.reportStatusCalled)\n\t})\n}\n\nvar (\n\t_ = component.Host(nil)\n\t_ = Reporter(nil)\n)\n\ntype reporter struct {\n\treportStatusCalled bool\n}\n\nfunc (r *reporter) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (r *reporter) Report(_ *Event) {\n\tr.reportStatusCalled = true\n}\n\nvar _ = component.Host(nil)\n\ntype host struct {\n\treportStatusCalled bool\n}\n\nfunc (h *host) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n"
  },
  {
    "path": "component/componenttest/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "component/componenttest/configtest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componenttest // import \"go.opentelemetry.io/collector/component/componenttest\"\n\nimport (\n\t\"fmt\"\n\t\"reflect\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"go.uber.org/multierr\"\n)\n\n// The regular expression for valid config field tag.\nvar configFieldTagRegExp = regexp.MustCompile(\"^[a-z0-9][a-z0-9_]*$\")\n\n// CheckConfigStruct enforces that given configuration object is following the patterns\n// used by the collector. This ensures consistency between different implementations\n// of components and extensions. It is recommended for implementers of components\n// to call this function on their tests passing the default configuration of the\n// component factory.\nfunc CheckConfigStruct(config any) error {\n\tt := reflect.TypeOf(config)\n\tif t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\n\tif t.Kind() != reflect.Struct {\n\t\treturn fmt.Errorf(\"config must be a struct or a pointer to one, the passed object is a %s\", t.Kind())\n\t}\n\n\treturn validateConfigDataType(t)\n}\n\n// validateConfigDataType performs a descending validation of the given type.\n// If the type is a struct it goes to each of its fields to check for the proper\n// tags.\nfunc validateConfigDataType(t reflect.Type) error {\n\tvar errs error\n\n\tswitch t.Kind() {\n\tcase reflect.Ptr:\n\t\terrs = multierr.Append(errs, validateConfigDataType(t.Elem()))\n\tcase reflect.Struct:\n\t\t// Reflect on the pointed data and check each of its fields.\n\t\tnf := t.NumField()\n\t\tfor i := range nf {\n\t\t\tf := t.Field(i)\n\t\t\terrs = multierr.Append(errs, checkStructFieldTags(f))\n\t\t}\n\tdefault:\n\t\t// The config object can carry other types but they are not used when\n\t\t// reading the configuration via koanf so ignore them. Basically ignore:\n\t\t// reflect.Uintptr, reflect.Chan, reflect.Func, reflect.Interface, and\n\t\t// reflect.UnsafePointer.\n\t}\n\n\tif errs != nil {\n\t\treturn fmt.Errorf(\"type %q from package %q has invalid config settings: %w\", t.Name(), t.PkgPath(), errs)\n\t}\n\n\treturn nil\n}\n\n// checkStructFieldTags inspects the tags of a struct field.\nfunc checkStructFieldTags(f reflect.StructField) error {\n\ttagValue, ok := f.Tag.Lookup(\"mapstructure\")\n\tif !ok {\n\t\t// Ignore special types.\n\t\tswitch f.Type.Kind() {\n\t\tcase reflect.Interface, reflect.Chan, reflect.Func, reflect.Uintptr, reflect.UnsafePointer:\n\t\t\t// Allow the config to carry the types above, but since they are not read\n\t\t\t// when loading configuration, just ignore them.\n\t\t\treturn nil\n\t\t}\n\n\t\t// Public fields of other types should be tagged.\n\t\tchars := []byte(f.Name)\n\t\tif len(chars) > 0 && chars[0] >= 'A' && chars[0] <= 'Z' {\n\t\t\treturn fmt.Errorf(\"mapstructure tag not present on field %q\", f.Name)\n\t\t}\n\n\t\t// Not public field, no need to have a tag.\n\t\treturn nil\n\t}\n\n\tif tagValue == \"\" {\n\t\treturn fmt.Errorf(\"mapstructure tag on field %q is empty\", f.Name)\n\t}\n\n\ttagParts := strings.Split(tagValue, \",\")\n\tif tagParts[0] != \"\" {\n\t\tif tagParts[0] == \"-\" {\n\t\t\t// Nothing to do, as mapstructure decode skips this field.\n\t\t\treturn nil\n\t\t}\n\t}\n\n\tfor _, tag := range tagParts[1:] {\n\t\tswitch tag {\n\t\tcase \"squash\":\n\t\t\tif (f.Type.Kind() != reflect.Struct) && (f.Type.Kind() != reflect.Ptr || f.Type.Elem().Kind() != reflect.Struct) {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"attempt to squash non-struct type on field %q\", f.Name)\n\t\t\t}\n\t\tcase \"remain\":\n\t\t\tif f.Type.Kind() != reflect.Map && f.Type.Kind() != reflect.Interface {\n\t\t\t\treturn fmt.Errorf(`attempt to use \"remain\" on non-map or interface type field %q`, f.Name)\n\t\t\t}\n\t\t}\n\t}\n\n\tswitch f.Type.Kind() {\n\tcase reflect.Struct:\n\t\t// It is another struct, continue down-level.\n\t\treturn validateConfigDataType(f.Type)\n\n\tcase reflect.Map, reflect.Slice, reflect.Array:\n\t\t// The element of map, array, or slice can be itself a configuration object.\n\t\treturn validateConfigDataType(f.Type.Elem())\n\n\tdefault:\n\t\tfieldTag := tagParts[0]\n\t\tif fieldTag != \"\" && !configFieldTagRegExp.MatchString(fieldTag) {\n\t\t\treturn fmt.Errorf(\n\t\t\t\t\"field %q has config tag %q which doesn't satisfy %q\",\n\t\t\t\tf.Name,\n\t\t\t\tfieldTag,\n\t\t\t\tconfigFieldTagRegExp.String())\n\t\t}\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "component/componenttest/configtest_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componenttest\n\nimport (\n\t\"io\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestCheckConfigStructPointerAndValue(t *testing.T) {\n\tconfig := struct {\n\t\tSomeFiled string `mapstructure:\"test\"`\n\t}{}\n\tassert.NoError(t, CheckConfigStruct(config))\n\tassert.NoError(t, CheckConfigStruct(&config))\n}\n\nfunc TestCheckConfigStruct(t *testing.T) {\n\ttype BadConfigTag struct {\n\t\tBadTagField int `mapstructure:\"test-dash\"`\n\t}\n\n\ttests := []struct {\n\t\tname             string\n\t\tconfig           any\n\t\twantErrMsgSubStr string\n\t}{\n\t\t{\n\t\t\tname: \"typical_config\",\n\t\t\tconfig: struct {\n\t\t\t\tMyPublicString string `mapstructure:\"string\"`\n\t\t\t}{},\n\t\t},\n\t\t{\n\t\t\tname: \"private_fields_ignored\",\n\t\t\tconfig: struct {\n\t\t\t\t// A public type with proper tag.\n\t\t\t\tMyPublicString string `mapstructure:\"string\"`\n\t\t\t\t// A public type with proper tag.\n\t\t\t\tMyPublicInt string `mapstructure:\"int\"`\n\t\t\t\t// A public type that should be ignored.\n\t\t\t\tMyFunc func() error\n\t\t\t\t// A public type that should be ignored.\n\t\t\t\tReader io.Reader\n\t\t\t\t// private type not tagged.\n\t\t\t\tmyPrivateString string\n\t\t\t\t_someInt        int\n\t\t\t}{},\n\t\t},\n\t\t{\n\t\t\tname: \"remain_mapstructure_tag\",\n\t\t\tconfig: struct {\n\t\t\t\tAdditionalProperties map[string]any `mapstructure:\",remain\"`\n\t\t\t}{},\n\t\t},\n\t\t{\n\t\t\tname: \"remain_with_interface_type\",\n\t\t\tconfig: struct {\n\t\t\t\tAdditionalProperties any `mapstructure:\",remain\"`\n\t\t\t}{},\n\t\t},\n\t\t{\n\t\t\tname: \"omitempty_mapstructure_tag\",\n\t\t\tconfig: struct {\n\t\t\t\tMyPublicString string `mapstructure:\",omitempty\"`\n\t\t\t}{},\n\t\t},\n\t\t{\n\t\t\tname: \"named_omitempty_mapstructure_tag\",\n\t\t\tconfig: struct {\n\t\t\t\tMyPublicString string `mapstructure:\"my_public_string,omitempty\"`\n\t\t\t}{},\n\t\t},\n\t\t{\n\t\t\tname: \"not_struct_nor_pointer\",\n\t\t\tconfig: func(x int) int {\n\t\t\t\treturn x * x\n\t\t\t},\n\t\t\twantErrMsgSubStr: \"config must be a struct or a pointer to one, the passed object is a func\",\n\t\t},\n\t\t{\n\t\t\tname: \"squash_on_non_struct\",\n\t\t\tconfig: struct {\n\t\t\t\tMyInt int `mapstructure:\",squash\"`\n\t\t\t}{},\n\t\t\twantErrMsgSubStr: \"attempt to squash non-struct type on field \\\"MyInt\\\"\",\n\t\t},\n\t\t{\n\t\t\tname: \"remain_on_non_map\",\n\t\t\tconfig: struct {\n\t\t\t\tAdditionalProperties string `mapstructure:\",remain\"`\n\t\t\t}{},\n\t\t\twantErrMsgSubStr: `attempt to use \"remain\" on non-map or interface type field \"AdditionalProperties\"`,\n\t\t},\n\t\t{\n\t\t\tname: \"bad_custom_field_name\",\n\t\t\tconfig: struct {\n\t\t\t\tAdditionalProperties any `mapstructure:\"Additional_Properties\"`\n\t\t\t}{},\n\t\t\twantErrMsgSubStr: `field \"AdditionalProperties\" has config tag \"Additional_Properties\" which doesn't satisfy \"^[a-z0-9][a-z0-9_]*$\"`,\n\t\t},\n\t\t{\n\t\t\tname:             \"invalid_tag_detected\",\n\t\t\tconfig:           BadConfigTag{},\n\t\t\twantErrMsgSubStr: \"field \\\"BadTagField\\\" has config tag \\\"test-dash\\\" which doesn't satisfy\",\n\t\t},\n\t\t{\n\t\t\tname: \"public_field_must_have_tag\",\n\t\t\tconfig: struct {\n\t\t\t\tPublicFieldWithoutMapstructureTag string\n\t\t\t}{},\n\t\t\twantErrMsgSubStr: \"mapstructure tag not present on field \\\"PublicFieldWithoutMapstructureTag\\\"\",\n\t\t},\n\t\t{\n\t\t\tname: \"public_field_must_have_nonempty_tag\",\n\t\t\tconfig: struct {\n\t\t\t\tPublicFieldWithoutMapstructureTag string `mapstructure:\"\"`\n\t\t\t}{},\n\t\t\twantErrMsgSubStr: \"mapstructure tag on field \\\"PublicFieldWithoutMapstructureTag\\\" is empty\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid_map_item\",\n\t\t\tconfig: struct {\n\t\t\t\tMap map[string]BadConfigTag `mapstructure:\"test_map\"`\n\t\t\t}{},\n\t\t\twantErrMsgSubStr: \"field \\\"BadTagField\\\" has config tag \\\"test-dash\\\" which doesn't satisfy\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid_slice_item\",\n\t\t\tconfig: struct {\n\t\t\t\tSlice []BadConfigTag `mapstructure:\"test_slice\"`\n\t\t\t}{},\n\t\t\twantErrMsgSubStr: \"field \\\"BadTagField\\\" has config tag \\\"test-dash\\\" which doesn't satisfy\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid_array_item\",\n\t\t\tconfig: struct {\n\t\t\t\tArray [2]BadConfigTag `mapstructure:\"test_array\"`\n\t\t\t}{},\n\t\t\twantErrMsgSubStr: \"field \\\"BadTagField\\\" has config tag \\\"test-dash\\\" which doesn't satisfy\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid_map_item_ptr\",\n\t\t\tconfig: struct {\n\t\t\t\tMap map[string]*BadConfigTag `mapstructure:\"test_map\"`\n\t\t\t}{},\n\t\t\twantErrMsgSubStr: \"field \\\"BadTagField\\\" has config tag \\\"test-dash\\\" which doesn't satisfy\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid_slice_item_ptr\",\n\t\t\tconfig: struct {\n\t\t\t\tSlice []*BadConfigTag `mapstructure:\"test_slice\"`\n\t\t\t}{},\n\t\t\twantErrMsgSubStr: \"field \\\"BadTagField\\\" has config tag \\\"test-dash\\\" which doesn't satisfy\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid_array_item_ptr\",\n\t\t\tconfig: struct {\n\t\t\t\tArray [2]*BadConfigTag `mapstructure:\"test_array\"`\n\t\t\t}{},\n\t\t\twantErrMsgSubStr: \"field \\\"BadTagField\\\" has config tag \\\"test-dash\\\" which doesn't satisfy\",\n\t\t},\n\t\t{\n\t\t\tname: \"valid_map_item\",\n\t\t\tconfig: struct {\n\t\t\t\tMap map[string]int `mapstructure:\"test_map\"`\n\t\t\t}{},\n\t\t},\n\t\t{\n\t\t\tname: \"valid_slice_item\",\n\t\t\tconfig: struct {\n\t\t\t\tSlice []string `mapstructure:\"test_slice\"`\n\t\t\t}{},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := CheckConfigStruct(tt.config)\n\t\t\tif tt.wantErrMsgSubStr == \"\" {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.ErrorContains(t, err, tt.wantErrMsgSubStr)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "component/componenttest/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package componenttest define types and functions used to help test packages\n// implementing the component package interfaces.\npackage componenttest // import \"go.opentelemetry.io/collector/component/componenttest\"\n"
  },
  {
    "path": "component/componenttest/go.mod",
    "content": "module go.opentelemetry.io/collector/component/componenttest\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/otel/metric v1.42.0\n\tgo.opentelemetry.io/otel/sdk v1.42.0\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0\n\tgo.opentelemetry.io/otel/trace v1.42.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/multierr v1.11.0\n\tgo.uber.org/zap v1.27.1\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n"
  },
  {
    "path": "component/componenttest/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "component/componenttest/metadata.yaml",
    "content": "type: component/componenttest\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "component/componenttest/nop_host.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componenttest // import \"go.opentelemetry.io/collector/component/componenttest\"\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar _ component.Host = (*nopHost)(nil)\n\n// nopHost mocks a [component.Host] for testing purposes.\ntype nopHost struct{}\n\n// NewNopHost returns a [component.Host] that returns empty values\n// from method calls. This host is intended to be used in tests\n// where a bare-minimum host is desired.\nfunc NewNopHost() component.Host {\n\treturn &nopHost{}\n}\n\n// GetExtensions returns an empty extensions map.\nfunc (nh *nopHost) GetExtensions() map[component.ID]component.Component {\n\treturn map[component.ID]component.Component{}\n}\n"
  },
  {
    "path": "component/componenttest/nop_host_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componenttest\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestNewNopHost(t *testing.T) {\n\tnh := NewNopHost()\n\trequire.NotNil(t, nh)\n\trequire.IsType(t, &nopHost{}, nh)\n\n\textensions := nh.GetExtensions()\n\tassert.NotNil(t, extensions)\n\tassert.Empty(t, extensions)\n}\n"
  },
  {
    "path": "component/componenttest/nop_telemetry.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componenttest // import \"go.opentelemetry.io/collector/component/componenttest\"\n\nimport (\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// NewNopTelemetrySettings returns a new nop telemetry settings for Create* functions.\nfunc NewNopTelemetrySettings() component.TelemetrySettings {\n\treturn component.TelemetrySettings{\n\t\tLogger:         zap.NewNop(),\n\t\tTracerProvider: nooptrace.NewTracerProvider(),\n\t\tMeterProvider:  noopmetric.NewMeterProvider(),\n\t\tResource:       pcommon.NewResource(),\n\t}\n}\n"
  },
  {
    "path": "component/componenttest/nop_telemetry_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componenttest\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestNewNopTelemetrySettings(t *testing.T) {\n\tnts := NewNopTelemetrySettings()\n\tassert.NotNil(t, nts.Logger)\n\tassert.NotNil(t, nts.TracerProvider)\n\tassert.NotPanics(t, func() {\n\t\tnts.TracerProvider.Tracer(\"test\")\n\t})\n\tassert.NotNil(t, nts.MeterProvider)\n\tassert.NotPanics(t, func() {\n\t\tnts.MeterProvider.Meter(\"test\")\n\t})\n\tassert.Equal(t, 0, nts.Resource.Attributes().Len())\n}\n"
  },
  {
    "path": "component/componenttest/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componenttest\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "component/componenttest/telemetry.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componenttest // import \"go.opentelemetry.io/collector/component/componenttest\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\n\tsdkmetric \"go.opentelemetry.io/otel/sdk/metric\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\tsdktrace \"go.opentelemetry.io/otel/sdk/trace\"\n\t\"go.opentelemetry.io/otel/sdk/trace/tracetest\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\ntype TelemetryOption interface {\n\tapply(*telemetryOption)\n}\n\ntype telemetryOption struct {\n\tmetricOpts []sdkmetric.Option\n\ttraceOpts  []sdktrace.TracerProviderOption\n}\n\ntype telemetryOptionFunc func(*telemetryOption)\n\nfunc (f telemetryOptionFunc) apply(o *telemetryOption) { f(o) }\n\nfunc WithMetricOptions(opts ...sdkmetric.Option) TelemetryOption {\n\treturn telemetryOptionFunc(func(to *telemetryOption) {\n\t\tto.metricOpts = append(to.metricOpts, opts...)\n\t})\n}\n\nfunc WithTraceOptions(opts ...sdktrace.TracerProviderOption) TelemetryOption {\n\treturn telemetryOptionFunc(func(to *telemetryOption) {\n\t\tto.traceOpts = append(to.traceOpts, opts...)\n\t})\n}\n\ntype Telemetry struct {\n\tReader        *sdkmetric.ManualReader\n\tSpanRecorder  *tracetest.SpanRecorder\n\tmeterProvider *sdkmetric.MeterProvider\n\ttraceProvider *sdktrace.TracerProvider\n}\n\nfunc NewTelemetry(opts ...TelemetryOption) *Telemetry {\n\treader := sdkmetric.NewManualReader()\n\tspanRecorder := new(tracetest.SpanRecorder)\n\ttOpts := telemetryOption{\n\t\tmetricOpts: []sdkmetric.Option{sdkmetric.WithReader(reader)},\n\t\ttraceOpts:  []sdktrace.TracerProviderOption{sdktrace.WithSpanProcessor(spanRecorder)},\n\t}\n\tfor _, opt := range opts {\n\t\topt.apply(&tOpts)\n\t}\n\treturn &Telemetry{\n\t\tReader:        reader,\n\t\tSpanRecorder:  spanRecorder,\n\t\tmeterProvider: sdkmetric.NewMeterProvider(tOpts.metricOpts...),\n\t\ttraceProvider: sdktrace.NewTracerProvider(tOpts.traceOpts...),\n\t}\n}\n\nfunc (tt *Telemetry) NewTelemetrySettings() component.TelemetrySettings {\n\tset := NewNopTelemetrySettings()\n\tset.MeterProvider = tt.meterProvider\n\tset.TracerProvider = tt.traceProvider\n\treturn set\n}\n\nfunc (tt *Telemetry) GetMetric(name string) (metricdata.Metrics, error) {\n\tvar rm metricdata.ResourceMetrics\n\tif err := tt.Reader.Collect(context.Background(), &rm); err != nil {\n\t\treturn metricdata.Metrics{}, err\n\t}\n\n\tfor _, sm := range rm.ScopeMetrics {\n\t\tfor _, m := range sm.Metrics {\n\t\t\tif m.Name == name {\n\t\t\t\treturn m, nil\n\t\t\t}\n\t\t}\n\t}\n\treturn metricdata.Metrics{}, fmt.Errorf(\"metric '%s' not found\", name)\n}\n\nfunc (tt *Telemetry) Shutdown(ctx context.Context) error {\n\treturn errors.Join(\n\t\ttt.meterProvider.Shutdown(ctx),\n\t\ttt.traceProvider.Shutdown(ctx),\n\t)\n}\n"
  },
  {
    "path": "component/componenttest/telemetry_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componenttest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tsdkmetric \"go.opentelemetry.io/otel/sdk/metric\"\n\tsdktrace \"go.opentelemetry.io/otel/sdk/trace\"\n)\n\nfunc TestNewTelemetry(t *testing.T) {\n\ttel := NewTelemetry()\n\tassert.NotNil(t, tel.Reader)\n\tassert.NotNil(t, tel.SpanRecorder)\n\tset := tel.NewTelemetrySettings()\n\tassert.IsType(t, &sdktrace.TracerProvider{}, set.TracerProvider)\n\tassert.IsType(t, &sdkmetric.MeterProvider{}, set.MeterProvider)\n\trequire.NoError(t, tel.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "component/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage component // import \"go.opentelemetry.io/collector/component\"\n\n// Config defines the configuration for a component.Component.\n//\n// Implementations and/or any sub-configs (other types embedded or included in the Config implementation)\n// MUST implement xconfmap.Validator if any validation is required for that part of the configuration\n// (e.g. check if a required field is present).\n//\n// A valid implementation MUST pass the check componenttest.CheckConfigStruct (return nil error).\ntype Config any\n"
  },
  {
    "path": "component/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package component outlines the components used in the collector\n// and provides a foundation for the component’s creation and\n// termination process. A component can be either a receiver, exporter,\n// processor, an extension, or a connector.\npackage component // import \"go.opentelemetry.io/collector/component\"\n"
  },
  {
    "path": "component/go.mod",
    "content": "module go.opentelemetry.io/collector/component\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/otel/metric v1.42.0\n\tgo.opentelemetry.io/otel/trace v1.42.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/zap v1.27.1\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/rogpeppe/go-internal v1.13.1 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/pdata => ../pdata\n\nretract (\n\tv0.76.0 // Depends on retracted pdata v1.0.0-rc10 module, use v0.76.1\n\tv0.69.0 // Release failed, use v0.69.1\n)\n\nreplace go.opentelemetry.io/collector/featuregate => ../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../internal/testutil\n"
  },
  {
    "path": "component/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "component/host.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage component // import \"go.opentelemetry.io/collector/component\"\n\n// Host represents the entity that is hosting a Component. It is used to allow communication\n// between the Component and its host (normally the service.Collector is the host).\n//\n// Components may require `component.Host` to implement additional interfaces to properly function.\n// The component is expected to cast the `component.Host` to the interface it needs and return\n// an error if the type assertion fails.\ntype Host interface {\n\t// GetExtensions returns the map of extensions. Only enabled and created extensions will be returned.\n\t// Typically, it is used to find an extension by type or by full config name. Both cases\n\t// can be done by iterating the returned map. There are typically very few extensions,\n\t// so there are no performance implications due to iteration.\n\t//\n\t// GetExtensions can be called by the component anytime after Component.Start() begins and\n\t// until Component.Shutdown() ends.\n\t//\n\t// The returned map should only be nil if the host does not support extensions at all.\n\tGetExtensions() map[ID]Component\n}\n"
  },
  {
    "path": "component/identifiable.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage component // import \"go.opentelemetry.io/collector/component\"\n\nimport (\n\t\"encoding\"\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n// typeAndNameSeparator is the separator that is used between type and name in type/name composite keys.\nconst typeAndNameSeparator = \"/\"\n\nvar (\n\t// typeRegexp is used to validate the type of component.\n\t// A type must start with an ASCII alphabetic character and\n\t// can only contain ASCII alphanumeric characters and '_'.\n\t// This must be kept in sync with the regex in cmd/mdatagen/validate.go.\n\ttypeRegexp = regexp.MustCompile(`^[a-zA-Z][0-9a-zA-Z_]{0,62}$`)\n\n\t// nameRegexp is used to validate the name of a component. A name can consist of\n\t// 1 to 1024 Unicode characters excluding whitespace, control characters, and\n\t// symbols.\n\tnameRegexp = regexp.MustCompile(`^[^\\pZ\\pC\\pS]+$`)\n)\n\nvar _ fmt.Stringer = Type{}\n\n// Type is the component type as it is used in the config.\ntype Type struct {\n\tname string\n}\n\n// String returns the string representation of the type.\nfunc (t Type) String() string {\n\treturn t.name\n}\n\n// MarshalText marshals returns the Type name.\nfunc (t Type) MarshalText() ([]byte, error) {\n\treturn []byte(t.name), nil\n}\n\n// NewType creates a type. It returns an error if the type is invalid.\n// A type must\n// - have at least one character,\n// - start with an ASCII alphabetic character and\n// - can only contain ASCII alphanumeric characters and '_'.\nfunc NewType(ty string) (Type, error) {\n\tif ty == \"\" {\n\t\treturn Type{}, errors.New(\"id must not be empty\")\n\t}\n\tif !typeRegexp.MatchString(ty) {\n\t\treturn Type{}, fmt.Errorf(\"invalid character(s) in type %q\", ty)\n\t}\n\treturn Type{name: ty}, nil\n}\n\n// MustNewType creates a type. It panics if the type is invalid.\n// A type must\n// - have at least one character,\n// - start with an ASCII alphabetic character and\n// - can only contain ASCII alphanumeric characters and '_'.\nfunc MustNewType(strType string) Type {\n\tty, err := NewType(strType)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn ty\n}\n\nvar (\n\t_ fmt.Stringer             = ID{}\n\t_ encoding.TextMarshaler   = ID{}\n\t_ encoding.TextUnmarshaler = (*ID)(nil)\n)\n\n// ID represents the identity for a component. It combines two values:\n// * type - the Type of the component.\n// * name - the name of that component.\n// The component ID (combination type + name) is unique for a given component.Kind.\ntype ID struct {\n\ttypeVal Type   `mapstructure:\"-\"`\n\tnameVal string `mapstructure:\"-\"`\n}\n\n// NewID returns a new ID with the given Type and empty name.\nfunc NewID(typeVal Type) ID {\n\treturn ID{typeVal: typeVal}\n}\n\n// MustNewID builds a Type and returns a new ID with the given Type and empty name.\n// This is equivalent to NewID(MustNewType(typeVal)).\n// See MustNewType to check the valid values of typeVal.\nfunc MustNewID(typeVal string) ID {\n\treturn NewID(MustNewType(typeVal))\n}\n\n// NewIDWithName returns a new ID with the given Type and name.\nfunc NewIDWithName(typeVal Type, nameVal string) ID {\n\treturn ID{typeVal: typeVal, nameVal: nameVal}\n}\n\n// MustNewIDWithName builds a Type and returns a new ID with the given Type and name.\n// This is equivalent to NewIDWithName(MustNewType(typeVal), nameVal).\n// See MustNewType to check the valid values of typeVal.\nfunc MustNewIDWithName(typeVal, nameVal string) ID {\n\treturn NewIDWithName(MustNewType(typeVal), nameVal)\n}\n\n// Type returns the type of the component.\nfunc (id ID) Type() Type {\n\treturn id.typeVal\n}\n\n// Name returns the custom name of the component.\nfunc (id ID) Name() string {\n\treturn id.nameVal\n}\n\n// MarshalText implements the encoding.TextMarshaler interface.\n// This marshals the type and name as one string in the config.\nfunc (id ID) MarshalText() ([]byte, error) {\n\treturn []byte(id.String()), nil\n}\n\n// UnmarshalText implements the encoding.TextUnmarshaler interface.\nfunc (id *ID) UnmarshalText(text []byte) error {\n\tidStr := string(text)\n\ttypeStr, nameStr, hasName := strings.Cut(idStr, typeAndNameSeparator)\n\ttypeStr = strings.TrimSpace(typeStr)\n\n\tif typeStr == \"\" {\n\t\tif hasName {\n\t\t\treturn fmt.Errorf(\"in %q id: the part before %s should not be empty\", idStr, typeAndNameSeparator)\n\t\t}\n\t\treturn errors.New(\"id must not be empty\")\n\t}\n\n\tif hasName {\n\t\t// \"name\" part is present.\n\t\tnameStr = strings.TrimSpace(nameStr)\n\t\tif nameStr == \"\" {\n\t\t\treturn fmt.Errorf(\"in %q id: the part after %s should not be empty\", idStr, typeAndNameSeparator)\n\t\t}\n\t\tif err := validateName(nameStr); err != nil {\n\t\t\treturn fmt.Errorf(\"in %q id: %w\", nameStr, err)\n\t\t}\n\t}\n\n\tvar err error\n\tif id.typeVal, err = NewType(typeStr); err != nil {\n\t\treturn fmt.Errorf(\"in %q id: %w\", idStr, err)\n\t}\n\tid.nameVal = nameStr\n\n\treturn nil\n}\n\n// String returns the ID string representation as \"type[/name]\" format.\nfunc (id ID) String() string {\n\tif id.nameVal == \"\" {\n\t\treturn id.typeVal.String()\n\t}\n\n\treturn id.typeVal.String() + typeAndNameSeparator + id.nameVal\n}\n\nfunc validateName(nameStr string) error {\n\tif len(nameStr) > 1024 {\n\t\treturn fmt.Errorf(\"name %q is longer than 1024 characters (%d characters)\", nameStr, len(nameStr))\n\t}\n\tif !nameRegexp.MatchString(nameStr) {\n\t\treturn fmt.Errorf(\"invalid character(s) in name %q\", nameStr)\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "component/identifiable_example_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage component_test\n\nimport (\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc ExampleNewType() {\n\tt, err := component.NewType(\"exampleexporter\")\n\tif err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t\treturn\n\t}\n\tfmt.Println(t.String())\n\n\t// Output:\n\t// exampleexporter\n}\n\nfunc ExampleMustNewType() {\n\tt := component.MustNewType(\"examplereceiver\")\n\tfmt.Println(t.String())\n\n\t// Output:\n\t// examplereceiver\n}\n\nfunc ExampleNewID() {\n\tt := component.MustNewType(\"exampleprocessor\")\n\tid := component.NewID(t)\n\tfmt.Println(id.String())\n\n\t// Output:\n\t// exampleprocessor\n}\n\nfunc ExampleMustNewID() {\n\tid := component.MustNewID(\"examplereceiver\")\n\tfmt.Println(id.String())\n\n\t// Output:\n\t// examplereceiver\n}\n\nfunc ExampleNewIDWithName() {\n\tt := component.MustNewType(\"exampleexporter\")\n\tid := component.NewIDWithName(t, \"customname\")\n\tfmt.Println(id.String())\n\n\t// Output:\n\t// exampleexporter/customname\n}\n\nfunc ExampleMustNewIDWithName() {\n\tid := component.MustNewIDWithName(\"exampleprocessor\", \"customproc\")\n\tfmt.Println(id.String())\n\n\t// Output:\n\t// exampleprocessor/customproc\n}\n"
  },
  {
    "path": "component/identifiable_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage component\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestMarshalText(t *testing.T) {\n\tid := NewIDWithName(MustNewType(\"test\"), \"name\")\n\tgot, err := id.MarshalText()\n\trequire.NoError(t, err)\n\tassert.Equal(t, id.String(), string(got))\n}\n\nfunc TestUnmarshalText(t *testing.T) {\n\tvalidType := MustNewType(\"valid_type\")\n\ttestCases := []struct {\n\t\tname        string\n\t\texpectedErr bool\n\t\texpectedID  ID\n\t}{\n\t\t{\n\t\t\tname:       \"valid_type\",\n\t\t\texpectedID: ID{typeVal: validType, nameVal: \"\"},\n\t\t},\n\t\t{\n\t\t\tname:       \"valid_type/valid_name\",\n\t\t\texpectedID: ID{typeVal: validType, nameVal: \"valid_name\"},\n\t\t},\n\t\t{\n\t\t\tname:       \"   valid_type   /   valid_name  \",\n\t\t\texpectedID: ID{typeVal: validType, nameVal: \"valid_name\"},\n\t\t},\n\t\t{\n\t\t\tname:       \"valid_type/中文好\",\n\t\t\texpectedID: ID{typeVal: validType, nameVal: \"中文好\"},\n\t\t},\n\t\t{\n\t\t\tname:       \"valid_type/name-with-dashes\",\n\t\t\texpectedID: ID{typeVal: validType, nameVal: \"name-with-dashes\"},\n\t\t},\n\t\t// issue 10816\n\t\t{\n\t\t\tname:       \"valid_type/Linux-Messages-File_01J49HCH3SWFXRVASWFZFRT3J2__processor0__logs\",\n\t\t\texpectedID: ID{typeVal: validType, nameVal: \"Linux-Messages-File_01J49HCH3SWFXRVASWFZFRT3J2__processor0__logs\"},\n\t\t},\n\t\t{\n\t\t\tname:       \"valid_type/1\",\n\t\t\texpectedID: ID{typeVal: validType, nameVal: \"1\"},\n\t\t},\n\t\t{\n\t\t\tname:        \"/valid_name\",\n\t\t\texpectedErr: true,\n\t\t},\n\t\t{\n\t\t\tname:        \"     /valid_name\",\n\t\t\texpectedErr: true,\n\t\t},\n\t\t{\n\t\t\tname:        \"valid_type/\",\n\t\t\texpectedErr: true,\n\t\t},\n\t\t{\n\t\t\tname:        \"valid_type/      \",\n\t\t\texpectedErr: true,\n\t\t},\n\t\t{\n\t\t\tname:        \"      \",\n\t\t\texpectedErr: true,\n\t\t},\n\t\t{\n\t\t\tname:        \"valid_type/invalid name\",\n\t\t\texpectedErr: true,\n\t\t},\n\t\t{\n\t\t\tname:        \"valid_type/\" + strings.Repeat(\"a\", 1025),\n\t\t\texpectedErr: true,\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tid := ID{}\n\t\t\terr := id.UnmarshalText([]byte(tt.name))\n\t\t\tif tt.expectedErr {\n\t\t\t\tassert.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tt.expectedID, id)\n\t\t\tassert.Equal(t, tt.expectedID.Type(), id.Type())\n\t\t\tassert.Equal(t, tt.expectedID.Name(), id.Name())\n\t\t\tassert.Equal(t, tt.expectedID.String(), id.String())\n\t\t})\n\t}\n}\n\nfunc TestNewType(t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tshouldErr bool\n\t}{\n\t\t{name: \"active_directory_ds\"},\n\t\t{name: \"aerospike\"},\n\t\t{name: \"alertmanager\"},\n\t\t{name: \"alibabacloud_logservice\"},\n\t\t{name: \"apache\"},\n\t\t{name: \"apachespark\"},\n\t\t{name: \"asapclient\"},\n\t\t{name: \"attributes\"},\n\t\t{name: \"awscloudwatch\"},\n\t\t{name: \"awscloudwatchlogs\"},\n\t\t{name: \"awscloudwatchmetrics\"},\n\t\t{name: \"awscontainerinsightreceiver\"},\n\t\t{name: \"awsecscontainermetrics\"},\n\t\t{name: \"awsemf\"},\n\t\t{name: \"awsfirehose\"},\n\t\t{name: \"awskinesis\"},\n\t\t{name: \"awsproxy\"},\n\t\t{name: \"awss3\"},\n\t\t{name: \"awsxray\"},\n\t\t{name: \"azureblob\"},\n\t\t{name: \"azuredataexplorer\"},\n\t\t{name: \"azureeventhub\"},\n\t\t{name: \"azuremonitor\"},\n\t\t{name: \"basicauth\"},\n\t\t{name: \"batch\"},\n\t\t{name: \"bearertokenauth\"},\n\t\t{name: \"bigip\"},\n\t\t{name: \"carbon\"},\n\t\t{name: \"cassandra\"},\n\t\t{name: \"chrony\"},\n\t\t{name: \"clickhouse\"},\n\t\t{name: \"cloudflare\"},\n\t\t{name: \"cloudfoundry\"},\n\t\t{name: \"collectd\"},\n\t\t{name: \"configschema\"},\n\t\t{name: \"coralogix\"},\n\t\t{name: \"couchdb\"},\n\t\t{name: \"count\"},\n\t\t{name: \"cumulativetodelta\"},\n\t\t{name: \"datadog\"},\n\t\t{name: \"dataset\"},\n\t\t{name: \"db_storage\"},\n\t\t{name: \"debug\"},\n\t\t{name: \"deltatorate\"},\n\t\t{name: \"demo\"},\n\t\t{name: \"docker_observer\"},\n\t\t{name: \"docker_stats\"},\n\t\t{name: \"dynatrace\"},\n\t\t{name: \"ecs_observer\"},\n\t\t{name: \"ecs_task_observer\"},\n\t\t{name: \"elasticsearch\"},\n\t\t{name: \"exceptions\"},\n\t\t{name: \"experimental_metricsgeneration\"},\n\t\t{name: \"expvar\"},\n\t\t{name: \"f5cloud\"},\n\t\t{name: \"failover\"},\n\t\t{name: \"file\"},\n\t\t{name: \"filelog\"},\n\t\t{name: \"filestats\"},\n\t\t{name: \"file_storage\"},\n\t\t{name: \"filter\"},\n\t\t{name: \"flinkmetrics\"},\n\t\t{name: \"fluentforward\"},\n\t\t{name: \"forward\"},\n\t\t{name: \"githubgen\"},\n\t\t{name: \"gitprovider\"},\n\t\t{name: \"golden\"},\n\t\t{name: \"googlecloud\"},\n\t\t{name: \"googlecloudpubsub\"},\n\t\t{name: \"googlecloudspanner\"},\n\t\t{name: \"googlemanagedprometheus\"},\n\t\t{name: \"groupbyattrs\"},\n\t\t{name: \"groupbytrace\"},\n\t\t{name: \"haproxy\"},\n\t\t{name: \"headers_setter\"},\n\t\t{name: \"health_check\"},\n\t\t{name: \"honeycombmarker\"},\n\t\t{name: \"hostmetrics\"},\n\t\t{name: \"host_observer\"},\n\t\t{name: \"httpcheck\"},\n\t\t{name: \"http_forwarder\"},\n\t\t{name: \"iis\"},\n\t\t{name: \"influxdb\"},\n\t\t{name: \"instana\"},\n\t\t{name: \"interval\"},\n\t\t{name: \"jaeger\"},\n\t\t{name: \"jaeger_encoding\"},\n\t\t{name: \"jaegerremotesampling\"},\n\t\t{name: \"jmx\"},\n\t\t{name: \"journald\"},\n\t\t{name: \"json_log_encoding\"},\n\t\t{name: \"k8sattributes\"},\n\t\t{name: \"k8s_cluster\"},\n\t\t{name: \"k8s_events\"},\n\t\t{name: \"k8sobjects\"},\n\t\t{name: \"k8s_observer\"},\n\t\t{name: \"kafka\"},\n\t\t{name: \"kafkametrics\"},\n\t\t{name: \"kinetica\"},\n\t\t{name: \"kubeletstats\"},\n\t\t{name: \"loadbalancing\"},\n\t\t{name: \"logicmonitor\"},\n\t\t{name: \"logstransform\"},\n\t\t{name: \"logzio\"},\n\t\t{name: \"loki\"},\n\t\t{name: \"mdatagen\"},\n\t\t{name: \"memcached\"},\n\t\t{name: \"memory_limiter\"},\n\t\t{name: \"metricstransform\"},\n\t\t{name: \"mezmo\"},\n\t\t{name: \"mongodb\"},\n\t\t{name: \"mongodbatlas\"},\n\t\t{name: \"mysql\"},\n\t\t{name: \"namedpipe\"},\n\t\t{name: \"nginx\"},\n\t\t{name: \"nsxt\"},\n\t\t{name: \"oauth2client\"},\n\t\t{name: \"oidc\"},\n\t\t{name: \"opamp\"},\n\t\t{name: \"opampsupervisor\"},\n\t\t{name: \"opencensus\"},\n\t\t{name: \"opensearch\"},\n\t\t{name: \"oracledb\"},\n\t\t{name: \"osquery\"},\n\t\t{name: \"otelarrow\"},\n\t\t{name: \"otelcontribcol\"},\n\t\t{name: \"oteltestbedcol\"},\n\t\t{name: \"otlp\"},\n\t\t{name: \"otlp_encoding\"},\n\t\t{name: \"otlp_http\"},\n\t\t{name: \"otlphttp\"},\n\t\t{name: \"otlpjsonfile\"},\n\t\t{name: \"ottl\"},\n\t\t{name: \"podman_stats\"},\n\t\t{name: \"postgresql\"},\n\t\t{name: \"pprof\"},\n\t\t{name: \"probabilistic_sampler\"},\n\t\t{name: \"prometheus\"},\n\t\t{name: \"prometheusremotewrite\"},\n\t\t{name: \"prometheus_simple\"},\n\t\t{name: \"pulsar\"},\n\t\t{name: \"purefa\"},\n\t\t{name: \"purefb\"},\n\t\t{name: \"rabbitmq\"},\n\t\t{name: \"receiver_creator\"},\n\t\t{name: \"redaction\"},\n\t\t{name: \"redis\"},\n\t\t{name: \"remotetap\"},\n\t\t{name: \"resource\"},\n\t\t{name: \"resourcedetection\"},\n\t\t{name: \"riak\"},\n\t\t{name: \"routing\"},\n\t\t{name: \"saphana\"},\n\t\t{name: \"sapm\"},\n\t\t{name: \"schema\"},\n\t\t{name: \"sentry\"},\n\t\t{name: \"servicegraph\"},\n\t\t{name: \"signalfx\"},\n\t\t{name: \"sigv4auth\"},\n\t\t{name: \"skywalking\"},\n\t\t{name: \"snmp\"},\n\t\t{name: \"snowflake\"},\n\t\t{name: \"solace\"},\n\t\t{name: \"solarwindsapmsettings\"},\n\t\t{name: \"span\"},\n\t\t{name: \"spanmetrics\"},\n\t\t{name: \"splunkenterprise\"},\n\t\t{name: \"splunk_hec\"},\n\t\t{name: \"sqlquery\"},\n\t\t{name: \"sqlserver\"},\n\t\t{name: \"sshcheck\"},\n\t\t{name: \"statsd\"},\n\t\t{name: \"sumologic\"},\n\t\t{name: \"syslog\"},\n\t\t{name: \"tail_sampling\"},\n\t\t{name: \"tcplog\"},\n\t\t{name: \"telemetrygen\"},\n\t\t{name: \"tencentcloud_logservice\"},\n\t\t{name: \"text_encoding\"},\n\t\t{name: \"transform\"},\n\t\t{name: \"udplog\"},\n\t\t{name: \"vcenter\"},\n\t\t{name: \"wavefront\"},\n\t\t{name: \"webhookevent\"},\n\t\t{name: \"windowseventlog\"},\n\t\t{name: \"windowsperfcounters\"},\n\t\t{name: \"zipkin\"},\n\t\t{name: \"zipkin_encoding\"},\n\t\t{name: \"zookeeper\"},\n\t\t{name: \"zpages\"},\n\t\t{name: strings.Repeat(\"a\", 63)},\n\n\t\t{name: \"\", shouldErr: true},\n\t\t{name: \"contains spaces\", shouldErr: true},\n\t\t{name: \"contains-dashes\", shouldErr: true},\n\t\t{name: \"0startswithnumber\", shouldErr: true},\n\t\t{name: \"contains/slash\", shouldErr: true},\n\t\t{name: \"contains:colon\", shouldErr: true},\n\t\t{name: \"contains#hash\", shouldErr: true},\n\t\t{name: strings.Repeat(\"a\", 64), shouldErr: true},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tty, err := NewType(tt.name)\n\t\t\tif tt.shouldErr {\n\t\t\t\tassert.Error(t, err)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.Equal(t, tt.name, ty.String())\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "component/metadata.yaml",
    "content": "type: component\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "component/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage component\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "component/telemetry.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage component // import \"go.opentelemetry.io/collector/component\"\n\nimport (\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/trace\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// TelemetrySettings provides components with APIs to report telemetry.\ntype TelemetrySettings struct {\n\t// Logger that the factory can use during creation and can pass to the created\n\t// component to be used later as well.\n\tLogger *zap.Logger\n\n\t// TracerProvider that the factory can pass to other instrumented third-party libraries.\n\t//\n\t// The service may wrap this provider for attribute injection. The wrapper may implement an\n\t// additional `Unwrap() trace.TracerProvider` method to grant access to the underlying SDK.\n\tTracerProvider trace.TracerProvider\n\n\t// MeterProvider that the factory can pass to other instrumented third-party libraries.\n\tMeterProvider metric.MeterProvider\n\n\t// Resource contains the resource attributes for the collector's telemetry.\n\tResource pcommon.Resource\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n"
  },
  {
    "path": "config/configauth/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "config/configauth/README.md",
    "content": "# Authentication configuration\n\nThis module defines necessary interfaces to implement server and client type authenticators:\n\n- Server type authenticators perform authentication for incoming HTTP/gRPC requests and are typically used in receivers.\n- Client type authenticators perform client-side authentication for outgoing HTTP/gRPC requests and are typically used in exporters.\n\nThe currently known authenticators are listed below.\n\n## Server Authenticators\n\n- [Basic Auth Extension](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/basicauthextension)\n- [Bearer Token Extension](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/bearertokenauthextension)\n- [OIDC Extension](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/oidcauthextension)\n\n## Client Authenticators\n\n- [ASAP Client Authentication Extension](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/asapauthextension)\n- [Basic Auth Extension](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/basicauthextension)\n- [Bearer Token Extension](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/bearertokenauthextension)\n- [OAuth2 Client Extension](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/oauth2clientauthextension)\n- [Sigv4 Extension](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/sigv4authextension)\n\nExample:\n\n```yaml\nextensions:\n  oidc:\n    # see the blog post on securing the otelcol for information\n    # on how to setup an OIDC server and how to generate the TLS certs\n    # required for this example\n    # https://medium.com/opentelemetry/securing-your-opentelemetry-collector-1a4f9fa5bd6f\n    issuer_url: http://localhost:8080/auth/realms/opentelemetry\n    audience: account\n\n  oauth2client:\n    client_id: someclientid\n    client_secret: someclientsecret\n    token_url: https://example.com/oauth2/default/v1/token\n    scopes: [\"api.metrics\"]\n    # tls settings for the token client\n    tls:\n      insecure: true\n      ca_file: /var/lib/mycert.pem\n      cert_file: certfile\n      key_file: keyfile\n    # timeout for the token client\n    timeout: 2s\n\nreceivers:\n  otlp/with_auth:\n    protocols:\n      grpc:\n        endpoint: localhost:4318\n        tls:\n          cert_file: /tmp/certs/cert.pem\n          key_file: /tmp/certs/cert-key.pem\n        auth:\n          ## oidc is the extension name to use as the authenticator for this receiver\n          authenticator: oidc\n\n  otlp_http/withauth:\n    endpoint: http://localhost:9000\n    auth:\n      authenticator: oauth2client\n\n```\n\n## Creating an authenticator\n\nNew authenticators can be added by creating a new extension that also implements the appropriate interface (`configauth.ServerAuthenticator` or `configauth.ClientAuthenticator`).\n\nGeneric authenticators that may be used by a good number of users might be accepted as part of the contrib distribution. If you have an interest in contributing an authenticator, open an issue with your proposal. For other cases, you'll need to include your custom authenticator as part of your custom OpenTelemetry Collector, perhaps being built using the [OpenTelemetry Collector Builder](https://github.com/open-telemetry/opentelemetry-collector/tree/main/cmd/builder).\n"
  },
  {
    "path": "config/configauth/config.schema.yaml",
    "content": "$defs:\n  config:\n    description: Config defines the auth settings for the receiver.\n    type: object\n    properties:\n      authenticator:\n        description: AuthenticatorID specifies the name of the extension to use in order to authenticate the incoming data point.\n        type: string\n        x-customType: go.opentelemetry.io/collector/component.ID\n"
  },
  {
    "path": "config/configauth/configauth.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package configauth implements the configuration settings to\n// ensure authentication on incoming requests, and allows\n// exporters to add authentication on outgoing requests.\npackage configauth // import \"go.opentelemetry.io/collector/config/configauth\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/extension/extensionauth\"\n)\n\nvar (\n\terrAuthenticatorNotFound = errors.New(\"authenticator not found\")\n\terrNotHTTPClient         = errors.New(\"requested authenticator is not a HTTP client authenticator\")\n\terrNotGRPCClient         = errors.New(\"requested authenticator is not a gRPC client authenticator\")\n\terrNotServer             = errors.New(\"requested authenticator is not a server authenticator\")\n)\n\n// Config defines the auth settings for the receiver.\ntype Config struct {\n\t// AuthenticatorID specifies the name of the extension to use in order to authenticate the incoming data point.\n\tAuthenticatorID component.ID `mapstructure:\"authenticator,omitempty\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// GetServerAuthenticator attempts to select the appropriate extensionauth.Server from the list of extensions,\n// based on the requested extension name. If an authenticator is not found, an error is returned.\nfunc (a Config) GetServerAuthenticator(_ context.Context, extensions map[component.ID]component.Component) (extensionauth.Server, error) {\n\tif ext, found := extensions[a.AuthenticatorID]; found {\n\t\tif server, ok := ext.(extensionauth.Server); ok {\n\t\t\treturn server, nil\n\t\t}\n\t\treturn nil, errNotServer\n\t}\n\n\treturn nil, fmt.Errorf(\"failed to resolve authenticator %q: %w\", a.AuthenticatorID, errAuthenticatorNotFound)\n}\n\n// GetHTTPClientAuthenticator attempts to select the appropriate extensionauth.Client from the list of extensions,\n// based on the component id of the extension. If an authenticator is not found, an error is returned.\n// This should be only used by HTTP clients.\nfunc (a Config) GetHTTPClientAuthenticator(_ context.Context, extensions map[component.ID]component.Component) (extensionauth.HTTPClient, error) {\n\tif ext, found := extensions[a.AuthenticatorID]; found {\n\t\tif client, ok := ext.(extensionauth.HTTPClient); ok {\n\t\t\treturn client, nil\n\t\t}\n\t\treturn nil, errNotHTTPClient\n\t}\n\treturn nil, fmt.Errorf(\"failed to resolve authenticator %q: %w\", a.AuthenticatorID, errAuthenticatorNotFound)\n}\n\n// GetGRPCClientAuthenticator attempts to select the appropriate extensionauth.Client from the list of extensions,\n// based on the component id of the extension. If an authenticator is not found, an error is returned.\n// This should be only used by gRPC clients.\nfunc (a Config) GetGRPCClientAuthenticator(_ context.Context, extensions map[component.ID]component.Component) (extensionauth.GRPCClient, error) {\n\tif ext, found := extensions[a.AuthenticatorID]; found {\n\t\tif client, ok := ext.(extensionauth.GRPCClient); ok {\n\t\t\treturn client, nil\n\t\t}\n\t\treturn nil, errNotGRPCClient\n\t}\n\treturn nil, fmt.Errorf(\"failed to resolve authenticator %q: %w\", a.AuthenticatorID, errAuthenticatorNotFound)\n}\n"
  },
  {
    "path": "config/configauth/configauth_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configauth\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest\"\n)\n\nvar mockID = component.MustNewID(\"mock\")\n\nfunc TestGetServer(t *testing.T) {\n\ttestCases := []struct {\n\t\tname          string\n\t\tauthenticator extension.Extension\n\t\texpected      error\n\t}{\n\t\t{\n\t\t\tname:          \"obtain server authenticator\",\n\t\t\tauthenticator: extensionauthtest.NewNopServer(),\n\t\t\texpected:      nil,\n\t\t},\n\t\t{\n\t\t\tname:          \"not a server authenticator\",\n\t\t\tauthenticator: extensionauthtest.NewNopClient(),\n\t\t\texpected:      errNotServer,\n\t\t},\n\t}\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// prepare\n\t\t\tcfg := &Config{\n\t\t\t\tAuthenticatorID: mockID,\n\t\t\t}\n\t\t\text := map[component.ID]component.Component{\n\t\t\t\tmockID: tt.authenticator,\n\t\t\t}\n\n\t\t\tauthenticator, err := cfg.GetServerAuthenticator(context.Background(), ext)\n\n\t\t\t// verify\n\t\t\tif tt.expected != nil {\n\t\t\t\trequire.ErrorIs(t, err, tt.expected)\n\t\t\t\tassert.Nil(t, authenticator)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.NotNil(t, authenticator)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGetServerFails(t *testing.T) {\n\tcfg := &Config{\n\t\tAuthenticatorID: component.MustNewID(\"does_not_exist\"),\n\t}\n\n\tauthenticator, err := cfg.GetServerAuthenticator(context.Background(), map[component.ID]component.Component{})\n\trequire.ErrorIs(t, err, errAuthenticatorNotFound)\n\tassert.Nil(t, authenticator)\n}\n\nfunc TestGetHTTPClient(t *testing.T) {\n\ttestCases := []struct {\n\t\tname          string\n\t\tauthenticator extension.Extension\n\t\texpected      error\n\t}{\n\t\t{\n\t\t\tname:          \"obtain client authenticator\",\n\t\t\tauthenticator: extensionauthtest.NewNopClient(),\n\t\t\texpected:      nil,\n\t\t},\n\t\t{\n\t\t\tname:          \"not a client authenticator\",\n\t\t\tauthenticator: extensionauthtest.NewNopServer(),\n\t\t\texpected:      errNotHTTPClient,\n\t\t},\n\t}\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// prepare\n\t\t\tcfg := &Config{\n\t\t\t\tAuthenticatorID: mockID,\n\t\t\t}\n\t\t\text := map[component.ID]component.Component{\n\t\t\t\tmockID: tt.authenticator,\n\t\t\t}\n\n\t\t\tauthenticator, err := cfg.GetHTTPClientAuthenticator(context.Background(), ext)\n\n\t\t\t// verify\n\t\t\tif tt.expected != nil {\n\t\t\t\trequire.ErrorIs(t, err, tt.expected)\n\t\t\t\tassert.Nil(t, authenticator)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.NotNil(t, authenticator)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGetGRPCClientFails(t *testing.T) {\n\tcfg := &Config{\n\t\tAuthenticatorID: component.MustNewID(\"does_not_exist\"),\n\t}\n\tauthenticator, err := cfg.GetGRPCClientAuthenticator(context.Background(), map[component.ID]component.Component{})\n\trequire.ErrorIs(t, err, errAuthenticatorNotFound)\n\tassert.Nil(t, authenticator)\n}\n"
  },
  {
    "path": "config/configauth/go.mod",
    "content": "module go.opentelemetry.io/collector/config/configauth\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/extension v1.54.0\n\tgo.opentelemetry.io/collector/extension/extensionauth v1.54.0\n\tgo.opentelemetry.io/collector/extension/extensionauth/extensionauthtest v0.148.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/extension => ../../extension\n\nreplace go.opentelemetry.io/collector/extension/extensionauth => ../../extension/extensionauth\n\nreplace go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest => ../../extension/extensionauth/extensionauthtest\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "config/configauth/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "config/configauth/metadata.yaml",
    "content": "type: config/configauth\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "config/configauth/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configauth\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "config/configcompression/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "config/configcompression/compressiontype.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configcompression // import \"go.opentelemetry.io/collector/config/configcompression\"\n\nimport (\n\t\"compress/zlib\"\n\t\"fmt\"\n)\n\n// Type represents a compression method\ntype Type string\n\ntype Level int\n\ntype CompressionParams struct {\n\tLevel Level `mapstructure:\"level\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\nconst (\n\tTypeGzip                Type = \"gzip\"\n\tTypeZlib                Type = \"zlib\"\n\tTypeDeflate             Type = \"deflate\"\n\tTypeSnappy              Type = \"snappy\"\n\tTypeSnappyFramed        Type = \"x-snappy-framed\"\n\tTypeZstd                Type = \"zstd\"\n\tTypeLz4                 Type = \"lz4\"\n\ttypeNone                Type = \"none\"\n\ttypeEmpty               Type = \"\"\n\tDefaultCompressionLevel      = zlib.DefaultCompression\n)\n\n// IsCompressed returns false if CompressionType is nil, none, or empty.\n// Otherwise, returns true.\nfunc (ct *Type) IsCompressed() bool {\n\treturn *ct != typeEmpty && *ct != typeNone\n}\n\nfunc (ct *Type) UnmarshalText(in []byte) error {\n\ttyp := Type(in)\n\tif typ == TypeGzip ||\n\t\ttyp == TypeZlib ||\n\t\ttyp == TypeDeflate ||\n\t\ttyp == TypeSnappy ||\n\t\ttyp == TypeSnappyFramed ||\n\t\ttyp == TypeZstd ||\n\t\ttyp == TypeLz4 ||\n\t\ttyp == typeNone ||\n\t\ttyp == typeEmpty {\n\t\t*ct = typ\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unsupported compression type %q\", typ)\n}\n\nfunc (ct *Type) ValidateParams(p CompressionParams) error {\n\tswitch *ct {\n\tcase TypeGzip, TypeZlib, TypeDeflate:\n\t\tif p.Level == zlib.DefaultCompression ||\n\t\t\tp.Level == zlib.HuffmanOnly ||\n\t\t\tp.Level == zlib.NoCompression ||\n\t\t\t(p.Level >= zlib.BestSpeed && p.Level <= zlib.BestCompression) {\n\t\t\treturn nil\n\t\t}\n\tcase TypeZstd:\n\t\t// Supports arbitrary levels: zstd will map any given\n\t\t// level to the nearest internally supported level.\n\t\treturn nil\n\t}\n\tif p.Level != 0 {\n\t\treturn fmt.Errorf(\"unsupported parameters {Level:%+v} for compression type %q\", p.Level, *ct)\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "config/configcompression/compressiontype_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configcompression\n\nimport (\n\t\"compress/zlib\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestUnmarshalText(t *testing.T) {\n\ttests := []struct {\n\t\tname            string\n\t\tcompressionName []byte\n\t\tshouldError     bool\n\t\tisCompressed    bool\n\t}{\n\t\t{\n\t\t\tname:            \"ValidGzip\",\n\t\t\tcompressionName: []byte(\"gzip\"),\n\t\t\tshouldError:     false,\n\t\t\tisCompressed:    true,\n\t\t},\n\t\t{\n\t\t\tname:            \"ValidZlib\",\n\t\t\tcompressionName: []byte(\"zlib\"),\n\t\t\tshouldError:     false,\n\t\t\tisCompressed:    true,\n\t\t},\n\t\t{\n\t\t\tname:            \"ValidDeflate\",\n\t\t\tcompressionName: []byte(\"deflate\"),\n\t\t\tshouldError:     false,\n\t\t\tisCompressed:    true,\n\t\t},\n\t\t{\n\t\t\tname:            \"ValidSnappy\",\n\t\t\tcompressionName: []byte(\"snappy\"),\n\t\t\tshouldError:     false,\n\t\t\tisCompressed:    true,\n\t\t},\n\t\t{\n\t\t\tname:            \"ValidSnappyFramed\",\n\t\t\tcompressionName: []byte(\"x-snappy-framed\"),\n\t\t\tshouldError:     false,\n\t\t\tisCompressed:    true,\n\t\t},\n\t\t{\n\t\t\tname:            \"ValidZstd\",\n\t\t\tcompressionName: []byte(\"zstd\"),\n\t\t\tshouldError:     false,\n\t\t\tisCompressed:    true,\n\t\t},\n\t\t{\n\t\t\tname:            \"ValidEmpty\",\n\t\t\tcompressionName: []byte(\"\"),\n\t\t\tshouldError:     false,\n\t\t},\n\t\t{\n\t\t\tname:            \"ValidNone\",\n\t\t\tcompressionName: []byte(\"none\"),\n\t\t\tshouldError:     false,\n\t\t},\n\t\t{\n\t\t\tname:            \"ValidLz4\",\n\t\t\tcompressionName: []byte(\"lz4\"),\n\t\t\tisCompressed:    true,\n\t\t\tshouldError:     false,\n\t\t},\n\t\t{\n\t\t\tname:            \"Invalid\",\n\t\t\tcompressionName: []byte(\"ggip\"),\n\t\t\tshouldError:     true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttemp := typeNone\n\t\t\terr := temp.UnmarshalText(tt.compressionName)\n\t\t\tif tt.shouldError {\n\t\t\t\tassert.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\tct := Type(tt.compressionName)\n\t\t\tassert.Equal(t, temp, ct)\n\t\t\tassert.Equal(t, tt.isCompressed, ct.IsCompressed())\n\t\t})\n\t}\n}\n\nfunc TestValidateParams(t *testing.T) {\n\ttests := []struct {\n\t\tname             string\n\t\tcompressionName  []byte\n\t\tcompressionLevel Level\n\t\tshouldError      bool\n\t}{\n\t\t{\n\t\t\tname:             \"ValidGzip\",\n\t\t\tcompressionName:  []byte(\"gzip\"),\n\t\t\tcompressionLevel: zlib.DefaultCompression,\n\t\t\tshouldError:      false,\n\t\t},\n\t\t{\n\t\t\tname:             \"InvalidGzip\",\n\t\t\tcompressionName:  []byte(\"gzip\"),\n\t\t\tcompressionLevel: 99,\n\t\t\tshouldError:      true,\n\t\t},\n\t\t{\n\t\t\tname:             \"ValidZlib\",\n\t\t\tcompressionName:  []byte(\"zlib\"),\n\t\t\tcompressionLevel: zlib.DefaultCompression,\n\t\t\tshouldError:      false,\n\t\t},\n\t\t{\n\t\t\tname:             \"ValidDeflate\",\n\t\t\tcompressionName:  []byte(\"deflate\"),\n\t\t\tcompressionLevel: zlib.DefaultCompression,\n\t\t\tshouldError:      false,\n\t\t},\n\t\t{\n\t\t\tname:            \"ValidSnappy\",\n\t\t\tcompressionName: []byte(\"snappy\"),\n\t\t\tshouldError:     false,\n\t\t},\n\t\t{\n\t\t\tname:             \"InvalidSnappy\",\n\t\t\tcompressionName:  []byte(\"snappy\"),\n\t\t\tcompressionLevel: 1,\n\t\t\tshouldError:      true,\n\t\t},\n\t\t{\n\t\t\tname:            \"ValidSnappyFramed\",\n\t\t\tcompressionName: []byte(\"x-snappy-framed\"),\n\t\t\tshouldError:     false,\n\t\t},\n\t\t{\n\t\t\tname:             \"InvalidSnappyFramed\",\n\t\t\tcompressionName:  []byte(\"x-snappy-framed\"),\n\t\t\tcompressionLevel: 1,\n\t\t\tshouldError:      true,\n\t\t},\n\t\t{\n\t\t\tname:             \"ValidZstd\",\n\t\t\tcompressionName:  []byte(\"zstd\"),\n\t\t\tcompressionLevel: zlib.DefaultCompression,\n\t\t\tshouldError:      false,\n\t\t},\n\t\t{\n\t\t\tname:            \"ValidEmpty\",\n\t\t\tcompressionName: []byte(\"\"),\n\t\t\tshouldError:     false,\n\t\t},\n\t\t{\n\t\t\tname:            \"ValidNone\",\n\t\t\tcompressionName: []byte(\"none\"),\n\t\t\tshouldError:     false,\n\t\t},\n\t\t{\n\t\t\tname:            \"ValidLz4\",\n\t\t\tcompressionName: []byte(\"lz4\"),\n\t\t\tshouldError:     false,\n\t\t},\n\t\t{\n\t\t\tname:             \"InvalidLz4\",\n\t\t\tcompressionName:  []byte(\"lz4\"),\n\t\t\tcompressionLevel: 1,\n\t\t\tshouldError:      true,\n\t\t},\n\t\t{\n\t\t\tname:             \"Invalid\",\n\t\t\tcompressionName:  []byte(\"ggip\"),\n\t\t\tcompressionLevel: zlib.DefaultCompression,\n\t\t\tshouldError:      true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcompressionParams := CompressionParams{Level: tt.compressionLevel}\n\t\t\ttemp := Type(tt.compressionName)\n\t\t\terr := temp.ValidateParams(compressionParams)\n\t\t\tif tt.shouldError {\n\t\t\t\tassert.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "config/configcompression/config.schema.yaml",
    "content": "$defs:\n  compression_params:\n    type: object\n    properties:\n      level:\n        $ref: level\n  level:\n    type: integer\n  type:\n    description: Type represents a compression method\n    type: string\n"
  },
  {
    "path": "config/configcompression/go.mod",
    "content": "module go.opentelemetry.io/collector/config/configcompression\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/kr/pretty v0.3.1 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/rogpeppe/go-internal v1.10.0 // indirect\n\tgopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n"
  },
  {
    "path": "config/configcompression/go.sum",
    "content": "github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=\ngithub.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "config/configcompression/metadata.yaml",
    "content": "type: config/configcompression\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "config/configcompression/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configcompression\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "config/configgrpc/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "config/configgrpc/README.md",
    "content": "# gRPC Configuration Settings\n\ngRPC exposes a [variety of settings](https://godoc.org/google.golang.org/grpc).\nSeveral of these settings are available for configuration within individual\nreceivers or exporters. In general, none of these settings should need to be\nadjusted.\n\n## Client Configuration\n\n[Exporters](https://github.com/open-telemetry/opentelemetry-collector/blob/main/exporter/README.md)\nleverage client configuration.\n\nNote that client configuration supports TLS configuration, the\nconfiguration parameters are also defined under `tls` like server\nconfiguration. For more information, see [configtls\nREADME](../configtls/README.md).\n\n- [`balancer_name`](https://github.com/grpc/grpc-go/blob/master/examples/features/load_balancing/README.md): Default before v0.103.0 is `pick_first`, default for v0.103.0 is `round_robin`. See [issue](https://github.com/open-telemetry/opentelemetry-collector/issues/10298). To restore the previous behavior, set `balancer_name` to `pick_first`.\n- `compression`: Compression type to use among `gzip`, `snappy`, `zstd`, and `none`.\n- `endpoint`: Valid value syntax available [here](https://github.com/grpc/grpc/blob/master/doc/naming.md)\n- [`tls`](../configtls/README.md)\n- `headers`: name/value pairs added to the request\n- [`keepalive`](https://godoc.org/google.golang.org/grpc/keepalive#ClientParameters)\n  - `permit_without_stream`\n  - `time`\n  - `timeout`\n- [`read_buffer_size`](https://godoc.org/google.golang.org/grpc#ReadBufferSize)\n- [`write_buffer_size`](https://godoc.org/google.golang.org/grpc#WriteBufferSize)\n- [`auth`](../configauth/README.md)\n- [`middlewares`](../configmiddleware/README.md)\n\nPlease note that [`per_rpc_auth`](https://pkg.go.dev/google.golang.org/grpc#PerRPCCredentials) which allows the credentials to send for every RPC is now moved to become an [extension](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/extension/bearertokenauthextension). Note that this feature isn't about sending the headers only during the initial connection as an `authorization` header under the `headers` would do: this is sent for every RPC performed during an established connection.\n\nExample:\n\n```yaml\nexporters:\n  otlp_grpc:\n    endpoint: otelcol2:55690\n    auth:\n      authenticator: some-authenticator-extension\n    tls:\n      ca_file: ca.pem\n      cert_file: cert.pem\n      key_file: key.pem\n    headers:\n      test1: \"value1\"\n      \"test 2\": \"value 2\"\n```\n\n### Compression Comparison\n\n[configgrpc_benchmark_test.go](./configgrpc_benchmark_test.go) contains benchmarks comparing the supported compression algorithms. It performs compression using `gzip`, `zstd`, and `snappy` compression on small, medium, and large sized log, trace, and metric payloads. Each test case outputs the uncompressed payload size, the compressed payload size, and the average nanoseconds spent on compression. \n\nThe following table summarizes the results, including some additional columns computed from the raw data. The benchmarks were performed on an AWS m5.large EC2 instance with an Intel(R) Xeon(R) Platinum 8259CL CPU @ 2.50GHz.\n\n| Request           | Compressor | Raw Bytes | Compressed bytes | Compression ratio | Ns / op | Mb compressed / second | Mb saved / second |\n|-------------------|------------|-----------|------------------|-------------------|---------|------------------------|-------------------|\n| lg_log_request    | gzip       | 5150      | 262              | 19.66             | 49231   | 104.61                 | 99.29             |\n| lg_metric_request | gzip       | 6800      | 201              | 33.83             | 51816   | 131.23                 | 127.35            |\n| lg_trace_request  | gzip       | 9200      | 270              | 34.07             | 65174   | 141.16                 | 137.02            |\n| md_log_request    | gzip       | 363       | 268              | 1.35              | 37609   | 9.65                   | 2.53              |\n| md_metric_request | gzip       | 320       | 145              | 2.21              | 30141   | 10.62                  | 5.81              |\n| md_trace_request  | gzip       | 451       | 288              | 1.57              | 38270   | 11.78                  | 4.26              |\n| sm_log_request    | gzip       | 166       | 168              | 0.99              | 30511   | 5.44                   | -0.07             |\n| sm_metric_request | gzip       | 185       | 142              | 1.30              | 29055   | 6.37                   | 1.48              |\n| sm_trace_request  | gzip       | 233       | 205              | 1.14              | 33466   | 6.96                   | 0.84              |\n| lg_log_request    | snappy     | 5150      | 475              | 10.84             | 1915    | 2,689.30               | 2,441.25          |\n| lg_metric_request | snappy     | 6800      | 466              | 14.59             | 2266    | 3,000.88               | 2,795.23          |\n| lg_trace_request  | snappy     | 9200      | 644              | 14.29             | 3281    | 2,804.02               | 2,607.74          |\n| md_log_request    | snappy     | 363       | 300              | 1.21              | 770.0   | 471.43                 | 81.82             |\n| md_metric_request | snappy     | 320       | 162              | 1.98              | 588.6   | 543.66                 | 268.43            |\n| md_trace_request  | snappy     | 451       | 330              | 1.37              | 907.7   | 496.86                 | 133.30            |\n| sm_log_request    | snappy     | 166       | 184              | 0.90              | 551.8   | 300.83                 | -32.62            |\n| sm_metric_request | snappy     | 185       | 154              | 1.20              | 526.3   | 351.51                 | 58.90             |\n| sm_trace_request  | snappy     | 233       | 251              | 0.93              | 682.1   | 341.59                 | -26.39            |\n| lg_log_request    | zstd       | 5150      | 223              | 23.09             | 17998   | 286.14                 | 273.75            |\n| lg_metric_request | zstd       | 6800      | 144              | 47.22             | 14289   | 475.89                 | 465.81            |\n| lg_trace_request  | zstd       | 9200      | 208              | 44.23             | 17160   | 536.13                 | 524.01            |\n| md_log_request    | zstd       | 363       | 261              | 1.39              | 11216   | 32.36                  | 9.09              |\n| md_metric_request | zstd       | 320       | 145              | 2.21              | 9318    | 34.34                  | 18.78             |\n| md_trace_request  | zstd       | 451       | 301              | 1.50              | 12583   | 35.84                  | 11.92             |\n| sm_log_request    | zstd       | 166       | 165              | 1.01              | 12482   | 13.30                  | 0.08              |\n| sm_metric_request | zstd       | 185       | 139              | 1.33              | 8824    | 20.97                  | 5.21              |\n| sm_trace_request  | zstd       | 233       | 203              | 1.15              | 10134   | 22.99                  | 2.96              |\n\nCompression ratios will vary in practice as they are highly dependent on the data's information entropy. Compression rates are dependent on the speed of the CPU, and the size of payloads being compressed: smaller payloads compress at slower rates relative to larger payloads, which are able to amortize fixed computation costs over more bytes.\n\n`gzip` is the only required compression algorithm required for [OTLP servers](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/otlp.md#protocol-details), and is a natural first choice. It is not as fast as `snappy`, but achieves better compression ratios and has reasonable performance. If your collector is CPU bound and your OTLP server supports it, you may benefit from using `snappy` compression. If your collector is CPU bound and has a very fast network link, you may benefit from disabling compression, which is the default.\n\n## Server Configuration\n\n[Receivers](https://github.com/open-telemetry/opentelemetry-collector/blob/main/receiver/README.md)\nleverage server configuration.\n\nNote that transport configuration can also be configured. The default transport\ntype is TCP. For more information, see [confignet\nREADME](../confignet/README.md).\n\n- [`keepalive`](https://godoc.org/google.golang.org/grpc/keepalive#ServerParameters)\n  - [`enforcement_policy`](https://godoc.org/google.golang.org/grpc/keepalive#EnforcementPolicy)\n    - `min_time`\n    - `permit_without_stream`\n  - [`server_parameters`](https://godoc.org/google.golang.org/grpc/keepalive#ServerParameters)\n    - `max_connection_age`\n    - `max_connection_age_grace`\n    - `max_connection_idle`\n    - `time`\n    - `timeout`\n- [`max_concurrent_streams`](https://godoc.org/google.golang.org/grpc#MaxConcurrentStreams)\n- [`max_recv_msg_size_mib`](https://godoc.org/google.golang.org/grpc#MaxRecvMsgSize)\n- [`read_buffer_size`](https://godoc.org/google.golang.org/grpc#ReadBufferSize)\n- [`tls`](../configtls/README.md)\n- [`write_buffer_size`](https://godoc.org/google.golang.org/grpc#WriteBufferSize)\n- [`auth`](../configauth/README.md)\n- [`middlewares`](../configmiddleware/README.md)\n"
  },
  {
    "path": "config/configgrpc/client_middleware_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configgrpc\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/metadata\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configmiddleware\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensionmiddleware\"\n\t\"go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest\"\n)\n\n// testlientMiddleware is a mock implementation of a middleware extension\ntype testClientMiddleware struct {\n\textension.Extension\n\textensionmiddleware.GetGRPCClientOptionsFunc\n}\n\nfunc newTestMiddlewareConfig(name string) configmiddleware.Config {\n\treturn configmiddleware.Config{\n\t\tID: component.MustNewID(name),\n\t}\n}\n\nfunc newTestClientMiddleware(name string) extension.Extension {\n\treturn &testClientMiddleware{\n\t\tExtension: extensionmiddlewaretest.NewNop(),\n\t\tGetGRPCClientOptionsFunc: func(_ context.Context) ([]grpc.DialOption, error) {\n\t\t\treturn []grpc.DialOption{\n\t\t\t\tgrpc.WithChainUnaryInterceptor(\n\t\t\t\t\tfunc(\n\t\t\t\t\t\tctx context.Context,\n\t\t\t\t\t\tmethod string,\n\t\t\t\t\t\treq, reply any,\n\t\t\t\t\t\tcc *grpc.ClientConn,\n\t\t\t\t\t\tinvoker grpc.UnaryInvoker,\n\t\t\t\t\t\topts ...grpc.CallOption,\n\t\t\t\t\t) error {\n\t\t\t\t\t\t// Get existing metadata or create new metadata\n\t\t\t\t\t\tmd, ok := metadata.FromOutgoingContext(ctx)\n\t\t\t\t\t\tif !ok {\n\t\t\t\t\t\t\tmd = metadata.New(nil)\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t// Clone the metadata to avoid modifying the real metadata map\n\t\t\t\t\t\t\tmd = md.Copy()\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Check if there's already a middleware sequence header\n\t\t\t\t\t\tsequence := \"\"\n\t\t\t\t\t\tif values := md.Get(\"middleware-sequence\"); len(values) > 0 {\n\t\t\t\t\t\t\tsequence = values[0]\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Append this middleware's ID to the sequence\n\t\t\t\t\t\tif sequence == \"\" {\n\t\t\t\t\t\t\tsequence = name\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tsequence = fmt.Sprintf(\"%s,%s\", sequence, name)\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Set the updated sequence\n\t\t\t\t\t\tmd.Set(\"middleware-sequence\", sequence)\n\n\t\t\t\t\t\t// Create a new context with the updated metadata\n\t\t\t\t\t\tnewCtx := metadata.NewOutgoingContext(ctx, md)\n\n\t\t\t\t\t\t// Continue the call with our updated context\n\t\t\t\t\t\treturn invoker(newCtx, method, req, reply, cc, opts...)\n\t\t\t\t\t}),\n\t\t\t}, nil\n\t\t},\n\t}\n}\n\n// TestClientMiddlewareOrdering verifies that client middleware\n// interceptors are called in the right order.\nfunc TestClientMiddlewareOrdering(t *testing.T) {\n\t// Create a middleware tracking header that will be modified by our middleware interceptors\n\tconst middlewareTrackingHeader = \"middleware-sequence\"\n\n\t// Create middleware extensions that will modify the metadata to track their execution order\n\tmockMiddleware1 := newTestClientMiddleware(\"middleware-1\")\n\tmockMiddleware2 := newTestClientMiddleware(\"middleware-2\")\n\n\tmockExt := map[component.ID]component.Component{\n\t\tcomponent.MustNewID(\"middleware1\"): mockMiddleware1,\n\t\tcomponent.MustNewID(\"middleware2\"): mockMiddleware2,\n\t}\n\n\t// Start a gRPC server that will record the incoming metadata\n\tserver := &grpcTraceServer{}\n\tsrv, addr := server.startTestServer(t, configoptional.Some(ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  \"localhost:0\",\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t}))\n\tdefer srv.Stop()\n\n\t// Create client config with middleware extensions\n\tclientConfig := ClientConfig{\n\t\tEndpoint: addr,\n\t\tTLS: configtls.ClientConfig{\n\t\t\tInsecure: true,\n\t\t},\n\t\tMiddlewares: []configmiddleware.Config{\n\t\t\tnewTestMiddlewareConfig(\"middleware1\"),\n\t\t\tnewTestMiddlewareConfig(\"middleware2\"),\n\t\t},\n\t}\n\n\t// Send a request using the client with middleware\n\tresp, err := sendTestRequestWithExtensions(t, clientConfig, mockExt)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, resp)\n\n\t// Verify that the middleware order was respected as recorded in the metadata\n\tictx, ok := metadata.FromIncomingContext(server.recordedContext)\n\trequire.True(t, ok, \"middleware tracking header not found in metadata\")\n\tmd := ictx[middlewareTrackingHeader]\n\trequire.Len(t, md, 1, \"expected exactly one middleware tracking header value\")\n\n\t// The sequence should be \"middleware-1,middleware-2\" as that's the order they were registered\n\texpectedSequence := \"middleware-1,middleware-2\"\n\tassert.Equal(t, expectedSequence, md[0])\n}\n\n// TestClientMiddlewareToClientErrors tests failure cases for the ToClient method\n// specifically related to middleware resolution and API calls.\nfunc TestClientMiddlewareToClientErrors(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\textensions map[component.ID]component.Component\n\t\tconfig     ClientConfig\n\t\terrText    string\n\t}{\n\t\t{\n\t\t\tname:       \"extension_not_found\",\n\t\t\textensions: map[component.ID]component.Component{},\n\t\t\tconfig: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tInsecure: true,\n\t\t\t\t},\n\t\t\t\tMiddlewares: []configmiddleware.Config{\n\t\t\t\t\t{\n\t\t\t\t\t\tID: component.MustNewID(\"nonexistent\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\terrText: \"failed to resolve middleware \\\"nonexistent\\\": middleware not found\",\n\t\t},\n\t\t{\n\t\t\tname: \"get_client_options_fails\",\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\tcomponent.MustNewID(\"errormw\"): extensionmiddlewaretest.NewErr(errors.New(\"get options failed\")),\n\t\t\t},\n\t\t\tconfig: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tInsecure: true,\n\t\t\t\t},\n\t\t\t\tMiddlewares: []configmiddleware.Config{\n\t\t\t\t\t{\n\t\t\t\t\t\tID: component.MustNewID(\"errormw\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\terrText: \"get options failed\",\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t// Test creating the client with middleware errors\n\t\t\t_, err := tc.config.ToClientConn(context.Background(), tc.extensions, componenttest.NewNopTelemetrySettings())\n\t\t\trequire.Error(t, err)\n\t\t\tassert.Contains(t, err.Error(), tc.errText)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "config/configgrpc/config.schema.yaml",
    "content": "$defs:\n  client_config:\n    description: ClientConfig defines common settings for a gRPC client configuration.\n    type: object\n    properties:\n      auth:\n        description: Auth configuration for outgoing RPCs.\n        x-optional: true\n        $ref: go.opentelemetry.io/collector/config/configauth.config\n      authority:\n        description: WithAuthority parameter configures client to rewrite \":authority\" header (godoc.org/google.golang.org/grpc#WithAuthority)\n        type: string\n      balancer_name:\n        description: Sets the balancer in grpclb_policy to discover the servers. Default is pick_first. https://github.com/grpc/grpc-go/blob/master/examples/features/load_balancing/README.md\n        type: string\n      compression:\n        description: The compression key for supported compression types within collector.\n        $ref: go.opentelemetry.io/collector/config/configcompression.type\n      endpoint:\n        description: The target to which the exporter is going to send traces or metrics, using the gRPC protocol. The valid syntax is described at https://github.com/grpc/grpc/blob/master/doc/naming.md.\n        type: string\n      headers:\n        description: The headers associated with gRPC requests.\n        $ref: go.opentelemetry.io/collector/config/configopaque.map_list\n      keepalive:\n        description: The keepalive parameters for gRPC client. See grpc.WithKeepaliveParams. (https://godoc.org/google.golang.org/grpc#WithKeepaliveParams).\n        x-optional: true\n        $ref: keepalive_client_config\n      middlewares:\n        description: Middlewares for the gRPC client.\n        type: array\n        items:\n          $ref: go.opentelemetry.io/collector/config/configmiddleware.config\n      read_buffer_size:\n        description: ReadBufferSize for gRPC client. See grpc.WithReadBufferSize. (https://godoc.org/google.golang.org/grpc#WithReadBufferSize).\n        type: integer\n      tls:\n        description: TLS struct exposes TLS client configuration.\n        $ref: go.opentelemetry.io/collector/config/configtls.client_config\n      wait_for_ready:\n        description: WaitForReady parameter configures client to wait for ready state before sending data. (https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md)\n        type: boolean\n      write_buffer_size:\n        description: WriteBufferSize for gRPC gRPC. See grpc.WithWriteBufferSize. (https://godoc.org/google.golang.org/grpc#WithWriteBufferSize).\n        type: integer\n  keepalive_client_config:\n    description: 'KeepaliveClientConfig exposes the keepalive.ClientParameters to be used by the exporter. Refer to the original data-structure for the meaning of each parameter: https://godoc.org/google.golang.org/grpc/keepalive#ClientParameters'\n    type: object\n    properties:\n      permit_without_stream:\n        type: boolean\n      time:\n        type: string\n        x-customType: time.Duration\n        format: duration\n      timeout:\n        type: string\n        x-customType: time.Duration\n        format: duration\n  keepalive_enforcement_policy:\n    description: KeepaliveEnforcementPolicy allow configuration of the keepalive.EnforcementPolicy. The same default values as keepalive.EnforcementPolicy are applicable and get applied by the server. See https://godoc.org/google.golang.org/grpc/keepalive#EnforcementPolicy for details.\n    type: object\n    properties:\n      min_time:\n        type: string\n        x-customType: time.Duration\n        format: duration\n      permit_without_stream:\n        type: boolean\n  keepalive_server_config:\n    description: KeepaliveServerConfig is the configuration for keepalive.\n    type: object\n    properties:\n      enforcement_policy:\n        x-optional: true\n        $ref: keepalive_enforcement_policy\n      server_parameters:\n        x-optional: true\n        $ref: keepalive_server_parameters\n  keepalive_server_parameters:\n    description: KeepaliveServerParameters allow configuration of the keepalive.ServerParameters. The same default values as keepalive.ServerParameters are applicable and get applied by the server. See https://godoc.org/google.golang.org/grpc/keepalive#ServerParameters for details.\n    type: object\n    properties:\n      max_connection_age:\n        type: string\n        x-customType: time.Duration\n        format: duration\n      max_connection_age_grace:\n        type: string\n        x-customType: time.Duration\n        format: duration\n      max_connection_idle:\n        type: string\n        x-customType: time.Duration\n        format: duration\n      time:\n        type: string\n        x-customType: time.Duration\n        format: duration\n      timeout:\n        type: string\n        x-customType: time.Duration\n        format: duration\n  server_config:\n    description: ServerConfig defines common settings for a gRPC server configuration.\n    type: object\n    properties:\n      auth:\n        description: Auth for this receiver\n        x-optional: true\n        $ref: go.opentelemetry.io/collector/config/configauth.config\n      include_metadata:\n        description: Include propagates the incoming connection's metadata to downstream consumers.\n        type: boolean\n      keepalive:\n        description: Keepalive anchor for all the settings related to keepalive.\n        x-optional: true\n        $ref: keepalive_server_config\n      max_concurrent_streams:\n        description: MaxConcurrentStreams sets the limit on the number of concurrent streams to each ServerTransport. It has effect only for streaming RPCs.\n        type: integer\n        x-customType: uint32\n      max_recv_msg_size_mib:\n        description: MaxRecvMsgSizeMiB sets the maximum size (in MiB) of messages accepted by the server.\n        type: integer\n      middlewares:\n        description: Middlewares for the gRPC server.\n        type: array\n        items:\n          $ref: go.opentelemetry.io/collector/config/configmiddleware.config\n      read_buffer_size:\n        description: ReadBufferSize for gRPC server. See grpc.ReadBufferSize. (https://godoc.org/google.golang.org/grpc#ReadBufferSize).\n        type: integer\n      tls:\n        description: Configures the protocol to use TLS. The default value is nil, which will cause the protocol to not use TLS.\n        x-optional: true\n        $ref: go.opentelemetry.io/collector/config/configtls.server_config\n      write_buffer_size:\n        description: WriteBufferSize for gRPC server. See grpc.WriteBufferSize. (https://godoc.org/google.golang.org/grpc#WriteBufferSize).\n        type: integer\n    allOf:\n      - $ref: go.opentelemetry.io/collector/config/confignet.addr_config\n"
  },
  {
    "path": "config/configgrpc/configgrpc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configgrpc // import \"go.opentelemetry.io/collector/config/configgrpc\"\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"errors\"\n\t\"fmt\"\n\t\"math\"\n\t\"net\"\n\t\"regexp\"\n\t\"strconv\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/mostynb/go-grpc-compression/nonclobbering/snappy\"\n\t\"github.com/mostynb/go-grpc-compression/nonclobbering/zstd\"\n\t\"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc\"\n\t\"go.opentelemetry.io/otel\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/balancer\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/credentials\"\n\t\"google.golang.org/grpc/credentials/insecure\"\n\t\"google.golang.org/grpc/encoding/gzip\"\n\t\"google.golang.org/grpc/keepalive\"\n\t\"google.golang.org/grpc/metadata\"\n\t\"google.golang.org/grpc/peer\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/client\"\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configauth\"\n\t\"go.opentelemetry.io/collector/config/configcompression\"\n\t\"go.opentelemetry.io/collector/config/configmiddleware\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/extension/extensionauth\"\n)\n\nvar errMetadataNotFound = errors.New(\"no request metadata found\")\n\n// KeepaliveClientConfig exposes the keepalive.ClientParameters to be used by the exporter.\n// Refer to the original data-structure for the meaning of each parameter:\n// https://godoc.org/google.golang.org/grpc/keepalive#ClientParameters\ntype KeepaliveClientConfig struct {\n\tTime                time.Duration `mapstructure:\"time\"`\n\tTimeout             time.Duration `mapstructure:\"timeout\"`\n\tPermitWithoutStream bool          `mapstructure:\"permit_without_stream,omitempty\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// NewDefaultKeepaliveClientConfig returns a new instance of KeepaliveClientConfig with default values.\nfunc NewDefaultKeepaliveClientConfig() KeepaliveClientConfig {\n\treturn KeepaliveClientConfig{\n\t\tTime:    time.Second * 10,\n\t\tTimeout: time.Second * 10,\n\t}\n}\n\n// BalancerName returns a string with default load balancer value\nfunc BalancerName() string {\n\treturn \"round_robin\"\n}\n\n// ClientConfig defines common settings for a gRPC client configuration.\ntype ClientConfig struct {\n\t// The target to which the exporter is going to send traces or metrics,\n\t// using the gRPC protocol. The valid syntax is described at\n\t// https://github.com/grpc/grpc/blob/master/doc/naming.md.\n\tEndpoint string `mapstructure:\"endpoint,omitempty\"`\n\n\t// The compression key for supported compression types within collector.\n\tCompression configcompression.Type `mapstructure:\"compression,omitempty\"`\n\n\t// TLS struct exposes TLS client configuration.\n\tTLS configtls.ClientConfig `mapstructure:\"tls,omitempty\"`\n\n\t// The keepalive parameters for gRPC client. See grpc.WithKeepaliveParams.\n\t// (https://godoc.org/google.golang.org/grpc#WithKeepaliveParams).\n\tKeepalive configoptional.Optional[KeepaliveClientConfig] `mapstructure:\"keepalive,omitempty\"`\n\n\t// ReadBufferSize for gRPC client. See grpc.WithReadBufferSize.\n\t// (https://godoc.org/google.golang.org/grpc#WithReadBufferSize).\n\tReadBufferSize int `mapstructure:\"read_buffer_size,omitempty\"`\n\n\t// WriteBufferSize for gRPC gRPC. See grpc.WithWriteBufferSize.\n\t// (https://godoc.org/google.golang.org/grpc#WithWriteBufferSize).\n\tWriteBufferSize int `mapstructure:\"write_buffer_size,omitempty\"`\n\n\t// WaitForReady parameter configures client to wait for ready state before sending data.\n\t// (https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md)\n\tWaitForReady bool `mapstructure:\"wait_for_ready,omitempty\"`\n\n\t// The headers associated with gRPC requests.\n\tHeaders configopaque.MapList `mapstructure:\"headers,omitempty\"`\n\n\t// Sets the balancer in grpclb_policy to discover the servers. Default is pick_first.\n\t// https://github.com/grpc/grpc-go/blob/master/examples/features/load_balancing/README.md\n\tBalancerName string `mapstructure:\"balancer_name\"`\n\n\t// WithAuthority parameter configures client to rewrite \":authority\" header\n\t// (godoc.org/google.golang.org/grpc#WithAuthority)\n\tAuthority string `mapstructure:\"authority,omitempty\"`\n\n\t// Auth configuration for outgoing RPCs.\n\tAuth configoptional.Optional[configauth.Config] `mapstructure:\"auth,omitempty\"`\n\n\t// Middlewares for the gRPC client.\n\tMiddlewares []configmiddleware.Config `mapstructure:\"middlewares,omitempty\"`\n}\n\n// NewDefaultClientConfig returns a new instance of ClientConfig with default values.\nfunc NewDefaultClientConfig() ClientConfig {\n\treturn ClientConfig{\n\t\tTLS:          configtls.NewDefaultClientConfig(),\n\t\tKeepalive:    configoptional.Some(NewDefaultKeepaliveClientConfig()),\n\t\tBalancerName: BalancerName(),\n\t}\n}\n\n// KeepaliveServerConfig is the configuration for keepalive.\ntype KeepaliveServerConfig struct {\n\tServerParameters  configoptional.Optional[KeepaliveServerParameters]  `mapstructure:\"server_parameters,omitempty\"`\n\tEnforcementPolicy configoptional.Optional[KeepaliveEnforcementPolicy] `mapstructure:\"enforcement_policy,omitempty\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// NewDefaultKeepaliveServerConfig returns a new instance of KeepaliveServerConfig with default values.\nfunc NewDefaultKeepaliveServerConfig() KeepaliveServerConfig {\n\treturn KeepaliveServerConfig{\n\t\tServerParameters:  configoptional.Some(NewDefaultKeepaliveServerParameters()),\n\t\tEnforcementPolicy: configoptional.Some(NewDefaultKeepaliveEnforcementPolicy()),\n\t}\n}\n\n// KeepaliveServerParameters allow configuration of the keepalive.ServerParameters.\n// The same default values as keepalive.ServerParameters are applicable and get applied by the server.\n// See https://godoc.org/google.golang.org/grpc/keepalive#ServerParameters for details.\ntype KeepaliveServerParameters struct {\n\tMaxConnectionIdle     time.Duration `mapstructure:\"max_connection_idle,omitempty\"`\n\tMaxConnectionAge      time.Duration `mapstructure:\"max_connection_age,omitempty\"`\n\tMaxConnectionAgeGrace time.Duration `mapstructure:\"max_connection_age_grace,omitempty\"`\n\tTime                  time.Duration `mapstructure:\"time,omitempty\"`\n\tTimeout               time.Duration `mapstructure:\"timeout,omitempty\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// NewDefaultKeepaliveServerParameters creates and returns a new instance of KeepaliveServerParameters with default settings.\nfunc NewDefaultKeepaliveServerParameters() KeepaliveServerParameters {\n\treturn KeepaliveServerParameters{}\n}\n\n// KeepaliveEnforcementPolicy allow configuration of the keepalive.EnforcementPolicy.\n// The same default values as keepalive.EnforcementPolicy are applicable and get applied by the server.\n// See https://godoc.org/google.golang.org/grpc/keepalive#EnforcementPolicy for details.\ntype KeepaliveEnforcementPolicy struct {\n\tMinTime             time.Duration `mapstructure:\"min_time,omitempty\"`\n\tPermitWithoutStream bool          `mapstructure:\"permit_without_stream,omitempty\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// NewDefaultKeepaliveEnforcementPolicy creates and returns a new instance of KeepaliveEnforcementPolicy with default settings.\nfunc NewDefaultKeepaliveEnforcementPolicy() KeepaliveEnforcementPolicy {\n\treturn KeepaliveEnforcementPolicy{}\n}\n\n// ServerConfig defines common settings for a gRPC server configuration.\ntype ServerConfig struct {\n\t// Server net.Addr config. For transport only \"tcp\" and \"unix\" are valid options.\n\tNetAddr confignet.AddrConfig `mapstructure:\",squash\"`\n\n\t// Configures the protocol to use TLS.\n\t// The default value is nil, which will cause the protocol to not use TLS.\n\tTLS configoptional.Optional[configtls.ServerConfig] `mapstructure:\"tls,omitempty\"`\n\n\t// MaxRecvMsgSizeMiB sets the maximum size (in MiB) of messages accepted by the server.\n\tMaxRecvMsgSizeMiB int `mapstructure:\"max_recv_msg_size_mib,omitempty\"`\n\n\t// MaxConcurrentStreams sets the limit on the number of concurrent streams to each ServerTransport.\n\t// It has effect only for streaming RPCs.\n\tMaxConcurrentStreams uint32 `mapstructure:\"max_concurrent_streams,omitempty,omitempty\"`\n\n\t// ReadBufferSize for gRPC server. See grpc.ReadBufferSize.\n\t// (https://godoc.org/google.golang.org/grpc#ReadBufferSize).\n\tReadBufferSize int `mapstructure:\"read_buffer_size,omitempty\"`\n\n\t// WriteBufferSize for gRPC server. See grpc.WriteBufferSize.\n\t// (https://godoc.org/google.golang.org/grpc#WriteBufferSize).\n\tWriteBufferSize int `mapstructure:\"write_buffer_size,omitempty\"`\n\n\t// Keepalive anchor for all the settings related to keepalive.\n\tKeepalive configoptional.Optional[KeepaliveServerConfig] `mapstructure:\"keepalive,omitempty\"`\n\n\t// Auth for this receiver\n\tAuth configoptional.Optional[configauth.Config] `mapstructure:\"auth,omitempty\"`\n\n\t// Include propagates the incoming connection's metadata to downstream consumers.\n\tIncludeMetadata bool `mapstructure:\"include_metadata,omitempty\"`\n\n\t// Middlewares for the gRPC server.\n\tMiddlewares []configmiddleware.Config `mapstructure:\"middlewares,omitempty\"`\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// NewDefaultServerConfig returns a new instance of ServerConfig with default values.\nfunc NewDefaultServerConfig() ServerConfig {\n\tnetAddr := confignet.NewDefaultAddrConfig()\n\n\t// We typically want to create a TCP server and listen over a network.\n\tnetAddr.Transport = confignet.TransportTypeTCP\n\n\treturn ServerConfig{\n\t\tKeepalive: configoptional.Some(NewDefaultKeepaliveServerConfig()),\n\t\tNetAddr:   netAddr,\n\t}\n}\n\nfunc (cc *ClientConfig) Validate() error {\n\tif after, ok := strings.CutPrefix(cc.Endpoint, \"unix://\"); ok {\n\t\tif after == \"\" {\n\t\t\treturn errors.New(\"unix socket path cannot be empty\")\n\t\t}\n\t\treturn nil\n\t}\n\n\tif endpoint := cc.sanitizedEndpoint(); endpoint != \"\" {\n\t\t// Validate that the port is in the address\n\t\t_, port, err := net.SplitHostPort(endpoint)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif _, err := strconv.Atoi(port); err != nil {\n\t\t\treturn fmt.Errorf(`invalid port \"%v\"`, port)\n\t\t}\n\t}\n\n\tif cc.BalancerName != \"\" {\n\t\tif balancer.Get(cc.BalancerName) == nil {\n\t\t\treturn fmt.Errorf(\"invalid balancer_name: %s\", cc.BalancerName)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// sanitizedEndpoint strips the prefix of either http:// or https:// from configgrpc.ClientConfig.Endpoint.\nfunc (cc *ClientConfig) sanitizedEndpoint() string {\n\tswitch {\n\tcase cc.isSchemeHTTP():\n\t\treturn strings.TrimPrefix(cc.Endpoint, \"http://\")\n\tcase cc.isSchemeHTTPS():\n\t\treturn strings.TrimPrefix(cc.Endpoint, \"https://\")\n\tcase strings.HasPrefix(cc.Endpoint, \"dns://\"):\n\t\tr := regexp.MustCompile(`^dns:///?`)\n\t\treturn r.ReplaceAllString(cc.Endpoint, \"\")\n\tdefault:\n\t\treturn cc.Endpoint\n\t}\n}\n\nfunc (cc *ClientConfig) isSchemeHTTP() bool {\n\treturn strings.HasPrefix(cc.Endpoint, \"http://\")\n}\n\nfunc (cc *ClientConfig) isSchemeHTTPS() bool {\n\treturn strings.HasPrefix(cc.Endpoint, \"https://\")\n}\n\n// ToClientConnOption is a sealed interface wrapping options for [ClientConfig.ToClientConn].\ntype ToClientConnOption interface {\n\tisToClientConnOption()\n}\n\ntype grpcDialOptionWrapper struct {\n\topt grpc.DialOption\n}\n\n// WithGrpcDialOption wraps a [grpc.DialOption] into a [ToClientConnOption].\nfunc WithGrpcDialOption(opt grpc.DialOption) ToClientConnOption {\n\treturn grpcDialOptionWrapper{opt: opt}\n}\nfunc (grpcDialOptionWrapper) isToClientConnOption() {}\n\n// ToClientConn creates a client connection to the given target. By default, it's\n// a non-blocking dial (the function won't wait for connections to be\n// established, and connecting happens in the background). To make it a blocking\n// dial, use the WithGrpcDialOption(grpc.WithBlock()) option.\n//\n// To allow the configuration to reference middleware or authentication extensions,\n// the `extensions` argument should be the output of `host.GetExtensions()`.\n// It may also be `nil` in tests where no such extension is expected to be used.\nfunc (cc *ClientConfig) ToClientConn(\n\tctx context.Context,\n\textensions map[component.ID]component.Component,\n\tsettings component.TelemetrySettings,\n\textraOpts ...ToClientConnOption,\n) (*grpc.ClientConn, error) {\n\tgrpcOpts, err := cc.getGrpcDialOptions(ctx, extensions, settings, extraOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tconn, err := grpc.NewClient(cc.sanitizedEndpoint(), grpcOpts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Initiate connection to match the previous behavior of DialContext\n\t// This ensures the connection is established eagerly rather than lazily\n\tconn.Connect()\n\n\treturn conn, nil\n}\n\nfunc (cc *ClientConfig) addHeadersIfAbsent(ctx context.Context) context.Context {\n\tkv := make([]string, 0, 2*len(cc.Headers))\n\texistingMd, _ := metadata.FromOutgoingContext(ctx)\n\tfor k, v := range cc.Headers.Iter {\n\t\tif len(existingMd.Get(k)) == 0 {\n\t\t\tkv = append(kv, k, string(v))\n\t\t}\n\t}\n\treturn metadata.AppendToOutgoingContext(ctx, kv...)\n}\n\nfunc (cc *ClientConfig) getGrpcDialOptions(\n\tctx context.Context,\n\textensions map[component.ID]component.Component,\n\tsettings component.TelemetrySettings,\n\textraOpts []ToClientConnOption,\n) ([]grpc.DialOption, error) {\n\tvar opts []grpc.DialOption\n\tif cc.Compression.IsCompressed() {\n\t\tcp, err := getGRPCCompressionName(cc.Compression)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topts = append(opts, grpc.WithDefaultCallOptions(grpc.UseCompressor(cp)))\n\t}\n\n\ttlsCfg, err := cc.TLS.LoadTLSConfig(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tcred := insecure.NewCredentials()\n\tif tlsCfg != nil {\n\t\tcred = credentials.NewTLS(tlsCfg)\n\t} else if cc.isSchemeHTTPS() {\n\t\tcred = credentials.NewTLS(&tls.Config{})\n\t}\n\topts = append(opts, grpc.WithTransportCredentials(cred))\n\n\tif cc.ReadBufferSize > 0 {\n\t\topts = append(opts, grpc.WithReadBufferSize(cc.ReadBufferSize))\n\t}\n\n\tif cc.WriteBufferSize > 0 {\n\t\topts = append(opts, grpc.WithWriteBufferSize(cc.WriteBufferSize))\n\t}\n\n\tif cc.Keepalive.HasValue() {\n\t\tkeepaliveConfig := cc.Keepalive.Get()\n\t\tkeepAliveOption := grpc.WithKeepaliveParams(keepalive.ClientParameters{\n\t\t\tTime:                keepaliveConfig.Time,\n\t\t\tTimeout:             keepaliveConfig.Timeout,\n\t\t\tPermitWithoutStream: keepaliveConfig.PermitWithoutStream,\n\t\t})\n\t\topts = append(opts, keepAliveOption)\n\t}\n\n\tif cc.Auth.HasValue() {\n\t\tif extensions == nil {\n\t\t\treturn nil, errors.New(\"authentication was configured but this component or its host does not support extensions\")\n\t\t}\n\n\t\tgrpcAuthenticator, cerr := cc.Auth.Get().GetGRPCClientAuthenticator(ctx, extensions)\n\t\tif cerr != nil {\n\t\t\treturn nil, cerr\n\t\t}\n\n\t\tperRPCCredentials, perr := grpcAuthenticator.PerRPCCredentials()\n\t\tif perr != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topts = append(opts, grpc.WithPerRPCCredentials(perRPCCredentials))\n\t}\n\n\tif cc.BalancerName != \"\" {\n\t\topts = append(opts, grpc.WithDefaultServiceConfig(fmt.Sprintf(`{\"loadBalancingPolicy\":%q}`, cc.BalancerName)))\n\t}\n\n\tif cc.Authority != \"\" {\n\t\topts = append(opts, grpc.WithAuthority(cc.Authority))\n\t}\n\n\totelOpts := []otelgrpc.Option{\n\t\totelgrpc.WithTracerProvider(settings.TracerProvider),\n\t\totelgrpc.WithPropagators(otel.GetTextMapPropagator()),\n\t\totelgrpc.WithMeterProvider(settings.MeterProvider),\n\t}\n\n\t// Enable OpenTelemetry observability plugin.\n\topts = append(opts, grpc.WithStatsHandler(otelgrpc.NewClientHandler(otelOpts...)))\n\n\tif len(cc.Headers) > 0 {\n\t\topts = append(opts,\n\t\t\tgrpc.WithUnaryInterceptor(func(ctx context.Context, method string, req, reply any, gcc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {\n\t\t\t\treturn invoker(cc.addHeadersIfAbsent(ctx), method, req, reply, gcc, opts...)\n\t\t\t}),\n\t\t\tgrpc.WithStreamInterceptor(func(ctx context.Context, desc *grpc.StreamDesc, gcc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) {\n\t\t\t\treturn streamer(cc.addHeadersIfAbsent(ctx), desc, gcc, method, opts...)\n\t\t\t}),\n\t\t)\n\t}\n\n\t// Apply middleware options. Note: OpenTelemetry could be registered as an extension.\n\tif len(cc.Middlewares) > 0 && extensions == nil {\n\t\treturn nil, errors.New(\"middlewares were configured but this component or its host does not support extensions\")\n\t}\n\tfor _, middleware := range cc.Middlewares {\n\t\tmiddlewareOptions, err := middleware.GetGRPCClientOptions(ctx, extensions)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get gRPC client options from middleware: %w\", err)\n\t\t}\n\t\topts = append(opts, middlewareOptions...)\n\t}\n\n\tfor _, opt := range extraOpts {\n\t\tif wrapper, ok := opt.(grpcDialOptionWrapper); ok {\n\t\t\topts = append(opts, wrapper.opt)\n\t\t}\n\t}\n\n\treturn opts, nil\n}\n\nfunc (sc *ServerConfig) Validate() error {\n\tif sc.MaxRecvMsgSizeMiB*1024*1024 < 0 {\n\t\treturn fmt.Errorf(\"invalid max_recv_msg_size_mib value, must be between 1 and %d: %d\", math.MaxInt/1024/1024, sc.MaxRecvMsgSizeMiB)\n\t}\n\n\tif sc.ReadBufferSize < 0 {\n\t\treturn fmt.Errorf(\"invalid read_buffer_size value: %d\", sc.ReadBufferSize)\n\t}\n\n\tif sc.WriteBufferSize < 0 {\n\t\treturn fmt.Errorf(\"invalid write_buffer_size value: %d\", sc.WriteBufferSize)\n\t}\n\n\treturn nil\n}\n\n// ToServerOption is a sealed interface wrapping options for [ServerConfig.ToServer].\ntype ToServerOption interface {\n\tisToServerOption()\n}\n\ntype grpcServerOptionWrapper struct {\n\topt grpc.ServerOption\n}\n\n// WithGrpcServerOption wraps a [grpc.ServerOption] into a [ToServerOption].\nfunc WithGrpcServerOption(opt grpc.ServerOption) ToServerOption {\n\treturn grpcServerOptionWrapper{opt: opt}\n}\nfunc (grpcServerOptionWrapper) isToServerOption() {}\n\n// ToServer returns a [grpc.Server] for the configuration.\n//\n// To allow the configuration to reference middleware or authentication extensions,\n// the `extensions` argument should be the output of `host.GetExtensions()`.\n// It may also be `nil` in tests where no such extension is expected to be used.\nfunc (sc *ServerConfig) ToServer(\n\tctx context.Context,\n\textensions map[component.ID]component.Component,\n\tsettings component.TelemetrySettings,\n\textraOpts ...ToServerOption,\n) (*grpc.Server, error) {\n\tgrpcOpts, err := sc.getGrpcServerOptions(ctx, extensions, settings, extraOpts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn grpc.NewServer(grpcOpts...), nil\n}\n\nfunc (sc *ServerConfig) getGrpcServerOptions(\n\tctx context.Context,\n\textensions map[component.ID]component.Component,\n\tsettings component.TelemetrySettings,\n\textraOpts []ToServerOption,\n) ([]grpc.ServerOption, error) {\n\tvar opts []grpc.ServerOption\n\n\tif sc.TLS.HasValue() {\n\t\ttlsCfg, err := sc.TLS.Get().LoadTLSConfig(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\topts = append(opts, grpc.Creds(credentials.NewTLS(tlsCfg)))\n\t}\n\n\tif sc.MaxRecvMsgSizeMiB > 0 && sc.MaxRecvMsgSizeMiB*1024*1024 > 0 {\n\t\topts = append(opts, grpc.MaxRecvMsgSize(sc.MaxRecvMsgSizeMiB*1024*1024))\n\t}\n\n\tif sc.MaxConcurrentStreams > 0 {\n\t\topts = append(opts, grpc.MaxConcurrentStreams(sc.MaxConcurrentStreams))\n\t}\n\n\tif sc.ReadBufferSize > 0 {\n\t\topts = append(opts, grpc.ReadBufferSize(sc.ReadBufferSize))\n\t}\n\n\tif sc.WriteBufferSize > 0 {\n\t\topts = append(opts, grpc.WriteBufferSize(sc.WriteBufferSize))\n\t}\n\n\t// The default values referenced in the GRPC docs are set within the server, so this code doesn't need\n\t// to apply them over zero/nil values before passing these as grpc.ServerOptions.\n\t// The following shows the server code for applying default grpc.ServerOptions.\n\t// https://github.com/grpc/grpc-go/blob/120728e1f775e40a2a764341939b78d666b08260/internal/transport/http2_server.go#L184-L200\n\tif sc.Keepalive.HasValue() {\n\t\tkeepaliveConfig := sc.Keepalive.Get()\n\t\tif keepaliveConfig.ServerParameters.HasValue() {\n\t\t\tsvrParams := keepaliveConfig.ServerParameters.Get()\n\t\t\topts = append(opts, grpc.KeepaliveParams(keepalive.ServerParameters{\n\t\t\t\tMaxConnectionIdle:     svrParams.MaxConnectionIdle,\n\t\t\t\tMaxConnectionAge:      svrParams.MaxConnectionAge,\n\t\t\t\tMaxConnectionAgeGrace: svrParams.MaxConnectionAgeGrace,\n\t\t\t\tTime:                  svrParams.Time,\n\t\t\t\tTimeout:               svrParams.Timeout,\n\t\t\t}))\n\t\t}\n\t\t// The default values referenced in the GRPC are set within the server, so this code doesn't need\n\t\t// to apply them over zero/nil values before passing these as grpc.ServerOptions.\n\t\t// The following shows the server code for applying default grpc.ServerOptions.\n\t\t// https://github.com/grpc/grpc-go/blob/120728e1f775e40a2a764341939b78d666b08260/internal/transport/http2_server.go#L202-L205\n\t\tif keepaliveConfig.EnforcementPolicy.HasValue() {\n\t\t\tenfPol := keepaliveConfig.EnforcementPolicy.Get()\n\t\t\topts = append(opts, grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{\n\t\t\t\tMinTime:             enfPol.MinTime,\n\t\t\t\tPermitWithoutStream: enfPol.PermitWithoutStream,\n\t\t\t}))\n\t\t}\n\t}\n\n\tvar uInterceptors []grpc.UnaryServerInterceptor\n\tvar sInterceptors []grpc.StreamServerInterceptor\n\n\t// Add client info first, before auth.\n\tuInterceptors = append(uInterceptors, enhanceWithClientInformation(sc.IncludeMetadata))\n\tsInterceptors = append(sInterceptors, enhanceStreamWithClientInformation(sc.IncludeMetadata)) //nolint:contextcheck // context already handled\n\n\tif sc.Auth.HasValue() {\n\t\tauthenticator, err := sc.Auth.Get().GetServerAuthenticator(ctx, extensions)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tuInterceptors = append(uInterceptors, authUnaryServerInterceptor(authenticator))\n\t\tsInterceptors = append(sInterceptors, authStreamServerInterceptor(authenticator)) //nolint:contextcheck // context already handled\n\t}\n\n\totelOpts := []otelgrpc.Option{\n\t\totelgrpc.WithTracerProvider(settings.TracerProvider),\n\t\totelgrpc.WithPropagators(otel.GetTextMapPropagator()),\n\t\totelgrpc.WithMeterProvider(settings.MeterProvider),\n\t}\n\n\t// Enable OpenTelemetry observability plugin.\n\topts = append(opts, grpc.StatsHandler(otelgrpc.NewServerHandler(otelOpts...)), grpc.ChainUnaryInterceptor(uInterceptors...), grpc.ChainStreamInterceptor(sInterceptors...))\n\n\t// Apply middleware options. Note: OpenTelemetry could be registered as an extension.\n\tfor _, middleware := range sc.Middlewares {\n\t\tmiddlewareOptions, err := middleware.GetGRPCServerOptions(ctx, extensions)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get gRPC server options from middleware: %w\", err)\n\t\t}\n\t\topts = append(opts, middlewareOptions...)\n\t}\n\n\tfor _, opt := range extraOpts {\n\t\tif wrapper, ok := opt.(grpcServerOptionWrapper); ok {\n\t\t\topts = append(opts, wrapper.opt)\n\t\t}\n\t}\n\n\treturn opts, nil\n}\n\n// getGRPCCompressionName returns compression name registered in grpc.\nfunc getGRPCCompressionName(compressionType configcompression.Type) (string, error) {\n\tswitch compressionType {\n\tcase configcompression.TypeGzip:\n\t\treturn gzip.Name, nil\n\tcase configcompression.TypeSnappy:\n\t\treturn snappy.Name, nil\n\tcase configcompression.TypeZstd:\n\t\treturn zstd.Name, nil\n\tdefault:\n\t\treturn \"\", fmt.Errorf(\"unsupported compression type %q\", compressionType)\n\t}\n}\n\n// enhanceWithClientInformation intercepts the incoming RPC, replacing the incoming context with one that includes\n// a client.Info, potentially with the peer's address.\nfunc enhanceWithClientInformation(includeMetadata bool) grpc.UnaryServerInterceptor {\n\treturn func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {\n\t\treturn handler(contextWithClient(ctx, includeMetadata), req)\n\t}\n}\n\nfunc enhanceStreamWithClientInformation(includeMetadata bool) grpc.StreamServerInterceptor {\n\treturn func(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {\n\t\treturn handler(srv, wrapServerStream(contextWithClient(ss.Context(), includeMetadata), ss))\n\t}\n}\n\n// contextWithClient attempts to add the peer address to the client.Info from the context. When no\n// client.Info exists in the context, one is created.\nfunc contextWithClient(ctx context.Context, includeMetadata bool) context.Context {\n\tcl := client.FromContext(ctx)\n\tif p, ok := peer.FromContext(ctx); ok {\n\t\tcl.Addr = p.Addr\n\t}\n\tif includeMetadata {\n\t\tif md, ok := metadata.FromIncomingContext(ctx); ok {\n\t\t\tcopiedMD := md.Copy()\n\t\t\tif len(md[client.MetadataHostName]) == 0 && len(md[\":authority\"]) > 0 {\n\t\t\t\tcopiedMD[client.MetadataHostName] = md[\":authority\"]\n\t\t\t}\n\t\t\tcl.Metadata = client.NewMetadata(copiedMD)\n\t\t}\n\t}\n\treturn client.NewContext(ctx, cl)\n}\n\nfunc authUnaryServerInterceptor(server extensionauth.Server) grpc.UnaryServerInterceptor {\n\treturn func(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) {\n\t\theaders, ok := metadata.FromIncomingContext(ctx)\n\t\tif !ok {\n\t\t\treturn nil, errMetadataNotFound\n\t\t}\n\n\t\tctx, err := server.Authenticate(ctx, headers)\n\t\tif err != nil {\n\t\t\tif s, ok := status.FromError(err); ok {\n\t\t\t\treturn nil, s.Err()\n\t\t\t}\n\n\t\t\treturn nil, status.Error(codes.Unauthenticated, err.Error())\n\t\t}\n\n\t\treturn handler(ctx, req)\n\t}\n}\n\nfunc authStreamServerInterceptor(server extensionauth.Server) grpc.StreamServerInterceptor {\n\treturn func(srv any, stream grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {\n\t\tctx := stream.Context()\n\t\theaders, ok := metadata.FromIncomingContext(ctx)\n\t\tif !ok {\n\t\t\treturn errMetadataNotFound\n\t\t}\n\n\t\tctx, err := server.Authenticate(ctx, headers)\n\t\tif err != nil {\n\t\t\tif s, ok := status.FromError(err); ok {\n\t\t\t\treturn s.Err()\n\t\t\t}\n\n\t\t\treturn status.Error(codes.Unauthenticated, err.Error())\n\t\t}\n\n\t\treturn handler(srv, wrapServerStream(ctx, stream))\n\t}\n}\n"
  },
  {
    "path": "config/configgrpc/configgrpc_benchmark_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// Copyright 2014 gRPC authors.\n// SPDX-License-Identifier: Apache-2.0\n\npackage configgrpc\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/mostynb/go-grpc-compression/nonclobbering/snappy\"\n\t\"github.com/mostynb/go-grpc-compression/nonclobbering/zstd\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/encoding\"\n\t\"google.golang.org/grpc/encoding/gzip\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc BenchmarkCompressors(b *testing.B) {\n\tpayloads := setupTestPayloads()\n\n\tcompressors := make([]encoding.Compressor, 0)\n\tcompressors = append(compressors,\n\t\tencoding.GetCompressor(gzip.Name),\n\t\tencoding.GetCompressor(zstd.Name),\n\t\tencoding.GetCompressor(snappy.Name))\n\n\tfor _, payload := range payloads {\n\t\tfor _, compressor := range compressors {\n\t\t\tfmt.Println(payload.name)\n\t\t\tmessageBytes, err := payload.marshaler.marshal(payload.message)\n\t\t\trequire.NoError(b, err, \"marshal(_) returned an error\")\n\n\t\t\tcompressedBytes, err := compress(compressor, messageBytes)\n\t\t\trequire.NoError(b, err, \"Compressor.Compress(_) returned an error\")\n\n\t\t\tname := fmt.Sprintf(\"%v/raw_bytes_%v/compressed_bytes_%v/compressor_%v\", payload.name, len(messageBytes), len(compressedBytes), compressor.Name())\n\n\t\t\tb.Run(name, func(b *testing.B) {\n\t\t\t\tb.ResetTimer()\n\t\t\t\tfor b.Loop() {\n\t\t\t\t\trequire.NoError(b, err, \"marshal(_) returned an error\")\n\t\t\t\t\t_, err := compress(compressor, messageBytes)\n\t\t\t\t\trequire.NoError(b, err, \"compress(_) returned an error\")\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc compress(compressor encoding.Compressor, in []byte) ([]byte, error) {\n\tif compressor == nil {\n\t\treturn nil, nil\n\t}\n\twrapErr := func(err error) error {\n\t\treturn status.Errorf(codes.Internal, \"error while compressing: %v\", err.Error())\n\t}\n\tcbuf := &bytes.Buffer{}\n\tz, err := compressor.Compress(cbuf)\n\tif err != nil {\n\t\treturn nil, wrapErr(err)\n\t}\n\tif _, err := z.Write(in); err != nil {\n\t\treturn nil, wrapErr(err)\n\t}\n\tif err := z.Close(); err != nil {\n\t\treturn nil, wrapErr(err)\n\t}\n\treturn cbuf.Bytes(), nil\n}\n\ntype testPayload struct {\n\tname      string\n\tmessage   any\n\tmarshaler marshaler\n}\n\ntype marshaler interface {\n\tmarshal(any) ([]byte, error)\n}\n\ntype logMarshaler struct {\n\tplog.Marshaler\n}\n\nfunc (m *logMarshaler) marshal(e any) ([]byte, error) {\n\treturn m.MarshalLogs(e.(plog.Logs))\n}\n\ntype traceMarshaler struct {\n\tptrace.Marshaler\n}\n\nfunc (m *traceMarshaler) marshal(e any) ([]byte, error) {\n\treturn m.MarshalTraces(e.(ptrace.Traces))\n}\n\ntype metricsMarshaler struct {\n\tpmetric.Marshaler\n}\n\nfunc (m *metricsMarshaler) marshal(e any) ([]byte, error) {\n\treturn m.MarshalMetrics(e.(pmetric.Metrics))\n}\n\nfunc setupTestPayloads() []testPayload {\n\tpayloads := make([]testPayload, 0)\n\n\t// log payloads\n\tlogMarshaler := &logMarshaler{Marshaler: &plog.ProtoMarshaler{}}\n\tpayloads = append(payloads,\n\t\ttestPayload{\n\t\t\tname:      \"sm_log_request\",\n\t\t\tmessage:   testdata.GenerateLogs(1),\n\t\t\tmarshaler: logMarshaler,\n\t\t},\n\t\ttestPayload{\n\t\t\tname:      \"md_log_request\",\n\t\t\tmessage:   testdata.GenerateLogs(2),\n\t\t\tmarshaler: logMarshaler,\n\t\t},\n\t\ttestPayload{\n\t\t\tname:      \"lg_log_request\",\n\t\t\tmessage:   testdata.GenerateLogs(50),\n\t\t\tmarshaler: logMarshaler,\n\t\t})\n\n\t// trace payloads\n\ttracesMarshaler := &traceMarshaler{Marshaler: &ptrace.ProtoMarshaler{}}\n\tpayloads = append(payloads,\n\t\ttestPayload{\n\t\t\tname:      \"sm_trace_request\",\n\t\t\tmessage:   testdata.GenerateTraces(1),\n\t\t\tmarshaler: tracesMarshaler,\n\t\t},\n\t\ttestPayload{\n\t\t\tname:      \"md_trace_request\",\n\t\t\tmessage:   testdata.GenerateTraces(2),\n\t\t\tmarshaler: tracesMarshaler,\n\t\t},\n\t\ttestPayload{\n\t\t\tname:      \"lg_trace_request\",\n\t\t\tmessage:   testdata.GenerateTraces(50),\n\t\t\tmarshaler: tracesMarshaler,\n\t\t})\n\n\t// metric payloads\n\tmetricsMarshaler := &metricsMarshaler{Marshaler: &pmetric.ProtoMarshaler{}}\n\tpayloads = append(payloads,\n\t\ttestPayload{\n\t\t\tname:      \"sm_metric_request\",\n\t\t\tmessage:   testdata.GenerateMetrics(1),\n\t\t\tmarshaler: metricsMarshaler,\n\t\t},\n\t\ttestPayload{\n\t\t\tname:      \"md_metric_request\",\n\t\t\tmessage:   testdata.GenerateMetrics(2),\n\t\t\tmarshaler: metricsMarshaler,\n\t\t},\n\t\ttestPayload{\n\t\t\tname:      \"lg_metric_request\",\n\t\t\tmessage:   testdata.GenerateMetrics(50),\n\t\t\tmarshaler: metricsMarshaler,\n\t\t})\n\n\treturn payloads\n}\n"
  },
  {
    "path": "config/configgrpc/configgrpc_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configgrpc\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/metadata\"\n\t\"google.golang.org/grpc/peer\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/client\"\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configauth\"\n\t\"go.opentelemetry.io/collector/config/configcompression\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensionauth\"\n\t\"go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n)\n\nvar (\n\t_ extension.Extension  = (*mockAuthServer)(nil)\n\t_ extensionauth.Server = (*mockAuthServer)(nil)\n)\n\ntype mockAuthServer struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\textensionauth.ServerAuthenticateFunc\n}\n\nfunc newMockAuthServer(auth func(ctx context.Context, sources map[string][]string) (context.Context, error)) extensionauth.Server {\n\treturn &mockAuthServer{ServerAuthenticateFunc: auth}\n}\n\nfunc TestNewDefaultKeepaliveClientConfig(t *testing.T) {\n\texpectedKeepaliveClientConfig := KeepaliveClientConfig{\n\t\tTime:    time.Second * 10,\n\t\tTimeout: time.Second * 10,\n\t}\n\tkeepaliveClientConfig := NewDefaultKeepaliveClientConfig()\n\tassert.Equal(t, expectedKeepaliveClientConfig, keepaliveClientConfig)\n}\n\nfunc TestNewDefaultClientConfig(t *testing.T) {\n\tkeepalive := NewDefaultKeepaliveClientConfig()\n\texpected := ClientConfig{\n\t\tTLS:          configtls.NewDefaultClientConfig(),\n\t\tKeepalive:    configoptional.Some(keepalive),\n\t\tBalancerName: BalancerName(),\n\t}\n\n\tresult := NewDefaultClientConfig()\n\n\tassert.Equal(t, expected, result)\n}\n\nfunc TestNewDefaultKeepaliveServerParameters(t *testing.T) {\n\texpectedParams := KeepaliveServerParameters{}\n\tparams := NewDefaultKeepaliveServerParameters()\n\n\tassert.Equal(t, expectedParams, params)\n}\n\nfunc TestNewDefaultKeepaliveEnforcementPolicy(t *testing.T) {\n\texpectedPolicy := KeepaliveEnforcementPolicy{}\n\n\tpolicy := NewDefaultKeepaliveEnforcementPolicy()\n\n\tassert.Equal(t, expectedPolicy, policy)\n}\n\nfunc TestNewDefaultKeepaliveServerConfig(t *testing.T) {\n\texpected := KeepaliveServerConfig{\n\t\tServerParameters:  configoptional.Some(NewDefaultKeepaliveServerParameters()),\n\t\tEnforcementPolicy: configoptional.Some(NewDefaultKeepaliveEnforcementPolicy()),\n\t}\n\tresult := NewDefaultKeepaliveServerConfig()\n\tassert.Equal(t, expected, result)\n}\n\nfunc TestNewDefaultServerConfig(t *testing.T) {\n\texpected := ServerConfig{\n\t\tKeepalive: configoptional.Some(NewDefaultKeepaliveServerConfig()),\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t}\n\n\tresult := NewDefaultServerConfig()\n\n\tassert.Equal(t, expected, result)\n}\n\nvar (\n\ttestAuthID    = component.MustNewID(\"testauth\")\n\tmockID        = component.MustNewID(\"mock\")\n\tdoesntExistID = component.MustNewID(\"doesntexist\")\n)\n\nfunc TestDefaultGrpcClientSettings(t *testing.T) {\n\tcc := &ClientConfig{\n\t\tTLS: configtls.ClientConfig{\n\t\t\tInsecure: true,\n\t\t},\n\t}\n\topts, err := cc.getGrpcDialOptions(context.Background(), nil, componenttest.NewNopTelemetrySettings(), []ToClientConnOption{})\n\trequire.NoError(t, err)\n\t/* Expecting 2 DialOptions:\n\t * - WithTransportCredentials (TLS)\n\t * - WithStatsHandler (always, for self-telemetry)\n\t */\n\tassert.Len(t, opts, 2)\n}\n\nfunc TestGrpcClientExtraOption(t *testing.T) {\n\tcc := &ClientConfig{\n\t\tTLS: configtls.ClientConfig{\n\t\t\tInsecure: true,\n\t\t},\n\t}\n\textraOpt := grpc.WithUserAgent(\"test-agent\")\n\topts, err := cc.getGrpcDialOptions(\n\t\tcontext.Background(),\n\t\tnil,\n\t\tcomponenttest.NewNopTelemetrySettings(),\n\t\t[]ToClientConnOption{WithGrpcDialOption(extraOpt)},\n\t)\n\trequire.NoError(t, err)\n\t/* Expecting 3 DialOptions:\n\t * - WithTransportCredentials (TLS)\n\t * - WithStatsHandler (always, for self-telemetry)\n\t * - extraOpt\n\t */\n\tassert.Len(t, opts, 3)\n\tassert.Equal(t, opts[2], extraOpt)\n}\n\nfunc TestAllGrpcClientSettings(t *testing.T) {\n\ttests := []struct {\n\t\tsettings   ClientConfig\n\t\tname       string\n\t\textensions map[component.ID]component.Component\n\t}{\n\t\t{\n\t\t\tname: \"test all with gzip compression\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tHeaders: configopaque.MapList{\n\t\t\t\t\t{Name: \"test\", Value: \"test\"},\n\t\t\t\t},\n\t\t\t\tEndpoint:    \"localhost:1234\",\n\t\t\t\tCompression: configcompression.TypeGzip,\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tInsecure: false,\n\t\t\t\t},\n\t\t\t\tKeepalive: configoptional.Some(KeepaliveClientConfig{\n\t\t\t\t\tTime:                time.Second,\n\t\t\t\t\tTimeout:             time.Second,\n\t\t\t\t\tPermitWithoutStream: true,\n\t\t\t\t}),\n\t\t\t\tReadBufferSize:  1024,\n\t\t\t\tWriteBufferSize: 1024,\n\t\t\t\tWaitForReady:    true,\n\t\t\t\tBalancerName:    \"round_robin\",\n\t\t\t\tAuthority:       \"pseudo-authority\",\n\t\t\t\tAuth:            configoptional.Some(configauth.Config{AuthenticatorID: testAuthID}),\n\t\t\t},\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\ttestAuthID: extensionauthtest.NewNopClient(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"test all with snappy compression\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tHeaders: configopaque.MapList{\n\t\t\t\t\t{Name: \"test\", Value: \"test\"},\n\t\t\t\t},\n\t\t\t\tEndpoint:    \"localhost:1234\",\n\t\t\t\tCompression: configcompression.TypeSnappy,\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tInsecure: false,\n\t\t\t\t},\n\t\t\t\tKeepalive: configoptional.Some(KeepaliveClientConfig{\n\t\t\t\t\tTime:                time.Second,\n\t\t\t\t\tTimeout:             time.Second,\n\t\t\t\t\tPermitWithoutStream: true,\n\t\t\t\t}),\n\t\t\t\tReadBufferSize:  1024,\n\t\t\t\tWriteBufferSize: 1024,\n\t\t\t\tWaitForReady:    true,\n\t\t\t\tBalancerName:    \"round_robin\",\n\t\t\t\tAuthority:       \"pseudo-authority\",\n\t\t\t\tAuth:            configoptional.Some(configauth.Config{AuthenticatorID: testAuthID}),\n\t\t\t},\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\ttestAuthID: extensionauthtest.NewNopClient(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"test all with zstd compression\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tHeaders: configopaque.MapList{\n\t\t\t\t\t{Name: \"test\", Value: \"test\"},\n\t\t\t\t},\n\t\t\t\tEndpoint:    \"localhost:1234\",\n\t\t\t\tCompression: configcompression.TypeZstd,\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tInsecure: false,\n\t\t\t\t},\n\t\t\t\tKeepalive: configoptional.Some(KeepaliveClientConfig{\n\t\t\t\t\tTime:                time.Second,\n\t\t\t\t\tTimeout:             time.Second,\n\t\t\t\t\tPermitWithoutStream: true,\n\t\t\t\t}),\n\t\t\t\tReadBufferSize:  1024,\n\t\t\t\tWriteBufferSize: 1024,\n\t\t\t\tWaitForReady:    true,\n\t\t\t\tBalancerName:    \"round_robin\",\n\t\t\t\tAuthority:       \"pseudo-authority\",\n\t\t\t\tAuth:            configoptional.Some(configauth.Config{AuthenticatorID: testAuthID}),\n\t\t\t},\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\ttestAuthID: extensionauthtest.NewNopClient(),\n\t\t\t},\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\topts, err := test.settings.getGrpcDialOptions(context.Background(), test.extensions, componenttest.NewNopTelemetrySettings(), []ToClientConnOption{})\n\t\t\trequire.NoError(t, err)\n\t\t\t/* Expecting 11 DialOptions:\n\t\t\t * - WithDefaultCallOptions (Compression)\n\t\t\t * - WithTransportCredentials (TLS)\n\t\t\t * - WithDefaultServiceConfig (BalancerName)\n\t\t\t * - WithAuthority (Authority)\n\t\t\t * - WithStatsHandler (always, for self-telemetry)\n\t\t\t * - WithReadBufferSize (ReadBufferSize)\n\t\t\t * - WithWriteBufferSize (WriteBufferSize)\n\t\t\t * - WithKeepaliveParams (Keepalive)\n\t\t\t * - WithPerRPCCredentials (Auth)\n\t\t\t * - WithUnaryInterceptor/WithStreamInterceptor (Headers)\n\t\t\t */\n\t\t\tassert.Len(t, opts, 11)\n\t\t})\n\t}\n}\n\nfunc TestSanitizeEndpoint(t *testing.T) {\n\tcfg := NewDefaultClientConfig()\n\tcfg.Endpoint = \"dns://authority/backend.example.com:4317\"\n\tassert.Equal(t, \"authority/backend.example.com:4317\", cfg.sanitizedEndpoint())\n\tcfg.Endpoint = \"dns:///backend.example.com:4317\"\n\tassert.Equal(t, \"backend.example.com:4317\", cfg.sanitizedEndpoint())\n\tcfg.Endpoint = \"dns:////backend.example.com:4317\"\n\tassert.Equal(t, \"/backend.example.com:4317\", cfg.sanitizedEndpoint())\n}\n\nfunc TestValidateEndpoint(t *testing.T) {\n\tcfg := NewDefaultClientConfig()\n\tcfg.Endpoint = \"dns://authority/backend.example.com:4317\"\n\tassert.NoError(t, cfg.Validate())\n\tcfg.Endpoint = \"unix:///my/unix/socket.sock\"\n\tassert.NoError(t, cfg.Validate())\n}\n\nfunc TestHeaders(t *testing.T) {\n\ttraceServer := &grpcTraceServer{}\n\tserver, addr := traceServer.startTestServer(t, configoptional.Some(ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  \"localhost:0\",\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t}))\n\tdefer server.Stop()\n\n\t// Create client and send request to server with headers\n\tresp, errResp := sendTestRequest(t, ClientConfig{\n\t\tEndpoint: addr,\n\t\tTLS: configtls.ClientConfig{\n\t\t\tInsecure: true,\n\t\t},\n\t\tHeaders: configopaque.MapList{\n\t\t\t{Name: \"testheader\", Value: \"testvalue\"},\n\t\t},\n\t})\n\trequire.NoError(t, errResp)\n\tassert.NotNil(t, resp)\n\n\t// Check received headers\n\tmd, ok := metadata.FromIncomingContext(traceServer.recordedContext)\n\trequire.True(t, ok)\n\tassert.Equal(t, []string{\"testvalue\"}, md.Get(\"testheader\"))\n}\n\nfunc TestDefaultGrpcServerSettings(t *testing.T) {\n\tgss := &ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint: \"0.0.0.0:1234\",\n\t\t},\n\t}\n\topts, err := gss.getGrpcServerOptions(context.Background(), nil, componenttest.NewNopTelemetrySettings(), []ToServerOption{})\n\trequire.NoError(t, err)\n\tassert.Len(t, opts, 3)\n}\n\nfunc TestGrpcServerExtraOption(t *testing.T) {\n\tgss := &ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint: \"0.0.0.0:1234\",\n\t\t},\n\t}\n\textraOpt := grpc.ConnectionTimeout(1_000_000_000)\n\topts, err := gss.getGrpcServerOptions(\n\t\tcontext.Background(),\n\t\tnil,\n\t\tcomponenttest.NewNopTelemetrySettings(),\n\t\t[]ToServerOption{WithGrpcServerOption(extraOpt)},\n\t)\n\trequire.NoError(t, err)\n\tassert.Len(t, opts, 4)\n\tassert.Equal(t, opts[3], extraOpt)\n}\n\nfunc TestGrpcServerValidate(t *testing.T) {\n\ttests := []struct {\n\t\tgss *ServerConfig\n\t\terr string\n\t}{\n\t\t{\n\t\t\tgss: &ServerConfig{\n\t\t\t\tMaxRecvMsgSizeMiB: -1,\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint: \"0.0.0.0:1234\",\n\t\t\t\t},\n\t\t\t},\n\t\t\terr: \"invalid max_recv_msg_size_mib value\",\n\t\t},\n\t\t{\n\t\t\tgss: &ServerConfig{\n\t\t\t\tMaxRecvMsgSizeMiB: 9223372036854775807,\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint: \"0.0.0.0:1234\",\n\t\t\t\t},\n\t\t\t},\n\t\t\terr: \"invalid max_recv_msg_size_mib value\",\n\t\t},\n\t\t{\n\t\t\tgss: &ServerConfig{\n\t\t\t\tReadBufferSize: -1,\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint: \"0.0.0.0:1234\",\n\t\t\t\t},\n\t\t\t},\n\t\t\terr: \"invalid read_buffer_size value\",\n\t\t},\n\t\t{\n\t\t\tgss: &ServerConfig{\n\t\t\t\tWriteBufferSize: -1,\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint: \"0.0.0.0:1234\",\n\t\t\t\t},\n\t\t\t},\n\t\t\terr: \"invalid write_buffer_size value\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.err, func(t *testing.T) {\n\t\t\terr := tt.gss.Validate()\n\t\t\trequire.Error(t, err)\n\t\t\tassert.ErrorContains(t, err, tt.err)\n\t\t})\n\t}\n}\n\nfunc TestAllGrpcServerSettingsExceptAuth(t *testing.T) {\n\tgss := &ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  \"localhost:1234\",\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t\tTLS: configoptional.Some(configtls.ServerConfig{\n\t\t\tConfig:       configtls.Config{},\n\t\t\tClientCAFile: \"\",\n\t\t}),\n\t\tMaxRecvMsgSizeMiB:    1,\n\t\tMaxConcurrentStreams: 1024,\n\t\tReadBufferSize:       1024,\n\t\tWriteBufferSize:      1024,\n\t\tKeepalive: configoptional.Some(KeepaliveServerConfig{\n\t\t\tServerParameters: configoptional.Some(KeepaliveServerParameters{\n\t\t\t\tMaxConnectionIdle:     time.Second,\n\t\t\t\tMaxConnectionAge:      time.Second,\n\t\t\t\tMaxConnectionAgeGrace: time.Second,\n\t\t\t\tTime:                  time.Second,\n\t\t\t\tTimeout:               time.Second,\n\t\t\t}),\n\t\t\tEnforcementPolicy: configoptional.Some(KeepaliveEnforcementPolicy{\n\t\t\t\tMinTime:             time.Second,\n\t\t\t\tPermitWithoutStream: true,\n\t\t\t}),\n\t\t}),\n\t}\n\topts, err := gss.getGrpcServerOptions(context.Background(), nil, componenttest.NewNopTelemetrySettings(), []ToServerOption{})\n\trequire.NoError(t, err)\n\tassert.Len(t, opts, 10)\n}\n\nfunc TestGrpcServerAuthSettings(t *testing.T) {\n\tgss := &ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint: \"0.0.0.0:1234\",\n\t\t},\n\t}\n\tgss.Auth = configoptional.Some(configauth.Config{\n\t\tAuthenticatorID: mockID,\n\t})\n\n\textensions := map[component.ID]component.Component{\n\t\tmockID: extensionauthtest.NewNopServer(),\n\t}\n\tsrv, err := gss.ToServer(context.Background(), extensions, componenttest.NewNopTelemetrySettings())\n\trequire.NoError(t, err)\n\tassert.NotNil(t, srv)\n}\n\nfunc TestGrpcClientConfigInvalidBalancer(t *testing.T) {\n\tsettings := ClientConfig{\n\t\tHeaders: configopaque.MapList{\n\t\t\t{Name: \"test\", Value: \"test\"},\n\t\t},\n\t\tEndpoint:    \"localhost:1234\",\n\t\tCompression: \"gzip\",\n\t\tTLS: configtls.ClientConfig{\n\t\t\tInsecure: false,\n\t\t},\n\t\tKeepalive: configoptional.Some(KeepaliveClientConfig{\n\t\t\tTime:                time.Second,\n\t\t\tTimeout:             time.Second,\n\t\t\tPermitWithoutStream: true,\n\t\t}),\n\t\tReadBufferSize:  1024,\n\t\tWriteBufferSize: 1024,\n\t\tWaitForReady:    true,\n\t\tBalancerName:    \"test\",\n\t}\n\tassert.ErrorContains(t, settings.Validate(), \"invalid balancer_name: test\")\n}\n\nfunc TestGRPCClientSettingsError(t *testing.T) {\n\ttests := []struct {\n\t\tsettings   ClientConfig\n\t\terr        string\n\t\textensions map[component.ID]component.Component\n\t}{\n\t\t{\n\t\t\terr: \"failed to load TLS config: failed to load CA CertPool File: failed to load cert /doesnt/exist:\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tHeaders:     nil,\n\t\t\t\tEndpoint:    \"localhost:1234\",\n\t\t\t\tCompression: \"\",\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\tCAFile: \"/doesnt/exist\",\n\t\t\t\t\t},\n\t\t\t\t\tInsecure:   false,\n\t\t\t\t\tServerName: \"\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\terr: \"failed to load TLS config: failed to load TLS cert and key: for auth via TLS, provide both certificate and key, or neither\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tHeaders:     nil,\n\t\t\t\tEndpoint:    \"localhost:1234\",\n\t\t\t\tCompression: \"\",\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\tCertFile: \"/doesnt/exist\",\n\t\t\t\t\t},\n\t\t\t\t\tInsecure:   false,\n\t\t\t\t\tServerName: \"\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\terr: \"failed to resolve authenticator \\\"doesntexist\\\": authenticator not found\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tAuth:     configoptional.Some(configauth.Config{AuthenticatorID: doesntExistID}),\n\t\t\t},\n\t\t\textensions: map[component.ID]component.Component{},\n\t\t},\n\t\t{\n\t\t\terr: \"authentication was configured but this component or its host does not support extensions\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tAuth:     configoptional.Some(configauth.Config{AuthenticatorID: doesntExistID}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\terr: \"unsupported compression type \\\"zlib\\\"\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tInsecure: true,\n\t\t\t\t},\n\t\t\t\tCompression: \"zlib\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\terr: \"unsupported compression type \\\"deflate\\\"\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tInsecure: true,\n\t\t\t\t},\n\t\t\t\tCompression: \"deflate\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\terr: \"unsupported compression type \\\"bad\\\"\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tInsecure: true,\n\t\t\t\t},\n\t\t\t\tCompression: \"bad\",\n\t\t\t},\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.err, func(t *testing.T) {\n\t\t\trequire.NoError(t, test.settings.Validate())\n\t\t\t_, err := test.settings.ToClientConn(context.Background(), test.extensions, componenttest.NewNopTelemetrySettings())\n\t\t\trequire.Error(t, err)\n\t\t\tassert.ErrorContains(t, err, test.err)\n\t\t})\n\t}\n}\n\nfunc TestUseSecure(t *testing.T) {\n\tcc := &ClientConfig{\n\t\tHeaders:     nil,\n\t\tEndpoint:    \"\",\n\t\tCompression: \"\",\n\t\tTLS:         configtls.ClientConfig{},\n\t}\n\tdialOpts, err := cc.getGrpcDialOptions(context.Background(), nil, componenttest.NewNopTelemetrySettings(), []ToClientConnOption{})\n\trequire.NoError(t, err)\n\tassert.Len(t, dialOpts, 2)\n}\n\nfunc TestGRPCServerSettingsError(t *testing.T) {\n\ttests := []struct {\n\t\tsettings ServerConfig\n\t\terr      string\n\t}{\n\t\t{\n\t\t\terr: \"failed to load TLS config: failed to load CA CertPool File: failed to load cert /doesnt/exist:\",\n\t\t\tsettings: ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"127.0.0.1:1234\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tTLS: configoptional.Some(configtls.ServerConfig{\n\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\tCAFile: \"/doesnt/exist\",\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\terr: \"failed to load TLS config: failed to load TLS cert and key: for auth via TLS, provide both certificate and key, or neither\",\n\t\t\tsettings: ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"127.0.0.1:1234\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tTLS: configoptional.Some(configtls.ServerConfig{\n\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\tCertFile: \"/doesnt/exist\",\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\terr: \"failed to load client CA CertPool: failed to load CA /doesnt/exist:\",\n\t\t\tsettings: ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"127.0.0.1:1234\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tTLS: configoptional.Some(configtls.ServerConfig{\n\t\t\t\t\tClientCAFile: \"/doesnt/exist\",\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.err, func(t *testing.T) {\n\t\t\t_, err := test.settings.ToServer(context.Background(), nil, componenttest.NewNopTelemetrySettings())\n\t\t\tassert.ErrorContains(t, err, test.err)\n\t\t})\n\t}\n}\n\nfunc TestGRPCServerSettings_ToListener_Error(t *testing.T) {\n\tsettings := ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  \"127.0.0.1:1234567\",\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t}\n\t_, err := settings.NetAddr.Listen(context.Background())\n\tassert.Error(t, err)\n}\n\nfunc TestHTTPReception(t *testing.T) {\n\ttests := []struct {\n\t\tname           string\n\t\ttlsServerCreds configoptional.Optional[configtls.ServerConfig]\n\t\ttlsClientCreds configoptional.Optional[configtls.ClientConfig]\n\t\thasError       bool\n\t}{\n\t\t{\n\t\t\tname:           \"noTLS\",\n\t\t\ttlsServerCreds: configoptional.None[configtls.ServerConfig](),\n\t\t\ttlsClientCreds: configoptional.Some(configtls.ClientConfig{\n\t\t\t\tInsecure: true,\n\t\t\t}),\n\t\t},\n\t\t{\n\t\t\tname: \"TLS\",\n\t\t\ttlsServerCreds: configoptional.Some(configtls.ServerConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t\tCertFile: filepath.Join(\"testdata\", \"server.crt\"),\n\t\t\t\t\tKeyFile:  filepath.Join(\"testdata\", \"server.key\"),\n\t\t\t\t},\n\t\t\t}),\n\t\t\ttlsClientCreds: configoptional.Some(configtls.ClientConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile: filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t},\n\t\t\t\tServerName: \"localhost\",\n\t\t\t}),\n\t\t},\n\t\t{\n\t\t\tname: \"NoServerCertificates\",\n\t\t\ttlsServerCreds: configoptional.Some(configtls.ServerConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile: filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t},\n\t\t\t}),\n\t\t\ttlsClientCreds: configoptional.Some(configtls.ClientConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile: filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t},\n\t\t\t\tServerName: \"localhost\",\n\t\t\t}),\n\t\t\thasError: true,\n\t\t},\n\t\t{\n\t\t\tname: \"mTLS\",\n\t\t\ttlsServerCreds: configoptional.Some(configtls.ServerConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t\tCertFile: filepath.Join(\"testdata\", \"server.crt\"),\n\t\t\t\t\tKeyFile:  filepath.Join(\"testdata\", \"server.key\"),\n\t\t\t\t},\n\t\t\t\tClientCAFile: filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t}),\n\t\t\ttlsClientCreds: configoptional.Some(configtls.ClientConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t\tCertFile: filepath.Join(\"testdata\", \"client.crt\"),\n\t\t\t\t\tKeyFile:  filepath.Join(\"testdata\", \"client.key\"),\n\t\t\t\t},\n\t\t\t\tServerName: \"localhost\",\n\t\t\t}),\n\t\t},\n\t\t{\n\t\t\tname: \"NoClientCertificate\",\n\t\t\ttlsServerCreds: configoptional.Some(configtls.ServerConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t\tCertFile: filepath.Join(\"testdata\", \"server.crt\"),\n\t\t\t\t\tKeyFile:  filepath.Join(\"testdata\", \"server.key\"),\n\t\t\t\t},\n\t\t\t\tClientCAFile: filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t}),\n\t\t\ttlsClientCreds: configoptional.Some(configtls.ClientConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile: filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t},\n\t\t\t\tServerName: \"localhost\",\n\t\t\t}),\n\t\t\thasError: true,\n\t\t},\n\t\t{\n\t\t\tname: \"WrongClientCA\",\n\t\t\ttlsServerCreds: configoptional.Some(configtls.ServerConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t\tCertFile: filepath.Join(\"testdata\", \"server.crt\"),\n\t\t\t\t\tKeyFile:  filepath.Join(\"testdata\", \"server.key\"),\n\t\t\t\t},\n\t\t\t\tClientCAFile: filepath.Join(\"testdata\", \"server.crt\"),\n\t\t\t}),\n\t\t\ttlsClientCreds: configoptional.Some(configtls.ClientConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t\tCertFile: filepath.Join(\"testdata\", \"client.crt\"),\n\t\t\t\t\tKeyFile:  filepath.Join(\"testdata\", \"client.key\"),\n\t\t\t\t},\n\t\t\t\tServerName: \"localhost\",\n\t\t\t}),\n\t\t\thasError: true,\n\t\t},\n\t}\n\t// prepare\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\ts, addr := (&grpcTraceServer{}).startTestServer(t, configoptional.Some(ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tTLS: test.tlsServerCreds,\n\t\t\t}))\n\t\t\tdefer s.Stop()\n\n\t\t\tresp, errResp := sendTestRequest(t, ClientConfig{\n\t\t\t\tEndpoint: addr,\n\t\t\t\tTLS:      *test.tlsClientCreds.Get(),\n\t\t\t})\n\t\t\tif test.hasError {\n\t\t\t\trequire.Error(t, errResp)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, errResp)\n\t\t\t\tassert.NotNil(t, resp)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestReceiveOnUnixDomainSocket(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"skipping test on windows\")\n\t}\n\n\tsocketName := tempSocketName(t)\n\tsrv, addr := (&grpcTraceServer{}).startTestServer(t, configoptional.Some(ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  socketName,\n\t\t\tTransport: confignet.TransportTypeUnix,\n\t\t},\n\t}))\n\tdefer srv.Stop()\n\n\tresp, errResp := sendTestRequest(t, ClientConfig{\n\t\tEndpoint: \"unix://\" + addr,\n\t\tTLS: configtls.ClientConfig{\n\t\t\tInsecure: true,\n\t\t},\n\t})\n\trequire.NoError(t, errResp)\n\tassert.NotNil(t, resp)\n}\n\nfunc TestContextWithClient(t *testing.T) {\n\ttestCases := []struct {\n\t\tdesc       string\n\t\tinput      context.Context\n\t\tdoMetadata bool\n\t\texpected   client.Info\n\t}{\n\t\t{\n\t\t\tdesc:     \"no peer information, empty client\",\n\t\t\tinput:    context.Background(),\n\t\t\texpected: client.Info{},\n\t\t},\n\t\t{\n\t\t\tdesc: \"existing client with IP, no peer information\",\n\t\t\tinput: client.NewContext(context.Background(), client.Info{\n\t\t\t\tAddr: &net.IPAddr{\n\t\t\t\t\tIP: net.IPv4(1, 2, 3, 4),\n\t\t\t\t},\n\t\t\t}),\n\t\t\texpected: client.Info{\n\t\t\t\tAddr: &net.IPAddr{\n\t\t\t\t\tIP: net.IPv4(1, 2, 3, 4),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdesc: \"empty client, with peer information\",\n\t\t\tinput: peer.NewContext(context.Background(), &peer.Peer{\n\t\t\t\tAddr: &net.IPAddr{\n\t\t\t\t\tIP: net.IPv4(1, 2, 3, 4),\n\t\t\t\t},\n\t\t\t}),\n\t\t\texpected: client.Info{\n\t\t\t\tAddr: &net.IPAddr{\n\t\t\t\t\tIP: net.IPv4(1, 2, 3, 4),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdesc: \"existing client, existing IP gets overridden with peer information\",\n\t\t\tinput: peer.NewContext(client.NewContext(context.Background(), client.Info{\n\t\t\t\tAddr: &net.IPAddr{\n\t\t\t\t\tIP: net.IPv4(1, 2, 3, 4),\n\t\t\t\t},\n\t\t\t}), &peer.Peer{\n\t\t\t\tAddr: &net.IPAddr{\n\t\t\t\t\tIP: net.IPv4(1, 2, 3, 5),\n\t\t\t\t},\n\t\t\t}),\n\t\t\texpected: client.Info{\n\t\t\t\tAddr: &net.IPAddr{\n\t\t\t\t\tIP: net.IPv4(1, 2, 3, 5),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdesc: \"existing client with metadata\",\n\t\t\tinput: client.NewContext(context.Background(), client.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\"test-metadata-key\": {\"test-value\"}}),\n\t\t\t}),\n\t\t\tdoMetadata: true,\n\t\t\texpected: client.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\"test-metadata-key\": {\"test-value\"}}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdesc: \"existing client with metadata in context\",\n\t\t\tinput: metadata.NewIncomingContext(\n\t\t\t\tclient.NewContext(context.Background(), client.Info{}),\n\t\t\t\tmetadata.Pairs(\"test-metadata-key\", \"test-value\"),\n\t\t\t),\n\t\t\tdoMetadata: true,\n\t\t\texpected: client.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\"test-metadata-key\": {\"test-value\"}}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tdesc: \"existing client with metadata in context, no metadata processing\",\n\t\t\tinput: metadata.NewIncomingContext(\n\t\t\t\tclient.NewContext(context.Background(), client.Info{}),\n\t\t\t\tmetadata.Pairs(\"test-metadata-key\", \"test-value\"),\n\t\t\t),\n\t\t\texpected: client.Info{},\n\t\t},\n\t\t{\n\t\t\tdesc: \"existing client with Host and metadata\",\n\t\t\tinput: metadata.NewIncomingContext(\n\t\t\t\tclient.NewContext(context.Background(), client.Info{}),\n\t\t\t\tmetadata.Pairs(\"test-metadata-key\", \"test-value\", \":authority\", \"localhost:55443\"),\n\t\t\t),\n\t\t\tdoMetadata: true,\n\t\t\texpected: client.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\"test-metadata-key\": {\"test-value\"}, \":authority\": {\"localhost:55443\"}, \"Host\": {\"localhost:55443\"}}),\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.desc, func(t *testing.T) {\n\t\t\tcl := client.FromContext(contextWithClient(tt.input, tt.doMetadata))\n\t\t\tassert.Equal(t, tt.expected, cl)\n\t\t})\n\t}\n}\n\nfunc TestStreamInterceptorEnhancesClient(t *testing.T) {\n\t// prepare\n\tinCtx := peer.NewContext(context.Background(), &peer.Peer{\n\t\tAddr: &net.IPAddr{IP: net.IPv4(1, 1, 1, 1)},\n\t})\n\n\tstream := &mockedStream{\n\t\tctx: inCtx,\n\t}\n\n\tvar handlerCalled bool\n\thandler := func(_ any, stream grpc.ServerStream) error {\n\t\thandlerCalled = true\n\t\tcl := client.FromContext(stream.Context())\n\t\tassert.Equal(t, \"1.1.1.1\", cl.Addr.String())\n\t\treturn nil\n\t}\n\n\t// test\n\terr := enhanceStreamWithClientInformation(false)(nil, stream, nil, handler)\n\n\t// verify\n\trequire.NoError(t, err)\n\tassert.True(t, handlerCalled, \"the handler should have been called\")\n}\n\ntype mockedStream struct {\n\tctx context.Context\n\tgrpc.ServerStream\n}\n\nfunc (ms *mockedStream) Context() context.Context {\n\treturn ms.ctx\n}\n\nfunc TestClientInfoInterceptors(t *testing.T) {\n\ttestCases := []struct {\n\t\tname   string\n\t\ttester func(ptraceotlp.ExportResponse, error)\n\t}{\n\t\t{\n\t\t\t// we only have unary services, we don't have any clients we could use\n\t\t\t// to test with streaming services\n\t\t\tname: \"unary\",\n\t\t\ttester: func(resp ptraceotlp.ExportResponse, errResp error) {\n\t\t\t\trequire.NoError(t, errResp)\n\t\t\t\trequire.NotNil(t, resp)\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tmock := &grpcTraceServer{}\n\t\t\tvar addr string\n\n\t\t\t// prepare the server\n\t\t\t{\n\t\t\t\tvar srv *grpc.Server\n\t\t\t\tsrv, addr = mock.startTestServer(t, configoptional.Some(ServerConfig{\n\t\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t\t},\n\t\t\t\t}))\n\t\t\t\tdefer srv.Stop()\n\t\t\t}\n\n\t\t\t// prepare the client and execute a RPC\n\t\t\t{\n\t\t\t\tresp, errResp := sendTestRequest(t, ClientConfig{\n\t\t\t\t\tEndpoint: addr,\n\t\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\t\tInsecure: true,\n\t\t\t\t\t},\n\t\t\t\t})\n\n\t\t\t\t// test\n\t\t\t\ttt.tester(resp, errResp)\n\t\t\t}\n\n\t\t\t// verify\n\t\t\tcl := client.FromContext(mock.recordedContext)\n\n\t\t\t// the client address is something like 127.0.0.1:41086\n\t\t\tassert.Contains(t, cl.Addr.String(), \"127.0.0.1\")\n\t\t})\n\t}\n}\n\nfunc TestClientInfoInterceptorBeforeAuth(t *testing.T) {\n\tmock := &grpcTraceServer{}\n\tvar addr string\n\tvar authCalled bool\n\n\ttype serverAuthExtension struct {\n\t\tcomponent.StartFunc\n\t\tcomponent.ShutdownFunc\n\t\textensionauth.Server\n\t}\n\n\t// prepare the server\n\t{\n\t\tvar srv *grpc.Server\n\t\tsrv, addr = mock.startTestServerWithExtensions(t, configoptional.Some(ServerConfig{\n\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t},\n\t\t\tAuth: configoptional.Some(configauth.Config{\n\t\t\t\tAuthenticatorID: mockID,\n\t\t\t}),\n\t\t}), map[component.ID]component.Component{\n\t\t\tmockID: serverAuthExtension{\n\t\t\t\tServer: newMockAuthServer(\n\t\t\t\t\tfunc(ctx context.Context, _ map[string][]string) (context.Context, error) {\n\t\t\t\t\t\t// verify that client info is populated before auth\n\t\t\t\t\t\tauthCalled = true\n\t\t\t\t\t\tcl := client.FromContext(ctx)\n\t\t\t\t\t\tassert.NotNil(t, cl.Addr)\n\t\t\t\t\t\treturn ctx, nil\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t},\n\t\t})\n\t\tdefer srv.Stop()\n\t}\n\n\t// prepare the client and execute a RPC\n\t{\n\t\t_, errResp := sendTestRequest(t, ClientConfig{\n\t\t\tEndpoint: addr,\n\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\tInsecure: true,\n\t\t\t},\n\t\t})\n\t\trequire.NoError(t, errResp)\n\t}\n\n\tassert.True(t, authCalled)\n}\n\nfunc TestDefaultUnaryInterceptorAuthSucceeded(t *testing.T) {\n\t// prepare\n\thandlerCalled := false\n\tauthCalled := false\n\texpectedAuthData := new(struct{ client.AuthData })\n\tauthFunc := func(ctx context.Context, _ map[string][]string) (context.Context, error) {\n\t\tauthCalled = true\n\t\tcl := client.FromContext(ctx)\n\t\tcl.Auth = expectedAuthData\n\t\tctx = client.NewContext(ctx, cl)\n\t\treturn ctx, nil\n\t}\n\thandler := func(ctx context.Context, _ any) (any, error) {\n\t\thandlerCalled = true\n\t\tcl := client.FromContext(ctx)\n\t\tassert.Equal(t, expectedAuthData, cl.Auth)\n\t\treturn nil, nil\n\t}\n\tctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs(\"authorization\", \"some-auth-data\"))\n\tinterceptor := authUnaryServerInterceptor(newMockAuthServer(authFunc))\n\n\t// test\n\tres, err := interceptor(ctx, nil, &grpc.UnaryServerInfo{}, handler)\n\n\t// verify\n\tassert.Nil(t, res)\n\trequire.NoError(t, err)\n\tassert.True(t, authCalled)\n\tassert.True(t, handlerCalled)\n}\n\nfunc TestDefaultUnaryInterceptorAuthFailure(t *testing.T) {\n\t// prepare\n\tauthCalled := false\n\texpectedErr := errors.New(\"not authenticated\")\n\tauthFunc := func(context.Context, map[string][]string) (context.Context, error) {\n\t\tauthCalled = true\n\t\treturn context.Background(), expectedErr\n\t}\n\thandler := func(context.Context, any) (any, error) {\n\t\tassert.FailNow(t, \"the handler should not have been called on auth failure!\")\n\t\treturn nil, nil\n\t}\n\tctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs(\"authorization\", \"some-auth-data\"))\n\tinterceptor := authUnaryServerInterceptor(newMockAuthServer(authFunc))\n\n\t// test\n\tres, err := interceptor(ctx, nil, &grpc.UnaryServerInfo{}, handler)\n\n\t// verify\n\tassert.Nil(t, res)\n\trequire.ErrorContains(t, err, expectedErr.Error())\n\tassert.Equal(t, codes.Unauthenticated, status.Code(err))\n\tassert.True(t, authCalled)\n}\n\nfunc TestDefaultUnaryInterceptorAuthFailureWithStatusErr(t *testing.T) {\n\t// prepare\n\tauthCalled := false\n\texpectedStatusErr := status.New(codes.Unavailable, \"unavailable\")\n\tauthFunc := func(context.Context, map[string][]string) (context.Context, error) {\n\t\tauthCalled = true\n\t\treturn context.Background(), expectedStatusErr.Err()\n\t}\n\thandler := func(context.Context, any) (any, error) {\n\t\tassert.FailNow(t, \"the handler should not have been called on auth failure!\")\n\t\treturn nil, nil\n\t}\n\tctx := metadata.NewIncomingContext(context.Background(), metadata.Pairs(\"authorization\", \"some-auth-data\"))\n\tinterceptor := authUnaryServerInterceptor(newMockAuthServer(authFunc))\n\n\t// test\n\tres, err := interceptor(ctx, nil, &grpc.UnaryServerInfo{}, handler)\n\n\t// verify\n\tassert.Nil(t, res)\n\trequire.ErrorContains(t, err, expectedStatusErr.Err().Error())\n\tassert.Equal(t, codes.Unavailable, status.Code(err))\n\tassert.True(t, authCalled)\n}\n\nfunc TestDefaultUnaryInterceptorMissingMetadata(t *testing.T) {\n\t// prepare\n\tauthFunc := func(context.Context, map[string][]string) (context.Context, error) {\n\t\tassert.FailNow(t, \"the auth func should not have been called!\")\n\t\treturn context.Background(), nil\n\t}\n\thandler := func(context.Context, any) (any, error) {\n\t\tassert.FailNow(t, \"the handler should not have been called!\")\n\t\treturn nil, nil\n\t}\n\tinterceptor := authUnaryServerInterceptor(newMockAuthServer(authFunc))\n\n\t// test\n\tres, err := interceptor(context.Background(), nil, &grpc.UnaryServerInfo{}, handler)\n\n\t// verify\n\tassert.Nil(t, res)\n\tassert.Equal(t, errMetadataNotFound, err)\n}\n\nfunc TestDefaultStreamInterceptorAuthSucceeded(t *testing.T) {\n\t// prepare\n\thandlerCalled := false\n\tauthCalled := false\n\texpectedAuthData := new(struct{ client.AuthData })\n\tauthFunc := func(ctx context.Context, _ map[string][]string) (context.Context, error) {\n\t\tauthCalled = true\n\t\tcl := client.FromContext(ctx)\n\t\tcl.Auth = expectedAuthData\n\t\tctx = client.NewContext(ctx, cl)\n\t\treturn ctx, nil\n\t}\n\thandler := func(_ any, stream grpc.ServerStream) error {\n\t\t// ensure that the client information is propagated down to the underlying stream\n\t\tcl := client.FromContext(stream.Context())\n\t\tassert.Equal(t, expectedAuthData, cl.Auth)\n\t\thandlerCalled = true\n\t\treturn nil\n\t}\n\tstreamServer := &mockServerStream{\n\t\tctx: metadata.NewIncomingContext(context.Background(), metadata.Pairs(\"authorization\", \"some-auth-data\")),\n\t}\n\tinterceptor := authStreamServerInterceptor(newMockAuthServer(authFunc))\n\n\t// test\n\terr := interceptor(nil, streamServer, &grpc.StreamServerInfo{}, handler)\n\n\t// verify\n\trequire.NoError(t, err)\n\tassert.True(t, authCalled)\n\tassert.True(t, handlerCalled)\n}\n\nfunc TestDefaultStreamInterceptorAuthFailureWithStatusErr(t *testing.T) {\n\t// prepare\n\tauthCalled := false\n\texpectedStatusErr := status.New(codes.Unavailable, \"unavailable\")\n\tauthFunc := func(context.Context, map[string][]string) (context.Context, error) {\n\t\tauthCalled = true\n\t\treturn context.Background(), expectedStatusErr.Err()\n\t}\n\thandler := func(any, grpc.ServerStream) error {\n\t\tassert.FailNow(t, \"the handler should not have been called on auth failure!\")\n\t\treturn nil\n\t}\n\tstreamServer := &mockServerStream{\n\t\tctx: metadata.NewIncomingContext(context.Background(), metadata.Pairs(\"authorization\", \"some-auth-data\")),\n\t}\n\tinterceptor := authStreamServerInterceptor(newMockAuthServer(authFunc))\n\n\t// test\n\terr := interceptor(nil, streamServer, &grpc.StreamServerInfo{}, handler)\n\n\t// verify\n\trequire.ErrorContains(t, err, expectedStatusErr.Err().Error()) // unfortunately, grpc errors don't wrap the original ones\n\tassert.Equal(t, codes.Unavailable, status.Code(err))\n\tassert.True(t, authCalled)\n}\n\nfunc TestDefaultStreamInterceptorAuthFailure(t *testing.T) {\n\t// prepare\n\tauthCalled := false\n\texpectedErr := errors.New(\"not authenticated\")\n\tauthFunc := func(context.Context, map[string][]string) (context.Context, error) {\n\t\tauthCalled = true\n\t\treturn context.Background(), expectedErr\n\t}\n\thandler := func(any, grpc.ServerStream) error {\n\t\tassert.FailNow(t, \"the handler should not have been called on auth failure!\")\n\t\treturn nil\n\t}\n\tstreamServer := &mockServerStream{\n\t\tctx: metadata.NewIncomingContext(context.Background(), metadata.Pairs(\"authorization\", \"some-auth-data\")),\n\t}\n\tinterceptor := authStreamServerInterceptor(newMockAuthServer(authFunc))\n\n\t// test\n\terr := interceptor(nil, streamServer, &grpc.StreamServerInfo{}, handler)\n\n\t// verify\n\trequire.ErrorContains(t, err, expectedErr.Error()) // unfortunately, grpc errors don't wrap the original ones\n\tassert.Equal(t, codes.Unauthenticated, status.Code(err))\n\tassert.True(t, authCalled)\n}\n\nfunc TestDefaultStreamInterceptorMissingMetadata(t *testing.T) {\n\t// prepare\n\tauthFunc := func(context.Context, map[string][]string) (context.Context, error) {\n\t\tassert.FailNow(t, \"the auth func should not have been called!\")\n\t\treturn context.Background(), nil\n\t}\n\thandler := func(any, grpc.ServerStream) error {\n\t\tassert.FailNow(t, \"the handler should not have been called!\")\n\t\treturn nil\n\t}\n\tstreamServer := &mockServerStream{\n\t\tctx: context.Background(),\n\t}\n\tinterceptor := authStreamServerInterceptor(newMockAuthServer(authFunc))\n\n\t// test\n\terr := interceptor(nil, streamServer, &grpc.StreamServerInfo{}, handler)\n\n\t// verify\n\tassert.Equal(t, errMetadataNotFound, err)\n}\n\ntype mockServerStream struct {\n\tgrpc.ServerStream\n\tctx context.Context\n}\n\nfunc (m *mockServerStream) Context() context.Context {\n\treturn m.ctx\n}\n\ntype grpcTraceServer struct {\n\tptraceotlp.UnimplementedGRPCServer\n\trecordedContext context.Context\n}\n\nfunc (gts *grpcTraceServer) Export(ctx context.Context, _ ptraceotlp.ExportRequest) (ptraceotlp.ExportResponse, error) {\n\tgts.recordedContext = ctx\n\treturn ptraceotlp.NewExportResponse(), nil\n}\n\nfunc (gts *grpcTraceServer) startTestServer(t *testing.T, gss configoptional.Optional[ServerConfig]) (*grpc.Server, string) {\n\treturn gts.startTestServerWithExtensions(t, gss, nil)\n}\n\nfunc (gts *grpcTraceServer) startTestServerWithExtensions(t *testing.T, gss configoptional.Optional[ServerConfig], extensions map[component.ID]component.Component, opts ...ToServerOption) (*grpc.Server, string) {\n\tlistener, err := gss.Get().NetAddr.Listen(context.Background())\n\trequire.NoError(t, err)\n\tserver, err := gss.Get().ToServer(context.Background(), extensions, componenttest.NewNopTelemetrySettings(), opts...)\n\trequire.NoError(t, err)\n\tptraceotlp.RegisterGRPCServer(server, gts)\n\tgo func() {\n\t\t_ = server.Serve(listener)\n\t}()\n\treturn server, listener.Addr().String()\n}\n\nfunc (gts *grpcTraceServer) startTestServerWithExtensionsError(_ *testing.T, gss ServerConfig, extensions map[component.ID]component.Component, opts ...ToServerOption) (*grpc.Server, error) {\n\tlistener, err := gss.NetAddr.Listen(context.Background())\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer listener.Close()\n\n\tserver, err := gss.ToServer(context.Background(), extensions, componenttest.NewNopTelemetrySettings(), opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tptraceotlp.RegisterGRPCServer(server, gts)\n\treturn server, nil\n}\n\n// sendTestRequest issues a ptraceotlp export request and captures metadata.\nfunc sendTestRequest(t *testing.T, cc ClientConfig) (ptraceotlp.ExportResponse, error) {\n\treturn sendTestRequestWithExtensions(t, cc, nil)\n}\n\n// sendTestRequestWithExtensions is similar to sendTestRequest but allows specifying the host\nfunc sendTestRequestWithExtensions(t *testing.T, cc ClientConfig, extensions map[component.ID]component.Component) (ptraceotlp.ExportResponse, error) {\n\tgrpcClientConn, errClient := cc.ToClientConn(context.Background(), extensions, componenttest.NewNopTelemetrySettings())\n\trequire.NoError(t, errClient)\n\tdefer func() { assert.NoError(t, grpcClientConn.Close()) }()\n\tc := ptraceotlp.NewGRPCClient(grpcClientConn)\n\tctx, cancelFunc := context.WithTimeout(context.Background(), 2*time.Second)\n\tresp, errResp := c.Export(ctx, ptraceotlp.NewExportRequest(), grpc.WaitForReady(true))\n\tcancelFunc()\n\treturn resp, errResp\n}\n\n// tempSocketName provides a temporary Unix socket name for testing.\nfunc tempSocketName(t *testing.T) string {\n\t// The socket path length limit on macOS is 104 characters. Using `os.TempDir` to produce a shorter file path (#12639)\n\ttmpfile, err := os.CreateTemp(os.TempDir(), \"sock\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, tmpfile.Close())\n\tsocket := tmpfile.Name()\n\trequire.NoError(t, os.Remove(socket))\n\treturn socket\n}\n"
  },
  {
    "path": "config/configgrpc/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package configgrpc defines the  configuration settings to create\n// a gRPC client and server.\n//\n// The configuration structs in this package may be shared across signals, but\n// assume each struct is used for a single protocol and component.\npackage configgrpc // import \"go.opentelemetry.io/collector/config/configgrpc\"\n"
  },
  {
    "path": "config/configgrpc/go.mod",
    "content": "module go.opentelemetry.io/collector/config/configgrpc\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/mostynb/go-grpc-compression v1.2.3\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/client v1.54.0\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/config/configauth v1.54.0\n\tgo.opentelemetry.io/collector/config/configcompression v1.54.0\n\tgo.opentelemetry.io/collector/config/configmiddleware v1.54.0\n\tgo.opentelemetry.io/collector/config/confignet v1.54.0\n\tgo.opentelemetry.io/collector/config/configopaque v1.54.0\n\tgo.opentelemetry.io/collector/config/configoptional v1.54.0\n\tgo.opentelemetry.io/collector/config/configtls v1.54.0\n\tgo.opentelemetry.io/collector/extension v1.54.0\n\tgo.opentelemetry.io/collector/extension/extensionauth v1.54.0\n\tgo.opentelemetry.io/collector/extension/extensionauth/extensionauthtest v0.148.0\n\tgo.opentelemetry.io/collector/extension/extensionmiddleware v0.148.0\n\tgo.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0\n\tgo.opentelemetry.io/otel v1.42.0\n\tgo.uber.org/goleak v1.3.0\n\tgoogle.golang.org/grpc v1.79.3\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f // indirect\n\tgithub.com/fsnotify/fsnotify v1.9.0 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/golang/snappy v0.0.4 // indirect\n\tgithub.com/google/go-tpm v0.9.8 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/klauspost/compress v1.17.9 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/confmap v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/crypto v0.48.0 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/client => ../../client\n\nreplace go.opentelemetry.io/collector/config/configauth => ../configauth\n\nreplace go.opentelemetry.io/collector/config/configcompression => ../configcompression\n\nreplace go.opentelemetry.io/collector/config/confignet => ../confignet\n\nreplace go.opentelemetry.io/collector/config/configopaque => ../configopaque\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../configoptional\n\nreplace go.opentelemetry.io/collector/config/configtls => ../configtls\n\nreplace go.opentelemetry.io/collector/extension => ../../extension\n\nreplace go.opentelemetry.io/collector/extension/extensionauth => ../../extension/extensionauth\n\nreplace go.opentelemetry.io/collector/config/configmiddleware => ../configmiddleware\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ../../extension/extensionmiddleware\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest => ../../extension/extensionauth/extensionauthtest\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest => ../../extension/extensionmiddleware/extensionmiddlewaretest\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "config/configgrpc/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f h1:RJ+BDPLSHQO7cSjKBqjPJSbi1qfk9WcsjQDtZiw3dZw=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f/go.mod h1:VHbbch/X4roIY22jL1s3qRbZhCiRIgUAF/PdSUcx2io=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=\ngithub.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=\ngithub.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=\ngithub.com/google/go-tpm-tools v0.4.7 h1:J3ycC8umYxM9A4eF73EofRZu4BxY0jjQnUnkhIBbvws=\ngithub.com/google/go-tpm-tools v0.4.7/go.mod h1:gSyXTZHe3fgbzb6WEGd90QucmsnT1SRdlye82gH8QjQ=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA=\ngithub.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/mostynb/go-grpc-compression v1.2.3 h1:42/BKWMy0KEJGSdWvzqIyOZ95YcR9mLPqKctH7Uo//I=\ngithub.com/mostynb/go-grpc-compression v1.2.3/go.mod h1:AghIxF3P57umzqM9yz795+y1Vjs47Km/Y2FE6ouQ7Lg=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 h1:yI1/OhfEPy7J9eoa6Sj051C7n5dvpj0QX8g4sRchg04=\ngo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0/go.mod h1:NoUCKYWK+3ecatC4HjkRktREheMeEtrXoQxrqYFeHSc=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=\ngolang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=\ngonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "config/configgrpc/gzip.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configgrpc // import \"go.opentelemetry.io/collector/config/configgrpc\"\n\nimport (\n\t// Import the gzip package which auto-registers the gzip gRPC compressor.\n\t_ \"google.golang.org/grpc/encoding/gzip\"\n)\n"
  },
  {
    "path": "config/configgrpc/metadata.yaml",
    "content": "type: config/configgrpc\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "config/configgrpc/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configgrpc\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "config/configgrpc/server_middleware_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configgrpc\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configmiddleware\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensionmiddleware\"\n\t\"go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest\"\n)\n\n// contextKey is a private type for keys defined in this test.\ntype contextKey int\n\n// Key for the slice of middleware names in the context.\nconst middlewareCallsKey contextKey = 0\n\n// getMiddlewareCalls retrieves the middleware calls from context or returns an empty slice.\nfunc getMiddlewareCalls(ctx context.Context) []string {\n\tcalls, ok := ctx.Value(middlewareCallsKey).([]string)\n\tif !ok {\n\t\treturn []string{}\n\t}\n\treturn calls\n}\n\n// testServerMiddleware is a test implementation of configmiddleware.Middleware\ntype testServerMiddleware struct {\n\textension.Extension\n\textensionmiddleware.GetGRPCServerOptionsFunc\n}\n\nfunc newTestServerMiddleware(name string) extension.Extension {\n\treturn &testServerMiddleware{\n\t\tExtension: extensionmiddlewaretest.NewNop(),\n\t\tGetGRPCServerOptionsFunc: func(_ context.Context) ([]grpc.ServerOption, error) {\n\t\t\treturn []grpc.ServerOption{grpc.ChainUnaryInterceptor(\n\t\t\t\tfunc(\n\t\t\t\t\tctx context.Context,\n\t\t\t\t\treq any, _ *grpc.UnaryServerInfo,\n\t\t\t\t\thandler grpc.UnaryHandler,\n\t\t\t\t) (any, error) {\n\t\t\t\t\tctx = context.WithValue(ctx, middlewareCallsKey, append(getMiddlewareCalls(ctx), name))\n\t\t\t\t\treturn handler(ctx, req)\n\t\t\t\t})}, nil\n\t\t},\n\t}\n}\n\nfunc TestGrpcServerUnaryInterceptor(t *testing.T) {\n\t// Register two test extensions\n\textensions := map[component.ID]component.Component{\n\t\tcomponent.MustNewID(\"test1\"): newTestServerMiddleware(\"test1\"),\n\t\tcomponent.MustNewID(\"test2\"): newTestServerMiddleware(\"test2\"),\n\t}\n\n\t// Setup the server with both middleware options\n\tserver := &grpcTraceServer{}\n\tvar addr string\n\n\t// Create the server with middleware interceptors\n\t{\n\t\tvar srv *grpc.Server\n\t\tsrv, addr = server.startTestServerWithExtensions(t, configoptional.Some(ServerConfig{\n\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t},\n\t\t\tMiddlewares: []configmiddleware.Config{\n\t\t\t\tnewTestMiddlewareConfig(\"test1\"),\n\t\t\t\tnewTestMiddlewareConfig(\"test2\"),\n\t\t\t},\n\t\t}), extensions)\n\t\tdefer srv.Stop()\n\t}\n\n\t// Send a request to trigger the interceptors\n\tresp, errResp := sendTestRequest(t, ClientConfig{\n\t\tEndpoint: addr,\n\t\tTLS: configtls.ClientConfig{\n\t\t\tInsecure: true,\n\t\t},\n\t})\n\trequire.NoError(t, errResp)\n\trequire.NotNil(t, resp)\n\n\t// Verify interceptors were called in the correct order\n\tassert.Equal(t, []string{\"test1\", \"test2\"}, getMiddlewareCalls(server.recordedContext))\n}\n\n// TestServerMiddlewareToServerErrors tests failure cases for the ToServer method\n// specifically related to middleware resolution and API calls.\nfunc TestServerMiddlewareToServerErrors(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\textensions map[component.ID]component.Component\n\t\tconfig     ServerConfig\n\t\terrText    string\n\t}{\n\t\t{\n\t\t\tname:       \"extension_not_found\",\n\t\t\textensions: map[component.ID]component.Component{},\n\t\t\tconfig: ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tMiddlewares: []configmiddleware.Config{\n\t\t\t\t\t{\n\t\t\t\t\t\tID: component.MustNewID(\"nonexistent\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\terrText: \"failed to resolve middleware \\\"nonexistent\\\": middleware not found\",\n\t\t},\n\t\t{\n\t\t\tname: \"get_server_options_fails\",\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\tcomponent.MustNewID(\"errormw\"): extensionmiddlewaretest.NewErr(errors.New(\"get server options failed\")),\n\t\t\t},\n\t\t\tconfig: ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tMiddlewares: []configmiddleware.Config{\n\t\t\t\t\t{\n\t\t\t\t\t\tID: component.MustNewID(\"errormw\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\terrText: \"get server options failed\",\n\t\t},\n\t}\n\n\tfor _, tc := range tests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t// Test creating the server with middleware errors\n\t\t\tserver := &grpcTraceServer{}\n\t\t\tsrv, err := server.startTestServerWithExtensionsError(t, tc.config, tc.extensions)\n\t\t\tif srv != nil {\n\t\t\t\tsrv.Stop()\n\t\t\t}\n\t\t\trequire.Error(t, err)\n\t\t\tassert.Contains(t, err.Error(), tc.errText)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "config/configgrpc/testdata/ca.crt",
    "content": "-----BEGIN CERTIFICATE-----\nMIIDNjCCAh4CCQC0I5IQT7eziDANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJB\nVTESMBAGA1UECAwJQXVzdHJhbGlhMQ8wDQYDVQQHDAZTeWRuZXkxEjAQBgNVBAoM\nCU15T3JnTmFtZTEVMBMGA1UEAwwMTXlDb21tb25OYW1lMB4XDTIyMDgwMzA0MTky\nMVoXDTMyMDczMTA0MTkyMVowXTELMAkGA1UEBhMCQVUxEjAQBgNVBAgMCUF1c3Ry\nYWxpYTEPMA0GA1UEBwwGU3lkbmV5MRIwEAYDVQQKDAlNeU9yZ05hbWUxFTATBgNV\nBAMMDE15Q29tbW9uTmFtZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB\nAMhGP0dy3zvkdx9zI+/XVjPOWlER0OUp7Sgzidc3nLOk42+bH4ofIVNtOFVqlNKi\nO1bImu238VdBhd6R5IZZ1ZdIMcCeDgSJYu2X9wA3m4PKz8IdXo5ly2OHghhmCvqG\nWxgqDj5wPXiczQwuf1EcDMtRWbXJ6Z/XH1U68R/kRdNLkiZ2LwtjoQpis5XYckLL\nCrdF+AL6GeDIe0Mh9QGs26Vux+2kvaOGNUWRPE6Wt4GkqyKqmzYfR9HbflJ4xHT2\nI+jE1lg+jMBeom7z8Z90RE4GGcHjO+Vens/88r5EAjTnFj1Kb5gL2deSHY1m/++R\nZ/kRyg+zQJyw4fAzlAA4+VkCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAM3gRdTKX\neGwGYVmmKqA2vTxeigQYLHml7OSopcWj2wJfxfp49HXPRuvgpQn9iubxO3Zmhd83\n2X1E+T0A8oy5CfxgpAhHb3lY0jm3TjKXm6m+dSODwL3uND8tX+SqR8sRTFxPvPuo\npmvhdTZoRI3EzIiHLTgCuSU25JNP/vrVoKk0JvCkDYTU/WcVfj0v95DTMoWR4JGz\nmtBwrgD0EM2XRw5ZMc7sMPli1gqmCbCQUrDZ+rPB78WDCBILBd8Cz75qYTUp98BY\nakJyBckdJHAdyEQYDKa9HpmpexOO7IhSXCTEN1DEBgpZgEi/lBDRG/b0OzenUUgt\nLUABtWt3pNQ9HA==\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "config/configgrpc/testdata/client.crt",
    "content": "-----BEGIN CERTIFICATE-----\nMIIDVTCCAj2gAwIBAgIJANt5fkUlfxyiMA0GCSqGSIb3DQEBCwUAMF0xCzAJBgNV\nBAYTAkFVMRIwEAYDVQQIDAlBdXN0cmFsaWExDzANBgNVBAcMBlN5ZG5leTESMBAG\nA1UECgwJTXlPcmdOYW1lMRUwEwYDVQQDDAxNeUNvbW1vbk5hbWUwHhcNMjIwODAz\nMDQxOTIxWhcNMzIwNzMxMDQxOTIxWjBdMQswCQYDVQQGEwJBVTESMBAGA1UECAwJ\nQXVzdHJhbGlhMQ8wDQYDVQQHDAZTeWRuZXkxEjAQBgNVBAoMCU15T3JnTmFtZTEV\nMBMGA1UEAwwMTXlDb21tb25OYW1lMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\nCgKCAQEAm/gURxkdWTDS0TyL2j920SfOtOZIo7DjubWLbZtNLrNCZNBsV+8c/ko/\nwleWmUJQRHeiZkNFs8TK6d8Grks6ta9oNO4CiCCO1kz4QidA827cL5+WaKWEVn8Y\nZ8aiEMjDOnpYnb/ycsXpERN/P22jHpFD3DKSwLXoXQvasbSJsZro+AIaPAurFB7W\nrMagCptwzGQDzryqVKEmXo+eN4XRxsoE8yroHsGbQ8GCZ+neftgV3Jhi1qcXZ//A\n3ApY5lg06n1A03fYBlXE5L9tYKpIRNl2kq45mJ8DX6Tdp4Z1Y15+keIIyQpx4LRf\nrtdbMQNJhBFOwpAajTmaKXxeICFRHQIDAQABoxgwFjAUBgNVHREEDTALgglsb2Nh\nbGhvc3QwDQYJKoZIhvcNAQELBQADggEBAKWrbMxms658R/wYwLxzWPrZVKFswOJX\nTpSkXGkyRnrhhZi3I8EhLZhlpZ9k8dplcvseVAUdX9hJu0BaDWBiW/VlPVUkWpWR\nQZzrssAKhmSYMgl3OiayU30vL9bxYsAX9KeOJfnJ4kWoBpnguToED7wrC1lbzrVK\nVj1AiI3hBdKUdPNO0hyb8yfxbP3MOottMkk89DIebtOhqj2KEU7sKrhW9a5P5D7d\n0A+0kf/IunUZ4IYFfha6qy0gRMyayfm9ttrPAY6q3faqtWR7nY87/T/7wHr1LQ1/\nQ622p7v3j3y75lGN50kFnSd77ykag/8avEKxOTFoGOQc5VCRYJnJwb4=\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "config/configgrpc/testdata/client.key",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAm/gURxkdWTDS0TyL2j920SfOtOZIo7DjubWLbZtNLrNCZNBs\nV+8c/ko/wleWmUJQRHeiZkNFs8TK6d8Grks6ta9oNO4CiCCO1kz4QidA827cL5+W\naKWEVn8YZ8aiEMjDOnpYnb/ycsXpERN/P22jHpFD3DKSwLXoXQvasbSJsZro+AIa\nPAurFB7WrMagCptwzGQDzryqVKEmXo+eN4XRxsoE8yroHsGbQ8GCZ+neftgV3Jhi\n1qcXZ//A3ApY5lg06n1A03fYBlXE5L9tYKpIRNl2kq45mJ8DX6Tdp4Z1Y15+keII\nyQpx4LRfrtdbMQNJhBFOwpAajTmaKXxeICFRHQIDAQABAoIBAQCWxrT7omi/vzYd\n9dUQ8Acx3LS0JmaUb71F2x3loJt1iO+nO+FxBIPXw/ltK3U3xWaJOcnx6Biq15R9\nkBAKUEl6OA6aFHi4FhlfS9s3QHFGo6YSF8m0ckXDxGvYbqpfZWVt07Z1EYkUsQRF\ncL6zl454T1/1r6I0z+XIhVwuLGRsHt2+GCwSrLMnF9aTUJvPFy5G7YlxmL5q1BFu\nF70AK9FLZcYqa5nP1F1HbIQB/zsQ8admpKIy5tjaZiLgctXv2GTzzXDEwEnaJMrq\nSPr1dGDhdGs5iYRMOMT5Pp9dIG2+ZSSMHFAn4IRoB/cPJbNEUkgwQOPmDYETqSg5\ntSjfIUw1AoGBAMjE6PlT1/orlHW4QvKmV73YtKPVfi1Coo/F8G45qFaHDkc6bI9W\nySrnvqWcPs++xOZMoGtLuESw/LEluFo8vMX8aQYrVSz4Pb7AvuYbBRE0EVVui7YB\n3B1O0c7QTabmfQYeATYD7qSShLccSpUE+FQa6NdrJOxddJLM0Z9K73q7AoGBAMbg\nI2+NYB6XME7tyStOS4pkA4y7brG/M8BCaY34nfOJT4Qh6pqZRnDJ4ReopGoXEqWg\nhwFRsBNhsji4GGejRBPnYcfJTSuMXSPromgoH1tR0OQbMJB0pCTavbI9j+endlv4\n/P+KV3ZMYOLhL/gaaTG+o6Wh2ehnE/8/rmqGpoIHAoGAHXVG+c5jkkFytxMiP5hI\np4J0ftWEff+Y+p+Ad6veF1QZtDnOU/nX6oO2ZXZXgQPswB3eK+AgWXPen994/USM\nLkCq6EzTYpXJ+YMuf3TXeX66TF68ASiks2gtQLsvqZ2IGq2sX9CT43HcJ0Hvb44b\nIbwRDgqakFPmFuQWndjQ6qECgYA9bOlFATOY/zWKi2NBHvOyEOYPx6yO9fF0Bo83\nrHyMxfJra1Zc3c6l85S0jAAMTIgT5BsOyz5JHjm/zwyqpgDW7PaEkKZnNvllqNgG\nt63HtOOCMOu1EnHIeE9zCBS0hkLGcYcjHoWZIkoiiU8ZoH6xQKKm+/CkGYJRqkei\n22f+bQKBgGHq2/ZzgxfblD3blKWp8mh5Kw7c/2VwJRvLEMlgzrnRgF7QNhEcH3Jm\naD/pqzAkqHnLVVQ5ogMKrrLl11jQp4kX74+Ps2Yul7UgzXFYy020mQSpJF/FMjrl\nPEqwfCiOT2nLyE30x9VClUOGXy1CxH52Yn/g81ENq3jKTptwh+fI\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "config/configgrpc/testdata/server.crt",
    "content": "-----BEGIN CERTIFICATE-----\nMIIDVTCCAj2gAwIBAgIJANt5fkUlfxyhMA0GCSqGSIb3DQEBCwUAMF0xCzAJBgNV\nBAYTAkFVMRIwEAYDVQQIDAlBdXN0cmFsaWExDzANBgNVBAcMBlN5ZG5leTESMBAG\nA1UECgwJTXlPcmdOYW1lMRUwEwYDVQQDDAxNeUNvbW1vbk5hbWUwHhcNMjIwODAz\nMDQxOTIxWhcNMzIwNzMxMDQxOTIxWjBdMQswCQYDVQQGEwJBVTESMBAGA1UECAwJ\nQXVzdHJhbGlhMQ8wDQYDVQQHDAZTeWRuZXkxEjAQBgNVBAoMCU15T3JnTmFtZTEV\nMBMGA1UEAwwMTXlDb21tb25OYW1lMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\nCgKCAQEAv1Pm2elKl/IpJlX5NqQjRTlA1rHws8F7v1IuaXB2qfk1MsDCt37OvlbR\n4ARrY6zdUIrEQ/wrhQsZ2M5/yaj0rfeCgd/SDUKMAqDvXQXBY2AaLubTAIEMs4rF\nR5Zq/pcBNz1zu8kRvRgvVuOpTCPR1kRvKFWAp689lXZhUU/BrQQXhdA993xVMRM9\nu4fZuJLxNGGR/EhqTec4Z65jAZiUfO7ID94PtaxTrzR/Kjr2CiceR5hwdY40Bcme\nD3IAd0J6nN1zIihe+Nqg/ImOG7YS+efQIEWJ8eHOoCK5knFBXRy6WwxeCyAPXyIb\nDTrqTy67eTDYc0XZ24F/5Q3GSvfMDwIDAQABoxgwFjAUBgNVHREEDTALgglsb2Nh\nbGhvc3QwDQYJKoZIhvcNAQELBQADggEBAKeFHP5rQasRS/XGbPkobfbFyTdGnLay\n0Vr6+Rs5+4siKlAIhuUP9A/De61CEkFj8NFi2bmXYv8q3qP/z0lrjw7btrvD7Qc7\nlth73k3U2sUVZoqbYQZz0GHCWfZm8yXjP63SKI+81LHbS40ArO0R44BLc9TbbRiR\n/LwO/x2+cxs28KdsEkU6jQ6Ly5jyoxw1ysoIeRfIk+FnQD4w29TyGgtX/G15/NN0\nytByIZ8wdbUciunQc3nPXoPc41N+hyi2GZaXMuJ4VlsNmgY+wPmp4y3pl4l0bgCb\n1FR8Vvtsi8jLH8J15oAMWdmHQKcoJDE49llx+bQGpNekp6mlfX1DIPI=\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "config/configgrpc/testdata/server.key",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIBAAKCAQEAv1Pm2elKl/IpJlX5NqQjRTlA1rHws8F7v1IuaXB2qfk1MsDC\nt37OvlbR4ARrY6zdUIrEQ/wrhQsZ2M5/yaj0rfeCgd/SDUKMAqDvXQXBY2AaLubT\nAIEMs4rFR5Zq/pcBNz1zu8kRvRgvVuOpTCPR1kRvKFWAp689lXZhUU/BrQQXhdA9\n93xVMRM9u4fZuJLxNGGR/EhqTec4Z65jAZiUfO7ID94PtaxTrzR/Kjr2CiceR5hw\ndY40BcmeD3IAd0J6nN1zIihe+Nqg/ImOG7YS+efQIEWJ8eHOoCK5knFBXRy6Wwxe\nCyAPXyIbDTrqTy67eTDYc0XZ24F/5Q3GSvfMDwIDAQABAoIBAQC/BuxlAhKiJvyC\n9DABKFy2zvU35y3mq/X8Dfec+tbf2pwM8nz3bLrLPDAMNR1rxbqqogJXxr1E9tJ1\nr6fTFshFsewx8+DrsFfOgBS9kfOGXvuFfJ2L0U13LcTPNxXY37gtCUQ2aAk3/Z+2\nZ1QvW0w1XNqHMOdlhQg95JZB8xnyvXs1niLT/I9d7KbPBmOWkB5Jp7+JaebmWqNS\nalxnNqYnhXcrNSAbuR4bgz0l4I+Jprms26C6sakmgCfeMjfWbd2k3tp06vKXmT6q\nqKa0855axP9wuSbKbscTDW5RFYTYnu/CSYJ4nZtzSS8a559iG3m61EgPOoVTnTX6\n0t0I+kwRAoGBAN403NO4FfHG8k2bFpbATQkmC9UwjMbl5RIEL0fFhNVsuM5jTwHc\n0wlFm9tMN8xqg66OFCimC/mUNPWX8nrb/MwrAw6/50rbyqOBFnmFKIfVf4ftpLzt\nBLhEg7a/FPgdDgldQD+C6XbMyBA1AF3nbpTnbnj5WVQTl672s9teegSzAoGBANxs\n1y6Nfh2DyyU16p61376AAP3WfHvuBgJAC0xGCqoTrbyzl4/r06BTMl51PbWJLDjm\nFryTtgM7a8XO1jwfWJno71dnT7Bsy+wYnmJ5+9XHwgO9oZfSFUk+ELrEImI/4NZX\ndJLkc0SuCG/wa3Wa76+sFNlzAzBBs83RE2j432E1AoGAF+x5GhJnynAxBkn8VJ6/\nrIx8GafwgDmgQCBTNtb9Rj0+aHoot3qe/hCQhzvdhhSxuMlzQi0efPCIAyko4jFt\nNk4rNhtTO6wOVSxAzzSW+Ij0Ah6D7hNWvsAhrjtEdrIqILf5gt0FZdUGdTg/odyY\n+08vhbbS90pkumG1W5kAaiECgYEAqjk3eBD26u4jjIn1tTk5H9GUcnMYUVCAvW4e\nC3ovtCZcTlTW3+M73B1D0aRy0mWrjAlMV7cuoZJa6TiRQ37lmn5Dj1kONm3ekWZ1\nshEIBZEtaFwila88lwJiQwlCkGNKS9zf/qyDw+8uPtwI8JqFLUIUG9VxCexDYddr\nSO6g+10CgYEAwUs2BRJb6Od+8XtH32+8DDOnpfWJARY0CwogN2k+D1dbAB8Wkda1\nBMADasAcjDFRX6xvyyDlqxcDIoCI1JvpS82I/PTNHeT8pEr5Caln7OHD/BtnPwmI\nYR0bvKkoN0jdQdjifpMVXEbJS1VfFLdQYQ8iQMwZfkFmzIkYpvqWVtw=\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "config/configgrpc/wrappedstream.go",
    "content": "// Copyright The OpenTelemetry Authors\n// Copyright 2016 Michal Witkowski. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n\npackage configgrpc // import \"go.opentelemetry.io/collector/config/configgrpc\"\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc\"\n)\n\n// this functionality was originally copied from grpc-ecosystem/go-grpc-middleware project\n\n// wrappedServerStream is a thin wrapper around grpc.ServerStream that allows modifying context.\ntype wrappedServerStream struct {\n\tgrpc.ServerStream\n\t// wrappedContext is the wrapper's own Context. You can assign it.\n\twrappedCtx context.Context\n}\n\n// Context returns the wrapper's wrappedContext, overwriting the nested grpc.ServerStream.Context()\nfunc (w *wrappedServerStream) Context() context.Context {\n\treturn w.wrappedCtx\n}\n\n// wrapServerStream returns a ServerStream with the new context.\nfunc wrapServerStream(wrappedCtx context.Context, stream grpc.ServerStream) *wrappedServerStream {\n\tif existing, ok := stream.(*wrappedServerStream); ok {\n\t\texisting.wrappedCtx = wrappedCtx\n\t\treturn existing\n\t}\n\treturn &wrappedServerStream{ServerStream: stream, wrappedCtx: wrappedCtx}\n}\n"
  },
  {
    "path": "config/configgrpc/wrappedstream_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// Copyright 2016 Michal Witkowski. All Rights Reserved.\n// SPDX-License-Identifier: Apache-2.0\n\npackage configgrpc // import \"go.opentelemetry.io/collector/internal/middleware\"\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"google.golang.org/grpc\"\n)\n\ntype ctxKey struct{}\n\nvar (\n\toneCtxKey   = ctxKey{}\n\totherCtxKey = ctxKey{}\n)\n\nfunc TestWrapServerStream(t *testing.T) {\n\tctx := context.WithValue(t.Context(), oneCtxKey, 1)\n\tfake := &fakeServerStream{ctx: ctx}\n\tassert.NotNil(t, fake.Context().Value(oneCtxKey), \"values from fake must propagate to wrapper\")\n\twrapped := wrapServerStream(context.WithValue(fake.Context(), otherCtxKey, 2), fake)\n\tassert.NotNil(t, wrapped.Context().Value(oneCtxKey), \"values from wrapper must be set\")\n\tassert.NotNil(t, wrapped.Context().Value(otherCtxKey), \"values from wrapper must be set\")\n}\n\nfunc TestDoubleWrapping(t *testing.T) {\n\tfake := &fakeServerStream{ctx: context.Background()}\n\twrapped := wrapServerStream(fake.Context(), fake)\n\tassert.Same(t, wrapped, wrapServerStream(wrapped.Context(), wrapped)) // should be noop\n\tassert.Equal(t, fake, wrapped.ServerStream)\n}\n\ntype fakeServerStream struct {\n\tgrpc.ServerStream\n\tctx context.Context\n}\n\nfunc (f *fakeServerStream) Context() context.Context {\n\treturn f.ctx\n}\n"
  },
  {
    "path": "config/confighttp/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "config/confighttp/README.md",
    "content": "# HTTP Configuration Settings\n\nHTTP exposes a [variety of settings](https://golang.org/pkg/net/http/).\nSeveral of these settings are available for configuration within individual\nreceivers or exporters.\n\n## Client Configuration\n\n[Exporters](https://github.com/open-telemetry/opentelemetry-collector/blob/main/exporter/README.md)\nleverage client configuration.\n\nNote that client configuration supports TLS configuration, the\nconfiguration parameters are also defined under `tls` like server\nconfiguration. For more information, see [configtls\nREADME](../configtls/README.md).\n\n- `endpoint`: address:port\n- `proxy_url`: Proxy URL to use for HTTP requests\n- [`tls`](../configtls/README.md)\n- [`headers`](https://pkg.go.dev/net/http#Request): name/value pairs added to the HTTP request headers\n  - certain headers such as Content-Length and Connection are automatically written when needed and values in Header may be ignored.\n  - `Host` header is automatically derived from `endpoint` value. However, this automatic assignment can be overridden by explicitly setting the Host field in the headers field.\n  - if `Host` header is provided then it overrides `Host` field in [Request](https://pkg.go.dev/net/http#Request) which results as an override of `Host` header value.\n- [`read_buffer_size`](https://golang.org/pkg/net/http/#Transport)\n- [`timeout`](https://golang.org/pkg/net/http/#Client)\n- [`write_buffer_size`](https://golang.org/pkg/net/http/#Transport)\n- `compression`: Compression type to use among `gzip`, `zstd`, `snappy`, `zlib`, `deflate`, and `lz4`.\n  - look at the documentation for the server-side of the communication.\n  - `none` will be treated as uncompressed, and any other inputs will cause an error.\n- `compression_params` : Configure advanced compression options\n  - `level`: Configure compression level for `compression` type\n  - The following are valid combinations of `compression` and `level`\n    - `gzip`\n      - BestSpeed: `1`\n      - BestCompression: `9`\n      - DefaultCompression: `-1`\n    - `zlib`\n      - BestSpeed: `1`\n      - BestCompression: `9`\n      - DefaultCompression: `-1`\n    - `deflate`\n      - BestSpeed: `1`\n      - BestCompression: `9`\n      - DefaultCompression: `-1`\n    - `zstd`\n      - SpeedFastest: `1`\n      - SpeedDefault: `3`\n      - SpeedBetterCompression: `6`\n      - SpeedBestCompression: `11`\n    - `snappy`\n      No compression levels supported yet\n    - `x-snappy-framed` (When feature gate `confighttp.framedSnappy` is enabled)\n      No compression levels supported yet\n- [`max_idle_conns`](https://golang.org/pkg/net/http/#Transport)\n- [`max_idle_conns_per_host`](https://golang.org/pkg/net/http/#Transport)\n- [`max_conns_per_host`](https://golang.org/pkg/net/http/#Transport)\n- [`idle_conn_timeout`](https://golang.org/pkg/net/http/#Transport)\n- [`auth`](../configauth/README.md)\n- [`disable_keep_alives`](https://golang.org/pkg/net/http/#Transport)\n- [`force_attempt_http2`](https://golang.org/pkg/net/http/#Transport)\n- [`http2_read_idle_timeout`](https://pkg.go.dev/golang.org/x/net/http2#Transport)\n- [`http2_ping_timeout`](https://pkg.go.dev/golang.org/x/net/http2#Transport)\n- [`cookies`](https://pkg.go.dev/net/http#CookieJar)\n  - [`enabled`] if enabled, the client will store cookies from server responses and reuse them in subsequent requests.\n- [`middlewares`](../configmiddleware/README.md)\n\nExample:\n\n```yaml\nexporter:\n  otlp_http:\n    endpoint: otelcol2:55690\n    auth:\n      authenticator: some-authenticator-extension\n    tls:\n      ca_file: ca.pem\n      cert_file: cert.pem\n      key_file: key.pem\n    headers:\n      test1: \"value1\"\n      \"test 2\": \"value 2\"\n    compression: gzip\n    compression_params:\n      level: 1\n    cookies:\n      enabled: true\n```\n\n## Server Configuration\n\n[Receivers](https://github.com/open-telemetry/opentelemetry-collector/blob/main/receiver/README.md)\nleverage server configuration.\n\n- [`cors`](https://github.com/rs/cors#parameters): Configure [CORS][cors],\nallowing the receiver to accept traces from web browsers, even if the receiver\nis hosted at a different [origin][origin]. If left blank or set to `null`, CORS\nwill not be enabled.\n  - `allowed_origins`: A list of [origins][origin] allowed to send requests to\n  the receiver. An origin may contain a wildcard (`*`) to replace 0 or more\n  characters (e.g., `https://*.example.com`). **Do not use** a plain wildcard\n  `[\"*\"]`, as our CORS response includes `Access-Control-Allow-Credentials: true`, which makes browsers to **disallow a plain wildcard** (this is a security standard). To allow any origin, you can specify at least the protocol, for example `[\"https://*\", \"http://*\"]`. If no origins are listed, CORS will not be enabled.\n  - `allowed_headers`: Allow CORS requests to include headers outside the\n  [default safelist][cors-headers]. By default, safelist headers and\n  `X-Requested-With` will be allowed. To allow any request header, set to\n  `[\"*\"]`.\n  - `max_age`: Sets the value of the [`Access-Control-Max-Age`][cors-cache]\n  header, allowing clients to cache the response to CORS preflight requests. If\n  not set, browsers use a default of 5 seconds.\n- `endpoint`: Valid value syntax available [here](https://github.com/grpc/grpc/blob/master/doc/naming.md)\n- `transport`: The transport protocol to use. Defaults to `tcp`. See the [confignet README](../confignet/README.md) for more information.\n- `max_request_body_size`: configures the maximum allowed body size in bytes for a single request. Default: `20971520` (20MiB)\n- `include_metadata`: propagates the client metadata from the incoming requests to the downstream consumers. Default: `false`\n- `response_headers`: Additional headers attached to each HTTP response sent to the client. Header values are opaque since they may be sensitive\n- `compression_algorithms`: configures the list of compression algorithms the server can accept. Default: [\"\", \"gzip\", \"zstd\", \"zlib\", \"snappy\", \"deflate\", \"lz4\"]\n  - `x-snappy-framed` can be used if feature gate `confighttp.snappyFramed` is enabled.\n- `read_timeout`: maximum duration for reading the entire request, including the body. A zero or negative value means there will be no timeout. Default: `0` (no timeout)\n- `read_header_timeout`: amount of time allowed to read request headers. If zero, the value of `read_timeout` is used. If both are zero, there is no timeout. Default: `1m`\n- `write_timeout`: maximum duration before timing out writes of the response. A zero or negative value means there will be no timeout. Default: `30s`\n- `idle_timeout`: maximum amount of time to wait for the next request when keep-alives are enabled. If zero, the value of `read_timeout` is used. If both are zero, there is no timeout. Default: `1m`\n- `keep_alives_enabled`: controls whether HTTP keep-alives are enabled. Default: `true`\n- [`tls`](../configtls/README.md)\n- [`auth`](../configauth/README.md)\n  - `request_params`: a list of query parameter names to add to the auth context, along with the HTTP headers\n- [`middlewares`](../configmiddleware/README.md)\n\nYou can enable [`attribute processor`][attribute-processor] to append any http header to span's attribute using custom key. You also need to enable the \"include_metadata\"\n\nExample:\n\n```yaml\nreceivers:\n  otlp:\n    protocols:\n      http:\n        include_metadata: true\n        auth:\n          request_params:\n          - token\n          authenticator: some-authenticator-extension\n        cors:\n          allowed_origins:\n            - https://foo.bar.com\n            - https://*.test.com\n          allowed_headers:\n            - Example-Header\n          max_age: 7200\n        endpoint: 0.0.0.0:55690\n        compression_algorithms: [\"\", \"gzip\"]\nprocessors:\n  attributes:\n    actions:\n      - key: http.client_ip\n        from_context: metadata.x-forwarded-for\n        action: upsert\n```\n\n[cors]: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS\n[cors-headers]: https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header\n[cors-cache]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age\n[origin]: https://developer.mozilla.org/en-US/docs/Glossary/Origin\n[attribute-processor]: https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/processor/attributesprocessor/README.md\n"
  },
  {
    "path": "config/confighttp/client.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confighttp // import \"go.opentelemetry.io/collector/config/confighttp\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/cookiejar\"\n\t\"net/url\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\"\n\t\"go.opentelemetry.io/otel\"\n\t\"golang.org/x/net/http2\"\n\t\"golang.org/x/net/publicsuffix\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configauth\"\n\t\"go.opentelemetry.io/collector/config/configcompression\"\n\t\"go.opentelemetry.io/collector/config/configmiddleware\"\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n)\n\nconst (\n\theaderContentEncoding = \"Content-Encoding\"\n)\n\n// ClientConfig defines settings for creating an HTTP client.\ntype ClientConfig struct {\n\t// The target URL to send data to (e.g.: http://some.url:9411/v1/traces).\n\tEndpoint string `mapstructure:\"endpoint,omitempty\"`\n\n\t// ProxyURL setting for the collector\n\tProxyURL string `mapstructure:\"proxy_url,omitempty\"`\n\n\t// TLS struct exposes TLS client configuration.\n\tTLS configtls.ClientConfig `mapstructure:\"tls,omitempty\"`\n\n\t// ReadBufferSize for HTTP client. See http.Transport.ReadBufferSize.\n\t// Default is 0.\n\tReadBufferSize int `mapstructure:\"read_buffer_size,omitempty\"`\n\n\t// WriteBufferSize for HTTP client. See http.Transport.WriteBufferSize.\n\t// Default is 0.\n\tWriteBufferSize int `mapstructure:\"write_buffer_size,omitempty\"`\n\n\t// Timeout parameter configures `http.Client.Timeout`.\n\t// Default is 0 (unlimited).\n\tTimeout time.Duration `mapstructure:\"timeout,omitempty\"`\n\n\t// Additional headers attached to each HTTP request sent by the client.\n\t// Existing header values are overwritten if collision happens.\n\t// Header values are opaque since they may be sensitive.\n\tHeaders configopaque.MapList `mapstructure:\"headers,omitempty\"`\n\n\t// Auth configuration for outgoing HTTP calls.\n\tAuth configoptional.Optional[configauth.Config] `mapstructure:\"auth,omitempty\"`\n\n\t// The compression key for supported compression types within collector.\n\tCompression configcompression.Type `mapstructure:\"compression,omitempty\"`\n\n\t// Advanced configuration options for the Compression\n\tCompressionParams configcompression.CompressionParams `mapstructure:\"compression_params,omitempty\"`\n\n\t// MaxIdleConns is used to set a limit to the maximum idle HTTP connections the client can keep open.\n\t// By default, it is set to 100. Zero means no limit.\n\tMaxIdleConns int `mapstructure:\"max_idle_conns\"`\n\n\t// MaxIdleConnsPerHost is used to set a limit to the maximum idle HTTP connections the host can keep open.\n\t// If zero, [net/http.DefaultMaxIdleConnsPerHost] is used.\n\tMaxIdleConnsPerHost int `mapstructure:\"max_idle_conns_per_host,omitempty\"`\n\n\t// MaxConnsPerHost limits the total number of connections per host, including connections in the dialing,\n\t// active, and idle states. Default is 0 (unlimited).\n\tMaxConnsPerHost int `mapstructure:\"max_conns_per_host,omitempty\"`\n\n\t// IdleConnTimeout is the maximum amount of time a connection will remain open before closing itself.\n\t// By default, it is set to 90 seconds.\n\tIdleConnTimeout time.Duration `mapstructure:\"idle_conn_timeout\"`\n\n\t// DisableKeepAlives, if true, disables HTTP keep-alives and will only use the connection to the server\n\t// for a single HTTP request.\n\t//\n\t// WARNING: enabling this option can result in significant overhead establishing a new HTTP(S)\n\t// connection for every request. Before enabling this option please consider whether changes\n\t// to idle connection settings can achieve your goal.\n\tDisableKeepAlives bool `mapstructure:\"disable_keep_alives,omitempty\"`\n\n\t// This is needed in case you run into\n\t// https://github.com/golang/go/issues/59690\n\t// https://github.com/golang/go/issues/36026\n\t// HTTP2ReadIdleTimeout if the connection has been idle for the configured value send a ping frame for health check\n\t// 0s means no health check will be performed.\n\tHTTP2ReadIdleTimeout time.Duration `mapstructure:\"http2_read_idle_timeout,omitempty\"`\n\t// HTTP2PingTimeout if there's no response to the ping within the configured value, the connection will be closed.\n\t// If not set or set to 0, it defaults to 15s.\n\tHTTP2PingTimeout time.Duration `mapstructure:\"http2_ping_timeout,omitempty\"`\n\t// Cookies configures the cookie management of the HTTP client.\n\tCookies configoptional.Optional[CookiesConfig] `mapstructure:\"cookies,omitempty\"`\n\n\t// Enabling ForceAttemptHTTP2 forces the HTTP transport to use the HTTP/2 protocol.\n\t// By default, this is set to true.\n\t// NOTE: HTTP/2 does not support settings such as MaxConnsPerHost, MaxIdleConnsPerHost and MaxIdleConns.\n\tForceAttemptHTTP2 bool `mapstructure:\"force_attempt_http2,omitempty\"`\n\n\t// Middlewares are used to add custom functionality to the HTTP client.\n\t// Middleware handlers are called in the order they appear in this list,\n\t// with the first middleware becoming the outermost handler.\n\tMiddlewares []configmiddleware.Config `mapstructure:\"middlewares,omitempty\"`\n}\n\n// CookiesConfig defines the configuration of the HTTP client regarding cookies served by the server.\ntype CookiesConfig struct {\n\t_ struct{}\n}\n\n// NewDefaultClientConfig returns ClientConfig type object with\n// the default values of 'MaxIdleConns' and 'IdleConnTimeout', as well as [http.DefaultTransport] values.\n// Other config options are not added as they are initialized with 'zero value' by GoLang as default.\n// We encourage to use this function to create an object of ClientConfig.\nfunc NewDefaultClientConfig() ClientConfig {\n\t// The default values are taken from the values of 'DefaultTransport' of 'http' package.\n\tdefaultTransport := http.DefaultTransport.(*http.Transport)\n\n\treturn ClientConfig{\n\t\tMaxIdleConns:      defaultTransport.MaxIdleConns,\n\t\tIdleConnTimeout:   defaultTransport.IdleConnTimeout,\n\t\tForceAttemptHTTP2: true,\n\t}\n}\n\nfunc (cc *ClientConfig) Validate() error {\n\tif cc.Compression.IsCompressed() {\n\t\tif err := cc.Compression.ValidateParams(cc.CompressionParams); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// ToClientOption is an option to change the behavior of the HTTP client\n// returned by ClientConfig.ToClient().\n// There are currently no available options.\ntype ToClientOption interface {\n\tsealed()\n}\n\n// ToClient creates an HTTP client.\n//\n// To allow the configuration to reference middleware or authentication extensions,\n// the `extensions` argument should be the output of `host.GetExtensions()`.\n// It may also be `nil` in tests where no such extension is expected to be used.\nfunc (cc *ClientConfig) ToClient(ctx context.Context, extensions map[component.ID]component.Component, settings component.TelemetrySettings, _ ...ToClientOption) (*http.Client, error) {\n\ttlsCfg, err := cc.TLS.LoadTLSConfig(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\ttransport := http.DefaultTransport.(*http.Transport).Clone()\n\tif tlsCfg != nil {\n\t\ttransport.TLSClientConfig = tlsCfg\n\t}\n\tif cc.ReadBufferSize > 0 {\n\t\ttransport.ReadBufferSize = cc.ReadBufferSize\n\t}\n\tif cc.WriteBufferSize > 0 {\n\t\ttransport.WriteBufferSize = cc.WriteBufferSize\n\t}\n\n\ttransport.MaxIdleConns = cc.MaxIdleConns\n\ttransport.MaxIdleConnsPerHost = cc.MaxIdleConnsPerHost\n\ttransport.MaxConnsPerHost = cc.MaxConnsPerHost\n\ttransport.IdleConnTimeout = cc.IdleConnTimeout\n\ttransport.ForceAttemptHTTP2 = cc.ForceAttemptHTTP2\n\n\t// Setting the Proxy URL\n\tif cc.ProxyURL != \"\" {\n\t\tproxyURL, parseErr := url.ParseRequestURI(cc.ProxyURL)\n\t\tif parseErr != nil {\n\t\t\treturn nil, parseErr\n\t\t}\n\t\ttransport.Proxy = http.ProxyURL(proxyURL)\n\t}\n\n\ttransport.DisableKeepAlives = cc.DisableKeepAlives\n\n\tif cc.HTTP2ReadIdleTimeout > 0 {\n\t\ttransport2, transportErr := http2.ConfigureTransports(transport)\n\t\tif transportErr != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to configure http2 transport: %w\", transportErr)\n\t\t}\n\t\ttransport2.ReadIdleTimeout = cc.HTTP2ReadIdleTimeout\n\t\ttransport2.PingTimeout = cc.HTTP2PingTimeout\n\t}\n\n\tclientTransport := http.RoundTripper(transport)\n\n\t// Apply middlewares in reverse order so they execute in\n\t// forward order. The first middleware runs after authentication.\n\tif len(cc.Middlewares) > 0 && extensions == nil {\n\t\treturn nil, errors.New(\"middlewares were configured but this component or its host does not support extensions\")\n\t}\n\tfor i := len(cc.Middlewares) - 1; i >= 0; i-- {\n\t\tgetClient, rerr := cc.Middlewares[i].GetHTTPClientRoundTripper(ctx, extensions)\n\t\t// If we failed to get the middleware\n\t\tif rerr != nil {\n\t\t\treturn nil, rerr\n\t\t}\n\t\tclientTransport, rerr = getClient(ctx, clientTransport)\n\t\t// If we failed to construct a wrapper\n\t\tif rerr != nil {\n\t\t\treturn nil, rerr\n\t\t}\n\t}\n\n\t// The Auth RoundTripper should always be the innermost to ensure that\n\t// request signing-based auth mechanisms operate after compression\n\t// and header middleware modifies the request\n\tif cc.Auth.HasValue() {\n\t\tif extensions == nil {\n\t\t\treturn nil, errors.New(\"authentication was configured but this component or its host does not support extensions\")\n\t\t}\n\n\t\tauth := cc.Auth.Get()\n\t\thttpCustomAuthRoundTripper, aerr := auth.GetHTTPClientAuthenticator(ctx, extensions)\n\t\tif aerr != nil {\n\t\t\treturn nil, aerr\n\t\t}\n\n\t\tclientTransport, err = httpCustomAuthRoundTripper.RoundTripper(clientTransport)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tif len(cc.Headers) > 0 {\n\t\tclientTransport = &headerRoundTripper{\n\t\t\ttransport: clientTransport,\n\t\t\theaders:   cc.Headers,\n\t\t}\n\t}\n\n\t// Compress the body using specified compression methods if non-empty string is provided.\n\t// Supporting gzip, zlib, deflate, snappy, and zstd; none is treated as uncompressed.\n\tif cc.Compression.IsCompressed() {\n\t\t// If the compression level is not set, use the default level.\n\t\tif cc.CompressionParams.Level == 0 {\n\t\t\tcc.CompressionParams.Level = configcompression.DefaultCompressionLevel\n\t\t}\n\t\tclientTransport, err = newCompressRoundTripper(clientTransport, cc.Compression, cc.CompressionParams)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\totelOpts := []otelhttp.Option{\n\t\totelhttp.WithTracerProvider(settings.TracerProvider),\n\t\totelhttp.WithPropagators(otel.GetTextMapPropagator()),\n\t\totelhttp.WithMeterProvider(settings.MeterProvider),\n\t}\n\t// wrapping http transport with otelhttp transport to enable otel instrumentation\n\tif settings.TracerProvider != nil && settings.MeterProvider != nil {\n\t\tclientTransport = otelhttp.NewTransport(clientTransport, otelOpts...)\n\t}\n\n\tvar jar http.CookieJar\n\tif cc.Cookies.HasValue() {\n\t\tjar, err = cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\treturn &http.Client{\n\t\tTransport: clientTransport,\n\t\tTimeout:   cc.Timeout,\n\t\tJar:       jar,\n\t}, nil\n}\n\n// Custom RoundTripper that adds headers.\ntype headerRoundTripper struct {\n\ttransport http.RoundTripper\n\theaders   configopaque.MapList\n}\n\n// RoundTrip is a custom RoundTripper that adds headers to the request.\nfunc (interceptor *headerRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\t// Set Host header if provided\n\thostHeader, found := interceptor.headers.Get(\"Host\")\n\tif found && hostHeader != \"\" {\n\t\t// `Host` field should be set to override default `Host` header value which is Endpoint\n\t\treq.Host = string(hostHeader)\n\t}\n\tfor k, v := range interceptor.headers.Iter {\n\t\treq.Header.Set(k, string(v))\n\t}\n\n\t// Send the request to next transport.\n\treturn interceptor.transport.RoundTrip(req)\n}\n"
  },
  {
    "path": "config/confighttp/client_middleware_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confighttp\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configmiddleware\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensionmiddleware\"\n\t\"go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest\"\n)\n\n// testClientMiddleware is a test middleware that appends a string to the response body\ntype testClientMiddleware struct {\n\textension.Extension\n\textensionmiddleware.GetHTTPRoundTripperFunc\n}\n\nfunc newTestClientMiddleware(name string) component.Component {\n\treturn &testClientMiddleware{\n\t\tExtension: extensionmiddlewaretest.NewNop(),\n\t\tGetHTTPRoundTripperFunc: func(_ context.Context) (extensionmiddleware.WrapHTTPRoundTripperFunc, error) {\n\t\t\treturn func(_ context.Context, transport http.RoundTripper) (http.RoundTripper, error) {\n\t\t\t\treturn extensionmiddlewaretest.RoundTripperFunc(\n\t\t\t\t\tfunc(req *http.Request) (*http.Response, error) {\n\t\t\t\t\t\tresp, err := transport.RoundTrip(req)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn resp, err\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t// Read the original body\n\t\t\t\t\t\tbody, err := io.ReadAll(resp.Body)\n\t\t\t\t\t\tif err != nil {\n\t\t\t\t\t\t\treturn resp, err\n\t\t\t\t\t\t}\n\t\t\t\t\t\t_ = resp.Body.Close()\n\n\t\t\t\t\t\t// Create a new body with the appended text\n\t\t\t\t\t\tnewBody := string(body) + \"\\r\\noutput by \" + name\n\n\t\t\t\t\t\t// Replace the response body\n\t\t\t\t\t\tresp.Body = io.NopCloser(strings.NewReader(newBody))\n\t\t\t\t\t\tresp.ContentLength = int64(len(newBody))\n\n\t\t\t\t\t\treturn resp, nil\n\t\t\t\t\t}), nil\n\t\t\t}, nil\n\t\t},\n\t}\n}\n\nfunc newTestClientConfig(name string) configmiddleware.Config {\n\treturn configmiddleware.Config{\n\t\tID: component.MustNewID(name),\n\t}\n}\n\nfunc TestClientMiddlewares(t *testing.T) {\n\t// Create a test server that returns \"OK\"\n\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_, _ = w.Write([]byte(\"OK\"))\n\t}))\n\tdefer server.Close()\n\n\t// Register two test extensions\n\textensions := map[component.ID]component.Component{\n\t\tcomponent.MustNewID(\"test1\"): newTestClientMiddleware(\"test1\"),\n\t\tcomponent.MustNewID(\"test2\"): newTestClientMiddleware(\"test2\"),\n\t}\n\n\t// Test with different middleware configurations\n\ttestCases := []struct {\n\t\tname           string\n\t\tmiddlewares    []configmiddleware.Config\n\t\texpectedOutput string\n\t}{\n\t\t{\n\t\t\tname:           \"no_middlewares\",\n\t\t\tmiddlewares:    nil,\n\t\t\texpectedOutput: \"OK\",\n\t\t},\n\t\t{\n\t\t\tname: \"single_middleware\",\n\t\t\tmiddlewares: []configmiddleware.Config{\n\t\t\t\tnewTestClientConfig(\"test1\"),\n\t\t\t},\n\t\t\texpectedOutput: \"OK\\r\\noutput by test1\",\n\t\t},\n\t\t{\n\t\t\tname: \"multiple_middlewares\",\n\t\t\tmiddlewares: []configmiddleware.Config{\n\t\t\t\tnewTestClientConfig(\"test1\"),\n\t\t\t\tnewTestClientConfig(\"test2\"),\n\t\t\t},\n\t\t\texpectedOutput: \"OK\\r\\noutput by test2\\r\\noutput by test1\",\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t// Create HTTP client config with the test middlewares\n\t\t\tclientConfig := ClientConfig{\n\t\t\t\tEndpoint:    server.URL,\n\t\t\t\tMiddlewares: tc.middlewares,\n\t\t\t}\n\n\t\t\t// Create the client\n\t\t\tclient, err := clientConfig.ToClient(context.Background(), extensions, componenttest.NewNopTelemetrySettings())\n\t\t\trequire.NoError(t, err)\n\n\t\t\t// Create a request to the test server\n\t\t\treq, err := http.NewRequest(http.MethodGet, server.URL, http.NoBody)\n\t\t\trequire.NoError(t, err)\n\n\t\t\t// Send the request\n\t\t\tresp, err := client.Do(req)\n\t\t\trequire.NoError(t, err)\n\t\t\tdefer resp.Body.Close()\n\n\t\t\t// Check the response\n\t\t\tbody, err := io.ReadAll(resp.Body)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tc.expectedOutput, string(body))\n\t\t})\n\t}\n}\n\nfunc TestClientMiddlewareErrors(t *testing.T) {\n\t// Create a test server that returns \"OK\"\n\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_, _ = w.Write([]byte(\"OK\"))\n\t}))\n\tdefer server.Close()\n\n\t// Test cases for HTTP client middleware errors\n\thttpTests := []struct {\n\t\tname       string\n\t\textensions map[component.ID]component.Component\n\t\tconfig     ClientConfig\n\t\terrText    string\n\t}{\n\t\t{\n\t\t\tname:       \"extension_not_found\",\n\t\t\textensions: map[component.ID]component.Component{},\n\t\t\tconfig: ClientConfig{\n\t\t\t\tEndpoint: server.URL,\n\t\t\t\tMiddlewares: []configmiddleware.Config{\n\t\t\t\t\t{\n\t\t\t\t\t\tID: component.MustNewID(\"nonexistent\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\terrText: \"failed to resolve middleware \\\"nonexistent\\\": middleware not found\",\n\t\t},\n\t\t{\n\t\t\tname: \"get_round_tripper_fails\",\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\tcomponent.MustNewID(\"errormw\"): extensionmiddlewaretest.NewErr(errors.New(\"http middleware error\")),\n\t\t\t},\n\t\t\tconfig: ClientConfig{\n\t\t\t\tEndpoint: server.URL,\n\t\t\t\tMiddlewares: []configmiddleware.Config{\n\t\t\t\t\t{\n\t\t\t\t\t\tID: component.MustNewID(\"errormw\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\terrText: \"http middleware error\",\n\t\t},\n\t}\n\n\tfor _, tc := range httpTests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t// Trying to create the client should fail\n\t\t\t_, err := tc.config.ToClient(context.Background(), tc.extensions, componenttest.NewNopTelemetrySettings())\n\t\t\trequire.Error(t, err)\n\t\t\tassert.Contains(t, err.Error(), tc.errText)\n\t\t})\n\t}\n}\n\n// Test failures for gRPC client middlewares by creating a mock implementation\n// that can fail in similar ways to HTTP clients\nfunc TestGRPCClientMiddlewareErrors(t *testing.T) {\n\t// Test cases for gRPC client middleware errors\n\tgrpcTests := []struct {\n\t\tname       string\n\t\textensions map[component.ID]component.Component\n\t\tconfig     ClientConfig\n\t\terrText    string\n\t}{\n\t\t{\n\t\t\tname:       \"grpc_extension_not_found\",\n\t\t\textensions: map[component.ID]component.Component{},\n\t\t\tconfig: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tMiddlewares: []configmiddleware.Config{\n\t\t\t\t\t{\n\t\t\t\t\t\tID: component.MustNewID(\"nonexistent\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\terrText: \"failed to resolve middleware \\\"nonexistent\\\": middleware not found\",\n\t\t},\n\t\t{\n\t\t\tname: \"grpc_get_client_options_fails\",\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\tcomponent.MustNewID(\"errormw\"): extensionmiddlewaretest.NewErr(errors.New(\"grpc middleware error\")),\n\t\t\t},\n\t\t\tconfig: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tMiddlewares: []configmiddleware.Config{\n\t\t\t\t\t{\n\t\t\t\t\t\tID: component.MustNewID(\"errormw\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\terrText: \"grpc middleware error\",\n\t\t},\n\t}\n\n\tfor _, tc := range grpcTests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t// For gRPC, we need to use the configgrpc.ClientConfig structure\n\t\t\t// We'll test the middleware failure path here using the HTTP client approach,\n\t\t\t// as the middleware resolution logic is the same\n\t\t\t_, err := tc.config.ToClient(context.Background(), tc.extensions, componenttest.NewNopTelemetrySettings())\n\t\t\trequire.Error(t, err)\n\t\t\tassert.Contains(t, err.Error(), tc.errText)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "config/confighttp/client_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confighttp\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"path/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/client\"\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configauth\"\n\t\"go.opentelemetry.io/collector/config/configcompression\"\n\t\"go.opentelemetry.io/collector/config/configmiddleware\"\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensionauth\"\n\t\"go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest\"\n)\n\nvar (\n\ttestAuthID    = component.MustNewID(\"testauth\")\n\tmockID        = component.MustNewID(\"mock\")\n\tdummyID       = component.MustNewID(\"dummy\")\n\tnonExistingID = component.MustNewID(\"nonexisting\")\n\t// Omit TracerProvider and MeterProvider in TelemetrySettings as otelhttp.Transport cannot be introspected\n\tnilProvidersSettings = component.TelemetrySettings{Logger: zap.NewNop()}\n)\n\nfunc TestAllHTTPClientSettings(t *testing.T) {\n\textensions := map[component.ID]component.Component{\n\t\ttestAuthID: extensionauthtest.NewNopClient(),\n\t}\n\n\tmaxIdleConns := 50\n\tmaxIdleConnsPerHost := 40\n\tmaxConnsPerHost := 45\n\tidleConnTimeout := 30 * time.Second\n\thttp2PingTimeout := 5 * time.Second\n\ttests := []struct {\n\t\tname        string\n\t\tsettings    ClientConfig\n\t\tshouldError bool\n\t}{\n\t\t{\n\t\t\tname: \"all_valid_settings\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tInsecure: false,\n\t\t\t\t},\n\t\t\t\tReadBufferSize:       1024,\n\t\t\t\tWriteBufferSize:      512,\n\t\t\t\tMaxIdleConns:         maxIdleConns,\n\t\t\t\tMaxIdleConnsPerHost:  maxIdleConnsPerHost,\n\t\t\t\tMaxConnsPerHost:      maxConnsPerHost,\n\t\t\t\tIdleConnTimeout:      idleConnTimeout,\n\t\t\t\tCompression:          \"\",\n\t\t\t\tDisableKeepAlives:    true,\n\t\t\t\tCookies:              configoptional.Some(CookiesConfig{}),\n\t\t\t\tHTTP2ReadIdleTimeout: idleConnTimeout,\n\t\t\t\tHTTP2PingTimeout:     http2PingTimeout,\n\t\t\t},\n\t\t\tshouldError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"all_valid_settings_http2_enabled\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tInsecure: false,\n\t\t\t\t},\n\t\t\t\tReadBufferSize:       1024,\n\t\t\t\tWriteBufferSize:      512,\n\t\t\t\tMaxIdleConns:         maxIdleConns,\n\t\t\t\tMaxIdleConnsPerHost:  maxIdleConnsPerHost,\n\t\t\t\tMaxConnsPerHost:      maxConnsPerHost,\n\t\t\t\tForceAttemptHTTP2:    true,\n\t\t\t\tIdleConnTimeout:      idleConnTimeout,\n\t\t\t\tCompression:          \"\",\n\t\t\t\tDisableKeepAlives:    true,\n\t\t\t\tCookies:              configoptional.Some(CookiesConfig{}),\n\t\t\t\tHTTP2ReadIdleTimeout: idleConnTimeout,\n\t\t\t\tHTTP2PingTimeout:     http2PingTimeout,\n\t\t\t},\n\t\t\tshouldError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"all_valid_settings_with_none_compression\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tInsecure: false,\n\t\t\t\t},\n\t\t\t\tReadBufferSize:       1024,\n\t\t\t\tWriteBufferSize:      512,\n\t\t\t\tMaxIdleConns:         maxIdleConns,\n\t\t\t\tMaxIdleConnsPerHost:  maxIdleConnsPerHost,\n\t\t\t\tMaxConnsPerHost:      maxConnsPerHost,\n\t\t\t\tIdleConnTimeout:      idleConnTimeout,\n\t\t\t\tCompression:          \"none\",\n\t\t\t\tDisableKeepAlives:    true,\n\t\t\t\tHTTP2ReadIdleTimeout: idleConnTimeout,\n\t\t\t\tHTTP2PingTimeout:     http2PingTimeout,\n\t\t\t},\n\t\t\tshouldError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"all_valid_settings_with_gzip_compression\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tInsecure: false,\n\t\t\t\t},\n\t\t\t\tReadBufferSize:       1024,\n\t\t\t\tWriteBufferSize:      512,\n\t\t\t\tMaxIdleConns:         maxIdleConns,\n\t\t\t\tMaxIdleConnsPerHost:  maxIdleConnsPerHost,\n\t\t\t\tMaxConnsPerHost:      maxConnsPerHost,\n\t\t\t\tIdleConnTimeout:      idleConnTimeout,\n\t\t\t\tCompression:          \"gzip\",\n\t\t\t\tDisableKeepAlives:    true,\n\t\t\t\tHTTP2ReadIdleTimeout: idleConnTimeout,\n\t\t\t\tHTTP2PingTimeout:     http2PingTimeout,\n\t\t\t},\n\t\t\tshouldError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"all_valid_settings_http2_health_check\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tInsecure: false,\n\t\t\t\t},\n\t\t\t\tReadBufferSize:       1024,\n\t\t\t\tWriteBufferSize:      512,\n\t\t\t\tMaxIdleConns:         maxIdleConns,\n\t\t\t\tMaxIdleConnsPerHost:  maxIdleConnsPerHost,\n\t\t\t\tMaxConnsPerHost:      maxConnsPerHost,\n\t\t\t\tIdleConnTimeout:      idleConnTimeout,\n\t\t\t\tCompression:          \"gzip\",\n\t\t\t\tDisableKeepAlives:    true,\n\t\t\t\tHTTP2ReadIdleTimeout: idleConnTimeout,\n\t\t\t\tHTTP2PingTimeout:     http2PingTimeout,\n\t\t\t},\n\t\t\tshouldError: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttel := componenttest.NewNopTelemetrySettings()\n\t\t\ttel.TracerProvider = nil\n\t\t\tclient, err := tt.settings.ToClient(context.Background(), extensions, tel)\n\t\t\tif tt.shouldError {\n\t\t\t\tassert.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\tswitch transport := client.Transport.(type) {\n\t\t\tcase *http.Transport:\n\t\t\t\tassert.Equal(t, 1024, transport.ReadBufferSize)\n\t\t\t\tassert.Equal(t, 512, transport.WriteBufferSize)\n\t\t\t\tassert.Equal(t, 50, transport.MaxIdleConns)\n\t\t\t\tassert.Equal(t, 40, transport.MaxIdleConnsPerHost)\n\t\t\t\tassert.Equal(t, 45, transport.MaxConnsPerHost)\n\t\t\t\tassert.Equal(t, 30*time.Second, transport.IdleConnTimeout)\n\t\t\t\tassert.True(t, transport.DisableKeepAlives)\n\t\t\tcase *compressRoundTripper:\n\t\t\t\tassert.EqualValues(t, \"gzip\", transport.compressionType)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestPartialHTTPClientSettings(t *testing.T) {\n\textensions := map[component.ID]component.Component{\n\t\ttestAuthID: extensionauthtest.NewNopClient(),\n\t}\n\n\ttests := []struct {\n\t\tname        string\n\t\tsettings    ClientConfig\n\t\tshouldError bool\n\t}{\n\t\t{\n\t\t\tname: \"valid_partial_settings\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tInsecure: false,\n\t\t\t\t},\n\t\t\t\tReadBufferSize:  1024,\n\t\t\t\tWriteBufferSize: 512,\n\t\t\t},\n\t\t\tshouldError: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttel := componenttest.NewNopTelemetrySettings()\n\t\t\ttel.TracerProvider = nil\n\t\t\tclient, err := tt.settings.ToClient(context.Background(), extensions, tel)\n\t\t\trequire.NoError(t, err)\n\t\t\ttransport := client.Transport.(*http.Transport)\n\t\t\tassert.Equal(t, 1024, transport.ReadBufferSize)\n\t\t\tassert.Equal(t, 512, transport.WriteBufferSize)\n\t\t\tassert.Equal(t, 0, transport.MaxIdleConns)\n\t\t\tassert.Equal(t, 0, transport.MaxIdleConnsPerHost)\n\t\t\tassert.Equal(t, 0, transport.MaxConnsPerHost)\n\t\t\tassert.EqualValues(t, 0, transport.IdleConnTimeout)\n\t\t\tassert.False(t, transport.DisableKeepAlives)\n\t\t})\n\t}\n}\n\nfunc TestDefaultHTTPClientSettings(t *testing.T) {\n\thttpClientSettings := NewDefaultClientConfig()\n\tassert.Equal(t, 100, httpClientSettings.MaxIdleConns)\n\tassert.Equal(t, 90*time.Second, httpClientSettings.IdleConnTimeout)\n}\n\nfunc TestProxyURL(t *testing.T) {\n\ttestCases := []struct {\n\t\tname        string\n\t\tproxyURL    string\n\t\texpectedURL *url.URL\n\t\terr         bool\n\t}{\n\t\t{\n\t\t\tname:        \"default config\",\n\t\t\texpectedURL: nil,\n\t\t},\n\t\t{\n\t\t\tname:        \"proxy is set\",\n\t\t\tproxyURL:    \"http://proxy.example.com:8080\",\n\t\t\texpectedURL: &url.URL{Scheme: \"http\", Host: \"proxy.example.com:8080\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"proxy is invalid\",\n\t\t\tproxyURL: \"://example.com\",\n\t\t\terr:      true,\n\t\t},\n\t}\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ts := NewDefaultClientConfig()\n\t\t\ts.ProxyURL = tt.proxyURL\n\n\t\t\ttel := componenttest.NewNopTelemetrySettings()\n\t\t\ttel.TracerProvider = nil\n\t\t\tclient, err := s.ToClient(context.Background(), nil, tel)\n\n\t\t\tif tt.err {\n\t\t\t\trequire.Error(t, err)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\n\t\t\tif err == nil {\n\t\t\t\ttransport := client.Transport.(*http.Transport)\n\t\t\t\trequire.NotNil(t, transport.Proxy)\n\n\t\t\t\turl, err := transport.Proxy(&http.Request{URL: &url.URL{Scheme: \"http\", Host: \"example.com\"}})\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\tif tt.expectedURL == nil {\n\t\t\t\t\tassert.Nil(t, url)\n\t\t\t\t} else {\n\t\t\t\t\trequire.NotNil(t, url)\n\t\t\t\t\tassert.Equal(t, tt.expectedURL, url)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestHTTPClientSettingsError(t *testing.T) {\n\textensions := map[component.ID]component.Component{}\n\ttests := []struct {\n\t\tsettings ClientConfig\n\t\terr      string\n\t}{\n\t\t{\n\t\t\terr: \"^failed to load TLS config: failed to load CA CertPool File: failed to load cert /doesnt/exist:\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"\",\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\tCAFile: \"/doesnt/exist\",\n\t\t\t\t\t},\n\t\t\t\t\tInsecure:   false,\n\t\t\t\t\tServerName: \"\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\terr: \"^failed to load TLS config: failed to load TLS cert and key: for auth via TLS, provide both certificate and key, or neither\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"\",\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\tCertFile: \"/doesnt/exist\",\n\t\t\t\t\t},\n\t\t\t\t\tInsecure:   false,\n\t\t\t\t\tServerName: \"\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\terr: \"failed to resolve authenticator \\\"dummy\\\": authenticator not found\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"https://localhost:1234/v1/traces\",\n\t\t\t\tAuth:     configoptional.Some(configauth.Config{AuthenticatorID: dummyID}),\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.err, func(t *testing.T) {\n\t\t\t_, err := tt.settings.ToClient(context.Background(), extensions, componenttest.NewNopTelemetrySettings())\n\t\t\tassert.Regexp(t, tt.err, err)\n\t\t})\n\t}\n}\n\nvar _ http.RoundTripper = &customRoundTripper{}\n\ntype customRoundTripper struct{}\n\nfunc (c *customRoundTripper) RoundTrip(*http.Request) (*http.Response, error) {\n\treturn nil, nil\n}\n\nvar (\n\t_ extensionauth.HTTPClient = (*mockClient)(nil)\n\t_ extension.Extension      = (*mockClient)(nil)\n)\n\ntype mockClient struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n}\n\n// RoundTripper implements extensionauth.HTTPClient.\nfunc (m *mockClient) RoundTripper(http.RoundTripper) (http.RoundTripper, error) {\n\treturn &customRoundTripper{}, nil\n}\n\nfunc TestHTTPClientSettingWithAuthConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\tshouldErr  bool\n\t\tsettings   ClientConfig\n\t\textensions map[component.ID]component.Component\n\t}{\n\t\t{\n\t\t\tname: \"no_auth_extension_enabled\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tAuth:     configoptional.None[configauth.Config](),\n\t\t\t},\n\t\t\tshouldErr: false,\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\tmockID: extensionauthtest.NewNopClient(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with_auth_configuration_and_no_extension\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tAuth:     configoptional.Some(configauth.Config{AuthenticatorID: dummyID}),\n\t\t\t},\n\t\t\tshouldErr: true,\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\tmockID: extensionauthtest.NewNopClient(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with_auth_configuration_and_no_extension_map\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tAuth:     configoptional.Some(configauth.Config{AuthenticatorID: dummyID}),\n\t\t\t},\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"with_auth_configuration_has_extension\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tAuth:     configoptional.Some(configauth.Config{AuthenticatorID: mockID}),\n\t\t\t},\n\t\t\tshouldErr: false,\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\tmockID: &mockClient{},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with_auth_configuration_has_extension_and_headers\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tAuth:     configoptional.Some(configauth.Config{AuthenticatorID: mockID}),\n\t\t\t\tHeaders: configopaque.MapList{\n\t\t\t\t\t{Name: \"foo\", Value: \"bar\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\tshouldErr: false,\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\tmockID: &mockClient{},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with_auth_configuration_has_extension_and_compression\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint:    \"localhost:1234\",\n\t\t\t\tAuth:        configoptional.Some(configauth.Config{AuthenticatorID: mockID}),\n\t\t\t\tCompression: configcompression.TypeGzip,\n\t\t\t},\n\t\t\tshouldErr: false,\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\tmockID: &mockClient{},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with_auth_configuration_has_err_extension\",\n\t\t\tsettings: ClientConfig{\n\t\t\t\tEndpoint: \"localhost:1234\",\n\t\t\t\tAuth:     configoptional.Some(configauth.Config{AuthenticatorID: mockID}),\n\t\t\t},\n\t\t\tshouldErr: true,\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\tmockID: extensionauthtest.NewErr(errors.New(\"error\")),\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// Omit TracerProvider and MeterProvider in TelemetrySettings as otelhttp.Transport cannot be introspected\n\t\t\tclient, err := tt.settings.ToClient(context.Background(), tt.extensions, nilProvidersSettings)\n\t\t\tif tt.shouldErr {\n\t\t\t\tassert.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.NotNil(t, client)\n\t\t\ttransport := client.Transport\n\n\t\t\t// Compression should wrap Auth, unwrap it\n\t\t\tif tt.settings.Compression.IsCompressed() {\n\t\t\t\tct, ok := transport.(*compressRoundTripper)\n\t\t\t\tassert.True(t, ok)\n\t\t\t\tassert.Equal(t, tt.settings.Compression, ct.compressionType)\n\t\t\t\ttransport = ct.rt\n\t\t\t}\n\n\t\t\t// Headers should wrap Auth, unwrap it\n\t\t\tif tt.settings.Headers != nil {\n\t\t\t\tht, ok := transport.(*headerRoundTripper)\n\t\t\t\tassert.True(t, ok)\n\t\t\t\tassert.Equal(t, tt.settings.Headers, ht.headers)\n\t\t\t\ttransport = ht.transport\n\t\t\t}\n\n\t\t\tif tt.settings.Auth.HasValue() {\n\t\t\t\t_, ok := transport.(*customRoundTripper)\n\t\t\t\tassert.True(t, ok)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestHTTPClientHeaders(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\theaders configopaque.MapList\n\t}{\n\t\t{\n\t\t\tname: \"with_headers\",\n\t\t\theaders: configopaque.MapList{\n\t\t\t\t{Name: \"header1\", Value: \"value1\"},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tfor k, v := range tt.headers.Iter {\n\t\t\t\t\tassert.Equal(t, r.Header.Get(k), string(v))\n\t\t\t\t}\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t}))\n\t\t\tdefer server.Close()\n\t\t\tserverURL, _ := url.Parse(server.URL)\n\t\t\tsetting := ClientConfig{\n\t\t\t\tEndpoint:        serverURL.String(),\n\t\t\t\tTLS:             configtls.ClientConfig{},\n\t\t\t\tReadBufferSize:  0,\n\t\t\t\tWriteBufferSize: 0,\n\t\t\t\tTimeout:         0,\n\t\t\t\tHeaders:         tt.headers,\n\t\t\t}\n\t\t\tclient, _ := setting.ToClient(context.Background(), nil, componenttest.NewNopTelemetrySettings())\n\t\t\treq, err := http.NewRequest(http.MethodGet, setting.Endpoint, http.NoBody)\n\t\t\trequire.NoError(t, err)\n\t\t\t_, err = client.Do(req)\n\t\t\tassert.NoError(t, err)\n\t\t})\n\t}\n}\n\nfunc TestHTTPClientHostHeader(t *testing.T) {\n\thostHeader := \"th\"\n\ttt := struct {\n\t\tname    string\n\t\theaders configopaque.MapList\n\t}{\n\t\tname: \"with_host_header\",\n\t\theaders: configopaque.MapList{\n\t\t\t{Name: \"Host\", Value: configopaque.String(hostHeader)},\n\t\t},\n\t}\n\n\tt.Run(tt.name, func(t *testing.T) {\n\t\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tassert.Equal(t, hostHeader, r.Host)\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t}))\n\t\tdefer server.Close()\n\t\tserverURL, _ := url.Parse(server.URL)\n\t\tsetting := ClientConfig{\n\t\t\tEndpoint:        serverURL.String(),\n\t\t\tTLS:             configtls.ClientConfig{},\n\t\t\tReadBufferSize:  0,\n\t\t\tWriteBufferSize: 0,\n\t\t\tTimeout:         0,\n\t\t\tHeaders:         tt.headers,\n\t\t}\n\t\tclient, _ := setting.ToClient(context.Background(), nil, componenttest.NewNopTelemetrySettings())\n\t\treq, err := http.NewRequest(http.MethodGet, setting.Endpoint, http.NoBody)\n\t\trequire.NoError(t, err)\n\t\t_, err = client.Do(req)\n\t\tassert.NoError(t, err)\n\t})\n}\n\nfunc TestHTTPTransportOptions(t *testing.T) {\n\tsettings := componenttest.NewNopTelemetrySettings()\n\t// Disable OTel instrumentation so the *http.Transport object is directly accessible\n\tsettings.MeterProvider = nil\n\tsettings.TracerProvider = nil\n\n\tclientConfig := NewDefaultClientConfig()\n\tclientConfig.MaxIdleConns = 100\n\tclientConfig.IdleConnTimeout = time.Duration(100)\n\tclientConfig.MaxConnsPerHost = 100\n\tclientConfig.MaxIdleConnsPerHost = 100\n\tclient, err := clientConfig.ToClient(context.Background(), nil, settings)\n\trequire.NoError(t, err)\n\ttransport, ok := client.Transport.(*http.Transport)\n\trequire.True(t, ok, \"client.Transport is not an *http.Transport\")\n\trequire.Equal(t, 100, transport.MaxIdleConns)\n\trequire.Equal(t, time.Duration(100), transport.IdleConnTimeout)\n\trequire.Equal(t, 100, transport.MaxConnsPerHost)\n\trequire.Equal(t, 100, transport.MaxIdleConnsPerHost)\n\n\tclientConfig = NewDefaultClientConfig()\n\tclientConfig.MaxIdleConns = 0\n\tclientConfig.IdleConnTimeout = 0\n\tclientConfig.MaxConnsPerHost = 0\n\tclientConfig.IdleConnTimeout = time.Duration(0)\n\tclient, err = clientConfig.ToClient(context.Background(), nil, settings)\n\trequire.NoError(t, err)\n\ttransport, ok = client.Transport.(*http.Transport)\n\trequire.True(t, ok, \"client.Transport is not an *http.Transport\")\n\trequire.Equal(t, 0, transport.MaxIdleConns)\n\trequire.Equal(t, time.Duration(0), transport.IdleConnTimeout)\n\trequire.Equal(t, 0, transport.MaxConnsPerHost)\n\trequire.Equal(t, 0, transport.MaxIdleConnsPerHost)\n}\n\nfunc TestContextWithClient(t *testing.T) {\n\ttestCases := []struct {\n\t\tname       string\n\t\tinput      *http.Request\n\t\tdoMetadata bool\n\t\texpected   client.Info\n\t}{\n\t\t{\n\t\t\tname:     \"request without client IP or headers\",\n\t\t\tinput:    &http.Request{},\n\t\t\texpected: client.Info{},\n\t\t},\n\t\t{\n\t\t\tname: \"request with client IP\",\n\t\t\tinput: &http.Request{\n\t\t\t\tRemoteAddr: \"1.2.3.4:55443\",\n\t\t\t},\n\t\t\texpected: client.Info{\n\t\t\t\tAddr: &net.IPAddr{\n\t\t\t\t\tIP: net.IPv4(1, 2, 3, 4),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"request with client headers, no metadata processing\",\n\t\t\tinput: &http.Request{\n\t\t\t\tHeader: map[string][]string{\"x-tt-header\": {\"tt-value\"}},\n\t\t\t},\n\t\t\tdoMetadata: false,\n\t\t\texpected:   client.Info{},\n\t\t},\n\t\t{\n\t\t\tname: \"request with client headers\",\n\t\t\tinput: &http.Request{\n\t\t\t\tHeader: map[string][]string{\"x-tt-header\": {\"tt-value\"}},\n\t\t\t},\n\t\t\tdoMetadata: true,\n\t\t\texpected: client.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\"x-tt-header\": {\"tt-value\"}}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"request with Host and client headers\",\n\t\t\tinput: &http.Request{\n\t\t\t\tHeader: map[string][]string{\"x-tt-header\": {\"tt-value\"}},\n\t\t\t\tHost:   \"localhost:55443\",\n\t\t\t},\n\t\t\tdoMetadata: true,\n\t\t\texpected: client.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\"x-tt-header\": {\"tt-value\"}, \"Host\": {\"localhost:55443\"}}),\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tctx := contextWithClient(tt.input, tt.doMetadata)\n\t\t\tassert.Equal(t, tt.expected, client.FromContext(ctx))\n\t\t})\n\t}\n}\n\n// TestUnmarshalYAMLWithMiddlewares tests that the \"middlewares\" field is correctly\n// parsed from YAML configurations (fixing the bug where \"middleware\" was used instead)\nfunc TestClientUnmarshalYAMLWithMiddlewares(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"middlewares.yaml\"))\n\trequire.NoError(t, err)\n\n\t// Test client configuration\n\tvar clientConfig ClientConfig\n\tclientSub, err := cm.Sub(\"client\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, clientSub.Unmarshal(&clientConfig))\n\n\t// Validate the client configuration using reflection-based validation\n\trequire.NoError(t, xconfmap.Validate(&clientConfig), \"Client configuration should be valid\")\n\n\tassert.Equal(t, \"http://localhost:4318/v1/traces\", clientConfig.Endpoint)\n\trequire.Len(t, clientConfig.Middlewares, 2)\n\tassert.Equal(t, component.MustNewID(\"fancy_middleware\"), clientConfig.Middlewares[0].ID)\n\tassert.Equal(t, component.MustNewID(\"careful_middleware\"), clientConfig.Middlewares[1].ID)\n}\n\n// TestUnmarshalYAMLComprehensiveConfig tests the complete configuration example\n// to ensure all fields including middlewares are parsed correctly\nfunc TestClientUnmarshalYAMLComprehensiveConfig(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\n\t// Test client configuration\n\tvar clientConfig ClientConfig\n\tclientSub, err := cm.Sub(\"client\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, clientSub.Unmarshal(&clientConfig))\n\n\t// Validate the client configuration using reflection-based validation\n\trequire.NoError(t, xconfmap.Validate(&clientConfig), \"Client configuration should be valid\")\n\n\t// Verify basic fields\n\tassert.Equal(t, \"http://example.com:4318/v1/traces\", clientConfig.Endpoint)\n\tassert.Equal(t, \"http://proxy.example.com:8080\", clientConfig.ProxyURL)\n\tassert.Equal(t, 30*time.Second, clientConfig.Timeout)\n\tassert.Equal(t, 4096, clientConfig.ReadBufferSize)\n\tassert.Equal(t, 4096, clientConfig.WriteBufferSize)\n\tassert.Equal(t, configcompression.TypeGzip, clientConfig.Compression)\n\n\t// Verify TLS configuration\n\tassert.False(t, clientConfig.TLS.Insecure)\n\tassert.Equal(t, \"/path/to/client.crt\", clientConfig.TLS.CertFile)\n\tassert.Equal(t, \"/path/to/client.key\", clientConfig.TLS.KeyFile)\n\tassert.Equal(t, \"/path/to/ca.crt\", clientConfig.TLS.CAFile)\n\tassert.Equal(t, \"example.com\", clientConfig.TLS.ServerName)\n\n\t// Verify headers\n\texpectedHeaders := configopaque.MapList{\n\t\t{Name: \"User-Agent\", Value: \"OpenTelemetry-Collector/1.0\"},\n\t\t{Name: \"X-Custom-Header\", Value: \"custom-value\"},\n\t}\n\tassert.Equal(t, expectedHeaders, clientConfig.Headers)\n\n\t// Verify middlewares\n\trequire.Len(t, clientConfig.Middlewares, 2)\n\tassert.Equal(t, component.MustNewID(\"middleware1\"), clientConfig.Middlewares[0].ID)\n\tassert.Equal(t, component.MustNewID(\"middleware2\"), clientConfig.Middlewares[1].ID)\n}\n\n// TestMiddlewaresFieldCompatibility tests that the new \"middlewares\" field name\n// is used instead of the old \"middleware\" name, ensuring the bug is fixed\nfunc TestClientMiddlewaresFieldCompatibility(t *testing.T) {\n\t// Test that we can create a config with middlewares using the new field name\n\tclientConfig := ClientConfig{\n\t\tEndpoint: \"http://localhost:4318\",\n\t\tMiddlewares: []configmiddleware.Config{\n\t\t\t{ID: component.MustNewID(\"test_middleware\")},\n\t\t},\n\t}\n\tassert.Equal(t, \"http://localhost:4318\", clientConfig.Endpoint)\n\tassert.Len(t, clientConfig.Middlewares, 1)\n\tassert.Equal(t, component.MustNewID(\"test_middleware\"), clientConfig.Middlewares[0].ID)\n}\n"
  },
  {
    "path": "config/confighttp/clientinfohandler.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confighttp // import \"go.opentelemetry.io/collector/config/confighttp\"\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"net/http\"\n\n\t\"go.opentelemetry.io/collector/client\"\n)\n\n// clientInfoHandler is an http.Handler that enhances the incoming request context with client.Info.\ntype clientInfoHandler struct {\n\tnext http.Handler\n\n\t// include client metadata or not\n\tincludeMetadata bool\n}\n\n// ServeHTTP intercepts incoming HTTP requests, replacing the request's context with one that contains\n// a client.Info containing the client's IP address.\nfunc (h *clientInfoHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {\n\treq = req.WithContext(contextWithClient(req, h.includeMetadata)) //nolint:contextcheck //context already handled through contextWithClient\n\th.next.ServeHTTP(w, req)\n}\n\n// contextWithClient attempts to add the client IP address to the client.Info from the context. When no\n// client.Info exists in the context, one is created.\nfunc contextWithClient(req *http.Request, includeMetadata bool) context.Context {\n\tcl := client.FromContext(req.Context())\n\n\tip := parseIP(req.RemoteAddr)\n\tif ip != nil {\n\t\tcl.Addr = ip\n\t}\n\n\tif includeMetadata {\n\t\tmd := req.Header.Clone()\n\t\tif md.Get(client.MetadataHostName) == \"\" && req.Host != \"\" {\n\t\t\tmd.Add(client.MetadataHostName, req.Host)\n\t\t}\n\n\t\tcl.Metadata = client.NewMetadata(md)\n\t}\n\n\tctx := client.NewContext(req.Context(), cl)\n\treturn ctx\n}\n\n// parseIP parses the given string for an IP address. The input string might contain the port,\n// but must not contain a protocol or path. Suitable for getting the IP part of a client connection.\nfunc parseIP(source string) *net.IPAddr {\n\tipstr, _, err := net.SplitHostPort(source)\n\tif err == nil {\n\t\tsource = ipstr\n\t}\n\tip := net.ParseIP(source)\n\tif ip != nil {\n\t\treturn &net.IPAddr{\n\t\t\tIP: ip,\n\t\t}\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "config/confighttp/clientinfohandler_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confighttp // import \"go.opentelemetry.io/collector/config/confighttp\"\n\nimport (\n\t\"net\"\n\t\"net/http\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nvar _ http.Handler = (*clientInfoHandler)(nil)\n\nfunc TestParseIP(t *testing.T) {\n\ttestCases := []struct {\n\t\tname     string\n\t\tinput    string\n\t\texpected *net.IPAddr\n\t}{\n\t\t{\n\t\t\tname:  \"addr\",\n\t\t\tinput: \"1.2.3.4\",\n\t\t\texpected: &net.IPAddr{\n\t\t\t\tIP: net.IPv4(1, 2, 3, 4),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:  \"addr:port\",\n\t\t\tinput: \"1.2.3.4:33455\",\n\t\t\texpected: &net.IPAddr{\n\t\t\t\tIP: net.IPv4(1, 2, 3, 4),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:     \"protocol://addr:port\",\n\t\t\tinput:    \"http://1.2.3.4:33455\",\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tname:     \"addr/path\",\n\t\t\tinput:    \"1.2.3.4/orders\",\n\t\t\texpected: nil,\n\t\t},\n\t}\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tassert.Equal(t, tt.expected, parseIP(tt.input))\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "config/confighttp/compress_readcloser.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confighttp // import \"go.opentelemetry.io/collector/config/confighttp\"\n\nimport \"io\"\n\n// compressReadCloser couples the original compressed reader\n// and the compression reader to ensure that the original body\n// is correctly closed to ensure resources are freed.\ntype compressReadCloser struct {\n\tio.Reader\n\torig io.ReadCloser\n}\n\nvar (\n\t_ io.Reader = (*compressReadCloser)(nil)\n\t_ io.Closer = (*compressReadCloser)(nil)\n)\n\nfunc (crc *compressReadCloser) Close() error {\n\treturn crc.orig.Close()\n}\n"
  },
  {
    "path": "config/confighttp/compress_readcloser_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confighttp\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"io\"\n\t\"testing\"\n\t\"testing/iotest\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\ntype errorReadCloser struct {\n\tio.Reader\n\terr error\n}\n\nfunc (erc errorReadCloser) Close() error {\n\treturn erc.err\n}\n\nfunc TestCompressReadCloser(t *testing.T) {\n\tt.Parallel()\n\n\tfor _, tc := range []struct {\n\t\tname    string\n\t\twrapper func(r io.Reader) io.ReadCloser\n\t\tcontent []byte\n\t\terrVal  string\n\t}{\n\t\t{\n\t\t\tname: \"non mutating wrapper\",\n\t\t\twrapper: func(r io.Reader) io.ReadCloser {\n\t\t\t\treturn errorReadCloser{\n\t\t\t\t\tReader: r,\n\t\t\t\t\terr:    nil,\n\t\t\t\t}\n\t\t\t},\n\t\t\tcontent: []byte(\"hello world\"),\n\t\t\terrVal:  \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"failed reader\",\n\t\t\twrapper: func(r io.Reader) io.ReadCloser {\n\t\t\t\treturn errorReadCloser{\n\t\t\t\t\tReader: r,\n\t\t\t\t\terr:    errors.New(\"failed to close reader\"),\n\t\t\t\t}\n\t\t\t},\n\t\t\terrVal: \"failed to close reader\",\n\t\t},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\n\t\t\torig := bytes.NewBuffer([]byte(\"hello world\"))\n\n\t\t\tcrc := &compressReadCloser{\n\t\t\t\tReader: orig,\n\t\t\t\torig:   tc.wrapper(orig),\n\t\t\t}\n\n\t\t\trequire.NoError(t, iotest.TestReader(crc, orig.Bytes()), \"Must be able to read original content\")\n\n\t\t\terr := crc.Close()\n\t\t\tif tc.errVal != \"\" {\n\t\t\t\trequire.EqualError(t, err, tc.errVal, \"Must match the expected error message\")\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err, \"Must not error when closing reader\")\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "config/confighttp/compression.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// This file contains helper functions regarding compression/decompression for confighttp.\n\npackage confighttp // import \"go.opentelemetry.io/collector/config/confighttp\"\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"compress/zlib\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"maps\"\n\t\"net/http\"\n\t\"sync\"\n\n\t\"github.com/golang/snappy\"\n\t\"github.com/klauspost/compress/zstd\"\n\t\"github.com/pierrec/lz4/v4\"\n\n\t\"go.opentelemetry.io/collector/config/configcompression\"\n\t\"go.opentelemetry.io/collector/config/confighttp/internal/metadata\"\n)\n\nfunc defaultCompressionAlgorithms() []string {\n\tif metadata.ConfighttpFramedSnappyFeatureGate.IsEnabled() {\n\t\treturn []string{\"\", \"gzip\", \"zstd\", \"zlib\", \"snappy\", \"deflate\", \"lz4\", \"x-snappy-framed\"}\n\t}\n\treturn []string{\"\", \"gzip\", \"zstd\", \"zlib\", \"snappy\", \"deflate\", \"lz4\"}\n}\n\ntype compressRoundTripper struct {\n\trt                http.RoundTripper\n\tcompressionType   configcompression.Type\n\tcompressionParams configcompression.CompressionParams\n\tcompressor        *compressor\n}\n\nvar zstdReaderPool sync.Pool\n\ntype pooledZstdReadCloser struct {\n\tinner *zstd.Decoder\n}\n\nfunc (pzrc *pooledZstdReadCloser) Read(dst []byte) (int, error) {\n\tif pzrc.inner == nil {\n\t\treturn 0, zstd.ErrDecoderClosed\n\t}\n\treturn pzrc.inner.Read(dst)\n}\n\nfunc (pzrc *pooledZstdReadCloser) Close() error {\n\tif pzrc.inner != nil {\n\t\terr := pzrc.inner.Reset(nil)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tzstdReaderPool.Put(pzrc.inner)\n\t\tpzrc.inner = nil\n\t}\n\treturn nil\n}\n\nvar availableDecoders = map[string]func(body io.ReadCloser) (io.ReadCloser, error){\n\t\"\": func(io.ReadCloser) (io.ReadCloser, error) {\n\t\t// Not a compressed payload. Nothing to do.\n\t\treturn nil, nil\n\t},\n\t\"gzip\": func(body io.ReadCloser) (io.ReadCloser, error) {\n\t\tgr, err := gzip.NewReader(body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn gr, nil\n\t},\n\t\"zstd\": func(body io.ReadCloser) (io.ReadCloser, error) {\n\t\tv := zstdReaderPool.Get()\n\t\tvar zr *zstd.Decoder\n\t\tvar err error\n\t\tif v == nil {\n\t\t\t// NOTE(tigrannajaryan):\n\t\t\t// Concurrency 1 disables async decoding. We don't need async decoding, it is pointless\n\t\t\t// for our use-case (a server accepting decoding http requests).\n\t\t\t// Disabling async improves performance (I benchmarked it previously when working\n\t\t\t// on https://github.com/open-telemetry/opentelemetry-collector-contrib/pull/23257).\n\t\t\tzr, err = zstd.NewReader(body, zstd.WithDecoderConcurrency(1))\n\t\t} else {\n\t\t\tzr = v.(*zstd.Decoder)\n\t\t\terr = zr.Reset(body)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn &pooledZstdReadCloser{inner: zr}, nil\n\t},\n\t\"zlib\": func(body io.ReadCloser) (io.ReadCloser, error) {\n\t\tzr, err := zlib.NewReader(body)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn zr, nil\n\t},\n\t\"snappy\": snappyHandler,\n\t//nolint:unparam // Ignoring the linter request to remove error return since it needs to match the method signature\n\t\"lz4\": func(body io.ReadCloser) (io.ReadCloser, error) {\n\t\treturn &compressReadCloser{\n\t\t\tReader: lz4.NewReader(body),\n\t\t\torig:   body,\n\t\t}, nil\n\t},\n\t//nolint:unparam // Ignoring the linter request to remove error return since it needs to match the method signature\n\t\"x-snappy-framed\": func(body io.ReadCloser) (io.ReadCloser, error) {\n\t\treturn &compressReadCloser{\n\t\t\tReader: snappy.NewReader(body),\n\t\t\torig:   body,\n\t\t}, nil\n\t},\n}\n\n// snappyFramingHeader is always the first 10 bytes of a snappy framed stream.\nvar snappyFramingHeader = []byte{\n\t0xff, 0x06, 0x00, 0x00,\n\t0x73, 0x4e, 0x61, 0x50, 0x70, 0x59, // \"sNaPpY\"\n}\n\n// snappyHandler returns an io.ReadCloser that auto-detects the snappy format.\n// This is necessary because the collector previously used \"content-encoding: snappy\"\n// but decompressed and compressed the payloads using the snappy framing format.\n// However, \"content-encoding: snappy\" is uses the block format, and \"x-snappy-framed\"\n// is the framing format.  This handler is a (hopefully temporary) hack to\n// make this work in a backwards-compatible way.\n//\n// See https://github.com/google/snappy/blob/6af9287fbdb913f0794d0148c6aa43b58e63c8e3/framing_format.txt#L27-L36\n// for more details on the framing format.\nfunc snappyHandler(body io.ReadCloser) (io.ReadCloser, error) {\n\tbr := bufio.NewReader(body)\n\n\tpeekBytes, err := br.Peek(len(snappyFramingHeader))\n\tif err != nil && !errors.Is(err, io.EOF) {\n\t\treturn nil, err\n\t}\n\n\tisFramed := len(peekBytes) >= len(snappyFramingHeader) && bytes.Equal(peekBytes[:len(snappyFramingHeader)], snappyFramingHeader)\n\n\tif isFramed {\n\t\treturn &compressReadCloser{\n\t\t\tReader: snappy.NewReader(br),\n\t\t\torig:   body,\n\t\t}, nil\n\t}\n\tcompressed, err := io.ReadAll(br)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdecoded, err := snappy.Decode(nil, compressed)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn io.NopCloser(bytes.NewReader(decoded)), nil\n}\n\nfunc newCompressionParams(level configcompression.Level) configcompression.CompressionParams {\n\treturn configcompression.CompressionParams{\n\t\tLevel: level,\n\t}\n}\n\nfunc newCompressRoundTripper(rt http.RoundTripper, compressionType configcompression.Type, compressionParams configcompression.CompressionParams) (*compressRoundTripper, error) {\n\tencoder, err := newCompressor(compressionType, compressionParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &compressRoundTripper{\n\t\trt:                rt,\n\t\tcompressionType:   compressionType,\n\t\tcompressionParams: compressionParams,\n\t\tcompressor:        encoder,\n\t}, nil\n}\n\nfunc (r *compressRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {\n\tif req.Header.Get(headerContentEncoding) != \"\" {\n\t\t// If the header already specifies a content encoding then skip compression\n\t\t// since we don't want to compress it again. This is a safeguard that normally\n\t\t// should not happen since CompressRoundTripper is not intended to be used\n\t\t// with http clients which already do their own compression.\n\t\treturn r.rt.RoundTrip(req)\n\t}\n\n\t// Compress the body.\n\tbuf := bytes.NewBuffer([]byte{})\n\tif err := r.compressor.compress(buf, req.Body); err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Create a new request since the docs say that we cannot modify the \"req\"\n\t// (see https://golang.org/pkg/net/http/#RoundTripper).\n\tcReq, err := http.NewRequestWithContext(req.Context(), req.Method, req.URL.String(), buf)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Clone the headers and add the encoding header.\n\tcReq.Header = req.Header.Clone()\n\tcReq.Header.Add(headerContentEncoding, string(r.compressionType))\n\n\treturn r.rt.RoundTrip(cReq)\n}\n\ntype decompressor struct {\n\terrHandler         func(w http.ResponseWriter, r *http.Request, errorMsg string, statusCode int)\n\tbase               http.Handler\n\tdecoders           map[string]func(body io.ReadCloser) (io.ReadCloser, error)\n\tmaxRequestBodySize int64\n}\n\n// httpContentDecompressor offloads the task of handling compressed HTTP requests\n// by identifying the compression format in the \"Content-Encoding\" header and re-writing\n// request body so that the handlers further in the chain can work on decompressed data.\nfunc httpContentDecompressor(h http.Handler, maxRequestBodySize int64, eh func(w http.ResponseWriter, r *http.Request, errorMsg string, statusCode int), enableDecoders []string, decoders map[string]func(body io.ReadCloser) (io.ReadCloser, error)) http.Handler {\n\terrHandler := defaultErrorHandler\n\tif eh != nil {\n\t\terrHandler = eh\n\t}\n\n\tenabled := map[string]func(body io.ReadCloser) (io.ReadCloser, error){}\n\tfor _, dec := range enableDecoders {\n\t\tif dec == \"x-frame-snappy\" && !metadata.ConfighttpFramedSnappyFeatureGate.IsEnabled() {\n\t\t\tcontinue\n\t\t}\n\t\tenabled[dec] = availableDecoders[dec]\n\n\t\tif dec == \"deflate\" {\n\t\t\tenabled[\"deflate\"] = availableDecoders[\"zlib\"]\n\t\t}\n\t}\n\n\td := &decompressor{\n\t\tmaxRequestBodySize: maxRequestBodySize,\n\t\terrHandler:         errHandler,\n\t\tbase:               h,\n\t\tdecoders:           enabled,\n\t}\n\n\tmaps.Copy(d.decoders, decoders)\n\n\treturn d\n}\n\nfunc (d *decompressor) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tnewBody, err := d.newBodyReader(r)\n\tif err != nil {\n\t\td.errHandler(w, r, err.Error(), http.StatusBadRequest)\n\t\treturn\n\t}\n\tif newBody != nil {\n\t\tdefer newBody.Close()\n\t\t// \"Content-Encoding\" header is removed to avoid decompressing twice\n\t\t// in case the next handler(s) have implemented a similar mechanism.\n\t\tr.Header.Del(\"Content-Encoding\")\n\t\t// \"Content-Length\" is set to -1 as the size of the decompressed body is unknown.\n\t\tr.Header.Del(\"Content-Length\")\n\t\tr.ContentLength = -1\n\t\tr.Body = http.MaxBytesReader(w, newBody, d.maxRequestBodySize)\n\t}\n\td.base.ServeHTTP(w, r)\n}\n\nfunc (d *decompressor) newBodyReader(r *http.Request) (io.ReadCloser, error) {\n\tif len(d.decoders) == 0 {\n\t\treturn nil, nil // Signal: don't replace r.Body\n\t}\n\tencoding := r.Header.Get(headerContentEncoding)\n\n\tdecoder, ok := d.decoders[encoding]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"unsupported %s: %s\", headerContentEncoding, encoding)\n\t}\n\treturn decoder(r.Body)\n}\n\n// defaultErrorHandler writes the error message in plain text.\nfunc defaultErrorHandler(w http.ResponseWriter, _ *http.Request, errMsg string, statusCode int) {\n\thttp.Error(w, errMsg, statusCode)\n}\n"
  },
  {
    "path": "config/confighttp/compression_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confighttp\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"compress/zlib\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\t\"testing\"\n\t\"testing/iotest\"\n\n\t\"github.com/golang/snappy\"\n\t\"github.com/klauspost/compress/zstd\"\n\t\"github.com/pierrec/lz4/v4\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configcompression\"\n\t\"go.opentelemetry.io/collector/config/confighttp/internal/metadata\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\nfunc TestHTTPClientCompression(t *testing.T) {\n\ttestBody := []byte(\"uncompressed_text\")\n\tcompressedGzipBody := compressGzip(t, testBody)\n\tcompressedZlibBody := compressZlib(t, testBody)\n\tcompressedDeflateBody := compressZlib(t, testBody)\n\tcompressedSnappyFramedBody := compressSnappyFramed(t, testBody)\n\tcompressedSnappyBody := compressSnappy(t, testBody)\n\tcompressedZstdBody := compressZstd(t, testBody)\n\tcompressedLz4Body := compressLz4(t, testBody)\n\n\tconst invalidGzipLevel configcompression.Level = 100\n\n\ttests := []struct {\n\t\tname                string\n\t\tencoding            configcompression.Type\n\t\tlevel               configcompression.Level\n\t\tframedSnappyEnabled bool\n\t\treqBody             []byte\n\t\tshouldError         bool\n\t}{\n\t\t{\n\t\t\tname:        \"ValidEmpty\",\n\t\t\tencoding:    \"\",\n\t\t\treqBody:     testBody,\n\t\t\tshouldError: false,\n\t\t},\n\t\t{\n\t\t\tname:        \"ValidNone\",\n\t\t\tencoding:    \"none\",\n\t\t\treqBody:     testBody,\n\t\t\tshouldError: false,\n\t\t},\n\t\t{\n\t\t\tname:        \"ValidGzip\",\n\t\t\tencoding:    configcompression.TypeGzip,\n\t\t\tlevel:       gzip.DefaultCompression,\n\t\t\treqBody:     compressedGzipBody.Bytes(),\n\t\t\tshouldError: false,\n\t\t},\n\t\t{\n\t\t\tname:        \"ValidGzip-DefaultLevel\",\n\t\t\tencoding:    configcompression.TypeGzip,\n\t\t\treqBody:     compressedGzipBody.Bytes(),\n\t\t\tshouldError: false,\n\t\t},\n\t\t{\n\t\t\tname:        \"InvalidGzip\",\n\t\t\tencoding:    configcompression.TypeGzip,\n\t\t\tlevel:       invalidGzipLevel,\n\t\t\treqBody:     compressedGzipBody.Bytes(),\n\t\t\tshouldError: true,\n\t\t},\n\t\t{\n\t\t\tname:        \"InvalidCompression\",\n\t\t\tencoding:    configcompression.Type(\"invalid\"),\n\t\t\tlevel:       invalidGzipLevel,\n\t\t\treqBody:     compressedGzipBody.Bytes(),\n\t\t\tshouldError: true,\n\t\t},\n\t\t{\n\t\t\tname:        \"ValidZlib\",\n\t\t\tencoding:    configcompression.TypeZlib,\n\t\t\tlevel:       gzip.DefaultCompression,\n\t\t\treqBody:     compressedZlibBody.Bytes(),\n\t\t\tshouldError: false,\n\t\t},\n\t\t{\n\t\t\tname:        \"ValidDeflate\",\n\t\t\tencoding:    configcompression.TypeDeflate,\n\t\t\tlevel:       gzip.DefaultCompression,\n\t\t\treqBody:     compressedDeflateBody.Bytes(),\n\t\t\tshouldError: false,\n\t\t},\n\t\t{\n\t\t\tname:                \"ValidSnappy\",\n\t\t\tencoding:            configcompression.TypeSnappy,\n\t\t\tframedSnappyEnabled: true,\n\t\t\treqBody:             compressedSnappyBody.Bytes(),\n\t\t\tshouldError:         false,\n\t\t},\n\t\t{\n\t\t\tname:        \"InvalidSnappy\",\n\t\t\tencoding:    configcompression.TypeSnappy,\n\t\t\tlevel:       gzip.DefaultCompression,\n\t\t\treqBody:     compressedSnappyBody.Bytes(),\n\t\t\tshouldError: true,\n\t\t},\n\t\t{\n\t\t\tname:                \"ValidSnappyFramed\",\n\t\t\tencoding:            configcompression.TypeSnappyFramed,\n\t\t\tframedSnappyEnabled: true,\n\t\t\treqBody:             compressedSnappyFramedBody.Bytes(),\n\t\t\tshouldError:         false,\n\t\t},\n\t\t{\n\t\t\tname:        \"InvalidSnappyFramed\",\n\t\t\tencoding:    configcompression.TypeSnappyFramed,\n\t\t\tlevel:       gzip.DefaultCompression,\n\t\t\treqBody:     compressedSnappyFramedBody.Bytes(),\n\t\t\tshouldError: true,\n\t\t},\n\t\t{\n\t\t\tname:        \"ValidZstd\",\n\t\t\tencoding:    configcompression.TypeZstd,\n\t\t\tlevel:       99,\n\t\t\treqBody:     compressedZstdBody.Bytes(),\n\t\t\tshouldError: false,\n\t\t},\n\t\t{\n\t\t\tname:        \"ValidLz4\",\n\t\t\tencoding:    configcompression.TypeLz4,\n\t\t\treqBody:     compressedLz4Body.Bytes(),\n\t\t\tshouldError: false,\n\t\t},\n\t\t{\n\t\t\tname:        \"InvalidLz4\",\n\t\t\tencoding:    configcompression.TypeLz4,\n\t\t\tlevel:       gzip.DefaultCompression,\n\t\t\treqBody:     compressedLz4Body.Bytes(),\n\t\t\tshouldError: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ConfighttpFramedSnappyFeatureGate.ID(), tt.framedSnappyEnabled))\n\n\t\t\tsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tbody, err := io.ReadAll(r.Body)\n\t\t\t\tassert.NoError(t, err, \"failed to read request body: %v\", err)\n\t\t\t\tassert.Equal(t, tt.reqBody, body)\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t}))\n\t\t\tt.Cleanup(srv.Close)\n\n\t\t\treqBody := bytes.NewBuffer(testBody)\n\n\t\t\treq, err := http.NewRequest(http.MethodGet, srv.URL, reqBody)\n\t\t\trequire.NoError(t, err, \"failed to create request to test handler\")\n\t\t\tclientSettings := ClientConfig{\n\t\t\t\tEndpoint:          srv.URL,\n\t\t\t\tCompression:       tt.encoding,\n\t\t\t\tCompressionParams: newCompressionParams(tt.level),\n\t\t\t}\n\t\t\terr = clientSettings.Validate()\n\t\t\tif tt.shouldError {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\tmessage := fmt.Sprintf(\"unsupported parameters {Level:%+v} for compression type %q\", tt.level, tt.encoding)\n\t\t\t\tassert.Equal(t, message, err.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\tclient, err := clientSettings.ToClient(context.Background(), nil, componenttest.NewNopTelemetrySettings())\n\t\t\trequire.NoError(t, err)\n\t\t\tres, err := client.Do(req)\n\t\t\tif tt.shouldError {\n\t\t\t\tassert.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\n\t\t\t_, err = io.ReadAll(res.Body)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, res.Body.Close(), \"failed to close request body: %v\", err)\n\t\t})\n\t}\n}\n\nfunc TestHTTPCustomDecompression(t *testing.T) {\n\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tbody, err := io.ReadAll(r.Body)\n\t\tif err != nil {\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\t_, _ = w.Write([]byte(err.Error()))\n\t\t\treturn\n\t\t}\n\n\t\tassert.NoError(t, err, \"failed to read request body: %v\", err)\n\t\tassert.Equal(t, \"decompressed body\", string(body))\n\t\tw.WriteHeader(http.StatusOK)\n\t})\n\tdecoders := map[string]func(io.ReadCloser) (io.ReadCloser, error){\n\t\t\"custom-encoding\": func(io.ReadCloser) (io.ReadCloser, error) { //nolint:unparam\n\t\t\treturn io.NopCloser(strings.NewReader(\"decompressed body\")), nil\n\t\t},\n\t}\n\tsrv := httptest.NewServer(httpContentDecompressor(handler, defaultMaxRequestBodySize, defaultErrorHandler, defaultCompressionAlgorithms(), decoders))\n\n\tt.Cleanup(srv.Close)\n\n\treq, err := http.NewRequest(http.MethodGet, srv.URL, bytes.NewBuffer([]byte(\"123decompressed body\")))\n\trequire.NoError(t, err, \"failed to create request to test handler\")\n\treq.Header.Set(\"Content-Encoding\", \"custom-encoding\")\n\n\tclient := srv.Client()\n\tres, err := client.Do(req)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, http.StatusOK, res.StatusCode, \"test handler returned unexpected status code \")\n\t_, err = io.ReadAll(res.Body)\n\trequire.NoError(t, res.Body.Close(), \"failed to close request body: %v\", err)\n}\n\nfunc TestHTTPContentDecompressionHandler(t *testing.T) {\n\ttestBody := []byte(\"uncompressed_text\")\n\tnoDecoders := map[string]func(io.ReadCloser) (io.ReadCloser, error){}\n\ttests := []struct {\n\t\tname                string\n\t\tencoding            string\n\t\treqBody             *bytes.Buffer\n\t\trespCode            int\n\t\trespBody            string\n\t\tframedSnappyEnabled bool\n\t}{\n\t\t{\n\t\t\tname:     \"NoCompression\",\n\t\t\tencoding: \"\",\n\t\t\treqBody:  bytes.NewBuffer(testBody),\n\t\t\trespCode: http.StatusOK,\n\t\t},\n\t\t{\n\t\t\tname:     \"ValidDeflate\",\n\t\t\tencoding: \"deflate\",\n\t\t\treqBody:  compressZlib(t, testBody),\n\t\t\trespCode: http.StatusOK,\n\t\t},\n\t\t{\n\t\t\tname:     \"ValidGzip\",\n\t\t\tencoding: \"gzip\",\n\t\t\treqBody:  compressGzip(t, testBody),\n\t\t\trespCode: http.StatusOK,\n\t\t},\n\t\t{\n\t\t\tname:     \"ValidZlib\",\n\t\t\tencoding: \"zlib\",\n\t\t\treqBody:  compressZlib(t, testBody),\n\t\t\trespCode: http.StatusOK,\n\t\t},\n\t\t{\n\t\t\tname:     \"ValidZstd\",\n\t\t\tencoding: \"zstd\",\n\t\t\treqBody:  compressZstd(t, testBody),\n\t\t\trespCode: http.StatusOK,\n\t\t},\n\t\t{\n\t\t\tname:                \"ValidSnappyFramed\",\n\t\t\tencoding:            \"x-snappy-framed\",\n\t\t\tframedSnappyEnabled: true,\n\t\t\treqBody:             compressSnappyFramed(t, testBody),\n\t\t\trespCode:            http.StatusOK,\n\t\t},\n\t\t{\n\t\t\tname:     \"ValidSnappy\",\n\t\t\tencoding: \"snappy\",\n\t\t\treqBody:  compressSnappy(t, testBody),\n\t\t\trespCode: http.StatusOK,\n\t\t},\n\t\t{\n\t\t\t// Should work even without the framed snappy feature gate enabled,\n\t\t\t// since during decompression we're peeking the compression header\n\t\t\t// and identifying which snappy encoding was used.\n\t\t\tname:     \"ValidSnappyFramedAsSnappy\",\n\t\t\tencoding: \"snappy\",\n\t\t\treqBody:  compressSnappyFramed(t, testBody),\n\t\t\trespCode: http.StatusOK,\n\t\t},\n\t\t{\n\t\t\tname:     \"ValidLz4\",\n\t\t\tencoding: \"lz4\",\n\t\t\treqBody:  compressLz4(t, testBody),\n\t\t\trespCode: http.StatusOK,\n\t\t},\n\t\t{\n\t\t\tname:     \"InvalidDeflate\",\n\t\t\tencoding: \"deflate\",\n\t\t\treqBody:  bytes.NewBuffer(testBody),\n\t\t\trespCode: http.StatusBadRequest,\n\t\t\trespBody: \"zlib: invalid header\\n\",\n\t\t},\n\t\t{\n\t\t\tname:     \"InvalidGzip\",\n\t\t\tencoding: \"gzip\",\n\t\t\treqBody:  bytes.NewBuffer(testBody),\n\t\t\trespCode: http.StatusBadRequest,\n\t\t\trespBody: \"gzip: invalid header\\n\",\n\t\t},\n\t\t{\n\t\t\tname:     \"InvalidZlib\",\n\t\t\tencoding: \"zlib\",\n\t\t\treqBody:  bytes.NewBuffer(testBody),\n\t\t\trespCode: http.StatusBadRequest,\n\t\t\trespBody: \"zlib: invalid header\\n\",\n\t\t},\n\t\t{\n\t\t\tname:     \"InvalidZstd\",\n\t\t\tencoding: \"zstd\",\n\t\t\treqBody:  bytes.NewBuffer(testBody),\n\t\t\trespCode: http.StatusBadRequest,\n\t\t\trespBody: \"invalid input: magic number mismatch\",\n\t\t},\n\t\t{\n\t\t\tname:                \"InvalidSnappyFramed\",\n\t\t\tencoding:            \"x-snappy-framed\",\n\t\t\tframedSnappyEnabled: true,\n\t\t\treqBody:             bytes.NewBuffer(testBody),\n\t\t\trespCode:            http.StatusBadRequest,\n\t\t\trespBody:            \"snappy: corrupt input\",\n\t\t},\n\t\t{\n\t\t\tname:     \"InvalidSnappy\",\n\t\t\tencoding: \"snappy\",\n\t\t\treqBody:  bytes.NewBuffer(testBody),\n\t\t\trespCode: http.StatusBadRequest,\n\t\t\trespBody: \"snappy: corrupt input\\n\",\n\t\t},\n\t\t{\n\t\t\tname:     \"UnsupportedCompression\",\n\t\t\tencoding: \"nosuchcompression\",\n\t\t\treqBody:  bytes.NewBuffer(testBody),\n\t\t\trespCode: http.StatusBadRequest,\n\t\t\trespBody: \"unsupported Content-Encoding: nosuchcompression\\n\",\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ConfighttpFramedSnappyFeatureGate.ID(), tt.framedSnappyEnabled))\n\n\t\t\tsrv := httptest.NewServer(httpContentDecompressor(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tbody, err := io.ReadAll(r.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\t\t\t_, _ = w.Write([]byte(err.Error()))\n\t\t\t\t\treturn\n\t\t\t\t}\n\n\t\t\t\tassert.NoError(t, err, \"failed to read request body: %v\", err)\n\t\t\t\tassert.EqualValues(t, testBody, string(body))\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t}), defaultMaxRequestBodySize, defaultErrorHandler, defaultCompressionAlgorithms(), noDecoders))\n\t\t\tt.Cleanup(srv.Close)\n\n\t\t\treq, err := http.NewRequest(http.MethodGet, srv.URL, tt.reqBody)\n\t\t\trequire.NoError(t, err, \"failed to create request to test handler\")\n\t\t\treq.Header.Set(\"Content-Encoding\", tt.encoding)\n\n\t\t\tclient := srv.Client()\n\t\t\tres, err := client.Do(req)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tassert.Equal(t, tt.respCode, res.StatusCode, \"test handler returned unexpected status code \")\n\t\t\tif tt.respBody != \"\" {\n\t\t\t\tbody, err := io.ReadAll(res.Body)\n\t\t\t\trequire.NoError(t, res.Body.Close(), \"failed to close request body: %v\", err)\n\t\t\t\tassert.Equal(t, tt.respBody, string(body))\n\t\t\t}\n\t\t})\n\t}\n}\n\n// TestEmptyCompressionAlgorithmsAllowsUncompressed verifies that when CompressionAlgorithms\n// is set to an empty array, requests without Content-Encoding header are accepted.\nfunc TestEmptyCompressionAlgorithmsAllowsUncompressed(t *testing.T) {\n\ttestBody := []byte(`{\"message\": \"test data\"}`)\n\n\ttests := []struct {\n\t\tname                  string\n\t\tcompressionAlgorithms []string\n\t\tcontentEncoding       string // empty string means no header\n\t\texpectedStatus        int\n\t\texpectedError         string\n\t\tcompressionBypassed   bool // If true, don't compress the body (simulates bypass behavior)\n\t}{\n\t\t// Case 1: Empty array should bypass decompression\n\t\t{\n\t\t\tname:                  \"EmptyArray_NoContentEncoding_Accepted\",\n\t\t\tcompressionAlgorithms: []string{},\n\t\t\tcontentEncoding:       \"\",\n\t\t\texpectedStatus:        http.StatusOK,\n\t\t},\n\t\t{\n\t\t\tname:                  \"EmptyArray_Gzip_PassedThrough\",\n\t\t\tcompressionAlgorithms: []string{},\n\t\t\tcontentEncoding:       \"gzip\",\n\t\t\texpectedStatus:        http.StatusOK,\n\t\t\tcompressionBypassed:   true, // Empty array bypasses decompression\n\t\t},\n\n\t\t{\n\t\t\tname:                  \"EmptyArray_RandomEncoding_Accepted\",\n\t\t\tcompressionAlgorithms: []string{},\n\t\t\tcontentEncoding:       \"randomstuff\",\n\t\t\texpectedStatus:        http.StatusOK,\n\t\t},\n\t\t// Case 2: Explicit list with only compressed formats should reject uncompressed\n\t\t{\n\t\t\tname:                  \"OnlyZstd_NoContentEncoding_Rejected\",\n\t\t\tcompressionAlgorithms: []string{\"zstd\"},\n\t\t\tcontentEncoding:       \"\",\n\t\t\texpectedStatus:        http.StatusBadRequest,\n\t\t\texpectedError:         \"unsupported Content-Encoding\",\n\t\t},\n\t\t{\n\t\t\tname:                  \"OnlyZstd_Zstd_Accepted\",\n\t\t\tcompressionAlgorithms: []string{\"zstd\"},\n\t\t\tcontentEncoding:       \"zstd\",\n\t\t\texpectedStatus:        http.StatusOK,\n\t\t},\n\t\t{\n\t\t\tname:                  \"OnlyZstd_GzipContentEncoding_Rejected\",\n\t\t\tcompressionAlgorithms: []string{\"zstd\"},\n\t\t\tcontentEncoding:       \"gzip\",\n\t\t\texpectedStatus:        http.StatusBadRequest,\n\t\t\texpectedError:         \"unsupported Content-Encoding\",\n\t\t},\n\t\t// Case 3: Explicit list including empty string should accept uncompressed\n\t\t{\n\t\t\tname:                  \"WithEmptyString_NoContentEncoding_Accepted\",\n\t\t\tcompressionAlgorithms: []string{\"\", \"gzip\", \"zstd\"},\n\t\t\tcontentEncoding:       \"\",\n\t\t\texpectedStatus:        http.StatusOK,\n\t\t},\n\t\t{\n\t\t\tname:                  \"WithEmptyString_Gzip_Accepted\",\n\t\t\tcompressionAlgorithms: []string{\"\", \"gzip\"},\n\t\t\tcontentEncoding:       \"gzip\",\n\t\t\texpectedStatus:        http.StatusOK,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// Create handler that echoes back the request body\n\t\t\t// If there's an error reading, it returns 500 which the test will catch\n\t\t\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tbody, err := io.ReadAll(r.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.Error(w, \"failed to read body\", http.StatusInternalServerError)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t\t_, _ = w.Write(body)\n\t\t\t})\n\n\t\t\t// Create ServerConfig with the specified CompressionAlgorithms\n\t\t\tserverConfig := &ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tCompressionAlgorithms: tt.compressionAlgorithms,\n\t\t\t}\n\n\t\t\tsrv, err := serverConfig.ToServer(\n\t\t\t\tcontext.Background(),\n\t\t\t\tnil,\n\t\t\t\tcomponenttest.NewNopTelemetrySettings(),\n\t\t\t\thandler,\n\t\t\t)\n\t\t\trequire.NoError(t, err)\n\n\t\t\t// Create test server\n\t\t\ttestSrv := httptest.NewServer(srv.Handler)\n\t\t\tdefer testSrv.Close()\n\n\t\t\t// Compress the body if needed for the test\n\t\t\trequestBody := testBody\n\t\t\tif !tt.compressionBypassed && tt.expectedStatus == http.StatusOK {\n\t\t\t\tswitch tt.contentEncoding {\n\t\t\t\tcase \"gzip\":\n\t\t\t\t\trequestBody = compressGzip(t, testBody).Bytes()\n\t\t\t\tcase \"zstd\":\n\t\t\t\t\trequestBody = compressZstd(t, testBody).Bytes()\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Create request\n\t\t\treq, err := http.NewRequest(http.MethodPost, testSrv.URL, bytes.NewReader(requestBody))\n\t\t\trequire.NoError(t, err)\n\t\t\treq.Header.Set(\"Content-Type\", \"application/json\")\n\n\t\t\t// Set Content-Encoding header if specified\n\t\t\tif tt.contentEncoding != \"\" {\n\t\t\t\treq.Header.Set(\"Content-Encoding\", tt.contentEncoding)\n\t\t\t}\n\n\t\t\t// Send request\n\t\t\tclient := &http.Client{}\n\t\t\tresp, err := client.Do(req)\n\t\t\trequire.NoError(t, err)\n\t\t\tdefer resp.Body.Close()\n\n\t\t\t// Verify response\n\t\t\tassert.Equal(t, tt.expectedStatus, resp.StatusCode, \"Unexpected status code\")\n\n\t\t\tbody, err := io.ReadAll(resp.Body)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tif tt.expectedError != \"\" {\n\t\t\t\tassert.Contains(t, string(body), tt.expectedError, \"Expected error message not found\")\n\t\t\t} else {\n\t\t\t\t// For successful requests, body should be echoed back\n\t\t\t\tassert.Equal(t, testBody, body, \"Response body should match request body\")\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestHTTPContentCompressionRequestWithNilBody(t *testing.T) {\n\tcompressedGzipBody := compressGzip(t, []byte{})\n\tsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\tbody, err := io.ReadAll(r.Body)\n\t\tassert.NoError(t, err, \"failed to read request body: %v\", err)\n\t\tassert.Equal(t, compressedGzipBody.Bytes(), body)\n\t}))\n\tdefer srv.Close()\n\n\treq, err := http.NewRequest(http.MethodGet, srv.URL, http.NoBody)\n\trequire.NoError(t, err, \"failed to create request to test handler\")\n\n\tclient := srv.Client()\n\tcompressionParams := newCompressionParams(gzip.DefaultCompression)\n\tclient.Transport, err = newCompressRoundTripper(http.DefaultTransport, configcompression.TypeGzip, compressionParams)\n\trequire.NoError(t, err)\n\tres, err := client.Do(req)\n\trequire.NoError(t, err)\n\n\t_, err = io.ReadAll(res.Body)\n\trequire.NoError(t, err)\n\trequire.NoError(t, res.Body.Close(), \"failed to close request body: %v\", err)\n}\n\nfunc TestHTTPContentCompressionCopyError(t *testing.T) {\n\tsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t}))\n\tt.Cleanup(srv.Close)\n\n\treq, err := http.NewRequest(http.MethodGet, srv.URL, iotest.ErrReader(errors.New(\"read failed\")))\n\trequire.NoError(t, err)\n\n\tclient := srv.Client()\n\tcompressionParams := newCompressionParams(gzip.DefaultCompression)\n\tclient.Transport, err = newCompressRoundTripper(http.DefaultTransport, configcompression.TypeGzip, compressionParams)\n\trequire.NoError(t, err)\n\t_, err = client.Do(req)\n\trequire.Error(t, err)\n}\n\ntype closeFailBody struct {\n\t*bytes.Buffer\n}\n\nfunc (*closeFailBody) Close() error {\n\treturn errors.New(\"close failed\")\n}\n\nfunc TestHTTPContentCompressionRequestBodyCloseError(t *testing.T) {\n\tsrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t}))\n\tt.Cleanup(srv.Close)\n\n\treq, err := http.NewRequest(http.MethodGet, srv.URL, &closeFailBody{Buffer: bytes.NewBuffer([]byte(\"blank\"))})\n\trequire.NoError(t, err)\n\n\tclient := srv.Client()\n\tcompressionParams := newCompressionParams(gzip.DefaultCompression)\n\tclient.Transport, err = newCompressRoundTripper(http.DefaultTransport, configcompression.TypeGzip, compressionParams)\n\trequire.NoError(t, err)\n\t_, err = client.Do(req)\n\trequire.Error(t, err)\n}\n\nfunc TestOverrideCompressionList(t *testing.T) {\n\t// prepare\n\tconfiguredDecoders := []string{\"none\", \"zlib\"}\n\n\tsrv := httptest.NewServer(httpContentDecompressor(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t}), defaultMaxRequestBodySize, defaultErrorHandler, configuredDecoders, nil))\n\tt.Cleanup(srv.Close)\n\n\treq, err := http.NewRequest(http.MethodGet, srv.URL, compressSnappyFramed(t, []byte(\"123decompressed body\")))\n\trequire.NoError(t, err, \"failed to create request to test handler\")\n\treq.Header.Set(\"Content-Encoding\", \"snappy\")\n\n\tclient := srv.Client()\n\n\t// test\n\tres, err := client.Do(req)\n\trequire.NoError(t, err)\n\n\t// verify\n\tassert.Equal(t, http.StatusBadRequest, res.StatusCode, \"test handler returned unexpected status code \")\n\t_, err = io.ReadAll(res.Body)\n\trequire.NoError(t, res.Body.Close(), \"failed to close request body: %v\", err)\n}\n\nfunc TestDecompressorAvoidDecompressionBomb(t *testing.T) {\n\tt.Parallel()\n\n\tfor _, tc := range []struct {\n\t\tname                string\n\t\tencoding            string\n\t\tcompress            func(tb testing.TB, payload []byte) *bytes.Buffer\n\t\tframedSnappyEnabled bool\n\t}{\n\t\t// None encoding is ignored since it does not\n\t\t// enforce the max body size if content encoding header is not set\n\t\t{\n\t\t\tname:     \"gzip\",\n\t\t\tencoding: \"gzip\",\n\t\t\tcompress: compressGzip,\n\t\t},\n\t\t{\n\t\t\tname:     \"zstd\",\n\t\t\tencoding: \"zstd\",\n\t\t\tcompress: compressZstd,\n\t\t},\n\t\t{\n\t\t\tname:     \"zlib\",\n\t\t\tencoding: \"zlib\",\n\t\t\tcompress: compressZlib,\n\t\t},\n\t\t{\n\t\t\tname:     \"x-snappy-framed\",\n\t\t\tencoding: \"x-snappy-framed\",\n\t\t\tcompress: compressSnappyFramed,\n\t\t},\n\t\t{\n\t\t\tname:                \"x-snappy-not-framed\",\n\t\t\tencoding:            \"x-snappy-framed\",\n\t\t\tcompress:            compressSnappyFramed,\n\t\t\tframedSnappyEnabled: false,\n\t\t},\n\t\t{\n\t\t\tname:     \"snappy\",\n\t\t\tencoding: \"snappy\",\n\t\t\tcompress: compressSnappy,\n\t\t},\n\t\t{\n\t\t\tname:     \"lz4\",\n\t\t\tencoding: \"lz4\",\n\t\t\tcompress: compressLz4,\n\t\t},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t// t.Parallel() // TODO: Re-enable parallel tests once feature gate is removed. We can't parallelize since registry is shared.\n\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ConfighttpFramedSnappyFeatureGate.ID(), tc.framedSnappyEnabled))\n\n\t\t\th := httpContentDecompressor(\n\t\t\t\thttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\t\tn, err := io.Copy(io.Discard, r.Body)\n\t\t\t\t\tassert.Equal(t, int64(1024), n, \"Must have only read the limited value of bytes\")\n\t\t\t\t\tassert.EqualError(t, err, \"http: request body too large\")\n\t\t\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t\t\t}),\n\t\t\t\t1024,\n\t\t\t\tdefaultErrorHandler,\n\t\t\t\tdefaultCompressionAlgorithms(),\n\t\t\t\tavailableDecoders,\n\t\t\t)\n\n\t\t\tpayload := tc.compress(t, make([]byte, 2*1024)) // 2KB uncompressed payload\n\t\t\tassert.NotEmpty(t, payload.Bytes(), \"Must have data available\")\n\n\t\t\treq := httptest.NewRequest(http.MethodPost, \"/\", payload)\n\t\t\treq.Header.Set(\"Content-Encoding\", tc.encoding)\n\n\t\t\tresp := httptest.NewRecorder()\n\n\t\t\th.ServeHTTP(resp, req)\n\n\t\t\tassert.Equal(t, http.StatusBadRequest, resp.Code, \"Must match the expected code\")\n\t\t\tassert.Empty(t, resp.Body.String(), \"Must match the returned string\")\n\t\t})\n\t}\n}\n\nfunc TestPooledZstdReadCloserReadAfterClose(t *testing.T) {\n\th := httpContentDecompressor(\n\t\thttp.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tbuf := make([]byte, 1024)\n\t\t\t_, err := r.Body.Read(buf)\n\t\t\tassert.NoError(t, err)\n\t\t\terr = r.Body.Close()\n\t\t\tassert.NoError(t, err)\n\t\t\t_, err = r.Body.Read(buf)\n\t\t\tassert.ErrorIs(t, err, zstd.ErrDecoderClosed)\n\t\t\tw.WriteHeader(http.StatusBadRequest)\n\t\t}),\n\t\tdefaultMaxRequestBodySize,\n\t\tdefaultErrorHandler,\n\t\tdefaultCompressionAlgorithms(),\n\t\tavailableDecoders,\n\t)\n\n\tpayload := compressZstd(t, make([]byte, 2*1024)) // 2KB uncompressed payload\n\tassert.NotEmpty(t, payload.Bytes(), \"Must have data available\")\n\n\treq := httptest.NewRequest(http.MethodPost, \"/\", payload)\n\treq.Header.Set(\"Content-Encoding\", \"zstd\")\n\n\tresp := httptest.NewRecorder()\n\n\th.ServeHTTP(resp, req)\n\n\tassert.Equal(t, http.StatusBadRequest, resp.Code, \"Must match the expected code\")\n\tassert.Empty(t, resp.Body.String(), \"Must match the returned string\")\n}\n\nfunc compressGzip(tb testing.TB, body []byte) *bytes.Buffer {\n\tvar buf bytes.Buffer\n\tgw, _ := gzip.NewWriterLevel(&buf, gzip.DefaultCompression)\n\t_, err := gw.Write(body)\n\trequire.NoError(tb, err)\n\trequire.NoError(tb, gw.Close())\n\treturn &buf\n}\n\nfunc compressZlib(tb testing.TB, body []byte) *bytes.Buffer {\n\tvar buf bytes.Buffer\n\tzw, _ := zlib.NewWriterLevel(&buf, zlib.DefaultCompression)\n\t_, err := zw.Write(body)\n\trequire.NoError(tb, err)\n\trequire.NoError(tb, zw.Close())\n\treturn &buf\n}\n\nfunc compressSnappyFramed(tb testing.TB, body []byte) *bytes.Buffer {\n\tvar buf bytes.Buffer\n\tsw := snappy.NewBufferedWriter(&buf)\n\t_, err := sw.Write(body)\n\trequire.NoError(tb, err)\n\trequire.NoError(tb, sw.Close())\n\treturn &buf\n}\n\nfunc compressSnappy(tb testing.TB, body []byte) *bytes.Buffer {\n\tvar buf bytes.Buffer\n\tcompressed := snappy.Encode(nil, body)\n\t_, err := buf.Write(compressed)\n\trequire.NoError(tb, err)\n\treturn &buf\n}\n\nfunc compressZstd(tb testing.TB, body []byte) *bytes.Buffer {\n\tvar buf bytes.Buffer\n\tcompression := zstd.SpeedFastest\n\tencoderLevel := zstd.WithEncoderLevel(compression)\n\tzw, _ := zstd.NewWriter(&buf, encoderLevel)\n\t_, err := zw.Write(body)\n\trequire.NoError(tb, err)\n\trequire.NoError(tb, zw.Close())\n\treturn &buf\n}\n\nfunc compressLz4(tb testing.TB, body []byte) *bytes.Buffer {\n\tvar buf bytes.Buffer\n\tlz := lz4.NewWriter(&buf)\n\t_, err := lz.Write(body)\n\trequire.NoError(tb, err)\n\trequire.NoError(tb, lz.Close())\n\treturn &buf\n}\n"
  },
  {
    "path": "config/confighttp/compressor.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confighttp // import \"go.opentelemetry.io/collector/config/confighttp\"\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"compress/zlib\"\n\t\"errors\"\n\t\"io\"\n\t\"sync\"\n\n\t\"github.com/golang/snappy\"\n\t\"github.com/klauspost/compress/zstd\"\n\t\"github.com/pierrec/lz4/v4\"\n\n\t\"go.opentelemetry.io/collector/config/configcompression\"\n\t\"go.opentelemetry.io/collector/config/confighttp/internal/metadata\"\n)\n\ntype writeCloserReset interface {\n\tio.WriteCloser\n\tReset(w io.Writer)\n}\n\ntype compressor struct {\n\tpool sync.Pool\n}\n\ntype compressorMap map[compressionMapKey]*compressor\n\ntype compressionMapKey struct {\n\tcompressionType   configcompression.Type\n\tcompressionParams configcompression.CompressionParams\n}\n\nvar (\n\tcompressorPools   = make(compressorMap)\n\tcompressorPoolsMu sync.Mutex\n)\n\n// writerFactory defines writer field in CompressRoundTripper.\n// The validity of input is already checked when NewCompressRoundTripper was called in confighttp,\nfunc newCompressor(compressionType configcompression.Type, compressionParams configcompression.CompressionParams) (*compressor, error) {\n\tcompressorPoolsMu.Lock()\n\tdefer compressorPoolsMu.Unlock()\n\tmapKey := compressionMapKey{compressionType, compressionParams}\n\tc, ok := compressorPools[mapKey]\n\tif ok {\n\t\treturn c, nil\n\t}\n\n\tf, err := newWriteCloserResetFunc(compressionType, compressionParams)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc = &compressor{pool: sync.Pool{New: func() any { return f() }}}\n\tcompressorPools[mapKey] = c\n\treturn c, nil\n}\n\nfunc newWriteCloserResetFunc(compressionType configcompression.Type, compressionParams configcompression.CompressionParams) (func() writeCloserReset, error) {\n\tswitch compressionType {\n\tcase configcompression.TypeGzip:\n\t\treturn func() writeCloserReset {\n\t\t\tw, _ := gzip.NewWriterLevel(nil, int(compressionParams.Level))\n\t\t\treturn w\n\t\t}, nil\n\tcase configcompression.TypeSnappyFramed:\n\t\tif !metadata.ConfighttpFramedSnappyFeatureGate.IsEnabled() {\n\t\t\treturn nil, errors.New(\"x-snappy-framed is not enabled\")\n\t\t}\n\t\treturn func() writeCloserReset {\n\t\t\treturn snappy.NewBufferedWriter(nil)\n\t\t}, nil\n\tcase configcompression.TypeSnappy:\n\t\tif !metadata.ConfighttpFramedSnappyFeatureGate.IsEnabled() {\n\t\t\t// If framed snappy feature gate is not enabled, we keep the current behavior\n\t\t\t// where the 'Content-Encoding: snappy' is compressed as the framed snappy format.\n\t\t\treturn func() writeCloserReset {\n\t\t\t\treturn snappy.NewBufferedWriter(nil)\n\t\t\t}, nil\n\t\t}\n\t\treturn func() writeCloserReset {\n\t\t\t// If framed snappy feature gate is enabled, we use the correct behavior\n\t\t\t// where the 'Content-Encoding: snappy' is compressed as the block snappy format.\n\t\t\treturn &rawSnappyWriter{}\n\t\t}, nil\n\tcase configcompression.TypeZstd:\n\t\tlevel := zstd.WithEncoderLevel(zstd.EncoderLevelFromZstd(int(compressionParams.Level)))\n\t\treturn func() writeCloserReset {\n\t\t\tzw, _ := zstd.NewWriter(nil, zstd.WithEncoderConcurrency(1), level)\n\t\t\treturn zw\n\t\t}, nil\n\tcase configcompression.TypeZlib, configcompression.TypeDeflate:\n\t\treturn func() writeCloserReset {\n\t\t\tw, _ := zlib.NewWriterLevel(nil, int(compressionParams.Level))\n\t\t\treturn w\n\t\t}, nil\n\tcase configcompression.TypeLz4:\n\t\treturn func() writeCloserReset {\n\t\t\tlz := lz4.NewWriter(nil)\n\t\t\t_ = lz.Apply(lz4.ConcurrencyOption(1))\n\t\t\treturn lz\n\t\t}, nil\n\t}\n\treturn nil, errors.New(\"unsupported compression type\")\n}\n\nfunc (p *compressor) compress(buf *bytes.Buffer, body io.ReadCloser) error {\n\twriter := p.pool.Get().(writeCloserReset)\n\tdefer p.pool.Put(writer)\n\twriter.Reset(buf)\n\n\tif body != nil {\n\t\t_, copyErr := io.Copy(writer, body)\n\t\tcloseErr := body.Close()\n\n\t\tif copyErr != nil {\n\t\t\treturn copyErr\n\t\t}\n\n\t\tif closeErr != nil {\n\t\t\treturn closeErr\n\t\t}\n\t}\n\n\treturn writer.Close()\n}\n\n// rawSnappyWriter buffers all writes and, on Close,\n// compresses the data as a raw snappy block (non-framed)\n// and writes the compressed bytes to the underlying writer.\ntype rawSnappyWriter struct {\n\tbuffer bytes.Buffer\n\tw      io.Writer\n\tclosed bool\n}\n\n// Write buffers the data.\nfunc (w *rawSnappyWriter) Write(p []byte) (int, error) {\n\treturn w.buffer.Write(p)\n}\n\n// Close compresses the buffered data in one shot using snappy.Encode,\n// writes the compressed block to the underlying writer, and marks the writer as closed.\nfunc (w *rawSnappyWriter) Close() error {\n\tif w.closed {\n\t\treturn nil\n\t}\n\tw.closed = true\n\t// Compress the buffered uncompressed bytes.\n\tcompressed := snappy.Encode(nil, w.buffer.Bytes())\n\t_, err := w.w.Write(compressed)\n\treturn err\n}\n\n// Reset sets a new underlying writer, resets the buffer and the closed flag.\nfunc (w *rawSnappyWriter) Reset(newWriter io.Writer) {\n\tw.buffer.Reset()\n\tw.w = newWriter\n\tw.closed = false\n}\n"
  },
  {
    "path": "config/confighttp/compressor_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// This file contains helper functions regarding compression/decompression for confighttp.\n\npackage confighttp // import \"go.opentelemetry.io/collector/config/confighttp\"\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/klauspost/compress/zstd\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/config/configcompression\"\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc BenchmarkCompression(b *testing.B) {\n\ttestutil.SkipGCHeavyBench(b)\n\tbenchmarks := []struct {\n\t\tcodec    configcompression.Type\n\t\tname     string\n\t\tfunction func(*testing.B, configcompression.Type, *bytes.Buffer, []byte)\n\t}{\n\t\t{\n\t\t\tcodec:    configcompression.TypeZstd,\n\t\t\tname:     \"zstdWithConcurrency\",\n\t\t\tfunction: benchmarkCompression,\n\t\t},\n\t\t{\n\t\t\tcodec:    configcompression.TypeZstd,\n\t\t\tname:     \"zstdNoConcurrency\",\n\t\t\tfunction: benchmarkCompressionNoConcurrency,\n\t\t},\n\t}\n\tpayload := make([]byte, 10<<22)\n\tbuffer := bytes.Buffer{}\n\tbuffer.Grow(len(payload))\n\n\tts := &bytes.Buffer{}\n\tdefer func() {\n\t\tfmt.Printf(\"input => %.2f MB\\n\", float64(len(payload))/(1024*1024))\n\t\tfmt.Println(ts)\n\t}()\n\n\tfor i := range benchmarks {\n\t\tbenchmark := &benchmarks[i]\n\t\tb.Run(benchmark.name, func(b *testing.B) {\n\t\t\tbenchmark.function(b, benchmark.codec, &buffer, payload)\n\t\t})\n\t}\n}\n\nfunc benchmarkCompression(b *testing.B, _ configcompression.Type, buf *bytes.Buffer, payload []byte) {\n\t// Concurrency Enabled\n\tstringReader := strings.NewReader(string(payload))\n\tstringReadCloser := io.NopCloser(stringReader)\n\tvar enc io.Writer\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tb.SetBytes(int64(len(payload)))\n\tfor b.Loop() {\n\t\tenc, _ = zstd.NewWriter(nil, zstd.WithEncoderConcurrency(5))\n\t\tenc.(writeCloserReset).Reset(buf)\n\t\t_, copyErr := io.Copy(enc, stringReadCloser)\n\t\trequire.NoError(b, copyErr)\n\t}\n}\n\nfunc benchmarkCompressionNoConcurrency(b *testing.B, _ configcompression.Type, buf *bytes.Buffer, payload []byte) {\n\tstringReader := strings.NewReader(string(payload))\n\tstringReadCloser := io.NopCloser(stringReader)\n\tvar enc io.Writer\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tb.SetBytes(int64(len(payload)))\n\tfor b.Loop() {\n\t\tenc, _ = zstd.NewWriter(nil, zstd.WithEncoderConcurrency(1))\n\t\tenc.(writeCloserReset).Reset(buf)\n\t\t_, copyErr := io.Copy(enc, stringReadCloser)\n\t\trequire.NoError(b, copyErr)\n\t}\n}\n"
  },
  {
    "path": "config/confighttp/config.schema.yaml",
    "content": "$defs:\n  auth_config:\n    type: object\n    properties:\n      request_params:\n        description: RequestParameters is a list of parameters that should be extracted from the request and added to the context. When a parameter is found in both the query string and the header, the value from the query string will be used.\n        type: array\n        items:\n          type: string\n    allOf:\n      - $ref: /config/configauth.config\n  cookies_config:\n    description: CookiesConfig defines the configuration of the HTTP client regarding cookies served by the server.\n  client_config:\n    description: ClientConfig defines settings for creating an HTTP client.\n    type: object\n    properties:\n      auth:\n        description: Auth configuration for outgoing HTTP calls.\n        x-optional: true\n        $ref: /config/configauth.config\n      compression:\n        description: The compression key for supported compression types within collector.\n        $ref: /config/configcompression.type\n      compression_params:\n        description: Advanced configuration options for the Compression\n        $ref: /config/configcompression.compression_params\n      cookies:\n        description: Cookies configures the cookie management of the HTTP client.\n        x-optional: true\n        $ref: cookies_config\n      disable_keep_alives:\n        description: 'DisableKeepAlives, if true, disables HTTP keep-alives and will only use the connection to the server for a single HTTP request. WARNING: enabling this option can result in significant overhead establishing a new HTTP(S) connection for every request. Before enabling this option please consider whether changes to idle connection settings can achieve your goal.'\n        type: boolean\n      endpoint:\n        description: 'The target URL to send data to (e.g.: http://some.url:9411/v1/traces).'\n        type: string\n      force_attempt_http2:\n        description: 'Enabling ForceAttemptHTTP2 forces the HTTP transport to use the HTTP/2 protocol. By default, this is set to true. NOTE: HTTP/2 does not support settings such as MaxConnsPerHost, MaxIdleConnsPerHost and MaxIdleConns.'\n        type: boolean\n      headers:\n        description: Additional headers attached to each HTTP request sent by the client. Existing header values are overwritten if collision happens. Header values are opaque since they may be sensitive.\n        $ref: /config/configopaque.map_list\n      http2_ping_timeout:\n        description: HTTP2PingTimeout if there's no response to the ping within the configured value, the connection will be closed. If not set or set to 0, it defaults to 15s.\n        type: string\n        x-customType: time.Duration\n        format: duration\n      http2_read_idle_timeout:\n        description: This is needed in case you run into https://github.com/golang/go/issues/59690 https://github.com/golang/go/issues/36026 HTTP2ReadIdleTimeout if the connection has been idle for the configured value send a ping frame for health check 0s means no health check will be performed.\n        type: string\n        x-customType: time.Duration\n        format: duration\n      idle_conn_timeout:\n        description: IdleConnTimeout is the maximum amount of time a connection will remain open before closing itself. By default, it is set to 90 seconds.\n        type: string\n        x-customType: time.Duration\n        format: duration\n      max_conns_per_host:\n        description: MaxConnsPerHost limits the total number of connections per host, including connections in the dialing, active, and idle states. Default is 0 (unlimited).\n        type: integer\n      max_idle_conns:\n        description: MaxIdleConns is used to set a limit to the maximum idle HTTP connections the client can keep open. By default, it is set to 100. Zero means no limit.\n        type: integer\n      max_idle_conns_per_host:\n        description: MaxIdleConnsPerHost is used to set a limit to the maximum idle HTTP connections the host can keep open. If zero, [net/http.DefaultMaxIdleConnsPerHost] is used.\n        type: integer\n      middlewares:\n        description: Middlewares are used to add custom functionality to the HTTP client. Middleware handlers are called in the order they appear in this list, with the first middleware becoming the outermost handler.\n        type: array\n        items:\n          $ref: /config/configmiddleware.config\n      proxy_url:\n        description: ProxyURL setting for the collector\n        type: string\n      read_buffer_size:\n        description: ReadBufferSize for HTTP client. See http.Transport.ReadBufferSize. Default is 0.\n        type: integer\n      timeout:\n        description: Timeout parameter configures `http.Client.Timeout`. Default is 0 (unlimited).\n        type: string\n        x-customType: time.Duration\n        format: duration\n      tls:\n        description: TLS struct exposes TLS client configuration.\n        $ref: /config/configtls.client_config\n      write_buffer_size:\n        description: WriteBufferSize for HTTP client. See http.Transport.WriteBufferSize. Default is 0.\n        type: integer\n  cors_config:\n    description: CORSConfig configures a receiver for HTTP cross-origin resource sharing (CORS). See the underlying https://github.com/rs/cors package for details.\n    type: object\n    properties:\n      allowed_headers:\n        description: AllowedHeaders sets what headers will be allowed in CORS requests. The Accept, Accept-Language, Content-Type, and Content-Language headers are implicitly allowed. If no headers are listed, X-Requested-With will also be accepted by default. Include \"*\" to allow any request header.\n        type: array\n        items:\n          type: string\n      allowed_origins:\n        description: AllowedOrigins sets the allowed values of the Origin header for HTTP/JSON requests to an OTLP receiver. An origin may contain a wildcard (*) to replace 0 or more characters (e.g., \"http://*.domain.com\", or \"*\" to allow any origin).\n        type: array\n        items:\n          type: string\n      max_age:\n        description: MaxAge sets the value of the Access-Control-Max-Age response header. Set it to the number of seconds that browsers should cache a CORS preflight response for.\n        type: integer\n  server_config:\n    description: ServerConfig defines settings for creating an HTTP server.\n    type: object\n    properties:\n      auth:\n        description: Auth for this receiver\n        x-optional: true\n        $ref: auth_config\n      compression_algorithms:\n        description: 'CompressionAlgorithms configures the list of compression algorithms the server can accept. Default: [\"\", \"gzip\", \"zstd\", \"zlib\", \"snappy\", \"deflate\"]'\n        type: array\n        items:\n          type: string\n      cors:\n        description: CORS configures the server for HTTP cross-origin resource sharing (CORS).\n        x-optional: true\n        $ref: cors_config\n      endpoint:\n        description: Endpoint configures the listening address for the server.\n        type: string\n      idle_timeout:\n        description: IdleTimeout is the maximum amount of time to wait for the next request when keep-alives are enabled. If IdleTimeout is zero, the value of ReadTimeout is used. If both are zero, there is no timeout.\n        type: string\n        x-customType: time.Duration\n        format: duration\n      include_metadata:\n        description: IncludeMetadata propagates the client metadata from the incoming requests to the downstream consumers\n        type: boolean\n      keep_alives_enabled:\n        description: KeepAlivesEnabled controls whether HTTP keep-alives are enabled. By default, keep-alives are always enabled. Only very resource-constrained environments should disable them.\n        type: boolean\n      max_request_body_size:\n        description: 'MaxRequestBodySize sets the maximum request body size in bytes. Default: 20MiB.'\n        type: integer\n        x-customType: int64\n      middlewares:\n        description: Middlewares are used to add custom functionality to the HTTP server. Middleware handlers are called in the order they appear in this list, with the first middleware becoming the outermost handler.\n        type: array\n        items:\n          $ref: /config/configmiddleware.config\n      read_header_timeout:\n        description: ReadHeaderTimeout is the amount of time allowed to read request headers. The connection's read deadline is reset after reading the headers and the Handler can decide what is considered too slow for the body. If ReadHeaderTimeout is zero, the value of ReadTimeout is used. If both are zero, there is no timeout.\n        type: string\n        x-customType: time.Duration\n        format: duration\n      read_timeout:\n        description: ReadTimeout is the maximum duration for reading the entire request, including the body. A zero or negative value means there will be no timeout. Because ReadTimeout does not let Handlers make per-request decisions on each request body's acceptable deadline or upload rate, most users will prefer to use ReadHeaderTimeout. It is valid to use them both.\n        type: string\n        x-customType: time.Duration\n        format: duration\n      response_headers:\n        description: Additional headers attached to each HTTP response sent to the client. Header values are opaque since they may be sensitive.\n        $ref: /config/configopaque.map_list\n      tls:\n        description: TLS struct exposes TLS client configuration.\n        x-optional: true\n        $ref: /config/configtls.server_config\n      write_timeout:\n        description: WriteTimeout is the maximum duration before timing out writes of the response. It is reset whenever a new request's header is read. Like ReadTimeout, it does not let Handlers make decisions on a per-request basis. A zero or negative value means there will be no timeout.\n        type: string\n        x-customType: time.Duration\n        format: duration\n"
  },
  {
    "path": "config/confighttp/confighttp_example_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confighttp\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\nfunc ExampleServerConfig() {\n\tsettings := NewDefaultServerConfig()\n\tsettings.NetAddr.Endpoint = \"localhost:443\"\n\n\t// Typically obtained as an argument of Component.Start()\n\thost := componenttest.NewNopHost()\n\n\ts, err := settings.ToServer(\n\t\tcontext.Background(),\n\t\thost.GetExtensions(),\n\t\tcomponenttest.NewNopTelemetrySettings(),\n\t\thttp.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tl, err := settings.ToListener(context.Background())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tif err = s.Serve(l); err != nil {\n\t\tpanic(err)\n\t}\n}\n"
  },
  {
    "path": "config/confighttp/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package confighttp defines the configuration settings\n// for creating an HTTP client and server.\n//\n// The configuration structs in this package may be shared across signals, but\n// assume each struct is used for a single protocol and component.\npackage confighttp // import \"go.opentelemetry.io/collector/config/confighttp\"\n\n//go:generate mdatagen metadata.yaml\n"
  },
  {
    "path": "config/confighttp/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# confighttp\n\n## Feature Gates\n\nThis component has the following feature gates:\n\n| Feature Gate | Stage | Description | From Version | To Version | Reference |\n| ------------ | ----- | ----------- | ------------ | ---------- | --------- |\n| `confighttp.framedSnappy` | beta | Content encoding 'snappy' will compress/decompress block snappy format while 'x-snappy-framed' will compress/decompress framed snappy format. | v0.125.0 | N/A | [Link](https://github.com/open-telemetry/opentelemetry-collector/issues/10584) |\n\nFor more information about feature gates, see the [Feature Gates](https://github.com/open-telemetry/opentelemetry-collector/blob/main/featuregate/README.md) documentation.\n"
  },
  {
    "path": "config/confighttp/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage confighttp\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "config/confighttp/go.mod",
    "content": "module go.opentelemetry.io/collector/config/confighttp\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/golang/snappy v1.0.0\n\tgithub.com/klauspost/compress v1.18.4\n\tgithub.com/pierrec/lz4/v4 v4.1.26\n\tgithub.com/rs/cors v1.11.1\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/client v1.54.0\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/config/configauth v1.54.0\n\tgo.opentelemetry.io/collector/config/configcompression v1.54.0\n\tgo.opentelemetry.io/collector/config/configmiddleware v1.54.0\n\tgo.opentelemetry.io/collector/config/confignet v1.54.0\n\tgo.opentelemetry.io/collector/config/configopaque v1.54.0\n\tgo.opentelemetry.io/collector/config/configoptional v1.54.0\n\tgo.opentelemetry.io/collector/config/configtls v1.54.0\n\tgo.opentelemetry.io/collector/extension v1.54.0\n\tgo.opentelemetry.io/collector/extension/extensionauth v1.54.0\n\tgo.opentelemetry.io/collector/extension/extensionauth/extensionauthtest v0.148.0\n\tgo.opentelemetry.io/collector/extension/extensionmiddleware v0.148.0\n\tgo.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest v0.148.0\n\tgo.opentelemetry.io/collector/featuregate v1.54.0\n\tgo.opentelemetry.io/collector/internal/testutil v0.148.0\n\tgo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0\n\tgo.opentelemetry.io/otel v1.42.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/zap v1.27.1\n\tgolang.org/x/net v0.51.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/felixge/httpsnoop v1.0.4 // indirect\n\tgithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f // indirect\n\tgithub.com/fsnotify/fsnotify v1.9.0 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/google/go-tpm v0.9.8 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/crypto v0.48.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/config/configauth => ../configauth\n\nreplace go.opentelemetry.io/collector/config/configcompression => ../configcompression\n\nreplace go.opentelemetry.io/collector/config/configmiddleware => ../configmiddleware\n\nreplace go.opentelemetry.io/collector/config/confignet => ../confignet\n\nreplace go.opentelemetry.io/collector/config/configopaque => ../configopaque\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../configoptional\n\nreplace go.opentelemetry.io/collector/config/configtls => ../configtls\n\nreplace go.opentelemetry.io/collector/extension => ../../extension\n\nreplace go.opentelemetry.io/collector/extension/extensionauth => ../../extension/extensionauth\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ../../extension/extensionmiddleware\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/client => ../../client\n\nreplace go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest => ../../extension/extensionauth/extensionauthtest\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest => ../../extension/extensionmiddleware/extensionmiddlewaretest\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "config/confighttp/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=\ngithub.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f h1:RJ+BDPLSHQO7cSjKBqjPJSbi1qfk9WcsjQDtZiw3dZw=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f/go.mod h1:VHbbch/X4roIY22jL1s3qRbZhCiRIgUAF/PdSUcx2io=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=\ngithub.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=\ngithub.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=\ngithub.com/google/go-tpm-tools v0.4.7 h1:J3ycC8umYxM9A4eF73EofRZu4BxY0jjQnUnkhIBbvws=\ngithub.com/google/go-tpm-tools v0.4.7/go.mod h1:gSyXTZHe3fgbzb6WEGd90QucmsnT1SRdlye82gH8QjQ=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=\ngithub.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=\ngithub.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=\ngithub.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=\ngolang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=\ngonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "config/confighttp/internal/metadata/generated_feature_gates.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\nvar ConfighttpFramedSnappyFeatureGate = featuregate.GlobalRegistry().MustRegister(\n\t\"confighttp.framedSnappy\",\n\tfeaturegate.StageBeta,\n\tfeaturegate.WithRegisterDescription(\"Content encoding 'snappy' will compress/decompress block snappy format while 'x-snappy-framed' will compress/decompress framed snappy format.\"),\n\tfeaturegate.WithRegisterReferenceURL(\"https://github.com/open-telemetry/opentelemetry-collector/issues/10584\"),\n\tfeaturegate.WithRegisterFromVersion(\"v0.125.0\"),\n)\n"
  },
  {
    "path": "config/confighttp/internal/options.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/config/confighttp/internal\"\n\nimport (\n\t\"io\"\n\t\"net/http\"\n\n\t\"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\"\n)\n\n// ToServerOptions has options that change the behavior of the HTTP server\n// returned by ServerConfig.ToServer().\ntype ToServerOptions struct {\n\tErrHandler   func(w http.ResponseWriter, r *http.Request, errorMsg string, statusCode int)\n\tDecoders     map[string]func(body io.ReadCloser) (io.ReadCloser, error)\n\tOtelhttpOpts []otelhttp.Option\n}\n\nfunc (tso *ToServerOptions) Apply(opts ...ToServerOption) {\n\tfor _, o := range opts {\n\t\to.apply(tso)\n\t}\n}\n\n// ToServerOption is an option to change the behavior of the HTTP server\n// returned by ServerConfig.ToServer().\ntype ToServerOption interface {\n\tapply(*ToServerOptions)\n}\n\n// ToServerOptionFunc converts a function into ToServerOption interface.\ntype ToServerOptionFunc func(*ToServerOptions)\n\nfunc (of ToServerOptionFunc) apply(e *ToServerOptions) {\n\tof(e)\n}\n"
  },
  {
    "path": "config/confighttp/metadata.yaml",
    "content": "type: confighttp\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  stability:\n    beta: [metrics, traces, logs]\n    alpha: [profiles]\n\nfeature_gates:\n  - id: confighttp.framedSnappy\n    description: \"Content encoding 'snappy' will compress/decompress block snappy format while 'x-snappy-framed' will compress/decompress framed snappy format.\"\n    stage: beta\n    from_version: 'v0.125.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/issues/10584'\n"
  },
  {
    "path": "config/confighttp/server.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confighttp // import \"go.opentelemetry.io/collector/config/confighttp\"\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"errors\"\n\t\"io\"\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n\t\"time\"\n\n\t\"github.com/rs/cors\"\n\t\"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\"\n\t\"go.opentelemetry.io/otel\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\t\"golang.org/x/net/http2\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configauth\"\n\t\"go.opentelemetry.io/collector/config/confighttp/internal\"\n\t\"go.opentelemetry.io/collector/config/configmiddleware\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/extension/extensionauth\"\n)\n\nconst defaultMaxRequestBodySize = 20 * 1024 * 1024 // 20MiB\n\n// ServerConfig defines settings for creating an HTTP server.\ntype ServerConfig struct {\n\t// NetAddr holds configuration for the network listener.\n\t//\n\t// Transport defaults to \"tcp\" if unspecified, and only\n\t// \"tcp\", \"tcp4\", \"tcp6\", and \"unix\" are valid options.\n\tNetAddr confignet.AddrConfig `mapstructure:\",squash\"`\n\n\t// TLS struct exposes TLS server configuration.\n\tTLS configoptional.Optional[configtls.ServerConfig] `mapstructure:\"tls\"`\n\n\t// CORS configures the server for HTTP cross-origin resource sharing (CORS).\n\tCORS configoptional.Optional[CORSConfig] `mapstructure:\"cors\"`\n\n\t// Auth for this receiver\n\tAuth configoptional.Optional[AuthConfig] `mapstructure:\"auth,omitempty\"`\n\n\t// MaxRequestBodySize sets the maximum request body size in bytes. Default: 20MiB.\n\tMaxRequestBodySize int64 `mapstructure:\"max_request_body_size,omitempty\"`\n\n\t// IncludeMetadata propagates the client metadata from the incoming requests to the downstream consumers\n\tIncludeMetadata bool `mapstructure:\"include_metadata,omitempty\"`\n\n\t// Additional headers attached to each HTTP response sent to the client.\n\t// Header values are opaque since they may be sensitive.\n\tResponseHeaders configopaque.MapList `mapstructure:\"response_headers,omitempty\"`\n\n\t// CompressionAlgorithms configures the list of compression algorithms the server can accept. Default: [\"\", \"gzip\", \"zstd\", \"zlib\", \"snappy\", \"deflate\"]\n\tCompressionAlgorithms []string `mapstructure:\"compression_algorithms,omitempty\"`\n\n\t// ReadTimeout is the maximum duration for reading the entire\n\t// request, including the body. A zero or negative value means\n\t// there will be no timeout.\n\t//\n\t// Because ReadTimeout does not let Handlers make per-request\n\t// decisions on each request body's acceptable deadline or\n\t// upload rate, most users will prefer to use\n\t// ReadHeaderTimeout. It is valid to use them both.\n\tReadTimeout time.Duration `mapstructure:\"read_timeout,omitempty\"`\n\n\t// ReadHeaderTimeout is the amount of time allowed to read\n\t// request headers. The connection's read deadline is reset\n\t// after reading the headers and the Handler can decide what\n\t// is considered too slow for the body. If ReadHeaderTimeout\n\t// is zero, the value of ReadTimeout is used. If both are\n\t// zero, there is no timeout.\n\tReadHeaderTimeout time.Duration `mapstructure:\"read_header_timeout\"`\n\n\t// WriteTimeout is the maximum duration before timing out\n\t// writes of the response. It is reset whenever a new\n\t// request's header is read. Like ReadTimeout, it does not\n\t// let Handlers make decisions on a per-request basis.\n\t// A zero or negative value means there will be no timeout.\n\tWriteTimeout time.Duration `mapstructure:\"write_timeout\"`\n\n\t// IdleTimeout is the maximum amount of time to wait for the\n\t// next request when keep-alives are enabled. If IdleTimeout\n\t// is zero, the value of ReadTimeout is used. If both are\n\t// zero, there is no timeout.\n\tIdleTimeout time.Duration `mapstructure:\"idle_timeout\"`\n\n\t// Middlewares are used to add custom functionality to the HTTP server.\n\t// Middleware handlers are called in the order they appear in this list,\n\t// with the first middleware becoming the outermost handler.\n\tMiddlewares []configmiddleware.Config `mapstructure:\"middlewares,omitempty\"`\n\n\t// KeepAlivesEnabled controls whether HTTP keep-alives are enabled.\n\t// By default, keep-alives are always enabled. Only very resource-constrained environments should disable them.\n\tKeepAlivesEnabled bool `mapstructure:\"keep_alives_enabled,omitempty\"`\n}\n\n// NewDefaultServerConfig returns ServerConfig type object with default values.\n// We encourage to use this function to create an object of ServerConfig.\nfunc NewDefaultServerConfig() ServerConfig {\n\tnetAddr := confignet.NewDefaultAddrConfig()\n\t// We typically want to create a TCP server and listen over a network.\n\tnetAddr.Transport = confignet.TransportTypeTCP\n\n\treturn ServerConfig{\n\t\tNetAddr:           netAddr,\n\t\tWriteTimeout:      30 * time.Second,\n\t\tReadHeaderTimeout: 1 * time.Minute,\n\t\tIdleTimeout:       1 * time.Minute,\n\t\tKeepAlivesEnabled: true,\n\t}\n}\n\ntype AuthConfig struct {\n\t// Auth for this receiver.\n\tconfigauth.Config `mapstructure:\",squash\"`\n\n\t// RequestParameters is a list of parameters that should be extracted from the request and added to the context.\n\t// When a parameter is found in both the query string and the header, the value from the query string will be used.\n\tRequestParameters []string `mapstructure:\"request_params,omitempty\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// ToListener creates a net.Listener.\nfunc (sc *ServerConfig) ToListener(ctx context.Context) (net.Listener, error) {\n\tlistener, err := sc.NetAddr.Listen(ctx)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif sc.TLS.HasValue() {\n\t\tvar tlsCfg *tls.Config\n\t\ttlsCfg, err = sc.TLS.Get().LoadTLSConfig(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttlsCfg.NextProtos = []string{http2.NextProtoTLS, \"http/1.1\"}\n\t\tlistener = tls.NewListener(listener, tlsCfg)\n\t}\n\n\treturn listener, nil\n}\n\n// toServerOptions has options that change the behavior of the HTTP server\n// returned by ServerConfig.ToServer().\ntype toServerOptions = internal.ToServerOptions\n\n// ToServerOption is an option to change the behavior of the HTTP server\n// returned by ServerConfig.ToServer().\ntype ToServerOption = internal.ToServerOption\n\n// WithErrorHandler overrides the HTTP error handler that gets invoked\n// when there is a failure inside httpContentDecompressor.\nfunc WithErrorHandler(e func(w http.ResponseWriter, r *http.Request, errorMsg string, statusCode int)) ToServerOption {\n\treturn internal.ToServerOptionFunc(func(opts *toServerOptions) {\n\t\topts.ErrHandler = e\n\t})\n}\n\n// WithDecoder provides support for additional decoders to be configured\n// by the caller.\nfunc WithDecoder(key string, dec func(body io.ReadCloser) (io.ReadCloser, error)) ToServerOption {\n\treturn internal.ToServerOptionFunc(func(opts *toServerOptions) {\n\t\tif opts.Decoders == nil {\n\t\t\topts.Decoders = map[string]func(body io.ReadCloser) (io.ReadCloser, error){}\n\t\t}\n\t\topts.Decoders[key] = dec\n\t})\n}\n\n// ToServer creates an http.Server from settings object.\n//\n// To allow the configuration to reference middleware or authentication extensions,\n// the `extensions` argument should be the output of `host.GetExtensions()`.\n// It may also be `nil` in tests where no such extension is expected to be used.\nfunc (sc *ServerConfig) ToServer(ctx context.Context, extensions map[component.ID]component.Component, settings component.TelemetrySettings, handler http.Handler, opts ...ToServerOption) (*http.Server, error) {\n\tserverOpts := &toServerOptions{}\n\tserverOpts.Apply(opts...)\n\n\tif sc.MaxRequestBodySize <= 0 {\n\t\tsc.MaxRequestBodySize = defaultMaxRequestBodySize\n\t}\n\n\tif sc.CompressionAlgorithms == nil {\n\t\tsc.CompressionAlgorithms = defaultCompressionAlgorithms()\n\t}\n\n\t// Apply middlewares in reverse order so they execute in\n\t// forward order.  The first middleware runs after\n\t// decompression, below, preceded by Auth, CORS, etc.\n\tif len(sc.Middlewares) > 0 && extensions == nil {\n\t\treturn nil, errors.New(\"middlewares were configured but this component or its host does not support extensions\")\n\t}\n\tfor i := len(sc.Middlewares) - 1; i >= 0; i-- {\n\t\twrapper, err := sc.Middlewares[i].GetHTTPServerHandler(ctx, extensions)\n\t\t// If we failed to get the middleware\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\thandler, err = wrapper(ctx, handler)\n\t\t// If we failed to construct a wrapper\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\thandler = httpContentDecompressor(\n\t\thandler,\n\t\tsc.MaxRequestBodySize,\n\t\tserverOpts.ErrHandler,\n\t\tsc.CompressionAlgorithms,\n\t\tserverOpts.Decoders,\n\t)\n\n\tif sc.MaxRequestBodySize > 0 {\n\t\thandler = maxRequestBodySizeInterceptor(handler, sc.MaxRequestBodySize)\n\t}\n\n\tif sc.Auth.HasValue() {\n\t\tif extensions == nil {\n\t\t\treturn nil, errors.New(\"authentication was configured but this component or its host does not support extensions\")\n\t\t}\n\n\t\tauth := sc.Auth.Get()\n\t\tserver, err := auth.GetServerAuthenticator(ctx, extensions)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\thandler = authInterceptor(handler, server, auth.RequestParameters, serverOpts)\n\t}\n\n\tif sc.CORS.HasValue() && len(sc.CORS.Get().AllowedOrigins) > 0 {\n\t\tcorsConfig := sc.CORS.Get()\n\t\tco := cors.Options{\n\t\t\tAllowedOrigins:   corsConfig.AllowedOrigins,\n\t\t\tAllowCredentials: true,\n\t\t\tAllowedHeaders:   corsConfig.AllowedHeaders,\n\t\t\tMaxAge:           corsConfig.MaxAge,\n\t\t}\n\t\thandler = cors.New(co).Handler(handler)\n\t}\n\tif sc.CORS.HasValue() && len(sc.CORS.Get().AllowedOrigins) == 0 && len(sc.CORS.Get().AllowedHeaders) > 0 {\n\t\tsettings.Logger.Warn(\"The CORS configuration specifies allowed headers but no allowed origins, and is therefore ignored.\")\n\t}\n\n\tif sc.ResponseHeaders != nil {\n\t\thandler = responseHeadersHandler(handler, sc.ResponseHeaders)\n\t}\n\n\totelOpts := append(\n\t\t[]otelhttp.Option{\n\t\t\totelhttp.WithTracerProvider(settings.TracerProvider),\n\t\t\totelhttp.WithPropagators(otel.GetTextMapPropagator()),\n\t\t\totelhttp.WithSpanNameFormatter(func(_ string, r *http.Request) string {\n\t\t\t\t// https://opentelemetry.io/docs/specs/semconv/http/http-spans/#name:\n\t\t\t\t//\n\t\t\t\t//   \"HTTP span names SHOULD be {method} {target} if there is a (low-cardinality) target available.\n\t\t\t\t//   If there is no (low-cardinality) {target} available, HTTP span names SHOULD be {method}.\n\t\t\t\t//\n\t\t\t\t//   The {method} MUST be {http.request.method} if the method represents the original method known\n\t\t\t\t//   to the instrumentation. In other cases (when {http.request.method} is set to _OTHER),\n\t\t\t\t//   {method} MUST be HTTP.\n\t\t\t\t//\n\t\t\t\t//   Instrumentation MUST NOT default to using URI path as a {target}.\"\n\t\t\t\t//\n\t\t\t\tmethod := standardizeHTTPMethod(r.Method, \"HTTP\")\n\t\t\t\tif r.Pattern != \"\" {\n\t\t\t\t\treturn method + \" \" + r.Pattern\n\t\t\t\t}\n\t\t\t\treturn method\n\t\t\t}),\n\t\t\totelhttp.WithMeterProvider(settings.MeterProvider),\n\t\t},\n\t\tserverOpts.OtelhttpOpts...)\n\n\t// Enable OpenTelemetry observability plugin.\n\thandler = otelhttp.NewHandler(handler, \"\", otelOpts...)\n\n\t// wrap the current handler in an interceptor that will add client.Info to the request's context\n\thandler = &clientInfoHandler{\n\t\tnext:            handler,\n\t\tincludeMetadata: sc.IncludeMetadata,\n\t}\n\n\terrorLog, err := zap.NewStdLogAt(settings.Logger, zapcore.ErrorLevel)\n\tif err != nil {\n\t\treturn nil, err // If an error occurs while creating the logger, return nil and the error\n\t}\n\n\tserver := &http.Server{\n\t\tHandler:           handler,\n\t\tReadTimeout:       sc.ReadTimeout,\n\t\tReadHeaderTimeout: sc.ReadHeaderTimeout,\n\t\tWriteTimeout:      sc.WriteTimeout,\n\t\tIdleTimeout:       sc.IdleTimeout,\n\t\tErrorLog:          errorLog,\n\t}\n\n\t// Set keep-alives enabled/disabled\n\tserver.SetKeepAlivesEnabled(sc.KeepAlivesEnabled)\n\n\treturn server, err\n}\n\nfunc responseHeadersHandler(handler http.Handler, headers configopaque.MapList) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\th := w.Header()\n\n\t\tfor k, v := range headers.Iter {\n\t\t\th.Set(k, string(v))\n\t\t}\n\n\t\thandler.ServeHTTP(w, r)\n\t})\n}\n\n// CORSConfig configures a receiver for HTTP cross-origin resource sharing (CORS).\n// See the underlying https://github.com/rs/cors package for details.\ntype CORSConfig struct {\n\t// AllowedOrigins sets the allowed values of the Origin header for\n\t// HTTP/JSON requests to an OTLP receiver. An origin may contain a\n\t// wildcard (*) to replace 0 or more characters (e.g.,\n\t// \"http://*.domain.com\", or \"*\" to allow any origin).\n\tAllowedOrigins []string `mapstructure:\"allowed_origins,omitempty\"`\n\n\t// AllowedHeaders sets what headers will be allowed in CORS requests.\n\t// The Accept, Accept-Language, Content-Type, and Content-Language\n\t// headers are implicitly allowed. If no headers are listed,\n\t// X-Requested-With will also be accepted by default. Include \"*\" to\n\t// allow any request header.\n\tAllowedHeaders []string `mapstructure:\"allowed_headers,omitempty\"`\n\n\t// MaxAge sets the value of the Access-Control-Max-Age response header.\n\t// Set it to the number of seconds that browsers should cache a CORS\n\t// preflight response for.\n\tMaxAge int `mapstructure:\"max_age,omitempty\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// NewDefaultCORSConfig creates a default cross-origin resource sharing (CORS) configuration.\nfunc NewDefaultCORSConfig() CORSConfig {\n\treturn CORSConfig{}\n}\n\nfunc authInterceptor(next http.Handler, server extensionauth.Server, requestParams []string, serverOpts *internal.ToServerOptions) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tsources := r.Header\n\t\tquery := r.URL.Query()\n\t\tfor _, param := range requestParams {\n\t\t\tif val, ok := query[param]; ok {\n\t\t\t\tsources[param] = val\n\t\t\t}\n\t\t}\n\t\tctx, err := server.Authenticate(r.Context(), sources)\n\t\tif err != nil {\n\t\t\tif serverOpts.ErrHandler != nil {\n\t\t\t\tserverOpts.ErrHandler(w, r, err.Error(), http.StatusUnauthorized)\n\t\t\t} else {\n\t\t\t\thttp.Error(w, err.Error(), http.StatusUnauthorized)\n\t\t\t}\n\n\t\t\treturn\n\t\t}\n\n\t\tnext.ServeHTTP(w, r.WithContext(ctx))\n\t})\n}\n\nfunc maxRequestBodySizeInterceptor(next http.Handler, maxRecvSize int64) http.Handler {\n\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\tr.Body = http.MaxBytesReader(w, r.Body, maxRecvSize)\n\t\tnext.ServeHTTP(w, r)\n\t})\n}\n\n// standardizeHTTPMethod returns an upper case HTTP method if well-known, otherwise unknown.\n// Based on https://github.com/open-telemetry/opentelemetry-go-contrib/blob/1530d71edc6d40d0659187d069081b639ef1b394/instrumentation/github.com/emicklei/go-restful/otelrestful/internal/semconv/util.go#L119\nfunc standardizeHTTPMethod(method, unknown string) string {\n\tmethod = strings.ToUpper(method)\n\tswitch method {\n\tcase http.MethodConnect, http.MethodDelete, http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodPatch, http.MethodPost, http.MethodPut, http.MethodTrace:\n\t\treturn method\n\t}\n\treturn unknown\n}\n"
  },
  {
    "path": "config/confighttp/server_middleware_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confighttp\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configmiddleware\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensionmiddleware\"\n\t\"go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest\"\n)\n\n// testServerMiddleware is a test implementation of configmiddleware.Config\ntype testServerMiddleware struct {\n\textension.Extension\n\textensionmiddleware.GetHTTPHandlerFunc\n}\n\nfunc newTestServerMiddleware(name string) component.Component {\n\treturn &testServerMiddleware{\n\t\tExtension: extensionmiddlewaretest.NewNop(),\n\t\tGetHTTPHandlerFunc: func(_ context.Context) (extensionmiddleware.WrapHTTPHandlerFunc, error) {\n\t\t\treturn func(_ context.Context, handler http.Handler) (http.Handler, error) {\n\t\t\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\t\t// Append middleware name to the URL path\n\t\t\t\t\tr.URL.Path += name + \"/\"\n\n\t\t\t\t\t// Call the next handler in the chain\n\t\t\t\t\thandler.ServeHTTP(w, r)\n\n\t\t\t\t\t// Add middleware name to the response\n\t\t\t\t\t_, _ = w.Write([]byte(\"\\r\\nserved by \" + name))\n\t\t\t\t}), nil\n\t\t\t}, nil\n\t\t},\n\t}\n}\n\nfunc newTestServerConfig(name string) configmiddleware.Config {\n\treturn configmiddleware.Config{\n\t\tID: component.MustNewID(name),\n\t}\n}\n\nfunc TestServerMiddleware(t *testing.T) {\n\t// Register two test extensions\n\textensions := map[component.ID]component.Component{\n\t\tcomponent.MustNewID(\"test1\"): newTestServerMiddleware(\"test1\"),\n\t\tcomponent.MustNewID(\"test2\"): newTestServerMiddleware(\"test2\"),\n\t}\n\n\t// Test with different middleware configurations\n\ttestCases := []struct {\n\t\tname           string\n\t\tmiddlewares    []configmiddleware.Config\n\t\texpectedOutput string\n\t}{\n\t\t{\n\t\t\tname:           \"no_middlewares\",\n\t\t\tmiddlewares:    nil,\n\t\t\texpectedOutput: \"OK{/}\",\n\t\t},\n\t\t{\n\t\t\tname: \"single_middleware\",\n\t\t\tmiddlewares: []configmiddleware.Config{\n\t\t\t\tnewTestServerConfig(\"test1\"),\n\t\t\t},\n\t\t\texpectedOutput: \"OK{/test1/}\\r\\nserved by test1\",\n\t\t},\n\t\t{\n\t\t\tname: \"multiple_middlewares\",\n\t\t\tmiddlewares: []configmiddleware.Config{\n\t\t\t\tnewTestServerConfig(\"test1\"),\n\t\t\t\tnewTestServerConfig(\"test2\"),\n\t\t\t},\n\t\t\texpectedOutput: \"OK{/test1/test2/}\\r\\nserved by test2\\r\\nserved by test1\",\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t// Create server config with the test middlewares\n\t\t\tcfg := ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tMiddlewares: tc.middlewares,\n\t\t\t}\n\n\t\t\t// Create a test handler that responds with the request path\n\t\t\thandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\t_, _ = w.Write([]byte(\"OK{\" + r.URL.Path + \"}\"))\n\t\t\t})\n\n\t\t\t// Create the server\n\t\t\tsrv, err := cfg.ToServer(\n\t\t\t\tcontext.Background(),\n\t\t\t\textensions,\n\t\t\t\tcomponenttest.NewNopTelemetrySettings(),\n\t\t\t\thandler,\n\t\t\t)\n\t\t\trequire.NoError(t, err)\n\n\t\t\t// Create a test request\n\t\t\treq := httptest.NewRequest(http.MethodGet, \"/\", http.NoBody)\n\n\t\t\t// Create a response recorder\n\t\t\trec := httptest.NewRecorder()\n\n\t\t\t// Serve the request\n\t\t\tsrv.Handler.ServeHTTP(rec, req)\n\n\t\t\t// Get the response\n\t\t\tresp := rec.Result()\n\t\t\tdefer resp.Body.Close()\n\n\t\t\t// Check the response\n\t\t\tbody, err := io.ReadAll(resp.Body)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tassert.Equal(t, tc.expectedOutput, string(body))\n\t\t})\n\t}\n}\n\nfunc TestServerMiddlewareErrors(t *testing.T) {\n\t// Create a basic handler for testing\n\thandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\t_, _ = w.Write([]byte(\"OK\"))\n\t})\n\n\t// Test cases for HTTP server middleware errors\n\thttpTests := []struct {\n\t\tname       string\n\t\textensions map[component.ID]component.Component\n\t\tconfig     ServerConfig\n\t\terrText    string\n\t}{\n\t\t{\n\t\t\tname:       \"extension_not_found\",\n\t\t\textensions: map[component.ID]component.Component{},\n\t\t\tconfig: ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tMiddlewares: []configmiddleware.Config{\n\t\t\t\t\t{\n\t\t\t\t\t\tID: component.MustNewID(\"nonexistent\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\terrText: \"failed to resolve middleware \\\"nonexistent\\\": middleware not found\",\n\t\t},\n\t\t{\n\t\t\tname: \"get_http_handler_fails\",\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\tcomponent.MustNewID(\"errormw\"): extensionmiddlewaretest.NewErr(errors.New(\"http middleware error\")),\n\t\t\t},\n\t\t\tconfig: ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tMiddlewares: []configmiddleware.Config{\n\t\t\t\t\t{\n\t\t\t\t\t\tID: component.MustNewID(\"errormw\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\terrText: \"http middleware error\",\n\t\t},\n\t}\n\n\tfor _, tc := range httpTests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t// Trying to create the server should fail\n\t\t\t_, err := tc.config.ToServer(\n\t\t\t\tcontext.Background(),\n\t\t\t\ttc.extensions,\n\t\t\t\tcomponenttest.NewNopTelemetrySettings(),\n\t\t\t\thandler,\n\t\t\t)\n\t\t\trequire.Error(t, err)\n\t\t\tassert.Contains(t, err.Error(), tc.errText)\n\t\t})\n\t}\n\n\t// Test cases for gRPC server middleware errors\n\tgrpcTests := []struct {\n\t\tname       string\n\t\textensions map[component.ID]component.Component\n\t\tconfig     ServerConfig\n\t\terrText    string\n\t}{\n\t\t{\n\t\t\tname:       \"grpc_extension_not_found\",\n\t\t\textensions: map[component.ID]component.Component{},\n\t\t\tconfig: ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tMiddlewares: []configmiddleware.Config{\n\t\t\t\t\t{\n\t\t\t\t\t\tID: component.MustNewID(\"nonexistent\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\terrText: \"failed to resolve middleware \\\"nonexistent\\\": middleware not found\",\n\t\t},\n\t\t{\n\t\t\tname: \"get_grpc_handler_fails\",\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\tcomponent.MustNewID(\"errormw\"): extensionmiddlewaretest.NewErr(errors.New(\"grpc middleware error\")),\n\t\t\t},\n\t\t\tconfig: ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tMiddlewares: []configmiddleware.Config{\n\t\t\t\t\t{\n\t\t\t\t\t\tID: component.MustNewID(\"errormw\"),\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\terrText: \"grpc middleware error\",\n\t\t},\n\t}\n\n\tfor _, tc := range grpcTests {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t// Trying to create the server should fail\n\t\t\t_, err := tc.config.ToServer(\n\t\t\t\tcontext.Background(),\n\t\t\t\ttc.extensions,\n\t\t\t\tcomponenttest.NewNopTelemetrySettings(),\n\t\t\t\thandler,\n\t\t\t)\n\t\t\trequire.Error(t, err)\n\t\t\tassert.Contains(t, err.Error(), tc.errText)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "config/confighttp/server_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confighttp\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configauth\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensionauth\"\n)\n\nvar (\n\t_ extension.Extension  = (*mockAuthServer)(nil)\n\t_ extensionauth.Server = (*mockAuthServer)(nil)\n)\n\ntype mockAuthServer struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\textensionauth.ServerAuthenticateFunc\n}\n\nfunc newMockAuthServer(auth func(ctx context.Context, sources map[string][]string) (context.Context, error)) extension.Extension {\n\treturn &mockAuthServer{ServerAuthenticateFunc: auth}\n}\n\nfunc TestHTTPServerSettingsError(t *testing.T) {\n\ttests := []struct {\n\t\tsettings ServerConfig\n\t\terr      string\n\t}{\n\t\t{\n\t\t\terr: \"^failed to load TLS config: failed to load CA CertPool File: failed to load cert /doesnt/exist:\",\n\t\t\tsettings: ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tTLS: configoptional.Some(configtls.ServerConfig{\n\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\tCAFile: \"/doesnt/exist\",\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\terr: \"^failed to load TLS config: failed to load TLS cert and key: for auth via TLS, provide both certificate and key, or neither\",\n\t\t\tsettings: ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tTLS: configoptional.Some(configtls.ServerConfig{\n\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\tCertFile: \"/doesnt/exist\",\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\terr: \"failed to load client CA CertPool: failed to load CA /doesnt/exist:\",\n\t\t\tsettings: ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tTLS: configoptional.Some(configtls.ServerConfig{\n\t\t\t\t\tClientCAFile: \"/doesnt/exist\",\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.err, func(t *testing.T) {\n\t\t\t_, err := tt.settings.ToListener(context.Background())\n\t\t\tassert.Regexp(t, tt.err, err)\n\t\t})\n\t}\n}\n\nfunc TestHTTPServerTLS(t *testing.T) {\n\ttests := []struct {\n\t\tname           string\n\t\ttlsServerCreds configoptional.Optional[configtls.ServerConfig]\n\t\ttlsClientCreds *configtls.ClientConfig\n\t\thasError       bool\n\t\tforceHTTP1     bool\n\t}{\n\t\t{\n\t\t\tname:           \"noTLS\",\n\t\t\ttlsServerCreds: configoptional.None[configtls.ServerConfig](),\n\t\t\ttlsClientCreds: &configtls.ClientConfig{\n\t\t\t\tInsecure: true,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"TLS\",\n\t\t\ttlsServerCreds: configoptional.Some(configtls.ServerConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t\tCertFile: filepath.Join(\"testdata\", \"server.crt\"),\n\t\t\t\t\tKeyFile:  filepath.Join(\"testdata\", \"server.key\"),\n\t\t\t\t},\n\t\t\t}),\n\t\t\ttlsClientCreds: &configtls.ClientConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile: filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t},\n\t\t\t\tServerName: \"localhost\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"TLS (HTTP/1.1)\",\n\t\t\ttlsServerCreds: configoptional.Some(configtls.ServerConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t\tCertFile: filepath.Join(\"testdata\", \"server.crt\"),\n\t\t\t\t\tKeyFile:  filepath.Join(\"testdata\", \"server.key\"),\n\t\t\t\t},\n\t\t\t}),\n\t\t\ttlsClientCreds: &configtls.ClientConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile: filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t},\n\t\t\t\tServerName: \"localhost\",\n\t\t\t},\n\t\t\tforceHTTP1: true,\n\t\t},\n\t\t{\n\t\t\tname: \"NoServerCertificates\",\n\t\t\ttlsServerCreds: configoptional.Some(configtls.ServerConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile: filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t},\n\t\t\t}),\n\t\t\ttlsClientCreds: &configtls.ClientConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile: filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t},\n\t\t\t\tServerName: \"localhost\",\n\t\t\t},\n\t\t\thasError: true,\n\t\t},\n\t\t{\n\t\t\tname: \"mTLS\",\n\t\t\ttlsServerCreds: configoptional.Some(configtls.ServerConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t\tCertFile: filepath.Join(\"testdata\", \"server.crt\"),\n\t\t\t\t\tKeyFile:  filepath.Join(\"testdata\", \"server.key\"),\n\t\t\t\t},\n\t\t\t\tClientCAFile: filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t}),\n\t\t\ttlsClientCreds: &configtls.ClientConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t\tCertFile: filepath.Join(\"testdata\", \"client.crt\"),\n\t\t\t\t\tKeyFile:  filepath.Join(\"testdata\", \"client.key\"),\n\t\t\t\t},\n\t\t\t\tServerName: \"localhost\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"NoClientCertificate\",\n\t\t\ttlsServerCreds: configoptional.Some(configtls.ServerConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t\tCertFile: filepath.Join(\"testdata\", \"server.crt\"),\n\t\t\t\t\tKeyFile:  filepath.Join(\"testdata\", \"server.key\"),\n\t\t\t\t},\n\t\t\t\tClientCAFile: filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t}),\n\t\t\ttlsClientCreds: &configtls.ClientConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile: filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t},\n\t\t\t\tServerName: \"localhost\",\n\t\t\t},\n\t\t\thasError: true,\n\t\t},\n\t\t{\n\t\t\tname: \"WrongClientCA\",\n\t\t\ttlsServerCreds: configoptional.Some(configtls.ServerConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t\tCertFile: filepath.Join(\"testdata\", \"server.crt\"),\n\t\t\t\t\tKeyFile:  filepath.Join(\"testdata\", \"server.key\"),\n\t\t\t\t},\n\t\t\t\tClientCAFile: filepath.Join(\"testdata\", \"server.crt\"),\n\t\t\t}),\n\t\t\ttlsClientCreds: &configtls.ClientConfig{\n\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\t\t\tCertFile: filepath.Join(\"testdata\", \"client.crt\"),\n\t\t\t\t\tKeyFile:  filepath.Join(\"testdata\", \"client.key\"),\n\t\t\t\t},\n\t\t\t\tServerName: \"localhost\",\n\t\t\t},\n\t\t\thasError: true,\n\t\t},\n\t}\n\t// prepare\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsc := &ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tTLS: tt.tlsServerCreds,\n\t\t\t}\n\t\t\tln, err := sc.ToListener(context.Background())\n\t\t\trequire.NoError(t, err)\n\n\t\t\tstartServer(t, sc, ln, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\t\t\t_, errWrite := fmt.Fprint(w, \"tt\")\n\t\t\t\tassert.NoError(t, errWrite)\n\t\t\t}))\n\n\t\t\tprefix := \"https://\"\n\t\t\texpectedProto := \"HTTP/2.0\"\n\t\t\tif tt.tlsClientCreds.Insecure {\n\t\t\t\tprefix = \"http://\"\n\t\t\t\texpectedProto = \"HTTP/1.1\"\n\t\t\t}\n\n\t\t\tcc := &ClientConfig{\n\t\t\t\tEndpoint:          prefix + ln.Addr().String(),\n\t\t\t\tTLS:               *tt.tlsClientCreds,\n\t\t\t\tForceAttemptHTTP2: true,\n\t\t\t}\n\n\t\t\tclient, errClient := cc.ToClient(context.Background(), nil, nilProvidersSettings)\n\t\t\trequire.NoError(t, errClient)\n\n\t\t\tif tt.forceHTTP1 {\n\t\t\t\texpectedProto = \"HTTP/1.1\"\n\t\t\t\tclient.Transport.(*http.Transport).ForceAttemptHTTP2 = false\n\t\t\t}\n\n\t\t\tresp, errResp := client.Get(cc.Endpoint)\n\t\t\tif tt.hasError {\n\t\t\t\trequire.Error(t, errResp)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, errResp)\n\t\t\t\tbody, errRead := io.ReadAll(resp.Body)\n\t\t\t\trequire.NoError(t, errRead)\n\t\t\t\tassert.Equal(t, \"tt\", string(body))\n\t\t\t\tassert.Equal(t, expectedProto, resp.Proto)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestHTTPServerTransport(t *testing.T) {\n\tif runtime.GOOS == \"linux\" {\n\t\tt.Run(\"unix\", func(t *testing.T) {\n\t\t\taddr := \"@\" + t.Name() // abstract unix socket\n\t\t\tsc := &ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  addr,\n\t\t\t\t\tTransport: confignet.TransportTypeUnix,\n\t\t\t\t},\n\t\t\t}\n\t\t\tln, err := sc.ToListener(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t\tstartServer(t, sc, ln, http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))\n\n\t\t\tclient := http.Client{\n\t\t\t\tTransport: &http.Transport{\n\t\t\t\t\tDialContext: func(_ context.Context, _, _ string) (net.Conn, error) {\n\t\t\t\t\t\treturn net.Dial(\"unix\", addr)\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tTimeout: 5 * time.Second, // Set a client-level timeout\n\t\t\t}\n\t\t\tresp, err := client.Get(\"http://whatever/foo\")\n\t\t\trequire.NoError(t, err)\n\t\t\tdefer resp.Body.Close()\n\t\t\tassert.Equal(t, http.StatusOK, resp.StatusCode)\n\t\t})\n\t}\n}\n\nfunc TestHTTPCors(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\n\t\tCORSConfig configoptional.Optional[CORSConfig]\n\n\t\tallowedWorks     bool\n\t\tdisallowedWorks  bool\n\t\textraHeaderWorks bool\n\t}{\n\t\t{\n\t\t\tname:             \"noCORS\",\n\t\t\tallowedWorks:     false,\n\t\t\tdisallowedWorks:  false,\n\t\t\textraHeaderWorks: false,\n\t\t},\n\t\t{\n\t\t\tname:             \"emptyCORS\",\n\t\t\tCORSConfig:       configoptional.Some(NewDefaultCORSConfig()),\n\t\t\tallowedWorks:     false,\n\t\t\tdisallowedWorks:  false,\n\t\t\textraHeaderWorks: false,\n\t\t},\n\t\t{\n\t\t\tname: \"OriginCORS\",\n\t\t\tCORSConfig: configoptional.Some(CORSConfig{\n\t\t\t\tAllowedOrigins: []string{\"allowed-*.com\"},\n\t\t\t}),\n\t\t\tallowedWorks:     true,\n\t\t\tdisallowedWorks:  false,\n\t\t\textraHeaderWorks: false,\n\t\t},\n\t\t{\n\t\t\tname: \"CacheableCORS\",\n\t\t\tCORSConfig: configoptional.Some(CORSConfig{\n\t\t\t\tAllowedOrigins: []string{\"allowed-*.com\"},\n\t\t\t\tMaxAge:         360,\n\t\t\t}),\n\t\t\tallowedWorks:     true,\n\t\t\tdisallowedWorks:  false,\n\t\t\textraHeaderWorks: false,\n\t\t},\n\t\t{\n\t\t\tname: \"HeaderCORS\",\n\t\t\tCORSConfig: configoptional.Some(CORSConfig{\n\t\t\t\tAllowedOrigins: []string{\"allowed-*.com\"},\n\t\t\t\tAllowedHeaders: []string{\"ExtraHeader\"},\n\t\t\t}),\n\t\t\tallowedWorks:     true,\n\t\t\tdisallowedWorks:  false,\n\t\t\textraHeaderWorks: true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsc := &ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tCORS: tt.CORSConfig,\n\t\t\t}\n\n\t\t\tln, err := sc.ToListener(context.Background())\n\t\t\trequire.NoError(t, err)\n\n\t\t\tstartServer(t, sc, ln, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t}))\n\n\t\t\turl := \"http://\" + ln.Addr().String()\n\n\t\t\texpectedStatus := http.StatusNoContent\n\t\t\tif !tt.CORSConfig.HasValue() || len(tt.CORSConfig.Get().AllowedOrigins) == 0 {\n\t\t\t\texpectedStatus = http.StatusOK\n\t\t\t}\n\n\t\t\t// Verify allowed domain gets responses that allow CORS.\n\t\t\tverifyCorsResp(t, url, \"allowed-origin.com\", tt.CORSConfig, false, expectedStatus, tt.allowedWorks)\n\n\t\t\t// Verify allowed domain and extra headers gets responses that allow CORS.\n\t\t\tverifyCorsResp(t, url, \"allowed-origin.com\", tt.CORSConfig, true, expectedStatus, tt.extraHeaderWorks)\n\n\t\t\t// Verify disallowed domain gets responses that disallow CORS.\n\t\t\tverifyCorsResp(t, url, \"disallowed-origin.com\", tt.CORSConfig, false, expectedStatus, tt.disallowedWorks)\n\t\t})\n\t}\n}\n\nfunc TestHTTPCorsInvalidSettings(t *testing.T) {\n\tsc := &ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  \"localhost:0\",\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t\tCORS: configoptional.Some(CORSConfig{AllowedHeaders: []string{\"some-header\"}}),\n\t}\n\n\t// This effectively does not enable CORS but should also not cause an error\n\ts, err := sc.ToServer(\n\t\tcontext.Background(),\n\t\tnil,\n\t\tcomponenttest.NewNopTelemetrySettings(),\n\t\thttp.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, s)\n\trequire.NoError(t, s.Close())\n}\n\nfunc TestHTTPCorsWithSettings(t *testing.T) {\n\tsc := &ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  \"localhost:0\",\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t\tCORS: configoptional.Some(CORSConfig{\n\t\t\tAllowedOrigins: []string{\"*\"},\n\t\t}),\n\t\tAuth: configoptional.Some(AuthConfig{\n\t\t\tConfig: configauth.Config{\n\t\t\t\tAuthenticatorID: mockID,\n\t\t\t},\n\t\t}),\n\t}\n\n\textensions := map[component.ID]component.Component{\n\t\tmockID: newMockAuthServer(func(ctx context.Context, _ map[string][]string) (context.Context, error) {\n\t\t\treturn ctx, errors.New(\"Settings failed\")\n\t\t}),\n\t}\n\n\tsrv, err := sc.ToServer(context.Background(), extensions, componenttest.NewNopTelemetrySettings(), nil)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, srv)\n\n\trec := httptest.NewRecorder()\n\treq := httptest.NewRequest(http.MethodOptions, \"/\", http.NoBody)\n\treq.Header.Set(\"Origin\", \"http://localhost\")\n\treq.Header.Set(\"Access-Control-Request-Method\", http.MethodPost)\n\tsrv.Handler.ServeHTTP(rec, req)\n\n\tassert.Equal(t, http.StatusNoContent, rec.Result().StatusCode)\n\tassert.Equal(t, \"*\", rec.Header().Get(\"Access-Control-Allow-Origin\"))\n}\n\nfunc TestHTTPServerHeaders(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\theaders configopaque.MapList\n\t}{\n\t\t{\n\t\t\tname:    \"noHeaders\",\n\t\t\theaders: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"withHeaders\",\n\t\t\theaders: configopaque.MapList{\n\t\t\t\t{Name: \"x-new-header-1\", Value: \"value1\"},\n\t\t\t\t{Name: \"x-new-header-2\", Value: \"value2\"},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsc := &ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tResponseHeaders: tt.headers,\n\t\t\t}\n\n\t\t\tln, err := sc.ToListener(context.Background())\n\t\t\trequire.NoError(t, err)\n\n\t\t\tstartServer(t, sc, ln, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t}))\n\n\t\t\turl := \"http://\" + ln.Addr().String()\n\n\t\t\t// Verify allowed domain gets responses that allow CORS.\n\t\t\tverifyHeadersResp(t, url, tt.headers)\n\t\t})\n\t}\n}\n\nfunc verifyCorsResp(t *testing.T, url, origin string, set configoptional.Optional[CORSConfig], extraHeader bool, wantStatus int, wantAllowed bool) {\n\treq, err := http.NewRequest(http.MethodOptions, url, http.NoBody)\n\trequire.NoError(t, err, \"Error creating trace OPTIONS request: %v\", err)\n\treq.Header.Set(\"Origin\", origin)\n\tif extraHeader {\n\t\treq.Header.Set(\"ExtraHeader\", \"foo\")\n\t\treq.Header.Set(\"Access-Control-Request-Headers\", \"extraheader\")\n\t}\n\treq.Header.Set(\"Access-Control-Request-Method\", \"POST\")\n\n\tresp, err := http.DefaultClient.Do(req)\n\trequire.NoError(t, err, \"Error sending OPTIONS to http server\")\n\trequire.NotNil(t, resp.Body)\n\trequire.NoError(t, resp.Body.Close(), \"Error closing OPTIONS response body\")\n\n\tassert.Equal(t, wantStatus, resp.StatusCode)\n\n\tgotAllowOrigin := resp.Header.Get(\"Access-Control-Allow-Origin\")\n\tgotAllowMethods := resp.Header.Get(\"Access-Control-Allow-Methods\")\n\n\twantAllowOrigin := \"\"\n\twantAllowMethods := \"\"\n\twantMaxAge := \"\"\n\tif wantAllowed {\n\t\twantAllowOrigin = origin\n\t\twantAllowMethods = \"POST\"\n\t\tif set.HasValue() && set.Get().MaxAge != 0 {\n\t\t\twantMaxAge = strconv.Itoa(set.Get().MaxAge)\n\t\t}\n\t}\n\tassert.Equal(t, wantAllowOrigin, gotAllowOrigin)\n\tassert.Equal(t, wantAllowMethods, gotAllowMethods)\n\tassert.Equal(t, wantMaxAge, resp.Header.Get(\"Access-Control-Max-Age\"))\n}\n\nfunc verifyHeadersResp(t *testing.T, url string, expected configopaque.MapList) {\n\treq, err := http.NewRequest(http.MethodGet, url, http.NoBody)\n\trequire.NoError(t, err, \"Error creating request\")\n\n\tresp, err := http.DefaultClient.Do(req)\n\trequire.NoError(t, err, \"Error sending request to http server\")\n\trequire.NotNil(t, resp.Body)\n\trequire.NoError(t, resp.Body.Close(), \"Error closing response body\")\n\n\tassert.Equal(t, http.StatusOK, resp.StatusCode)\n\n\tfor k, v := range expected.Iter {\n\t\tassert.Equal(t, string(v), resp.Header.Get(k))\n\t}\n}\n\nfunc TestServerAuth(t *testing.T) {\n\t// prepare\n\tauthCalled := false\n\tsc := ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  \"localhost:0\",\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t\tAuth: configoptional.Some(AuthConfig{\n\t\t\tConfig: configauth.Config{\n\t\t\t\tAuthenticatorID: mockID,\n\t\t\t},\n\t\t}),\n\t}\n\n\textensions := map[component.ID]component.Component{\n\t\tmockID: newMockAuthServer(func(ctx context.Context, _ map[string][]string) (context.Context, error) {\n\t\t\tauthCalled = true\n\t\t\treturn ctx, nil\n\t\t}),\n\t}\n\n\thandlerCalled := false\n\thandler := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {\n\t\thandlerCalled = true\n\t})\n\n\tsrv, err := sc.ToServer(context.Background(), extensions, componenttest.NewNopTelemetrySettings(), handler)\n\trequire.NoError(t, err)\n\n\t// tt\n\tsrv.Handler.ServeHTTP(&httptest.ResponseRecorder{}, httptest.NewRequest(http.MethodGet, \"/\", http.NoBody))\n\n\t// verify\n\tassert.True(t, handlerCalled)\n\tassert.True(t, authCalled)\n}\n\nfunc TestInvalidServerAuth(t *testing.T) {\n\tsc := ServerConfig{\n\t\tAuth: configoptional.Some(AuthConfig{\n\t\t\tConfig: configauth.Config{\n\t\t\t\tAuthenticatorID: nonExistingID,\n\t\t\t},\n\t\t}),\n\t}\n\n\tsrv, err := sc.ToServer(context.Background(), nil, componenttest.NewNopTelemetrySettings(), http.NewServeMux())\n\trequire.Error(t, err)\n\trequire.Nil(t, srv)\n}\n\nfunc TestFailedServerAuth(t *testing.T) {\n\t// prepare\n\tsc := ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  \"localhost:0\",\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t\tAuth: configoptional.Some(AuthConfig{\n\t\t\tConfig: configauth.Config{\n\t\t\t\tAuthenticatorID: mockID,\n\t\t\t},\n\t\t}),\n\t}\n\textensions := map[component.ID]component.Component{\n\t\tmockID: newMockAuthServer(func(ctx context.Context, _ map[string][]string) (context.Context, error) {\n\t\t\treturn ctx, errors.New(\"invalid authorization\")\n\t\t}),\n\t}\n\n\tsrv, err := sc.ToServer(context.Background(), extensions, componenttest.NewNopTelemetrySettings(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))\n\trequire.NoError(t, err)\n\n\t// tt\n\tresponse := &httptest.ResponseRecorder{}\n\tsrv.Handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, \"/\", http.NoBody))\n\n\t// verify\n\tassert.Equal(t, http.StatusUnauthorized, response.Result().StatusCode)\n\tassert.Equal(t, fmt.Sprintf(\"%v %s\", http.StatusUnauthorized, http.StatusText(http.StatusUnauthorized)), response.Result().Status)\n}\n\nfunc TestFailedServerAuthWithErrorHandler(t *testing.T) {\n\t// prepare\n\tsc := ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  \"localhost:0\",\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t\tAuth: configoptional.Some(AuthConfig{\n\t\t\tConfig: configauth.Config{\n\t\t\t\tAuthenticatorID: mockID,\n\t\t\t},\n\t\t}),\n\t}\n\textensions := map[component.ID]component.Component{\n\t\tmockID: newMockAuthServer(func(ctx context.Context, _ map[string][]string) (context.Context, error) {\n\t\t\treturn ctx, errors.New(\"invalid authorization\")\n\t\t}),\n\t}\n\n\teh := func(w http.ResponseWriter, _ *http.Request, err string, statusCode int) {\n\t\tassert.Equal(t, http.StatusUnauthorized, statusCode)\n\t\t// custom error handler uses real error string\n\t\tassert.Equal(t, \"invalid authorization\", err)\n\t\t// custom error handler changes returned status code\n\t\thttp.Error(w, err, http.StatusInternalServerError)\n\t}\n\n\tsrv, err := sc.ToServer(context.Background(), extensions, componenttest.NewNopTelemetrySettings(), http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}), WithErrorHandler(eh))\n\trequire.NoError(t, err)\n\n\t// tt\n\tresponse := &httptest.ResponseRecorder{}\n\tsrv.Handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, \"/\", http.NoBody))\n\n\t// verify\n\tassert.Equal(t, http.StatusInternalServerError, response.Result().StatusCode)\n\tassert.Equal(t, fmt.Sprintf(\"%v %s\", http.StatusInternalServerError, http.StatusText(http.StatusInternalServerError)), response.Result().Status)\n}\n\nfunc TestServerWithErrorHandler(t *testing.T) {\n\t// prepare\n\tsc := ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  \"localhost:0\",\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t}\n\teh := func(w http.ResponseWriter, _ *http.Request, _ string, statusCode int) {\n\t\tassert.Equal(t, http.StatusBadRequest, statusCode)\n\t\t// custom error handler changes returned status code\n\t\thttp.Error(w, \"invalid request\", http.StatusInternalServerError)\n\t}\n\n\tsrv, err := sc.ToServer(\n\t\tcontext.Background(),\n\t\tnil,\n\t\tcomponenttest.NewNopTelemetrySettings(),\n\t\thttp.HandlerFunc(func(http.ResponseWriter, *http.Request) {}),\n\t\tWithErrorHandler(eh),\n\t)\n\trequire.NoError(t, err)\n\t// tt\n\tresponse := &httptest.ResponseRecorder{}\n\n\treq, err := http.NewRequest(http.MethodGet, srv.Addr, http.NoBody)\n\trequire.NoError(t, err, \"Error creating request: %v\", err)\n\treq.Header.Set(\"Content-Encoding\", \"something-invalid\")\n\n\tsrv.Handler.ServeHTTP(response, req)\n\t// verify\n\tassert.Equal(t, http.StatusInternalServerError, response.Result().StatusCode)\n}\n\nfunc TestServerWithDecoder(t *testing.T) {\n\t// prepare\n\tsc := NewDefaultServerConfig()\n\tsc.NetAddr.Endpoint = \"localhost:0\"\n\tdecoder := func(body io.ReadCloser) (io.ReadCloser, error) {\n\t\treturn body, nil\n\t}\n\n\tsrv, err := sc.ToServer(\n\t\tcontext.Background(),\n\t\tnil,\n\t\tcomponenttest.NewNopTelemetrySettings(),\n\t\thttp.HandlerFunc(func(http.ResponseWriter, *http.Request) {}),\n\t\tWithDecoder(\"something-else\", decoder),\n\t)\n\trequire.NoError(t, err)\n\t// tt\n\tresponse := &httptest.ResponseRecorder{}\n\n\treq, err := http.NewRequest(http.MethodGet, srv.Addr, bytes.NewBuffer([]byte(\"something\")))\n\trequire.NoError(t, err, \"Error creating request: %v\", err)\n\treq.Header.Set(\"Content-Encoding\", \"something-else\")\n\n\tsrv.Handler.ServeHTTP(response, req)\n\t// verify\n\tassert.Equal(t, http.StatusOK, response.Result().StatusCode)\n}\n\nfunc TestServerWithDecompression(t *testing.T) {\n\t// prepare\n\tsc := ServerConfig{\n\t\tMaxRequestBodySize: 1000, // 1 KB\n\t}\n\tbody := []byte(strings.Repeat(\"a\", 1000*1000)) // 1 MB\n\n\tsrv, err := sc.ToServer(\n\t\tcontext.Background(),\n\t\tnil,\n\t\tcomponenttest.NewNopTelemetrySettings(),\n\t\thttp.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {\n\t\t\tactualBody, err := io.ReadAll(req.Body)\n\t\t\tassert.ErrorContains(t, err, \"http: request body too large\")\n\t\t\tassert.Len(t, actualBody, 1000)\n\n\t\t\tif err != nil {\n\t\t\t\tresp.WriteHeader(http.StatusBadRequest)\n\t\t\t} else {\n\t\t\t\tresp.WriteHeader(http.StatusOK)\n\t\t\t}\n\t\t}),\n\t)\n\trequire.NoError(t, err)\n\n\ttestSrv := httptest.NewServer(srv.Handler)\n\tdefer testSrv.Close()\n\n\treq, err := http.NewRequest(http.MethodGet, testSrv.URL, compressZstd(t, body))\n\trequire.NoError(t, err, \"Error creating request: %v\", err)\n\n\treq.Header.Set(\"Content-Encoding\", \"zstd\")\n\n\t// tt\n\tc := http.Client{}\n\tresp, err := c.Do(req)\n\trequire.NoError(t, err, \"Error sending request: %v\", err)\n\n\t_, err = io.ReadAll(resp.Body)\n\trequire.NoError(t, err, \"Error reading response body: %v\", err)\n\n\t// verifications is done mostly within the tt, but this is only a sanity check\n\t// that we got into the tt handler\n\tassert.Equal(t, http.StatusBadRequest, resp.StatusCode)\n}\n\nfunc TestDefaultMaxRequestBodySize(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tsettings ServerConfig\n\t\texpected int64\n\t}{\n\t\t{\n\t\t\tname:     \"default\",\n\t\t\tsettings: ServerConfig{},\n\t\t\texpected: defaultMaxRequestBodySize,\n\t\t},\n\t\t{\n\t\t\tname:     \"zero\",\n\t\t\tsettings: ServerConfig{MaxRequestBodySize: 0},\n\t\t\texpected: defaultMaxRequestBodySize,\n\t\t},\n\t\t{\n\t\t\tname:     \"negative\",\n\t\t\tsettings: ServerConfig{MaxRequestBodySize: -1},\n\t\t\texpected: defaultMaxRequestBodySize,\n\t\t},\n\t\t{\n\t\t\tname:     \"custom\",\n\t\t\tsettings: ServerConfig{MaxRequestBodySize: 100},\n\t\t\texpected: 100,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t_, err := tt.settings.ToServer(\n\t\t\t\tcontext.Background(),\n\t\t\t\tnil,\n\t\t\t\tcomponenttest.NewNopTelemetrySettings(),\n\t\t\t\thttp.HandlerFunc(func(http.ResponseWriter, *http.Request) {}),\n\t\t\t)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tt.expected, tt.settings.MaxRequestBodySize)\n\t\t})\n\t}\n}\n\nfunc TestAuthWithQueryParams(t *testing.T) {\n\t// prepare\n\tauthCalled := false\n\tsc := ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  \"localhost:0\",\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t\tAuth: configoptional.Some(AuthConfig{\n\t\t\tRequestParameters: []string{\"auth\"},\n\t\t\tConfig: configauth.Config{\n\t\t\t\tAuthenticatorID: mockID,\n\t\t\t},\n\t\t}),\n\t}\n\n\textensions := map[component.ID]component.Component{\n\t\tmockID: newMockAuthServer(func(ctx context.Context, sources map[string][]string) (context.Context, error) {\n\t\t\trequire.Len(t, sources, 1)\n\t\t\tassert.Equal(t, \"1\", sources[\"auth\"][0])\n\t\t\tauthCalled = true\n\t\t\treturn ctx, nil\n\t\t}),\n\t}\n\n\thandlerCalled := false\n\thandler := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {\n\t\thandlerCalled = true\n\t})\n\n\tsrv, err := sc.ToServer(context.Background(), extensions, componenttest.NewNopTelemetrySettings(), handler)\n\trequire.NoError(t, err)\n\n\t// tt\n\tsrv.Handler.ServeHTTP(&httptest.ResponseRecorder{}, httptest.NewRequest(http.MethodGet, \"/?auth=1\", http.NoBody))\n\n\t// verify\n\tassert.True(t, handlerCalled)\n\tassert.True(t, authCalled)\n}\n\nfunc BenchmarkHTTPRequest(b *testing.B) {\n\ttests := []struct {\n\t\tname            string\n\t\tforceHTTP1      bool\n\t\tclientPerThread bool\n\t}{\n\t\t{\n\t\t\tname:            \"HTTP/2.0, shared client (like load balancer)\",\n\t\t\tforceHTTP1:      false,\n\t\t\tclientPerThread: false,\n\t\t},\n\t\t{\n\t\t\tname:            \"HTTP/1.1, shared client (like load balancer)\",\n\t\t\tforceHTTP1:      true,\n\t\t\tclientPerThread: false,\n\t\t},\n\t\t{\n\t\t\tname:            \"HTTP/2.0, client per thread (like single app)\",\n\t\t\tforceHTTP1:      false,\n\t\t\tclientPerThread: true,\n\t\t},\n\t\t{\n\t\t\tname:            \"HTTP/1.1, client per thread (like single app)\",\n\t\t\tforceHTTP1:      true,\n\t\t\tclientPerThread: true,\n\t\t},\n\t}\n\n\ttlsServerCreds := configoptional.Some(configtls.ServerConfig{\n\t\tConfig: configtls.Config{\n\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t\tCertFile: filepath.Join(\"testdata\", \"server.crt\"),\n\t\t\tKeyFile:  filepath.Join(\"testdata\", \"server.key\"),\n\t\t},\n\t})\n\ttlsClientCreds := &configtls.ClientConfig{\n\t\tConfig: configtls.Config{\n\t\t\tCAFile: filepath.Join(\"testdata\", \"ca.crt\"),\n\t\t},\n\t\tServerName: \"localhost\",\n\t}\n\n\tsc := &ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  \"localhost:0\",\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t\tTLS: tlsServerCreds,\n\t}\n\n\tln, err := sc.ToListener(context.Background())\n\trequire.NoError(b, err)\n\n\tstartServer(b, sc, ln, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\t_, errWrite := fmt.Fprint(w, \"tt\")\n\t\tassert.NoError(b, errWrite)\n\t}))\n\n\tfor _, bb := range tests {\n\t\tcc := &ClientConfig{\n\t\t\tEndpoint: \"https://\" + ln.Addr().String(),\n\t\t\tTLS:      *tlsClientCreds,\n\t\t}\n\n\t\tb.Run(bb.name, func(b *testing.B) {\n\t\t\tvar c *http.Client\n\t\t\tif !bb.clientPerThread {\n\t\t\t\tc, err = cc.ToClient(context.Background(), nil, nilProvidersSettings)\n\t\t\t\trequire.NoError(b, err)\n\t\t\t}\n\t\t\tb.RunParallel(func(pb *testing.PB) {\n\t\t\t\tif c == nil {\n\t\t\t\t\tc, err = cc.ToClient(context.Background(), nil, nilProvidersSettings)\n\t\t\t\t\trequire.NoError(b, err)\n\t\t\t\t}\n\t\t\t\tif bb.forceHTTP1 {\n\t\t\t\t\tc.Transport.(*http.Transport).ForceAttemptHTTP2 = false\n\t\t\t\t}\n\n\t\t\t\tfor pb.Next() {\n\t\t\t\t\tresp, errResp := c.Get(cc.Endpoint)\n\t\t\t\t\trequire.NoError(b, errResp)\n\t\t\t\t\tbody, errRead := io.ReadAll(resp.Body)\n\t\t\t\t\t_ = resp.Body.Close()\n\t\t\t\t\trequire.NoError(b, errRead)\n\t\t\t\t\trequire.Equal(b, \"tt\", string(body))\n\t\t\t\t}\n\t\t\t\tc.CloseIdleConnections()\n\t\t\t})\n\t\t\t// Wait for connections to close before closing server to prevent log spam\n\t\t\t<-time.After(10 * time.Millisecond)\n\t\t})\n\t}\n}\n\nfunc TestDefaultHTTPServerSettings(t *testing.T) {\n\thttpServerSettings := NewDefaultServerConfig()\n\tassert.NotNil(t, httpServerSettings.CORS)\n\tassert.NotNil(t, httpServerSettings.TLS)\n\tassert.Equal(t, 1*time.Minute, httpServerSettings.IdleTimeout)\n\tassert.Equal(t, 30*time.Second, httpServerSettings.WriteTimeout)\n\tassert.Equal(t, time.Duration(0), httpServerSettings.ReadTimeout)\n\tassert.Equal(t, 1*time.Minute, httpServerSettings.ReadHeaderTimeout)\n\tassert.True(t, httpServerSettings.KeepAlivesEnabled) // Default should be true (keep-alives enabled by default)\n}\n\nfunc TestHTTPServerKeepAlives(t *testing.T) {\n\ttests := []struct {\n\t\tname               string\n\t\tkeepAlivesEnabled  bool\n\t\texpectedKeepAlives bool\n\t}{\n\t\t{\n\t\t\tname:               \"KeepAlives enabled\",\n\t\t\tkeepAlivesEnabled:  true,\n\t\t\texpectedKeepAlives: true,\n\t\t},\n\t\t{\n\t\t\tname:               \"KeepAlives disabled\",\n\t\t\tkeepAlivesEnabled:  false,\n\t\t\texpectedKeepAlives: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsc := &ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tKeepAlivesEnabled: tt.keepAlivesEnabled,\n\t\t\t}\n\n\t\t\tln, err := sc.ToListener(context.Background())\n\t\t\trequire.NoError(t, err)\n\n\t\t\tstartServer(t, sc, ln, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\t\t\tw.WriteHeader(http.StatusOK)\n\t\t\t}))\n\n\t\t\t// Since http.Server.disableKeepAlives is a private field and difficult to test directly,\n\t\t\t// we'll verify the configuration was set by testing the server behavior.\n\t\t\t// The main verification is that ToServer() succeeds without error when DisableKeepAlives is set.\n\n\t\t\tresp, err := http.Get(\"http://\" + ln.Addr().String())\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NotNil(t, resp)\n\t\t\t_ = resp.Body.Close()\n\t\t\tassert.Equal(t, http.StatusOK, resp.StatusCode)\n\n\t\t\tassert.Equal(t, tt.keepAlivesEnabled, sc.KeepAlivesEnabled)\n\t\t})\n\t}\n}\n\nfunc TestHTTPServerTelemetry_Tracing(t *testing.T) {\n\t// Create a pattern route. The server name the span after the\n\t// pattern rather than the client-specified path.\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/b/{bucket}/o/{objectname...}\", func(http.ResponseWriter, *http.Request) {})\n\n\ttype testcase struct {\n\t\thandler          http.Handler\n\t\thttpMethod       string\n\t\texpectedSpanName string\n\t}\n\n\tfor name, tc := range map[string]testcase{\n\t\t\"pattern\": {\n\t\t\thandler:          mux,\n\t\t\thttpMethod:       \"GET\",\n\t\t\texpectedSpanName: \"GET /b/{bucket}/o/{objectname...}\",\n\t\t},\n\t\t\"no_pattern\": {\n\t\t\thandler:          http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}),\n\t\t\thttpMethod:       \"GET\",\n\t\t\texpectedSpanName: \"GET\",\n\t\t},\n\t\t\"unknown_method\": {\n\t\t\thandler:          mux,\n\t\t\thttpMethod:       \"FOOBAR\",\n\t\t\texpectedSpanName: \"HTTP /b/{bucket}/o/{objectname...}\",\n\t\t},\n\t\t\"lowercase_method\": {\n\t\t\thandler:          mux,\n\t\t\thttpMethod:       \"get\",\n\t\t\texpectedSpanName: \"GET /b/{bucket}/o/{objectname...}\",\n\t\t},\n\t} {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\ttelemetry := componenttest.NewTelemetry()\n\t\t\tconfig := NewDefaultServerConfig()\n\t\t\tconfig.NetAddr.Endpoint = \"localhost:0\"\n\t\t\tsrv, err := config.ToServer(\n\t\t\t\tcontext.Background(),\n\t\t\t\tnil,\n\t\t\t\ttelemetry.NewTelemetrySettings(),\n\t\t\t\ttc.handler,\n\t\t\t)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdone := make(chan struct{})\n\t\t\tlis, err := config.ToListener(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t\tgo func() {\n\t\t\t\tdefer close(done)\n\t\t\t\t_ = srv.Serve(lis)\n\t\t\t}()\n\t\t\tdefer func() {\n\t\t\t\tassert.NoError(t, srv.Close())\n\t\t\t\t<-done\n\t\t\t}()\n\n\t\t\treq, err := http.NewRequest(tc.httpMethod, fmt.Sprintf(\"http://%s/b/bucket123/o/object456/segment\", lis.Addr()), http.NoBody)\n\t\t\trequire.NoError(t, err)\n\t\t\tresp, err := http.DefaultClient.Do(req)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, http.StatusOK, resp.StatusCode)\n\t\t\tresp.Body.Close()\n\n\t\t\tspans := telemetry.SpanRecorder.Ended()\n\t\t\trequire.Len(t, spans, 1)\n\t\t\tassert.Equal(t, tc.expectedSpanName, spans[0].Name())\n\t\t})\n\t}\n}\n\n// TestUnmarshalYAMLWithMiddlewares tests that the \"middlewares\" field is correctly\n// parsed from YAML configurations (fixing the bug where \"middleware\" was used instead)\nfunc TestServerUnmarshalYAMLWithMiddlewares(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"middlewares.yaml\"))\n\trequire.NoError(t, err)\n\n\t// Test server configuration\n\tvar serverConfig ServerConfig\n\tserverSub, err := cm.Sub(\"server\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, serverSub.Unmarshal(&serverConfig))\n\n\t// Validate the server configuration using reflection-based validation\n\trequire.NoError(t, xconfmap.Validate(&serverConfig), \"Server configuration should be valid\")\n\n\tassert.Equal(t, \"0.0.0.0:4318\", serverConfig.NetAddr.Endpoint)\n\trequire.Len(t, serverConfig.Middlewares, 2)\n\tassert.Equal(t, component.MustNewID(\"careful_middleware\"), serverConfig.Middlewares[0].ID)\n\tassert.Equal(t, component.MustNewID(\"support_middleware\"), serverConfig.Middlewares[1].ID)\n}\n\n// TestUnmarshalYAMLComprehensiveConfig tests the complete configuration example\n// to ensure all fields including middlewares are parsed correctly\nfunc TestServerUnmarshalYAMLComprehensiveConfig(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\n\t// Test server configuration\n\tvar serverConfig ServerConfig\n\tserverSub, err := cm.Sub(\"server\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, serverSub.Unmarshal(&serverConfig))\n\n\t// Validate the server configuration using reflection-based validation\n\trequire.NoError(t, xconfmap.Validate(&serverConfig), \"Server configuration should be valid\")\n\n\t// Verify basic fields\n\tassert.Equal(t, \"0.0.0.0:4318\", serverConfig.NetAddr.Endpoint)\n\tassert.Equal(t, 30*time.Second, serverConfig.ReadTimeout)\n\tassert.Equal(t, 10*time.Second, serverConfig.ReadHeaderTimeout)\n\tassert.Equal(t, 30*time.Second, serverConfig.WriteTimeout)\n\tassert.Equal(t, 120*time.Second, serverConfig.IdleTimeout)\n\tassert.True(t, serverConfig.KeepAlivesEnabled) // Should be true as configured in config.yaml\n\tassert.Equal(t, int64(33554432), serverConfig.MaxRequestBodySize)\n\tassert.True(t, serverConfig.IncludeMetadata)\n\n\t// Verify TLS configuration\n\tassert.Equal(t, \"/path/to/server.crt\", serverConfig.TLS.Get().CertFile)\n\tassert.Equal(t, \"/path/to/server.key\", serverConfig.TLS.Get().KeyFile)\n\tassert.Equal(t, \"/path/to/ca.crt\", serverConfig.TLS.Get().CAFile)\n\tassert.Equal(t, \"/path/to/client-ca.crt\", serverConfig.TLS.Get().ClientCAFile)\n\n\t// Verify CORS configuration\n\texpectedOrigins := []string{\"https://example.com\", \"https://*.test.com\"}\n\tassert.Equal(t, expectedOrigins, serverConfig.CORS.Get().AllowedOrigins)\n\tcorsHeaders := []string{\"Content-Type\", \"Accept\"}\n\tassert.Equal(t, corsHeaders, serverConfig.CORS.Get().AllowedHeaders)\n\tassert.Equal(t, 7200, serverConfig.CORS.Get().MaxAge)\n\n\t// Verify response headers\n\texpectedResponseHeaders := configopaque.MapList{\n\t\t{Name: \"Server\", Value: \"OpenTelemetry-Collector\"},\n\t\t{Name: \"X-Flavor\", Value: \"apple\"},\n\t}\n\tassert.Equal(t, expectedResponseHeaders, serverConfig.ResponseHeaders)\n\n\t// Verify compression algorithms\n\texpectedAlgorithms := []string{\"\", \"gzip\", \"zstd\", \"zlib\", \"snappy\", \"deflate\"}\n\tassert.Equal(t, expectedAlgorithms, serverConfig.CompressionAlgorithms)\n\n\t// Verify middlewares\n\trequire.Len(t, serverConfig.Middlewares, 3)\n\tassert.Equal(t, component.MustNewID(\"server_middleware1\"), serverConfig.Middlewares[0].ID)\n\tassert.Equal(t, component.MustNewID(\"server_middleware2\"), serverConfig.Middlewares[1].ID)\n\tassert.Equal(t, component.MustNewID(\"server_middleware3\"), serverConfig.Middlewares[2].ID)\n}\n\nfunc startServer(tb testing.TB, sc *ServerConfig, ln net.Listener, h http.Handler) {\n\ts, err := sc.ToServer(tb.Context(), nil, componenttest.NewNopTelemetrySettings(), h)\n\trequire.NoError(tb, err)\n\ttb.Cleanup(func() {\n\t\trequire.NoError(tb, s.Close())\n\t})\n\tgo func() { _ = s.Serve(ln) }()\n}\n"
  },
  {
    "path": "config/confighttp/testdata/ca.crt",
    "content": "-----BEGIN CERTIFICATE-----\nMIIDNjCCAh4CCQCBqDI24JacNTANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJB\nVTESMBAGA1UECAwJQXVzdHJhbGlhMQ8wDQYDVQQHDAZTeWRuZXkxEjAQBgNVBAoM\nCU15T3JnTmFtZTEVMBMGA1UEAwwMTXlDb21tb25OYW1lMB4XDTIyMDgwMzA0MTAx\nN1oXDTMyMDczMTA0MTAxN1owXTELMAkGA1UEBhMCQVUxEjAQBgNVBAgMCUF1c3Ry\nYWxpYTEPMA0GA1UEBwwGU3lkbmV5MRIwEAYDVQQKDAlNeU9yZ05hbWUxFTATBgNV\nBAMMDE15Q29tbW9uTmFtZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB\nANFDGZCSxNdaJQ1q7P5qVAZDKCj+3ClpFWAVT5HYDlOqgIjYRZ45/YGfKsDbK6rj\n/+v5xTnTZt8e8kRfPgrZTBtPtefu6tKwxYYr3sSCR3TU4bX4dIM9ZwrFaTrPP1hk\nUXR8zlk7F6gcWS+WX7LdupMs5SdZIePhkzpkxYIBatdRMf7w2f5v6M3UnOrCoyz0\nYPvvyZKq5zo9uBlVkrUL/QDrOB5yYjith7l8FkLHAirGTaszfF+8pZwzZn4ykVbn\neQQs1g6ujR0DgQh/k6A6XDQfg4JWQqNt3kkiO7NPIHTrl+W/nKdqve864ECAHSM2\nNIgGtQqVavPKD6pr15V328cCAwEAATANBgkqhkiG9w0BAQsFAAOCAQEALZuCeu8U\nyjJlR+BbDqiZw7/EBpGgTX4mv9CofJc9ErxFGJTYiaLZ1Jf3bwE+0G9ym8UfxKG8\n9xCYmoVbEQhgLzYDpYPxkKi5X7RUMw9fKlbRqwy2Ek1mDnSIYPRalhfOXBT5E652\nOUeILLRJlAPL3SrALjJM5Jjn4pkwankE53mfU4LpC7xWOjuwkSPRor1XCwoAZMTz\nEZsZGUQf5M69ZAy0wWHu4C94rlgD37hybUEzhsr9UiK2v1Gn3a7BSAgtkbD0OIe5\nBzCu+UHQO4u841SbXn4q8aO1idaR8UhPAqfVno+L7ZmHRGsgvMk1vlMbroIIYaAz\n2LQP6IwYUWRM9Q==\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "config/confighttp/testdata/client.crt",
    "content": "-----BEGIN CERTIFICATE-----\nMIIDVTCCAj2gAwIBAgIJANt5fkUlfxyOMA0GCSqGSIb3DQEBCwUAMF0xCzAJBgNV\nBAYTAkFVMRIwEAYDVQQIDAlBdXN0cmFsaWExDzANBgNVBAcMBlN5ZG5leTESMBAG\nA1UECgwJTXlPcmdOYW1lMRUwEwYDVQQDDAxNeUNvbW1vbk5hbWUwHhcNMjIwODAz\nMDQxMDE3WhcNMzIwNzMxMDQxMDE3WjBdMQswCQYDVQQGEwJBVTESMBAGA1UECAwJ\nQXVzdHJhbGlhMQ8wDQYDVQQHDAZTeWRuZXkxEjAQBgNVBAoMCU15T3JnTmFtZTEV\nMBMGA1UEAwwMTXlDb21tb25OYW1lMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\nCgKCAQEApmnIUees+b/V5gEgEOwyjPo9xeejzd/DSo02x/syauoU4mhINwa8cuB+\nnvGhCUY5w+bZfOnWhY03wjnqM1Ay+sg7yHZgqeHclzQh5d39ojeaMa3x8c3IQsKZ\nj/UTyYmkX6Gap8Z8fk1ucM43clM3nUUf3THzeo0X3MTm7FIs2OCxcbCYo8GUo6GV\nrn7nhutOrYgyPrgo7bi8xF2sJRRKC/C7MBCeNaJlgj53jB93gF15/ZxPbAQCtI5R\nJ+3YrKp987RSuXtDeqm1zSCmV6LnT2vVsSNmnDdvWHQF7SqgauqT0Z7gm4/M/xXw\nge6GJaENOV1wIUsfbYj6UCMt6tZpjQIDAQABoxgwFjAUBgNVHREEDTALgglsb2Nh\nbGhvc3QwDQYJKoZIhvcNAQELBQADggEBAHwMOQIz++7JPWRb3xHTkt6jIlAw/zVl\n3UmdXMqEEscLGcjmDqu0u1qPGlS48Ukb4efAQsp+/2KLQex7jdl3r4p0+3O530AY\nMEtlK2oH1uE3KDMyswA0INrGeZpHRP2BI6QJGbxcJN22MuHFmKwPBJlltgVtK0Gt\nIhG/cRJnVMcX+iBdsxygW5u7P8MpC8Eoved/F8yKB66uJ4LyZC5KL9RG58Y0JJin\nKDvpzSGLMnHgnuJlGOGz/uUYXZ4IX5g95yKiDZ9+GkVo+DRHAUNEUjfQSRujmO10\nINTHs4/hd0MI6NaHXwObvmOsa8VRRVWa995O5Y9rZMYg/4mjm1Axcm4=\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "config/confighttp/testdata/client.key",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEApmnIUees+b/V5gEgEOwyjPo9xeejzd/DSo02x/syauoU4mhI\nNwa8cuB+nvGhCUY5w+bZfOnWhY03wjnqM1Ay+sg7yHZgqeHclzQh5d39ojeaMa3x\n8c3IQsKZj/UTyYmkX6Gap8Z8fk1ucM43clM3nUUf3THzeo0X3MTm7FIs2OCxcbCY\no8GUo6GVrn7nhutOrYgyPrgo7bi8xF2sJRRKC/C7MBCeNaJlgj53jB93gF15/ZxP\nbAQCtI5RJ+3YrKp987RSuXtDeqm1zSCmV6LnT2vVsSNmnDdvWHQF7SqgauqT0Z7g\nm4/M/xXwge6GJaENOV1wIUsfbYj6UCMt6tZpjQIDAQABAoIBAEAIGfUyAMPEhchP\njIgWakkGjLhWrhesTtejyH1gcYDj+w828vqBVAeby/zamo0YAWgYrny6+TlAIkFQ\nyYXfCQ6n9yDmM8GKT7e6boSlS0+ct28AMEVLWhAeErpqoad9l8rYQsrlu8dZgfJT\n1s/dp1uTWnRhIP95xMHE3dn2sJzuEV9HunkgS6re6YyTqNZFLAPVn33wDRVSaxH6\n3VJG6T3Y2xs77AKTKz5Mji/gqK3XFAed0rehowgS4A8mEUrZt9gzioRlmV2tshvx\nst5KDw7lGEZKbgGB/+cwLJhHgEK7KyJRsR/shtDyXKRlEC19qV6zSupz9BSQNqRN\n+vWQ070CgYEA0NTYgdxz8msVMXtLCectwMLfLU99H/frGCvjBv0wLni2XF+eS9gX\nD6W4nFbDA+wZfSBMpEqriHvrDpMk7RN3Q9rAKtqeyzDboWiJRRT4DZeRz9o+WEt3\n+wDP8W0dS7IRw8Jnrsj9JgmY35fGXZDUWZRnPuvrpolojUnMTKNK/ccCgYEAzAA1\nroKRNOn08P3SZ0jCUA0O+Ke5sycV6QPoLk5qQnL5eEjOlvd+6U128DAf1DW5O6/8\nC0YsTMOY/sQxXliSt/iygaJVoo7Tt1L60ctNY4KX5EiWs2AgvvTu89ESwbhvvfvw\nXt7PNfa0eBSgC+Lrg5y2Lahs8DijWkTbxo3ebgsCgYEAmyLjzGUnRZnDXsUHE85H\nsQGTpid8/rjAT26a82A34O4QG0N1Z0aaqycjpBDYQxusO8Y46XwHPhdAoc0yC2UA\nnsntJGjQuoYLQzdTcpyHQiGtUsoAsrst4KvTzriOoOMiS1kqiTAKz60lgkVQOcYT\n2pBiut2sbEV8BCokuXI9jZUCgYBbg9yRJNGvQyU21ycEXoeNEc6djeColegmWDJY\nU6Unmhx/8Wl8IBs23iF1LqGYuWEXfaM8C4bkCPshjzH2eRWYomCx9vkjq58epoMO\nin11Hqi1KDsyzPTjtU1c43Xeoba/K75xUNL0CnB7TgVeT7YHnM29PclhGodtf2Z4\ndDxMcQKBgQC46rtyosn/2uR+88DCWSVTnc4cA6tOEB8WP7Z7mk8yOv1CGgyP4187\niDPL+91O4C5sT02MFuwElCmxuO1RQQhVTGzIxPd9RQ7t+l1PorTeodYF/ezrRl47\nxuxp4nF50ThlTf1AuhQxpPC1JsXqkH3d582ZLErzrgijMYxk5sYJRA==\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "config/confighttp/testdata/config.yaml",
    "content": "# Comprehensive HTTP configuration example showing all available options\n# with middleware configurations (using the new \"middlewares\" field)\n\n# HTTP Client Configuration\nclient:\n  # The target URL to send data to\n  endpoint: \"http://example.com:4318/v1/traces\"\n\n  # Proxy URL setting for the collector\n  proxy_url: \"http://proxy.example.com:8080\"\n\n  # TLS configuration\n  tls:\n    insecure: false\n    cert_file: \"/path/to/client.crt\"\n    key_file: \"/path/to/client.key\"\n    ca_file: \"/path/to/ca.crt\"\n    server_name_override: \"example.com\"\n    insecure_skip_verify: false\n\n  # HTTP client buffer sizes\n  read_buffer_size: 4096\n  write_buffer_size: 4096\n\n  # Request timeout\n  timeout: 30s\n\n  # Custom headers\n  headers:\n    \"User-Agent\": \"OpenTelemetry-Collector/1.0\"\n    \"X-Custom-Header\": \"custom-value\"\n\n  # Compression setting\n  compression: \"gzip\"\n\n  # Disable HTTP/2\n  disable_keep_alives: false\n  http2_read_idle_timeout: 10s\n  http2_ping_timeout: 15s\n\n  # Maximum idle connections\n  max_idle_conns: 100\n  max_idle_conns_per_host: 10\n  max_conns_per_host: 50\n  idle_conn_timeout: 90s\n\n  # Authentication configuration\n  auth:\n    authenticator: \"oauth2client\"\n\n  # Cookies configuration\n  cookies:\n    enabled: true\n\n  # Middlewares configuration (note: plural \"middlewares\")\n  middlewares:\n    - id: \"middleware1\"\n    - id: \"middleware2\"\n\n# HTTP Server Configuration\nserver:\n  # Network endpoint configuration\n  endpoint: \"0.0.0.0:4318\"\n  transport: tcp\n\n  # TLS configuration\n  tls:\n    cert_file: \"/path/to/server.crt\"\n    key_file: \"/path/to/server.key\"\n    ca_file: \"/path/to/ca.crt\"\n    client_ca_file: \"/path/to/client-ca.crt\"\n    reload_interval: 24h\n\n  # CORS configuration\n  cors:\n    allowed_origins:\n      - \"https://example.com\"\n      - \"https://*.test.com\"\n    allowed_headers:\n      - \"Content-Type\"\n      - \"Accept\"\n    max_age: 7200\n\n  # Authentication configuration\n  auth:\n    authenticator: \"basic\"\n\n  # Server timeouts\n  read_timeout: 30s\n  read_header_timeout: 10s\n  write_timeout: 30s\n  idle_timeout: 120s\n\n  # HTTP keep-alives configuration\n  keep_alives_enabled: true\n\n  # Maximum request size\n  max_request_body_size: 33554432  # 32MB\n\n  # Include metadata in the context\n  include_metadata: true\n\n  # Response headers to add to every response\n  response_headers:\n    \"Server\": \"OpenTelemetry-Collector\"\n    \"X-Flavor\": \"apple\"\n\n  # Compression algorithms supported by the server\n  compression_algorithms: [\"\", \"gzip\", \"zstd\", \"zlib\", \"snappy\", \"deflate\"]\n\n  # Middlewares configuration (note: plural \"middlewares\")\n  middlewares:\n    - id: \"server_middleware1\"\n    - id: \"server_middleware2\"\n    - id: \"server_middleware3\"\n"
  },
  {
    "path": "config/confighttp/testdata/middlewares.yaml",
    "content": "# Simple middleware-focused test configuration\n\nclient:\n  endpoint: \"http://localhost:4318/v1/traces\"\n  middlewares:\n    - id: \"fancy_middleware\"\n    - id: \"careful_middleware\"\n\nserver:\n  endpoint: \"0.0.0.0:4318\"\n  transport: tcp\n  middlewares:\n    - id: \"careful_middleware\"\n    - id: \"support_middleware\"\n"
  },
  {
    "path": "config/confighttp/testdata/server.crt",
    "content": "-----BEGIN CERTIFICATE-----\nMIIDVTCCAj2gAwIBAgIJANt5fkUlfxyNMA0GCSqGSIb3DQEBCwUAMF0xCzAJBgNV\nBAYTAkFVMRIwEAYDVQQIDAlBdXN0cmFsaWExDzANBgNVBAcMBlN5ZG5leTESMBAG\nA1UECgwJTXlPcmdOYW1lMRUwEwYDVQQDDAxNeUNvbW1vbk5hbWUwHhcNMjIwODAz\nMDQxMDE3WhcNMzIwNzMxMDQxMDE3WjBdMQswCQYDVQQGEwJBVTESMBAGA1UECAwJ\nQXVzdHJhbGlhMQ8wDQYDVQQHDAZTeWRuZXkxEjAQBgNVBAoMCU15T3JnTmFtZTEV\nMBMGA1UEAwwMTXlDb21tb25OYW1lMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\nCgKCAQEAupEXxNIX+2k0PC/yLfuWSbFr22eLwYSYkPDydFENKYID905hcWqaqr4o\nu1Fu8nofbeKrpTgmx7lwXB5VIkdNcnwLyt40nPETGN2m0vBa7Bm6z/KJTW0iHmTz\n5fVzt9rggnRTRSovNy43weKoZXHcl/lmGbGy+lqQ69jJTT9yXipkMTIkscYgSHK3\nGVxUhrsBc/mZyBLSj3Tpt3Az71N4npTp6XYbgx4MhllbH9xFlw2hLs1DU+vwJhSE\nw99UrLhRz8L3ePmShdkySD9QZxCKD5euiumVfPLfzWV2JmLejC3MD3sd5ql+5itv\nWrnYPcky3OclXcnZgDo+ZloWLYPWhQIDAQABoxgwFjAUBgNVHREEDTALgglsb2Nh\nbGhvc3QwDQYJKoZIhvcNAQELBQADggEBAJGfixdI6T6dxb37fJPNa0Uerq5aZPb9\nGLJg3CqkZ4yjfsveZ91lH7fRPRjXld3aMb6978kpoczGYJeAdY8j0BPvA+UfsuYO\nbzm6HUgiTjyCnLPQIuAlzuYDsBQhzz6gdRclgnuQ8JO/xTDIxVLJDuueannqEn9x\ns/RQ5PeWf0D+zvSu4p8UENKfaPqoI5q7nb93IHL38PMDfB7n4oEDIkG0zfxX/zYI\nh5ZhzlWSscfCRE4Hdcb8RcSuzwI2JzidMY/ZXUr20iNuCSbv4zhsoDASk7Ud+yj4\nd4JkdOA4NbaT8/aR+Ectc2ItBc2lb0xzEqQnjg3zRQjEzeryHN0hxWU=\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "config/confighttp/testdata/server.key",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIBAAKCAQEAupEXxNIX+2k0PC/yLfuWSbFr22eLwYSYkPDydFENKYID905h\ncWqaqr4ou1Fu8nofbeKrpTgmx7lwXB5VIkdNcnwLyt40nPETGN2m0vBa7Bm6z/KJ\nTW0iHmTz5fVzt9rggnRTRSovNy43weKoZXHcl/lmGbGy+lqQ69jJTT9yXipkMTIk\nscYgSHK3GVxUhrsBc/mZyBLSj3Tpt3Az71N4npTp6XYbgx4MhllbH9xFlw2hLs1D\nU+vwJhSEw99UrLhRz8L3ePmShdkySD9QZxCKD5euiumVfPLfzWV2JmLejC3MD3sd\n5ql+5itvWrnYPcky3OclXcnZgDo+ZloWLYPWhQIDAQABAoIBAF8u/01vUsT126yJ\nWamUHgzi9AAwR+EnYR8xjsFBSNHQf22BE73lgZtzARzwYwZawAY0CxZ0G3TyaxzU\nbOLcNese1nVeAMHBTNj23NHpxrmGNwU43EwgTbPsFXNRUwSOKtTjvEghSY2Bivjk\nRr3a5YyztR+OxZ1s71skcy9yG0tmveGRQS2Gn3SrLgrX7PjgUULpd7TNkWlAyTB7\nsFvVeHVEv8AcFDvHCBvlNJvMG2WT7kD4vjbRc0V1y89D4wO3kNVumajNjiSUopsU\nzFe1vegcSLIgf1i2QEtXLob6mrQJplDA3G8oQX4FF0Oovk/bLwzC6IHNeFOo5eFM\nTfGzd9ECgYEA6Ixx+2Bai2zdSz19NVaQEksDVdT/ivorgYGpIllLOwjU3ZCIEs2J\niNNPlIX9uFcwIGcfoHsU66iUWrwprfnbloezq5aPdHuhW2PE+JUEBqzmQDy+ax/i\nHI2IaD42+OJY5RdRfS7cvczIFrW9XECCTkhr08CxZTO7W7VCP0OnpPMCgYEAzWGQ\nhHgpyj5kfco/KlRrK6bQBkhbqWkbkoZohVL6hJ2UxC/NBFS3fWYQ2LFyFPBdu+lI\nRXkDxroCQJfWGNAe4PlbKcWh5Q9Ps/s8wl0DIR/KM2yhzE2GqfDC6pQ3xFpizbcm\njl+AL2U6Y9Et1nvPjZKo6STf5yrEdIuHgaq61KcCgYEA4g/tmf2/53vr4AGlXx2I\nLpBHbMADrzmk41+FaMO/M2NRcxXWgdjW03EAEpTy4am4Ojelch9UZgZaOZ5jMiIL\nSlke2zYgvI6WfD4Ps8tAv7CCoH2sanzzFOitaxDX5bg7zHCPog7VPZj+Bb2kmDKJ\nucoDMDVI/eV9RBh/jvqY1OsCgYEAx5iYxVSucGFgcis6Zd3y5VJRermZczO12xmK\nvH9e/cDTUjKOUTYvuMuXdbBFiXnr7nIRjYrFE72z8KhfJnAkgklzwk3SP3U45VY1\nv0J7hxaJAJ8DQzTYuZFFLIptBAM/YGMtMlI3llgPffBNVtOuawzr4OC4RMV4dTcg\nsvCEb6MCgYEAnRx87p5bAgDVug3pdFI7qRi5Tgxa25c5GsFwhmmr3EgtxKQKLFIH\nG6KOWJBpFePVrz3PH71d+J1mB/g8GqzpHBuYTBDD3hyz8iKHN+pmoM4m2/tTqKRY\n26XUGOUIxnksgsw2O2R9AASrEm4hhAg5AxmANgqOIZijIcHWF8q9QpE=\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "config/confighttp/xconfighttp/Makefile",
    "content": "include ../../../Makefile.Common\n"
  },
  {
    "path": "config/confighttp/xconfighttp/go.mod",
    "content": "module go.opentelemetry.io/collector/config/confighttp/xconfighttp\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/config/confighttp v0.148.0\n\tgo.opentelemetry.io/collector/config/confignet v1.54.0\n\tgo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0\n\tgo.opentelemetry.io/otel/sdk v1.42.0\n\tgo.opentelemetry.io/otel/trace v1.42.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/felixge/httpsnoop v1.0.4 // indirect\n\tgithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f // indirect\n\tgithub.com/fsnotify/fsnotify v1.9.0 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/golang/snappy v1.0.0 // indirect\n\tgithub.com/google/go-tpm v0.9.8 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/klauspost/compress v1.18.4 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pierrec/lz4/v4 v4.1.26 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/rs/cors v1.11.1 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/client v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/component v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configauth v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configcompression v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configmiddleware v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configopaque v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configoptional v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configtls v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/confmap v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionauth v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionmiddleware v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/crypto v0.48.0 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/config/confighttp => ../../confighttp\n\nreplace go.opentelemetry.io/collector/client => ../../../client\n\nreplace go.opentelemetry.io/collector/consumer => ../../../consumer\n\nreplace go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest => ../../../extension/extensionauth/extensionauthtest\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../../component/componenttest\n\nreplace go.opentelemetry.io/collector/config/configauth => ../../configauth\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../../configoptional\n\nreplace go.opentelemetry.io/collector/pdata => ../../../pdata\n\nreplace go.opentelemetry.io/collector/extension/extensionauth => ../../../extension/extensionauth\n\nreplace go.opentelemetry.io/collector/config/configopaque => ../../configopaque\n\nreplace go.opentelemetry.io/collector/component => ../../../component\n\nreplace go.opentelemetry.io/collector/extension => ../../../extension\n\nreplace go.opentelemetry.io/collector/config/configtls => ../../configtls\n\nreplace go.opentelemetry.io/collector/config/configcompression => ../../configcompression\n\nreplace go.opentelemetry.io/collector/featuregate => ../../../featuregate\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ../../../extension/extensionmiddleware\n\nreplace go.opentelemetry.io/collector/config/configmiddleware => ../../configmiddleware\n\nreplace go.opentelemetry.io/collector/config/confignet => ../../confignet\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest => ../../../extension/extensionmiddleware/extensionmiddlewaretest\n\nreplace go.opentelemetry.io/collector/confmap => ../../../confmap\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../../internal/componentalias\n"
  },
  {
    "path": "config/confighttp/xconfighttp/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=\ngithub.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f h1:RJ+BDPLSHQO7cSjKBqjPJSbi1qfk9WcsjQDtZiw3dZw=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f/go.mod h1:VHbbch/X4roIY22jL1s3qRbZhCiRIgUAF/PdSUcx2io=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=\ngithub.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=\ngithub.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=\ngithub.com/google/go-tpm-tools v0.4.7 h1:J3ycC8umYxM9A4eF73EofRZu4BxY0jjQnUnkhIBbvws=\ngithub.com/google/go-tpm-tools v0.4.7/go.mod h1:gSyXTZHe3fgbzb6WEGd90QucmsnT1SRdlye82gH8QjQ=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=\ngithub.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=\ngithub.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=\ngithub.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=\ngolang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=\ngonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "config/confighttp/xconfighttp/metadata.yaml",
    "content": "type: config/confighttp/xconfighttp\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "config/confighttp/xconfighttp/options.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xconfighttp // import \"go.opentelemetry.io/collector/config/confighttp/xconfighttp\"\n\nimport (\n\t\"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\"\n\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/confighttp/internal\"\n)\n\n// WithOtelHTTPOptions allows providing (or overriding) options passed\n// to the otelhttp.NewHandler() function.\n//\n// This is located in the experimental sub-package because the otelhttp library\n// has not reached v1.x yet and exposing its types in confighttp public API\n// could lead to breaking changes in the future.\n// See https://github.com/open-telemetry/opentelemetry-collector/pull/11769\nfunc WithOtelHTTPOptions(httpopts ...otelhttp.Option) confighttp.ToServerOption {\n\treturn internal.ToServerOptionFunc(func(opts *internal.ToServerOptions) {\n\t\topts.OtelhttpOpts = append(opts.OtelhttpOpts, httpopts...)\n\t})\n}\n"
  },
  {
    "path": "config/confighttp/xconfighttp/options_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xconfighttp\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\"\n\tsdktrace \"go.opentelemetry.io/otel/sdk/trace\"\n\t\"go.opentelemetry.io/otel/sdk/trace/tracetest\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n)\n\nfunc TestServerWithOtelHTTPOptions(t *testing.T) {\n\t// prepare\n\tsc := confighttp.ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  \"localhost:0\",\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t}\n\n\ttelemetry := componenttest.NewNopTelemetrySettings()\n\ttp, te := tracerProvider(t)\n\ttelemetry.TracerProvider = tp\n\n\tsrv, err := sc.ToServer(\n\t\tcontext.Background(),\n\t\tnil,\n\t\ttelemetry,\n\t\thttp.HandlerFunc(func(http.ResponseWriter, *http.Request) {}),\n\t\tWithOtelHTTPOptions(\n\t\t\totelhttp.WithSpanNameFormatter(func(_ string, r *http.Request) string {\n\t\t\t\treturn \"example\" + r.URL.Path\n\t\t\t}),\n\t\t\totelhttp.WithFilter(func(r *http.Request) bool {\n\t\t\t\treturn r.URL.Path != \"/foobar\"\n\t\t\t}),\n\t\t),\n\t)\n\trequire.NoError(t, err)\n\n\tfor _, path := range []string{\"/path\", \"/foobar\"} {\n\t\tresponse := &httptest.ResponseRecorder{}\n\t\treq, err := http.NewRequest(http.MethodGet, srv.Addr+path, http.NoBody)\n\t\trequire.NoError(t, err)\n\t\tsrv.Handler.ServeHTTP(response, req)\n\t\tassert.Equal(t, http.StatusOK, response.Result().StatusCode)\n\t}\n\n\tspans := te.GetSpans().Snapshots()\n\tassert.Len(t, spans, 1, \"the request to /foobar should not be traced\")\n\tassert.Equal(t, \"example/path\", spans[0].Name())\n}\n\nfunc tracerProvider(t *testing.T) (trace.TracerProvider, *tracetest.InMemoryExporter) {\n\texporter := tracetest.NewInMemoryExporter()\n\ttp := sdktrace.NewTracerProvider(\n\t\tsdktrace.WithSampler(sdktrace.AlwaysSample()),\n\t\tsdktrace.WithSyncer(exporter),\n\t)\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, tp.Shutdown(context.Background()))\n\t})\n\treturn tp, exporter\n}\n"
  },
  {
    "path": "config/configmiddleware/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "config/configmiddleware/README.md",
    "content": "# OpenTelemetry Collector Middleware Configuration\n\nThis package implements a configuration struct for referring to\n[middleware extensions](../../extension/extensionmiddleware/README.md).\n\n## Overview\n\nThe `configmiddleware` package defines a `Config` type that\nallows components to configure middleware extensions, typically as\nan ordered list.\nThis support is built in for push-based receivers configured through\n`confighttp` and `configgrpc`, as for example in the OTLP receiver:\n\n```yaml\nreceivers:\n  otlp:\n    protocols:\n\t  http:\n\t    middlewares:\n\t\t- id: limitermiddleware\n```\n\n## Methods\n\nThe package provides four key methods to retrieve appropriate middleware handlers:\n\n1. **GetHTTPClientRoundTripper**: Obtains a function to wrap an HTTP client with a middleware extension via a `http.RoundTripper`.\n\n2. **GetHTTPServerHandler**: Obtains a function to wrap an HTTP server with a middleware extension via a `http.Handler`.\n\n3. **GetGRPCClientOptions**: Obtains a `[]grpc.DialOption` that configure a middleware extension for gRPC clients.\n\n4. **GetGRPCServerOptions**: Obtains a `[]grpc.ServerOption` that configure a middleware extension for gRPC servers.\n\nThese functions are typically called during Start() by a component,\npassing the `component.Host` extensions.\nAn error is returned if the named extension cannot be found.\n"
  },
  {
    "path": "config/configmiddleware/config.schema.yaml",
    "content": "$defs:\n  config:\n    description: Middleware defines the extension ID for a middleware component.\n    type: object\n    properties:\n      id:\n        description: ID specifies the name of the extension to use.\n        type: string\n        x-customType: go.opentelemetry.io/collector/component.ID\n"
  },
  {
    "path": "config/configmiddleware/configmiddleware.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package configmiddleware implements a configuration struct to\n// name middleware extensions.\npackage configmiddleware // import \"go.opentelemetry.io/collector/config/configmiddleware\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"google.golang.org/grpc\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/extension/extensionmiddleware\"\n)\n\nvar (\n\terrMiddlewareNotFound = errors.New(\"middleware not found\")\n\terrNotHTTPServer      = errors.New(\"requested extension is not an HTTP server middleware\")\n\terrNotGRPCServer      = errors.New(\"requested extension is not a gRPC server middleware\")\n\terrNotHTTPClient      = errors.New(\"requested extension is not an HTTP client middleware\")\n\terrNotGRPCClient      = errors.New(\"requested extension is not a gRPC client middleware\")\n)\n\n// Middleware defines the extension ID for a middleware component.\ntype Config struct {\n\t// ID specifies the name of the extension to use.\n\tID component.ID `mapstructure:\"id,omitempty\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// GetHTTPClientRoundTripper attempts to select the appropriate\n// extensionmiddleware.HTTPClient from the map of extensions, and\n// returns the HTTP client wrapper function. If a middleware is not\n// found, an error is returned.  This should only be used by HTTP\n// clients.\nfunc (m Config) GetHTTPClientRoundTripper(ctx context.Context, extensions map[component.ID]component.Component) (extensionmiddleware.WrapHTTPRoundTripperFunc, error) {\n\tif ext, found := extensions[m.ID]; found {\n\t\tif client, ok := ext.(extensionmiddleware.HTTPClient); ok {\n\t\t\treturn client.GetHTTPRoundTripper(ctx)\n\t\t}\n\t\treturn nil, errNotHTTPClient\n\t}\n\treturn nil, fmt.Errorf(\"failed to resolve middleware %q: %w\", m.ID, errMiddlewareNotFound)\n}\n\n// GetHTTPServerHandler attempts to select the appropriate\n// extensionmiddleware.HTTPServer from the map of extensions, and\n// returns the http.Handler wrapper function. If a middleware is not\n// found, an error is returned.  This should only be used by HTTP\n// servers.\nfunc (m Config) GetHTTPServerHandler(ctx context.Context, extensions map[component.ID]component.Component) (extensionmiddleware.WrapHTTPHandlerFunc, error) {\n\tif ext, found := extensions[m.ID]; found {\n\t\tif server, ok := ext.(extensionmiddleware.HTTPServer); ok {\n\t\t\treturn server.GetHTTPHandler(ctx)\n\t\t}\n\t\treturn nil, errNotHTTPServer\n\t}\n\n\treturn nil, fmt.Errorf(\"failed to resolve middleware %q: %w\", m.ID, errMiddlewareNotFound)\n}\n\n// GetGRPCClientOptions attempts to select the appropriate\n// extensionmiddleware.GRPCClient from the map of extensions, and\n// returns the gRPC dial options. If a middleware is not found, an\n// error is returned.  This should only be used by gRPC clients.\nfunc (m Config) GetGRPCClientOptions(ctx context.Context, extensions map[component.ID]component.Component) ([]grpc.DialOption, error) {\n\tif ext, found := extensions[m.ID]; found {\n\t\tif client, ok := ext.(extensionmiddleware.GRPCClient); ok {\n\t\t\treturn client.GetGRPCClientOptions(ctx)\n\t\t}\n\t\treturn nil, errNotGRPCClient\n\t}\n\treturn nil, fmt.Errorf(\"failed to resolve middleware %q: %w\", m.ID, errMiddlewareNotFound)\n}\n\n// GetGRPCServerOptions attempts to select the appropriate\n// extensionmiddleware.GRPCServer from the map of extensions, and\n// returns the gRPC server options. If a middleware is not found, an\n// error is returned.  This should only be used by gRPC servers.\nfunc (m Config) GetGRPCServerOptions(ctx context.Context, extensions map[component.ID]component.Component) ([]grpc.ServerOption, error) {\n\tif ext, found := extensions[m.ID]; found {\n\t\tif server, ok := ext.(extensionmiddleware.GRPCServer); ok {\n\t\t\treturn server.GetGRPCServerOptions(ctx)\n\t\t}\n\t\treturn nil, errNotGRPCServer\n\t}\n\n\treturn nil, fmt.Errorf(\"failed to resolve middleware %q: %w\", m.ID, errMiddlewareNotFound)\n}\n"
  },
  {
    "path": "config/configmiddleware/configmiddleware_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configmiddleware\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensionmiddleware\"\n\t\"go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest\"\n)\n\nvar testID = component.MustNewID(\"test\")\n\ntype mockWrongType struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n}\n\nfunc TestConfig_GetHTTPServerHandler(t *testing.T) {\n\tctx := context.Background()\n\n\ttests := []struct {\n\t\tname       string\n\t\tmiddleware Config\n\t\textensions map[component.ID]component.Component\n\t\twantErr    error\n\t}{\n\t\t{\n\t\t\tname: \"found_and_valid\",\n\t\t\tmiddleware: Config{\n\t\t\t\tID: testID,\n\t\t\t},\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\ttestID: extensionmiddlewaretest.NewNop(),\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"middleware_not_found\",\n\t\t\tmiddleware: Config{\n\t\t\t\tID: testID,\n\t\t\t},\n\t\t\textensions: map[component.ID]component.Component{},\n\t\t\twantErr:    errMiddlewareNotFound,\n\t\t},\n\t\t{\n\t\t\tname: \"middleware_wrong_type\",\n\t\t\tmiddleware: Config{\n\t\t\t\tID: testID,\n\t\t\t},\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\ttestID: mockWrongType{},\n\t\t\t},\n\t\t\twantErr: errNotHTTPServer,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvalue, err := tt.middleware.GetHTTPServerHandler(ctx, tt.extensions)\n\n\t\t\tif tt.wantErr != nil {\n\t\t\t\trequire.ErrorIs(t, err, tt.wantErr)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.NotNil(t, value)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestConfig_GetHTTPClientRoundTripper(t *testing.T) {\n\tctx := context.Background()\n\n\ttests := []struct {\n\t\tname       string\n\t\tmiddleware Config\n\t\textensions map[component.ID]component.Component\n\t\twantErr    error\n\t}{\n\t\t{\n\t\t\tname: \"found_and_valid\",\n\t\t\tmiddleware: Config{\n\t\t\t\tID: testID,\n\t\t\t},\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\ttestID: extensionmiddlewaretest.NewNop(),\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"middleware_not_found\",\n\t\t\tmiddleware: Config{\n\t\t\t\tID: testID,\n\t\t\t},\n\t\t\textensions: map[component.ID]component.Component{},\n\t\t\twantErr:    errMiddlewareNotFound,\n\t\t},\n\t\t{\n\t\t\tname: \"middleware_wrong_type\",\n\t\t\tmiddleware: Config{\n\t\t\t\tID: testID,\n\t\t\t},\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\ttestID: mockWrongType{},\n\t\t\t},\n\t\t\twantErr: errNotHTTPClient,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvalue, err := tt.middleware.GetHTTPClientRoundTripper(ctx, tt.extensions)\n\n\t\t\tif tt.wantErr != nil {\n\t\t\t\trequire.ErrorIs(t, err, tt.wantErr)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.NotNil(t, value)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestConfig_GetGRPCServerOptions(t *testing.T) {\n\tctx := context.Background()\n\n\ttests := []struct {\n\t\tname       string\n\t\tmiddleware Config\n\t\textensions map[component.ID]component.Component\n\t\twantErr    error\n\t}{\n\t\t{\n\t\t\tname: \"found_and_valid\",\n\t\t\tmiddleware: Config{\n\t\t\t\tID: testID,\n\t\t\t},\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\ttestID: struct {\n\t\t\t\t\textension.Extension\n\t\t\t\t\textensionmiddleware.GetGRPCServerOptionsFunc\n\t\t\t\t}{\n\t\t\t\t\tExtension: extensionmiddlewaretest.NewNop(),\n\t\t\t\t\tGetGRPCServerOptionsFunc: func(context.Context) ([]grpc.ServerOption, error) {\n\t\t\t\t\t\treturn []grpc.ServerOption{\n\t\t\t\t\t\t\tgrpc.EmptyServerOption{},\n\t\t\t\t\t\t}, nil\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"middleware_not_found\",\n\t\t\tmiddleware: Config{\n\t\t\t\tID: testID,\n\t\t\t},\n\t\t\textensions: map[component.ID]component.Component{},\n\t\t\twantErr:    errMiddlewareNotFound,\n\t\t},\n\t\t{\n\t\t\tname: \"middleware_wrong_type\",\n\t\t\tmiddleware: Config{\n\t\t\t\tID: testID,\n\t\t\t},\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\ttestID: mockWrongType{},\n\t\t\t},\n\t\t\twantErr: errNotGRPCServer,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvalue, err := tt.middleware.GetGRPCServerOptions(ctx, tt.extensions)\n\n\t\t\tif tt.wantErr != nil {\n\t\t\t\trequire.ErrorIs(t, err, tt.wantErr)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.NotNil(t, value)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestConfig_GetGRPCClientOptions(t *testing.T) {\n\tctx := context.Background()\n\n\ttests := []struct {\n\t\tname       string\n\t\tmiddleware Config\n\t\textensions map[component.ID]component.Component\n\t\twantErr    error\n\t}{\n\t\t{\n\t\t\tname: \"found_and_valid\",\n\t\t\tmiddleware: Config{\n\t\t\t\tID: testID,\n\t\t\t},\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\ttestID: struct {\n\t\t\t\t\textension.Extension\n\t\t\t\t\textensionmiddleware.GetGRPCClientOptionsFunc\n\t\t\t\t}{\n\t\t\t\t\tExtension: extensionmiddlewaretest.NewNop(),\n\t\t\t\t\tGetGRPCClientOptionsFunc: func(_ context.Context) ([]grpc.DialOption, error) {\n\t\t\t\t\t\treturn []grpc.DialOption{\n\t\t\t\t\t\t\tgrpc.EmptyDialOption{},\n\t\t\t\t\t\t}, nil\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"middleware_not_found\",\n\t\t\tmiddleware: Config{\n\t\t\t\tID: testID,\n\t\t\t},\n\t\t\textensions: map[component.ID]component.Component{},\n\t\t\twantErr:    errMiddlewareNotFound,\n\t\t},\n\t\t{\n\t\t\tname: \"middleware_wrong_type\",\n\t\t\tmiddleware: Config{\n\t\t\t\tID: testID,\n\t\t\t},\n\t\t\textensions: map[component.ID]component.Component{\n\t\t\t\ttestID: mockWrongType{},\n\t\t\t},\n\t\t\twantErr: errNotGRPCClient,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvalue, err := tt.middleware.GetGRPCClientOptions(ctx, tt.extensions)\n\n\t\t\tif tt.wantErr != nil {\n\t\t\t\trequire.ErrorIs(t, err, tt.wantErr)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.NotNil(t, value)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "config/configmiddleware/go.mod",
    "content": "module go.opentelemetry.io/collector/config/configmiddleware\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/extension v1.54.0\n\tgo.opentelemetry.io/collector/extension/extensionmiddleware v0.148.0\n\tgo.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest v0.148.0\n\tgoogle.golang.org/grpc v1.79.3\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ../../extension/extensionmiddleware\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest => ../../extension/extensionmiddleware/extensionmiddlewaretest\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/extension => ../../extension\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "config/configmiddleware/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18=\ngo.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE=\ngo.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8=\ngo.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=\ngonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "config/configmiddleware/metadata.yaml",
    "content": "type: config/configmiddleware\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "config/confignet/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "config/confignet/README.md",
    "content": "# Network Configuration Settings\n\n[Receivers](https://github.com/open-telemetry/opentelemetry-collector/blob/main/receiver/README.md)\nleverage network configuration to set connection and transport information.\n\n- `endpoint`: Configures the address for this network connection. For TCP and\n  UDP networks, the address has the form \"host:port\". The host must be a\n  literal IP address, or a host name that can be resolved to IP addresses. The\n  port must be a literal port number or a service name. If the host is a\n  literal IPv6 address it must be enclosed in square brackets, as in\n  \"[2001:db8::1]:80\" or \"[fe80::1%zone]:80\". The zone specifies the scope of\n  the literal IPv6 address as defined in RFC 4007.\n- `transport`: Known protocols are \"tcp\", \"tcp4\" (IPv4-only), \"tcp6\"\n  (IPv6-only), \"udp\", \"udp4\" (IPv4-only), \"udp6\" (IPv6-only), \"ip\", \"ip4\"\n  (IPv4-only), \"ip6\" (IPv6-only), \"unix\", \"unixgram\" and \"unixpacket\".\n- `dialer`: Dialer configuration\n  - `timeout`: Dialer timeout is the maximum amount of time a dial will wait for a connect to complete. The default is no timeout.\n\nNote that for TCP receivers only the `endpoint` configuration setting is\nrequired.\n"
  },
  {
    "path": "config/confignet/config.schema.yaml",
    "content": "$defs:\n  addr_config:\n    description: AddrConfig represents a network endpoint address.\n    type: object\n    properties:\n      dialer:\n        description: DialerConfig contains options for connecting to an address.\n        $ref: dialer_config\n      endpoint:\n        description: Endpoint configures the address for this network connection. For TCP and UDP networks, the address has the form \"host:port\". The host must be a literal IP address, or a host name that can be resolved to IP addresses. The port must be a literal port number or a service name. If the host is a literal IPv6 address it must be enclosed in square brackets, as in \"[2001:db8::1]:80\" or \"[fe80::1%zone]:80\". The zone specifies the scope of the literal IPv6 address as defined in RFC 4007.\n        type: string\n      transport:\n        description: Transport to use. Allowed protocols are \"tcp\", \"tcp4\" (IPv4-only), \"tcp6\" (IPv6-only), \"udp\", \"udp4\" (IPv4-only), \"udp6\" (IPv6-only), \"ip\", \"ip4\" (IPv4-only), \"ip6\" (IPv6-only), \"unix\", \"unixgram\" and \"unixpacket\".\n        $ref: transport_type\n  dialer_config:\n    description: DialerConfig contains options for connecting to an address.\n    type: object\n    properties:\n      timeout:\n        description: Timeout is the maximum amount of time a dial will wait for a connect to complete. The default is no timeout.\n        type: string\n        x-customType: time.Duration\n        format: duration\n  tcp_addr_config:\n    description: TCPAddrConfig represents a TCP endpoint address.\n    type: object\n    properties:\n      dialer:\n        description: DialerConfig contains options for connecting to an address.\n        $ref: dialer_config\n      endpoint:\n        description: Endpoint configures the address for this network connection. The address has the form \"host:port\". The host must be a literal IP address, or a host name that can be resolved to IP addresses. The port must be a literal port number or a service name. If the host is a literal IPv6 address it must be enclosed in square brackets, as in \"[2001:db8::1]:80\" or \"[fe80::1%zone]:80\". The zone specifies the scope of the literal IPv6 address as defined in RFC 4007.\n        type: string\n  transport_type:\n    description: TransportType represents a type of network transport protocol\n    type: string\n"
  },
  {
    "path": "config/confignet/confignet.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confignet // import \"go.opentelemetry.io/collector/config/confignet\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net\"\n\t\"time\"\n)\n\n// TransportType represents a type of network transport protocol\ntype TransportType string\n\nconst (\n\tTransportTypeTCP        TransportType = \"tcp\"\n\tTransportTypeTCP4       TransportType = \"tcp4\"\n\tTransportTypeTCP6       TransportType = \"tcp6\"\n\tTransportTypeUDP        TransportType = \"udp\"\n\tTransportTypeUDP4       TransportType = \"udp4\"\n\tTransportTypeUDP6       TransportType = \"udp6\"\n\tTransportTypeIP         TransportType = \"ip\"\n\tTransportTypeIP4        TransportType = \"ip4\"\n\tTransportTypeIP6        TransportType = \"ip6\"\n\tTransportTypeUnix       TransportType = \"unix\"\n\tTransportTypeUnixgram   TransportType = \"unixgram\"\n\tTransportTypeUnixPacket TransportType = \"unixpacket\"\n\ttransportTypeEmpty      TransportType = \"\"\n)\n\n// UnmarshalText unmarshalls text to a TransportType.\n// Valid values are \"tcp\", \"tcp4\", \"tcp6\", \"udp\", \"udp4\",\n// \"udp6\", \"ip\", \"ip4\", \"ip6\", \"unix\", \"unixgram\" and \"unixpacket\"\nfunc (tt *TransportType) UnmarshalText(in []byte) error {\n\ttyp := TransportType(in)\n\tswitch typ {\n\tcase TransportTypeTCP,\n\t\tTransportTypeTCP4,\n\t\tTransportTypeTCP6,\n\t\tTransportTypeUDP,\n\t\tTransportTypeUDP4,\n\t\tTransportTypeUDP6,\n\t\tTransportTypeIP,\n\t\tTransportTypeIP4,\n\t\tTransportTypeIP6,\n\t\tTransportTypeUnix,\n\t\tTransportTypeUnixgram,\n\t\tTransportTypeUnixPacket,\n\t\ttransportTypeEmpty:\n\t\t*tt = typ\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"unsupported transport type %q\", typ)\n\t}\n}\n\n// DialerConfig contains options for connecting to an address.\ntype DialerConfig struct {\n\t// Timeout is the maximum amount of time a dial will wait for\n\t// a connect to complete. The default is no timeout.\n\tTimeout time.Duration `mapstructure:\"timeout,omitempty\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// NewDefaultDialerConfig creates a new DialerConfig with any default values set\nfunc NewDefaultDialerConfig() DialerConfig {\n\treturn DialerConfig{}\n}\n\n// AddrConfig represents a network endpoint address.\ntype AddrConfig struct {\n\t// Endpoint configures the address for this network connection.\n\t// For TCP and UDP networks, the address has the form \"host:port\". The host must be a literal IP address,\n\t// or a host name that can be resolved to IP addresses. The port must be a literal port number or a service name.\n\t// If the host is a literal IPv6 address it must be enclosed in square brackets, as in \"[2001:db8::1]:80\" or\n\t// \"[fe80::1%zone]:80\". The zone specifies the scope of the literal IPv6 address as defined in RFC 4007.\n\tEndpoint string `mapstructure:\"endpoint,omitempty\"`\n\n\t// Transport to use. Allowed protocols are \"tcp\", \"tcp4\" (IPv4-only), \"tcp6\" (IPv6-only), \"udp\", \"udp4\" (IPv4-only),\n\t// \"udp6\" (IPv6-only), \"ip\", \"ip4\" (IPv4-only), \"ip6\" (IPv6-only), \"unix\", \"unixgram\" and \"unixpacket\".\n\tTransport TransportType `mapstructure:\"transport,omitempty\"`\n\n\t// DialerConfig contains options for connecting to an address.\n\tDialerConfig DialerConfig `mapstructure:\"dialer,omitempty\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// NewDefaultAddrConfig creates a new AddrConfig with any default values set\nfunc NewDefaultAddrConfig() AddrConfig {\n\treturn AddrConfig{\n\t\tDialerConfig: NewDefaultDialerConfig(),\n\t}\n}\n\n// Dial equivalent with net.Dialer's DialContext for this address.\nfunc (na *AddrConfig) Dial(ctx context.Context) (net.Conn, error) {\n\td := net.Dialer{Timeout: na.DialerConfig.Timeout}\n\treturn d.DialContext(ctx, string(na.Transport), na.Endpoint)\n}\n\n// Listen equivalent with net.ListenConfig's Listen for this address.\nfunc (na *AddrConfig) Listen(ctx context.Context) (net.Listener, error) {\n\tlc := net.ListenConfig{}\n\treturn lc.Listen(ctx, string(na.Transport), na.Endpoint)\n}\n\nfunc (na *AddrConfig) Validate() error {\n\tswitch na.Transport {\n\tcase TransportTypeTCP,\n\t\tTransportTypeTCP4,\n\t\tTransportTypeTCP6,\n\t\tTransportTypeUDP,\n\t\tTransportTypeUDP4,\n\t\tTransportTypeUDP6,\n\t\tTransportTypeIP,\n\t\tTransportTypeIP4,\n\t\tTransportTypeIP6,\n\t\tTransportTypeUnix,\n\t\tTransportTypeUnixgram,\n\t\tTransportTypeUnixPacket:\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid transport type %q\", na.Transport)\n\t}\n}\n\n// TCPAddrConfig represents a TCP endpoint address.\ntype TCPAddrConfig struct {\n\t// Endpoint configures the address for this network connection.\n\t// The address has the form \"host:port\". The host must be a literal IP address, or a host name that can be\n\t// resolved to IP addresses. The port must be a literal port number or a service name.\n\t// If the host is a literal IPv6 address it must be enclosed in square brackets, as in \"[2001:db8::1]:80\" or\n\t// \"[fe80::1%zone]:80\". The zone specifies the scope of the literal IPv6 address as defined in RFC 4007.\n\tEndpoint string `mapstructure:\"endpoint,omitempty\"`\n\n\t// DialerConfig contains options for connecting to an address.\n\tDialerConfig DialerConfig `mapstructure:\"dialer,omitempty\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// NewDefaultTCPAddrConfig creates a new TCPAddrConfig with any default values set\nfunc NewDefaultTCPAddrConfig() TCPAddrConfig {\n\treturn TCPAddrConfig{\n\t\tDialerConfig: NewDefaultDialerConfig(),\n\t}\n}\n\n// Dial equivalent with net.Dialer's DialContext for this address.\nfunc (na *TCPAddrConfig) Dial(ctx context.Context) (net.Conn, error) {\n\td := net.Dialer{Timeout: na.DialerConfig.Timeout}\n\treturn d.DialContext(ctx, string(TransportTypeTCP), na.Endpoint)\n}\n\n// Listen equivalent with net.ListenConfig's Listen for this address.\nfunc (na *TCPAddrConfig) Listen(ctx context.Context) (net.Listener, error) {\n\tlc := net.ListenConfig{}\n\treturn lc.Listen(ctx, string(TransportTypeTCP), na.Endpoint)\n}\n"
  },
  {
    "path": "config/confignet/confignet_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confignet\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestNewDefaultDialerConfig(t *testing.T) {\n\texpectedDialerConfig := DialerConfig{}\n\tdialerConfig := NewDefaultDialerConfig()\n\trequire.Equal(t, expectedDialerConfig, dialerConfig)\n}\n\nfunc TestNewDefaultAddrConfig(t *testing.T) {\n\texpectedAddrConfig := AddrConfig{}\n\taddrConfig := NewDefaultAddrConfig()\n\trequire.Equal(t, expectedAddrConfig, addrConfig)\n}\n\nfunc TestNewDefaultTCPAddrConfig(t *testing.T) {\n\texpectedTCPAddrConfig := TCPAddrConfig{}\n\ttcpAddrconfig := NewDefaultTCPAddrConfig()\n\trequire.Equal(t, expectedTCPAddrConfig, tcpAddrconfig)\n}\n\nfunc TestAddrConfigTimeout(t *testing.T) {\n\tnac := &AddrConfig{\n\t\tEndpoint:  \"localhost:0\",\n\t\tTransport: TransportTypeTCP,\n\t\tDialerConfig: DialerConfig{\n\t\t\tTimeout: -1 * time.Second,\n\t\t},\n\t}\n\t_, err := nac.Dial(context.Background())\n\trequire.Error(t, err)\n\tvar netErr net.Error\n\tif errors.As(err, &netErr) {\n\t\tassert.True(t, netErr.Timeout())\n\t} else {\n\t\tassert.Fail(t, \"error should be a net.Error\")\n\t}\n}\n\nfunc TestTCPAddrConfigTimeout(t *testing.T) {\n\tnac := &TCPAddrConfig{\n\t\tEndpoint: \"localhost:0\",\n\t\tDialerConfig: DialerConfig{\n\t\t\tTimeout: -1 * time.Second,\n\t\t},\n\t}\n\t_, err := nac.Dial(context.Background())\n\trequire.Error(t, err)\n\tvar netErr net.Error\n\tif errors.As(err, &netErr) {\n\t\tassert.True(t, netErr.Timeout())\n\t} else {\n\t\tassert.Fail(t, \"error should be a net.Error\")\n\t}\n}\n\nfunc TestAddrConfig(t *testing.T) {\n\tnas := &AddrConfig{\n\t\tEndpoint:  \"localhost:0\",\n\t\tTransport: TransportTypeTCP,\n\t}\n\tln, err := nas.Listen(context.Background())\n\trequire.NoError(t, err)\n\tdone := make(chan bool, 1)\n\n\tgo func() {\n\t\tconn, errGo := ln.Accept()\n\t\tassert.NoError(t, errGo)\n\t\tbuf := make([]byte, 10)\n\t\tvar numChr int\n\t\tnumChr, errGo = conn.Read(buf)\n\t\tassert.NoError(t, errGo)\n\t\tassert.Equal(t, \"test\", string(buf[:numChr]))\n\t\tassert.NoError(t, conn.Close())\n\t\tdone <- true\n\t}()\n\n\tnac := &AddrConfig{\n\t\tEndpoint:  ln.Addr().String(),\n\t\tTransport: TransportTypeTCP,\n\t}\n\tvar conn net.Conn\n\tconn, err = nac.Dial(context.Background())\n\trequire.NoError(t, err)\n\t_, err = conn.Write([]byte(\"test\"))\n\tassert.NoError(t, err)\n\tassert.NoError(t, conn.Close())\n\t<-done\n\tassert.NoError(t, ln.Close())\n}\n\nfunc Test_NetAddr_Validate(t *testing.T) {\n\tna := &AddrConfig{\n\t\tTransport: TransportTypeTCP,\n\t}\n\trequire.NoError(t, na.Validate())\n\n\tna = &AddrConfig{\n\t\tTransport: transportTypeEmpty,\n\t}\n\trequire.Error(t, na.Validate())\n\n\tna = &AddrConfig{\n\t\tTransport: \"random string\",\n\t}\n\tassert.Error(t, na.Validate())\n}\n\nfunc TestTCPAddrConfig(t *testing.T) {\n\tnas := &TCPAddrConfig{\n\t\tEndpoint: \"localhost:0\",\n\t}\n\tln, err := nas.Listen(context.Background())\n\trequire.NoError(t, err)\n\tdone := make(chan bool, 1)\n\n\tgo func() {\n\t\tconn, errGo := ln.Accept()\n\t\tassert.NoError(t, errGo)\n\t\tbuf := make([]byte, 10)\n\t\tvar numChr int\n\t\tnumChr, errGo = conn.Read(buf)\n\t\tassert.NoError(t, errGo)\n\t\tassert.Equal(t, \"test\", string(buf[:numChr]))\n\t\tassert.NoError(t, conn.Close())\n\t\tdone <- true\n\t}()\n\n\tnac := &TCPAddrConfig{\n\t\tEndpoint: ln.Addr().String(),\n\t}\n\tvar conn net.Conn\n\tconn, err = nac.Dial(context.Background())\n\trequire.NoError(t, err)\n\t_, err = conn.Write([]byte(\"test\"))\n\tassert.NoError(t, err)\n\tassert.NoError(t, conn.Close())\n\t<-done\n\tassert.NoError(t, ln.Close())\n}\n\nfunc Test_TransportType_UnmarshalText(t *testing.T) {\n\tvar tt TransportType\n\terr := tt.UnmarshalText([]byte(\"tcp\"))\n\trequire.NoError(t, err)\n\terr = tt.UnmarshalText([]byte(\"invalid\"))\n\trequire.Error(t, err)\n}\n"
  },
  {
    "path": "config/confignet/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package confignet implements the configuration settings for protocols to\n// connect and transport data information.\npackage confignet // import \"go.opentelemetry.io/collector/config/confignet\"\n"
  },
  {
    "path": "config/confignet/go.mod",
    "content": "module go.opentelemetry.io/collector/config/confignet\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/kr/pretty v0.3.1 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/rogpeppe/go-internal v1.10.0 // indirect\n\tgopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n"
  },
  {
    "path": "config/confignet/go.sum",
    "content": "github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=\ngithub.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "config/confignet/metadata.yaml",
    "content": "type: config/confignet\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "config/confignet/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confignet\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "config/configopaque/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "config/configopaque/config.schema.yaml",
    "content": "$defs:\n  map_list:\n    description: MapList is a replacement for map[string]configopaque.String with a similar API, which can also be unmarshalled from (and is stored as) a list of name/value pairs. Pairs are assumed to have distinct names. This is checked during config validation.\n    type: array\n    items:\n      $ref: pair\n  pair:\n    description: Pair is an element of a MapList, and consists of a name and an opaque value.\n    type: object\n    properties:\n      name:\n        type: string\n      value:\n        $ref: string\n  string:\n    description: String alias that is marshaled and printed in an opaque way. To recover the original value, cast it to a string.\n    type: string\n"
  },
  {
    "path": "config/configopaque/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package configopaque implements a String type alias to mask sensitive information.\n// Use configopaque.String on the type of sensitive fields, to mask the\n// opaque string as `[REDACTED]`.\n//\n// This ensures that no sensitive information is leaked in logs or when printing the\n// full Collector configurations.\n//\n// The only way to view the value stored in a configopaque.String is to first convert\n// it to a string by casting with the builtin `string` function.\n//\n// To achieve this, configopaque.String implements standard library interfaces\n// like fmt.Stringer, encoding.TextMarshaler and others to ensure that the\n// underlying value is masked when printed or serialized.\n//\n// If new interfaces that would leak opaque values are added to the standard library\n// or become widely used in the Go ecosystem, these will eventually be implemented\n// by configopaque.String as well. This is not considered a breaking change.\npackage configopaque // import \"go.opentelemetry.io/collector/config/configopaque\"\n"
  },
  {
    "path": "config/configopaque/doc_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configopaque_test\n\nimport (\n\t\"encoding/json\"\n\t\"fmt\"\n\n\t\"go.yaml.in/yaml/v3\"\n\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n)\n\nfunc Example_opaqueString() {\n\trawBytes := []byte(`{\n\t\t\"Censored\":   \"sensitive\",\n\t\t\"Uncensored\": \"not sensitive\"\n\t}`)\n\n\t// JSON unmarshaling\n\tvar cfg ExampleConfigString\n\terr := json.Unmarshal(rawBytes, &cfg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\t// YAML marshaling\n\tbytes, err := yaml.Marshal(cfg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"encoded cfg (YAML) is:\\n%s\\n\\n\", string(bytes))\n\t// Output: encoded cfg (YAML) is:\n\t// censored: '[REDACTED]'\n\t// uncensored: not sensitive\n}\n\ntype ExampleConfigString struct {\n\tCensored   configopaque.String\n\tUncensored string\n}\n\nfunc Example_opaqueSlice() {\n\tcfg := &ExampleConfigSlice{\n\t\tCensored:   []configopaque.String{\"data\", \"is\", \"sensitive\"},\n\t\tUncensored: []string{\"data\", \"is\", \"not\", \"sensitive\"},\n\t}\n\n\t// JSON marshaling\n\tbytes, err := json.MarshalIndent(cfg, \"\", \"  \")\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"encoded cfg (JSON) is\\n%s\\n\\n\", string(bytes))\n\t// Output: encoded cfg (JSON) is\n\t// {\n\t//   \"Censored\": [\n\t//     \"[REDACTED]\",\n\t//     \"[REDACTED]\",\n\t//     \"[REDACTED]\"\n\t//   ],\n\t//   \"Uncensored\": [\n\t//     \"data\",\n\t//     \"is\",\n\t//     \"not\",\n\t//     \"sensitive\"\n\t//   ]\n\t// }\n}\n\ntype ExampleConfigSlice struct {\n\tCensored   []configopaque.String\n\tUncensored []string\n}\n\nfunc Example_opaqueMap() {\n\tcfg := &ExampleConfigMap{\n\t\tCensored: map[string]configopaque.String{\n\t\t\t\"token\": \"sensitivetoken\",\n\t\t},\n\t\tUncensored: map[string]string{\n\t\t\t\"key\":   \"cloud.zone\",\n\t\t\t\"value\": \"zone-1\",\n\t\t},\n\t}\n\n\t// yaml marshaling\n\tbytes, err := yaml.Marshal(cfg)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"encoded cfg (YAML) is:\\n%s\\n\\n\", string(bytes))\n\t// Output: encoded cfg (YAML) is:\n\t// censored:\n\t//     token: '[REDACTED]'\n\t// uncensored:\n\t//     key: cloud.zone\n\t//     value: zone-1\n}\n\ntype ExampleConfigMap struct {\n\tCensored   map[string]configopaque.String\n\tUncensored map[string]string\n}\n"
  },
  {
    "path": "config/configopaque/go.mod",
    "content": "module go.opentelemetry.io/collector/config/configopaque\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.yaml.in/yaml/v3 v3.0.4\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n"
  },
  {
    "path": "config/configopaque/go.sum",
    "content": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "config/configopaque/maplist.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configopaque // import \"go.opentelemetry.io/collector/config/configopaque\"\n\nimport (\n\t\"cmp\"\n\t\"fmt\"\n\t\"iter\"\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n)\n\n// Pair is an element of a MapList, and consists of a name and an opaque value.\ntype Pair struct {\n\tName  string `mapstructure:\"name\"`\n\tValue String `mapstructure:\"value\"`\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// MapList is a replacement for map[string]configopaque.String with a similar API,\n// which can also be unmarshalled from (and is stored as) a list of name/value pairs.\n//\n// Pairs are assumed to have distinct names. This is checked during config validation.\ntype MapList []Pair\n\nvar _ confmap.Unmarshaler = (*MapList)(nil)\n\n// Unmarshal is called by the Collector when unmarshalling from a map.\n// When the input config is a slice, this will be skipped,\n// and mapstructure's default unmarshalling logic will be used.\nfunc (ml *MapList) Unmarshal(conf *confmap.Conf) error {\n\tvar m2 map[string]String\n\tif err := conf.Unmarshal(&m2); err != nil {\n\t\treturn err\n\t}\n\t*ml = make(MapList, 0, len(m2))\n\tfor name, value := range m2 {\n\t\t*ml = append(*ml, Pair{\n\t\t\tName:  name,\n\t\t\tValue: value,\n\t\t})\n\t}\n\tslices.SortFunc(*ml, func(p1, p2 Pair) int {\n\t\treturn cmp.Compare(p1.Name, p2.Name)\n\t})\n\treturn nil\n}\n\nvar _ xconfmap.Validator = MapList(nil)\n\nfunc (ml MapList) Validate() error {\n\t// Check for duplicate keys\n\tcounts := make(map[string]int, len(ml))\n\tfor _, OpaquePair := range ml {\n\t\tcounts[OpaquePair.Name]++\n\t}\n\tif len(counts) == len(ml) {\n\t\treturn nil\n\t}\n\tvar duplicates []string\n\tfor name, cnt := range counts {\n\t\tif cnt > 1 {\n\t\t\tduplicates = append(duplicates, name)\n\t\t}\n\t}\n\tslices.Sort(duplicates)\n\treturn fmt.Errorf(\"duplicate keys in map-style list: %v\", duplicates)\n}\n\nvar _ iter.Seq2[string, String] = MapList(nil).Iter\n\n// Iter is an iterator over key/value pairs for use in for-range loops.\n// It is the MapList equivalent of directly ranging over a map.\nfunc (ml MapList) Iter(yield func(name string, value String) bool) {\n\tfor _, OpaquePair := range ml {\n\t\tif !yield(OpaquePair.Name, OpaquePair.Value) {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n// Get looks up a pair's value based on its name.\n// It is the MapList equivalent of `val, ok := m[key]`.\n// However, it has linear time complexity.\nfunc (ml MapList) Get(name string) (val String, ok bool) {\n\tfor _, OpaquePair := range ml {\n\t\tif OpaquePair.Name == name {\n\t\t\treturn OpaquePair.Value, true\n\t\t}\n\t}\n\treturn val, false\n}\n\n// Set sets the value corresponding to a given name.\n// It is the MapList equivalent of `m[key] = val`.\n// However, it has linear time complexity,\n// and does not affect shallow copies.\nfunc (ml *MapList) Set(name string, val String) {\n\tif ml == nil {\n\t\tpanic(\"assignment to entry in nil *MapList\")\n\t}\n\tfor i, OpaquePair := range *ml {\n\t\tif OpaquePair.Name == name {\n\t\t\t*ml = slices.Clone(*ml)\n\t\t\t(*ml)[i].Value = val\n\t\t\treturn\n\t\t}\n\t}\n\t*ml = append(make(MapList, 0, len(*ml)+1), *ml...)\n\t*ml = append(*ml, Pair{Name: name, Value: val})\n}\n"
  },
  {
    "path": "config/configopaque/maplist_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configopaque_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n)\n\nconst headersList = `\nheaders:\n- name: \"a\"\n  value: \"b\"\n- name: \"c\"\n  value: \"d\"\n`\n\nconst headersMap = `\nheaders:\n  \"a\": \"b\"\n  \"c\": \"d\"\n`\n\nconst headersBad1 = `\nheaders:\n  \"bad\": 1\n`\n\nconst headersBad2 = `\nheaders: \"foo\"\n`\n\nconst headersDupe = `\nheaders:\n- name: \"foo\"\n  value: \"bar\"\n- name: \"foo\"\n  value: \"baz\"\n`\n\ntype testConfig struct {\n\tHeaders configopaque.MapList `mapstructure:\"headers\"`\n}\n\nfunc TestMapListDuality(t *testing.T) {\n\tretrieved1, err := confmap.NewRetrievedFromYAML([]byte(headersList))\n\trequire.NoError(t, err)\n\tconf1, err := retrieved1.AsConf()\n\trequire.NoError(t, err)\n\tvar tc1 testConfig\n\trequire.NoError(t, conf1.Unmarshal(&tc1))\n\tassert.NoError(t, xconfmap.Validate(&tc1))\n\n\tretrieved2, err := confmap.NewRetrievedFromYAML([]byte(headersMap))\n\trequire.NoError(t, err)\n\tconf2, err := retrieved2.AsConf()\n\trequire.NoError(t, err)\n\tvar tc2 testConfig\n\trequire.NoError(t, conf2.Unmarshal(&tc2))\n\tassert.NoError(t, xconfmap.Validate(&tc2))\n\n\tassert.Equal(t, tc1, tc2)\n}\n\nfunc TestMapListUnmarshalError(t *testing.T) {\n\tvar tc testConfig\n\n\tretrieved, err := confmap.NewRetrievedFromYAML([]byte(headersBad1))\n\trequire.NoError(t, err)\n\tconf, err := retrieved.AsConf()\n\trequire.NoError(t, err)\n\trequire.EqualError(t, conf.Unmarshal(&tc),\n\t\t\"decoding failed due to the following error(s):\\n\\n\"+\n\t\t\t\"'headers' decoding failed due to the following error(s):\\n\\n\"+\n\t\t\t\"'[bad]' expected type 'configopaque.String', got unconvertible type 'int'\")\n\n\tretrieved, err = confmap.NewRetrievedFromYAML([]byte(headersBad2))\n\trequire.NoError(t, err)\n\tconf, err = retrieved.AsConf()\n\trequire.NoError(t, err)\n\t// Not sure if there is a way to change the error message to include the map case?\n\trequire.EqualError(t, conf.Unmarshal(&tc),\n\t\t\"decoding failed due to the following error(s):\\n\\n\"+\n\t\t\t\"'headers' source data must be an array or slice, got string\")\n}\n\nfunc TestMapListValidate(t *testing.T) {\n\tretrieved, err := confmap.NewRetrievedFromYAML([]byte(headersDupe))\n\trequire.NoError(t, err)\n\tconf, err := retrieved.AsConf()\n\trequire.NoError(t, err)\n\tvar tc testConfig\n\trequire.NoError(t, conf.Unmarshal(&tc))\n\trequire.EqualError(t, xconfmap.Validate(&tc), `headers: duplicate keys in map-style list: [foo]`)\n}\n\nfunc TestMapListMethods(t *testing.T) {\n\tml := configopaque.MapList{\n\t\t{Name: \"a\", Value: \"1\"},\n\t\t{Name: \"b\", Value: \"2\"},\n\t\t{Name: \"c\", Value: \"3\"},\n\t}\n\n\ttype pair = struct {\n\t\tk string\n\t\tv configopaque.String\n\t}\n\tvar kvs []pair\n\tfor k, v := range ml.Iter {\n\t\tkvs = append(kvs, pair{k, v})\n\t\tif k == \"b\" {\n\t\t\tbreak\n\t\t}\n\t}\n\tassert.Equal(t, []pair{{\"a\", \"1\"}, {\"b\", \"2\"}}, kvs)\n\n\tv, ok := ml.Get(\"a\")\n\tassert.True(t, ok)\n\tif ok {\n\t\tassert.Equal(t, configopaque.String(\"1\"), v)\n\t}\n\tv, ok = ml.Get(\"d\")\n\tassert.False(t, ok)\n\tassert.Zero(t, v)\n\n\tml2 := ml\n\tassert.Len(t, ml2, 3)\n\n\t// Set existing key\n\tml2.Set(\"c\", \"4\")\n\tassert.Len(t, ml, 3)\n\tassert.Len(t, ml2, 3)\n\tv, _ = ml.Get(\"c\")\n\tassert.Equal(t, configopaque.String(\"3\"), v)\n\tv, _ = ml2.Get(\"c\")\n\tassert.Equal(t, configopaque.String(\"4\"), v)\n\n\t// Set new key\n\tml2.Set(\"d\", \"5\")\n\tassert.Len(t, ml, 3)\n\tassert.Len(t, ml2, 4)\n\t_, ok = ml.Get(\"d\")\n\tassert.False(t, ok)\n\tv, ok = ml2.Get(\"d\")\n\tassert.True(t, ok)\n\tassert.Equal(t, configopaque.String(\"5\"), v)\n}\n\nfunc TestMapListNil(t *testing.T) {\n\tvar ml *configopaque.MapList\n\tassert.Panics(t, func() {\n\t\tml.Set(\"a\", \"0\")\n\t})\n}\n"
  },
  {
    "path": "config/configopaque/metadata.yaml",
    "content": "type: config/configopaque\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "config/configopaque/opaque.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configopaque // import \"go.opentelemetry.io/collector/config/configopaque\"\n\nimport (\n\t\"fmt\"\n)\n\n// String alias that is marshaled and printed in an opaque way.\n// To recover the original value, cast it to a string.\ntype String string\n\nconst maskedString = \"[REDACTED]\"\n\n// MarshalText marshals the string as `[REDACTED]`.\nfunc (s String) MarshalText() ([]byte, error) {\n\treturn []byte(maskedString), nil\n}\n\n// String formats the string as `[REDACTED]`.\n// This is used for the %s and %q verbs.\nfunc (s String) String() string {\n\treturn maskedString\n}\n\n// GoString formats the string as `[REDACTED]`.\n// This is used for the %#v verb.\nfunc (s String) GoString() string {\n\treturn fmt.Sprintf(\"%#v\", maskedString)\n}\n\n// MarshalBinary marshals the string `[REDACTED]` as []byte.\nfunc (s String) MarshalBinary() (text []byte, err error) {\n\treturn []byte(maskedString), nil\n}\n"
  },
  {
    "path": "config/configopaque/opaque_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configopaque // import \"go.opentelemetry.io/collector/config/configopaque\"\n\nimport (\n\t\"encoding\"\n\t\"encoding/hex\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar _ encoding.TextMarshaler = String(\"\")\n\nvar _ fmt.Stringer = String(\"\")\n\nvar _ fmt.GoStringer = String(\"\")\n\nvar _ encoding.BinaryMarshaler = String(\"\")\n\nfunc TestStringMarshalText(t *testing.T) {\n\texamples := []String{\"opaque\", \"s\", \"veryveryveryveryveryveryveryveryveryverylong\"}\n\tfor _, example := range examples {\n\t\topaque, err := example.MarshalText()\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, maskedString, string(opaque))\n\t}\n}\n\ntype TestStruct struct {\n\tOpaque String `json:\"opaque\" yaml:\"opaque\"`\n\tPlain  string `json:\"plain\" yaml:\"plain\"`\n}\n\nvar example = TestStruct{\n\tOpaque: \"opaque\",\n\tPlain:  \"plain\",\n}\n\nfunc TestStringJSON(t *testing.T) {\n\tbytes, err := json.Marshal(example)\n\trequire.NoError(t, err)\n\tassert.JSONEq(t, `{\"opaque\":\"[REDACTED]\",\"plain\":\"plain\"}`, string(bytes))\n}\n\nfunc TestStringFmt(t *testing.T) {\n\texamples := []String{\"opaque\", \"s\", \"veryveryveryveryveryveryveryveryveryverylong\"}\n\tverbs := []string{\"%s\", \"%q\", \"%v\", \"%#v\", \"%+v\", \"%x\"}\n\tfor _, example := range examples {\n\t\tfor _, verb := range verbs {\n\t\t\tt.Run(fmt.Sprintf(\"%s/%s\", string(example), verb), func(t *testing.T) {\n\t\t\t\tassert.Equal(t,\n\t\t\t\t\tfmt.Sprintf(verb, maskedString),\n\t\t\t\t\tfmt.Sprintf(verb, example),\n\t\t\t\t)\n\t\t\t})\n\t\t}\n\n\t\tfor _, verb := range verbs {\n\t\t\tt.Run(fmt.Sprintf(\"string(%s)/%s\", string(example), verb), func(t *testing.T) {\n\t\t\t\t// converting to a string allows to output as an unredacted string still:\n\t\t\t\tvar expected string\n\t\t\t\tswitch verb {\n\t\t\t\tcase \"%s\", \"%v\", \"%+v\":\n\t\t\t\t\texpected = string(example)\n\t\t\t\tcase \"%q\", \"%#v\":\n\t\t\t\t\texpected = \"\\\"\" + string(example) + \"\\\"\"\n\t\t\t\tcase \"%x\":\n\t\t\t\t\texpected = hex.EncodeToString([]byte(example))\n\t\t\t\tdefault:\n\t\t\t\t\tt.Errorf(\"unexpected verb %q\", verb)\n\t\t\t\t}\n\n\t\t\t\tassert.Equal(t,\n\t\t\t\t\texpected,\n\t\t\t\t\tfmt.Sprintf(verb, string(example)),\n\t\t\t\t)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestStringMarshalBinary(t *testing.T) {\n\texamples := []String{\"opaque\", \"s\", \"veryveryveryveryveryveryveryveryveryverylong\"}\n\tfor _, example := range examples {\n\t\topaque, err := example.MarshalBinary()\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, []byte(\"[REDACTED]\"), opaque)\n\t}\n}\n"
  },
  {
    "path": "config/configopaque/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configopaque\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "config/configoptional/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "config/configoptional/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# configoptional\n\n## Feature Gates\n\nThis component has the following feature gates:\n\n| Feature Gate | Stage | Description | From Version | To Version | Reference |\n| ------------ | ----- | ----------- | ------------ | ---------- | --------- |\n| `configoptional.AddEnabledField` | beta | Allows optional fields to be toggled via an 'enabled' field. | v0.138.0 | N/A | [Link](https://github.com/open-telemetry/opentelemetry-collector/issues/14021) |\n\nFor more information about feature gates, see the [Feature Gates](https://github.com/open-telemetry/opentelemetry-collector/blob/main/featuregate/README.md) documentation.\n"
  },
  {
    "path": "config/configoptional/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage configoptional\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "config/configoptional/go.mod",
    "content": "module go.opentelemetry.io/collector/config/configoptional\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0\n\tgo.opentelemetry.io/collector/featuregate v1.54.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n"
  },
  {
    "path": "config/configoptional/go.sum",
    "content": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "config/configoptional/internal/metadata/generated_feature_gates.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\nvar ConfigoptionalAddEnabledFieldFeatureGate = featuregate.GlobalRegistry().MustRegister(\n\t\"configoptional.AddEnabledField\",\n\tfeaturegate.StageBeta,\n\tfeaturegate.WithRegisterDescription(\"Allows optional fields to be toggled via an 'enabled' field.\"),\n\tfeaturegate.WithRegisterReferenceURL(\"https://github.com/open-telemetry/opentelemetry-collector/issues/14021\"),\n\tfeaturegate.WithRegisterFromVersion(\"v0.138.0\"),\n)\n"
  },
  {
    "path": "config/configoptional/metadata.yaml",
    "content": "type: configoptional\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  stability:\n    beta: [metrics, traces, logs]\n    alpha: [profiles]\n\nfeature_gates:\n  - id: configoptional.AddEnabledField\n    description: \"Allows optional fields to be toggled via an 'enabled' field.\"\n    stage: beta\n    from_version: 'v0.138.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/issues/14021'\n"
  },
  {
    "path": "config/configoptional/optional.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configoptional // import \"go.opentelemetry.io/collector/config/configoptional\"\n\n//go:generate mdatagen metadata.yaml\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/config/configoptional/internal/metadata\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n)\n\ntype flavor int\n\nconst (\n\tnoneFlavor    flavor = 0\n\tdefaultFlavor flavor = 1\n\tsomeFlavor    flavor = 2\n)\n\n// Optional represents a value that may or may not be present.\n// It supports two flavors for all types: Some(value) and None.\n// It supports a third flavor for struct types: Default(defaultVal).\n//\n// For struct types, it supports unmarshaling from a configuration source.\n// For struct types, it supports an 'enabled' field to explicitly disable a section.\n// The zero value of Optional is None.\ntype Optional[T any] struct {\n\t// value is the value of the Optional.\n\tvalue T\n\n\t// flavor indicates the flavor of the Optional.\n\t// The zero value of flavor is noneFlavor.\n\tflavor flavor\n}\n\n// deref a reflect.Type to its underlying type.\nfunc deref(t reflect.Type) reflect.Type {\n\tfor t.Kind() == reflect.Ptr {\n\t\tt = t.Elem()\n\t}\n\treturn t\n}\n\n// assertStructKind checks if T can be dereferenced into a type with struct kind.\n//\n// We assert this because our unmarshaling logic currently only supports structs.\n// This can be removed if we ever support scalar values.\nfunc assertStructKind[T any]() error {\n\tvar instance T\n\tt := deref(reflect.TypeOf(instance))\n\tif t.Kind() != reflect.Struct {\n\t\treturn fmt.Errorf(\"configoptional: %q does not have a struct kind\", t)\n\t}\n\n\treturn nil\n}\n\n// assertNoEnabledField checks that a struct type\n// does not have a field with a mapstructure tag \"enabled\".\n//\n// We assert this because we discussed an alternative design where we have an explicit\n// \"enabled\" field in the struct to indicate if the struct is enabled or not.\n// See https://github.com/open-telemetry/opentelemetry-collector/pull/13060.\n// This can be removed if we ever support such a design (or if we just want to allow\n// the \"enabled\" field in the struct).\nfunc assertNoEnabledField[T any]() error {\n\tvar i T\n\tt := deref(reflect.TypeOf(i))\n\tif t.Kind() != reflect.Struct {\n\t\t// Not a struct, no need to check for \"enabled\" field.\n\t\treturn nil\n\t}\n\n\t// Check if the struct has a field with the name \"enabled\".\n\tfor i := 0; i < t.NumField(); i++ {\n\t\tfield := t.Field(i)\n\t\tmapstructureTags := strings.SplitN(field.Tag.Get(\"mapstructure\"), \",\", 2)\n\t\tif len(mapstructureTags) > 0 && mapstructureTags[0] == \"enabled\" {\n\t\t\treturn errors.New(\"configoptional: underlying type cannot have a field with mapstructure tag 'enabled'\")\n\t\t}\n\t}\n\treturn nil\n}\n\n// Some creates an Optional with a value and no factory.\n//\n// It panics if T has a field with the mapstructure tag \"enabled\".\nfunc Some[T any](value T) Optional[T] {\n\tif err := assertNoEnabledField[T](); err != nil {\n\t\tpanic(err)\n\t}\n\treturn Optional[T]{value: value, flavor: someFlavor}\n}\n\n// Default creates an Optional with a default value for unmarshaling.\n//\n// It panics if\n// - T is not a struct OR\n// - T has a field with the mapstructure tag \"enabled\".\nfunc Default[T any](value T) Optional[T] {\n\terr := errors.Join(assertStructKind[T](), assertNoEnabledField[T]())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn Optional[T]{value: value, flavor: defaultFlavor}\n}\n\n// None has no value. It has the same behavior as a nil pointer when unmarshaling.\n//\n// The zero value of Optional[T] is None[T]. Prefer using this constructor\n// for validation.\n//\n// It panics if T has a field with the mapstructure tag \"enabled\".\nfunc None[T any]() Optional[T] {\n\tif err := assertNoEnabledField[T](); err != nil {\n\t\tpanic(err)\n\t}\n\treturn Optional[T]{}\n}\n\n// HasValue checks if the Optional has a value.\nfunc (o Optional[T]) HasValue() bool {\n\treturn o.flavor == someFlavor\n}\n\n// Get returns the value of the Optional.\n// If the value is not present, it returns nil.\nfunc (o *Optional[T]) Get() *T {\n\tif !o.HasValue() {\n\t\treturn nil\n\t}\n\treturn &o.value\n}\n\n// GetOrInsertDefault makes the Optional into a Some(val) and returns val.\n//\n// In particular, if it is Default(val) it turns it into Some(val)\n// and if it is None[T]() it turns it into Some(zeroVal) where zeroVal is T's zero value.\n// This method is useful for programmatic usage of an optional.\n//\n// It panics if\n// - T is not a struct OR\n// - T has a field with the mapstructure tag \"enabled\".\nfunc (o *Optional[T]) GetOrInsertDefault() *T {\n\terr := errors.Join(assertStructKind[T](), assertNoEnabledField[T]())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tif o.HasValue() {\n\t\treturn o.Get()\n\t}\n\n\tempty := confmap.NewFromStringMap(map[string]any{})\n\tif err := empty.Unmarshal(o); err != nil {\n\t\t// This should never happen, if it happens it is a bug, so this panic is not documented.\n\t\tpanic(fmt.Errorf(\"failed to unmarshal empty map into %T type: %w. Please report this bug\", o.value, err))\n\t}\n\n\treturn o.Get()\n}\n\nvar _ confmap.Unmarshaler = (*Optional[any])(nil)\n\n// Unmarshal the configuration into the Optional value.\n//\n// The behavior of this method depends on the state of the Optional:\n//   - None[T]: does nothing if the configuration is nil, otherwise it unmarshals into the zero value of T.\n//   - Some[T](val): equivalent to unmarshaling into a field of type T with value val.\n//   - Default[T](val), equivalent to unmarshaling into a field of type T with base value val,\n//     using val without overrides from the configuration if the configuration is nil.\n//\n// (Under the `configoptional.AddEnabledField` feature gate)\n// If the configuration contains an 'enabled' field:\n//   - if enabled is true: the Optional becomes Some after unmarshaling.\n//   - if enabled is false: the Optional becomes None regardless of other configuration values.\n//\n// T must be derefenceable to a type with struct kind and not have an 'enabled' field.\n// Scalar values are not supported.\nfunc (o *Optional[T]) Unmarshal(conf *confmap.Conf) error {\n\tif err := assertNoEnabledField[T](); err != nil {\n\t\treturn err\n\t}\n\n\tif o.flavor == noneFlavor && conf.ToStringMap() == nil {\n\t\t// If the Optional is None and the configuration is nil, we do nothing.\n\t\t// This replicates the behavior of unmarshaling into a field with a nil pointer.\n\t\treturn nil\n\t}\n\n\tisEnabled := true\n\tif metadata.ConfigoptionalAddEnabledFieldFeatureGate.IsEnabled() && conf.IsSet(\"enabled\") {\n\t\tenabled := conf.Get(\"enabled\")\n\t\tconf.Delete(\"enabled\")\n\t\tvar ok bool\n\t\tif isEnabled, ok = enabled.(bool); !ok {\n\t\t\treturn fmt.Errorf(\"unexpected type %T for 'enabled': got '%v' value expected 'true' or 'false'\", enabled, enabled)\n\t\t}\n\t}\n\n\tif err := conf.Unmarshal(&o.value, xconfmap.WithForceUnmarshaler()); err != nil {\n\t\treturn err\n\t}\n\n\tif isEnabled {\n\t\to.flavor = someFlavor\n\t} else {\n\t\to.flavor = noneFlavor\n\t\t// override o.value with zero value.\n\t\tvar zero T\n\t\to.value = zero\n\t}\n\n\treturn nil\n}\n\nvar _ confmap.Marshaler = (*Optional[any])(nil)\n\n// Marshal the Optional value into the configuration.\n// If the Optional is None or Default, it does not marshal anything.\n// If the Optional is Some, it marshals the value into the configuration.\n//\n// T must be derefenceable to a type with struct kind.\n// Scalar values are not supported.\nfunc (o Optional[T]) Marshal(conf *confmap.Conf) error {\n\tif err := assertStructKind[T](); err != nil {\n\t\treturn err\n\t}\n\n\tif o.flavor == noneFlavor || o.flavor == defaultFlavor {\n\t\t// Optional is None or Default, do not marshal anything.\n\t\treturn conf.Marshal(map[string]any(nil))\n\t}\n\n\tif err := conf.Marshal(o.value); err != nil {\n\t\treturn fmt.Errorf(\"configoptional: failed to marshal Optional value: %w\", err)\n\t}\n\n\treturn nil\n}\n\nvar _ xconfmap.Validator = (*Optional[any])(nil)\n\n// Validate implements [xconfmap.Validator]. This is required because the\n// private fields in [xconfmap.Validator] can't be seen by the reflection used\n// by [xconfmap.Validate], and therefore we have to continue the validation\n// chain manually. This method isn't meant to be called directly, and should\n// generally only be called by [xconfmap.Validate].\nfunc (o *Optional[T]) Validate() error {\n\t// When the flavor is None, the user has not passed this value,\n\t// and therefore we should not validate it. The parent struct holding\n\t// the Optional type can determine whether a None value is valid for\n\t// a given config.\n\t//\n\t// If the flavor is still Default, then the user has not passed this\n\t// value and we should also not validate it.\n\tif o.flavor == noneFlavor || o.flavor == defaultFlavor {\n\t\treturn nil\n\t}\n\n\t// For the some flavor, validate the actual value.\n\treturn xconfmap.Validate(o.value)\n}\n"
  },
  {
    "path": "config/configoptional/optional_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configoptional\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/config/configoptional/internal/metadata\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\ntype Config[T any] struct {\n\tSub1 Optional[T] `mapstructure:\"sub\"`\n}\n\ntype Sub struct {\n\tFoo string `mapstructure:\"foo\"`\n}\n\ntype WithEnabled struct {\n\tEnabled bool `mapstructure:\"enabled\"`\n}\n\ntype WithEnabledOmitEmpty struct {\n\tEnabled bool `mapstructure:\"enabled,omitempty\"`\n}\n\ntype OmitEmpty struct {\n\tFoo int `mapstructure:\",omitempty\"`\n}\n\ntype NoMapstructure struct {\n\tFoo string\n}\n\nvar subDefault = Sub{\n\tFoo: \"foobar\",\n}\n\nfunc ptr[T any](v T) *T {\n\treturn &v\n}\n\nfunc TestDefaultPanics(t *testing.T) {\n\tassert.Panics(t, func() {\n\t\t_ = Default(1)\n\t})\n\n\tassert.Panics(t, func() {\n\t\t_ = Default(ptr(1))\n\t})\n\n\tassert.Panics(t, func() {\n\t\t_ = Default(WithEnabled{})\n\t})\n\n\tassert.Panics(t, func() {\n\t\t_ = Default(WithEnabledOmitEmpty{})\n\t})\n\n\tassert.Panics(t, func() {\n\t\t_ = Some(WithEnabled{})\n\t})\n\n\tassert.Panics(t, func() {\n\t\t_ = None[WithEnabled]()\n\t})\n\n\tassert.Panics(t, func() {\n\t\topt := None[int]()\n\t\t_ = opt.GetOrInsertDefault()\n\t})\n\n\tassert.Panics(t, func() {\n\t\tvar opt Optional[WithEnabled]\n\t\t_ = opt.GetOrInsertDefault()\n\t})\n\n\tassert.NotPanics(t, func() {\n\t\t_ = Default(NoMapstructure{})\n\t})\n\n\tassert.NotPanics(t, func() {\n\t\t_ = Default(OmitEmpty{})\n\t})\n\n\tassert.NotPanics(t, func() {\n\t\t_ = Default(subDefault)\n\t})\n\n\tassert.NotPanics(t, func() {\n\t\t_ = Default(ptr(subDefault))\n\t})\n}\n\nfunc TestEqualityDefault(t *testing.T) {\n\tdefaultOne := Default(subDefault)\n\tdefaultTwo := Default(subDefault)\n\tassert.Equal(t, defaultOne, defaultTwo)\n}\n\nfunc TestNoneZeroVal(t *testing.T) {\n\tvar none Optional[Sub]\n\trequire.False(t, none.HasValue())\n\trequire.Nil(t, none.Get())\n\n\tvar zeroVal Sub\n\tret := none.GetOrInsertDefault()\n\trequire.True(t, none.HasValue())\n\tassert.Equal(t, &zeroVal, ret)\n}\n\nfunc TestNone(t *testing.T) {\n\tnone := None[Sub]()\n\trequire.False(t, none.HasValue())\n\trequire.Nil(t, none.Get())\n\n\tvar zeroVal Sub\n\tret := none.GetOrInsertDefault()\n\trequire.True(t, none.HasValue())\n\tassert.Equal(t, &zeroVal, ret)\n}\n\nfunc ExampleNone() {\n\ttype Person struct {\n\t\tName string\n\t\tAge  int\n\t}\n\n\topt := None[Person]()\n\n\t// A None has no value.\n\tfmt.Println(opt.HasValue())\n\tfmt.Println(opt.Get())\n\n\t// GetOrInsertDefault places the zero value\n\t// and returns it, allowing you to modify it.\n\topt.GetOrInsertDefault().Name = \"John Doe\"\n\tfmt.Println(opt.HasValue())\n\tfmt.Println(opt.Get())\n\n\t// Output:\n\t// false\n\t// <nil>\n\t// true\n\t// &{John Doe 0}\n}\n\nfunc TestSome(t *testing.T) {\n\tsome := Some(Sub{\n\t\tFoo: \"foobar\",\n\t})\n\trequire.True(t, some.HasValue())\n\tretGet := some.Get()\n\tassert.Equal(t, \"foobar\", retGet.Foo)\n\n\tretGetOrInsertDefault := some.GetOrInsertDefault()\n\trequire.True(t, some.HasValue())\n\tassert.Equal(t, retGet, retGetOrInsertDefault)\n}\n\nfunc ExampleSome() {\n\ttype Person struct {\n\t\tName string\n\t\tAge  int\n\t}\n\n\topt := Some(Person{\n\t\tName: \"John Doe\",\n\t\tAge:  42,\n\t})\n\n\t// A Some has a value.\n\tfmt.Println(opt.HasValue())\n\tfmt.Println(opt.Get())\n\n\t// GetOrInsertDefault only returns a reference\n\t// to the inner value without modifying it.\n\topt.GetOrInsertDefault().Name = \"Jane Doe\"\n\tfmt.Println(opt.HasValue())\n\tfmt.Println(opt.Get())\n\n\t// Output:\n\t// true\n\t// &{John Doe 42}\n\t// true\n\t// &{Jane Doe 42}\n}\n\nfunc TestDefault(t *testing.T) {\n\tdefaultSub := Default(subDefault)\n\trequire.False(t, defaultSub.HasValue())\n\trequire.Nil(t, defaultSub.Get())\n\n\tret := defaultSub.GetOrInsertDefault()\n\trequire.True(t, defaultSub.HasValue())\n\tassert.Equal(t, &subDefault, ret)\n}\n\nfunc ExampleDefault() {\n\ttype Person struct {\n\t\tName string\n\t\tAge  int\n\t}\n\n\topt := Default(Person{\n\t\tName: \"John Doe\",\n\t\tAge:  42,\n\t})\n\n\t// A Default has no value.\n\tfmt.Println(opt.HasValue())\n\tfmt.Println(opt.Get())\n\n\t// GetOrInsertDefault places the default value\n\t// and returns it, allowing you to modify it.\n\topt.GetOrInsertDefault().Age = 38\n\tfmt.Println(opt.HasValue())\n\tfmt.Println(opt.Get())\n\n\t// Output:\n\t// false\n\t// <nil>\n\t// true\n\t// &{John Doe 38}\n}\n\nfunc TestUnmarshalOptional(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tconfig      map[string]any\n\t\tdefaultCfg  Config[Sub]\n\t\texpectedSub bool\n\t\texpectedFoo string\n\t}{\n\t\t{\n\t\t\tname: \"none_no_config\",\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: None[Sub](),\n\t\t\t},\n\t\t\texpectedSub: false,\n\t\t},\n\t\t{\n\t\t\tname: \"none_with_config\",\n\t\t\tconfig: map[string]any{\n\t\t\t\t\"sub\": map[string]any{\n\t\t\t\t\t\"foo\": \"bar\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: None[Sub](),\n\t\t\t},\n\t\t\texpectedSub: true,\n\t\t\texpectedFoo: \"bar\", // input overrides default\n\t\t},\n\t\t{\n\t\t\t// nil is treated as an empty map because of the hooks we use.\n\t\t\tname: \"none_with_config_no_foo\",\n\t\t\tconfig: map[string]any{\n\t\t\t\t\"sub\": nil,\n\t\t\t},\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: None[Sub](),\n\t\t\t},\n\t\t\texpectedSub: false,\n\t\t},\n\t\t{\n\t\t\tname: \"none_with_config_no_foo_empty_map\",\n\t\t\tconfig: map[string]any{\n\t\t\t\t\"sub\": map[string]any{},\n\t\t\t},\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: None[Sub](),\n\t\t\t},\n\t\t\texpectedSub: true,\n\t\t\texpectedFoo: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"default_no_config\",\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: Default(subDefault),\n\t\t\t},\n\t\t\texpectedSub: false,\n\t\t},\n\t\t{\n\t\t\tname: \"default_with_config\",\n\t\t\tconfig: map[string]any{\n\t\t\t\t\"sub\": map[string]any{\n\t\t\t\t\t\"foo\": \"bar\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: Default(subDefault),\n\t\t\t},\n\t\t\texpectedSub: true,\n\t\t\texpectedFoo: \"bar\", // input overrides default\n\t\t},\n\t\t{\n\t\t\tname: \"default_with_config_no_foo\",\n\t\t\tconfig: map[string]any{\n\t\t\t\t\"sub\": nil,\n\t\t\t},\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: Default(subDefault),\n\t\t\t},\n\t\t\texpectedSub: true,\n\t\t\texpectedFoo: \"foobar\", // default applies\n\t\t},\n\t\t{\n\t\t\tname: \"default_with_config_no_foo_empty_map\",\n\t\t\tconfig: map[string]any{\n\t\t\t\t\"sub\": map[string]any{},\n\t\t\t},\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: Default(subDefault),\n\t\t\t},\n\t\t\texpectedSub: true,\n\t\t\texpectedFoo: \"foobar\", // default applies\n\t\t},\n\t\t{\n\t\t\tname: \"some_no_config\",\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: Some(Sub{\n\t\t\t\t\tFoo: \"foobar\",\n\t\t\t\t}),\n\t\t\t},\n\t\t\texpectedSub: true,\n\t\t\texpectedFoo: \"foobar\", // value is not modified\n\t\t},\n\t\t{\n\t\t\tname: \"some_with_config\",\n\t\t\tconfig: map[string]any{\n\t\t\t\t\"sub\": map[string]any{\n\t\t\t\t\t\"foo\": \"bar\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: Some(Sub{\n\t\t\t\t\tFoo: \"foobar\",\n\t\t\t\t}),\n\t\t\t},\n\t\t\texpectedSub: true,\n\t\t\texpectedFoo: \"bar\", // input overrides previous value\n\t\t},\n\t\t{\n\t\t\tname: \"some_with_config_no_foo\",\n\t\t\tconfig: map[string]any{\n\t\t\t\t\"sub\": nil,\n\t\t\t},\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: Some(Sub{\n\t\t\t\t\tFoo: \"foobar\",\n\t\t\t\t}),\n\t\t\t},\n\t\t\texpectedSub: true,\n\t\t\texpectedFoo: \"foobar\", // default applies\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tcfg := test.defaultCfg\n\t\t\tconf := confmap.NewFromStringMap(test.config)\n\t\t\trequire.NoError(t, conf.Unmarshal(&cfg))\n\t\t\trequire.Equal(t, test.expectedSub, cfg.Sub1.HasValue())\n\t\t\tif test.expectedSub {\n\t\t\t\trequire.Equal(t, test.expectedFoo, cfg.Sub1.Get().Foo)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestAddFieldEnabledFeatureGate(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tconfig      map[string]any\n\t\tdefaultCfg  Config[Sub]\n\t\texpectedSub bool\n\t\texpectedFoo string\n\t}{\n\t\t{\n\t\t\tname: \"none_with_enabled_true\",\n\t\t\tconfig: map[string]any{\n\t\t\t\t\"sub\": map[string]any{\n\t\t\t\t\t\"enabled\": true,\n\t\t\t\t\t\"foo\":     \"bar\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: None[Sub](),\n\t\t\t},\n\t\t\texpectedSub: true,\n\t\t\texpectedFoo: \"bar\",\n\t\t},\n\t\t{\n\t\t\tname: \"none_with_enabled_false\",\n\t\t\tconfig: map[string]any{\n\t\t\t\t\"sub\": map[string]any{\n\t\t\t\t\t\"enabled\": false,\n\t\t\t\t\t\"foo\":     \"bar\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: None[Sub](),\n\t\t\t},\n\t\t\texpectedSub: false,\n\t\t},\n\t\t{\n\t\t\tname: \"none_with_enabled_false_no_other_config\",\n\t\t\tconfig: map[string]any{\n\t\t\t\t\"sub\": map[string]any{\n\t\t\t\t\t\"enabled\": false,\n\t\t\t\t},\n\t\t\t},\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: None[Sub](),\n\t\t\t},\n\t\t\texpectedSub: false,\n\t\t},\n\t\t{\n\t\t\tname: \"default_with_enabled_true\",\n\t\t\tconfig: map[string]any{\n\t\t\t\t\"sub\": map[string]any{\n\t\t\t\t\t\"enabled\": true,\n\t\t\t\t\t\"foo\":     \"bar\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: Default(subDefault),\n\t\t\t},\n\t\t\texpectedSub: true,\n\t\t\texpectedFoo: \"bar\",\n\t\t},\n\t\t{\n\t\t\tname: \"default_with_enabled_false\",\n\t\t\tconfig: map[string]any{\n\t\t\t\t\"sub\": map[string]any{\n\t\t\t\t\t\"enabled\": false,\n\t\t\t\t\t\"foo\":     \"bar\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: Default(subDefault),\n\t\t\t},\n\t\t\texpectedSub: false,\n\t\t},\n\t\t{\n\t\t\tname: \"default_with_enabled_false_no_other_config\",\n\t\t\tconfig: map[string]any{\n\t\t\t\t\"sub\": map[string]any{\n\t\t\t\t\t\"enabled\": false,\n\t\t\t\t},\n\t\t\t},\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: Default(subDefault),\n\t\t\t},\n\t\t\texpectedSub: false,\n\t\t},\n\t\t{\n\t\t\tname: \"some_with_enabled_true\",\n\t\t\tconfig: map[string]any{\n\t\t\t\t\"sub\": map[string]any{\n\t\t\t\t\t\"enabled\": true,\n\t\t\t\t\t\"foo\":     \"baz\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: Some(Sub{\n\t\t\t\t\tFoo: \"foobar\",\n\t\t\t\t}),\n\t\t\t},\n\t\t\texpectedSub: true,\n\t\t\texpectedFoo: \"baz\",\n\t\t},\n\t\t{\n\t\t\tname: \"some_with_enabled_false\",\n\t\t\tconfig: map[string]any{\n\t\t\t\t\"sub\": map[string]any{\n\t\t\t\t\t\"enabled\": false,\n\t\t\t\t\t\"foo\":     \"baz\",\n\t\t\t\t},\n\t\t\t},\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: Some(Sub{\n\t\t\t\t\tFoo: \"foobar\",\n\t\t\t\t}),\n\t\t\t},\n\t\t\texpectedSub: false,\n\t\t},\n\t\t{\n\t\t\tname: \"some_with_enabled_false_no_other_config\",\n\t\t\tconfig: map[string]any{\n\t\t\t\t\"sub\": map[string]any{\n\t\t\t\t\t\"enabled\": false,\n\t\t\t\t},\n\t\t\t},\n\t\t\tdefaultCfg: Config[Sub]{\n\t\t\t\tSub1: Some(Sub{\n\t\t\t\t\tFoo: \"foobar\",\n\t\t\t\t}),\n\t\t\t},\n\t\t\texpectedSub: false,\n\t\t},\n\t}\n\n\toldVal := metadata.ConfigoptionalAddEnabledFieldFeatureGate.IsEnabled()\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ConfigoptionalAddEnabledFieldFeatureGate.ID(), true))\n\tdefer func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ConfigoptionalAddEnabledFieldFeatureGate.ID(), oldVal))\n\t}()\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tcfg := test.defaultCfg\n\t\t\tconf := confmap.NewFromStringMap(test.config)\n\t\t\trequire.NoError(t, conf.Unmarshal(&cfg))\n\t\t\trequire.Equal(t, test.expectedSub, cfg.Sub1.HasValue())\n\t\t\tif test.expectedSub {\n\t\t\t\trequire.Equal(t, test.expectedFoo, cfg.Sub1.Get().Foo)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestEnabledFalseResetsValue(t *testing.T) {\n\toldVal := metadata.ConfigoptionalAddEnabledFieldFeatureGate.IsEnabled()\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ConfigoptionalAddEnabledFieldFeatureGate.ID(), true))\n\tdefer func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ConfigoptionalAddEnabledFieldFeatureGate.ID(), oldVal))\n\t}()\n\n\tcfg := Config[Sub]{Sub1: Some(Sub{Foo: \"initial\"})}\n\trequire.True(t, cfg.Sub1.HasValue())\n\n\tcm := confmap.NewFromStringMap(map[string]any{\n\t\t\"sub\": map[string]any{\"enabled\": false, \"foo\": \"ignored\"},\n\t})\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\trequire.Equal(t, None[Sub](), cfg.Sub1)\n}\n\nfunc TestUnmarshalErrorEnabledInvalidType(t *testing.T) {\n\toldVal := metadata.ConfigoptionalAddEnabledFieldFeatureGate.IsEnabled()\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ConfigoptionalAddEnabledFieldFeatureGate.ID(), true))\n\tdefer func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ConfigoptionalAddEnabledFieldFeatureGate.ID(), oldVal))\n\t}()\n\n\tcm := confmap.NewFromStringMap(map[string]any{\n\t\t\"sub\": map[string]any{\n\t\t\t\"enabled\": \"something\",\n\t\t\t\"foo\":     \"bar\",\n\t\t},\n\t})\n\tcfg := Config[Sub]{\n\t\tSub1: None[Sub](),\n\t}\n\terr := cm.Unmarshal(&cfg)\n\trequire.ErrorContains(t, err, \"unexpected type string for 'enabled': got 'something' value expected 'true' or 'false'\")\n}\n\nfunc TestUnmarshalErrorEnabledField(t *testing.T) {\n\tcm := confmap.NewFromStringMap(map[string]any{\n\t\t\"enabled\": true,\n\t})\n\t// Use zero value to avoid panic on constructor.\n\tvar none Optional[WithEnabled]\n\trequire.Error(t, cm.Unmarshal(&none))\n}\n\nfunc TestUnmarshalConfigPointer(t *testing.T) {\n\tcm := confmap.NewFromStringMap(map[string]any{\n\t\t\"sub\": map[string]any{\n\t\t\t\"foo\": \"bar\",\n\t\t},\n\t})\n\n\tvar cfg Config[*Sub]\n\terr := cm.Unmarshal(&cfg)\n\trequire.NoError(t, err)\n\tassert.True(t, cfg.Sub1.HasValue())\n\tassert.Equal(t, \"bar\", (*cfg.Sub1.Get()).Foo)\n}\n\nfunc TestUnmarshalErr(t *testing.T) {\n\tcm := confmap.NewFromStringMap(map[string]any{\n\t\t\"field\": \"value\",\n\t})\n\n\tcfg := Config[Sub]{\n\t\tSub1: Default(subDefault),\n\t}\n\n\tassert.False(t, cfg.Sub1.HasValue())\n\n\terr := cm.Unmarshal(&cfg)\n\trequire.Error(t, err)\n\trequire.ErrorContains(t, err, \"has invalid keys: field\")\n\tassert.False(t, cfg.Sub1.HasValue())\n}\n\ntype MyIntConfig struct {\n\tVal int `mapstructure:\"my_int\"`\n}\ntype MyConfig struct {\n\tOptional[MyIntConfig] `mapstructure:\",squash\"`\n}\n\nvar myIntDefault = MyIntConfig{\n\tVal: 1,\n}\n\nfunc TestSquashedOptional(t *testing.T) {\n\tcm := confmap.NewFromStringMap(map[string]any{\n\t\t\"my_int\": 42,\n\t})\n\n\tcfg := MyConfig{\n\t\tDefault(myIntDefault),\n\t}\n\n\terr := cm.Unmarshal(&cfg)\n\trequire.NoError(t, err)\n\n\tassert.True(t, cfg.HasValue())\n\tassert.Equal(t, 42, cfg.Get().Val)\n}\n\nfunc confFromYAML(t *testing.T, yaml string) *confmap.Conf {\n\tt.Helper()\n\tcm, err := confmap.NewRetrievedFromYAML([]byte(yaml))\n\trequire.NoError(t, err)\n\tconf, err := cm.AsConf()\n\trequire.NoError(t, err)\n\treturn conf\n}\n\nfunc TestComparePointerUnmarshal(t *testing.T) {\n\ttests := []struct {\n\t\tyaml string\n\t}{\n\t\t{yaml: \"\"},\n\t\t{yaml: \"sub: \"},\n\t\t{yaml: \"sub: null\"},\n\t\t{yaml: \"sub: {}\"},\n\t\t{yaml: \"sub: {foo: bar}\"},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.yaml, func(t *testing.T) {\n\t\t\tvar optCfg Config[Sub]\n\t\t\tconf := confFromYAML(t, test.yaml)\n\t\t\toptErr := conf.Unmarshal(&optCfg)\n\t\t\trequire.NoError(t, optErr)\n\n\t\t\tvar ptrCfg struct {\n\t\t\t\tSub1 *Sub `mapstructure:\"sub\"`\n\t\t\t}\n\t\t\tptrErr := conf.Unmarshal(&ptrCfg)\n\t\t\trequire.NoError(t, ptrErr)\n\n\t\t\tassert.Equal(t, optCfg.Sub1.Get(), ptrCfg.Sub1)\n\t\t})\n\t}\n}\n\nfunc TestOptionalMarshal(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tvalue    Config[Sub]\n\t\texpected map[string]any\n\t}{\n\t\t{\n\t\t\tname:     \"none (zero value)\",\n\t\t\tvalue:    Config[Sub]{},\n\t\t\texpected: map[string]any{\"sub\": nil},\n\t\t},\n\t\t{\n\t\t\tname:     \"none\",\n\t\t\tvalue:    Config[Sub]{Sub1: None[Sub]()},\n\t\t\texpected: map[string]any{\"sub\": nil},\n\t\t},\n\t\t{\n\t\t\tname:     \"default\",\n\t\t\tvalue:    Config[Sub]{Sub1: Default(subDefault)},\n\t\t\texpected: map[string]any{\"sub\": nil},\n\t\t},\n\t\t{\n\t\t\tname: \"some\",\n\t\t\tvalue: Config[Sub]{Sub1: Some(Sub{\n\t\t\t\tFoo: \"bar\",\n\t\t\t})},\n\t\t\texpected: map[string]any{\n\t\t\t\t\"sub\": map[string]any{\n\t\t\t\t\t\"foo\": \"bar\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tconf := confmap.New()\n\t\t\trequire.NoError(t, conf.Marshal(test.value))\n\t\t\tassert.Equal(t, test.expected, conf.ToStringMap())\n\t\t})\n\t}\n}\n\nfunc TestComparePointerMarshal(t *testing.T) {\n\ttype Wrap[T any] struct {\n\t\t// Note: passes without requiring \"squash\".\n\t\tSub1 T `mapstructure:\"sub\"`\n\t}\n\n\ttype WrapOmitEmpty[T any] struct {\n\t\t// Note: passes without requiring \"squash\", except with Default-flavored Optional values.\n\t\tSub1 T `mapstructure:\"sub,omitempty\"`\n\t}\n\n\ttests := []struct {\n\t\tpointer       *Sub\n\t\toptional      Optional[Sub]\n\t\tskipOmitEmpty bool\n\t}{\n\t\t{pointer: nil, optional: None[Sub]()},\n\t\t{pointer: nil, optional: Default(subDefault), skipOmitEmpty: true}, // does not work with omitempty\n\t\t{pointer: &Sub{Foo: \"bar\"}, optional: Some(Sub{Foo: \"bar\"})},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(fmt.Sprintf(\"%v vs %v\", test.pointer, test.optional), func(t *testing.T) {\n\t\t\twrapPointer := Wrap[*Sub]{Sub1: test.pointer}\n\t\t\tconfPointer := confmap.NewFromStringMap(nil)\n\t\t\trequire.NoError(t, confPointer.Marshal(wrapPointer))\n\n\t\t\twrapOptional := Wrap[Optional[Sub]]{Sub1: test.optional}\n\t\t\tconfOptional := confmap.NewFromStringMap(nil)\n\t\t\trequire.NoError(t, confOptional.Marshal(wrapOptional))\n\n\t\t\tassert.Equal(t, confPointer.ToStringMap(), confOptional.ToStringMap())\n\t\t})\n\n\t\tif test.skipOmitEmpty {\n\t\t\tcontinue\n\t\t}\n\t\tt.Run(fmt.Sprintf(\"%v vs %v (omitempty)\", test.pointer, test.optional), func(t *testing.T) {\n\t\t\twrapPointer := WrapOmitEmpty[*Sub]{Sub1: test.pointer}\n\t\t\tconfPointer := confmap.NewFromStringMap(nil)\n\t\t\trequire.NoError(t, confPointer.Marshal(wrapPointer))\n\n\t\t\twrapOptional := WrapOmitEmpty[Optional[Sub]]{Sub1: test.optional}\n\t\t\tconfOptional := confmap.NewFromStringMap(nil)\n\t\t\trequire.NoError(t, confOptional.Marshal(wrapOptional))\n\n\t\t\tassert.Equal(t, confPointer.ToStringMap(), confOptional.ToStringMap())\n\t\t})\n\t}\n}\n\ntype invalid struct{}\n\nfunc (invalid) Validate() error {\n\treturn errors.New(\"invalid\")\n}\n\nvar _ xconfmap.Validator = invalid{}\n\ntype hasNested struct {\n\tCouldBe Optional[invalid]\n}\n\nfunc TestOptionalValidate(t *testing.T) {\n\trequire.NoError(t, xconfmap.Validate(hasNested{\n\t\tCouldBe: None[invalid](),\n\t}))\n\trequire.NoError(t, xconfmap.Validate(hasNested{\n\t\tCouldBe: Default(invalid{}),\n\t}))\n\trequire.Error(t, xconfmap.Validate(hasNested{\n\t\tCouldBe: Some(invalid{}),\n\t}))\n}\n\ntype validatedConfig struct {\n\tDefault Optional[optionalConfig] `mapstructure:\"default\"`\n\tSome    Optional[someConfig]     `mapstructure:\"some\"`\n}\n\nvar _ xconfmap.Validator = (*optionalConfig)(nil)\n\ntype optionalConfig struct {\n\tStringVal string `mapstructure:\"string_val\"`\n}\n\nfunc (n optionalConfig) Validate() error {\n\tif n.StringVal == \"invalid\" {\n\t\treturn errors.New(\"field `string_val` cannot be set to `invalid`\")\n\t}\n\n\treturn nil\n}\n\ntype someConfig struct {\n\tNested Optional[optionalConfig] `mapstructure:\"nested\"`\n}\n\nfunc newDefaultValidatedConfig() validatedConfig {\n\treturn validatedConfig{\n\t\tDefault: Default(optionalConfig{StringVal: \"valid\"}),\n\t}\n}\n\nfunc newInvalidDefaultConfig() validatedConfig {\n\treturn validatedConfig{\n\t\tDefault: Default(optionalConfig{StringVal: \"invalid\"}),\n\t}\n}\n\nfunc TestOptionalFileValidate(t *testing.T) {\n\tcases := []struct {\n\t\tname    string\n\t\tvariant string\n\t\tcfg     func() validatedConfig\n\t\terr     error\n\t}{\n\t\t{\n\t\t\tname:    \"valid default with just key set and no subfields\",\n\t\t\tvariant: \"implicit\",\n\t\t\tcfg:     newDefaultValidatedConfig,\n\t\t},\n\t\t{\n\t\t\tname:    \"valid default with keys set in default\",\n\t\t\tvariant: \"explicit\",\n\t\t\tcfg:     newDefaultValidatedConfig,\n\t\t},\n\t\t{\n\t\t\tname:    \"invalid config\",\n\t\t\tvariant: \"invalid\",\n\t\t\tcfg:     newDefaultValidatedConfig,\n\t\t\terr:     errors.New(\"default: field `string_val` cannot be set to `invalid`\\nsome: nested: field `string_val` cannot be set to `invalid`\"),\n\t\t},\n\t\t{\n\t\t\tname:    \"invalid default throws an error\",\n\t\t\tvariant: \"implicit\",\n\t\t\tcfg:     newInvalidDefaultConfig,\n\t\t\terr:     errors.New(\"default: field `string_val` cannot be set to `invalid`\"),\n\t\t},\n\t\t{\n\t\t\tname:    \"invalid default does not throw an error when key is not set\",\n\t\t\tvariant: \"no_default\",\n\t\t\tcfg:     newInvalidDefaultConfig,\n\t\t},\n\t\t{\n\t\t\tname:    \"invalid default invalid default does not throw an error when the value is overridden\",\n\t\t\tvariant: \"explicit\",\n\t\t\tcfg:     newInvalidDefaultConfig,\n\t\t},\n\t}\n\n\tfor _, tt := range cases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tconf, err := confmaptest.LoadConf(fmt.Sprintf(\"testdata/validate_%s.yaml\", tt.variant))\n\t\t\trequire.NoError(t, err)\n\n\t\t\tcfg := tt.cfg()\n\n\t\t\terr = conf.Unmarshal(&cfg)\n\t\t\trequire.NoError(t, err)\n\n\t\t\terr = xconfmap.Validate(cfg)\n\t\t\tif tt.err == nil {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.EqualError(t, err, tt.err.Error())\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "config/configoptional/testdata/validate_explicit.yaml",
    "content": "default:\n  string_val: valid\nsome:\n  nested:\n    string_val: valid\n"
  },
  {
    "path": "config/configoptional/testdata/validate_implicit.yaml",
    "content": "default:\nsome:\n  nested:\n    string_val: value1\n"
  },
  {
    "path": "config/configoptional/testdata/validate_invalid.yaml",
    "content": "default:\n  string_val: invalid\nsome:\n  nested:\n    string_val: invalid\n"
  },
  {
    "path": "config/configoptional/testdata/validate_no_default.yaml",
    "content": "some:\n  nested:\n    string_val: value1\n"
  },
  {
    "path": "config/configretry/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "config/configretry/backoff.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configretry // import \"go.opentelemetry.io/collector/config/configretry\"\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"github.com/cenkalti/backoff/v5\"\n)\n\n// NewDefaultBackOffConfig returns the default settings for RetryConfig.\nfunc NewDefaultBackOffConfig() BackOffConfig {\n\treturn BackOffConfig{\n\t\tEnabled:             true,\n\t\tInitialInterval:     5 * time.Second,\n\t\tRandomizationFactor: backoff.DefaultRandomizationFactor,\n\t\tMultiplier:          backoff.DefaultMultiplier,\n\t\tMaxInterval:         30 * time.Second,\n\t\tMaxElapsedTime:      5 * time.Minute,\n\t}\n}\n\n// BackOffConfig defines configuration for retrying batches in case of export failure.\n// The current supported strategy is exponential backoff.\ntype BackOffConfig struct {\n\t// Enabled indicates whether to not retry sending batches in case of export failure.\n\tEnabled bool `mapstructure:\"enabled\"`\n\t// InitialInterval the time to wait after the first failure before retrying.\n\tInitialInterval time.Duration `mapstructure:\"initial_interval\"`\n\t// RandomizationFactor is a random factor used to calculate next backoffs\n\t// Randomized interval = RetryInterval * (1 ± RandomizationFactor)\n\tRandomizationFactor float64 `mapstructure:\"randomization_factor\"`\n\t// Multiplier is the value multiplied by the backoff interval bounds\n\tMultiplier float64 `mapstructure:\"multiplier\"`\n\t// MaxInterval is the upper bound on backoff interval. Once this value is reached the delay between\n\t// consecutive retries will always be `MaxInterval`.\n\tMaxInterval time.Duration `mapstructure:\"max_interval\"`\n\t// MaxElapsedTime is the maximum amount of time (including retries) spent trying to send a request/batch.\n\t// Once this value is reached, the data is discarded. If set to 0, the retries are never stopped.\n\tMaxElapsedTime time.Duration `mapstructure:\"max_elapsed_time\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\nfunc (bs *BackOffConfig) Validate() error {\n\tif !bs.Enabled {\n\t\treturn nil\n\t}\n\tif bs.InitialInterval < 0 {\n\t\treturn errors.New(\"'initial_interval' must be non-negative\")\n\t}\n\tif bs.RandomizationFactor < 0 || bs.RandomizationFactor > 1 {\n\t\treturn errors.New(\"'randomization_factor' must be within [0, 1]\")\n\t}\n\tif bs.Multiplier < 0 {\n\t\treturn errors.New(\"'multiplier' must be non-negative\")\n\t}\n\tif bs.MaxInterval < 0 {\n\t\treturn errors.New(\"'max_interval' must be non-negative\")\n\t}\n\tif bs.MaxElapsedTime < 0 {\n\t\treturn errors.New(\"'max_elapsed_time' must be non-negative\")\n\t}\n\tif bs.MaxElapsedTime > 0 {\n\t\tif bs.MaxElapsedTime < bs.InitialInterval {\n\t\t\treturn errors.New(\"'max_elapsed_time' must not be less than 'initial_interval'\")\n\t\t}\n\t\tif bs.MaxElapsedTime < bs.MaxInterval {\n\t\t\treturn errors.New(\"'max_elapsed_time' must not be less than 'max_interval'\")\n\t\t}\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "config/configretry/backoff_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configretry\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestNewDefaultBackOffSettings(t *testing.T) {\n\tcfg := NewDefaultBackOffConfig()\n\trequire.NoError(t, cfg.Validate())\n\tassert.Equal(t,\n\t\tBackOffConfig{\n\t\t\tEnabled:             true,\n\t\t\tInitialInterval:     5 * time.Second,\n\t\t\tRandomizationFactor: 0.5,\n\t\t\tMultiplier:          1.5,\n\t\t\tMaxInterval:         30 * time.Second,\n\t\t\tMaxElapsedTime:      5 * time.Minute,\n\t\t}, cfg)\n}\n\nfunc TestInvalidInitialInterval(t *testing.T) {\n\tcfg := NewDefaultBackOffConfig()\n\trequire.NoError(t, cfg.Validate())\n\tcfg.InitialInterval = -1\n\tassert.Error(t, cfg.Validate())\n}\n\nfunc TestInvalidRandomizationFactor(t *testing.T) {\n\tcfg := NewDefaultBackOffConfig()\n\trequire.NoError(t, cfg.Validate())\n\tcfg.RandomizationFactor = -1\n\trequire.Error(t, cfg.Validate())\n\tcfg.RandomizationFactor = 2\n\tassert.Error(t, cfg.Validate())\n}\n\nfunc TestInvalidMultiplier(t *testing.T) {\n\tcfg := NewDefaultBackOffConfig()\n\trequire.NoError(t, cfg.Validate())\n\tcfg.Multiplier = -1\n\tassert.Error(t, cfg.Validate())\n}\n\nfunc TestZeroMultiplierIsValid(t *testing.T) {\n\tcfg := NewDefaultBackOffConfig()\n\tassert.NoError(t, cfg.Validate())\n\tcfg.Multiplier = 0\n\tassert.NoError(t, cfg.Validate())\n}\n\nfunc TestInvalidMaxInterval(t *testing.T) {\n\tcfg := NewDefaultBackOffConfig()\n\trequire.NoError(t, cfg.Validate())\n\tcfg.MaxInterval = -1\n\tassert.Error(t, cfg.Validate())\n}\n\nfunc TestInvalidMaxElapsedTime(t *testing.T) {\n\tcfg := NewDefaultBackOffConfig()\n\trequire.NoError(t, cfg.Validate())\n\tcfg.MaxElapsedTime = -1\n\trequire.Error(t, cfg.Validate())\n\tcfg.MaxElapsedTime = 60\n\t// MaxElapsedTime is 60, InitialInterval is 5s, so it should be invalid\n\trequire.Error(t, cfg.Validate())\n\tcfg.InitialInterval = 0\n\t// MaxElapsedTime is 60, MaxInterval is 30s, so it should be invalid\n\trequire.Error(t, cfg.Validate())\n\tcfg.MaxInterval = 0\n\tassert.NoError(t, cfg.Validate())\n\tcfg.InitialInterval = 50\n\t// MaxElapsedTime is 0, so it should be valid\n\tcfg.MaxElapsedTime = 0\n\tassert.NoError(t, cfg.Validate())\n}\n\nfunc TestDisabledWithInvalidValues(t *testing.T) {\n\tcfg := BackOffConfig{\n\t\tEnabled:             false,\n\t\tInitialInterval:     -1,\n\t\tRandomizationFactor: -1,\n\t\tMultiplier:          0,\n\t\tMaxInterval:         -1,\n\t\tMaxElapsedTime:      -1,\n\t}\n\tassert.NoError(t, cfg.Validate())\n}\n"
  },
  {
    "path": "config/configretry/config.schema.yaml",
    "content": "$defs:\n  back_off_config:\n    description: BackOffConfig defines configuration for retrying batches in case of export failure. The current supported strategy is exponential backoff.\n    type: object\n    properties:\n      enabled:\n        description: Enabled indicates whether to not retry sending batches in case of export failure.\n        type: boolean\n      initial_interval:\n        description: InitialInterval the time to wait after the first failure before retrying.\n        type: string\n        x-customType: time.Duration\n        format: duration\n      max_elapsed_time:\n        description: MaxElapsedTime is the maximum amount of time (including retries) spent trying to send a request/batch. Once this value is reached, the data is discarded. If set to 0, the retries are never stopped.\n        type: string\n        x-customType: time.Duration\n        format: duration\n      max_interval:\n        description: MaxInterval is the upper bound on backoff interval. Once this value is reached the delay between consecutive retries will always be `MaxInterval`.\n        type: string\n        x-customType: time.Duration\n        format: duration\n      multiplier:\n        description: Multiplier is the value multiplied by the backoff interval bounds\n        type: number\n        x-customType: float64\n      randomization_factor:\n        description: RandomizationFactor is a random factor used to calculate next backoffs Randomized interval = RetryInterval * (1 ± RandomizationFactor)\n        type: number\n        x-customType: float64\n"
  },
  {
    "path": "config/configretry/go.mod",
    "content": "module go.opentelemetry.io/collector/config/configretry\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/cenkalti/backoff/v5 v5.0.3\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/kr/pretty v0.3.1 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/rogpeppe/go-internal v1.10.0 // indirect\n\tgopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n"
  },
  {
    "path": "config/configretry/go.sum",
    "content": "github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=\ngithub.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=\ngithub.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=\ngithub.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "config/configretry/metadata.yaml",
    "content": "type: config/configretry\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "config/configretry/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configretry\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "config/configtelemetry/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "config/configtelemetry/config.schema.yaml",
    "content": "$defs:\n  level:\n    description: Level is the level of internal telemetry (metrics, logs, traces about the component itself) that every component should generate.\n    type: integer\n    x-customType: int32\n"
  },
  {
    "path": "config/configtelemetry/configtelemetry.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configtelemetry // import \"go.opentelemetry.io/collector/config/configtelemetry\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n)\n\nconst (\n\t// LevelNone indicates that no telemetry should be collected.\n\tLevelNone Level = iota - 1\n\t// LevelBasic indicates that only core Collector telemetry should be collected.\n\tLevelBasic\n\t// LevelNormal indicates that all low-overhead telemetry should be collected.\n\tLevelNormal\n\t// LevelDetailed indicates that all available telemetry should be collected.\n\tLevelDetailed\n\n\tlevelNoneStr     = \"None\"\n\tlevelBasicStr    = \"Basic\"\n\tlevelNormalStr   = \"Normal\"\n\tlevelDetailedStr = \"Detailed\"\n)\n\n// Level is the level of internal telemetry (metrics, logs, traces about the component itself)\n// that every component should generate.\ntype Level int32\n\nfunc (l Level) String() string {\n\tswitch l {\n\tcase LevelNone:\n\t\treturn levelNoneStr\n\tcase LevelBasic:\n\t\treturn levelBasicStr\n\tcase LevelNormal:\n\t\treturn levelNormalStr\n\tcase LevelDetailed:\n\t\treturn levelDetailedStr\n\t}\n\treturn \"\"\n}\n\n// MarshalText marshals Level to text.\nfunc (l Level) MarshalText() (text []byte, err error) {\n\treturn []byte(l.String()), nil\n}\n\n// UnmarshalText unmarshalls text to a Level.\nfunc (l *Level) UnmarshalText(text []byte) error {\n\tif l == nil {\n\t\treturn errors.New(\"cannot unmarshal to a nil *Level\")\n\t}\n\n\tstr := strings.ToLower(string(text))\n\tswitch str {\n\tcase strings.ToLower(levelNoneStr):\n\t\t*l = LevelNone\n\t\treturn nil\n\tcase strings.ToLower(levelBasicStr):\n\t\t*l = LevelBasic\n\t\treturn nil\n\tcase strings.ToLower(levelNormalStr):\n\t\t*l = LevelNormal\n\t\treturn nil\n\tcase strings.ToLower(levelDetailedStr):\n\t\t*l = LevelDetailed\n\t\treturn nil\n\t}\n\treturn fmt.Errorf(\"unknown metrics level %q\", str)\n}\n"
  },
  {
    "path": "config/configtelemetry/configtelemetry_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configtelemetry\n\nimport (\n\t\"encoding\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar (\n\t_ encoding.TextMarshaler   = (*Level)(nil)\n\t_ encoding.TextUnmarshaler = (*Level)(nil)\n)\n\nfunc TestUnmarshalText(t *testing.T) {\n\ttests := []struct {\n\t\tstr   []string\n\t\tlevel Level\n\t\terr   bool\n\t}{\n\t\t{\n\t\t\tstr:   []string{\"\", \"other_string\"},\n\t\t\tlevel: LevelNone,\n\t\t\terr:   true,\n\t\t},\n\t\t{\n\t\t\tstr:   []string{\"none\", \"None\", \"NONE\"},\n\t\t\tlevel: LevelNone,\n\t\t},\n\t\t{\n\t\t\tstr:   []string{\"basic\", \"Basic\", \"BASIC\"},\n\t\t\tlevel: LevelBasic,\n\t\t},\n\t\t{\n\t\t\tstr:   []string{\"normal\", \"Normal\", \"NORMAL\"},\n\t\t\tlevel: LevelNormal,\n\t\t},\n\t\t{\n\t\t\tstr:   []string{\"detailed\", \"Detailed\", \"DETAILED\"},\n\t\t\tlevel: LevelDetailed,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tfor _, str := range test.str {\n\t\t\tt.Run(str, func(t *testing.T) {\n\t\t\t\tvar lvl Level\n\t\t\t\terr := lvl.UnmarshalText([]byte(str))\n\t\t\t\tif test.err {\n\t\t\t\t\tassert.Error(t, err)\n\t\t\t\t} else {\n\t\t\t\t\trequire.NoError(t, err)\n\t\t\t\t\tassert.Equal(t, test.level, lvl)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestUnmarshalTextNilLevel(t *testing.T) {\n\tlvl := (*Level)(nil)\n\tassert.Error(t, lvl.UnmarshalText([]byte(levelNormalStr)))\n}\n\nfunc TestLevelStringMarshal(t *testing.T) {\n\ttests := []struct {\n\t\tstr   string\n\t\tlevel Level\n\t\terr   bool\n\t}{\n\t\t{\n\t\t\tstr:   \"\",\n\t\t\tlevel: Level(-10),\n\t\t},\n\t\t{\n\t\t\tstr:   levelNoneStr,\n\t\t\tlevel: LevelNone,\n\t\t},\n\t\t{\n\t\t\tstr:   levelBasicStr,\n\t\t\tlevel: LevelBasic,\n\t\t},\n\t\t{\n\t\t\tstr:   levelNormalStr,\n\t\t\tlevel: LevelNormal,\n\t\t},\n\t\t{\n\t\t\tstr:   levelDetailedStr,\n\t\t\tlevel: LevelDetailed,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.str, func(t *testing.T) {\n\t\t\tassert.Equal(t, tt.str, tt.level.String())\n\t\t\tgot, err := tt.level.MarshalText()\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tt.str, string(got))\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "config/configtelemetry/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package configtelemetry defines various telemetry level for configuration.\n// It enables every component to have access to telemetry level\n// to enable metrics only when necessary.\n//\n// This document provides guidance on which telemetry level to adopt for Collector metrics.\n// When adopting a telemetry level, component authors are expected to rely on this guidance to\n// justify their choice of telemetry level.\n//\n// 1. configtelemetry.None\n//\n// No telemetry data is recorded.\n//\n// 2. configtelemetry.Basic\n//\n// Telemetry associated with this level provides essential coverage of the Collector telemetry.\n// It should only be used for telemetry generated by the core Collector API.\n// Components outside of the core API MUST NOT record telemetry at this level.\n//\n// 3. configtelemetry.Normal\n//\n// Telemetry associated with this level provides intermediate coverage of the Collector telemetry.\n// It should be the default for component authors.\n//\n// Normal-level telemetry should have limited cardinality and data volume, though it is acceptable\n// for them to scale linearly with the monitored resources.\n// For example, there may be a limit of 5 attribute sets or 5 spans generated per request.\n//\n// Normal-level telemetry should also have a low computational cost: it should not contain values\n// requiring significant additional computation compared to the normal flow of processing.\n//\n// This is the default level recommended when running the Collector.\n//\n// 4. configtelemetry.Detailed\n//\n// Telemetry associated with this level provides complete coverage of the collector telemetry.\n//\n// The signals associated with this level may exhibit high cardinality, high data volume, or high\n// computational cost.\npackage configtelemetry // import \"go.opentelemetry.io/collector/config/configtelemetry\"\n"
  },
  {
    "path": "config/configtelemetry/go.mod",
    "content": "module go.opentelemetry.io/collector/config/configtelemetry\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/kr/pretty v0.3.1 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/rogpeppe/go-internal v1.10.0 // indirect\n\tgopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n"
  },
  {
    "path": "config/configtelemetry/go.sum",
    "content": "github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=\ngithub.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "config/configtelemetry/metadata.yaml",
    "content": "type: config/configtelemetry\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "config/configtelemetry/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configtelemetry\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "config/configtls/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "config/configtls/README.md",
    "content": "# TLS Configuration Settings\n\nCrypto TLS exposes a [variety of settings](https://godoc.org/crypto/tls).\nSeveral of these settings are available for configuration within individual\nreceivers or exporters.\n\nNote that mutual TLS (mTLS) is also supported.\n\n## TLS / mTLS Configuration\n\nBy default, TLS is enabled:\n\n- `insecure` (default = false): whether to enable client transport security for\n  the exporter's HTTPs or gRPC connection. See\n  [grpc.WithInsecure()](https://godoc.org/google.golang.org/grpc#WithInsecure)\n  for gRPC.\n- `curve_preferences` (default = []): specify your curve preferences  that will\n\t be used in an ECDHE handshake, in preference order. Accepted values are:\n  - X25519\n  - P521\n  - P256\n  - P384\n\nAs a result, the following parameters are also required:\n\n- `cert_file`: Path to the TLS cert to use for TLS required connections. Should\n  only be used if `insecure` is set to false.\n  - `cert_pem`: Alternative to `cert_file`. Provide the certificate contents as a string instead of a filepath.\n\n- `key_file`: Path to the TLS key to use for TLS required connections. Should\n  only be used if `insecure` is set to false.\n  - `key_pem`: Alternative to `key_file`. Provide the key contents as a string instead of a filepath.\n\nA certificate authority may also need to be defined:\n\n- `ca_file`: Path to the CA cert. For a client this verifies the server\n  certificate. For a server this verifies client certificates. If empty uses\n  system root CA. Should only be used if `insecure` is set to false.\n  - `ca_pem`: Alternative to `ca_file`. Provide the CA cert contents as a string instead of a filepath.\n\nYou can also combine defining a certificate authority with the system certificate authorities.\n\n- `include_system_ca_certs_pool` (default = false): whether to load the system certificate authorities pool\n  alongside the certificate authority.\n\nAdditionally you can configure TLS to be enabled but skip verifying the server's\ncertificate chain. This cannot be combined with `insecure` since `insecure`\nwon't use TLS at all.\n\n- `insecure_skip_verify` (default = false): whether to skip verifying the\n  certificate or not.\n\nMinimum and maximum TLS version can be set:\n\n__IMPORTANT__: TLS 1.0 and 1.1 are deprecated due to known vulnerabilities and should be avoided.\n\n- `min_version` (default = \"1.2\"): Minimum acceptable TLS version.\n  - options: [\"1.0\", \"1.1\", \"1.2\", \"1.3\"]\n\n- `max_version` (default = \"\" handled by [crypto/tls](https://github.com/golang/go/blob/ed9db1d36ad6ef61095d5941ad9ee6da7ab6d05a/src/crypto/tls/common.go#L700) - currently TLS 1.3): Maximum acceptable TLS version.\n  - options: [\"1.0\", \"1.1\", \"1.2\", \"1.3\"]\n\nExplicit cipher suites can be set. If left blank, a safe default list is used. See https://go.dev/src/crypto/tls/cipher_suites.go for a list of supported cipher suites.\n- `cipher_suites`: (default = []): List of cipher suites to use.\n\nExample:\n```\n  cipher_suites:\n    - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256\n    - TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384\n    - TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256\n```\n\nAdditionally certificates may be reloaded by setting the below configuration.\n\n- `reload_interval` (optional) : ReloadInterval specifies the duration after which the certificate will be reloaded.\n   If not set, it will never be reloaded.\n   Accepts a [duration string](https://pkg.go.dev/time#ParseDuration),\n   valid time units are \"ns\", \"us\" (or \"µs\"), \"ms\", \"s\", \"m\", \"h\".\n\nHow TLS/mTLS is configured depends on whether configuring the client or server.\nSee below for examples.\n\n- `tpm` (optional): Use the trusted platform module to retrieve the TLS key.\n\n## Client Configuration\n\n[Exporters](https://github.com/open-telemetry/opentelemetry-collector/blob/main/exporter/README.md)\nleverage client configuration. The TLS configuration parameters are defined\nunder `tls`, like server configuration.\n\nBeyond TLS configuration, the following setting can optionally be configured:\n\n- `server_name_override`: If set to a non-empty string, it will override the\n  virtual host name of authority (e.g. :authority header field) in requests\n  (typically used for testing).\n\nExample:\n\n```yaml\nexporters:\n  otlp_grpc:\n    endpoint: myserver.local:55690\n    tls:\n      insecure: false\n      ca_file: server.crt\n      cert_file: client.crt\n      key_file: client.key\n      min_version: \"1.1\"\n      max_version: \"1.2\"\n  otlp/insecure:\n    endpoint: myserver.local:55690\n    tls:\n      insecure: true\n  otlp/secure_no_verify:\n    endpoint: myserver.local:55690\n    tls:\n      insecure: false\n      insecure_skip_verify: true\n```\n\n## Server Configuration\n\n[Receivers](https://github.com/open-telemetry/opentelemetry-collector/blob/main/receiver/README.md)\nleverage server configuration.\n\nBeyond TLS configuration, the following setting can optionally be configured\n(required for mTLS):\n\n- `client_ca_file`: Path to the TLS cert to use by the server to verify a\n  client certificate. (optional) This sets the ClientCAs and ClientAuth to\n  RequireAndVerifyClientCert in the TLSConfig. Please refer to\n  https://godoc.org/crypto/tls#Config for more information.\n- `client_ca_file_reload` (default = false): Reload the ClientCAs file when it is modified.\n\nExample:\n\n```yaml\nreceivers:\n  otlp:\n    protocols:\n      grpc:\n        endpoint: mysite.local:55690\n        tls:\n          cert_file: server.crt\n          key_file: server.key\n  otlp/mtls:\n    protocols:\n      grpc:\n        endpoint: mysite.local:55690\n        tls:\n          client_ca_file: client.pem\n          cert_file: server.crt\n          key_file: server.key\n  otlp/notls:\n    protocols:\n      grpc:\n        endpoint: mysite.local:55690\n```\n\n## Trusted platform module (TPM) configuration\n\nThe [trusted platform module](https://trustedcomputinggroup.org/resource/trusted-platform-module-tpm-summary/) (TPM) configuration can be used for loading TLS key from TPM. Currently only TSS2 format is supported.\n\n- `enabled` (default = false): Enables loading `tls.key_file` from TPM.\n\n- `path` (default = \"\"): The path to the TPM device or Unix domain socket. For instance `/dev/tpm0` or `/dev/tpmrm0`. This option is not supported on Windows.\n\n- `owner_auth` (default = \"\"): The owner authorization value. This is used to authenticate the TPM device. If not set, the default owner authorization will be used.\n\n- `auth` (default = \"\"): The authorization value. This is used to authenticate the TPM device. If not set, the default authorization will be used.\n\nExample:\n\n```yaml\nexporters:\n  otlp_grpc:\n    endpoint: myserver.local:55690\n    tls:\n      ca_file: ca.crt\n      cert_file: client.crt\n      key_file: client-tss2.key\n      tpm:\n        enabled: true\n        path: /dev/tpmrm0\n```\n\nThe `client-tss2.key` private key with TSS2 format will be loaded from the TPM device `/dev/tpmrm0`."
  },
  {
    "path": "config/configtls/clientcasfilereloader.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configtls // import \"go.opentelemetry.io/collector/config/configtls\"\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"errors\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"github.com/fsnotify/fsnotify\"\n)\n\ntype clientCAsFileReloader struct {\n\tclientCAsFile   string\n\tcertPool        *x509.CertPool\n\tlastReloadError error\n\tlock            sync.RWMutex\n\tloader          clientCAsFileLoader\n\twatcher         *fsnotify.Watcher\n\tshutdownCH      chan bool\n}\n\ntype clientCAsFileLoader interface {\n\tloadClientCAFile() (*x509.CertPool, error)\n}\n\nfunc newClientCAsReloader(clientCAsFile string, loader clientCAsFileLoader) (*clientCAsFileReloader, error) {\n\tcertPool, err := loader.loadClientCAFile()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load client CA CertPool: %w\", err)\n\t}\n\n\treloader := &clientCAsFileReloader{\n\t\tclientCAsFile: clientCAsFile,\n\t\tcertPool:      certPool,\n\t\tloader:        loader,\n\t\tshutdownCH:    nil,\n\t\twatcher:       nil,\n\t}\n\n\treturn reloader, nil\n}\n\nfunc (r *clientCAsFileReloader) getClientConfig(original *tls.Config) (*tls.Config, error) {\n\tr.lock.RLock()\n\tdefer r.lock.RUnlock()\n\treturn &tls.Config{\n\t\tRootCAs:              original.RootCAs,\n\t\tGetCertificate:       original.GetCertificate,\n\t\tGetClientCertificate: original.GetClientCertificate,\n\t\tMinVersion:           original.MinVersion,\n\t\tMaxVersion:           original.MaxVersion,\n\t\tNextProtos:           original.NextProtos,\n\t\tClientCAs:            r.certPool,\n\t\tClientAuth:           tls.RequireAndVerifyClientCert,\n\t}, nil\n}\n\nfunc (r *clientCAsFileReloader) reload() {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\tcertPool, err := r.loader.loadClientCAFile()\n\tif err != nil {\n\t\tr.lastReloadError = err\n\t} else {\n\t\tr.certPool = certPool\n\t\tr.lastReloadError = nil\n\t}\n}\n\nfunc (r *clientCAsFileReloader) getLastError() error {\n\tr.lock.Lock()\n\tdefer r.lock.Unlock()\n\treturn r.lastReloadError\n}\n\nfunc (r *clientCAsFileReloader) startWatching() error {\n\tif r.shutdownCH != nil {\n\t\treturn errors.New(\"client CA file watcher already started\")\n\t}\n\n\twatcher, err := fsnotify.NewWatcher()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create watcher to reload client CA CertPool: %w\", err)\n\t}\n\tr.watcher = watcher\n\n\terr = watcher.Add(r.clientCAsFile)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to add client CA file to watcher: %w\", err)\n\t}\n\n\tr.shutdownCH = make(chan bool)\n\tgo r.handleWatcherEvents()\n\n\treturn nil\n}\n\nfunc (r *clientCAsFileReloader) handleWatcherEvents() {\n\tdefer r.watcher.Close()\n\tfor {\n\t\tselect {\n\t\tcase _, ok := <-r.shutdownCH:\n\t\t\t_ = ok\n\t\t\treturn\n\t\tcase event, ok := <-r.watcher.Events:\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\t// NOTE: k8s configmaps uses symlinks, we need this workaround.\n\t\t\t// original configmap file is removed.\n\t\t\t// SEE: https://martensson.io/go-fsnotify-and-kubernetes-configmaps/\n\t\t\tif event.Has(fsnotify.Remove) || event.Has(fsnotify.Chmod) {\n\t\t\t\t// remove the watcher since the file is removed\n\t\t\t\tif err := r.watcher.Remove(event.Name); err != nil {\n\t\t\t\t\tr.lastReloadError = err\n\t\t\t\t}\n\t\t\t\t// add a new watcher pointing to the new symlink/file\n\t\t\t\tif err := r.watcher.Add(r.clientCAsFile); err != nil {\n\t\t\t\t\tr.lastReloadError = err\n\t\t\t\t}\n\t\t\t\tr.reload()\n\t\t\t}\n\t\t\tif event.Has(fsnotify.Write) {\n\t\t\t\tr.reload()\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (r *clientCAsFileReloader) shutdown() error {\n\tif r.shutdownCH == nil {\n\t\treturn errors.New(\"client CAs file watcher is not running\")\n\t}\n\tr.shutdownCH <- true\n\tclose(r.shutdownCH)\n\tr.shutdownCH = nil\n\treturn nil\n}\n"
  },
  {
    "path": "config/configtls/clientcasfilereloader_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configtls\n\nimport (\n\t\"crypto/x509\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestCannotShutdownIfNotWatching(t *testing.T) {\n\treloader, _, _ := createReloader(t)\n\terr := reloader.shutdown()\n\tassert.Error(t, err)\n}\n\nfunc TestCannotStartIfAlreadyWatching(t *testing.T) {\n\treloader, _, _ := createReloader(t)\n\n\terr := reloader.startWatching()\n\trequire.NoError(t, err)\n\n\terr = reloader.startWatching()\n\trequire.Error(t, err)\n\n\terr = reloader.shutdown()\n\tassert.NoError(t, err)\n}\n\nfunc TestClosingWatcherDoesntBreakReloader(t *testing.T) {\n\treloader, loader, _ := createReloader(t)\n\n\terr := reloader.startWatching()\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, 1, loader.reloadNumber())\n\n\terr = reloader.watcher.Close()\n\trequire.NoError(t, err)\n\n\terr = reloader.shutdown()\n\tassert.NoError(t, err)\n}\n\nfunc TestErrorRecordedIfFileDeleted(t *testing.T) {\n\treloader, loader, filePath := createReloader(t)\n\n\terr := reloader.startWatching()\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, 1, loader.reloadNumber())\n\n\tloader.returnErrorOnSubsequentCalls(\"test error on reload\")\n\n\terr = os.WriteFile(filePath, []byte(\"some_data\"), 0o600)\n\trequire.NoError(t, err)\n\n\tassert.Eventually(t, func() bool {\n\t\treturn loader.reloadNumber() > 1 && reloader.getLastError() != nil\n\t}, 5*time.Second, 10*time.Millisecond)\n\n\tlastErr := reloader.getLastError()\n\trequire.EqualError(t, lastErr, \"test error on reload\")\n\n\terr = reloader.shutdown()\n\tassert.NoError(t, err)\n}\n\nfunc createReloader(t *testing.T) (*clientCAsFileReloader, *testLoader, string) {\n\ttmpClientCAsFilePath := createTempFile(t)\n\tloader := &testLoader{}\n\treloader, _ := newClientCAsReloader(tmpClientCAsFilePath, loader)\n\treturn reloader, loader, tmpClientCAsFilePath\n}\n\nfunc createTempFile(t *testing.T) string {\n\ttmpCa, err := os.CreateTemp(t.TempDir(), \"clientCAs.crt\")\n\trequire.NoError(t, err)\n\ttmpCaPath, err := filepath.Abs(tmpCa.Name())\n\tassert.NoError(t, err)\n\tassert.NoError(t, tmpCa.Close())\n\treturn tmpCaPath\n}\n\ntype testLoader struct {\n\terr     atomic.Value\n\tcounter atomic.Uint32\n}\n\nfunc (r *testLoader) loadClientCAFile() (*x509.CertPool, error) {\n\tr.counter.Add(1)\n\n\tv := r.err.Load()\n\tif v == nil {\n\t\treturn nil, nil\n\t}\n\n\treturn nil, v.(error)\n}\n\nfunc (r *testLoader) returnErrorOnSubsequentCalls(msg string) {\n\tr.err.Store(fmt.Errorf(\"%s\", msg))\n}\n\nfunc (r *testLoader) reloadNumber() int {\n\treturn int(r.counter.Load())\n}\n"
  },
  {
    "path": "config/configtls/config.schema.yaml",
    "content": "$defs:\n  client_config:\n    description: ClientConfig contains TLS configurations that are specific to client connections in addition to the common configurations. This should be used by components configuring TLS client connections.\n    type: object\n    properties:\n      insecure:\n        description: In gRPC and HTTP when set to true, this is used to disable the client transport security. See https://godoc.org/google.golang.org/grpc#WithInsecure for gRPC. Please refer to https://godoc.org/crypto/tls#Config for more information. (optional, default false)\n        type: boolean\n      insecure_skip_verify:\n        description: InsecureSkipVerify will enable TLS but not verify the certificate.\n        type: boolean\n      server_name_override:\n        description: ServerName requested by client for virtual hosting. This sets the ServerName in the TLSConfig. Please refer to https://godoc.org/crypto/tls#Config for more information. (optional)\n        type: string\n    allOf:\n      - $ref: config\n  config:\n    description: 'Config exposes the common client and server TLS configurations. Note: Since there isn''t anything specific to a server connection. Components with server connections should use Config.'\n    type: object\n    properties:\n      ca_file:\n        description: Path to the CA cert. For a client this verifies the server certificate. For a server this verifies client certificates. If empty uses system root CA. (optional)\n        type: string\n      ca_pem:\n        description: In memory PEM encoded cert. (optional)\n        $ref: /config/configopaque.string\n      cert_file:\n        description: Path to the TLS cert to use for TLS required connections. (optional)\n        type: string\n      cert_pem:\n        description: In memory PEM encoded TLS cert to use for TLS required connections. (optional)\n        $ref: /config/configopaque.string\n      cipher_suites:\n        description: CipherSuites is a list of TLS cipher suites that the TLS transport can use. If left blank, a safe default list is used. See https://go.dev/src/crypto/tls/cipher_suites.go for a list of supported cipher suites.\n        type: array\n        items:\n          type: string\n      curve_preferences:\n        description: contains the elliptic curves that will be used in an ECDHE handshake, in preference order Defaults to empty list and \"crypto/tls\" defaults are used, internally.\n        type: array\n        items:\n          type: string\n      include_system_ca_certs_pool:\n        description: If true, load system CA certificates pool in addition to the certificates configured in this struct.\n        type: boolean\n      key_file:\n        description: Path to the TLS key to use for TLS required connections. (optional)\n        type: string\n      key_pem:\n        description: In memory PEM encoded TLS key to use for TLS required connections. (optional)\n        $ref: /config/configopaque.string\n      max_version:\n        description: MaxVersion sets the maximum TLS version that is acceptable. If not set, refer to crypto/tls for defaults. (optional)\n        type: string\n      min_version:\n        description: MinVersion sets the minimum TLS version that is acceptable. If not set, TLS 1.2 will be used. (optional)\n        type: string\n      reload_interval:\n        description: ReloadInterval specifies the duration after which the certificate will be reloaded If not set, it will never be reloaded (optional)\n        type: string\n        x-customType: time.Duration\n        format: duration\n      tpm:\n        description: Trusted platform module configuration\n        $ref: tpm_config\n  server_config:\n    description: ServerConfig contains TLS configurations that are specific to server connections in addition to the common configurations. This should be used by components configuring TLS server connections.\n    type: object\n    properties:\n      client_ca_file:\n        description: Path to the TLS cert to use by the server to verify a client certificate. (optional) This sets the ClientCAs and ClientAuth to RequireAndVerifyClientCert in the TLSConfig. Please refer to https://godoc.org/crypto/tls#Config for more information. (optional)\n        type: string\n      client_ca_file_reload:\n        description: Reload the ClientCAs file when it is modified (optional, default false)\n        type: boolean\n    allOf:\n      - $ref: config\n  tpm_config:\n    description: TPMConfig defines trusted platform module configuration for storing TLS keys.\n    type: object\n    properties:\n      auth:\n        type: string\n      enabled:\n        type: boolean\n      owner_auth:\n        type: string\n      path:\n        description: The path to the TPM device or Unix domain socket. For instance /dev/tpm0 or /dev/tpmrm0.\n        type: string\n"
  },
  {
    "path": "config/configtls/configtls.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configtls // import \"go.opentelemetry.io/collector/config/configtls\"\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"errors\"\n\t\"fmt\"\n\t\"maps\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"slices\"\n\t\"sync\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n)\n\n// We should avoid that users unknowingly use a vulnerable TLS version.\n// The defaults should be a safe configuration\nconst defaultMinTLSVersion = tls.VersionTLS12\n\n// Uses the default MaxVersion from \"crypto/tls\" which is the maximum supported version\nconst defaultMaxTLSVersion = 0\n\nvar systemCertPool = x509.SystemCertPool\n\n// Config exposes the common client and server TLS configurations.\n// Note: Since there isn't anything specific to a server connection. Components\n// with server connections should use Config.\ntype Config struct {\n\t// Path to the CA cert. For a client this verifies the server certificate.\n\t// For a server this verifies client certificates. If empty uses system root CA.\n\t// (optional)\n\tCAFile string `mapstructure:\"ca_file,omitempty\"`\n\n\t// In memory PEM encoded cert. (optional)\n\tCAPem configopaque.String `mapstructure:\"ca_pem,omitempty\"`\n\n\t// If true, load system CA certificates pool in addition to the certificates\n\t// configured in this struct.\n\tIncludeSystemCACertsPool bool `mapstructure:\"include_system_ca_certs_pool,omitempty\"`\n\n\t// Path to the TLS cert to use for TLS required connections. (optional)\n\tCertFile string `mapstructure:\"cert_file,omitempty\"`\n\n\t// In memory PEM encoded TLS cert to use for TLS required connections. (optional)\n\tCertPem configopaque.String `mapstructure:\"cert_pem,omitempty\"`\n\n\t// Path to the TLS key to use for TLS required connections. (optional)\n\tKeyFile string `mapstructure:\"key_file,omitempty\"`\n\n\t// In memory PEM encoded TLS key to use for TLS required connections. (optional)\n\tKeyPem configopaque.String `mapstructure:\"key_pem,omitempty\"`\n\n\t// MinVersion sets the minimum TLS version that is acceptable.\n\t// If not set, TLS 1.2 will be used. (optional)\n\tMinVersion string `mapstructure:\"min_version,omitempty\"`\n\n\t// MaxVersion sets the maximum TLS version that is acceptable.\n\t// If not set, refer to crypto/tls for defaults. (optional)\n\tMaxVersion string `mapstructure:\"max_version,omitempty\"`\n\n\t// CipherSuites is a list of TLS cipher suites that the TLS transport can use.\n\t// If left blank, a safe default list is used.\n\t// See https://go.dev/src/crypto/tls/cipher_suites.go for a list of supported cipher suites.\n\tCipherSuites []string `mapstructure:\"cipher_suites,omitempty\"`\n\n\t// ReloadInterval specifies the duration after which the certificate will be reloaded\n\t// If not set, it will never be reloaded (optional)\n\tReloadInterval time.Duration `mapstructure:\"reload_interval,omitempty\"`\n\n\t// contains the elliptic curves that will be used in\n\t// an ECDHE handshake, in preference order\n\t// Defaults to empty list and \"crypto/tls\" defaults are used, internally.\n\tCurvePreferences []string `mapstructure:\"curve_preferences,omitempty\"`\n\n\t// Trusted platform module configuration\n\tTPMConfig TPMConfig `mapstructure:\"tpm,omitempty\"`\n}\n\n// NewDefaultConfig creates a new Config with any default values set.\nfunc NewDefaultConfig() Config {\n\treturn Config{}\n}\n\n// ClientConfig contains TLS configurations that are specific to client\n// connections in addition to the common configurations. This should be used by\n// components configuring TLS client connections.\ntype ClientConfig struct {\n\t// squash ensures fields are correctly decoded in embedded struct.\n\tConfig `mapstructure:\",squash\"`\n\n\t// These are config options specific to client connections.\n\n\t// In gRPC and HTTP when set to true, this is used to disable the client transport security.\n\t// See https://godoc.org/google.golang.org/grpc#WithInsecure for gRPC.\n\t// Please refer to https://godoc.org/crypto/tls#Config for more information.\n\t// (optional, default false)\n\tInsecure bool `mapstructure:\"insecure,omitempty\"`\n\t// InsecureSkipVerify will enable TLS but not verify the certificate.\n\tInsecureSkipVerify bool `mapstructure:\"insecure_skip_verify,omitempty\"`\n\t// ServerName requested by client for virtual hosting.\n\t// This sets the ServerName in the TLSConfig. Please refer to\n\t// https://godoc.org/crypto/tls#Config for more information. (optional)\n\tServerName string `mapstructure:\"server_name_override,omitempty\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// NewDefaultClientConfig creates a new ClientConfig with any default values set.\nfunc NewDefaultClientConfig() ClientConfig {\n\treturn ClientConfig{\n\t\tConfig: NewDefaultConfig(),\n\t}\n}\n\n// ServerConfig contains TLS configurations that are specific to server\n// connections in addition to the common configurations. This should be used by\n// components configuring TLS server connections.\ntype ServerConfig struct {\n\t// squash ensures fields are correctly decoded in embedded struct.\n\tConfig `mapstructure:\",squash\"`\n\n\t// These are config options specific to server connections.\n\n\t// Path to the TLS cert to use by the server to verify a client certificate. (optional)\n\t// This sets the ClientCAs and ClientAuth to RequireAndVerifyClientCert in the TLSConfig. Please refer to\n\t// https://godoc.org/crypto/tls#Config for more information. (optional)\n\tClientCAFile string `mapstructure:\"client_ca_file,omitempty\"`\n\n\t// Reload the ClientCAs file when it is modified\n\t// (optional, default false)\n\tReloadClientCAFile bool `mapstructure:\"client_ca_file_reload,omitempty\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// NewDefaultServerConfig creates a new ServerConfig with any default values set.\nfunc NewDefaultServerConfig() ServerConfig {\n\treturn ServerConfig{\n\t\tConfig: NewDefaultConfig(),\n\t}\n}\n\n// certReloader is a wrapper object for certificate reloading\n// Its GetCertificate method will either return the current certificate or reload from disk\n// if the last reload happened more than ReloadInterval ago\ntype certReloader struct {\n\tnextReload time.Time\n\tcert       *tls.Certificate\n\tlock       sync.RWMutex\n\ttls        Config\n}\n\nfunc (c Config) newCertReloader() (*certReloader, error) {\n\tcert, err := c.loadCertificate()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &certReloader{\n\t\ttls:        c,\n\t\tnextReload: time.Now().Add(c.ReloadInterval),\n\t\tcert:       &cert,\n\t}, nil\n}\n\nfunc (r *certReloader) GetCertificate() (*tls.Certificate, error) {\n\tnow := time.Now()\n\t// Read locking here before we do the time comparison\n\t// If a reload is in progress this will block and we will skip reloading in the current\n\t// call once we can continue\n\tr.lock.RLock()\n\tif r.tls.ReloadInterval != 0 && r.nextReload.Before(now) && (r.tls.hasCertFile() || r.tls.hasKeyFile()) {\n\t\t// Need to release the read lock, otherwise we deadlock\n\t\tr.lock.RUnlock()\n\t\tr.lock.Lock()\n\t\tdefer r.lock.Unlock()\n\t\tcert, err := r.tls.loadCertificate()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to load TLS cert and key: %w\", err)\n\t\t}\n\t\tr.cert = &cert\n\t\tr.nextReload = now.Add(r.tls.ReloadInterval)\n\t\treturn r.cert, nil\n\t}\n\tdefer r.lock.RUnlock()\n\treturn r.cert, nil\n}\n\nfunc (c Config) Validate() error {\n\tif c.hasCAFile() && c.hasCAPem() {\n\t\treturn errors.New(\"provide either a CA file or the PEM-encoded string, but not both\")\n\t}\n\n\t// Ensure certificate is not set using both file and PEM\n\tif c.hasCertFile() && c.hasCertPem() {\n\t\treturn errors.New(\"provide either certificate file or PEM, but not both\")\n\t}\n\n\t// Ensure key is not set using both file and PEM\n\tif c.hasKeyFile() && c.hasKeyPem() {\n\t\treturn errors.New(\"provide either key file or PEM, but not both\")\n\t}\n\n\t// Fail if only one of cert/key is provided (mismatch case)\n\tif c.hasCert() != c.hasKey() {\n\t\treturn errors.New(\"TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)\")\n\t}\n\n\tminTLS, err := convertVersion(c.MinVersion, defaultMinTLSVersion)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid TLS min_version: %w\", err)\n\t}\n\n\tmaxTLS, err := convertVersion(c.MaxVersion, defaultMaxTLSVersion)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid TLS max_version: %w\", err)\n\t}\n\n\tif maxTLS < minTLS && maxTLS != defaultMaxTLSVersion {\n\t\treturn errors.New(\"invalid TLS configuration: min_version cannot be greater than max_version\")\n\t}\n\n\treturn nil\n}\n\nfunc (c ServerConfig) Validate() error {\n\t// For servers, both certificate and key are required:\n\t// - If both are missing, error.\n\t// - If only one is provided (mismatch), error.\n\tif !c.hasCert() && !c.hasKey() {\n\t\treturn errors.New(\"TLS configuration must include both certificate and key for server connections\")\n\t}\n\treturn nil\n}\n\n// loadTLSConfig loads TLS certificates and returns a tls.Config.\n// This will set the RootCAs and Certificates of a tls.Config.\nfunc (c Config) loadTLSConfig() (*tls.Config, error) {\n\tcertPool, err := c.loadCACertPool()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvar getCertificate func(*tls.ClientHelloInfo) (*tls.Certificate, error)\n\tvar getClientCertificate func(*tls.CertificateRequestInfo) (*tls.Certificate, error)\n\tif c.hasCert() || c.hasKey() {\n\t\tvar certReloader *certReloader\n\t\tcertReloader, err = c.newCertReloader()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to load TLS cert and key: %w\", err)\n\t\t}\n\t\tgetCertificate = func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return certReloader.GetCertificate() }\n\t\tgetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { return certReloader.GetCertificate() }\n\t}\n\n\tminTLS, err := convertVersion(c.MinVersion, defaultMinTLSVersion)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid TLS min_version: %w\", err)\n\t}\n\tmaxTLS, err := convertVersion(c.MaxVersion, defaultMaxTLSVersion)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid TLS max_version: %w\", err)\n\t}\n\tcipherSuites, err := convertCipherSuites(c.CipherSuites)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tallowedCurves := slices.Collect(maps.Values(tlsCurveTypes))\n\tcurvePreferences := make([]tls.CurveID, 0, len(c.CurvePreferences))\n\tfor _, curve := range c.CurvePreferences {\n\t\tcurveID, ok := tlsCurveTypes[curve]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"invalid curve type: %s. Expected values are %s\", curveID, allowedCurves)\n\t\t}\n\t\tcurvePreferences = append(curvePreferences, curveID)\n\t}\n\n\t// If no curve preferences were explicitly specified in the configuration, use\n\t// the ones we allow. This helps in particular with FIPS builds where not all curves\n\t// are allowed.\n\tif len(curvePreferences) == 0 {\n\t\tcurvePreferences = allowedCurves\n\t}\n\n\treturn &tls.Config{\n\t\tRootCAs:              certPool,\n\t\tGetCertificate:       getCertificate,\n\t\tGetClientCertificate: getClientCertificate,\n\t\tMinVersion:           minTLS,\n\t\tMaxVersion:           maxTLS,\n\t\tCipherSuites:         cipherSuites,\n\t\tCurvePreferences:     curvePreferences,\n\t}, nil\n}\n\nfunc convertCipherSuites(cipherSuites []string) ([]uint16, error) {\n\tvar result []uint16\n\tvar errs []error\n\tfor _, suite := range cipherSuites {\n\t\tfound := false\n\t\tfor _, supported := range tls.CipherSuites() {\n\t\t\tif suite == supported.Name {\n\t\t\t\tresult = append(result, supported.ID)\n\t\t\t\tfound = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !found {\n\t\t\terrs = append(errs, fmt.Errorf(\"invalid TLS cipher suite: %q\", suite))\n\t\t}\n\t}\n\treturn result, errors.Join(errs...)\n}\n\nfunc (c Config) loadCACertPool() (*x509.CertPool, error) {\n\t// There is no need to load the System Certs for RootCAs because\n\t// if the value is nil, it will default to checking against th System Certs.\n\tvar err error\n\tvar certPool *x509.CertPool\n\n\tswitch {\n\tcase c.hasCAFile() && c.hasCAPem():\n\t\treturn nil, errors.New(\"failed to load CA CertPool: provide either a CA file or the PEM-encoded string, but not both\")\n\tcase c.hasCAFile():\n\t\t// Set up user specified truststore from file\n\t\tcertPool, err = c.loadCertFile(c.CAFile)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to load CA CertPool File: %w\", err)\n\t\t}\n\tcase c.hasCAPem():\n\t\t// Set up user specified truststore from PEM\n\t\tcertPool, err = c.loadCertPem([]byte(c.CAPem))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to load CA CertPool PEM: %w\", err)\n\t\t}\n\t}\n\n\treturn certPool, nil\n}\n\nfunc (c Config) loadCertFile(certPath string) (*x509.CertPool, error) {\n\tcertPem, err := os.ReadFile(filepath.Clean(certPath))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load cert %s: %w\", certPath, err)\n\t}\n\n\treturn c.loadCertPem(certPem)\n}\n\nfunc (c Config) loadCertPem(certPem []byte) (*x509.CertPool, error) {\n\tcertPool := x509.NewCertPool()\n\tif c.IncludeSystemCACertsPool {\n\t\tscp, err := systemCertPool()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif scp != nil {\n\t\t\tcertPool = scp\n\t\t}\n\t}\n\tif !certPool.AppendCertsFromPEM(certPem) {\n\t\treturn nil, errors.New(\"failed to parse cert\")\n\t}\n\treturn certPool, nil\n}\n\nfunc (c Config) loadCertificate() (tls.Certificate, error) {\n\tswitch {\n\tcase c.hasCert() != c.hasKey():\n\t\treturn tls.Certificate{}, errors.New(\"for auth via TLS, provide both certificate and key, or neither\")\n\tcase !c.hasCert() && !c.hasKey():\n\t\treturn tls.Certificate{}, nil\n\tcase c.hasCertFile() && c.hasCertPem():\n\t\treturn tls.Certificate{}, errors.New(\"for auth via TLS, provide either a certificate or the PEM-encoded string, but not both\")\n\tcase c.hasKeyFile() && c.hasKeyPem():\n\t\treturn tls.Certificate{}, errors.New(\"for auth via TLS, provide either a key or the PEM-encoded string, but not both\")\n\t}\n\n\tvar certPem, keyPem []byte\n\tvar err error\n\tif c.hasCertFile() {\n\t\tcertPem, err = os.ReadFile(c.CertFile)\n\t\tif err != nil {\n\t\t\treturn tls.Certificate{}, err\n\t\t}\n\t} else {\n\t\tcertPem = []byte(c.CertPem)\n\t}\n\n\tif c.hasKeyFile() {\n\t\tkeyPem, err = os.ReadFile(c.KeyFile)\n\t\tif err != nil {\n\t\t\treturn tls.Certificate{}, err\n\t\t}\n\t} else {\n\t\tkeyPem = []byte(c.KeyPem)\n\t}\n\n\tif c.TPMConfig.Enabled {\n\t\tcertificate, errTPM := c.TPMConfig.tpmCertificate(keyPem, certPem, openTPM(c.TPMConfig.Path))\n\t\tif errTPM != nil {\n\t\t\treturn tls.Certificate{}, fmt.Errorf(\"failed to load private key from TPM: %w\", errTPM)\n\t\t}\n\t\treturn certificate, nil\n\t}\n\n\tcertificate, errKeyPair := tls.X509KeyPair(certPem, keyPem)\n\tif errKeyPair != nil {\n\t\treturn tls.Certificate{}, fmt.Errorf(\"failed to load TLS cert and key PEMs: %w\", errKeyPair)\n\t}\n\treturn certificate, err\n}\n\nfunc (c Config) loadCert(caPath string) (*x509.CertPool, error) {\n\tcaPEM, err := os.ReadFile(filepath.Clean(caPath))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load CA %s: %w\", caPath, err)\n\t}\n\n\tvar certPool *x509.CertPool\n\tif c.IncludeSystemCACertsPool {\n\t\tif certPool, err = systemCertPool(); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\tif certPool == nil {\n\t\tcertPool = x509.NewCertPool()\n\t}\n\tif !certPool.AppendCertsFromPEM(caPEM) {\n\t\treturn nil, fmt.Errorf(\"failed to parse CA %s\", caPath)\n\t}\n\treturn certPool, nil\n}\n\n// LoadTLSConfig loads the TLS configuration.\nfunc (c ClientConfig) LoadTLSConfig(_ context.Context) (*tls.Config, error) {\n\tif c.Insecure && !c.hasCA() {\n\t\treturn nil, nil\n\t}\n\n\ttlsCfg, err := c.loadTLSConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load TLS config: %w\", err)\n\t}\n\ttlsCfg.ServerName = c.ServerName\n\ttlsCfg.InsecureSkipVerify = c.InsecureSkipVerify\n\treturn tlsCfg, nil\n}\n\n// LoadTLSConfig loads the TLS configuration.\nfunc (c ServerConfig) LoadTLSConfig(_ context.Context) (*tls.Config, error) {\n\ttlsCfg, err := c.loadTLSConfig()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to load TLS config: %w\", err)\n\t}\n\tif c.ClientCAFile != \"\" {\n\t\treloader, err := newClientCAsReloader(c.ClientCAFile, &c)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif c.ReloadClientCAFile {\n\t\t\terr = reloader.startWatching()\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\ttlsCfg.GetConfigForClient = func(*tls.ClientHelloInfo) (*tls.Config, error) { return reloader.getClientConfig(tlsCfg) }\n\t\t}\n\t\ttlsCfg.ClientCAs = reloader.certPool\n\t\ttlsCfg.ClientAuth = tls.RequireAndVerifyClientCert\n\t}\n\treturn tlsCfg, nil\n}\n\nfunc (c ServerConfig) loadClientCAFile() (*x509.CertPool, error) {\n\treturn c.loadCert(c.ClientCAFile)\n}\n\nfunc (c Config) hasCA() bool   { return c.hasCAFile() || c.hasCAPem() }\nfunc (c Config) hasCert() bool { return c.hasCertFile() || c.hasCertPem() }\nfunc (c Config) hasKey() bool  { return c.hasKeyFile() || c.hasKeyPem() }\n\nfunc (c Config) hasCAFile() bool { return c.CAFile != \"\" }\nfunc (c Config) hasCAPem() bool  { return len(c.CAPem) != 0 }\n\nfunc (c Config) hasCertFile() bool { return c.CertFile != \"\" }\nfunc (c Config) hasCertPem() bool  { return len(c.CertPem) != 0 }\n\nfunc (c Config) hasKeyFile() bool { return c.KeyFile != \"\" }\nfunc (c Config) hasKeyPem() bool  { return len(c.KeyPem) != 0 }\n\nfunc convertVersion(v string, defaultVersion uint16) (uint16, error) {\n\t// Use a default that is explicitly defined\n\tif v == \"\" {\n\t\treturn defaultVersion, nil\n\t}\n\tval, ok := tlsVersions[v]\n\tif !ok {\n\t\treturn 0, fmt.Errorf(\"unsupported TLS version: %q\", v)\n\t}\n\treturn val, nil\n}\n\nvar tlsVersions = map[string]uint16{\n\t\"1.0\": tls.VersionTLS10,\n\t\"1.1\": tls.VersionTLS11,\n\t\"1.2\": tls.VersionTLS12,\n\t\"1.3\": tls.VersionTLS13,\n}\n"
  },
  {
    "path": "config/configtls/configtls_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configtls\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n)\n\nfunc TestNewDefaultConfig(t *testing.T) {\n\texpectedConfig := Config{}\n\tconfig := NewDefaultConfig()\n\trequire.Equal(t, expectedConfig, config)\n}\n\nfunc TestNewDefaultClientConfig(t *testing.T) {\n\texpectedConfig := ClientConfig{\n\t\tConfig: NewDefaultConfig(),\n\t}\n\tconfig := NewDefaultClientConfig()\n\trequire.Equal(t, expectedConfig, config)\n}\n\nfunc TestNewDefaultServerConfig(t *testing.T) {\n\texpectedConfig := ServerConfig{\n\t\tConfig: NewDefaultConfig(),\n\t}\n\tconfig := NewDefaultServerConfig()\n\trequire.Equal(t, expectedConfig, config)\n}\n\nfunc TestOptionsToConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\toptions     Config\n\t\texpectError string\n\t}{\n\t\t{\n\t\t\tname:    \"should load system CA\",\n\t\t\toptions: Config{CAFile: \"\"},\n\t\t},\n\t\t{\n\t\t\tname:    \"should load custom CA\",\n\t\t\toptions: Config{CAFile: filepath.Join(\"testdata\", \"ca-1.crt\")},\n\t\t},\n\t\t{\n\t\t\tname:    \"should load system CA and custom CA\",\n\t\t\toptions: Config{IncludeSystemCACertsPool: true, CAFile: filepath.Join(\"testdata\", \"ca-1.crt\")},\n\t\t},\n\t\t{\n\t\t\tname:        \"should fail with invalid CA file path\",\n\t\t\toptions:     Config{CAFile: filepath.Join(\"testdata\", \"not/valid\")},\n\t\t\texpectError: \"failed to load CA\",\n\t\t},\n\t\t{\n\t\t\tname:        \"should fail with invalid CA file content\",\n\t\t\toptions:     Config{CAFile: filepath.Join(\"testdata\", \"testCA-bad.txt\")},\n\t\t\texpectError: \"failed to parse cert\",\n\t\t},\n\t\t{\n\t\t\tname: \"should load valid TLS  settings\",\n\t\t\toptions: Config{\n\t\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca-1.crt\"),\n\t\t\t\tCertFile: filepath.Join(\"testdata\", \"server-1.crt\"),\n\t\t\t\tKeyFile:  filepath.Join(\"testdata\", \"server-1.key\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"should fail with missing TLS KeyFile\",\n\t\t\toptions: Config{\n\t\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca-1.crt\"),\n\t\t\t\tCertFile: filepath.Join(\"testdata\", \"server-1.crt\"),\n\t\t\t},\n\t\t\texpectError: \"provide both certificate and key, or neither\",\n\t\t},\n\t\t{\n\t\t\tname: \"should fail with invalid TLS KeyFile\",\n\t\t\toptions: Config{\n\t\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca-1.crt\"),\n\t\t\t\tCertFile: filepath.Join(\"testdata\", \"server-1.crt\"),\n\t\t\t\tKeyFile:  filepath.Join(\"testdata\", \"not/valid\"),\n\t\t\t},\n\t\t\texpectError: \"failed to load TLS cert and key\",\n\t\t},\n\t\t{\n\t\t\tname: \"should fail with missing TLS Cert\",\n\t\t\toptions: Config{\n\t\t\t\tCAFile:  filepath.Join(\"testdata\", \"ca-1.crt\"),\n\t\t\t\tKeyFile: filepath.Join(\"testdata\", \"server-1.key\"),\n\t\t\t},\n\t\t\texpectError: \"provide both certificate and key, or neither\",\n\t\t},\n\t\t{\n\t\t\tname: \"should fail with invalid TLS Cert\",\n\t\t\toptions: Config{\n\t\t\t\tCAFile:   filepath.Join(\"testdata\", \"ca-1.crt\"),\n\t\t\t\tCertFile: filepath.Join(\"testdata\", \"not/valid\"),\n\t\t\t\tKeyFile:  filepath.Join(\"testdata\", \"server-1.key\"),\n\t\t\t},\n\t\t\texpectError: \"failed to load TLS cert and key\",\n\t\t},\n\t\t{\n\t\t\tname: \"should fail with invalid TLS CA\",\n\t\t\toptions: Config{\n\t\t\t\tCAFile: filepath.Join(\"testdata\", \"not/valid\"),\n\t\t\t},\n\t\t\texpectError: \"failed to load CA\",\n\t\t},\n\t\t{\n\t\t\tname: \"should fail with invalid CA pool\",\n\t\t\toptions: Config{\n\t\t\t\tCAFile: filepath.Join(\"testdata\", \"testCA-bad.txt\"),\n\t\t\t},\n\t\t\texpectError: \"failed to parse cert\",\n\t\t},\n\t\t{\n\t\t\tname: \"should pass with valid CA pool\",\n\t\t\toptions: Config{\n\t\t\t\tCAFile: filepath.Join(\"testdata\", \"ca-1.crt\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"should pass with valid min and max version\",\n\t\t\toptions: Config{\n\t\t\t\tMinVersion: \"1.1\",\n\t\t\t\tMaxVersion: \"1.2\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"should pass with invalid min\",\n\t\t\toptions: Config{\n\t\t\t\tMinVersion: \"1.7\",\n\t\t\t},\n\t\t\texpectError: \"invalid TLS min_\",\n\t\t},\n\t\t{\n\t\t\tname: \"should pass with invalid max\",\n\t\t\toptions: Config{\n\t\t\t\tMaxVersion: \"1.7\",\n\t\t\t},\n\t\t\texpectError: \"invalid TLS max_\",\n\t\t},\n\t\t{\n\t\t\tname:    \"should load custom CA PEM\",\n\t\t\toptions: Config{CAPem: readFilePanics(\"testdata/ca-1.crt\")},\n\t\t},\n\t\t{\n\t\t\tname: \"should load valid TLS settings with PEMs\",\n\t\t\toptions: Config{\n\t\t\t\tCAPem:   readFilePanics(\"testdata/ca-1.crt\"),\n\t\t\t\tCertPem: readFilePanics(\"testdata/server-1.crt\"),\n\t\t\t\tKeyPem:  readFilePanics(\"testdata/server-1.key\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"mix Cert file and Key PEM provided\",\n\t\t\toptions: Config{\n\t\t\t\tCertFile: \"testdata/server-1.crt\",\n\t\t\t\tKeyPem:   readFilePanics(\"testdata/server-1.key\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"mix Cert PEM and Key File provided\",\n\t\t\toptions: Config{\n\t\t\t\tCertPem: readFilePanics(\"testdata/server-1.crt\"),\n\t\t\t\tKeyFile: \"testdata/server-1.key\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:        \"should fail with invalid CA PEM\",\n\t\t\toptions:     Config{CAPem: readFilePanics(\"testdata/testCA-bad.txt\")},\n\t\t\texpectError: \"failed to parse cert\",\n\t\t},\n\t\t{\n\t\t\tname: \"should fail CA file and PEM both provided\",\n\t\t\toptions: Config{\n\t\t\t\tCAFile: \"testdata/ca-1.crt\",\n\t\t\t\tCAPem:  readFilePanics(\"testdata/ca-1.crt\"),\n\t\t\t},\n\t\t\texpectError: \"provide either a CA file or the PEM-encoded string, but not both\",\n\t\t},\n\t\t{\n\t\t\tname: \"should fail Cert file and PEM both provided\",\n\t\t\toptions: Config{\n\t\t\t\tCertFile: \"testdata/server-1.crt\",\n\t\t\t\tCertPem:  readFilePanics(\"testdata/server-1.crt\"),\n\t\t\t\tKeyFile:  \"testdata/server-1.key\",\n\t\t\t},\n\t\t\texpectError: \"provide either a certificate or the PEM-encoded string, but not both\",\n\t\t},\n\t\t{\n\t\t\tname: \"should fail Key file and PEM both provided\",\n\t\t\toptions: Config{\n\t\t\t\tCertFile: \"testdata/server-1.crt\",\n\t\t\t\tKeyFile:  \"testdata/ca-1.crt\",\n\t\t\t\tKeyPem:   readFilePanics(\"testdata/server-1.key\"),\n\t\t\t},\n\t\t\texpectError: \"provide either a key or the PEM-encoded string, but not both\",\n\t\t},\n\t\t{\n\t\t\tname: \"should fail to load valid TLS settings with bad Cert PEM\",\n\t\t\toptions: Config{\n\t\t\t\tCAPem:   readFilePanics(\"testdata/ca-1.crt\"),\n\t\t\t\tCertPem: readFilePanics(\"testdata/testCA-bad.txt\"),\n\t\t\t\tKeyPem:  readFilePanics(\"testdata/server-1.key\"),\n\t\t\t},\n\t\t\texpectError: \"failed to load TLS cert and key PEMs\",\n\t\t},\n\t\t{\n\t\t\tname: \"should fail to load valid TLS settings with bad Key PEM\",\n\t\t\toptions: Config{\n\t\t\t\tCAPem:   readFilePanics(\"testdata/ca-1.crt\"),\n\t\t\t\tCertPem: readFilePanics(\"testdata/server-1.crt\"),\n\t\t\t\tKeyPem:  readFilePanics(\"testdata/testCA-bad.txt\"),\n\t\t\t},\n\t\t\texpectError: \"failed to load TLS cert and key PEMs\",\n\t\t},\n\t\t{\n\t\t\tname: \"should fail with missing TLS KeyPem\",\n\t\t\toptions: Config{\n\t\t\t\tCAPem:   readFilePanics(\"testdata/ca-1.crt\"),\n\t\t\t\tCertPem: readFilePanics(\"testdata/server-1.crt\"),\n\t\t\t},\n\t\t\texpectError: \"provide both certificate and key, or neither\",\n\t\t},\n\t\t{\n\t\t\tname: \"should fail with missing TLS Cert PEM\",\n\t\t\toptions: Config{\n\t\t\t\tCAPem:  readFilePanics(\"testdata/ca-1.crt\"),\n\t\t\t\tKeyPem: readFilePanics(\"testdata/server-1.key\"),\n\t\t\t},\n\t\t\texpectError: \"provide both certificate and key, or neither\",\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tcfg, err := test.options.loadTLSConfig()\n\t\t\tif test.expectError != \"\" {\n\t\t\t\tassert.ErrorContains(t, err, test.expectError)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.NotNil(t, cfg)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc readFilePanics(filePath string) configopaque.String {\n\tfileContents, err := os.ReadFile(filepath.Clean(filePath))\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"failed to read file %s: %v\", filePath, err))\n\t}\n\n\treturn configopaque.String(fileContents)\n}\n\nfunc TestLoadTLSClientConfigError(t *testing.T) {\n\ttlsSetting := ClientConfig{\n\t\tConfig: Config{\n\t\t\tCertFile: \"doesnt/exist\",\n\t\t\tKeyFile:  \"doesnt/exist\",\n\t\t},\n\t}\n\t_, err := tlsSetting.LoadTLSConfig(context.Background())\n\tassert.Error(t, err)\n}\n\nfunc TestLoadTLSClientConfig(t *testing.T) {\n\ttlsSetting := ClientConfig{\n\t\tInsecure: true,\n\t}\n\ttlsCfg, err := tlsSetting.LoadTLSConfig(context.Background())\n\trequire.NoError(t, err)\n\tassert.Nil(t, tlsCfg)\n\n\ttlsSetting = ClientConfig{}\n\ttlsCfg, err = tlsSetting.LoadTLSConfig(context.Background())\n\trequire.NoError(t, err)\n\tassert.NotNil(t, tlsCfg)\n\n\ttlsSetting = ClientConfig{\n\t\tInsecureSkipVerify: true,\n\t}\n\ttlsCfg, err = tlsSetting.LoadTLSConfig(context.Background())\n\trequire.NoError(t, err)\n\tassert.NotNil(t, tlsCfg)\n\tassert.True(t, tlsCfg.InsecureSkipVerify)\n}\n\nfunc TestLoadTLSServerConfigError(t *testing.T) {\n\ttlsSetting := ServerConfig{\n\t\tConfig: Config{\n\t\t\tCertFile: \"doesnt/exist\",\n\t\t\tKeyFile:  \"doesnt/exist\",\n\t\t},\n\t}\n\t_, err := tlsSetting.LoadTLSConfig(context.Background())\n\trequire.Error(t, err)\n\n\ttlsSetting = ServerConfig{\n\t\tClientCAFile: \"doesnt/exist\",\n\t}\n\t_, err = tlsSetting.LoadTLSConfig(context.Background())\n\tassert.Error(t, err)\n}\n\nfunc TestLoadTLSServerConfig(t *testing.T) {\n\ttlsSetting := ServerConfig{}\n\ttlsCfg, err := tlsSetting.LoadTLSConfig(context.Background())\n\trequire.NoError(t, err)\n\tassert.NotNil(t, tlsCfg)\n}\n\nfunc TestLoadTLSServerConfigReload(t *testing.T) {\n\ttmpCaPath := createTempClientCaFile(t)\n\n\toverwriteClientCA(t, tmpCaPath, \"ca-1.crt\")\n\n\ttlsSetting := ServerConfig{\n\t\tClientCAFile:       tmpCaPath,\n\t\tReloadClientCAFile: true,\n\t}\n\n\ttlsCfg, err := tlsSetting.LoadTLSConfig(context.Background())\n\trequire.NoError(t, err)\n\tassert.NotNil(t, tlsCfg)\n\n\tfirstClient, err := tlsCfg.GetConfigForClient(nil)\n\trequire.NoError(t, err)\n\n\toverwriteClientCA(t, tmpCaPath, \"ca-2.crt\")\n\n\tassert.EventuallyWithT(t, func(t *assert.CollectT) {\n\t\tsecondClient, err := tlsCfg.GetConfigForClient(nil)\n\t\trequire.NoError(t, err)\n\t\tassert.NotEqual(t, firstClient.ClientCAs, secondClient.ClientCAs)\n\t}, 5*time.Second, 10*time.Millisecond)\n}\n\nfunc TestLoadTLSServerConfigFailingReload(t *testing.T) {\n\ttmpCaPath := createTempClientCaFile(t)\n\n\toverwriteClientCA(t, tmpCaPath, \"ca-1.crt\")\n\n\ttlsSetting := ServerConfig{\n\t\tClientCAFile:       tmpCaPath,\n\t\tReloadClientCAFile: true,\n\t}\n\n\ttlsCfg, err := tlsSetting.LoadTLSConfig(context.Background())\n\trequire.NoError(t, err)\n\tassert.NotNil(t, tlsCfg)\n\n\tfirstClient, err := tlsCfg.GetConfigForClient(nil)\n\trequire.NoError(t, err)\n\n\toverwriteClientCA(t, tmpCaPath, \"testCA-bad.txt\")\n\n\tassert.Eventually(t, func() bool {\n\t\t_, loadError := tlsCfg.GetConfigForClient(nil)\n\t\treturn loadError == nil\n\t}, 5*time.Second, 10*time.Millisecond)\n\n\tsecondClient, err := tlsCfg.GetConfigForClient(nil)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, firstClient.ClientCAs, secondClient.ClientCAs)\n}\n\nfunc TestLoadTLSServerConfigFailingInitialLoad(t *testing.T) {\n\ttmpCaPath := createTempClientCaFile(t)\n\n\toverwriteClientCA(t, tmpCaPath, \"testCA-bad.txt\")\n\n\ttlsSetting := ServerConfig{\n\t\tClientCAFile:       tmpCaPath,\n\t\tReloadClientCAFile: true,\n\t}\n\n\ttlsCfg, err := tlsSetting.LoadTLSConfig(context.Background())\n\trequire.Error(t, err)\n\tassert.Nil(t, tlsCfg)\n}\n\nfunc TestLoadTLSServerConfigWrongPath(t *testing.T) {\n\ttmpCaPath := createTempClientCaFile(t)\n\n\ttlsSetting := ServerConfig{\n\t\tClientCAFile:       tmpCaPath + \"wrong-path\",\n\t\tReloadClientCAFile: true,\n\t}\n\n\ttlsCfg, err := tlsSetting.LoadTLSConfig(context.Background())\n\trequire.Error(t, err)\n\tassert.Nil(t, tlsCfg)\n}\n\nfunc TestLoadTLSServerConfigFailing(t *testing.T) {\n\ttmpCaPath := createTempClientCaFile(t)\n\n\toverwriteClientCA(t, tmpCaPath, \"ca-1.crt\")\n\n\ttlsSetting := ServerConfig{\n\t\tClientCAFile:       tmpCaPath,\n\t\tReloadClientCAFile: true,\n\t}\n\n\ttlsCfg, err := tlsSetting.LoadTLSConfig(context.Background())\n\trequire.NoError(t, err)\n\tassert.NotNil(t, tlsCfg)\n\n\tfirstClient, err := tlsCfg.GetConfigForClient(nil)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, firstClient)\n\n\terr = os.Remove(tmpCaPath)\n\trequire.NoError(t, err)\n\n\tfirstClient, err = tlsCfg.GetConfigForClient(nil)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, firstClient)\n}\n\nfunc overwriteClientCA(t *testing.T, targetFilePath, testdataFileName string) {\n\ttargetFile, err := os.OpenFile(filepath.Clean(targetFilePath), os.O_RDWR, 0o600)\n\trequire.NoError(t, err)\n\n\ttestdataFilePath := filepath.Join(\"testdata\", testdataFileName)\n\ttestdataFile, err := os.OpenFile(filepath.Clean(testdataFilePath), os.O_RDONLY, 0o200)\n\trequire.NoError(t, err)\n\n\t_, err = io.Copy(targetFile, testdataFile)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, targetFile.Close())\n\tassert.NoError(t, testdataFile.Close())\n}\n\nfunc createTempClientCaFile(t *testing.T) string {\n\ttmpCa, err := os.CreateTemp(t.TempDir(), \"ca-tmp.crt\")\n\trequire.NoError(t, err)\n\ttmpCaPath, err := filepath.Abs(tmpCa.Name())\n\tassert.NoError(t, err)\n\tassert.NoError(t, tmpCa.Close())\n\treturn tmpCaPath\n}\n\nfunc TestEagerlyLoadCertificate(t *testing.T) {\n\toptions := Config{\n\t\tCertFile: filepath.Join(\"testdata\", \"client-1.crt\"),\n\t\tKeyFile:  filepath.Join(\"testdata\", \"client-1.key\"),\n\t}\n\tcfg, err := options.loadTLSConfig()\n\trequire.NoError(t, err)\n\tassert.NotNil(t, cfg)\n\tcert, err := cfg.GetCertificate(&tls.ClientHelloInfo{})\n\trequire.NoError(t, err)\n\tassert.NotNil(t, cert)\n\tpCert, err := x509.ParseCertificate(cert.Certificate[0])\n\trequire.NoError(t, err)\n\tassert.NotNil(t, pCert)\n\tassert.ElementsMatch(t, []string{\"example1\"}, pCert.DNSNames)\n}\n\nfunc TestCertificateReload(t *testing.T) {\n\ttests := []struct {\n\t\tname           string\n\t\treloadInterval time.Duration\n\t\twait           time.Duration\n\t\tcert2          string\n\t\tkey2           string\n\t\tdns1           string\n\t\tdns2           string\n\t\terrText        string\n\t}{\n\t\t{\n\t\t\tname:           \"Should reload the certificate after reload-interval\",\n\t\t\treloadInterval: 100 * time.Microsecond,\n\t\t\twait:           100 * time.Microsecond,\n\t\t\tcert2:          \"client-2.crt\",\n\t\t\tkey2:           \"client-2.key\",\n\t\t\tdns1:           \"example1\",\n\t\t\tdns2:           \"example2\",\n\t\t},\n\t\t{\n\t\t\tname:           \"Should return same cert if called before reload-interval\",\n\t\t\treloadInterval: 100 * time.Millisecond,\n\t\t\twait:           100 * time.Microsecond,\n\t\t\tcert2:          \"client-2.crt\",\n\t\t\tkey2:           \"client-2.key\",\n\t\t\tdns1:           \"example1\",\n\t\t\tdns2:           \"example1\",\n\t\t},\n\t\t{\n\t\t\tname:           \"Should always return same cert if reload-interval is 0\",\n\t\t\treloadInterval: 0,\n\t\t\twait:           100 * time.Microsecond,\n\t\t\tcert2:          \"client-2.crt\",\n\t\t\tkey2:           \"client-2.key\",\n\t\t\tdns1:           \"example1\",\n\t\t\tdns2:           \"example1\",\n\t\t},\n\t\t{\n\t\t\tname:           \"Should return an error if reloading fails\",\n\t\t\treloadInterval: 100 * time.Microsecond,\n\t\t\twait:           100 * time.Microsecond,\n\t\t\tcert2:          \"testCA-bad.txt\",\n\t\t\tkey2:           \"client-2.key\",\n\t\t\tdns1:           \"example1\",\n\t\t\terrText:        \"failed to load TLS cert and key: failed to load TLS cert and key PEMs: tls: failed to find any PEM data in certificate input\",\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t// Copy certs into a temp dir so we can safely modify them\n\t\t\ttempDir := t.TempDir()\n\t\t\tcertFile, err := os.CreateTemp(tempDir, \"cert\")\n\t\t\trequire.NoError(t, err)\n\t\t\tdefer certFile.Close()\n\n\t\t\tkeyFile, err := os.CreateTemp(tempDir, \"key\")\n\t\t\trequire.NoError(t, err)\n\t\t\tdefer keyFile.Close()\n\n\t\t\tfdc, err := os.Open(filepath.Join(\"testdata\", \"client-1.crt\"))\n\t\t\trequire.NoError(t, err)\n\t\t\t_, err = io.Copy(certFile, fdc)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, fdc.Close())\n\n\t\t\tfdk, err := os.Open(filepath.Join(\"testdata\", \"client-1.key\"))\n\t\t\trequire.NoError(t, err)\n\t\t\t_, err = io.Copy(keyFile, fdk)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.NoError(t, fdk.Close())\n\n\t\t\toptions := Config{\n\t\t\t\tCertFile:       certFile.Name(),\n\t\t\t\tKeyFile:        keyFile.Name(),\n\t\t\t\tReloadInterval: test.reloadInterval,\n\t\t\t}\n\t\t\tcfg, err := options.loadTLSConfig()\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.NotNil(t, cfg)\n\n\t\t\t// Assert that we loaded the original certificate\n\t\t\tcert, err := cfg.GetCertificate(&tls.ClientHelloInfo{})\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.NotNil(t, cert)\n\t\t\tpCert, err := x509.ParseCertificate(cert.Certificate[0])\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.NotNil(t, pCert)\n\t\t\tassert.Equal(t, test.dns1, pCert.DNSNames[0])\n\n\t\t\t// Change the certificate\n\t\t\tassert.NoError(t, certFile.Truncate(0))\n\t\t\tassert.NoError(t, keyFile.Truncate(0))\n\t\t\t_, err = certFile.Seek(0, 0)\n\t\t\trequire.NoError(t, err)\n\t\t\t_, err = keyFile.Seek(0, 0)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tfdc2, err := os.Open(filepath.Join(\"testdata\", test.cert2))\n\t\t\trequire.NoError(t, err)\n\t\t\t_, err = io.Copy(certFile, fdc2)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.NoError(t, fdc2.Close())\n\n\t\t\tfdk2, err := os.Open(filepath.Join(\"testdata\", test.key2))\n\t\t\trequire.NoError(t, err)\n\t\t\t_, err = io.Copy(keyFile, fdk2)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.NoError(t, fdk2.Close())\n\n\t\t\t// Wait ReloadInterval to ensure a reload will happen\n\t\t\ttime.Sleep(test.wait)\n\n\t\t\t// Assert that we loaded the new certificate\n\t\t\tcert, err = cfg.GetCertificate(&tls.ClientHelloInfo{})\n\t\t\tif test.errText == \"\" {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.NotNil(t, cert)\n\t\t\t\tpCert, err = x509.ParseCertificate(cert.Certificate[0])\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.NotNil(t, pCert)\n\t\t\t\tassert.Equal(t, test.dns2, pCert.DNSNames[0])\n\t\t\t} else {\n\t\t\t\tassert.EqualError(t, err, test.errText)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMinMaxTLSVersions(t *testing.T) {\n\ttests := []struct {\n\t\tname          string\n\t\tminVersion    string\n\t\tmaxVersion    string\n\t\toutMinVersion uint16\n\t\toutMaxVersion uint16\n\t\terrorTxt      string\n\t}{\n\t\t{name: `TLS Config [\"\", \"\"] to give [TLS1.2, 0]`, minVersion: \"\", maxVersion: \"\", outMinVersion: tls.VersionTLS12, outMaxVersion: 0},\n\t\t{name: `TLS Config [\"\", \"1.3\"] to give [TLS1.2, TLS1.3]`, minVersion: \"\", maxVersion: \"1.3\", outMinVersion: tls.VersionTLS12, outMaxVersion: tls.VersionTLS13},\n\t\t{name: `TLS Config [\"1.2\", \"\"] to give [TLS1.2, 0]`, minVersion: \"1.2\", maxVersion: \"\", outMinVersion: tls.VersionTLS12, outMaxVersion: 0},\n\t\t{name: `TLS Config [\"1.3\", \"1.3\"] to give [TLS1.3, TLS1.3]`, minVersion: \"1.3\", maxVersion: \"1.3\", outMinVersion: tls.VersionTLS13, outMaxVersion: tls.VersionTLS13},\n\t\t{name: `TLS Config [\"1.0\", \"1.1\"] to give [TLS1.0, TLS1.1]`, minVersion: \"1.0\", maxVersion: \"1.1\", outMinVersion: tls.VersionTLS10, outMaxVersion: tls.VersionTLS11},\n\t\t{name: `TLS Config [\"asd\", \"\"] to give [Error]`, minVersion: \"asd\", maxVersion: \"\", errorTxt: `invalid TLS min_version: unsupported TLS version: \"asd\"`},\n\t\t{name: `TLS Config [\"\", \"asd\"] to give [Error]`, minVersion: \"\", maxVersion: \"asd\", errorTxt: `invalid TLS max_version: unsupported TLS version: \"asd\"`},\n\t\t{name: `TLS Config [\"0.4\", \"\"] to give [Error]`, minVersion: \"0.4\", maxVersion: \"\", errorTxt: `invalid TLS min_version: unsupported TLS version: \"0.4\"`},\n\n\t\t// Allowing this, however, expecting downstream TLS handshake will throw an error\n\t\t{name: `TLS Config [\"1.2\", \"1.1\"] to give [TLS1.2, TLS1.1]`, minVersion: \"1.2\", maxVersion: \"1.1\", outMinVersion: tls.VersionTLS12, outMaxVersion: tls.VersionTLS11},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tsetting := Config{\n\t\t\t\tMinVersion: test.minVersion,\n\t\t\t\tMaxVersion: test.maxVersion,\n\t\t\t}\n\n\t\t\tconfig, err := setting.loadTLSConfig()\n\n\t\t\tif test.errorTxt == \"\" {\n\t\t\t\tassert.Equal(t, config.MinVersion, test.outMinVersion)\n\t\t\t\tassert.Equal(t, config.MaxVersion, test.outMaxVersion)\n\t\t\t} else {\n\t\t\t\tassert.EqualError(t, err, test.errorTxt)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestConfigValidate(t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\ttlsConfig Config\n\t\terrorTxt  string\n\t}{\n\t\t{name: `TLS Config [\"\", \"\"] to be valid`, tlsConfig: Config{MinVersion: \"\", MaxVersion: \"\"}},\n\t\t{name: `TLS Config [\"\", \"1.3\"] to be valid`, tlsConfig: Config{MinVersion: \"\", MaxVersion: \"1.3\"}},\n\t\t{name: `TLS Config [\"1.2\", \"\"] to be valid`, tlsConfig: Config{MinVersion: \"1.2\", MaxVersion: \"\"}},\n\t\t{name: `TLS Config [\"1.3\", \"1.3\"] to be valid`, tlsConfig: Config{MinVersion: \"1.3\", MaxVersion: \"1.3\"}},\n\t\t{name: `TLS Config [\"1.0\", \"1.1\"] to be valid`, tlsConfig: Config{MinVersion: \"1.0\", MaxVersion: \"1.1\"}},\n\t\t{name: `TLS Config [\"asd\", \"\"] to give [Error]`, tlsConfig: Config{MinVersion: \"asd\", MaxVersion: \"\"}, errorTxt: `invalid TLS min_version: unsupported TLS version: \"asd\"`},\n\t\t{name: `TLS Config [\"\", \"asd\"] to give [Error]`, tlsConfig: Config{MinVersion: \"\", MaxVersion: \"asd\"}, errorTxt: `invalid TLS max_version: unsupported TLS version: \"asd\"`},\n\t\t{name: `TLS Config [\"0.4\", \"\"] to give [Error]`, tlsConfig: Config{MinVersion: \"0.4\", MaxVersion: \"\"}, errorTxt: `invalid TLS min_version: unsupported TLS version: \"0.4\"`},\n\t\t{name: `TLS Config [\"1.2\", \"1.1\"] to give [Error]`, tlsConfig: Config{MinVersion: \"1.2\", MaxVersion: \"1.1\"}, errorTxt: `invalid TLS configuration: min_version cannot be greater than max_version`},\n\t\t{name: `TLS Config with both CA File and PEM`, tlsConfig: Config{CAFile: \"test\", CAPem: \"test\"}, errorTxt: `provide either a CA file or the PEM-encoded string, but not both`},\n\t\t{name: `TLS Config with cert file but no key`, tlsConfig: Config{CertFile: \"cert.pem\"}, errorTxt: `TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)`},\n\t\t{name: `TLS Config with key file but no cert`, tlsConfig: Config{KeyFile: \"key.pem\"}, errorTxt: `TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)`},\n\t\t{name: `TLS Config with cert PEM but no key`, tlsConfig: Config{CertPem: \"cert-pem\"}, errorTxt: `TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)`},\n\t\t{name: `TLS Config with key PEM but no cert`, tlsConfig: Config{KeyPem: \"key-pem\"}, errorTxt: `TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)`},\n\t\t{name: `TLS Config with both cert file and cert PEM`, tlsConfig: Config{CertFile: \"cert.pem\", CertPem: \"cert-pem\", KeyFile: \"key.pem\"}, errorTxt: `provide either certificate file or PEM, but not both`},\n\t\t{name: `TLS Config with both key file and key PEM`, tlsConfig: Config{CertFile: \"cert.pem\", KeyFile: \"key.pem\", KeyPem: \"key-pem\"}, errorTxt: `provide either key file or PEM, but not both`},\n\t\t{name: `TLS Config with cert file and key PEM`, tlsConfig: Config{CertFile: \"cert.pem\", KeyPem: \"key-pem\"}},\n\t\t{name: `TLS Config with cert PEM and key file`, tlsConfig: Config{CertPem: \"cert-pem\", KeyFile: \"key.pem\"}},\n\t\t{name: `TLS Config with valid cert and key files`, tlsConfig: Config{CertFile: \"cert.pem\", KeyFile: \"key.pem\"}},\n\t\t{name: `TLS Config with valid cert and key PEM`, tlsConfig: Config{CertPem: \"cert-pem\", KeyPem: \"key-pem\"}},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\terr := test.tlsConfig.Validate()\n\n\t\t\tif test.errorTxt == \"\" {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t} else {\n\t\t\t\tassert.EqualError(t, err, test.errorTxt)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCipherSuites(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\ttlsSetting Config\n\t\twantErr    string\n\t\tresult     []uint16\n\t}{\n\t\t{\n\t\t\tname:       \"no suites set\",\n\t\t\ttlsSetting: Config{},\n\t\t\tresult:     nil,\n\t\t},\n\t\t{\n\t\t\tname: \"one cipher suite set\",\n\t\t\ttlsSetting: Config{\n\t\t\t\tCipherSuites: []string{\"TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA\"},\n\t\t\t},\n\t\t\tresult: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA},\n\t\t},\n\t\t{\n\t\t\tname: \"invalid cipher suite set\",\n\t\t\ttlsSetting: Config{\n\t\t\t\tCipherSuites: []string{\"FOO\"},\n\t\t\t},\n\t\t\twantErr: `invalid TLS cipher suite: \"FOO\"`,\n\t\t},\n\t\t{\n\t\t\tname: \"multiple invalid cipher suites set\",\n\t\t\ttlsSetting: Config{\n\t\t\t\tCipherSuites: []string{\"FOO\", \"BAR\"},\n\t\t\t},\n\t\t\twantErr: `invalid TLS cipher suite: \"FOO\"\ninvalid TLS cipher suite: \"BAR\"`,\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tconfig, err := test.tlsSetting.loadTLSConfig()\n\t\t\tif test.wantErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, test.wantErr)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.Equal(t, test.result, config.CipherSuites)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestSystemCertPool(t *testing.T) {\n\tanError := errors.New(\"my error\")\n\ttests := []struct {\n\t\tname         string\n\t\ttlsConfig    Config\n\t\twantErr      error\n\t\tsystemCertFn func() (*x509.CertPool, error)\n\t}{\n\t\t{\n\t\t\tname: \"not using system cert pool\",\n\t\t\ttlsConfig: Config{\n\t\t\t\tIncludeSystemCACertsPool: false,\n\t\t\t\tCAFile:                   filepath.Join(\"testdata\", \"ca-1.crt\"),\n\t\t\t},\n\t\t\twantErr:      nil,\n\t\t\tsystemCertFn: x509.SystemCertPool,\n\t\t},\n\t\t{\n\t\t\tname: \"using system cert pool\",\n\t\t\ttlsConfig: Config{\n\t\t\t\tIncludeSystemCACertsPool: true,\n\t\t\t\tCAFile:                   filepath.Join(\"testdata\", \"ca-1.crt\"),\n\t\t\t},\n\t\t\twantErr:      nil,\n\t\t\tsystemCertFn: x509.SystemCertPool,\n\t\t},\n\t\t{\n\t\t\tname: \"error loading system cert pool\",\n\t\t\ttlsConfig: Config{\n\t\t\t\tIncludeSystemCACertsPool: true,\n\t\t\t\tCAFile:                   filepath.Join(\"testdata\", \"ca-1.crt\"),\n\t\t\t},\n\t\t\twantErr: anError,\n\t\t\tsystemCertFn: func() (*x509.CertPool, error) {\n\t\t\t\treturn nil, anError\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"nil system cert pool\",\n\t\t\ttlsConfig: Config{\n\t\t\t\tIncludeSystemCACertsPool: true,\n\t\t\t\tCAFile:                   filepath.Join(\"testdata\", \"ca-1.crt\"),\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\tsystemCertFn: func() (*x509.CertPool, error) {\n\t\t\t\treturn nil, nil\n\t\t\t},\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\toldSystemCertPool := systemCertPool\n\t\t\tsystemCertPool = test.systemCertFn\n\t\t\tdefer func() {\n\t\t\t\tsystemCertPool = oldSystemCertPool\n\t\t\t}()\n\n\t\t\tserverConfig := ServerConfig{\n\t\t\t\tConfig: test.tlsConfig,\n\t\t\t}\n\t\t\tc, err := serverConfig.LoadTLSConfig(context.Background())\n\t\t\tif test.wantErr != nil {\n\t\t\t\trequire.ErrorContains(t, err, test.wantErr.Error())\n\t\t\t} else {\n\t\t\t\tassert.NotNil(t, c.RootCAs)\n\t\t\t}\n\n\t\t\tclientConfig := ClientConfig{\n\t\t\t\tConfig: test.tlsConfig,\n\t\t\t}\n\t\t\tc, err = clientConfig.LoadTLSConfig(context.Background())\n\t\t\tif test.wantErr != nil {\n\t\t\t\tassert.ErrorContains(t, err, test.wantErr.Error())\n\t\t\t} else {\n\t\t\t\tassert.NotNil(t, c.RootCAs)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestSystemCertPool_loadCert(t *testing.T) {\n\tanError := errors.New(\"my error\")\n\ttests := []struct {\n\t\tname         string\n\t\ttlsConfig    Config\n\t\twantErr      error\n\t\tsystemCertFn func() (*x509.CertPool, error)\n\t}{\n\t\t{\n\t\t\tname: \"not using system cert pool\",\n\t\t\ttlsConfig: Config{\n\t\t\t\tIncludeSystemCACertsPool: false,\n\t\t\t},\n\t\t\twantErr:      nil,\n\t\t\tsystemCertFn: x509.SystemCertPool,\n\t\t},\n\t\t{\n\t\t\tname: \"using system cert pool\",\n\t\t\ttlsConfig: Config{\n\t\t\t\tIncludeSystemCACertsPool: true,\n\t\t\t},\n\t\t\twantErr:      nil,\n\t\t\tsystemCertFn: x509.SystemCertPool,\n\t\t},\n\t\t{\n\t\t\tname: \"error loading system cert pool\",\n\t\t\ttlsConfig: Config{\n\t\t\t\tIncludeSystemCACertsPool: true,\n\t\t\t},\n\t\t\twantErr: anError,\n\t\t\tsystemCertFn: func() (*x509.CertPool, error) {\n\t\t\t\treturn nil, anError\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"nil system cert pool\",\n\t\t\ttlsConfig: Config{\n\t\t\t\tIncludeSystemCACertsPool: true,\n\t\t\t},\n\t\t\twantErr: nil,\n\t\t\tsystemCertFn: func() (*x509.CertPool, error) {\n\t\t\t\treturn nil, nil\n\t\t\t},\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\toldSystemCertPool := systemCertPool\n\t\t\tsystemCertPool = test.systemCertFn\n\t\t\tdefer func() {\n\t\t\t\tsystemCertPool = oldSystemCertPool\n\t\t\t}()\n\t\t\tcertPool, err := test.tlsConfig.loadCert(filepath.Join(\"testdata\", \"ca-1.crt\"))\n\t\t\tif test.wantErr != nil {\n\t\t\t\tassert.Equal(t, test.wantErr, err)\n\t\t\t} else {\n\t\t\t\tassert.NotNil(t, certPool)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCurvePreferences(t *testing.T) {\n\ttype testCase struct {\n\t\tname             string\n\t\tpreferences      []string\n\t\texpectedCurveIDs []tls.CurveID\n\t\texpectedErr      string\n\t}\n\n\ttests := []testCase{\n\t\t{\n\t\t\tname:             \"P521\",\n\t\t\tpreferences:      []string{\"P521\"},\n\t\t\texpectedCurveIDs: []tls.CurveID{tls.CurveP521},\n\t\t},\n\t\t{\n\t\t\tname:             \"P-256\",\n\t\t\tpreferences:      []string{\"P256\"},\n\t\t\texpectedCurveIDs: []tls.CurveID{tls.CurveP256},\n\t\t},\n\t\t{\n\t\t\tname:             \"multiple\",\n\t\t\tpreferences:      []string{\"P256\", \"P521\"},\n\t\t\texpectedCurveIDs: []tls.CurveID{tls.CurveP256, tls.CurveP521},\n\t\t},\n\t\t{\n\t\t\tname:             \"invalid-curve\",\n\t\t\tpreferences:      []string{\"P25223236\"},\n\t\t\texpectedCurveIDs: []tls.CurveID{},\n\t\t\texpectedErr:      \"invalid curve type\",\n\t\t},\n\t}\n\n\t// X25519 curves are not supported when GODEBUG=fips140=only is set, so we\n\t// detect if it is and conditionally add test cases for those curves.\n\tif !strings.Contains(os.Getenv(\"GODEBUG\"), \"fips140=only\") {\n\t\ttests = append(tests,\n\t\t\ttestCase{\n\t\t\t\tname:             \"X25519MLKEM768\",\n\t\t\t\tpreferences:      []string{\"X25519MLKEM768\"},\n\t\t\t\texpectedCurveIDs: []tls.CurveID{tls.X25519MLKEM768},\n\t\t\t},\n\t\t\ttestCase{\n\t\t\t\tname:             \"X25519\",\n\t\t\t\tpreferences:      []string{\"X25519\"},\n\t\t\t\texpectedCurveIDs: []tls.CurveID{tls.X25519},\n\t\t\t},\n\t\t)\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\ttlsSetting := ClientConfig{\n\t\t\t\tConfig: Config{\n\t\t\t\t\tCurvePreferences: test.preferences,\n\t\t\t\t},\n\t\t\t}\n\t\t\tconfig, err := tlsSetting.LoadTLSConfig(context.Background())\n\t\t\tif test.expectedErr == \"\" {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.ElementsMatchf(t, test.expectedCurveIDs, config.CurvePreferences, \"expected %v, got %v\", test.expectedCurveIDs, config.CurvePreferences)\n\t\t\t} else {\n\t\t\t\trequire.ErrorContains(t, err, test.expectedErr)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestServerConfigValidate(t *testing.T) {\n\ttests := []struct {\n\t\tname         string\n\t\tserverConfig ServerConfig\n\t\terrorTxt     string\n\t}{\n\t\t{\n\t\t\tname:         \"server config without certificates\",\n\t\t\tserverConfig: ServerConfig{},\n\t\t\terrorTxt:     \"TLS configuration must include both certificate and key for server connections\",\n\t\t},\n\t\t{\n\t\t\tname: \"server config with cert file but no key\",\n\t\t\tserverConfig: ServerConfig{\n\t\t\t\tConfig: Config{\n\t\t\t\t\tCertFile: \"cert.pem\",\n\t\t\t\t},\n\t\t\t},\n\t\t\terrorTxt: \"config: TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)\",\n\t\t},\n\t\t{\n\t\t\tname: \"server config with key file but no cert\",\n\t\t\tserverConfig: ServerConfig{\n\t\t\t\tConfig: Config{\n\t\t\t\t\tKeyFile: \"key.pem\",\n\t\t\t\t},\n\t\t\t},\n\t\t\terrorTxt: \"config: TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)\",\n\t\t},\n\t\t{\n\t\t\tname: \"server config with cert PEM but no key\",\n\t\t\tserverConfig: ServerConfig{\n\t\t\t\tConfig: Config{\n\t\t\t\t\tCertPem: \"cert-pem\",\n\t\t\t\t},\n\t\t\t},\n\t\t\terrorTxt: \"config: TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)\",\n\t\t},\n\t\t{\n\t\t\tname: \"server config with key PEM but no cert\",\n\t\t\tserverConfig: ServerConfig{\n\t\t\t\tConfig: Config{\n\t\t\t\t\tKeyPem: \"key-pem\",\n\t\t\t\t},\n\t\t\t},\n\t\t\terrorTxt: \"config: TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)\",\n\t\t},\n\t\t{\n\t\t\tname: \"server config with both cert file and cert PEM\",\n\t\t\tserverConfig: ServerConfig{\n\t\t\t\tConfig: Config{\n\t\t\t\t\tCertFile: \"cert.pem\",\n\t\t\t\t\tCertPem:  \"cert-pem\",\n\t\t\t\t\tKeyFile:  \"key.pem\",\n\t\t\t\t},\n\t\t\t},\n\t\t\terrorTxt: \"config: provide either certificate file or PEM, but not both\",\n\t\t},\n\t\t{\n\t\t\tname: \"server config with both key file and key PEM\",\n\t\t\tserverConfig: ServerConfig{\n\t\t\t\tConfig: Config{\n\t\t\t\t\tCertFile: \"cert.pem\",\n\t\t\t\t\tKeyFile:  \"key.pem\",\n\t\t\t\t\tKeyPem:   \"key-pem\",\n\t\t\t\t},\n\t\t\t},\n\t\t\terrorTxt: \"config: provide either key file or PEM, but not both\",\n\t\t},\n\t\t{\n\t\t\tname: \"valid server config with cert and key files\",\n\t\t\tserverConfig: ServerConfig{\n\t\t\t\tConfig: Config{\n\t\t\t\t\tCertFile: \"cert.pem\",\n\t\t\t\t\tKeyFile:  \"key.pem\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"valid server config with cert and key PEM\",\n\t\t\tserverConfig: ServerConfig{\n\t\t\t\tConfig: Config{\n\t\t\t\t\tCertPem: \"cert-pem\",\n\t\t\t\t\tKeyPem:  \"key-pem\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"valid server config with mixed cert file and key PEM\",\n\t\t\tserverConfig: ServerConfig{\n\t\t\t\tConfig: Config{\n\t\t\t\t\tCertFile: \"cert.pem\",\n\t\t\t\t\tKeyPem:   \"key-pem\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\terr := xconfmap.Validate(test.serverConfig)\n\n\t\t\tif test.errorTxt == \"\" {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t} else {\n\t\t\t\tassert.ErrorContains(t, err, test.errorTxt)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestClientConfigValidate(t *testing.T) {\n\ttests := []struct {\n\t\tname         string\n\t\tclientConfig ClientConfig\n\t\terrorTxt     string\n\t}{\n\t\t{\n\t\t\tname:         \"valid empty client config\",\n\t\t\tclientConfig: ClientConfig{},\n\t\t},\n\t\t{\n\t\t\tname: \"valid client config with insecure connection\",\n\t\t\tclientConfig: ClientConfig{\n\t\t\t\tInsecure: true,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"valid client config with cert and key files\",\n\t\t\tclientConfig: ClientConfig{\n\t\t\t\tConfig: Config{\n\t\t\t\t\tCertFile: \"cert.pem\",\n\t\t\t\t\tKeyFile:  \"key.pem\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"valid client config with mixed cert file and key PEM\",\n\t\t\tclientConfig: ClientConfig{\n\t\t\t\tConfig: Config{\n\t\t\t\t\tCertFile: \"cert.pem\",\n\t\t\t\t\tKeyPem:   \"key-pem\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"client config with only cert file\",\n\t\t\tclientConfig: ClientConfig{\n\t\t\t\tConfig: Config{\n\t\t\t\t\tCertFile: \"cert.pem\",\n\t\t\t\t},\n\t\t\t},\n\t\t\terrorTxt: \"config: TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)\",\n\t\t},\n\t\t{\n\t\t\tname: \"client config with only key file\",\n\t\t\tclientConfig: ClientConfig{\n\t\t\t\tConfig: Config{\n\t\t\t\t\tKeyFile: \"key.pem\",\n\t\t\t\t},\n\t\t\t},\n\t\t\terrorTxt: \"config: TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)\",\n\t\t},\n\t\t{\n\t\t\tname: \"client config with only cert PEM\",\n\t\t\tclientConfig: ClientConfig{\n\t\t\t\tConfig: Config{\n\t\t\t\t\tCertPem: \"cert-pem\",\n\t\t\t\t},\n\t\t\t},\n\t\t\terrorTxt: \"config: TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)\",\n\t\t},\n\t\t{\n\t\t\tname: \"client config with only key PEM\",\n\t\t\tclientConfig: ClientConfig{\n\t\t\t\tConfig: Config{\n\t\t\t\t\tKeyPem: \"key-pem\",\n\t\t\t\t},\n\t\t\t},\n\t\t\terrorTxt: \"config: TLS configuration must include both certificate and key (CertFile/CertPem and KeyFile/KeyPem)\",\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\terr := xconfmap.Validate(test.clientConfig)\n\n\t\t\tif test.errorTxt == \"\" {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t} else {\n\t\t\t\tassert.ErrorContains(t, err, test.errorTxt)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "config/configtls/curves_fips.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build requirefips\n\npackage configtls // import \"go.opentelemetry.io/collector/config/configtls\"\n\nimport \"crypto/tls\"\n\nvar tlsCurveTypes = map[string]tls.CurveID{\n\t\"P256\": tls.CurveP256,\n\t\"P384\": tls.CurveP384,\n\t\"P521\": tls.CurveP521,\n\n\t// The following X25519 curves are not available in FIPS mode, so we remove them from the map.\n\t// See also https://cs.opensource.google/go/go/+/refs/tags/go1.24.6:src/crypto/ecdh/x25519.go\n\t//\"X25519\": tls.X25519,\n\t//\"X25519MLKEM768\": tls.X25519MLKEM768,\n}\n"
  },
  {
    "path": "config/configtls/curves_nofips.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build !requirefips\n\npackage configtls // import \"go.opentelemetry.io/collector/config/configtls\"\n\nimport \"crypto/tls\"\n\nvar tlsCurveTypes = map[string]tls.CurveID{\n\t\"P256\":           tls.CurveP256,\n\t\"P384\":           tls.CurveP384,\n\t\"P521\":           tls.CurveP521,\n\t\"X25519\":         tls.X25519,\n\t\"X25519MLKEM768\": tls.X25519MLKEM768,\n}\n"
  },
  {
    "path": "config/configtls/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package configtls implements the TLS settings to load and\n// configure TLS clients and servers.\npackage configtls // import \"go.opentelemetry.io/collector/config/configtls\"\n"
  },
  {
    "path": "config/configtls/go.mod",
    "content": "module go.opentelemetry.io/collector/config/configtls\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/foxboron/go-tpm-keyfiles v0.0.0-20250903184740-5d135037bd4d\n\tgithub.com/fsnotify/fsnotify v1.9.0\n\tgithub.com/google/go-tpm v0.9.8\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/config/configopaque v1.54.0\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0\n\tgo.opentelemetry.io/collector/internal/testutil v0.148.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/google/go-tpm-tools v0.4.7 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/confmap v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/crypto v0.48.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/config/configopaque => ../configopaque\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n"
  },
  {
    "path": "config/configtls/go.sum",
    "content": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20250903184740-5d135037bd4d h1:EdO/NMMuCZfxhdzTZLuKAciQSnI2DV+Ppg8+vAYrnqA=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20250903184740-5d135037bd4d/go.mod h1:uAyTlAUxchYuiFjTHmuIEJ4nGSm7iOPaGcAyA81fJ80=\ngithub.com/foxboron/swtpm_test v0.0.0-20230726224112-46aaafdf7006 h1:50sW4r0PcvlpG4PV8tYh2RVCapszJgaOLRCS2subvV4=\ngithub.com/foxboron/swtpm_test v0.0.0-20230726224112-46aaafdf7006/go.mod h1:eIXCMsMYCaqq9m1KSSxXwQG11krpuNPGP3k0uaWrbas=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/google/go-configfs-tsm v0.3.3-0.20240919001351-b4b5b84fdcbc h1:SG12DWUUM5igxm+//YX5Yq4vhdoRnOG9HkCodkOn+YU=\ngithub.com/google/go-configfs-tsm v0.3.3-0.20240919001351-b4b5b84fdcbc/go.mod h1:EL1GTDFMb5PZQWDviGfZV9n87WeGTR/JUg13RfwkgRo=\ngithub.com/google/go-sev-guest v0.14.0 h1:dCb4F3YrHTtrDX3cYIPTifEDz7XagZmXQioxRBW4wOo=\ngithub.com/google/go-sev-guest v0.14.0/go.mod h1:SK9vW+uyfuzYdVN0m8BShL3OQCtXZe/JPF7ZkpD3760=\ngithub.com/google/go-tdx-guest v0.3.2-0.20241009005452-097ee70d0843 h1:+MoPobRN9HrDhGyn6HnF5NYo4uMBKaiFqAtf/D/OB4A=\ngithub.com/google/go-tdx-guest v0.3.2-0.20241009005452-097ee70d0843/go.mod h1:g/n8sKITIT9xRivBUbizo34DTsUm2nN2uU3A662h09g=\ngithub.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=\ngithub.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=\ngithub.com/google/go-tpm-tools v0.4.7 h1:J3ycC8umYxM9A4eF73EofRZu4BxY0jjQnUnkhIBbvws=\ngithub.com/google/go-tpm-tools v0.4.7/go.mod h1:gSyXTZHe3fgbzb6WEGd90QucmsnT1SRdlye82gH8QjQ=\ngithub.com/google/logger v1.1.1 h1:+6Z2geNxc9G+4D4oDO9njjjn2d0wN5d7uOo0vOIW1NQ=\ngithub.com/google/logger v1.1.1/go.mod h1:BkeJZ+1FhQ+/d087r4dzojEg1u2ZX+ZqG1jTUrLM+zQ=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=\ngolang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngoogle.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA=\ngoogle.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "config/configtls/metadata.yaml",
    "content": "type: config/configtls\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "config/configtls/testdata/ca-1.crt",
    "content": "-----BEGIN CERTIFICATE-----\nMIIDNjCCAh4CCQDkU3rM23H5hzANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJB\nVTESMBAGA1UECAwJQXVzdHJhbGlhMQ8wDQYDVQQHDAZTeWRuZXkxEjAQBgNVBAoM\nCU15T3JnTmFtZTEVMBMGA1UEAwwMTXlDb21tb25OYW1lMB4XDTIyMDgwMzA0MTgx\nOFoXDTMyMDczMTA0MTgxOFowXTELMAkGA1UEBhMCQVUxEjAQBgNVBAgMCUF1c3Ry\nYWxpYTEPMA0GA1UEBwwGU3lkbmV5MRIwEAYDVQQKDAlNeU9yZ05hbWUxFTATBgNV\nBAMMDE15Q29tbW9uTmFtZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB\nAK836YUxmCDcznt11ReI5fY/DSJzz+Fs7czoE72RMvW+SMH2YhX9XC55xAMPZ+IV\nszoG5Fatd/GWBfoACmaM3ZEmYskuRnu4pxqOEpRIsBukOiILBMxa/cwqiDyLiacC\nw0B1NhysG28XnxUWrYxd9jFlJ+wAIx7XT+1QM0xGCGr9agSQ/ow6+QMWZ5Qc1n2e\nEmaoU861qlF+0LeyZeBNeo+C7jTikIC+CRKVNX5t9MLqSmlxfrXe0qCS99zmPKfg\nOhtteZVAKbdPKSoi2ls6EQ1dNB2Mq3GHkd8kGi30FuRCTQLKaXacUdjtQfbKxuGl\nRjXlN6mDoUs8mIO861mVFXECAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAUrgRTBBO\npwYjZsLNw10FYK19P6FpVm/nbbzTJmqKlxReLRkkTyNm/tB5W1LdRN9RG15h62Ii\nJBGxpeCMDElwCwXN2OOwqdXczafLa9AhPnPw/DYuQAd9dS7/XHG/ArQFTL+GLd8T\nbdlnED9Z9qMygF13btLQUHzKaOk6dndLsquoTjgjj4SNBe2Isj7z4upZOix2cgJB\n9ddZGlv8/zKSgRp9UotGOOxG7HJ1KWhYLU7E0aERqambNv8UFvhmf+biHq3nCeAF\nHBeua27MNj4kGCzqHS7sVqZKVU81aFyhV2WmfIUA0Qp+nh9QEW0yrgI+pTnOx6np\nJUHGleZ3rKHQZw==\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "config/configtls/testdata/ca-2.crt",
    "content": "-----BEGIN CERTIFICATE-----\nMIIDNjCCAh4CCQDOIY+kxxC6dzANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJB\nVTESMBAGA1UECAwJQXVzdHJhbGlhMQ8wDQYDVQQHDAZTeWRuZXkxEjAQBgNVBAoM\nCU15T3JnTmFtZTEVMBMGA1UEAwwMTXlDb21tb25OYW1lMB4XDTIyMDgwMzA0MTgy\nN1oXDTMyMDczMTA0MTgyN1owXTELMAkGA1UEBhMCQVUxEjAQBgNVBAgMCUF1c3Ry\nYWxpYTEPMA0GA1UEBwwGU3lkbmV5MRIwEAYDVQQKDAlNeU9yZ05hbWUxFTATBgNV\nBAMMDE15Q29tbW9uTmFtZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB\nALm3FA/0uN36RPpMnRbV7HF2dY0quEevuHFPjDwBa6bRrn+p1kDezkZ+YGatT7yg\nOr+HLU+9WoJKQe738d/gp+BRwTpuTkFh6YeM1t+EclZZfSX/jQwia/7p0CGZ24wD\nCR33YifauT+AMS1VLbkTTFQFQ+XwkIqUL8aP3T1XvYSnOvbeNcIYEH6ABXyDwBdL\nytuJ0YnFwYj0lJcAHf1EYQEXNXz6s1E1Y3r4pZfo209PK8aHR/oT1Gc310B35cfA\ntrYaGsynla/aUjrvm147hj32Wln3EG10qkIOAwkR0iTYNfYdCG4vJKUFOSj1AFei\nA0PWnOYP+zDFR1bEz22VfV8CAwEAATANBgkqhkiG9w0BAQsFAAOCAQEAluPjsPhg\nOZ31iLqnRoxDJ8EuYtY2ft1RV4WUY+o9zY24JRZ/1b1cC6VzTECQQTiOuM+G+U0k\nFlTfU3VaY+m+oP8F/2n9X+9M87flX1AgE3EOqae3CNN7IYCu6ipCLaOZQwL4CjFe\nhsurX7eyu8LDrX8/T+B60V13gCsXi6E1Dt+9lRNzjIU9YcqwuDqlPU0I0WCjuP2H\nflisUQ3Z70gg9bPd7h3EVfdrlceGYQpuiO5aHXhzr8oIoOo3K6L6RXaHAjLd56SM\nZKa+VUCCJcfq6HwnSRUveu2txD1lUHFag2amfJu22V0JgB4Dvm1ZkzU4PM00ZJSK\nlSu6E+lI09aLHg==\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "config/configtls/testdata/client-1.crt",
    "content": "-----BEGIN CERTIFICATE-----\nMIIDVDCCAjygAwIBAgIJANt5fkUlfxyeMA0GCSqGSIb3DQEBCwUAMF0xCzAJBgNV\nBAYTAkFVMRIwEAYDVQQIDAlBdXN0cmFsaWExDzANBgNVBAcMBlN5ZG5leTESMBAG\nA1UECgwJTXlPcmdOYW1lMRUwEwYDVQQDDAxNeUNvbW1vbk5hbWUwHhcNMjIwODAz\nMDQxODE5WhcNMzIwNzMxMDQxODE5WjBdMQswCQYDVQQGEwJBVTESMBAGA1UECAwJ\nQXVzdHJhbGlhMQ8wDQYDVQQHDAZTeWRuZXkxEjAQBgNVBAoMCU15T3JnTmFtZTEV\nMBMGA1UEAwwMTXlDb21tb25OYW1lMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\nCgKCAQEAwDgNEcPTkTASpfFa0AwPlUFPWhlm2Av1mh3oNsf3kHOBXQymJ3HkXDq/\n7durWduubkP1jsOGqO9rcXD1Q3mmNYqsqRRydi5DbMHcFcSSA6g2QncTJwhRE/q/\n/00t6e5BhBLXscK+uJEDzEGu9CJVFkkdbeMccfb26C3os1VHGzcp5c/pCNjj93TM\n3iwlQYMoEgCo7iUDxyIQ5tjQBn/QmEPcytut11tAIlGPy+SxQjMCykREPOVuwvNh\nhZFscpCkvQPTEvv7KBZFBvYafa820CY3z++IIqQ7YBZdxYpYwBuVamUyPKB+lpsn\naD5G2LQjENdjYcRXys04bWgafalZJQIDAQABoxcwFTATBgNVHREEDDAKgghleGFt\ncGxlMTANBgkqhkiG9w0BAQsFAAOCAQEAoN6fyv+0ri3wnYMZaP2+m4NA/gk+I4Lp\neP4OpQHkHbm3wjbWZUYLJZ6IvhPHfCNAXdqCs+mpG35HI6Bg+x1CVFrNeueInKTg\n0v+0q1FlvSQhsQJoumX2bk/uSLHMIU3hhYIts0vFC0k04Vf7n9hEq7pOZD/akTaw\nhaLsQe/SRXSTjkar+Csi4DXyi/qshlkV6FOUz9vogAR0W3l8x7dqzwBHL4gRMddM\nZdSfhVFOMwKqUrucYebYZhdAvYqMtlTph46lk+hd5TarFDFJ2zEjbx9NU5gY1b8V\n/Kfm2ZHR0yWKGfg9I4TRGZgufm1HBEMnMq1b15DUZxNTagFtPAP18Q==\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "config/configtls/testdata/client-1.key",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAwDgNEcPTkTASpfFa0AwPlUFPWhlm2Av1mh3oNsf3kHOBXQym\nJ3HkXDq/7durWduubkP1jsOGqO9rcXD1Q3mmNYqsqRRydi5DbMHcFcSSA6g2QncT\nJwhRE/q//00t6e5BhBLXscK+uJEDzEGu9CJVFkkdbeMccfb26C3os1VHGzcp5c/p\nCNjj93TM3iwlQYMoEgCo7iUDxyIQ5tjQBn/QmEPcytut11tAIlGPy+SxQjMCykRE\nPOVuwvNhhZFscpCkvQPTEvv7KBZFBvYafa820CY3z++IIqQ7YBZdxYpYwBuVamUy\nPKB+lpsnaD5G2LQjENdjYcRXys04bWgafalZJQIDAQABAoIBAFemN29uWD7QKPC6\nSaqslT599W0kQB0r9uY71POF44Fe6hI//lPmPzc/It2XWV80KSnmm0ZqKjFGWzvz\nQiNuiTfI8Ep5JGh3WA9zpqPWaq54OaW9HmKiDDaMFJiZ3OHa3s0Wunw4TTdkCNNO\n8DQqo5nx5RWChioBbz0YEhAURsRFbGqFavDPvlEPOSanCB+mDOliKqX0XizffRZ3\nUBQuWa6VjDxHH93b+oJ2/zR5UOlXKHgcqNWeBofxBiiX8ZF5ylwNGOCEE2Gm+KfZ\nKUYxGlDKohSYxVjmcyLPoWGrUX83lDKD2u9VrVdgCJwA+IHEsIg9KARb6jFLzACp\nRYSDM9ECgYEA7gm8+h44D27I1yRF/3rbhxggsgRo0j5ag9NVLehp11G0ZsdoklJx\nuVhDJbjHG9HVqEMfduljr4GpyeMt2ayEmo/ejcWyl0JBMFXPXRvrubM5qoCVOqUu\nWYo/JtvIyEAQQicwo5okiPddhFvcQebSH7NXRpKWROMftnlisgtv/xsCgYEAzrk1\nvB2O/DTydcLxkY2m8E5qo1ZvTMPW6211ZCKNyQ475ZE/QxZ5iuodwErCQOHjAlV7\nn6FeWWZveOsVQeTkSvUOnPCocct+/Dx+sMcRO8k9HuC33bNcw9eHwBoztginIxEb\ns7ee+S06AT6r7SQScgBrhD6uevW+dUVbdw/6TL8CgYEAzOyNSDZjxMV3GeAccsjt\n3Oukmhy5sOYFPp/dINyI4dlxGVpqaC2Zwhp+FCdzIjwPWAARQmnCbAGQjkGJ429l\n6ToaOqsMCLP9MwNstZen5AKrjmGMFyTFNkiR/X4Q6HReitT6Rp4Y/eEXHS+H+yQf\nmTLn29WukDeHwavWj7jQ/ikCgYBDPYEZ+C9bH8nBvjAfHQkw3wDWsjWvrX/JwifN\n82NVA3k+GbmPE89i/PXCZ066Ff9l8fItISr0P1qA5U5byZzsOLuRFsJjiUJ7vx2i\nWI3leXaVBZko1r+UwBVayesKCdR7loQBN/fQqwJUB1Oa5gHN7Q8Ly+uq+SYDNRUk\nLCFJNwKBgGWcVuIarQ2mCLqqZ0zxeAp3lFTNeWG2ZMQtzeuo0iGx0xTTUEaZSiNW\nMSAvYjGrRzM6XpGEYasfwy0Zoc3loi9nzP5uE4tv8vE72nyMf+OhaPG+Rn+mdBv4\n7emViVNVfzLW7L//IkxtEamV0yc6gYwcCfzUckxxXVRD4z2aM78q\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "config/configtls/testdata/client-2.crt",
    "content": "-----BEGIN CERTIFICATE-----\nMIIDVDCCAjygAwIBAgIJANt5fkUlfxygMA0GCSqGSIb3DQEBCwUAMF0xCzAJBgNV\nBAYTAkFVMRIwEAYDVQQIDAlBdXN0cmFsaWExDzANBgNVBAcMBlN5ZG5leTESMBAG\nA1UECgwJTXlPcmdOYW1lMRUwEwYDVQQDDAxNeUNvbW1vbk5hbWUwHhcNMjIwODAz\nMDQxODI3WhcNMzIwNzMxMDQxODI3WjBdMQswCQYDVQQGEwJBVTESMBAGA1UECAwJ\nQXVzdHJhbGlhMQ8wDQYDVQQHDAZTeWRuZXkxEjAQBgNVBAoMCU15T3JnTmFtZTEV\nMBMGA1UEAwwMTXlDb21tb25OYW1lMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\nCgKCAQEA3lTMPmGwYAC86UQWOiXxz5zOPWayTJabxZFyiBkO2kSB2oPD8UuY9Lmn\nSFd3lj1d5d87sODImwBfpAl8OtWkAlQ7Gz94Qx94tkK1h5t44u2GEM/AZZbAoeaw\ngLxoGXnWPIt043ZocMlwZHhuwOLTg0sPA8Nqiw6wwrTw6iPvbZZ9h5MtQTETJ2qa\nBN1sKB/NsHWGfGsIcsiTvDMYfjjOv8w9xKjsVvipsA4MTN6caoJ7Ei1XT61ssp08\nzUT+SCQQERlgO+rnVCsz2XbFEJBYqvV1m+QoU/4Ow9D7toT6tgMrGTIKgefiyUSW\ntoMosHXVxK1O7cEjO5ml1o2yhVn6DQIDAQABoxcwFTATBgNVHREEDDAKgghleGFt\ncGxlMjANBgkqhkiG9w0BAQsFAAOCAQEAO17rOH/w0fZtJ6XL/uVBtcRBX6++7gx0\n0hwQ6Gle/XBC/Rt9kK8bGNlULC7f/RIwe2tAvSR9ecu6e29r9tHl+YD7nrHSUsfX\niio+pTX7NwD3cERqftq8Gigb9Kgsi6zMlJucwZZFoJfZqC7I0QYUCWasuQLfAQPy\nX8YFqVsuylICeKbW3WjN3c+Myfr8FGVnA7iXl28nlCMhqQHBQamG1SXlUjYi3jCv\n+9yPO3fpKeY/KZTfiNVxwYo/JbXorKHjzzObP3gqvHY5ofeOfVsG9dyaTj3oTT1W\nuLvKkUJqCtgFDsx/F3cUp+aBMCFRkbUHDHEl7HJizqutomTZategNg==\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "config/configtls/testdata/client-2.key",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIBAAKCAQEA3lTMPmGwYAC86UQWOiXxz5zOPWayTJabxZFyiBkO2kSB2oPD\n8UuY9LmnSFd3lj1d5d87sODImwBfpAl8OtWkAlQ7Gz94Qx94tkK1h5t44u2GEM/A\nZZbAoeawgLxoGXnWPIt043ZocMlwZHhuwOLTg0sPA8Nqiw6wwrTw6iPvbZZ9h5Mt\nQTETJ2qaBN1sKB/NsHWGfGsIcsiTvDMYfjjOv8w9xKjsVvipsA4MTN6caoJ7Ei1X\nT61ssp08zUT+SCQQERlgO+rnVCsz2XbFEJBYqvV1m+QoU/4Ow9D7toT6tgMrGTIK\ngefiyUSWtoMosHXVxK1O7cEjO5ml1o2yhVn6DQIDAQABAoIBAQDTSe8YUapWch0V\n6fjdpfXaAgEV5SUJGBBNf95CbN3qnDRzv8lU5S0lVdIeM9GYXBWCQdXuUJEUjRRX\nRhRjrWjCNd4+FOFrmNsVCuyNRTlrH6PLEkSbxtqmgh+3GFYt79WjkDyzdnHmzekb\n8j/+2xF7srdAMlRsdreRMnfJbAE8OISfk3aYoLc1Kn4YGKXLegcEAPTrEKOMNaXZ\njGRwHlj1A/HFCh8tHnzdLJOay1aKxyuo82zPV4uVCXcz5Tof21QPjDjW3SaPOq+m\nUHRYGKqFzK7WWBN7xnbMIkup/HpRtx7ZJ3jaTHBAP72foQyfbBJ+1KLawPK/BBET\nwcgBkvHBAoGBAPg/tgA3mjNWkwMeAao+YCOND2nhsXejnSHfA44PPOyDWqxefzDx\nhyf29Rq2dDcJyJV6uyMkyu9XQb0pf+Hh+a4NRXlS6dPzIW0Z1XPoSu9VeXVLPSh0\nCZg82t8UtGMTtGinfDEULM3v0sQWhND1xsX/vFCZvBEXlwAI1zuqFm/1AoGBAOVF\n7GywlCdm4xn4RErA/+HqWPaNAaJAAo4OVgvj/mcu91swGrQoLy6yFEu61mkAr2nn\nH+hYV/WU8nhkR6nStq1eydBKZxzyRIi8ZAmT4CemGX2C/fNF7KSNYqzFsHK/Pymh\nAsMNiykvPFCeG7S2GiDEFO+AKExqy5O16Q4nBYq5AoGAUZ9BDBk8Dh0tAR1glsUj\nfwzmQH4Ah8G37GcTGCZSdcFKktoPH9yJ/83nEP1kgKQq21sbJJb4UnFyH+wBLBfM\nrDmY2ic00odiOikAUbfSy5Zi9PnkBeUBMpjvreF03g6ghrhq0Qg9IwjzV52/1aS5\n0mgfVrD1cPk8oLpHakqmTfECgYEAvvra8MK59oRWwigyws43l7j8+AsHBF8rgadh\nd7AoF01hEF1msREUFGKUU2zD8111wNKcmo8UXeX/f9eQdl6meo4Nr+p6L/uCqR+8\neNnsCzrp2soFveJON9fqDR7zVvIFrCiJw26BsAG/zSuWypYx938+LS5k4xrGjzkl\nc/t/O0kCgYEA0Iwb+qWOCQ4U+wlQjYjhTn3scDZ/EpVEzuh53FEOWY1OtXm8f1qK\nm5I8yj1mOJ5N11cuk7zi0THFJ/wDYSJBshG+05jx2ngk5rWsnnV0jmX6ivOUMrFf\nBbZZjSvzRQlRQbrtwKWluC7yDO0X+YuG4Wbte4i6XNMn5fseWTnwGdY=\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "config/configtls/testdata/server-1.crt",
    "content": "-----BEGIN CERTIFICATE-----\nMIIDVDCCAjygAwIBAgIJANt5fkUlfxydMA0GCSqGSIb3DQEBCwUAMF0xCzAJBgNV\nBAYTAkFVMRIwEAYDVQQIDAlBdXN0cmFsaWExDzANBgNVBAcMBlN5ZG5leTESMBAG\nA1UECgwJTXlPcmdOYW1lMRUwEwYDVQQDDAxNeUNvbW1vbk5hbWUwHhcNMjIwODAz\nMDQxODE4WhcNMzIwNzMxMDQxODE4WjBdMQswCQYDVQQGEwJBVTESMBAGA1UECAwJ\nQXVzdHJhbGlhMQ8wDQYDVQQHDAZTeWRuZXkxEjAQBgNVBAoMCU15T3JnTmFtZTEV\nMBMGA1UEAwwMTXlDb21tb25OYW1lMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\nCgKCAQEAzEc0zUZZhPx+70Et3YVvNv9Ss/EriG3x/Eo7gUr+JH1bi2dJe8bBhaqJ\nj1XXr0qFAahOlj9+/NDS7RON8p1AeXLMzL8mJ162WUU+a4Uus78Md6l0oVKNsVm+\ntUiNT2RVeJWkJtJPRnScdXqf10I498xNNYDfYcl0u/JHX33oekwKPhxn6zHJ6V/b\nZ6BbOsV/MXaB6WRYHRfzxO25hoxELBS6rdlrLdeqy0hlQ3i2UE/Yet3pl1Wi18bh\nBk6kyhoqIfF5tMLNdwwYfHNVNutpv9jUcPFkxLWXVU/FxwjJrBsGVAp4fohUbSN8\nlHj+BtYthyF6vL0gdXxnD01jkYXDVwIDAQABoxcwFTATBgNVHREEDDAKgghleGFt\ncGxlMTANBgkqhkiG9w0BAQsFAAOCAQEAKFflP5DnHjloj3PvSQ1iVKBRTvxwEtKV\n9ObCPK59uUaLZbwZ0QljgfkqxNtL/8FB/LgBdvqHioYx9F4kocpJrwci8a6oU42/\niOpw+D4d6emjPWZDf3WVgmynjyPd5VxK/TO8ly//FjPXNTDpWCs/CqIphHR64/5B\nl1VunN9STqj24WP+Ud+3OxNd1GPu0r45lqO/PDdn7cWWYbNZ67zJdnZPoHQRyL1U\ndZ/jYmS99y66AfG16TFFKNa3bfCS4uRFOlddNs1uXnq40yqsaE/Gv6Ts7X3uND/0\nqExVGHaK2iR7qgBIV8axE3nwZ5RbIxF5LR64I43RI5HaDrRt2e1YAw==\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "config/configtls/testdata/server-1.key",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAzEc0zUZZhPx+70Et3YVvNv9Ss/EriG3x/Eo7gUr+JH1bi2dJ\ne8bBhaqJj1XXr0qFAahOlj9+/NDS7RON8p1AeXLMzL8mJ162WUU+a4Uus78Md6l0\noVKNsVm+tUiNT2RVeJWkJtJPRnScdXqf10I498xNNYDfYcl0u/JHX33oekwKPhxn\n6zHJ6V/bZ6BbOsV/MXaB6WRYHRfzxO25hoxELBS6rdlrLdeqy0hlQ3i2UE/Yet3p\nl1Wi18bhBk6kyhoqIfF5tMLNdwwYfHNVNutpv9jUcPFkxLWXVU/FxwjJrBsGVAp4\nfohUbSN8lHj+BtYthyF6vL0gdXxnD01jkYXDVwIDAQABAoIBAQCxGeLLPPyLcSTT\nZJzQ+sgq1DztSF9HjppG8kyYkV24YP4m48svhmds7ScJn5C4plCd2T8Yv7/mi1zy\nsQtVlcO6By9LK0V2yIQq7P9q1DJjH3U9oSo+WoYBhh7yqA3rEL+RJZsFFTwphxvG\nNiOxyfX9z5/4jNwduTx9XVVHkq8kpo9saJ0FAPCgAlwKTrUwVANm9D0UlJEotat2\nqDLV2WKzJHL3v0MLku2hN1B4pOpOCIzQUNMtxvW9kWSETBBYuEDj0qmUoRQgCJS2\n4dbF5nvbiK3dEdZgp1dGDX2RJY/+Oe3jDlCtvJCLShLnb2g/j8ByKRY7zICrYtIO\nEBxvmvyhAoGBAOqRQl95l8zw8uaBZu8QQ9RnbSt9nk7aYJGMdUABE88Hc8sOtC2U\nayBKd1v/d46Op2otDEYWNQI0DzLdW0LBIjP1qbTiGL2FCknGq4fqbvySy21DcX+b\n+sGd90fNRVG3XJGn63nhoGKGnYvzQGrmm0cVlbQ3KyMzwhsqcUrDv5/ZAoGBAN7x\ndDoIximyp/98CFmCFMtxCMBvNVywmHTTyieeO36A3Mdy300IItUwBtENxMjotXB0\nKc6MX3JrJh8d+z8xsAkmeFnfL9uMjjL0EpZy11eDTi/+fUZ/Bcph/zOYFfPFccK7\ncHLCJyFhnSJNR63QE0Avz6oPcFI7rvjMJnSOsq6vAoGAIznhT9lA1MQyli9EuA4n\nQZSurmNVDN56tiDz0sLWqLajyxDQOjAZzmWgey5oU/5UYfuV5kibeVM8HRVlCSdb\n7ZWtAL8bnAqIuv+c7vJj7IZXCnegaduQ0tbYNe47xMPWoQEoucsKfQFeU5AaUnOD\nSi+RpdjLH6Q8ODwte17ePjECgYA5G/j99MluXQmT9J3e7+eLxcTMJrCwsbwcETSz\nuWDcIv5rSQ3SmcbyfX8BhllmbdYsnFUpR+QbVz9IsVFu+rdxYJ1ryDRmNTcn7kXk\nrD5leIlK2hIVQOymzzukZ80XyPg/PeysOPf1ISAzbUBzUd3cj2LO2W2YYxmLOiCP\nsw4qmQKBgCR0EpTfcm+wzQ3LWAPbsA6DsqvDtYfQumfg1uFglHrJXHtPZj9Mp0om\nZdRWL4vOmI/o6lfmHYdqHMnwyMHJU1JkcBnnhbQo5cGJZ17d580FZ9oVPVqqVQvR\nOhjWcqU7n+0ZvSWakHAvbgPSCeQpA19x0WLDR1WUbKszHIoQwzwe\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "config/configtls/testdata/server-2.crt",
    "content": "-----BEGIN CERTIFICATE-----\nMIIDVDCCAjygAwIBAgIJANt5fkUlfxyfMA0GCSqGSIb3DQEBCwUAMF0xCzAJBgNV\nBAYTAkFVMRIwEAYDVQQIDAlBdXN0cmFsaWExDzANBgNVBAcMBlN5ZG5leTESMBAG\nA1UECgwJTXlPcmdOYW1lMRUwEwYDVQQDDAxNeUNvbW1vbk5hbWUwHhcNMjIwODAz\nMDQxODI3WhcNMzIwNzMxMDQxODI3WjBdMQswCQYDVQQGEwJBVTESMBAGA1UECAwJ\nQXVzdHJhbGlhMQ8wDQYDVQQHDAZTeWRuZXkxEjAQBgNVBAoMCU15T3JnTmFtZTEV\nMBMGA1UEAwwMTXlDb21tb25OYW1lMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\nCgKCAQEA2bdn2gv8i6J0gNHilYDFVTwYUgNWJNe23sdxyuAbSoocir61LT1HBtWP\nm/Slfw8xcGYomiu5iIPNWF6KGDpUsafawkxZFySNCWTXlU68Vk7iyJLGQ3e1uhFM\nlOsRvrRB65OUsdyXF1e4+T1KMGiz2yEWIDxpe1o4uchenVM1WOddlZMIPB1E3UzR\nDjLJUXfihWeoQwWisfBJw6bHPne1sj7OmS0feUJUza9i8bXe8TgYLkLyo5IUNQpf\nEkpAu+7DoOdRfURApz4TpeY5RkQ5ztSC8LnXQ0ZR4C0D8i8DdOxW1Sj2HTkjY9KO\nexPnP12UgVeo9KsdtEqIF15n3TDxzQIDAQABoxcwFTATBgNVHREEDDAKgghleGFt\ncGxlMjANBgkqhkiG9w0BAQsFAAOCAQEAq05+tW+c6jg/Kes9RPpnGKgm73COu+qR\nT/n9D+jeqizBszQbjvwwQWzyQEIeN5hVf0DqMa/GJPvtVu+Im4FeW9cCc/2UccvK\nKsRagdLJUBih9KkY4Z+uzVcPUt6xYFQHgKlR7aR7uSoUicgw8Xtg84px4BDrKlJJ\nRoPAI6+RdauRUs9XqYG4bU1rr1pbhxNMMlNYAvLekgT/5h39uxuaqgkmWZXRRQBP\nrbddw+wPPhYJ0X6lzs5LbtAa1oiaLgQxWnrmKWAgEQqfr8apWBuC3CWg9GyXH5OK\n5AgjxKCQJHc5WdUUxbcNYCMBubEBxGp9FTwfvYOF6sFhrC8+1kTrHg==\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "config/configtls/testdata/server-2.key",
    "content": "-----BEGIN RSA PRIVATE KEY-----\nMIIEpgIBAAKCAQEA2bdn2gv8i6J0gNHilYDFVTwYUgNWJNe23sdxyuAbSoocir61\nLT1HBtWPm/Slfw8xcGYomiu5iIPNWF6KGDpUsafawkxZFySNCWTXlU68Vk7iyJLG\nQ3e1uhFMlOsRvrRB65OUsdyXF1e4+T1KMGiz2yEWIDxpe1o4uchenVM1WOddlZMI\nPB1E3UzRDjLJUXfihWeoQwWisfBJw6bHPne1sj7OmS0feUJUza9i8bXe8TgYLkLy\no5IUNQpfEkpAu+7DoOdRfURApz4TpeY5RkQ5ztSC8LnXQ0ZR4C0D8i8DdOxW1Sj2\nHTkjY9KOexPnP12UgVeo9KsdtEqIF15n3TDxzQIDAQABAoIBAQCoCDKiCoBG8QJD\n7jmXs4QZ7cDDg4m387lTJdGAiAjoNcIjn17L5LBt6OPmtSIJ95rrqh0KKFcQstEI\ntCaW3mZBm1Buh2h3QSGNL4Rn2xXm8wl7TjSxG7JpQjK9+NOAQTVjcUrhH2SJgo3j\n51bcF+NAa7/c72Nl7dM8KBZGDFNvIe3uhFk67aBZ/A3Qto7ZYTz9hrowc08iehhm\ni9fZ0T09UPw3Mplpx5bUx8kSZQLe15No7B5VJ31J4+64ufG9iypEW62bueROitgz\nshBTifEg/9rhZbt2wDIC31oZ2jXORSFLZPKjji5ygSm7ExVvaTfgsn+XMXP4JXVt\nv5F0gDthAoGBAPPk3y9ZAmTTecAiFL01FQdpEpd4qOQQenGBhhuOxaP7ZQRjxGDK\nyWV7taJyAVhdXAhKLMpqsE6wLMskRp8FZwkFZc+1Wt5QE4XfNmme2s/tSltQ2uG+\n7bMeGys5yhUjsWWuZ/57/1xlyUmMpYTPG66CQuqg4qGn3SFg2aiqZ5GZAoGBAOSF\n5gzo4Wn/jFeRTXUqkn1smBPBZC5/zqyfX6zlzJrPFm93NJ8jZqp53qzixcCs+yls\nEWIUkFCFy7GN+tU+Wkz4JWs2BTXcThraoa4hciAmYIHCB+ZTbncnaHbBP/C/0pZp\nZ0HvhKR01FAXEDfxN+A0807LoHcFDlv7cRvBzqpVAoGBAJlkPsJGluzW3GHsjWKa\neglZGipN5trZSkkND01RtBf4SoZCQQYnRBchgRET5qiuvu0vyY/dHdm/j8yLmib1\nfOH9lRTXmLjtX/n4cv5mvHO9Z+Car67/J/xZWPkMtX4qHq42zI0Pa4GvOrOZU5h9\nsYlFv9RVL3RAYSFXCk28LrsxAoGBAMrBLoq3uQAWF0u+hM329sBHsGqexKcpCJNK\nWFYMEcws/wfo6QxlGXsZ5ALatYAtOi7XTlkKS7zV6RNhGHNI/k+aP4DvDhJqo/XZ\nk2fvDtYNlsSqBd5KmhEoKtxqu7N8Tnjbjh0HSVWsvo9M1zv7ToskD9gSfQ38s2/T\nGNj6zMV9AoGBAJAdinxXTWMWLCWyZREPolRiRMoahYhPYuHWHU0LiWJ3VidGo8Uv\nhaTOyhyx3zHqRtQKBTHdQLcGa2NGwdeKWmctCn7v593ykKIwde66xu0RFNbwrxbl\nD2m1zpim+nKj4YQqmSBg+Y7FixLgywKgE2djmUTHFl8Fa3d1xw9mXUS5\n-----END RSA PRIVATE KEY-----\n"
  },
  {
    "path": "config/configtls/testdata/testCA-bad.txt",
    "content": "-----BEGIN CERTIFICATE-----\nbad certificate\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "config/configtls/tpm.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configtls // import \"go.opentelemetry.io/collector/config/configtls\"\n\nimport (\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"encoding/pem\"\n\t\"fmt\"\n\n\ttpmkeyfile \"github.com/foxboron/go-tpm-keyfiles\"\n\t\"github.com/google/go-tpm/tpm2/transport\"\n)\n\n// TPMConfig defines trusted platform module configuration for storing TLS keys.\ntype TPMConfig struct {\n\tEnabled bool `mapstructure:\"enabled\"`\n\t// The path to the TPM device or Unix domain socket.\n\t// For instance /dev/tpm0 or /dev/tpmrm0.\n\tPath      string `mapstructure:\"path\"`\n\tOwnerAuth string `mapstructure:\"owner_auth\"`\n\tAuth      string `mapstructure:\"auth\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\nfunc (c TPMConfig) tpmCertificate(keyPem, certPem []byte, openTPM func() (transport.TPMCloser, error)) (tls.Certificate, error) {\n\ttpm, err := openTPM()\n\tif err != nil {\n\t\treturn tls.Certificate{}, err\n\t}\n\n\ttpmKey, err := tpmkeyfile.Decode(keyPem)\n\tif err != nil {\n\t\treturn tls.Certificate{}, fmt.Errorf(\"failed to load TPM key: %w\", err)\n\t}\n\n\ttpmSigner, err := tpmKey.Signer(tpm, []byte(c.OwnerAuth), []byte(c.Auth))\n\tif err != nil {\n\t\treturn tls.Certificate{}, fmt.Errorf(\"failed to load TPM signer: %w\", err)\n\t}\n\n\tcertDER, _ := pem.Decode(certPem)\n\tx509Cert, err := x509.ParseCertificate(certDER.Bytes)\n\tif err != nil {\n\t\treturn tls.Certificate{}, fmt.Errorf(\"failed to parse certificate: %w\", err)\n\t}\n\treturn tls.Certificate{\n\t\tCertificate: [][]byte{\n\t\t\tx509Cert.Raw,\n\t\t},\n\t\tLeaf:       x509Cert,\n\t\tPrivateKey: tpmSigner,\n\t}, nil\n}\n"
  },
  {
    "path": "config/configtls/tpm_open_linux.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build linux\n\npackage configtls // import \"go.opentelemetry.io/collector/config/configtls\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"github.com/google/go-tpm/tpm2/transport\"\n\t\"github.com/google/go-tpm/tpmutil\"\n)\n\n// for testing\nvar tpmSimulator transport.TPMCloser\n\nfunc openTPM(path string) func() (transport.TPMCloser, error) {\n\treturn func() (transport.TPMCloser, error) {\n\t\tif path == \"\" {\n\t\t\treturn nil, errors.New(\"TPM path is not set\")\n\t\t}\n\t\tif path == \"simulator\" {\n\t\t\treturn tpmSimulator, nil\n\t\t}\n\n\t\ttpm, err := tpmutil.OpenTPM(path)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to open TPM (%s): %w\", path, err)\n\t\t}\n\t\treturn transport.FromReadWriteCloser(tpm), nil\n\t}\n}\n"
  },
  {
    "path": "config/configtls/tpm_open_others.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build !linux && !windows\n\npackage configtls // import \"go.opentelemetry.io/collector/config/configtls\"\n\nimport (\n\t\"errors\"\n\n\t\"github.com/google/go-tpm/tpm2/transport\"\n)\n\n// for testing\nvar tpmSimulator transport.TPMCloser\n\nfunc openTPM(path string) func() (transport.TPMCloser, error) {\n\treturn func() (transport.TPMCloser, error) {\n\t\tif path == \"simulator\" {\n\t\t\treturn tpmSimulator, nil\n\t\t}\n\t\treturn nil, errors.New(\"TPM is not supported on this platform\")\n\t}\n}\n"
  },
  {
    "path": "config/configtls/tpm_open_windows.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build windows\n\npackage configtls // import \"go.opentelemetry.io/collector/config/configtls\"\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/google/go-tpm/tpm2/transport\"\n\t\"github.com/google/go-tpm/tpmutil\"\n)\n\nfunc openTPM(_ string) func() (transport.TPMCloser, error) {\n\treturn func() (transport.TPMCloser, error) {\n\t\ttpm, err := tpmutil.OpenTPM()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to open TPM: %w\", err)\n\t\t}\n\t\treturn transport.FromReadWriteCloser(tpm), nil\n\t}\n}\n"
  },
  {
    "path": "config/configtls/tpm_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Don't run this test on Windows, as it requires a TPM simulator which depends on openssl headers.\n//go:build !windows && !darwin\n\npackage configtls // import \"go.opentelemetry.io/collector/config/configtls\"\n\nimport (\n\t\"bytes\"\n\t\"crypto\"\n\t\"crypto/rand\"\n\t\"crypto/x509\"\n\t\"crypto/x509/pkix\"\n\t\"encoding/pem\"\n\t\"errors\"\n\t\"io\"\n\t\"math/big\"\n\t\"net\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\tkeyfile \"github.com/foxboron/go-tpm-keyfiles\"\n\t\"github.com/google/go-tpm/tpm2\"\n\t\"github.com/google/go-tpm/tpm2/transport\"\n\t\"github.com/google/go-tpm/tpm2/transport/simulator\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc TestTPM_loadCertificate(t *testing.T) {\n\ttestutil.SkipIfFIPSOnly(t, \"use of CFB is not allowed in FIPS 140-only mode\")\n\ttpm, err := simulator.OpenSimulator()\n\trequire.NoError(t, err)\n\tdefer tpm.Close()\n\ttpmSimulator = tpm\n\n\t// create a TPM key and certificate\n\t// the TPM key will be stored in the simulator\n\ttpmKey, cert := createTPMKeyCert(t, tpm)\n\n\ttempFileKey, err := os.CreateTemp(t.TempDir(), \"tpmkey.key\")\n\trequire.NoError(t, err)\n\t_, err = tempFileKey.Write(tpmKey)\n\trequire.NoError(t, err)\n\ttempFileCrt, err := os.CreateTemp(t.TempDir(), \"tpmcert.crt\")\n\trequire.NoError(t, err)\n\t_, err = tempFileCrt.Write(cert)\n\trequire.NoError(t, err)\n\tdefer func() {\n\t\ttempFileKey.Close()\n\t\tos.Remove(tempFileKey.Name())\n\t\ttempFileCrt.Close()\n\t\tos.Remove(tempFileCrt.Name())\n\t}()\n\n\ttlsCfg := Config{\n\t\tCertFile: tempFileCrt.Name(),\n\t\tKeyFile:  tempFileKey.Name(),\n\t\tTPMConfig: TPMConfig{\n\t\t\tEnabled: true,\n\t\t\tPath:    \"simulator\",\n\t\t},\n\t}\n\ttlsCertificate, err := tlsCfg.loadCertificate()\n\trequire.NoError(t, err)\n\trequire.NotNil(t, tlsCertificate)\n\n\th := crypto.SHA256.New()\n\th.Write([]byte(\"message\"))\n\tb := h.Sum(nil)\n\n\t// this is delegated to the TPM\n\tsigner := tlsCertificate.PrivateKey.(crypto.Signer)\n\tsignature, _ := signer.Sign(io.Reader(nil), b, crypto.SHA256)\n\n\t// load the key again to get access to verify function\n\tloadedTPMKey, err := keyfile.Decode(tpmKey)\n\trequire.NoError(t, err)\n\tok, err := loadedTPMKey.Verify(crypto.SHA256, b, signature)\n\trequire.NoError(t, err)\n\tassert.True(t, ok)\n}\n\nfunc TestTPM_loadCertificate_error(t *testing.T) {\n\ttlsCfg := Config{\n\t\tCertPem: \"invalid\",\n\t\tKeyPem:  \"invalid\",\n\t\tTPMConfig: TPMConfig{\n\t\t\tEnabled: true,\n\t\t\tPath:    \"simulator\",\n\t\t},\n\t}\n\ttlsCertificate, err := tlsCfg.loadCertificate()\n\tassert.Equal(t, \"failed to load private key from TPM: failed to load TPM key: not an armored key\", err.Error())\n\trequire.NotNil(t, tlsCertificate)\n}\n\nfunc TestTPM_tpmCertificate_errors(t *testing.T) {\n\ttestutil.SkipIfFIPSOnly(t, \"use of CFB is not allowed in FIPS 140-only mode\")\n\ttpm, err := simulator.OpenSimulator()\n\trequire.NoError(t, err)\n\tdefer tpm.Close()\n\n\topenTPMFunc := func() (transport.TPMCloser, error) {\n\t\treturn tpm, nil\n\t}\n\n\tkey, _ := createTPMKeyCert(t, tpm)\n\n\tinvalidCert := []byte(`-----BEGIN CERTIFICATE-----\nVGhpcyBpcyBub3QgYSBjZXJ0aWZpY2F0ZS4=\n-----END CERTIFICATE-----`)\n\n\ttests := []struct {\n\t\tname    string\n\t\tkey     string\n\t\topenTPM func() (transport.TPMCloser, error)\n\t\tcert    string\n\t\terr     string\n\t}{\n\t\t{\n\t\t\tname:    \"invalid key\",\n\t\t\tkey:     \"invalid\",\n\t\t\topenTPM: openTPMFunc,\n\t\t\terr:     \"failed to load TPM key: not an armored key\",\n\t\t},\n\t\t{\n\t\t\tname:    \"invalid cert\",\n\t\t\tkey:     string(key),\n\t\t\tcert:    string(invalidCert),\n\t\t\topenTPM: openTPMFunc,\n\t\t\terr:     \"failed to parse certificate: x509: malformed certificate\",\n\t\t},\n\t\t{\n\t\t\tname: \"failed to open TPM\",\n\t\t\topenTPM: func() (transport.TPMCloser, error) {\n\t\t\t\treturn nil, errors.New(\"failed to open TPM\")\n\t\t\t},\n\t\t\terr: \"failed to open TPM\",\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\ttpmCfg := &TPMConfig{}\n\t\t\t_, err = tpmCfg.tpmCertificate([]byte(test.key), []byte(test.cert), test.openTPM)\n\t\t\tassert.EqualError(t, err, test.err)\n\t\t})\n\t}\n}\n\nfunc TestTPM_open(t *testing.T) {\n\tsocketPath := filepath.Join(t.TempDir(), \"app.sock\")\n\tlistener, err := net.Listen(\"unix\", socketPath)\n\trequire.NoError(t, err)\n\tdefer listener.Close()\n\n\ttests := []struct {\n\t\tpath string\n\t\terr  string\n\t}{\n\t\t{\n\t\t\tpath: \"\",\n\t\t\terr:  \"TPM path is not set\",\n\t\t},\n\t\t{\n\t\t\tpath: \"/foo\",\n\t\t\terr:  \"failed to open TPM (/foo): stat /foo: no such file or directory\",\n\t\t},\n\t\t{\n\t\t\tpath: socketPath,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.path, func(t *testing.T) {\n\t\t\ttpm, openErr := openTPM(test.path)()\n\t\t\tif test.err != \"\" {\n\t\t\t\trequire.Nil(t, tpm)\n\t\t\t\tassert.Equal(t, test.err, openErr.Error())\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, openErr)\n\t\t\t\trequire.NotNil(t, tpm)\n\t\t\t\ttpm.Close()\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc createTPMKeyCert(t *testing.T, tpm transport.TPMCloser) ([]byte, []byte) {\n\ttpmKey, err := keyfile.NewLoadableKey(tpm, tpm2.TPMAlgECC, 256, []byte(\"\"))\n\trequire.NoError(t, err)\n\ttpmKeySigner, err := tpmKey.Signer(tpm, []byte(\"\"), []byte(\"\"))\n\trequire.NoError(t, err)\n\n\tserialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) // 128-bit random number\n\tserialNumber, err := rand.Int(rand.Reader, serialNumberLimit)\n\trequire.NoError(t, err)\n\n\ttemplate := x509.Certificate{\n\t\tSerialNumber: serialNumber,\n\t\tSubject: pkix.Name{\n\t\t\tOrganization: []string{\"OpenTelemetry\"},\n\t\t\tCommonName:   \"localhost\",\n\t\t},\n\t\tNotBefore: time.Now(),\n\t\tNotAfter:  time.Now().Add(366 * 24 * time.Hour),\n\n\t\tKeyUsage:              x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,\n\t\tExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},\n\t\tBasicConstraintsValid: true,\n\t\tDNSNames:              []string{\"localhost\"},\n\t\tIPAddresses: []net.IP{\n\t\t\tnet.ParseIP(\"127.0.0.1\"),\n\t\t\tnet.ParseIP(\"::1\"),\n\t\t},\n\t}\n\n\ttpmPublicKey, err := tpmKey.PublicKey()\n\trequire.NoError(t, err)\n\tderBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, tpmPublicKey, tpmKeySigner)\n\trequire.NoError(t, err)\n\tcertBuffer := &bytes.Buffer{}\n\terr = pem.Encode(certBuffer, &pem.Block{Type: \"CERTIFICATE\", Bytes: derBytes})\n\trequire.NoError(t, err)\n\n\treturn tpmKey.Bytes(), certBuffer.Bytes()\n}\n"
  },
  {
    "path": "confmap/Makefile",
    "content": "include ../Makefile.Common\n"
  },
  {
    "path": "confmap/README.md",
    "content": "# Confmap\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [stable]: logs, metrics, traces   |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Apkg%2Fconfmap%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Apkg%2Fconfmap) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Apkg%2Fconfmap%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Apkg%2Fconfmap) |\n| [Code Owners](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/CONTRIBUTING.md#becoming-a-code-owner)    | [@mx-psi](https://www.github.com/mx-psi), [@evan-bradley](https://www.github.com/evan-bradley) |\n\n[stable]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stable\n<!-- end autogenerated section -->\n\n# High Level Design\n\n## Conf\n\nThe [Conf](confmap.go) represents the raw configuration for a service (e.g. OpenTelemetry Collector).\n\n## Provider\n\nThe [Provider](provider.go) provides configuration, and allows to watch/monitor for changes. Any `Provider`\nhas a `<scheme>` associated with it, and will provide configs for `configURI` that follow the \"<scheme>:<opaque_data>\" format.\nThis format is compatible with the URI definition (see [RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986)).\nThe `<scheme>` MUST be always included in the `configURI`. The scheme for any `Provider` MUST be at least 2\ncharacters long to avoid conflicting with a driver-letter identifier as specified in\n[file URI syntax](https://datatracker.ietf.org/doc/html/rfc8089#section-2).\n\n## Converter\n\nThe [Converter](converter.go) allows implementing conversion logic for the provided configuration. One of the most\ncommon use-case is to migrate/transform the configuration after a backwards incompatible change.\n\n## Resolver\n\nThe `Resolver` handles the use of multiple [Providers](#provider) and [Converters](#converter)\nsimplifying configuration parsing, monitoring for updates, and the overall life-cycle of the used config providers.\nThe `Resolver` provides two main functionalities: [Configuration Resolving](#configuration-resolving) and\n[Watching for Updates](#watching-for-updates).\n\n### Configuration Resolving\n\nThe `Resolver` receives as input a set of `Providers`, a list of `Converters`, and a list of configuration identifier\n`configURI` that will be used to generate the resulting, or effective, configuration in the form of a `Conf`,\nthat can be used by code that is oblivious to the usage of `Providers` and `Converters`.\n\n`Providers` are used to provide an entire configuration when the `configURI` is given directly to the `Resolver`,\nor an individual value (partial configuration) when the `configURI` is embedded into the `Conf` as a values using\nthe syntax `${configURI}`.\n\n**Limitation:**\n- When embedding a `${configURI}` the uri cannot contain dollar sign (\"$\") character unless it embeds another uri.\n- The number of URIs is limited to 100.\n\n```terminal\n              Resolver                   Provider\n   Resolve       │                          │\n────────────────►│                          │\n                 │                          │\n              ┌─ │        Retrieve          │\n              │  ├─────────────────────────►│\n              │  │          Conf            │\n              │  │◄─────────────────────────┤\n  foreach     │  │                          │\n  configURI   │  ├───┐                      │\n              │  │   │Merge                 │\n              │  │◄──┘                      │\n              └─ │                          │\n              ┌─ │        Retrieve          │\n              │  ├─────────────────────────►│\n              │  │    Partial Conf Value    │\n              │  │◄─────────────────────────┤\n  foreach     │  │                          │\n  embedded    │  │                          │\n  configURI   │  ├───┐                      │\n              │  │   │Replace               │\n              │  │◄──┘                      │\n              └─ │                          │\n                 │            Converter     │\n              ┌─ │     Convert    │         │\n              │  ├───────────────►│         │\n    foreach   │  │                │         │\n   Converter  │  │◄───────────────┤         │\n              └─ │                          │\n                 │                          │\n◄────────────────┤                          │\n```\n\nThe `Resolve` method proceeds in the following steps:\n\n1. Start with an empty \"result\" of `Conf` type.\n2. For each config URI retrieves individual configurations, and merges it into the \"result\".\n3. For each embedded config URI retrieves individual value, and replaces it into the \"result\".\n4. For each \"Converter\", call \"Convert\" for the \"result\".\n5. Return the \"result\", aka effective, configuration.\n\n#### (Experimental) Append merging strategy for lists\n\nYou can opt-in to experimentally combine slices instead of discarding the existing ones by enabling the `confmap.enableMergeAppendOption` feature flag. Lists are appended in the order in which they appear in their configuration sources.\nThis will **not** become the default in the future, we are still deciding how this should be configured and want your feedback on [this issue](https://github.com/open-telemetry/opentelemetry-collector/issues/8754).\n\n##### Example\nConsider the following configs,\n\n```yaml\n# main.yaml\nreceivers:\n  otlp/in:\nprocessors:\n  attributes/example:\n    actions:\n      - key: key\n        value: \"value\"\n        action: upsert\n\nexporters:\n  otlp/out:\nextensions:\n  file_storage:\n\nservice:\n  pipelines:\n    traces:\n      receivers: [ otlp/in ]\n      processors: [ attributes/example ]\n      exporters: [ otlp/out ]\n  extensions: [ file_storage ]\n```\n\n\n```yaml\n# extra_extension.yaml\nextensions:\n  healthcheckv2:\n\nservice:\n  extensions: [ healthcheckv2 ]\n  pipelines:\n    traces:\n```\n\nIf you run the Collector with following command,\n```\notelcol --config=main.yaml --config=extra_extension.yaml --feature-gates=confmap.enableMergeAppendOption\n```\nthen the final configuration after config resolution will look like following:\n\n```yaml\n# main.yaml\nreceivers:\n  otlp/in:\nprocessors:\n  attributes/example:\n    actions:\n      - key: key\n        value: \"value\"\n        action: upsert\nexporters:\n  otlp/out:\nextensions:\n  file_storage:\n  healthcheckv2:\n\nservice:\n  pipelines:\n    traces:\n      receivers: [ otlp/in ]\n      processors: [ attributes/example ]\n      exporters: [ otlp/out ]\n  extensions: [ file_storage, healthcheckv2 ]\n```\n\nNotice that the `service::extensions` list is a combination of both configurations. By default, the value of the last configuration source passed, `extra_extension`, would be used, so the extensions list would be: `service::extensions: [healthcheckv2]`.\n\n> [!NOTE]\n> By enabling this feature gate, all the lists in the given configuration will be merged. \n\n### Watching for Updates\nAfter the configuration was processed, the `Resolver` can be used as a single point to watch for updates in the\nconfiguration retrieved via the `Provider` used to retrieve the “initial” configuration and to generate the “effective” one.\n\n```terminal\n         Resolver              Provider\n            │                     │\n   Watch    │                     │\n───────────►│                     │\n            │                     │\n            .                     .\n            .                     .\n            .                     .\n            │      onChange       │\n            │◄────────────────────┤\n◄───────────┤                     │\n\n```\n\nThe `Resolver` does that by passing an `onChange` func to each `Provider.Retrieve` call and capturing all watch events.\n\nCalling the `onChange` func from a provider triggers the collector to re-resolve new configuration:\n\n```terminal\n         Resolver              Provider\n            │                     │\n   Watch    │                     │\n───────────►│                     │\n            │                     │\n            .                     .\n            .                     .\n            .                     .\n            │      onChange       │\n            │◄────────────────────┤\n◄───────────┤                     │\n            |                     |\n  Resolve   │                     │\n───────────►│                     │\n            │                     │\n            │      Retrieve       │\n            ├────────────────────►│\n            │        Conf         │\n            │◄────────────────────┤\n◄───────────┤                     │\n```\n\nAn example of a `Provider` with an `onChange` func that periodically gets notified can be found in provider_test.go as UpdatingProvider\n\n## Troubleshooting\n\n### Null Maps\n\nDue to how our underlying merge library, [koanf](https://github.com/knadh/koanf), behaves, configuration resolution\nwill treat configuration such as\n\n```yaml\nprocessors:\n```\n\nas null, which is a valid value. As a result if you have configuration `A`:\n\n```yaml\nreceivers:\n    nop:\n\nprocessors:\n    nop:\n\nexporters:\n    nop:\n\nextensions:\n    nop:\n\nservice:\n    extensions: [nop]\n    pipelines:\n        traces:\n            receivers: [nop]\n            processors: [nop]\n            exporters: [nop]\n```\n\nand configuration `B`:\n\n```yaml\nprocessors:\n```\n\nand do `./otelcorecol --config A.yaml --config B.yaml`\n\nThe result will be an error:\n\n```\nError: invalid configuration: service::pipelines::traces: references processor \"nop\" which is not configured\n2024/06/10 14:37:14 collector server run finished with error: invalid configuration: service::pipelines::traces: references processor \"nop\" which is not configured\n```\n\nThis happens because configuration `B` sets `processors` to null, removing the `nop` processor defined in configuration `A`,\nso the `nop` processor referenced in configuration `A`'s pipeline no longer exists.\n\nThis situation can be remedied 2 ways:\n1. Use `{}` when you want to represent an empty map, such as `processors: {}` instead of `processors:`.\n2. Omit configuration like `processors:` from your configuration.\n"
  },
  {
    "path": "confmap/confmap.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\npackage confmap // import \"go.opentelemetry.io/collector/confmap\"\n\nimport (\n\t\"go.opentelemetry.io/collector/confmap/internal\"\n)\n\n// KeyDelimiter is used as the default key delimiter in the default koanf instance.\nvar KeyDelimiter = internal.KeyDelimiter\n\n// MapstructureTag is the struct field tag used to record marshaling/unmarshaling settings.\n// See https://pkg.go.dev/github.com/go-viper/mapstructure/v2 for supported values.\nvar MapstructureTag = internal.MapstructureTag\n\n// New creates a new empty confmap.Conf instance.\nfunc New() *Conf {\n\treturn internal.New()\n}\n\n// NewFromStringMap creates a confmap.Conf from a map[string]any.\nfunc NewFromStringMap(data map[string]any) *Conf {\n\treturn internal.NewFromStringMap(data)\n}\n\n// Conf represents the raw configuration map for the OpenTelemetry Collector.\n// The confmap.Conf can be unmarshalled into the Collector's config using the \"service\" package.\ntype Conf = internal.Conf\n\ntype UnmarshalOption = internal.UnmarshalOption\n\n// WithIgnoreUnused sets an option to ignore errors if existing\n// keys in the original Conf were unused in the decoding process\n// (extra keys).\nfunc WithIgnoreUnused() UnmarshalOption {\n\treturn internal.WithIgnoreUnused()\n}\n\ntype MarshalOption = internal.MarshalOption\n\n// Unmarshaler interface may be implemented by types to customize their behavior when being unmarshaled from a Conf.\n// Only types with struct or pointer to struct kind are supported.\ntype Unmarshaler = internal.Unmarshaler\n\n// Marshaler defines an optional interface for custom configuration marshaling.\n// A configuration struct can implement this interface to override the default\n// marshaling.\ntype Marshaler = internal.Marshaler\n"
  },
  {
    "path": "confmap/confmaptest/configtest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confmaptest // import \"go.opentelemetry.io/collector/confmap/confmaptest\"\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"regexp\"\n\n\t\"go.yaml.in/yaml/v3\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\n// LoadConf loads a confmap.Conf from file, and does NOT validate the configuration.\nfunc LoadConf(fileName string) (*confmap.Conf, error) {\n\t// Clean the path before using it.\n\tcontent, err := os.ReadFile(filepath.Clean(fileName))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to read the file %v: %w\", fileName, err)\n\t}\n\n\tvar rawConf map[string]any\n\tif err := yaml.Unmarshal(content, &rawConf); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn confmap.NewFromStringMap(rawConf), nil\n}\n\nvar schemeValidator = regexp.MustCompile(\"^[A-Za-z][A-Za-z0-9+.-]+$\")\n\n// ValidateProviderScheme enforces that given confmap.Provider.Scheme() object is following the restriction defined by the collector:\n//   - Checks that the scheme name follows the restrictions defined https://datatracker.ietf.org/doc/html/rfc3986#section-3.1\n//   - Checks that the scheme name has at leas two characters per the confmap.Provider.Scheme() comment.\nfunc ValidateProviderScheme(p confmap.Provider) error {\n\tscheme := p.Scheme()\n\tif len(scheme) < 2 {\n\t\treturn fmt.Errorf(\"scheme must be at least 2 characters long: %q\", scheme)\n\t}\n\n\tif !schemeValidator.MatchString(scheme) {\n\t\treturn fmt.Errorf(\"scheme names consist of a sequence of characters beginning with a letter and followed by any combination of letters, digits, \\\"+\\\", \\\".\\\", or \\\"-\\\": %q\", scheme)\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "confmap/confmaptest/configtest_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confmaptest\n\nimport (\n\t\"context\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\nfunc TestLoadConfFileNotFound(t *testing.T) {\n\t_, err := LoadConf(\"file/not/found\")\n\tassert.Error(t, err)\n}\n\nfunc TestLoadConfInvalidYAML(t *testing.T) {\n\t_, err := LoadConf(filepath.Join(\"testdata\", \"invalid.yaml\"))\n\trequire.Error(t, err)\n}\n\nfunc TestLoadConf(t *testing.T) {\n\tcfg, err := LoadConf(filepath.Join(\"testdata\", \"simple.yaml\"))\n\trequire.NoError(t, err)\n\tassert.Equal(t, map[string]any{\"floating\": 3.14}, cfg.ToStringMap())\n}\n\nfunc TestToStringMapSanitizeEmptySlice(t *testing.T) {\n\tcfg, err := LoadConf(filepath.Join(\"testdata\", \"empty-slice.yaml\"))\n\trequire.NoError(t, err)\n\tassert.Equal(t, map[string]any{\"slice\": []any{}}, cfg.ToStringMap())\n}\n\nfunc TestValidateProviderScheme(t *testing.T) {\n\tassert.NoError(t, ValidateProviderScheme(&schemeProvider{scheme: \"file\"}))\n\tassert.NoError(t, ValidateProviderScheme(&schemeProvider{scheme: \"s3\"}))\n\tassert.NoError(t, ValidateProviderScheme(&schemeProvider{scheme: \"a.l-l+\"}))\n\t// Too short.\n\trequire.Error(t, ValidateProviderScheme(&schemeProvider{scheme: \"a\"}))\n\t// Invalid first character.\n\trequire.Error(t, ValidateProviderScheme(&schemeProvider{scheme: \"3s\"}))\n\t// Invalid underscore character.\n\tassert.Error(t, ValidateProviderScheme(&schemeProvider{scheme: \"all_\"}))\n}\n\ntype schemeProvider struct {\n\tscheme string\n}\n\nfunc (s schemeProvider) Retrieve(context.Context, string, confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\treturn nil, nil\n}\n\nfunc (s schemeProvider) Scheme() string {\n\treturn s.scheme\n}\n\nfunc (s schemeProvider) Shutdown(context.Context) error {\n\treturn nil\n}\n"
  },
  {
    "path": "confmap/confmaptest/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package confmaptest helps loading confmap.Conf to test packages implementing using the configuration.\npackage confmaptest // import \"go.opentelemetry.io/collector/confmap/confmaptest\"\n"
  },
  {
    "path": "confmap/confmaptest/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confmaptest\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "confmap/confmaptest/provider_settings.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confmaptest // import \"go.opentelemetry.io/collector/confmap/confmaptest\"\n\nimport (\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\nfunc NewNopProviderSettings() confmap.ProviderSettings {\n\treturn confmap.ProviderSettings{Logger: zap.NewNop()}\n}\n"
  },
  {
    "path": "confmap/confmaptest/testdata/empty-slice.yaml",
    "content": "slice: [] # empty slices are sanitized to nil in ToStringMap\n"
  },
  {
    "path": "confmap/confmaptest/testdata/invalid.yaml",
    "content": "[invalid,"
  },
  {
    "path": "confmap/confmaptest/testdata/simple.yaml",
    "content": "floating:  3.14\n"
  },
  {
    "path": "confmap/converter.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confmap // import \"go.opentelemetry.io/collector/confmap\"\n\nimport (\n\t\"context\"\n\n\t\"go.uber.org/zap\"\n)\n\n// ConverterSettings are the settings to initialize a Converter.\ntype ConverterSettings struct {\n\t// Logger is a zap.Logger that will be passed to Converters.\n\t// Converters should be able to rely on the Logger being non-nil;\n\t// when instantiating a Converter with a ConverterFactory,\n\t// nil Logger references should be replaced with a no-op Logger.\n\tLogger *zap.Logger\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// ConverterFactory defines a factory that can be used to instantiate\n// new instances of a Converter.\ntype ConverterFactory = moduleFactory[Converter, ConverterSettings]\n\n// CreateConverterFunc is a function that creates a Converter instance.\ntype CreateConverterFunc = createConfmapFunc[Converter, ConverterSettings]\n\n// NewConverterFactory can be used to create a ConverterFactory.\nfunc NewConverterFactory(f CreateConverterFunc) ConverterFactory {\n\treturn newConfmapModuleFactory(f)\n}\n\n// Converter is a converter interface for the confmap.Conf that allows distributions\n// (in the future components as well) to build backwards compatible config converters.\ntype Converter interface {\n\t// Convert applies the conversion logic to the given \"conf\".\n\tConvert(ctx context.Context, conf *Conf) error\n}\n"
  },
  {
    "path": "confmap/doc_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confmap_test\n\nimport (\n\t\"fmt\"\n\t\"slices\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\ntype DiskScrape struct {\n\tDisk   string        `mapstructure:\"disk\"`\n\tScrape time.Duration `mapstructure:\"scrape\"`\n}\n\n// We can annotate a struct with mapstructure field annotations.\nfunc Example_simpleUnmarshaling() {\n\tconf := confmap.NewFromStringMap(map[string]any{\n\t\t\"disk\":   \"c\",\n\t\t\"scrape\": \"5s\",\n\t})\n\tscrapeInfo := &DiskScrape{}\n\tif err := conf.Unmarshal(scrapeInfo); err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"Configuration contains the following:\\nDisk: %q\\nScrape: %s\\n\", scrapeInfo.Disk, scrapeInfo.Scrape)\n\t// Output: Configuration contains the following:\n\t// Disk: \"c\"\n\t// Scrape: 5s\n}\n\ntype CPUScrape struct {\n\tEnabled bool `mapstructure:\"enabled\"`\n}\n\ntype ComputerScrape struct {\n\tDiskScrape `mapstructure:\",squash\"`\n\tCPUScrape  `mapstructure:\",squash\"`\n}\n\n// We can unmarshal embedded structs with mapstructure field annotations.\nfunc Example_embeddedUnmarshaling() {\n\tconf := confmap.NewFromStringMap(map[string]any{\n\t\t\"disk\":    \"c\",\n\t\t\"scrape\":  \"5s\",\n\t\t\"enabled\": true,\n\t})\n\tscrapeInfo := &ComputerScrape{}\n\tif err := conf.Unmarshal(scrapeInfo); err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"Configuration contains the following:\\nDisk: %q\\nScrape: %s\\nEnabled: %v\\n\", scrapeInfo.Disk, scrapeInfo.Scrape, scrapeInfo.Enabled)\n\t// Output: Configuration contains the following:\n\t// Disk: \"c\"\n\t// Scrape: 5s\n\t// Enabled: true\n}\n\ntype NetworkScrape struct {\n\tEnabled  bool     `mapstructure:\"enabled\"`\n\tNetworks []string `mapstructure:\"networks\"`\n\tWifi     bool     `mapstructure:\"wifi\"`\n}\n\nfunc (n *NetworkScrape) Unmarshal(c *confmap.Conf) error {\n\tif err := c.Unmarshal(n, confmap.WithIgnoreUnused()); err != nil {\n\t\treturn err\n\t}\n\tif slices.Contains(n.Networks, \"wlan0\") {\n\t\tn.Wifi = true\n\t}\n\treturn nil\n}\n\ntype ManualScrapeInfo struct {\n\tDisk   string\n\tScrape time.Duration\n}\n\nfunc (m *ManualScrapeInfo) Unmarshal(c *confmap.Conf) error {\n\tm.Disk = c.Get(\"disk\").(string)\n\tif c.Get(\"vinyl\") == \"33\" {\n\t\tm.Scrape = 10 * time.Second\n\t} else {\n\t\tm.Scrape = 2 * time.Second\n\t}\n\treturn nil\n}\n\ntype RouterScrape struct {\n\tNetworkScrape `mapstructure:\",squash\"`\n}\n\n// We can unmarshal an embedded struct with a custom `Unmarshal` method.\nfunc Example_embeddedManualUnmarshaling() {\n\tconf := confmap.NewFromStringMap(map[string]any{\n\t\t\"networks\": []string{\"eth0\", \"eth1\", \"wlan0\"},\n\t\t\"enabled\":  true,\n\t})\n\tscrapeInfo := &RouterScrape{}\n\tif err := conf.Unmarshal(scrapeInfo); err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"Configuration contains the following:\\nNetworks: %q\\nWifi: %v\\nEnabled: %v\\n\", scrapeInfo.Networks, scrapeInfo.Wifi, scrapeInfo.Enabled)\n\t// Output: Configuration contains the following:\n\t// Networks: [\"eth0\" \"eth1\" \"wlan0\"]\n\t// Wifi: true\n\t// Enabled: true\n}\n\nfunc Example_manualUnmarshaling() {\n\tconf := confmap.NewFromStringMap(map[string]any{\n\t\t\"disk\":  \"Beatles\",\n\t\t\"vinyl\": \"33\",\n\t})\n\tscrapeInfo := &ManualScrapeInfo{}\n\tif err := conf.Unmarshal(scrapeInfo, confmap.WithIgnoreUnused()); err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"Configuration contains the following:\\nDisk: %q\\nScrape: %s\\n\", scrapeInfo.Disk, scrapeInfo.Scrape)\n\t// Output: Configuration contains the following:\n\t// Disk: \"Beatles\"\n\t// Scrape: 10s\n}\n"
  },
  {
    "path": "confmap/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# confmap\n\n## Feature Gates\n\nThis component has the following feature gates:\n\n| Feature Gate | Stage | Description | From Version | To Version | Reference |\n| ------------ | ----- | ----------- | ------------ | ---------- | --------- |\n| `confmap.enableMergeAppendOption` | alpha | Combines lists when resolving configs from different sources. This feature gate will not be stabilized 'as is'; the current behavior will remain the default. | v0.120.0 | N/A | [Link](https://github.com/open-telemetry/opentelemetry-collector/issues/8754) |\n| `confmap.newExpandedValueSanitizer` | beta | Fixes some types of decoding errors where environment variables are parsed as non-string types but assigned to string fields. | v0.144.0 | N/A | [Link](https://github.com/open-telemetry/opentelemetry-collector/pull/14413) |\n\nFor more information about feature gates, see the [Feature Gates](https://github.com/open-telemetry/opentelemetry-collector/blob/main/featuregate/README.md) documentation.\n"
  },
  {
    "path": "confmap/example_provider_and_converter_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confmap_test\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\n// mockFileProvider simulates the standard file provider behavior.\n// In typical usage, it reads a single file as the root configuration.\n// This mock implementation always returns a fixed configuration:\n// { \"my-config\": \"${expand:to-expand}\" }\ntype mockFileProvider struct{}\n\nfunc (d mockFileProvider) Retrieve(_ context.Context, uri string, _ confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\texpectedURI := \"file:mock-file\"\n\tif uri != expectedURI {\n\t\tpanic(\"should not happen, the uri is expected to be \" + expectedURI + \" for mockFileProvider\")\n\t}\n\treturn confmap.NewRetrieved(map[string]any{\n\t\t\"my-config\": \"${expand:to-expand}\",\n\t})\n}\n\nfunc (d mockFileProvider) Scheme() string {\n\treturn \"file\"\n}\n\nfunc (d mockFileProvider) Shutdown(_ context.Context) error {\n\treturn nil\n}\n\n// mockExpandProvider simulates a typical inline expansion provider.\n// In configurations, you can use expressions like ${SCHEMA:VALUE},\n// where the provider associated with SCHEMA is responsible for resolving the value.\ntype mockExpandProvider struct{}\n\nfunc (m mockExpandProvider) Retrieve(_ context.Context, uri string, _ confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\texpectedURI := \"expand:to-expand\"\n\tif uri != expectedURI {\n\t\tpanic(\"should not happen, the uri is expected to be \" + expectedURI + \" for mockExpandProvider\")\n\t}\n\treturn confmap.NewRetrieved(\"expanded\")\n}\n\nfunc (m mockExpandProvider) Scheme() string {\n\treturn \"expand\"\n}\n\nfunc (m mockExpandProvider) Shutdown(_ context.Context) error {\n\treturn nil\n}\n\n// mockUpperCaseConverter transforms the value of the `my-config` field in the configuration to uppercase.\ntype mockUpperCaseConverter struct{}\n\nfunc (m mockUpperCaseConverter) Convert(_ context.Context, conf *confmap.Conf) error {\n\tcurrentValue := conf.Get(\"my-config\")\n\texpectedValue := \"expanded\"\n\tif currentValue != expectedValue {\n\t\tpanic(\"should not happen, the value for converter should always be \" + expectedValue + \" for mockUpperCaseConverter\")\n\t}\n\tupperCaseConf := confmap.NewFromStringMap(map[string]any{\n\t\t\"my-config\": strings.ToUpper(currentValue.(string)),\n\t})\n\tif conf.Merge(upperCaseConf) != nil {\n\t\tpanic(\"merge failed, this should not happen in this example.\")\n\t}\n\treturn nil\n}\n\nfunc Example() {\n\tresolver, err := confmap.NewResolver(confmap.ResolverSettings{\n\t\tURIs: []string{\"file:mock-file\"},\n\t\tProviderFactories: []confmap.ProviderFactory{\n\t\t\tconfmap.NewProviderFactory(func(_ confmap.ProviderSettings) confmap.Provider {\n\t\t\t\treturn &mockFileProvider{}\n\t\t\t}),\n\t\t\tconfmap.NewProviderFactory(func(_ confmap.ProviderSettings) confmap.Provider {\n\t\t\t\treturn &mockExpandProvider{}\n\t\t\t}),\n\t\t},\n\t\tConverterFactories: []confmap.ConverterFactory{\n\t\t\tconfmap.NewConverterFactory(func(_ confmap.ConverterSettings) confmap.Converter {\n\t\t\t\treturn &mockUpperCaseConverter{}\n\t\t\t}),\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\tconf, err := resolver.Resolve(context.Background())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tfmt.Printf(\"Configuration contains the following:\\nmy-config: %s\", conf.Get(\"my-config\"))\n\t// Output: Configuration contains the following:\n\t// my-config: EXPANDED\n}\n"
  },
  {
    "path": "confmap/expand.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confmap // import \"go.opentelemetry.io/collector/confmap\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/confmap/internal\"\n)\n\n// schemePattern defines the regexp pattern for scheme names.\n// Scheme name consist of a sequence of characters beginning with a letter and followed by any\n// combination of letters, digits, plus (\"+\"), period (\".\"), or hyphen (\"-\").\nconst schemePattern = `[A-Za-z][A-Za-z0-9+.-]+`\n\nvar (\n\t// Need to match new line as well in the OpaqueValue, so setting the \"s\" flag. See https://pkg.go.dev/regexp/syntax.\n\turiRegexp = regexp.MustCompile(`(?s:^(?P<Scheme>` + schemePattern + `):(?P<OpaqueValue>.*)$)`)\n\n\terrTooManyRecursiveExpansions = errors.New(\"too many recursive expansions\")\n)\n\nfunc (mr *Resolver) expandValueRecursively(ctx context.Context, value any) (any, error) {\n\tfor range 1000 {\n\t\tval, changed, err := mr.expandValue(ctx, value)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif !changed {\n\t\t\treturn val, nil\n\t\t}\n\t\tvalue = val\n\t}\n\treturn nil, errTooManyRecursiveExpansions\n}\n\nfunc (mr *Resolver) expandValue(ctx context.Context, value any) (any, bool, error) {\n\tswitch v := value.(type) {\n\tcase internal.ExpandedValue:\n\t\texpanded, changed, err := mr.expandValue(ctx, v.Value)\n\t\tif err != nil {\n\t\t\treturn nil, false, err\n\t\t}\n\n\t\tswitch exp := expanded.(type) {\n\t\tcase internal.ExpandedValue, string:\n\t\t\t// Return expanded values or strings verbatim.\n\t\t\treturn exp, changed, nil\n\t\t}\n\n\t\t// At this point we don't know the target field type, so we need to expand the original representation as well.\n\t\toriginalExpanded, originalChanged, err := mr.expandValue(ctx, v.Original)\n\t\tif err != nil {\n\t\t\t// The original representation is not valid, return the expanded value.\n\t\t\treturn expanded, changed, nil\n\t\t}\n\n\t\tif originalExpanded, ok := originalExpanded.(string); ok {\n\t\t\t// If the original representation is a string, return the expanded value with the original representation.\n\t\t\treturn internal.ExpandedValue{\n\t\t\t\tValue:    expanded,\n\t\t\t\tOriginal: originalExpanded,\n\t\t\t}, changed || originalChanged, nil\n\t\t}\n\n\t\treturn expanded, changed, nil\n\tcase string:\n\t\tif !strings.Contains(v, \"${\") || !strings.Contains(v, \"}\") {\n\t\t\t// No URIs to expand.\n\t\t\treturn value, false, nil\n\t\t}\n\t\t// Embedded or nested URIs.\n\t\treturn mr.findAndExpandURI(ctx, v)\n\tcase []any:\n\t\tnslice := make([]any, 0, len(v))\n\t\tnchanged := false\n\t\tfor _, vint := range v {\n\t\t\tval, changed, err := mr.expandValue(ctx, vint)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, false, err\n\t\t\t}\n\t\t\tnslice = append(nslice, val)\n\t\t\tnchanged = nchanged || changed\n\t\t}\n\t\treturn nslice, nchanged, nil\n\tcase map[string]any:\n\t\tnmap := map[string]any{}\n\t\tnchanged := false\n\t\tfor mk, mv := range v {\n\t\t\tval, changed, err := mr.expandValue(ctx, mv)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, false, err\n\t\t\t}\n\t\t\tnmap[mk] = val\n\t\t\tnchanged = nchanged || changed\n\t\t}\n\t\treturn nmap, nchanged, nil\n\t}\n\treturn value, false, nil\n}\n\n// findURI attempts to find the first potentially expandable URI in input. It returns a potentially expandable\n// URI, or an empty string if none are found.\n// Note: findURI is only called when input contains a closing bracket.\n// We do not support escaping nested URIs (such as ${env:$${FOO}}, since that would result in an invalid outer URI (${env:${FOO}}).\nfunc (mr *Resolver) findURI(input string) string {\n\tcloseIndex := strings.Index(input, \"}\")\n\tremaining := input[closeIndex+1:]\n\topenIndex := strings.LastIndex(input[:closeIndex+1], \"${\")\n\n\t// if there is any of:\n\t//  - a missing \"${\"\n\t//  - there is no default scheme AND no scheme is detected because no `:` is found.\n\t// then check the next URI.\n\tif openIndex < 0 || (mr.defaultScheme == \"\" && !strings.Contains(input[openIndex:closeIndex+1], \":\")) {\n\t\t// if remaining does not contain \"}\", there are no URIs left: stop recursion.\n\t\tif !strings.Contains(remaining, \"}\") {\n\t\t\treturn \"\"\n\t\t}\n\t\treturn mr.findURI(remaining)\n\t}\n\n\tindex := openIndex - 1\n\tcurrentRune := '$'\n\tcount := 0\n\tfor index >= 0 && currentRune == '$' {\n\t\tcurrentRune = rune(input[index])\n\t\tif currentRune == '$' {\n\t\t\tcount++\n\t\t}\n\t\tindex--\n\t}\n\t// if we found an odd number of immediately $ preceding ${, then the expansion is escaped\n\tif count%2 == 1 {\n\t\treturn \"\"\n\t}\n\n\treturn input[openIndex : closeIndex+1]\n}\n\n// findAndExpandURI attempts to find and expand the first occurrence of an expandable URI in input. If an expandable URI is found it\n// returns the input with the URI expanded, true and nil. Otherwise, it returns the unchanged input, false and the expanding error.\n// This method expects input to start with ${ and end with }\nfunc (mr *Resolver) findAndExpandURI(ctx context.Context, input string) (any, bool, error) {\n\turi := mr.findURI(input)\n\tif uri == \"\" {\n\t\t// No URI found, return.\n\t\treturn input, false, nil\n\t}\n\tif uri == input {\n\t\t// If the value is a single URI, then the return value can be anything.\n\t\t// This is the case `foo: ${file:some_extra_config.yml}`.\n\t\tret, err := mr.expandURI(ctx, input)\n\t\tif err != nil {\n\t\t\treturn input, false, err\n\t\t}\n\n\t\tval, err := ret.AsRaw()\n\t\tif err != nil {\n\t\t\treturn input, false, err\n\t\t}\n\n\t\tif asStr, err2 := ret.AsString(); err2 == nil {\n\t\t\treturn internal.ExpandedValue{\n\t\t\t\tValue:    val,\n\t\t\t\tOriginal: asStr,\n\t\t\t}, true, nil\n\t\t}\n\n\t\treturn val, true, nil\n\t}\n\texpanded, err := mr.expandURI(ctx, uri)\n\tif err != nil {\n\t\treturn input, false, err\n\t}\n\n\trepl, err := expanded.AsString()\n\tif err != nil {\n\t\treturn input, false, fmt.Errorf(\"expanding %v: %w\", uri, err)\n\t}\n\treturn strings.ReplaceAll(input, uri, repl), true, err\n}\n\nfunc (mr *Resolver) expandURI(ctx context.Context, input string) (*Retrieved, error) {\n\t// strip ${ and }\n\turi := input[2 : len(input)-1]\n\n\tif !strings.Contains(uri, \":\") {\n\t\turi = fmt.Sprintf(\"%s:%s\", mr.defaultScheme, uri)\n\t}\n\n\tlURI, err := newLocation(uri)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif strings.Contains(lURI.opaqueValue, \"$\") {\n\t\treturn nil, fmt.Errorf(\"the uri %q contains unsupported characters ('$')\", lURI.asString())\n\t}\n\tret, err := mr.retrieveValue(ctx, lURI)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tmr.closers = append(mr.closers, ret.Close)\n\treturn ret, nil\n}\n\ntype location struct {\n\tscheme      string\n\topaqueValue string\n}\n\nfunc (c location) asString() string {\n\treturn c.scheme + \":\" + c.opaqueValue\n}\n\nfunc newLocation(uri string) (location, error) {\n\tsubmatches := uriRegexp.FindStringSubmatch(uri)\n\tif len(submatches) != 3 {\n\t\treturn location{}, fmt.Errorf(\"invalid uri: %q\", uri)\n\t}\n\treturn location{scheme: submatches[1], opaqueValue: submatches[2]}, nil\n}\n"
  },
  {
    "path": "confmap/expand_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confmap // import \"go.opentelemetry.io/collector/confmap\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestResolverExpandEnvVars(t *testing.T) {\n\ttestCases := []struct {\n\t\tname string // test case name (also file name containing config yaml)\n\t}{\n\t\t{name: \"expand-with-no-env.yaml\"},\n\t\t{name: \"expand-with-partial-env.yaml\"},\n\t\t{name: \"expand-with-all-env.yaml\"},\n\t}\n\n\tenvs := map[string]string{\n\t\t\"EXTRA\":                  \"some string\",\n\t\t\"EXTRA_MAP_VALUE_1\":      \"some map value_1\",\n\t\t\"EXTRA_MAP_VALUE_2\":      \"some map value_2\",\n\t\t\"EXTRA_LIST_MAP_VALUE_1\": \"some list map value_1\",\n\t\t\"EXTRA_LIST_MAP_VALUE_2\": \"some list map value_2\",\n\t\t\"EXTRA_LIST_VALUE_1\":     \"some list value_1\",\n\t\t\"EXTRA_LIST_VALUE_2\":     \"some list value_2\",\n\t}\n\n\texpectedCfgMap := newConfFromFile(t, filepath.Join(\"testdata\", \"expand-with-no-env.yaml\"))\n\tfileProvider := newFakeProvider(\"file\", func(_ context.Context, uri string, _ WatcherFunc) (*Retrieved, error) {\n\t\treturn NewRetrieved(newConfFromFile(t, uri[5:]))\n\t})\n\tenvProvider := newFakeProvider(\"env\", func(_ context.Context, uri string, _ WatcherFunc) (*Retrieved, error) {\n\t\treturn NewRetrieved(envs[uri[4:]])\n\t})\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresolver, err := NewResolver(ResolverSettings{URIs: []string{filepath.Join(\"testdata\", tt.name)}, ProviderFactories: []ProviderFactory{fileProvider, envProvider}, ConverterFactories: nil})\n\t\t\trequire.NoError(t, err)\n\n\t\t\t// Test that expanded configs are the same with the simple config with no env vars.\n\t\t\tcfgMap, err := resolver.Resolve(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, expectedCfgMap, cfgMap.ToStringMap())\n\t\t})\n\t}\n}\n\nfunc TestResolverDoneNotExpandOldEnvVars(t *testing.T) {\n\texpectedCfgMap := map[string]any{\"test.1\": \"${EXTRA}\", \"test.2\": \"$EXTRA\", \"test.3\": \"${EXTRA}:${EXTRA}\"}\n\tfileProvider := newFakeProvider(\"test\", func(context.Context, string, WatcherFunc) (*Retrieved, error) {\n\t\treturn NewRetrieved(expectedCfgMap)\n\t})\n\tenvProvider := newFakeProvider(\"env\", func(context.Context, string, WatcherFunc) (*Retrieved, error) {\n\t\treturn NewRetrieved(\"some string\")\n\t})\n\n\tresolver, err := NewResolver(ResolverSettings{URIs: []string{\"test:\"}, ProviderFactories: []ProviderFactory{fileProvider, envProvider}, ConverterFactories: nil})\n\trequire.NoError(t, err)\n\n\t// Test that expanded configs are the same with the simple config with no env vars.\n\tcfgMap, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\tassert.Equal(t, expectedCfgMap, cfgMap.ToStringMap())\n}\n\nfunc TestResolverExpandMapAndSliceValues(t *testing.T) {\n\tprovider := newFakeProvider(\"input\", func(context.Context, string, WatcherFunc) (*Retrieved, error) {\n\t\treturn NewRetrieved(map[string]any{\n\t\t\t\"test_map\":   map[string]any{\"recv\": \"${test:MAP_VALUE}\"},\n\t\t\t\"test_slice\": []any{\"${test:MAP_VALUE}\"},\n\t\t})\n\t})\n\n\tconst receiverExtraMapValue = \"some map value\"\n\ttestProvider := newFakeProvider(\"test\", func(context.Context, string, WatcherFunc) (*Retrieved, error) {\n\t\treturn NewRetrieved(receiverExtraMapValue)\n\t})\n\n\tresolver, err := NewResolver(ResolverSettings{URIs: []string{\"input:\"}, ProviderFactories: []ProviderFactory{provider, testProvider}, ConverterFactories: nil})\n\trequire.NoError(t, err)\n\n\tcfgMap, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\texpectedMap := map[string]any{\n\t\t\"test_map\":   map[string]any{\"recv\": receiverExtraMapValue},\n\t\t\"test_slice\": []any{receiverExtraMapValue},\n\t}\n\tassert.Equal(t, expectedMap, cfgMap.ToStringMap())\n}\n\nfunc TestResolverExpandStringValues(t *testing.T) {\n\ttests := []struct {\n\t\tname            string\n\t\tinput           string\n\t\toutput          any\n\t\tdefaultProvider bool\n\t}{\n\t\t// Embedded.\n\t\t{\n\t\t\tname:   \"NoMatchOldStyle\",\n\t\t\tinput:  \"${HOST}:${PORT}\",\n\t\t\toutput: \"${HOST}:${PORT}\",\n\t\t},\n\t\t{\n\t\t\tname:            \"NoMatchOldStyleDefaultProvider\",\n\t\t\tinput:           \"${HOST}:${PORT}\",\n\t\t\toutput:          \"localhost:3044\",\n\t\t\tdefaultProvider: true,\n\t\t},\n\t\t{\n\t\t\tname:   \"NoMatchOldStyleNoBrackets\",\n\t\t\tinput:  \"${HOST}:$PORT\",\n\t\t\toutput: \"${HOST}:$PORT\",\n\t\t},\n\t\t{\n\t\t\tname:            \"NoMatchOldStyleNoBracketsDefaultProvider\",\n\t\t\tinput:           \"${HOST}:$PORT\",\n\t\t\toutput:          \"localhost:$PORT\",\n\t\t\tdefaultProvider: true,\n\t\t},\n\t\t{\n\t\t\tname:   \"ComplexValue\",\n\t\t\tinput:  \"${env:COMPLEX_VALUE}\",\n\t\t\toutput: []any{\"localhost:3042\"},\n\t\t},\n\t\t{\n\t\t\tname:   \"Embedded\",\n\t\t\tinput:  \"${env:HOST}:3043\",\n\t\t\toutput: \"localhost:3043\",\n\t\t},\n\t\t{\n\t\t\tname:   \"EmbeddedMulti\",\n\t\t\tinput:  \"${env:HOST}:${env:PORT}\",\n\t\t\toutput: \"localhost:3044\",\n\t\t},\n\t\t{\n\t\t\tname:   \"EmbeddedConcat\",\n\t\t\tinput:  \"https://${env:HOST}:3045\",\n\t\t\toutput: \"https://localhost:3045\",\n\t\t},\n\t\t{\n\t\t\tname:   \"EmbeddedNewAndOldStyle\",\n\t\t\tinput:  \"${env:HOST}:${PORT}\",\n\t\t\toutput: \"localhost:${PORT}\",\n\t\t},\n\t\t{\n\t\t\tname:            \"EmbeddedNewAndOldStyleDefaultProvider\",\n\t\t\tinput:           \"${env:HOST}:${PORT}\",\n\t\t\toutput:          \"localhost:3044\",\n\t\t\tdefaultProvider: true,\n\t\t},\n\t\t{\n\t\t\tname:   \"Int\",\n\t\t\tinput:  \"test_${env:INT}\",\n\t\t\toutput: \"test_1\",\n\t\t},\n\t\t{\n\t\t\tname:   \"Int32\",\n\t\t\tinput:  \"test_${env:INT32}\",\n\t\t\toutput: \"test_32\",\n\t\t},\n\t\t{\n\t\t\tname:   \"Int64\",\n\t\t\tinput:  \"test_${env:INT64}\",\n\t\t\toutput: \"test_64\",\n\t\t},\n\t\t{\n\t\t\tname:   \"Float32\",\n\t\t\tinput:  \"test_${env:FLOAT32}\",\n\t\t\toutput: \"test_3.25\",\n\t\t},\n\t\t{\n\t\t\tname:   \"Float64\",\n\t\t\tinput:  \"test_${env:FLOAT64}\",\n\t\t\toutput: \"test_6.4\",\n\t\t},\n\t\t{\n\t\t\tname:   \"Bool\",\n\t\t\tinput:  \"test_${env:BOOL}\",\n\t\t\toutput: \"test_true\",\n\t\t},\n\t\t{\n\t\t\tname:   \"Timestamp\",\n\t\t\tinput:  \"test_${env:TIMESTAMP}\",\n\t\t\toutput: \"test_2023-03-20T03:17:55.432328Z\",\n\t\t},\n\t\t{\n\t\t\tname:   \"MultipleSameMatches\",\n\t\t\tinput:  \"test_${env:BOOL}_test_${env:BOOL}\",\n\t\t\toutput: \"test_true_test_true\",\n\t\t},\n\n\t\t// Nested.\n\t\t{\n\t\t\tname:   \"Nested\",\n\t\t\tinput:  \"${test:localhost:${env:PORT}}\",\n\t\t\toutput: \"localhost:3044\",\n\t\t},\n\t\t{\n\t\t\tname:            \"NestedDefaultProvider\",\n\t\t\tinput:           \"${test:localhost:${PORT}}\",\n\t\t\toutput:          \"localhost:3044\",\n\t\t\tdefaultProvider: true,\n\t\t},\n\t\t{\n\t\t\tname:   \"EmbeddedInNested\",\n\t\t\tinput:  \"${test:${env:HOST}:${env:PORT}}\",\n\t\t\toutput: \"localhost:3044\",\n\t\t},\n\t\t{\n\t\t\tname:            \"EmbeddedInNestedDefaultProvider\",\n\t\t\tinput:           \"${test:${HOST}:${PORT}}\",\n\t\t\toutput:          \"localhost:3044\",\n\t\t\tdefaultProvider: true,\n\t\t},\n\t\t{\n\t\t\tname:   \"EmbeddedAndNested\",\n\t\t\tinput:  \"${test:localhost:${env:PORT}}?os=${env:OS}\",\n\t\t\toutput: \"localhost:3044?os=ubuntu\",\n\t\t},\n\t\t{\n\t\t\tname:   \"NestedMultiple\",\n\t\t\tinput:  \"${test:1${test:2${test:3${test:4${test:5${test:6}}}}}}\",\n\t\t\toutput: \"123456\",\n\t\t},\n\t\t// No expand.\n\t\t{\n\t\t\tname:   \"NoMatchMissingOpeningBracket\",\n\t\t\tinput:  \"env:HOST}\",\n\t\t\toutput: \"env:HOST}\",\n\t\t},\n\t\t{\n\t\t\tname:            \"NoMatchMissingOpeningBracketDefaultProvider\",\n\t\t\tinput:           \"env:HOST}\",\n\t\t\toutput:          \"env:HOST}\",\n\t\t\tdefaultProvider: true,\n\t\t},\n\t\t{\n\t\t\tname:   \"NoMatchMissingClosingBracket\",\n\t\t\tinput:  \"${HOST\",\n\t\t\toutput: \"${HOST\",\n\t\t},\n\t\t{\n\t\t\tname:            \"NoMatchMissingClosingBracketDefaultProvider\",\n\t\t\tinput:           \"${HOST\",\n\t\t\toutput:          \"${HOST\",\n\t\t\tdefaultProvider: true,\n\t\t},\n\t\t{\n\t\t\tname:   \"NoMatchBracketsWithout$\",\n\t\t\tinput:  \"HO{ST}\",\n\t\t\toutput: \"HO{ST}\",\n\t\t},\n\t\t{\n\t\t\tname:            \"NoMatchBracketsWithout$DefaultProvider\",\n\t\t\tinput:           \"HO{ST}\",\n\t\t\toutput:          \"HO{ST}\",\n\t\t\tdefaultProvider: true,\n\t\t},\n\t\t{\n\t\t\tname:   \"NoMatchOnlyMissingClosingBracket\",\n\t\t\tinput:  \"${env:HOST${env:PORT?os=${env:OS\",\n\t\t\toutput: \"${env:HOST${env:PORT?os=${env:OS\",\n\t\t},\n\t\t{\n\t\t\tname:            \"NoMatchOnlyMissingClosingBracketDefaultProvider\",\n\t\t\tinput:           \"${env:HOST${env:PORT?os=${env:OS\",\n\t\t\toutput:          \"${env:HOST${env:PORT?os=${env:OS\",\n\t\t\tdefaultProvider: true,\n\t\t},\n\t\t{\n\t\t\tname:   \"NoMatchOnlyMissingOpeningBracket\",\n\t\t\tinput:  \"env:HOST}env:PORT}?os=env:OS}\",\n\t\t\toutput: \"env:HOST}env:PORT}?os=env:OS}\",\n\t\t},\n\t\t{\n\t\t\tname:            \"NoMatchOnlyMissingOpeningBracketDefaultProvider\",\n\t\t\tinput:           \"env:HOST}env:PORT}?os=env:OS}\",\n\t\t\toutput:          \"env:HOST}env:PORT}?os=env:OS}\",\n\t\t\tdefaultProvider: true,\n\t\t},\n\t\t{\n\t\t\tname:   \"NoMatchCloseBeforeOpen\",\n\t\t\tinput:  \"env:HOST}${env:PORT\",\n\t\t\toutput: \"env:HOST}${env:PORT\",\n\t\t},\n\t\t{\n\t\t\tname:            \"NoMatchCloseBeforeOpenDefaultProvider\",\n\t\t\tinput:           \"env:HOST}${env:PORT\",\n\t\t\toutput:          \"env:HOST}${env:PORT\",\n\t\t\tdefaultProvider: true,\n\t\t},\n\t\t{\n\t\t\tname:   \"NoMatchOldStyleNested\",\n\t\t\tinput:  \"${test:localhost:${PORT}}\",\n\t\t\toutput: \"${test:localhost:${PORT}}\",\n\t\t},\n\t\t// Partial expand.\n\t\t{\n\t\t\tname:   \"PartialMatchMissingOpeningBracketFirst\",\n\t\t\tinput:  \"env:HOST}${env:PORT}\",\n\t\t\toutput: \"env:HOST}3044\",\n\t\t},\n\t\t{\n\t\t\tname:            \"PartialMatchMissingOpeningBracketFirstDefaultProvider\",\n\t\t\tinput:           \"env:HOST}${PORT}\",\n\t\t\toutput:          \"env:HOST}3044\",\n\t\t\tdefaultProvider: true,\n\t\t},\n\t\t{\n\t\t\tname:   \"PartialMatchMissingOpeningBracketLast\",\n\t\t\tinput:  \"${env:HOST}env:PORT}\",\n\t\t\toutput: \"localhostenv:PORT}\",\n\t\t},\n\t\t{\n\t\t\tname:   \"PartialMatchMissingClosingBracketFirst\",\n\t\t\tinput:  \"${env:HOST${env:PORT}\",\n\t\t\toutput: \"${env:HOST3044\",\n\t\t},\n\t\t{\n\t\t\tname:   \"PartialMatchMissingClosingBracketLast\",\n\t\t\tinput:  \"${env:HOST}${env:PORT\",\n\t\t\toutput: \"localhost${env:PORT\",\n\t\t},\n\t\t{\n\t\t\tname:   \"PartialMatchMultipleMissingOpen\",\n\t\t\tinput:  \"env:HOST}env:PORT}?os=${env:OS}\",\n\t\t\toutput: \"env:HOST}env:PORT}?os=ubuntu\",\n\t\t},\n\t\t{\n\t\t\tname:   \"PartialMatchMultipleMissingClosing\",\n\t\t\tinput:  \"${env:HOST${env:PORT?os=${env:OS}\",\n\t\t\toutput: \"${env:HOST${env:PORT?os=ubuntu\",\n\t\t},\n\t\t{\n\t\t\tname:   \"PartialMatchMoreClosingBrackets\",\n\t\t\tinput:  \"${env:HOST}}}}}}${env:PORT?os=${env:OS}\",\n\t\t\toutput: \"localhost}}}}}${env:PORT?os=ubuntu\",\n\t\t},\n\t\t{\n\t\t\tname:   \"PartialMatchMoreOpeningBrackets\",\n\t\t\tinput:  \"${env:HOST}${${${${${env:PORT}?os=${env:OS}\",\n\t\t\toutput: \"localhost${${${${3044?os=ubuntu\",\n\t\t},\n\t\t{\n\t\t\tname:   \"PartialMatchAlternatingMissingOpening\",\n\t\t\tinput:  \"env:HOST}${env:PORT}?os=env:OS}&pr=${env:PR}\",\n\t\t\toutput: \"env:HOST}3044?os=env:OS}&pr=amd\",\n\t\t},\n\t\t{\n\t\t\tname:   \"PartialMatchAlternatingMissingClosing\",\n\t\t\tinput:  \"${env:HOST${env:PORT}?os=${env:OS&pr=${env:PR}\",\n\t\t\toutput: \"${env:HOST3044?os=${env:OS&pr=amd\",\n\t\t},\n\t\t{\n\t\t\tname:   \"SchemeAfterNoSchemeIsExpanded\",\n\t\t\tinput:  \"${HOST}${env:PORT}\",\n\t\t\toutput: \"${HOST}3044\",\n\t\t},\n\t\t{\n\t\t\tname:            \"SchemeAfterNoSchemeIsExpandedDefaultProvider\",\n\t\t\tinput:           \"${HOST}${env:PORT}\",\n\t\t\toutput:          \"localhost3044\",\n\t\t\tdefaultProvider: true,\n\t\t},\n\t\t{\n\t\t\tname:   \"SchemeBeforeNoSchemeIsExpanded\",\n\t\t\tinput:  \"${env:HOST}${PORT}\",\n\t\t\toutput: \"localhost${PORT}\",\n\t\t},\n\t\t{\n\t\t\tname:            \"SchemeBeforeNoSchemeIsExpandedDefaultProvider\",\n\t\t\tinput:           \"${env:HOST}${PORT}\",\n\t\t\toutput:          \"localhost3044\",\n\t\t\tdefaultProvider: true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tprovider := newFakeProvider(\"input\", func(context.Context, string, WatcherFunc) (*Retrieved, error) {\n\t\t\t\treturn NewRetrieved(map[string]any{tt.name: tt.input})\n\t\t\t})\n\n\t\t\ttestProvider := newFakeProvider(\"test\", func(_ context.Context, uri string, _ WatcherFunc) (*Retrieved, error) {\n\t\t\t\treturn NewRetrieved(uri[5:])\n\t\t\t})\n\n\t\t\tenvProvider := newEnvProvider()\n\t\t\tset := ResolverSettings{URIs: []string{\"input:\"}, ProviderFactories: []ProviderFactory{provider, envProvider, testProvider}, ConverterFactories: nil}\n\t\t\tif tt.defaultProvider {\n\t\t\t\tset.DefaultScheme = \"env\"\n\t\t\t}\n\t\t\tresolver, err := NewResolver(set)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tcfgMap, err := resolver.Resolve(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, map[string]any{tt.name: tt.output}, cfgMap.ToStringMap())\n\t\t})\n\t}\n}\n\nfunc newEnvProvider() ProviderFactory {\n\treturn newFakeProvider(\"env\", func(_ context.Context, uri string, _ WatcherFunc) (*Retrieved, error) {\n\t\t// When using `env` as the default scheme for tests, the uri will not include `env:`.\n\t\t// Instead of duplicating the switch cases, the scheme is added instead.\n\t\tif uri[0:4] != \"env:\" {\n\t\t\turi = \"env:\" + uri\n\t\t}\n\t\tswitch uri {\n\t\tcase \"env:COMPLEX_VALUE\":\n\t\t\treturn NewRetrievedFromYAML([]byte(\"[localhost:3042]\"))\n\t\tcase \"env:HOST\":\n\t\t\treturn NewRetrievedFromYAML([]byte(\"localhost\"))\n\t\tcase \"env:TIMESTAMP\":\n\t\t\treturn NewRetrievedFromYAML([]byte(\"2023-03-20T03:17:55.432328Z\"))\n\t\tcase \"env:OS\":\n\t\t\treturn NewRetrievedFromYAML([]byte(\"ubuntu\"))\n\t\tcase \"env:PR\":\n\t\t\treturn NewRetrievedFromYAML([]byte(\"amd\"))\n\t\tcase \"env:PORT\":\n\t\t\treturn NewRetrievedFromYAML([]byte(\"3044\"))\n\t\tcase \"env:INT\":\n\t\t\treturn NewRetrievedFromYAML([]byte(\"1\"))\n\t\tcase \"env:INT32\":\n\t\t\treturn NewRetrieved(int32(32), withStringRepresentation(\"32\"))\n\t\tcase \"env:INT64\":\n\t\t\treturn NewRetrieved(int64(64), withStringRepresentation(\"64\"))\n\t\tcase \"env:FLOAT32\":\n\t\t\treturn NewRetrieved(float32(3.25), withStringRepresentation(\"3.25\"))\n\t\tcase \"env:FLOAT64\":\n\t\t\treturn NewRetrieved(float64(6.4), withStringRepresentation(\"6.4\"))\n\t\tcase \"env:BOOL\":\n\t\t\treturn NewRetrievedFromYAML([]byte(\"true\"))\n\t\t}\n\t\treturn nil, errors.New(\"impossible\")\n\t})\n}\n\nfunc TestResolverExpandReturnError(t *testing.T) {\n\ttests := []struct {\n\t\tname  string\n\t\tinput any\n\t}{\n\t\t{\n\t\t\tname:  \"string_value\",\n\t\t\tinput: \"${test:VALUE}\",\n\t\t},\n\t\t{\n\t\t\tname:  \"slice_value\",\n\t\t\tinput: []any{\"${test:VALUE}\"},\n\t\t},\n\t\t{\n\t\t\tname:  \"map_value\",\n\t\t\tinput: map[string]any{\"test\": \"${test:VALUE}\"},\n\t\t},\n\t\t{\n\t\t\tname:  \"string_embedded_value\",\n\t\t\tinput: \"https://${test:HOST}:3045\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tprovider := newFakeProvider(\"input\", func(context.Context, string, WatcherFunc) (*Retrieved, error) {\n\t\t\t\treturn NewRetrieved(map[string]any{tt.name: tt.input})\n\t\t\t})\n\n\t\t\tmyErr := errors.New(tt.name)\n\t\t\ttestProvider := newFakeProvider(\"test\", func(context.Context, string, WatcherFunc) (*Retrieved, error) {\n\t\t\t\treturn nil, myErr\n\t\t\t})\n\n\t\t\tresolver, err := NewResolver(ResolverSettings{URIs: []string{\"input:\"}, ProviderFactories: []ProviderFactory{provider, testProvider}, ConverterFactories: nil})\n\t\t\trequire.NoError(t, err)\n\n\t\t\t_, err = resolver.Resolve(context.Background())\n\t\t\tassert.ErrorIs(t, err, myErr)\n\t\t})\n\t}\n}\n\nfunc TestResolverInfiniteExpand(t *testing.T) {\n\tconst receiverValue = \"${test:VALUE}\"\n\tprovider := newFakeProvider(\"input\", func(context.Context, string, WatcherFunc) (*Retrieved, error) {\n\t\treturn NewRetrieved(map[string]any{\"test\": receiverValue})\n\t})\n\n\ttestProvider := newFakeProvider(\"test\", func(context.Context, string, WatcherFunc) (*Retrieved, error) {\n\t\treturn NewRetrieved(receiverValue)\n\t})\n\n\tresolver, err := NewResolver(ResolverSettings{URIs: []string{\"input:\"}, ProviderFactories: []ProviderFactory{provider, testProvider}, ConverterFactories: nil})\n\trequire.NoError(t, err)\n\n\t_, err = resolver.Resolve(context.Background())\n\tassert.ErrorIs(t, err, errTooManyRecursiveExpansions)\n}\n\nfunc TestResolverExpandInvalidScheme(t *testing.T) {\n\tprovider := newFakeProvider(\"input\", func(context.Context, string, WatcherFunc) (*Retrieved, error) {\n\t\treturn NewRetrieved(map[string]any{\"test\": \"${g_c_s:VALUE}\"})\n\t})\n\n\ttestProvider := newFakeProvider(\"g_c_s\", func(context.Context, string, WatcherFunc) (*Retrieved, error) {\n\t\tpanic(\"must not be called\")\n\t})\n\n\t_, err := NewResolver(ResolverSettings{URIs: []string{\"input:\"}, ProviderFactories: []ProviderFactory{provider, testProvider}, ConverterFactories: nil})\n\tassert.ErrorContains(t, err, \"invalid 'confmap.Provider' scheme\")\n}\n\nfunc TestResolverExpandInvalidOpaqueValue(t *testing.T) {\n\tprovider := newFakeProvider(\"input\", func(context.Context, string, WatcherFunc) (*Retrieved, error) {\n\t\treturn NewRetrieved(map[string]any{\"test\": []any{map[string]any{\"test\": \"${test:$VALUE}\"}}})\n\t})\n\n\ttestProvider := newFakeProvider(\"test\", func(context.Context, string, WatcherFunc) (*Retrieved, error) {\n\t\tpanic(\"must not be called\")\n\t})\n\n\tresolver, err := NewResolver(ResolverSettings{URIs: []string{\"input:\"}, ProviderFactories: []ProviderFactory{provider, testProvider}, ConverterFactories: nil})\n\trequire.NoError(t, err)\n\n\t_, err = resolver.Resolve(context.Background())\n\tassert.EqualError(t, err, `the uri \"test:$VALUE\" contains unsupported characters ('$')`)\n}\n\nfunc TestResolverExpandUnsupportedScheme(t *testing.T) {\n\tprovider := newFakeProvider(\"input\", func(context.Context, string, WatcherFunc) (*Retrieved, error) {\n\t\treturn NewRetrieved(map[string]any{\"test\": \"${unsupported:VALUE}\"})\n\t})\n\n\ttestProvider := newFakeProvider(\"test\", func(context.Context, string, WatcherFunc) (*Retrieved, error) {\n\t\tpanic(\"must not be called\")\n\t})\n\n\tresolver, err := NewResolver(ResolverSettings{URIs: []string{\"input:\"}, ProviderFactories: []ProviderFactory{provider, testProvider}, ConverterFactories: nil})\n\trequire.NoError(t, err)\n\n\t_, err = resolver.Resolve(context.Background())\n\tassert.EqualError(t, err, `scheme \"unsupported\" is not supported for uri \"unsupported:VALUE\"`)\n}\n\nfunc TestResolverDefaultProviderExpand(t *testing.T) {\n\tprovider := newFakeProvider(\"input\", func(context.Context, string, WatcherFunc) (*Retrieved, error) {\n\t\treturn NewRetrieved(map[string]any{\"foo\": \"${HOST}\"})\n\t})\n\n\tresolver, err := NewResolver(ResolverSettings{URIs: []string{\"input:\"}, ProviderFactories: []ProviderFactory{provider, newEnvProvider()}, DefaultScheme: \"env\", ConverterFactories: nil})\n\trequire.NoError(t, err)\n\n\tcfgMap, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\tassert.Equal(t, map[string]any{\"foo\": \"localhost\"}, cfgMap.ToStringMap())\n}\n"
  },
  {
    "path": "confmap/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confmap // import \"go.opentelemetry.io/collector/confmap\"\n\ntype moduleFactory[T any, S any] interface {\n\tCreate(s S) T\n}\n\ntype createConfmapFunc[T any, S any] func(s S) T\n\ntype confmapModuleFactory[T any, S any] struct {\n\tf createConfmapFunc[T, S]\n}\n\nfunc (c confmapModuleFactory[T, S]) Create(s S) T {\n\treturn c.f(s)\n}\n\nfunc newConfmapModuleFactory[T, S any](f createConfmapFunc[T, S]) moduleFactory[T, S] {\n\treturn confmapModuleFactory[T, S]{\n\t\tf: f,\n\t}\n}\n"
  },
  {
    "path": "confmap/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage confmap\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "confmap/go.mod",
    "content": "module go.opentelemetry.io/collector/confmap\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0\n\tgithub.com/gobwas/glob v0.2.3\n\tgithub.com/knadh/koanf/maps v0.1.2\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0\n\tgithub.com/knadh/koanf/v2 v2.3.3\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/featuregate v1.54.0\n\tgo.opentelemetry.io/collector/internal/testutil v0.148.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/multierr v1.11.0\n\tgo.uber.org/zap v1.27.1\n\tgo.yaml.in/yaml/v3 v3.0.4\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nretract (\n\tv0.76.0 // Depends on retracted pdata v1.0.0-rc10 module, use v0.76.1\n\tv0.69.0 // Release failed, use v0.69.1\n)\n\nreplace (\n\tgo.opentelemetry.io/collector/featuregate => ../featuregate\n\tgo.opentelemetry.io/collector/internal/testutil => ../internal/testutil\n)\n"
  },
  {
    "path": "confmap/go.sum",
    "content": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "confmap/internal/conf.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/confmap/internal\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\n\t\"github.com/knadh/koanf/maps\"\n\t\"github.com/knadh/koanf/providers/confmap\"\n\t\"github.com/knadh/koanf/v2\"\n\n\tencoder \"go.opentelemetry.io/collector/confmap/internal/mapstructure\"\n\t\"go.opentelemetry.io/collector/confmap/internal/metadata\"\n)\n\nconst (\n\t// KeyDelimiter is used as the default key delimiter in the default koanf instance.\n\tKeyDelimiter = \"::\"\n)\n\n// Conf represents the raw configuration map for the OpenTelemetry Collector.\n// The confmap.Conf can be unmarshalled into the Collector's config using the \"service\" package.\ntype Conf struct {\n\tk *koanf.Koanf\n\t// If true, upon unmarshaling do not call the Unmarshal function on the struct\n\t// if it implements Unmarshaler and is the top-level struct.\n\t// This avoids running into an infinite recursion where Unmarshaler.Unmarshal and\n\t// Conf.Unmarshal would call each other.\n\tskipTopLevelUnmarshaler bool\n\t// isNil is true if this Conf was created from a nil field, as opposed to an empty map.\n\t// AllKeys must return an empty slice if this is true.\n\tisNil bool\n}\n\n// New creates a new empty confmap.Conf instance.\nfunc New() *Conf {\n\treturn &Conf{k: koanf.New(KeyDelimiter), isNil: false}\n}\n\n// NewFromStringMap creates a confmap.Conf from a map[string]any.\nfunc NewFromStringMap(data map[string]any) *Conf {\n\tp := New()\n\tif data == nil {\n\t\tp.isNil = true\n\t} else {\n\t\t// Cannot return error because the koanf instance is empty.\n\t\t_ = p.k.Load(confmap.Provider(data, KeyDelimiter), nil)\n\t}\n\treturn p\n}\n\n// Unmarshal unmarshalls the config into a struct using the given options.\n// Tags on the fields of the structure must be properly set.\nfunc (l *Conf) Unmarshal(result any, opts ...UnmarshalOption) error {\n\tset := UnmarshalOptions{}\n\tfor _, opt := range opts {\n\t\topt.apply(&set)\n\t}\n\treturn Decode(l.toStringMapWithExpand(), result, set, l.skipTopLevelUnmarshaler)\n}\n\n// Marshal encodes the config and merges it into the Conf.\nfunc (l *Conf) Marshal(rawVal any, opts ...MarshalOption) error {\n\tset := MarshalOptions{}\n\tfor _, opt := range opts {\n\t\topt.apply(&set)\n\t}\n\tenc := encoder.New(EncoderConfig(rawVal, set))\n\tdata, err := enc.Encode(rawVal)\n\tif err != nil {\n\t\treturn err\n\t}\n\tout, ok := data.(map[string]any)\n\tif !ok {\n\t\treturn errors.New(\"invalid config encoding\")\n\t}\n\treturn l.Merge(NewFromStringMap(out))\n}\n\n// AllKeys returns all keys holding a value, regardless of where they are set.\n// Nested keys are returned with a KeyDelimiter separator.\nfunc (l *Conf) AllKeys() []string {\n\treturn l.k.Keys()\n}\n\n// Get can retrieve any value given the key to use.\nfunc (l *Conf) Get(key string) any {\n\tval := l.unsanitizedGet(key)\n\treturn sanitizeExpanded(val, false)\n}\n\n// IsSet checks to see if the key has been set in any of the data locations.\nfunc (l *Conf) IsSet(key string) bool {\n\treturn l.k.Exists(key)\n}\n\n// Merge merges the input given configuration into the existing config.\n// Note that the given map may be modified.\nfunc (l *Conf) Merge(in *Conf) error {\n\tif metadata.ConfmapEnableMergeAppendOptionFeatureGate.IsEnabled() {\n\t\treturn l.mergeAppend(in)\n\t}\n\tl.isNil = l.isNil && in.isNil\n\treturn l.k.Merge(in.k)\n}\n\n// Delete a path from the Conf.\n// If the path exists, deletes it and returns true.\n// If the path does not exist, does nothing and returns false.\nfunc (l *Conf) Delete(key string) bool {\n\twasSet := l.IsSet(key)\n\tl.k.Delete(key)\n\treturn wasSet\n}\n\n// mergeAppend merges the input given configuration into the existing config.\n// Note that the given map may be modified.\n// Additionally, mergeAppend performs deduplication when merging lists.\n// For example, if listA = [extension1, extension2] and listB = [extension1, extension3],\n// the resulting list will be [extension1, extension2, extension3].\nfunc (l *Conf) mergeAppend(in *Conf) error {\n\terr := l.k.Load(confmap.Provider(in.ToStringMap(), \"\"), nil, koanf.WithMergeFunc(mergeAppend))\n\tif err != nil {\n\t\treturn err\n\t}\n\tl.isNil = l.isNil && in.isNil\n\treturn nil\n}\n\n// Sub returns new Conf instance representing a sub-config of this instance.\n// It returns an error is the sub-config is not a map[string]any (use Get()), and an empty Map if none exists.\nfunc (l *Conf) Sub(key string) (*Conf, error) {\n\t// Code inspired by the koanf \"Cut\" func, but returns an error instead of empty map for unsupported sub-config type.\n\tdata := l.unsanitizedGet(key)\n\tif data == nil {\n\t\tc := New()\n\t\tc.isNil = true\n\t\treturn c, nil\n\t}\n\n\tswitch v := data.(type) {\n\tcase map[string]any:\n\t\treturn NewFromStringMap(v), nil\n\tcase ExpandedValue:\n\t\tif m, ok := v.Value.(map[string]any); ok {\n\t\t\treturn NewFromStringMap(m), nil\n\t\t} else if v.Value == nil {\n\t\t\t// If the value is nil, return a new empty Conf.\n\t\t\tc := New()\n\t\t\tc.isNil = true\n\t\t\treturn c, nil\n\t\t}\n\t\t// override data with the original value to make the error message more informative.\n\t\tdata = v.Value\n\t}\n\n\treturn nil, fmt.Errorf(\"unexpected sub-config value kind for key:%s value:%v kind:%v\", key, data, reflect.TypeOf(data).Kind())\n}\n\nfunc (l *Conf) toStringMapWithExpand() map[string]any {\n\tif l.isNil {\n\t\treturn nil\n\t}\n\tm := maps.Unflatten(l.k.All(), KeyDelimiter)\n\treturn m\n}\n\n// ToStringMap creates a map[string]any from a Conf.\n// Values with multiple representations\n// are normalized with the YAML parsed representation.\n//\n// For example, for a Conf created from `foo: ${env:FOO}` and `FOO=123`\n// ToStringMap will return `map[string]any{\"foo\": 123}`.\n//\n// For any map `m`, `NewFromStringMap(m).ToStringMap() == m`.\n// In particular, if the Conf was created from a nil value,\n// ToStringMap will return map[string]any(nil).\nfunc (l *Conf) ToStringMap() map[string]any {\n\treturn sanitize(l.toStringMapWithExpand()).(map[string]any)\n}\n\nfunc ToStringMapRaw(conf *Conf) map[string]any {\n\treturn conf.toStringMapWithExpand()\n}\n\nfunc (l *Conf) unsanitizedGet(key string) any {\n\treturn l.k.Get(key)\n}\n\n// sanitize recursively removes expandedValue references from the given data.\n// It uses the expandedValue.Value field to replace the expandedValue references.\nfunc sanitize(a any) any {\n\treturn sanitizeExpanded(a, false)\n}\n\n// sanitizeToStringMap recursively removes expandedValue references from the given data.\n// It uses the expandedValue.Original field to replace the expandedValue references.\nfunc sanitizeToStr(a any) any {\n\treturn sanitizeExpanded(a, true)\n}\n\nfunc sanitizeExpanded(a any, useOriginal bool) any {\n\tswitch m := a.(type) {\n\tcase map[string]any:\n\t\tc := maps.Copy(m)\n\t\tfor k, v := range m {\n\t\t\tc[k] = sanitizeExpanded(v, useOriginal)\n\t\t}\n\t\treturn c\n\tcase []any:\n\t\t// If the value is nil, return nil.\n\t\tvar newSlice []any\n\t\tif m == nil {\n\t\t\treturn newSlice\n\t\t}\n\t\tnewSlice = make([]any, 0, len(m))\n\t\tfor _, e := range m {\n\t\t\tnewSlice = append(newSlice, sanitizeExpanded(e, useOriginal))\n\t\t}\n\t\treturn newSlice\n\tcase ExpandedValue:\n\t\tif useOriginal {\n\t\t\treturn m.Original\n\t\t}\n\t\treturn m.Value\n\t}\n\treturn a\n}\n\ntype UnsanitizedGetter struct {\n\tConf *Conf\n}\n\nfunc (ug *UnsanitizedGetter) UnsanitizedGet(key string) any {\n\treturn ug.Conf.unsanitizedGet(key)\n}\n"
  },
  {
    "path": "confmap/internal/confmap.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/confmap/internal\"\n\n// Unmarshaler interface may be implemented by types to customize their behavior when being unmarshaled from a Conf.\n// Only types with struct or pointer to struct kind are supported.\ntype Unmarshaler interface {\n\t// Unmarshal a Conf into the struct in a custom way.\n\t// The Conf for this specific component may be nil or empty if no config available.\n\t// This method should only be called by decoding hooks when calling Conf.Unmarshal.\n\tUnmarshal(component *Conf) error\n}\n\n// Marshaler defines an optional interface for custom configuration marshaling.\n// A configuration struct can implement this interface to override the default\n// marshaling.\ntype Marshaler interface {\n\t// Marshal the config into a Conf in a custom way.\n\t// The Conf will be empty and can be merged into.\n\tMarshal(component *Conf) error\n}\n"
  },
  {
    "path": "confmap/internal/confmap_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"encoding\"\n\t\"errors\"\n\t\"math\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.yaml.in/yaml/v3\"\n\n\t\"go.opentelemetry.io/collector/confmap/internal/metadata\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\nfunc TestToStringMapFlatten(t *testing.T) {\n\tconf := NewFromStringMap(map[string]any{\"key::embedded\": int64(123)})\n\tassert.Equal(t, map[string]any{\"key\": map[string]any{\"embedded\": int64(123)}}, conf.ToStringMap())\n}\n\nfunc TestToStringMap(t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tfileName  string\n\t\tstringMap map[string]any\n\t}{\n\t\t{\n\t\t\tname:     \"Sample Collector configuration\",\n\t\t\tfileName: filepath.Join(\"testdata\", \"config.yaml\"),\n\t\t\tstringMap: map[string]any{\n\t\t\t\t\"receivers\": map[string]any{\n\t\t\t\t\t\"nop\":            nil,\n\t\t\t\t\t\"nop/myreceiver\": nil,\n\t\t\t\t},\n\n\t\t\t\t\"processors\": map[string]any{\n\t\t\t\t\t\"nop\":             nil,\n\t\t\t\t\t\"nop/myprocessor\": nil,\n\t\t\t\t},\n\n\t\t\t\t\"exporters\": map[string]any{\n\t\t\t\t\t\"nop\":            nil,\n\t\t\t\t\t\"nop/myexporter\": nil,\n\t\t\t\t},\n\n\t\t\t\t\"extensions\": map[string]any{\n\t\t\t\t\t\"nop\":             nil,\n\t\t\t\t\t\"nop/myextension\": nil,\n\t\t\t\t},\n\n\t\t\t\t\"service\": map[string]any{\n\t\t\t\t\t\"extensions\": []any{\"nop\"},\n\t\t\t\t\t\"pipelines\": map[string]any{\n\t\t\t\t\t\t\"traces\": map[string]any{\n\t\t\t\t\t\t\t\"receivers\":  []any{\"nop\"},\n\t\t\t\t\t\t\t\"processors\": []any{\"nop\"},\n\t\t\t\t\t\t\t\"exporters\":  []any{\"nop\"},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:     \"Sample types\",\n\t\t\tfileName: filepath.Join(\"testdata\", \"basic_types.yaml\"),\n\t\t\tstringMap: map[string]any{\n\t\t\t\t\"typed.options\": map[string]any{\n\t\t\t\t\t\"floating.point.example\": 3.14,\n\t\t\t\t\t\"integer.example\":        1234,\n\t\t\t\t\t\"bool.example\":           false,\n\t\t\t\t\t\"string.example\":         \"this is a string\",\n\t\t\t\t\t\"nil.example\":            nil,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:     \"Embedded keys\",\n\t\t\tfileName: filepath.Join(\"testdata\", \"embedded_keys.yaml\"),\n\t\t\tstringMap: map[string]any{\n\t\t\t\t\"typed\": map[string]any{\"options\": map[string]any{\n\t\t\t\t\t\"floating\": map[string]any{\"point\": map[string]any{\"example\": 3.14}},\n\t\t\t\t\t\"integer\":  map[string]any{\"example\": 1234},\n\t\t\t\t\t\"bool\":     map[string]any{\"example\": false},\n\t\t\t\t\t\"string\":   map[string]any{\"example\": \"this is a string\"},\n\t\t\t\t\t\"nil\":      map[string]any{\"example\": nil},\n\t\t\t\t}},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tassert.Equal(t, test.stringMap, newConfFromFile(t, test.fileName))\n\t\t})\n\t}\n}\n\ntype testConfigAny struct {\n\tAnyField any `mapstructure:\"any_field\"`\n}\n\nfunc TestNilToAnyField(t *testing.T) {\n\tstringMap := map[string]any{\n\t\t\"any_field\": nil,\n\t}\n\tconf := NewFromStringMap(stringMap)\n\tcfg := &testConfigAny{}\n\trequire.NoError(t, conf.Unmarshal(cfg))\n\tassert.Nil(t, cfg.AnyField)\n}\n\nfunc TestExpandNilStructPointersHookFunc(t *testing.T) {\n\tstringMap := map[string]any{\n\t\t\"boolean\": nil,\n\t\t\"struct\":  nil,\n\t\t\"map_struct\": map[string]any{\n\t\t\t\"struct\": nil,\n\t\t},\n\t}\n\tconf := NewFromStringMap(stringMap)\n\tcfg := &testConfig{}\n\tassert.Nil(t, cfg.Struct)\n\trequire.NoError(t, conf.Unmarshal(cfg))\n\tassert.Nil(t, cfg.Boolean)\n\t// assert.False(t, *cfg.Boolean)\n\tassert.Nil(t, cfg.Struct)\n\tassert.NotNil(t, cfg.MapStruct)\n\tassert.Equal(t, &myStruct{}, cfg.MapStruct[\"struct\"])\n}\n\nfunc TestExpandNilStructPointersHookFuncDefaultNotNilConfigNil(t *testing.T) {\n\tstringMap := map[string]any{\n\t\t\"boolean\": nil,\n\t\t\"struct\":  nil,\n\t\t\"map_struct\": map[string]any{\n\t\t\t\"struct\": nil,\n\t\t},\n\t}\n\tconf := NewFromStringMap(stringMap)\n\tvarBool := true\n\ts1 := &myStruct{Name: \"s1\"}\n\ts2 := &myStruct{Name: \"s2\"}\n\tcfg := &testConfig{\n\t\tBoolean:   &varBool,\n\t\tStruct:    s1,\n\t\tMapStruct: map[string]*myStruct{\"struct\": s2},\n\t}\n\trequire.NoError(t, conf.Unmarshal(cfg))\n\tassert.NotNil(t, cfg.Boolean)\n\tassert.True(t, *cfg.Boolean)\n\tassert.NotNil(t, cfg.Struct)\n\tassert.Equal(t, s1, cfg.Struct)\n\tassert.NotNil(t, cfg.MapStruct)\n\tassert.Equal(t, &myStruct{}, cfg.MapStruct[\"struct\"])\n}\n\nfunc TestUnmarshalWithIgnoreUnused(t *testing.T) {\n\tstringMap := map[string]any{\n\t\t\"boolean\": true,\n\t\t\"string\":  \"this is a string\",\n\t}\n\tconf := NewFromStringMap(stringMap)\n\trequire.Error(t, conf.Unmarshal(&testIDConfig{}))\n\tassert.NoError(t, conf.Unmarshal(&testIDConfig{}, WithIgnoreUnused()))\n}\n\ntype testConfig struct {\n\tBoolean   *bool                `mapstructure:\"boolean\"`\n\tStruct    *myStruct            `mapstructure:\"struct\"`\n\tMapStruct map[string]*myStruct `mapstructure:\"map_struct\"`\n}\n\nfunc (t testConfig) Marshal(conf *Conf) error {\n\tif t.Boolean != nil && !*t.Boolean {\n\t\treturn errors.New(\"unable to marshal\")\n\t}\n\tif err := conf.Marshal(t); err != nil {\n\t\treturn err\n\t}\n\treturn conf.Merge(NewFromStringMap(map[string]any{\n\t\t\"additional\": \"field\",\n\t}))\n}\n\ntype myStruct struct {\n\tName string\n}\n\ntype TestID string\n\nfunc (tID *TestID) UnmarshalText(text []byte) error {\n\t*tID = TestID(strings.TrimSuffix(string(text), \"_\"))\n\tif *tID == \"error\" {\n\t\treturn errors.New(\"parsing error\")\n\t}\n\treturn nil\n}\n\nfunc (tID TestID) MarshalText() (text []byte, err error) {\n\tout := string(tID)\n\tif !strings.HasSuffix(out, \"_\") {\n\t\tout += \"_\"\n\t}\n\treturn []byte(out), nil\n}\n\ntype testIDConfig struct {\n\tBoolean bool              `mapstructure:\"bool\"`\n\tMap     map[TestID]string `mapstructure:\"map\"`\n}\n\nfunc TestMapKeyStringToMapKeyTextUnmarshalerHookFunc(t *testing.T) {\n\tstringMap := map[string]any{\n\t\t\"bool\": true,\n\t\t\"map\": map[string]any{\n\t\t\t\"string\": \"this is a string\",\n\t\t},\n\t}\n\tconf := NewFromStringMap(stringMap)\n\n\tcfg := &testIDConfig{}\n\trequire.NoError(t, conf.Unmarshal(cfg))\n\tassert.True(t, cfg.Boolean)\n\tassert.Equal(t, map[TestID]string{\"string\": \"this is a string\"}, cfg.Map)\n}\n\ntype uint32Config struct {\n\tValue uint32 `mapstructure:\"value\"`\n}\n\nfunc TestUint32UnmarshalerSuccess(t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\ttestValue uint32\n\t}{\n\t\t{\n\t\t\tname:      \"Test convert 0 to uint\",\n\t\t\ttestValue: 0,\n\t\t},\n\t\t{\n\t\t\tname:      \"Test positive uint conversion\",\n\t\t\ttestValue: 1000,\n\t\t},\n\t\t{\n\t\t\tname:      \"Test largest uint64 conversion\",\n\t\t\ttestValue: math.MaxUint32,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tstringMap := map[string]any{\n\t\t\t\t\"value\": int(tt.testValue),\n\t\t\t}\n\t\t\tconf := NewFromStringMap(stringMap)\n\t\t\tcfg := &uint32Config{}\n\t\t\terr := conf.Unmarshal(cfg)\n\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, cfg.Value, tt.testValue)\n\t\t})\n\t}\n}\n\nfunc TestUint32UnmarshalerFailure(t *testing.T) {\n\tstringMap := map[string]any{\n\t\t\"value\": -1000,\n\t}\n\tconf := NewFromStringMap(stringMap)\n\tcfg := &uint32Config{}\n\terr := conf.Unmarshal(cfg)\n\n\tassert.ErrorContains(t, err, \"decoding failed due to the following error(s):\\n\\n'value' cannot parse value as 'uint32': -1000 overflows uint\")\n}\n\ntype uint64Config struct {\n\tValue uint64 `mapstructure:\"value\"`\n}\n\nfunc TestUint64Unmarshaler(t *testing.T) {\n\t// Equivalent to -1000, but converted to uint64\n\tvalue := uint64(1000)\n\ttestValue := ^(value - 1)\n\n\tstringMap := map[string]any{\n\t\t\"value\": testValue,\n\t}\n\n\tconf := NewFromStringMap(stringMap)\n\tcfg := &uint64Config{}\n\terr := conf.Unmarshal(cfg)\n\n\trequire.NoError(t, err)\n\tassert.Equal(t, cfg.Value, testValue)\n}\n\nfunc TestUint64UnmarshalerFailure(t *testing.T) {\n\tstringMap := map[string]any{\n\t\t\"value\": -1000,\n\t}\n\tconf := NewFromStringMap(stringMap)\n\tcfg := &uint64Config{}\n\terr := conf.Unmarshal(cfg)\n\n\tassert.ErrorContains(t, err, \"decoding failed due to the following error(s):\\n\\n'value' cannot parse value as 'uint64': -1000 overflows uint\")\n}\n\nfunc TestMapKeyStringToMapKeyTextUnmarshalerHookFuncDuplicateID(t *testing.T) {\n\tstringMap := map[string]any{\n\t\t\"bool\": true,\n\t\t\"map\": map[string]any{\n\t\t\t\"string\":  \"this is a string\",\n\t\t\t\"string_\": \"this is another string\",\n\t\t},\n\t}\n\tconf := NewFromStringMap(stringMap)\n\n\tcfg := &testIDConfig{}\n\tassert.Error(t, conf.Unmarshal(cfg))\n}\n\nfunc TestMapKeyStringToMapKeyTextUnmarshalerHookFuncErrorUnmarshal(t *testing.T) {\n\tstringMap := map[string]any{\n\t\t\"bool\": true,\n\t\t\"map\": map[string]any{\n\t\t\t\"error\": \"this is a string\",\n\t\t},\n\t}\n\tconf := NewFromStringMap(stringMap)\n\n\tcfg := &testIDConfig{}\n\tassert.Error(t, conf.Unmarshal(cfg))\n}\n\nfunc TestMarshal(t *testing.T) {\n\tconf := New()\n\tcfg := &testIDConfig{\n\t\tBoolean: true,\n\t\tMap: map[TestID]string{\n\t\t\t\"string\": \"this is a string\",\n\t\t},\n\t}\n\trequire.NoError(t, conf.Marshal(cfg))\n\tassert.Equal(t, true, conf.Get(\"bool\"))\n\tassert.Equal(t, map[string]any{\"string_\": \"this is a string\"}, conf.Get(\"map\"))\n}\n\nfunc TestMarshalDuplicateID(t *testing.T) {\n\tconf := New()\n\tcfg := &testIDConfig{\n\t\tBoolean: true,\n\t\tMap: map[TestID]string{\n\t\t\t\"string\":  \"this is a string\",\n\t\t\t\"string_\": \"this is another string\",\n\t\t},\n\t}\n\tassert.Error(t, conf.Marshal(cfg))\n}\n\nfunc TestMarshalError(t *testing.T) {\n\tconf := New()\n\tassert.Error(t, conf.Marshal(nil))\n}\n\nfunc TestMarshaler(t *testing.T) {\n\tconf := New()\n\tcfg := &testConfig{\n\t\tStruct: &myStruct{\n\t\t\tName: \"StructName\",\n\t\t},\n\t}\n\trequire.NoError(t, conf.Marshal(cfg))\n\tassert.Equal(t, \"field\", conf.Get(\"additional\"))\n\n\tconf = New()\n\ttype NestedMarshaler struct {\n\t\tTestConfig *testConfig\n\t}\n\tnmCfg := &NestedMarshaler{\n\t\tTestConfig: cfg,\n\t}\n\trequire.NoError(t, conf.Marshal(nmCfg))\n\tsub, err := conf.Sub(\"testconfig\")\n\trequire.NoError(t, err)\n\tassert.True(t, sub.IsSet(\"additional\"))\n\tassert.Equal(t, \"field\", sub.Get(\"additional\"))\n\tvarBool := false\n\tnmCfg.TestConfig.Boolean = &varBool\n\tassert.Error(t, conf.Marshal(nmCfg))\n}\n\n// newConfFromFile creates a new Conf by reading the given file.\nfunc newConfFromFile(tb testing.TB, fileName string) map[string]any {\n\tcontent, err := os.ReadFile(filepath.Clean(fileName))\n\trequire.NoErrorf(tb, err, \"unable to read the file %v\", fileName)\n\n\tvar data map[string]any\n\trequire.NoError(tb, yaml.Unmarshal(content, &data), \"unable to parse yaml\")\n\n\treturn NewFromStringMap(data).ToStringMap()\n}\n\ntype testConfig2 struct {\n\tNext            *nextConfig `mapstructure:\"next\"`\n\tAnother         string      `mapstructure:\"another\"`\n\tEmbeddedConfig  `mapstructure:\",squash\"`\n\tEmbeddedConfig2 `mapstructure:\",squash\"`\n}\n\ntype testConfigWithoutUnmarshaler struct {\n\tNext            *nextConfig `mapstructure:\"next\"`\n\tAnother         string      `mapstructure:\"another\"`\n\tEmbeddedConfig  `mapstructure:\",squash\"`\n\tEmbeddedConfig2 `mapstructure:\",squash\"`\n}\n\ntype testConfigWithEmbeddedError struct {\n\tNext                    *nextConfig `mapstructure:\"next\"`\n\tAnother                 string      `mapstructure:\"another\"`\n\tEmbeddedConfigWithError `mapstructure:\",squash\"`\n}\n\ntype testConfigWithMarshalError struct {\n\tNext                           *nextConfig `mapstructure:\"next\"`\n\tAnother                        string      `mapstructure:\"another\"`\n\tEmbeddedConfigWithMarshalError `mapstructure:\",squash\"`\n}\n\nfunc (tc *testConfigWithEmbeddedError) Unmarshal(component *Conf) error {\n\tif err := component.Unmarshal(tc, WithIgnoreUnused()); err != nil {\n\t\treturn err\n\t}\n\treturn nil\n}\n\ntype EmbeddedConfig struct {\n\tSome string `mapstructure:\"some\"`\n}\n\nfunc (ec *EmbeddedConfig) Unmarshal(component *Conf) error {\n\tif err := component.Unmarshal(ec, WithIgnoreUnused()); err != nil {\n\t\treturn err\n\t}\n\tec.Some += \" is also called\"\n\treturn nil\n}\n\ntype EmbeddedConfig2 struct {\n\tSome2 string `mapstructure:\"some_2\"`\n}\n\nfunc (ec *EmbeddedConfig2) Unmarshal(component *Conf) error {\n\tif err := component.Unmarshal(ec, WithIgnoreUnused()); err != nil {\n\t\treturn err\n\t}\n\tec.Some2 += \" also called2\"\n\treturn nil\n}\n\ntype EmbeddedConfigWithError struct{}\n\nfunc (ecwe *EmbeddedConfigWithError) Unmarshal(_ *Conf) error {\n\treturn errors.New(\"embedded error\")\n}\n\ntype EmbeddedConfigWithMarshalError struct{}\n\nfunc (ecwe EmbeddedConfigWithMarshalError) Marshal(_ *Conf) error {\n\treturn errors.New(\"marshaling error\")\n}\n\nfunc (ecwe EmbeddedConfigWithMarshalError) Unmarshal(_ *Conf) error {\n\treturn nil\n}\n\nfunc (tc *testConfig2) Unmarshal(component *Conf) error {\n\tif err := component.Unmarshal(tc); err != nil {\n\t\treturn err\n\t}\n\ttc.Another += \" is only called directly\"\n\treturn nil\n}\n\ntype nextConfig struct {\n\tString  string `mapstructure:\"string\"`\n\tprivate string\n}\n\nfunc (nc *nextConfig) Unmarshal(component *Conf) error {\n\tif err := component.Unmarshal(nc); err != nil {\n\t\treturn err\n\t}\n\tnc.String += \" is called\"\n\treturn nil\n}\n\nfunc TestUnmarshaler(t *testing.T) {\n\tcfgMap := NewFromStringMap(map[string]any{\n\t\t\"next\": map[string]any{\n\t\t\t\"string\": \"make sure this\",\n\t\t},\n\t\t\"another\": \"make sure this\",\n\t\t\"some\":    \"make sure this\",\n\t\t\"some_2\":  \"this better be\",\n\t})\n\n\ttc := &testConfig2{}\n\trequire.NoError(t, cfgMap.Unmarshal(tc))\n\tassert.Equal(t, \"make sure this is only called directly\", tc.Another)\n\tassert.Equal(t, \"make sure this is called\", tc.Next.String)\n\tassert.Equal(t, \"make sure this is also called\", tc.Some)\n\tassert.Equal(t, \"this better be also called2\", tc.Some2)\n}\n\nfunc TestEmbeddedUnmarshaler(t *testing.T) {\n\tcfgMap := NewFromStringMap(map[string]any{\n\t\t\"next\": map[string]any{\n\t\t\t\"string\": \"make sure this\",\n\t\t},\n\t\t\"another\": \"make sure this\",\n\t\t\"some\":    \"make sure this\",\n\t\t\"some_2\":  \"this better be\",\n\t})\n\n\ttc := &testConfigWithoutUnmarshaler{}\n\trequire.NoError(t, cfgMap.Unmarshal(tc))\n\tassert.Equal(t, \"make sure this\", tc.Another)\n\tassert.Equal(t, \"make sure this is called\", tc.Next.String)\n\tassert.Equal(t, \"make sure this is also called\", tc.Some)\n\tassert.Equal(t, \"this better be also called2\", tc.Some2)\n}\n\nfunc TestEmbeddedUnmarshalerError(t *testing.T) {\n\tcfgMap := NewFromStringMap(map[string]any{\n\t\t\"next\": map[string]any{\n\t\t\t\"string\": \"make sure this\",\n\t\t},\n\t\t\"another\": \"make sure this\",\n\t\t\"some\":    \"make sure this\",\n\t})\n\n\ttc := &testConfigWithEmbeddedError{}\n\tassert.ErrorContains(t, cfgMap.Unmarshal(tc), \"embedded error\")\n}\n\nfunc TestEmbeddedMarshalerError(t *testing.T) {\n\tt.Skip(\"This test fails because the main struct calls the embedded struct Unmarshal method, and doesn't execute the embedded struct hook.\")\n\tcfgMap := NewFromStringMap(map[string]any{\n\t\t\"next\": map[string]any{\n\t\t\t\"string\": \"make sure this\",\n\t\t},\n\t\t\"another\": \"make sure this\",\n\t})\n\n\ttc := &testConfigWithMarshalError{}\n\tassert.EqualError(t, cfgMap.Unmarshal(tc), \"error running encode hook: marshaling error\")\n}\n\n// stringOpaque is similar to configopaque.String, in that\n// marshaling then unmarshaling it changes its value.\ntype stringOpaque string\n\nvar _ encoding.TextMarshaler = stringOpaque(\"\")\n\nfunc (s stringOpaque) MarshalText() (text []byte, err error) {\n\treturn []byte(\"opaque\"), nil\n}\n\ntype squashedConfigOpaque struct {\n\tValue  stringOpaque `mapstructure:\"value\"`\n\tsecret bool\n}\n\nvar _ Unmarshaler = (*squashedConfigOpaque)(nil)\n\nfunc (ecwrt *squashedConfigOpaque) Unmarshal(conf *Conf) error {\n\tif err := conf.Unmarshal(ecwrt); err != nil {\n\t\treturn err\n\t}\n\tecwrt.secret = true\n\treturn nil\n}\n\ntype testConfigOpaque struct {\n\t// Don't embed, otherwise testConfigOpaque will implement Unmarshaler,\n\t// and unmarshalerHookFunc will be called instead of unmarshalerEmbeddedStructsHookFunc.\n\tSquashed squashedConfigOpaque `mapstructure:\",squash\"`\n}\n\n// Regression test: the hook processing embedded marshalers previously made the assumption that\n// marshaling a struct then unmarshaling the resulting map back into the struct\n// is a no-op, which is not true for configopaque.String.\nfunc TestEmbeddedMarshalerWithoutRoundtrip(t *testing.T) {\n\tcfgMap := NewFromStringMap(map[string]any{\n\t\t\"value\": \"hello\",\n\t})\n\n\ttc := &testConfigOpaque{}\n\trequire.NoError(t, cfgMap.Unmarshal(tc))\n\t// Check that \"hello\" hasn't been replaced by \"opaque\"\n\tassert.Equal(t, \"hello\", string(tc.Squashed.Value))\n\t// Check that the inner Unmarshal was called\n\tassert.True(t, tc.Squashed.secret)\n}\n\ntype B struct {\n\tString string `mapstructure:\"string\"`\n}\n\nfunc (b *B) Unmarshal(conf *Conf) error {\n\treturn conf.Unmarshal(b)\n}\n\ntype A struct {\n\tB `mapstructure:\",squash\"`\n}\n\nfunc (a *A) Unmarshal(conf *Conf) error {\n\treturn conf.Unmarshal(a)\n}\n\nfunc TestUnmarshalerEmbeddedNilMap(t *testing.T) {\n\tcfg := A{}\n\tnilConf := NewFromStringMap(nil)\n\trequire.NoError(t, nilConf.Unmarshal(&cfg))\n}\n\nfunc TestUnmarshalerKeepAlreadyInitialized(t *testing.T) {\n\tcfgMap := NewFromStringMap(map[string]any{\n\t\t\"next\": map[string]any{\n\t\t\t\"string\": \"make sure this\",\n\t\t},\n\t\t\"another\": \"make sure this\",\n\t})\n\n\ttc := &testConfig2{Next: &nextConfig{\n\t\tprivate: \"keep already configured members\",\n\t}}\n\trequire.NoError(t, cfgMap.Unmarshal(tc))\n\tassert.Equal(t, \"make sure this is only called directly\", tc.Another)\n\tassert.Equal(t, \"make sure this is called\", tc.Next.String)\n\tassert.Equal(t, \"keep already configured members\", tc.Next.private)\n}\n\nfunc TestDirectUnmarshaler(t *testing.T) {\n\tcfgMap := NewFromStringMap(map[string]any{\n\t\t\"next\": map[string]any{\n\t\t\t\"string\": \"make sure this\",\n\t\t},\n\t\t\"another\": \"make sure this\",\n\t})\n\n\ttc := &testConfig2{Next: &nextConfig{\n\t\tprivate: \"keep already configured members\",\n\t}}\n\trequire.NoError(t, tc.Unmarshal(cfgMap))\n\tassert.Equal(t, \"make sure this is only called directly is only called directly\", tc.Another)\n\tassert.Equal(t, \"make sure this is called\", tc.Next.String)\n\tassert.Equal(t, \"keep already configured members\", tc.Next.private)\n}\n\ntype testErrConfig struct {\n\tErr errConfig `mapstructure:\"err\"`\n}\n\ntype errConfig struct {\n\tFoo string `mapstructure:\"foo\"`\n}\n\nfunc (tc *errConfig) Unmarshal(*Conf) error {\n\treturn errors.New(\"never works\")\n}\n\nfunc TestUnmarshalerErr(t *testing.T) {\n\tcfgMap := NewFromStringMap(map[string]any{\n\t\t\"err\": map[string]any{\n\t\t\t\"foo\": \"will not unmarshal due to error\",\n\t\t},\n\t})\n\n\ttc := &testErrConfig{}\n\trequire.EqualError(t, cfgMap.Unmarshal(tc), \"decoding failed due to the following error(s):\\n\\n'err' never works\")\n\tassert.Empty(t, tc.Err.Foo)\n}\n\nfunc TestZeroSliceHookFunc(t *testing.T) {\n\ttype structWithSlices struct {\n\t\tStrings []string `mapstructure:\"strings\"`\n\t}\n\n\ttests := []struct {\n\t\tname     string\n\t\tcfg      map[string]any\n\t\tprovided any\n\t\texpected any\n\t}{\n\t\t{\n\t\t\tname: \"overridden by slice\",\n\t\t\tcfg: map[string]any{\n\t\t\t\t\"strings\": []string{\"111\"},\n\t\t\t},\n\t\t\tprovided: &structWithSlices{\n\t\t\t\tStrings: []string{\"xxx\", \"yyyy\", \"zzzz\"},\n\t\t\t},\n\t\t\texpected: &structWithSlices{\n\t\t\t\tStrings: []string{\"111\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"overridden by a bigger slice\",\n\t\t\tcfg: map[string]any{\n\t\t\t\t\"strings\": []string{\"111\", \"222\", \"333\"},\n\t\t\t},\n\t\t\tprovided: &structWithSlices{\n\t\t\t\tStrings: []string{\"xxx\", \"yyyy\"},\n\t\t\t},\n\t\t\texpected: &structWithSlices{\n\t\t\t\tStrings: []string{\"111\", \"222\", \"333\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"overridden by an empty slice\",\n\t\t\tcfg: map[string]any{\n\t\t\t\t\"strings\": []string{},\n\t\t\t},\n\t\t\tprovided: &structWithSlices{\n\t\t\t\tStrings: []string{\"xxx\", \"yyyy\"},\n\t\t\t},\n\t\t\texpected: &structWithSlices{\n\t\t\t\tStrings: []string{},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"not overridden by nil\",\n\t\t\tcfg: map[string]any{\n\t\t\t\t\"strings\": nil,\n\t\t\t},\n\t\t\tprovided: &structWithSlices{\n\t\t\t\tStrings: []string{\"xxx\", \"yyyy\"},\n\t\t\t},\n\t\t\texpected: &structWithSlices{\n\t\t\t\tStrings: []string{\"xxx\", \"yyyy\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"not overridden by missing value\",\n\t\t\tcfg:  map[string]any{},\n\t\t\tprovided: &structWithSlices{\n\t\t\t\tStrings: []string{\"xxx\", \"yyyy\"},\n\t\t\t},\n\t\t\texpected: &structWithSlices{\n\t\t\t\tStrings: []string{\"xxx\", \"yyyy\"},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := NewFromStringMap(tt.cfg)\n\n\t\t\terr := cfg.Unmarshal(tt.provided)\n\t\t\tif assert.NoError(t, err) {\n\t\t\t\tassert.Equal(t, tt.expected, tt.provided)\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Tests for issue that happened in https://github.com/open-telemetry/opentelemetry-collector/issues/12661.\nfunc TestStructValuesReplaced(t *testing.T) {\n\ttype S struct {\n\t\tA string `mapstructure:\"A,omitempty\"`\n\t\tB string `mapstructure:\"B,omitempty\"`\n\t}\n\n\ttype structWithSlices struct {\n\t\tStructs []S `mapstructure:\"structs\"`\n\t}\n\n\tslicesStruct := structWithSlices{\n\t\tStructs: []S{\n\t\t\t{A: \"A\"},\n\t\t},\n\t}\n\n\tbCfg := map[string]any{\n\t\t\"structs\": []any{\n\t\t\tmap[string]any{\n\t\t\t\t\"B\": \"B\",\n\t\t\t},\n\t\t},\n\t}\n\tbConf := NewFromStringMap(bCfg)\n\terr := bConf.Unmarshal(&slicesStruct)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, []S{{B: \"B\"}}, slicesStruct.Structs)\n}\n\nfunc TestNilValuesUnchanged(t *testing.T) {\n\ttype structWithSlices struct {\n\t\tStrings []string `mapstructure:\"strings\"`\n\t}\n\n\tslicesStruct := &structWithSlices{}\n\n\tnilCfg := map[string]any{\n\t\t\"strings\": []any(nil),\n\t}\n\tnilConf := NewFromStringMap(nilCfg)\n\terr := nilConf.Unmarshal(slicesStruct)\n\trequire.NoError(t, err)\n\n\tconfFromStruct := New()\n\terr = confFromStruct.Marshal(slicesStruct)\n\trequire.NoError(t, err)\n\n\trequire.Equal(t, nilCfg, nilConf.ToStringMap())\n\trequire.Equal(t, confFromStruct.ToStringMap(), nilConf.ToStringMap())\n}\n\nfunc TestEmptySliceUnchanged(t *testing.T) {\n\ttype structWithSlices struct {\n\t\tStrings []string `mapstructure:\"strings\"`\n\t}\n\n\tslicesStruct := &structWithSlices{}\n\n\tnilCfg := map[string]any{\n\t\t\"strings\": []any{},\n\t}\n\tnilConf := NewFromStringMap(nilCfg)\n\terr := nilConf.Unmarshal(slicesStruct)\n\trequire.NoError(t, err)\n\n\tconfFromStruct := New()\n\terr = confFromStruct.Marshal(slicesStruct)\n\trequire.NoError(t, err)\n\n\trequire.Equal(t, nilCfg, nilConf.ToStringMap())\n\trequire.Equal(t, nilConf.ToStringMap(), confFromStruct.ToStringMap())\n}\n\ntype c struct {\n\tModifiers []string `mapstructure:\"modifiers\"`\n}\n\nfunc (c *c) Unmarshal(conf *Conf) error {\n\tif err := conf.Unmarshal(c); err != nil {\n\t\treturn err\n\t}\n\tc.Modifiers = append(c.Modifiers, \"c.Unmarshal\")\n\treturn nil\n}\n\ntype b struct {\n\tModifiers []string `mapstructure:\"modifiers\"`\n\tC         c        `mapstructure:\"c\"`\n}\n\nfunc (b *b) Unmarshal(conf *Conf) error {\n\tif err := conf.Unmarshal(b); err != nil {\n\t\treturn err\n\t}\n\tb.Modifiers = append(b.Modifiers, \"B.Unmarshal\")\n\tb.C.Modifiers = append(b.C.Modifiers, \"B.Unmarshal\")\n\treturn nil\n}\n\ntype a struct {\n\tModifiers []string `mapstructure:\"modifiers\"`\n\tB         b        `mapstructure:\"b\"`\n}\n\nfunc (a *a) Unmarshal(conf *Conf) error {\n\tif err := conf.Unmarshal(a); err != nil {\n\t\treturn err\n\t}\n\ta.Modifiers = append(a.Modifiers, \"A.Unmarshal\")\n\ta.B.Modifiers = append(a.B.Modifiers, \"A.Unmarshal\")\n\ta.B.C.Modifiers = append(a.B.C.Modifiers, \"A.Unmarshal\")\n\treturn nil\n}\n\ntype wrapper struct {\n\tA a `mapstructure:\"a\"`\n}\n\n// Test that calling the Unmarshal method on configuration structs is done from the inside out.\nfunc TestNestedUnmarshalerImplementations(t *testing.T) {\n\tconf := NewFromStringMap(map[string]any{\"a\": map[string]any{\n\t\t\"modifiers\": []string{\"conf.Unmarshal\"},\n\t\t\"b\": map[string]any{\n\t\t\t\"modifiers\": []string{\"conf.Unmarshal\"},\n\t\t\t\"c\": map[string]any{\n\t\t\t\t\"modifiers\": []string{\"conf.Unmarshal\"},\n\t\t\t},\n\t\t},\n\t}})\n\n\t// Use a wrapper struct until we deprecate component.UnmarshalConfig\n\tw := &wrapper{}\n\trequire.NoError(t, conf.Unmarshal(w))\n\n\ta := w.A\n\tassert.Equal(t, []string{\"conf.Unmarshal\", \"A.Unmarshal\"}, a.Modifiers)\n\tassert.Equal(t, []string{\"conf.Unmarshal\", \"B.Unmarshal\", \"A.Unmarshal\"}, a.B.Modifiers)\n\tassert.Equal(t, []string{\"conf.Unmarshal\", \"c.Unmarshal\", \"B.Unmarshal\", \"A.Unmarshal\"}, a.B.C.Modifiers)\n}\n\n// Test that unmarshaling the same conf twice works.\nfunc TestUnmarshalDouble(t *testing.T) {\n\tconf := NewFromStringMap(map[string]any{\n\t\t\"str\": \"test\",\n\t})\n\n\ttype Struct struct {\n\t\tStr string `mapstructure:\"str\"`\n\t}\n\ts := &Struct{}\n\trequire.NoError(t, conf.Unmarshal(s))\n\tassert.Equal(t, \"test\", s.Str)\n\n\ttype Struct2 struct {\n\t\tStr string `mapstructure:\"str\"`\n\t}\n\ts2 := &Struct2{}\n\trequire.NoError(t, conf.Unmarshal(s2))\n\tassert.Equal(t, \"test\", s2.Str)\n}\n\ntype embeddedStructWithUnmarshal struct {\n\tFoo     string `mapstructure:\"foo\"`\n\tsuccess string\n}\n\nfunc (e *embeddedStructWithUnmarshal) Unmarshal(c *Conf) error {\n\tif err := c.Unmarshal(e, WithIgnoreUnused()); err != nil {\n\t\treturn err\n\t}\n\te.success = \"success\"\n\treturn nil\n}\n\ntype configWithUnmarshalFromEmbeddedStruct struct {\n\tembeddedStructWithUnmarshal\n}\n\ntype topLevel struct {\n\tCfg *configWithUnmarshalFromEmbeddedStruct `mapstructure:\"toplevel\"`\n}\n\n// Test that Unmarshal is called on the embedded struct on the struct.\nfunc TestUnmarshalThroughEmbeddedStruct(t *testing.T) {\n\tc := NewFromStringMap(map[string]any{\n\t\t\"toplevel\": map[string]any{\n\t\t\t\"foo\": \"bar\",\n\t\t},\n\t})\n\tcfg := &topLevel{}\n\terr := c.Unmarshal(cfg)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"success\", cfg.Cfg.success)\n\trequire.Equal(t, \"bar\", cfg.Cfg.Foo)\n}\n\ntype configWithOwnUnmarshalAndEmbeddedSquashedStruct struct {\n\tembeddedStructWithUnmarshal `mapstructure:\",squash\"`\n}\n\ntype topLevelSquashedEmbedded struct {\n\tCfg *configWithOwnUnmarshalAndEmbeddedSquashedStruct `mapstructure:\"toplevel\"`\n}\n\n// Test that the Unmarshal method is called on the squashed, embedded struct.\nfunc TestUnmarshalOwnThroughEmbeddedSquashedStruct(t *testing.T) {\n\tc := NewFromStringMap(map[string]any{\n\t\t\"toplevel\": map[string]any{\n\t\t\t\"foo\": \"bar\",\n\t\t},\n\t})\n\tcfg := &topLevelSquashedEmbedded{}\n\terr := c.Unmarshal(cfg)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"success\", cfg.Cfg.success)\n\trequire.Equal(t, \"bar\", cfg.Cfg.Foo)\n}\n\ntype recursive struct {\n\tFoo string `mapstructure:\"foo\"`\n}\n\nfunc (r *recursive) Unmarshal(conf *Conf) error {\n\tnewR := &recursive{}\n\tif err := conf.Unmarshal(newR); err != nil {\n\t\treturn err\n\t}\n\t*r = *newR\n\treturn nil\n}\n\n// Tests that a struct can unmarshal itself by creating a new copy of itself, unmarshaling itself, and setting its value.\nfunc TestRecursiveUnmarshaling(t *testing.T) {\n\tconf := NewFromStringMap(map[string]any{\n\t\t\"foo\": \"something\",\n\t})\n\tr := &recursive{}\n\trequire.NoError(t, conf.Unmarshal(r))\n\trequire.Equal(t, \"something\", r.Foo)\n}\n\nfunc testExpandedValue(t *testing.T, newSanitizer bool) {\n\terr := featuregate.GlobalRegistry().Set(metadata.ConfmapNewExpandedValueSanitizerFeatureGate.ID(), newSanitizer)\n\trequire.NoError(t, err)\n\n\tcm := NewFromStringMap(map[string]any{\n\t\t\"key\": ExpandedValue{\n\t\t\tValue:    0xdeadbeef,\n\t\t\tOriginal: \"original\",\n\t\t},\n\t})\n\tassert.Equal(t, 0xdeadbeef, cm.Get(\"key\"))\n\tassert.Equal(t, map[string]any{\"key\": 0xdeadbeef}, cm.ToStringMap())\n\n\ttype ConfigStr struct {\n\t\tKey string `mapstructure:\"key\"`\n\t}\n\n\tcfgStr := ConfigStr{}\n\trequire.NoError(t, cm.Unmarshal(&cfgStr))\n\tassert.Equal(t, \"original\", cfgStr.Key)\n\n\ttype ConfigStrPtr struct {\n\t\tKey *string `mapstructure:\"key\"`\n\t}\n\n\tcfgStrPtr := ConfigStrPtr{}\n\tif newSanitizer {\n\t\trequire.NoError(t, cm.Unmarshal(&cfgStrPtr))\n\t\tif assert.NotNil(t, cfgStrPtr.Key) {\n\t\t\tassert.Equal(t, \"original\", *cfgStrPtr.Key)\n\t\t}\n\t} else {\n\t\trequire.Error(t, cm.Unmarshal(&cfgStrPtr))\n\t}\n\n\tcfgMapStrPtr := map[string]*string{}\n\tif newSanitizer {\n\t\trequire.NoError(t, cm.Unmarshal(&cfgMapStrPtr))\n\t\tif assert.NotNil(t, cfgMapStrPtr[\"key\"]) {\n\t\t\tassert.Equal(t, \"original\", *cfgMapStrPtr[\"key\"])\n\t\t}\n\t} else {\n\t\trequire.Error(t, cm.Unmarshal(&cfgMapStrPtr))\n\t}\n\n\ttype ConfigInt struct {\n\t\tKey int `mapstructure:\"key\"`\n\t}\n\tcfgInt := ConfigInt{}\n\trequire.NoError(t, cm.Unmarshal(&cfgInt))\n\tassert.Equal(t, 0xdeadbeef, cfgInt.Key)\n\n\ttype ConfigBool struct {\n\t\tKey bool `mapstructure:\"key\"`\n\t}\n\tcfgBool := ConfigBool{}\n\tassert.Error(t, cm.Unmarshal(&cfgBool))\n}\n\nfunc TestExpandedValue(t *testing.T) {\n\tbefore := metadata.ConfmapNewExpandedValueSanitizerFeatureGate.IsEnabled()\n\tt.Run(\"old sanitizer\", func(t *testing.T) {\n\t\ttestExpandedValue(t, false)\n\t})\n\tt.Run(\"new sanitizer\", func(t *testing.T) {\n\t\ttestExpandedValue(t, true)\n\t})\n\terr := featuregate.GlobalRegistry().Set(metadata.ConfmapNewExpandedValueSanitizerFeatureGate.ID(), before)\n\trequire.NoError(t, err)\n}\n\nfunc TestExpandedValueNil(t *testing.T) {\n\tcm := NewFromStringMap(map[string]any{\n\t\t\"key\": ExpandedValue{\n\t\t\tValue:    nil,\n\t\t\tOriginal: \"NULL\",\n\t\t},\n\t})\n\n\ttype ConfigStrPtr struct {\n\t\tKey *string `mapstructure:\"key\"`\n\t}\n\n\tcfgStrPtr := ConfigStrPtr{}\n\trequire.NoError(t, cm.Unmarshal(&cfgStrPtr))\n\tassert.Nil(t, cfgStrPtr.Key)\n\n\tcfgMapStrPtr := map[string]*string{}\n\trequire.NoError(t, cm.Unmarshal(&cfgMapStrPtr))\n\tassert.Nil(t, cfgMapStrPtr[\"key\"])\n}\n\nfunc TestSubExpandedValue(t *testing.T) {\n\tcm := NewFromStringMap(map[string]any{\n\t\t\"key\": map[string]any{\n\t\t\t\"subkey\": ExpandedValue{\n\t\t\t\tValue:    map[string]any{\"subsubkey\": \"value\"},\n\t\t\t\tOriginal: \"subsubkey: value\",\n\t\t\t},\n\t\t},\n\t})\n\n\tassert.Equal(t, map[string]any{\"subkey\": map[string]any{\"subsubkey\": \"value\"}}, cm.Get(\"key\"))\n\tassert.Equal(t, map[string]any{\"key\": map[string]any{\"subkey\": map[string]any{\"subsubkey\": \"value\"}}}, cm.ToStringMap())\n\tassert.Equal(t, map[string]any{\"subsubkey\": \"value\"}, cm.Get(\"key::subkey\"))\n\n\tsub, err := cm.Sub(\"key::subkey\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, map[string]any{\"subsubkey\": \"value\"}, sub.ToStringMap())\n\n\t// This should return value, but currently `Get` does not support keys within expanded values.\n\tassert.Nil(t, cm.Get(\"key::subkey::subsubkey\"))\n}\n\nfunc TestStringyTypes(t *testing.T) {\n\ttests := []struct {\n\t\tvalueOfType any\n\t\tisStringy   bool\n\t}{\n\t\t{\n\t\t\tvalueOfType: \"string\",\n\t\t\tisStringy:   true,\n\t\t},\n\t\t{\n\t\t\tvalueOfType: 1,\n\t\t\tisStringy:   false,\n\t\t},\n\t\t{\n\t\t\tvalueOfType: map[string]any{},\n\t\t\tisStringy:   false,\n\t\t},\n\t\t{\n\t\t\tvalueOfType: []any{},\n\t\t\tisStringy:   false,\n\t\t},\n\t\t{\n\t\t\tvalueOfType: map[string]string{},\n\t\t\tisStringy:   true,\n\t\t},\n\t\t{\n\t\t\tvalueOfType: []string{},\n\t\t\tisStringy:   true,\n\t\t},\n\t\t{\n\t\t\tvalueOfType: map[string][]string{},\n\t\t\tisStringy:   true,\n\t\t},\n\t\t{\n\t\t\tvalueOfType: map[string]map[string]string{},\n\t\t\tisStringy:   true,\n\t\t},\n\t\t{\n\t\t\tvalueOfType: []map[string]any{},\n\t\t\tisStringy:   false,\n\t\t},\n\t\t{\n\t\t\tvalueOfType: []map[string]string{},\n\t\t\tisStringy:   true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\t// Create a reflect.Type from the value\n\t\tto := reflect.TypeOf(tt.valueOfType)\n\t\tassert.Equal(t, tt.isStringy, isStringyStructure(to))\n\t}\n}\n\nfunc TestConfDelete(t *testing.T) {\n\ttests := []struct {\n\t\tpath      string\n\t\tstringMap map[string]any\n\t}{\n\t\t{\n\t\t\tpath:      \"key\",\n\t\t\tstringMap: map[string]any{\"key\": \"value\"},\n\t\t},\n\t\t{\n\t\t\tpath: \"map::expanded\",\n\t\t\tstringMap: map[string]any{\"map\": map[string]any{\n\t\t\t\t\"expanded\": ExpandedValue{\n\t\t\t\t\tValue:    0o1234,\n\t\t\t\t\tOriginal: \"01234\",\n\t\t\t\t},\n\t\t\t}},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.path, func(t *testing.T) {\n\t\t\tcm := NewFromStringMap(test.stringMap)\n\n\t\t\tassert.True(t, cm.IsSet(test.path))\n\t\t\tassert.True(t, cm.Delete(test.path))\n\t\t\tassert.Nil(t, cm.Get(test.path))\n\t\t\tassert.False(t, cm.IsSet(test.path))\n\n\t\t\tassert.False(t, cm.Delete(test.path))\n\t\t\tassert.Nil(t, cm.Get(test.path))\n\t\t\tassert.False(t, cm.IsSet(test.path))\n\t\t})\n\t}\n}\n\ntype structWithConfigOpaqueMap struct {\n\tHeaders map[string]string `mapstructure:\"headers\"`\n}\n\nfunc TestMapMerge(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinitial  map[string]string\n\t\tadded    map[string]string\n\t\texpected map[string]string\n\t}{\n\t\t{\n\t\t\tname:     \"both nil\",\n\t\t\tinitial:  nil,\n\t\t\tadded:    nil,\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tname:     \"nil map\",\n\t\t\tinitial:  map[string]string{},\n\t\t\tadded:    nil,\n\t\t\texpected: map[string]string{},\n\t\t},\n\t\t{\n\t\t\tname: \"initialized\",\n\t\t\tinitial: map[string]string{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t\tadded: nil,\n\t\t\texpected: map[string]string{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"both\",\n\t\t\tinitial: map[string]string{\n\t\t\t\t\"foo\": \"bar\",\n\t\t\t},\n\t\t\tadded: map[string]string{\n\t\t\t\t\"foobar\": \"bar\",\n\t\t\t},\n\t\t\texpected: map[string]string{\n\t\t\t\t\"foo\":    \"bar\",\n\t\t\t\t\"foobar\": \"bar\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\ts := structWithConfigOpaqueMap{\n\t\t\t\tHeaders: test.initial,\n\t\t\t}\n\t\t\tc := NewFromStringMap(map[string]any{\n\t\t\t\t\"headers\": test.added,\n\t\t\t})\n\t\t\trequire.NoError(t, c.Unmarshal(&s))\n\t\t\tassert.Equal(t, test.expected, s.Headers)\n\t\t})\n\t}\n}\n\nfunc TestConfIsNil(t *testing.T) {\n\tconst subKey = \"foo\"\n\ttestCases := []struct {\n\t\tname         string\n\t\tinput        map[string]any\n\t\texpectIsNil  bool\n\t\tsubExpectNil bool\n\t\tsubExpectErr string\n\t}{\n\t\t{\n\t\t\tname:         \"nil input\",\n\t\t\tinput:        nil,\n\t\t\texpectIsNil:  true,\n\t\t\tsubExpectNil: true,\n\t\t},\n\t\t{\n\t\t\tname:         \"empty map\",\n\t\t\tinput:        map[string]any{},\n\t\t\texpectIsNil:  false,\n\t\t\tsubExpectNil: true,\n\t\t},\n\t\t{\n\t\t\tname:         \"nil subkey\",\n\t\t\tinput:        map[string]any{subKey: nil},\n\t\t\texpectIsNil:  false,\n\t\t\tsubExpectNil: true,\n\t\t},\n\t\t{\n\t\t\tname:         \"empty subkey\",\n\t\t\tinput:        map[string]any{subKey: map[string]any{}},\n\t\t\texpectIsNil:  false,\n\t\t\tsubExpectNil: false,\n\t\t},\n\t\t{\n\t\t\tname:         \"non-empty map\",\n\t\t\tinput:        map[string]any{subKey: map[string]any{\"bar\": 42}},\n\t\t\texpectIsNil:  false,\n\t\t\tsubExpectNil: false,\n\t\t},\n\t\t{\n\t\t\tname:         \"non-map subkey\",\n\t\t\tinput:        map[string]any{subKey: 123},\n\t\t\texpectIsNil:  false,\n\t\t\tsubExpectErr: \"unexpected sub-config value kind\",\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tconf := NewFromStringMap(tc.input)\n\t\t\tif tc.expectIsNil {\n\t\t\t\tassert.Empty(t, conf.AllKeys())\n\t\t\t\tassert.Equal(t, map[string]any(nil), conf.ToStringMap())\n\t\t\t} else {\n\t\t\t\tassert.NotEqual(t, map[string]any(nil), conf.ToStringMap())\n\t\t\t}\n\n\t\t\tsub, err := conf.Sub(subKey)\n\t\t\tif tc.subExpectErr != \"\" {\n\t\t\t\tassert.ErrorContains(t, err, tc.subExpectErr)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tif tc.subExpectNil {\n\t\t\t\t\tassert.Empty(t, sub.AllKeys())\n\t\t\t\t\tassert.Equal(t, map[string]any(nil), sub.ToStringMap())\n\t\t\t\t} else {\n\t\t\t\t\tassert.NotEqual(t, map[string]any(nil), sub.ToStringMap())\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestConfmapNilMerge(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tleft     map[string]any\n\t\tright    map[string]any\n\t\texpected map[string]any\n\t}{\n\t\t{\n\t\t\tname:     \"both nil\",\n\t\t\tleft:     nil,\n\t\t\tright:    nil,\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tname:     \"left nil\",\n\t\t\tleft:     nil,\n\t\t\tright:    map[string]any{\"key\": \"value\"},\n\t\t\texpected: map[string]any{\"key\": \"value\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"right nil\",\n\t\t\tleft:     map[string]any{\"key\": \"value\"},\n\t\t\tright:    nil,\n\t\t\texpected: map[string]any{\"key\": \"value\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"both non-nil\",\n\t\t\tleft:     map[string]any{\"key1\": \"value1\"},\n\t\t\tright:    map[string]any{\"key2\": \"value2\"},\n\t\t\texpected: map[string]any{\"key1\": \"value1\", \"key2\": \"value2\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"left empty, right non-empty\",\n\t\t\tleft:     map[string]any{},\n\t\t\tright:    map[string]any{\"key\": \"value\"},\n\t\t\texpected: map[string]any{\"key\": \"value\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"left non-empty, right empty\",\n\t\t\tleft:     map[string]any{\"key\": \"value\"},\n\t\t\tright:    map[string]any{},\n\t\t\texpected: map[string]any{\"key\": \"value\"},\n\t\t},\n\t\t{\n\t\t\tname:     \"left nil, right empty\",\n\t\t\tleft:     nil,\n\t\t\tright:    map[string]any{},\n\t\t\texpected: map[string]any{},\n\t\t},\n\t\t{\n\t\t\tname:     \"left empty, right nil\",\n\t\t\tleft:     map[string]any{},\n\t\t\tright:    nil,\n\t\t\texpected: map[string]any{},\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tleftConf := NewFromStringMap(test.left)\n\t\t\tassert.Equal(t, test.left, leftConf.ToStringMap())\n\t\t\trightConf := NewFromStringMap(test.right)\n\t\t\tassert.Equal(t, test.right, rightConf.ToStringMap())\n\n\t\t\terr := leftConf.Merge(rightConf)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tassert.Equal(t, test.expected, leftConf.ToStringMap())\n\t\t})\n\n\t\tt.Run(test.name+\"merge append\", func(t *testing.T) {\n\t\t\tleftConf := NewFromStringMap(test.left)\n\t\t\tassert.Equal(t, test.left, leftConf.ToStringMap())\n\t\t\trightConf := NewFromStringMap(test.right)\n\t\t\tassert.Equal(t, test.right, rightConf.ToStringMap())\n\n\t\t\terr := leftConf.mergeAppend(rightConf)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tassert.Equal(t, test.expected, leftConf.ToStringMap())\n\t\t})\n\t}\n}\n\ntype simpleUnmarshaler struct {\n\tunmarshaled bool\n\tValue       string `mapstructure:\"value\"`\n}\n\nvar _ Unmarshaler = (*simpleUnmarshaler)(nil)\n\nfunc (s *simpleUnmarshaler) Unmarshal(c *Conf) error {\n\ts.unmarshaled = true\n\treturn c.Unmarshal(s) // Does not call simpleUnmarshaler.Unmarshal\n}\n\ntype wrapperUnmarshaler[T any] struct {\n\tinner T\n}\n\nvar _ Unmarshaler = (*wrapperUnmarshaler[simpleUnmarshaler])(nil)\n\nfunc (w *wrapperUnmarshaler[T]) Unmarshal(c *Conf) error {\n\treturn c.Unmarshal(&w.inner, WithForceUnmarshaler()) // Calls T.Unmarshal\n}\n\nfunc TestUnmarshalWithForceUnmarshaler(t *testing.T) {\n\tconf := NewFromStringMap(map[string]any{\n\t\t\"value\": \"test_value\",\n\t})\n\tvar out wrapperUnmarshaler[simpleUnmarshaler]\n\trequire.NoError(t, conf.Unmarshal(&out))\n\tassert.Equal(t, \"test_value\", out.inner.Value)\n\tassert.True(t, out.inner.unmarshaled)\n}\n"
  },
  {
    "path": "confmap/internal/decoder.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/confmap/internal\"\n\nimport (\n\t\"encoding\"\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"slices\"\n\t\"strings\"\n\n\t\"github.com/go-viper/mapstructure/v2\"\n\n\t\"go.opentelemetry.io/collector/confmap/internal/metadata\"\n\t\"go.opentelemetry.io/collector/confmap/internal/third_party/composehook\"\n)\n\nconst (\n\t// MapstructureTag is the struct field tag used to record marshaling/unmarshaling settings.\n\t// See https://pkg.go.dev/github.com/go-viper/mapstructure/v2 for supported values.\n\tMapstructureTag = \"mapstructure\"\n)\n\n// WithIgnoreUnused sets an option to ignore errors if existing\n// keys in the original Conf were unused in the decoding process\n// (extra keys).\nfunc WithIgnoreUnused() UnmarshalOption {\n\treturn UnmarshalOptionFunc(func(uo *UnmarshalOptions) {\n\t\tuo.IgnoreUnused = true\n\t})\n}\n\n// WithForceUnmarshaler sets an option to run a top-level Unmarshal method,\n// even if the Conf being unmarshaled is already a parameter from an Unmarshal method.\n// To avoid infinite recursion, this should only be used when unmarshaling into\n// a different type from the current Unmarshaler.\n// For instance, this should be used in wrapper types such as configoptional.Optional\n// to ensure the inner type's Unmarshal method is called.\nfunc WithForceUnmarshaler() UnmarshalOption {\n\treturn UnmarshalOptionFunc(func(uo *UnmarshalOptions) {\n\t\tuo.ForceUnmarshaler = true\n\t})\n}\n\n// Decode decodes the contents of the Conf into the result argument, using a\n// mapstructure decoder with the following notable behaviors. Ensures that maps whose\n// values are nil pointer structs resolved to the zero value of the target struct (see\n// expandNilStructPointers). Converts string to []string by splitting on ','. Ensures\n// uniqueness of component IDs (see mapKeyStringToMapKeyTextUnmarshalerHookFunc).\n// Decodes time.Duration from strings. Allows custom unmarshaling for structs implementing\n// encoding.TextUnmarshaler. Allows custom unmarshaling for structs implementing confmap.Unmarshaler.\nfunc Decode(input, result any, settings UnmarshalOptions, skipTopLevelUnmarshaler bool) error {\n\tdc := &mapstructure.DecoderConfig{\n\t\tErrorUnused:      !settings.IgnoreUnused,\n\t\tResult:           result,\n\t\tTagName:          MapstructureTag,\n\t\tWeaklyTypedInput: false,\n\t\tMatchName:        caseSensitiveMatchName,\n\t\tDecodeNil:        true,\n\t\tDecodeHook: composehook.ComposeDecodeHookFunc(\n\t\t\tuseExpandValue(),\n\t\t\texpandNilStructPointersHookFunc(),\n\t\t\tmapstructure.StringToSliceHookFunc(\",\"),\n\t\t\tmapKeyStringToMapKeyTextUnmarshalerHookFunc(),\n\t\t\tmapstructure.StringToTimeDurationHookFunc(),\n\t\t\tmapstructure.TextUnmarshallerHookFunc(),\n\t\t\tunmarshalerHookFunc(result, skipTopLevelUnmarshaler && !settings.ForceUnmarshaler),\n\t\t\t// after the main unmarshaler hook is called,\n\t\t\t// we unmarshal the embedded structs if present to merge with the result:\n\t\t\tunmarshalerEmbeddedStructsHookFunc(settings),\n\t\t\tzeroSliceAndMapHookFunc(),\n\t\t),\n\t}\n\tdecoder, err := mapstructure.NewDecoder(dc)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif err = decoder.Decode(input); err != nil {\n\t\tif strings.HasPrefix(err.Error(), \"error decoding ''\") {\n\t\t\treturn errors.Unwrap(err)\n\t\t}\n\t\treturn err\n\t}\n\treturn nil\n}\n\n// When a value has been loaded from an external source via a provider, we keep both the\n// parsed value and the original string value. This allows us to expand the value to its\n// original string representation when decoding into a string field, and use the parsed value otherwise.\n//\n// Fields containing a pointer to a string will also be set to the original string representation,\n// except when the parsed value is nil (i.e. parsed from YAML `null`, `NULL`, `~`, the empty string, etc.)\nfunc useExpandValue() mapstructure.DecodeHookFuncType {\n\treturn func(\n\t\t_ reflect.Type,\n\t\tto reflect.Type,\n\t\tdata any,\n\t) (any, error) {\n\t\tif exp, ok := data.(ExpandedValue); ok {\n\t\t\tvar useOriginal bool\n\t\t\tif metadata.ConfmapNewExpandedValueSanitizerFeatureGate.IsEnabled() {\n\t\t\t\t// Check if the target field is string, *string, **string, etc.\n\t\t\t\tbaseType := to\n\t\t\t\tpointed := false\n\t\t\t\tfor baseType.Kind() == reflect.Pointer {\n\t\t\t\t\tbaseType = baseType.Elem()\n\t\t\t\t\tpointed = true\n\t\t\t\t}\n\t\t\t\tuseOriginal = baseType.Kind() == reflect.String\n\n\t\t\t\t// If the parsed value is nil and the target is a pointer, use the parsed value.\n\t\t\t\tif pointed && exp.Value == nil {\n\t\t\t\t\tuseOriginal = false\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tuseOriginal = to.Kind() == reflect.String\n\t\t\t}\n\n\t\t\tv := castTo(exp, useOriginal)\n\t\t\t// See https://github.com/open-telemetry/opentelemetry-collector/issues/10949\n\t\t\t// If the `to.Kind` is not a string, then expandValue's original value is useless and\n\t\t\t// the casted-to value will be nil. In that scenario, we need to use the default value of `to`'s kind.\n\t\t\tif v == nil {\n\t\t\t\treturn reflect.Zero(to).Interface(), nil\n\t\t\t}\n\t\t\treturn v, nil\n\t\t}\n\n\t\tif !metadata.ConfmapNewExpandedValueSanitizerFeatureGate.IsEnabled() {\n\t\t\tswitch to.Kind() {\n\t\t\tcase reflect.Array, reflect.Slice, reflect.Map:\n\t\t\t\tif isStringyStructure(to) {\n\t\t\t\t\t// If the target field is a stringy structure, sanitize to use the original string value everywhere.\n\t\t\t\t\treturn sanitizeToStr(data), nil\n\t\t\t\t}\n\n\t\t\t\t// Otherwise, sanitize to use the parsed value everywhere.\n\t\t\t\treturn sanitize(data), nil\n\t\t\t}\n\t\t}\n\t\treturn data, nil\n\t}\n}\n\n// In cases where a config has a mapping of something to a struct pointers\n// we want nil values to resolve to a pointer to the zero value of the\n// underlying struct just as we want nil values of a mapping of something\n// to a struct to resolve to the zero value of that struct.\n//\n// e.g. given a config type:\n// type Config struct { Thing *SomeStruct `mapstructure:\"thing\"` }\n//\n// and yaml of:\n// config:\n//\n//\tthing:\n//\n// we want an unmarshaled Config to be equivalent to\n// Config{Thing: &SomeStruct{}} instead of Config{Thing: nil}\nfunc expandNilStructPointersHookFunc() mapstructure.DecodeHookFuncValue {\n\treturn safeWrapDecodeHookFunc(func(from, to reflect.Value) (any, error) {\n\t\t// ensure we are dealing with map to map comparison\n\t\tif from.Kind() == reflect.Map && to.Kind() == reflect.Map {\n\t\t\ttoElem := to.Type().Elem()\n\t\t\t// ensure that map values are pointers to a struct\n\t\t\t// (that may be nil and require manual setting w/ zero value)\n\t\t\tif toElem.Kind() == reflect.Ptr && toElem.Elem().Kind() == reflect.Struct {\n\t\t\t\tfromRange := from.MapRange()\n\t\t\t\tfor fromRange.Next() {\n\t\t\t\t\tfromKey := fromRange.Key()\n\t\t\t\t\tfromValue := fromRange.Value()\n\t\t\t\t\t// ensure that we've run into a nil pointer instance\n\t\t\t\t\tif fromValue.IsNil() {\n\t\t\t\t\t\tnewFromValue := reflect.New(toElem.Elem())\n\t\t\t\t\t\tfrom.SetMapIndex(fromKey, newFromValue)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn from.Interface(), nil\n\t})\n}\n\n// mapKeyStringToMapKeyTextUnmarshalerHookFunc returns a DecodeHookFuncType that checks that a conversion from\n// map[string]any to map[encoding.TextUnmarshaler]any does not overwrite keys,\n// when UnmarshalText produces equal elements from different strings (e.g. trims whitespaces).\n//\n// This is needed in combination with ComponentID, which may produce equal IDs for different strings,\n// and an error needs to be returned in that case, otherwise the last equivalent ID overwrites the previous one.\nfunc mapKeyStringToMapKeyTextUnmarshalerHookFunc() mapstructure.DecodeHookFuncType {\n\treturn func(from, to reflect.Type, data any) (any, error) {\n\t\tif from.Kind() != reflect.Map || from.Key().Kind() != reflect.String {\n\t\t\treturn data, nil\n\t\t}\n\n\t\tif to.Kind() != reflect.Map {\n\t\t\treturn data, nil\n\t\t}\n\n\t\t// Checks that the key type of to implements the TextUnmarshaler interface.\n\t\tif _, ok := reflect.New(to.Key()).Interface().(encoding.TextUnmarshaler); !ok {\n\t\t\treturn data, nil\n\t\t}\n\n\t\t// Create a map with key value of to's key to bool.\n\t\tfieldNameSet := reflect.MakeMap(reflect.MapOf(to.Key(), reflect.TypeFor[bool]()))\n\t\tfor k := range data.(map[string]any) {\n\t\t\t// Create a new value of the to's key type.\n\t\t\ttKey := reflect.New(to.Key())\n\n\t\t\t// Use tKey to unmarshal the key of the map.\n\t\t\tif err := tKey.Interface().(encoding.TextUnmarshaler).UnmarshalText([]byte(k)); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\t// Checks if the key has already been decoded in a previous iteration.\n\t\t\tif fieldNameSet.MapIndex(reflect.Indirect(tKey)).IsValid() {\n\t\t\t\treturn nil, fmt.Errorf(\"duplicate name %q after unmarshaling %v\", k, tKey)\n\t\t\t}\n\t\t\tfieldNameSet.SetMapIndex(reflect.Indirect(tKey), reflect.ValueOf(true))\n\t\t}\n\t\treturn data, nil\n\t}\n}\n\n// unmarshalerEmbeddedStructsHookFunc provides a mechanism for embedded structs to define their own unmarshal logic,\n// by implementing the Unmarshaler interface.\nfunc unmarshalerEmbeddedStructsHookFunc(settings UnmarshalOptions) mapstructure.DecodeHookFuncValue {\n\treturn safeWrapDecodeHookFunc(func(from, to reflect.Value) (any, error) {\n\t\tif to.Type().Kind() != reflect.Struct {\n\t\t\treturn from.Interface(), nil\n\t\t}\n\t\tfromAsMap, ok := from.Interface().(map[string]any)\n\t\tif !ok {\n\t\t\treturn from.Interface(), nil\n\t\t}\n\n\t\t// First call Unmarshaler on squashed embedded fields, if necessary.\n\t\tvar squashedUnmarshalers []int\n\t\tfor i := 0; i < to.Type().NumField(); i++ {\n\t\t\tf := to.Type().Field(i)\n\t\t\tif !f.IsExported() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\ttagParts := strings.Split(f.Tag.Get(MapstructureTag), \",\")\n\t\t\tif !slices.Contains(tagParts[1:], \"squash\") {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tunmarshaler, ok := to.Field(i).Addr().Interface().(Unmarshaler)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tc := NewFromStringMap(fromAsMap)\n\t\t\tc.skipTopLevelUnmarshaler = true\n\t\t\tif err := unmarshaler.Unmarshal(c); err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tsquashedUnmarshalers = append(squashedUnmarshalers, i)\n\t\t}\n\n\t\t// No squashed unmarshalers, we can let mapstructure do its job.\n\t\tif len(squashedUnmarshalers) == 0 {\n\t\t\treturn fromAsMap, nil\n\t\t}\n\n\t\t// We need to unmarshal into all other fields without overwriting the output of the Unmarshal calls.\n\t\t// To do that, create a custom \"partial\" struct containing only the non-squashed fields.\n\t\tvar fields []reflect.StructField\n\t\tvar fieldValues []reflect.Value\n\t\tfor i := 0; i < to.Type().NumField(); i++ {\n\t\t\tf := to.Type().Field(i)\n\t\t\tif !f.IsExported() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif slices.Contains(squashedUnmarshalers, i) {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfields = append(fields, f)\n\t\t\tfieldValues = append(fieldValues, to.Field(i))\n\t\t}\n\t\trestType := reflect.StructOf(fields)\n\t\trestValue := reflect.New(restType)\n\n\t\t// Copy initial values into partial struct.\n\t\tfor i, fieldValue := range fieldValues {\n\t\t\trestValue.Elem().Field(i).Set(fieldValue)\n\t\t}\n\n\t\t// Decode into the partial struct.\n\t\t// This performs a recursive call into this hook, which will be handled by the \"no squashed unmarshalers\" case above.\n\t\t// We need to set `IgnoreUnused` to avoid errors from the map containing fields only present in the full struct.\n\t\tsettings.IgnoreUnused = true\n\t\tif err := Decode(fromAsMap, restValue.Interface(), settings, true); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\t// Copy decoding results back to the original struct.\n\t\tfor i, fieldValue := range fieldValues {\n\t\t\tfieldValue.Set(restValue.Elem().Field(i))\n\t\t}\n\n\t\treturn to, nil\n\t})\n}\n\n// Provides a mechanism for individual structs to define their own unmarshal logic,\n// by implementing the Unmarshaler interface, unless skipTopLevelUnmarshaler is\n// true and the struct matches the top level object being unmarshaled.\nfunc unmarshalerHookFunc(result any, skipTopLevelUnmarshaler bool) mapstructure.DecodeHookFuncValue {\n\treturn safeWrapDecodeHookFunc(func(from, to reflect.Value) (any, error) {\n\t\tif !to.CanAddr() {\n\t\t\treturn from.Interface(), nil\n\t\t}\n\n\t\ttoPtr := to.Addr().Interface()\n\t\t// Need to ignore the top structure to avoid running into an infinite recursion\n\t\t// where Unmarshaler.Unmarshal and Conf.Unmarshal would call each other.\n\t\tif toPtr == result && skipTopLevelUnmarshaler {\n\t\t\treturn from.Interface(), nil\n\t\t}\n\n\t\tunmarshaler, ok := toPtr.(Unmarshaler)\n\t\tif !ok {\n\t\t\treturn from.Interface(), nil\n\t\t}\n\n\t\tif _, ok = from.Interface().(map[string]any); !ok {\n\t\t\treturn from.Interface(), nil\n\t\t}\n\n\t\t// Use the current object if not nil (to preserve other configs in the object), otherwise zero initialize.\n\t\tif to.Addr().IsNil() {\n\t\t\tunmarshaler = reflect.New(to.Type()).Interface().(Unmarshaler)\n\t\t}\n\n\t\tc := NewFromStringMap(from.Interface().(map[string]any))\n\t\tc.skipTopLevelUnmarshaler = true\n\t\tif err := unmarshaler.Unmarshal(c); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\treturn unmarshaler, nil\n\t})\n}\n\n// safeWrapDecodeHookFunc wraps a DecodeHookFuncValue to ensure fromVal is a valid `reflect.Value`\n// object and therefore it is safe to call `reflect.Value` methods on fromVal.\n//\n// Use this only if the hook does not need to be called on untyped nil values.\n// Typed nil values are safe to call and will be passed to the hook.\n// See https://github.com/golang/go/issues/51649\nfunc safeWrapDecodeHookFunc(\n\tf mapstructure.DecodeHookFuncValue,\n) mapstructure.DecodeHookFuncValue {\n\treturn func(fromVal, toVal reflect.Value) (any, error) {\n\t\tif !fromVal.IsValid() {\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn f(fromVal, toVal)\n\t}\n}\n\n// This hook is used to solve the issue: https://github.com/open-telemetry/opentelemetry-collector/issues/4001\n// We adopt the suggestion provided in this issue: https://github.com/mitchellh/mapstructure/issues/74#issuecomment-279886492\n// We should empty every slice before unmarshalling unless user provided slice is nil.\n// Assume that we had a struct with a field of type slice called `keys`, which has default values of [\"a\", \"b\"]\n//\n//\ttype Config struct {\n//\t  Keys []string `mapstructure:\"keys\"`\n//\t}\n//\n// The configuration provided by users may have following cases\n// 1. configuration have `keys` field and have a non-nil values for this key, the output should be overridden\n//   - for example, input is {\"keys\", [\"c\"]}, then output is Config{ Keys: [\"c\"]}\n//\n// 2. configuration have `keys` field and have an empty slice for this key, the output should be overridden by empty slices\n//   - for example, input is {\"keys\", []}, then output is Config{ Keys: []}\n//\n// 3. configuration have `keys` field and have nil value for this key, the output should be default config\n//   - for example, input is {\"keys\": nil}, then output is Config{ Keys: [\"a\", \"b\"]}\n//\n// 4. configuration have no `keys` field specified, the output should be default config\n//   - for example, input is {}, then output is Config{ Keys: [\"a\", \"b\"]}\n//\n// This hook is also used to solve https://github.com/open-telemetry/opentelemetry-collector/issues/13117.\n// Since v0.127.0, we decode nil values to avoid creating empty map objects.\n// The nil value is not well understood when layered on top of a default map non-nil value.\n// The fix is to avoid the assignment and return the previous value.\nfunc zeroSliceAndMapHookFunc() mapstructure.DecodeHookFuncValue {\n\treturn safeWrapDecodeHookFunc(func(from, to reflect.Value) (any, error) {\n\t\tif to.CanSet() && to.Kind() == reflect.Slice && from.Kind() == reflect.Slice {\n\t\t\tif !from.IsNil() {\n\t\t\t\t// input slice is not nil, set the output slice to a new slice of the same type.\n\t\t\t\tto.Set(reflect.MakeSlice(to.Type(), from.Len(), from.Cap()))\n\t\t\t}\n\t\t}\n\t\tif to.CanSet() && to.Kind() == reflect.Map && from.Kind() == reflect.Map {\n\t\t\tif from.IsNil() {\n\t\t\t\treturn to.Interface(), nil\n\t\t\t}\n\t\t}\n\n\t\treturn from.Interface(), nil\n\t})\n}\n\n// case-sensitive version of the callback to be used in the MatchName property\n// of the DecoderConfig. The default for MatchEqual is to use strings.EqualFold,\n// which is case-insensitive.\nfunc caseSensitiveMatchName(a, b string) bool {\n\treturn a == b\n}\n\nfunc castTo(exp ExpandedValue, useOriginal bool) any {\n\t// If the target field is a string, use `exp.Original` or fail if not available.\n\tif useOriginal {\n\t\treturn exp.Original\n\t}\n\t// Otherwise, use the parsed value (previous behavior).\n\treturn exp.Value\n}\n\n// Check if a reflect.Type is of the form T, where:\n// X is any type or interface\n// T = string | map[X]T | []T | [n]T\nfunc isStringyStructure(t reflect.Type) bool {\n\tif t.Kind() == reflect.String {\n\t\treturn true\n\t}\n\tif t.Kind() == reflect.Map {\n\t\treturn isStringyStructure(t.Elem())\n\t}\n\tif t.Kind() == reflect.Slice || t.Kind() == reflect.Array {\n\t\treturn isStringyStructure(t.Elem())\n\t}\n\treturn false\n}\n"
  },
  {
    "path": "confmap/internal/e2e/Makefile",
    "content": "include ../../../Makefile.Common\n\n# Override COVER_PKGS to include the parent package that this e2e module tests\nCOVER_PKGS := go.opentelemetry.io/collector/confmap/internal,$(COVER_PKGS)\n"
  },
  {
    "path": "confmap/internal/e2e/expand_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2etest\n\nimport (\n\t\"context\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/internal\"\n\t\"go.opentelemetry.io/collector/confmap/provider/envprovider\"\n\t\"go.opentelemetry.io/collector/confmap/provider/fileprovider\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n)\n\nfunc Test_EscapedEnvVars_NoDefaultScheme(t *testing.T) {\n\tconst expandedValue = \"some expanded value\"\n\tt.Setenv(\"ENV_VALUE\", expandedValue)\n\tt.Setenv(\"ENV_LIST\", \"['$$ESCAPE_ME','$${ESCAPE_ME}','$${env:ESCAPE_ME}']\")\n\tt.Setenv(\"ENV_MAP\", \"{'key1':'$$ESCAPE_ME','key2':'$${ESCAPE_ME}','key3':'$${env:ESCAPE_ME}'}\")\n\tt.Setenv(\"ENV_NESTED_DOLLARSIGN\", \"here is 1 $$\")\n\tt.Setenv(\"ENV_NESTED_DOLLARSIGN_ESCAPED\", \"here are 2 $$$\")\n\tt.Setenv(\"ENV_EXPAND_NESTED\", \"${env:ENV_VALUE} came from nested expansion\")\n\n\texpectedMap := map[string]any{\n\t\t\"test_map\": map[string]any{\n\t\t\t\"key1\":  \"$ENV_VALUE\",\n\t\t\t\"key2\":  \"$$ENV_VALUE\",\n\t\t\t\"key3\":  \"$${ENV_VALUE}\",\n\t\t\t\"key4\":  \"some${ENV_VALUE}text\",\n\t\t\t\"key5\":  \"some${ENV_VALUE}text\",\n\t\t\t\"key6\":  \"${ONE}${TWO}\",\n\t\t\t\"key7\":  \"text$\",\n\t\t\t\"key8\":  \"$\",\n\t\t\t\"key9\":  \"${1}${env:2}\",\n\t\t\t\"key10\": \"some${env:ENV_VALUE}text\",\n\t\t\t\"key11\": \"${env:${ENV_VALUE}}\",\n\t\t\t\"key12\": \"${env:${ENV_VALUE}}\",\n\t\t\t\"key13\": \"env:MAP_VALUE_2}${ENV_VALUE}{\",\n\t\t\t\"key14\": \"$\" + expandedValue,\n\t\t\t\"key15\": \"$ENV_VALUE\",\n\t\t\t\"key16\": []any{\"$ESCAPE_ME\", \"${ESCAPE_ME}\", \"${env:ESCAPE_ME}\"},\n\t\t\t\"key17\": map[string]any{\"key1\": \"$ESCAPE_ME\", \"key2\": \"${ESCAPE_ME}\", \"key3\": \"${env:ESCAPE_ME}\"},\n\t\t\t\"key18\": \"here is 1 $\",\n\t\t\t\"key19\": \"here are 2 $$\",\n\t\t\t\"key20\": \"some expanded value came from nested expansion\",\n\t\t\t\"key21\": \"default_value\",\n\t\t\t\"key22\": \"${env:UNDEFINED_KEY:-${env:UNDEFINED_KEY}}\",\n\t\t},\n\t}\n\n\tresolver, err := confmap.NewResolver(confmap.ResolverSettings{\n\t\tURIs:              []string{filepath.Join(\"testdata\", \"expand-escaped-env.yaml\")},\n\t\tProviderFactories: []confmap.ProviderFactory{fileprovider.NewFactory(), envprovider.NewFactory()},\n\t\tDefaultScheme:     \"\",\n\t})\n\trequire.NoError(t, err)\n\n\t// Test that expanded configs are the same with the simple config with no env vars.\n\tcfgMap, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\tm := cfgMap.ToStringMap()\n\tassert.Equal(t, expectedMap, m)\n}\n\nfunc Test_EscapedEnvVars_DefaultScheme(t *testing.T) {\n\tconst expandedValue = \"some expanded value\"\n\tt.Setenv(\"ENV_VALUE\", expandedValue)\n\tt.Setenv(\"ENV_LIST\", \"['$$ESCAPE_ME','$${ESCAPE_ME}','$${env:ESCAPE_ME}']\")\n\tt.Setenv(\"ENV_MAP\", \"{'key1':'$$ESCAPE_ME','key2':'$${ESCAPE_ME}','key3':'$${env:ESCAPE_ME}'}\")\n\tt.Setenv(\"ENV_NESTED_DOLLARSIGN\", \"here is 1 $$\")\n\tt.Setenv(\"ENV_NESTED_DOLLARSIGN_ESCAPED\", \"here are 2 $$$\")\n\tt.Setenv(\"ENV_EXPAND_NESTED\", \"${env:ENV_VALUE} came from nested expansion\")\n\n\texpectedMap := map[string]any{\n\t\t\"test_map\": map[string]any{\n\t\t\t\"key1\":  \"$ENV_VALUE\",\n\t\t\t\"key2\":  \"$$ENV_VALUE\",\n\t\t\t\"key3\":  \"$\" + expandedValue,\n\t\t\t\"key4\":  \"some\" + expandedValue + \"text\",\n\t\t\t\"key5\":  \"some${ENV_VALUE}text\",\n\t\t\t\"key6\":  \"${ONE}${TWO}\",\n\t\t\t\"key7\":  \"text$\",\n\t\t\t\"key8\":  \"$\",\n\t\t\t\"key9\":  \"${1}${env:2}\",\n\t\t\t\"key10\": \"some${env:ENV_VALUE}text\",\n\t\t\t\"key11\": \"${env:\" + expandedValue + \"}\",\n\t\t\t\"key12\": \"${env:${ENV_VALUE}}\",\n\t\t\t\"key13\": \"env:MAP_VALUE_2}${ENV_VALUE}{\",\n\t\t\t\"key14\": \"$\" + expandedValue,\n\t\t\t\"key15\": \"$ENV_VALUE\",\n\t\t\t\"key16\": []any{\"$ESCAPE_ME\", \"${ESCAPE_ME}\", \"${env:ESCAPE_ME}\"},\n\t\t\t\"key17\": map[string]any{\"key1\": \"$ESCAPE_ME\", \"key2\": \"${ESCAPE_ME}\", \"key3\": \"${env:ESCAPE_ME}\"},\n\t\t\t\"key18\": \"here is 1 $\",\n\t\t\t\"key19\": \"here are 2 $$\",\n\t\t\t\"key20\": \"some expanded value came from nested expansion\",\n\t\t\t\"key21\": \"default_value\",\n\t\t\t\"key22\": \"${env:UNDEFINED_KEY:-${env:UNDEFINED_KEY}}\",\n\t\t},\n\t}\n\n\tresolver, err := confmap.NewResolver(confmap.ResolverSettings{\n\t\tURIs:              []string{filepath.Join(\"testdata\", \"expand-escaped-env.yaml\")},\n\t\tProviderFactories: []confmap.ProviderFactory{fileprovider.NewFactory(), envprovider.NewFactory()},\n\t\tDefaultScheme:     \"env\",\n\t})\n\trequire.NoError(t, err)\n\n\t// Test that expanded configs are the same with the simple config with no env vars.\n\tcfgMap, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\tm := cfgMap.ToStringMap()\n\tassert.Equal(t, expectedMap, m)\n}\n\nfunc Test_RawConfMap(t *testing.T) {\n\tdata := map[string]any{\n\t\t\"value\": internal.ExpandedValue{\n\t\t\tValue:    8080,\n\t\t\tOriginal: \"8080\",\n\t\t},\n\t}\n\tconf := confmap.NewFromStringMap(data)\n\n\trawData := xconfmap.ToStringMapRaw(conf)\n\t_, isPresentAndExpandedValue := rawData[\"value\"].(internal.ExpandedValue)\n\trequire.True(t, isPresentAndExpandedValue)\n}\n"
  },
  {
    "path": "confmap/internal/e2e/fuzz_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2etest\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n// targetNested tests the following property:\n// > Passing a value of type T directly through an environment variable\n// > should be equivalent to passing it through a nested environment variable.\nfunc targetNested[T any](t *testing.T, value string) {\n\tresolver := NewResolver(t, \"types_expand.yaml\")\n\n\t// Use os.Setenv so we can check the error and return instead of failing the fuzzing.\n\tos.Setenv(\"ENV\", \"${env:ENV2}\") //nolint:usetesting\n\tdefer os.Unsetenv(\"ENV\")\n\terr := os.Setenv(\"ENV2\", value) //nolint:usetesting\n\tdefer os.Unsetenv(\"ENV2\")\n\tif err != nil {\n\t\treturn\n\t}\n\tconfNested, errResolveNested := resolver.Resolve(context.Background())\n\n\terr = os.Setenv(\"ENV\", value) //nolint:usetesting\n\tif err != nil {\n\t\treturn\n\t}\n\tconfSimple, errResolveSimple := resolver.Resolve(context.Background())\n\trequire.Equal(t, errResolveNested, errResolveSimple)\n\tif errResolveNested != nil {\n\t\treturn\n\t}\n\n\tvar cfgNested targetConfig[T]\n\terrNested := confNested.Unmarshal(cfgNested)\n\n\tvar cfgSimple targetConfig[T]\n\terrSimple := confSimple.Unmarshal(cfgSimple)\n\n\trequire.Equal(t, errNested, errSimple)\n\tif errNested != nil {\n\t\treturn\n\t}\n\tassert.Equal(t, cfgNested, cfgSimple)\n}\n\n// testStrings for fuzzing targets\nvar testStrings = []string{\n\t\"123\",\n\t\"opentelemetry\",\n\t\"!!str 123\",\n\t\"\\\"0123\\\"\",\n\t\"\\\"\",\n\t\"1111:1111:1111:1111:1111::\",\n\t\"{field: value}\",\n\t\"0xdeadbeef\",\n\t\"0b101\",\n\t\"field:\",\n\t\"2006-01-02T15:04:05Z07:00\",\n}\n\nfunc FuzzNestedString(f *testing.F) {\n\tfor _, value := range testStrings {\n\t\tf.Add(value)\n\t}\n\tf.Fuzz(targetNested[string])\n}\n\nfunc FuzzNestedInt(f *testing.F) {\n\tfor _, value := range testStrings {\n\t\tf.Add(value)\n\t}\n\tf.Fuzz(targetNested[int])\n}\n\nfunc FuzzNestedMap(f *testing.F) {\n\tfor _, value := range testStrings {\n\t\tf.Add(value)\n\t}\n\tf.Fuzz(targetNested[map[string]any])\n}\n"
  },
  {
    "path": "confmap/internal/e2e/go.mod",
    "content": "module go.opentelemetry.io/collector/confmap/internal/e2e\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/config/configopaque v1.54.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/confmap/provider/envprovider v1.54.0\n\tgo.opentelemetry.io/collector/confmap/provider/fileprovider v1.54.0\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0\n\tgo.opentelemetry.io/collector/featuregate v1.54.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/confmap => ../../\n\nreplace go.opentelemetry.io/collector/confmap/provider/fileprovider => ../../provider/fileprovider\n\nreplace go.opentelemetry.io/collector/confmap/provider/envprovider => ../../provider/envprovider\n\nreplace go.opentelemetry.io/collector/config/configopaque => ../../../config/configopaque\n\nreplace go.opentelemetry.io/collector/featuregate => ../../../featuregate\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../xconfmap\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../../internal/testutil\n"
  },
  {
    "path": "confmap/internal/e2e/go.sum",
    "content": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "confmap/internal/e2e/maplist_expanded_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2etest\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/internal\"\n\t\"go.opentelemetry.io/collector/confmap/internal/metadata\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\ntype testHeadersConfig struct {\n\tHeaders configopaque.MapList `mapstructure:\"headers\"`\n}\n\n// TestMapListWithExpandedValue tests that MapList can handle ExpandedValue\n// from environment variable expansion\nfunc TestMapListWithExpandedValue(t *testing.T) {\n\t// Simulate what happens when ${env:TOKEN} is expanded\n\t// The confmap will contain an ExpandedValue instead of a plain string\n\tdata := map[string]any{\n\t\t\"headers\": []any{\n\t\t\tmap[string]any{\n\t\t\t\t\"name\": \"Authorization\",\n\t\t\t\t\"value\": internal.ExpandedValue{\n\t\t\t\t\tValue:    \"Bearer secret-token\",\n\t\t\t\t\tOriginal: \"Bearer secret-token\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tconf := confmap.NewFromStringMap(data)\n\tvar tc testHeadersConfig\n\terr := conf.Unmarshal(&tc)\n\trequire.NoError(t, err)\n\n\tval, ok := tc.Headers.Get(\"Authorization\")\n\trequire.True(t, ok)\n\trequire.Equal(t, configopaque.String(\"Bearer secret-token\"), val)\n}\n\n// TestMapListWithExpandedValueIntValue tests an ExpandedValue with an integer Value\nfunc TestMapListWithExpandedValueIntValue(t *testing.T) {\n\t// Simulate what happens when expanding a value that parses as an int\n\tdata := map[string]any{\n\t\t\"headers\": []any{\n\t\t\tmap[string]any{\n\t\t\t\t\"name\": \"X-Port\",\n\t\t\t\t\"value\": internal.ExpandedValue{\n\t\t\t\t\tValue:    8080,   // Value is parsed as int\n\t\t\t\t\tOriginal: \"8080\", // Original is string\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\toriginalState := metadata.ConfmapNewExpandedValueSanitizerFeatureGate.IsEnabled()\n\tdefer func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ConfmapNewExpandedValueSanitizerFeatureGate.ID(), originalState))\n\t}()\n\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ConfmapNewExpandedValueSanitizerFeatureGate.ID(), true))\n\n\tconf := confmap.NewFromStringMap(data)\n\tvar tc testHeadersConfig\n\terr := conf.Unmarshal(&tc)\n\trequire.NoError(t, err)\n\n\tval, ok := tc.Headers.Get(\"X-Port\")\n\trequire.True(t, ok)\n\trequire.Equal(t, configopaque.String(\"8080\"), val)\n\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ConfmapNewExpandedValueSanitizerFeatureGate.ID(), false))\n\n\t// This will fail because when reverting to old behavior, ExpandedValues get decoded at collection time and doesn't\n\t// take struct collections into account.\n\terr = conf.Unmarshal(&tc)\n\trequire.Error(t, err)\n}\n\n// TestDirectConfigopaqueStringWithExpandedValueIntValue tests that direct unmarshaling works\nfunc TestDirectConfigopaqueStringWithExpandedValueIntValue(t *testing.T) {\n\ttype testConfig struct {\n\t\tValue configopaque.String `mapstructure:\"value\"`\n\t}\n\n\t// Direct configopaque.String field (not in a map/slice structure)\n\tdata := map[string]any{\n\t\t\"value\": internal.ExpandedValue{\n\t\t\tValue:    8080,\n\t\t\tOriginal: \"8080\",\n\t\t},\n\t}\n\n\tconf := confmap.NewFromStringMap(data)\n\tvar tc testConfig\n\terr := conf.Unmarshal(&tc)\n\t// This should work because useExpandValue detects the target is a string\n\trequire.NoError(t, err)\n\trequire.Equal(t, configopaque.String(\"8080\"), tc.Value)\n}\n\n// TestStringyStructureWithExpandedValue tests the isStringyStructure path in useExpandValue\nfunc TestStringyStructureWithExpandedValue(t *testing.T) {\n\ttype testConfig struct {\n\t\tTags []string `mapstructure:\"tags\"`\n\t}\n\n\tdata := map[string]any{\n\t\t\"tags\": []any{\n\t\t\tinternal.ExpandedValue{\n\t\t\t\tValue:    8080,\n\t\t\t\tOriginal: \"8080\",\n\t\t\t},\n\t\t},\n\t}\n\n\toriginalState := metadata.ConfmapNewExpandedValueSanitizerFeatureGate.IsEnabled()\n\tdefer func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ConfmapNewExpandedValueSanitizerFeatureGate.ID(), originalState))\n\t}()\n\n\t// With feature gate disabled, useExpandValue should detect []string as stringy\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ConfmapNewExpandedValueSanitizerFeatureGate.ID(), false))\n\n\tconf := confmap.NewFromStringMap(data)\n\tvar tc testConfig\n\terr := conf.Unmarshal(&tc)\n\trequire.NoError(t, err)\n\trequire.Equal(t, []string{\"8080\"}, tc.Tags)\n}\n"
  },
  {
    "path": "confmap/internal/e2e/nil_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2etest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestNilToStringMap(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\texpectedMap map[string]any\n\t\texpectedSub map[string]any\n\t}{\n\t\t{\n\t\t\tname: \"subsection_null.yaml\",\n\t\t\texpectedMap: map[string]any{\n\t\t\t\t\"field\": map[string]any{\n\t\t\t\t\t\"key\": nil,\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedSub: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"subsection_empty_map.yaml\",\n\t\t\texpectedMap: map[string]any{\n\t\t\t\t\"field\": map[string]any{\n\t\t\t\t\t\"key\": map[string]any{},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedSub: map[string]any{},\n\t\t},\n\t\t{\n\t\t\tname: \"subsection_set_but_empty.yaml\",\n\t\t\texpectedMap: map[string]any{\n\t\t\t\t\"field\": map[string]any{\n\t\t\t\t\t\"key\": nil,\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedSub: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"subsection_unset.yaml\",\n\t\t\texpectedMap: map[string]any{\n\t\t\t\t\"field\": nil,\n\t\t\t},\n\t\t\texpectedSub: nil,\n\t\t},\n\n\t\t{\n\t\t\tname: \"subsection_unset_empty_map.yaml\",\n\t\t\texpectedMap: map[string]any{\n\t\t\t\t\"field\": map[string]any{},\n\t\t\t},\n\t\t\texpectedSub: nil,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresolver := NewResolver(t, tt.name)\n\t\t\tconf, err := resolver.Resolve(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expectedMap, conf.ToStringMap())\n\n\t\t\tsub, err := conf.Sub(\"field::key\")\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expectedSub, sub.ToStringMap())\n\t\t})\n\t}\n}\n\nfunc TestNilToStringMapEnv(t *testing.T) {\n\ttests := []struct {\n\t\tenvValue    string\n\t\texpectedMap map[string]any\n\t\texpectedSub map[string]any\n\t}{\n\t\t{\n\t\t\tenvValue: \"null\",\n\t\t\texpectedMap: map[string]any{\n\t\t\t\t\"field\": map[string]any{\n\t\t\t\t\t\"key\": nil,\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedSub: nil,\n\t\t},\n\t\t{\n\t\t\tenvValue: \"{}\",\n\t\t\texpectedMap: map[string]any{\n\t\t\t\t\"field\": map[string]any{\n\t\t\t\t\t\"key\": map[string]any{},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedSub: map[string]any{},\n\t\t},\n\t\t{\n\t\t\tenvValue: \"\",\n\t\t\texpectedMap: map[string]any{\n\t\t\t\t\"field\": map[string]any{\n\t\t\t\t\t\"key\": nil,\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedSub: nil,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.envValue, func(t *testing.T) {\n\t\t\tt.Setenv(\"VALUE\", tt.envValue)\n\t\t\tresolver := NewResolver(t, \"types_map.yaml\")\n\t\t\tconf, err := resolver.Resolve(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expectedMap, conf.ToStringMap())\n\t\t\tsub, err := conf.Sub(\"field::key\")\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expectedSub, sub.ToStringMap())\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "confmap/internal/e2e/testdata/expand-escaped-env.yaml",
    "content": "test_map:\n  # $$ -> escaped $\n  key1: \"$$ENV_VALUE\"\n  # $$$$ -> two escaped $\n  key2: \"$$$$ENV_VALUE\"\n  # $$ -> escaped $ + ${ENV_VALUE} expanded\n  key3: \"$$${ENV_VALUE}\"\n  # expanded in the middle\n  key4: \"some${ENV_VALUE}text\"\n  # escaped $ in the middle\n  key5: \"some$${ENV_VALUE}text\"\n  # two escaped $\n  key6: \"$${ONE}$${TWO}\"\n  # trailing escaped $\n  key7: \"text$$\"\n  # escaped $ alone\n  key8: \"$$\"\n  # escaped number and uri\n  key9: \"$${1}$${env:2}\"\n  # escape provider\n  key10: \"some$${env:ENV_VALUE}text\"\n  # can escape outer when nested\n  key11: \"$${env:${ENV_VALUE}}\"\n  # can escape inner and outer when nested\n  key12: \"$${env:$${ENV_VALUE}}\"\n  # can escape partial\n  key13: \"env:MAP_VALUE_2}$${ENV_VALUE}{\"\n  # $$$ -> escaped $ + expanded env var\n  key14: \"$$${env:ENV_VALUE}\"\n  # $ -> $\n  key15: \"$ENV_VALUE\"\n  # list is escaped\n  key16: \"${env:ENV_LIST}\"\n  # map is escaped\n  key17: \"${env:ENV_MAP}\"\n  # nested $$ -> escaped $\n  key18: \"${env:ENV_NESTED_DOLLARSIGN}\"\n  # nested $$$ -> escaped $$\n  key19: \"${env:ENV_NESTED_DOLLARSIGN_ESCAPED}\"\n  # nested env var syntax is expanded\n  key20: \"${env:ENV_EXPAND_NESTED}\"\n  # default value\n  key21: \"${env:UNDEFINED_KEY:-default_value}\"\n  # escaped default value\n  key22: \"${env:UNDEFINED_KEY:-$${env:UNDEFINED_KEY}}\"\n"
  },
  {
    "path": "confmap/internal/e2e/testdata/indirect-slice-env-var-main.yaml",
    "content": "receivers:\n  nop:\n  otlp:\n    protocols:\n      grpc:\n\nexporters:\n  nop:\n  otlp_grpc:\n    endpoint: localhost:4317\n\nservice:\n  pipelines: ${file:${env:BASE_FOLDER}/indirect-slice-env-var-pipelines.yaml}\n"
  },
  {
    "path": "confmap/internal/e2e/testdata/indirect-slice-env-var-pipelines.yaml",
    "content": "logs:\n  receivers: ${env:OTEL_LOGS_RECEIVER}\n  exporters: ${env:OTEL_LOGS_EXPORTER}\n"
  },
  {
    "path": "confmap/internal/e2e/testdata/issue-10787-main.yaml",
    "content": "receivers:\n  otlp:\n    protocols:\n      grpc:\n        endpoint: 0.0.0.0:4317\n      http:\n        endpoint: 0.0.0.0:4318\nprocessors:\n  memory_limiter:\n\nexporters:\n  ${file:testdata/issue-10787-snippet.yaml}\n\nservice:\n  telemetry:\n    metrics:\n      level: detailed\n  pipelines:\n    traces:\n      receivers: [otlp]\n      processors: [memory_limiter]\n      exporters: [debug]\n"
  },
  {
    "path": "confmap/internal/e2e/testdata/issue-10787-snippet.yaml",
    "content": "# ${hello.world}\ndebug:\n  verbosity: detailed\n"
  },
  {
    "path": "confmap/internal/e2e/testdata/subsection_empty_map.yaml",
    "content": "field:\n  key: {}\n"
  },
  {
    "path": "confmap/internal/e2e/testdata/subsection_null.yaml",
    "content": "field:\n  key: null\n"
  },
  {
    "path": "confmap/internal/e2e/testdata/subsection_set_but_empty.yaml",
    "content": "field:\n  key:\n"
  },
  {
    "path": "confmap/internal/e2e/testdata/subsection_unset.yaml",
    "content": "field:\n"
  },
  {
    "path": "confmap/internal/e2e/testdata/subsection_unset_empty_map.yaml",
    "content": "field: {}\n"
  },
  {
    "path": "confmap/internal/e2e/testdata/types_complex.yaml",
    "content": "field: [key: [\"${env:VALUE}\"]]\n"
  },
  {
    "path": "confmap/internal/e2e/testdata/types_expand.yaml",
    "content": "field: ${env:ENV}\n"
  },
  {
    "path": "confmap/internal/e2e/testdata/types_expand_inline.yaml",
    "content": "field: \"inline field with ${env:ENV} expansion\"\n"
  },
  {
    "path": "confmap/internal/e2e/testdata/types_map.yaml",
    "content": "field:\n  key: ${env:VALUE}\n"
  },
  {
    "path": "confmap/internal/e2e/testdata/types_slice.yaml",
    "content": "field: [\"${env:VALUE}\"]\n"
  },
  {
    "path": "confmap/internal/e2e/types_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2etest\n\nimport (\n\t\"context\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/provider/envprovider\"\n\t\"go.opentelemetry.io/collector/confmap/provider/fileprovider\"\n)\n\ntype TargetField string\n\nconst (\n\tTargetFieldInt          TargetField = \"int_field\"\n\tTargetFieldString       TargetField = \"string_field\"\n\tTargetFieldBool         TargetField = \"bool_field\"\n\tTargetFieldInlineString TargetField = \"inline_string_field\"\n\tTargetFieldSlice        TargetField = \"slice_field\"\n)\n\ntype Test struct {\n\tvalue        string\n\ttargetField  TargetField\n\texpected     any\n\tresolveErr   string\n\tunmarshalErr string\n}\n\ntype targetConfig[T any] struct {\n\tField T `mapstructure:\"field\"`\n}\n\nfunc NewResolver(tb testing.TB, path string) *confmap.Resolver {\n\tresolver, err := confmap.NewResolver(confmap.ResolverSettings{\n\t\tURIs: []string{filepath.Join(\"testdata\", path)},\n\t\tProviderFactories: []confmap.ProviderFactory{\n\t\t\tfileprovider.NewFactory(),\n\t\t\tenvprovider.NewFactory(),\n\t\t},\n\t\tDefaultScheme: \"env\",\n\t})\n\trequire.NoError(tb, err)\n\treturn resolver\n}\n\nfunc AssertExpectedMatch[T any](t *testing.T, tt Test, conf *confmap.Conf, cfg *targetConfig[T]) {\n\terr := conf.Unmarshal(cfg)\n\tif tt.unmarshalErr != \"\" {\n\t\trequire.ErrorContains(t, err, tt.unmarshalErr)\n\t\treturn\n\t}\n\trequire.NoError(t, err)\n\trequire.Equal(t, tt.expected, cfg.Field)\n}\n\nfunc AssertResolvesTo(t *testing.T, resolver *confmap.Resolver, tt Test) {\n\tconf, err := resolver.Resolve(context.Background())\n\tif tt.resolveErr != \"\" {\n\t\trequire.ErrorContains(t, err, tt.resolveErr)\n\t\treturn\n\t}\n\trequire.NoError(t, err)\n\n\tswitch tt.targetField {\n\tcase TargetFieldInt:\n\t\tvar cfg targetConfig[int]\n\t\tAssertExpectedMatch(t, tt, conf, &cfg)\n\tcase TargetFieldString, TargetFieldInlineString:\n\t\tvar cfg targetConfig[string]\n\t\tAssertExpectedMatch(t, tt, conf, &cfg)\n\tcase TargetFieldBool:\n\t\tvar cfg targetConfig[bool]\n\t\tAssertExpectedMatch(t, tt, conf, &cfg)\n\tcase TargetFieldSlice:\n\t\tvar cfg targetConfig[[]any]\n\t\tAssertExpectedMatch(t, tt, conf, &cfg)\n\tdefault:\n\t\tt.Fatalf(\"unexpected target field %q\", tt.targetField)\n\t}\n}\n\nfunc TestStrictTypeCasting(t *testing.T) {\n\tt.Setenv(\"ENV_VALUE\", \"testreceiver\")\n\n\tvalues := []Test{\n\t\t{\n\t\t\tvalue:       \"123\",\n\t\t\ttargetField: TargetFieldInt,\n\t\t\texpected:    123,\n\t\t},\n\t\t{\n\t\t\tvalue:       \"123\",\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    \"123\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"123\",\n\t\t\ttargetField: TargetFieldInlineString,\n\t\t\texpected:    \"inline field with 123 expansion\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"0123\",\n\t\t\ttargetField: TargetFieldInt,\n\t\t\texpected:    83,\n\t\t},\n\t\t{\n\t\t\tvalue:       \"0123\",\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    \"0123\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"0123\",\n\t\t\ttargetField: TargetFieldInlineString,\n\t\t\texpected:    \"inline field with 0123 expansion\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"0xdeadbeef\",\n\t\t\ttargetField: TargetFieldInt,\n\t\t\texpected:    3735928559,\n\t\t},\n\t\t{\n\t\t\tvalue:       \"0xdeadbeef\",\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    \"0xdeadbeef\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"0xdeadbeef\",\n\t\t\ttargetField: TargetFieldInlineString,\n\t\t\texpected:    \"inline field with 0xdeadbeef expansion\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"\\\"0123\\\"\",\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    \"\\\"0123\\\"\",\n\t\t},\n\t\t{\n\t\t\tvalue:        \"\\\"0123\\\"\",\n\t\t\ttargetField:  TargetFieldInt,\n\t\t\tunmarshalErr: \"'field' expected type 'int', got unconvertible type 'string'\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"\\\"0123\\\"\",\n\t\t\ttargetField: TargetFieldInlineString,\n\t\t\texpected:    \"inline field with \\\"0123\\\" expansion\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"!!str 0123\",\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    \"!!str 0123\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"!!str 0123\",\n\t\t\ttargetField: TargetFieldInlineString,\n\t\t\texpected:    \"inline field with !!str 0123 expansion\",\n\t\t},\n\t\t{\n\t\t\tvalue:        \"t\",\n\t\t\ttargetField:  TargetFieldBool,\n\t\t\tunmarshalErr: \"'field' expected type 'bool', got unconvertible type 'string'\",\n\t\t},\n\t\t{\n\t\t\tvalue:        \"23\",\n\t\t\ttargetField:  TargetFieldBool,\n\t\t\tunmarshalErr: \"'field' expected type 'bool', got unconvertible type 'int'\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"{\\\"field\\\": 123}\",\n\t\t\ttargetField: TargetFieldInlineString,\n\t\t\texpected:    \"inline field with {\\\"field\\\": 123} expansion\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"1111:1111:1111:1111:1111::\",\n\t\t\ttargetField: TargetFieldInlineString,\n\t\t\texpected:    \"inline field with 1111:1111:1111:1111:1111:: expansion\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"1111:1111:1111:1111:1111::\",\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    \"1111:1111:1111:1111:1111::\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"2006-01-02T15:04:05Z07:00\",\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    \"2006-01-02T15:04:05Z07:00\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"2006-01-02T15:04:05Z07:00\",\n\t\t\ttargetField: TargetFieldInlineString,\n\t\t\texpected:    \"inline field with 2006-01-02T15:04:05Z07:00 expansion\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"2023-03-20T03:17:55.432328Z\",\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    \"2023-03-20T03:17:55.432328Z\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"2023-03-20T03:17:55.432328Z\",\n\t\t\ttargetField: TargetFieldInlineString,\n\t\t\texpected:    \"inline field with 2023-03-20T03:17:55.432328Z expansion\",\n\t\t},\n\t\t// issue 10787\n\t\t{\n\t\t\tvalue:       \"true # comment with a ${env:hello.world} reference\",\n\t\t\ttargetField: TargetFieldBool,\n\t\t\texpected:    true,\n\t\t},\n\t\t{\n\t\t\tvalue:        \"true # comment with a ${env:hello.world} reference\",\n\t\t\ttargetField:  TargetFieldString,\n\t\t\tunmarshalErr: `expected type 'string', got unconvertible type 'bool'`,\n\t\t},\n\t\t{\n\t\t\tvalue:       \"true # comment with a ${env:hello.world} reference\",\n\t\t\ttargetField: TargetFieldInlineString,\n\t\t\tresolveErr:  `environment variable \"hello.world\" has invalid name`,\n\t\t},\n\t\t// issue 10759\n\t\t{\n\t\t\tvalue:       `[\"a\",`,\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    `[\"a\",`,\n\t\t},\n\t\t{\n\t\t\tvalue:       `[\"a\",`,\n\t\t\ttargetField: TargetFieldInlineString,\n\t\t\texpected:    `inline field with [\"a\", expansion`,\n\t\t},\n\t\t// issue 10799\n\t\t{\n\t\t\tvalue:       `[filelog,windowseventlog/application]`,\n\t\t\ttargetField: TargetFieldSlice,\n\t\t\texpected:    []any{\"filelog\", \"windowseventlog/application\"},\n\t\t},\n\t\t{\n\t\t\tvalue:       `[filelog,windowseventlog/application]`,\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    \"[filelog,windowseventlog/application]\",\n\t\t},\n\t\t{\n\t\t\tvalue:       `[filelog,windowseventlog/application]`,\n\t\t\ttargetField: TargetFieldInlineString,\n\t\t\texpected:    \"inline field with [filelog,windowseventlog/application] expansion\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"$$ENV\",\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    \"$ENV\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"$$ENV\",\n\t\t\ttargetField: TargetFieldInlineString,\n\t\t\texpected:    \"inline field with $ENV expansion\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"$${ENV}\",\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    \"${ENV}\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"$${ENV}\",\n\t\t\ttargetField: TargetFieldInlineString,\n\t\t\texpected:    \"inline field with ${ENV} expansion\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"$${env:ENV}\",\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    \"${env:ENV}\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"$${env:ENV}\",\n\t\t\ttargetField: TargetFieldInlineString,\n\t\t\texpected:    \"inline field with ${env:ENV} expansion\",\n\t\t},\n\t\t{\n\t\t\tvalue:       `[filelog,${env:ENV_VALUE}]`,\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    \"[filelog,testreceiver]\",\n\t\t},\n\t\t{\n\t\t\tvalue:       `[filelog,${ENV_VALUE}]`,\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    \"[filelog,testreceiver]\",\n\t\t},\n\t\t{\n\t\t\tvalue:       `[\"filelog\",\"$${env:ENV_VALUE}\"]`,\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    `[\"filelog\",\"${env:ENV_VALUE}\"]`,\n\t\t},\n\t\t{\n\t\t\tvalue:       `[\"filelog\",\"$${ENV_VALUE}\"]`,\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    `[\"filelog\",\"${ENV_VALUE}\"]`,\n\t\t},\n\t\t{\n\t\t\tvalue:       `[\"filelog\",\"$$ENV_VALUE\"]`,\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    `[\"filelog\",\"$ENV_VALUE\"]`,\n\t\t},\n\t\t{\n\t\t\tvalue:       `[\"filelog\",\"$ENV_VALUE\"]`,\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    `[\"filelog\",\"$ENV_VALUE\"]`,\n\t\t},\n\t}\n\n\tfor _, tt := range values {\n\t\tt.Run(tt.value+\"/\"+string(tt.targetField)+\"/\"+\"direct\", func(t *testing.T) {\n\t\t\ttestFile := \"types_expand.yaml\"\n\t\t\tif tt.targetField == TargetFieldInlineString {\n\t\t\t\ttestFile = \"types_expand_inline.yaml\"\n\t\t\t}\n\t\t\tresolver := NewResolver(t, testFile)\n\t\t\tt.Setenv(\"ENV\", tt.value)\n\t\t\tAssertResolvesTo(t, resolver, tt)\n\t\t})\n\n\t\tt.Run(tt.value+\"/\"+string(tt.targetField)+\"/\"+\"indirect\", func(t *testing.T) {\n\t\t\ttestFile := \"types_expand.yaml\"\n\t\t\tif tt.targetField == TargetFieldInlineString {\n\t\t\t\ttestFile = \"types_expand_inline.yaml\"\n\t\t\t}\n\n\t\t\tresolver := NewResolver(t, testFile)\n\t\t\tt.Setenv(\"ENV\", \"${env:ENV2}\")\n\t\t\tt.Setenv(\"ENV2\", tt.value)\n\t\t\tAssertResolvesTo(t, resolver, tt)\n\t\t})\n\t}\n}\n\nfunc TestRecursiveInlineString(t *testing.T) {\n\tvalues := []Test{\n\t\t{\n\t\t\tvalue:       \"123\",\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    \"The value The value 123 is wrapped is wrapped\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"123\",\n\t\t\ttargetField: TargetFieldInlineString,\n\t\t\texpected:    \"inline field with The value The value 123 is wrapped is wrapped expansion\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"opentelemetry\",\n\t\t\ttargetField: TargetFieldString,\n\t\t\texpected:    \"The value The value opentelemetry is wrapped is wrapped\",\n\t\t},\n\t\t{\n\t\t\tvalue:       \"opentelemetry\",\n\t\t\ttargetField: TargetFieldInlineString,\n\t\t\texpected:    \"inline field with The value The value opentelemetry is wrapped is wrapped expansion\",\n\t\t},\n\t}\n\n\tfor _, tt := range values {\n\t\tt.Run(tt.value+\"/\"+string(tt.targetField), func(t *testing.T) {\n\t\t\ttestFile := \"types_expand.yaml\"\n\t\t\tif tt.targetField == TargetFieldInlineString {\n\t\t\t\ttestFile = \"types_expand_inline.yaml\"\n\t\t\t}\n\n\t\t\tresolver := NewResolver(t, testFile)\n\t\t\tt.Setenv(\"ENV\", \"The value ${env:ENV2} is wrapped\")\n\t\t\tt.Setenv(\"ENV2\", \"The value ${env:ENV3} is wrapped\")\n\t\t\tt.Setenv(\"ENV3\", tt.value)\n\t\t\tAssertResolvesTo(t, resolver, tt)\n\t\t})\n\t}\n}\n\nfunc TestRecursiveMaps(t *testing.T) {\n\tvalue := \"{value: 123}\"\n\tresolver := NewResolver(t, \"types_expand.yaml\")\n\tt.Setenv(\"ENV\", `{env: \"${env:ENV2}\", inline: \"inline ${env:ENV2}\"}`)\n\tt.Setenv(\"ENV2\", `{env2: \"${env:ENV3}\"}`)\n\tt.Setenv(\"ENV3\", value)\n\tconf, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\n\ttype Value struct {\n\t\tValue int `mapstructure:\"value\"`\n\t}\n\ttype ENV2 struct {\n\t\tEnv2 Value `mapstructure:\"env2\"`\n\t}\n\ttype ENV struct {\n\t\tEnv    ENV2   `mapstructure:\"env\"`\n\t\tInline string `mapstructure:\"inline\"`\n\t}\n\ttype Target struct {\n\t\tField ENV `mapstructure:\"field\"`\n\t}\n\n\tvar cfg Target\n\terr = conf.Unmarshal(&cfg)\n\trequire.NoError(t, err)\n\trequire.Equal(t,\n\t\tTarget{Field: ENV{\n\t\t\tEnv: ENV2{\n\t\t\t\tEnv2: Value{\n\t\t\t\t\tValue: 123,\n\t\t\t\t},\n\t\t\t},\n\t\t\tInline: \"inline {env2: \\\"{value: 123}\\\"}\",\n\t\t}},\n\t\tcfg,\n\t)\n\n\tconfStr, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\tvar cfgStr targetConfig[string]\n\terr = confStr.Unmarshal(&cfgStr)\n\trequire.NoError(t, err)\n\trequire.Equal(t, `{env: \"{env2: \"{value: 123}\"}\", inline: \"inline {env2: \"{value: 123}\"}\"}`,\n\t\tcfgStr.Field,\n\t)\n}\n\n// Test that comments with invalid ${env:...} references do not prevent configuration from loading.\nfunc TestIssue10787(t *testing.T) {\n\tresolver := NewResolver(t, \"issue-10787-main.yaml\")\n\tconf, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\tassert.Equal(t, map[string]any{\n\t\t\"exporters\": map[string]any{\n\t\t\t\"debug\": map[string]any{\n\t\t\t\t\"verbosity\": \"detailed\",\n\t\t\t},\n\t\t},\n\t\t\"processors\": map[string]any{\n\t\t\t\"memory_limiter\": nil,\n\t\t},\n\t\t\"receivers\": map[string]any{\n\t\t\t\"otlp\": map[string]any{\n\t\t\t\t\"protocols\": map[string]any{\n\t\t\t\t\t\"grpc\": map[string]any{\n\t\t\t\t\t\t\"endpoint\": \"0.0.0.0:4317\",\n\t\t\t\t\t},\n\t\t\t\t\t\"http\": map[string]any{\n\t\t\t\t\t\t\"endpoint\": \"0.0.0.0:4318\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t\"service\": map[string]any{\n\t\t\t\"pipelines\": map[string]any{\n\t\t\t\t\"traces\": map[string]any{\n\t\t\t\t\t\"exporters\":  []any{\"debug\"},\n\t\t\t\t\t\"processors\": []any{\"memory_limiter\"},\n\t\t\t\t\t\"receivers\":  []any{\"otlp\"},\n\t\t\t\t},\n\t\t\t},\n\t\t\t\"telemetry\": map[string]any{\n\t\t\t\t\"metrics\": map[string]any{\n\t\t\t\t\t\"level\": \"detailed\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, conf.ToStringMap(),\n\t)\n}\n\nfunc TestStructMappingIssue10787(t *testing.T) {\n\tresolver := NewResolver(t, \"types_expand.yaml\")\n\tt.Setenv(\"ENV\", `# this is a comment\ndebug:\n  verbosity: detailed`)\n\tconf, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\n\ttype Debug struct {\n\t\tVerbosity string `mapstructure:\"verbosity\"`\n\t}\n\ttype Exporters struct {\n\t\tDebug Debug `mapstructure:\"debug\"`\n\t}\n\ttype Target struct {\n\t\tField Exporters `mapstructure:\"field\"`\n\t}\n\n\tvar cfg Target\n\terr = conf.Unmarshal(&cfg)\n\trequire.NoError(t, err)\n\trequire.Equal(t,\n\t\tTarget{Field: Exporters{\n\t\t\tDebug: Debug{\n\t\t\t\tVerbosity: \"detailed\",\n\t\t\t},\n\t\t}},\n\t\tcfg,\n\t)\n\n\tconfStr, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\tvar cfgStr targetConfig[string]\n\terr = confStr.Unmarshal(&cfgStr)\n\trequire.NoError(t, err)\n\trequire.Equal(t, `# this is a comment\ndebug:\n  verbosity: detailed`,\n\t\tcfgStr.Field,\n\t)\n}\n\nfunc TestStructMappingIssue10787_ExpandComment(t *testing.T) {\n\tresolver := NewResolver(t, \"types_expand.yaml\")\n\tt.Setenv(\"EXPAND_ME\", \"an expanded env var\")\n\tt.Setenv(\"ENV\", `# this is a comment with ${EXPAND_ME}\ndebug:\n  verbosity: detailed`)\n\tconf, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\n\ttype Debug struct {\n\t\tVerbosity string `mapstructure:\"verbosity\"`\n\t}\n\ttype Exporters struct {\n\t\tDebug Debug `mapstructure:\"debug\"`\n\t}\n\ttype Target struct {\n\t\tField Exporters `mapstructure:\"field\"`\n\t}\n\n\tvar cfg Target\n\terr = conf.Unmarshal(&cfg)\n\trequire.NoError(t, err)\n\trequire.Equal(t,\n\t\tTarget{Field: Exporters{\n\t\t\tDebug: Debug{\n\t\t\t\tVerbosity: \"detailed\",\n\t\t\t},\n\t\t}},\n\t\tcfg,\n\t)\n\n\tconfStr, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\tvar cfgStr targetConfig[string]\n\terr = confStr.Unmarshal(&cfgStr)\n\trequire.NoError(t, err)\n\trequire.Equal(t, `# this is a comment with an expanded env var\ndebug:\n  verbosity: detailed`,\n\t\tcfgStr.Field,\n\t)\n}\n\nfunc TestIndirectSliceEnvVar(t *testing.T) {\n\t// This replicates the situation in https://github.com/open-telemetry/opentelemetry-collector/issues/10799\n\t// where a configuration file is loaded that contains a reference to a slice of strings in an environment variable.\n\tt.Setenv(\"BASE_FOLDER\", \"testdata\")\n\tt.Setenv(\"OTEL_LOGS_RECEIVER\", \"[nop, otlp]\")\n\tt.Setenv(\"OTEL_LOGS_EXPORTER\", \"[otlp, nop]\")\n\tresolver := NewResolver(t, \"indirect-slice-env-var-main.yaml\")\n\tconf, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\n\ttype CollectorConf struct {\n\t\tExporters struct {\n\t\t\tOTLP struct {\n\t\t\t\tEndpoint string `mapstructure:\"endpoint\"`\n\t\t\t} `mapstructure:\"otlp_grpc\"`\n\t\t\tNop struct{} `mapstructure:\"nop\"`\n\t\t} `mapstructure:\"exporters\"`\n\t\tReceivers struct {\n\t\t\tOTLP struct {\n\t\t\t\tProtocols struct {\n\t\t\t\t\tGRPC struct{} `mapstructure:\"grpc\"`\n\t\t\t\t} `mapstructure:\"protocols\"`\n\t\t\t} `mapstructure:\"otlp\"`\n\t\t\tNop struct{} `mapstructure:\"nop\"`\n\t\t} `mapstructure:\"receivers\"`\n\t\tService struct {\n\t\t\tPipelines struct {\n\t\t\t\tLogs struct {\n\t\t\t\t\tExporters []string `mapstructure:\"exporters\"`\n\t\t\t\t\tReceivers []string `mapstructure:\"receivers\"`\n\t\t\t\t} `mapstructure:\"logs\"`\n\t\t\t} `mapstructure:\"pipelines\"`\n\t\t} `mapstructure:\"service\"`\n\t}\n\n\tvar collectorConf CollectorConf\n\terr = conf.Unmarshal(&collectorConf)\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"localhost:4317\", collectorConf.Exporters.OTLP.Endpoint)\n\tassert.Equal(t, []string{\"nop\", \"otlp\"}, collectorConf.Service.Pipelines.Logs.Receivers)\n\tassert.Equal(t, []string{\"otlp\", \"nop\"}, collectorConf.Service.Pipelines.Logs.Exporters)\n}\n\nfunc TestIssue10937_MapType(t *testing.T) {\n\tt.Setenv(\"VALUE\", \"1234\")\n\n\tresolver := NewResolver(t, \"types_map.yaml\")\n\tconf, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\n\tvar cfg targetConfig[map[string]configopaque.String]\n\terr = conf.Unmarshal(&cfg)\n\trequire.NoError(t, err)\n\trequire.Equal(t, map[string]configopaque.String{\"key\": \"1234\"}, cfg.Field)\n}\n\nfunc TestIssue10937_ArrayType(t *testing.T) {\n\tt.Setenv(\"VALUE\", \"1234\")\n\n\tresolver := NewResolver(t, \"types_slice.yaml\")\n\tconf, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\n\tvar cfgStrSlice targetConfig[[]string]\n\terr = conf.Unmarshal(&cfgStrSlice)\n\trequire.NoError(t, err)\n\trequire.Equal(t, []string{\"1234\"}, cfgStrSlice.Field)\n\n\tvar cfgStrArray targetConfig[[1]string]\n\terr = conf.Unmarshal(&cfgStrArray)\n\trequire.NoError(t, err)\n\trequire.Equal(t, [1]string{\"1234\"}, cfgStrArray.Field)\n\n\tvar cfgAnySlice targetConfig[[]any]\n\terr = conf.Unmarshal(&cfgAnySlice)\n\trequire.NoError(t, err)\n\trequire.Equal(t, []any{1234}, cfgAnySlice.Field)\n\n\tvar cfgAnyArray targetConfig[[1]any]\n\terr = conf.Unmarshal(&cfgAnyArray)\n\trequire.NoError(t, err)\n\trequire.Equal(t, [1]any{1234}, cfgAnyArray.Field)\n}\n\nfunc TestIssue10937_ComplexType(t *testing.T) {\n\tt.Setenv(\"VALUE\", \"1234\")\n\n\tresolver := NewResolver(t, \"types_complex.yaml\")\n\tconf, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\n\tvar cfgStringy targetConfig[[]map[string][]string]\n\terr = conf.Unmarshal(&cfgStringy)\n\trequire.NoError(t, err)\n\trequire.Equal(t, []map[string][]string{{\"key\": {\"1234\"}}}, cfgStringy.Field)\n\n\tvar cfgNotStringy targetConfig[[]map[string][]any]\n\terr = conf.Unmarshal(&cfgNotStringy)\n\trequire.NoError(t, err)\n\trequire.Equal(t, []map[string][]any{{\"key\": {1234}}}, cfgNotStringy.Field)\n}\n\nfunc TestIssue10949_UnsetVar(t *testing.T) {\n\tt.Setenv(\"ENV\", \"\")\n\tresolver := NewResolver(t, \"types_expand.yaml\")\n\tconf, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\n\tvar cfg targetConfig[int]\n\terr = conf.Unmarshal(&cfg)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 0, cfg.Field)\n}\n"
  },
  {
    "path": "confmap/internal/encoder.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/confmap/internal\"\n\nimport (\n\t\"reflect\"\n\n\t\"github.com/go-viper/mapstructure/v2\"\n\n\tencoder \"go.opentelemetry.io/collector/confmap/internal/mapstructure\"\n)\n\n// EncoderConfig returns a default encoder.EncoderConfig that includes\n// an EncodeHook that handles both TextMarshaler and Marshaler\n// interfaces.\nfunc EncoderConfig(rawVal any, _ MarshalOptions) *encoder.EncoderConfig {\n\treturn &encoder.EncoderConfig{\n\t\tEncodeHook: mapstructure.ComposeDecodeHookFunc(\n\t\t\tencoder.YamlMarshalerHookFunc(),\n\t\t\tencoder.TextMarshalerHookFunc(),\n\t\t\tmarshalerHookFunc(rawVal),\n\t\t),\n\t}\n}\n\n// marshalerHookFunc returns a DecodeHookFuncValue that checks structs that aren't\n// the original to see if they implement the Marshaler interface.\nfunc marshalerHookFunc(orig any) mapstructure.DecodeHookFuncValue {\n\torigType := reflect.TypeOf(orig)\n\treturn safeWrapDecodeHookFunc(func(from, _ reflect.Value) (any, error) {\n\t\tif from.Kind() != reflect.Struct {\n\t\t\treturn from.Interface(), nil\n\t\t}\n\n\t\t// ignore original to avoid infinite loop.\n\t\tif from.Type() == origType && reflect.DeepEqual(from.Interface(), orig) {\n\t\t\treturn from.Interface(), nil\n\t\t}\n\t\tmarshaler, ok := from.Interface().(Marshaler)\n\t\tif !ok {\n\t\t\treturn from.Interface(), nil\n\t\t}\n\t\tconf := NewFromStringMap(nil)\n\t\tif err := marshaler.Marshal(conf); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tstringMap := conf.ToStringMap()\n\t\tif stringMap == nil {\n\t\t\t// If conf is still nil after marshaling, we want to encode it as an untyped nil\n\t\t\t// instead of a map-typed nil. This ensures the value is a proper null value\n\t\t\t// in the final marshaled output instead of an empty map. We hit this case\n\t\t\t// when marshaling wrapper structs that have no direct representation\n\t\t\t// in the marshaled output that aren't tagged with \"squash\" on the fields\n\t\t\t// they're used on.\n\t\t\treturn nil, nil\n\t\t}\n\t\treturn stringMap, nil\n\t})\n}\n"
  },
  {
    "path": "confmap/internal/envvar/pattern.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage envvar // import \"go.opentelemetry.io/collector/confmap/internal/envvar\"\n\nimport \"regexp\"\n\nconst ValidationPattern = `^[a-zA-Z_][a-zA-Z0-9_]*$`\n\nvar ValidationRegexp = regexp.MustCompile(ValidationPattern)\n"
  },
  {
    "path": "confmap/internal/expand.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/confmap/internal\"\n\n// ExpandedValue holds the YAML parsed value and original representation of a value.\n// It keeps track of the original representation to be used by the 'useExpandValue' hook\n// if the target field is a string. We need to keep both representations because we don't know\n// what the target field type is until `Unmarshal` is called.\ntype ExpandedValue struct {\n\t// Value is the expanded value.\n\tValue any\n\t// Original is the original representation of the value.\n\tOriginal string\n}\n"
  },
  {
    "path": "confmap/internal/mapstructure/encoder.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage mapstructure // import \"go.opentelemetry.io/collector/confmap/internal/mapstructure\"\n\nimport (\n\t\"encoding\"\n\t\"errors\"\n\t\"fmt\"\n\t\"maps\"\n\t\"reflect\"\n\t\"strings\"\n\n\t\"github.com/go-viper/mapstructure/v2\"\n\t\"go.yaml.in/yaml/v3\"\n)\n\nconst (\n\ttagNameMapStructure = \"mapstructure\"\n\toptionSeparator     = \",\"\n\toptionOmitEmpty     = \"omitempty\"\n\toptionSquash        = \"squash\"\n\toptionRemain        = \"remain\"\n\toptionSkip          = \"-\"\n)\n\nvar errNonStringEncodedKey = errors.New(\"non string-encoded key\")\n\n// tagInfo stores the mapstructure tag details.\ntype tagInfo struct {\n\tname      string\n\tomitEmpty bool\n\tsquash    bool\n}\n\n// An Encoder takes structured data and converts it into an\n// interface following the mapstructure tags.\ntype Encoder struct {\n\tconfig *EncoderConfig\n}\n\n// EncoderConfig is the configuration used to create a new encoder.\ntype EncoderConfig struct {\n\t// EncodeHook, if set, is a way to provide custom encoding. It\n\t// will be called before structs and primitive types.\n\tEncodeHook mapstructure.DecodeHookFunc\n}\n\n// New returns a new encoder for the configuration.\nfunc New(cfg *EncoderConfig) *Encoder {\n\treturn &Encoder{config: cfg}\n}\n\n// Encode takes the input and uses reflection to encode it to\n// an interface based on the mapstructure spec.\nfunc (e *Encoder) Encode(input any) (any, error) {\n\treturn e.encode(reflect.ValueOf(input))\n}\n\n// encode processes the value based on the reflect.Kind.\nfunc (e *Encoder) encode(value reflect.Value) (any, error) {\n\tif value.IsValid() {\n\t\tswitch value.Kind() {\n\t\tcase reflect.Interface, reflect.Ptr:\n\t\t\treturn e.encode(value.Elem())\n\t\tcase reflect.Map:\n\t\t\treturn e.encodeMap(value)\n\t\tcase reflect.Slice:\n\t\t\treturn e.encodeSlice(value)\n\t\tcase reflect.Struct:\n\t\t\treturn e.encodeStruct(value)\n\t\tdefault:\n\t\t\treturn e.encodeHook(value)\n\t\t}\n\t}\n\treturn nil, nil\n}\n\n// encodeHook calls the EncodeHook in the EncoderConfig with the value passed in.\n// This is called before processing structs and for primitive data types.\nfunc (e *Encoder) encodeHook(value reflect.Value) (any, error) {\n\tif e.config != nil && e.config.EncodeHook != nil {\n\t\tout, err := mapstructure.DecodeHookExec(e.config.EncodeHook, value, value)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error running encode hook: %w\", err)\n\t\t}\n\t\treturn out, nil\n\t}\n\treturn value.Interface(), nil\n}\n\n// encodeStruct encodes the struct by iterating over the fields, getting the\n// mapstructure tagInfo for each exported field, and encoding the value.\nfunc (e *Encoder) encodeStruct(value reflect.Value) (any, error) {\n\tif value.Kind() != reflect.Struct {\n\t\treturn nil, &reflect.ValueError{\n\t\t\tMethod: \"encodeStruct\",\n\t\t\tKind:   value.Kind(),\n\t\t}\n\t}\n\tout, err := e.encodeHook(value)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tvalue = reflect.ValueOf(out)\n\t// if the output of encodeHook is no longer a struct,\n\t// call encode against it.\n\tif value.Kind() != reflect.Struct {\n\t\treturn e.encode(value)\n\t}\n\tresult := make(map[string]any)\n\tfor i := 0; i < value.NumField(); i++ {\n\t\tfield := value.Field(i)\n\t\tif field.CanInterface() {\n\t\t\tinfo := getTagInfo(value.Type().Field(i))\n\t\t\tif (info.omitEmpty && field.IsZero()) || info.name == optionSkip {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tencoded, err := e.encode(field)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"error encoding field %q: %w\", info.name, err)\n\t\t\t}\n\t\t\tif info.squash {\n\t\t\t\tif m, ok := encoded.(map[string]any); ok {\n\t\t\t\t\tmaps.Copy(result, m)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tresult[info.name] = encoded\n\t\t\t}\n\t\t}\n\t}\n\treturn result, nil\n}\n\n// encodeSlice iterates over the slice and encodes each of the elements.\nfunc (e *Encoder) encodeSlice(value reflect.Value) (any, error) {\n\tif value.Kind() != reflect.Slice {\n\t\treturn nil, &reflect.ValueError{\n\t\t\tMethod: \"encodeSlice\",\n\t\t\tKind:   value.Kind(),\n\t\t}\n\t}\n\n\tif value.IsNil() {\n\t\treturn []any(nil), nil\n\t}\n\n\tresult := make([]any, value.Len())\n\tfor i := 0; i < value.Len(); i++ {\n\t\tvar err error\n\t\tif result[i], err = e.encode(value.Index(i)); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error encoding element in slice at index %d: %w\", i, err)\n\t\t}\n\t}\n\treturn result, nil\n}\n\n// encodeMap encodes a map by encoding the key and value. Returns errNonStringEncodedKey\n// if the key is not encoded into a string.\nfunc (e *Encoder) encodeMap(value reflect.Value) (any, error) {\n\tif value.Kind() != reflect.Map {\n\t\treturn nil, &reflect.ValueError{\n\t\t\tMethod: \"encodeMap\",\n\t\t\tKind:   value.Kind(),\n\t\t}\n\t}\n\n\tvar result map[string]any\n\tif value.Len() > 0 || !value.IsNil() {\n\t\tresult = make(map[string]any)\n\t}\n\n\titerator := value.MapRange()\n\tfor iterator.Next() {\n\t\tencoded, err := e.encode(iterator.Key())\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error encoding key: %w\", err)\n\t\t}\n\n\t\tv := reflect.ValueOf(encoded)\n\t\tvar key string\n\n\t\tswitch v.Kind() {\n\t\tcase reflect.String:\n\t\t\tkey = v.String()\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"%w, key: %q, kind: %v, type: %T\", errNonStringEncodedKey, iterator.Key().Interface(), iterator.Key().Kind(), encoded)\n\t\t}\n\n\t\tif _, ok := result[key]; ok {\n\t\t\treturn nil, fmt.Errorf(\"duplicate key %q while encoding\", key)\n\t\t}\n\t\tif result[key], err = e.encode(iterator.Value()); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"error encoding map value for key %q: %w\", key, err)\n\t\t}\n\t}\n\treturn result, nil\n}\n\n// getTagInfo looks up the mapstructure tag and uses that if available.\n// Uses the lowercase field if not found. Checks for omitempty and squash.\nfunc getTagInfo(field reflect.StructField) *tagInfo {\n\tinfo := tagInfo{}\n\tif tag, ok := field.Tag.Lookup(tagNameMapStructure); ok {\n\t\toptions := strings.Split(tag, optionSeparator)\n\t\tinfo.name = options[0]\n\t\tif len(options) > 1 {\n\t\t\tfor _, option := range options[1:] {\n\t\t\t\tswitch option {\n\t\t\t\tcase optionOmitEmpty:\n\t\t\t\t\tinfo.omitEmpty = true\n\t\t\t\tcase optionSquash, optionRemain:\n\t\t\t\t\tinfo.squash = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t} else {\n\t\tinfo.name = strings.ToLower(field.Name)\n\t}\n\treturn &info\n}\n\n// TextMarshalerHookFunc returns a DecodeHookFuncValue that checks\n// for the encoding.TextMarshaler interface and calls the MarshalText\n// function if found.\nfunc TextMarshalerHookFunc() mapstructure.DecodeHookFuncValue {\n\treturn func(from, _ reflect.Value) (any, error) {\n\t\tmarshaler, ok := from.Interface().(encoding.TextMarshaler)\n\t\tif !ok {\n\t\t\treturn from.Interface(), nil\n\t\t}\n\t\tout, err := marshaler.MarshalText()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\treturn string(out), nil\n\t}\n}\n\n// YamlMarshalerHookFunc returns a DecodeHookFuncValue that checks for structs\n// that have yaml tags but no mapstructure tags. If found, it will convert the struct\n// to map[string]any using the yaml package, which respects the yaml tags. Ultimately,\n// this allows mapstructure to later marshal the map[string]any in a generic way.\nfunc YamlMarshalerHookFunc() mapstructure.DecodeHookFuncValue {\n\treturn func(from, _ reflect.Value) (any, error) {\n\t\tif from.Kind() == reflect.Struct {\n\t\t\tfor i := 0; i < from.NumField(); i++ {\n\t\t\t\tif _, ok := from.Type().Field(i).Tag.Lookup(\"mapstructure\"); ok {\n\t\t\t\t\t// The struct has at least one mapstructure tag so don't do anything.\n\t\t\t\t\treturn from.Interface(), nil\n\t\t\t\t}\n\n\t\t\t\tif _, ok := from.Type().Field(i).Tag.Lookup(\"yaml\"); ok {\n\t\t\t\t\t// The struct has at least one yaml tag, so convert it to map[string]any using yaml.\n\t\t\t\t\tyamlBytes, err := yaml.Marshal(from.Interface())\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\tvar m map[string]any\n\t\t\t\t\terr = yaml.Unmarshal(yamlBytes, &m)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn nil, err\n\t\t\t\t\t}\n\t\t\t\t\treturn m, nil\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn from.Interface(), nil\n\t}\n}\n"
  },
  {
    "path": "confmap/internal/mapstructure/encoder_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage mapstructure\n\nimport (\n\t\"encoding\"\n\t\"errors\"\n\t\"reflect\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/go-viper/mapstructure/v2\"\n\t\"github.com/stretchr/testify/require\"\n)\n\ntype TestComplexStruct struct {\n\tSkipped               TestEmptyStruct             `mapstructure:\",squash\"`\n\tNested                TestSimpleStruct            `mapstructure:\",squash\"`\n\tSlice                 []TestSimpleStruct          `mapstructure:\"slice,omitempty\"`\n\tPointer               *TestSimpleStruct           `mapstructure:\"ptr\"`\n\tMap                   map[string]TestSimpleStruct `mapstructure:\"map,omitempty\"`\n\tRemain                map[string]any              `mapstructure:\",remain\"`\n\tTranslatedYaml        TestYamlStruct              `mapstructure:\"translated\"`\n\tSquashedYaml          TestYamlStruct              `mapstructure:\",squash\"`\n\tPointerTranslatedYaml *TestPtrToYamlStruct        `mapstructure:\"translated_ptr\"`\n\tPointerSquashedYaml   *TestPtrToYamlStruct        `mapstructure:\",squash\"`\n\tInterface             encoding.TextMarshaler\n}\n\ntype TestSimpleStruct struct {\n\tValue   string `mapstructure:\"value\"`\n\tskipped string\n\terr     error\n}\n\ntype TestEmptyStruct struct {\n\tValue string `mapstructure:\"-\"`\n}\n\ntype TestYamlStruct struct {\n\tYamlValue     string               `yaml:\"yaml_value\"`\n\tYamlOmitEmpty string               `yaml:\"yaml_omit,omitempty\"`\n\tYamlInline    TestYamlSimpleStruct `yaml:\",inline\"`\n}\n\ntype TestPtrToYamlStruct struct {\n\tYamlValue     string                     `yaml:\"yaml_value_ptr\"`\n\tYamlOmitEmpty string                     `yaml:\"yaml_omit_ptr,omitempty\"`\n\tYamlInline    *TestYamlPtrToSimpleStruct `yaml:\",inline\"`\n}\n\ntype TestYamlSimpleStruct struct {\n\tInline string `yaml:\"yaml_inline\"`\n}\n\ntype TestYamlPtrToSimpleStruct struct {\n\tInlinePtr string `yaml:\"yaml_inline_ptr\"`\n}\n\ntype TestID string\n\nfunc (tID TestID) MarshalText() (text []byte, err error) {\n\tout := string(tID)\n\tif out == \"error\" {\n\t\treturn nil, errors.New(\"parsing error\")\n\t}\n\tif !strings.HasSuffix(out, \"_\") {\n\t\tout += \"_\"\n\t}\n\treturn []byte(out), nil\n}\n\ntype TestStringLike string\n\nfunc TestEncode(t *testing.T) {\n\tenc := New(&EncoderConfig{\n\t\tEncodeHook: mapstructure.ComposeDecodeHookFunc(\n\t\t\tYamlMarshalerHookFunc(),\n\t\t\tTextMarshalerHookFunc(),\n\t\t),\n\t})\n\ttestCases := map[string]struct {\n\t\tinput any\n\t\twant  any\n\t}{\n\t\t\"WithString\": {\n\t\t\tinput: \"test\",\n\t\t\twant:  \"test\",\n\t\t},\n\t\t\"WithTextMarshaler\": {\n\t\t\tinput: TestID(\"type\"),\n\t\t\twant:  \"type_\",\n\t\t},\n\t\t\"MapWithTextMarshalerKey\": {\n\t\t\tinput: map[TestID]TestSimpleStruct{\n\t\t\t\tTestID(\"type\"): {Value: \"value\"},\n\t\t\t},\n\t\t\twant: map[string]any{\n\t\t\t\t\"type_\": map[string]any{\"value\": \"value\"},\n\t\t\t},\n\t\t},\n\t\t\"MapWithoutTextMarshalerKey\": {\n\t\t\tinput: map[TestStringLike]TestSimpleStruct{\n\t\t\t\tTestStringLike(\"key\"): {Value: \"value\"},\n\t\t\t},\n\t\t\twant: map[string]any{\n\t\t\t\t\"key\": map[string]any{\"value\": \"value\"},\n\t\t\t},\n\t\t},\n\t\t\"WithSlice\": {\n\t\t\tinput: []TestID{\n\t\t\t\tTestID(\"nop\"),\n\t\t\t\tTestID(\"type_\"),\n\t\t\t},\n\t\t\twant: []any{\"nop_\", \"type_\"},\n\t\t},\n\t\t\"WithSimpleStruct\": {\n\t\t\tinput: TestSimpleStruct{Value: \"test\", skipped: \"skipped\"},\n\t\t\twant: map[string]any{\n\t\t\t\t\"value\": \"test\",\n\t\t\t},\n\t\t},\n\t\t\"WithComplexStruct\": {\n\t\t\tinput: &TestComplexStruct{\n\t\t\t\tSkipped: TestEmptyStruct{\n\t\t\t\t\tValue: \"omitted\",\n\t\t\t\t},\n\t\t\t\tNested: TestSimpleStruct{\n\t\t\t\t\tValue: \"nested\",\n\t\t\t\t},\n\t\t\t\tSlice: []TestSimpleStruct{\n\t\t\t\t\t{Value: \"slice\"},\n\t\t\t\t},\n\t\t\t\tMap: map[string]TestSimpleStruct{\n\t\t\t\t\t\"Key\": {Value: \"map\"},\n\t\t\t\t},\n\t\t\t\tPointer: &TestSimpleStruct{\n\t\t\t\t\tValue: \"pointer\",\n\t\t\t\t},\n\t\t\t\tRemain: map[string]any{\n\t\t\t\t\t\"remain1\": 23,\n\t\t\t\t\t\"remain2\": \"value\",\n\t\t\t\t},\n\t\t\t\tInterface: TestID(\"value\"),\n\t\t\t\tTranslatedYaml: TestYamlStruct{\n\t\t\t\t\tYamlValue:     \"foo_translated\",\n\t\t\t\t\tYamlOmitEmpty: \"\",\n\t\t\t\t\tYamlInline: TestYamlSimpleStruct{\n\t\t\t\t\t\tInline: \"bar_translated\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSquashedYaml: TestYamlStruct{\n\t\t\t\t\tYamlValue:     \"foo_squashed\",\n\t\t\t\t\tYamlOmitEmpty: \"\",\n\t\t\t\t\tYamlInline: TestYamlSimpleStruct{\n\t\t\t\t\t\tInline: \"bar_squashed\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tPointerTranslatedYaml: &TestPtrToYamlStruct{\n\t\t\t\t\tYamlValue:     \"foo_translated_ptr\",\n\t\t\t\t\tYamlOmitEmpty: \"\",\n\t\t\t\t\tYamlInline: &TestYamlPtrToSimpleStruct{\n\t\t\t\t\t\tInlinePtr: \"bar_translated_ptr\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tPointerSquashedYaml: &TestPtrToYamlStruct{\n\t\t\t\t\tYamlValue:     \"foo_squashed_ptr\",\n\t\t\t\t\tYamlOmitEmpty: \"\",\n\t\t\t\t\tYamlInline: &TestYamlPtrToSimpleStruct{\n\t\t\t\t\t\tInlinePtr: \"bar_squashed_ptr\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\twant: map[string]any{\n\t\t\t\t\"value\": \"nested\",\n\t\t\t\t\"slice\": []any{map[string]any{\"value\": \"slice\"}},\n\t\t\t\t\"map\": map[string]any{\n\t\t\t\t\t\"Key\": map[string]any{\"value\": \"map\"},\n\t\t\t\t},\n\t\t\t\t\"ptr\":         map[string]any{\"value\": \"pointer\"},\n\t\t\t\t\"interface\":   \"value_\",\n\t\t\t\t\"yaml_value\":  \"foo_squashed\",\n\t\t\t\t\"yaml_inline\": \"bar_squashed\",\n\t\t\t\t\"translated\": map[string]any{\n\t\t\t\t\t\"yaml_value\":  \"foo_translated\",\n\t\t\t\t\t\"yaml_inline\": \"bar_translated\",\n\t\t\t\t},\n\t\t\t\t\"yaml_value_ptr\":  \"foo_squashed_ptr\",\n\t\t\t\t\"yaml_inline_ptr\": \"bar_squashed_ptr\",\n\t\t\t\t\"translated_ptr\": map[string]any{\n\t\t\t\t\t\"yaml_value_ptr\":  \"foo_translated_ptr\",\n\t\t\t\t\t\"yaml_inline_ptr\": \"bar_translated_ptr\",\n\t\t\t\t},\n\t\t\t\t\"remain1\": 23,\n\t\t\t\t\"remain2\": \"value\",\n\t\t\t},\n\t\t},\n\t}\n\tfor name, testCase := range testCases {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tgot, err := enc.Encode(testCase.input)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, testCase.want, got)\n\t\t})\n\t}\n\t// without the TextMarshalerHookFunc\n\tenc.config.EncodeHook = nil\n\ttestCase := TestID(\"test\")\n\tgot, err := enc.Encode(testCase)\n\trequire.NoError(t, err)\n\trequire.Equal(t, testCase, got)\n}\n\nfunc TestGetTagInfo(t *testing.T) {\n\ttestCases := []struct {\n\t\tname       string\n\t\tfield      reflect.StructField\n\t\twantName   string\n\t\twantOmit   bool\n\t\twantSquash bool\n\t}{\n\t\t{\n\t\t\tname: \"WithoutTags\",\n\t\t\tfield: reflect.StructField{\n\t\t\t\tName: \"Test\",\n\t\t\t},\n\t\t\twantName: \"test\",\n\t\t},\n\t\t{\n\t\t\tname: \"WithoutMapStructureTag\",\n\t\t\tfield: reflect.StructField{\n\t\t\t\tTag:  `yaml:\"hello,inline\"`,\n\t\t\t\tName: \"YAML\",\n\t\t\t},\n\t\t\twantName: \"yaml\",\n\t\t},\n\t\t{\n\t\t\tname: \"WithRename\",\n\t\t\tfield: reflect.StructField{\n\t\t\t\tTag:  `mapstructure:\"hello\"`,\n\t\t\t\tName: \"Test\",\n\t\t\t},\n\t\t\twantName: \"hello\",\n\t\t},\n\t\t{\n\t\t\tname: \"WithOmitEmpty\",\n\t\t\tfield: reflect.StructField{\n\t\t\t\tTag:  `mapstructure:\"hello,omitempty\"`,\n\t\t\t\tName: \"Test\",\n\t\t\t},\n\t\t\twantName: \"hello\",\n\t\t\twantOmit: true,\n\t\t},\n\t\t{\n\t\t\tname: \"WithSquash\",\n\t\t\tfield: reflect.StructField{\n\t\t\t\tTag:  `mapstructure:\",squash\"`,\n\t\t\t\tName: \"Test\",\n\t\t\t},\n\t\t\twantSquash: true,\n\t\t},\n\t\t{\n\t\t\tname: \"WithRemain\",\n\t\t\tfield: reflect.StructField{\n\t\t\t\tTag:  `mapstructure:\",remain\"`,\n\t\t\t\tName: \"Test\",\n\t\t\t},\n\t\t\twantSquash: true,\n\t\t},\n\t}\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := getTagInfo(tt.field)\n\t\t\trequire.Equal(t, tt.wantName, got.name)\n\t\t\trequire.Equal(t, tt.wantOmit, got.omitEmpty)\n\t\t\trequire.Equal(t, tt.wantSquash, got.squash)\n\t\t})\n\t}\n}\n\nfunc TestEncodeValueError(t *testing.T) {\n\tenc := New(nil)\n\ttestValue := reflect.ValueOf(\"\")\n\ttestCases := []struct {\n\t\tencodeFn func(value reflect.Value) (any, error)\n\t\twantErr  error\n\t}{\n\t\t{encodeFn: enc.encodeMap, wantErr: &reflect.ValueError{Method: \"encodeMap\", Kind: reflect.String}},\n\t\t{encodeFn: enc.encodeStruct, wantErr: &reflect.ValueError{Method: \"encodeStruct\", Kind: reflect.String}},\n\t\t{encodeFn: enc.encodeSlice, wantErr: &reflect.ValueError{Method: \"encodeSlice\", Kind: reflect.String}},\n\t}\n\tfor _, tt := range testCases {\n\t\tgot, err := tt.encodeFn(testValue)\n\t\trequire.Error(t, err)\n\t\trequire.Equal(t, tt.wantErr, err)\n\t\trequire.Nil(t, got)\n\t}\n}\n\nfunc TestEncodeNonStringEncodedKey(t *testing.T) {\n\tenc := New(nil)\n\ttestCase := []struct {\n\t\tTest map[string]any\n\t}{\n\t\t{\n\t\t\tTest: map[string]any{\n\t\t\t\t\"test\": map[TestEmptyStruct]TestSimpleStruct{\n\t\t\t\t\t{Value: \"key\"}: {Value: \"value\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tgot, err := enc.Encode(testCase)\n\trequire.Error(t, err)\n\trequire.ErrorIs(t, err, errNonStringEncodedKey)\n\trequire.Nil(t, got)\n}\n\nfunc TestDuplicateKey(t *testing.T) {\n\tenc := New(&EncoderConfig{\n\t\tEncodeHook: TextMarshalerHookFunc(),\n\t})\n\ttestCase := map[TestID]string{\n\t\t\"test\":  \"value\",\n\t\t\"test_\": \"other value\",\n\t}\n\tgot, err := enc.Encode(testCase)\n\trequire.Error(t, err)\n\trequire.Nil(t, got)\n}\n\nfunc TestTextMarshalerError(t *testing.T) {\n\tenc := New(&EncoderConfig{\n\t\tEncodeHook: TextMarshalerHookFunc(),\n\t})\n\ttestCase := map[TestID]string{\n\t\t\"error\": \"value\",\n\t}\n\tgot, err := enc.Encode(testCase)\n\trequire.Error(t, err)\n\trequire.Nil(t, got)\n}\n\nfunc TestEncodeStruct(t *testing.T) {\n\tenc := New(&EncoderConfig{\n\t\tEncodeHook: testHookFunc(),\n\t})\n\ttestCase := TestSimpleStruct{\n\t\tValue:   \"original\",\n\t\tskipped: \"final\",\n\t}\n\tgot, err := enc.Encode(testCase)\n\trequire.NoError(t, err)\n\trequire.Equal(t, \"final\", got)\n}\n\nfunc TestEncodeStructError(t *testing.T) {\n\tenc := New(&EncoderConfig{\n\t\tEncodeHook: testHookFunc(),\n\t})\n\twantErr := errors.New(\"test\")\n\ttestCase := map[TestSimpleStruct]string{\n\t\t{err: wantErr}: \"value\",\n\t}\n\tgot, err := enc.Encode(testCase)\n\trequire.Error(t, err)\n\trequire.ErrorIs(t, err, wantErr)\n\trequire.Nil(t, got)\n}\n\nfunc TestEncodeNil(t *testing.T) {\n\tenc := New(nil)\n\tgot, err := enc.Encode(nil)\n\trequire.NoError(t, err)\n\trequire.Nil(t, got)\n}\n\nfunc testHookFunc() mapstructure.DecodeHookFuncValue {\n\treturn func(from, _ reflect.Value) (any, error) {\n\t\tif from.Kind() != reflect.Struct {\n\t\t\treturn from.Interface(), nil\n\t\t}\n\n\t\tgot, ok := from.Interface().(TestSimpleStruct)\n\t\tif !ok {\n\t\t\treturn from.Interface(), nil\n\t\t}\n\t\tif got.err != nil {\n\t\t\treturn nil, got.err\n\t\t}\n\t\treturn got.skipped, nil\n\t}\n}\n"
  },
  {
    "path": "confmap/internal/mapstructure/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage mapstructure\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "confmap/internal/marshaloption.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/confmap/internal\"\n\ntype MarshalOption interface {\n\tapply(*MarshalOptions)\n}\n\n// MarshalOptions is used by (*Conf).Marshal to toggle unmarshaling settings.\n// It is in the `internal` package so experimental options can be added in xconfmap.\ntype MarshalOptions struct{}\n\ntype MarshalOptionFunc func(*MarshalOptions)\n\nfunc (fn MarshalOptionFunc) apply(set *MarshalOptions) {\n\tfn(set)\n}\n"
  },
  {
    "path": "confmap/internal/merge.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/confmap/internal\"\n\nimport (\n\t\"reflect\"\n\n\t\"github.com/gobwas/glob\"\n\t\"github.com/knadh/koanf/maps\"\n)\n\nfunc mergeAppend(src, dest map[string]any) error {\n\t// mergeAppend recursively merges the src map into the dest map (left to right),\n\t// modifying and expanding the dest map in the process.\n\t// This function does not overwrite component lists, and ensures that the\n\t// final value is a name-aware copy of lists from src and dest.\n\n\t// Compile the globs once\n\tpatterns := []string{\n\t\t\"service::extensions\",\n\t\t\"service::**::receivers\",\n\t\t\"service::**::exporters\",\n\t}\n\tvar globs []glob.Glob\n\tfor _, p := range patterns {\n\t\tif g, err := glob.Compile(p); err == nil {\n\t\t\tglobs = append(globs, g)\n\t\t}\n\t}\n\n\t// Flatten both source and destination maps\n\tsrcFlat, _ := maps.Flatten(src, []string{}, KeyDelimiter)\n\tdestFlat, _ := maps.Flatten(dest, []string{}, KeyDelimiter)\n\n\tfor sKey, sVal := range srcFlat {\n\t\tif !isMatch(sKey, globs) {\n\t\t\tcontinue\n\t\t}\n\n\t\tdVal, dOk := destFlat[sKey]\n\t\tif !dOk {\n\t\t\tcontinue // Let maps.Merge handle missing keys\n\t\t}\n\n\t\tsrcVal := reflect.ValueOf(sVal)\n\t\tdestVal := reflect.ValueOf(dVal)\n\n\t\t// Only merge if the value is a slice or array; let maps.Merge handle other types\n\t\tif srcVal.Kind() == reflect.Slice || srcVal.Kind() == reflect.Array {\n\t\t\tsrcFlat[sKey] = mergeSlice(srcVal, destVal)\n\t\t}\n\t}\n\n\t// Unflatten and merge\n\tmergedSrc := maps.Unflatten(srcFlat, KeyDelimiter)\n\tmaps.Merge(mergedSrc, dest)\n\n\treturn nil\n}\n\n// isMatch checks if a key matches any glob in the list\nfunc isMatch(key string, globs []glob.Glob) bool {\n\tfor _, g := range globs {\n\t\tif g.Match(key) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc mergeSlice(src, dest reflect.Value) any {\n\tslice := reflect.MakeSlice(src.Type(), 0, src.Cap()+dest.Cap())\n\tfor i := 0; i < dest.Len(); i++ {\n\t\tslice = reflect.Append(slice, dest.Index(i))\n\t}\n\n\tfor i := 0; i < src.Len(); i++ {\n\t\tif isPresent(slice, src.Index(i)) {\n\t\t\tcontinue\n\t\t}\n\t\tslice = reflect.Append(slice, src.Index(i))\n\t}\n\treturn slice.Interface()\n}\n\nfunc isPresent(slice, val reflect.Value) bool {\n\tfor i := 0; i < slice.Len(); i++ {\n\t\tif reflect.DeepEqual(val.Interface(), slice.Index(i).Interface()) {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n"
  },
  {
    "path": "confmap/internal/metadata/generated_feature_gates.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\nvar ConfmapEnableMergeAppendOptionFeatureGate = featuregate.GlobalRegistry().MustRegister(\n\t\"confmap.enableMergeAppendOption\",\n\tfeaturegate.StageAlpha,\n\tfeaturegate.WithRegisterDescription(\"Combines lists when resolving configs from different sources. This feature gate will not be stabilized 'as is'; the current behavior will remain the default.\"),\n\tfeaturegate.WithRegisterReferenceURL(\"https://github.com/open-telemetry/opentelemetry-collector/issues/8754\"),\n\tfeaturegate.WithRegisterFromVersion(\"v0.120.0\"),\n)\n\nvar ConfmapNewExpandedValueSanitizerFeatureGate = featuregate.GlobalRegistry().MustRegister(\n\t\"confmap.newExpandedValueSanitizer\",\n\tfeaturegate.StageBeta,\n\tfeaturegate.WithRegisterDescription(\"Fixes some types of decoding errors where environment variables are parsed as non-string types but assigned to string fields.\"),\n\tfeaturegate.WithRegisterReferenceURL(\"https://github.com/open-telemetry/opentelemetry-collector/pull/14413\"),\n\tfeaturegate.WithRegisterFromVersion(\"v0.144.0\"),\n)\n"
  },
  {
    "path": "confmap/internal/testdata/basic_types.yaml",
    "content": "typed.options:\n  floating.point.example:  3.14\n  integer.example: 1234\n  bool.example: false\n  string.example: this is a string\n  nil.example:\n"
  },
  {
    "path": "confmap/internal/testdata/config.yaml",
    "content": "receivers:\n    nop:\n    nop/myreceiver:\n\nprocessors:\n    nop:\n    nop/myprocessor:\n\nexporters:\n    nop:\n    nop/myexporter:\n\nextensions:\n    nop:\n    nop/myextension:\n\nservice:\n    extensions: [nop]\n    pipelines:\n        traces:\n            receivers: [nop]\n            processors: [nop]\n            exporters: [nop]\n"
  },
  {
    "path": "confmap/internal/testdata/config2.yaml",
    "content": "service:\n    extensions: [nop2]\n    pipelines:\n        traces:\n            receivers: [nop2]\n            processors: [nop]\n            exporters: [nop2]\n"
  },
  {
    "path": "confmap/internal/testdata/embedded_keys.yaml",
    "content": "typed::options:\n  floating::point::example:  3.14\n  integer::example: 1234\n  bool::example: false\n  string::example: this is a string\n  nil::example:\n"
  },
  {
    "path": "confmap/internal/third_party/composehook/compose_hook.go",
    "content": "// Copyright (c) 2013 Mitchell Hashimoto\n// SPDX-License-Identifier: MIT\n// This code is a modified version of https://github.com/go-viper/mapstructure\n\npackage composehook // import \"go.opentelemetry.io/collector/confmap/internal/third_party/composehook\"\n\nimport (\n\t\"errors\"\n\t\"reflect\"\n\n\t\"github.com/go-viper/mapstructure/v2\"\n)\n\n// typedDecodeHook takes a raw DecodeHookFunc (an any) and turns\n// it into the proper DecodeHookFunc type, such as DecodeHookFuncType.\nfunc typedDecodeHook(h mapstructure.DecodeHookFunc) mapstructure.DecodeHookFunc {\n\t// Create variables here so we can reference them with the reflect pkg\n\tvar f1 mapstructure.DecodeHookFuncType\n\tvar f2 mapstructure.DecodeHookFuncKind\n\tvar f3 mapstructure.DecodeHookFuncValue\n\n\t// Fill in the variables into this interface and the rest is done\n\t// automatically using the reflect package.\n\tpotential := []any{f3, f1, f2}\n\n\tv := reflect.ValueOf(h)\n\tvt := v.Type()\n\tfor _, raw := range potential {\n\t\tpt := reflect.ValueOf(raw).Type()\n\t\tif vt.ConvertibleTo(pt) {\n\t\t\treturn v.Convert(pt).Interface()\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// cachedDecodeHook takes a raw DecodeHookFunc (an any) and turns\n// it into a closure to be used directly\n// if the type fails to convert we return a closure always erroring to keep the previous behavior\nfunc cachedDecodeHook(raw mapstructure.DecodeHookFunc) func(reflect.Value, reflect.Value) (any, error) {\n\tswitch f := typedDecodeHook(raw).(type) {\n\tcase mapstructure.DecodeHookFuncType:\n\t\treturn func(from, to reflect.Value) (any, error) {\n\t\t\t// CHANGE FROM UPSTREAM: check if from is valid and return nil if not\n\t\t\tif !from.IsValid() {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t\treturn f(from.Type(), to.Type(), from.Interface())\n\t\t}\n\tcase mapstructure.DecodeHookFuncKind:\n\t\treturn func(from, to reflect.Value) (any, error) {\n\t\t\t// CHANGE FROM UPSTREAM: check if from is valid and return nil if not\n\t\t\tif !from.IsValid() {\n\t\t\t\treturn nil, nil\n\t\t\t}\n\t\t\treturn f(from.Kind(), to.Kind(), from.Interface())\n\t\t}\n\tcase mapstructure.DecodeHookFuncValue:\n\t\treturn func(from, to reflect.Value) (any, error) {\n\t\t\treturn f(from, to)\n\t\t}\n\tdefault:\n\t\treturn func(reflect.Value, reflect.Value) (any, error) {\n\t\t\treturn nil, errors.New(\"invalid decode hook signature\")\n\t\t}\n\t}\n}\n\n// ComposeDecodeHookFunc creates a single DecodeHookFunc that\n// automatically composes multiple DecodeHookFuncs.\n//\n// The composed funcs are called in order, with the result of the\n// previous transformation.\n//\n// This is a copy of [mapstructure.ComposeDecodeHookFunc] but with\n// validation added.\nfunc ComposeDecodeHookFunc(fs ...mapstructure.DecodeHookFunc) mapstructure.DecodeHookFunc {\n\tcached := make([]func(reflect.Value, reflect.Value) (any, error), 0, len(fs))\n\tfor _, f := range fs {\n\t\tcached = append(cached, cachedDecodeHook(f))\n\t}\n\treturn func(f, t reflect.Value) (any, error) {\n\t\tvar err error\n\n\t\t// CHANGE FROM UPSTREAM: check if f is valid before calling f.Interface()\n\t\tvar data any\n\t\tif f.IsValid() {\n\t\t\tdata = f.Interface()\n\t\t}\n\n\t\tnewFrom := f\n\t\tfor _, c := range cached {\n\t\t\tdata, err = c(newFrom, t)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, err\n\t\t\t}\n\t\t\tnewFrom = reflect.ValueOf(data)\n\t\t}\n\n\t\treturn data, nil\n\t}\n}\n"
  },
  {
    "path": "confmap/internal/unmarshaloption.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/confmap/internal\"\n\ntype UnmarshalOption interface {\n\tapply(*UnmarshalOptions)\n}\n\n// UnmarshalOptions is used by (*Conf).Unmarshal to toggle unmarshaling settings.\n// It is in the `internal` package so experimental options can be added in xconfmap.\ntype UnmarshalOptions struct {\n\tIgnoreUnused     bool\n\tForceUnmarshaler bool\n}\n\ntype UnmarshalOptionFunc func(*UnmarshalOptions)\n\nfunc (fn UnmarshalOptionFunc) apply(set *UnmarshalOptions) {\n\tfn(set)\n}\n"
  },
  {
    "path": "confmap/metadata.yaml",
    "content": "type: confmap\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  codeowners:\n    active:\n      - mx-psi\n      - evan-bradley\n  class: pkg\n  stability:\n    stable: [logs, metrics, traces]\n\nfeature_gates:\n  - id: confmap.enableMergeAppendOption\n    description: \"Combines lists when resolving configs from different sources. This feature gate will not be stabilized 'as is'; the current behavior will remain the default.\"\n    stage: alpha\n    from_version: 'v0.120.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/issues/8754'\n  - id: confmap.newExpandedValueSanitizer\n    description: 'Fixes some types of decoding errors where environment variables are parsed as non-string types but assigned to string fields.'\n    stage: beta\n    from_version: 'v0.144.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/pull/14413'\n"
  },
  {
    "path": "confmap/provider/envprovider/Makefile",
    "content": "include ../../../Makefile.Common\n"
  },
  {
    "path": "confmap/provider/envprovider/README.md",
    "content": "# Environment Variable Provider\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [stable]  |\n| Distributions | [core], [contrib], [k8s], [otlp] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Aprovider%2Fenvprovider%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Aprovider%2Fenvprovider) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Aprovider%2Fenvprovider%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Aprovider%2Fenvprovider) |\n\n[stable]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stable\n[core]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n[k8s]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\n[otlp]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-otlp\n<!-- end autogenerated section -->\n\n## Usage\n\nThe scheme for this provider is `env`. Usage looks like the following:\n\n```text\nenv:NAME_OF_ENVIRONMENT_VARIABLE\n```\n\nTo use default values when the environment variable has not been set, you can\ninclude a suffix to specify it:\n\n```text\nenv:NAME_OF_ENVIRONMENT_VARIABLE:-default_value\n```\n\nEnvironment variables must match the following regular expression. That is, they\nmust be at least one character, start with a letter or underscore, and can only\ninclude letters, numbers, and underscores.\n\n```text\n^[a-zA-Z_][a-zA-Z0-9_]*$\n```\n"
  },
  {
    "path": "confmap/provider/envprovider/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage envprovider\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "confmap/provider/envprovider/go.mod",
    "content": "module go.opentelemetry.io/collector/confmap/provider/envprovider\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/zap v1.27.1\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/confmap => ../../\n\nreplace go.opentelemetry.io/collector/featuregate => ../../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../../internal/testutil\n"
  },
  {
    "path": "confmap/provider/envprovider/go.sum",
    "content": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "confmap/provider/envprovider/metadata.yaml",
    "content": "type: env\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: provider\n  stability:\n    stable: [provider]\n  distributions: [core, contrib, k8s, otlp]\n"
  },
  {
    "path": "confmap/provider/envprovider/provider.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\npackage envprovider // import \"go.opentelemetry.io/collector/confmap/provider/envprovider\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/internal/envvar\"\n)\n\nconst (\n\tschemeName = \"env\"\n)\n\ntype provider struct {\n\tlogger *zap.Logger\n}\n\n// NewFactory returns a factory for a confmap.Provider that reads the configuration from the given environment variable.\n//\n// This Provider supports \"env\" scheme, and can be called with a selector:\n// `env:NAME_OF_ENVIRONMENT_VARIABLE`\n//\n// A default value for unset variable can be provided after :- suffix, for example:\n// `env:NAME_OF_ENVIRONMENT_VARIABLE:-default_value`\n//\n// See also: https://opentelemetry.io/docs/specs/otel/configuration/data-model/#environment-variable-substitution\nfunc NewFactory() confmap.ProviderFactory {\n\treturn confmap.NewProviderFactory(newProvider)\n}\n\nfunc newProvider(ps confmap.ProviderSettings) confmap.Provider {\n\treturn &provider{\n\t\tlogger: ps.Logger,\n\t}\n}\n\nfunc (emp *provider) Retrieve(_ context.Context, uri string, _ confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\tif !strings.HasPrefix(uri, schemeName+\":\") {\n\t\treturn nil, fmt.Errorf(\"%q uri is not supported by %q provider\", uri, schemeName)\n\t}\n\tenvVarName, defaultValuePtr := parseEnvVarURI(uri[len(schemeName)+1:])\n\tif !envvar.ValidationRegexp.MatchString(envVarName) {\n\t\treturn nil, fmt.Errorf(\"environment variable %q has invalid name: must match regex %s\", envVarName, envvar.ValidationPattern)\n\t}\n\n\tval, exists := os.LookupEnv(envVarName)\n\tif !exists {\n\t\tif defaultValuePtr != nil {\n\t\t\tval = *defaultValuePtr\n\t\t} else {\n\t\t\temp.logger.Warn(\"Configuration references unset environment variable\", zap.String(\"name\", envVarName))\n\t\t}\n\t} else if val == \"\" {\n\t\temp.logger.Info(\"Configuration references empty environment variable\", zap.String(\"name\", envVarName))\n\t}\n\n\treturn confmap.NewRetrievedFromYAML([]byte(val))\n}\n\nfunc (*provider) Scheme() string {\n\treturn schemeName\n}\n\nfunc (*provider) Shutdown(context.Context) error {\n\treturn nil\n}\n\n// returns (var name, default value)\nfunc parseEnvVarURI(uri string) (string, *string) {\n\tconst defaultSuffix = \":-\"\n\tname, defaultValue, hasDefault := strings.Cut(uri, defaultSuffix)\n\tif hasDefault {\n\t\treturn name, &defaultValue\n\t}\n\treturn uri, nil\n}\n"
  },
  {
    "path": "confmap/provider/envprovider/provider_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage envprovider\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/confmap/internal/envvar\"\n)\n\nconst envSchemePrefix = schemeName + \":\"\n\nconst validYAML = `\nprocessors:\n  testprocessor:\nexporters:\n  otlp_grpc:\n    endpoint: \"localhost:4317\"\n`\n\nfunc TestValidateProviderScheme(t *testing.T) {\n\tassert.NoError(t, confmaptest.ValidateProviderScheme(createProvider()))\n}\n\nfunc TestEmptyName(t *testing.T) {\n\tenv := createProvider()\n\t_, err := env.Retrieve(context.Background(), \"\", nil)\n\trequire.Error(t, err)\n\tassert.NoError(t, env.Shutdown(context.Background()))\n}\n\nfunc TestUnsupportedScheme(t *testing.T) {\n\tenv := createProvider()\n\t_, err := env.Retrieve(context.Background(), \"https://\", nil)\n\trequire.Error(t, err)\n\tassert.NoError(t, env.Shutdown(context.Background()))\n}\n\nfunc TestInvalidYAML(t *testing.T) {\n\tconst envName = \"invalid_yaml\"\n\tt.Setenv(envName, \"[invalid,\")\n\tenv := createProvider()\n\tret, err := env.Retrieve(context.Background(), envSchemePrefix+envName, nil)\n\trequire.NoError(t, err)\n\traw, err := ret.AsRaw()\n\trequire.NoError(t, err)\n\tassert.IsType(t, \"\", raw)\n\tassert.NoError(t, env.Shutdown(context.Background()))\n}\n\nfunc TestEnv(t *testing.T) {\n\tconst envName = \"default_config\"\n\tt.Setenv(envName, validYAML)\n\n\tenv := createProvider()\n\tret, err := env.Retrieve(context.Background(), envSchemePrefix+envName, nil)\n\trequire.NoError(t, err)\n\tretMap, err := ret.AsConf()\n\trequire.NoError(t, err)\n\texpectedMap := confmap.NewFromStringMap(map[string]any{\n\t\t\"processors::testprocessor\":      nil,\n\t\t\"exporters::otlp_grpc::endpoint\": \"localhost:4317\",\n\t})\n\tassert.Equal(t, expectedMap.ToStringMap(), retMap.ToStringMap())\n\n\tassert.NoError(t, env.Shutdown(context.Background()))\n}\n\nfunc TestEnvWithLogger(t *testing.T) {\n\tconst envName = \"default_config\"\n\tt.Setenv(envName, validYAML)\n\tcore, ol := observer.New(zap.WarnLevel)\n\tlogger := zap.New(core)\n\n\tenv := NewFactory().Create(confmap.ProviderSettings{Logger: logger})\n\tret, err := env.Retrieve(context.Background(), envSchemePrefix+envName, nil)\n\trequire.NoError(t, err)\n\tretMap, err := ret.AsConf()\n\trequire.NoError(t, err)\n\texpectedMap := confmap.NewFromStringMap(map[string]any{\n\t\t\"processors::testprocessor\":      nil,\n\t\t\"exporters::otlp_grpc::endpoint\": \"localhost:4317\",\n\t})\n\tassert.Equal(t, expectedMap.ToStringMap(), retMap.ToStringMap())\n\n\trequire.NoError(t, env.Shutdown(context.Background()))\n\tassert.Equal(t, 0, ol.Len())\n}\n\nfunc TestUnsetEnvWithLoggerWarn(t *testing.T) {\n\tconst envName = \"default_config\"\n\tcore, ol := observer.New(zap.WarnLevel)\n\tlogger := zap.New(core)\n\n\tenv := NewFactory().Create(confmap.ProviderSettings{Logger: logger})\n\tret, err := env.Retrieve(context.Background(), envSchemePrefix+envName, nil)\n\trequire.NoError(t, err)\n\tretMap, err := ret.AsConf()\n\trequire.NoError(t, err)\n\texpectedMap := confmap.NewFromStringMap(map[string]any{})\n\tassert.Equal(t, expectedMap.ToStringMap(), retMap.ToStringMap())\n\n\trequire.NoError(t, env.Shutdown(context.Background()))\n\n\tassert.Equal(t, 1, ol.Len())\n\tlogLine := ol.All()[0]\n\tassert.Equal(t, \"Configuration references unset environment variable\", logLine.Message)\n\tassert.Equal(t, zap.WarnLevel, logLine.Level)\n\tassert.Equal(t, envName, logLine.Context[0].String)\n}\n\nfunc TestEnvVarNameRestriction(t *testing.T) {\n\tconst envName = \"default%config\"\n\tt.Setenv(envName, validYAML)\n\n\tenv := createProvider()\n\tret, err := env.Retrieve(context.Background(), envSchemePrefix+envName, nil)\n\tassert.Equal(t, err, fmt.Errorf(\"environment variable \\\"default%%config\\\" has invalid name: must match regex %s\", envvar.ValidationRegexp))\n\trequire.NoError(t, env.Shutdown(context.Background()))\n\tassert.Nil(t, ret)\n}\n\nfunc TestEmptyEnvWithLoggerWarn(t *testing.T) {\n\tconst envName = \"default_config\"\n\tt.Setenv(envName, \"\")\n\n\tcore, ol := observer.New(zap.InfoLevel)\n\tlogger := zap.New(core)\n\n\tenv := NewFactory().Create(confmap.ProviderSettings{Logger: logger})\n\tret, err := env.Retrieve(context.Background(), envSchemePrefix+envName, nil)\n\trequire.NoError(t, err)\n\tretMap, err := ret.AsConf()\n\trequire.NoError(t, err)\n\texpectedMap := confmap.NewFromStringMap(map[string]any{})\n\tassert.Equal(t, expectedMap.ToStringMap(), retMap.ToStringMap())\n\n\trequire.NoError(t, env.Shutdown(context.Background()))\n\n\tassert.Equal(t, 1, ol.Len())\n\tlogLine := ol.All()[0]\n\tassert.Equal(t, \"Configuration references empty environment variable\", logLine.Message)\n\tassert.Equal(t, zap.InfoLevel, logLine.Level)\n\tassert.Equal(t, envName, logLine.Context[0].String)\n}\n\nfunc TestEnvWithDefaultValue(t *testing.T) {\n\tenv := createProvider()\n\ttests := []struct {\n\t\tname        string\n\t\tunset       bool\n\t\tvalue       string\n\t\turi         string\n\t\texpectedVal string\n\t\texpectedErr string\n\t}{\n\t\t{name: \"unset\", unset: true, uri: \"env:MY_VAR:-default % value\", expectedVal: \"default % value\"},\n\t\t{name: \"unset2\", unset: true, uri: \"env:MY_VAR:-\", expectedVal: \"\"}, // empty default still applies\n\t\t{name: \"empty\", value: \"\", uri: \"env:MY_VAR:-foo\", expectedVal: \"\"},\n\t\t{name: \"not empty\", value: \"value\", uri: \"env:MY_VAR:-\", expectedVal: \"value\"},\n\t\t{name: \"syntax1\", unset: true, uri: \"env:-MY_VAR\", expectedErr: \"invalid name\"},\n\t\t{name: \"syntax2\", unset: true, uri: \"env:MY_VAR:-test:-test\", expectedVal: \"test:-test\"},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif !tt.unset {\n\t\t\t\tt.Setenv(\"MY_VAR\", tt.value)\n\t\t\t}\n\t\t\tret, err := env.Retrieve(context.Background(), tt.uri, nil)\n\t\t\tif tt.expectedErr != \"\" {\n\t\t\t\trequire.ErrorContains(t, err, tt.expectedErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\tstr, err := ret.AsString()\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tt.expectedVal, str)\n\t\t})\n\t}\n\tassert.NoError(t, env.Shutdown(context.Background()))\n}\n\nfunc createProvider() confmap.Provider {\n\treturn NewFactory().Create(confmaptest.NewNopProviderSettings())\n}\n"
  },
  {
    "path": "confmap/provider/fileprovider/Makefile",
    "content": "include ../../../Makefile.Common\n"
  },
  {
    "path": "confmap/provider/fileprovider/README.md",
    "content": "# File Provider\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [stable]  |\n| Distributions | [core], [contrib], [k8s], [otlp] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Aprovider%2Ffileprovider%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Aprovider%2Ffileprovider) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Aprovider%2Ffileprovider%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Aprovider%2Ffileprovider) |\n\n[stable]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stable\n[core]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n[k8s]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\n[otlp]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-otlp\n<!-- end autogenerated section -->\n\n## Overview\n\nThe File Provider takes paths to files and reads their contents as YAML to provide configuration to the Collector.\n\n## Usage\n\nThe scheme for this provider is `file`. Usage looks like the following:\n\n```text\nfile:/path/to/file.yaml\n```\n"
  },
  {
    "path": "confmap/provider/fileprovider/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage fileprovider\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "confmap/provider/fileprovider/go.mod",
    "content": "module go.opentelemetry.io/collector/confmap/provider/fileprovider\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/confmap => ../../\n\nreplace go.opentelemetry.io/collector/featuregate => ../../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../../internal/testutil\n"
  },
  {
    "path": "confmap/provider/fileprovider/go.sum",
    "content": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "confmap/provider/fileprovider/metadata.yaml",
    "content": "type: file\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: provider\n  stability:\n    stable: [provider]\n  distributions: [core, contrib, k8s, otlp]\n"
  },
  {
    "path": "confmap/provider/fileprovider/provider.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\npackage fileprovider // import \"go.opentelemetry.io/collector/confmap/provider/fileprovider\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\nconst schemeName = \"file\"\n\ntype provider struct{}\n\n// NewFactory returns a factory for a confmap.Provider that reads the configuration from a file.\n//\n// This Provider supports \"file\" scheme, and can be called with a \"uri\" that follows:\n//\n//\tfile-uri\t\t= \"file:\" local-path\n//\tlocal-path\t\t= [ drive-letter ] file-path\n//\tdrive-letter\t= ALPHA \":\"\n//\n// The \"file-path\" can be relative or absolute, and it can be any OS supported format.\n//\n// Examples:\n// `file:path/to/file` - relative path (unix, windows)\n// `file:/path/to/file` - absolute path (unix, windows)\n// `file:c:/path/to/file` - absolute path including drive-letter (windows)\n// `file:c:\\path\\to\\file` - absolute path including drive-letter (windows)\nfunc NewFactory() confmap.ProviderFactory {\n\treturn confmap.NewProviderFactory(newProvider)\n}\n\nfunc newProvider(confmap.ProviderSettings) confmap.Provider {\n\treturn &provider{}\n}\n\nfunc (fmp *provider) Retrieve(_ context.Context, uri string, _ confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\tif !strings.HasPrefix(uri, schemeName+\":\") {\n\t\treturn nil, fmt.Errorf(\"%q uri is not supported by %q provider\", uri, schemeName)\n\t}\n\n\t// Clean the path before using it.\n\tcontent, err := os.ReadFile(filepath.Clean(uri[len(schemeName)+1:]))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to read the file %v: %w\", uri, err)\n\t}\n\n\treturn confmap.NewRetrievedFromYAML(content)\n}\n\nfunc (*provider) Scheme() string {\n\treturn schemeName\n}\n\nfunc (*provider) Shutdown(context.Context) error {\n\treturn nil\n}\n"
  },
  {
    "path": "confmap/provider/fileprovider/provider_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage fileprovider\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n)\n\nconst fileSchemePrefix = schemeName + \":\"\n\nfunc TestValidateProviderScheme(t *testing.T) {\n\tassert.NoError(t, confmaptest.ValidateProviderScheme(createProvider()))\n}\n\nfunc TestEmptyName(t *testing.T) {\n\tfp := createProvider()\n\t_, err := fp.Retrieve(context.Background(), \"\", nil)\n\trequire.Error(t, err)\n\trequire.NoError(t, fp.Shutdown(context.Background()))\n}\n\nfunc TestUnsupportedScheme(t *testing.T) {\n\tfp := createProvider()\n\t_, err := fp.Retrieve(context.Background(), \"https://\", nil)\n\trequire.Error(t, err)\n\tassert.NoError(t, fp.Shutdown(context.Background()))\n}\n\nfunc TestNonExistent(t *testing.T) {\n\tfp := createProvider()\n\t_, err := fp.Retrieve(context.Background(), fileSchemePrefix+filepath.Join(\"testdata\", \"non-existent.yaml\"), nil)\n\trequire.Error(t, err)\n\t_, err = fp.Retrieve(context.Background(), fileSchemePrefix+absolutePath(t, filepath.Join(\"testdata\", \"non-existent.yaml\")), nil)\n\trequire.Error(t, err)\n\trequire.NoError(t, fp.Shutdown(context.Background()))\n}\n\nfunc TestInvalidYAML(t *testing.T) {\n\tfp := createProvider()\n\tret, err := fp.Retrieve(context.Background(), fileSchemePrefix+filepath.Join(\"testdata\", \"invalid-yaml.yaml\"), nil)\n\trequire.NoError(t, err)\n\traw, err := ret.AsRaw()\n\trequire.NoError(t, err)\n\tassert.IsType(t, \"\", raw)\n\n\tret, err = fp.Retrieve(context.Background(), fileSchemePrefix+absolutePath(t, filepath.Join(\"testdata\", \"invalid-yaml.yaml\")), nil)\n\trequire.NoError(t, err)\n\traw, err = ret.AsRaw()\n\trequire.NoError(t, err)\n\tassert.IsType(t, \"\", raw)\n\n\trequire.NoError(t, fp.Shutdown(context.Background()))\n}\n\nfunc TestRelativePath(t *testing.T) {\n\tfp := createProvider()\n\tret, err := fp.Retrieve(context.Background(), fileSchemePrefix+filepath.Join(\"testdata\", \"default-config.yaml\"), nil)\n\trequire.NoError(t, err)\n\tretMap, err := ret.AsConf()\n\trequire.NoError(t, err)\n\texpectedMap := confmap.NewFromStringMap(map[string]any{\n\t\t\"processors::testprocessor\":      nil,\n\t\t\"exporters::otlp_grpc::endpoint\": \"localhost:4317\",\n\t})\n\tassert.Equal(t, expectedMap, retMap)\n\tassert.NoError(t, fp.Shutdown(context.Background()))\n}\n\nfunc TestAbsolutePath(t *testing.T) {\n\tfp := createProvider()\n\tret, err := fp.Retrieve(context.Background(), fileSchemePrefix+absolutePath(t, filepath.Join(\"testdata\", \"default-config.yaml\")), nil)\n\trequire.NoError(t, err)\n\tretMap, err := ret.AsConf()\n\trequire.NoError(t, err)\n\texpectedMap := confmap.NewFromStringMap(map[string]any{\n\t\t\"processors::testprocessor\":      nil,\n\t\t\"exporters::otlp_grpc::endpoint\": \"localhost:4317\",\n\t})\n\tassert.Equal(t, expectedMap, retMap)\n\tassert.NoError(t, fp.Shutdown(context.Background()))\n}\n\nfunc absolutePath(t *testing.T, relativePath string) string {\n\tdir, err := os.Getwd()\n\trequire.NoError(t, err)\n\treturn filepath.Join(dir, relativePath)\n}\n\nfunc createProvider() confmap.Provider {\n\treturn NewFactory().Create(confmaptest.NewNopProviderSettings())\n}\n"
  },
  {
    "path": "confmap/provider/fileprovider/testdata/default-config.yaml",
    "content": "processors:\n  testprocessor:\nexporters:\n  otlp_grpc:\n    endpoint: \"localhost:4317\"\n"
  },
  {
    "path": "confmap/provider/fileprovider/testdata/invalid-yaml.yaml",
    "content": "[invalid,"
  },
  {
    "path": "confmap/provider/httpprovider/Makefile",
    "content": "include ../../../Makefile.Common\n"
  },
  {
    "path": "confmap/provider/httpprovider/README.md",
    "content": "# HTTP Provider\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [stable]  |\n| Distributions | [core], [contrib], [k8s] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Aprovider%2Fhttpprovider%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Aprovider%2Fhttpprovider) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Aprovider%2Fhttpprovider%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Aprovider%2Fhttpprovider) |\n\n[stable]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stable\n[core]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n[k8s]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\n<!-- end autogenerated section -->\n\n## Overview\n\nThe HTTP Provider takes an HTTP URI to a file and reads its contents as YAML to provide configuration to the Collector.\n\nFor HTTPS endpoints, please see the [HTTPS provider](../httpsprovider/README.md).\n\n## Usage\n\nThe scheme for this provider is `http`. Usage looks like the following passed to the Collector's command line invocation:\n\n```text\n--config=http://example.com/config.yaml\n```\n"
  },
  {
    "path": "confmap/provider/httpprovider/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage httpprovider\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "confmap/provider/httpprovider/go.mod",
    "content": "module go.opentelemetry.io/collector/confmap/provider/httpprovider\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/confmap => ../../\n\nreplace go.opentelemetry.io/collector/featuregate => ../../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../../internal/testutil\n"
  },
  {
    "path": "confmap/provider/httpprovider/go.sum",
    "content": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "confmap/provider/httpprovider/metadata.yaml",
    "content": "type: http\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: provider\n  stability:\n    stable: [provider]\n  distributions: [core, contrib, k8s]\n"
  },
  {
    "path": "confmap/provider/httpprovider/provider.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\npackage httpprovider // import \"go.opentelemetry.io/collector/confmap/provider/httpprovider\"\n\nimport (\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/provider/internal/configurablehttpprovider\"\n)\n\n// NewFactory returns a factory for a confmap.Provider that reads the configuration from a http server.\n//\n// This Provider supports \"http\" scheme.\n//\n// One example for HTTP URI is: http://localhost:3333/getConfig\nfunc NewFactory() confmap.ProviderFactory {\n\treturn confmap.NewProviderFactory(newProvider)\n}\n\nfunc newProvider(set confmap.ProviderSettings) confmap.Provider {\n\treturn configurablehttpprovider.New(configurablehttpprovider.HTTPScheme, set)\n}\n"
  },
  {
    "path": "confmap/provider/httpprovider/provider_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage httpprovider\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n)\n\nfunc TestSupportedScheme(t *testing.T) {\n\tfp := NewFactory().Create(confmaptest.NewNopProviderSettings())\n\tassert.Equal(t, \"http\", fp.Scheme())\n\trequire.NoError(t, fp.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "confmap/provider/httpsprovider/Makefile",
    "content": "include ../../../Makefile.Common\n"
  },
  {
    "path": "confmap/provider/httpsprovider/README.md",
    "content": "# HTTPS Provider\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [stable]  |\n| Distributions | [core], [contrib], [k8s] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Aprovider%2Fhttpsprovider%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Aprovider%2Fhttpsprovider) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Aprovider%2Fhttpsprovider%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Aprovider%2Fhttpsprovider) |\n\n[stable]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stable\n[core]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n[k8s]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\n<!-- end autogenerated section -->\n\n## Overview\n\nThe HTTPS Provider takes an HTTPS URI to a file and reads its contents as YAML\nto provide configuration to the Collector. The validity of the certificate of\nthe HTTPS endpoint is verified when making the connection.\n\n## Usage\n\nThe scheme for this provider is `https`. Usage looks like the following passed\nto the Collector's command line invocation:\n\n```text\n--config=https://example.com/config.yaml\n```\n\n### Notes\n\nThe provider currently only supports communicating with servers whose\ncertificate can be verified using the root CA certificates installed in the\nsystem. The process of adding more root CA certificates to the system is\nOperating System-dependent. For Linux, please refer to the `update-ca-trust`\ncommand.\n"
  },
  {
    "path": "confmap/provider/httpsprovider/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage httpsprovider\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "confmap/provider/httpsprovider/go.mod",
    "content": "module go.opentelemetry.io/collector/confmap/provider/httpsprovider\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/confmap => ../../\n\nreplace go.opentelemetry.io/collector/featuregate => ../../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../../internal/testutil\n"
  },
  {
    "path": "confmap/provider/httpsprovider/go.sum",
    "content": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "confmap/provider/httpsprovider/metadata.yaml",
    "content": "type: https\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: provider\n  stability:\n    stable: [provider]\n  distributions: [core, contrib, k8s]\n"
  },
  {
    "path": "confmap/provider/httpsprovider/provider.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\npackage httpsprovider // import \"go.opentelemetry.io/collector/confmap/provider/httpsprovider\"\n\nimport (\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/provider/internal/configurablehttpprovider\"\n)\n\n// NewFactory returns a factory for a confmap.Provider that reads the configuration from a https server.\n//\n// This Provider supports \"https\" scheme. One example of an HTTPS URI is: https://localhost:3333/getConfig\n//\n// To add extra CA certificates you need to install certificates in the system pool. This procedure is operating system\n// dependent. E.g.: on Linux please refer to the `update-ca-trust` command.\nfunc NewFactory() confmap.ProviderFactory {\n\treturn confmap.NewProviderFactory(newProvider)\n}\n\nfunc newProvider(set confmap.ProviderSettings) confmap.Provider {\n\treturn configurablehttpprovider.New(configurablehttpprovider.HTTPSScheme, set)\n}\n"
  },
  {
    "path": "confmap/provider/httpsprovider/provider_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage httpsprovider\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n)\n\nfunc TestSupportedScheme(t *testing.T) {\n\tfp := NewFactory().Create(confmaptest.NewNopProviderSettings())\n\tassert.Equal(t, \"https\", fp.Scheme())\n}\n"
  },
  {
    "path": "confmap/provider/internal/configurablehttpprovider/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configurablehttpprovider\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "confmap/provider/internal/configurablehttpprovider/provider.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configurablehttpprovider // import \"go.opentelemetry.io/collector/confmap/provider/internal/configurablehttpprovider\"\n\nimport (\n\t\"context\"\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\ntype SchemeType string\n\nconst (\n\tHTTPScheme  SchemeType = \"http\"\n\tHTTPSScheme SchemeType = \"https\"\n)\n\ntype provider struct {\n\tscheme             SchemeType\n\tcaCertPath         string // Used for tests\n\tinsecureSkipVerify bool   // Used for tests\n}\n\n// New returns a new provider that reads the configuration from http server using the configured transport mechanism\n// depending on the selected scheme.\n// There are two types of transport supported: PlainText (HTTPScheme) and TLS (HTTPSScheme).\n//\n// One example for http-uri: http://localhost:3333/getConfig\n// One example for https-uri: https://localhost:3333/getConfig\n// This is used by the http and https external implementations.\nfunc New(scheme SchemeType, _ confmap.ProviderSettings) confmap.Provider {\n\treturn &provider{scheme: scheme}\n}\n\n// Create the client based on the type of scheme that was selected.\nfunc (fmp *provider) createClient() (*http.Client, error) {\n\tswitch fmp.scheme {\n\tcase HTTPScheme:\n\t\treturn &http.Client{}, nil\n\tcase HTTPSScheme:\n\t\tpool, err := x509.SystemCertPool()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"unable to create a cert pool: %w\", err)\n\t\t}\n\n\t\tif fmp.caCertPath != \"\" {\n\t\t\tcert, err := os.ReadFile(filepath.Clean(fmp.caCertPath))\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to read CA from %q URI: %w\", fmp.caCertPath, err)\n\t\t\t}\n\n\t\t\tif ok := pool.AppendCertsFromPEM(cert); !ok {\n\t\t\t\treturn nil, fmt.Errorf(\"unable to add CA from uri: %s into the cert pool\", fmp.caCertPath)\n\t\t\t}\n\t\t}\n\n\t\treturn &http.Client{\n\t\t\tTransport: &http.Transport{\n\t\t\t\tTLSClientConfig: &tls.Config{\n\t\t\t\t\tInsecureSkipVerify: fmp.insecureSkipVerify,\n\t\t\t\t\tRootCAs:            pool,\n\t\t\t\t},\n\t\t\t},\n\t\t}, nil\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"invalid scheme type: %s\", fmp.scheme)\n\t}\n}\n\nfunc (fmp *provider) Retrieve(_ context.Context, uri string, _ confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\tif !strings.HasPrefix(uri, string(fmp.scheme)+\":\") {\n\t\treturn nil, fmt.Errorf(\"%q uri is not supported by %q provider\", uri, string(fmp.scheme))\n\t}\n\n\tif _, err := url.ParseRequestURI(uri); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid uri %q: %w\", uri, err)\n\t}\n\n\tclient, err := fmp.createClient()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to configure http transport layer: %w\", err)\n\t}\n\n\t// send a HTTP GET request\n\tresp, err := client.Get(uri)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to download the file via HTTP GET for uri %q: %w \", uri, err)\n\t}\n\tdefer resp.Body.Close()\n\n\t// check the HTTP status code\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil, fmt.Errorf(\"failed to load resource from uri %q. status code: %d\", uri, resp.StatusCode)\n\t}\n\n\t// read the response body\n\tbody, err := io.ReadAll(resp.Body)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"fail to read the response body from uri %q: %w\", uri, err)\n\t}\n\n\treturn confmap.NewRetrievedFromYAML(body)\n}\n\nfunc (fmp *provider) Scheme() string {\n\treturn string(fmp.scheme)\n}\n\nfunc (*provider) Shutdown(context.Context) error {\n\treturn nil\n}\n"
  },
  {
    "path": "confmap/provider/internal/configurablehttpprovider/provider_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configurablehttpprovider\n\nimport (\n\t\"context\"\n\t\"crypto/rand\"\n\t\"crypto/rsa\"\n\t\"crypto/tls\"\n\t\"crypto/x509\"\n\t\"crypto/x509/pkix\"\n\t\"encoding/pem\"\n\t\"fmt\"\n\t\"math/big\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"os\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc newConfigurableHTTPProvider(scheme SchemeType, set confmap.ProviderSettings) *provider {\n\treturn New(scheme, set).(*provider)\n}\n\nfunc answerGet(w http.ResponseWriter, _ *http.Request) {\n\tf, err := os.ReadFile(\"./testdata/otel-config.yaml\")\n\tif err != nil {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t\t_, innerErr := w.Write([]byte(\"Cannot find the config file\"))\n\t\tif innerErr != nil {\n\t\t\tfmt.Println(\"Write failed: \", innerErr)\n\t\t}\n\t\treturn\n\t}\n\tw.WriteHeader(http.StatusOK)\n\t_, err = w.Write(f)\n\tif err != nil {\n\t\tfmt.Println(\"Write failed: \", err)\n\t}\n}\n\n// Generate a self signed certificate specific for the tests. Based on\n// https://go.dev/src/crypto/tls/generate_cert.go\nfunc generateCertificate(t *testing.T, hostname string) (cert, key string, err error) {\n\ttestutil.SkipIfFIPSOnly(t, \"x509.CreateCertificate uses SHA-1\")\n\tpriv, err := rsa.GenerateKey(rand.Reader, 2048)\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"Failed to generate private key: %w\", err)\n\t}\n\n\tkeyUsage := x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageCertSign\n\tnotBefore := time.Now()\n\tnotAfter := notBefore.Add(time.Hour * 12)\n\tserialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)\n\tserialNumber, err := rand.Int(rand.Reader, serialNumberLimit)\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"Failed to generate serial number: %w\", err)\n\t}\n\n\ttemplate := x509.Certificate{\n\t\tSerialNumber: serialNumber,\n\t\tSubject: pkix.Name{\n\t\t\tOrganization: []string{\"Httpprovider Co\"},\n\t\t},\n\t\tNotBefore:             notBefore,\n\t\tNotAfter:              notAfter,\n\t\tKeyUsage:              keyUsage,\n\t\tExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},\n\t\tBasicConstraintsValid: true,\n\t\tIsCA:                  true,\n\t\tDNSNames:              []string{hostname},\n\t}\n\tderBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"Failed to create certificate: %w\", err)\n\t}\n\n\ttempDir := t.TempDir()\n\tcertOut, err := os.CreateTemp(tempDir, \"cert*.pem\")\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"Failed to open cert.pem for writing: %w\", err)\n\t}\n\n\tdefer certOut.Close()\n\n\tif err = pem.Encode(certOut, &pem.Block{Type: \"CERTIFICATE\", Bytes: derBytes}); err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"Failed to write data to cert.pem: %w\", err)\n\t}\n\n\tkeyOut, err := os.CreateTemp(tempDir, \"key*.pem\")\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"Failed to open key.pem for writing: %w\", err)\n\t}\n\tdefer keyOut.Close()\n\n\tprivBytes, err := x509.MarshalPKCS8PrivateKey(priv)\n\tif err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"Unable to marshal private key: %w\", err)\n\t}\n\n\tif err := pem.Encode(keyOut, &pem.Block{Type: \"PRIVATE KEY\", Bytes: privBytes}); err != nil {\n\t\treturn \"\", \"\", fmt.Errorf(\"Failed to write data to key.pem: %w\", err)\n\t}\n\n\treturn certOut.Name(), keyOut.Name(), nil\n}\n\nfunc TestFunctionalityDownloadFileHTTP(t *testing.T) {\n\tfp := newConfigurableHTTPProvider(HTTPScheme, confmaptest.NewNopProviderSettings())\n\tts := httptest.NewServer(http.HandlerFunc(answerGet))\n\tdefer ts.Close()\n\t_, err := fp.Retrieve(context.Background(), ts.URL, nil)\n\tassert.NoError(t, err)\n\tassert.NoError(t, fp.Shutdown(context.Background()))\n}\n\nfunc TestFunctionalityDownloadFileHTTPS(t *testing.T) {\n\tcertPath, keyPath, err := generateCertificate(t, \"localhost\")\n\trequire.NoError(t, err)\n\n\tinvalidCert, err := os.CreateTemp(t.TempDir(), \"cert*.crt\")\n\tdefer func() { require.NoError(t, invalidCert.Close()) }()\n\trequire.NoError(t, err)\n\t_, err = invalidCert.Write([]byte{0, 1, 2})\n\trequire.NoError(t, err)\n\n\tcert, err := tls.LoadX509KeyPair(certPath, keyPath)\n\trequire.NoError(t, err)\n\tts := httptest.NewUnstartedServer(http.HandlerFunc(answerGet))\n\tts.TLS = &tls.Config{Certificates: []tls.Certificate{cert}}\n\tts.StartTLS()\n\n\tdefer ts.Close()\n\n\ttests := []struct {\n\t\tname                   string\n\t\tcertPath               string\n\t\thostName               string\n\t\tuseCertificate         bool\n\t\tskipHostnameValidation bool\n\t\tshouldError            bool\n\t}{\n\t\t{\n\t\t\tname:                   \"Test valid certificate and name\",\n\t\t\tcertPath:               certPath,\n\t\t\thostName:               \"localhost\",\n\t\t\tuseCertificate:         true,\n\t\t\tskipHostnameValidation: false,\n\t\t\tshouldError:            false,\n\t\t},\n\t\t{\n\t\t\tname:                   \"Test valid certificate with invalid name\",\n\t\t\tcertPath:               certPath,\n\t\t\thostName:               \"127.0.0.1\",\n\t\t\tuseCertificate:         true,\n\t\t\tskipHostnameValidation: false,\n\t\t\tshouldError:            true,\n\t\t},\n\t\t{\n\t\t\tname:                   \"Test valid certificate with invalid name, skip validation\",\n\t\t\tcertPath:               certPath,\n\t\t\thostName:               \"127.0.0.1\",\n\t\t\tuseCertificate:         true,\n\t\t\tskipHostnameValidation: true,\n\t\t\tshouldError:            false,\n\t\t},\n\t\t{\n\t\t\tname:                   \"Test no certificate should fail\",\n\t\t\tcertPath:               certPath,\n\t\t\thostName:               \"localhost\",\n\t\t\tuseCertificate:         false,\n\t\t\tskipHostnameValidation: false,\n\t\t\tshouldError:            true,\n\t\t},\n\t\t{\n\t\t\tname:                   \"Test invalid cert\",\n\t\t\tcertPath:               invalidCert.Name(),\n\t\t\thostName:               \"localhost\",\n\t\t\tuseCertificate:         true,\n\t\t\tskipHostnameValidation: false,\n\t\t\tshouldError:            true,\n\t\t},\n\t\t{\n\t\t\tname:                   \"Test no cert\",\n\t\t\tcertPath:               \"no_certificate\",\n\t\t\thostName:               \"localhost\",\n\t\t\tuseCertificate:         true,\n\t\t\tskipHostnameValidation: false,\n\t\t\tshouldError:            true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tfp := newConfigurableHTTPProvider(HTTPSScheme, confmaptest.NewNopProviderSettings())\n\t\t\t// Parse url of the test server to get the port number.\n\t\t\ttsURL, err := url.Parse(ts.URL)\n\t\t\trequire.NoError(t, err)\n\t\t\tif tt.useCertificate {\n\t\t\t\tfp.caCertPath = tt.certPath\n\t\t\t}\n\t\t\tfp.insecureSkipVerify = tt.skipHostnameValidation\n\t\t\t_, err = fp.Retrieve(context.Background(), fmt.Sprintf(\"https://%s:%s\", tt.hostName, tsURL.Port()), nil)\n\t\t\tif tt.shouldError {\n\t\t\t\tassert.Error(t, err)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestUnsupportedScheme(t *testing.T) {\n\tfp := New(HTTPScheme, confmaptest.NewNopProviderSettings())\n\t_, err := fp.Retrieve(context.Background(), \"https://...\", nil)\n\trequire.Error(t, err)\n\trequire.NoError(t, fp.Shutdown(context.Background()))\n\n\tfp = New(HTTPSScheme, confmaptest.NewNopProviderSettings())\n\t_, err = fp.Retrieve(context.Background(), \"http://...\", nil)\n\trequire.Error(t, err)\n\tassert.NoError(t, fp.Shutdown(context.Background()))\n}\n\nfunc TestEmptyURI(t *testing.T) {\n\tfp := New(HTTPScheme, confmaptest.NewNopProviderSettings())\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusBadRequest)\n\t}))\n\tdefer ts.Close()\n\t_, err := fp.Retrieve(context.Background(), ts.URL, nil)\n\trequire.Error(t, err)\n\trequire.NoError(t, fp.Shutdown(context.Background()))\n}\n\nfunc TestRetrieveFromShutdownServer(t *testing.T) {\n\tfp := New(HTTPScheme, confmaptest.NewNopProviderSettings())\n\tts := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))\n\tts.Close()\n\t_, err := fp.Retrieve(context.Background(), ts.URL, nil)\n\trequire.Error(t, err)\n\trequire.NoError(t, fp.Shutdown(context.Background()))\n}\n\nfunc TestNonExistent(t *testing.T) {\n\tfp := New(HTTPScheme, confmaptest.NewNopProviderSettings())\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusNotFound)\n\t}))\n\tdefer ts.Close()\n\t_, err := fp.Retrieve(context.Background(), ts.URL, nil)\n\trequire.Error(t, err)\n\trequire.NoError(t, fp.Shutdown(context.Background()))\n}\n\nfunc TestInvalidYAML(t *testing.T) {\n\tfp := New(HTTPScheme, confmaptest.NewNopProviderSettings())\n\tts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\tw.WriteHeader(http.StatusOK)\n\t\t_, err := w.Write([]byte(\"wrong : [\"))\n\t\tif err != nil {\n\t\t\tfmt.Println(\"Write failed: \", err)\n\t\t}\n\t}))\n\tdefer ts.Close()\n\tret, err := fp.Retrieve(context.Background(), ts.URL, nil)\n\trequire.NoError(t, err)\n\traw, err := ret.AsRaw()\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"wrong : [\", raw)\n\trequire.NoError(t, fp.Shutdown(context.Background()))\n}\n\nfunc TestScheme(t *testing.T) {\n\tfp := New(HTTPScheme, confmaptest.NewNopProviderSettings())\n\tassert.Equal(t, \"http\", fp.Scheme())\n\trequire.NoError(t, fp.Shutdown(context.Background()))\n}\n\nfunc TestValidateProviderScheme(t *testing.T) {\n\tassert.NoError(t, confmaptest.ValidateProviderScheme(New(HTTPScheme, confmaptest.NewNopProviderSettings())))\n}\n\nfunc TestInvalidURI(t *testing.T) {\n\tfp := New(HTTPScheme, confmaptest.NewNopProviderSettings())\n\n\ttests := []struct {\n\t\turi string\n\t\terr string\n\t}{\n\t\t{\n\t\t\turi: \"foo://..\",\n\t\t\terr: \"uri is not supported by \\\"http\\\" provider\",\n\t\t},\n\t\t{\n\t\t\turi: \"http://\",\n\t\t\terr: \"no Host in request URL\",\n\t\t},\n\t\t{\n\t\t\turi: \"http://{}\",\n\t\t\terr: \"invalid character \\\"{\\\" in host name\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.uri, func(t *testing.T) {\n\t\t\t_, err := fp.Retrieve(context.Background(), tt.uri, nil)\n\t\t\tassert.ErrorContains(t, err, tt.err)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "confmap/provider/internal/configurablehttpprovider/testdata/otel-config.yaml",
    "content": "extensions:\n  zpages:\n    endpoint: 0.0.0.0:55679\n\nreceivers:\n  otlp:\n    protocols:\n      grpc:\n      http:\n\nprocessors:\n  memory_limiter:\n    # 75% of maximum memory up to 2G\n    limit_mib: 1536\n    # 25% of limit up to 2G\n    spike_limit_mib: 512\n    check_interval: 5s\n\nexporters:\n  debug:\n    verbosity: detailed\n\nservice:\n  pipelines:\n    traces:\n      receivers: [otlp]\n      processors: [memory_limiter]\n      exporters: [debug]\n    metrics:\n      receivers: [otlp]\n      processors: [memory_limiter]\n      exporters: [debug]\n\n  extensions: [zpages]\n"
  },
  {
    "path": "confmap/provider/internal/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "confmap/provider/yamlprovider/Makefile",
    "content": "include ../../../Makefile.Common\n"
  },
  {
    "path": "confmap/provider/yamlprovider/README.md",
    "content": "# YAML Provider\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [stable]  |\n| Distributions | [core], [contrib], [k8s] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Aprovider%2Fyamlprovider%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Aprovider%2Fyamlprovider) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Aprovider%2Fyamlprovider%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Aprovider%2Fyamlprovider) |\n\n[stable]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stable\n[core]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n[k8s]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\n<!-- end autogenerated section -->\n\n## Overview\n\nThe YAML Provider takes a literal YAML string as Collector configuration.\n\n## Usage\n\nThe scheme for this provider is `yaml`. Usage looks like the following passed to the Collector's command line invocation:\n\n```text\n--config=\"yaml:exporters::otlp_http::sending_queue::batch::flush_timeout: 2s\"\n```\n"
  },
  {
    "path": "confmap/provider/yamlprovider/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage yamlprovider\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "confmap/provider/yamlprovider/go.mod",
    "content": "module go.opentelemetry.io/collector/confmap/provider/yamlprovider\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/confmap => ../../\n\nreplace go.opentelemetry.io/collector/featuregate => ../../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../../internal/testutil\n"
  },
  {
    "path": "confmap/provider/yamlprovider/go.sum",
    "content": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "confmap/provider/yamlprovider/metadata.yaml",
    "content": "type: yaml\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: provider\n  stability:\n    stable: [provider]\n  distributions: [core, contrib, k8s]\n"
  },
  {
    "path": "confmap/provider/yamlprovider/provider.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage yamlprovider // import \"go.opentelemetry.io/collector/confmap/provider/yamlprovider\"\n\n//go:generate mdatagen metadata.yaml\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\nconst schemeName = \"yaml\"\n\ntype provider struct{}\n\n// NewFactory returns a factory for a confmap.Provider that allows to provide yaml bytes.\n//\n// This Provider supports \"yaml\" scheme, and can be called with a \"uri\" that follows:\n//\n//\tbytes-uri = \"yaml:\" yaml-bytes\n//\n// Examples:\n// `yaml:exporters::otlp_http::sending_queue::batch::flush_timeout: 2s`\n// `yaml:exporters::otlp_http/foo::sending_queue::batch::flush_timeout: 2s`\nfunc NewFactory() confmap.ProviderFactory {\n\treturn confmap.NewProviderFactory(newProvider)\n}\n\nfunc newProvider(confmap.ProviderSettings) confmap.Provider {\n\treturn &provider{}\n}\n\nfunc (s *provider) Retrieve(_ context.Context, uri string, _ confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\tif !strings.HasPrefix(uri, schemeName+\":\") {\n\t\treturn nil, fmt.Errorf(\"%q uri is not supported by %q provider\", uri, schemeName)\n\t}\n\n\treturn confmap.NewRetrievedFromYAML([]byte(uri[len(schemeName)+1:]))\n}\n\nfunc (*provider) Scheme() string {\n\treturn schemeName\n}\n\nfunc (s *provider) Shutdown(context.Context) error {\n\treturn nil\n}\n"
  },
  {
    "path": "confmap/provider/yamlprovider/provider_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage yamlprovider\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n)\n\nfunc TestValidateProviderScheme(t *testing.T) {\n\tassert.NoError(t, confmaptest.ValidateProviderScheme(createProvider()))\n}\n\nfunc TestEmpty(t *testing.T) {\n\tsp := createProvider()\n\t_, err := sp.Retrieve(context.Background(), \"\", nil)\n\trequire.Error(t, err)\n\tassert.NoError(t, sp.Shutdown(context.Background()))\n}\n\nfunc TestInvalidYAML(t *testing.T) {\n\tsp := createProvider()\n\tret, err := sp.Retrieve(context.Background(), \"yaml:[invalid,\", nil)\n\trequire.NoError(t, err)\n\traw, err := ret.AsRaw()\n\trequire.NoError(t, err)\n\tassert.IsType(t, \"\", raw)\n\n\tassert.NoError(t, sp.Shutdown(context.Background()))\n}\n\nfunc TestOneValue(t *testing.T) {\n\tsp := createProvider()\n\tret, err := sp.Retrieve(context.Background(), \"yaml:processors::test::timeout: 2s\", nil)\n\trequire.NoError(t, err)\n\tretMap, err := ret.AsConf()\n\trequire.NoError(t, err)\n\tassert.Equal(t, map[string]any{\n\t\t\"processors\": map[string]any{\n\t\t\t\"test\": map[string]any{\n\t\t\t\t\"timeout\": \"2s\",\n\t\t\t},\n\t\t},\n\t}, retMap.ToStringMap())\n\tassert.NoError(t, sp.Shutdown(context.Background()))\n}\n\nfunc TestNamedComponent(t *testing.T) {\n\tsp := createProvider()\n\tret, err := sp.Retrieve(context.Background(), \"yaml:processors::test/foo::timeout: 3s\", nil)\n\trequire.NoError(t, err)\n\tretMap, err := ret.AsConf()\n\trequire.NoError(t, err)\n\tassert.Equal(t, map[string]any{\n\t\t\"processors\": map[string]any{\n\t\t\t\"test/foo\": map[string]any{\n\t\t\t\t\"timeout\": \"3s\",\n\t\t\t},\n\t\t},\n\t}, retMap.ToStringMap())\n\tassert.NoError(t, sp.Shutdown(context.Background()))\n}\n\nfunc TestMapEntry(t *testing.T) {\n\tsp := createProvider()\n\tret, err := sp.Retrieve(context.Background(), \"yaml:processors: {test/foo::timeout: 3s, test::timeout: 2s}\", nil)\n\trequire.NoError(t, err)\n\tretMap, err := ret.AsConf()\n\trequire.NoError(t, err)\n\tassert.Equal(t, map[string]any{\n\t\t\"processors\": map[string]any{\n\t\t\t\"test/foo\": map[string]any{\n\t\t\t\t\"timeout\": \"3s\",\n\t\t\t},\n\t\t\t\"test\": map[string]any{\n\t\t\t\t\"timeout\": \"2s\",\n\t\t\t},\n\t\t},\n\t}, retMap.ToStringMap())\n\tassert.NoError(t, sp.Shutdown(context.Background()))\n}\n\nfunc TestArrayEntry(t *testing.T) {\n\tsp := createProvider()\n\tret, err := sp.Retrieve(context.Background(), \"yaml:service::extensions: [zpages, zpages/foo]\", nil)\n\trequire.NoError(t, err)\n\tretMap, err := ret.AsConf()\n\trequire.NoError(t, err)\n\tassert.Equal(t, map[string]any{\n\t\t\"service\": map[string]any{\n\t\t\t\"extensions\": []any{\n\t\t\t\t\"zpages\",\n\t\t\t\t\"zpages/foo\",\n\t\t\t},\n\t\t},\n\t}, retMap.ToStringMap())\n\tassert.NoError(t, sp.Shutdown(context.Background()))\n}\n\nfunc TestNewLine(t *testing.T) {\n\tsp := createProvider()\n\tret, err := sp.Retrieve(context.Background(), \"yaml:processors::test/foo::timeout: 3s\\nprocessors::test::timeout: 2s\", nil)\n\trequire.NoError(t, err)\n\tretMap, err := ret.AsConf()\n\trequire.NoError(t, err)\n\tassert.Equal(t, map[string]any{\n\t\t\"processors\": map[string]any{\n\t\t\t\"test/foo\": map[string]any{\n\t\t\t\t\"timeout\": \"3s\",\n\t\t\t},\n\t\t\t\"test\": map[string]any{\n\t\t\t\t\"timeout\": \"2s\",\n\t\t\t},\n\t\t},\n\t}, retMap.ToStringMap())\n\tassert.NoError(t, sp.Shutdown(context.Background()))\n}\n\nfunc TestDotSeparator(t *testing.T) {\n\tsp := createProvider()\n\tret, err := sp.Retrieve(context.Background(), \"yaml:processors.test.timeout: 4s\", nil)\n\trequire.NoError(t, err)\n\tretMap, err := ret.AsConf()\n\trequire.NoError(t, err)\n\tassert.Equal(t, map[string]any{\"processors.test.timeout\": \"4s\"}, retMap.ToStringMap())\n\tassert.NoError(t, sp.Shutdown(context.Background()))\n}\n\nfunc createProvider() confmap.Provider {\n\treturn NewFactory().Create(confmaptest.NewNopProviderSettings())\n}\n"
  },
  {
    "path": "confmap/provider.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confmap // import \"go.opentelemetry.io/collector/confmap\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"go.uber.org/zap\"\n\t\"go.yaml.in/yaml/v3\"\n)\n\n// ProviderSettings are the settings to initialize a Provider.\ntype ProviderSettings struct {\n\t// Logger is a zap.Logger that will be passed to Providers.\n\t// Providers should be able to rely on the Logger being non-nil;\n\t// when instantiating a Provider with a ProviderFactory,\n\t// nil Logger references should be replaced with a no-op Logger.\n\tLogger *zap.Logger\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// ProviderFactory defines a factory that can be used to instantiate\n// new instances of a Provider.\ntype ProviderFactory = moduleFactory[Provider, ProviderSettings]\n\n// CreateProviderFunc is a function that creates a Provider instance.\ntype CreateProviderFunc = createConfmapFunc[Provider, ProviderSettings]\n\n// NewProviderFactory can be used to create a ProviderFactory.\nfunc NewProviderFactory(f CreateProviderFunc) ProviderFactory {\n\treturn newConfmapModuleFactory(f)\n}\n\n// Provider is an interface that helps to retrieve a config map and watch for any\n// changes to the config map. Implementations may load the config from a file,\n// a database or any other source.\n//\n// The typical usage is the following:\n//\n//\tr, err := provider.Retrieve(\"file:/path/to/config\")\n//\t// Use r.Map; wait for watcher to be called.\n//\tr.Close()\n//\tr, err = provider.Retrieve(\"file:/path/to/config\")\n//\t// Use r.Map; wait for watcher to be called.\n//\tr.Close()\n//\t// repeat retrieve/wait/close cycle until it is time to shut down the Collector process.\n//\t// ...\n//\tprovider.Shutdown()\ntype Provider interface {\n\t// Retrieve goes to the configuration source and retrieves the selected data which\n\t// contains the value to be injected in the configuration and the corresponding watcher that\n\t// will be used to monitor for updates of the retrieved value.\n\t//\n\t// `uri` must follow the \"<scheme>:<opaque_data>\" format. This format is compatible\n\t// with the URI definition (see https://datatracker.ietf.org/doc/html/rfc3986). The \"<scheme>\"\n\t// must be always included in the `uri`. The \"<scheme>\" supported by any provider:\n\t//   - MUST consist of a sequence of characters beginning with a letter and followed by any\n\t//     combination of letters, digits, plus (\"+\"), period (\".\"), or hyphen (\"-\").\n\t//     See https://datatracker.ietf.org/doc/html/rfc3986#section-3.1.\n\t//   - MUST be at least 2 characters long to avoid conflicting with a driver-letter identifier as specified\n\t//     in https://tools.ietf.org/id/draft-kerwin-file-scheme-07.html#syntax.\n\t//   - For testing, all implementation MUST check that confmaptest.ValidateProviderScheme returns no error.\n\t//\n\t// `watcher` callback is called when the config changes. watcher may be called from\n\t// a different go routine. After watcher is called, Provider.Retrieve should be called\n\t// to get the new config. See description of Retrieved for more details.\n\t// watcher may be nil, which indicates that the caller is not interested in\n\t// knowing about the changes.\n\t//\n\t// If ctx is cancelled should return immediately with an error.\n\t// Should never be called concurrently with itself or with Shutdown.\n\tRetrieve(ctx context.Context, uri string, watcher WatcherFunc) (*Retrieved, error)\n\n\t// Scheme returns the location scheme used by Retrieve.\n\tScheme() string\n\n\t// Shutdown signals that the configuration for which this Provider was used to\n\t// retrieve values is no longer in use and the Provider should close and release\n\t// any resources that it may have created.\n\t//\n\t// This method must be called when the Collector service ends, either in case of\n\t// success or error. Retrieve cannot be called after Shutdown.\n\t//\n\t// Provider MUST shutdown and wait for any goroutine(s) that were created to call `watcher`, if any.\n\t//\n\t// Should never be called concurrently with itself or with Retrieve.\n\t// If ctx is cancelled should return immediately with an error.\n\tShutdown(ctx context.Context) error\n}\n\ntype WatcherFunc func(*ChangeEvent)\n\n// ChangeEvent describes the particular change event that happened with the config.\ntype ChangeEvent struct {\n\t// Error is nil if the config is changed and needs to be re-fetched.\n\t// Any non-nil error indicates that there was a problem with watching the config changes.\n\tError error\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// Retrieved holds the result of a call to the Retrieve method of a Provider object.\ntype Retrieved struct {\n\trawConf   any\n\terrorHint error\n\tcloseFunc CloseFunc\n\n\tstringRepresentation string\n\tisSetString          bool\n}\n\ntype retrievedSettings struct {\n\terrorHint            error\n\tstringRepresentation string\n\tisSetString          bool\n\tcloseFunc            CloseFunc\n}\n\n// RetrievedOption options to customize Retrieved values.\ntype RetrievedOption interface {\n\tapply(*retrievedSettings)\n}\n\ntype retrievedOptionFunc func(*retrievedSettings)\n\nfunc (of retrievedOptionFunc) apply(e *retrievedSettings) {\n\tof(e)\n}\n\n// WithRetrievedClose overrides the default Retrieved.Close function.\n// The default Retrieved.Close function does nothing and always returns nil.\nfunc WithRetrievedClose(closeFunc CloseFunc) RetrievedOption {\n\treturn retrievedOptionFunc(func(settings *retrievedSettings) {\n\t\tsettings.closeFunc = closeFunc\n\t})\n}\n\nfunc withStringRepresentation(stringRepresentation string) RetrievedOption {\n\treturn retrievedOptionFunc(func(settings *retrievedSettings) {\n\t\tsettings.stringRepresentation = stringRepresentation\n\t\tsettings.isSetString = true\n\t})\n}\n\nfunc withErrorHint(errorHint error) RetrievedOption {\n\treturn retrievedOptionFunc(func(settings *retrievedSettings) {\n\t\tsettings.errorHint = errorHint\n\t})\n}\n\n// NewRetrievedFromYAML returns a new Retrieved instance that contains the deserialized data from the yaml bytes.\n// * yamlBytes the yaml bytes that will be deserialized.\n// * opts specifies options associated with this Retrieved value, such as CloseFunc.\nfunc NewRetrievedFromYAML(yamlBytes []byte, opts ...RetrievedOption) (*Retrieved, error) {\n\tvar rawConf any\n\tif err := yaml.Unmarshal(yamlBytes, &rawConf); err != nil {\n\t\t// If the string is not valid YAML, we try to use it verbatim as a string.\n\t\tstrRep := string(yamlBytes)\n\t\treturn NewRetrieved(strRep, append(opts,\n\t\t\twithStringRepresentation(strRep),\n\t\t\twithErrorHint(fmt.Errorf(\"assuming string type since contents are not valid YAML: %w\", err)),\n\t\t)...)\n\t}\n\n\tswitch rawConf.(type) {\n\tcase string:\n\t\tval := string(yamlBytes)\n\t\treturn NewRetrieved(val, append(opts, withStringRepresentation(val))...)\n\tdefault:\n\t\topts = append(opts, withStringRepresentation(string(yamlBytes)))\n\t}\n\n\treturn NewRetrieved(rawConf, opts...)\n}\n\n// NewRetrieved returns a new Retrieved instance that contains the data from the raw deserialized config.\n// The rawConf can be one of the following types:\n//   - Primitives: int, int32, int64, float32, float64, bool, string;\n//   - []any;\n//   - map[string]any;\nfunc NewRetrieved(rawConf any, opts ...RetrievedOption) (*Retrieved, error) {\n\tif err := checkRawConfType(rawConf); err != nil {\n\t\treturn nil, err\n\t}\n\tset := retrievedSettings{}\n\tfor _, opt := range opts {\n\t\topt.apply(&set)\n\t}\n\treturn &Retrieved{\n\t\trawConf:              rawConf,\n\t\terrorHint:            set.errorHint,\n\t\tcloseFunc:            set.closeFunc,\n\t\tstringRepresentation: set.stringRepresentation,\n\t\tisSetString:          set.isSetString,\n\t}, nil\n}\n\n// AsConf returns the retrieved configuration parsed as a Conf.\nfunc (r *Retrieved) AsConf() (*Conf, error) {\n\tif r.rawConf == nil {\n\t\treturn New(), nil\n\t}\n\tval, ok := r.rawConf.(map[string]any)\n\tif !ok {\n\t\tif r.errorHint != nil {\n\t\t\treturn nil, fmt.Errorf(\"retrieved value (type=%T) cannot be used as a Conf: %w\", r.rawConf, r.errorHint)\n\t\t}\n\t\treturn nil, fmt.Errorf(\"retrieved value (type=%T) cannot be used as a Conf\", r.rawConf)\n\t}\n\treturn NewFromStringMap(val), nil\n}\n\n// AsRaw returns the retrieved configuration parsed as an any which can be one of the following types:\n//   - Primitives: int, int32, int64, float32, float64, bool, string;\n//   - []any - every member follows the same rules as the given any;\n//   - map[string]any - every value follows the same rules as the given any;\nfunc (r *Retrieved) AsRaw() (any, error) {\n\treturn r.rawConf, nil\n}\n\n// AsString returns the retrieved configuration as a string.\n// If the retrieved configuration is not convertible to a string unambiguously, an error is returned.\n// If the retrieved configuration is a string, the string is returned.\n// This method is used to resolve ${} references in inline position.\nfunc (r *Retrieved) AsString() (string, error) {\n\tif !r.isSetString {\n\t\tif str, ok := r.rawConf.(string); ok {\n\t\t\treturn str, nil\n\t\t}\n\t\treturn \"\", fmt.Errorf(\"retrieved value does not have unambiguous string representation: %v\", r.rawConf)\n\t}\n\treturn r.stringRepresentation, nil\n}\n\n// Close and release any watchers that Provider.Retrieve may have created.\n//\n// Should block until all resources are closed, and guarantee that `onChange` is not\n// going to be called after it returns except when `ctx` is cancelled.\n//\n// Should never be called concurrently with itself.\nfunc (r *Retrieved) Close(ctx context.Context) error {\n\tif r.closeFunc == nil {\n\t\treturn nil\n\t}\n\treturn r.closeFunc(ctx)\n}\n\n// CloseFunc a function equivalent to Retrieved.Close.\ntype CloseFunc func(context.Context) error\n\nfunc checkRawConfType(rawConf any) error {\n\tif rawConf == nil {\n\t\treturn nil\n\t}\n\tswitch rawConf.(type) {\n\tcase int, int32, int64, float32, float64, bool, string, []any, map[string]any, time.Time:\n\t\treturn nil\n\tdefault:\n\t\treturn fmt.Errorf(\n\t\t\t\"unsupported type=%T for retrieved config,\"+\n\t\t\t\t\" ensure that values are wrapped in quotes\", rawConf)\n\t}\n}\n"
  },
  {
    "path": "confmap/provider_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confmap\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n// This is an example of a provider that calls a provided WatcherFunc to update configuration dynamically every second.\n// The example is useful for implementing Providers of configuration that changes over time.\ntype UpdatingProvider struct{}\n\nfunc (p UpdatingProvider) getCurrentConfig(_ string) any {\n\treturn \"hello\"\n}\n\nfunc (p UpdatingProvider) Retrieve(ctx context.Context, uri string, watcher WatcherFunc) (*Retrieved, error) {\n\tticker := time.NewTicker(1 * time.Second)\n\tstop := make(chan bool, 1)\n\n\tretrieved, err := NewRetrieved(p.getCurrentConfig(uri), WithRetrievedClose(func(_ context.Context) error {\n\t\t// the retriever should call this function when it no longer wants config updates\n\t\tticker.Stop()\n\t\tstop <- true\n\t\treturn nil\n\t}))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\t// it's necessary to start a go function that can notify the caller of changes asynchronously\n\tgo func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ctx.Done():\n\t\t\t\t// if the context is closed, then we should stop sending updates\n\t\t\t\tticker.Stop()\n\t\t\t\treturn\n\t\t\tcase <-stop:\n\t\t\t\t// closeFunc was called, so stop updating the watcher\n\t\t\t\treturn\n\t\t\tcase <-ticker.C:\n\t\t\t\t// the configuration has \"changed\". Notify the watcher that a new config is available\n\t\t\t\t// the watcher is expected to call Provider.Retrieve again to get the update\n\t\t\t\t// note that the collector calls closeFunc before calling Retrieve for the second time,\n\t\t\t\t// so these go functions don't accumulate indefinitely. (see otelcol/collector.go, Collector.reloadConfiguration)\n\t\t\t\twatcher(&ChangeEvent{})\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn retrieved, nil\n}\n\nfunc ExampleProvider() {\n\tprovider := UpdatingProvider{}\n\n\treceivedNotification := make(chan bool)\n\n\twatcherFunc := func(_ *ChangeEvent) {\n\t\tfmt.Println(\"received notification of new config\")\n\t\treceivedNotification <- true\n\t}\n\n\tretrieved, err := provider.Retrieve(context.Background(), \"example\", watcherFunc)\n\tif err != nil {\n\t\tfmt.Println(\"received an error\")\n\t} else {\n\t\tfmt.Printf(\"received: %s\\n\", retrieved.rawConf)\n\t}\n\n\t// after one second, we should receive a notification that config has changed\n\t<-receivedNotification\n\t// signal that we no longer want updates\n\tretrieved.Close(context.Background())\n\n\t// Output:\n\t// received: hello\n\t// received notification of new config\n}\n\nfunc TestNewRetrieved(t *testing.T) {\n\tret, err := NewRetrieved(nil)\n\trequire.NoError(t, err)\n\tretMap, err := ret.AsConf()\n\trequire.NoError(t, err)\n\tassert.Equal(t, New(), retMap)\n\tassert.NoError(t, ret.Close(context.Background()))\n}\n\nfunc TestNewRetrievedWithOptions(t *testing.T) {\n\twant := errors.New(\"my error\")\n\tret, err := NewRetrieved(nil, WithRetrievedClose(func(context.Context) error { return want }))\n\trequire.NoError(t, err)\n\tretMap, err := ret.AsConf()\n\trequire.NoError(t, err)\n\tassert.Equal(t, New(), retMap)\n\tassert.Equal(t, want, ret.Close(context.Background()))\n}\n\nfunc TestNewRetrievedUnsupportedType(t *testing.T) {\n\t_, err := NewRetrieved(errors.New(\"my error\"))\n\trequire.Error(t, err)\n}\n\nfunc TestNewRetrievedFromYAML(t *testing.T) {\n\tret, err := NewRetrievedFromYAML([]byte{})\n\trequire.NoError(t, err)\n\tretMap, err := ret.AsConf()\n\trequire.NoError(t, err)\n\tassert.Equal(t, New(), retMap)\n\tassert.NoError(t, ret.Close(context.Background()))\n}\n\nfunc TestNewRetrievedFromYAMLWithOptions(t *testing.T) {\n\twant := errors.New(\"my error\")\n\tret, err := NewRetrievedFromYAML([]byte{}, WithRetrievedClose(func(context.Context) error { return want }))\n\trequire.NoError(t, err)\n\tretMap, err := ret.AsConf()\n\trequire.NoError(t, err)\n\tassert.Equal(t, New(), retMap)\n\tassert.Equal(t, want, ret.Close(context.Background()))\n}\n\nfunc TestNewRetrievedFromYAMLInvalidYAMLBytes(t *testing.T) {\n\tret, err := NewRetrievedFromYAML([]byte(\"[invalid:,\"))\n\trequire.NoError(t, err)\n\n\t_, err = ret.AsConf()\n\trequire.EqualError(t, err,\n\t\t\"retrieved value (type=string) cannot be used as a Conf: assuming string type since contents are not valid YAML: yaml: line 1: did not find expected node content\",\n\t)\n\n\tstr, err := ret.AsString()\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"[invalid:,\", str)\n\n\traw, err := ret.AsRaw()\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"[invalid:,\", raw)\n}\n\nfunc TestNewRetrievedFromYAMLInvalidAsMap(t *testing.T) {\n\tret, err := NewRetrievedFromYAML([]byte(\"string\"))\n\trequire.NoError(t, err)\n\n\t_, err = ret.AsConf()\n\trequire.EqualError(t, err, \"retrieved value (type=string) cannot be used as a Conf\")\n\n\tstr, err := ret.AsString()\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"string\", str)\n}\n\nfunc TestNewRetrievedFromYAMLString(t *testing.T) {\n\ttests := []struct {\n\t\tyaml       string\n\t\tvalue      any\n\t\taltStrRepr string\n\t\tstrReprErr string\n\t}{\n\t\t{\n\t\t\tyaml:  \"string\",\n\t\t\tvalue: \"string\",\n\t\t},\n\t\t{\n\t\t\tyaml:       \"\\\"string\\\"\",\n\t\t\tvalue:      \"\\\"string\\\"\",\n\t\t\taltStrRepr: \"\\\"string\\\"\",\n\t\t},\n\t\t{\n\t\t\tyaml:  \"123\",\n\t\t\tvalue: 123,\n\t\t},\n\t\t{\n\t\t\tyaml:  \"2023-03-20T03:17:55.432328Z\",\n\t\t\tvalue: time.Date(2023, 3, 20, 3, 17, 55, 432328000, time.UTC),\n\t\t},\n\t\t{\n\t\t\tyaml:  \"true\",\n\t\t\tvalue: true,\n\t\t},\n\t\t{\n\t\t\tyaml:  \"0123\",\n\t\t\tvalue: 0o123,\n\t\t},\n\t\t{\n\t\t\tyaml:  \"0x123\",\n\t\t\tvalue: 0x123,\n\t\t},\n\t\t{\n\t\t\tyaml:  \"0b101\",\n\t\t\tvalue: 0b101,\n\t\t},\n\t\t{\n\t\t\tyaml:  \"0.123\",\n\t\t\tvalue: 0.123,\n\t\t},\n\t\t{\n\t\t\tyaml:  \"{key: value}\",\n\t\t\tvalue: map[string]any{\"key\": \"value\"},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.yaml, func(t *testing.T) {\n\t\t\tret, err := NewRetrievedFromYAML([]byte(tt.yaml))\n\t\t\trequire.NoError(t, err)\n\n\t\t\traw, err := ret.AsRaw()\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tt.value, raw)\n\n\t\t\tstr, err := ret.AsString()\n\t\t\tif tt.strReprErr != \"\" {\n\t\t\t\tassert.ErrorContains(t, err, tt.strReprErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\n\t\t\tif tt.altStrRepr != \"\" {\n\t\t\t\tassert.Equal(t, tt.altStrRepr, str)\n\t\t\t} else {\n\t\t\t\tassert.Equal(t, tt.yaml, str)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "confmap/resolver.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confmap // import \"go.opentelemetry.io/collector/confmap\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"go.uber.org/multierr\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/confmap/internal\"\n)\n\n// follows drive-letter specification:\n// https://datatracker.ietf.org/doc/html/draft-kerwin-file-scheme-07.html#section-2.2\nvar driverLetterRegexp = regexp.MustCompile(\"^[A-z]:\")\n\n// Resolver resolves a configuration as a Conf.\ntype Resolver struct {\n\turis          []location\n\tproviders     map[string]Provider\n\tdefaultScheme string\n\tconverters    []Converter\n\n\tclosers []CloseFunc\n\twatcher chan error\n}\n\n// ResolverSettings are the settings to configure the behavior of the Resolver.\ntype ResolverSettings struct {\n\t// URIs locations from where the Conf is retrieved, and merged in the given order.\n\t// It is required to have at least one location.\n\tURIs []string\n\n\t// ProviderFactories is a slice of Provider factories.\n\t// It is required to have at least one factory.\n\tProviderFactories []ProviderFactory\n\n\t// DefaultScheme is the scheme that is used if ${} syntax is used but no schema is provided.\n\t// If no DefaultScheme is set, ${} with no schema will not be expanded.\n\t// It is strongly recommended to set \"env\" as the default scheme to align with the\n\t// OpenTelemetry Configuration Specification\n\tDefaultScheme string\n\n\t// ProviderSettings contains settings that will be passed to Provider\n\t// factories when instantiating Providers.\n\tProviderSettings ProviderSettings\n\n\t// ConverterFactories is a slice of Converter creation functions.\n\tConverterFactories []ConverterFactory\n\n\t// ConverterSettings contains settings that will be passed to Converter\n\t// factories when instantiating Converters.\n\tConverterSettings ConverterSettings\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// NewResolver returns a new Resolver that resolves configuration from multiple URIs.\n//\n// To resolve a configuration the following steps will happen:\n//  1. Retrieves individual configurations from all given \"URIs\", and merge them in the retrieve order.\n//  2. Once the Conf is merged, apply the converters in the given order.\n//\n// After the configuration was resolved the `Resolver` can be used as a single point to watch for updates in\n// the configuration data retrieved via the config providers used to process the \"initial\" configuration and to generate\n// the \"effective\" one. The typical usage is the following:\n//\n//\tResolver.Resolve(ctx)\n//\tResolver.Watch() // wait for an event.\n//\tResolver.Resolve(ctx)\n//\tResolver.Watch() // wait for an event.\n//\t// repeat Resolve/Watch cycle until it is time to shut down the Collector process.\n//\tResolver.Shutdown(ctx)\n//\n// `uri` must follow the \"<scheme>:<opaque_data>\" format. This format is compatible with the URI definition\n// (see https://datatracker.ietf.org/doc/html/rfc3986). An empty \"<scheme>\" defaults to \"file\" schema.\nfunc NewResolver(set ResolverSettings) (*Resolver, error) {\n\tif len(set.URIs) == 0 {\n\t\treturn nil, errors.New(\"invalid 'confmap.ResolverSettings' configuration: no URIs\")\n\t}\n\n\tif len(set.ProviderFactories) == 0 {\n\t\treturn nil, errors.New(\"invalid 'confmap.ResolverSettings' configuration: no Providers\")\n\t}\n\n\tif set.ProviderSettings.Logger == nil {\n\t\tset.ProviderSettings.Logger = zap.NewNop()\n\t}\n\n\tif set.ConverterSettings.Logger == nil {\n\t\tset.ConverterSettings.Logger = zap.NewNop()\n\t}\n\n\tproviders := make(map[string]Provider, len(set.ProviderFactories))\n\tfor _, factory := range set.ProviderFactories {\n\t\tprovider := factory.Create(set.ProviderSettings)\n\t\tscheme := provider.Scheme()\n\t\t// Check that the scheme follows the pattern.\n\t\tif !regexp.MustCompile(schemePattern).MatchString(scheme) {\n\t\t\treturn nil, fmt.Errorf(\"invalid 'confmap.Provider' scheme %q\", scheme)\n\t\t}\n\t\t// Check that the scheme is unique.\n\t\tif _, ok := providers[scheme]; ok {\n\t\t\treturn nil, fmt.Errorf(\"duplicate 'confmap.Provider' scheme %q\", scheme)\n\t\t}\n\n\t\tproviders[scheme] = provider\n\t}\n\n\tif set.DefaultScheme != \"\" {\n\t\t_, ok := providers[set.DefaultScheme]\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"invalid 'confmap.ResolverSettings' configuration: DefaultScheme not found in providers list\")\n\t\t}\n\t}\n\n\tconverters := make([]Converter, len(set.ConverterFactories))\n\tfor i, factory := range set.ConverterFactories {\n\t\tconverters[i] = factory.Create(set.ConverterSettings)\n\t}\n\n\t// Safe copy, ensures the slices and maps cannot be changed from the caller.\n\turis := make([]location, len(set.URIs))\n\tfor i, uri := range set.URIs {\n\t\t// For backwards compatibility:\n\t\t// - empty url scheme means \"file\".\n\t\t// - \"^[A-z]:\" also means \"file\"\n\t\tif driverLetterRegexp.MatchString(uri) || !strings.Contains(uri, \":\") {\n\t\t\turis[i] = location{scheme: \"file\", opaqueValue: uri}\n\t\t\tcontinue\n\t\t}\n\t\tlURI, err := newLocation(uri)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tif _, ok := providers[lURI.scheme]; !ok {\n\t\t\treturn nil, fmt.Errorf(\"unsupported scheme on URI %q\", uri)\n\t\t}\n\t\turis[i] = lURI\n\t}\n\n\treturn &Resolver{\n\t\turis:          uris,\n\t\tproviders:     providers,\n\t\tdefaultScheme: set.DefaultScheme,\n\t\tconverters:    converters,\n\t\twatcher:       make(chan error, 1),\n\t}, nil\n}\n\n// Resolve returns the configuration as a Conf, or error otherwise.\n// Should never be called concurrently with itself, Watch or Shutdown.\nfunc (mr *Resolver) Resolve(ctx context.Context) (*Conf, error) {\n\t// First check if already an active watching, close that if any.\n\tif err := mr.closeIfNeeded(ctx); err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot close previous watch: %w\", err)\n\t}\n\n\t// Retrieves individual configurations from all URIs in the given order, and merge them in retMap.\n\tretMap := New()\n\tfor _, uri := range mr.uris {\n\t\tret, err := mr.retrieveValue(ctx, uri)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot retrieve the configuration: %w\", err)\n\t\t}\n\t\tmr.closers = append(mr.closers, ret.Close)\n\t\tretCfgMap, err := ret.AsConf()\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tif err := retMap.Merge(retCfgMap); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tcfgMap := make(map[string]any)\n\tfor _, k := range retMap.AllKeys() {\n\t\tug := internal.UnsanitizedGetter{Conf: retMap}\n\t\tval, err := mr.expandValueRecursively(ctx, ug.UnsanitizedGet(k))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tcfgMap[k] = escapeDollarSigns(val)\n\t}\n\tretMap = NewFromStringMap(cfgMap)\n\n\t// Apply the converters in the given order.\n\tfor _, confConv := range mr.converters {\n\t\tif err := confConv.Convert(ctx, retMap); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"cannot convert the confmap.Conf: %w\", err)\n\t\t}\n\t}\n\n\treturn retMap, nil\n}\n\nfunc escapeDollarSigns(val any) any {\n\tswitch v := val.(type) {\n\tcase string:\n\t\treturn strings.ReplaceAll(v, \"$$\", \"$\")\n\tcase internal.ExpandedValue:\n\t\tv.Original = strings.ReplaceAll(v.Original, \"$$\", \"$\")\n\t\tv.Value = escapeDollarSigns(v.Value)\n\t\treturn v\n\tcase []any:\n\t\tnslice := make([]any, len(v))\n\t\tfor i, x := range v {\n\t\t\tnslice[i] = escapeDollarSigns(x)\n\t\t}\n\t\treturn nslice\n\tcase map[string]any:\n\t\tnmap := make(map[string]any, len(v))\n\t\tfor k, x := range v {\n\t\t\tnmap[k] = escapeDollarSigns(x)\n\t\t}\n\t\treturn nmap\n\tdefault:\n\t\treturn val\n\t}\n}\n\n// Watch blocks until any configuration change was detected or an unrecoverable error\n// happened during monitoring the configuration changes.\n//\n// Error is nil if the configuration is changed and needs to be re-fetched. Any non-nil\n// error indicates that there was a problem with watching the configuration changes.\n//\n// Should never be called concurrently with itself or Get.\nfunc (mr *Resolver) Watch() <-chan error {\n\treturn mr.watcher\n}\n\n// Shutdown signals that the provider is no longer in use and the that should close\n// and release any resources that it may have created. It terminates the Watch channel.\n//\n// Should never be called concurrently with itself or Get.\nfunc (mr *Resolver) Shutdown(ctx context.Context) error {\n\tvar errs error\n\terrs = multierr.Append(errs, mr.closeIfNeeded(ctx))\n\tfor _, p := range mr.providers {\n\t\terrs = multierr.Append(errs, p.Shutdown(ctx))\n\t}\n\n\tclose(mr.watcher)\n\n\treturn errs\n}\n\nfunc (mr *Resolver) onChange(event *ChangeEvent) {\n\tmr.watcher <- event.Error\n}\n\nfunc (mr *Resolver) closeIfNeeded(ctx context.Context) error {\n\tvar err error\n\tfor _, ret := range mr.closers {\n\t\terr = multierr.Append(err, ret(ctx))\n\t}\n\tmr.closers = nil\n\treturn err\n}\n\nfunc (mr *Resolver) retrieveValue(ctx context.Context, uri location) (*Retrieved, error) {\n\tp, ok := mr.providers[uri.scheme]\n\tif !ok {\n\t\treturn nil, fmt.Errorf(\"scheme %q is not supported for uri %q\", uri.scheme, uri.asString())\n\t}\n\treturn p.Retrieve(ctx, uri.asString(), mr.onChange)\n}\n"
  },
  {
    "path": "confmap/resolver_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage confmap\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"reflect\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\t\"go.yaml.in/yaml/v3\"\n\n\t\"go.opentelemetry.io/collector/confmap/internal/metadata\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\ntype mockProvider struct {\n\tscheme    string\n\tretM      any\n\terrR      error\n\terrS      error\n\terrW      error\n\tcloseFunc func(ctx context.Context) error\n}\n\nfunc (m *mockProvider) Retrieve(_ context.Context, _ string, watcher WatcherFunc) (*Retrieved, error) {\n\tif m.errR != nil {\n\t\treturn nil, m.errR\n\t}\n\tif m.retM == nil {\n\t\treturn NewRetrieved(nil)\n\t}\n\n\twatcher(&ChangeEvent{Error: m.errW})\n\treturn NewRetrieved(m.retM, WithRetrievedClose(m.closeFunc))\n}\n\nfunc (m *mockProvider) Scheme() string {\n\tif m.scheme == \"\" {\n\t\treturn \"mock\"\n\t}\n\treturn m.scheme\n}\n\nfunc (m *mockProvider) Shutdown(context.Context) error {\n\treturn m.errS\n}\n\nfunc newMockProvider(m *mockProvider) ProviderFactory {\n\treturn NewProviderFactory(func(_ ProviderSettings) Provider {\n\t\treturn m\n\t})\n}\n\ntype fakeProvider struct {\n\tscheme string\n\tret    func(ctx context.Context, uri string, watcher WatcherFunc) (*Retrieved, error)\n\tlogger *zap.Logger\n}\n\nfunc newFileProvider(tb testing.TB) ProviderFactory {\n\treturn newFakeProvider(\"file\", func(_ context.Context, uri string, _ WatcherFunc) (*Retrieved, error) {\n\t\treturn NewRetrieved(newConfFromFile(tb, uri[5:]))\n\t})\n}\n\nfunc newFakeProvider(scheme string, ret func(ctx context.Context, uri string, watcher WatcherFunc) (*Retrieved, error)) ProviderFactory {\n\treturn NewProviderFactory(func(ps ProviderSettings) Provider {\n\t\treturn &fakeProvider{\n\t\t\tscheme: scheme,\n\t\t\tret:    ret,\n\t\t\tlogger: ps.Logger,\n\t\t}\n\t})\n}\n\nfunc newObservableFileProvider(tb testing.TB) (ProviderFactory, *fakeProvider) {\n\treturn newObservableProvider(\"file\", func(_ context.Context, uri string, _ WatcherFunc) (*Retrieved, error) {\n\t\treturn NewRetrieved(newConfFromFile(tb, uri[5:]))\n\t})\n}\n\nfunc newObservableProvider(scheme string, ret func(ctx context.Context, uri string, watcher WatcherFunc) (*Retrieved, error)) (ProviderFactory, *fakeProvider) {\n\tfp := &fakeProvider{\n\t\tscheme: scheme,\n\t\tret:    ret,\n\t}\n\treturn NewProviderFactory(func(ps ProviderSettings) Provider {\n\t\tfp.logger = ps.Logger\n\t\treturn fp\n\t}), fp\n}\n\nfunc (f *fakeProvider) Retrieve(ctx context.Context, uri string, watcher WatcherFunc) (*Retrieved, error) {\n\treturn f.ret(ctx, uri, watcher)\n}\n\nfunc (f *fakeProvider) Scheme() string {\n\treturn f.scheme\n}\n\nfunc (f *fakeProvider) Shutdown(context.Context) error {\n\treturn nil\n}\n\ntype mockConverter struct {\n\terr error\n}\n\nfunc (m *mockConverter) Convert(context.Context, *Conf) error {\n\treturn errors.New(\"converter_err\")\n}\n\nfunc TestNewResolverInvalidSchemeInURI(t *testing.T) {\n\t_, err := NewResolver(ResolverSettings{URIs: []string{\"s_3:has invalid char\"}, ProviderFactories: []ProviderFactory{newMockProvider(&mockProvider{scheme: \"s3\"})}})\n\tassert.EqualError(t, err, `invalid uri: \"s_3:has invalid char\"`)\n}\n\nfunc TestNewResolverDuplicateScheme(t *testing.T) {\n\t_, err := NewResolver(ResolverSettings{URIs: []string{\"mock:something\"}, ProviderFactories: []ProviderFactory{newMockProvider(&mockProvider{scheme: \"mock\"}), newMockProvider(&mockProvider{scheme: \"mock\"})}})\n\tassert.EqualError(t, err, `duplicate 'confmap.Provider' scheme \"mock\"`)\n}\n\nfunc TestResolverErrors(t *testing.T) {\n\ttests := []struct {\n\t\tname              string\n\t\tlocations         []string\n\t\tproviders         []Provider\n\t\tconverters        []Converter\n\t\tdefaultScheme     string\n\t\texpectBuildErr    bool\n\t\texpectResolveErr  bool\n\t\texpectWatchErr    bool\n\t\texpectCloseErr    bool\n\t\texpectShutdownErr bool\n\t}{\n\t\t{\n\t\t\tname:           \"unsupported location scheme\",\n\t\t\tlocations:      []string{\"mock:\", \"notsupported:\"},\n\t\t\tproviders:      []Provider{&mockProvider{}},\n\t\t\texpectBuildErr: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"default scheme not found\",\n\t\t\tlocations: []string{\"mock:\", \"err:\"},\n\t\t\tproviders: []Provider{\n\t\t\t\t&mockProvider{},\n\t\t\t\t&mockProvider{scheme: \"err\", errR: errors.New(\"retrieve_err\")},\n\t\t\t},\n\t\t\tdefaultScheme:  \"missing\",\n\t\t\texpectBuildErr: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"retrieve location config error\",\n\t\t\tlocations: []string{\"mock:\", \"err:\"},\n\t\t\tproviders: []Provider{\n\t\t\t\t&mockProvider{},\n\t\t\t\t&mockProvider{scheme: \"err\", errR: errors.New(\"retrieve_err\")},\n\t\t\t},\n\t\t\texpectResolveErr: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"retrieve location not convertible to Conf\",\n\t\t\tlocations: []string{\"mock:\", \"err:\"},\n\t\t\tproviders: []Provider{\n\t\t\t\t&mockProvider{},\n\t\t\t\t&mockProvider{scheme: \"err\", retM: \"invalid value\"},\n\t\t\t},\n\t\t\texpectResolveErr: true,\n\t\t},\n\t\t{\n\t\t\tname:             \"converter error\",\n\t\t\tlocations:        []string{\"mock:\"},\n\t\t\tproviders:        []Provider{&mockProvider{}},\n\t\t\tconverters:       []Converter{&mockConverter{err: errors.New(\"converter_err\")}},\n\t\t\texpectResolveErr: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"watch error\",\n\t\t\tlocations: []string{\"mock:\", \"err:\"},\n\t\t\tproviders: []Provider{\n\t\t\t\t&mockProvider{},\n\t\t\t\t&mockProvider{scheme: \"err\", retM: map[string]any{}, errW: errors.New(\"watch_err\")},\n\t\t\t},\n\t\t\texpectWatchErr: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"close error\",\n\t\t\tlocations: []string{\"mock:\", \"err:\"},\n\t\t\tproviders: []Provider{\n\t\t\t\t&mockProvider{},\n\t\t\t\t&mockProvider{scheme: \"err\", retM: map[string]any{}, closeFunc: func(context.Context) error { return errors.New(\"close_err\") }},\n\t\t\t},\n\t\t\texpectCloseErr: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"shutdown error\",\n\t\t\tlocations: []string{\"mock:\", \"err:\"},\n\t\t\tproviders: []Provider{\n\t\t\t\t&mockProvider{},\n\t\t\t\t&mockProvider{scheme: \"err\", retM: map[string]any{}, errS: errors.New(\"close_err\")},\n\t\t\t},\n\t\t\texpectShutdownErr: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tmockProviderFuncs := make([]ProviderFactory, len(tt.providers))\n\t\t\tfor i, provider := range tt.providers {\n\t\t\t\tp := provider\n\t\t\t\tmockProviderFuncs[i] = NewProviderFactory(func(_ ProviderSettings) Provider { return p })\n\t\t\t}\n\t\t\tconverterFuncs := make([]ConverterFactory, len(tt.converters))\n\t\t\tfor i, converter := range tt.converters {\n\t\t\t\tc := converter\n\t\t\t\tconverterFuncs[i] = NewConverterFactory(func(_ ConverterSettings) Converter { return c })\n\t\t\t}\n\t\t\tresolver, err := NewResolver(ResolverSettings{URIs: tt.locations, ProviderFactories: mockProviderFuncs, DefaultScheme: tt.defaultScheme, ConverterFactories: converterFuncs})\n\t\t\tif tt.expectBuildErr {\n\t\t\t\tassert.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\n\t\t\t_, errN := resolver.Resolve(context.Background())\n\t\t\tif tt.expectResolveErr {\n\t\t\t\tassert.Error(t, errN)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, errN)\n\n\t\t\terrW := <-resolver.Watch()\n\t\t\tif tt.expectWatchErr {\n\t\t\t\tassert.Error(t, errW)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, errW)\n\n\t\t\t_, errC := resolver.Resolve(context.Background())\n\t\t\tif tt.expectCloseErr {\n\t\t\t\tassert.Error(t, errC)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, errN)\n\n\t\t\terrS := resolver.Shutdown(context.Background())\n\t\t\tif tt.expectShutdownErr {\n\t\t\t\tassert.Error(t, errS)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tassert.NoError(t, errC)\n\t\t})\n\t}\n}\n\nfunc TestBackwardsCompatibilityForFilePath(t *testing.T) {\n\ttests := []struct {\n\t\tname           string\n\t\tlocation       string\n\t\terrMessage     string\n\t\texpectBuildErr bool\n\t}{\n\t\t{\n\t\t\tname:       \"unix\",\n\t\t\tlocation:   `/test`,\n\t\t\terrMessage: `file:/test`,\n\t\t},\n\t\t{\n\t\t\tname:       \"file_unix\",\n\t\t\tlocation:   `file:/test`,\n\t\t\terrMessage: `file:/test`,\n\t\t},\n\t\t{\n\t\t\tname:       \"windows_C\",\n\t\t\tlocation:   `c:\\test`,\n\t\t\terrMessage: `file:c:\\test`,\n\t\t},\n\t\t{\n\t\t\tname:       \"windows_z\",\n\t\t\tlocation:   `z:\\test`,\n\t\t\terrMessage: `file:z:\\test`,\n\t\t},\n\t\t{\n\t\t\tname:       \"file_windows\",\n\t\t\tlocation:   `file:c:\\test`,\n\t\t\terrMessage: `file:c:\\test`,\n\t\t},\n\t\t{\n\t\t\tname:           \"invalid_scheme\",\n\t\t\tlocation:       `LL:\\test`,\n\t\t\texpectBuildErr: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresolver, err := NewResolver(ResolverSettings{\n\t\t\t\tURIs: []string{tt.location},\n\t\t\t\tProviderFactories: []ProviderFactory{\n\t\t\t\t\tnewFakeProvider(\"file\", func(_ context.Context, uri string, _ WatcherFunc) (*Retrieved, error) {\n\t\t\t\t\t\treturn nil, errors.New(uri)\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t\tConverterFactories: nil,\n\t\t\t})\n\t\t\tif tt.expectBuildErr {\n\t\t\t\tassert.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\t_, err = resolver.Resolve(context.Background())\n\t\t\tassert.ErrorContains(t, err, tt.errMessage, tt.name)\n\t\t})\n\t}\n}\n\nfunc TestResolver(t *testing.T) {\n\tnumCalls := atomic.Int32{}\n\tresolver, err := NewResolver(ResolverSettings{\n\t\tURIs: []string{\"mock:\"},\n\t\tProviderFactories: []ProviderFactory{\n\t\t\tnewMockProvider(&mockProvider{retM: map[string]any{}, closeFunc: func(context.Context) error {\n\t\t\t\tnumCalls.Add(1)\n\t\t\t\treturn nil\n\t\t\t}}),\n\t\t},\n\t\tConverterFactories: nil,\n\t})\n\trequire.NoError(t, err)\n\t_, errN := resolver.Resolve(context.Background())\n\trequire.NoError(t, errN)\n\tassert.Equal(t, int32(0), numCalls.Load())\n\n\terrW := <-resolver.Watch()\n\trequire.NoError(t, errW)\n\n\t// Repeat Resolve/Watch.\n\n\t_, errN = resolver.Resolve(context.Background())\n\trequire.NoError(t, errN)\n\tassert.Equal(t, int32(1), numCalls.Load())\n\n\terrW = <-resolver.Watch()\n\trequire.NoError(t, errW)\n\n\t_, errN = resolver.Resolve(context.Background())\n\trequire.NoError(t, errN)\n\tassert.Equal(t, int32(2), numCalls.Load())\n\n\terrC := resolver.Shutdown(context.Background())\n\trequire.NoError(t, errC)\n\tassert.Equal(t, int32(3), numCalls.Load())\n}\n\nfunc TestResolverNewLinesInOpaqueValue(t *testing.T) {\n\t_, err := NewResolver(ResolverSettings{\n\t\tURIs:               []string{\"mock:receivers:\\n nop:\\n\"},\n\t\tProviderFactories:  []ProviderFactory{newMockProvider(&mockProvider{retM: map[string]any{}})},\n\t\tConverterFactories: nil,\n\t})\n\tassert.NoError(t, err)\n}\n\nfunc TestResolverNoLocations(t *testing.T) {\n\t_, err := NewResolver(ResolverSettings{\n\t\tURIs:               []string{},\n\t\tProviderFactories:  []ProviderFactory{newMockProvider(&mockProvider{})},\n\t\tConverterFactories: nil,\n\t})\n\tassert.Error(t, err)\n}\n\nfunc TestResolverNoProviders(t *testing.T) {\n\t_, err := NewResolver(ResolverSettings{\n\t\tURIs:               []string{filepath.Join(\"testdata\", \"config.yaml\")},\n\t\tProviderFactories:  nil,\n\t\tConverterFactories: nil,\n\t})\n\tassert.Error(t, err)\n}\n\nfunc TestResolverShutdownClosesWatch(t *testing.T) {\n\tresolver, err := NewResolver(ResolverSettings{\n\t\tURIs:               []string{filepath.Join(\"testdata\", \"config.yaml\")},\n\t\tProviderFactories:  []ProviderFactory{newFileProvider(t)},\n\t\tConverterFactories: nil,\n\t})\n\trequire.NoError(t, err)\n\t_, errN := resolver.Resolve(context.Background())\n\trequire.NoError(t, errN)\n\n\tvar watcherWG sync.WaitGroup\n\twatcherWG.Go(func() {\n\t\terrW, ok := <-resolver.Watch()\n\t\t// Channel is closed, no exception\n\t\trequire.NoError(t, errW)\n\t\tassert.False(t, ok)\n\t})\n\n\trequire.NoError(t, resolver.Shutdown(context.Background()))\n\twatcherWG.Wait()\n}\n\nfunc TestProvidesDefaultLogger(t *testing.T) {\n\tfactory, provider := newObservableFileProvider(t)\n\t_, err := NewResolver(ResolverSettings{\n\t\tURIs:              []string{filepath.Join(\"testdata\", \"config.yaml\")},\n\t\tProviderFactories: []ProviderFactory{factory},\n\t\tConverterFactories: []ConverterFactory{NewConverterFactory(func(set ConverterSettings) Converter {\n\t\t\tassert.NotNil(t, set.Logger)\n\t\t\treturn &mockConverter{}\n\t\t})},\n\t})\n\trequire.NoError(t, err)\n\trequire.NotNil(t, provider.logger)\n}\n\nfunc TestResolverDefaultProviderSet(t *testing.T) {\n\tenvProvider := newEnvProvider()\n\tfileProvider := newFileProvider(t)\n\n\tr, err := NewResolver(ResolverSettings{\n\t\tURIs:              []string{\"env:\"},\n\t\tProviderFactories: []ProviderFactory{fileProvider, envProvider},\n\t\tDefaultScheme:     \"env\",\n\t})\n\trequire.NoError(t, err)\n\tassert.NotNil(t, r.defaultScheme)\n\t_, ok := r.providers[\"env\"]\n\tassert.True(t, ok)\n}\n\ntype mergeTest struct {\n\tName        string           `yaml:\"name\"`\n\tAppendPaths []string         `yaml:\"append_paths\"`\n\tConfigs     []map[string]any `yaml:\"configs\"`\n\tExpected    map[string]any   `yaml:\"expected\"`\n}\n\nfunc TestMergeFunctionality(t *testing.T) {\n\ttests := []struct {\n\t\tname         string\n\t\tscenarioFile string\n\t\tflagEnabled  bool\n\t}{\n\t\t{\n\t\t\tname:         \"feature-flag-enabled\",\n\t\t\tscenarioFile: \"testdata/merge-append-scenarios.yaml\",\n\t\t\tflagEnabled:  true,\n\t\t},\n\t\t{\n\t\t\tname:         \"feature-flag-disabled\",\n\t\t\tscenarioFile: \"testdata/merge-append-scenarios-featuregate-disabled.yaml\",\n\t\t\tflagEnabled:  false,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif tt.flagEnabled {\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ConfmapEnableMergeAppendOptionFeatureGate.ID(), true))\n\t\t\t\tdefer func() {\n\t\t\t\t\t// Restore previous value.\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ConfmapEnableMergeAppendOptionFeatureGate.ID(), false))\n\t\t\t\t}()\n\t\t\t}\n\t\t\trunScenario(t, tt.scenarioFile)\n\t\t})\n\t}\n}\n\nfunc runScenario(t *testing.T, path string) {\n\tyamlData, err := os.ReadFile(filepath.Clean(path))\n\trequire.NoError(t, err)\n\tvar testcases []*mergeTest\n\terr = yaml.Unmarshal(yamlData, &testcases)\n\trequire.NoError(t, err)\n\tfor _, tt := range testcases {\n\t\tt.Run(tt.Name, func(t *testing.T) {\n\t\t\tconfigFiles := make([]string, 0)\n\t\t\tfor _, c := range tt.Configs {\n\t\t\t\t// store configs into a temp file. This makes it easier for us to test feature gate functionality\n\t\t\t\tfile, err := os.CreateTemp(t.TempDir(), \"*.yaml\")\n\t\t\t\tdefer func() { require.NoError(t, file.Close()) }()\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tb, err := json.Marshal(c)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tn, err := file.Write(b)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.Positive(t, n)\n\t\t\t\tconfigFiles = append(configFiles, file.Name())\n\t\t\t}\n\n\t\t\tresolver, err := NewResolver(ResolverSettings{\n\t\t\t\tURIs:              configFiles,\n\t\t\t\tProviderFactories: []ProviderFactory{newFileProvider(t)},\n\t\t\t\tDefaultScheme:     \"file\",\n\t\t\t})\n\t\t\trequire.NoError(t, err)\n\t\t\tconf, err := resolver.Resolve(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t\tmergedConf := conf.ToStringMap()\n\t\t\trequire.Truef(t, reflect.DeepEqual(mergedConf, tt.Expected), \"Exp: %s\\nGot: %s\", tt.Expected, mergedConf)\n\t\t})\n\t}\n}\n\n// newConfFromFile creates a new Conf by reading the given file.\nfunc newConfFromFile(tb testing.TB, fileName string) map[string]any {\n\tcontent, err := os.ReadFile(filepath.Clean(fileName))\n\trequire.NoErrorf(tb, err, \"unable to read the file %v\", fileName)\n\n\tvar data map[string]any\n\trequire.NoError(tb, yaml.Unmarshal(content, &data), \"unable to parse yaml\")\n\n\treturn NewFromStringMap(data).ToStringMap()\n}\n\ntype provider struct {\n\twg sync.WaitGroup\n}\n\nfunc newRaceDetectorProvider() ProviderFactory {\n\treturn NewProviderFactory(func(_ ProviderSettings) Provider {\n\t\treturn &provider{}\n\t})\n}\n\nfunc (p *provider) Retrieve(_ context.Context, _ string, watcher WatcherFunc) (*Retrieved, error) {\n\tp.wg.Go(func() {\n\t\t// mock a config change event and wait for goroutine to return.\n\t\twatcher(&ChangeEvent{})\n\t})\n\treturn NewRetrieved(map[string]any{})\n}\n\nfunc (p *provider) Scheme() string {\n\treturn \"race\"\n}\n\nfunc (p *provider) Shutdown(context.Context) error {\n\tp.wg.Wait()\n\treturn nil\n}\n\nfunc TestProviderRaceCondition(t *testing.T) {\n\tresolver, err := NewResolver(ResolverSettings{\n\t\tURIs: []string{\"race:\"},\n\t\tProviderFactories: []ProviderFactory{\n\t\t\tnewRaceDetectorProvider(),\n\t\t},\n\t\tConverterFactories: nil,\n\t})\n\trequire.NoError(t, err)\n\tc, err := resolver.Resolve(context.Background())\n\trequire.NoError(t, err)\n\trequire.NotNil(t, c)\n\trequire.NoError(t, resolver.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "confmap/testdata/config.yaml",
    "content": "receivers:\n    nop:\n    nop/myreceiver:\n\nprocessors:\n    nop:\n    nop/myprocessor:\n\nexporters:\n    nop:\n    nop/myexporter:\n\nextensions:\n    nop:\n    nop/myextension:\n\nservice:\n    extensions: [nop]\n    pipelines:\n        traces:\n            receivers: [nop]\n            processors: [nop]\n            exporters: [nop]\n"
  },
  {
    "path": "confmap/testdata/expand-with-all-env.yaml",
    "content": "test_map:\n  extra: \"${env:EXTRA}\"\n  extra_map:\n    recv.1: \"${env:EXTRA_MAP_VALUE_1}\"\n    recv.2: \"${env:EXTRA_MAP_VALUE_2}\"\n  extra_list_map:\n    - { recv.1: \"${env:EXTRA_LIST_MAP_VALUE_1}\",recv.2: \"${env:EXTRA_LIST_MAP_VALUE_2}\" }\n  extra_list:\n    - \"${env:EXTRA_LIST_VALUE_1}\"\n    - \"${env:EXTRA_LIST_VALUE_2}\"\n    \n"
  },
  {
    "path": "confmap/testdata/expand-with-no-env.yaml",
    "content": "test_map:\n  extra: \"some string\"\n  extra_map:\n    recv.1: \"some map value_1\"\n    recv.2: \"some map value_2\"\n  extra_list_map:\n    - { recv.1: \"some list map value_1\",recv.2: \"some list map value_2\" }\n  extra_list:\n    - \"some list value_1\"\n    - \"some list value_2\"\n"
  },
  {
    "path": "confmap/testdata/expand-with-partial-env.yaml",
    "content": "test_map:\n  extra: \"${env:EXTRA}\"\n  extra_map:\n    recv.1: \"${env:EXTRA_MAP_VALUE_1}\"\n    recv.2: \"some map value_2\"\n  extra_list_map:\n    - { recv.1: \"some list map value_1\",recv.2: \"${env:EXTRA_LIST_MAP_VALUE_2}\" }\n  extra_list:\n    - \"some list value_1\"\n    - \"${env:EXTRA_LIST_VALUE_2}\"\n"
  },
  {
    "path": "confmap/testdata/merge-append-scenarios-featuregate-disabled.yaml",
    "content": "- name: merge-mode-default\n  configs:\n    -\n        receivers:\n            nop:\n            nop/myreceiver:\n\n        processors:\n            nop:\n            nop/myprocessor:\n\n        exporters:\n            nop:\n            nop/myexporter:\n\n        extensions:\n            nop:\n            nop/myextension:\n\n        service:\n            extensions: [nop]\n            pipelines:\n                traces:\n                    receivers: [nop]\n                    processors: [nop]\n                    exporters: [nop]\n    -\n        receivers:\n            nop2:\n\n        exporters:\n            nop2:\n\n        extensions:\n            nop2:\n\n        service:\n            extensions: [nop2]\n            pipelines:\n                traces:\n                    receivers: [nop2]\n                    processors: [nop2]\n                    exporters: [nop2]\n  expected: \n    receivers:\n        nop2:\n        nop:\n        nop/myreceiver:\n\n    exporters:\n        nop2:\n        nop:\n        nop/myexporter:\n\n    processors:\n        nop:\n        nop/myprocessor:\n\n    extensions:\n        nop2:\n        nop:\n        nop/myextension:\n\n    service:\n        extensions: [nop2]\n        pipelines:\n            traces:\n                receivers: [nop2]\n                processors: [nop2]\n                exporters: [nop2]\n- name: merge-mode-append\n  append_paths: [\"service\"]\n  configs:\n    -\n        receivers:\n            nop:\n                key: val\n\n        processors:\n            nop:\n\n        exporters:\n            nop:\n                key: 2\n\n        extensions:\n            nop:\n\n        service:\n            extensions: [nop]\n            pipelines:\n                traces:\n                    receivers: [nop]\n                    processors: [nop]\n                    exporters: [nop]\n    -\n        receivers:\n            nop2:\n\n        exporters:\n            nop2:\n            nop:\n                key: updated_value\n\n        extensions:\n            nop2:\n\n        service:\n            extensions: [nop2]\n            pipelines:\n                traces:\n                    receivers: [nop2]\n                    processors: [nop2]\n                    exporters: [nop2]\n  expected: \n    receivers:\n        nop2:\n        nop:\n            key: val\n\n    exporters:\n        nop2:\n        nop:\n            key: updated_value\n\n    processors:\n        nop:\n\n    extensions:\n        nop2:\n        nop:\n\n    service:\n        extensions: [nop2]\n        pipelines:\n            traces:\n                receivers: [nop2]\n                processors: [nop2]\n                exporters: [nop2]\n- name: merge-mode-append-override-old-values\n  append_paths: [\"service\"]\n  configs:\n    -\n        receivers:\n            nop:\n                key1: \"value\"\n                key2: 1\n\n        processors:\n            nop:\n\n        exporters:\n            nop:\n\n        extensions:\n            nop:\n            ext:\n                key: 1\n\n        service:\n            extensions: [nop, ext]\n            pipelines:\n                traces:\n                    receivers: [nop]\n                    processors: [nop]\n                    exporters: [nop]\n    -\n        receivers:\n            nop2:\n\n        exporters:\n            nop2:\n\n        extensions:\n            ext:\n                key: 2\n\n        service:\n            extensions: [ext]\n            pipelines:\n                traces:\n                    receivers: [nop2]\n                    exporters: [nop2]\n  expected: \n    receivers:\n        nop:\n            key1: \"value\"\n            key2: 1\n        nop2:\n\n    exporters:\n        nop2:\n        nop:\n\n    processors:\n        nop:\n\n    extensions:\n        nop:\n        ext:\n            key: 2\n\n    service:\n        extensions: [ext]\n        pipelines:\n            traces:\n                receivers: [nop2]\n                processors: [nop]\n                exporters: [nop2]\n"
  },
  {
    "path": "confmap/testdata/merge-append-scenarios.yaml",
    "content": "- name: merge-mode-default\n  configs:\n    -\n        receivers:\n            nop:\n            nop/myreceiver:\n\n        processors:\n            nop:\n            nop/myprocessor:\n\n        exporters:\n            nop:\n            nop/myexporter:\n\n        extensions:\n            nop:\n            nop/myextension:\n\n        service:\n            extensions: [nop]\n            pipelines:\n                traces:\n                    receivers: [nop]\n                    processors: [nop]\n                    exporters: [nop]\n    -\n        receivers:\n            nop2:\n\n        exporters:\n            nop2:\n\n        extensions:\n            nop2:\n\n        service:\n            extensions: [nop2]\n            pipelines:\n                traces:\n                    receivers: [nop2]\n                    processors: [nop2]\n                    exporters: [nop2]\n  expected: \n    receivers:\n        nop2:\n        nop:\n        nop/myreceiver:\n\n    exporters:\n        nop2:\n        nop:\n        nop/myexporter:\n\n    processors:\n        nop:\n        nop/myprocessor:\n\n    extensions:\n        nop2:\n        nop:\n        nop/myextension:\n\n    service:\n        extensions: [nop, nop2]\n        pipelines:\n            traces:\n                receivers: [nop, nop2]\n                processors: [nop2]\n                exporters: [nop, nop2]\n- name: merge-mode-append\n  configs:\n    -\n        receivers:\n            nop:\n                key: val\n\n        processors:\n            nop:\n\n        exporters:\n            nop:\n                key: 2\n\n        extensions:\n            nop:\n\n        service:\n            extensions: [nop]\n            pipelines:\n                traces:\n                    receivers: [nop]\n                    processors: [nop]\n                    exporters: [nop]\n    -\n        receivers:\n            nop2:\n\n        exporters:\n            nop2:\n            nop:\n                key: updated_value\n\n        extensions:\n            nop2:\n\n        service:\n            extensions: [nop2]\n            pipelines:\n                traces:\n                    receivers: [nop2]\n                    processors: [nop2]\n                    exporters: [nop2]\n  expected: \n    receivers:\n        nop2:\n        nop:\n            key: val\n\n    exporters:\n        nop2:\n        nop:\n            key: updated_value\n\n    processors:\n        nop:\n\n    extensions:\n        nop2:\n        nop:\n\n    service:\n        extensions: [nop, nop2]\n        pipelines:\n            traces:\n                receivers: [nop, nop2]\n                processors: [nop2]\n                exporters: [nop, nop2]\n- name: merge-mode-append-override-old-values\n  configs:\n    -\n        receivers:\n            nop:\n                key1: \"value\"\n                key2: 1\n\n        processors:\n            nop:\n\n        exporters:\n            nop:\n\n        extensions:\n            nop:\n            ext:\n                key: 1\n\n        service:\n            extensions: [nop, ext]\n            pipelines:\n                traces:\n                    receivers: [nop]\n                    processors: [nop]\n                    exporters: [nop]\n    -\n        receivers:\n            nop2:\n\n        exporters:\n            nop2:\n\n        extensions:\n            ext:\n                key: 2\n\n        service:\n            extensions: [ext]\n            pipelines:\n                traces:\n                    receivers: [nop2]\n                    exporters: [nop2]\n  expected: \n    receivers:\n        nop:\n            key1: \"value\"\n            key2: 1\n        nop2:\n\n    exporters:\n        nop2:\n        nop:\n\n    processors:\n        nop:\n\n    extensions:\n        nop:\n        ext:\n            key: 2\n\n    service:\n        extensions: [nop, ext]\n        pipelines:\n            traces:\n                receivers: [nop, nop2]\n                processors: [nop]\n                exporters: [nop, nop2]\n- name: merge-mode-append-name-aware\n  configs:\n    -\n        receivers:\n            nop:\n\n        exporters:\n            nop:\n\n        extensions:\n            nop:\n            ext:\n            ext2: \n\n        service:\n            extensions: [nop, ext, ext2]\n            pipelines:\n                traces:\n                    receivers: [nop]\n                    exporters: [nop]\n    -\n        receivers:\n            nop:\n\n        exporters:\n            nop:\n\n        extensions:\n            nop:\n                key: 1\n            ext3:\n\n        service:\n            extensions: [nop, ext3]\n            pipelines:\n                traces:\n                    receivers: [nop]\n                    exporters: [nop]\n  expected: \n    receivers:\n        nop:\n\n    exporters:\n        nop:\n\n    extensions:\n        nop:\n            key: 1\n        ext:\n        ext2:\n        ext3:\n\n    service:\n        extensions: [nop, ext, ext2, ext3]\n        pipelines:\n            traces:\n                receivers: [nop]\n                exporters: [nop]\n- name: merge-mode-append-multiple\n  configs:\n    -\n        receivers:\n            nop:\n\n        exporters:\n            nop:\n\n        extensions:\n            nop:\n\n        service:\n            extensions: [nop]\n            pipelines:\n                traces:\n                    receivers: [nop]\n                    exporters: [nop]\n    -\n        receivers:\n            nop2:\n\n        exporters:\n            nop2:\n\n        extensions:\n            nop2:\n\n        service:\n            extensions: [nop2]\n            pipelines:\n                traces:\n                    receivers: [nop2]\n                    exporters: [nop2]\n    -\n        receivers:\n            nop3:\n\n        exporters:\n            nop3:\n\n        extensions:\n            nop3:\n\n        service:\n            extensions: [nop3]\n            pipelines:\n                traces:\n                    receivers: [nop3]\n                    exporters: [nop3]\n  expected: \n    receivers:\n        nop:\n        nop2:\n        nop3:\n\n    exporters:\n        nop:\n        nop2:\n        nop3:\n\n    extensions:\n        nop:\n        nop2:\n        nop3:\n\n    service:\n        extensions: [nop, nop2, nop3]\n        pipelines:\n            traces:\n                receivers: [nop, nop2, nop3]\n                exporters: [nop, nop2, nop3]\n- name: merge-mode-append-processor-service\n  configs:\n    -\n        receivers:\n            nop:\n\n        exporters:\n            nop:\n\n        extensions:\n            nop:\n        processors:\n            processor:\n                path: [path]\n        service:\n            extensions: [nop]\n            pipelines:\n                traces:\n                    receivers: [nop]\n                    processors: [processor]\n                    exporters: [nop]\n    -\n        receivers:\n            nop2:\n\n        exporters:\n            nop2:\n\n        extensions:\n            nop2:\n        processors:\n            processor:\n                path: [path2]\n\n        service:\n            extensions: [nop2]\n            pipelines:\n                traces:\n                    receivers: [nop2]\n                    processors: [processor]\n                    exporters: [nop2]\n  expected: \n    receivers:\n        nop:\n        nop2:\n\n    exporters:\n        nop:\n        nop2:\n\n    extensions:\n        nop:\n        nop2:\n    processors:\n        processor:\n            path: [path2]\n\n    service:\n        extensions: [nop, nop2]\n        pipelines:\n            traces:\n                receivers: [nop, nop2]\n                processors: [processor]\n                exporters: [nop, nop2]\n- name: merge-mode-append-entire-config\n  configs:\n    -\n        receivers:\n            nop:\n\n        exporters:\n            nop:\n\n        extensions:\n            nop:\n        processors:\n            processor:\n                path: [path]\n        service:\n            extensions: [nop]\n            pipelines:\n                traces:\n                    receivers: [nop]\n                    processors: [processor]\n                    exporters: [nop]\n    -\n        receivers:\n            nop2:\n\n        exporters:\n            nop2:\n\n        extensions:\n            nop2:\n        processors:\n            processor:\n                path: [path2]\n\n        service:\n            extensions: [nop2]\n            pipelines:\n                traces:\n                    receivers: [nop2]\n                    processors: [processor]\n                    exporters: [nop2]\n    -\n        receivers:\n            nop3:\n\n        exporters:\n            nop3:\n\n        extensions:\n            nop3:\n        processors:\n            processor:\n                path: [path3]\n            processor2:\n\n        service:\n            extensions: [nop3]\n            pipelines:\n                traces:\n                    receivers: [nop3]\n                    processors: [processor, processor2]\n                    exporters: [nop3]\n  expected: \n    receivers:\n        nop:\n        nop2:\n        nop3:\n\n    exporters:\n        nop:\n        nop2:\n        nop3:\n\n    extensions:\n        nop:\n        nop2:\n        nop3:\n\n    processors:\n        processor:\n            path: [path3]\n        processor2:\n\n    service:\n        extensions: [nop, nop2, nop3]\n        pipelines:\n            traces:\n                receivers: [nop, nop2, nop3]\n                processors: [processor, processor2]\n                exporters: [nop, nop2, nop3]\n- name: merge-mode-append-different-kinds\n  configs:\n    -\n        receivers:\n            nop:\n                key: val\n\n        processors:\n            nop:\n\n        exporters:\n            nop:\n                key: 2\n\n        extensions:\n            nop:\n\n        service:\n            extensions: [nop]\n            pipelines:\n                traces:\n                    receivers: [nop]\n                    processors: [nop]\n                    exporters: [nop]\n    -\n        receivers:\n            nop:\n                key: 1.2\n  expected: \n    receivers:\n        nop:\n            key: 1.2\n\n    processors:\n        nop:\n\n    exporters:\n        nop:\n            key: 2\n\n    extensions:\n        nop:\n\n    service:\n        extensions: [nop]\n        pipelines:\n            traces:\n                receivers: [nop]\n                processors: [nop]\n                exporters: [nop]\n- name: merge-mode-multiple-pipelines\n  configs:\n    -\n        receivers:\n            nop:\n                key: val\n\n        processors:\n            nop:\n                key: val\n\n        exporters:\n            nop:\n                key: 2\n\n        extensions:\n            nop:\n\n        service:\n            extensions: [nop]\n            pipelines:\n                traces:\n                    receivers: [nop]\n                    processors: [attributes/example]\n                    exporters: [nop]\n                logs:\n                    receivers: [nop]\n                    processors: [attributes/example]\n                    exporters: [nop]\n    -\n        receivers:\n            nop1:\n                key: val\n\n        processors:\n            nop1:\n                key: val\n\n        exporters:\n            nop1:\n                key: 2\n\n        extensions:\n            nop1:\n\n        service:\n            extensions: [nop1]\n            pipelines:\n                traces:\n                    receivers: [nop1]\n                    processors: [nop1]\n                    exporters: [nop1]\n                logs:\n                    receivers: [nop1]\n                    processors: [nop1]\n                    exporters: [nop1]\n  expected: \n    receivers:\n        nop:\n            key: val\n        nop1:\n            key: val\n\n    processors:\n        nop:\n            key: val\n        nop1:\n            key: val\n\n    exporters:\n        nop:\n            key: 2\n        nop1:\n            key: 2\n\n    extensions:\n        nop:\n        nop1:\n\n    service:\n        extensions: [nop, nop1]\n        pipelines:\n            traces:\n                receivers: [nop, nop1]\n                processors: [nop1]\n                exporters: [nop, nop1]\n            logs:\n                receivers: [nop, nop1]\n                processors: [nop1]\n                exporters: [nop, nop1]\n- name: merge-mode-map\n  configs:\n    -\n        processors:\n            resource:\n                attributes:\n                - key: deployment.region\n                  value: \"nl\"\n                  action: upsert\n    -\n        processors:\n            resource:\n                attributes:\n                - key: app\n                  value: \"foo\"\n                  action: upsert\n\n  expected: \n    processors:\n        resource:\n            attributes:\n            # TODO: once merge append mode is configurable, comment this out.\n            # - key: deployment.region\n            #   value: \"nl\"\n            #   action: upsert\n            - key: app\n              value: \"foo\"\n              action: upsert\n"
  },
  {
    "path": "confmap/xconfmap/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "confmap/xconfmap/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xconfmap // import \"go.opentelemetry.io/collector/confmap/xconfmap\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"reflect\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/internal\"\n)\n\n// As interface types are only used for static typing, a common idiom to find the reflection Type\n// for an interface type Foo is to use a *Foo value.\nvar configValidatorType = reflect.TypeFor[Validator]()\n\n// Validator defines an optional interface for configurations to implement to do validation.\ntype Validator interface {\n\t// Validate the configuration and returns an error if invalid.\n\tValidate() error\n}\n\n// Validate validates a config, by doing this:\n//   - Call Validate on the config itself if the config implements ConfigValidator.\nfunc Validate(cfg any) error {\n\tvar err error\n\n\tfor _, validationErr := range validate(reflect.ValueOf(cfg)) {\n\t\terr = errors.Join(err, validationErr)\n\t}\n\n\treturn err\n}\n\ntype pathError struct {\n\terr  error\n\tpath []string\n}\n\nfunc (pe pathError) Error() string {\n\tif len(pe.path) > 0 {\n\t\tvar path string\n\t\tsb := strings.Builder{}\n\n\t\t_, _ = sb.WriteString(pe.path[len(pe.path)-1])\n\t\tfor i := len(pe.path) - 2; i >= 0; i-- {\n\t\t\t_, _ = sb.WriteString(confmap.KeyDelimiter)\n\t\t\t_, _ = sb.WriteString(pe.path[i])\n\t\t}\n\t\tpath = sb.String()\n\n\t\treturn fmt.Sprintf(\"%s: %s\", path, pe.err)\n\t}\n\n\treturn pe.err.Error()\n}\n\nfunc (pe pathError) Unwrap() error {\n\treturn pe.err\n}\n\nfunc validate(v reflect.Value) []pathError {\n\terrs := []pathError{}\n\t// Validate the value itself.\n\tswitch v.Kind() {\n\tcase reflect.Invalid:\n\t\treturn nil\n\tcase reflect.Ptr, reflect.Interface:\n\t\treturn validate(v.Elem())\n\tcase reflect.Struct:\n\t\terr := callValidateIfPossible(v)\n\t\tif err != nil {\n\t\t\terrs = append(errs, pathError{err: err})\n\t\t}\n\n\t\t// Reflect on the pointed data and check each of its fields.\n\t\tfor i := 0; i < v.NumField(); i++ {\n\t\t\tif !v.Type().Field(i).IsExported() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tfield := v.Type().Field(i)\n\t\t\tpath := fieldName(field)\n\n\t\t\tsubpathErrs := validate(v.Field(i))\n\t\t\tfor _, err := range subpathErrs {\n\t\t\t\terrs = append(errs, pathError{\n\t\t\t\t\terr:  err.err,\n\t\t\t\t\tpath: append(err.path, path),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\treturn errs\n\tcase reflect.Slice, reflect.Array:\n\t\terr := callValidateIfPossible(v)\n\t\tif err != nil {\n\t\t\terrs = append(errs, pathError{err: err})\n\t\t}\n\n\t\t// Reflect on the pointed data and check each of its fields.\n\t\tfor i := 0; i < v.Len(); i++ {\n\t\t\tsubPathErrs := validate(v.Index(i))\n\n\t\t\tfor _, err := range subPathErrs {\n\t\t\t\terrs = append(errs, pathError{\n\t\t\t\t\terr:  err.err,\n\t\t\t\t\tpath: append(err.path, strconv.Itoa(i)),\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\treturn errs\n\tcase reflect.Map:\n\t\terr := callValidateIfPossible(v)\n\t\tif err != nil {\n\t\t\terrs = append(errs, pathError{err: err})\n\t\t}\n\n\t\titer := v.MapRange()\n\t\tfor iter.Next() {\n\t\t\tkeyErrs := validate(iter.Key())\n\t\t\tvalueErrs := validate(iter.Value())\n\t\t\tkey := stringifyMapKey(iter.Key())\n\n\t\t\tfor _, err := range keyErrs {\n\t\t\t\terrs = append(errs, pathError{err: err.err, path: append(err.path, key)})\n\t\t\t}\n\n\t\t\tfor _, err := range valueErrs {\n\t\t\t\terrs = append(errs, pathError{err: err.err, path: append(err.path, key)})\n\t\t\t}\n\t\t}\n\t\treturn errs\n\tdefault:\n\t\terr := callValidateIfPossible(v)\n\t\tif err != nil {\n\t\t\treturn []pathError{{err: err}}\n\t\t}\n\n\t\treturn nil\n\t}\n}\n\nfunc callValidateIfPossible(v reflect.Value) error {\n\t// If the value type implements ConfigValidator just call Validate\n\tif v.Type().Implements(configValidatorType) {\n\t\treturn v.Interface().(Validator).Validate()\n\t}\n\n\t// If the pointer type implements ConfigValidator call Validate on the pointer to the current value.\n\tif reflect.PointerTo(v.Type()).Implements(configValidatorType) {\n\t\t// If not addressable, then create a new *V pointer and set the value to current v.\n\t\tif !v.CanAddr() {\n\t\t\tpv := reflect.New(reflect.PointerTo(v.Type()).Elem())\n\t\t\tpv.Elem().Set(v)\n\t\t\tv = pv.Elem()\n\t\t}\n\t\treturn v.Addr().Interface().(Validator).Validate()\n\t}\n\n\treturn nil\n}\n\nfunc fieldName(field reflect.StructField) string {\n\tvar fieldName string\n\tif tag, ok := field.Tag.Lookup(confmap.MapstructureTag); ok {\n\t\ttags := strings.Split(tag, \",\")\n\t\tif len(tags) > 0 {\n\t\t\tfieldName = tags[0]\n\t\t}\n\t}\n\t// Even if the mapstructure tag exists, the field name may not\n\t// be available, so set it if it is still blank.\n\tif fieldName == \"\" {\n\t\tfieldName = strings.ToLower(field.Name)\n\t}\n\n\treturn fieldName\n}\n\nfunc stringifyMapKey(val reflect.Value) string {\n\tswitch v := val.Interface().(type) {\n\tcase string:\n\t\treturn v\n\tcase fmt.Stringer:\n\t\treturn v.String()\n\tdefault:\n\t\tswitch val.Kind() {\n\t\tcase reflect.Ptr, reflect.Interface, reflect.Struct, reflect.Slice, reflect.Array, reflect.Map:\n\t\t\treturn fmt.Sprintf(\"[%T key]\", val.Interface())\n\t\tdefault:\n\t\t\treturn fmt.Sprintf(\"%v\", val.Interface())\n\t\t}\n\t}\n}\n\n// WithForceUnmarshaler sets an option to run a top-level Unmarshal method,\n// even if the Conf being unmarshaled is already a parameter from an Unmarshal method.\n// To avoid infinite recursion, this should only be used when unmarshaling into\n// a different type from the current Unmarshaler.\n// For instance, this should be used in wrapper types such as configoptional.Optional\n// to ensure the inner type's Unmarshal method is called.\nfunc WithForceUnmarshaler() confmap.UnmarshalOption {\n\treturn internal.WithForceUnmarshaler()\n}\n"
  },
  {
    "path": "confmap/xconfmap/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xconfmap\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\ntype configChildStruct struct {\n\tChild    errValidateConfig\n\tChildPtr *errValidateConfig\n}\n\ntype configChildSlice struct {\n\tChild    []errValidateConfig\n\tChildPtr []*errValidateConfig\n}\n\ntype configChildMapValue struct {\n\tChild    map[string]errValidateConfig\n\tChildPtr map[string]*errValidateConfig\n}\n\ntype configChildMapKey struct {\n\tChild    map[errType]string\n\tChildPtr map[*errType]string\n}\n\ntype configChildTypeDef struct {\n\tChild    errType\n\tChildPtr *errType\n}\n\ntype config any\n\ntype configChildInterface struct {\n\tChild config\n}\n\ntype errValidateConfig struct {\n\terr error\n}\n\nfunc (e *errValidateConfig) Validate() error {\n\treturn e.err\n}\n\ntype errType string\n\nfunc (e errType) Validate() error {\n\tif e == \"\" {\n\t\treturn nil\n\t}\n\treturn errors.New(string(e))\n}\n\nfunc newErrType(etStr string) *errType {\n\tet := errType(etStr)\n\treturn &et\n}\n\ntype errMapType map[string]string\n\nfunc (e errMapType) Validate() error {\n\treturn errors.New(e[\"err\"])\n}\n\ntype structKey struct {\n\tk string\n\te error\n}\n\nfunc (s structKey) String() string {\n\treturn s.k\n}\n\nfunc (s structKey) Validate() error {\n\treturn s.e\n}\n\ntype configChildMapCustomKey struct {\n\tChild map[structKey]errValidateConfig\n}\n\nfunc newErrMapType() *errMapType {\n\tet := errMapType(nil)\n\treturn &et\n}\n\ntype configMapstructure struct {\n\tValid  *errValidateConfig `mapstructure:\"validtag,omitempty\"`\n\tNoData *errValidateConfig `mapstructure:\"\"`\n\tNoName *errValidateConfig `mapstructure:\",remain\"`\n}\n\ntype configDeeplyNested struct {\n\tMapKeyChild   map[configChildStruct]string\n\tMapValueChild map[string]configChildStruct\n\tSliceChild    []configChildSlice\n\tMapIntKey     map[int]errValidateConfig\n\tMapFloatKey   map[float64]errValidateConfig\n}\n\ntype sliceTypeAlias []configChildSlice\n\nfunc (sliceTypeAlias) Validate() error {\n\treturn errors.New(\"sliceTypeAlias error\")\n}\n\nfunc TestValidateConfig(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tcfg      any\n\t\texpected error\n\t}{\n\t\t{\n\t\t\tname:     \"struct\",\n\t\t\tcfg:      errValidateConfig{err: errors.New(\"struct\")},\n\t\t\texpected: errors.New(\"struct\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"pointer struct\",\n\t\t\tcfg:      &errValidateConfig{err: errors.New(\"pointer struct\")},\n\t\t\texpected: errors.New(\"pointer struct\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"type\",\n\t\t\tcfg:      errType(\"type\"),\n\t\t\texpected: errors.New(\"type\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"pointer child\",\n\t\t\tcfg:      newErrType(\"pointer type\"),\n\t\t\texpected: errors.New(\"pointer type\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"child interface with nil\",\n\t\t\tcfg:      configChildInterface{},\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tname:     \"pointer to child interface with nil\",\n\t\t\tcfg:      &configChildInterface{},\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tname:     \"nil\",\n\t\t\tcfg:      nil,\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tname:     \"nil map type\",\n\t\t\tcfg:      errMapType(nil),\n\t\t\texpected: errors.New(\"\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"nil pointer map type\",\n\t\t\tcfg:      newErrMapType(),\n\t\t\texpected: errors.New(\"\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"child struct\",\n\t\t\tcfg:      configChildStruct{Child: errValidateConfig{err: errors.New(\"child struct\")}},\n\t\t\texpected: errors.New(\"child: child struct\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"pointer child struct\",\n\t\t\tcfg:      &configChildStruct{Child: errValidateConfig{err: errors.New(\"pointer child struct\")}},\n\t\t\texpected: errors.New(\"child: pointer child struct\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"child struct pointer\",\n\t\t\tcfg:      &configChildStruct{ChildPtr: &errValidateConfig{err: errors.New(\"child struct pointer\")}},\n\t\t\texpected: errors.New(\"childptr: child struct pointer\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"child interface\",\n\t\t\tcfg:      configChildInterface{Child: errValidateConfig{err: errors.New(\"child interface\")}},\n\t\t\texpected: errors.New(\"child: child interface\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"pointer to child interface\",\n\t\t\tcfg:      &configChildInterface{Child: errValidateConfig{err: errors.New(\"pointer to child interface\")}},\n\t\t\texpected: errors.New(\"child: pointer to child interface\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"child interface with pointer\",\n\t\t\tcfg:      configChildInterface{Child: &errValidateConfig{err: errors.New(\"child interface with pointer\")}},\n\t\t\texpected: errors.New(\"child: child interface with pointer\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"pointer to child interface with pointer\",\n\t\t\tcfg:      &configChildInterface{Child: &errValidateConfig{err: errors.New(\"pointer to child interface with pointer\")}},\n\t\t\texpected: errors.New(\"child: pointer to child interface with pointer\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"child slice\",\n\t\t\tcfg:      configChildSlice{Child: []errValidateConfig{{}, {err: errors.New(\"child slice\")}}},\n\t\t\texpected: errors.New(\"child::1: child slice\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"pointer child slice\",\n\t\t\tcfg:      &configChildSlice{Child: []errValidateConfig{{}, {err: errors.New(\"pointer child slice\")}}},\n\t\t\texpected: errors.New(\"child::1: pointer child slice\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"child slice pointer\",\n\t\t\tcfg:      &configChildSlice{ChildPtr: []*errValidateConfig{{}, {err: errors.New(\"child slice pointer\")}}},\n\t\t\texpected: errors.New(\"childptr::1: child slice pointer\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"child map value\",\n\t\t\tcfg:      configChildMapValue{Child: map[string]errValidateConfig{\"test\": {err: errors.New(\"child map\")}}},\n\t\t\texpected: errors.New(\"child::test: child map\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"pointer child map value\",\n\t\t\tcfg:      &configChildMapValue{Child: map[string]errValidateConfig{\"test\": {err: errors.New(\"pointer child map\")}}},\n\t\t\texpected: errors.New(\"child::test: pointer child map\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"child map value pointer\",\n\t\t\tcfg:      &configChildMapValue{ChildPtr: map[string]*errValidateConfig{\"test\": {err: errors.New(\"child map pointer\")}}},\n\t\t\texpected: errors.New(\"childptr::test: child map pointer\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"child map key\",\n\t\t\tcfg:      configChildMapKey{Child: map[errType]string{\"child_map_key\": \"\"}},\n\t\t\texpected: errors.New(\"child::child_map_key: child_map_key\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"pointer child map key\",\n\t\t\tcfg:      &configChildMapKey{Child: map[errType]string{\"pointer_child_map_key\": \"\"}},\n\t\t\texpected: errors.New(\"child::pointer_child_map_key: pointer_child_map_key\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"child map key pointer\",\n\t\t\tcfg:      &configChildMapKey{ChildPtr: map[*errType]string{newErrType(\"child map key pointer\"): \"\"}},\n\t\t\texpected: errors.New(\"childptr::[*xconfmap.errType key]: child map key pointer\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"map with stringified non-string key type\",\n\t\t\tcfg:      &configChildMapCustomKey{Child: map[structKey]errValidateConfig{{k: \"struct_key\", e: errors.New(\"custom key error\")}: {err: errors.New(\"value error\")}}},\n\t\t\texpected: errors.New(\"child::struct_key: custom key error\\nchild::struct_key: value error\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"child type\",\n\t\t\tcfg:      configChildTypeDef{Child: \"child type\"},\n\t\t\texpected: errors.New(\"child: child type\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"pointer child type\",\n\t\t\tcfg:      &configChildTypeDef{Child: \"pointer child type\"},\n\t\t\texpected: errors.New(\"child: pointer child type\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"child type pointer\",\n\t\t\tcfg:      &configChildTypeDef{ChildPtr: newErrType(\"child type pointer\")},\n\t\t\texpected: errors.New(\"childptr: child type pointer\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"valid mapstructure tag\",\n\t\t\tcfg:      configMapstructure{Valid: &errValidateConfig{errors.New(\"test\")}},\n\t\t\texpected: errors.New(\"validtag: test\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"zero-length mapstructure tag\",\n\t\t\tcfg:      configMapstructure{NoData: &errValidateConfig{errors.New(\"test\")}},\n\t\t\texpected: errors.New(\"nodata: test\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"no field name in mapstructure tag\",\n\t\t\tcfg:      configMapstructure{NoName: &errValidateConfig{errors.New(\"test\")}},\n\t\t\texpected: errors.New(\"noname: test\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"nested map key error\",\n\t\t\tcfg:      configDeeplyNested{MapKeyChild: map[configChildStruct]string{{Child: errValidateConfig{err: errors.New(\"child key error\")}}: \"val\"}},\n\t\t\texpected: errors.New(\"mapkeychild::[xconfmap.configChildStruct key]::child: child key error\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"nested map value error\",\n\t\t\tcfg:      configDeeplyNested{MapValueChild: map[string]configChildStruct{\"key\": {Child: errValidateConfig{err: errors.New(\"child key error\")}}}},\n\t\t\texpected: errors.New(\"mapvaluechild::key::child: child key error\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"nested slice value error\",\n\t\t\tcfg:      configDeeplyNested{SliceChild: []configChildSlice{{Child: []errValidateConfig{{err: errors.New(\"child key error\")}}}}},\n\t\t\texpected: errors.New(\"slicechild::0::child::0: child key error\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"nested map with int key\",\n\t\t\tcfg:      configDeeplyNested{MapIntKey: map[int]errValidateConfig{1: {err: errors.New(\"int key error\")}}},\n\t\t\texpected: errors.New(\"mapintkey::1: int key error\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"nested map with float key\",\n\t\t\tcfg:      configDeeplyNested{MapFloatKey: map[float64]errValidateConfig{1.2: {err: errors.New(\"float key error\")}}},\n\t\t\texpected: errors.New(\"mapfloatkey::1.2: float key error\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"slice type alias\",\n\t\t\tcfg:      sliceTypeAlias{},\n\t\t\texpected: errors.New(\"sliceTypeAlias error\"),\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := Validate(tt.cfg)\n\n\t\t\tif tt.expected != nil {\n\t\t\t\tassert.EqualError(t, err, tt.expected.Error())\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "confmap/xconfmap/confmap.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xconfmap // import \"go.opentelemetry.io/collector/confmap/xconfmap\"\n\nimport (\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/internal\"\n)\n\n// ExpandedValue represents a configuration value that has been expanded from a template\n// (e.g., environment variable substitution). It contains both the parsed value and the\n// original string representation.\n//\n// This type is exposed to allow working with configuration values returned by ToStringMapRaw.\ntype ExpandedValue = internal.ExpandedValue\n\n// ToStringMapRaw returns the raw configuration map without sanitization.\n// This is an experimental API and may change or be removed in future versions.\n// The returned map may change at any time without prior notice.\n//\n// Unlike confmap.Conf.ToStringMap(), this function does not sanitize the map\n// by removing expandedValue references. This allows for configmap manipulation\n// without destroying internal types.\nfunc ToStringMapRaw(conf *confmap.Conf) map[string]any {\n\treturn internal.ToStringMapRaw(conf)\n}\n"
  },
  {
    "path": "confmap/xconfmap/example_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xconfmap\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n)\n\n// Config represents the receiver config settings within the collector's config.yaml\ntype Config struct {\n\tInterval       time.Duration `mapstructure:\"interval\"`\n\tNumberOfTraces int           `mapstructure:\"number_of_traces\"`\n}\n\n// Validate checks if the receiver configuration is valid\n// this function is automatically called by the collector when it loads the configurations\n// for a component\nfunc (cfg *Config) Validate() error {\n\tif cfg.Interval.Minutes() < 1 {\n\t\treturn errors.New(\"when defined, the interval has to be set to at least 1 minute (1m)\")\n\t}\n\n\tif cfg.NumberOfTraces < 1 {\n\t\treturn errors.New(\"number_of_traces must be greater or equal to 1\")\n\t}\n\treturn nil\n}\n\n// Example usage validated configuration\nfunc Example() {\n\t// invalid number of traces\n\tmyCfg := Config{\n\t\tInterval:       time.Minute,\n\t\tNumberOfTraces: 0,\n\t}\n\terr := myCfg.Validate()\n\tfmt.Println(err)\n\n\t// invalid interval\n\tmyCfg = Config{\n\t\tInterval:       time.Second,\n\t\tNumberOfTraces: 1,\n\t}\n\terr = myCfg.Validate()\n\tfmt.Println(err)\n\n\t// valid config\n\tmyCfg = Config{\n\t\tInterval:       time.Minute,\n\t\tNumberOfTraces: 1,\n\t}\n\terr = myCfg.Validate()\n\tfmt.Println(err)\n\n\t// Output:\n\t// number_of_traces must be greater or equal to 1\n\t// when defined, the interval has to be set to at least 1 minute (1m)\n\t// <nil>\n}\n"
  },
  {
    "path": "confmap/xconfmap/go.mod",
    "content": "module go.opentelemetry.io/collector/confmap/xconfmap\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/confmap => ../\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n"
  },
  {
    "path": "confmap/xconfmap/go.sum",
    "content": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "confmap/xconfmap/metadata.yaml",
    "content": "type: xconfmap\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "connector/Makefile",
    "content": "include ../Makefile.Common\n"
  },
  {
    "path": "connector/README.md",
    "content": "# Connectors\n\nA connector is both an exporter and receiver. As the name suggests a Connector connects\ntwo pipelines: it emits data as an exporter at the end of one pipeline and consumes data\nas a receiver at the start of another pipeline. It may consume and emit data of the same data\ntype, or of different data types. A connector may generate and emit data to summarize the\nconsumed data, or it may simply replicate or route data.\n\n## Supported Data Types\n\nEach type of connector is designed to work with one or more _pairs_ of data types and may only\nbe used to connect pipelines accordingly. (Recall that every pipeline is associated with a single\ndata type, either traces, metrics, or logs.)\n\nFor example, the `count` connector counts traces, metrics, and logs, and reports the counts as a\nmetric. Therefore, it may be used to connect the following types of pipelines.\n\n| [Exporter Pipeline Type] | [Receiver Pipeline Type] |\n| ------------------------ | ------------------------ |\n| traces                   | metrics                  |\n| metrics                  | metrics                  |\n| logs                     | metrics                  |\n\nAnother example, the `router` connector, is useful for routing data onto the appropriate pipeline\nso that it may be processed in distinct ways  and/or exported to an appropriate backend. It does not\nalter the data it consumes in any ways, nor does it produce any additional data. Therefore, it may be\nused to connect the following types of pipelines.\n\n| [Exporter Pipeline Type] | [Receiver Pipeline Type] |\n| ------------------------ | ------------------------ |\n| traces                   | traces                   |\n| metrics                  | metrics                  |\n| logs                     | logs                     |\n\n## Configuration\n\n### Declaration\n\nConnectors are defined within a dedicated `connectors` section at the top level of the collector config.\n\nThe count connector may be used with default settings.\n\n```yaml\nreceivers:\n  foo:\nexporters:\n  bar:\nconnectors:\n  count:\n  router:\n```\n\n### Usage\n\nRecall that a connector _is_ an exporter _and_ a receiver and that each connector\nMUST be used as both, in separate pipelines.\n\n```yaml\nreceivers:\n  foo:\nexporters:\n  bar:\nconnectors:\n  count:\nservice:\n  pipelines:\n    traces:\n      receivers: [foo]\n      exporters: [count]\n    metrics:\n      receivers: [count]\n      exporters: [bar]\n```\n\nConnectors can be used alongside traditional exporters.\n\n```yaml\nreceivers:\n  foo:\nexporters:\n  bar/traces_backend:\n  bar/metrics_backend:\nconnectors:\n  count:\nservice:\n  pipelines:\n    traces:\n      receivers: [foo]\n      exporters: [bar/traces_backend, count]\n    metrics:\n      receivers: [count]\n      exporters: [bar/metrics_backend]\n```\n\nConnectors can be used alongside traditional receivers.\n\n```yaml\nreceivers:\n  foo/traces:\n  foo/metrics:\nexporters:\n  bar:\nconnectors:\n  count:\nservice:\n  pipelines:\n    traces:\n      receivers: [foo/traces]\n      exporters: [count]\n    metrics:\n      receivers: [foo/metrics, count]\n      exporters: [bar]\n```\n\nA connector can be an exporter in multiple pipelines.\n\n```yaml\nreceivers:\n  foo/traces:\n  foo/metrics:\n  foo/logs:\nexporters:\n  bar/traces_backend:\n  bar/metrics_backend:\n  bar/logs_backend:\nconnectors:\n  count:\nservice:\n  pipelines:\n    traces:\n      receivers: [foo/traces]\n      exporters: [bar/traces_backend, count]\n    metrics:\n      receivers: [foo/metrics]\n      exporters: [bar/metrics_backend, count]\n    logs:\n      receivers: [foo/logs]\n      exporters: [bar/logs_backend, count]\n    metrics/counts:\n      receivers: [count]\n      exporters: [bar/metrics_backend]\n```\n\nA connector can be a receiver in multiple pipelines.\n\n```yaml\nreceivers:\n  foo/traces:\n  foo/metrics:\nexporters:\n  bar/traces_backend:\n  bar/metrics_backend:\n  bar/metrics_backend/2:\nconnectors:\n  count:\nservice:\n  pipelines:\n    traces:\n      receivers: [foo/traces]\n      exporters: [bar/traces_backend, count]\n    metrics:\n      receivers: [count]\n      exporters: [bar/metrics_backend]\n    metrics/2:\n      receivers: [count]\n      exporters: [bar/metrics_backend/2]\n```\n\nMultiple connectors can be used in sequence.\n\n```yaml\nreceivers:\n  foo:\nexporters:\n  bar:\nconnectors:\n  count:\n  count/the_counts:\nservice:\n  pipelines:\n    traces:\n      receivers: [foo]\n      exporters: [count]\n    metrics:\n      receivers: [count]\n      exporters: [bar/metrics_backend, count/the_counts]\n    metrics/count_the_counts:\n      receivers: [count/the_counts]\n      exporters: [bar]\n```\n\nA connector can only be used in a pair of pipelines when it supports the combination of\n[Exporter Pipeline Type] and [Receiver Pipeline Type].\n\n```yaml\nreceivers:\n  foo:\nexporters:\n  bar:\nconnectors:\n  count:\nservice:\n  pipelines:\n    traces:\n      receivers: [foo]\n      exporters: [count]\n    logs:\n      receivers: [count] # Invalid. The count connector does not support traces -> logs.\n      exporters: [bar]\n```\n\n#### Exporter Pipeline Type\n\nThe type of pipeline in which a connector is used as an exporter.\n\n#### Receiver Pipeline Type\n\nThe type of pipeline in which the connector is used as a receiver.\n\n[Exporter Pipeline Type]:#exporter-pipeline-type\n[Receiver Pipeline Type]:#receiver-pipeline-type\n"
  },
  {
    "path": "connector/connector.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage connector // import \"go.opentelemetry.io/collector/connector\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector/internal\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\n// A Traces connector acts as an exporter from a traces pipeline and a receiver\n// to one or more traces, metrics, or logs pipelines.\n// Traces feeds a consumer.Traces, consumer.Metrics, or consumer.Logs with data.\n//\n// Examples:\n//   - Traces could be collected in one pipeline and routed to another traces pipeline\n//     based on criteria such as attributes or other content of the trace. The second\n//     pipeline can then process and export the trace to the appropriate backend.\n//   - Traces could be summarized by a metrics connector that emits statistics describing\n//     the number of traces observed.\n//   - Traces could be analyzed by a logs connector that emits events when particular\n//     criteria are met.\ntype Traces interface {\n\tcomponent.Component\n\tconsumer.Traces\n}\n\n// A Metrics connector acts as an exporter from a metrics pipeline and a receiver\n// to one or more traces, metrics, or logs pipelines.\n// Metrics feeds a consumer.Traces, consumer.Metrics, or consumer.Logs with data.\n//\n// Examples:\n//   - Latency between related data points could be modeled and emitted as traces.\n//   - Metrics could be collected in one pipeline and routed to another metrics pipeline\n//     based on criteria such as attributes or other content of the metric. The second\n//     pipeline can then process and export the metric to the appropriate backend.\n//   - Metrics could be analyzed by a logs connector that emits events when particular\n//     criteria are met.\ntype Metrics interface {\n\tcomponent.Component\n\tconsumer.Metrics\n}\n\n// A Logs connector acts as an exporter from a logs pipeline and a receiver\n// to one or more traces, metrics, or logs pipelines.\n// Logs feeds a consumer.Traces, consumer.Metrics, or consumer.Logs with data.\n//\n// Examples:\n//   - Structured logs containing span information could be consumed and emitted as traces.\n//   - Metrics could be extracted from structured logs that contain numeric data.\n//   - Logs could be collected in one pipeline and routed to another logs pipeline\n//     based on criteria such as attributes or other content of the log. The second\n//     pipeline can then process and export the log to the appropriate backend.\ntype Logs interface {\n\tcomponent.Component\n\tconsumer.Logs\n}\n\n// Settings configures Connector creators.\ntype Settings struct {\n\t// ID returns the ID of the component that will be created.\n\tID component.ID\n\n\tcomponent.TelemetrySettings\n\n\t// BuildInfo can be used by components for informational purposes\n\tBuildInfo component.BuildInfo\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// Factory is a factory interface for connectors.\n//\n// This interface cannot be directly implemented. Implementations must\n// use the NewFactory to implement it.\ntype Factory interface {\n\tcomponent.Factory\n\n\t// CreateDefaultConfig creates the default configuration for the Connector.\n\t// This method can be called multiple times depending on the pipeline\n\t// configuration and should not cause side-effects that prevent the creation\n\t// of multiple instances of the Connector.\n\t// The object returned by this method needs to pass the checks implemented by\n\t// 'configtest.CheckConfigStruct'. It is recommended to have these checks in the\n\t// tests of any implementation of the Factory interface.\n\tCreateDefaultConfig() component.Config\n\n\tCreateTracesToTraces(ctx context.Context, set Settings, cfg component.Config, next consumer.Traces) (Traces, error)\n\tCreateTracesToMetrics(ctx context.Context, set Settings, cfg component.Config, next consumer.Metrics) (Traces, error)\n\tCreateTracesToLogs(ctx context.Context, set Settings, cfg component.Config, next consumer.Logs) (Traces, error)\n\n\tCreateMetricsToTraces(ctx context.Context, set Settings, cfg component.Config, next consumer.Traces) (Metrics, error)\n\tCreateMetricsToMetrics(ctx context.Context, set Settings, cfg component.Config, next consumer.Metrics) (Metrics, error)\n\tCreateMetricsToLogs(ctx context.Context, set Settings, cfg component.Config, next consumer.Logs) (Metrics, error)\n\n\tCreateLogsToTraces(ctx context.Context, set Settings, cfg component.Config, next consumer.Traces) (Logs, error)\n\tCreateLogsToMetrics(ctx context.Context, set Settings, cfg component.Config, next consumer.Metrics) (Logs, error)\n\tCreateLogsToLogs(ctx context.Context, set Settings, cfg component.Config, next consumer.Logs) (Logs, error)\n\n\tTracesToTracesStability() component.StabilityLevel\n\tTracesToMetricsStability() component.StabilityLevel\n\tTracesToLogsStability() component.StabilityLevel\n\n\tMetricsToTracesStability() component.StabilityLevel\n\tMetricsToMetricsStability() component.StabilityLevel\n\tMetricsToLogsStability() component.StabilityLevel\n\n\tLogsToTracesStability() component.StabilityLevel\n\tLogsToMetricsStability() component.StabilityLevel\n\tLogsToLogsStability() component.StabilityLevel\n\n\tunexportedFactoryFunc()\n}\n\n// FactoryOption applies changes to Factory.\ntype FactoryOption interface {\n\t// apply applies the option.\n\tapply(o *factory)\n}\n\nvar _ FactoryOption = (*factoryOptionFunc)(nil)\n\n// factoryOptionFunc is an FactoryOption created through a function.\ntype factoryOptionFunc func(*factory)\n\nfunc (f factoryOptionFunc) apply(o *factory) {\n\tf(o)\n}\n\n// CreateTracesToTracesFunc is the equivalent of Factory.CreateTracesToTraces().\ntype CreateTracesToTracesFunc func(context.Context, Settings, component.Config, consumer.Traces) (Traces, error)\n\n// CreateTracesToMetricsFunc is the equivalent of Factory.CreateTracesToMetrics().\ntype CreateTracesToMetricsFunc func(context.Context, Settings, component.Config, consumer.Metrics) (Traces, error)\n\n// CreateTracesToLogsFunc is the equivalent of Factory.CreateTracesToLogs().\ntype CreateTracesToLogsFunc func(context.Context, Settings, component.Config, consumer.Logs) (Traces, error)\n\n// CreateMetricsToTracesFunc is the equivalent of Factory.CreateMetricsToTraces().\ntype CreateMetricsToTracesFunc func(context.Context, Settings, component.Config, consumer.Traces) (Metrics, error)\n\n// CreateMetricsToMetricsFunc is the equivalent of Factory.CreateMetricsToTraces().\ntype CreateMetricsToMetricsFunc func(context.Context, Settings, component.Config, consumer.Metrics) (Metrics, error)\n\n// CreateMetricsToLogsFunc is the equivalent of Factory.CreateMetricsToLogs().\ntype CreateMetricsToLogsFunc func(context.Context, Settings, component.Config, consumer.Logs) (Metrics, error)\n\n// CreateLogsToTracesFunc is the equivalent of Factory.CreateLogsToTraces().\ntype CreateLogsToTracesFunc func(context.Context, Settings, component.Config, consumer.Traces) (Logs, error)\n\n// CreateLogsToMetricsFunc is the equivalent of Factory.CreateLogsToMetrics().\ntype CreateLogsToMetricsFunc func(context.Context, Settings, component.Config, consumer.Metrics) (Logs, error)\n\n// CreateLogsToLogsFunc is the equivalent of Factory.CreateLogsToLogs().\ntype CreateLogsToLogsFunc func(context.Context, Settings, component.Config, consumer.Logs) (Logs, error)\n\n// WithTracesToTraces overrides the default \"error not supported\" implementation for WithTracesToTraces and the default \"undefined\" stability level.\nfunc WithTracesToTraces(createTracesToTraces CreateTracesToTracesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.tracesToTracesStabilityLevel = sl\n\t\to.createTracesToTracesFunc = createTracesToTraces\n\t})\n}\n\n// WithTracesToMetrics overrides the default \"error not supported\" implementation for WithTracesToMetrics and the default \"undefined\" stability level.\nfunc WithTracesToMetrics(createTracesToMetrics CreateTracesToMetricsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.tracesToMetricsStabilityLevel = sl\n\t\to.createTracesToMetricsFunc = createTracesToMetrics\n\t})\n}\n\n// WithTracesToLogs overrides the default \"error not supported\" implementation for WithTracesToLogs and the default \"undefined\" stability level.\nfunc WithTracesToLogs(createTracesToLogs CreateTracesToLogsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.tracesToLogsStabilityLevel = sl\n\t\to.createTracesToLogsFunc = createTracesToLogs\n\t})\n}\n\n// WithMetricsToTraces overrides the default \"error not supported\" implementation for WithMetricsToTraces and the default \"undefined\" stability level.\nfunc WithMetricsToTraces(createMetricsToTraces CreateMetricsToTracesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.metricsToTracesStabilityLevel = sl\n\t\to.createMetricsToTracesFunc = createMetricsToTraces\n\t})\n}\n\n// WithMetricsToMetrics overrides the default \"error not supported\" implementation for WithMetricsToMetrics and the default \"undefined\" stability level.\nfunc WithMetricsToMetrics(createMetricsToMetrics CreateMetricsToMetricsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.metricsToMetricsStabilityLevel = sl\n\t\to.createMetricsToMetricsFunc = createMetricsToMetrics\n\t})\n}\n\n// WithMetricsToLogs overrides the default \"error not supported\" implementation for WithMetricsToLogs and the default \"undefined\" stability level.\nfunc WithMetricsToLogs(createMetricsToLogs CreateMetricsToLogsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.metricsToLogsStabilityLevel = sl\n\t\to.createMetricsToLogsFunc = createMetricsToLogs\n\t})\n}\n\n// WithLogsToTraces overrides the default \"error not supported\" implementation for WithLogsToTraces and the default \"undefined\" stability level.\nfunc WithLogsToTraces(createLogsToTraces CreateLogsToTracesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.logsToTracesStabilityLevel = sl\n\t\to.createLogsToTracesFunc = createLogsToTraces\n\t})\n}\n\n// WithLogsToMetrics overrides the default \"error not supported\" implementation for WithLogsToMetrics and the default \"undefined\" stability level.\nfunc WithLogsToMetrics(createLogsToMetrics CreateLogsToMetricsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.logsToMetricsStabilityLevel = sl\n\t\to.createLogsToMetricsFunc = createLogsToMetrics\n\t})\n}\n\n// WithLogsToLogs overrides the default \"error not supported\" implementation for WithLogsToLogs and the default \"undefined\" stability level.\nfunc WithLogsToLogs(createLogsToLogs CreateLogsToLogsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.logsToLogsStabilityLevel = sl\n\t\to.createLogsToLogsFunc = createLogsToLogs\n\t})\n}\n\n// factory implements the Factory interface.\ntype factory struct {\n\tcfgType component.Type\n\tcomponent.CreateDefaultConfigFunc\n\tcomponentalias.TypeAliasHolder\n\n\tcreateTracesToTracesFunc  CreateTracesToTracesFunc\n\tcreateTracesToMetricsFunc CreateTracesToMetricsFunc\n\tcreateTracesToLogsFunc    CreateTracesToLogsFunc\n\n\tcreateMetricsToTracesFunc  CreateMetricsToTracesFunc\n\tcreateMetricsToMetricsFunc CreateMetricsToMetricsFunc\n\tcreateMetricsToLogsFunc    CreateMetricsToLogsFunc\n\n\tcreateLogsToTracesFunc  CreateLogsToTracesFunc\n\tcreateLogsToMetricsFunc CreateLogsToMetricsFunc\n\tcreateLogsToLogsFunc    CreateLogsToLogsFunc\n\n\ttracesToTracesStabilityLevel  component.StabilityLevel\n\ttracesToMetricsStabilityLevel component.StabilityLevel\n\ttracesToLogsStabilityLevel    component.StabilityLevel\n\n\tmetricsToTracesStabilityLevel  component.StabilityLevel\n\tmetricsToMetricsStabilityLevel component.StabilityLevel\n\tmetricsToLogsStabilityLevel    component.StabilityLevel\n\n\tlogsToTracesStabilityLevel  component.StabilityLevel\n\tlogsToMetricsStabilityLevel component.StabilityLevel\n\tlogsToLogsStabilityLevel    component.StabilityLevel\n}\n\n// Type returns the type of component.\nfunc (f *factory) Type() component.Type {\n\treturn f.cfgType\n}\n\nfunc (f *factory) unexportedFactoryFunc() {}\n\nfunc (f *factory) TracesToTracesStability() component.StabilityLevel {\n\treturn f.tracesToTracesStabilityLevel\n}\n\nfunc (f *factory) TracesToMetricsStability() component.StabilityLevel {\n\treturn f.tracesToMetricsStabilityLevel\n}\n\nfunc (f *factory) TracesToLogsStability() component.StabilityLevel {\n\treturn f.tracesToLogsStabilityLevel\n}\n\nfunc (f *factory) MetricsToTracesStability() component.StabilityLevel {\n\treturn f.metricsToTracesStabilityLevel\n}\n\nfunc (f *factory) MetricsToMetricsStability() component.StabilityLevel {\n\treturn f.metricsToMetricsStabilityLevel\n}\n\nfunc (f *factory) MetricsToLogsStability() component.StabilityLevel {\n\treturn f.metricsToLogsStabilityLevel\n}\n\nfunc (f *factory) LogsToTracesStability() component.StabilityLevel {\n\treturn f.logsToTracesStabilityLevel\n}\n\nfunc (f *factory) LogsToMetricsStability() component.StabilityLevel {\n\treturn f.logsToMetricsStabilityLevel\n}\n\nfunc (f *factory) LogsToLogsStability() component.StabilityLevel {\n\treturn f.logsToLogsStabilityLevel\n}\n\nfunc (f *factory) CreateTracesToTraces(ctx context.Context, set Settings, cfg component.Config, next consumer.Traces) (Traces, error) {\n\tif f.createTracesToTracesFunc == nil {\n\t\treturn nil, internal.ErrDataTypes(set.ID, pipeline.SignalTraces, pipeline.SignalTraces)\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createTracesToTracesFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateTracesToMetrics(ctx context.Context, set Settings, cfg component.Config, next consumer.Metrics) (Traces, error) {\n\tif f.createTracesToMetricsFunc == nil {\n\t\treturn nil, internal.ErrDataTypes(set.ID, pipeline.SignalTraces, pipeline.SignalMetrics)\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createTracesToMetricsFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateTracesToLogs(ctx context.Context, set Settings, cfg component.Config, next consumer.Logs) (Traces, error) {\n\tif f.createTracesToLogsFunc == nil {\n\t\treturn nil, internal.ErrDataTypes(set.ID, pipeline.SignalTraces, pipeline.SignalLogs)\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createTracesToLogsFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateMetricsToTraces(ctx context.Context, set Settings, cfg component.Config, next consumer.Traces) (Metrics, error) {\n\tif f.createMetricsToTracesFunc == nil {\n\t\treturn nil, internal.ErrDataTypes(set.ID, pipeline.SignalMetrics, pipeline.SignalTraces)\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createMetricsToTracesFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateMetricsToMetrics(ctx context.Context, set Settings, cfg component.Config, next consumer.Metrics) (Metrics, error) {\n\tif f.createMetricsToMetricsFunc == nil {\n\t\treturn nil, internal.ErrDataTypes(set.ID, pipeline.SignalMetrics, pipeline.SignalMetrics)\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createMetricsToMetricsFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateMetricsToLogs(ctx context.Context, set Settings, cfg component.Config, next consumer.Logs) (Metrics, error) {\n\tif f.createMetricsToLogsFunc == nil {\n\t\treturn nil, internal.ErrDataTypes(set.ID, pipeline.SignalMetrics, pipeline.SignalLogs)\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createMetricsToLogsFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateLogsToTraces(ctx context.Context, set Settings, cfg component.Config, next consumer.Traces) (Logs, error) {\n\tif f.createLogsToTracesFunc == nil {\n\t\treturn nil, internal.ErrDataTypes(set.ID, pipeline.SignalLogs, pipeline.SignalTraces)\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createLogsToTracesFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateLogsToMetrics(ctx context.Context, set Settings, cfg component.Config, next consumer.Metrics) (Logs, error) {\n\tif f.createLogsToMetricsFunc == nil {\n\t\treturn nil, internal.ErrDataTypes(set.ID, pipeline.SignalLogs, pipeline.SignalMetrics)\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createLogsToMetricsFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateLogsToLogs(ctx context.Context, set Settings, cfg component.Config, next consumer.Logs) (Logs, error) {\n\tif f.createLogsToLogsFunc == nil {\n\t\treturn nil, internal.ErrDataTypes(set.ID, pipeline.SignalLogs, pipeline.SignalLogs)\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createLogsToLogsFunc(ctx, set, cfg, next)\n}\n\n// NewFactory returns a Factory.\nfunc NewFactory(cfgType component.Type, createDefaultConfig component.CreateDefaultConfigFunc, options ...FactoryOption) Factory {\n\tf := &factory{\n\t\tcfgType:                 cfgType,\n\t\tCreateDefaultConfigFunc: createDefaultConfig,\n\t\tTypeAliasHolder:         componentalias.NewTypeAliasHolder(),\n\t}\n\tfor _, opt := range options {\n\t\topt.apply(f)\n\t}\n\treturn f\n}\n"
  },
  {
    "path": "connector/connector_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage connector // import \"go.opentelemetry.io/collector/connector\"\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector/internal\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\nvar (\n\ttestType = component.MustNewType(\"test\")\n\ttestID   = component.MustNewIDWithName(\"test\", \"name\")\n)\n\nfunc TestNewFactoryNoOptions(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tfactory := NewFactory(testType, func() component.Config { return &defaultCfg })\n\tassert.Equal(t, testType, factory.Type())\n\tassert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())\n\n\t_, err := factory.CreateTracesToTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalTraces, pipeline.SignalTraces))\n\t_, err = factory.CreateTracesToMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalTraces, pipeline.SignalMetrics))\n\t_, err = factory.CreateTracesToLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalTraces, pipeline.SignalLogs))\n\n\t_, err = factory.CreateMetricsToTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalMetrics, pipeline.SignalTraces))\n\t_, err = factory.CreateMetricsToMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalMetrics, pipeline.SignalMetrics))\n\t_, err = factory.CreateMetricsToLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalMetrics, pipeline.SignalLogs))\n\n\t_, err = factory.CreateLogsToTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalLogs, pipeline.SignalTraces))\n\t_, err = factory.CreateLogsToMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalLogs, pipeline.SignalMetrics))\n\t_, err = factory.CreateLogsToLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalLogs, pipeline.SignalLogs))\n}\n\nfunc TestNewFactoryWithSameTypes(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tfactory := NewFactory(testType, func() component.Config { return &defaultCfg },\n\t\tWithTracesToTraces(createTracesToTraces, component.StabilityLevelAlpha),\n\t\tWithMetricsToMetrics(createMetricsToMetrics, component.StabilityLevelBeta),\n\t\tWithLogsToLogs(createLogsToLogs, component.StabilityLevelUnmaintained))\n\tassert.Equal(t, testType, factory.Type())\n\tassert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())\n\twrongID := component.MustNewID(\"wrong\")\n\twrongIDErrStr := internal.ErrIDMismatch(wrongID, testType).Error()\n\n\tassert.Equal(t, component.StabilityLevelAlpha, factory.TracesToTracesStability())\n\t_, err := factory.CreateTracesToTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = factory.CreateTracesToTraces(context.Background(), Settings{ID: wrongID}, &defaultCfg, consumertest.NewNop())\n\trequire.ErrorContains(t, err, wrongIDErrStr)\n\n\tassert.Equal(t, component.StabilityLevelBeta, factory.MetricsToMetricsStability())\n\t_, err = factory.CreateMetricsToMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = factory.CreateMetricsToMetrics(context.Background(), Settings{ID: wrongID}, &defaultCfg, consumertest.NewNop())\n\trequire.ErrorContains(t, err, wrongIDErrStr)\n\n\tassert.Equal(t, component.StabilityLevelUnmaintained, factory.LogsToLogsStability())\n\t_, err = factory.CreateLogsToLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = factory.CreateLogsToLogs(context.Background(), Settings{ID: wrongID}, &defaultCfg, consumertest.NewNop())\n\trequire.ErrorContains(t, err, wrongIDErrStr)\n\n\t_, err = factory.CreateTracesToMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalTraces, pipeline.SignalMetrics))\n\t_, err = factory.CreateTracesToLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalTraces, pipeline.SignalLogs))\n\n\t_, err = factory.CreateMetricsToTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalMetrics, pipeline.SignalTraces))\n\t_, err = factory.CreateMetricsToLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalMetrics, pipeline.SignalLogs))\n\n\t_, err = factory.CreateLogsToTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalLogs, pipeline.SignalTraces))\n\t_, err = factory.CreateLogsToMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalLogs, pipeline.SignalMetrics))\n}\n\nfunc TestNewFactoryWithTranslateTypes(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tfactory := NewFactory(testType, func() component.Config { return &defaultCfg },\n\t\tWithTracesToMetrics(createTracesToMetrics, component.StabilityLevelDevelopment),\n\t\tWithTracesToLogs(createTracesToLogs, component.StabilityLevelAlpha),\n\t\tWithMetricsToTraces(createMetricsToTraces, component.StabilityLevelBeta),\n\t\tWithMetricsToLogs(createMetricsToLogs, component.StabilityLevelStable),\n\t\tWithLogsToTraces(createLogsToTraces, component.StabilityLevelDeprecated),\n\t\tWithLogsToMetrics(createLogsToMetrics, component.StabilityLevelUnmaintained))\n\tassert.Equal(t, testType, factory.Type())\n\tassert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())\n\n\t_, err := factory.CreateTracesToTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalTraces, pipeline.SignalTraces))\n\t_, err = factory.CreateMetricsToMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalMetrics, pipeline.SignalMetrics))\n\t_, err = factory.CreateLogsToLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalLogs, pipeline.SignalLogs))\n\n\tassert.Equal(t, component.StabilityLevelDevelopment, factory.TracesToMetricsStability())\n\t_, err = factory.CreateTracesToMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, component.StabilityLevelAlpha, factory.TracesToLogsStability())\n\t_, err = factory.CreateTracesToLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, component.StabilityLevelBeta, factory.MetricsToTracesStability())\n\t_, err = factory.CreateMetricsToTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, component.StabilityLevelStable, factory.MetricsToLogsStability())\n\t_, err = factory.CreateMetricsToLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, component.StabilityLevelDeprecated, factory.LogsToTracesStability())\n\t_, err = factory.CreateLogsToTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, component.StabilityLevelUnmaintained, factory.LogsToMetricsStability())\n\t_, err = factory.CreateLogsToMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.NoError(t, err)\n}\n\nfunc TestNewFactoryWithAllTypes(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tfactory := NewFactory(testType, func() component.Config { return &defaultCfg },\n\t\tWithTracesToTraces(createTracesToTraces, component.StabilityLevelAlpha),\n\t\tWithTracesToMetrics(createTracesToMetrics, component.StabilityLevelDevelopment),\n\t\tWithTracesToLogs(createTracesToLogs, component.StabilityLevelAlpha),\n\t\tWithMetricsToTraces(createMetricsToTraces, component.StabilityLevelBeta),\n\t\tWithMetricsToMetrics(createMetricsToMetrics, component.StabilityLevelBeta),\n\t\tWithMetricsToLogs(createMetricsToLogs, component.StabilityLevelStable),\n\t\tWithLogsToTraces(createLogsToTraces, component.StabilityLevelDeprecated),\n\t\tWithLogsToMetrics(createLogsToMetrics, component.StabilityLevelUnmaintained),\n\t\tWithLogsToLogs(createLogsToLogs, component.StabilityLevelUnmaintained))\n\tassert.Equal(t, testType, factory.Type())\n\tassert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())\n\n\tassert.Equal(t, component.StabilityLevelAlpha, factory.TracesToTracesStability())\n\t_, err := factory.CreateTracesToTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.Equal(t, component.StabilityLevelDevelopment, factory.TracesToMetricsStability())\n\t_, err = factory.CreateTracesToMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.Equal(t, component.StabilityLevelAlpha, factory.TracesToLogsStability())\n\t_, err = factory.CreateTracesToLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, component.StabilityLevelBeta, factory.MetricsToTracesStability())\n\t_, err = factory.CreateMetricsToTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.Equal(t, component.StabilityLevelBeta, factory.MetricsToMetricsStability())\n\t_, err = factory.CreateMetricsToMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.Equal(t, component.StabilityLevelStable, factory.MetricsToLogsStability())\n\t_, err = factory.CreateMetricsToLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, component.StabilityLevelDeprecated, factory.LogsToTracesStability())\n\t_, err = factory.CreateLogsToTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.Equal(t, component.StabilityLevelUnmaintained, factory.LogsToMetricsStability())\n\t_, err = factory.CreateLogsToMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.Equal(t, component.StabilityLevelUnmaintained, factory.LogsToLogsStability())\n\t_, err = factory.CreateLogsToLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.NoError(t, err)\n}\n\nvar nopInstance = &nopConnector{\n\tConsumer: consumertest.NewNop(),\n}\n\n// nopConnector stores consumed traces and metrics for testing purposes.\ntype nopConnector struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumertest.Consumer\n}\n\nfunc createTracesToTraces(context.Context, Settings, component.Config, consumer.Traces) (Traces, error) {\n\treturn nopInstance, nil\n}\n\nfunc createTracesToMetrics(context.Context, Settings, component.Config, consumer.Metrics) (Traces, error) {\n\treturn nopInstance, nil\n}\n\nfunc createTracesToLogs(context.Context, Settings, component.Config, consumer.Logs) (Traces, error) {\n\treturn nopInstance, nil\n}\n\nfunc createMetricsToTraces(context.Context, Settings, component.Config, consumer.Traces) (Metrics, error) {\n\treturn nopInstance, nil\n}\n\nfunc createMetricsToMetrics(context.Context, Settings, component.Config, consumer.Metrics) (Metrics, error) {\n\treturn nopInstance, nil\n}\n\nfunc createMetricsToLogs(context.Context, Settings, component.Config, consumer.Logs) (Metrics, error) {\n\treturn nopInstance, nil\n}\n\nfunc createLogsToTraces(context.Context, Settings, component.Config, consumer.Traces) (Logs, error) {\n\treturn nopInstance, nil\n}\n\nfunc createLogsToMetrics(context.Context, Settings, component.Config, consumer.Metrics) (Logs, error) {\n\treturn nopInstance, nil\n}\n\nfunc createLogsToLogs(context.Context, Settings, component.Config, consumer.Logs) (Logs, error) {\n\treturn nopInstance, nil\n}\n"
  },
  {
    "path": "connector/connectortest/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "connector/connectortest/connector.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage connectortest // import \"go.opentelemetry.io/collector/connector/connectortest\"\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/uuid\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/xconnector\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n)\n\nvar NopType = component.MustNewType(\"nop\")\n\n// NewNopSettings returns a new nop settings for Create* functions with the given type.\nfunc NewNopSettings(typ component.Type) connector.Settings {\n\treturn connector.Settings{\n\t\tID:                component.NewIDWithName(typ, uuid.NewString()),\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t\tBuildInfo:         component.NewDefaultBuildInfo(),\n\t}\n}\n\ntype nopConfig struct{}\n\n// NewNopFactory returns a connector.Factory that constructs nop processors.\nfunc NewNopFactory() connector.Factory {\n\treturn xconnector.NewFactory(\n\t\tNopType,\n\t\tfunc() component.Config {\n\t\t\treturn &nopConfig{}\n\t\t},\n\t\txconnector.WithTracesToTraces(createTracesToTracesConnector, component.StabilityLevelDevelopment),\n\t\txconnector.WithTracesToMetrics(createTracesToMetricsConnector, component.StabilityLevelDevelopment),\n\t\txconnector.WithTracesToLogs(createTracesToLogsConnector, component.StabilityLevelDevelopment),\n\t\txconnector.WithTracesToProfiles(createTracesToProfilesConnector, component.StabilityLevelAlpha),\n\t\txconnector.WithMetricsToTraces(createMetricsToTracesConnector, component.StabilityLevelDevelopment),\n\t\txconnector.WithMetricsToMetrics(createMetricsToMetricsConnector, component.StabilityLevelDevelopment),\n\t\txconnector.WithMetricsToLogs(createMetricsToLogsConnector, component.StabilityLevelDevelopment),\n\t\txconnector.WithMetricsToProfiles(createMetricsToProfilesConnector, component.StabilityLevelAlpha),\n\t\txconnector.WithLogsToTraces(createLogsToTracesConnector, component.StabilityLevelDevelopment),\n\t\txconnector.WithLogsToMetrics(createLogsToMetricsConnector, component.StabilityLevelDevelopment),\n\t\txconnector.WithLogsToLogs(createLogsToLogsConnector, component.StabilityLevelDevelopment),\n\t\txconnector.WithLogsToProfiles(createLogsToProfilesConnector, component.StabilityLevelAlpha),\n\t\txconnector.WithProfilesToTraces(createProfilesToTracesConnector, component.StabilityLevelAlpha),\n\t\txconnector.WithProfilesToMetrics(createProfilesToMetricsConnector, component.StabilityLevelAlpha),\n\t\txconnector.WithProfilesToLogs(createProfilesToLogsConnector, component.StabilityLevelAlpha),\n\t\txconnector.WithProfilesToProfiles(createProfilesToProfilesConnector, component.StabilityLevelAlpha),\n\t)\n}\n\nfunc createTracesToTracesConnector(context.Context, connector.Settings, component.Config, consumer.Traces) (connector.Traces, error) {\n\treturn &nopConnector{Consumer: consumertest.NewNop()}, nil\n}\n\nfunc createTracesToMetricsConnector(context.Context, connector.Settings, component.Config, consumer.Metrics) (connector.Traces, error) {\n\treturn &nopConnector{Consumer: consumertest.NewNop()}, nil\n}\n\nfunc createTracesToLogsConnector(context.Context, connector.Settings, component.Config, consumer.Logs) (connector.Traces, error) {\n\treturn &nopConnector{Consumer: consumertest.NewNop()}, nil\n}\n\nfunc createTracesToProfilesConnector(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (connector.Traces, error) {\n\treturn &nopConnector{Consumer: consumertest.NewNop()}, nil\n}\n\nfunc createMetricsToTracesConnector(context.Context, connector.Settings, component.Config, consumer.Traces) (connector.Metrics, error) {\n\treturn &nopConnector{Consumer: consumertest.NewNop()}, nil\n}\n\nfunc createMetricsToMetricsConnector(context.Context, connector.Settings, component.Config, consumer.Metrics) (connector.Metrics, error) {\n\treturn &nopConnector{Consumer: consumertest.NewNop()}, nil\n}\n\nfunc createMetricsToLogsConnector(context.Context, connector.Settings, component.Config, consumer.Logs) (connector.Metrics, error) {\n\treturn &nopConnector{Consumer: consumertest.NewNop()}, nil\n}\n\nfunc createMetricsToProfilesConnector(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (connector.Metrics, error) {\n\treturn &nopConnector{Consumer: consumertest.NewNop()}, nil\n}\n\nfunc createLogsToTracesConnector(context.Context, connector.Settings, component.Config, consumer.Traces) (connector.Logs, error) {\n\treturn &nopConnector{Consumer: consumertest.NewNop()}, nil\n}\n\nfunc createLogsToMetricsConnector(context.Context, connector.Settings, component.Config, consumer.Metrics) (connector.Logs, error) {\n\treturn &nopConnector{Consumer: consumertest.NewNop()}, nil\n}\n\nfunc createLogsToLogsConnector(context.Context, connector.Settings, component.Config, consumer.Logs) (connector.Logs, error) {\n\treturn &nopConnector{Consumer: consumertest.NewNop()}, nil\n}\n\nfunc createLogsToProfilesConnector(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (connector.Logs, error) {\n\treturn &nopConnector{Consumer: consumertest.NewNop()}, nil\n}\n\nfunc createProfilesToTracesConnector(context.Context, connector.Settings, component.Config, consumer.Traces) (xconnector.Profiles, error) {\n\treturn &nopConnector{Consumer: consumertest.NewNop()}, nil\n}\n\nfunc createProfilesToMetricsConnector(context.Context, connector.Settings, component.Config, consumer.Metrics) (xconnector.Profiles, error) {\n\treturn &nopConnector{Consumer: consumertest.NewNop()}, nil\n}\n\nfunc createProfilesToLogsConnector(context.Context, connector.Settings, component.Config, consumer.Logs) (xconnector.Profiles, error) {\n\treturn &nopConnector{Consumer: consumertest.NewNop()}, nil\n}\n\nfunc createProfilesToProfilesConnector(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (xconnector.Profiles, error) {\n\treturn &nopConnector{Consumer: consumertest.NewNop()}, nil\n}\n\n// nopConnector stores consumed traces and metrics for testing purposes.\ntype nopConnector struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumertest.Consumer\n}\n"
  },
  {
    "path": "connector/connectortest/connector_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage connectortest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/connector/xconnector\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nfunc TestNewNopConnectorFactory(t *testing.T) {\n\tfactory := NewNopFactory()\n\trequire.NotNil(t, factory)\n\tassert.Equal(t, component.MustNewType(\"nop\"), factory.Type())\n\tcfg := factory.CreateDefaultConfig()\n\tassert.Equal(t, &nopConfig{}, cfg)\n\n\ttracesToTraces, err := factory.CreateTracesToTraces(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, tracesToTraces.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, tracesToTraces.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n\tassert.NoError(t, tracesToTraces.Shutdown(context.Background()))\n\n\ttracesToMetrics, err := factory.CreateTracesToMetrics(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, tracesToMetrics.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, tracesToMetrics.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n\tassert.NoError(t, tracesToMetrics.Shutdown(context.Background()))\n\n\ttracesToLogs, err := factory.CreateTracesToLogs(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, tracesToLogs.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, tracesToLogs.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n\tassert.NoError(t, tracesToLogs.Shutdown(context.Background()))\n\n\ttracesToProfiles, err := factory.(xconnector.Factory).CreateTracesToProfiles(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, tracesToProfiles.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, tracesToProfiles.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n\tassert.NoError(t, tracesToProfiles.Shutdown(context.Background()))\n\n\tmetricsToTraces, err := factory.CreateMetricsToTraces(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, metricsToTraces.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, metricsToTraces.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n\tassert.NoError(t, metricsToTraces.Shutdown(context.Background()))\n\n\tmetricsToMetrics, err := factory.CreateMetricsToMetrics(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, metricsToMetrics.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, metricsToMetrics.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n\tassert.NoError(t, metricsToMetrics.Shutdown(context.Background()))\n\n\tmetricsToLogs, err := factory.CreateMetricsToLogs(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, metricsToLogs.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, metricsToLogs.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n\tassert.NoError(t, metricsToLogs.Shutdown(context.Background()))\n\n\tmetricsToProfiles, err := factory.(xconnector.Factory).CreateMetricsToProfiles(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, metricsToProfiles.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, metricsToProfiles.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n\tassert.NoError(t, metricsToProfiles.Shutdown(context.Background()))\n\n\tlogsToTraces, err := factory.CreateLogsToTraces(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, logsToTraces.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, logsToTraces.ConsumeLogs(context.Background(), plog.NewLogs()))\n\tassert.NoError(t, logsToTraces.Shutdown(context.Background()))\n\n\tlogsToMetrics, err := factory.CreateLogsToMetrics(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, logsToMetrics.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, logsToMetrics.ConsumeLogs(context.Background(), plog.NewLogs()))\n\tassert.NoError(t, logsToMetrics.Shutdown(context.Background()))\n\n\tlogsToLogs, err := factory.CreateLogsToLogs(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, logsToLogs.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, logsToLogs.ConsumeLogs(context.Background(), plog.NewLogs()))\n\tassert.NoError(t, logsToLogs.Shutdown(context.Background()))\n\n\tlogsToProfiles, err := factory.(xconnector.Factory).CreateLogsToProfiles(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, logsToProfiles.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, logsToProfiles.ConsumeLogs(context.Background(), plog.NewLogs()))\n\tassert.NoError(t, logsToProfiles.Shutdown(context.Background()))\n\n\tprofilesToTraces, err := factory.(xconnector.Factory).CreateProfilesToTraces(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, profilesToTraces.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, profilesToTraces.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n\tassert.NoError(t, profilesToTraces.Shutdown(context.Background()))\n\n\tprofilesToMetrics, err := factory.(xconnector.Factory).CreateProfilesToMetrics(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, profilesToMetrics.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, profilesToMetrics.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n\tassert.NoError(t, profilesToMetrics.Shutdown(context.Background()))\n\n\tprofilesToLogs, err := factory.(xconnector.Factory).CreateProfilesToProfiles(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, profilesToLogs.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, profilesToLogs.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n\tassert.NoError(t, profilesToLogs.Shutdown(context.Background()))\n\n\tprofilesToProfiles, err := factory.(xconnector.Factory).CreateProfilesToProfiles(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, profilesToProfiles.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, profilesToProfiles.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n\tassert.NoError(t, profilesToProfiles.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "connector/connectortest/go.mod",
    "content": "module go.opentelemetry.io/collector/connector/connectortest\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/google/uuid v1.6.0\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/connector v0.148.0\n\tgo.opentelemetry.io/collector/connector/xconnector v0.148.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/internal/fanoutconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/connector => ../../connector\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/connector/xconnector => ../xconnector\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/internal/fanoutconsumer => ../../internal/fanoutconsumer\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "connector/connectortest/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "connector/connectortest/metadata.yaml",
    "content": "type: connector/connectortest\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "connector/connectortest/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage connectortest\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "connector/forwardconnector/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "connector/forwardconnector/README.md",
    "content": "<!-- status autogenerated section -->\n# Forward Connector\n| Status        |           |\n| ------------- |-----------|\n| Distributions | [core], [contrib], [k8s] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Aconnector%2Fforward%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Aconnector%2Fforward) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Aconnector%2Fforward%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Aconnector%2Fforward) |\n\n[alpha]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#alpha\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[core]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n[k8s]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\n\n## Supported Pipeline Types\n\n| [Exporter Pipeline Type] | [Receiver Pipeline Type] | [Stability Level] |\n| ------------------------ | ------------------------ | ----------------- |\n| profiles | profiles | [alpha] |\n| traces | traces | [beta] |\n| metrics | metrics | [beta] |\n| logs | logs | [beta] |\n\n[Exporter Pipeline Type]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/connector/README.md#exporter-pipeline-type\n[Receiver Pipeline Type]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/connector/README.md#receiver-pipeline-type\n[Stability Level]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stability-levels\n<!-- end autogenerated section -->\n\nThe `forward` connector can merge or fork pipelines of the same type.\n\n## Configuration\n\nIf you are not already familiar with connectors, you may find it helpful to first visit the [Connectors README].\n\nThe `forward` connector does not have any configuration settings.\n\n```yaml\nreceivers:\n  foo:\nexporters:\n  bar:\nconnectors:\n  forward:\n```\n\n### Example Usage\n\nAnnotate distinct log streams, then merge them together, and export.\n\n```yaml\nreceivers:\n  foo/blue:\n  foo/green:\nprocessors:\n  attributes/blue:\n  attributes/green:\nexporters:\n  bar:\nconnectors:\n  forward:\nservice:\n  pipelines:\n    logs/blue:\n      receivers: [foo/blue]\n      processors: [attributes/blue]\n      exporters: [forward]\n    logs/green:\n      receivers: [foo/green]\n      processors: [attributes/green]\n      exporters: [forward]\n    logs:\n      receivers: [forward]\n      exporters: [bar]\n```\n\nPreprocess data, then replicate and handle in distinct ways.\n\n```yaml\nreceivers:\n  foo:\nprocessors:\n  resourcedetection:\n  sample:\n  attributes:\nexporters:\n  bar/hot:\n  bar/cold:\nconnectors:\n  forward:\nservice:\n  pipelines:\n    traces:\n      receivers: [foo]\n      processors: [resourcedetection]\n      exporters: [forward]\n    traces/hot:\n      receivers: [forward]\n      processors: [sample]\n      exporters: [bar/hot]\n    traces/cold:\n      receivers: [forward]\n      processors: [attributes]\n      exporters: [bar/cold]\n```\n\nAdd a temporary debugging exporter. (Uncomment to enable.)\n\n```yaml\nreceivers:\n  foo:\nprocessors:\n  filter:\nexporters:\n  bar:\n# connectors:\n#   forward:\nservice:\n  pipelines:\n    traces:\n      receivers:\n        - foo\n      processors:\n        - filter\n      exporters:\n        - bar\n      # - forward\n  # traces/log:\n  #   receivers: [forward]\n  #   exporters: [debug]\n```\n\n[Connectors README]:../README.md\n"
  },
  {
    "path": "connector/forwardconnector/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\n// Package forwardconnector passes signals from one pipeline to another.\npackage forwardconnector // import \"go.opentelemetry.io/collector/connector/forwardconnector\"\n"
  },
  {
    "path": "connector/forwardconnector/forward.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage forwardconnector // import \"go.opentelemetry.io/collector/connector/forwardconnector\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/forwardconnector/internal/metadata\"\n\t\"go.opentelemetry.io/collector/connector/xconnector\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n)\n\n// NewFactory returns a connector.Factory.\nfunc NewFactory() xconnector.Factory {\n\treturn xconnector.NewFactory(\n\t\tmetadata.Type,\n\t\tcreateDefaultConfig,\n\t\txconnector.WithTracesToTraces(createTracesToTraces, metadata.TracesToTracesStability),\n\t\txconnector.WithMetricsToMetrics(createMetricsToMetrics, metadata.MetricsToMetricsStability),\n\t\txconnector.WithLogsToLogs(createLogsToLogs, metadata.LogsToLogsStability),\n\t\txconnector.WithProfilesToProfiles(createProfilesToProfiles, metadata.ProfilesToProfilesStability),\n\t)\n}\n\ntype Config struct{}\n\n// createDefaultConfig creates the default configuration.\nfunc createDefaultConfig() component.Config {\n\treturn &Config{}\n}\n\n// createTracesToTraces creates a trace receiver based on provided config.\nfunc createTracesToTraces(\n\t_ context.Context,\n\t_ connector.Settings,\n\t_ component.Config,\n\tnextConsumer consumer.Traces,\n) (connector.Traces, error) {\n\treturn &forward{Traces: nextConsumer}, nil\n}\n\n// createMetricsToMetrics creates a metrics receiver based on provided config.\nfunc createMetricsToMetrics(\n\t_ context.Context,\n\t_ connector.Settings,\n\t_ component.Config,\n\tnextConsumer consumer.Metrics,\n) (connector.Metrics, error) {\n\treturn &forward{Metrics: nextConsumer}, nil\n}\n\n// createLogsToLogs creates a log receiver based on provided config.\nfunc createLogsToLogs(\n\t_ context.Context,\n\t_ connector.Settings,\n\t_ component.Config,\n\tnextConsumer consumer.Logs,\n) (connector.Logs, error) {\n\treturn &forward{Logs: nextConsumer}, nil\n}\n\n// createProfilesToProfiles creates a profile receiver based on provided config.\nfunc createProfilesToProfiles(\n\t_ context.Context,\n\t_ connector.Settings,\n\t_ component.Config,\n\tnextConsumer xconsumer.Profiles,\n) (xconnector.Profiles, error) {\n\treturn &forward{Profiles: nextConsumer}, nil\n}\n\n// forward is used to pass signals directly from one pipeline to another.\n// This is useful when there is a need to replicate data and process it in more\n// than one way. It can also be used to join pipelines together.\ntype forward struct {\n\tconsumer.Traces\n\tconsumer.Metrics\n\tconsumer.Logs\n\txconsumer.Profiles\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n}\n\nfunc (c *forward) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: false}\n}\n"
  },
  {
    "path": "connector/forwardconnector/forward_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\npackage forwardconnector\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/connector/connectortest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nfunc TestForward(t *testing.T) {\n\tf := NewFactory()\n\tcfg := f.CreateDefaultConfig()\n\tassert.Equal(t, &Config{}, cfg)\n\n\tctx := context.Background()\n\tset := connectortest.NewNopSettings(f.Type())\n\thost := componenttest.NewNopHost()\n\n\ttracesSink := new(consumertest.TracesSink)\n\ttracesToTraces, err := f.CreateTracesToTraces(ctx, set, cfg, tracesSink)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, tracesToTraces)\n\n\tmetricsSink := new(consumertest.MetricsSink)\n\tmetricsToMetrics, err := f.CreateMetricsToMetrics(ctx, set, cfg, metricsSink)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, metricsToMetrics)\n\n\tlogsSink := new(consumertest.LogsSink)\n\tlogsToLogs, err := f.CreateLogsToLogs(ctx, set, cfg, logsSink)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, logsToLogs)\n\n\tprofilesSink := new(consumertest.ProfilesSink)\n\tprofilesToProfiles, err := f.CreateProfilesToProfiles(ctx, set, cfg, profilesSink)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, profilesToProfiles)\n\n\tassert.NoError(t, tracesToTraces.Start(ctx, host))\n\tassert.NoError(t, metricsToMetrics.Start(ctx, host))\n\tassert.NoError(t, logsToLogs.Start(ctx, host))\n\tassert.NoError(t, profilesToProfiles.Start(ctx, host))\n\n\tassert.NoError(t, tracesToTraces.ConsumeTraces(ctx, ptrace.NewTraces()))\n\n\tassert.NoError(t, metricsToMetrics.ConsumeMetrics(ctx, pmetric.NewMetrics()))\n\tassert.NoError(t, metricsToMetrics.ConsumeMetrics(ctx, pmetric.NewMetrics()))\n\n\tassert.NoError(t, logsToLogs.ConsumeLogs(ctx, plog.NewLogs()))\n\tassert.NoError(t, logsToLogs.ConsumeLogs(ctx, plog.NewLogs()))\n\tassert.NoError(t, logsToLogs.ConsumeLogs(ctx, plog.NewLogs()))\n\n\tassert.NoError(t, profilesToProfiles.ConsumeProfiles(ctx, pprofile.NewProfiles()))\n\n\tassert.NoError(t, tracesToTraces.Shutdown(ctx))\n\tassert.NoError(t, metricsToMetrics.Shutdown(ctx))\n\tassert.NoError(t, logsToLogs.Shutdown(ctx))\n\tassert.NoError(t, profilesToProfiles.Shutdown(ctx))\n\n\tassert.Len(t, tracesSink.AllTraces(), 1)\n\tassert.Len(t, metricsSink.AllMetrics(), 2)\n\tassert.Len(t, logsSink.AllLogs(), 3)\n\tassert.Len(t, profilesSink.AllProfiles(), 1)\n}\n"
  },
  {
    "path": "connector/forwardconnector/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage forwardconnector\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/connectortest\"\n\t\"go.opentelemetry.io/collector/connector/xconnector\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n)\n\nvar typ = component.MustNewType(\"forward\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct {\n\t\tcreateFn func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error)\n\t\tname     string\n\t}{\n\n\t\t{\n\t\t\tname: \"logs_to_logs\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewLogsRouter(map[pipeline.ID]consumer.Logs{pipeline.NewID(pipeline.SignalLogs): consumertest.NewNop()})\n\t\t\t\treturn factory.CreateLogsToLogs(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"metrics_to_metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewMetricsRouter(map[pipeline.ID]consumer.Metrics{pipeline.NewID(pipeline.SignalMetrics): consumertest.NewNop()})\n\t\t\t\treturn factory.CreateMetricsToMetrics(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"traces_to_traces\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := connector.NewTracesRouter(map[pipeline.ID]consumer.Traces{pipeline.NewID(pipeline.SignalTraces): consumertest.NewNop()})\n\t\t\t\treturn factory.CreateTracesToTraces(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"profiles_to_profiles\",\n\t\t\tcreateFn: func(ctx context.Context, set connector.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\trouter := xconnector.NewProfilesRouter(map[pipeline.ID]xconsumer.Profiles{pipeline.NewID(xpipeline.SignalProfiles): consumertest.NewNop()})\n\t\t\t\treturn factory.(xconnector.Factory).CreateProfilesToProfiles(ctx, set, cfg, router)\n\t\t\t},\n\t\t},\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name+\"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), connectortest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\tt.Run(tt.name+\"-lifecycle\", func(t *testing.T) {\n\t\t\tfirstConnector, err := tt.createFn(context.Background(), connectortest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := newMdatagenNopHost()\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, firstConnector.Start(context.Background(), host))\n\t\t\trequire.NoError(t, firstConnector.Shutdown(context.Background()))\n\t\t\tsecondConnector, err := tt.createFn(context.Background(), connectortest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, secondConnector.Start(context.Background(), host))\n\t\t\trequire.NoError(t, secondConnector.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "connector/forwardconnector/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage forwardconnector\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "connector/forwardconnector/go.mod",
    "content": "module go.opentelemetry.io/collector/connector/forwardconnector\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/connector v0.148.0\n\tgo.opentelemetry.io/collector/connector/connectortest v0.148.0\n\tgo.opentelemetry.io/collector/connector/xconnector v0.148.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/internal/fanoutconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/connector => ../\n\nreplace go.opentelemetry.io/collector/connector/connectortest => ../connectortest\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nretract (\n\tv0.76.0 // Depends on retracted pdata v1.0.0-rc10 module, use v0.76.1\n\tv0.69.0 // Release failed, use v0.69.1\n)\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/connector/xconnector => ../xconnector\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/internal/fanoutconsumer => ../../internal/fanoutconsumer\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "connector/forwardconnector/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "connector/forwardconnector/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"forward\")\n\tScopeName = \"go.opentelemetry.io/collector/connector/forwardconnector\"\n)\n\nconst (\n\tProfilesToProfilesStability = component.StabilityLevelAlpha\n\tTracesToTracesStability     = component.StabilityLevelBeta\n\tMetricsToMetricsStability   = component.StabilityLevelBeta\n\tLogsToLogsStability         = component.StabilityLevelBeta\n)\n"
  },
  {
    "path": "connector/forwardconnector/metadata.yaml",
    "content": "display_name: Forward Connector\ntype: forward\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: connector\n  stability:\n    alpha: [profiles_to_profiles]\n    beta: [traces_to_traces, metrics_to_metrics, logs_to_logs]\n  distributions: [core, contrib, k8s]\n"
  },
  {
    "path": "connector/go.mod",
    "content": "module go.opentelemetry.io/collector/connector\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0\n\tgo.opentelemetry.io/collector/internal/fanoutconsumer v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/multierr v1.11.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../component\n\nreplace go.opentelemetry.io/collector/consumer => ../consumer\n\nreplace go.opentelemetry.io/collector/pdata => ../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/pipeline => ../pipeline\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../internal/componentalias\n\nreplace go.opentelemetry.io/collector/internal/fanoutconsumer => ../internal/fanoutconsumer\n\nreplace go.opentelemetry.io/collector/featuregate => ../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../internal/testutil\n"
  },
  {
    "path": "connector/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "connector/internal/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/connector/internal\"\n\nimport (\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\nfunc ErrDataTypes(id component.ID, from, to pipeline.Signal) error {\n\treturn fmt.Errorf(\"connector %q cannot connect from %s to %s: %w\", id, from, to, pipeline.ErrSignalNotSupported)\n}\n\nfunc ErrIDMismatch(id component.ID, typ component.Type) error {\n\treturn fmt.Errorf(\"component type mismatch: component ID %q does not have type %q\", id, typ)\n}\n"
  },
  {
    "path": "connector/internal/router.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/connector/internal\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"maps\"\n\n\t\"go.uber.org/multierr\"\n\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\ntype BaseRouter[T any] struct {\n\tfanout    func([]T) T\n\tConsumers map[pipeline.ID]T\n}\n\nfunc NewBaseRouter[T any](fanout func([]T) T, cm map[pipeline.ID]T) BaseRouter[T] {\n\tconsumers := make(map[pipeline.ID]T, len(cm))\n\tmaps.Copy(consumers, cm)\n\treturn BaseRouter[T]{fanout: fanout, Consumers: consumers}\n}\n\nfunc (r *BaseRouter[T]) PipelineIDs() []pipeline.ID {\n\tids := make([]pipeline.ID, 0, len(r.Consumers))\n\tfor id := range r.Consumers {\n\t\tids = append(ids, id)\n\t}\n\treturn ids\n}\n\nfunc (r *BaseRouter[T]) Consumer(pipelineIDs ...pipeline.ID) (T, error) {\n\tvar ret T\n\tif len(pipelineIDs) == 0 {\n\t\treturn ret, errors.New(\"missing consumers\")\n\t}\n\tconsumers := make([]T, 0, len(pipelineIDs))\n\tvar errors error\n\tfor _, pipelineID := range pipelineIDs {\n\t\tc, ok := r.Consumers[pipelineID]\n\t\tif ok {\n\t\t\tconsumers = append(consumers, c)\n\t\t} else {\n\t\t\terrors = multierr.Append(errors, fmt.Errorf(\"missing consumer: %q\", pipelineID))\n\t\t}\n\t}\n\tif errors != nil {\n\t\t// TODO potentially this could return a NewTraces with the valid consumers\n\t\treturn ret, errors\n\t}\n\treturn r.fanout(consumers), nil\n}\n"
  },
  {
    "path": "connector/logs_router.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage connector // import \"go.opentelemetry.io/collector/connector\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"go.uber.org/multierr\"\n\n\t\"go.opentelemetry.io/collector/connector/internal\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/internal/fanoutconsumer\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\n// LogsRouterAndConsumer feeds the first consumer.Logs in each of the specified pipelines.\ntype LogsRouterAndConsumer interface {\n\tconsumer.Logs\n\tConsumer(...pipeline.ID) (consumer.Logs, error)\n\tPipelineIDs() []pipeline.ID\n\tprivateFunc()\n}\n\ntype logsRouter struct {\n\tconsumer.Logs\n\tinternal.BaseRouter[consumer.Logs]\n}\n\nfunc NewLogsRouter(cm map[pipeline.ID]consumer.Logs) LogsRouterAndConsumer {\n\tconsumers := make([]consumer.Logs, 0, len(cm))\n\tfor _, cons := range cm {\n\t\tconsumers = append(consumers, cons)\n\t}\n\treturn &logsRouter{\n\t\tLogs:       fanoutconsumer.NewLogs(consumers),\n\t\tBaseRouter: internal.NewBaseRouter(fanoutconsumer.NewLogs, cm),\n\t}\n}\n\nfunc (r *logsRouter) PipelineIDs() []pipeline.ID {\n\tids := make([]pipeline.ID, 0, len(r.Consumers))\n\tfor id := range r.Consumers {\n\t\tids = append(ids, id)\n\t}\n\treturn ids\n}\n\nfunc (r *logsRouter) Consumer(pipelineIDs ...pipeline.ID) (consumer.Logs, error) {\n\tif len(pipelineIDs) == 0 {\n\t\treturn nil, errors.New(\"missing consumers\")\n\t}\n\tconsumers := make([]consumer.Logs, 0, len(pipelineIDs))\n\tvar errors error\n\tfor _, pipelineID := range pipelineIDs {\n\t\tc, ok := r.Consumers[pipelineID]\n\t\tif ok {\n\t\t\tconsumers = append(consumers, c)\n\t\t} else {\n\t\t\terrors = multierr.Append(errors, fmt.Errorf(\"missing consumer: %q\", pipelineID))\n\t\t}\n\t}\n\tif errors != nil {\n\t\t// TODO potentially this could return a NewLogs with the valid consumers\n\t\treturn nil, errors\n\t}\n\treturn fanoutconsumer.NewLogs(consumers), nil\n}\n\nfunc (r *logsRouter) privateFunc() {}\n"
  },
  {
    "path": "connector/logs_router_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage connector\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\ntype mutatingLogsSink struct {\n\t*consumertest.LogsSink\n}\n\nfunc (mts *mutatingLogsSink) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: true}\n}\n\nfunc TestLogsRouterMultiplexing(t *testing.T) {\n\tnum := 20\n\tfor numIDs := 1; numIDs < num; numIDs++ {\n\t\tfor numCons := 1; numCons < num; numCons++ {\n\t\t\tfor numLogs := 1; numLogs < num; numLogs++ {\n\t\t\t\tt.Run(\n\t\t\t\t\tfmt.Sprintf(\"%d-ids/%d-cons/%d-logs\", numIDs, numCons, numLogs),\n\t\t\t\t\tfuzzLogs(numIDs, numCons, numLogs),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc fuzzLogs(numIDs, numCons, numLogs int) func(*testing.T) {\n\treturn func(t *testing.T) {\n\t\tallIDs := make([]pipeline.ID, 0, numCons)\n\t\tallCons := make([]consumer.Logs, 0, numCons)\n\t\tallConsMap := make(map[pipeline.ID]consumer.Logs)\n\n\t\t// If any consumer is mutating, the router must report mutating\n\t\tfor i := range numCons {\n\t\t\tallIDs = append(allIDs, pipeline.NewIDWithName(pipeline.SignalLogs, \"sink_\"+strconv.Itoa(numCons)))\n\t\t\t// Random chance for each consumer to be mutating\n\t\t\tif (numCons+numLogs+i)%4 == 0 {\n\t\t\t\tallCons = append(allCons, &mutatingLogsSink{LogsSink: new(consumertest.LogsSink)})\n\t\t\t} else {\n\t\t\t\tallCons = append(allCons, new(consumertest.LogsSink))\n\t\t\t}\n\t\t\tallConsMap[allIDs[i]] = allCons[i]\n\t\t}\n\n\t\tr := NewLogsRouter(allConsMap)\n\t\tld := testdata.GenerateLogs(1)\n\n\t\t// Keep track of how many logs each consumer should receive.\n\t\t// This will be validated after every call to RouteLogs.\n\t\texpected := make(map[pipeline.ID]int, numCons)\n\n\t\tfor i := range numLogs {\n\t\t\t// Build a random set of ids (no duplicates)\n\t\t\trandCons := make(map[pipeline.ID]bool, numIDs)\n\t\t\tfor j := range numIDs {\n\t\t\t\t// This number should be pretty random and less than numCons\n\t\t\t\tconNum := (numCons + numIDs + i + j) % numCons\n\t\t\t\trandCons[allIDs[conNum]] = true\n\t\t\t}\n\n\t\t\t// Convert to slice, update expectations\n\t\t\tconIDs := make([]pipeline.ID, 0, len(randCons))\n\t\t\tfor id := range randCons {\n\t\t\t\tconIDs = append(conIDs, id)\n\t\t\t\texpected[id]++\n\t\t\t}\n\n\t\t\t// Route to list of consumers\n\t\t\tfanout, err := r.Consumer(conIDs...)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.NoError(t, fanout.ConsumeLogs(context.Background(), ld))\n\n\t\t\t// Validate expectations for all consumers\n\t\t\tfor id := range expected {\n\t\t\t\tlogs := []plog.Logs{}\n\t\t\t\tswitch con := allConsMap[id].(type) {\n\t\t\t\tcase *consumertest.LogsSink:\n\t\t\t\t\tlogs = con.AllLogs()\n\t\t\t\tcase *mutatingLogsSink:\n\t\t\t\t\tlogs = con.AllLogs()\n\t\t\t\t}\n\t\t\t\tassert.Len(t, logs, expected[id])\n\t\t\t\tfor n := 0; n < len(logs); n++ {\n\t\t\t\t\tassert.Equal(t, ld, logs[n])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestLogsRouterConsumers(t *testing.T) {\n\tctx := context.Background()\n\tld := testdata.GenerateLogs(1)\n\n\tfooID := pipeline.NewIDWithName(pipeline.SignalLogs, \"foo\")\n\tbarID := pipeline.NewIDWithName(pipeline.SignalLogs, \"bar\")\n\n\tfoo := new(consumertest.LogsSink)\n\tbar := new(consumertest.LogsSink)\n\tr := NewLogsRouter(map[pipeline.ID]consumer.Logs{fooID: foo, barID: bar})\n\n\trcs := r.PipelineIDs()\n\tassert.Len(t, rcs, 2)\n\tassert.ElementsMatch(t, []pipeline.ID{fooID, barID}, rcs)\n\n\tassert.Empty(t, foo.AllLogs())\n\tassert.Empty(t, bar.AllLogs())\n\n\tboth, err := r.Consumer(fooID, barID)\n\tassert.NotNil(t, both)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, both.ConsumeLogs(ctx, ld))\n\tassert.Len(t, foo.AllLogs(), 1)\n\tassert.Len(t, bar.AllLogs(), 1)\n\n\tfooOnly, err := r.Consumer(fooID)\n\tassert.NotNil(t, fooOnly)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, fooOnly.ConsumeLogs(ctx, ld))\n\tassert.Len(t, foo.AllLogs(), 2)\n\tassert.Len(t, bar.AllLogs(), 1)\n\n\tbarOnly, err := r.Consumer(barID)\n\tassert.NotNil(t, barOnly)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, barOnly.ConsumeLogs(ctx, ld))\n\tassert.Len(t, foo.AllLogs(), 2)\n\tassert.Len(t, bar.AllLogs(), 2)\n\n\tnone, err := r.Consumer()\n\tassert.Nil(t, none)\n\trequire.Error(t, err)\n\n\tfake, err := r.Consumer(pipeline.NewIDWithName(pipeline.SignalLogs, \"fake\"))\n\tassert.Nil(t, fake)\n\tassert.Error(t, err)\n}\n"
  },
  {
    "path": "connector/metadata.yaml",
    "content": "type: connector\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "connector/metrics_router.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage connector // import \"go.opentelemetry.io/collector/connector\"\n\nimport (\n\t\"go.opentelemetry.io/collector/connector/internal\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/internal/fanoutconsumer\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\n// MetricsRouterAndConsumer feeds the first consumer.Metrics in each of the specified pipelines.\ntype MetricsRouterAndConsumer interface {\n\tconsumer.Metrics\n\tConsumer(...pipeline.ID) (consumer.Metrics, error)\n\tPipelineIDs() []pipeline.ID\n\tprivateFunc()\n}\n\ntype metricsRouter struct {\n\tconsumer.Metrics\n\tinternal.BaseRouter[consumer.Metrics]\n}\n\nfunc NewMetricsRouter(cm map[pipeline.ID]consumer.Metrics) MetricsRouterAndConsumer {\n\tconsumers := make([]consumer.Metrics, 0, len(cm))\n\tfor _, cons := range cm {\n\t\tconsumers = append(consumers, cons)\n\t}\n\treturn &metricsRouter{\n\t\tMetrics:    fanoutconsumer.NewMetrics(consumers),\n\t\tBaseRouter: internal.NewBaseRouter(fanoutconsumer.NewMetrics, cm),\n\t}\n}\n\nfunc (r *metricsRouter) privateFunc() {}\n"
  },
  {
    "path": "connector/metrics_router_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage connector\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\ntype mutatingMetricsSink struct {\n\t*consumertest.MetricsSink\n}\n\nfunc (mts *mutatingMetricsSink) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: true}\n}\n\nfunc TestMetricsRouterMultiplexing(t *testing.T) {\n\tnum := 20\n\tfor numIDs := 1; numIDs < num; numIDs++ {\n\t\tfor numCons := 1; numCons < num; numCons++ {\n\t\t\tfor numMetrics := 1; numMetrics < num; numMetrics++ {\n\t\t\t\tt.Run(\n\t\t\t\t\tfmt.Sprintf(\"%d-ids/%d-cons/%d-logs\", numIDs, numCons, numMetrics),\n\t\t\t\t\tfuzzMetrics(numIDs, numCons, numMetrics),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc fuzzMetrics(numIDs, numCons, numMetrics int) func(*testing.T) {\n\treturn func(t *testing.T) {\n\t\tallIDs := make([]pipeline.ID, 0, numCons)\n\t\tallCons := make([]consumer.Metrics, 0, numCons)\n\t\tallConsMap := make(map[pipeline.ID]consumer.Metrics)\n\n\t\t// If any consumer is mutating, the router must report mutating\n\t\tfor i := range numCons {\n\t\t\tallIDs = append(allIDs, pipeline.NewIDWithName(pipeline.SignalMetrics, \"sink_\"+strconv.Itoa(numCons)))\n\t\t\t// Random chance for each consumer to be mutating\n\t\t\tif (numCons+numMetrics+i)%4 == 0 {\n\t\t\t\tallCons = append(allCons, &mutatingMetricsSink{MetricsSink: new(consumertest.MetricsSink)})\n\t\t\t} else {\n\t\t\t\tallCons = append(allCons, new(consumertest.MetricsSink))\n\t\t\t}\n\t\t\tallConsMap[allIDs[i]] = allCons[i]\n\t\t}\n\n\t\tr := NewMetricsRouter(allConsMap)\n\t\tmd := testdata.GenerateMetrics(1)\n\n\t\t// Keep track of how many logs each consumer should receive.\n\t\t// This will be validated after every call to RouteMetrics.\n\t\texpected := make(map[pipeline.ID]int, numCons)\n\n\t\tfor i := range numMetrics {\n\t\t\t// Build a random set of ids (no duplicates)\n\t\t\trandCons := make(map[pipeline.ID]bool, numIDs)\n\t\t\tfor j := range numIDs {\n\t\t\t\t// This number should be pretty random and less than numCons\n\t\t\t\tconNum := (numCons + numIDs + i + j) % numCons\n\t\t\t\trandCons[allIDs[conNum]] = true\n\t\t\t}\n\n\t\t\t// Convert to slice, update expectations\n\t\t\tconIDs := make([]pipeline.ID, 0, len(randCons))\n\t\t\tfor id := range randCons {\n\t\t\t\tconIDs = append(conIDs, id)\n\t\t\t\texpected[id]++\n\t\t\t}\n\n\t\t\t// Route to list of consumers\n\t\t\tfanout, err := r.Consumer(conIDs...)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.NoError(t, fanout.ConsumeMetrics(context.Background(), md))\n\n\t\t\t// Validate expectations for all consumers\n\t\t\tfor id := range expected {\n\t\t\t\tmetrics := []pmetric.Metrics{}\n\t\t\t\tswitch con := allConsMap[id].(type) {\n\t\t\t\tcase *consumertest.MetricsSink:\n\t\t\t\t\tmetrics = con.AllMetrics()\n\t\t\t\tcase *mutatingMetricsSink:\n\t\t\t\t\tmetrics = con.AllMetrics()\n\t\t\t\t}\n\t\t\t\tassert.Len(t, metrics, expected[id])\n\t\t\t\tfor n := 0; n < len(metrics); n++ {\n\t\t\t\t\tassert.Equal(t, md, metrics[n])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestMetricsRouterConsumers(t *testing.T) {\n\tctx := context.Background()\n\tmd := testdata.GenerateMetrics(1)\n\n\tfooID := pipeline.NewIDWithName(pipeline.SignalMetrics, \"foo\")\n\tbarID := pipeline.NewIDWithName(pipeline.SignalMetrics, \"bar\")\n\n\tfoo := new(consumertest.MetricsSink)\n\tbar := new(consumertest.MetricsSink)\n\tr := NewMetricsRouter(map[pipeline.ID]consumer.Metrics{fooID: foo, barID: bar})\n\n\trcs := r.PipelineIDs()\n\tassert.Len(t, rcs, 2)\n\tassert.ElementsMatch(t, []pipeline.ID{fooID, barID}, rcs)\n\n\tassert.Empty(t, foo.AllMetrics())\n\tassert.Empty(t, bar.AllMetrics())\n\n\tboth, err := r.Consumer(fooID, barID)\n\tassert.NotNil(t, both)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, both.ConsumeMetrics(ctx, md))\n\tassert.Len(t, foo.AllMetrics(), 1)\n\tassert.Len(t, bar.AllMetrics(), 1)\n\n\tfooOnly, err := r.Consumer(fooID)\n\tassert.NotNil(t, fooOnly)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, fooOnly.ConsumeMetrics(ctx, md))\n\tassert.Len(t, foo.AllMetrics(), 2)\n\tassert.Len(t, bar.AllMetrics(), 1)\n\n\tbarOnly, err := r.Consumer(barID)\n\tassert.NotNil(t, barOnly)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, barOnly.ConsumeMetrics(ctx, md))\n\tassert.Len(t, foo.AllMetrics(), 2)\n\tassert.Len(t, bar.AllMetrics(), 2)\n\n\tnone, err := r.Consumer()\n\tassert.Nil(t, none)\n\trequire.Error(t, err)\n\n\tfake, err := r.Consumer(pipeline.NewIDWithName(pipeline.SignalMetrics, \"fake\"))\n\tassert.Nil(t, fake)\n\tassert.Error(t, err)\n}\n"
  },
  {
    "path": "connector/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage connector\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "connector/traces_router.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage connector // import \"go.opentelemetry.io/collector/connector\"\n\nimport (\n\t\"go.opentelemetry.io/collector/connector/internal\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/internal/fanoutconsumer\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\n// TracesRouterAndConsumer feeds the first consumer.Traces in each of the specified pipelines.\ntype TracesRouterAndConsumer interface {\n\tconsumer.Traces\n\tConsumer(...pipeline.ID) (consumer.Traces, error)\n\tPipelineIDs() []pipeline.ID\n\tprivateFunc()\n}\n\ntype tracesRouter struct {\n\tconsumer.Traces\n\tinternal.BaseRouter[consumer.Traces]\n}\n\nfunc NewTracesRouter(cm map[pipeline.ID]consumer.Traces) TracesRouterAndConsumer {\n\tconsumers := make([]consumer.Traces, 0, len(cm))\n\tfor _, cons := range cm {\n\t\tconsumers = append(consumers, cons)\n\t}\n\treturn &tracesRouter{\n\t\tTraces:     fanoutconsumer.NewTraces(consumers),\n\t\tBaseRouter: internal.NewBaseRouter(fanoutconsumer.NewTraces, cm),\n\t}\n}\n\nfunc (r *tracesRouter) privateFunc() {}\n"
  },
  {
    "path": "connector/traces_router_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage connector\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\ntype mutatingTracesSink struct {\n\t*consumertest.TracesSink\n}\n\nfunc (mts *mutatingTracesSink) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: true}\n}\n\nfunc TestTracesRouterMultiplexing(t *testing.T) {\n\tnum := 20\n\tfor numIDs := 1; numIDs < num; numIDs++ {\n\t\tfor numCons := 1; numCons < num; numCons++ {\n\t\t\tfor numTraces := 1; numTraces < num; numTraces++ {\n\t\t\t\tt.Run(\n\t\t\t\t\tfmt.Sprintf(\"%d-ids/%d-cons/%d-logs\", numIDs, numCons, numTraces),\n\t\t\t\t\tfuzzTraces(numIDs, numCons, numTraces),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc fuzzTraces(numIDs, numCons, numTraces int) func(*testing.T) {\n\treturn func(t *testing.T) {\n\t\tallIDs := make([]pipeline.ID, 0, numCons)\n\t\tallCons := make([]consumer.Traces, 0, numCons)\n\t\tallConsMap := make(map[pipeline.ID]consumer.Traces)\n\n\t\t// If any consumer is mutating, the router must report mutating\n\t\tfor i := range numCons {\n\t\t\tallIDs = append(allIDs, pipeline.NewIDWithName(pipeline.SignalTraces, \"sink_\"+strconv.Itoa(numCons)))\n\t\t\t// Random chance for each consumer to be mutating\n\t\t\tif (numCons+numTraces+i)%4 == 0 {\n\t\t\t\tallCons = append(allCons, &mutatingTracesSink{TracesSink: new(consumertest.TracesSink)})\n\t\t\t} else {\n\t\t\t\tallCons = append(allCons, new(consumertest.TracesSink))\n\t\t\t}\n\t\t\tallConsMap[allIDs[i]] = allCons[i]\n\t\t}\n\n\t\tr := NewTracesRouter(allConsMap)\n\t\ttd := testdata.GenerateTraces(1)\n\n\t\t// Keep track of how many logs each consumer should receive.\n\t\t// This will be validated after every call to RouteTraces.\n\t\texpected := make(map[pipeline.ID]int, numCons)\n\n\t\tfor i := range numTraces {\n\t\t\t// Build a random set of ids (no duplicates)\n\t\t\trandCons := make(map[pipeline.ID]bool, numIDs)\n\t\t\tfor j := range numIDs {\n\t\t\t\t// This number should be pretty random and less than numCons\n\t\t\t\tconNum := (numCons + numIDs + i + j) % numCons\n\t\t\t\trandCons[allIDs[conNum]] = true\n\t\t\t}\n\n\t\t\t// Convert to slice, update expectations\n\t\t\tconIDs := make([]pipeline.ID, 0, len(randCons))\n\t\t\tfor id := range randCons {\n\t\t\t\tconIDs = append(conIDs, id)\n\t\t\t\texpected[id]++\n\t\t\t}\n\n\t\t\t// Route to list of consumers\n\t\t\tfanout, err := r.Consumer(conIDs...)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.NoError(t, fanout.ConsumeTraces(context.Background(), td))\n\n\t\t\t// Validate expectations for all consumers\n\t\t\tfor id := range expected {\n\t\t\t\ttraces := []ptrace.Traces{}\n\t\t\t\tswitch con := allConsMap[id].(type) {\n\t\t\t\tcase *consumertest.TracesSink:\n\t\t\t\t\ttraces = con.AllTraces()\n\t\t\t\tcase *mutatingTracesSink:\n\t\t\t\t\ttraces = con.AllTraces()\n\t\t\t\t}\n\t\t\t\tassert.Len(t, traces, expected[id])\n\t\t\t\tfor n := 0; n < len(traces); n++ {\n\t\t\t\t\tassert.Equal(t, td, traces[n])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestTracesRouterConsumer(t *testing.T) {\n\tctx := context.Background()\n\ttd := testdata.GenerateTraces(1)\n\n\tfooID := pipeline.NewIDWithName(pipeline.SignalTraces, \"foo\")\n\tbarID := pipeline.NewIDWithName(pipeline.SignalTraces, \"bar\")\n\n\tfoo := new(consumertest.TracesSink)\n\tbar := new(consumertest.TracesSink)\n\tr := NewTracesRouter(map[pipeline.ID]consumer.Traces{fooID: foo, barID: bar})\n\n\trcs := r.PipelineIDs()\n\tassert.Len(t, rcs, 2)\n\tassert.ElementsMatch(t, []pipeline.ID{fooID, barID}, rcs)\n\n\tassert.Empty(t, foo.AllTraces())\n\tassert.Empty(t, bar.AllTraces())\n\n\tboth, err := r.Consumer(fooID, barID)\n\tassert.NotNil(t, both)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, both.ConsumeTraces(ctx, td))\n\tassert.Len(t, foo.AllTraces(), 1)\n\tassert.Len(t, bar.AllTraces(), 1)\n\n\tfooOnly, err := r.Consumer(fooID)\n\tassert.NotNil(t, fooOnly)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, fooOnly.ConsumeTraces(ctx, td))\n\tassert.Len(t, foo.AllTraces(), 2)\n\tassert.Len(t, bar.AllTraces(), 1)\n\n\tbarOnly, err := r.Consumer(barID)\n\tassert.NotNil(t, barOnly)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, barOnly.ConsumeTraces(ctx, td))\n\tassert.Len(t, foo.AllTraces(), 2)\n\tassert.Len(t, bar.AllTraces(), 2)\n\n\tnone, err := r.Consumer()\n\tassert.Nil(t, none)\n\trequire.Error(t, err)\n\n\tfake, err := r.Consumer(pipeline.NewIDWithName(pipeline.SignalTraces, \"fake\"))\n\tassert.Nil(t, fake)\n\tassert.Error(t, err)\n}\n"
  },
  {
    "path": "connector/xconnector/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "connector/xconnector/connector.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xconnector // import \"go.opentelemetry.io/collector/connector/xconnector\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/internal\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n)\n\ntype Factory interface {\n\tconnector.Factory\n\n\tCreateTracesToProfiles(ctx context.Context, set connector.Settings, cfg component.Config, next xconsumer.Profiles) (connector.Traces, error)\n\tCreateMetricsToProfiles(ctx context.Context, set connector.Settings, cfg component.Config, next xconsumer.Profiles) (connector.Metrics, error)\n\tCreateLogsToProfiles(ctx context.Context, set connector.Settings, cfg component.Config, next xconsumer.Profiles) (connector.Logs, error)\n\n\tTracesToProfilesStability() component.StabilityLevel\n\tMetricsToProfilesStability() component.StabilityLevel\n\tLogsToProfilesStability() component.StabilityLevel\n\n\tCreateProfilesToProfiles(ctx context.Context, set connector.Settings, cfg component.Config, next xconsumer.Profiles) (Profiles, error)\n\tCreateProfilesToTraces(ctx context.Context, set connector.Settings, cfg component.Config, next consumer.Traces) (Profiles, error)\n\tCreateProfilesToMetrics(ctx context.Context, set connector.Settings, cfg component.Config, next consumer.Metrics) (Profiles, error)\n\tCreateProfilesToLogs(ctx context.Context, set connector.Settings, cfg component.Config, next consumer.Logs) (Profiles, error)\n\n\tProfilesToProfilesStability() component.StabilityLevel\n\tProfilesToTracesStability() component.StabilityLevel\n\tProfilesToMetricsStability() component.StabilityLevel\n\tProfilesToLogsStability() component.StabilityLevel\n}\n\n// A Profiles connector acts as an exporter from a profiles pipeline and a receiver\n// to one or more traces, metrics, logs, or profiles pipelines.\n// Profiles feeds a consumer.Traces, consumer.Metrics, consumer.Logs, or xconsumer.Profiles with data.\n//\n// Examples:\n//   - Profiles could be collected in one pipeline and routed to another profiles pipeline\n//     based on criteria such as attributes or other content of the profile. The second\n//     pipeline can then process and export the profile to the appropriate backend.\n//   - Profiles could be summarized by a metrics connector that emits statistics describing\n//     the number of profiles observed.\n//   - Profiles could be analyzed by a logs connector that emits events when particular\n//     criteria are met.\ntype Profiles interface {\n\tcomponent.Component\n\txconsumer.Profiles\n}\n\n// CreateTracesToProfilesFunc is the equivalent of Factory.CreateTracesToProfiles().\ntype CreateTracesToProfilesFunc func(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (connector.Traces, error)\n\n// CreateMetricsToProfilesFunc is the equivalent of Factory.CreateMetricsToProfiles().\ntype CreateMetricsToProfilesFunc func(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (connector.Metrics, error)\n\n// CreateLogsToProfilesFunc is the equivalent of Factory.CreateLogsToProfiles().\ntype CreateLogsToProfilesFunc func(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (connector.Logs, error)\n\n// CreateProfilesToProfilesFunc is the equivalent of Factory.CreateProfilesToProfiles().\ntype CreateProfilesToProfilesFunc func(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (Profiles, error)\n\n// CreateProfilesToTracesFunc is the equivalent of Factory.CreateProfilesToTraces().\ntype CreateProfilesToTracesFunc func(context.Context, connector.Settings, component.Config, consumer.Traces) (Profiles, error)\n\n// CreateProfilesToMetricsFunc is the equivalent of Factory.CreateProfilesToMetrics().\ntype CreateProfilesToMetricsFunc func(context.Context, connector.Settings, component.Config, consumer.Metrics) (Profiles, error)\n\n// CreateProfilesToLogsFunc is the equivalent of Factory.CreateProfilesToLogs().\ntype CreateProfilesToLogsFunc func(context.Context, connector.Settings, component.Config, consumer.Logs) (Profiles, error)\n\n// FactoryOption apply changes to ReceiverOptions.\ntype FactoryOption interface {\n\t// applyOption applies the option.\n\tapplyOption(o *factory)\n}\n\n// factoryOptionFunc is an ReceiverFactoryOption created through a function.\ntype factoryOptionFunc func(*factory)\n\nfunc (f factoryOptionFunc) applyOption(o *factory) {\n\tf(o)\n}\n\n// WithTracesToTraces overrides the default \"error not supported\" implementation for WithTracesToTraces and the default \"undefined\" stability level.\nfunc WithTracesToTraces(createTracesToTraces connector.CreateTracesToTracesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, connector.WithTracesToTraces(createTracesToTraces, sl))\n\t})\n}\n\n// WithTracesToMetrics overrides the default \"error not supported\" implementation for WithTracesToMetrics and the default \"undefined\" stability level.\nfunc WithTracesToMetrics(createTracesToMetrics connector.CreateTracesToMetricsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, connector.WithTracesToMetrics(createTracesToMetrics, sl))\n\t})\n}\n\n// WithTracesToLogs overrides the default \"error not supported\" implementation for WithTracesToLogs and the default \"undefined\" stability level.\nfunc WithTracesToLogs(createTracesToLogs connector.CreateTracesToLogsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, connector.WithTracesToLogs(createTracesToLogs, sl))\n\t})\n}\n\n// WithMetricsToTraces overrides the default \"error not supported\" implementation for WithMetricsToTraces and the default \"undefined\" stability level.\nfunc WithMetricsToTraces(createMetricsToTraces connector.CreateMetricsToTracesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, connector.WithMetricsToTraces(createMetricsToTraces, sl))\n\t})\n}\n\n// WithMetricsToMetrics overrides the default \"error not supported\" implementation for WithMetricsToMetrics and the default \"undefined\" stability level.\nfunc WithMetricsToMetrics(createMetricsToMetrics connector.CreateMetricsToMetricsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, connector.WithMetricsToMetrics(createMetricsToMetrics, sl))\n\t})\n}\n\n// WithMetricsToLogs overrides the default \"error not supported\" implementation for WithMetricsToLogs and the default \"undefined\" stability level.\nfunc WithMetricsToLogs(createMetricsToLogs connector.CreateMetricsToLogsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, connector.WithMetricsToLogs(createMetricsToLogs, sl))\n\t})\n}\n\n// WithLogsToTraces overrides the default \"error not supported\" implementation for WithLogsToTraces and the default \"undefined\" stability level.\nfunc WithLogsToTraces(createLogsToTraces connector.CreateLogsToTracesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, connector.WithLogsToTraces(createLogsToTraces, sl))\n\t})\n}\n\n// WithLogsToMetrics overrides the default \"error not supported\" implementation for WithLogsToMetrics and the default \"undefined\" stability level.\nfunc WithLogsToMetrics(createLogsToMetrics connector.CreateLogsToMetricsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, connector.WithLogsToMetrics(createLogsToMetrics, sl))\n\t})\n}\n\n// WithLogsToLogs overrides the default \"error not supported\" implementation for WithLogsToLogs and the default \"undefined\" stability level.\nfunc WithLogsToLogs(createLogsToLogs connector.CreateLogsToLogsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, connector.WithLogsToLogs(createLogsToLogs, sl))\n\t})\n}\n\n// WithTracesToProfiles overrides the default \"error not supported\" implementation for WithTracesToProfiles and the default \"undefined\" stability level.\nfunc WithTracesToProfiles(createTracesToProfiles CreateTracesToProfilesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.tracesToProfilesStabilityLevel = sl\n\t\to.createTracesToProfilesFunc = createTracesToProfiles\n\t})\n}\n\n// WithMetricsToProfiles overrides the default \"error not supported\" implementation for WithMetricsToProfiles and the default \"undefined\" stability level.\nfunc WithMetricsToProfiles(createMetricsToProfiles CreateMetricsToProfilesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.metricsToProfilesStabilityLevel = sl\n\t\to.createMetricsToProfilesFunc = createMetricsToProfiles\n\t})\n}\n\n// WithLogsToProfiles overrides the default \"error not supported\" implementation for WithLogsToProfiles and the default \"undefined\" stability level.\nfunc WithLogsToProfiles(createLogsToProfiles CreateLogsToProfilesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.logsToProfilesStabilityLevel = sl\n\t\to.createLogsToProfilesFunc = createLogsToProfiles\n\t})\n}\n\n// WithProfilesToProfiles overrides the default \"error not supported\" implementation for WithProfilesToProfiles and the default \"undefined\" stability level.\nfunc WithProfilesToProfiles(createProfilesToProfiles CreateProfilesToProfilesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.profilesToProfilesStabilityLevel = sl\n\t\to.createProfilesToProfilesFunc = createProfilesToProfiles\n\t})\n}\n\n// WithProfilesToTraces overrides the default \"error not supported\" implementation for WithProfilesToTraces and the default \"undefined\" stability level.\nfunc WithProfilesToTraces(createProfilesToTraces CreateProfilesToTracesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.profilesToTracesStabilityLevel = sl\n\t\to.createProfilesToTracesFunc = createProfilesToTraces\n\t})\n}\n\n// WithProfilesToMetrics overrides the default \"error not supported\" implementation for WithProfilesToMetrics and the default \"undefined\" stability level.\nfunc WithProfilesToMetrics(createProfilesToMetrics CreateProfilesToMetricsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.profilesToMetricsStabilityLevel = sl\n\t\to.createProfilesToMetricsFunc = createProfilesToMetrics\n\t})\n}\n\n// WithProfilesToLogs overrides the default \"error not supported\" implementation for WithProfilesToLogs and the default \"undefined\" stability level.\nfunc WithProfilesToLogs(createProfilesToLogs CreateProfilesToLogsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.profilesToLogsStabilityLevel = sl\n\t\to.createProfilesToLogsFunc = createProfilesToLogs\n\t})\n}\n\n// WithDeprecatedTypeAlias configures a deprecated type alias for the connector. Only one alias is supported per connector.\n// When the alias is used in configuration, a deprecation warning is automatically logged.\nfunc WithDeprecatedTypeAlias(alias component.Type) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.SetDeprecatedAlias(alias)\n\t})\n}\n\n// factory implements the Factory interface.\ntype factory struct {\n\tconnector.Factory\n\tcomponentalias.TypeAliasHolder\n\topts []connector.FactoryOption\n\n\tcreateTracesToProfilesFunc  CreateTracesToProfilesFunc\n\tcreateMetricsToProfilesFunc CreateMetricsToProfilesFunc\n\tcreateLogsToProfilesFunc    CreateLogsToProfilesFunc\n\n\tcreateProfilesToProfilesFunc CreateProfilesToProfilesFunc\n\tcreateProfilesToTracesFunc   CreateProfilesToTracesFunc\n\tcreateProfilesToMetricsFunc  CreateProfilesToMetricsFunc\n\tcreateProfilesToLogsFunc     CreateProfilesToLogsFunc\n\n\ttracesToProfilesStabilityLevel  component.StabilityLevel\n\tmetricsToProfilesStabilityLevel component.StabilityLevel\n\tlogsToProfilesStabilityLevel    component.StabilityLevel\n\n\tprofilesToProfilesStabilityLevel component.StabilityLevel\n\tprofilesToTracesStabilityLevel   component.StabilityLevel\n\tprofilesToMetricsStabilityLevel  component.StabilityLevel\n\tprofilesToLogsStabilityLevel     component.StabilityLevel\n}\n\nfunc (f *factory) TracesToProfilesStability() component.StabilityLevel {\n\treturn f.tracesToProfilesStabilityLevel\n}\n\nfunc (f *factory) MetricsToProfilesStability() component.StabilityLevel {\n\treturn f.metricsToProfilesStabilityLevel\n}\n\nfunc (f *factory) LogsToProfilesStability() component.StabilityLevel {\n\treturn f.logsToProfilesStabilityLevel\n}\n\nfunc (f *factory) ProfilesToProfilesStability() component.StabilityLevel {\n\treturn f.profilesToProfilesStabilityLevel\n}\n\nfunc (f *factory) ProfilesToTracesStability() component.StabilityLevel {\n\treturn f.profilesToTracesStabilityLevel\n}\n\nfunc (f *factory) ProfilesToMetricsStability() component.StabilityLevel {\n\treturn f.profilesToMetricsStabilityLevel\n}\n\nfunc (f *factory) ProfilesToLogsStability() component.StabilityLevel {\n\treturn f.profilesToLogsStabilityLevel\n}\n\nfunc (f *factory) CreateTracesToProfiles(ctx context.Context, set connector.Settings, cfg component.Config, next xconsumer.Profiles) (connector.Traces, error) {\n\tif f.createTracesToProfilesFunc == nil {\n\t\treturn nil, internal.ErrDataTypes(set.ID, pipeline.SignalTraces, xpipeline.SignalProfiles)\n\t}\n\tif err := componentalias.ValidateComponentType(f.Factory, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.createTracesToProfilesFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateMetricsToProfiles(ctx context.Context, set connector.Settings, cfg component.Config, next xconsumer.Profiles) (connector.Metrics, error) {\n\tif f.createMetricsToProfilesFunc == nil {\n\t\treturn nil, internal.ErrDataTypes(set.ID, pipeline.SignalMetrics, xpipeline.SignalProfiles)\n\t}\n\tif err := componentalias.ValidateComponentType(f.Factory, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.createMetricsToProfilesFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateLogsToProfiles(ctx context.Context, set connector.Settings, cfg component.Config, next xconsumer.Profiles) (connector.Logs, error) {\n\tif f.createLogsToProfilesFunc == nil {\n\t\treturn nil, internal.ErrDataTypes(set.ID, pipeline.SignalLogs, xpipeline.SignalProfiles)\n\t}\n\tif err := componentalias.ValidateComponentType(f.Factory, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.createLogsToProfilesFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateProfilesToProfiles(ctx context.Context, set connector.Settings, cfg component.Config, next xconsumer.Profiles) (Profiles, error) {\n\tif f.createProfilesToProfilesFunc == nil {\n\t\treturn nil, internal.ErrDataTypes(set.ID, xpipeline.SignalProfiles, xpipeline.SignalProfiles)\n\t}\n\tif err := componentalias.ValidateComponentType(f.Factory, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.createProfilesToProfilesFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateProfilesToTraces(ctx context.Context, set connector.Settings, cfg component.Config, next consumer.Traces) (Profiles, error) {\n\tif f.createProfilesToTracesFunc == nil {\n\t\treturn nil, internal.ErrDataTypes(set.ID, xpipeline.SignalProfiles, pipeline.SignalTraces)\n\t}\n\tif err := componentalias.ValidateComponentType(f.Factory, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.createProfilesToTracesFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateProfilesToMetrics(ctx context.Context, set connector.Settings, cfg component.Config, next consumer.Metrics) (Profiles, error) {\n\tif f.createProfilesToMetricsFunc == nil {\n\t\treturn nil, internal.ErrDataTypes(set.ID, xpipeline.SignalProfiles, pipeline.SignalMetrics)\n\t}\n\tif err := componentalias.ValidateComponentType(f.Factory, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.createProfilesToMetricsFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateProfilesToLogs(ctx context.Context, set connector.Settings, cfg component.Config, next consumer.Logs) (Profiles, error) {\n\tif f.createProfilesToLogsFunc == nil {\n\t\treturn nil, internal.ErrDataTypes(set.ID, xpipeline.SignalProfiles, pipeline.SignalLogs)\n\t}\n\tif err := componentalias.ValidateComponentType(f.Factory, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.createProfilesToLogsFunc(ctx, set, cfg, next)\n}\n\n// NewFactory creates a wrapped connector.Factory with experimental capabilities\nfunc NewFactory(cfgType component.Type, createDefaultConfig component.CreateDefaultConfigFunc, options ...FactoryOption) Factory {\n\tf := &factory{TypeAliasHolder: componentalias.NewTypeAliasHolder()}\n\tfor _, opt := range options {\n\t\topt.applyOption(f)\n\t}\n\tf.Factory = connector.NewFactory(cfgType, createDefaultConfig, f.opts...)\n\tf.Factory.(componentalias.TypeAliasHolder).SetDeprecatedAlias(f.DeprecatedAlias())\n\treturn f\n}\n"
  },
  {
    "path": "connector/xconnector/connector_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xconnector // import \"go.opentelemetry.io/collector/connector/xconnector\"\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/internal\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n)\n\nvar (\n\ttestType = component.MustNewType(\"test\")\n\ttestID   = component.MustNewIDWithName(testType.String(), \"name\")\n)\n\nfunc TestNewFactoryNoOptions(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tfactory := NewFactory(testType, func() component.Config { return &defaultCfg })\n\tassert.Equal(t, testType, factory.Type())\n\tassert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())\n\n\t_, err := factory.CreateTracesToProfiles(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalTraces, xpipeline.SignalProfiles))\n\t_, err = factory.CreateMetricsToProfiles(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalMetrics, xpipeline.SignalProfiles))\n\t_, err = factory.CreateLogsToProfiles(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, pipeline.SignalLogs, xpipeline.SignalProfiles))\n\n\t_, err = factory.CreateProfilesToTraces(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, xpipeline.SignalProfiles, pipeline.SignalTraces))\n\t_, err = factory.CreateProfilesToMetrics(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, xpipeline.SignalProfiles, pipeline.SignalMetrics))\n\t_, err = factory.CreateProfilesToLogs(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, xpipeline.SignalProfiles, pipeline.SignalLogs))\n}\n\nfunc TestNewFactoryWithSameTypes(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tfactory := NewFactory(testType, func() component.Config { return &defaultCfg },\n\t\tWithProfilesToProfiles(createProfilesToProfiles, component.StabilityLevelAlpha),\n\t)\n\tassert.Equal(t, testType, factory.Type())\n\tassert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())\n\twrongID := component.MustNewID(\"wrong\")\n\twrongIDErrStr := internal.ErrIDMismatch(wrongID, testType).Error()\n\n\tassert.Equal(t, component.StabilityLevelAlpha, factory.ProfilesToProfilesStability())\n\t_, err := factory.CreateProfilesToProfiles(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = factory.CreateProfilesToProfiles(context.Background(), connector.Settings{ID: wrongID}, &defaultCfg, consumertest.NewNop())\n\trequire.ErrorContains(t, err, wrongIDErrStr)\n\n\t_, err = factory.CreateProfilesToTraces(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, xpipeline.SignalProfiles, pipeline.SignalTraces))\n\t_, err = factory.CreateProfilesToMetrics(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, xpipeline.SignalProfiles, pipeline.SignalMetrics))\n\t_, err = factory.CreateProfilesToLogs(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, xpipeline.SignalProfiles, pipeline.SignalLogs))\n}\n\nfunc TestNewFactoryWithTranslateTypes(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tfactory := NewFactory(testType, func() component.Config { return &defaultCfg },\n\t\tWithTracesToProfiles(createTracesToProfiles, component.StabilityLevelBeta),\n\t\tWithMetricsToProfiles(createMetricsToProfiles, component.StabilityLevelDevelopment),\n\t\tWithLogsToProfiles(createLogsToProfiles, component.StabilityLevelAlpha),\n\n\t\tWithProfilesToTraces(createProfilesToTraces, component.StabilityLevelBeta),\n\t\tWithProfilesToMetrics(createProfilesToMetrics, component.StabilityLevelDevelopment),\n\t\tWithProfilesToLogs(createProfilesToLogs, component.StabilityLevelAlpha),\n\t)\n\tassert.Equal(t, testType, factory.Type())\n\tassert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())\n\twrongID := component.MustNewID(\"wrong\")\n\twrongIDErrStr := internal.ErrIDMismatch(wrongID, testType).Error()\n\n\t_, err := factory.CreateProfilesToProfiles(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\tassert.Equal(t, err, internal.ErrDataTypes(testID, xpipeline.SignalProfiles, xpipeline.SignalProfiles))\n\n\tassert.Equal(t, component.StabilityLevelBeta, factory.TracesToProfilesStability())\n\t_, err = factory.CreateTracesToProfiles(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = factory.CreateTracesToProfiles(context.Background(), connector.Settings{ID: wrongID}, &defaultCfg, consumertest.NewNop())\n\trequire.ErrorContains(t, err, wrongIDErrStr)\n\n\tassert.Equal(t, component.StabilityLevelDevelopment, factory.MetricsToProfilesStability())\n\t_, err = factory.CreateMetricsToProfiles(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = factory.CreateMetricsToProfiles(context.Background(), connector.Settings{ID: wrongID}, &defaultCfg, consumertest.NewNop())\n\trequire.ErrorContains(t, err, wrongIDErrStr)\n\n\tassert.Equal(t, component.StabilityLevelAlpha, factory.LogsToProfilesStability())\n\t_, err = factory.CreateLogsToProfiles(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = factory.CreateLogsToProfiles(context.Background(), connector.Settings{ID: wrongID}, &defaultCfg, consumertest.NewNop())\n\trequire.ErrorContains(t, err, wrongIDErrStr)\n\n\tassert.Equal(t, component.StabilityLevelBeta, factory.ProfilesToTracesStability())\n\t_, err = factory.CreateProfilesToTraces(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = factory.CreateProfilesToTraces(context.Background(), connector.Settings{ID: wrongID}, &defaultCfg, consumertest.NewNop())\n\trequire.ErrorContains(t, err, wrongIDErrStr)\n\n\tassert.Equal(t, component.StabilityLevelDevelopment, factory.ProfilesToMetricsStability())\n\t_, err = factory.CreateProfilesToMetrics(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = factory.CreateProfilesToMetrics(context.Background(), connector.Settings{ID: wrongID}, &defaultCfg, consumertest.NewNop())\n\trequire.ErrorContains(t, err, wrongIDErrStr)\n\n\tassert.Equal(t, component.StabilityLevelAlpha, factory.ProfilesToLogsStability())\n\t_, err = factory.CreateProfilesToLogs(context.Background(), connector.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = factory.CreateProfilesToLogs(context.Background(), connector.Settings{ID: wrongID}, &defaultCfg, consumertest.NewNop())\n\trequire.ErrorContains(t, err, wrongIDErrStr)\n}\n\nvar nopInstance = &nopConnector{\n\tConsumer: consumertest.NewNop(),\n}\n\n// nopConnector stores consumed traces and metrics for testing purposes.\ntype nopConnector struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumertest.Consumer\n}\n\nfunc createTracesToProfiles(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (connector.Traces, error) {\n\treturn nopInstance, nil\n}\n\nfunc createMetricsToProfiles(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (connector.Metrics, error) {\n\treturn nopInstance, nil\n}\n\nfunc createLogsToProfiles(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (connector.Logs, error) {\n\treturn nopInstance, nil\n}\n\nfunc createProfilesToProfiles(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (Profiles, error) {\n\treturn nopInstance, nil\n}\n\nfunc createProfilesToTraces(context.Context, connector.Settings, component.Config, consumer.Traces) (Profiles, error) {\n\treturn nopInstance, nil\n}\n\nfunc createProfilesToMetrics(context.Context, connector.Settings, component.Config, consumer.Metrics) (Profiles, error) {\n\treturn nopInstance, nil\n}\n\nfunc createProfilesToLogs(context.Context, connector.Settings, component.Config, consumer.Logs) (Profiles, error) {\n\treturn nopInstance, nil\n}\n\nfunc TestNewFactoryWithDeprecatedAlias(t *testing.T) {\n\ttestType := component.MustNewType(\"newname\")\n\taliasType := component.MustNewType(\"oldname\")\n\tdefaultCfg := struct{}{}\n\n\tf := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg },\n\t\tWithProfilesToProfiles(createProfilesToProfiles, component.StabilityLevelAlpha),\n\t\tWithDeprecatedTypeAlias(aliasType),\n\t)\n\n\tassert.Equal(t, testType, f.Type())\n\tassert.Equal(t, aliasType, f.(*factory).Factory.(componentalias.TypeAliasHolder).DeprecatedAlias())\n\tassert.EqualValues(t, &defaultCfg, f.CreateDefaultConfig())\n\n\t_, err := f.CreateProfilesToProfiles(context.Background(), connector.Settings{ID: component.MustNewID(\"newname\")}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = f.CreateProfilesToProfiles(context.Background(), connector.Settings{ID: component.MustNewID(\"oldname\")}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = f.CreateProfilesToProfiles(context.Background(), connector.Settings{ID: component.MustNewID(\"wrongname\")}, &defaultCfg, consumertest.NewNop())\n\trequire.Error(t, err)\n}\n"
  },
  {
    "path": "connector/xconnector/go.mod",
    "content": "module go.opentelemetry.io/collector/connector/xconnector\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/connector v0.148.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0\n\tgo.opentelemetry.io/collector/internal/fanoutconsumer v0.148.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/connector => ../\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/internal/fanoutconsumer => ../../internal/fanoutconsumer\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "connector/xconnector/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "connector/xconnector/metadata.yaml",
    "content": "type: xconnector\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  codeowners:\n    active:\n      - mx-psi\n      - dmathieu\n  stability:\n    alpha: [profiles]\n"
  },
  {
    "path": "connector/xconnector/profiles_router.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xconnector // import \"go.opentelemetry.io/collector/connector/xconnector\"\n\nimport (\n\t\"go.opentelemetry.io/collector/connector/internal\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/internal/fanoutconsumer\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\ntype ProfilesRouterAndConsumer interface {\n\txconsumer.Profiles\n\tConsumer(...pipeline.ID) (xconsumer.Profiles, error)\n\tPipelineIDs() []pipeline.ID\n\tprivateFunc()\n}\n\ntype profilesRouter struct {\n\txconsumer.Profiles\n\tinternal.BaseRouter[xconsumer.Profiles]\n}\n\nfunc NewProfilesRouter(cm map[pipeline.ID]xconsumer.Profiles) ProfilesRouterAndConsumer {\n\tconsumers := make([]xconsumer.Profiles, 0, len(cm))\n\tfor _, cons := range cm {\n\t\tconsumers = append(consumers, cons)\n\t}\n\treturn &profilesRouter{\n\t\tProfiles:   fanoutconsumer.NewProfiles(consumers),\n\t\tBaseRouter: internal.NewBaseRouter(fanoutconsumer.NewProfiles, cm),\n\t}\n}\n\nfunc (r *profilesRouter) privateFunc() {}\n"
  },
  {
    "path": "connector/xconnector/profiles_router_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xconnector\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n)\n\ntype mutatingProfilesSink struct {\n\t*consumertest.ProfilesSink\n}\n\nfunc (mts *mutatingProfilesSink) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: true}\n}\n\nfunc TestProfilesRouterMultiplexing(t *testing.T) {\n\tnum := 20\n\tfor numIDs := 1; numIDs < num; numIDs++ {\n\t\tfor numCons := 1; numCons < num; numCons++ {\n\t\t\tfor numProfiles := 1; numProfiles < num; numProfiles++ {\n\t\t\t\tt.Run(\n\t\t\t\t\tfmt.Sprintf(\"%d-ids/%d-cons/%d-logs\", numIDs, numCons, numProfiles),\n\t\t\t\t\tfuzzProfiles(numIDs, numCons, numProfiles),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc fuzzProfiles(numIDs, numCons, numProfiles int) func(*testing.T) {\n\treturn func(t *testing.T) {\n\t\tallIDs := make([]pipeline.ID, 0, numCons)\n\t\tallCons := make([]xconsumer.Profiles, 0, numCons)\n\t\tallConsMap := make(map[pipeline.ID]xconsumer.Profiles)\n\n\t\t// If any consumer is mutating, the router must report mutating\n\t\tfor i := range numCons {\n\t\t\tallIDs = append(allIDs, pipeline.NewIDWithName(xpipeline.SignalProfiles, \"sink_\"+strconv.Itoa(numCons)))\n\t\t\t// Random chance for each consumer to be mutating\n\t\t\tif (numCons+numProfiles+i)%4 == 0 {\n\t\t\t\tallCons = append(allCons, &mutatingProfilesSink{ProfilesSink: new(consumertest.ProfilesSink)})\n\t\t\t} else {\n\t\t\t\tallCons = append(allCons, new(consumertest.ProfilesSink))\n\t\t\t}\n\t\t\tallConsMap[allIDs[i]] = allCons[i]\n\t\t}\n\n\t\tr := NewProfilesRouter(allConsMap)\n\t\ttd := testdata.GenerateProfiles(1)\n\n\t\t// Keep track of how many logs each consumer should receive.\n\t\t// This will be validated after every call to RouteProfiles.\n\t\texpected := make(map[pipeline.ID]int, numCons)\n\n\t\tfor i := range numProfiles {\n\t\t\t// Build a random set of ids (no duplicates)\n\t\t\trandCons := make(map[pipeline.ID]bool, numIDs)\n\t\t\tfor j := range numIDs {\n\t\t\t\t// This number should be pretty random and less than numCons\n\t\t\t\tconNum := (numCons + numIDs + i + j) % numCons\n\t\t\t\trandCons[allIDs[conNum]] = true\n\t\t\t}\n\n\t\t\t// Convert to slice, update expectations\n\t\t\tconIDs := make([]pipeline.ID, 0, len(randCons))\n\t\t\tfor id := range randCons {\n\t\t\t\tconIDs = append(conIDs, id)\n\t\t\t\texpected[id]++\n\t\t\t}\n\n\t\t\t// Route to list of consumers\n\t\t\tfanout, err := r.Consumer(conIDs...)\n\t\t\tassert.NoError(t, err)\n\t\t\tassert.NoError(t, fanout.ConsumeProfiles(context.Background(), td))\n\n\t\t\t// Validate expectations for all consumers\n\t\t\tfor id := range expected {\n\t\t\t\tprofiles := []pprofile.Profiles{}\n\t\t\t\tswitch con := allConsMap[id].(type) {\n\t\t\t\tcase *consumertest.ProfilesSink:\n\t\t\t\t\tprofiles = con.AllProfiles()\n\t\t\t\tcase *mutatingProfilesSink:\n\t\t\t\t\tprofiles = con.AllProfiles()\n\t\t\t\t}\n\t\t\t\tassert.Len(t, profiles, expected[id])\n\t\t\t\tfor n := 0; n < len(profiles); n++ {\n\t\t\t\t\tassert.Equal(t, td, profiles[n])\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestProfilessRouterConsumer(t *testing.T) {\n\tctx := context.Background()\n\ttd := testdata.GenerateProfiles(1)\n\n\tfooID := pipeline.NewIDWithName(xpipeline.SignalProfiles, \"foo\")\n\tbarID := pipeline.NewIDWithName(xpipeline.SignalProfiles, \"bar\")\n\n\tfoo := new(consumertest.ProfilesSink)\n\tbar := new(consumertest.ProfilesSink)\n\tr := NewProfilesRouter(map[pipeline.ID]xconsumer.Profiles{fooID: foo, barID: bar})\n\n\trcs := r.PipelineIDs()\n\tassert.Len(t, rcs, 2)\n\tassert.ElementsMatch(t, []pipeline.ID{fooID, barID}, rcs)\n\n\tassert.Empty(t, foo.AllProfiles())\n\tassert.Empty(t, bar.AllProfiles())\n\n\tboth, err := r.Consumer(fooID, barID)\n\tassert.NotNil(t, both)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, both.ConsumeProfiles(ctx, td))\n\tassert.Len(t, foo.AllProfiles(), 1)\n\tassert.Len(t, bar.AllProfiles(), 1)\n\n\tfooOnly, err := r.Consumer(fooID)\n\tassert.NotNil(t, fooOnly)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, fooOnly.ConsumeProfiles(ctx, td))\n\tassert.Len(t, foo.AllProfiles(), 2)\n\tassert.Len(t, bar.AllProfiles(), 1)\n\n\tbarOnly, err := r.Consumer(barID)\n\tassert.NotNil(t, barOnly)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, barOnly.ConsumeProfiles(ctx, td))\n\tassert.Len(t, foo.AllProfiles(), 2)\n\tassert.Len(t, bar.AllProfiles(), 2)\n\n\tnone, err := r.Consumer()\n\tassert.Nil(t, none)\n\trequire.Error(t, err)\n\n\tfake, err := r.Consumer(pipeline.NewIDWithName(xpipeline.SignalProfiles, \"fake\"))\n\tassert.Nil(t, fake)\n\tassert.Error(t, err)\n}\n"
  },
  {
    "path": "consumer/Makefile",
    "content": "include ../Makefile.Common\n"
  },
  {
    "path": "consumer/consumer.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumer // import \"go.opentelemetry.io/collector/consumer\"\n\nimport (\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/consumer/internal\"\n)\n\n// Capabilities describes the capabilities of a Processor.\ntype Capabilities = internal.Capabilities\n\nvar errNilFunc = errors.New(\"nil consumer func\")\n\n// Option to construct new consumers.\ntype Option = internal.Option\n\n// WithCapabilities overrides the default GetCapabilities function for a processor.\n// The default GetCapabilities function returns mutable capabilities.\nfunc WithCapabilities(capabilities Capabilities) Option {\n\treturn internal.OptionFunc(func(o *internal.BaseImpl) {\n\t\to.Cap = capabilities\n\t})\n}\n"
  },
  {
    "path": "consumer/consumererror/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "consumer/consumererror/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package consumererror provides wrappers to easily classify errors. This allows\n// appropriate action by error handlers without the need to know each individual\n// error type/instance. These errors are returned by the Consume*() functions of\n// the consumer interfaces.\n//\n// # Error handling\n//\n// The consumererror package provides a way to classify errors into two categories: Permanent and\n// NonPermanent. The Permanent errors are those that are not expected to be resolved by retrying the\n// same data.\n//\n// If the error is Permanent, then the Consume*() call should not be retried with the same data.\n// This typically happens when the data cannot be serialized by the exporter that is attached to the\n// pipeline or when the destination refuses the data because it cannot decode it.\n//\n// If the error is non-Permanent then the Consume*() call should be retried with the same data. This\n// may be done by the component itself, however typically it is done by the original sender, after\n// the receiver in the pipeline returns a response to the sender indicating that the Collector is\n// currently overloaded and the request must be retried.\npackage consumererror // import \"go.opentelemetry.io/collector/consumer/consumererror\"\n"
  },
  {
    "path": "consumer/consumererror/downstream.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumererror // import \"go.opentelemetry.io/collector/consumer/consumererror\"\n\nimport \"errors\"\n\ntype downstreamError struct {\n\tinner error\n}\n\nvar _ error = downstreamError{}\n\nfunc (de downstreamError) Error() string {\n\treturn de.inner.Error()\n}\n\nfunc (de downstreamError) Unwrap() error {\n\treturn de.inner\n}\n\n// NewDownstream wraps an error to indicate that it is a downstream error, i.e. an\n// error that does not come from the current component, but from one further downstream.\n// This is used by pipeline instrumentation to determine whether an operation's outcome\n// was an internal failure, or if it successfully produced data that was later refused.\n// This wrapper is not intended to be used manually inside components.\nfunc NewDownstream(err error) error {\n\treturn downstreamError{\n\t\tinner: err,\n\t}\n}\n\n// IsDownstream checks if an error was wrapped with the NewDownstream function,\n// or if it contains one such error in its Unwrap() tree.\nfunc IsDownstream(err error) bool {\n\tvar de downstreamError\n\treturn errors.As(err, &de)\n}\n"
  },
  {
    "path": "consumer/consumererror/downstream_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumererror\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\n//nolint:testifylint // Testing properties of errors, no reason to use require\nfunc TestDownstream(t *testing.T) {\n\terr1 := errors.New(\"test error\")\n\tassert.False(t, IsDownstream(err1))\n\terr2 := errors.New(\"test error 2\")\n\tassert.False(t, IsDownstream(err2))\n\n\terrDownstream1 := NewDownstream(err1)\n\tassert.True(t, IsDownstream(errDownstream1))\n\tassert.Equal(t, err1.Error(), errDownstream1.Error())\n\tassert.ErrorIs(t, errDownstream1, err1)\n\tassert.NotErrorIs(t, errDownstream1, err2)\n\n\t// we can access downstream wrappers through other wrappers\n\terrWrapDownstream := NewRetryableError(errDownstream1)\n\tassert.True(t, IsDownstream(errWrapDownstream))\n\terrorStruct := new(Error)\n\tassert.ErrorAs(t, errWrapDownstream, &errorStruct)\n\n\t// we can access other wrappers through downstream wrappers\n\terrDownstreamWrap := NewDownstream(NewRetryableError(err1))\n\tassert.True(t, IsDownstream(errDownstreamWrap))\n\tassert.ErrorAs(t, errDownstreamWrap, &errorStruct)\n\n\t// downstream + downstream = downstream\n\terrJoin2 := errors.Join(errDownstream1, NewDownstream(err2))\n\tassert.True(t, IsDownstream(errJoin2))\n\n\t// downstream + not downstream = downstream\n\terrJoin1 := errors.Join(errDownstream1, err2)\n\tassert.True(t, IsDownstream(errJoin1))\n}\n"
  },
  {
    "path": "consumer/consumererror/error.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumererror // import \"go.opentelemetry.io/collector/consumer/consumererror\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/http\"\n\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/consumer/consumererror/internal/statusconversion\"\n)\n\n// Error is intended to be used to encapsulate various information that can add\n// context to an error that occurred within a pipeline component. Error objects\n// are constructed through calling `New` with the relevant options to capture\n// data around the error that occurred.\n//\n// Error should be obtained from a given `error` object using `errors.As`.\ntype Error struct {\n\terror\n\thttpStatus  int\n\tgrpcStatus  *status.Status\n\tisRetryable bool\n}\n\nvar _ error = (*Error)(nil)\n\n// NewOTLPHTTPError records an HTTP status code that was received from a server\n// during data submission.\n//\n// NOTE: This function will panic if passed an HTTP status between 200 and 299 inclusive.\n// This is to reserve the behavior for handling these codes for the future.\nfunc NewOTLPHTTPError(origErr error, httpStatus int) error {\n\t// Matches what is considered a successful response in the OTLP/HTTP Exporter.\n\tif httpStatus >= 200 && httpStatus <= 299 {\n\t\tpanic(\"NewOTLPHTTPError should not be called with a success code\")\n\t}\n\tvar retryable bool\n\tswitch httpStatus {\n\tcase http.StatusTooManyRequests, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:\n\t\tretryable = true\n\t}\n\n\treturn &Error{error: origErr, httpStatus: httpStatus, isRetryable: retryable}\n}\n\n// NewOTLPGRPCError records a gRPC status code that was received from a server\n// during data submission.\n//\n// NOTE: This function will panic if passed a *status.Status with an underlying\n// code of codes.OK. This is to reserve the behavior for handling this code for\n// the future.\nfunc NewOTLPGRPCError(origErr error, status *status.Status) error {\n\tvar retryable bool\n\tif status != nil {\n\t\tswitch status.Code() {\n\t\tcase codes.Canceled, codes.DeadlineExceeded, codes.Aborted, codes.OutOfRange, codes.Unavailable, codes.DataLoss:\n\t\t\tretryable = true\n\t\t// Matches what is considered a successful response in the OTLP Exporter.\n\t\tcase codes.OK:\n\t\t\tpanic(\"NewOTLPGRPCError should not be called with an OK code\")\n\t\t}\n\t}\n\n\treturn &Error{error: origErr, grpcStatus: status, isRetryable: retryable}\n}\n\n// NewRetryableError records that this error is retryable according to OTLP specification.\nfunc NewRetryableError(origErr error) error {\n\treturn &Error{error: origErr, isRetryable: true}\n}\n\n// Error implements the error interface.\n//\n// If an error object was given, that is used.\n// Otherwise, the gRPC error from the status.Status is used,\n// or an error message containing the HTTP status code is given.\nfunc (e *Error) Error() string {\n\tif e.error != nil {\n\t\treturn e.error.Error()\n\t}\n\n\tif e.grpcStatus != nil {\n\t\treturn e.grpcStatus.Err().Error()\n\t} else if e.httpStatus > 0 {\n\t\treturn fmt.Sprintf(\"network error: received HTTP status %d\", e.httpStatus)\n\t}\n\n\treturn \"uninitialized consumererror.Error\"\n}\n\n// Unwrap returns the wrapped error for use by `errors.Is` and `errors.As`.\n//\n// If an error object was not passed but a gRPC `status.Status` was passed,\n// the underlying error from the status is returned.\nfunc (e *Error) Unwrap() error {\n\tif e.error != nil {\n\t\treturn e.error\n\t}\n\n\tif e.grpcStatus != nil {\n\t\treturn e.grpcStatus.Err()\n\t}\n\n\treturn nil\n}\n\n// IsRetryable returns true if the error was created with NewRetryableError, if\n// the HTTP status code is retryable according to OTLP, or if the gRPC status is\n// retryable according to OTLP. Otherwise, returns false.\n//\n// See https://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md for retryable\n// HTTP and gRPC codes.\nfunc (e *Error) IsRetryable() bool {\n\treturn e.isRetryable\n}\n\n// ToHTTPStatus returns an HTTP status code either directly set by the source on\n// an [Error] object, derived from a gRPC status code set by the source, or\n// derived from Retryable. When deriving the value, the OTLP specification is\n// used to map to HTTP. See\n// https://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md\n// for more details.\n//\n// If a http status code cannot be derived from these three sources then 500 is\n// returned.\nfunc ToHTTPStatus(err error) int {\n\tvar e *Error\n\tif errors.As(err, &e) {\n\t\tif e.httpStatus != 0 {\n\t\t\treturn e.httpStatus\n\t\t}\n\t\tif e.grpcStatus != nil {\n\t\t\treturn statusconversion.GetHTTPStatusCodeFromStatus(e.grpcStatus)\n\t\t}\n\t\tif e.isRetryable {\n\t\t\treturn http.StatusServiceUnavailable\n\t\t}\n\t}\n\treturn http.StatusInternalServerError\n}\n\n// ToGRPCStatus returns a gRPC status code either directly set by the source on\n// an [Error] object, derived from an HTTP status code set by the\n// source, or derived from Retryable. When deriving the value, the OTLP\n// specification is used to map to gRPC. See\n// https://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md\n// for more details.\n//\n// If an [Error] object is not present, then we attempt to get a status.Status from the\n// error tree.\n//\n// If a status.Status cannot be derived from these sources then INTERNAL is\n// returned.\nfunc ToGRPCStatus(err error) *status.Status {\n\tvar e *Error\n\tif errors.As(err, &e) {\n\t\tif e.grpcStatus != nil {\n\t\t\treturn e.grpcStatus\n\t\t}\n\t\tif e.httpStatus != 0 {\n\t\t\treturn statusconversion.NewStatusFromMsgAndHTTPCode(e.Error(), e.httpStatus)\n\t\t}\n\t\tif e.isRetryable {\n\t\t\treturn status.New(codes.Unavailable, e.Error())\n\t\t}\n\t}\n\tif st, ok := status.FromError(err); ok {\n\t\treturn st\n\t}\n\treturn status.New(codes.Unknown, e.Error())\n}\n"
  },
  {
    "path": "consumer/consumererror/error_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumererror\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n)\n\nvar errTest = errors.New(\"consumererror testing error\")\n\nfunc Test_NewOTLPHTTPError(t *testing.T) {\n\thttpStatus := 500\n\twantErr := &Error{\n\t\terror:      errTest,\n\t\thttpStatus: httpStatus,\n\t}\n\n\tnewErr := NewOTLPHTTPError(errTest, httpStatus)\n\n\trequire.Equal(t, wantErr, newErr)\n}\n\nfunc Test_NewOTLPGRPCError(t *testing.T) {\n\tgrpcStatus := status.New(codes.Aborted, \"aborted\")\n\twantErr := &Error{\n\t\terror:       errTest,\n\t\tgrpcStatus:  grpcStatus,\n\t\tisRetryable: true,\n\t}\n\n\tnewErr := NewOTLPGRPCError(errTest, grpcStatus)\n\n\trequire.Equal(t, wantErr, newErr)\n}\n\nfunc Test_NewRetryableError(t *testing.T) {\n\twantErr := &Error{\n\t\terror:       errTest,\n\t\tisRetryable: true,\n\t}\n\n\tnewErr := NewRetryableError(errTest)\n\n\trequire.Equal(t, wantErr, newErr)\n}\n\nfunc Test_Error(t *testing.T) {\n\tnewErr := Error{error: errTest}\n\n\trequire.Equal(t, errTest.Error(), newErr.Error())\n}\n\nfunc TestUnwrap(t *testing.T) {\n\tgrpcErr := status.New(codes.InvalidArgument, \"not allowed\")\n\ttestCases := []struct {\n\t\tname     string\n\t\terr      *Error\n\t\texpected error\n\t}{\n\t\t{\n\t\t\tname: \"Error object\",\n\t\t\terr: &Error{\n\t\t\t\terror:      errTest,\n\t\t\t\tgrpcStatus: grpcErr,\n\t\t\t},\n\t\t\texpected: errTest,\n\t\t},\n\t\t{\n\t\t\tname: \"gRPC error\",\n\t\t\terr: &Error{\n\t\t\t\tgrpcStatus: grpcErr,\n\t\t\t},\n\t\t\texpected: grpcErr.Err(),\n\t\t},\n\t\t{\n\t\t\tname:     \"zero value struct\",\n\t\t\terr:      &Error{},\n\t\t\texpected: nil,\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\trequire.Equal(t, tt.expected, tt.err.Unwrap())\n\t\t})\n\t}\n}\n\nfunc TestAs(t *testing.T) {\n\terr := &Error{\n\t\terror: errTest,\n\t}\n\n\tsecondError := errors.Join(errors.New(\"test\"), err)\n\n\tvar e *Error\n\trequire.ErrorAs(t, secondError, &e)\n\tassert.Equal(t, errTest.Error(), e.Error())\n}\n\nfunc TestError_Error(t *testing.T) {\n\ttestCases := []struct {\n\t\tname     string\n\t\terr      *Error\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname: \"Error object\",\n\t\t\terr: &Error{\n\t\t\t\terror:      errTest,\n\t\t\t\tgrpcStatus: status.New(codes.InvalidArgument, \"not allowed\"),\n\t\t\t\thttpStatus: 400,\n\t\t\t},\n\t\t\texpected: errTest.Error(),\n\t\t},\n\t\t{\n\t\t\tname: \"gRPC error\",\n\t\t\terr: &Error{\n\t\t\t\tgrpcStatus: status.New(codes.InvalidArgument, \"not allowed\"),\n\t\t\t},\n\t\t\texpected: \"rpc error: code = InvalidArgument desc = not allowed\",\n\t\t},\n\t\t{\n\t\t\tname: \"HTTP error\",\n\t\t\terr: &Error{\n\t\t\t\thttpStatus: 400,\n\t\t\t},\n\t\t\texpected: \"network error: received HTTP status 400\",\n\t\t},\n\t\t{\n\t\t\tname:     \"zero value struct\",\n\t\t\terr:      &Error{},\n\t\t\texpected: \"uninitialized consumererror.Error\",\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\trequire.Equal(t, tt.expected, tt.err.Error())\n\t\t})\n\t}\n}\n\nfunc TestError_Unwrap(t *testing.T) {\n\terr := &Error{\n\t\terror: errTest,\n\t}\n\n\trequire.Equal(t, errTest, err.Unwrap())\n}\n\nfunc TestError_ToHTTPStatus(t *testing.T) {\n\tserverErr := http.StatusTooManyRequests\n\ttestCases := []struct {\n\t\tname       string\n\t\thttpStatus int\n\t\tgrpcStatus *status.Status\n\t\tretryable  bool\n\t\twant       int\n\t\thasCode    bool\n\t}{\n\t\t{\n\t\t\tname:       \"Passes through HTTP status\",\n\t\t\thttpStatus: serverErr,\n\t\t\twant:       serverErr,\n\t\t\thasCode:    true,\n\t\t},\n\t\t{\n\t\t\tname:       \"Converts gRPC status\",\n\t\t\tgrpcStatus: status.New(codes.ResourceExhausted, errTest.Error()),\n\t\t\twant:       serverErr,\n\t\t\thasCode:    true,\n\t\t},\n\t\t{\n\t\t\tname:       \"Passes through HTTP status when gRPC status also present\",\n\t\t\thttpStatus: serverErr,\n\t\t\tgrpcStatus: status.New(codes.OK, errTest.Error()),\n\t\t\twant:       serverErr,\n\t\t\thasCode:    true,\n\t\t},\n\t\t{\n\t\t\tname:       \"Passes through HTTP status when retryable also present\",\n\t\t\thttpStatus: serverErr,\n\t\t\tretryable:  true,\n\t\t\twant:       serverErr,\n\t\t},\n\t\t{\n\t\t\tname:      \"No statuses set with retryable\",\n\t\t\tretryable: true,\n\t\t\twant:      http.StatusServiceUnavailable,\n\t\t},\n\t\t{\n\t\t\tname: \"No statuses set\",\n\t\t\twant: http.StatusInternalServerError,\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := &Error{\n\t\t\t\terror:       errTest,\n\t\t\t\thttpStatus:  tt.httpStatus,\n\t\t\t\tgrpcStatus:  tt.grpcStatus,\n\t\t\t\tisRetryable: tt.retryable,\n\t\t\t}\n\n\t\t\ts := ToHTTPStatus(err)\n\n\t\t\trequire.Equal(t, tt.want, s)\n\t\t})\n\t}\n}\n\nfunc TestError_ToGRPCStatus(t *testing.T) {\n\thttpStatus := http.StatusTooManyRequests\n\totherOTLPHTTPStatus := http.StatusOK\n\tserverErr := status.New(codes.ResourceExhausted, errTest.Error())\n\ttestCases := []struct {\n\t\tname       string\n\t\thttpStatus int\n\t\tgrpcStatus *status.Status\n\t\tretryable  bool\n\t\twant       *status.Status\n\t\thasCode    bool\n\t}{\n\t\t{\n\t\t\tname:       \"Converts HTTP status\",\n\t\t\thttpStatus: httpStatus,\n\t\t\twant:       serverErr,\n\t\t\thasCode:    true,\n\t\t},\n\t\t{\n\t\t\tname:       \"Passes through gRPC status\",\n\t\t\tgrpcStatus: serverErr,\n\t\t\twant:       serverErr,\n\t\t\thasCode:    true,\n\t\t},\n\t\t{\n\t\t\tname:       \"Passes through gRPC status when HTTP status also present\",\n\t\t\thttpStatus: otherOTLPHTTPStatus,\n\t\t\tgrpcStatus: serverErr,\n\t\t\twant:       serverErr,\n\t\t\thasCode:    true,\n\t\t},\n\t\t{\n\t\t\tname:       \"Passes through gRPC status when retryable also present\",\n\t\t\tgrpcStatus: serverErr,\n\t\t\tretryable:  true,\n\t\t\twant:       serverErr,\n\t\t},\n\t\t{\n\t\t\tname:      \"No statuses set with retryable\",\n\t\t\tretryable: true,\n\t\t\twant:      status.New(codes.Unavailable, errTest.Error()),\n\t\t},\n\t\t{\n\t\t\tname: \"No statuses set\",\n\t\t\twant: status.New(codes.Unknown, errTest.Error()),\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := &Error{\n\t\t\t\terror:       errTest,\n\t\t\t\thttpStatus:  tt.httpStatus,\n\t\t\t\tgrpcStatus:  tt.grpcStatus,\n\t\t\t\tisRetryable: tt.retryable,\n\t\t\t}\n\n\t\t\ts := ToGRPCStatus(err)\n\n\t\t\trequire.Equal(t, tt.want, s)\n\t\t})\n\t}\n}\n\nfunc TestStatus_ToGRPCStatus(t *testing.T) {\n\tst := status.New(codes.ResourceExhausted, errTest.Error())\n\trequire.Equal(t, st, ToGRPCStatus(st.Err()))\n}\n\nfunc TestError_Retryable(t *testing.T) {\n\tretryableCodes := []codes.Code{codes.Canceled, codes.DeadlineExceeded, codes.Aborted, codes.OutOfRange, codes.Unavailable, codes.DataLoss}\n\tretryableStatuses := []*status.Status{}\n\n\tfor _, code := range retryableCodes {\n\t\tretryableStatuses = append(retryableStatuses, status.New(code, errTest.Error()))\n\t}\n\n\tnonretryableCodes := []codes.Code{codes.Unauthenticated, codes.Unknown, codes.NotFound, codes.InvalidArgument}\n\tnonretryableStatuses := []*status.Status{}\n\n\tfor _, code := range nonretryableCodes {\n\t\tnonretryableStatuses = append(nonretryableStatuses, status.New(code, errTest.Error()))\n\t}\n\n\ttestCases := []struct {\n\t\tname         string\n\t\thttpStatuses []int\n\t\tgrpcStatuses []*status.Status\n\t\twant         bool\n\t}{\n\t\t{\n\t\t\tname:         \"HTTP statuses: retryable\",\n\t\t\thttpStatuses: []int{http.StatusTooManyRequests, http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout},\n\t\t\twant:         true,\n\t\t},\n\t\t{\n\t\t\tname:         \"HTTP statuses: non-retryable\",\n\t\t\thttpStatuses: []int{0, http.StatusInternalServerError, http.StatusNotFound, http.StatusUnauthorized},\n\t\t\twant:         false,\n\t\t},\n\t\t{\n\t\t\tname:         \"gRPC statuses: retryable\",\n\t\t\tgrpcStatuses: retryableStatuses,\n\t\t\twant:         true,\n\t\t},\n\t\t{\n\t\t\tname:         \"gRPC statuses: non-retryable\",\n\t\t\tgrpcStatuses: nonretryableStatuses,\n\t\t\twant:         false,\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tfor _, httpStatus := range tt.httpStatuses {\n\t\t\t\terr := NewOTLPHTTPError(errTest, httpStatus)\n\t\t\t\tvar httpErr *Error\n\t\t\t\tif errors.As(err, &httpErr) {\n\t\t\t\t\trequire.Equal(t, tt.want, httpErr.IsRetryable(), \"Expected %d to be retryable=%t\", httpStatus, tt.want)\n\t\t\t\t} else {\n\t\t\t\t\trequire.Fail(t, \"NewOTLPHTTPError didn't return an *Error\")\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfor _, grpcStatus := range tt.grpcStatuses {\n\t\t\t\terr := NewOTLPGRPCError(errTest, grpcStatus)\n\t\t\t\tvar grpcErr *Error\n\n\t\t\t\tif errors.As(err, &grpcErr) {\n\t\t\t\t\trequire.Equal(t, tt.want, grpcErr.IsRetryable(), \"Expected %q to be retryable=%t\", grpcStatus.Code().String(), tt.want)\n\t\t\t\t} else {\n\t\t\t\t\trequire.Fail(t, \"NewOTLPGRPCError didn't return an *Error\")\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestSuccessCodes(t *testing.T) {\n\trequire.Panics(t, func() {\n\t\t_ = NewOTLPHTTPError(nil, 200)\n\t})\n\trequire.Panics(t, func() {\n\t\t_ = NewOTLPHTTPError(nil, 299)\n\t})\n\trequire.NotPanics(t, func() {\n\t\trequire.Error(t, NewOTLPHTTPError(nil, 199))\n\t})\n\trequire.NotPanics(t, func() {\n\t\trequire.Error(t, NewOTLPHTTPError(nil, 300))\n\t})\n\trequire.Panics(t, func() {\n\t\t_ = NewOTLPGRPCError(nil, status.New(codes.OK, \"\"))\n\t})\n\trequire.NotPanics(t, func() {\n\t\trequire.Error(t, NewOTLPGRPCError(nil, status.New(codes.AlreadyExists, \"\")))\n\t})\n}\n"
  },
  {
    "path": "consumer/consumererror/go.mod",
    "content": "module go.opentelemetry.io/collector/consumer/consumererror\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.uber.org/goleak v1.3.0\n\tgoogle.golang.org/grpc v1.79.3\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/kr/text v0.2.0 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n"
  },
  {
    "path": "consumer/consumererror/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/otel v1.40.0 h1:oA5YeOcpRTXq6NN7frwmwFR0Cn3RhTVZvXsP4duvCms=\ngo.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlV14J0g=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "consumer/consumererror/internal/retryable.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/consumer/consumererror/internal\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\ntype Retryable[V ptrace.Traces | pmetric.Metrics | plog.Logs | pprofile.Profiles] struct {\n\tErr   error\n\tValue V\n}\n\n// Error provides the error message\nfunc (err Retryable[V]) Error() string {\n\treturn err.Err.Error()\n}\n\n// Unwrap returns the wrapped error for functions Is and As in standard package errors.\nfunc (err Retryable[V]) Unwrap() error {\n\treturn err.Err\n}\n\n// Data returns the telemetry data that failed to be processed or sent.\nfunc (err Retryable[V]) Data() V {\n\treturn err.Value\n}\n"
  },
  {
    "path": "consumer/consumererror/internal/statusconversion/conversion.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage statusconversion // import \"go.opentelemetry.io/collector/consumer/consumererror/internal/statusconversion\"\n\nimport (\n\t\"net/http\"\n\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n)\n\nfunc GetHTTPStatusCodeFromStatus(s *status.Status) int {\n\t// See https://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md#failures\n\t// to see if a code is retryable.\n\t// See https://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md#failures-1\n\t// to see a list of retryable http status codes.\n\tswitch s.Code() {\n\t// Retryable\n\tcase codes.Canceled, codes.DeadlineExceeded, codes.Aborted, codes.OutOfRange, codes.Unavailable, codes.DataLoss:\n\t\treturn http.StatusServiceUnavailable\n\t// Retryable\n\tcase codes.ResourceExhausted:\n\t\treturn http.StatusTooManyRequests\n\t// Not Retryable\n\tcase codes.InvalidArgument:\n\t\treturn http.StatusBadRequest\n\t// Not Retryable\n\tcase codes.Unauthenticated:\n\t\treturn http.StatusUnauthorized\n\t// Not Retryable\n\tcase codes.PermissionDenied:\n\t\treturn http.StatusForbidden\n\t// Not Retryable\n\tcase codes.Unimplemented:\n\t\treturn http.StatusNotFound\n\t// Not Retryable\n\tdefault:\n\t\treturn http.StatusInternalServerError\n\t}\n}\n\nfunc NewStatusFromMsgAndHTTPCode(errMsg string, statusCode int) *status.Status {\n\tvar c codes.Code\n\t// Mapping based on https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md\n\t// 429 mapping to ResourceExhausted and 400 mapping to StatusBadRequest are exceptions.\n\tswitch statusCode {\n\tcase http.StatusBadRequest:\n\t\tc = codes.InvalidArgument\n\tcase http.StatusUnauthorized:\n\t\tc = codes.Unauthenticated\n\tcase http.StatusForbidden:\n\t\tc = codes.PermissionDenied\n\tcase http.StatusNotFound:\n\t\tc = codes.Unimplemented\n\tcase http.StatusTooManyRequests:\n\t\tc = codes.ResourceExhausted\n\tcase http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:\n\t\tc = codes.Unavailable\n\tdefault:\n\t\tc = codes.Unknown\n\t}\n\treturn status.New(c, errMsg)\n}\n"
  },
  {
    "path": "consumer/consumererror/internal/statusconversion/conversion_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage statusconversion // import \"go.opentelemetry.io/collector/consumer/consumererror/internal/statusconversion\"\n\nimport (\n\t\"net/http\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n)\n\nfunc Test_GetHTTPStatusCodeFromStatus(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    *status.Status\n\t\texpected int\n\t}{\n\t\t{\n\t\t\tname:     \"Retryable Status\",\n\t\t\tinput:    status.New(codes.Unavailable, \"test\"),\n\t\t\texpected: http.StatusServiceUnavailable,\n\t\t},\n\t\t{\n\t\t\tname:     \"Non-retryable Status\",\n\t\t\tinput:    status.New(codes.InvalidArgument, \"test\"),\n\t\t\texpected: http.StatusBadRequest,\n\t\t},\n\t\t{\n\t\t\tname:     \"Specifically 429\",\n\t\t\tinput:    status.New(codes.ResourceExhausted, \"test\"),\n\t\t\texpected: http.StatusTooManyRequests,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := GetHTTPStatusCodeFromStatus(tt.input)\n\t\t\tassert.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc Test_ErrorMsgAndHTTPCodeToStatus(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\terrMsg     string\n\t\tstatusCode int\n\t\texpected   *status.Status\n\t}{\n\t\t{\n\t\t\tname:       \"Bad Request\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusBadRequest,\n\t\t\texpected:   status.New(codes.InvalidArgument, \"test\"),\n\t\t},\n\t\t{\n\t\t\tname:       \"Unauthorized\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusUnauthorized,\n\t\t\texpected:   status.New(codes.Unauthenticated, \"test\"),\n\t\t},\n\t\t{\n\t\t\tname:       \"Forbidden\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusForbidden,\n\t\t\texpected:   status.New(codes.PermissionDenied, \"test\"),\n\t\t},\n\t\t{\n\t\t\tname:       \"Not Found\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusNotFound,\n\t\t\texpected:   status.New(codes.Unimplemented, \"test\"),\n\t\t},\n\t\t{\n\t\t\tname:       \"Too Many Requests\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusTooManyRequests,\n\t\t\texpected:   status.New(codes.ResourceExhausted, \"test\"),\n\t\t},\n\t\t{\n\t\t\tname:       \"Bad Gateway\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusBadGateway,\n\t\t\texpected:   status.New(codes.Unavailable, \"test\"),\n\t\t},\n\t\t{\n\t\t\tname:       \"Service Unavailable\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusServiceUnavailable,\n\t\t\texpected:   status.New(codes.Unavailable, \"test\"),\n\t\t},\n\t\t{\n\t\t\tname:       \"Gateway Timeout\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusGatewayTimeout,\n\t\t\texpected:   status.New(codes.Unavailable, \"test\"),\n\t\t},\n\t\t{\n\t\t\tname:       \"Unsupported Media Type\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusUnsupportedMediaType,\n\t\t\texpected:   status.New(codes.Unknown, \"test\"),\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := NewStatusFromMsgAndHTTPCode(tt.errMsg, tt.statusCode)\n\t\t\tassert.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "consumer/consumererror/metadata.yaml",
    "content": "type: consumer/consumererror\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "consumer/consumererror/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumererror\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "consumer/consumererror/permanent.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumererror // import \"go.opentelemetry.io/collector/consumer/consumererror\"\n\nimport \"errors\"\n\n// permanent is an error that will be always returned if its source\n// receives the same inputs.\ntype permanent struct {\n\terr error\n}\n\n// NewPermanent wraps an error to indicate that it is a permanent error, i.e. an\n// error that will be always returned if its source receives the same inputs.\nfunc NewPermanent(err error) error {\n\treturn permanent{err: err}\n}\n\nfunc (p permanent) Error() string {\n\treturn \"Permanent error: \" + p.err.Error()\n}\n\n// Unwrap returns the wrapped error for functions Is and As in standard package errors.\nfunc (p permanent) Unwrap() error {\n\treturn p.err\n}\n\n// IsPermanent checks if an error was wrapped with the NewPermanent function, which\n// is used to indicate that a given error will always be returned in the case\n// that its sources receives the same input.\nfunc IsPermanent(err error) bool {\n\tif err == nil {\n\t\treturn false\n\t}\n\treturn errors.As(err, &permanent{})\n}\n"
  },
  {
    "path": "consumer/consumererror/permanent_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumererror\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\ntype testErrorType struct {\n\ts string\n}\n\nfunc (t testErrorType) Error() string {\n\treturn \"\"\n}\n\nfunc TestIsPermanent(t *testing.T) {\n\tvar err error\n\tassert.False(t, IsPermanent(err))\n\n\terr = errors.New(\"testError\")\n\tassert.False(t, IsPermanent(err))\n\n\terr = NewPermanent(err)\n\tassert.True(t, IsPermanent(err))\n\n\terr = fmt.Errorf(\"%w\", err)\n\tassert.True(t, IsPermanent(err))\n}\n\nfunc TestPermanent_Unwrap(t *testing.T) {\n\tvar err error = testErrorType{\"testError\"}\n\trequire.False(t, IsPermanent(err))\n\n\t// Wrapping testErrorType err with permanent error.\n\tpermanentErr := NewPermanent(err)\n\trequire.True(t, IsPermanent(permanentErr))\n\n\ttarget := testErrorType{}\n\trequire.NotEqual(t, err, target)\n\n\tisTestErrorTypeWrapped := errors.As(permanentErr, &target)\n\trequire.True(t, isTestErrorTypeWrapped)\n\n\trequire.Equal(t, err, target)\n}\n"
  },
  {
    "path": "consumer/consumererror/signalerrors.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumererror // import \"go.opentelemetry.io/collector/consumer/consumererror\"\n\nimport (\n\t\"go.opentelemetry.io/collector/consumer/consumererror/internal\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\n// Traces is an error that may carry associated Trace data for a subset of received data\n// that failed to be processed or sent.\ntype Traces struct {\n\tinternal.Retryable[ptrace.Traces]\n}\n\n// NewTraces creates a Traces that can encapsulate received data that failed to be processed or sent.\nfunc NewTraces(err error, data ptrace.Traces) error {\n\treturn Traces{\n\t\tRetryable: internal.Retryable[ptrace.Traces]{\n\t\t\tErr:   NewRetryableError(err),\n\t\t\tValue: data,\n\t\t},\n\t}\n}\n\n// Logs is an error that may carry associated Log data for a subset of received data\n// that failed to be processed or sent.\ntype Logs struct {\n\tinternal.Retryable[plog.Logs]\n}\n\n// NewLogs creates a Logs that can encapsulate received data that failed to be processed or sent.\nfunc NewLogs(err error, data plog.Logs) error {\n\treturn Logs{\n\t\tRetryable: internal.Retryable[plog.Logs]{\n\t\t\tErr:   NewRetryableError(err),\n\t\t\tValue: data,\n\t\t},\n\t}\n}\n\n// Metrics is an error that may carry associated Metrics data for a subset of received data\n// that failed to be processed or sent.\ntype Metrics struct {\n\tinternal.Retryable[pmetric.Metrics]\n}\n\n// NewMetrics creates a Metrics that can encapsulate received data that failed to be processed or sent.\nfunc NewMetrics(err error, data pmetric.Metrics) error {\n\treturn Metrics{\n\t\tRetryable: internal.Retryable[pmetric.Metrics]{\n\t\t\tErr:   NewRetryableError(err),\n\t\t\tValue: data,\n\t\t},\n\t}\n}\n"
  },
  {
    "path": "consumer/consumererror/signalerrors_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumererror\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestTraces(t *testing.T) {\n\ttd := testdata.GenerateTraces(1)\n\terr := errors.New(\"some error\")\n\ttraceErr := NewTraces(err, td)\n\trequire.EqualError(t, err, traceErr.Error())\n\tvar target Traces\n\tassert.NotErrorAs(t, nil, &target)\n\tassert.NotErrorAs(t, err, &target)\n\trequire.ErrorAs(t, traceErr, &target)\n\tassert.Equal(t, td, target.Data())\n}\n\nfunc TestTraces_Unwrap(t *testing.T) {\n\ttd := testdata.GenerateTraces(1)\n\tvar err error = testErrorType{\"some error\"}\n\t// Wrapping err with error Traces.\n\ttraceErr := NewTraces(err, td)\n\ttarget := testErrorType{}\n\trequire.NotEqual(t, err, target)\n\t// Unwrapping traceErr for err and assigning to target.\n\trequire.ErrorAs(t, traceErr, &target)\n\trequire.Equal(t, err, target)\n\tvar e *Error\n\trequire.ErrorAs(t, traceErr, &e)\n\tassert.True(t, e.IsRetryable())\n}\n\nfunc TestLogs(t *testing.T) {\n\ttd := testdata.GenerateLogs(1)\n\terr := errors.New(\"some error\")\n\tlogsErr := NewLogs(err, td)\n\trequire.EqualError(t, err, logsErr.Error())\n\tvar target Logs\n\tassert.NotErrorAs(t, nil, &target)\n\tassert.NotErrorAs(t, err, &target)\n\trequire.ErrorAs(t, logsErr, &target)\n\tassert.Equal(t, td, target.Data())\n}\n\nfunc TestLogs_Unwrap(t *testing.T) {\n\ttd := testdata.GenerateLogs(1)\n\tvar err error = testErrorType{\"some error\"}\n\t// Wrapping err with error Logs.\n\tlogsErr := NewLogs(err, td)\n\ttarget := testErrorType{}\n\trequire.NotEqual(t, err, target)\n\t// Unwrapping logsErr for err and assigning to target.\n\trequire.ErrorAs(t, logsErr, &target)\n\trequire.Equal(t, err, target)\n\tvar e *Error\n\trequire.ErrorAs(t, logsErr, &e)\n\tassert.True(t, e.IsRetryable())\n}\n\nfunc TestMetrics(t *testing.T) {\n\ttd := testdata.GenerateMetrics(1)\n\terr := errors.New(\"some error\")\n\tmetricErr := NewMetrics(err, td)\n\trequire.EqualError(t, err, metricErr.Error())\n\tvar target Metrics\n\tassert.NotErrorAs(t, nil, &target)\n\tassert.NotErrorAs(t, err, &target)\n\trequire.ErrorAs(t, metricErr, &target)\n\tassert.Equal(t, td, target.Data())\n}\n\nfunc TestMetrics_Unwrap(t *testing.T) {\n\ttd := testdata.GenerateMetrics(1)\n\tvar err error = testErrorType{\"some error\"}\n\t// Wrapping err with error Metrics.\n\tmetricErr := NewMetrics(err, td)\n\ttarget := testErrorType{}\n\trequire.NotEqual(t, err, target)\n\t// Unwrapping metricErr for err and assigning to target.\n\trequire.ErrorAs(t, metricErr, &target)\n\trequire.Equal(t, err, target)\n\tvar e *Error\n\trequire.ErrorAs(t, metricErr, &e)\n\tassert.True(t, e.IsRetryable())\n}\n"
  },
  {
    "path": "consumer/consumererror/xconsumererror/Makefile",
    "content": "include ../../../Makefile.Common\n"
  },
  {
    "path": "consumer/consumererror/xconsumererror/go.mod",
    "content": "module go.opentelemetry.io/collector/consumer/consumererror/xconsumererror\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/pdata => ../../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumererror\n\nreplace go.opentelemetry.io/collector/featuregate => ../../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../../internal/testutil\n"
  },
  {
    "path": "consumer/consumererror/xconsumererror/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/otel v1.40.0 h1:oA5YeOcpRTXq6NN7frwmwFR0Cn3RhTVZvXsP4duvCms=\ngo.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlV14J0g=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "consumer/consumererror/xconsumererror/metadata.yaml",
    "content": "type: consumererror/xconsumererror\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: consumer\n  stability:\n    alpha: [profiles]\n"
  },
  {
    "path": "consumer/consumererror/xconsumererror/signalerrors.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xconsumererror // import \"go.opentelemetry.io/collector/consumer/consumererror/xconsumererror\"\n\nimport (\n\t\"go.opentelemetry.io/collector/consumer/consumererror/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n)\n\n// Profiles is an error that may carry associated Profile data for a subset of received data\n// that failed to be processed or sent.\ntype Profiles struct {\n\tinternal.Retryable[pprofile.Profiles]\n}\n\n// NewProfiles creates a Profiles that can encapsulate received data that failed to be processed or sent.\nfunc NewProfiles(err error, data pprofile.Profiles) error {\n\treturn Profiles{\n\t\tRetryable: internal.Retryable[pprofile.Profiles]{\n\t\t\tErr:   err,\n\t\t\tValue: data,\n\t\t},\n\t}\n}\n"
  },
  {
    "path": "consumer/consumererror/xconsumererror/signalerrors_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xconsumererror // import \"go.opentelemetry.io/collector/consumer/consumererror/xconsumererror\"\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestProfiles(t *testing.T) {\n\ttd := testdata.GenerateProfiles(1)\n\terr := errors.New(\"some error\")\n\tprofileErr := NewProfiles(err, td)\n\tassert.Equal(t, err.Error(), profileErr.Error())\n\tvar target Profiles\n\tassert.NotErrorAs(t, nil, &target)\n\tassert.NotErrorAs(t, err, &target)\n\trequire.ErrorAs(t, profileErr, &target)\n\tassert.Equal(t, td, target.Data())\n}\n\nfunc TestProfiles_Unwrap(t *testing.T) {\n\ttd := testdata.GenerateProfiles(1)\n\tvar err error = testErrorType{\"some error\"}\n\t// Wrapping err with error Profiles.\n\tprofileErr := NewProfiles(err, td)\n\ttarget := testErrorType{}\n\trequire.NotEqual(t, err, target)\n\t// Unwrapping profileErr for err and assigning to target.\n\trequire.ErrorAs(t, profileErr, &target)\n\trequire.Equal(t, err, target)\n}\n\ntype testErrorType struct {\n\ts string\n}\n\nfunc (t testErrorType) Error() string {\n\treturn \"\"\n}\n"
  },
  {
    "path": "consumer/consumertest/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "consumer/consumertest/consumer.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumertest // import \"go.opentelemetry.io/collector/consumer/consumertest\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\n// Consumer is a convenience interface that implements all consumer interfaces.\n// It has a private function on it to forbid external users from implementing it\n// and, as a result, to allow us to add extra functions without breaking\n// compatibility.\ntype Consumer interface {\n\t// Capabilities to implement the base consumer functionality.\n\tCapabilities() consumer.Capabilities\n\n\t// ConsumeTraces to implement the consumer.Traces.\n\tConsumeTraces(context.Context, ptrace.Traces) error\n\n\t// ConsumeMetrics to implement the consumer.Metrics.\n\tConsumeMetrics(context.Context, pmetric.Metrics) error\n\n\t// ConsumeLogs to implement the consumer.Logs.\n\tConsumeLogs(context.Context, plog.Logs) error\n\n\t// ConsumeProfiles to implement the xconsumer.Profiles.\n\tConsumeProfiles(context.Context, pprofile.Profiles) error\n\n\tunexported()\n}\n\nvar (\n\t_ consumer.Logs      = Consumer(nil)\n\t_ consumer.Metrics   = Consumer(nil)\n\t_ consumer.Traces    = Consumer(nil)\n\t_ xconsumer.Profiles = Consumer(nil)\n)\n\ntype nonMutatingConsumer struct{}\n\n// Capabilities returns the base consumer capabilities.\nfunc (bc nonMutatingConsumer) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: false}\n}\n\ntype baseConsumer struct {\n\tnonMutatingConsumer\n\tconsumer.ConsumeTracesFunc\n\tconsumer.ConsumeMetricsFunc\n\tconsumer.ConsumeLogsFunc\n\txconsumer.ConsumeProfilesFunc\n}\n\nfunc (bc baseConsumer) unexported() {}\n"
  },
  {
    "path": "consumer/consumertest/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package consumertest defines types and functions used to help test packages\n// implementing the consumer package interfaces.\npackage consumertest // import \"go.opentelemetry.io/collector/consumer/consumertest\"\n"
  },
  {
    "path": "consumer/consumertest/err.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumertest // import \"go.opentelemetry.io/collector/consumer/consumertest\"\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\n// NewErr returns a Consumer that just drops all received data and returns the specified error to Consume* callers.\nfunc NewErr(err error) Consumer {\n\treturn &baseConsumer{\n\t\tConsumeTracesFunc:   func(context.Context, ptrace.Traces) error { return err },\n\t\tConsumeMetricsFunc:  func(context.Context, pmetric.Metrics) error { return err },\n\t\tConsumeLogsFunc:     func(context.Context, plog.Logs) error { return err },\n\t\tConsumeProfilesFunc: func(context.Context, pprofile.Profiles) error { return err },\n\t}\n}\n"
  },
  {
    "path": "consumer/consumertest/err_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumertest\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nfunc TestErr(t *testing.T) {\n\terr := errors.New(\"my error\")\n\tec := NewErr(err)\n\trequire.NotNil(t, ec)\n\tassert.NotPanics(t, ec.unexported)\n\tassert.Equal(t, err, ec.ConsumeLogs(context.Background(), plog.NewLogs()))\n\tassert.Equal(t, err, ec.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n\tassert.Equal(t, err, ec.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n\tassert.Equal(t, err, ec.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n}\n"
  },
  {
    "path": "consumer/consumertest/go.mod",
    "content": "module go.opentelemetry.io/collector/consumer/consumertest\n\ngo 1.25.0\n\nreplace go.opentelemetry.io/collector/consumer => ../\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../xconsumer\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n"
  },
  {
    "path": "consumer/consumertest/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/otel v1.40.0 h1:oA5YeOcpRTXq6NN7frwmwFR0Cn3RhTVZvXsP4duvCms=\ngo.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlV14J0g=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "consumer/consumertest/metadata.yaml",
    "content": "type: consumer/consumertest\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "consumer/consumertest/nop.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumertest // import \"go.opentelemetry.io/collector/consumer/consumertest\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\n// NewNop returns a Consumer that just drops all received data and returns no error.\nfunc NewNop() Consumer {\n\treturn &baseConsumer{\n\t\tConsumeTracesFunc:   func(context.Context, ptrace.Traces) error { return nil },\n\t\tConsumeMetricsFunc:  func(context.Context, pmetric.Metrics) error { return nil },\n\t\tConsumeLogsFunc:     func(context.Context, plog.Logs) error { return nil },\n\t\tConsumeProfilesFunc: func(context.Context, pprofile.Profiles) error { return nil },\n\t}\n}\n"
  },
  {
    "path": "consumer/consumertest/nop_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumertest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nfunc TestNop(t *testing.T) {\n\tnc := NewNop()\n\trequire.NotNil(t, nc)\n\tassert.NotPanics(t, nc.unexported)\n\tassert.NoError(t, nc.ConsumeLogs(context.Background(), plog.NewLogs()))\n\tassert.NoError(t, nc.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n\tassert.NoError(t, nc.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n\tassert.NoError(t, nc.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n}\n"
  },
  {
    "path": "consumer/consumertest/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumertest\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "consumer/consumertest/sink.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumertest // import \"go.opentelemetry.io/collector/consumer/consumertest\"\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\n// TracesSink is a consumer.Traces that acts like a sink that\n// stores all traces and allows querying them for testing.\ntype TracesSink struct {\n\tnonMutatingConsumer\n\tmu        sync.Mutex\n\ttraces    []ptrace.Traces\n\tcontexts  []context.Context\n\tspanCount int\n}\n\nvar _ consumer.Traces = (*TracesSink)(nil)\n\n// ConsumeTraces stores traces to this sink.\nfunc (ste *TracesSink) ConsumeTraces(ctx context.Context, td ptrace.Traces) error {\n\tste.mu.Lock()\n\tdefer ste.mu.Unlock()\n\n\tste.traces = append(ste.traces, td)\n\tste.contexts = append(ste.contexts, ctx)\n\tste.spanCount += td.SpanCount()\n\n\treturn nil\n}\n\n// AllTraces returns the traces stored by this sink since last Reset.\nfunc (ste *TracesSink) AllTraces() []ptrace.Traces {\n\tste.mu.Lock()\n\tdefer ste.mu.Unlock()\n\n\tcopyTraces := make([]ptrace.Traces, len(ste.traces))\n\tcopy(copyTraces, ste.traces)\n\treturn copyTraces\n}\n\n// Contexts returns the contexts stored by this sink since last Reset.\nfunc (ste *TracesSink) Contexts() []context.Context {\n\tste.mu.Lock()\n\tdefer ste.mu.Unlock()\n\n\tcopyContexts := make([]context.Context, len(ste.contexts))\n\tcopy(copyContexts, ste.contexts)\n\treturn copyContexts\n}\n\n// SpanCount returns the number of spans sent to this sink.\nfunc (ste *TracesSink) SpanCount() int {\n\tste.mu.Lock()\n\tdefer ste.mu.Unlock()\n\treturn ste.spanCount\n}\n\n// Reset deletes any stored data.\nfunc (ste *TracesSink) Reset() {\n\tste.mu.Lock()\n\tdefer ste.mu.Unlock()\n\n\tste.traces = nil\n\tste.contexts = nil\n\tste.spanCount = 0\n}\n\n// MetricsSink is a consumer.Metrics that acts like a sink that\n// stores all metrics and allows querying them for testing.\ntype MetricsSink struct {\n\tnonMutatingConsumer\n\tmu             sync.Mutex\n\tmetrics        []pmetric.Metrics\n\tcontexts       []context.Context\n\tdataPointCount int\n}\n\nvar _ consumer.Metrics = (*MetricsSink)(nil)\n\n// ConsumeMetrics stores metrics to this sink.\nfunc (sme *MetricsSink) ConsumeMetrics(ctx context.Context, md pmetric.Metrics) error {\n\tsme.mu.Lock()\n\tdefer sme.mu.Unlock()\n\n\tsme.metrics = append(sme.metrics, md)\n\tsme.contexts = append(sme.contexts, ctx)\n\tsme.dataPointCount += md.DataPointCount()\n\n\treturn nil\n}\n\n// AllMetrics returns the metrics stored by this sink since last Reset.\nfunc (sme *MetricsSink) AllMetrics() []pmetric.Metrics {\n\tsme.mu.Lock()\n\tdefer sme.mu.Unlock()\n\n\tcopyMetrics := make([]pmetric.Metrics, len(sme.metrics))\n\tcopy(copyMetrics, sme.metrics)\n\treturn copyMetrics\n}\n\n// Contexts returns the contexts stored by this sink since last Reset.\nfunc (sme *MetricsSink) Contexts() []context.Context {\n\tsme.mu.Lock()\n\tdefer sme.mu.Unlock()\n\n\tcopyContexts := make([]context.Context, len(sme.contexts))\n\tcopy(copyContexts, sme.contexts)\n\treturn copyContexts\n}\n\n// DataPointCount returns the number of metrics stored by this sink since last Reset.\nfunc (sme *MetricsSink) DataPointCount() int {\n\tsme.mu.Lock()\n\tdefer sme.mu.Unlock()\n\treturn sme.dataPointCount\n}\n\n// Reset deletes any stored data.\nfunc (sme *MetricsSink) Reset() {\n\tsme.mu.Lock()\n\tdefer sme.mu.Unlock()\n\n\tsme.metrics = nil\n\tsme.contexts = nil\n\tsme.dataPointCount = 0\n}\n\n// LogsSink is a consumer.Logs that acts like a sink that\n// stores all logs and allows querying them for testing.\ntype LogsSink struct {\n\tnonMutatingConsumer\n\tmu             sync.Mutex\n\tlogs           []plog.Logs\n\tcontexts       []context.Context\n\tlogRecordCount int\n}\n\nvar _ consumer.Logs = (*LogsSink)(nil)\n\n// ConsumeLogs stores logs to this sink.\nfunc (sle *LogsSink) ConsumeLogs(ctx context.Context, ld plog.Logs) error {\n\tsle.mu.Lock()\n\tdefer sle.mu.Unlock()\n\n\tsle.logs = append(sle.logs, ld)\n\tsle.logRecordCount += ld.LogRecordCount()\n\tsle.contexts = append(sle.contexts, ctx)\n\treturn nil\n}\n\n// AllLogs returns the logs stored by this sink since last Reset.\nfunc (sle *LogsSink) AllLogs() []plog.Logs {\n\tsle.mu.Lock()\n\tdefer sle.mu.Unlock()\n\n\tcopyLogs := make([]plog.Logs, len(sle.logs))\n\tcopy(copyLogs, sle.logs)\n\treturn copyLogs\n}\n\n// LogRecordCount returns the number of log records stored by this sink since last Reset.\nfunc (sle *LogsSink) LogRecordCount() int {\n\tsle.mu.Lock()\n\tdefer sle.mu.Unlock()\n\treturn sle.logRecordCount\n}\n\n// Reset deletes any stored data.\nfunc (sle *LogsSink) Reset() {\n\tsle.mu.Lock()\n\tdefer sle.mu.Unlock()\n\n\tsle.logs = nil\n\tsle.contexts = nil\n\tsle.logRecordCount = 0\n}\n\n// Contexts returns the contexts stored by this sink since last Reset.\nfunc (sle *LogsSink) Contexts() []context.Context {\n\tsle.mu.Lock()\n\tdefer sle.mu.Unlock()\n\n\tcopyContexts := make([]context.Context, len(sle.contexts))\n\tcopy(copyContexts, sle.contexts)\n\treturn copyContexts\n}\n\n// ProfilesSink is a xconsumer.Profiles that acts like a sink that\n// stores all profiles and allows querying them for testing.\ntype ProfilesSink struct {\n\tnonMutatingConsumer\n\tmu           sync.Mutex\n\tprofiles     []pprofile.Profiles\n\tcontexts     []context.Context\n\tsampleCount  int\n\tprofileCount int\n}\n\nvar _ xconsumer.Profiles = (*ProfilesSink)(nil)\n\n// ConsumeProfiles stores profiles to this sink.\nfunc (ste *ProfilesSink) ConsumeProfiles(ctx context.Context, td pprofile.Profiles) error {\n\tste.mu.Lock()\n\tdefer ste.mu.Unlock()\n\n\tste.profiles = append(ste.profiles, td)\n\tste.contexts = append(ste.contexts, ctx)\n\tste.sampleCount += td.SampleCount()\n\tste.profileCount += td.ProfileCount()\n\n\treturn nil\n}\n\n// AllProfiles returns the profiles stored by this sink since last Reset.\nfunc (ste *ProfilesSink) AllProfiles() []pprofile.Profiles {\n\tste.mu.Lock()\n\tdefer ste.mu.Unlock()\n\n\tcopyProfiles := make([]pprofile.Profiles, len(ste.profiles))\n\tcopy(copyProfiles, ste.profiles)\n\treturn copyProfiles\n}\n\n// SampleCount returns the number of samples stored by this sink since last Reset.\nfunc (ste *ProfilesSink) SampleCount() int {\n\tste.mu.Lock()\n\tdefer ste.mu.Unlock()\n\treturn ste.sampleCount\n}\n\n// ProfileCount returns the number of profiles stored by this sink since last Reset.\nfunc (ste *ProfilesSink) ProfileCount() int {\n\tste.mu.Lock()\n\tdefer ste.mu.Unlock()\n\treturn ste.profileCount\n}\n\n// Reset deletes any stored data.\nfunc (ste *ProfilesSink) Reset() {\n\tste.mu.Lock()\n\tdefer ste.mu.Unlock()\n\n\tste.profiles = nil\n\tste.contexts = nil\n\tste.sampleCount = 0\n\tste.profileCount = 0\n}\n\n// Contexts returns the contexts stored by this sink since last Reset.\nfunc (ste *ProfilesSink) Contexts() []context.Context {\n\tste.mu.Lock()\n\tdefer ste.mu.Unlock()\n\n\tcopyContexts := make([]context.Context, len(ste.contexts))\n\tcopy(copyContexts, ste.contexts)\n\treturn copyContexts\n}\n"
  },
  {
    "path": "consumer/consumertest/sink_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumertest\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\ntype (\n\tctxKey  string\n\ttestKey int\n)\n\nfunc TestTracesSink(t *testing.T) {\n\tsink := new(TracesSink)\n\ttd := testdata.GenerateTraces(1)\n\twant := make([]ptrace.Traces, 0, 7)\n\tfor range 7 {\n\t\trequire.NoError(t, sink.ConsumeTraces(context.Background(), td))\n\t\twant = append(want, td)\n\t}\n\tassert.Equal(t, want, sink.AllTraces())\n\tassert.Equal(t, len(want), sink.SpanCount())\n\tsink.Reset()\n\tassert.Empty(t, sink.AllTraces())\n\tassert.Equal(t, 0, sink.SpanCount())\n}\n\nfunc TestMetricsSink(t *testing.T) {\n\tsink := new(MetricsSink)\n\tmd := testdata.GenerateMetrics(1)\n\twant := make([]pmetric.Metrics, 0, 7)\n\tfor range 7 {\n\t\trequire.NoError(t, sink.ConsumeMetrics(context.Background(), md))\n\t\twant = append(want, md)\n\t}\n\tassert.Equal(t, want, sink.AllMetrics())\n\tassert.Equal(t, 2*len(want), sink.DataPointCount())\n\tsink.Reset()\n\tassert.Empty(t, sink.AllMetrics())\n\tassert.Equal(t, 0, sink.DataPointCount())\n}\n\nfunc TestLogsSink(t *testing.T) {\n\tsink := new(LogsSink)\n\tmd := testdata.GenerateLogs(1)\n\twant := make([]plog.Logs, 0, 7)\n\tfor range 7 {\n\t\trequire.NoError(t, sink.ConsumeLogs(context.Background(), md))\n\t\twant = append(want, md)\n\t}\n\tassert.Equal(t, want, sink.AllLogs())\n\tassert.Equal(t, len(want), sink.LogRecordCount())\n\tsink.Reset()\n\tassert.Empty(t, sink.AllLogs())\n\tassert.Equal(t, 0, sink.LogRecordCount())\n}\n\nfunc TestProfilesSink(t *testing.T) {\n\tsink := new(ProfilesSink)\n\ttd := testdata.GenerateProfiles(1)\n\twant := make([]pprofile.Profiles, 0, 7)\n\tfor range 7 {\n\t\trequire.NoError(t, sink.ConsumeProfiles(context.Background(), td))\n\t\twant = append(want, td)\n\t}\n\tassert.Equal(t, want, sink.AllProfiles())\n\t// Each Profile in Profiles holds a single sample.\n\t// So SampleCount() equals ProfileCount() in this case.\n\tassert.Equal(t, len(want), sink.SampleCount())\n\tassert.Equal(t, len(want), sink.ProfileCount())\n\tsink.Reset()\n\tassert.Empty(t, sink.AllProfiles())\n\tassert.Equal(t, 0, sink.SampleCount())\n\tassert.Equal(t, 0, sink.ProfileCount())\n}\n\nfunc TestTracesSinkWithContext(t *testing.T) {\n\tsink := new(TracesSink)\n\ttd := testdata.GenerateTraces(1)\n\twant := make([]ptrace.Traces, 0, 7)\n\twantCtx := make([]context.Context, 0, 7)\n\n\tfor i := range 7 {\n\t\tctx := context.WithValue(context.Background(), testKey(i), fmt.Sprintf(\"value-%d\", i))\n\t\trequire.NoError(t, sink.ConsumeTraces(ctx, td))\n\t\twant = append(want, td)\n\t\twantCtx = append(wantCtx, ctx)\n\t}\n\n\tassert.Equal(t, want, sink.AllTraces())\n\tassert.Equal(t, len(want), sink.SpanCount())\n\n\t// Verify contexts\n\tgotCtx := sink.Contexts()\n\tassert.Len(t, gotCtx, len(wantCtx))\n\tfor i, ctx := range gotCtx {\n\t\tassert.Equal(t, fmt.Sprintf(\"value-%d\", i), ctx.Value(testKey(i)))\n\t}\n\n\tsink.Reset()\n\tassert.Empty(t, sink.AllTraces())\n\tassert.Empty(t, sink.Contexts())\n\tassert.Equal(t, 0, sink.SpanCount())\n}\n\nfunc TestMetricsSinkWithContext(t *testing.T) {\n\tsink := new(MetricsSink)\n\tmd := testdata.GenerateMetrics(1)\n\twant := make([]pmetric.Metrics, 0, 7)\n\twantCtx := make([]context.Context, 0, 7)\n\n\tfor i := range 7 {\n\t\tctx := context.WithValue(context.Background(), testKey(i), fmt.Sprintf(\"value-%d\", i))\n\t\trequire.NoError(t, sink.ConsumeMetrics(ctx, md))\n\t\twant = append(want, md)\n\t\twantCtx = append(wantCtx, ctx)\n\t}\n\n\tassert.Equal(t, want, sink.AllMetrics())\n\tassert.Equal(t, 2*len(want), sink.DataPointCount())\n\n\t// Verify contexts\n\tgotCtx := sink.Contexts()\n\tassert.Len(t, gotCtx, len(wantCtx))\n\tfor i, ctx := range gotCtx {\n\t\tassert.Equal(t, fmt.Sprintf(\"value-%d\", i), ctx.Value(testKey(i)))\n\t}\n\n\tsink.Reset()\n\tassert.Empty(t, sink.AllMetrics())\n\tassert.Empty(t, sink.Contexts())\n\tassert.Equal(t, 0, sink.DataPointCount())\n}\n\nfunc TestLogsSinkWithContext(t *testing.T) {\n\tsink := new(LogsSink)\n\tmd := testdata.GenerateLogs(1)\n\twant := make([]plog.Logs, 0, 7)\n\twantCtx := make([]context.Context, 0, 7)\n\n\tfor i := range 7 {\n\t\tctx := context.WithValue(context.Background(), testKey(i), fmt.Sprintf(\"value-%d\", i))\n\t\trequire.NoError(t, sink.ConsumeLogs(ctx, md))\n\t\twant = append(want, md)\n\t\twantCtx = append(wantCtx, ctx)\n\t}\n\n\tassert.Equal(t, want, sink.AllLogs())\n\tassert.Equal(t, len(want), sink.LogRecordCount())\n\n\t// Verify contexts\n\tgotCtx := sink.Contexts()\n\tassert.Len(t, gotCtx, len(wantCtx))\n\tfor i, ctx := range gotCtx {\n\t\tassert.Equal(t, fmt.Sprintf(\"value-%d\", i), ctx.Value(testKey(i)))\n\t}\n\n\tsink.Reset()\n\tassert.Empty(t, sink.AllLogs())\n\tassert.Empty(t, sink.Contexts())\n\tassert.Equal(t, 0, sink.LogRecordCount())\n}\n\nfunc TestProfilesSinkWithContext(t *testing.T) {\n\tsink := new(ProfilesSink)\n\ttd := testdata.GenerateProfiles(1)\n\twant := make([]pprofile.Profiles, 0, 7)\n\twantCtx := make([]context.Context, 0, 7)\n\n\tfor i := range 7 {\n\t\tctx := context.WithValue(context.Background(), testKey(i), fmt.Sprintf(\"value-%d\", i))\n\t\trequire.NoError(t, sink.ConsumeProfiles(ctx, td))\n\t\twant = append(want, td)\n\t\twantCtx = append(wantCtx, ctx)\n\t}\n\n\tassert.Equal(t, want, sink.AllProfiles())\n\tassert.Equal(t, len(want), sink.SampleCount())\n\n\t// Verify contexts\n\tgotCtx := sink.Contexts()\n\tassert.Len(t, gotCtx, len(wantCtx))\n\tfor i, ctx := range gotCtx {\n\t\tassert.Equal(t, fmt.Sprintf(\"value-%d\", i), ctx.Value(testKey(i)))\n\t}\n\n\tsink.Reset()\n\tassert.Empty(t, sink.AllProfiles())\n\tassert.Empty(t, sink.Contexts())\n\tassert.Equal(t, 0, sink.SampleCount())\n}\n\n// TestSinkContextTransformation verifies that the context is stored and transformed correctly\nfunc TestSinkContextTransformation(t *testing.T) {\n\ttestCases := []struct {\n\t\tname string\n\t\tsink interface {\n\t\t\tContexts() []context.Context\n\t\t}\n\t\tconsumeFunc func(any, context.Context) error\n\t\ttestData    any\n\t}{\n\t\t{\n\t\t\tname: \"TracesSink\",\n\t\t\tsink: new(TracesSink),\n\t\t\tconsumeFunc: func(sink any, ctx context.Context) error {\n\t\t\t\treturn sink.(*TracesSink).ConsumeTraces(ctx, testdata.GenerateTraces(1))\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"MetricsSink\",\n\t\t\tsink: new(MetricsSink),\n\t\t\tconsumeFunc: func(sink any, ctx context.Context) error {\n\t\t\t\treturn sink.(*MetricsSink).ConsumeMetrics(ctx, testdata.GenerateMetrics(1))\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"LogsSink\",\n\t\t\tsink: new(LogsSink),\n\t\t\tconsumeFunc: func(sink any, ctx context.Context) error {\n\t\t\t\treturn sink.(*LogsSink).ConsumeLogs(ctx, testdata.GenerateLogs(1))\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"ProfilesSink\",\n\t\t\tsink: new(ProfilesSink),\n\t\t\tconsumeFunc: func(sink any, ctx context.Context) error {\n\t\t\t\treturn sink.(*ProfilesSink).ConsumeProfiles(ctx, testdata.GenerateProfiles(1))\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\t// Create a context with initial values\n\t\t\tinitialCtx := context.WithValue(context.Background(), ctxKey(\"initial-key\"), \"initial-value\")\n\n\t\t\t// Create a context chain to simulate transformation\n\t\t\ttransformedCtx := context.WithValue(initialCtx, ctxKey(\"transformed-key\"), \"transformed-value\")\n\n\t\t\t// Consume data with the transformed context\n\t\t\terr := tc.consumeFunc(tc.sink, transformedCtx)\n\t\t\trequire.NoError(t, err)\n\n\t\t\t// Verify context storage and transformation\n\t\t\tstoredContexts := tc.sink.Contexts()\n\t\t\tassert.Len(t, storedContexts, 1, \"Should have stored exactly one context\")\n\n\t\t\tstoredCtx := storedContexts[0]\n\t\t\t// Verify both initial and transformed values are preserved\n\t\t\tassert.Equal(t, \"initial-value\", storedCtx.Value(ctxKey(\"initial-key\")),\n\t\t\t\t\"Initial context value should be preserved\")\n\t\t\tassert.Equal(t, \"transformed-value\", storedCtx.Value(ctxKey(\"transformed-key\")),\n\t\t\t\t\"Transformed context value should be stored\")\n\t\t})\n\t}\n}\n\n// TestContextTransformationChain verifies that the context is stored and transformed correctly in a chain of transformations\nfunc TestContextTransformationChain(t *testing.T) {\n\tsink := new(TracesSink)\n\n\t// Create a context transformation chain\n\tbaseCtx := context.Background()\n\tctx1 := context.WithValue(baseCtx, ctxKey(\"step1\"), \"value1\")\n\tctx2 := context.WithValue(ctx1, ctxKey(\"step2\"), \"value2\")\n\tctx3 := context.WithValue(ctx2, ctxKey(\"step3\"), \"value3\")\n\n\t// Consume traces with the transformed context\n\ttd := testdata.GenerateTraces(1)\n\terr := sink.ConsumeTraces(ctx3, td)\n\trequire.NoError(t, err)\n\n\t// Verify the complete transformation chain\n\tstoredContexts := sink.Contexts()\n\trequire.Len(t, storedContexts, 1)\n\n\tfinalCtx := storedContexts[0]\n\t// Verify each transformation step\n\tassert.Equal(t, \"value1\", finalCtx.Value(ctxKey(\"step1\")), \"First transformation should be preserved\")\n\tassert.Equal(t, \"value2\", finalCtx.Value(ctxKey(\"step2\")), \"Second transformation should be preserved\")\n\tassert.Equal(t, \"value3\", finalCtx.Value(ctxKey(\"step3\")), \"Third transformation should be preserved\")\n}\n\n// TestConcurrentContextTransformations verifies context handling under concurrent operations\nfunc TestConcurrentContextTransformations(t *testing.T) {\n\tsink := new(TracesSink)\n\tconst numGoroutines = 10\n\terrChan := make(chan error, numGoroutines)\n\n\tvar wg sync.WaitGroup\n\twg.Add(numGoroutines)\n\n\tfor i := range numGoroutines {\n\t\tgo func(idx int) {\n\t\t\tdefer wg.Done()\n\t\t\tkey := ctxKey(fmt.Sprintf(\"goroutine-%d\", idx))\n\t\t\tvalue := fmt.Sprintf(\"value-%d\", idx)\n\t\t\tctx := context.WithValue(context.Background(), key, value)\n\n\t\t\ttd := testdata.GenerateTraces(1)\n\t\t\tif err := sink.ConsumeTraces(ctx, td); err != nil {\n\t\t\t\terrChan <- err\n\t\t\t}\n\t\t}(i)\n\t}\n\n\twg.Wait()\n\tclose(errChan)\n\n\t// Check for any errors that occurred in goroutines\n\tfor err := range errChan {\n\t\tt.Errorf(\"Error in goroutine: %v\", err)\n\t}\n\n\t// Verify all contexts were stored correctly\n\tstoredContexts := sink.Contexts()\n\tassert.Len(t, storedContexts, numGoroutines)\n\n\t// Create a map to verify all expected values are present\n\tcontextValues := make(map[string]bool)\n\tfor _, ctx := range storedContexts {\n\t\tfor i := range numGoroutines {\n\t\t\tkey := ctxKey(fmt.Sprintf(\"goroutine-%d\", i))\n\t\t\texpectedValue := fmt.Sprintf(\"value-%d\", i)\n\t\t\tif val := ctx.Value(key); val == expectedValue {\n\t\t\t\tcontextValues[fmt.Sprintf(\"goroutine-%d\", i)] = true\n\t\t\t}\n\t\t}\n\t}\n\n\t// Verify all goroutines' contexts were preserved\n\tassert.Len(t, contextValues, numGoroutines,\n\t\t\"Should have stored contexts from all goroutines\")\n}\n"
  },
  {
    "path": "consumer/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package consumer contains interfaces that receive and process data.\npackage consumer // import \"go.opentelemetry.io/collector/consumer\"\n"
  },
  {
    "path": "consumer/go.mod",
    "content": "module go.opentelemetry.io/collector/consumer\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/kr/text v0.2.0 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/pdata => ../pdata\n\nretract (\n\tv0.76.0 // Depends on retracted pdata v1.0.0-rc10 module, use v0.76.1\n\tv0.69.0 // Release failed, use v0.69.1\n)\n\nreplace go.opentelemetry.io/collector/featuregate => ../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../internal/testutil\n"
  },
  {
    "path": "consumer/go.sum",
    "content": "github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "consumer/internal/consumer.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/consumer/internal\"\n\n// Capabilities describes the capabilities of a Processor.\ntype Capabilities struct {\n\t// MutatesData is set to true if Consume* function of the\n\t// processor modifies the input Traces, Logs or Metrics argument.\n\t// Processors which modify the input data MUST set this flag to true. If the processor\n\t// does not modify the data it MUST set this flag to false. If the processor creates\n\t// a copy of the data before modifying then this flag can be safely set to false.\n\tMutatesData bool\n}\n\ntype BaseConsumer interface {\n\tCapabilities() Capabilities\n}\n\ntype BaseImpl struct {\n\tCap Capabilities\n}\n\n// Option to construct new consumers.\ntype Option interface {\n\tapply(*BaseImpl)\n}\n\ntype OptionFunc func(*BaseImpl)\n\nfunc (of OptionFunc) apply(e *BaseImpl) {\n\tof(e)\n}\n\n// Capabilities returns the capabilities of the component\nfunc (bs BaseImpl) Capabilities() Capabilities {\n\treturn bs.Cap\n}\n\nfunc NewBaseImpl(options ...Option) *BaseImpl {\n\tbs := &BaseImpl{\n\t\tCap: Capabilities{MutatesData: false},\n\t}\n\n\tfor _, op := range options {\n\t\top.apply(bs)\n\t}\n\n\treturn bs\n}\n"
  },
  {
    "path": "consumer/logs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumer // import \"go.opentelemetry.io/collector/consumer\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/consumer/internal\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\n// Logs is an interface that receives plog.Logs, processes it\n// as needed, and sends it to the next processing node if any or to the destination.\ntype Logs interface {\n\tinternal.BaseConsumer\n\t// ConsumeLogs processes the logs. After the function returns, the logs are no longer accessible,\n\t// and accessing them is considered undefined behavior.\n\tConsumeLogs(ctx context.Context, ld plog.Logs) error\n}\n\n// ConsumeLogsFunc is a helper function that is similar to ConsumeLogs.\ntype ConsumeLogsFunc func(ctx context.Context, ld plog.Logs) error\n\n// ConsumeLogs calls f(ctx, ld).\nfunc (f ConsumeLogsFunc) ConsumeLogs(ctx context.Context, ld plog.Logs) error {\n\treturn f(ctx, ld)\n}\n\ntype baseLogs struct {\n\t*internal.BaseImpl\n\tConsumeLogsFunc\n}\n\n// NewLogs returns a Logs configured with the provided options.\nfunc NewLogs(consume ConsumeLogsFunc, options ...Option) (Logs, error) {\n\tif consume == nil {\n\t\treturn nil, errNilFunc\n\t}\n\treturn &baseLogs{\n\t\tBaseImpl:        internal.NewBaseImpl(options...),\n\t\tConsumeLogsFunc: consume,\n\t}, nil\n}\n"
  },
  {
    "path": "consumer/logs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumer\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\nfunc TestDefaultLogs(t *testing.T) {\n\tcp, err := NewLogs(func(context.Context, plog.Logs) error { return nil })\n\tassert.NoError(t, err)\n\tassert.NoError(t, cp.ConsumeLogs(context.Background(), plog.NewLogs()))\n\tassert.Equal(t, Capabilities{MutatesData: false}, cp.Capabilities())\n}\n\nfunc TestNilFuncLogs(t *testing.T) {\n\t_, err := NewLogs(nil)\n\tassert.Equal(t, errNilFunc, err)\n}\n\nfunc TestWithCapabilitiesLogs(t *testing.T) {\n\tcp, err := NewLogs(\n\t\tfunc(context.Context, plog.Logs) error { return nil },\n\t\tWithCapabilities(Capabilities{MutatesData: true}))\n\tassert.NoError(t, err)\n\tassert.NoError(t, cp.ConsumeLogs(context.Background(), plog.NewLogs()))\n\tassert.Equal(t, Capabilities{MutatesData: true}, cp.Capabilities())\n}\n\nfunc TestConsumeLogs(t *testing.T) {\n\tconsumeCalled := false\n\tcp, err := NewLogs(func(context.Context, plog.Logs) error { consumeCalled = true; return nil })\n\tassert.NoError(t, err)\n\tassert.NoError(t, cp.ConsumeLogs(context.Background(), plog.NewLogs()))\n\tassert.True(t, consumeCalled)\n}\n\nfunc TestConsumeLogs_ReturnError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tcp, err := NewLogs(func(context.Context, plog.Logs) error { return want })\n\trequire.NoError(t, err)\n\tassert.Equal(t, want, cp.ConsumeLogs(context.Background(), plog.NewLogs()))\n}\n"
  },
  {
    "path": "consumer/metadata.yaml",
    "content": "type: consumer\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "consumer/metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumer // import \"go.opentelemetry.io/collector/consumer\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/consumer/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\n// Metrics is an interface that receives pmetric.Metrics, processes it\n// as needed, and sends it to the next processing node if any or to the destination.\ntype Metrics interface {\n\tinternal.BaseConsumer\n\t// ConsumeMetrics processes the metrics. After the function returns, the metrics are no longer accessible,\n\t// and accessing them is considered undefined behavior.\n\tConsumeMetrics(ctx context.Context, md pmetric.Metrics) error\n}\n\n// ConsumeMetricsFunc is a helper function that is similar to ConsumeMetrics.\ntype ConsumeMetricsFunc func(ctx context.Context, md pmetric.Metrics) error\n\n// ConsumeMetrics calls f(ctx, md).\nfunc (f ConsumeMetricsFunc) ConsumeMetrics(ctx context.Context, md pmetric.Metrics) error {\n\treturn f(ctx, md)\n}\n\ntype baseMetrics struct {\n\t*internal.BaseImpl\n\tConsumeMetricsFunc\n}\n\n// NewMetrics returns a Metrics configured with the provided options.\nfunc NewMetrics(consume ConsumeMetricsFunc, options ...Option) (Metrics, error) {\n\tif consume == nil {\n\t\treturn nil, errNilFunc\n\t}\n\treturn &baseMetrics{\n\t\tBaseImpl:           internal.NewBaseImpl(options...),\n\t\tConsumeMetricsFunc: consume,\n\t}, nil\n}\n"
  },
  {
    "path": "consumer/metrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumer\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\nfunc TestDefaultMetrics(t *testing.T) {\n\tcp, err := NewMetrics(func(context.Context, pmetric.Metrics) error { return nil })\n\tassert.NoError(t, err)\n\tassert.NoError(t, cp.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n\tassert.Equal(t, Capabilities{MutatesData: false}, cp.Capabilities())\n}\n\nfunc TestNilFuncMetrics(t *testing.T) {\n\t_, err := NewMetrics(nil)\n\tassert.Equal(t, errNilFunc, err)\n}\n\nfunc TestWithCapabilitiesMetrics(t *testing.T) {\n\tcp, err := NewMetrics(\n\t\tfunc(context.Context, pmetric.Metrics) error { return nil },\n\t\tWithCapabilities(Capabilities{MutatesData: true}))\n\tassert.NoError(t, err)\n\tassert.NoError(t, cp.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n\tassert.Equal(t, Capabilities{MutatesData: true}, cp.Capabilities())\n}\n\nfunc TestConsumeMetrics(t *testing.T) {\n\tconsumeCalled := false\n\tcp, err := NewMetrics(func(context.Context, pmetric.Metrics) error { consumeCalled = true; return nil })\n\tassert.NoError(t, err)\n\tassert.NoError(t, cp.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n\tassert.True(t, consumeCalled)\n}\n\nfunc TestConsumeMetrics_ReturnError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tcp, err := NewMetrics(func(context.Context, pmetric.Metrics) error { return want })\n\trequire.NoError(t, err)\n\tassert.Equal(t, want, cp.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n}\n"
  },
  {
    "path": "consumer/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumer\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "consumer/traces.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumer // import \"go.opentelemetry.io/collector/consumer\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/consumer/internal\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\n// Traces is an interface that receives ptrace.Traces, processes it\n// as needed, and sends it to the next processing node if any or to the destination.\ntype Traces interface {\n\tinternal.BaseConsumer\n\t// ConsumeTraces processes the traces. After the function returns, the traces are no longer accessible,\n\t// and accessing them is considered undefined behavior.\n\tConsumeTraces(ctx context.Context, td ptrace.Traces) error\n}\n\n// ConsumeTracesFunc is a helper function that is similar to ConsumeTraces.\ntype ConsumeTracesFunc func(ctx context.Context, td ptrace.Traces) error\n\n// ConsumeTraces calls f(ctx, td).\nfunc (f ConsumeTracesFunc) ConsumeTraces(ctx context.Context, td ptrace.Traces) error {\n\treturn f(ctx, td)\n}\n\ntype baseTraces struct {\n\t*internal.BaseImpl\n\tConsumeTracesFunc\n}\n\n// NewTraces returns a Traces configured with the provided options.\nfunc NewTraces(consume ConsumeTracesFunc, options ...Option) (Traces, error) {\n\tif consume == nil {\n\t\treturn nil, errNilFunc\n\t}\n\treturn &baseTraces{\n\t\tBaseImpl:          internal.NewBaseImpl(options...),\n\t\tConsumeTracesFunc: consume,\n\t}, nil\n}\n"
  },
  {
    "path": "consumer/traces_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage consumer\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nfunc TestDefaultTraces(t *testing.T) {\n\tcp, err := NewTraces(func(context.Context, ptrace.Traces) error { return nil })\n\tassert.NoError(t, err)\n\tassert.NoError(t, cp.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n\tassert.Equal(t, Capabilities{MutatesData: false}, cp.Capabilities())\n}\n\nfunc TestNilFuncTraces(t *testing.T) {\n\t_, err := NewTraces(nil)\n\tassert.Equal(t, errNilFunc, err)\n}\n\nfunc TestWithCapabilitiesTraces(t *testing.T) {\n\tcp, err := NewTraces(\n\t\tfunc(context.Context, ptrace.Traces) error { return nil },\n\t\tWithCapabilities(Capabilities{MutatesData: true}))\n\tassert.NoError(t, err)\n\tassert.NoError(t, cp.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n\tassert.Equal(t, Capabilities{MutatesData: true}, cp.Capabilities())\n}\n\nfunc TestConsumeTraces(t *testing.T) {\n\tconsumeCalled := false\n\tcp, err := NewTraces(func(context.Context, ptrace.Traces) error { consumeCalled = true; return nil })\n\tassert.NoError(t, err)\n\tassert.NoError(t, cp.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n\tassert.True(t, consumeCalled)\n}\n\nfunc TestConsumeTraces_ReturnError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tcp, err := NewTraces(func(context.Context, ptrace.Traces) error { return want })\n\trequire.NoError(t, err)\n\tassert.Equal(t, want, cp.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n}\n"
  },
  {
    "path": "consumer/xconsumer/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "consumer/xconsumer/go.mod",
    "content": "module go.opentelemetry.io/collector/consumer/xconsumer\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer => ../\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n"
  },
  {
    "path": "consumer/xconsumer/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/otel v1.40.0 h1:oA5YeOcpRTXq6NN7frwmwFR0Cn3RhTVZvXsP4duvCms=\ngo.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlV14J0g=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "consumer/xconsumer/metadata.yaml",
    "content": "type: xconsumer\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: consumer\n  codeowners:\n    active:\n      - mx-psi\n      - dmathieu\n  stability:\n    alpha: [profiles]\n"
  },
  {
    "path": "consumer/xconsumer/profiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xconsumer // import \"go.opentelemetry.io/collector/consumer/xconsumer\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n)\n\nvar errNilFunc = errors.New(\"nil consumer func\")\n\n// Profiles is an interface that receives pprofile.Profiles, processes it\n// as needed, and sends it to the next processing node if any or to the destination.\ntype Profiles interface {\n\tinternal.BaseConsumer\n\t// ConsumeProfiles processes the profiles. After the function returns, the profiles are no longer accessible,\n\t// and accessing them is considered undefined behavior.\n\tConsumeProfiles(ctx context.Context, td pprofile.Profiles) error\n}\n\n// ConsumeProfilesFunc is a helper function that is similar to ConsumeProfiles.\ntype ConsumeProfilesFunc func(ctx context.Context, td pprofile.Profiles) error\n\n// ConsumeProfiles calls f(ctx, td).\nfunc (f ConsumeProfilesFunc) ConsumeProfiles(ctx context.Context, td pprofile.Profiles) error {\n\treturn f(ctx, td)\n}\n\ntype baseProfiles struct {\n\t*internal.BaseImpl\n\tConsumeProfilesFunc\n}\n\n// NewProfiles returns a Profiles configured with the provided options.\nfunc NewProfiles(consume ConsumeProfilesFunc, options ...consumer.Option) (Profiles, error) {\n\tif consume == nil {\n\t\treturn nil, errNilFunc\n\t}\n\treturn &baseProfiles{\n\t\tBaseImpl:            internal.NewBaseImpl(options...),\n\t\tConsumeProfilesFunc: consume,\n\t}, nil\n}\n"
  },
  {
    "path": "consumer/xconsumer/profiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xconsumer\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n)\n\nfunc TestDefaultProfiles(t *testing.T) {\n\tcp, err := NewProfiles(func(context.Context, pprofile.Profiles) error { return nil })\n\tassert.NoError(t, err)\n\tassert.NoError(t, cp.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n\tassert.Equal(t, consumer.Capabilities{MutatesData: false}, cp.Capabilities())\n}\n\nfunc TestNilFuncProfiles(t *testing.T) {\n\t_, err := NewProfiles(nil)\n\tassert.Equal(t, errNilFunc, err)\n}\n\nfunc TestWithCapabilitiesProfiles(t *testing.T) {\n\tcp, err := NewProfiles(\n\t\tfunc(context.Context, pprofile.Profiles) error { return nil },\n\t\tconsumer.WithCapabilities(consumer.Capabilities{MutatesData: true}))\n\tassert.NoError(t, err)\n\tassert.NoError(t, cp.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n\tassert.Equal(t, consumer.Capabilities{MutatesData: true}, cp.Capabilities())\n}\n\nfunc TestConsumeProfiles(t *testing.T) {\n\tconsumeCalled := false\n\tcp, err := NewProfiles(func(context.Context, pprofile.Profiles) error { consumeCalled = true; return nil })\n\tassert.NoError(t, err)\n\tassert.NoError(t, cp.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n\tassert.True(t, consumeCalled)\n}\n\nfunc TestConsumeProfiles_ReturnError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tcp, err := NewProfiles(func(context.Context, pprofile.Profiles) error { return want })\n\trequire.NoError(t, err)\n\tassert.Equal(t, want, cp.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n}\n"
  },
  {
    "path": "distributions.yaml",
    "content": "# A collection of distributions that can be referenced in the metadata.yaml files.\n# The rules below apply to every distribution added to this list:\n# - The distribution is open source and maintained by the OpenTelemetry project.\n# - The link must point to a publicly accessible repository.\n - name: core\n   url: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n - name: contrib\n   url: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n - name: k8s\n   url: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\n - name: otlp\n   url: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-otlp\n"
  },
  {
    "path": "docs/README.md",
    "content": "# OpenTelemetry Collector\n\n**Status**: [Beta](https://github.com/open-telemetry/opentelemetry-specification/blob/main/oteps/0232-maturity-of-otel.md#beta)\n\nThe OpenTelemetry Collector consists of the following components:\n\n* A mechanism that _MUST_ be able to load and parse an [OpenTelemetry Collector configuration\n  file](#configuration-file).\n* A mechanism that _MUST_ be able to include compatible\n  [Collector components](#opentelemetry-collector-components) that\n  the user wishes to include.\n\nThese combined provide users the ability to easily switch between\n[OpenTelemetry Collector Distributions](#opentelemetry-collector-distribution) while also ensuring that components produced by\nthe OpenTelemetry Collector SIG are able to work with any vendor who claims\nsupport for an OpenTelemetry Collector.\n\n## Configuration file\n\nAn OpenTelemetry Collector configuration file is defined as YAML and _MUST_ support\nthe following [minimum structure](https://pkg.go.dev/go.opentelemetry.io/collector/otelcol#Config):\n\n```yaml\nreceivers:\nprocessors:\nexporters:\nconnectors:\nextensions:\nservice:\n  telemetry:\n  pipelines:\n```\n\n## OpenTelemetry Collector components\n\nFor a library to be considered an OpenTelemetry Collector component, it _MUST_\nimplement a [Component interface](https://pkg.go.dev/go.opentelemetry.io/collector/component#Component)\ndefined by the OpenTelemetry Collector SIG.\n\nComponents require a [unique identifier](https://pkg.go.dev/go.opentelemetry.io/collector/component#ID)\nto be included in an OpenTelemetry Collector. In the event of a name collision,\nthe components resulting in the collision cannot be used simultaneously in a single OpenTelemetry\nCollector. In order to resolve this, the clashing components must use different identifiers.\n\n### Compatibility requirements\n\nA component is defined as compatible with an OpenTelemetry Collector when its dependencies are\nsource- and version-compatible with the Component interfaces of that Collector.\n\nFor example, a Collector derived from version tag v0.100.0 of the [OpenTelemetry Collector](https://github.com/open-telemetry/opentelemetry-collector) _MUST_ support all components that\nare version-compatible with the Golang Component API defined in the `github.com/open-telemetry/opentelemetry-collector/component` module found in that repository for that version tag.\n\n## OpenTelemetry Collector Distribution\n\nAn OpenTelemetry Collector Distribution (Distro) is a compiled instance\nof an OpenTelemetry Collector with a specific set of components and features. A\nDistribution author _MAY_ choose to produce a distribution by utilizing tools\nand/or documentation supported by the OpenTelemetry project. Alternatively, a\nDistribution author _MUST_ provide end users with the capability for adding\ntheir own components to the Distribution's components. Note that the resulting\nbinary from updating a Distribution to include new components\nis a different Distribution.\n"
  },
  {
    "path": "docs/coding-guidelines.md",
    "content": "# Coding guidelines\n\nWe consider the OpenTelemetry Collector to be close to production quality and the quality bar\nfor contributions is set accordingly. Contributions must have readable code written\nwith maintainability in mind (if in doubt check [Effective Go](https://golang.org/doc/effective_go.html)\nfor coding advice). The code must adhere to the following robustness principles that\nare important for software that runs autonomously and continuously without direct\ninteraction with a human (such as this Collector).\n\n## Naming convention\n\n### Component naming\n\nComponents (receivers, processors, exporters, extensions, and connectors) MUST use `lower_snake_case` naming convention. This ensures consistency and enhances readability for end users.\n\nThis naming convention applies to the component identifier used in configuration files and component registration, not to Go package names which follow standard Go naming conventions (lowercase, no underscores).\n\nExamples of correct component names:\n- `memory_limiter` (not `memorylimiter`)\n- `otlp_http` (not `otlphttp`)\n\nFor example, a component with identifier `memory_limiter` would typically have a Go package name like `memorylimiterprocessor`.\n\n#### Migration for existing components\n\nComponents that currently use a different naming convention:\n- SHOULD add the `lower_snake_case` name as the primary identifier\n- MAY support the old name as a deprecated alias for backwards compatibility\n- MUST document the migration path in their README\n\nOnly components following the `lower_snake_case` naming convention should be marked as stable.\n\n### Go API naming conventions\n\nTo keep naming patterns consistent across the project, naming patterns are enforced to make intent clear by:\n\n- Methods that return a variable that uses the zero value or values provided via the method MUST have the prefix `New`. For example:\n  - `func NewKinesisExporter(kpl aws.KinesisProducerLibrary)` allocates a variable that uses\n    the variables passed on creation.\n  - `func NewKeyValueBuilder()` SHOULD allocate internal variables to a safe zero value.\n- Methods that return a variable that uses non-zero value(s) that impacts business logic MUST use the prefix `NewDefault`. For example:\n  - `func NewDefaultKinesisConfig()` would return a configuration that is the suggested default\n    and can be updated without concern of causing a race condition.\n- Methods that act upon an input variable MUST have a signature that reflects concisely the logic being done. For example:\n  - `func FilterAttributes(attrs []Attribute, match func(attr Attribute) bool) []Attribute` MUST only filter attributes out of the passed input\n    slice and return a new slice with values that `match` returns true. It may not do more work than what the method name implies, ie, it\n    must not key a global history of all the slices that have been filtered.\n- Methods that get the value of a field i.e. a getterMethod MUST use an uppercase first letter and NOT a `get` prefix. For example:\n  - `func (p *Person) Name() string {return p.name} ` Name (with an uppercase N, exported) method is used here to get the value of the name field and not `getName`.The use of upper-case names for export provides the hook to discriminate the field from the method.\n- Methods that set the value of a field i.e. a setterMethod MUST use a `set` prefix. For example:\n  - `func (p *Person) SetName(newName string) {p.name = newName}` SetName method here sets the value of the name field.\n- Variable assigned in a package's global scope that is preconfigured with a default set of values MUST use `Default` as the prefix. For example:\n  - `var DefaultMarshallers = map[string]pdata.Marshallers{...}` is defined with an exporter package that allows for converting an encoding name,\n    `zipkin`, and return the preconfigured marshaller to be used in the export process.\n- Types that are specific to a signal MUST be worded with the signal used as an adjective, i.e. `SignalType`. For example:\n  - `type TracesSink interface {...}`\n- Types that deal with multiple signal types should use the relationship between the signals to describe the type, e.g. `SignalToSignalType` or `SignalAndSignalType`. For example:\n  - `type TracesToTracesFunc func(...) ...`\n- Functions dealing with specific signals or signal-specific types MUST be worded with the signal or type as a direct object, i.e. `VerbSignal`, or `VerbType` where `Type` is the full name of the type including the signal name. For example:\n  - `func ConsumeTraces(...) {...}`\n  - `func CreateTracesExport(...) {...}`\n  - `func CreateTracesToTracesFunc(...) {...}`\n\n#### Configuration structs\n\nWhen naming configuration structs, use the following guidelines:\n\n- Separate the configuration set by end users in their YAML configuration from the configuration set by developers in the code into different structs.\n- Use the `Config` suffix for configuration structs that have end user configuration (i.e. that set in their YAML configuration). For example, `configgrpc.ClientConfig` ends in `Config` since it contains end user configuration.\n- Use the `Settings` suffix for configuration structs that are set by developers in the code. For example, `component.TelemetrySettings` ends in `Settings` since it is set by developers in the code.\n- Avoid redundant prefixes that are already implied by the package name. For example, use`configgrpc.ClientConfig` instead of `configgrpc.GRPCClientConfig`.\n\n#### Avoid Embedded Structs\n\nWhen defining configuration structs, avoid using embedded (anonymous) struct fields. Instead, use explicitly named fields.\n\n**Rationale:**\n\n1. **Unmarshal Compatibility**: Embedded structs can break custom `Unmarshal` implementations. If an embedded struct requires special unmarshaling logic, it may not function correctly when embedded.\n\n2. **Naming Conflicts**: Embedded structs can cause field name collisions. Even if the YAML configuration nests them properly (e.g., under `sending_queue`), having identical field names in embedded structs creates ambiguity in the Go code.\n\n3. **Clarity**: Named fields make the configuration structure more explicit and easier to understand.\n\n**Example:**\n\n```go\n// ❌ BAD: Using embedded structs\ntype ExporterConfig struct {\n    exporterhelper.TimeoutConfig     // embedded\n    exporterhelper.QueueConfig       // embedded\n    exporterhelper.RetryConfig       // embedded\n}\n\n// ✅ GOOD: Using named fields\ntype ExporterConfig struct {\n    Timeout exporterhelper.TimeoutConfig `mapstructure:\"timeout\"`\n    Queue   exporterhelper.QueueConfig   `mapstructure:\"sending_queue\"`\n    Retry   exporterhelper.RetryConfig   `mapstructure:\"retry_on_failure\"`\n}\n```\n\nThis practice ensures better maintainability and prevents subtle bugs related to struct composition and configuration unmarshaling.\n\n**Preserving Flat YAML Structure with the `squash` Tag:**\n\nIn some cases, you may need to maintain backward compatibility with an existing flat YAML configuration structure while still using named fields in Go. The `mapstructure:\",squash\"` tag achieves this by flattening the nested struct's fields into the parent configuration:\n\n```go\n// Using named fields with squash tag for flat YAML structure\ntype Config struct {\n    ClientConfig confighttp.ClientConfig `mapstructure:\",squash\"`\n}\n```\n\nThis allows the YAML configuration to remain flat (fields at the top level) while the Go code uses a named field. However, prefer explicitly nested configurations (without `squash`) for new components, as the nested structure is clearer and avoids the issues mentioned above.\n\n## Module organization\n\nAs usual in Go projects, organize your code into packages grouping related functionality. To ensure\nthat we can evolve different parts of the API independently, you should also group related packages\ninto modules.\n\nWe use the following rules for some common situations where we split into separate modules:\n1. Each top-level directory should be a separate module.\n1. Each component referenceable by the OpenTelemetry Collector Builder should be in a separate\n   module. For example, the OTLP receiver is in its own module, different from that of other\n   receivers.\n1. Consider splitting into separate modules if the API may evolve independently in separate groups\n   of packages. For example, the configuration related to HTTP and gRPC evolve independently, so\n   `config/configgrpc` and `config/confighttp` are separate modules.\n1. For component names, add the component kind as a suffix for the module name. For example, the\n   OTLP receiver is in the `receiver/otlpreceiver` module.\n1. Modules that add specific functionality related to a parent folder should have a prefix in the\n   name that relates to the parent module. For example, `configauth` has the `config` prefix since\n   it is part of the `config` folder, and `extensionauth` has `extension` as a prefix since it is\n   part of the `extension` module.\n1. Testing helpers should be in a separate submodule with the suffix `test`. For example, if you\n   have a module `component`, the helpers should be in `component/componenttest`. Testing helpers\n   that are used across multiple modules should be in the [`internal/testutil`](https://github.com/open-telemetry/opentelemetry-collector/tree/main/internal/testutil)\n   module.\n1. Experimental packages that will later be added to another module should be in their own module,\n   named as they will be after integration. For example, if adding a `pprofile` package to `pdata`,\n   you should add a separate module `pdata/pprofile` for the experimental code.\n1. Experimental code that will be added to an existing package in a stable module can be a submodule\n   with the same name, but prefixed with an `x`. For example, `config/confighttp` module can have an\n   experimental module named `config/confighttp/xconfighttp` that contains experimental APIs.\n\nWhen adding a new module remember to update the following:\n1. Add a changelog note for the new module.\n1. Add the module in `versions.yaml`.\n1. Use `make crosslink` to make sure the module replaces are added correctly throughout the\n   codebase. You may also have to manually add some of the replaces.\n1. Update the [otelcorecol\n   manifest](https://github.com/open-telemetry/opentelemetry-collector/blob/main/cmd/otelcorecol/builder-config.yaml)\n   and [builder\n   tests](https://github.com/open-telemetry/opentelemetry-collector/blob/main/cmd/builder/internal/builder/main_test.go).\n1. Open a follow up PR to update pseudo-versions in all go.mod files. See [this example\n   PR](https://github.com/open-telemetry/opentelemetry-collector/pull/11668).\n\n## Enumerations\n\nTo keep naming patterns consistent across the project, enumeration patterns are enforced to make intent clear:\n\n- Enumerations should be defined using a type definition, such as `type Level int32`.\n- Enumerations should use either `int` or `string` as the underlying type\n- The enumeration name should succinctly describe its purpose\n  - If the package name represents the entity described by the enumeration then the package name should be factored into the name of the enumeration.  For example, `component.Type` instead of `component.ComponentType`.\n  - The name should convey a sense of limited categorization. For example, `pcommon.ValueType` is better than `pcommon.Value` and `component.Kind` is better than `component.KindType`, since `Kind` already conveys categorization.\n- Constant values of an enumeration should be prefixed with the enumeration type name in the name:\n  - `pcommon.ValueTypeStr` for `pcommon.ValueType`\n  - `pmetric.MetricTypeGauge` for `pmetric.MetricType`\n\n\n## Recommended Libraries / Defaults\n\nIn order to simplify development within the project, we have made certain library recommendations that should be followed.\n\n| Scenario \t | Recommended                   \t                | Rationale                                                                                                                  |\n|------------|------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------|\n| Hashing  \t | [\"hashing/fnv\"](https://pkg.go.dev/hash/fnv) \t | The project adopted this as the default hashing method due to the efficiency and is reasonable for non-cryptographic use \t |\n| Testing  \t | Use `t.Parallel()` where possible            \t | Enabling more tests to be run in parallel will speed up the feedback process when working on the project.                 \t |\n\n\nWithin the project, there are some packages that have yet to follow the recommendations and are being addressed. However, any new code should adhere to the recommendations.\n\n## Default Configuration\n\nTo guarantee backward-compatible behavior, all configuration packages should supply a `NewDefault[config name]` functions that create a default version of the config. The package does not need to guarantee that `NewDefault[config name]` returns a usable configuration—only that default values will be set. For example, if the configuration requires that a field, such as `Endpoint` be set, but there is no valid default value, then `NewDefault[config name]` may set that value to `\"\"` with the expectation that the user will set a valid value.\n\nUsers should always initialize the config struct with this function and overwrite anything as needed.\n\n## Startup Error Handling\n\nVerify configuration during startup and fail fast if the configuration is invalid.\nThis will bring the attention of a human to the problem as it is more typical for humans\nto notice problems when the process is starting as opposed to problems that may arise\nsometime (potentially long time) after process startup. Monitoring systems are likely\nto automatically flag processes that exit with failure during startup, making it\neasier to notice the problem. The Collector should print a reasonable log message to\nexplain the problem and exit with a non-zero code. It is acceptable to crash the process\nduring startup if there is no good way to exit cleanly but do your best to log and\nexit cleanly with a process exit code.\n\n## Propagate Errors to the Caller\n\nDo not crash or exit outside the `main()` function, e.g. via `log.Fatal` or `os.Exit`,\neven during startup. Instead, return detailed errors to be handled appropriately\nby the caller. The code in packages other than `main` may be imported and used by\nthird-party applications, and they should have full control over error handling\nand process termination.\n\n## Do not Crash after Startup\n\nDo not crash or exit the Collector process after the startup sequence is finished.\nA running Collector typically contains data that is received but not yet exported further\n(e.g. data that is stored in the queues and other processors). Crashing or exiting the Collector\nprocess will result in losing this data since typically the receiver has\nalready acknowledged the receipt for this data and the senders of the data will\nnot send that data again.\n\n## Bad Input Handling\n\nDo not crash on bad input in receivers or elsewhere in the pipeline.\n[Crash-only software](https://en.wikipedia.org/wiki/Crash-only_software)\nis valid in certain cases; however, this is not a correct approach for Collector (except\nduring startup, see above). The reason is that many senders from which the Collector\nreceives data have built-in automatic retries of the _same_ data if no\nacknowledgment is received from the Collector. If you crash on bad input\nchances are high that after the Collector is restarted it will see the same\ndata in the input and will crash again. This will likely result in an infinite\ncrashing loop if you have automatic retries in place.\n\nTypically bad input when detected in a receiver should be reported back to the\nsender. If it is elsewhere in the pipeline it may be too late to send a response\nto the sender (particularly in processors which are not synchronously processing\ndata). In either case, it is recommended to keep a metric that counts bad input data.\n\n## Error Handling and Retries\n\nBe rigorous in error handling. Don't ignore errors. Think carefully about each\nerror and decide if it is a fatal problem or a transient problem that may go away\nwhen retried. Fatal errors should be logged or recorded in an internal metric to\nprovide visibility to users of the Collector. For transient errors come up with a\nretrying strategy and implement it. Typically you will\nwant to implement retries with some sort of exponential back-off strategy. For\nconnection or sending retries use jitter for back-off intervals to avoid overwhelming\nyour destination when the network is restored or the destination is recovered.\n[Exponential Backoff](https://github.com/cenkalti/backoff) is a good library that\nprovides all this functionality.\n\n## Logging\n\nLog your component startup and shutdown, including successful outcomes (but don't\noverdo it, and keep the number of success messages to a minimum).\nThis can help to understand the context of failures if they occur elsewhere after\nyour code is successfully executed.\n\nUse logging carefully for events that can happen frequently to avoid flooding\nthe logs. Avoid outputting logs per a received or processed data item since this can\namount to a very large number of log entries (Collector is designed to process\nmany thousands of spans and metrics per second). For such high-frequency events\ninstead of logging consider adding an internal metric and incrementing it when\nthe event happens.\n\nMake log messages human readable and also include data that is needed for easier\nunderstanding of what happened and in what context.\n\n## Executing External Processes\n\nThe components should avoid executing arbitrary external processes with arbitrary command\nline arguments based on user input, including input received from the network or input\nread from the configuration file. Failure to follow this rule can result in arbitrary\nremote code execution, compelled by malicious actors that can craft the input.\n\nThe following limitations are recommended:\n- If an external process needs to be executed limit and hard-code the location where\n  the executable file may be located, instead of allowing the input to dictate the\n  full path to the executable.\n- If possible limit the name of the executable file to be pulled from a hard-coded\n  list defined at compile time.\n- If command line arguments need to be passed to the process do not take the arguments\n  from the user input directly. Instead, compose the command line arguments indirectly,\n  if necessary, deriving the value from the user input. Limit as much as possible the\n  size of the possible space of values for command line arguments.\n\n## Observability\n\nOut of the box, your users should be able to observe the state of your\ncomponent. See [observability.md](observability.md) for more details.\n\nWhen using the regular helpers, you should have some metrics added around key\nevents automatically. For instance, exporters should have\n`otelcol_exporter_sent_spans` tracked without your exporter doing anything.\n\nCustom metrics can be defined as part of the `metadata.yaml` for your component.\nThe authoritative source of information for this is [the\nschema](https://github.com/open-telemetry/opentelemetry-collector/blob/main/cmd/mdatagen/metadata-schema.yaml),\nbut here are a few examples for reference, adapted from the tail sampling\nprocessor:\n\n```yaml\ntelemetry:\n  metrics:\n    # example of a histogram\n    processor.tailsampling.samplingdecision.latency:\n      description: Latency (in microseconds) of a given sampling policy.\n      unit: µs # from https://ucum.org/ucum\n      enabled: true\n      histogram:\n        value_type: int\n        # bucket boundaries can be overridden\n        bucket_boundaries: [1, 2, 5, 10, 25, 50, 75, 100, 150, 200, 300, 400, 500, 750, 1000, 2000, 3000, 4000, 5000, 10000, 20000, 30000, 50000]\n\n    # example of a counter\n    processor.tailsampling.policyevaluation.errors:\n      description: Count of sampling policy evaluation errors.\n      unit: \"{errors}\"\n      enabled: true\n      sum:\n        value_type: int\n        monotonic: true\n\n    # example of a gauge\n    processor.tailsampling.tracesonmemory:\n      description: Tracks the number of traces current on memory.\n      unit: \"{traces}\"\n      enabled: true\n      gauge:\n        value_type: int\n```\n\nRunning `go generate ./...` at the root of your component should generate the\nfollowing files:\n\n- `documentation.md`, with the metrics and their descriptions\n- `internal/metadata/generated_telemetry.go`, with code that defines the metric\n  using the OTel API\n- `internal/metadata/generated_telemetry_test.go`, with sanity tests for the\n  generated code\n\nOn your component's code, you can use the metric by initializing the telemetry\nbuilder and storing it on a component's field:\n\n```go\ntype tailSamplingSpanProcessor struct {\n    ctx context.Context\n\n    telemetry *metadata.TelemetryBuilder\n}\n\nfunc newTracesProcessor(ctx context.Context, settings component.TelemetrySettings, nextConsumer consumer.Traces, cfg Config, opts ...Option) (processor.Traces, error) {\n    telemetry, err := metadata.NewTelemetryBuilder(settings)\n    if err != nil {\n        return nil, err\n    }\n\n    tsp := &tailSamplingSpanProcessor{\n        ctx:            ctx,\n        telemetry:      telemetry,\n  }\n}\n```\n\nTo record the measurement, you can then call the metric stored in the telemetry\nbuilder:\n\n```go\ntsp.telemetry.ProcessorTailsamplingSamplingdecisionLatency.Record(ctx, ...)\n```\n\n## Resource Usage\n\nLimit usage of CPU, RAM, and other resources that the code can use. Do not write code\nthat consumes resources in an uncontrolled manner. For example, if you have a queue\nthat can contain unprocessed messages always limit the size of the queue unless you\nhave other ways to guarantee that the queue will be consumed faster than items are\nadded to it.\n\nPerformance test the code for both normal use-cases under acceptable load and also for\nabnormal use-cases when the load exceeds acceptable limits many times over. Ensure that\nyour code performs predictably under abnormal use. For example, if the code\nneeds to process received data and cannot keep up with the receiving rate it is\nnot acceptable to keep allocating more memory for received data until the Collector\nruns out of memory. Instead have protections for these situations, e.g. when hitting\nresource limits drop the data and record the fact that it was dropped in a metric\nthat is exposed to users.\n\n## Graceful Shutdown\n\nCollector does not yet support graceful shutdown but we plan to add it. All components\nmust be ready to shutdown gracefully via `Shutdown()` function that all component\ninterfaces require. If components contain any temporary data they need to process\nand export it out of the Collector before shutdown is completed. The shutdown process\nwill have a maximum allowed duration so put a limit on how long your shutdown\noperation can take.\n\n## Unit Tests\n\nCover important functionality with unit tests. We require that contributions\ndo not decrease the overall code coverage of the codebase - this is aligned with our\ngoal to increase coverage over time. Keep track of execution time for your unit\ntests and try to keep them as short as possible.\n\n## Semantic Conventions compatibility\n\nWhen adding new metrics, attributes or entity attributes to a Collector's component (receiver, processor etc), the\n[Semantic Conventions](https://github.com/open-telemetry/semantic-conventions) project should be checked first\nto see if those are already defined as Semantic Conventions.\nIt's also important to check for any open issues that may already propose these or similar Semantic Conventions.\nIf no such Semantic Conventions are defined in the Semantic Conventions project, the component’s code owners\nshould consider initiating that process first\n(refer to Semantic Conventions'\n[contribution guidelines](https://github.com/open-telemetry/semantic-conventions/blob/main/CONTRIBUTING.md) \nfor specific details).\nThe implementation of the component can still be submitted as a draft PR to demonstrate how the proposed\nSemantic Conventions would be used while working in parallel to contribute the relevant updates to\nthe Semantic Conventions project.\nThe components's code owners can review the Semantic Conventions PR in collaboration with any existing domain-specific\nSemConv approvers.\nAt their discretion, the code owners may choose to block the component’s implementation PR until the related\nSemantic Conventions changes are completed.\n\n## Telemetry Stability Levels\n\n### Metrics\n\nMetrics emitted by Collector scrapers/receivers (e.g. `system.cpu.time`) follow the same stability levels\nas the Collector's internal metrics (e.g. `otelcol_process_cpu_seconds`), as documented in\n[Internal Telemetry Stability](https://opentelemetry.io/docs/collector/internal-telemetry/#metrics).\n\nIn particular, for beta and stable levels the following guidelines apply:\n\n#### Beta stability level\n\nIt is highly encouraged that metrics in beta stage\nare also defined as Semantic Conventions based on the [Semantic Conventions compatibility](#semantic-conventions-compatibility),\nensuring cross-project consistency.\n\n#### Stable stability level\n\nBefore promoting a metric to stable, it should be discussed whether it needs to\nbe defined as a Semantic Convention, following the [Semantic Conventions compatibility](#semantic-conventions-compatibility).\nPromoting a metric to stable without it being a Semantic Convention involves\nthe risk of potential divergence within OpenTelemetry's projects.\nFor example, a stable metric in the Collector might be introduced in a slightly\ndifferent way in another OpenTelemetry project in the future, or it might be proposed\nas a Semantic Convention in the future.\nIn case of such divergence, a stable Collector metric won't be allowed to\nchange, and if wider alignment is needed, the metric should be deprecated and\nremoved in order to come into alignment with the Semantic Conventions.\nConsequently, the Collector's maintainers and components' code owners should\nacknowledge that risk before marking a metric as stable without it being a\nstable Semantic Convention and should provide justification for the decision. In\nany case, [Semantic Conventions' guidelines](https://opentelemetry.io/docs/specs/semconv/how-to-write-conventions/)\nshould be advised when metrics are defined within the Collector directly.\n\n### Testing Library Recommendations\n\nTo keep testing practices consistent across the project, it is advised to use these libraries under\nthese circumstances:\n\n- For assertions to validate expectations, use `\"github.com/stretchr/testify/assert\"`\n- For assertions that are required to continue the test, use `\"github.com/stretchr/testify/require\"`\n- For mocking external resources, use `\"github.com/stretchr/testify/mock\"`\n- For validating HTTP traffic interactions, `\"net/http/httptest\"`\n\n## Integration Testing\n\nIntegration testing is encouraged throughout the project, container images can be used in order to facilitate\na local version. In their absence, it is strongly advised to mock the integration.\n\n## Using CGO\n\nUsing CGO is prohibited due to the lack of portability and complexity\nthat comes with managing external libraries with different operating systems and configurations.\nHowever, if the package MUST use CGO, this should be explicitly called out within the readme\nwith clear instructions on how to install the required libraries.\nFurthermore, if your package requires CGO, it MUST be able to compile and operate in a no-op mode\nor report a warning back to the collector with a clear error saying CGO is required to work.\n\n## Breaking changes\n\nWhenever possible, we adhere to [semver](https://semver.org/) as our minimum standards. Even before v1, we strive not to break compatibility\nwithout a good reason. Hence, when a change is known to cause a breaking change, we intend to follow these principles:\n\n- Breaking changes MUST have migration guidelines that clearly explain how to adapt to them.\n- Users SHOULD be able to adopt the breaking change at their own pace, independent of other Collector updates.\n- Users SHOULD be proactively notified about the breaking change before a migration is required.\n- Users SHOULD be able to easily tell whether they have completed the migration for a breaking change.\n\nNot all changes have the same effects on users, so some of the steps may be unnecessary for some changes.\n\n### API breaking changes\n\nWe strive to perform API breaking changes in two stages, deprecating it first (`vM.N`) and breaking it in a subsequent\nversion (`vM.N+1`).\n\n- when we need to remove something, we MUST mark a feature as deprecated in one version and MAY remove it in a\n  subsequent one\n- when renaming or refactoring types, functions, or attributes, we MUST create the new name and MUST deprecate the old\n  one in one version (step 1), and MAY remove it in a subsequent version (step 2). For simple renames, the old name\n  SHALL call the new one.\n- when a feature is being replaced in favor of an existing one, we MUST mark a feature as deprecated in one version, and\n  MAY remove it in a subsequent one.\n\nDeprecation notice SHOULD contain a version starting from which the deprecation takes effect for tracking purposes. For\nexample, if `GetFoo` function is going to be deprecated in `v0.45.0` version, it gets the following godoc line:\n\n```golang\npackage test\n\n// Deprecated: [v0.45.0] Use MustDoFoo instead.\nfunc DoFoo() {}\n```\n\nIf applicable, add the [`//go:fix inline`\ndirective](https://pkg.go.dev/golang.org/x/tools/go/analysis/passes/inline#hdr-Analyzer_inline) on\nthe deprecated function to help with the migration.\n\n#### Example #1 - Renaming a function\n\n1. Current version `v0.N` has `func GetFoo() Bar`\n1. We now decided that `GetBar` is a better name. As such, on `v0.N+1` we add a new `func GetBar() Bar` function,\n   changing the existing `func GetFoo() Bar` to be an alias of the new function. Additionally, a log entry with a\n   warning is added to the old function, along with an entry to the changelog.\n1. On `v0.N+2`, we MAY remove `func GetFoo() Bar`.\n\n#### Example #2 - Changing the return values of a function\n\n1. Current version `v0.N` has `func GetFoo() Foo`\n1. We now need to also return an error. We do it by creating a new function that will be equivalent to the existing one\n   so that current users can easily migrate to that: `func MustGetFoo() Foo`, which panics on errors. We release this in\n   `v0.N+1`, deprecating the existing `func GetFoo() Foo` with it, adding an entry to the changelog and perhaps a log\n   entry with a warning.\n1. On `v0.N+2`, we change `func GetFoo() Foo` to `func GetFoo() (Foo, error)`.\n\n#### Example #3 - Changing the arguments of a function\n\n1. Current version `v0.N` has `func GetFoo() Foo`\n2. We now decide to do something that might be blocking as part of `func GetFoo() Foo`, so, we start accepting a\n   context: `func GetFooWithContext(context.Context) Foo`. We release this in `v0.N+1`, deprecating the existing `func\n   GetFoo() Foo` with it, adding an entry to the changelog and perhaps a log entry with a warning. The existing `func\n   GetFoo() Foo` is changed to call `func GetFooWithContext(context.Background()) Foo`.\n3. On `v0.N+2`, we change `func GetFoo() Foo` to `func GetFoo(context.Context) Foo` if desired or remove it entirely if\n   needed.\n\n#### Exceptions\n\nFor changes to modules that do not have a version of `v1` or higher, we may skip the deprecation process described above\nfor the following situations. Note that these changes should still be recorded as breaking changes in the changelog.\n\n* **Variadic arguments.** Functions that are not already variadic may have a variadic parameter added as a method of\n  supporting optional parameters, particularly through the functional options pattern. If a variadic parameter is\n  added to a function with no change in functionality when no variadic arguments are passed, the deprecation process\n  may be skipped. Calls to updated functions without the new argument will continue to work before, but users who depend\n  on the exact function signature as a type, for example as an argument to another function, will experience a\n  breaking change. For this reason, the deprecation process should only be skipped when it is not expected that\n  the function is commonly passed as a value.\n\n### End-user impacting changes\n\nFor end user breaking changes, we follow the [feature gate](https://github.com/open-telemetry/opentelemetry-collector/tree/main/featuregate#feature-lifecycle)\napproach. This is a well-known approach in other projects such as Kubernetes. A feature gate has\nthree stages: alpha, beta and stable. The intent of these stages is to decouple other software\nchanges from the breaking change; some users may adopt the change early, while other users may delay\nits adoption.\n\n#### Feature gate IDs\n\nFeature gate IDs should be namespaced using dots to denote the hierarchy. The namespace should be as\nspecific as possible; in particular, for feature gates specific to a certain component the ID should\nhave the following structure: `<component kind>.<component type>.<base ID>`. The \"base ID\" should be\nwritten with a verb that describes what happens when the feature gate is enabled. For example, if\nyou want to add a feature gate for the OTLP receiver that changes the default endpoint to bind to an\nunspecified host, you could name your feature gate `receiver.otlp.UseUnspecifiedHostAsDefaultHost`.\n\n#### Lifecycle of a breaking change\n\n##### Alpha stage\n\nAt the alpha stage, the change is opt-in. At this stage we want to notify users that a change is\ncoming, so they can start preparing for it and we have some early adopters that provide us with\nfeedback. Consider the following items before the initial release of an alpha feature gate:\n\n* If **docs and examples** can be updated in a way that prevents the breaking change from affecting\n  users, this is the time to update them!\n* Provide users with tools to understand the breaking change\n  * (Optional) Create or update a **Github issue** to document what the change is about, who it\n    affects and what its effects are\n  * (Optional) Consider adding **telemetry** that allows users to track their migration. For\n    example, you can add a counter for the times that you see a payload that would be affected by\n    the breaking change.\n* Notify users about the upcoming change\n  * Add a **changelog entry** that describes the feature gate. It should include its name, when you\n    may want to use it, and what its effects are. The changelog entry can be given the `enhancement`\n    classification at this stage.\n  * (Optional but strongly recommended) Log a **warning** if the user is using the software in a way\n    that would be affected by the breaking change. Point the user to the feature gate and any\n    official docs.\n* (Optional) Try to **test this in a realistic setting.** If this solves an issue, ask the poster to\n  try to use it and check that everything works.\n\n##### Beta stage\n\nAt the beta stage, the change is opt-out. At this stage we want to notify users that the change is\nhappening, and help them understand how to revert back to the previous behavior temporarily if they\nneed to do so. You may directly start from this stage for breaking changes that are less impactful\nor for changes that should not have a functional impact such as performance changes. Consider the\nfollowing items before moving from alpha to beta:\n\n* Schedule the **docs and examples** update to align with the breaking change release if you\n  couldn’t do it before\n* Provide users with tools to understand the breaking change\n  * Update the **Github issue** with the new default behavior (or create one if starting from here)\n  * Update the feature gate to add the ‘to version’ to the feature gate\n* Notify users about the change\n  * Add a second **changelog entry** that describes the change one more time and is marked as\n    ‘breaking’.\n  * If applicable, add an **error message** that tells you this is the result of a breaking change\n    that can be temporarily reverted disabling the feature gate and points to any issue or docs\n    about it.\n\n##### Stable stage\n\nAt the stable stage, the change cannot be reverted. In some cases, you may directly start here and\njust do the change, in which case you do not need a feature gate, but you should still follow the\nchecklist below (notify, update docs and examples). Consider the following items before moving from\nbeta to stable:\n\n* Remove the dead code\n* Provide users with tools to understand the breaking change\n  * Update the **documentation** **and examples** to remove any references to the feature gate and\n    the previous behavior. Close the **Github issue** if you opened one before.\n* Notify users about the change\n  * Add one last **changelog entry** so users know the range where the feature gate was in beta\n  * Amend the **error message** to remove any references to the feature gate.\n\n## Specification Tracking\n\nThe [OpenTelemetry Specification](https://github.com/open-telemetry/opentelemetry-specification) can be a rapidly\nmoving target at times.  While it may seem efficient to get an early start on implementing new features or\nfunctionality under development in the specification, this can also lead to significant churn and a risk that\nchanges in the specification can result in breaking changes to the implementation.  For this reason, it is the\npolicy of the Collector SIG to not implement, or accept implementations of, new or changed specification language\nprior to inclusion in a stable release of the specification.\n"
  },
  {
    "path": "docs/component-stability.md",
    "content": "# Stability Levels and versioning\n\n## Table of Contents\n\n- [Stability levels](#stability-levels)\n  - [Development](#development)\n  - [Alpha](#alpha)\n  - [Beta](#beta)\n  - [Stable](#stable)\n  - [Deprecated](#deprecated)\n  - [Unmaintained](#unmaintained)\n- [Moving between stability levels](#moving-between-stability-levels)\n- [Graduation criteria](#graduation-criteria)\n  - [In development to alpha](#in-development-to-alpha)\n  - [Alpha to beta](#alpha-to-beta)\n  - [Beta to stable](#beta-to-stable)\n- [Deprecation Information](#deprecation-information)\n- [Versioning](#versioning)\n- [Component Graduation to Stable](#component-graduation-to-stable)\n  - [Difference between signal and component graduation](#difference-between-signal-and-component-graduation)\n  - [Requirements for component graduation](#requirements-for-component-graduation)\n  - [Adoption evidence](#adoption-evidence)\n  - [Graduation process](#graduation-process)\n\n## Stability levels\n\nThe Collector components and implementation are in different stages of stability, and usually split between\nfunctionality and configuration. While we intend to provide high-quality components as part of this repository,\nwe acknowledge that not all of them are ready for prime time. Moreover, the stability of components that can\nhandle multiple signals can depend on the signal in question.\n\nAs such, each component should list its current stability level for each telemetry signal in its README file, according to\nthe following definitions:\n\n### Development\n\nNot all pieces of the component are in place yet and it might not be available as part of any distributions yet. Bugs and performance issues should be reported, but it is likely that the component owners might not give them much attention. Your feedback is still desired, especially when it comes to the user-experience (configuration options, component observability, technical implementation details, ...). Configuration options might break often depending on how things evolve. The component should not be used in production.\n\n### Alpha\n\nThe component is ready to be used for limited non-critical workloads and the authors of this component would welcome your feedback. Bugs and performance problems should be reported, but component owners might not work on them right away.\n\n#### Configuration changes\n\nConfiguration for alpha components can be changed with minimal notice. Documenting them as part of the changelog is\nsufficient. We still recommend giving users one or two minor versions' notice before breaking the configuration, such as\nwhen removing or renaming a configuration option. Providing a migration path in the component's repository is NOT\nrequired for alpha components, although it is still recommended.\n\n- when adding a new configuration option, components MAY mark the new option as required and are not required to provide\n  a reasonable default.\n- when renaming a configuration option, components MAY treat the old name as an alias to the new one and log a WARN\n  level message in case the old option is being used.\n- when removing a configuration option, components MAY keep the old option for a few minor releases and log a WARN level\n  message instructing users to remove the option.\n\n#### Documentation requirements\n\nAlpha components should document how to use them in the most common situations, including:\n- One or more example configuration snippets for the most common use cases.\n\n### Beta\n\nSame as Alpha, but the configuration options are deemed stable. While there might be breaking changes between releases, component owners should try to minimize them. A component at this stage is expected to have had exposure to non-critical production workloads already during its **Alpha** phase, making it suitable for broader usage.\n\n#### Configuration changes\n\nBackward incompatible changes should be rare events for beta components. Users of those components are not expecting to\nhave their Collector instances failing at startup because of a configuration change. When doing backward incompatible\nchanges, component owners should add the migration path to a place within the component's repository, linked from the\ncomponent's main README. This is to ensure that people using older instructions can understand how to migrate to the\nlatest version of the component.\n\nWhen adding a new required option:\n- the option MUST come with a sensible default value\n\nWhen renaming or removing a configuration option:\n- the option MUST be deprecated in one version\n- a WARN level message should be logged, with a link to a place within the component's repository where the change is\n  documented and a migration path is provided\n- the option MUST be kept for at least N+1 version and MAY be hidden behind a feature gate in N+2\n- the option and the WARN level message MUST NOT be removed earlier than N+2 or 6 months, whichever comes later\n\nAdditionally, when removing an option:\n- the option MAY be made non-operational already by the same version where it is deprecated\n\n#### Documentation requirements\n\nBeta components should have a set of documentation that documents its usage in most cases,\nincluding:\n- One or more example configuration snippets for the most common use cases.\n- Advanced configuration options that are known to be used in common environments.\n- All component-specific feature gates including a description for them and when they should be\n  used.\n- Warnings about known limitations and ways to misuse the component.\n\nReceivers that produce a fixed set of telemetry should document the telemetry they produce,\nincluding:\n- For all signals, the resource attributes that are expected to be present in telemetry.\n- For metrics, the name, description, type, units and attributes of each metric.\n\n### Stable\n\nThe component is ready for general availability. Bugs and performance problems should be reported and there's an expectation that the component owners will work on them. Breaking changes, including configuration options and the component's output are not expected to happen without prior notice, unless under special circumstances.\n\n#### Configuration changes\n\nStable components MUST be compatible between minor versions unless critical security issues are found. In that case, the\ncomponent owner MUST provide a migration path and a reasonable time frame for users to upgrade. The same rules from beta\ncomponents apply to stable when it comes to configuration changes.\n\n#### Testing requirements\n\nStable components MUST have a comprehensive test suite. In particular they MUST have:\n1. A **test coverage** that exceeds the highest between 80% coverage and the repository-wide\nminimum. The unit test suite SHOULD cover all configuration options. The coverage MUST be shown as\npart of the component documentation.\n2. At least one **lifecycle test** that tests the component's initialization with a valid\n   configuration and ensures proper context propagation if applicable.\n3. At least one **benchmark test** for each stable signal. The component's documentation MUST\n   include a link to the latest run of benchmark results.\n\n#### Documentation requirements\n\nStable components should have a complete set of documentation, including:\n- One or more example configuration snippets for the most common use cases.\n- All configuration options supported by the component and a description for each of them.\n- All component-specific feature gates including a description for them and when they should be\n  used.\n- All component-specific self-observability features that are not available for other components and\n  what they provide.\n- Compatibility guarantees with external dependencies including the versions it is compatible with\n  and under what conditions.\n- Guidance related to the component's usage in production environments, including how to scale a deployment of this component properly if it needs special considerations.\n- If stateful, how to configure the component to use persistent storage and how to gracefully\n  shutdown and restart the component.\n- Warnings about known limitations and ways to misuse the component.\n\nReceivers that produce a fixed set of telemetry should document the telemetry they produce,\nincluding:\n- For all signals, the resource attributes that are expected to be present in telemetry.\n- For metrics, the name, description, type, units and attributes of each metric.\n\n#### Observability requirements\n\nStable components should emit enough internal telemetry to let users detect errors, as well as data\nloss and performance issues inside the component, and to help diagnose them if possible.\n\nFor extension components, this means some way to monitor errors (for example through logs or span\nevents), and some way to monitor performance (for example through spans or histograms). Because\nextensions can be so diverse, the details will be up to the component authors, and no further\nconstraints are set out in this document.\n\nFor pipeline components however, this section details the kinds of values that should be observable\nvia internal telemetry for all stable components.\n\n> [!NOTE]\n> - The following categories MUST all be covered, unless justification is given as to why one may\n>   not be applicable.\n> - However, for each category, many reasonable implementations are possible, as long as the\n>   relevant information can be derived from the emitted telemetry; everything after the basic\n>   category description is a recommendation, and is not normative.\n> - Of course, a component may define additional internal telemetry which is not in this list.\n> - Some of this internal telemetry may already be provided by pipeline auto-instrumentation or\n>   helper modules (such as `receiverhelper`, `scraperhelper`, `processorhelper`, or\n>   `exporterhelper`). Please check the documentation to verify which parts, if any, need to be\n>   implemented manually.\n\n**Definition:** In the following, an \"item\" refers generically to a single log record, metric point,\nor span.\n\nThe internal telemetry of a stable pipeline component should allow observing the following:\n\n1. How much data the component receives.\n\n    For receivers, this could be a metric counting requests, received bytes, scraping attempts, etc.\n\n    For other components, this would typically be the number of items received through the\n    `Consumer` API.\n\n2. How much data the component outputs.\n\n    For exporters, this could be a metric counting requests, sent bytes, etc.\n\n    For other components, this would typically be the number of items forwarded to the next\n    component through the `Consumer` API.\n\n3. How much data is dropped because of errors.\n\n    For receivers, this could include a metric counting payloads that could not be parsed in.\n\n    For receivers and exporters that interact with an external service, this could include a metric\n    counting requests that failed because of network errors.\n\n    For processors, this could be an `outcome` (`success` or `failure`) attribute on a \"received\n    items\" metric defined for point 1.\n\n    The goal is to be able to easily pinpoint the source of data loss in the Collector pipeline, so\n    this should either:\n    - only include errors internal to the component, or;\n    - allow distinguishing said errors from ones originating in an external service, or propagated\n        from downstream Collector components.\n\n4. Details for error conditions.\n\n    This could be in the form of logs or spans detailing the reason for an error. As much detail as\n    necessary should be provided to ease debugging. Processed signal data should not be included for\n    security and privacy reasons.\n\n5. Other possible discrepancies between input and output, if any. This may include:\n\n    - How much data is dropped as part of normal operation (eg. filtered out).\n\n    - How much data is created by the component.\n\n    - How much data is currently held by the component, and how much can be held if there is a fixed\n        capacity.\n    \n        This would typically be an UpDownCounter keeping track of the size of an internal queue, along\n        with a gauge exposing the queue's capacity.\n\n6. Processing performance.\n\n    This could include spans for each operation of the component, or a histogram of end-to-end\n    component latency.\n    \n    The goal is to be able to easily pinpoint the source of latency in the Collector pipeline, so\n    this should either:\n    - only include time spent processing inside the component, or;\n    - allow distinguishing this latency from that caused by an external service, or from time spent\n        in downstream Collector components.\n    \n    As an application of this, components which hold items in a queue should allow differentiating\n    between time spent processing a batch of data and time where the batch is simply waiting in the\n    queue.\n    \n    If multiple spans are emitted for a given batch (before and after a queue for example), they\n    should either belong to the same trace, or have span links between them, so that they can be\n    correlated.\n\nWhen measuring amounts of data, it is recommended to use \"items\" as your unit of measure. Where this\ncan't easily be done, any relevant unit may be used, as long as zero is a reliable indicator of the\nabsence of data. In any case, all metrics should have a defined unit (not \"1\").\n\nAll internal telemetry emitted by a component should have attributes identifying the specific\ncomponent instance that it originates from. This should follow the same conventions as the\n[pipeline universal telemetry](rfcs/component-universal-telemetry.md).\n\nIf data can be dropped/created/held at multiple distinct points in a component's pipeline (eg.\nscraping, validation, processing, etc.), it is recommended to define additional attributes to help\ndiagnose the specific source of the discrepancy, or to define different signals for each.\n\nThe breakdown of emitted telemetry per telemetry level (basic / normal / detailed) should follow\nthe guidelines in [the Go package documentation for `configtelemetry`](/config/configtelemetry/doc.go).\n\n### Deprecated\n\nThe component is planned to be removed in a future version and no further support will be provided. Note that new issues will likely not be worked on. When a component enters \"deprecated\" mode, it is expected to exist for at least two minor releases. See the component's readme file for more details on when a component will cease to exist.\n\n### Unmaintained\n\nA component identified as unmaintained does not have an active code owner. Such component may have never been assigned a code owner or a previously active code owner has not responded to requests for feedback within 6 weeks of being contacted. Issues and pull requests for unmaintained components will be labelled as such. After 3 months of being unmaintained, these components will be removed from official distribution. Components that are unmaintained are actively seeking contributors to become code owners.\n\nComponents that were accepted based on being vendor-specific components will be marked as unmaintained if\nthey have no active code owners from the vendor even if there are other code owners listed. As part of being marked unmaintained, we'll attempt to contact the vendor to notify them of the change. Other active code\nowners may petition for its continued maintenance if they want, at which point the component will no\nlonger be considered vendor-specific.\n\n## Moving between stability levels\n\nComponents can move between stability levels. The valid transitions are described in the following diagram:\n\n```mermaid\nstateDiagram-v2\n    state Maintained {\n    InDevelopment --> Alpha\n    Alpha --> Beta\n    Beta --> Stable\n    }\n\n    InDevelopment: In Development\n\n    Maintained --> Unmaintained\n    Unmaintained --> Maintained\n    Maintained --> Deprecated\n    Deprecated --> Maintained: (should be rare)\n```\n\nTo move within the 'Maintained' ladder (\"graduate\"), the process for doing so is as follows:\n\n1. One of the component owners should file an issue with the 'Graduation' issue template to request\n   the graduation.\n2. An approver is assigned in a rotating basis to evaluate the request and provide feedback. For\n   vendor specific components, the approver should be from a different employer to the one owning\n   the component.\n3. If approved, a PR to change the stability level should be opened and MUST be approved by all\n   listed code owners.\n\n## Graduation criteria\n\nIn addition to the requirements outlined above, additional criteria should be met before a component\ncan graduate to a higher stability level. These ensure that the component is ready for the increased\nusage and scrutiny that comes with a higher stability level, and that the community around it is\nsufficiently healthy.\n\nIf the graduation criteria are not met, the approver should provide feedback on what is missing and\nhow to address it. The component owners can then address the feedback and re-request graduation on\nthe same issue.\n\n## In development to alpha\n\nNo additional criteria are required to graduate from development to alpha.\nThe component still needs to meet the general requirements for alpha components.\n\n## Alpha to beta\n\nTo graduate any signal from alpha to beta on a component:\n1. The component MUST have at least two active code owners.\n3. Within the 30 days prior to the graduation request, the code owners MUST have reviewed and\n   replied to at least 80% of the issues and pull requests opened against the component. This\n   excludes general PRs or issues that are not specific to the component itself (e.g. repo-wide API\n   updates). It is not necessary that the issues and PRs are closed or merged, but that they have\n   been reviewed and replied to appropriately.\n\n## Beta to stable\n\nTo graduate any signal from beta to stable on a component:\n1. The component MUST have at least three active code owners.\n2. The component benchmark results MUST have been updated within the last 30 days and published in the component's README.\n3. Within the 60 days prior to the graduation request, the code owners MUST have reviewed and\n   replied to at least 80% of the issues and pull requests opened against the component. This\n   excludes general PRs or issues that are not specific to the component itself (e.g. repo-wide API\n   updates). It is not necessary that the issues and PRs are closed or merged, but that they have\n   been reviewed and replied to appropriately.\n\n## Deprecation Information\n\nWhen a component is moved to deprecated, a deprecation section should indicate the date it was deprecated\nas well as any migration guidance. In some occasions might not be offered migration guidance but reviewers should\nexplicitly agree on this, and use a \"No migration is offered for this component\" hint.\n\n## Versioning\n\nFor a component to be marked as 1.x it MUST be stable for at least one signal.\nEven if a component has a 1.x or greater version, its behavior for specific signals might change in ways that break end users if the component is not stable for a particular signal.\n\nHowever, components are Go modules and as such follow [semantic versioning](https://semver.org/). Go API stability guarantees are covered in the [VERSIONING.md](../VERSIONING.md) document.\nThe versioning of a component, and the Go API stability guarantees that come with it, apply to ALL signals simultaneously, regardless of their stability level.\nThis means that, once a component is marked as 1.x, signal-specific configuration options MUST NOT be removed or changed in a way that breaks our Go API compatibility promise, even if the signal is not stable.\n\n## Component Graduation to Stable\n\nThis section describes the process for graduating a component as a whole from beta to stable. This\nis distinct from signal-level graduation, which is covered in the [Graduation criteria](#graduation-criteria)\nsection above.\n\n### Difference between signal and component graduation\n\nA component can support multiple telemetry signals (traces, metrics, logs and profiles), and each signal has its own stability level. The sections above describe the requirements and process for graduating\nindividual signals within a component.\n\n**Component graduation** refers to declaring the component as a whole as stable. This is a higher\nbar than having individual signals stable, as it represents a commitment that the component is\nproduction-ready, well-maintained, and has demonstrated real-world adoption.\n\nA component MAY have some signals at stable while the component itself is not yet graduated. \nComponent graduation is optional but signals a stronger commitment to the end-user community.\n\n### Requirements for component graduation\n\nBefore opening a PR to graduate a component to stable, the code owners MUST gather evidence that the\nfollowing requirements are met.\n\n#### Signal requirements\n\n1. All supported signals MUST be at beta stability or higher.\n2. At least one signal MUST be at stable stability.\n\n#### Code owner requirements\n\n1. The component MUST have at least three active code owners.\n2. Within the 60 days prior to the graduation request, the code owners MUST have reviewed and\n   replied to at least 80% of the issues and pull requests opened against the component. This\n   excludes general PRs or issues that are not specific to the component itself (e.g. repo-wide API\n   updates).\n\n#### Technical requirements\n\n1. The component MUST meet all [testing requirements](#testing-requirements) for stable components.\n2. The component MUST meet all [documentation requirements](#documentation-requirements) for stable\n   components.\n3. The component MUST meet all [observability requirements](#observability-requirements) for stable\n   components.\n4. The component MUST follow the [coding guidelines](coding-guidelines.md), including the naming\n   conventions for components.\n5. The component MUST have evidence of real-world adoption. See [Adoption evidence](#adoption-evidence)\n   for details on what constitutes acceptable evidence.\n\n### Adoption evidence\n\nAdoption evidence demonstrates that the component has been validated in real-world environments and\nthat there is a community invested in its continued success. Code owners MUST provide at least one\nof the following forms of evidence:\n\n1. **Public adopter testimonials**: At least two organizations have publicly stated (in blog posts,\n   conference talks, GitHub issues, or other public forums) that they use the component in\n   production.\n\n2. **Private attestation**: If adopters cannot be named publicly, code owners MAY provide private\n   attestation to the reviewing maintainer. The attestation MUST include a general description of the\n   scale of usage (e.g., \"processing millions of spans per day\"). The maintainer verifying the\n   attestation MUST confirm they find it credible, but is not required to disclose the details.\n\nThe adoption evidence MUST be documented in the graduation request issue.\n\n### Graduation process\n\nThe process for graduating a component to stable is as follows:\n\n1. **Code owners prepare the request**: One of the code owners files an issue using the 'Component\n   Graduation' issue template. The issue MUST include:\n   - Evidence that all [requirements](#requirements-for-component-graduation) are met.\n   - Links to documentation, test coverage reports, and benchmark results.\n   - [Adoption evidence](#adoption-evidence).\n\n2. **Maintainer assignment**: A maintainer is assigned on a rotating basis to verify the graduation\n   request. For vendor-specific components, the assigned maintainer SHOULD be from a different\n   employer than the one owning the component.\n\n3. **Maintainer verification**: The assigned maintainer reviews the evidence provided by the code\n   owners and verifies that all requirements are met. The maintainer is verifying the evidence, not\n   generating it. If requirements are not met, the maintainer provides feedback on what is missing.\n\n4. **PR submission**: Once the maintainer confirms the requirements are met, the code owners open a\n   PR to update the component's stability level. The PR MUST be approved by:\n   - The assigned maintainer.\n   - All listed code owners.\n\n5. **Merge**: After all approvals are obtained, the PR can be merged.\n\nIf there are disputes about whether the requirements are met, the issue should be escalated to the\nmaintainers for discussion in a Collector SIG meeting.\n"
  },
  {
    "path": "docs/component-status.md",
    "content": "# Component Status Reporting\n\nComponent status reporting is a collector feature that allows components to report their status (aka health) via status events to extensions. In order for an extension receive these events it must implement the [StatusWatcher interface](https://github.com/open-telemetry/opentelemetry-collector/blob/f05f556780632d12ef7dbf0656534d771210aa1f/extension/extension.go#L54-L63).\n\n### Status Definitions\n\nThe system defines six statuses, listed in the table below:\n\n| Status           | Meaning                                                                                                                                            |\n| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Starting         | The component is starting.                                                                                                                         |\n| OK               | The component is running without issue.                                                                                                            |\n| RecoverableError | The component has experienced a transient error and may recover.                                                                                   |\n| PermanentError   | The component has detected a condition at runtime that will need human intervention to fix. The collector will continue to run in a degraded mode. |\n| FatalError       | A component has experienced a fatal error and the collector will shutdown.                                                                        |\n| Stopping         | The component is in the process of shutting down.                                                                                                  |\n| Stopped          | The component has completed shutdown.                                                                                                              |\n\nStatuses can be categorized into two groups: lifecycle and runtime.\n\n**Lifecycle Statuses**\n- Starting\n- Stopping\n- Stopped\n\n**Runtime Statuses**\n- OK\n- RecoverableError\n- PermanentError\n- FatalError\n\n### Transitioning Between Statuses\n\nThere is a finite state machine underlying the status reporting API that governs the allowable state transitions. See the state diagram below:\n\n\n![State Diagram](img/component-status-state-diagram.png)\n\nThe finite state machine ensures that components progress through the lifecycle properly and it manages transitions through runtime states so that components do not need to track their state internally. Only changes in status result in new events being generated; repeat reports of the same status are ignored. PermanentError is a permanent runtime state. A component in a PermanentError state cannot transition to OK or RecoverableError, but it can transition to Stopping. FatalError is a final state. A component in a FatalError state cannot make any further state transitions.\n\n![Status Event Generation](img/component-status-event-generation.png)\n\n### Automation\n\nThe collector's service implementation is responsible for starting and stopping components. Since it knows when these events occur and their outcomes, it can automate status reporting of lifecycle events for components.\n\n**Start**\n\nThe collector will report a Starting event when starting a component. If an error is returned from Start, the collector will report a PermanentError event. If start returns without an error and the component hasn't reported status itself, the collector will report an OK event.\n\n**Shutdown**\n\nThe collector will report a Stopping event when shutting down a component. If Shutdown returns an error, the collector will report a PermanentError event. If Shutdown completes without an error, the collector will report a Stopped event.\n\n### Best Practices\n\n**Start**\n\nUnder most circumstances, a component does not need to report explicit status during component.Start. An exception to this rule is components that start async work (e.g. spawn a go routine). This is because async work may or may not complete before start returns and timing can vary between executions. A component can halt startup by returning an error from start. If start returns an error, automated status reporting will report a PermanentError on behalf of the component. If start returns without an error automated status reporting will report OK, so long has the component hasn't already reported for itself.\n\n**Runtime**\n\n![Runtime State Diagram](img/component-status-runtime-states.png)\n\nDuring runtime a component should not have to keep track of its state. A component should report status as operations succeed or fail and the finite state machine will handle the rest. Changes in status will result in new status events being emitted. Repeat reports of the same status will no-op. Similarly, attempts to make an invalid state transition, such as PermanentError to OK, will have no effect.\n\nWe intend to define guidelines to help component authors distinguish between recoverable and permanent errors on a per-component type basis and we'll update this document as we make decisions. See [this issue](https://github.com/open-telemetry/opentelemetry-collector/issues/9957) for current thoughts and discussions.\n\n**Shutdown**\n\nA component should never have to report explicit status during shutdown. Automated status reporting should handle all cases. To recap, the collector will report Stopping before Shutdown is called. If a component returns an error from shutdown the collector will report a PermanentError and it will report Stopped if Shutdown returns without an error.\n\n### Implementation Details\n\nThere are a couple of implementation details that are worth discussing for those who work on or wish to understand the collector internals.\n\n**component.TelemetrySettings**\n\nThe API for components to report status is the ReportStatus method on the component.TelemetrySettings instance that is part of the CreateSettings passed to a component's factory during creation. It takes a single argument, a status event. The StatusWatcher interface takes both a component instance ID and a status event. The ReportStatus function is customized for each component and passes along the instance ID with each event. A component doesn't know its instance ID, but its ReportStatus method does.\n\n**servicetelemetry.TelemetrySettings**\n\nThe service gets a slightly different TelemetrySettings object, a servicetelemetry.TelemetrySettings, which references the ReportStatus method on a status.Reporter. Unlike the ReportStatus method on component.TelemetrySettings, this version takes two arguments, a component instance ID and a status event. The service uses this function to report status on behalf of the components it manages. This is what the collector uses for the automated status reporting of lifecycle events.\n\n**sharedcomponent**\n\nThe collector has the concept of a shared component. A shared component is represented as a single component to the collector, but represents multiple logical components elsewhere. The most common usage of this is the OTLP receiver, where a single shared component represents a logical instance for each signal: traces, metrics, and logs (although this can vary based on configuration). When a shared component reports status it must report an event for each of the logical instances it represents. In the current implementation, shared component reports status for all its logical instances during [Start](https://github.com/open-telemetry/opentelemetry-collector/blob/31ac3336d956d93abede6db76453730613e1f076/internal/sharedcomponent/sharedcomponent.go#L89-L98) and [Shutdown](https://github.com/open-telemetry/opentelemetry-collector/blob/31ac3336d956d93abede6db76453730613e1f076/internal/sharedcomponent/sharedcomponent.go#L105-L117). It also [modifies the ReportStatus method](https://github.com/open-telemetry/opentelemetry-collector/blob/31ac3336d956d93abede6db76453730613e1f076/internal/sharedcomponent/sharedcomponent.go#L34-L44) on component.TelemetrySettings to report status for each logical instance when called.\n"
  },
  {
    "path": "docs/ga-roadmap.md",
    "content": "# Collector v1 Roadmap\n\nThis document contains the roadmap for the Collector. The main goal of this roadmap is to provide clarity on the areas of focus in order to release a v1 of the Collector.\n\n## Proposal\n\nThe proposed approach to delivering a stable release of the OpenTelemetry Collector is to produce a distribution of the Collector that contains a minimum set of components which have been stabilized. By doing so, the project contributors will ensure dependencies of those components have also been released under a stable version.\n\nThe proposed distribution is set to include the following components only:\n\n- OTLP receiver\n- OTLP exporter\n- OTLP HTTP exporter\n\nThese modules depend on a list of other modules, the full list is available in issue [#9375](https://github.com/open-telemetry/opentelemetry-collector/issues/9375).\n\nAll stabilized modules will conform to the API expectations outlined in the [VERSIONING.md](../VERSIONING.md) document.\n\n### Scope within each module\n\nThe Collector is already used in production at scale and has been tested in a variety of\nenvironments. The focus of the stabilization is primarily not to add missing features but to ensure\nthe maintainability of the project and to provide a predictable and consistent experience for\nend-users.\n\nIn particular when considering enhancement proposals we will focus on:\n1. Binary end-users impact above other audiences.\n2. Parts of the proposals that imply breaking changes to end-users.\n3. Small, predictable or self-contained changes that don't imply a major change in the end-user\n   experience.\n\nAdditionally, when considering bug reports we will prioritize:\n1. [Critical bugs](release.md#bugfix-release-criteria) that affect the stability of the Collector.\n2. Regressions from previous behavior caused by 1.0-related changes.\n\n## Out of scope\n\nExplicitly, the following are not in the scope of v1 for the purposes of this document:\n\n* stabilization of additional components/APIs needed by distribution maintainers. Vendors are not the audience\n  * This explicitly excludes the `service` and `otelcol` modules, for which we will only guarantee that there are no breaking changes impacting end-users of the binary after 1.0, while Go API only changes will continue to be admissible until these modules are tagged as 1.0.\n* Collector Builder\n* telemetrygen\n* mdatagen\n* Operator\n\nThose components are free to pursue v1 at their own pace and may be the focus of future stability work.\n\n## Additional Requirements\n\nThe following is a list of requirements for this minimal Collector distribution to be deemed as 1.0:\n\n* The Collector must be observable\n  * Metrics and traces should be produced for data in the hot path\n  * Metrics should be documented in the end-user documentation\n  * Metrics, or a subset of them, should be marked as stable in the documentation\n  * Logs should be produced for Collector lifecycle events\n  * Stability expectations and lifecycle for telemetry should be documented, so that users can know what they can rely on  for their dashboards and alerts\n* The Collector must be scalable\n  * Backpressure from the exporter all the way back to the receiver should be supported\n  * Queueing must be supported to handle increased loads\n  * Performance metrics are in place and follow best practices for benchmarking\n  * Individual components must:\n    * Have their lifecycle expectations enshrined in tests\n    * Have goleak enabled\n* End-user documentation should be provided as part of the official project’s documentation under opentelemetry.io, including:\n  * Getting started with the Collector\n  * Available (stable) components and how to use them\n  * Blueprints for common use cases\n  * Error scenarios and error propagation\n  * Troubleshooting and how to obtain telemetry from the Collector for the purposes of bug reporting\n  * Queueing, batching, and handling of backpressure\n* The Collector must be supported\n  * Processes, workflows and expectations regarding support, bug reporting and questions should be documented.\n  * A minimum support period for 1.0 is documented, similarly to [API and SDK](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/versioning-and-stability.md#api-support) stability guarantees.\n"
  },
  {
    "path": "docs/internal-architecture.md",
    "content": "## Internal architecture\n\nThis document describes the Collector internal architecture and startup flow. It can be helpful if you are starting to contribute to the Collector codebase.\n\nFor the end-user focused architecture document, please see the [opentelemetry.io's Architecture documentation](https://opentelemetry.io/docs/collector/architecture/).  While it is end user focused, it's still a good place to start if you're trying to learn about the Collector codebase.\n\n### Startup Diagram\n```mermaid\nflowchart TD\n    A(\"`**command.NewCommand**`\") -->|1| B(\"`**updateSettingsUsingFlags**`\")\n    A --> |2| C(\"`**NewCollector**\n    Creates and returns a new instance of Collector`\")\n    A --> |3| D(\"`**Collector.Run**\n    Starts the collector and blocks until it shuts down`\")\n    D --> E(\"`**setupConfigurationComponents**`\")\n    E -->  |1| F(\"`**getConfMap**`\")\n    E ---> |2| G(\"`**Service.New**\n     Initializes telemetry, then initializes the pipelines`\")\n    E --> |3| Q(\"`**Service.Start**\n    1. Start all extensions.\n    2. Notify extensions about Collector configuration\n    3. Start all pipelines.\n    4. Notify extensions that the pipeline is ready.\n    `\")\n    Q --> R(\"`**Graph.StartAll**\n    Calls Start on each component in reverse topological order`\")\n    G --> H(\"`**initExtensionsAndPipeline**\n     Creates extensions and then builds the pipeline graph`\")\n    H --> I(\"`**Graph.Build**\n     Converts the settings to an internal graph representation`\")\n    I --> |1| J(\"`**createNodes**\n     Builds the node objects from pipeline configuration and adds to graph.  Also validates connectors`\")\n    I --> |2| K(\"`**createEdges**\n     Iterates through the pipelines and creates edges between components`\")\n    I --> |3| L(\"`**buildComponents**\n     Topological sort the graph, and create each component in reverse order`\")\n    L --> M(Receiver Factory) & N(Processor Factory) & O(Exporter Factory) & P(Connector Factory)\n```\n### Where to start to read the code\nHere is a brief list of useful and/or important files and interfaces that you may find valuable to glance through.\nMost of these have package-level documentation and function/struct-level comments that help explain the Collector!\n\n- [collector.go](../otelcol/collector.go)\n- [graph.go](../service/internal/graph/graph.go)\n- [component.go](../component/component.go)\n\n#### Factories\nEach component type contains a `Factory` interface along with its corresponding `NewFactory` function.\nImplementations of new components use this `NewFactory` function in their implementation to register key functions with \nthe Collector.  An example of this is in [receiver.go](../receiver/receiver.go).\n\nFor example, the Collector uses this interface to give receivers a handle to a `nextConsumer` -\nwhich represents where the receiver will send its data next in its telemetry pipeline.\n"
  },
  {
    "path": "docs/observability.md",
    "content": "# OpenTelemetry Collector internal observability\n\nThe [Internal telemetry] page on OpenTelemetry's website contains the\ndocumentation for the Collector's internal observability, including:\n\n- Which types of observability are emitted by the Collector.\n- How to enable and configure these signals.\n- How to use this telemetry to monitor your Collector instance.\n\nIf you need to troubleshoot the Collector, see [Troubleshooting].\n\nRead on to learn about experimental features and the project's overall vision\nfor internal telemetry.\n\n<!-- toc -->\n\n- [Goals of internal telemetry](#goals-of-internal-telemetry)\n  * [Observable elements](#observable-elements)\n  * [Impact](#impact)\n  * [Configurable level of observability](#configurable-level-of-observability)\n  * [Internal telemetry properties](#internal-telemetry-properties)\n    + [Units](#units)\n    + [Process for defining new metrics](#process-for-defining-new-metrics)\n- [Experimental trace telemetry](#experimental-trace-telemetry)\n\n<!-- tocstop -->\n\n## Goals of internal telemetry\n\nThe Collector's internal telemetry is an important part of fulfilling\nOpenTelemetry's [project vision](vision.md). The following section explains the\npriorities for making the Collector an observable service.\n\n### Observable elements\n\nThe following aspects of the Collector need to be observable.\n\n- [Current values]\n  - Some of the current values and rates might be calculated as derivatives of\n    cumulative values in the backend, so it's an open question whether to expose\n    them separately or not.\n- [Cumulative values]\n- [Trace or log events]\n  - For start or stop events, an appropriate hysteresis must be defined to avoid\n    generating too many events. Note that start and stop events can't be\n    detected in the backend simply as derivatives of current rates. The events\n    include additional data that is not present in the current value.\n- [Host metrics]\n  - Host metrics can help users determine if the observed problem in a service\n    is caused by a different process on the same host.\n\n### Impact\n\nThe impact of these observability improvements on the core performance of the\nCollector must be assessed.\n\n### Configurable level of observability\n\nSome metrics and traces can be high volume and users might not always want to\nobserve them. An observability verbosity “level” allows configuration of the\nCollector to send more or less observability data or with even finer\ngranularity, to allow turning on or off specific metrics.\n\nThe default level of observability must be defined in a way that has\ninsignificant performance impact on the service.\n\n### Internal telemetry properties\n\nTelemetry produced by the Collector has the following properties:\n\n- metrics produced by Collector components use the prefix `otelcol_`\n- metrics produced by any instrumentation library used by Collector components will *not* be prefixed with `otelcol_`\n- code is instrumented using the OpenTelemetry API for metrics, and traces. Logs are instrumented using zap. Telemetry is collected and produced via the OpenTelemetry Go SDK\n- instrumentation scope defaults to the package name of the component recording telemetry. It can be configured\n  via the `scope_name` option in mdatagen, but the recommendation is to keep the default\n- metrics are defined via `metadata.yaml` except in components that have specific cases where\n  it is not possible to do so. See the [issue](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/33523)\n  which list such components\n- whenever possible, components should leverage core components or helper libraries to capture\n  telemetry, ensuring that all components of the Collector can be consistently observed\n- telemetry produced by components should include attributes that identify specific instances\n  of the components\n\n#### Units\n\nThe following units should be used for metrics emitted by the Collector\nfor the purpose of its internal telemetry:\n\n| Field type                                                                 | Unit           |\n| -------------------------------------------------------------------------- | -------------- |\n| Metric counting the number of log records received, processed, or exported | `{records}`    |\n| Metric counting the number of spans received, processed, or exported       | `{spans}`      |\n| Metric counting the number of data points received, processed, or exported | `{datapoints}` |\n\n#### Process for defining new metrics\n\nMetrics in the Collector are defined via `metadata.yaml`, which is used by [mdatagen] to\nproduce:\n\n- code to create metric instruments that can be used by components\n- documentation for internal metrics\n- a consistent prefix for all internal metrics\n- convenience accessors for meter and tracer\n- a consistent instrumentation scope for components\n- test methods for validating the telemetry\n\nThe process to generate new metrics is to configure them via\n`metadata.yaml`, and run `go generate` on the component.\n\n## Experimental trace telemetry\n\nThe Collector does not expose traces by default, but can be configured.\nThe Collector's internal telemetry uses OpenTelemetry SDK.\n\nThe following configuration can be used in combination with the aforementioned\nfeature gates to emit internal metrics and traces from the Collector to an OTLP\nbackend:\n\n```yaml\nservice:\n  telemetry:\n    metrics:\n      readers:\n        - periodic:\n            interval: 5000\n            exporter:\n              otlp:\n                protocol: grpc\n                endpoint: https://backend:4317\n    traces:\n      processors:\n        - batch:\n            exporter:\n              otlp:\n                protocol: grpc\n                endpoint: https://backend2:4317\n```\n\nSee the [example configuration][kitchen-sink] for additional options.\n\n> This configuration does not support emitting logs as there is no support for\n> [logs] in the OpenTelemetry Go SDK at this time.\n\nYou can also configure the Collector to send its own traces using the OTLP\nexporter. Send the traces to an OTLP server running on the same Collector, so it\ngoes through configured pipelines. For example:\n\n```yaml\nservice:\n  telemetry:\n    traces:\n      processors:\n        batch:\n          exporter:\n            otlp:\n              protocol: grpc\n              endpoint: ${MY_POD_IP}:4317\n```\n\n[Internal telemetry]:\n  https://opentelemetry.io/docs/collector/internal-telemetry/\n[Troubleshooting]: https://opentelemetry.io/docs/collector/troubleshooting/\n[issue7532]:\n  https://github.com/open-telemetry/opentelemetry-collector/issues/7532\n[issue7454]:\n  https://github.com/open-telemetry/opentelemetry-collector/issues/7454\n[logs]: https://github.com/open-telemetry/opentelemetry-go/issues/3827\n[OpenTelemetry Configuration]:\n  https://github.com/open-telemetry/opentelemetry-configuration\n[kitchen-sink]:\n  https://github.com/open-telemetry/opentelemetry-configuration/blob/main/examples/kitchen-sink.yaml\n[Current values]:\n  https://opentelemetry.io/docs/collector/internal-telemetry/#summary-of-values-observable-with-internal-metrics\n[Cumulative values]:\n  https://opentelemetry.io/docs/collector/internal-telemetry/#summary-of-values-observable-with-internal-metrics\n[Trace or log events]:\n  https://opentelemetry.io/docs/collector/internal-telemetry/#events-observable-with-internal-logs\n[Host metrics]:\n  https://opentelemetry.io/docs/collector/internal-telemetry/#lists-of-internal-metrics\n[mdatagen]:\n  https://github.com/open-telemetry/opentelemetry-collector/tree/main/cmd/mdatagen\n"
  },
  {
    "path": "docs/platform-support.md",
    "content": "# Platform Support\n\nThe OpenTelemetry Collector will be supported following a tiered platform support model to balance between the aim to support as many platforms as possible and to guarantee stability for the most important platforms. A platform is described by the pair of operating system and processor architecture family as they are defined by the Go programming language as [known operating systems and architectures for use with the GOOS and GOARCH values](https://go.dev/src/internal/syslist/syslist.go). \n\nFor a supported platform, the OpenTelemetry Collector is supported when the [minimum requirements](https://github.com/golang/go/wiki/MinimumRequirements) of the Go release used by the collector are met for the operating system and architecture. Each supported platform requires the naming of designated owners. The platform support for the OpenTelemetry Collector is broken into three tiers with different levels of support for each tier and aligns with the current test strategy. \n\nFor platforms not listed as supported by any of the tiers, support cannot be assumed to be provided. While the project may accept specific changes related to these platforms, there will be no official builds, support of issues and development of enhancements or bug fixes for these platforms. Future development of project for supported platforms may break the functionality of unsupported platforms.\n\n## Current Test Strategy\n\nThe current verification process of the OpenTelemetry Collector includes unit and performance tests for core and additional end-to-end and integration tests for contrib. In the end-to-end tests, receivers, processors, and exporters etc. are tested in a testbed, while the integration tests rely on actual instances and available container images. Additional stability tests are in preparation for the future as well. All verification tests are run on the linux/amd64 as the primary platform today. In addition, unit tests are run for the _contrib_ collector on windows/amd64. The tests use as execution environments the latest Ubuntu and Windows Server versions [supported as Github runners](https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners#supported-runners-and-hardware-resources). \n\nThe cross compile supports the following targets:\n- darwin/amd64 and darwin/arm64\n- linux/amd64, linux/arm64, linux/386, linux/arm and linux/ppc64le\n- windows/amd64, windows/arm64 and windows/386.\n\nExcept of the mentioned tests for linux/amd64 and windows/amd64, no other platforms are tested by the CI/CD tooling. \n\nContainer images of the _core_ and _contrib_ collector are built and published to Docker Hub and ghcr.io for the platforms specified in the [goreleaser configuration](https://github.com/open-telemetry/opentelemetry-collector-releases/blob/bf8002ec6d2109cdb4184fc6eb6f8bda59ea96a2/.goreleaser.yaml#L137). End-to-end tests of the _contrib_ container images are run on the latest Ubuntu Linux supported by GitHub runners and for the four most recent Kubernetes versions.\n\n## Tiered platform support model\n\nThe platform support for the OpenTelemetry Collector is broken into three tiers with different levels of support for each tier. \n\n### Platform Support - Summary\n\nThe following tables summarized the platform tiers of support by the verification tests performed for them and by the specification if dummy implementations are allowed for selected features, the availability of precompiled binaries incl. container images and if bugfix releases are provided for previous releases in case of critical defects. \n\n| Tier | Unit tests | Performance tests | End-to-end tests | Integrations tests | Dummy implementations | Precompiled binaries | Bugfix releases |\n|------|------------|-------------------|------------------|--------------------|-----------------------|----------------------|-----------------|\n| 1    | yes        | yes               | yes              | yes                | no                    | yes                  | yes             |\n| 2    | yes        | optional          | optional         | optional           | yes                   | yes                  | no              |\n| 3    | no         | no                | no               | no                 | yes                   | yes                  | no              |\n\n### Tier 1 – Primary Support\n\nThe Tier 1 supported platforms are _guaranteed to work_. Precompiled binaries are built on the platform, fully supported for all collector add-ons (receivers, processor, exporters etc.), and continuously tested as part of the development processes to ensure any proposed change will function correctly. Build and test infrastructure is provided by the project. All tests are executed on the platform as part of automated continuous integration (CI) for each pull request and the [release cycle](https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/release.md#release-schedule). Any build or test failure block the release of the collector distribution for all platforms. Defects are addressed with priority and depending on severity fixed for previous release(s) in a bug fix release.\n\nTier 1 platforms are currently:\n| Platform    | Owner(s)                                                                                                    |\n|-------------|-------------------------------------------------------------------------------------------------------------|\n| linux/amd64 | [OpenTelemetry Collector approvers](https://github.com/open-telemetry/opentelemetry-collector#contributing) |\n\n### Tier 2 – Secondary Support\n\nTier 2 platforms are _guaranteed to work with specified limitations_. Precompiled binaries are built and tested on the platform as part of the release cycle. Build and test infrastructure is provided by the platform maintainers. All tests are executed on the platform as far as they are applicable, and all prerequisites are fulfilled. Not executed tests and not tested collector add-ons (receivers, processors, exporters, etc.) are published on release of the collector distribution. Any build or test failure delays the release of the binaries for the respective platform but not the collector distribution for all other platforms. Defects are addressed but not with the priority as for Tier 1 and, if specific to the platform, require the support of the platform maintainers.\n\nTier 2 platforms are currently:\n| Platform      | Owner(s)                                           |\n|---------------|----------------------------------------------------|\n| darwin/arm64  | [@MovieStoreGuy](https://github.com/MovieStoreGuy) |\n| linux/arm64   | [@atoulme](https://github.com/atoulme)             |\n| windows/amd64 | [@pjanotti](https://github.com/pjanotti)           |\n\n### Tier 3 - Community Support\n\nTier 3 platforms are _guaranteed to build_. Precompiled binaries are made available as part of the release process and as result of a cross compile build on Linux amd64 but the binaries are not tested at all. Any build failure delays the release of the binaries for the respective platform but not the collector distribution for all other platforms. Defects are addressed based on community contributions. Core developers might provide guidance or code reviews, but direct fixes may be limited.\n\nTier 3 platforms are currently:\n| Platform      | Owner(s)                                                                                                                                                       |\n|---------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| aix/ppc64     | [@Dylan-M](https://github.com/Dylan-M) [@atoulme](https://github.com/atoulme)                                                                                  |\n| darwin/amd64  | [@h0cheung](https://github.com/h0cheung)                                                                                                                       |\n| js/wasm       | [@evan-bradley](https://github.com/evan-bradley), [@mx-psi](https://github.com/mx-psi)                                                                         |\n| linux/386     | [@andrzej-stencel](https://github.com/andrzej-stencel)                                                                                                         |\n| linux/arm     | [@Wal8800](https://github.com/Wal8800), [@atoulme](https://github.com/atoulme)                                                                                 |\n| linux/ppc64le | [@IBM-Currency-Helper](https://github.com/IBM-Currency-Helper), [@adilhusain-s](https://github.com/adilhusain-s), [@seth-priya](https://github.com/seth-priya) |\n| linux/riscv64 | [@shanduur](https://github.com/shanduur)                                                                                                                       |\n| linux/s390x   | [@bwalk-at-ibm](https://github.com/bwalk-at-ibm), [@rrschulze](https://github.com/rrschulze)                                                                   |\n| windows/386   | [@pjanotti](https://github.com/pjanotti)                                                                                                                       |\n| windows/arm64 | [@pjanotti](https://github.com/pjanotti)                                                                                                                       |\n"
  },
  {
    "path": "docs/release.md",
    "content": "# OpenTelemetry Collector Release Procedure\n\nCollector build and testing is currently fully automated. However there are still certain operations that need to be performed manually in order to make a release.\n\nWe release both core and contrib collectors with the same versions where the contrib release uses the core release as a dependency. We’ve divided this process into three sections. Each section is assigned to an approver or maintainer of the corresponding repository. The sections are:\n\n1. The [Core](#releasing-opentelemetry-collector) collector, including the collector builder CLI tool.\n2. The [Contrib](#releasing-opentelemetry-collector-contrib) collector repository, containing Collector components.\n3. The [artifacts](#producing-the-artifacts)\n\n**Important Note:** You’ll need to be able to sign git commits/tags in order to be able to release a collector version. Follow [this guide](https://docs.github.com/en/authentication/managing-commit-signature-verification/signing-commits) to set it up.\n\n## Release managers\n\nA release manager is the person responsible for a specific release. While the manager might request help from other folks, they are ultimately responsible for the success of a release.\n\nIn order to have more people comfortable with the release process, and in order to decrease the burden on a small number of volunteers, all core, contrib and releases approvers are release managers from time to time, listed under the [Release Schedule](#release-schedule) section. That table is updated at every release, with the current core release manager adding themselves to the bottom of the table, removing themselves from the top of the table.\n\nThe assigned release managers should coordinate with each other to ensure a smooth release process. The release managers may be the same person for different repositories, but it is not required.\n\nTo ensure the rest of the community is informed about the release and can properly help the release manager, the core release manager should open a thread on the #otel-collector-dev CNCF Slack channel and provide updates there.\nThe thread should be shared with all Collector leads (core, contrib and releases approvers and maintainers).\n\nBefore the release, make sure there are no open release blockers in [core](https://github.com/open-telemetry/opentelemetry-collector/labels/release%3Ablocker), [contrib](https://github.com/open-telemetry/opentelemetry-collector-contrib/labels/release%3Ablocker) and [releases](https://github.com/open-telemetry/opentelemetry-collector-releases/labels/release%3Ablocker) repos.\n\n## Releasing opentelemetry-collector (core release manager)\n\n1. Update Contrib to use the latest in development version of Core by running [Update contrib to the latest core source](https://github.com/open-telemetry/opentelemetry-collector-contrib/actions/workflows/update-otel.yaml). This is to ensure that the latest core does not break contrib in any way. If the job is failing for any reason, you can do it locally by running `make update-otel` in Contrib root directory and pushing a PR. If you are unable to run `make update-otel`, it is possible to skip this step and resolve conflicts with Contrib after Core is released, but this is generally inadvisable.\n   - While this PR is open, all merging in Core is automatically halted via the `Merge freeze / Check` CI check.\n   -  🛑 **Do not move forward until this PR is merged.**\n\n2. Determine the version number that will be assigned to the release. Usually, we increment the minor version number and set the patch number to 0. In this document, we are using `v0.85.0` as the version to be released, following `v0.84.0`.\n\n3. Manually run the action [Automation - Prepare Release](https://github.com/open-telemetry/opentelemetry-collector/actions/workflows/prepare-release.yml). This action will create an issue to track the progress of the release and a pull request to update the changelog and version numbers in the repo.\n   - When prompted, enter the version numbers determined in Step 2, but do not include a leading `v`.\n   - While this PR is open all merging in Core is automatically halted via the `Merge freeze / Check` CI check.\n   - If the PR needs updated in any way you can make the changes in a fork and PR those changes into the `prepare-release-prs/x` branch. You do not need to wait for the CI to pass in this prep-to-prep PR.\n   -  🛑 **Do not move forward until this PR is merged.** 🛑\n\n4. On your local machine, make sure you are on the `main` branch and that the PR from step 3 is incorporated **at the head of your branch** (this is required to ensure the proper commit is used for the release tags and branch creation below). Tag the module groups with the new release version by running:\n\n   ⚠️ If you set your remote using `https` you need to include `REMOTE=https://github.com/open-telemetry/opentelemetry-collector.git` in each command. ⚠️\n\n   - `make push-tags MODSET=beta` for the beta modules group,\n   - `make push-tags MODSET=stable` for the stable modules group.\n\n   **Note**: Pushing the **beta** tags will automatically trigger the [Automation - Release Branch](https://github.com/open-telemetry/opentelemetry-collector/actions/workflows/release-branch.yml) GitHub Action, which will create the release branch (e.g. `release/v0.127.x`) from the commit that prepared the release. Pushing stable tags, if required, will not trigger creation of an additional release branch.\n\n5. Wait for the \"Automation - Release Branch\" workflow to complete successfully. This workflow will automatically:\n   - Detect the version from the pushed beta tags\n   - Use the commit on which the tags were pushed as the \"prepare release\" commit\n   - Create a new release branch (e.g. `release/v0.127.x`) from that commit\n\n   If the workflow fails, you can check the [Actions tab](https://github.com/open-telemetry/opentelemetry-collector/actions) for details. The underlying script (./.github/workflows/scripts/release-branch.sh) can also be tested and run locally if needed by setting the GITHUB_REF environment variable (e.g., `GITHUB_REF=refs/tags/v0.85.0 ./.github/workflows/scripts/release-branch.sh`).\n\n6. Wait for the tag-triggered build workflows to pass successfully.\n\n7. A new `v0.85.0` source code release should be automatically created on Github by now. Its description should already contain the corresponding CHANGELOG.md and CHANGELOG-API.md contents.\n\n## Releasing opentelemetry-collector-contrib (contrib release manager)\n\nSee the [opentelemetry-collector-contrib release documentation](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/docs/release.md) for the release process in that repository.\n\n## Producing the artifacts ('releases' release manager)\n\nSee the [opentelemetry-collector-releases release documentation](https://github.com/open-telemetry/opentelemetry-collector-releases/blob/main/docs/release.md) for the release process in that repository.\n\n## Post-release steps (all release managers)\n\nAfter the release is complete, the release manager should do the following steps:\n\n1. Create an issue or update existing issues for each problem encountered throughout the release in\nthe appropriate repositories and label them with the `release:retro` label. The release manager\nshould share the list of issues that affected the release with the Collector leads.\n2. Update the [release schedule](#release-schedule) section of this document to remove the completed\nreleases and add new schedules to the bottom of the list. To update the release schedule, follow these rules:\n   1. If the core release manager is also eligible as a contrib and 'releases' release manager, assign them to all roles they can perform.\n   2. Otherwise, pick a contrib/'releases' approver/maintainer that is not a core approver/maintainer, rotating through the list of eligible people. The contrib approvers/maintainers are all members of the [@collector-contrib-approvers](https://github.com/orgs/open-telemetry/teams/collector-contrib-approvers) team, and the 'releases' approvers/maintainers are all members of the [@collector-releases-approvers](https://github.com/orgs/open-telemetry/teams/collector-releases-approvers) team.\n\n\n## Troubleshooting\n\n1. `unknown revision internal/coreinternal/v0.85.0` -- This is typically an indication that there's a dependency on a new module. You can fix it by adding a new `replaces` entry to the `go.mod` for the affected module.\n2. `unable to tag modules: unable to load repo config: branch config: invalid merge` when running `make push-tags` -- This is a [known issue](https://github.com/open-telemetry/opentelemetry-go-build-tools/issues/47) with our release tooling, caused by a bug in `go-git`.\n\n    It occurs if you have branches in your local repository whose entry in `.git/config` has a `merge` attribute not starting with `refs/heads`. This can typically happen when checking out PR branches using the Github CLI tool, for which the `merge` attribute starts with `refs/pull`.\n\n    A possible workaround is to:\n    - Comment out the problematic lines with `sed -E -i.bak 's/(merge = refs\\/pull)/#\\1/' .git/config`;\n    - Try `make push-tags` again;\n    - Restore the config with `mv .git/config.bak .git/config`.\n\n    If that doesn't work, you can clone a fresh copy of the repository and try again. Note that you may need to set up a `fork` remote pointing to your own fork for the release tooling to work properly.\n3. `could not run Go Mod Tidy: go mod tidy failed` when running `multimod` -- This is a [known issue](https://github.com/open-telemetry/opentelemetry-go-build-tools/issues/46) with our release tooling. The current workaround is to run `make gotidy` manually after the multimod tool fails and commit the result.\n4. `Incorrect version \"X\" of \"go.opentelemetry.io/collector/component\" is included in \"X\"` in CI after `make update-otel` -- It could be because the make target was run too soon after updating Core and the goproxy hasn't updated yet.  Try running `export GOPROXY=direct` and then `make update-otel`.\n5. `error: failed to push some refs to 'https://github.com/open-telemetry/opentelemetry-collector-contrib.git'` during `make push-tags` -- If you encounter this error the `make push-tags` target will terminate without pushing all the tags. Using the output of the `make push-tags` target, save all the un-pushed the tags in `tags.txt` and then use this make target to complete the push:\n\n   ```bash\n   .PHONY: temp-push-tags\n   temp-push-tags:\n       for tag in `cat tags.txt`; do \\\n           echo \"pushing tag $${tag}\"; \\\n           git push ${REMOTE} $${tag}; \\\n       done;\n   ```\n\n6. `unable to tag modules: git tag failed for v0.112.0: unable to create tag:\n   \"error: gpg failed to sign the data:`. Make sure you have GPG set up to sign\n   commits. You can run `gpg --gen-key` to generate a GPG key.\n\n7. When using a new GitHub Actions workflow in opentelemetry-collector-releases\n   for the first time during a release, a workflow may fail. If it is possible\n   to fix the workflow, a maintainer can update the release tag to the commit\n   with the fix and re-run the release. (Note: This cannot be done by\n   approvers.)\n\n   It is safe to re-run the workflows that already succeeded. Publishing\n   container images can be done multiple times, and publishing artifacts or\n   pushing OCB/Supervisor tags to GitHub will fail without any adverse effects.\n\n## Bugfix releases\n\n### Bugfix release criteria\n\nAll OpenTelemetry Collector repositories have very short 2 week release cycles. Because of this, we put a high bar when considering making a patch release, to avoid wasting engineering time unnecessarily.\n\nWhen considering making a bugfix release on the `v0.N.x` release cycle, the bug in question needs to fulfill the following criteria:\n\n1. The bug has no workaround or the workaround is significantly harder to put in place than updating the version. Examples of simple workarounds are:\n    - Reverting a feature gate.\n    - Changing the configuration to an easy to find value.\n2. The bug happens in common setups. To gauge this, maintainers can consider the following:\n    - If the bug is specific to a certain platform, and if that platform is in [Tier 1](../docs/platform-support.md#tiered-platform-support-model).\n    - The bug happens with the default configuration or with one that is known to be used in production.\n3. The bug is sufficiently severe. For example (non-exhaustive list):\n    - The bug makes the Collector crash reliably\n    - The bug makes the Collector fail to start under an accepted configuration\n    - The bug produces significant data loss\n    - The bug makes the Collector negatively affect its environment (e.g. significantly affects its host machine)\n    - The bug makes it difficult to troubleshoot or debug Collector setups\n\nWe aim to provide a release that fixes security-related issues in at most 30 days since they are publicly announced; with the current release schedule this means security issues will typically not warrant a bugfix release. An exception is critical vulnerabilities (CVSSv3 score >= 9.0), which will warrant a release within five business days.\n\nThe OpenTelemetry Collector maintainers will ultimately have the responsibility to assess if a given bug or security issue fulfills all the necessary criteria and may grant exceptions in a case-by-case basis.\nIf the maintainers are unable to reach consensus within one working day, we will lean towards releasing a bugfix version.\n\n### Bugfix release procedure\n\nThe release manager of a minor version is responsible for releasing any bugfix versions on this release series for their repository. The following documents the procedure to release a bugfix:\n\n1. Create a pull request against the `release/<release-series>` (e.g. `release/v0.90.x`) branch to apply the fix.\n2. Make sure you are on `release/<release-series>`. Prepare release commits with `prepare-release` make target, e.g. `make prepare-release PREVIOUS_VERSION=0.90.0 RELEASE_CANDIDATE=0.90.1 MODSET=beta`, and create a pull request against the `release/<release-series>` branch.\n3. Once those changes have been merged, create a pull request to the `main` branch from the `release/<release-series>` branch.\n4. If you see merge conflicts when creating the pull request, do the following:\n    1. Create a new branch from `origin:main`.\n    2. Merge the `release/<release-series>` branch into the new branch.\n    3. Resolve the conflicts.\n    4. Create another pull request to the `main` branch from the new branch to replace the pull request from the `release/<release-series>` branch.\n5. Disable the merge queue. An admin of the repo needs to be available for this.\n6. Enable the **Merge pull request** setting in the repository's **Settings** tab.\n7. Make sure you are on `release/<release-series>`. Push the new release version tags for a target module set by running `make push-tags MODSET=<beta|stable>`. Wait for the new tag build to pass successfully.\n8. **IMPORTANT**: The pull request to bring the changes from the release branch *MUST* be merged using the **Merge pull request** method, and *NOT* squashed using “**Squash and merge**”. This is important as it allows us to ensure the commit SHA from the release branch is also on the main branch. **Not following this step will cause much go dependency sadness.**\n9. If the pull request was created from the `release/<release-series>` branch, it will be auto-deleted. Restore the release branch via GitHub.\n10. Once the patch is released, disable the **Merge pull request** setting and re-enable the merge queue.\n\n## 1.0 release\n\nStable modules adhere to our [versioning document guarantees](../VERSIONING.md), so we need to be careful before releasing. Before adding a module to the stable module set and making a first 1.x release, please [open a new stabilization issue](https://github.com/open-telemetry/opentelemetry-collector/issues/new/choose) and follow the instructions in the issue template.\n\nOnce a module is ready to be released under the `1.x` version scheme, file a PR to move the module to the `stable` module set and remove it from the `beta` module set. Note that we do not make `v1.x.y-rc.z` style releases for new stable modules; we instead treat the last two beta minor releases as release candidates and the module moves directly from the `0.x` to the `1.x` release series.\n\n## Release schedule\n\n| Date       | Version  | Core Release manager  | Contrib release manager | 'Releases' release manager |\n|------------|----------|-----------------------|-------------------------|----------------------------|\n| 2026-03-16 | v0.148.0 | [@dmitryax][7]        | [@dmitryax][7]          | [@dmitryax][7]             |\n| 2026-03-30 | v0.149.0 | [@codeboten][8]       | [@codeboten][8]         | [@codeboten][8]            |\n| 2026-04-13 | v0.150.0 | [@dmathieu][12]       | [@andrzej-stencel][4]   | [@crobert-1][20]           |\n| 2026-04-27 | v0.151.0 | [@bogdandrutu][9]     | [@bogdandrutu][9]       | [@bogdandrutu][9]          |\n| 2026-05-11 | v0.152.0 | [@jade-guiton-dd][10] | [@ChrsMark][19]         | [@dehaansa][16]            |\n| 2026-05-25 | v0.153.0 | [@axw][18]            | [@braydonk][13]         | [@MovieStoreGuy][17]       |\n| 2025-06-08 | v0.154.0 | [@atoulme][5]         | [@atoulme][5]           | [@atoulme][5]              |\n| 2026-06-22 | v0.155.0 | [@jmacd][1]           | [@ArthurSens][11]       | [@TylerHelmuth][3]         |\n| 2026-07-06 | v0.156.0 | [@mx-psi][14]         | [@mx-psi][14]           | [@mx-psi][14]              |\n| 2026-07-20 | v0.157.0 | [@TylerHelmuth][3]    | [@TylerHelmuth][3]      | [@mowies][15]              |\n| 2026-08-03 | v0.158.0 | [@evan-bradley][2]    | [@evan-bradley][2]      | [@evan-bradley][2]         |\n| 2026-08-17 | v0.159.0 | [@songy23][6]         | [@songy23][6]           | [@songy23][6]              |\n\n[1]: https://github.com/jmacd\n[2]: https://github.com/evan-bradley\n[3]: https://github.com/TylerHelmuth\n[4]: https://github.com/andrzej-stencel\n[5]: https://github.com/atoulme\n[6]: https://github.com/songy23\n[7]: https://github.com/dmitryax\n[8]: https://github.com/codeboten\n[9]: https://github.com/bogdandrutu\n[10]: https://github.com/jade-guiton-dd\n[11]: https://github.com/ArthurSens\n[12]: https://github.com/dmathieu\n[13]: https://github.com/braydonk\n[14]: https://github.com/mx-psi\n[15]: https://github.com/mowies\n[16]: https://github.com/dehaansa\n[17]: https://github.com/MovieStoreGuy\n[18]: https://github.com/axw\n[19]: https://github.com/ChrsMark\n[20]: https://github.com/crobert-1\n"
  },
  {
    "path": "docs/rfcs/README.md",
    "content": "# Collector RFCs\n\nThis folder contains accepted design documents for the Collector. Proposals here imply changes only\non the OpenTelemetry Collector and not on other parts of OpenTelemetry; if you have a cross-cutting\nproposal, file an [OTEP][1] instead.\n\n# RFC Process\n\n## Scope\n\nThe Request For Comments (RFC) process is intended to be used for significant changes to the Collector. Major design\ndecisions, especially those that imply a change that is hard to reverse, should generally be\ndocumented as an RFC. Controversial changes should also be documented as an RFC, so that the\ncommunity can have a chance to provide feedback. The goal of this process is to ensure we have a\ncoherent vision before embarking on significant work.\n\nUltimately, if any opentelemetry-collector maintainer feels that a change requires an RFC, then a\nmerged RFC is a requirement for said change.\n\n## Contents\n\nWe are purposefully light on the structure of RFCs, with the focus being the decision process and\nnot the document itself. When in doubt, the [OTEP template][2] can be a good starting point.\nRegardless of the structure, the RFC should make clear what commitments are being made by the\nCollector SIG when merging it.\n\n## Announcement\n\nRFCs should be announced in a Collector SIG meeting and on the #otel-collector-dev Slack channel.\n\n## Approval process\n\nAn RFC is just like any other PR in this repository, with the exception of more stringent criteria\nfor merging it.\n\n### Stakeholders\n\nTo define merge criteria and voting, each RFC has a set of 'stakeholders'. All\nopentelemetry-collector approvers are considered stakeholders. Additional stakeholders (e.g.\nmaintainers of related SIGs or experts) may be explicitly noted in the RFC.\n\n### Merge rules\n\nWe use a [Lazy Consensus](https://www.apache.org/foundation/glossary.html#LazyConsensus) method with the following rules:\n\n1. *Quorum*: For an RFC to be mergeable, it needs to have at least **two approvals** from the\n   approvers set as well as approvals from any additional stakeholders.\n2. *Waiting period*: Maintainers need to announce their intent to merge the RFC with a GitHub\n   comment. They will need to add a `rfc:final-comment-period` label to the PR, comment on the PR\n   and note the final comment period in the #otel-collector-dev CNCF Slack channel, and wait for at\n   least **4 business days** after making the announcement to merge the RFC.\n3. *Objections*: Objections should be communicated as a 'request changes' review. All objections\n   must be addressed before merging an RFC. If addressing an objection does not appear feasible, any\n   maintainer may call for a vote to be made on the objection (see below). This will be signified by\n   adding a `rfc:vote-needed` label to the PR. The voting result is binding and a maintainer can\n   drop any 'request changes' reviews based on the vote results or consensus.\n4. *Modifications*: Non-trivial modifications to an RFC reset the waiting period. RFC authors must\n   re-request any approving, comment, or 'request changes' reviews if the RFC has been modified significantly.\n5. *All conversations are resolved*: All Github conversations on the PR must be marked as resolved\n   before merging. The RFC author may resolve conversations at their discretion, but they must\n   explain in the conversation thread why they believe it is appropriate to do so.\n\n### Voting\n\nIf there is no consensus on a particular issue, a vote may be called by any of the maintainers. The\nvote will be open to all stakeholders for at least **5 business days** or until at least one third\nof the stakeholders have voted, whichever comes last. The vote will be decided by simple majority,\nrestricting the set to approvers and then maintainers in case of a tie among stakeholders.\n\nVoting should be done on a dedicated issue via comments. The related discussion threads should be\nlinked in the issue. The voting result should be documented in the RFC itself.\n\n# Modifications to existing RFCs and to this document\n\nNon-trivial modifications to this document and to existing RFCs should be done through the RFC\nprocess itself and have the same merge criteria.\n\n[1]: https://github.com/open-telemetry/oteps\n[2]: https://github.com/open-telemetry/oteps/blob/main/0000-template.md\n"
  },
  {
    "path": "docs/rfcs/component-configuration-schema-roadmap.md",
    "content": "# Component Configuration Management Roadmap\n\n## Motivation\n\nThe OpenTelemetry Collector ecosystem lacks a unified approach to configuration management, leading to several problems:\n\n1. **Documentation Drift**: Go configuration structs and documentation exist independently and frequently diverge over time\n2. **Inconsistent Developer Experience**: No standardized patterns for defining component configurations\n3. **No config validation capabilities**: Lack of JSON schemas prevents autocompletion and validation in configuration editors\n\n## Current state\n\n- Go configuration structs in each component with validation implemented via custom code and defaults set in `setDefaultConfig` functions\n- Manual documentation that often becomes outdated\n- No standardized JSON schemas for configuration validation\n\n## Desired state\n\n**Goal**: Establish a single source of truth for component configuration that generates:\n1. **Go configuration structs** with proper mapstructure tags, validation, and default values. \n2. **JSON schemas** for configuration validation and editor autocompletion\n3. **Documentation** that stays automatically synchronized with implementation\n\n## Previous and current approaches\n\n### Past attempts\n\n- [Previously available contrib configschema tool](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/v0.102.0/cmd/configschema): Retired due to incompleteness, complexity and maintenance burden. It required dynamic analysis of Go code and pulling all dependencies.\n\n- [PR #27003](https://github.com/open-telemetry/opentelemetry-collector-contrib/pull/27003): Failed due to trying to cover all corner-cases in the design phase instead of quickly iterating from a simpler approach.\n\n- [PR #10694](https://github.com/open-telemetry/opentelemetry-collector/pull/10694): An attempt to generate config structs from the schema defined in metadata.yaml using github.com/atombender/go-jsonschema. It faced some limitations of the library. However, it was abandoned mostly due to a lack of involvement from the reviewers.\n\n### Current initiatives\n\n- [opentelemetry-collector-contrib/cmd/schemagen/](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/cmd/schemagen): Generates JSON schemas from Go structs with limited support for validation and default values. It uses AST parsing with module-aware loading of dependencies to handle shared libraries.\n\n- [PR #14288](https://github.com/open-telemetry/opentelemetry-collector/pull/14288): Also uses AST parsing to generate JSON schemas from Go structs for the component configurations without using shared config support. Written as part of mdatagen tool.\n\nParsing Go code to generate schemas is inherently limited. Community consensus recommends reversing the process: generate Go code from schemas instead. There is already widely established practice in other ecosystems to generate go code and documentation for other parts of the OTel Collector.\n\n## Suggested approach\n\n### Overview\n\nThis RFC proposes an approach that transitions from the current Go-struct-first model to a schema-first configuration generation system:\n\n1. **Bootstrap Phase**: Use existing `schemagen` tool to generate initial schema specifications\n2. **Tool Development Phase**: Create new tooling that generates Go structs, JSON schemas, and documentation from YAML schema specifications \n3. **Migration Phase**: Migrate all components to the new schema-first approach\n\nUse of the `schemagen` tool is dictated by the modularity of the Collector components. It allows generating schemas for shared libraries (e.g., scraperhelper) that can be referenced by individual components.\n\n### Reasoning behind this approach\n\n- **Explicit validation**: Schema specifications can explicitly capture validation rules and default config values that cannot be extracted from Go code\n- **Rich documentation**: Schemas can include descriptions, examples, and constraints that enhance generated documentation\n- **Simplified tooling**: Template-based code generation is more predictable than AST parsing\n\n**Why YAML schema format for the source of truth?**\n- **Human-readable**: Easier for component developers to author and maintain than JSON\n- **Integration with existing infrastructure**: Natural extension of `metadata.yaml` approach used by `mdatagen` given that it already uses YAML to generate metrics builder configs\n- **Extensibility**: YAML allows for custom fields to capture domain-specific configuration and provide escape-hatches to generate config fields that still require custom implementation, validation or default value setters.\n\n### Example schema format\n\n```yaml\nconfig:\n  allOf:\n    - $ref: \"go.opentelemetry.io/collector/scraper/scraperhelper#/$defs/ControllerConfig\"\n    - $ref: \"#/$defs/MetricsBuilderConfig\"\n  properties:\n    targets:\n      type: array\n      items:\n        type: object\n        properties:\n          host:\n            type: string\n            description: \"Target hostname or IP address\"\n          ping_count:\n            type: integer\n            description: \"Number of pings to send\"\n            default: 3\n          ping_interval:\n            type: string\n            format: duration\n            x-customType: \"time.Duration\"\n            description: \"Interval between pings\"\n            default: \"1s\"\n        required: [\"host\"]\n```\n\n`#/$defs/MetricsBuilderConfig` would be automatically generated by mdatagen with the same process used to generate the go structs and documentation today.\n\n`go.opentelemetry.io/collector/scraper/scraperhelper#/$defs/ControllerConfig` would be generated by the new tool from the schema definition in the scraperhelper component.\n\n#### Extensibility\n\nThe YAML schema specification can be extended with custom fields (e.g., `x-customType`) to capture domain-specific types and validation rules that are not natively supported in JSON schema. Additionally, we may introduce custom fields that generate fields that will produce references to structs or validation functions that require more complex logic and manual implementation.\n\n### Roadmap\n\n#### Phase 1: Bootstrap initial schemas\n\n**Objective**: Use `schemagen` tool to generate initial schema specifications for all components\n\n**Success Criteria:**\n- YAML schemas generated for all components in core and contrib repositories \n- Setup CI check to ensure schemas remain up-to-date with Go structs\n\n#### Phase 2: Implement new generation tool\n\n**Objective**: Implement a new tool that takes YAML schema from the user and generates Go structs, combined JSON schema, and documentation per component.\n\n**Success Criteria:**\n- New tool generates Go structs that are API-compatible with existing implementations with the following features:\n  - Parses YAML schema specifications\n  - Generates Go configuration structs with proper validation\n  - Produces JSON schemas for config validation\n  - Creates synchronized documentation\n- Generated JSON schemas pass validation tests with real collector configurations\n- Generated documentation accurately reflects all configuration options\n- Pilot components successfully replace hand-written implementations\n\nIf existing config structs don't follow the established naming patterns produced by the generated code, the implementation may allow breaking the Go API compatibility in favor of consistent Go API naming standards and long-term maintainability. However, the configuration file format MUST remain compatible for end users.\n\n#### Phase 3: Migrate all components\n\n**Objective**: Migrate all components to the new tool introduced in Phase 2\n\n**Success Criteria:**\n- All core and contrib components migrated to schema-first approach\n- All new components use schema-first tooling by default\n"
  },
  {
    "path": "docs/rfcs/component-status-reporting.md",
    "content": "# Component Status Reporting\n\n## Overview\n\nSince the OpenTelemetry Collector is made up of pipelines with components, it needs a way for the components within those pipelines to emit information about their health. This information allows the collector service, or other interested software or people, to make decisions about how to proceed when something goes wrong. This document describes:\n\n1. The historical state of how components reported health\n2. The current state of how components report health\n3. The goals component health reporting should achieve\n4. Existing deviations from those goals\n5. Desired behavior for 1.0\n\nFor context throughout this document, component defines a `component.Host` interface, which components may use to interact with the struct that is managing all the collector pipelines and the components. In this repository, our implementation of `component.Host` can be found in `service/internal/graph.Host`.\n\n## Out Of Scope\n\nHow to get from the current to desired behavior is also considered out of scope and will be discussed on individual PRs. It will likely involve one or multiple feature gates, warnings and transition periods.\n\n## The Collector’s Historical method of reporting component health\nUntil recently, the Collector relied on four ways to report health.\n\n1. The `error` returned by the Component’s Start method. During startup, if any component decided to return an error, the Collector would stop gracefully.\n2. The `component.Host.ReportFatalError` method.  This method let components tell the `component.Host` that something bad happened and the collector needed to shut down.  While this method could be used anywhere in the component, it was primarily used with a Component’s Start method to report errors in async work, such as starting a server.\n    ```golang\n    if errHTTP := fmr.server.Serve(listener); errHTTP != nil && !errors.Is(errHTTP, http.ErrServerClosed) {\n       host.ReportFatalError(errHTTP)\n    }\n    ```\n3. The error returned by `Shutdown`. This error was indicative that the collector did not cleanly shut down, but did not prevent the shutdown process from moving forward.\n\n4. Panicking. During runtime, if the collector experienced an unhandled error, it crashes.\n\nThese are all the way the components in a collector could report that they were unhealthy.\n\nThere are several major gaps in the Collector’s historic reporting of component health. First, many components return recoverable errors from Start, causing the collector to shutdown, while it could recover if the collector was allowed to run. Second, when a component experienced a transient error, such as an endpoint suddenly not working, the component would simply log the error and return it up the pipeline. There was no mechanism for the component to tell the `component.Host` or anything else that something was going wrong. Last, when a component experienced an issue it would never be able to recover from, such as receiving a 404 response from an endpoint, the component would log the error and return it up the pipeline.  This situation was handled in the same way as the transient error, which means the component could not tell the `component.Host` or anything else that something was wrong, but worse is that the issue would never get better.\n\n## Current State of Component Health Reporting\n\nSee [Component Status Reporting](../component-status.md)\n\n## The Goals the Component Health Reporting Should Achieve\n\nThe following are the goals, as of June 2024 and with Collector 1.0 looming, for a component health reporting system.\n\n1. A `component.Host` implementation, such as `service/internal/graph.Host`, may report statuses Starting, Ok, Stopping and PermanentError on behalf of components.\n    - Additional status may be reported in the future\n2. Components may opt-in to reporting health status at runtime. Components must not be required to report health statuses themselves.\n    - The consumers of the health reporting system must be able to identify which components are and are not opting to report their own statuses.\n3. Component health reporting must be opt-in for collector users.  While the underlying components are always allowed to report their health via the system, the `component.Host` implementation, such as `service/internal/graph.Host`, or any other listener may only take action when the user has configured the collector accordingly.\n   - As one example of compliance, the current health reporting system is dependent on the user configuring an extension that can watch for status updates.\n4. Component health must be representable as a finite state machine with clear transitions between states.\n5. Component health reporting must only be a mechanism for reporting health - it should have no mechanisms for taking actions on the health it reports. How consumers of the health reporting system respond to component updates is not a concern of the health reporting system.\n\n## Existing deviations from those goals\n\n### Fatal Error Reporting\n\nBefore the current implementation of component status reporting, a component could stop the collector by using `component.Host.ReportFatalError`. Now, a component MUST use component status reporting and emit a `FatalError`. This fact is in conflict with Goal 1, which states component health reporting must be opt-in for components.\n\nA couple solutions:\n1. Accept this reality as an exception to Goal 2.\n2. Add back `component.Host.ReportFatalError`.\n3. Remove the ability for components to stop the collector be removing `FatalError`.\n\n### No way to identify components that are not reporting status\nGoal 2 states that consumers of component status reporting must be able to identify components in use that have not opted in to component status reporting. Our current implementation does not have this feature.\n\n### Should component health reporting be an opt-in for `component.Host` implementations?\n\nThe current implementation of component status reporting does not add anything to `component.Host` to force a `component.Host` implementation, such as `service/internal/graph.Host`, to be compatible with component status reporting.  Instead, it adds `ReportStatus func(*StatusEvent)` to `component.TelemetrySettings` and things that instantiate components, such as `service/internal/graph.Host`, should, but are not required, to pass in a value for `ReportStatus`.\n\nAs a result, `component.Host` implementation is not required to engage with the component status reporting system.  This could lead to situations where a user adds a status watcher extension that can do nothing because the `component.Host` is not reporting component status updates.\n\nIs this acceptable? Should we:\n1. Require the `component.Host` implementations be compatible with the component status reporting framework?\n2. Add some sort of configuration/build flag then enforces the `component.Host` implementation be compatible (or not) with component status reporting?\n3. Accept this edge case.\n\n### Component TelemetrySettings Requirements\n\nThe current implementation of component status reporting added a new field to `component.TelemetrySettings`, `ReportStatus`.  This field is technically optional, but would be marked as stable with component 1.0. Are we ok with 1 of the following?\n\n1. Including a component status reporting feature, `component.TelemetrySettings.ReportStatus`, in the 1.0 version of `component.TelemetrySettings`?\n2. Marking `component.TelemetrySettings.ReportStatus` as experimental via godoc comments in the 1.0 version of `component.TelemetrySettings`?\n\nOr should we refactor `component` somehow to remove `ReportStatus` from `component.TelemetrySettings`?\n\n## Desired Behavior for 1.0\n\nFor each listed deviation, the solution for unblocking component 1.0 is:\n\n- `Fatal Error Reporting` :white_check_mark:: The `component` module provides no mechanism for a component to stop a collector after it has started. It is expected that an error returned from `Start` will terminate a starting Collector, but it is ultimately up to the caller of `Start` how to handle the returned error. A `component.Host` implementation may choose to provide a mechanism to stop a running collector via a different Interface, but doing so is not required.\n  - As part of this stance, we agree that the `component.Component.Start` method will continue returning an error.  \n- `No way to identify components that are not reporting status` :white_check_mark:: This can be implemented as a feature addition to component status reporting without blocking `component` 1.0\n- `Should component health reporting be an opt-in for component.Host implementations?` :white_check_mark:: Yes. A `component.Host` implementation is not required to provide a component status reporting feature. They may do so via an additional interface, such as `componentstatus.Reporter`.\n- `Component TelemetrySettings Requirements` :white_check_mark:: `component.TelemetrySettings.ReportStatus` has been removed. Instead, component status reporting is expected to be provided via an additional interface that `component.Host` implements. Components can check if the `component.Host` implements the desired interface, such as `componentstatus.Reporter` to access component status reporting features.\n\n\n## Reference\n- Remove FatalError? Looking for opinions either way: https://github.com/open-telemetry/opentelemetry-collector/issues/9823\n- In order to prioritize lifecycle events over runtime events for status reporting, allow a component to transition from PermanentError -> Stopping: https://github.com/open-telemetry/opentelemetry-collector/issues/10058\n- Runtime status reporting for components in core: https://github.com/open-telemetry/opentelemetry-collector/issues/9957\n- Should Start return an error: https://github.com/open-telemetry/opentelemetry-collector/issues/9324\n- Should Shutdown return an error: https://github.com/open-telemetry/opentelemetry-collector/issues/9325\n- Status reporting doc incoming; preview here: https://github.com/mwear/opentelemetry-collector/blob/cc870fd2a7160da298acdda447511ea9a83455e0/docs/component-status.md\n- Issues\n  - Closed: https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/8349\n  - Open: https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/8816\n- Status Reporting PRs\n  - Closed\n    - https://github.com/open-telemetry/opentelemetry-collector/pull/5304\n    - https://github.com/open-telemetry/opentelemetry-collector/pull/6550\n    - https://github.com/open-telemetry/opentelemetry-collector/pull/6560\n  - Merged\n    - https://github.com/open-telemetry/opentelemetry-collector/pull/8169\n\n\n\n\n"
  },
  {
    "path": "docs/rfcs/component-universal-telemetry.md",
    "content": "# Pipeline Component Telemetry\n\n## Motivation and Scope\n\nThe collector should be observable and this must naturally include observability of its pipeline components. Pipeline components\nare those components of the collector which directly interact with data, specifically receivers, processors, exporters, and connectors.\n\nIt is understood that each _type_ (`filelog`, `otlp`, etc) of component may emit telemetry describing its internal workings,\nand that these internally derived signals may vary greatly based on the concerns and maturity of each component. Naturally\nthough, there is much we can do to normalize the telemetry emitted from and about pipeline components.\n\nTwo major challenges in pursuit of broadly normalized telemetry are (1) consistent attributes, and (2) automatic capture.\n\nThis RFC represents an evolving consensus about the desired end state of component telemetry. It does _not_ claim\nto describe the final state of all component telemetry, but rather seeks to document some specific aspects. It proposes a set of\nattributes which are both necessary and sufficient to identify components and their instances. It also articulates one specific\nmechanism by which some telemetry can be automatically captured. Finally, it describes some specific metrics and logs which should\nbe automatically captured for each kind of pipeline component.\n\n## Goals\n\n1. Define attributes that are (A) specific enough to describe individual component [_instances_](https://github.com/open-telemetry/opentelemetry-collector/issues/10534)\n   and (B) consistent enough for correlation across signals.\n2. Articulate a mechanism which enables us to _automatically_ capture telemetry from _all pipeline components_.\n3. Define specific metrics for each kind of pipeline component.\n4. Define specific logs for all kinds of pipeline component.\n\n## Attributes\n\nTraces, logs, and metrics should carry the following instrumentation scope attributes:\n\n### Receivers\n\n- `otelcol.component.kind`: `receiver`\n- `otelcol.component.id`: The component ID\n- `otelcol.signal`: `logs`, `metrics`, `traces`, `profiles`\n\n### Processors\n\n- `otelcol.component.kind`: `processor`\n- `otelcol.component.id`: The component ID\n- `otelcol.pipeline.id`: The pipeline ID\n- `otelcol.signal`: `logs`, `metrics`, `traces`, `profiles`\n\n### Exporters\n\n- `otelcol.component.kind`: `exporter`\n- `otelcol.component.id`: The component ID\n- `otelcol.signal`: `logs`, `metrics`, `traces`, `profiles`\n\n### Connectors\n\n- `otelcol.component.kind`: `connector`\n- `otelcol.component.id`: The component ID\n- `otelcol.signal`: `logs`, `metrics` `traces`\n- `otelcol.signal.output`: `logs`, `metrics`, `traces`, `profiles`\n\nNote: The `otelcol.signal`, `otelcol.signal.output`, or `otelcol.pipeline.id` attributes may be omitted if the corresponding component instances\nare unified by the component implementation. For example, the `otlp` receiver is a singleton, so its telemetry is not specific to a signal.\nSimilarly, the `memory_limiter` processor is a singleton, so its telemetry is not specific to a pipeline.\n\nThese instrumentation scope attributes are automatically injected into the telemetry associated with a component, by wrapping the Logger, TracerProvider, and MeterProvider provided to it.\n\n## Auto-Instrumentation Mechanism\n\nThe mechanism of telemetry capture should be _external_ to components. Specifically, we should observe telemetry at each point where a\ncomponent passes data to another component, and, at each point where a component consumes data from another component. In terms of the\ncomponent graph, every _edge_ in the graph will have two layers of instrumentation - one for the producing component and one for the\nconsuming component. Importantly, each layer generates telemetry ascribed to a single component instance, so by having two layers per\nedge we can describe both sides of each handoff independently.\n\nTelemetry captured by this mechanism should be associated with an instrumentation scope with a name corresponding to the package which implements\nthe mechanism. Currently, that package is `go.opentelemetry.io/collector/service`, but this may change in the future. Notably, this telemetry is not\nascribed to individual component packages, both because the instrumentation scope is intended to describe the origin of the telemetry,\nand because no mechanism is presently identified which would allow us to determine the characteristics of a component-specific scope.\n\n### Instrumentation Scope\n\nAll telemetry described in this RFC should include a scope name which corresponds to the package which implements the telemetry. If the\npackage is internal, then the scope name should be that of the module which contains the package. For example,\n`go.opentelemetry.io/service` should be used instead of `go.opentelemetry.io/service/internal/graph`.\n\n### Auto-Instrumented Metrics\n\nThere are two straightforward measurements that can be made on any pdata:\n\n1. A count of \"items\" (spans, data points, or log records). These are low cost but broadly useful, so they should be enabled by default.\n2. A measure of size, based on [ProtoMarshaler.Sizer()](https://github.com/open-telemetry/opentelemetry-collector/blob/9907ba50df0d5853c34d2962cf21da42e15a560d/pdata/ptrace/pb.go#l11).\n  These may be high cost to compute, so by default they should be disabled (and not calculated). This default setting may change in the future if it is demonstrated that the cost is generally acceptable.\n\nThe location of these measurements can be described in terms of whether the data is \"consumed\" or \"produced\", from the perspective of the\ncomponent to which the telemetry is attributed. Metrics which contain the term \"produced\" describe data which is emitted from the component,\nwhile metrics which contain the term \"consumed\" describe data which is received by the component.\n\nFor both metrics, an `otelcol.component.outcome` attribute with possible values `success`, `failure`, and `refused` should be automatically recorded,\nbased on whether the corresponding function call returned successfully, returned an error originating from the associated component, or propagated an error from a component further downstream.\n\nSpecifically, a call to `ConsumeX` is recorded with:\n- `otelcol.component.outcome = success` if the call returns `nil`;\n- `otelcol.component.outcome = failure` if the call returns a regular error;\n- `otelcol.component.outcome = refused` if the call returns an error tagged as coming from downstream.\n\nAfter inspecting the error, the instrumentation layer should tag it as coming from downstream before returning it to the caller. Since there are two instrumentation layers between each pair of successive components (one recording produced data and one recording consumed data), this means that a call recorded with `outcome = failure` by the \"consumer\" layer will be recorded with `outcome = refused` by the \"producer\" layer, reflecting the fact that only the \"consumer\" component failed. In all other cases, the `outcome` recorded by both layers should be identical.\n\nErrors should be \"tagged as coming from downstream\" the same way permanent errors are currently handled: they can be wrapped in a `type downstreamError struct { err error }` wrapper error type, then checked with `errors.As`. Note that care may need to be taken when dealing with the `multiError`s returned by the `fanoutconsumer`. If PR #11085 introducing a single generic `Error` type is merged, an additional `downstream bool` field can be added to it to serve the same purpose instead.\n\n```yaml\n    otelcol.receiver.produced.items:\n      enabled: true\n      description: Number of items emitted from the receiver.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n    otelcol.processor.consumed.items:\n      enabled: true\n      description: Number of items passed to the processor.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n    otelcol.processor.produced.items:\n      enabled: true\n      description: Number of items emitted from the processor.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n    otelcol.connector.consumed.items:\n      enabled: true\n      description: Number of items passed to the connector.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n    otelcol.connector.produced.items:\n      enabled: true\n      description: Number of items emitted from the connector.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n    otelcol.exporter.consumed.items:\n      enabled: true\n      description: Number of items passed to the exporter.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    otelcol.receiver.produced.size:\n      enabled: false\n      description: Size of items emitted from the receiver.\n      unit: \"By\"\n      sum:\n        value_type: int\n        monotonic: true\n    otelcol.processor.consumed.size:\n      enabled: false\n      description: Size of items passed to the processor.\n      unit: \"By\"\n      sum:\n        value_type: int\n        monotonic: true\n    otelcol.processor.produced.size:\n      enabled: false\n      description: Size of items emitted from the processor.\n      unit: \"By\"\n      sum:\n        value_type: int\n        monotonic: true\n    otelcol.connector.consumed.size:\n      enabled: false\n      description: Size of items passed to the connector.\n      unit: \"By\"\n      sum:\n        value_type: int\n        monotonic: true\n    otelcol.connector.produced.size:\n      enabled: false\n      description: Size of items emitted from the connector.\n      unit: \"By\"\n      sum:\n        value_type: int\n        monotonic: true\n    otelcol.exporter.consumed.size:\n      enabled: false\n      description: Size of items passed to the exporter.\n      unit: \"By\"\n      sum:\n        value_type: int\n        monotonic: true\n```\n\n#### Additional Attribute for Connectors\n\nConnectors can route telemetry to specific pipelines. Therefore, `otelcol.connector.produced.*` metrics should carry an\nadditional data point attribute, `otelcol.pipeline.id`, to describe the pipeline ID to which the data is sent.\n\n### Auto-Instrumented Logs\n\nMetrics provide most of the observability we need but there are some gaps which logs can fill. Although metrics would describe the overall\nitem counts, it is helpful in some cases to record more granular events. For example, if a produced batch of 10,000 spans results in an error, but\n100 batches of 100 spans succeed, this may be a matter of batch size that can be detected by analyzing logs, while the corresponding metric\nreports only that a 50% success rate is observed.\n\nFor security and performance reasons, it would not be appropriate to log the contents of telemetry.\n\nIt's very easy for logs to become too noisy. Even if errors are occurring frequently in the data pipeline, only the errors that are not\nhandled automatically will be of interest to most users.\n\nWith the above considerations, this proposal includes only that we add a DEBUG log for each error, with the attributes from the corresponding \nmetrics as well as the error message and item count. This should be sufficient for detailed troubleshooting but does not impact users otherwise.\n\nIn the future, it may be helpful to define triggers for reporting repeated failures at a higher severity level. e.g. N number of failures in\na row, or a moving average success %. For now, the criteria and necessary configurability is unclear so this is mentioned only as an example\nof future possibilities.\n\n### Auto-Instrumented Spans\n\nIt is not clear that any spans can be captured automatically with the proposed mechanism. We have the ability to insert instrumentation both\nbefore and after processors and connectors. However, we generally cannot assume a 1:1 relationship between consumed and produced data.\n\n## Additional Context\n\nThis proposal pulls from a number of issues and PRs:\n\n- [Demonstrate graph-based metrics](https://github.com/open-telemetry/opentelemetry-collector/pull/11311)\n- [Attributes for component instancing](https://github.com/open-telemetry/opentelemetry-collector/issues/11179)\n- [Simple processor metrics](https://github.com/open-telemetry/opentelemetry-collector/issues/10708)\n- [Component instancing is complicated](https://github.com/open-telemetry/opentelemetry-collector/issues/10534)\n"
  },
  {
    "path": "docs/rfcs/configuration-merging-strategy.md",
    "content": "# Configuration merging\n\n## Background\n\nAs part of issue [#8754](https://github.com/open-telemetry/opentelemetry-collector/issues/8754), a new feature gate has been introduced to support merging component lists instead of replacing them ([first PR](https://github.com/open-telemetry/opentelemetry-collector/pull/12097)). This enhancement enables configurations from multiple sources to be combined, preserving all defined components in the final configuration.\n\nMore information about this feature can be found in the [confmap README](https://github.com/open-telemetry/opentelemetry-collector/blob/d4539dd6b4e554e15066226fa975b156af7b1510/confmap/README.md#experimental-append-merging-strategy-for-lists).\n\nThe main motivation for this change was to allow users to define configuration fragments in different sources, and have them merged in such a way that all specified components are included under `service::pipeline` in the final configuration.\n\nPreviously, we relied on Koanf’s default merging strategy, which overrides static values and slices (such as strings, numbers, and lists). This behavior often resulted in configurations being unintentionally overwritten when merged from multiple sources.\n\nThis issue has been highlighted in several discussions and feature requests:\n- https://github.com/open-telemetry/opentelemetry-collector/issues/8394\n- https://github.com/open-telemetry/opentelemetry-collector/issues/8754\n- https://github.com/open-telemetry/opentelemetry-collector/issues/10370\n\n## Motivation and Scope\n\nWe’ve already implemented a feature gate and foundational logic that supports merging lists across configuration files. Currently, this logic is hardcoded to merge lists only for specific keys: receivers, exporters, and extensions. The relevant implementation can be found [here](https://github.com/open-telemetry/opentelemetry-collector/blob/main/confmap/internal/merge.go).\n\nThe current implementation lacks flexibility. Ideally, users should be able to specify which configuration paths should be merged, rather than relying on hardcoded defaults. \nThis RFC proposes extending the existing functionality by introducing a user-configurable mechanism to define merge behavior.\n\nThis RFC builds on top of feedback gathered from the [original PR](https://github.com/open-telemetry/opentelemetry-collector/pull/12097).\nMore specifically, this RFC aims to:\n1. Add an option to specify which configuration paths should be merged.\n2. Introduce support for prepend and append operations when merging list values:\n    - This is good to have for lists that rely on certain ordering, such as:\n        - `processors`\n        - `transformprocessor` statements\n\n## Proposed approaches:\n\n### Approach 1 (Recommended): Use yaml tags\n\nThe first approach relies on the concept of [yaml tags](https://tutorialreference.com/yaml/yaml-tags). We can specify a custom tag in our configuration files to indicate the lists we want to merge.\n\nConsider following two configurations:\n\n```yaml\n#main.yaml\nreceivers:\n    ...\nexporters:\n    ...\nextensions:\n    extension1:\n\nservice:\n  extensions: [extension1]\n  pipelines:\n    logs:\n      receivers: [...]\n      exporters: [...]\n```\n\n```yaml\n#extra.yaml\nextensions:\n    extension2:\n\nservice:\n  extensions: !mode=append [extension2]\n```\n\nAfter running the collector with above configurations, the `service::extensions` path will get merged and final configuration will look like:\n\n```yaml\n#final.yaml\nreceivers:\n    ...\nexporters:\n    ...\nextensions:\n    extension1:\n    extension2:\n\nservice:\n  extensions: [extension1, extension2]\n  pipelines:\n    logs:\n      receivers: [...]\n      exporters: [...]\n```\n\nThis approach completely relies on the configuration files and doesn't introduce any command line option.\nInternally, we will loop through the yaml tree and fetch the paths we want to merged based on user-defined tags, then merge the lists found at those paths.\n\nOur \"custom\" yaml tag will be in the format of URI query parameters. For starters, we can support following options:\n1. `mode`:\n    - This setting will control the ordering of merged list.\n    - The value will be either of `append` or `prepend`.\n    - Default: `append`\n2. `duplicates`:\n    - This setting controls the duplication of elements in the final list. \n    - If the user wants to allow duplicates, they can simply turn this flag on.\n    - Default: `false`\n3. `recursive`:\n    - This setting controls the merging of child elements of the given yaml path. \n    - This is useful if user wants to merge all the lists under a give sub-tree. \n        - For eg. merging all the lists under the `service` section.\n\n#### Examples of first approach\n\n1. _Merge the `service::extensions` list_:\n\n```yaml\n#main.yaml\nreceivers:\n    ...\nexporters:\n    ...\nextensions:\n    extension1:\n\nservice:\n  extensions: [extension1]\n  pipelines:\n    logs:\n      receivers: [...]\n      exporters: [...]\n      \n---\n\n#extra.yaml\nextensions:\n    extension2:\n\nservice:\n  extensions: !mode=append [extension2]\n```\n\n```yaml\n#final.yaml\nreceivers:\n    ...\nexporters:\n    ...\nextensions:\n    extension1:\n    extension2:\n\nservice:\n  extensions: [extension1, extension2]\n  pipelines:\n    logs:\n      receivers: [...]\n      exporters: [...]\n```\n\n2. _Merge all the lists under the `service::*` section_:\n\n\n```yaml\n#main.yaml\nreceivers:\n    ...\nexporters:\n    ...\nextensions:\n    extension1:\n\nservice:\n  extensions: [extension1]\n  pipelines:\n    logs:\n      receivers: [...]\n      exporters: [...]\n      \n---\n\n#extra.yaml\nextensions:\n    extension2:\nreceiver:\n    receiver2:\n\nservice: !mode=append&recursive=true\n  extensions: [extension2]\n  pipelines:\n    logs:\n        receivers: [receiver2]\n```\n\n```yaml\n#final.yaml\nreceivers:\n    ...\n    receiver2:\nexporters:\n    ...\nextensions:\n    extension1:\n    extension2:\n\nservice:\n  extensions: [extension1, extension2]\n  pipelines:\n    logs:\n      receivers: [..., receiver2]\n      exporters: [...]\n```\n\n### Approach 2: URI params\n\nThe proposed approach will rely on concept of URI query parameters([_RFC 3986_](https://datatracker.ietf.org/doc/html/rfc3986#page-23)). Our configuration URIs already adhere to this syntax and we can extend it to support query params instead adding new CLI flags. \n\nFor now, the new merging strategy is only enabled under `confmap.enableMergeAppendOption` gate. If user specifies the options and tries to run the collector without gate, we will merge as per default behaviour.\n\nWe will support new parameters to config URIs as follows:\n1. `merge_paths`: A comma-separated list of glob patterns which will be used while config merging\n    - This setting will control the paths user wants to merge from the given config.\n    - Example: \n        - `otelcol --config main.yaml --config extra.yaml?merge_paths=service::extensions,service::**::receivers`\n            - In this example, we will merge the list of extensions and receivers from pipeline, excluding lists in the rest of the config.\n        - `otelcol --config main.yaml --config ext.yaml?merge_paths=service::extensions --config rec.yaml?merge_paths=service::**::receivers`\n            - In this example, we will merge all list of extensions from `ext.yml` and list of receivers from `rec.yaml`, excluding lists in the rest of the config.\n2. `merge_mode`: One of `prepend` or `append`.\n    - This setting will control the ordering of merged list.\n\n#### Examples of second approach\n\nHere are some examples:\n\n1. _Append to default mergeable components_:\n```bash\notelcol --config=main.yaml --config=extra_components.yaml?merge_mode=append --feature-gates=confmap.enableMergeAppendOption\n```\n\n- After running above command, the final configuration will include:\n    - Merged component(s) (`receivers`, `exporters` and `extensions`) from `extra_components.yaml`\n\n2. _Specify exact paths for merging_:\n```bash\notelcol \\\n  --config=main.yaml \\\n  --config=extra_extension.yaml?merge_mode=append&merge_paths=service::extensions \\\n  --config=extra_receiver.yaml?merge_mode=append&merge_paths=service::**::receivers \\\n  --feature-gates=confmap.enableMergeAppendOption\n```\n\n- After running above command, the final configuration will include:\n    - Merged extension(s) from `extra_extension.yaml`\n    - Merged receiver(s) from `extra_receiver.yaml`\n\n\n3. _Prepend processors_:\n```bash\notelcol --config=main.yaml --config=extra_processor.yaml?merge_mode=prepend&merge_paths=service::**::processors --feature-gates=confmap.enableMergeAppendOption\n```\n\n- After running above command, the final configuration will include:\n    - Merged processor(s) from `extra_processor.yaml`, but prepend the existing list.\n\n4. _Exclude a config file from lists merging process_:\n```bash\notelcol --config=main.yaml --config=extra_components.yaml?merge_mode=append --config override_components.yaml --feature-gates=confmap.enableMergeAppendOption\n```\n\n- In the above command, we have no specified any options for `override_components.yaml`. Hence, it will override all the conflicting lists from previous configuration, which is the default behaviour.\n\n## Open questions\n\n- What to do if an invalid option is provided for `merge_mode` or `merge_paths`?\n    - I can think of two possibilities:\n        1. Error out.\n        2. Log an error and merge the default way\n- What to do if an invalid query param is provided in config URI?\n    - In this case, I strongly feel that we should error out. \n\n## Extensibility \n\nThis URI-based approach is highly extensible. In the future, it can enable advanced operations such as map overriding. Currently, it's impossible to do so."
  },
  {
    "path": "docs/rfcs/configuring-confmap-providers.md",
    "content": "# Configuration of confmap Providers\n\n## Motivation\n\nThe `confmap.Provider` interface is used by the Collector to retrieve map\nobjects representing the Collector's configuration or a subset thereof. Sources\nof config may include locally-available information such as files on disk or\nenvironment variables, or may be remotely accessed over the network. In the\nprocess of obtaining configuration from a source, the user may wish to modify\nthe behavior of how the source is obtained.\n\nFor example, consider the case where the Collector obtains configuration over\nHTTP from an HTTP endpoint. A user may want to:\n\n1. Poll the HTTP endpoint for configuration at a configurable interval and\n   reload the Collector service if the configuration changes.\n2. Authenticate the request to get configuration by including a header in the\n   request. Additional headers may be necessary as part of this flow.\n\nThis would produce a set of options like the following:\n\n- `poll-interval`: Sets an interval for the Provider to check the HTTP endpoint\n  for changes. If the config has changed, the service will be reloaded.\n- `headers`: Specifies a map of headers to be put into the HTTP request to the\n  server.\n\n## Current state\n\nNo upstream Providers currently offer any configuration options. The exported\ninterfaces are still able to change before the `confmap` module is declared\nstable, but avoiding breaking changes in the API would be preferable.\n\n## Desired state\n\nWe would like the following features available to users to configure Providers:\n\n1. Global configuration of a certain type of Provider (`file`, `http`, etc.).\n   This allows for users to express things such as \"all files should be watched\n   for changes\" and \"all HTTP requests should include authentication\".\n2. Named configuration for a certain type of provider that can be applied to\n   particular URIs. This will allow users to express things such as \"some HTTP\n   URLs should be watched for changes with a certain set of settings applied\".\n3. Configuration options applied to specific URIs.\n\n## Resolution\n\nThe `confmap` module APIs will not substantially change for 1.0. The following\nsteps will be taken to ensure that configuration can be made to work post-1.0:\n\n1. Restrict URIs sufficiently to allow for extension after 1.0, e.g. restricting\n   the scheme to allow for things like \"named schemes\" (`file/auth:`).\n2. Stabilize confmap Providers individually, so they can impose any desired\n   restrictions on their own.\n3. Offer configuration as an optional interface for things like options that are\n   applied to all instances of a Provider.\n\n## Possible technical solutions\n\n*NOTE*: This section is speculative and may not reflect the final implementation\nfor providing options to confmap Providers.\n\nProviders are invoked through passing `--config` flags to the Collector binary\nor by using the braces syntax inside a Collector config file (`${scheme:uri}`).\nEach invocation contains a scheme specifying how to obtain config and URI\nspecifying the config to be obtained. A single instance of a Provider is created\nfor each scheme and is tasked with retrieving config for its scheme for each\ncorresponding URI passed to the Collector.\n\nWith the above in mind, we have the following places where it may make sense to\nsupport specifying options for Providers:\n\n1. Parts of the URI we are requesting.\n1. Separate flags to configure Providers per config URI.\n1. Use a separate config file that specifies config sources inside a map\n   structure.\n1. Extend the Collector's config schema to support specifying additional places\n   to obtain configuration.\n\nAll of the above options are targeted toward configuring how specific URIs are\nresolved into config. To configure how a Provider resolves every URI it\nreceives, we should consider how to extend the above options to be specified\nwithout a URI and to ensure the options are always applied to all URI\nresolutions.\n\n### Configure options inside the URI\n\n[RFC 3986](https://datatracker.ietf.org/doc/html/rfc3986#section-3), which\nspecifies the format of a URI, specifies the different parts of a URI and\nsuggests two places where we could pass options to Providers: queries and\nfragments.\n\n#### Queries\n\nBreaking changes:\n\n- confmap Providers would have breaking changes since they would now consume\n  unescaped URI queries. There would be no breaking changes to the confmap API.\n\nAdvantages:\n\n- Explicitly intended to specify non-hierarchical data in a URI.\n- Often used for this purpose.\n- Fits into existing config URIs for URL-based Providers.\n\nDisadvantages:\n\n- Only allows easily specifying key-value pairs.\n- Query parameters are somewhat frequently used, which may extend to backend\n  requests, and this may cause some churn for users who are unfamiliar that we\n  would be consuming them.\n\n#### Fragments\n\nWe could specify options in a query parameter-encoded string placed into the URI\nfragment.\n\nBreaking changes:\n\n- confmap Providers would have breaking changes since they would now consume\n  fragments. There would be no breaking changes to the confmap API.\n\nAdvantages:\n\n- Not likely to be used by config backends for any of our supported protocols,\n  so has a low chance of conflict when using unescaped fragments.\n- Fits into existing config URIs for URL-based Providers.\n\nDisadvantages:\n\n- Even if fragments are likely not useful to backends, we are still preventing\n  unescaped use in upstream Providers.\n- Doesn't conform to the spirit of how fragments should be used according to RFC\n  3986.\n- Only allows easily specifying key-value pairs.\n\nWe could likely partially circumvent the key-value pair limitation by\nrecursively calling confmap Providers to resolve files, env vars, HTTP URLs,\netc. For example:\n\n```text\nhttps://config.com/config#refresh-interval=env:REFRESH_INTERVAL&headers=file:headers.yaml\n```\n\nUsing this strategy would also allow us to more easily get env vars and to get\nvalues from files for things like API tokens.\n\n### Separate flags to configure Providers per config URI\n\nBreaking changes:\n\n- Will need factory options if we provide config through a mechanism similar to\n  `component.Factory`, along with making a Provider instance per URI.\n- Otherwise will need to break `confmap.Provider` interface to support providing\n  options in `Retrieve`.\n\nAdvantages:\n\n- Allows us to keep config URIs opaque.\n- Options live right next to config URIs on the command line.\n\nDisadvantages:\n\n- The flags would need to be placed in a certain position in the arguments list\n  to specify which URI they apply to.\n- Configuring URIs present in files requires users to look in two places for\n  each URI and is suboptimal UX.\n- Complicating the flags like this would be suboptimal UX.\n\n### Specify additional config sources inside the main Collector configuration\n\nThis is a variant of providing a separate config source-only configuration file\nthat instead puts those URIs and their options inside the main configuration\nfile.\n\nAPI changes:\n\n- Need a way to specify options, either through a factory option, or an optional\n  interface.\n\nAdvantages:\n\n- Allows us to keep URIs opaque.\n- Map structures are easier to work with than command-line arguments for complex\n  config.\n\nDisadvantages:\n\n- There are now two ways to include config inside a Collector config file.\n- Complicates the config schema and the config resolution process.\n"
  },
  {
    "path": "docs/rfcs/env-vars.md",
    "content": "# Stabilizing environment variable resolution\n\n## Overview\n\nThe OpenTelemetry Collector supports three different syntaxes for\nenvironment variable resolution which differ in their syntax, semantics\nand allowed variable names. Before we stabilize confmap, we need to\naddress several issues related to environment variables. This document\ndescribes:\n\n- the current (as of v0.97.0) behavior of the Collector\n- the goals that an environment variable resolution should aim for\n- existing deviations from these goals\n- the desired behavior after making some changes\n\n### Out of scope\n\nCLI environment variable resolution has a single syntax (`--config env:ENV`) \nand it is considered out of scope for this document, focusing\ninstead on expansion within the Collector configuration.\n\nHow to get from the current to desired behavior is also considered out\nof scope and will be discussed on individual PRs. It will likely involve\none or multiple feature gates, warnings and transition periods.\n\n## Goals of an expansion system\n\nThe following are considered goals of the expansion system:\n\n1.  ***Expansion should happen only when the user expects it***. We\n    should aim to expand when the user expects it and keep the original\n    value when we don't (e.g. because the syntax is used for something\n    different).\n2.  ***Expansion must have predictable behavior***.\n3.  ***Multiple expansion methods, if present, should have similar behavior.***\n    Switching from `${env:ENV}` to `${ENV}` or vice versa\n    should not lead to any surprises.\n4.  ***When the syntax overlaps, expansion should be aligned with*** \n    [***the expansion defined by the Configuration Working Group***](https://github.com/open-telemetry/opentelemetry-specification/blob/032213cedde54a2171dfbd234a371501a3537919/specification/configuration/file-configuration.md#environment-variable-substitution). See [opentelemetry-specification/issues/3963](https://github.com/open-telemetry/opentelemetry-specification/issues/3963) for the counterpart to this line of work in the SDK File spec.\n\n## Current behavior\n\nThe Collector supports three different syntaxes for environment variable\nresolution:\n\n1.  The *naked syntax*, `$ENV`.\n2.  The *braces syntax*, `${ENV}`.\n3.  The *env provider syntax*, `${env:ENV}`.\n\nThese differ in the character set allowed for environment variable names\nas well as the type of parsing they return. Escaping is supported in all\nsyntaxes by using two dollar signs.\n\n### Type casting rules\n\nA provider or converter takes a string and returns some sort of value\nafter potentially doing some parsing. This gets stored in a\n`confmap.Conf`. When unmarshalling, we use [mapstructure](https://github.com/mitchellh/mapstructure) with\n`WeaklyTypedInput` enabled, which does a lot of implicit casting. The\ndetails of this type casting are complex and are outlined on issue\n[#9532](https://github.com/open-telemetry/opentelemetry-collector/issues/9532).\n\nWhen using this notation in inline mode (e.g.\n`http://endpoint/${env:PATH}`) we also do manual implicit type\ncasting with a similar approach to mapstructure. These are outlined\n[here](https://github.com/open-telemetry/opentelemetry-collector/blob/fc4c13d3c2822bec39fa9d9658836d1a020c6844/confmap/expand.go#L124-L139).\n\n### Naked syntax\n\nThe naked syntax is supported via the expand converter. It is\nimplemented using the [`os.Expand`](https://pkg.go.dev/os#Expand) stdlib\nfunction. This syntax supports identifiers made up of:\n\n1. ASCII alphanumerics and the `_` character\n2. Certain special characters if they appear alone typically used in\n   Bash: `*`, `#`, `$`, `@`, `!`, `?` and `-`.\n\nYou can see supported identifiers in this example:\n[`go.dev/play/p/YfxLtYbsL6j`](https://go.dev/play/p/YfxLtYbsL6j).\n\nThe environment variable value is taken as-is and the type is always\nstring.\n\n### Braces syntax\n\nThe braces syntax is supported via the expand converter. It is also\nimplemented using the os.Expand stdlib function. This syntax supports\nany identifiers that don't contain `}`. Again, refer to the os.Expand\nexample to see how it works in practice:\n[`go.dev/play/p/YfxLtYbsL6j`](https://go.dev/play/p/YfxLtYbsL6j).\n\nThe environment variable value is taken as-is and the type is always\nstring.\n\n### `env` provider\n\nThe `env` provider syntax is supported via the `env`\nprovider. It is a custom implementation with a syntax that supports any\nidentifier that does not contain a `$`. This is done to support recursive\nresolution (e.g. `${env:${http://example.com}}` would get the\nenvironment variable whose name is stored in the URL\n`http://example.com`).\n\nThe environment variable value is parsed by the yaml.v3 parser to an\nany-typed variable. The yaml.v3 parser mostly follows the YAML v1.2\nspecification with [*some exceptions*](https://github.com/go-yaml/yaml#compatibility). \nYou can see how it works for some edge cases in\n[this go.dev/play example](https://go.dev/play/p/3vNLznwSZQe).\n\n### Issues of current behavior\n\n#### Unintuitive behavior on unset environment variables\n\nWhen an environment variable is empty, all syntaxes return an empty\nstring with no warning given; this is frequently unexpected but can also\nbe used intentionally. This is especially unintuitive when the user did\nnot expect expansion to happen. Three examples where this is unexpected\nare the following:\n\n1.  **Opaque values such as passwords that contain `$`** (issue\n    [#8215](https://github.com/open-telemetry/opentelemetry-collector/issues/8215)).\n    If the $ is followed by an alphanumeric character or one of the\n    special characters, it's going to lead to false positives.\n2.  **Prometheus relabel config** (issue\n    [`contrib#9984`](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/9984)).\n    Prometheus uses `${1}` in some of its configuration values. We\n    resolve this to the value of the environment variable with name\n    '`1`'.\n3.  **Other uses of $** (issue\n    [`contrib#11846`](https://github.com/open-telemetry/opentelemetry-collector-contrib/issues/11846)).\n    If a product requires the use of `$` in some field, we would most\n    likely interpret it as an environment variable. This is not\n    intuitive for users.\n\n#### Unexpected type casting\n\nWhen using the env syntax we parse its value as YAML. Even if you are\nfamiliar with YAML, because of the implicit type casting rules and the\nway we store intermediate values, we can get unintuitive results.\n\nThe most clear example of this is issue\n[*#8565*](https://github.com/open-telemetry/opentelemetry-collector/issues/8565):\nWhen setting a variable to value `0123` and using it in a string-typed\nfield, it will end up as the string `\"83\"` (where as the user would\nexpect the string to be `0123`).\n\n#### We are less restrictive than the Configuration WG\n\nThe Configuration WG defines an [*environment variable expansion feature\nfor SDK\nconfigurations*](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/data-model.md#environment-variable-substitution).\nThis accepts only non empty alphanumeric + underscore identifiers\nstarting with alphabetic or underscore. If the Configuration WG were to\nexpand this in the future (e.g. to include other features present in\nBash-like syntax as in [opentelemetry-specification/pull/3948](https://github.com/open-telemetry/opentelemetry-specification/pull/3948)), we would not be able to expand our braces syntax to\nsupport new features without breaking users.\n\n## Desired behavior\n\n*This section is written as if the changes were already implemented.*\n\nThe Collector supports **two** different syntaxes for environment\nvariable resolution:\n\n1.  The *braces syntax*, `${ENV}`.\n2.  The *env provider syntax*, `${env:ENV}`.\n\nThese both have **the same character set and behavior**. They both use\nthe env provider under the hood. This means we support the exact same\nsyntax as the Configuration WG.\n\nThe naked syntax supported in Bash is not supported in the Collector.\nEscaping is supported by using two dollar signs. Escaping is also\nhonored for unsupported identifiers like `${1}` (i.e. anything that \nmatches `\\${[^$}]+}`).\n\n### Type casting rules\n\nThe environment variable value is parsed by the yaml.v3 parser to an\nany-typed variable and the original representation as a string is also stored. \nThe `yaml.v3` parser mostly follows the YAML v1.2 specification with [*some\nexceptions*](https://github.com/go-yaml/yaml#compatibility). You can see\nhow it works for some edge cases in this example:\n[*https://go.dev/play/p/RtPmH8aZA1X*](https://go.dev/play/p/RtPmH8aZA1X).\n\nWhen unmarshalling, we use mapstructure with WeaklyTypedInput\n**disabled**. We check via a hook the original string representation of the data\nand use its return value when it is valid and we are mapping to a string\nfield. This method has default casting rules for unambiguous scalar\ntypes but may return the original representation depending on the\nconstruction of confmap.Conf (see the comparison table below for details).\n\nFor using this notation in inline mode (e.g.`http://endpoint/${env:PATH}`), we\nuse the original string representation as well (see the comparison table below for details).\n\n### Character set\n\nAn environment variable identifier must be a nonempty ASCII alphanumeric\nor underscore starting with an alphabetic or underscore character. Its\nmaximum length is 200 characters. Both syntaxes support recursive\nresolution.\n\nWhen an invalid identifier is found, an error is emitted. To use an invalid\nidentifier, the string must be escaped.\n\n### Comparison table with current behavior\n\nThis is a comparison between the current and desired behavior for\nloading a field with the braces syntax, `env` syntax.\n\n| Raw value    | Field type | Current behavior, `${ENV}`, single field | Current behavior,  `${env:ENV}` , single field | Desired behavior, entire field | Desired behavior, inline string field |\n|--------------|------------|------------------------------------------|------------------------------------------------|--------------------------------|---------------------------------------|\n| `123`        | integer    | 123                                      | 123                                            | 123                            | n/a                                   |\n| `0123`       | integer    | 83                                       | 83                                             | 83                             | n/a                                   |\n| `0123`       | string     | 0123                                     | 83                                             | 0123                           | 0123                                  |\n| `0xdeadbeef` | string     | 0xdeadbeef                               | 3735928559                                     | 0xdeadbeef                     | 0xdeadbeef                            |\n| `\"0123\"`     | string     | \"0123\"                                   | 0123                                           | \"0123\"                         | \"0123\"                                |\n| `!!str 0123` | string     | !!str 0123                               | 0123                                           | !!str 0123                     | !!str 0123                            |\n| `t`          | boolean    | true                                     | true                                           | Error: mapping string to bool  | n/a                                   |\n| `23`         | boolean    | true                                     | true                                           | Error: mapping integer to bool | n/a                                   |\n"
  },
  {
    "path": "docs/rfcs/experimental-profiling.md",
    "content": "# Experimental support for profiling\n\n## Overview\n\nThe OpenTelemetry collector has traces, metrics and logs as stable signals. We\nwant to start experimenting with support for profiles as an experimental\nsignal. But we also don't want to introduce breaking changes in packages\notherwise considered stable.\n\nThis document describes:\n\n* The approach we intend to take to introduce profiling with no breaking changes\n* How the migration will happen once profiling goes stable\n\n### Discarded approaches\n\n#### Refactor everything into per-signal subpackages\n\nA first approach, discussed in [issue\n10207](https://github.com/open-telemetry/opentelemetry-collector/issues/10207)\nhas been discarded.\nIt aimed to refactor the current packages with per-signal subpackages, so each\nsubpackage could have its own stability level, like pdata does.\n\nThis has been discarded, as the Collector SIG does not want the profiling\nsignal to impact the road to the collector reaching 1.0.\n\n#### Use build tags\n\nAn approach would have been to use build tags to limit the availability of\nprofiles within packages.\n\nThis approach would make the UX very bad though, as most packages are meant to\nbe imported and not used in a compiled collector. It would therefore not have\nbeen possible to specify the appropriate build tags.\n\nThis has been discarded, as the usage would have been too difficult.\n\n## Proposed approach\n\nThe proposed approach will consist of two main phases:\n\n* Introduce `experimental` packages for each required module of the collector that needs to be profiles-aware.\n\t* `consumer`, `receiver`, `connector`, `component`, `processor`\n* Mark specific APIs as `experimental` in their godoc for parts that can't be a new package.\n\t* `service`\n\n### Introduce \"experimental\" subpackages\n\nEach package that needs to be profiling signal-aware will have its public\nmethods and interfaces moves into an internal subpackage.\n\nThen, the original package will get similar API methods and interfaces as the\nones currently available on the main branch.\n\nThe profiling methods and interfaces will be made available in a `profiles`\nsubpackage.\n\nSee [PR\n#10253](https://github.com/open-telemetry/opentelemetry-collector/pull/10253)\nfor an example.\n\n### Mark specific APIs as `experimental`\n\nIn order to boot a functional collector with profiles support, some stable\npackages need to be aware of the experimental ones.\n\nTo support that case, we will mark new APIs as `experimental` with go docs.\nEvery experimental API will be documented as such:\n\n```golang\n// # Experimental\n//\n// Notice: This method is EXPERIMENTAL and may be changed or removed in a\n// later release.\n```\n\nAs documented, APIs marked as experimental may changed or removed across\nreleases, without it being considered as a breaking change.\n\nThere are no symbols that would need to be marked as experimental today. If\nthere ever are then implementers may add an experimental comment to them\n\n#### User specified configuration\n\nThe user-specified configuration will let users specify a `profiles` pipeline:\n\n```\nservice:\n\tpipelines:\n\t\tprofiles:\n\t\t\treceivers: [otlp]\n\t\t\texporters: [otlp]\n```\n\nWhen an experimental signal is being used, the collector will log a warning at\nboot.\n\n## Signal status change\n\nIf the profiling signal becomes stable, all the experimental packages will be\nmerged back into their stable counterpart, and the `service` module's imports\nwill be updated.\n\nIf the profiling signal is removed, all the experimental packages will be\nremoved from the repository, and support for them will be removed in the\n`service` module.\n"
  },
  {
    "path": "docs/rfcs/logging-before-config-resolution.md",
    "content": "# How To Log Before Config Resolution\n\n## Overview\n\nThe OpenTelemetry Collector supports configuring a primary logger that the collector and its components use to write logs.\nThis logger cannot be created until the user's configuration has been completely resolved.\nThere is a need to write logs during the collector start-up, before the primary logger is instantiated, such as during\nconfiguration resolution or config validation. This document describes\n\n- why providing logging capabilities during startup is important\n- the current (as of v0.99.0) behavior of the Collector\n- different solutions to the problem\n- the accepted solution\n\n## Why Logging During Startup is Important\n\nWhen the collector is starting it tries to resolve user configuration as quickly as possible.\nBut the Collector's configuration resolution strategy is not trivial - it allows for complex interactions between\nmultiple, different config sources that must all resolve without error. During this process important information could\nbe shared with users such as:\n- [Warnings about deprecated syntax](https://github.com/open-telemetry/opentelemetry-collector/issues/9162)\n- [Warnings about undesired, but handled, situations](https://github.com/open-telemetry/opentelemetry-collector/issues/5615)\n- Debug information\n\n## Requirements for any solution\n\n1. Once the primary logger is instantiated, it should be usable anywhere in the Collector that does logging.\n2. Log timestamps must be accurate to when the log was written, regardless of when the log is written to the user-specified location(s).\n3. The EntryCaller (what line number the log originates from) must be accurate to where the log was written.\n4. If an error causes the collector to gracefully terminate before the primary logger is created any previously written logs MUST be written to the either stout or stderr if they have not already been written there.\n\n## Current behavior\n\nAs of v0.99.0, the collector does not provide a way to log before the primary logger is instantiated.\n\n## Solutions\n\n### Buffer Logs in Memory and Write Them Once the Primary Logger Exists\n\nThe Collector could provide a temporary logger that, when written to, keeps the logs in memory. These logs could then\nbe passed to the primary logger to be written out in the properly configured format/level.\n\nBenefits:\n- Logs are written in the user-specified format/level\n\nDownsides:\n- If the primary logger is used to write any logs before the buffered logs are passed, logs may be out of order. There are no guarantees that logs will be written in order, so the log timestamps should be taken as the source of truth for ordering.\n\n### Create a Logger Using the Primary Logger's Defaults\n\nWhen the user provides no primary logger configuration the Collector creates a Logger using a set of default values.\nThe Collector could, very early in startup, create a logger using these exact defaults and use it until the primary\nlogger is instantiated.\n\nBenefits:\n- Logs order is preserved\n- Logs are still written when an error occurs before the primary logger can be instantiated\n\nDownsides:\n- Logs may be written in a format/level that differs from the format/level of the primary logger\n\n## Accepted Solution\n\n[Buffer Logs in Memory and Write Them Once the Primary Logger Exists](#buffer-logs-in-memory-and-write-them-once-the-primary-logger-exists)\n\nThis solution, while more complex, allows the collector to write out the logs in the user-specified format whenever possible.  A fallback logger must be used in situations where the primary logger could not be created and the collector is shutting down, such as when encountering an error during configuration resolution, but otherwise the primary logger will be used to write logs that occurred before the primary logger existed.\n"
  },
  {
    "path": "docs/rfcs/metadata.yaml",
    "content": "type: rfcs\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: docs\n  codeowners:\n    active:\n      - codeboten\n      - bogdandrutu\n      - dmitryax\n      - mx-psi\n"
  },
  {
    "path": "docs/rfcs/optional-config-type.md",
    "content": "# Optional[T] type for use in configuration structs\n\n## Overview\n\nIn Go, types are by default set to a \"zero-value\", a supported value for the\nrespective type that is semantically equivalent or similar to \"empty\", but which\nis also a valid value for the type. For many config fields, the zero value is\nnot a valid configuration value and can be taken to mean that the option is\ndisabled, but in certain cases it can indicate a default value, necessitating a\nway to represent the presence of a value without using a valid value for the\ntype.\n\nUsing standard Go without inventing any new types, the two most straightforward\nways to accomplish this are:\n\n1. Using a separate boolean field to indicate whether the field is enabled or\n   disabled.\n2. Making the type a pointer, which makes a `nil` pointer represent that a\n   value is not present, and a valid pointer represent the desired value.\n\nEach of these approaches has deficiencies: Using a separate boolean field\nrequires the user to set the boolean field to `true` in addition to setting the\nactual config option, leading to suboptimal UX. Using a pointer value has a few\ndrawbacks:\n\n1. It may not be immediately obvious to a new user that a pointer type indicates\n   a field is optional.\n2. The distinction between values that are conventionally pointers (e.g. gRPC\n   configs) and optional values is lost.\n3. Setting a default value for a pointer field when decoding will set the field\n   on the resulting config struct, and additional logic must be done to unset\n   the default if the user has not specified a value.\n4. The potential for null pointer exceptions is created.\n5. Config structs are generally intended to be immutable and may be passed\n   around a lot, which makes the mutability property of pointer fields\n   an undesirable property.\n\n## Optional types\n\nGo does not include any form of Optional type in the standard library, but other\npopular languages like Rust and Java do. We could implement something similar in\nour config packages that allows us to address the downsides of using pointers\nfor optional config fields.\n\n## Basic definition\n\nA production-grade implementation will not be discussed or shown here, but the\nbasic implementation for an Optional type in Go could look something like:\n\n```golang\ntype Optional[T any] struct {\n\thasValue bool\n\tvalue    T\n\n\tdefaultVal T\n}\n\nfunc Some[T any](value T) Optional[T] {\n\treturn Optional[T]{value: value, hasValue: true}\n}\n\nfunc None[T any]() Optional[T] {\n\treturn Optional[T]{}\n}\n\nfunc WithDefault[T any](defaultVal T) Optional[T] {\n\treturn Optional[T]{defaultVal: defaultVal}\n}\n\nfunc (o Optional[T]) HasValue() bool {\n\treturn o.hasValue\n}\n\nfunc (o Optional[T]) Value() T {\n    return o.value\n}\n\nfunc (o Optional[T]) Default() T {\n    return o.defaultVal\n}\n```\n\n## Use cases\n\nOptional types can fulfill the following use cases we have when decoding config.\n\n### Representing optional config fields\n\nTo use the optional type to mark a config field as optional, the type can simply be used as a type\nparameter to `Optional[T]`. The YAML representation of `Optional[T]` is the same as that of `T`,\nexcept that the type records whether the value is present. The following config struct shows how\nthis may look, both in definition and in usage:\n\n```golang\ntype Protocols struct {\n\tGRPC Optional[configgrpc.ServerConfig] `mapstructure:\"grpc\"`\n\tHTTP Optional[HTTPConfig]              `mapstructure:\"http\"`\n}\n\nfunc (cfg *Config) Validate() error {\n\tif !cfg.GRPC.HasValue() && !cfg.HTTP.HasValue() {\n\t\treturn errors.New(\"must specify at least one protocol when using the OTLP receiver\")\n\t}\n\treturn nil\n}\n\nfunc createDefaultConfig() component.Config {\n\treturn &Config{\n\t\tProtocols: Protocols{\n\t\t\tGRPC: WithDefault(configgrpc.ServerConfig{\n                // ...\n            }),\n\t\t\tHTTP: WithDefault(HTTPConfig{\n                // ...\n            }),\n\t\t},\n\t}\n}\n```\n\nFor something like `confighttp.ServerConfig`, using an `Optional[T]` type for\noptional fields would look like this:\n\n```golang\ntype ServerConfig struct {\n\tTLSSetting Optional[configtls.ServerConfig] `mapstructure:\"tls\"`\n\n\tCORS Optional[CORSConfig] `mapstructure:\"cors\"`\n\n\tAuth Optional[AuthConfig] `mapstructure:\"auth,omitempty\"`\n\n\tResponseHeaders Optional[map[string]configopaque.String] `mapstructure:\"response_headers\"`\n}\n\nfunc NewDefaultServerConfig() ServerConfig {\n\treturn ServerConfig{\n\t\tTLSSetting:        WithDefault(configtls.NewDefaultServerConfig()),\n\t\tCORS:              WithDefault(NewDefaultCORSConfig()),\n\t\tWriteTimeout:      30 * time.Second,\n\t\tReadHeaderTimeout: 1 * time.Minute,\n\t\tIdleTimeout:       1 * time.Minute,\n\t}\n}\n\nfunc (sc *ServerConfig) ToListener(ctx context.Context) (net.Listener, error) {\n\tlistener, err := net.Listen(\"tcp\", sc.Endpoint)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif sc.TLSSetting.HasValue() {\n\t\tvar tlsCfg *tls.Config\n\t\ttlsCfg, err = sc.TLSSetting.Value().LoadTLSConfig(ctx)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ttlsCfg.NextProtos = []string{http2.NextProtoTLS, \"http/1.1\"}\n\t\tlistener = tls.NewListener(listener, tlsCfg)\n\t}\n\n\treturn listener, nil\n}\n\nfunc (sc *ServerConfig) ToServer(_ context.Context, host component.Host, settings component.TelemetrySettings, handler http.Handler, opts ...ToServerOption) (*http.Server, error) {\n\t// ...\n\n\thandler = httpContentDecompressor(\n\t\thandler,\n\t\tsc.MaxRequestBodySize,\n\t\tserverOpts.ErrHandler,\n\t\tsc.CompressionAlgorithms,\n\t\tserverOpts.Decoders,\n\t)\n\n\t// ...\n\n\tif sc.Auth.HasValue() {\n\t\tserver, err := sc.Auth.Value().GetServerAuthenticator(context.Background(), host.GetExtensions())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\thandler = authInterceptor(handler, server, sc.Auth.Value().RequestParameters)\n\t}\n\n\tcorsValue := sc.CORS.Value()\n\tif sc.CORS.HasValue() && len(sc.CORS.AllowedOrigins) > 0 {\n\t\tco := cors.Options{\n\t\t\tAllowedOrigins:   corsValue.AllowedOrigins,\n\t\t\tAllowCredentials: true,\n\t\t\tAllowedHeaders:   corsValue.AllowedHeaders,\n\t\t\tMaxAge:           corsValue.MaxAge,\n\t\t}\n\t\thandler = cors.New(co).Handler(handler)\n\t}\n\tif sc.CORS.HasValue() && len(sc.CORS.AllowedOrigins) == 0 && len(sc.CORS.AllowedHeaders) > 0 {\n\t\tsettings.Logger.Warn(\"The CORS configuration specifies allowed headers but no allowed origins, and is therefore ignored.\")\n\t}\n\n\tif sc.ResponseHeaders.HasValue() {\n\t\thandler = responseHeadersHandler(handler, sc.ResponseHeaders.Value())\n\t}\n\n\t// ...\n}\n```\n\n### Proper unmarshaling of empty values when a default is set\n\nCurrently, the OTLP receiver requires a workaround to make enabling each\nprotocol optional while providing defaults if a key for the protocol has been\nset:\n\n```golang\ntype Protocols struct {\n\tGRPC *configgrpc.ServerConfig `mapstructure:\"grpc\"`\n\tHTTP *HTTPConfig              `mapstructure:\"http\"`\n}\n\n// Config defines configuration for OTLP receiver.\ntype Config struct {\n\t// Protocols is the configuration for the supported protocols, currently gRPC and HTTP (Proto and JSON).\n\tProtocols `mapstructure:\"protocols\"`\n}\n\nfunc createDefaultConfig() component.Config {\n\treturn &Config{\n\t\tProtocols: Protocols{\n\t\t\tGRPC: configgrpc.NewDefaultServerConfig(),\n\t\t\tHTTP: &HTTPConfig{\n                // ...\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc (cfg *Config) Unmarshal(conf *confmap.Conf) error {\n\t// first load the config normally\n\terr := conf.Unmarshal(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\n    // gRPC will be enabled if this line is not run\n\tif !conf.IsSet(protoGRPC) {\n        cfg.GRPC = nil\n\t}\n\n     // HTTP will be enabled if this line is not run\n\tif !conf.IsSet(protoHTTP) {\n\t\tcfg.HTTP = nil\n\t}\n\n\treturn nil\n}\n```\n\nWith an Optional type, the checks in `Unmarshal` become unnecessary, and it's\npossible the entire `Unmarshal` function may no longer be needed. Instead, when\nthe config is unmarshaled, no value would be put into the default Optional\nvalues and `HasValue` would return false when using this config object.\n\nThis situation is something of an edge case with our current unmarshaling\nfacilities and while not common, could be a rough edge for users looking to\nimplement similar config structures.\n\n## Disadvantages of an Optional type\n\nThere is one noteworthy disadvantage of introducing an Optional type:\n\n1. Since the type isn't standard, external packages working with config may\n   require additional adaptations to work with our config structs. For example,\n   if we wanted to generate our types from a JSON schema using a package like\n   [github.com/atombender/go-jsonschema][go-jsonschema], we would need some way\n   to ensure compatibility with an Optional type.\n\n[go-jsonschema]: https://github.com/omissis/go-jsonschema\n"
  },
  {
    "path": "docs/rfcs/processing.md",
    "content": "# OpenTelemetry Collector Processor Exploration\n\n**Status:** *Draft*\n\n## Objective\n\nTo describe a user experience and strategies for configuring processors in the OpenTelemetry collector.\n\nThis work is being prototyped in opentelemetry-collector-contrib, the design doc is here for broader discussion.\n\n## Summary\n\nThe OpenTelemetry (OTel) collector is a tool to set up pipelines to receive telemetry from an application and export it\nto an observability backend. Part of the pipeline can include processing stages, which executes various business logic\non incoming telemetry before it is exported.\n\nOver time, the collector has added various processors to satisfy different use cases, generally in an ad-hoc way to\nsupport each feature independently. We can improve the experience for users of the collector by consolidating processing\npatterns in terms of user experience, and this can be supported by defining a querying model for processors\nwithin the collector core, and likely also for use in SDKs, to simplify implementation and promote the consistent user\nexperience and best practices.\n\n## Goals and non-goals\n\nGoals:\n- List out use cases for processing within the collector\n- Consider what could be an ideal configuration experience for users\n\nNon-Goals:\n- Merge every processor into one. Many use cases overlap and generalize, but not all of them\n- Technical design or implementation of configuration experience. Currently focused on user experience.\n\n## Use cases for processing\n\n### Telemetry mutation\n\nProcessors can be used to mutate the telemetry in the collector pipeline. OpenTelemetry SDKs collect detailed telemetry\nfrom applications, and it is common to have to mutate this into a way that is appropriate for an individual use case.\n\nSome types of mutation include\n\n- Remove a forbidden attribute such as `http.request.header.authorization`\n- Reduce cardinality of an attribute such as translating `http.target` value of `/user/123451/profile` to `/user/{userId}/profile`\n- Decrease the size of the telemetry payload by removing large resource attributes such as `process.command_line`\n- Filtering out signals such as by removing all telemetry with a `http.target` of `/health`\n- Attach information from resource into telemetry, for example adding certain resource fields as metric dimensions\n\nThe processors implementing this use case are `attributesprocessor`, `filterprocessor`, `metricstransformprocessor`, \n`resourceprocessor`, `spanprocessor`.\n\n### Metric generation\n\nThe collector may generate new metrics based on incoming telemetry. This can be for covering gaps in SDK coverage of\nmetrics vs spans, or to create new metrics based on existing ones to model the data better for backend-specific\nexpectations.\n\n- Create new metrics based on information in spans, for example to create a duration metric that is not implemented in the SDK yet\n- Apply arithmetic between multiple incoming metrics to produce an output one, for example divide an `amount` and a `capacity` to create a `utilization` metric\n\nThe components implementing this use case are `metricsgenerationprocessor` and the former `spanmetricsprocessor` (now `spanmetricsconnector`).\n\n### Grouping\n\nSome processors are stateful, grouping telemetry over a window of time based on either a trace ID or an attribute value,\nor just general batching.\n\n- Batch incoming telemetry before sending to exporters to reduce export requests\n- Group spans by trace ID to allow doing tail sampling\n- Group telemetry for the same path\n\nThe processors implementing this use case are `batchprocessor`, `groupbyattrprocessor`, `groupbytraceprocessor`.\n\n### Metric temporality\n\nTwo processors convert between the two types of temporality, cumulative and delta. The conversion is generally expected\nto happen as close to the source data as possible, for example within receivers themselves. The same configuration\nmechanism could be used for selecting metrics for temporality conversion as other cases, but it is expected that in\npractice configuration will be limited.\n\nThe processors implementing this use case are `cumulativetodeltaprocessor`.\n\n### Telemetry enrichment\n\nOpenTelemetry SDKs focus on collecting application specific data. They also may include resource detectors to populate\nenvironment specific data but the collector is commonly used to fill gaps in coverage of environment specific data.\n\n- Add environment about a cloud provider to `Resource` of all incoming telemetry\n\nThe processors implementing this use case are `k8sattributesprocessor`, `resourcedetectionprocessor`.\n\n## OpenTelemetry Transformation Language\n\nWhen looking at the use cases, there are certain common features for telemetry mutation and metric generation.\n\n- Identify the type of signal (`span`, `metric`, `log`).\n- Navigate to a path within the telemetry to operate on it\n- Define an operation, and possibly operation arguments\n\nWe can try to model these into a transformation language, in particular allowing the first two points to be shared among all\nprocessing operations, and only have implementation of individual types of processing need to implement operators that\nthe user can use within an expression.\n\nTelemetry is modeled in the collector as [`pdata`](https://github.com/open-telemetry/opentelemetry-collector/tree/main/pdata)\nwhich is roughly a 1:1 mapping of the [OTLP protocol](https://github.com/open-telemetry/opentelemetry-proto/tree/main/opentelemetry/proto).\nThis data can be navigated using field expressions, which are fields within the protocol separated by dots. For example,\nthe status message of a span is `status.message`. A map lookup can include the key as a string, for example `attributes[\"http.status_code\"]`.\n\nOperations are scoped to the type of a signal (`span`, `metric`, `log`), with all of the flattened points of that\nsignal being part of a transformation space. Virtual fields are added to access data from a higher level before flattening, for\n`resource`, `library_info`. For metrics, the structure presented for processing is actual data points, e.g. `NumberDataPoint`, \n`HistogramDataPoint`, with the information from higher levels like `Metric` or the data type available as virtual fields.\n\nVirtual fields for all signals: `resource`, `library_info`.  \nVirtual fields for metrics: `metric`, which contains `name`, `description`, `unit`, `type`, `aggregation_temporality`, and `is_monotonic`.\n\nNavigation can then be used with a simple expression language for identifying telemetry to operate on.\n\n```\n... where name = \"GET /cats\"\n```\n```\n... from span where attributes[\"http.target\"] = \"/health\"\n```\n```\n... where resource.attributes[\"deployment\"] = \"canary\"\n```\n```\n... from metric where metric.type = gauge\n```\n```\n... from metric where metric.name = \"http.active_requests\"\n```\n\nFields should always be fully specified - for example `attributes` refers to the `attributes` field in the telemetry, not\nthe `resource`. In the future, we may allow shorthand for accessing scoped information that is not ambiguous.\n\nHaving selected telemetry to operate on, any needed operations can be defined as functions. Known useful functions should\nbe implemented within the collector itself, provide registration from extension modules to allow customization with\ncontrib components, and in the future can even allow user plugins possibly through WASM, similar to work in \n[HTTP proxies](https://github.com/proxy-wasm/spec). The arguments to operations will primarily be field expressions,\nallowing the operation to mutate telemetry as needed.\n\nThere are times when the transformation language input and the underlying telemetry model do not translate cleanly.  For example, a span ID is represented in pdata as a SpanID struct, but in the transformation language it is more natural to represent the span ID as a string or a byte array.  The solution to this problem is Factories. Factories are functions that help translate between the transformation language input into the underlying pdata structure.  These types of functions do not change the telemetry in any way.  Instead, they manipulate the transformation language input into a form that will make working with the telemetry easier or more efficient.\n\n### Examples\n\nThese examples contain a SQL-like declarative language.  Applied statements interact with only one signal, but statements can be declared across multiple signals.\n\nRemove a forbidden attribute such as `http.request.header.authorization` from spans only\n\n```\ntraces:\n  delete(attributes[\"http.request.header.authorization\"])\nmetrics:\n  delete(attributes[\"http.request.header.authorization\"])\nlogs:\n  delete(attributes[\"http.request.header.authorization\"])\n```\n\nRemove all attributes except for some\n\n```\ntraces:\n  keep_keys(attributes, \"http.method\", \"http.status_code\")\nmetrics:\n  keep_keys(attributes, \"http.method\", \"http.status_code\")\nlogs:\n  keep_keys(attributes, \"http.method\", \"http.status_code\")\n```\n\nReduce cardinality of an attribute\n\n```\ntraces:\n  replace_match(attributes[\"http.target\"], \"/user/*/list/*\", \"/user/{userId}/list/{listId}\")\n```\n\nReduce cardinality of a span name\n\n```\ntraces:\n  replace_match(name, \"GET /user/*/list/*\", \"GET /user/{userId}/list/{listId}\")\n``` \n\nReduce cardinality of any matching attribute\n\n```\ntraces:\n  replace_all_matches(attributes, \"/user/*/list/*\", \"/user/{userId}/list/{listId}\")\n``` \n\nDecrease the size of the telemetry payload by removing large resource attributes\n\n```\ntraces:\n  delete(resource.attributes[\"process.command_line\"])\nmetrics:\n  delete(resource.attributes[\"process.command_line\"])\nlogs:\n  delete(resource.attributes[\"process.command_line\"])\n```\n\nFiltering out signals such as by removing all metrics with a `http.target` of `/health`\n\n```\nmetrics:\n  drop() where attributes[\"http.target\"] = \"/health\"\n```\n\nAttach information from resource into telemetry, for example adding certain resource fields as metric attributes\n\n```\nmetrics:\n  set(attributes[\"k8s_pod\"], resource.attributes[\"k8s.pod.name\"])\n```\n\nGroup spans by trace ID\n\n```\ntraces:\n  group_by(trace_id, 2m)\n```\n\n\nUpdate a spans ID\n\n```\nlogs:\n  set(span_id, SpanID(0x0000000000000000))\ntraces:\n  set(span_id, SpanID(0x0000000000000000))\n```\n\nCreate utilization metric from base metrics. Because navigation expressions only operate on a single piece of telemetry,\nhelper functions for reading values from other metrics need to be provided.\n\n```\nmetrics:\n  create_gauge(\"pod.cpu.utilized\", read_gauge(\"pod.cpu.usage\") / read_gauge(\"node.cpu.limit\")\n```\n\nA lot of processing. Queries are executed in order. While initially performance may degrade compared to more specialized\nprocessors, the expectation is that over time, the transform processor's engine would improve to be able to apply optimizations \nacross queries, compile into machine code, etc.\n\n```yaml\nreceivers:\n  otlp:\n\nexporters:\n  otlp_grpc:\n\nprocessors:\n  transform:\n    # Assuming group_by is defined in a contrib extension module, not baked into the \"transform\" processor\n    extensions: [group_by]\n    traces:\n      queries:\n        - drop() where attributes[\"http.target\"] = \"/health\"\n        - delete(attributes[\"http.request.header.authorization\"])\n        - replace_wildcards(\"/user/*/list/*\", \"/user/{userId}/list/{listId}\", attributes[\"http.target\"])\n        - group_by(trace_id, 2m)\n    metrics:\n      queries:\n        - drop() where attributes[\"http.target\"] = \"/health\"\n        - delete(attributes[\"http.request.header.authorization\"])\n        - replace_wildcards(\"/user/*/list/*\", \"/user/{userId}/list/{listId}\", attributes[\"http.target\"])\n        - set(attributes[\"k8s_pod\"], resource.attributes[\"k8s.pod.name\"])\n    logs:\n      queries:\n        - drop() where attributes[\"http.target\"] = \"/health\"\n        - delete(attributes[\"http.request.header.authorization\"])\n        - replace_wildcards(\"/user/*/list/*\", \"/user/{userId}/list/{listId}\", attributes[\"http.target\"])\n\npipelines:\n  - receivers: [otlp]\n    exporters: [otlp]\n    processors: [transform]\n```\n\nThe expressions would be executed in order, with each expression either mutating an input telemetry, dropping input\ntelemetry, or adding additional telemetry. One caveat to note is that we would like to implement optimizations\nin the transform engine, for example to only apply filtering once for multiple operations with a shared filter. Functions\nwith unknown side effects may cause issues with optimization we will need to explore.\n\n## Declarative configuration\n\nThe telemetry transformation language presents an SQL-like experience for defining telemetry transformations - it is made up of\nthe three primary components described above, however, and can be presented declaratively instead depending on what makes\nsense as a user experience.\n\n```yaml\n- type: span\n  filter:\n    match:\n      path: status.code\n      value: OK\n  operation:\n    name: drop\n- type: all\n  operation:\n    name: delete\n    args:\n      - attributes[\"http.request.header.authorization\"]\n```\n\nAn implementation of the transformation language would likely parse expressions into this sort of structure so given an SQL-like\nimplementation, it would likely be little overhead to support a YAML approach in addition.\n\n## Function syntax\n\nFunctions should be named and formatted according to the following standards.\n- Function names MUST start with a verb unless it is a Factory.\n- Factory functions MUST be UpperCamelCase and named based on the object being created.\n- Function names that contain multiple words MUST separate those words with `_`.\n- Functions that interact with multiple items MUST have plurality in the name.  Ex: `truncate_all`, `keep_keys`, `replace_all_matches`.\n- Functions that interact with a single item MUST NOT have plurality in the name.  If a function would interact with multiple items due to a condition, like `where`, it is still considered singular.  Ex: `set`, `delete`, `drop`, `replace_match`.\n- Functions that change a specific target MUST set the target as the first parameter.\n- Functions that take a list MUST set the list as the last parameter.\n\n## Implementing a processor function\n\nThe `replace_match` function may look like this.\n\n```go\n\npackage replaceMatch\n\nimport \"regexp\"\n\nimport \"github.com/open-telemetry/opentelemetry/processors\"\n\n// Assuming this is not in \"core\"\nprocessors.register(\"replace_match\", replace_match)\n\nfunc replace_match(path processors.TelemetryPath, pattern regexp.Regexp, replacement string) processors.Result  {\n    val := path.Get()\n\tif val == nil {\n\t\treturn processors.CONTINUE\n    }\n\t\n\t// replace finds placeholders in \"replacement\" and swaps them in for regex matched substrings.\n\treplaced := replace(val, pattern, replacement)\n\tpath.Set(replaced)\n\treturn processors.CONTINUE\n}\n```\n\nHere, the processor framework recognizes the second parameter of the function is `regexp.Regexp` so will compile the string\nprovided by the user in the config when processing it. Similarly for `path`, it recognizes properties of type `TelemetryPath`\nand will resolve it to the path within a matched telemetry during execution and pass it to the function. The path allows\nscalar operations on the field within the telemetry. The processor does not need to be aware of telemetry filtering,\nthe `where ...` clause, as that will be handled by the framework before passing to the function.\n\n## Embedded processors\n\nThe above describes a transformation language for configuring processing logic in the OpenTelemetry collector. There will be a\nsingle processor that exposes the processing logic into the collector config; however, the logic will be implemented\nwithin core packages rather than directly inside a processor. This is to ensure that where appropriate, processing\ncan be embedded into other components, for example metric processing is often most appropriate to execute within a\nreceiver based on receiver-specific requirements.\n\n## Limitations\n\nThere are some known issues and limitations that we hope to address while iterating on this idea.\n\n- Handling array-typed attributes\n- Working on a array of points, rather than a single point\n- Metric alignment - for example defining an expression on two metrics, that may not be at the same timestamp\n- The collector has separate pipelines per signal - while the transformation language could apply cross-signal, we will need to remain single-signal for now\n"
  },
  {
    "path": "docs/rfcs/release-approvers.md",
    "content": "# OpenTelemetry Collector Releases approvers\n\n## Problem statement\n\nRelease engineering requires a different set of skills and interests than developing the Collector\ncodebase. As such, the set of contributors for the Collector releases has overlap with but is\ndifferent from the set of contributors for the Collector codebase. We are missing out on retaining\npeople who are more interested in these aspects. We can see this with the examples of the\nOpenTelemetry Operator repository and the OpenTelemetry Collector Helm Chart repository; they are\nable to work independently from the other Collector repositories and have been able to create an\nindependent community. \n\nWe also have a [growing backlog][1] of issues related to the release process that would benefit from\na dedicated set of people.\n\n## Overview \n\nI propose we create a new `collector-releases-approvers` Github team that are [approvers][2] on the\n[opentelemetry-collector-releases][3] repository and code owners for the Builder and release\nworkflows. The existing approvers teams will focus on the Collector and Collector components\ncodebases. This opens future possibilities for creating a separate WG/SIG for this and further\nimproving our release process.\n\n## Team scope and responsibilities\n\nThe `collector-releases-approvers` team will be [approvers][2] for the\nopentelemetry-collector-releases repository. They will also be listed as [code owners][4] for the\nrelease workflows on the opentelemetry-collector and opentelemetry-collector-contrib repositories.\n\nThe new team will not acquire any responsibilities related to the release; there will be no changes\nin the release rotation or release duties after this change.\n\n## Initial team members\n\nInitially, all members of the `collector-contrib-approvers` team will be part of the\n`collector-releases-approvers` team. The Collector maintainers will reach out to existing\ncontributors to the Collector releases to invite them to join the team.\n\n## Prior art\n\nThis introduces an approver group without a maintainer. It also introduces this team as a code owner for files in other repositories. There are prior instances of both of these patterns within the OpenTelemetry project:\n\n1. There are currently two SIGs that have approver teams without corresponding maintainer teams:\n  - The Docs SIG has multiple localization approver teams that have approver duties for the translations of the OpenTelemetry documentation.\n  - The Semantic Conventions SIG has multiple approver teams corresponding to different Working Groups and/or semantic conventions areas.\n2. There are multiple instances of teams being code owners:\n  - [opentelemetry-collector approvers are code owners for `examples/demo` in `opentelemetry-collector-contrib`][5]\n  - [Helm chart and Operator approvers are code owners for the k8s distro in `opentelemetry-collector-releases`][6]\n  - [Go instrumentation approvers are code owners of instrgen in `opentelemetry-go-contrib`][7]\n\n## Future work\n\nIf we are able to grow a healthy community around the releases repository, in the future we can\nconsider the following:\n\n- Having a dedicated SIG/WG for the opentelemetry-collector-releases repository.\n- Making the `collector-releases-approvers` code owners of the OpenTelemetry Collector Builder.\n- Having dedicated meetings for release retros that allow us to iteratively improve the Collector\n  release process.\n- Splitting off the artifact and container release process to be independent from the source code\n  release from opentelemetry-collector and opentelemetry-collector-contrib.\n\nThis proposal does not require us to do any of the above, but they are interesting possibilities for\nthe future.\n\n[1]: https://github.com/search?q=org%3Aopen-telemetry+label%3Arelease-retro++&type=issues&state=open\n[2]: https://github.com/open-telemetry/community/blob/main/guides/contributor/membership.md#approver\n[3]: https://github.com/open-telemetry/opentelemetry-collector-releases\n[4]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/CONTRIBUTING.md#membership-roles-and-responsibilities\n[5]: https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/40fa8b8a925cadf569e785cbc85d6dfca152bde2/.github/CODEOWNERS#L40\n[6]: https://github.com/open-telemetry/opentelemetry-collector-releases/blob/3ba7931410d1696d9df7bef424b634a5d64cffbd/.github/CODEOWNERS#L17\n[7]: https://github.com/open-telemetry/opentelemetry-go-contrib/blob/c0cc77f10a2dae774161d6a03441b12c0e8b0816/CODEOWNERS#L73\n"
  },
  {
    "path": "docs/rfcs/semconv-feature-gates.md",
    "content": "# Semantic conventions migrations in the Collector\n\n## Overview\n\nThe OpenTelemetry Collector components emit telemetry that often conforms to semantic conventions.\nSemantic conventions have [varying levels of stability][1] and often have an SDK-focused migration\nguide.\n\nThis RFC defines how migration should be handled in Collector components that have\nsemantic conventions that migrate to a stable version, in a Collector-native way.\n\n## Scope and goals\n\nThis RFC provides general guidelines for semantic convention-mandated migrations of telemetry created by Collector components (usually receivers) and output into the Collector's pipeline. It explicitly does not attempt to cover:\n- telemetry created by an application and forwarded by a Collector receiver;\n- internal telemetry of Collector components;\n- guidelines for the migration of specific semantic conventions.\n\nThe migration mechanism should have the following characteristics:\n\n1. **Collector native**: the mechanism should work in a similar way to other Collector migrations\n   and should feel natural and intuitive to users. \n2. **Simple**: a user should have to make a small number of changes to their Collector deployment to\n   migrate to a new set of conventions.\n3. **Easy to understand**: It should be easy to understand how to migrate a particular set of\n   conventions.\n5. **Flexible (double publish)**: The mechanism should allow you to 'double publish' v0 and v1\n   conventions\n6. **Flexible (other conventions)**: The mechanism should still allow for evolution of other\n   semantic conventions that are not being migrated.\n\n## Background \n\n### Setup\n\nWe want to write guidance for when we have a component that emits telemetry from a common\n`area` that is undergoing a migration mandated by the Semantic Conventions SIG. In the rest of this\ndocument we refer to the **v0** conventions and the **v1** conventions, which are the conventions\nin this area before and after the migration.\n\nWhen the semantic conventions are specific to a component we use \n- `kind` to refer to the component kind (receiver, exporter...)\n- `id` for the component id (e.g. `hostmetrics`)\n\n### What does the semconv spec say?\n\nThe semantic conventions specification defines an environment variable named\n`OTEL_SEMCONV_STABILITY_OPT_IN` that, for each area, takes two possible values:\n1. One value representing the new semantic conventions (e.g. `http`, `gen_ai_latest_experimental`)\n2. Once mature enough, a second value ending in `/dup` that emits both the old conventions and the\n   new ones.\n\nThis is not specified in a generic way, but it is a consistent pattern across all semantic\nconventions areas that are being actively worked on:\n\n<details>\n\n<summary> Example 1: HTTP compatibility warning </summary>\n\nTaken from [semconv v1.38.0][2]:\n\n> **Warning**\n> Existing HTTP instrumentations that are using\n> [v1.20.0 of this document](https://github.com/open-telemetry/opentelemetry-specification/blob/v1.20.0/specification/trace/semantic_conventions/http.md)\n> (or prior):\n>\n> * SHOULD NOT change the version of the HTTP or networking conventions that they emit\n>   until the HTTP semantic conventions are marked stable (HTTP stabilization will\n>   include stabilization of a core set of networking conventions which are also used\n>   in HTTP instrumentations). Conventions include, but are not limited to, attributes,\n>   metric and span names, and unit of measure.\n> * SHOULD introduce an environment variable `OTEL_SEMCONV_STABILITY_OPT_IN`\n>   in the existing major version which is a comma-separated list of values.\n>   The only values defined so far are:\n>   * `http` - emit the new, stable HTTP and networking conventions,\n>     and stop emitting the old experimental HTTP and networking conventions\n>     that the instrumentation emitted previously.\n>   * `http/dup` - emit both the old and the stable HTTP and networking conventions,\n>     allowing for a seamless transition.\n>   * The default behavior (in the absence of one of these values) is to continue\n>     emitting whatever version of the old experimental HTTP and networking conventions\n>     the instrumentation was emitting previously.\n>   * Note: `http/dup` has higher precedence than `http` in case both values are present\n> * SHOULD maintain (security patching at a minimum) the existing major version\n>   for at least six months after it starts emitting both sets of conventions.\n> * SHOULD drop the environment variable in the next major version (stable\n>   next major version SHOULD NOT be released prior to October 1, 2023).\n\n</details>\n\n<details>\n\n<summary> Example 2: GenAI compatibility warning </summary>\n\nFrom [semconv v1.38.0][3]:\n\n> [!Warning]\n>\n> Existing GenAI instrumentations that are using\n> [v1.36.0 of this document](https://github.com/open-telemetry/semantic-conventions/blob/v1.36.0/docs/gen-ai/README.md)\n> (or prior):\n>\n> * SHOULD NOT change the version of the GenAI conventions that they emit by default.\n>   Conventions include, but are not limited to, attributes, metric, span and event names,\n>   span kind and unit of measure.\n> * SHOULD introduce an environment variable `OTEL_SEMCONV_STABILITY_OPT_IN`\n>   as a comma-separated list of category-specific values. The list of values\n>   includes:\n>   * `gen_ai_latest_experimental` - emit the latest experimental version of\n>     GenAI conventions (supported by the instrumentation) and do not emit the\n>     old one (v1.36.0 or prior).\n>   * The default behavior is to continue emitting whatever version of the GenAI\n>     conventions the instrumentation was emitting (1.36.0 or prior).\n>\n> This transition plan will be updated to include stable version before the\n> GenAI conventions are marked as stable.\n\n</details>\n\n<details>\n\n<summary> Example 3: K8s compatibility warning </summary>\n\n> From [semconv v1.38.0][3]:\n\n> When existing K8s instrumentations published by OpenTelemetry are\n> updated to the stable K8s semantic conventions, they:\n> \n> - SHOULD introduce an environment variable `OTEL_SEMCONV_STABILITY_OPT_IN` in\n>   their existing major version, which accepts:\n>   - `k8s` - emit the stable k8s conventions, and stop emitting\n>     the old k8s conventions that the instrumentation emitted previously.\n>   - `k8s/dup` - emit both the old and the stable k8s conventions,\n>     allowing for a phased rollout of the stable semantic conventions.\n>   - The default behavior (in the absence of one of these values) is to continue\n>     emitting whatever version of the old k8s conventions the\n>     instrumentation was emitting previously.\n> - Need to maintain (security patching at a minimum) their existing major version\n>   for at least six months after it starts emitting both sets of conventions.\n> - May drop the environment variable in their next major version and emit only\n>   the stable k8s conventions.\n\n> Specifically for the Opentelemetry Collector:\n\n> The transition will happen through two different feature gates.\n> One for enabling the new schema called `semconv.k8s.enableStable`,\n> and one for disabling the old schema called `semconv.k8s.disableLegacy`. Then:\n\n> - On alpha the old schema is enabled by default (`semconv.k8s.disableLegacy` defaults to false),\n>   while the new schema is disabled by default (`semconv.k8s.enableStable` defaults to false).\n> - On beta/stable the old schema is disabled by default (`semconv.k8s.disableLegacy` defaults to true),\n>   while the new is enabled by default (`semconv.k8s.enableStable` defaults to true).\n> - It is an error to disable both schemas\n> - Both schemas can be enabled with `--feature-gates=-semconv.k8s.disableLegacy,+semconv.k8s.enableStable`.\n\n</details>\n\n## Proposed mechanism\n\nSuppose the `<id>` (e.g. `hostmetrics`) `kind` (e.g. `receiver`) component is migrating from v0 to\nv1 semantic conventions on the area `area` (e.g. `process`). The semantic conventions specification\ndefines the set of conventions that are in scope for a particular migration.\n\nTo support this migration, the component defines two feature gates: `<kind>.<id>.EmitV1<Area>Conventions` (e.g.\n`receiver.hostmetrics.EmitV1ProcessConventions`) and `<kind>.<id>.DontEmitV0<Area>Conventions`\n(e.g. `receiver.hostmetrics.DontEmitV0ProcessConventions`). These feature gates work as follows:\n\n| `<kind>.<id>.EmitV1<Area>Conventions` status | `<kind>.<id>.DontEmitV0<Area>Conventions` status    | Resulting behavior                                        |\n|-----------------------------------------------|-------------------------------------------------------|-----------------------------------------------------------|\n| Disabled                                      | Disabled                                              | Emit telemetry under the 'v0' conventions                |\n| Disabled                                      | Enabled                                               | Error at startup since this would not emit any telemetry  |\n| Enabled                                       | Disabled                                              | Emit telemetry under both the v0 and the v1 conventions |\n| Enabled                                       | Enabled                                               | Emit telemetry under the v1 conventions                  |\n\nBoth feature gates evolve at the same pace through the feature gate stages, so that the progression\nis as follows:\n1. Initially both are at **alpha** stage (disabled by default). This means that the default behavior\n   is to emit only the 'v0' conventions. Users can opt-in to emit the v1 conventions alongside the\n   v0 conventions or to emit only the v1 conventions. A warning message must be logged by the component at startup indicating the upcoming change.\n2. Whenever there is a semantic conventions release that marks these as stable, the feature gates are promoted to the\n   **beta** stage on the same Collector release. The new default behavior is therefore to emit only the\n   'v1' conventions. Users can opt-out to emit the v1 conventions alongside the v0 conventions or\n   to emit only the v0 conventions.\n3. After 4 minor releases, the feature gates are promoted to the **stable** stage. At this point users\n   can only use the v1 conventions.\n4. After additional 4 minor releases, the feature gates are removed.\n\nThis mechanism does not cover any sort of transition for experimental semantic conventions. These\npresumably would be covered by separate feature gates or some other mechanism.\n\n## Handling conflicts during double-publishing\n\nDuring the double-publishing phase (when both `<kind>.<id>.EmitV1<Area>Conventions` is enabled and `<kind>.<id>.DontEmitV0<Area>Conventions` is disabled), components typically emit both v0 and v1 telemetry. For metrics, this usually means emitting two separate metrics with different names (e.g., `http.server.duration` for v0 and `http.server.request.duration` for v1).\n\nHowever, in some cases v0 and v1 conventions may use the same metric name but with different characteristics (e.g., different attributes or metric types). Two metrics with identical names must not be emitted, as this would produce an invalid OpenTelemetry dataset and cause issues on backends. Below are examples illustrating how such conflicts can be resolved:\n\n**Different attributes:** If a metric name stays the same but an attribute is renamed, emit a single metric with both the v0 and v1 attributes present. For instance, if `process.cpu.time` uses `process.owner` in v0 and `process.owner.name` in v1, emit one metric with both attributes.\n\n**Different metric type:** If a metric name stays the same but the type changes (e.g., Gauge to UpDownCounter), emit a single metric with the v1 type, effectively prioritizing the new convention. For instance, if `system.memory.usage` changes from Gauge to UpDownCounter, emit it as an UpDownCounter.\n\n## Alternative mechanisms\n\nThere are some other possibilities:\n\n### Environment variable\n\nWe could just use the `OTEL_SEMCONV_STABILITY_OPT_IN` mechanism. However, this does not feel\n\"Collector native\": Collector users expect experimental features to be controlled via feature gates\nand as such this could be a surprising mechanism. In particular, users would expect that they are\nable to 'roll back' to the previous behavior even after a Collector upgrade, something that the\nenvironment variable mechanism explicitly does not support.\n\n### More granular feature gate pairs\n\nThe granularity of the feature gates described could be changed: we could have a pair per convention\nor even a pair for the whole Collector. I argue 'per component' strikes the right balance between\nsimplicity and flexibility: \n- per convention would lead to dozens of feature gates on some of the areas we want to stabilize. It\n  would also be unclear how these interact on edge cases (semantic conventions may only make sense\n  holistically)\n- a single pair of feature gates would effectively be forever unstable and would not be flexible\n  enough to allow people to migrate on a per dashboard basis\n\n### Meta feature gate\n\nWe could have both a feature gate pair per component and a meta target feature gate pair that allows\nyou to enable/disable all v1 conventions at the same time. This is effectively a superset of the\nproposed mechanism, so I argue we can postpone this for later: if users ask for it, we can always\nadd it in the future.\n\n## Open questions and future possibilities\n\nThis document does not cover how to deal with experimental semantic conventions after the 'big'\nmigration has been completed in one particular area. What to do here in part depends on the\n[stabilization changes][4]. Quoting the blogpost:\n> Instrumentation stability should be decoupled from semantic convention stability. We have a lot of\n> stable instrumentation that is safe to run in production, but has data that may change in the\n> future. Users have told us that conflating these two levels of stability is confusing and limits\n> their options.\n\nHow to deal with these remains an open question that should be tackled in OTEPs first.\n\nAs mentioned above, the 'Meta feature gate' remains a possibility even when adopting this mechanism.\n\n[1]: https://opentelemetry.io/docs/specs/semconv/general/semantic-convention-groups/#group-stability\n[2]: https://github.com/open-telemetry/semantic-conventions/blob/v1.38.0/docs/http/README.md\n[3]: https://github.com/open-telemetry/semantic-conventions/blob/v1.38.0/docs/gen-ai/README.md\n[4]: https://opentelemetry.io/blog/2025/stability-proposal-announcement/\n"
  },
  {
    "path": "docs/scraping-receivers.md",
    "content": "# Scraping Metrics Receivers\n\nScraping metrics receivers are receivers that pull data from external sources at regular intervals and translate it\ninto [pdata](../pdata/README.md) which is sent further in the pipeline. The external source of metrics usually is a\nmonitored system providing data about itself in some arbitrary format. There are two types of scraping metrics\nreceivers:\n\n- **Generic scraping metrics receivers:** The set of metrics emitted by this type of receiver fully depends on the \n  state of the external source and/or the user settings. Examples:\n  - [Prometheus Receiver](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/prometheusreceiver)\n  - [SQL Query Receiver](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/sqlqueryreceiver)\n\n- **Built-in scraping metrics receivers:** Receivers of this type emit a predefined set of metrics. However, the \n  metrics themselves are configurable via user settings. Examples of scrapings metrics receivers:\n  - [Redis Receiver](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/redisreceiver)\n  - [Zookeeper Receiver](https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/receiver/zookeeperreceiver)\n\nThis document covers built-in scraping metrics receivers. It defines which metrics these receivers can emit, \ndefines stability guarantees and provides guidelines for metric updates.\n\n## Defining emitted metrics \n\nEach built-in scraping metrics receiver has a `metadata.yaml` file that MUST define all the metrics emitted by the \nreceiver. The file is being used to generate an API for metrics recording, user settings to customize the emitted \nmetrics and user documentation. The file schema is defined in \nhttps://github.com/open-telemetry/opentelemetry-collector/blob/main/cmd/mdatagen/metadata-schema.yaml\nDefining a metric in `metadata.yaml` DOES NOT guarantee that the metric will always be produced by the receiver. In\nsome cases it may be impossible to fetch particular metrics from a system in a particular state.\n\nThere are two categories of the metrics emitted by scraping receivers:\n\n- **Default metrics**: emitted by default, but can be disabled in user settings.\n\n- **Optional metrics**: not emitted by default, but can be enabled in user settings.\n\nSee also [Semantic Convention compatibility](./coding-guidelines.md#semantic-conventions-compatibility) guidance.\n\n### How to identify if new metric should be default or optional?\n\nThere is no strict rule to differentiate default metrics from optional. As a rule of thumb, default metrics SHOULD be \ntreated as metrics essential to determine healthiness of a particular monitored system. Optional metrics on the \nother hand SHOULD be treated as a source of additional information about the monitored system. \n\nAdditionally, if any of the following conditions can be applied to a metric, it MUST be marked as optional:\n\n- **It is redundant with another metric.** For example system CPU usage can be emitted as two different metrics:\n  `system.cpu.time` (CPU time reported as cumulative sum in seconds) or `system.cpu.utilization` (fraction of CPU \n  time spent in different states reported as gauge), one of them has to be marked as option.\n- **It creates a disproportionately high cardinality of resources and/or data points.**\n- **There is a notable expected performance impact.**\n- **The source must be configured in an unusual way.**\n- **It requires dedicated configuration in the receiver.**\n\n## Stability levels of scraping receivers\n\nAll the requirements defined for components in [the Collector's README](../README.md#stability-levels) are\napplicable to the scraping receivers as well. In addition, the following rules applied specifically to scraping\nmetrics receivers:\n\n### Development\n\nThe receiver is not ready for use. All the metrics emitted by the receiver are not finalized and can change in any way.\n\n### Alpha\n\nThe receiver is ready for limited non-critical workloads. The list of emitted default metrics SHOULD be \nconsidered as complete, but any changes to the `metadata.yaml` still MAY be applied.\n\n### Beta\n\nThe receiver is ready for non-critical production workloads. The list of emitted default metrics MUST be\nconsidered as complete. Breaking changes to the emitted metrics SHOULD be applied following [the deprecation \nprocess](#changing-the-emitted-metrics).\n\n### Stable\n\nThe receiver is ready for production workloads. Breaking changes to the emitted metrics SHOULD be avoided.\nNevertheless, metrics that are emitted by default MUST be always kept up-to-date with the latest stable version of the \nmonitored system. Given that, occasional breaking changes in the emitted metrics are expected even in the stable \nreceivers. Any breaking change MUST be applied following [the deprecation process](#changing-the-emitted-metrics).\n\n## Stability levels for metrics and attributes\n\nSee [Collector's Telemetry Stability levels](./coding-guidelines.md#telemetry-stability-levels)\n\n## Changing the emitted metrics\n\nSome changes are not considered breaking and can be applied to metrics emitted by scraping receivers of any \nstability level:\n\n- Adding a new optional metric.\n\nMost of other changes to the emitted metrics are considered breaking and MUST be handled according to the stability \nlevel of the receiver. Each type of breaking change defines a set of steps that MUST (or SHOULD) be applied across \nseveral releases for a Stable (or Beta) components. At least 3 versions SHOULD be kept between the steps to give \nusers time to prepare, e.g. if the first step is released in v0.62.0, the second step SHOULD be released not earlier\nthan 0.65.0. Any warnings SHOULD include the version starting from which the next step will take effect. If a \nbreaking change is more complicated and many metrics are involved in the change, feature gates SHOULD be used instead.\n\n### Removing an optional metric\n\nSteps to remove an optional metric:\n\n1. Mark the metric as deprecated in `metadata.yaml` by adding \"[DEPRECATED]\" in its description. Show a warning that \n   the metric will be removed if the `enabled` option is set explicitly to `true` in user settings. \n2. Remove the metric.\n\n### Removing a default metric\n\nSteps to remove a default metric:\n\n1. Mark the metric as deprecated in `metadata.yaml` by adding \"[DEPRECATED]\" in its description. Show a warning that\n   the metric will be removed if the `enabled` option is not explicitly set to `false` in user settings.\n2. Make the metric optional. Show a warning that the metric will be removed if the `enabled` option is set to `true`\n   in user settings.\n3. Remove the metric.\n\n### Making a default metric optional\n\nSteps to turn a metric from default to optional:\n\n1. Add a warning that the metric will be turned into optional if `enabled` field is not set explicitly to any value in\n   user settings. Warning example: \"WARNING: Metric `foo.bar` will be disabled by default in v0.65.0. If you want to\n   keep it, please enable it explicitly in the receiver settings.\"\n2. Remove the warning and update `metadata.yaml` to make the metric optional.\n\n### Adding a new default metric or turning an existing optional metric into default\n\nAdding a new default metric is a breaking change for a scraping receiver because it introduces an unexpected output\nfor users and additional load on metric backends. Steps to apply such a change:\n\n1. If the metric doesn't exist yet, add one as an optional metric. Add a warning that the metric will be turned into \n   default if the `enabled` option is not set explicitly to any value in user settings. A warning example: \"WARNING: \n   Metric `foo.bar` will be enabled by default in v0.65.0. If you don't want the metric to be emitted, please\n   disable it in the receiver settings.\"\n2. Remove the warning and update `metadata.yaml` to make the metric default.\n\n### Other changes\n\nOther breaking changes SHOULD follow similar strategies inspecting presence of `enabled` field in user settings. For\nexample, if a metric has to be renamed for any reason, the guidelines for \"Removing an optional metric\" and \"Adding a  \nnew default metric\" SHOULD be followed simultaneously.\n\nBreaking changes that cannot be done through enabling/disabling metrics (e.g. removing or adding an extra attribute)\nSHOULD be applied using a feature gate with the following steps:\n\n1. Add a feature gate that is disabled by default. Enabling the feature gate changes the metrics behavior in a desired \n   way. For example, if several metrics emitted by host metrics receiver need to be updated to have an additional \n   `direction` attribute, the following feature gate can be used:\n  `receiver.hostmetricsreceiver.emitMetricsWithDirectionAttribute`. Show user a warning if the feature gate is not \n   enabled explicitly, for example: \"[WARNING] Metrics `system.network.packets` and `system.network.errors` will be \n   changed in v0.65.0 to emit an additional `direction` attribute, enable a feature gate\n   `receiver.hostmetricsreceiver.emitMetricsWithDirectionAttribute` to apply and test the upcoming changes earlier\".\n2. Enable the feature gate by default and update the warning thrown if user disables the feature gate explicitly. \n3. Remove the feature gate along with the old behavior.\n"
  },
  {
    "path": "docs/security-best-practices.md",
    "content": "# Security\n\nThe OpenTelemetry Collector defaults to operating in a secure manner but is\nconfiguration driven. This document captures important security aspects and\nconsiderations for the Collector. This document is intended for component\ndevelopers. It assumes at least a basic understanding of the Collector\narchitecture and functionality.\n\n> Note: Please review the\n> [configuration documentation](https://opentelemetry.io/docs/collector/configuration/)\n> prior to this security document.\n\nSecurity documentation for end users can be found on the OpenTelemetry\ndocumentation website:\n\n- [Collector configuration best practices](https://opentelemetry.io/docs/security/config-best-practices/)\n- [Collector hosting best practices](https://opentelemetry.io/docs/security/hosting-best-practices/)\n\n## TL;DR\n\n- Configuration\n  - MUST come from the central configuration file\n  - SHOULD use configuration helpers\n- Permissions\n  - SHOULD minimize privileged access\n  - MUST document what requires privileged access and why\n- Receivers/Exporters\n  - MUST default to encrypted connections\n  - SHOULD leverage helper functions\n- Extensions\n  - SHOULD NOT expose sensitive health or telemetry data by default\n\n> For more information about securing the OpenTelemetry Collector, see\n> [this blog post](https://medium.com/opentelemetry/securing-your-opentelemetry-collector-1a4f9fa5bd6f).\n\n## Configuration\n\nThe Collector binary does not contain an embedded or default configuration and\nMUST NOT start without a configuration file being specified. The configuration\nfile passed to the Collector MUST be validated prior to being loaded. If an\ninvalid configuration is detected, the Collector MUST fail to start as a\nprotective mechanism.\n\nComponent developers MUST get configuration information from the Collector's\nconfiguration file. Component developers SHOULD leverage\n[configuration helper functions](https://github.com/open-telemetry/opentelemetry-collector/tree/main/config).\n\nWhen defining Go structs for configuration data that may contain sensitive\ninformation, use the `configopaque` package to define fields with the\n`configopaque.String` type. This ensures that the data is masked when serialized\nto prevent accidental exposure.\n\n> For more information, see the\n> [configopaque](https://pkg.go.dev/go.opentelemetry.io/collector/config/configopaque)\n> documentation.\n\n## Permissions\n\nThe Collector supports running as a custom user and SHOULD NOT be run as a\nroot/admin user. For the majority of use-cases, the Collector SHOULD NOT require\nprivileged access to function. Some components MAY require privileged access or\nexternal permissions, including network access or RBAC.\n\nComponent developers SHOULD minimize privileged access requirements and MUST\ndocument what requires privileged access and why.\n\n## Receivers and Exporters\n\nReceivers and Exporters can be either push or pull-based. In either case, the\nconnection established SHOULD be over a secure and authenticated channel.\n\nComponent developers MUST default to encrypted connections (using the\n`insecure: false` configuration setting) and SHOULD leverage\n[gRPC](https://github.com/open-telemetry/opentelemetry-collector/tree/main/config/configgrpc)\nand\n[http](https://github.com/open-telemetry/opentelemetry-collector/tree/main/config/confighttp)\nhelper functions.\n\n## Safeguards against denial of service attacks\n\nSee the [Collector configuration security documentation](https://opentelemetry.io/docs/security/config-best-practices/#protect-against-denial-of-service-attacks) to learn how to safeguard against denial of service attacks. \n\n## Extensions\n\nComponent developers SHOULD NOT expose health or telemetry data outside the\nCollector by default.\n"
  },
  {
    "path": "docs/standard-warnings.md",
    "content": "# Standard Warnings\nSome components have scenarios that could cause issues.  Some components require the collector be interacted with in a specific way in order to ensure the component works as intended. This document describes common warnings that may affect a component in the collector. \n\nVisit a component's README to see if it is affected by any of these standard warnings.\n\n## Unsound Transformations\nIncorrect usage of the component may lead to telemetry data that is unsound i.e. not spec-compliant/meaningless.  This would most likely be caused by converting metric data types or creating new metrics from existing metrics.\n\n## Statefulness\nThe component keeps state related to telemetry data and therefore needs all data from a producer to be sent to the same Collector instance to ensure a correct behavior. Examples of scenarios that require state would be computing/exporting delta metrics, tail-based sampling and grouping telemetry.\n\n## Identity Conflict\nThe component may change the [identity of a metric](https://github.com/open-telemetry/opentelemetry-specification/blob/main//specification/metrics/data-model.md#opentelemetry-protocol-data-model-producer-recommendations) or the [identity of a timeseries](https://github.com/open-telemetry/opentelemetry-specification/blob/main//specification/metrics/data-model.md#timeseries-model). This could be done by modifying the metric/timeseries's name, attributes, or instrumentation scope. Modifying a metric/timeseries's identity could result in a metric/timeseries identity conflict, which caused by two metrics/timeseries sharing the same name, attributes, and instrumentation scope.\n\n## Orphaned Telemetry\nThe component modifies the incoming telemetry in such a way that a span becomes orphaned, that is, it contains a `trace_id` or `parent_span_id` that does not exist.  This may occur because the component can modify `span_id`, `trace_id`, or `parent_span_id` or because the component can delete telemetry.  "
  },
  {
    "path": "docs/vision.md",
    "content": "# OpenTelemetry Collector Long-term Vision\n\nThe following are high-level items that define our long-term vision for OpenTelemetry Collector, what we aspire to achieve. This vision is our daily guidance when we design new features and make changes to the Collector.\n\nThis is a living document that is expected to evolve over time.\n\n## Performant\nHighly stable and performant under varying loads. Well-behaved under extreme load, with predictable, low resource consumption.\n\n## Observable\nExpose own operational metrics in a clear way. Be an exemplar of observable service. Allow configuring the level of observability (more or less metrics, traces, logs, etc reported). See [more details](https://opentelemetry.io/docs/collector/internal-telemetry/).\n\n## Multi-Data\nSupport traces, metrics, logs and other relevant data types.\n\n## Usable Out of the Box\nReasonable default configuration, supports popular protocols, runs and collects out of the box.\n\n## Extensible\nExtensible and customizable without touching the core code. Can create custom agents based on the core and extend with own components. Welcoming 3rd party contribution policy.\n\n## Unified Codebase\nOne codebase for daemon (Agent) and standalone service (Collector).\n"
  },
  {
    "path": "examples/README.md",
    "content": "# Examples\n\nInformation on how the examples can be used can be found in the [Getting\nStarted\ndocumentation](https://opentelemetry.io/docs/collector/getting-started/).\n"
  },
  {
    "path": "examples/k8s/otel-config.yaml",
    "content": "---\napiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: otel-agent-conf\n  labels:\n    app: opentelemetry\n    component: otel-agent-conf\ndata:\n  otel-agent-config: |\n    receivers:\n      otlp:\n        protocols:\n          grpc:\n            endpoint: ${env:MY_POD_IP}:4317\n          http:\n            endpoint: ${env:MY_POD_IP}:4318\n    exporters:\n      otlp_grpc:\n        endpoint: \"otel-collector.default:4317\"\n        tls:\n          insecure: true\n        sending_queue:\n          num_consumers: 4\n          queue_size: 100\n        retry_on_failure:\n          enabled: true\n    processors:\n      memory_limiter:\n        # 80% of maximum memory up to 2G\n        limit_mib: 400\n        # 25% of limit up to 2G\n        spike_limit_mib: 100\n        check_interval: 5s\n    extensions:\n      zpages: {}\n    service:\n      extensions: [zpages]\n      pipelines:\n        traces:\n          receivers: [otlp]\n          processors: [memory_limiter]\n          exporters: [otlp]\n---\napiVersion: apps/v1\nkind: DaemonSet\nmetadata:\n  name: otel-agent\n  labels:\n    app: opentelemetry\n    component: otel-agent\nspec:\n  selector:\n    matchLabels:\n      app: opentelemetry\n      component: otel-agent\n  template:\n    metadata:\n      labels:\n        app: opentelemetry\n        component: otel-agent\n    spec:\n      containers:\n      - command:\n          - \"/otelcol\"\n          - \"--config=/conf/otel-agent-config.yaml\"\n        image: otel/opentelemetry-collector:latest\n        name: otel-agent\n        resources:\n          limits:\n            cpu: 500m\n            memory: 500Mi\n          requests:\n            cpu: 100m\n            memory: 100Mi\n        ports:\n        - containerPort: 55679 # ZPages endpoint.\n        - containerPort: 4317 # Default OpenTelemetry receiver port.\n        - containerPort: 8888  # Metrics.\n        env:\n          - name: MY_POD_IP\n            valueFrom:\n              fieldRef:\n                apiVersion: v1\n                fieldPath: status.podIP\n          - name: GOMEMLIMIT\n            value: 400MiB\n        volumeMounts:\n        - name: otel-agent-config-vol\n          mountPath: /conf\n      volumes:\n        - configMap:\n            name: otel-agent-conf\n            items:\n              - key: otel-agent-config\n                path: otel-agent-config.yaml\n          name: otel-agent-config-vol\n---\napiVersion: v1\nkind: ConfigMap\nmetadata:\n  name: otel-collector-conf\n  labels:\n    app: opentelemetry\n    component: otel-collector-conf\ndata:\n  otel-collector-config: |\n    receivers:\n      otlp:\n        protocols:\n          grpc:\n            endpoint: ${env:MY_POD_IP}:4317\n          http:\n            endpoint: ${env:MY_POD_IP}:4318\n    processors:\n      memory_limiter:\n        # 80% of maximum memory up to 2G\n        limit_mib: 1500\n        # 25% of limit up to 2G\n        spike_limit_mib: 512\n        check_interval: 5s\n    extensions:\n      zpages: {}\n    exporters:\n      otlp_grpc:\n        endpoint: \"http://someotlp.target.com:4317\" # Replace with a real endpoint.\n        tls:\n          insecure: true\n    service:\n      extensions: [zpages]\n      pipelines:\n        traces/1:\n          receivers: [otlp]\n          processors: [memory_limiter]\n          exporters: [otlp]\n---\napiVersion: v1\nkind: Service\nmetadata:\n  name: otel-collector\n  labels:\n    app: opentelemetry\n    component: otel-collector\nspec:\n  ports:\n  - name: otlp-grpc # Default endpoint for OpenTelemetry gRPC receiver.\n    port: 4317\n    protocol: TCP\n    targetPort: 4317\n  - name: otlp-http # Default endpoint for OpenTelemetry HTTP receiver.\n    port: 4318\n    protocol: TCP\n    targetPort: 4318\n  - name: metrics # Default endpoint for querying metrics.\n    port: 8888\n  selector:\n    component: otel-collector\n---\napiVersion: apps/v1\nkind: Deployment\nmetadata:\n  name: otel-collector\n  labels:\n    app: opentelemetry\n    component: otel-collector\nspec:\n  selector:\n    matchLabels:\n      app: opentelemetry\n      component: otel-collector\n  minReadySeconds: 5\n  progressDeadlineSeconds: 120\n  replicas: 1 #TODO - adjust this to your own requirements\n  template:\n    metadata:\n      labels:\n        app: opentelemetry\n        component: otel-collector\n    spec:\n      containers:\n      - command:\n          - \"/otelcol\"\n          - \"--config=/conf/otel-collector-config.yaml\"\n        image: otel/opentelemetry-collector:latest\n        name: otel-collector\n        resources:\n          limits:\n            cpu: 1\n            memory: 2Gi\n          requests:\n            cpu: 200m\n            memory: 400Mi\n        ports:\n        - containerPort: 55679 # Default endpoint for ZPages.\n        - containerPort: 4317 # Default endpoint for OpenTelemetry receiver.\n        - containerPort: 14250 # Default endpoint for Jaeger gRPC receiver.\n        - containerPort: 14268 # Default endpoint for Jaeger HTTP receiver.\n        - containerPort: 9411 # Default endpoint for Zipkin receiver.\n        - containerPort: 8888  # Default endpoint for querying metrics.\n        env:\n          - name: MY_POD_IP\n            valueFrom:\n              fieldRef:\n                apiVersion: v1\n                fieldPath: status.podIP\n          - name: GOMEMLIMIT\n            value: 1600MiB\n        volumeMounts:\n        - name: otel-collector-config-vol\n          mountPath: /conf\n#        - name: otel-collector-secrets\n#          mountPath: /secrets\n      volumes:\n        - configMap:\n            name: otel-collector-conf\n            items:\n              - key: otel-collector-config\n                path: otel-collector-config.yaml\n          name: otel-collector-config-vol\n#        - secret:\n#            name: otel-collector-secrets\n#            items:\n#              - key: cert.pem\n#                path: cert.pem\n#              - key: key.pem\n#                path: key.pem\n"
  },
  {
    "path": "examples/local/otel-config.yaml",
    "content": "extensions:\n  zpages:\n    endpoint: localhost:55679\n\nreceivers:\n  otlp:\n    protocols:\n      grpc:\n        endpoint: localhost:4317\n      http:\n        endpoint: localhost:4318\n\nprocessors:\n  memory_limiter:\n    # 75% of maximum memory up to 2G\n    limit_mib: 1536\n    # 25% of limit up to 2G\n    spike_limit_mib: 512\n    check_interval: 5s\n\nexporters:\n  debug:\n    verbosity: detailed\n\nservice:\n  pipelines:\n    traces:\n      receivers: [otlp]\n      processors: [memory_limiter]\n      exporters: [debug]\n    metrics:\n      receivers: [otlp]\n      processors: [memory_limiter]\n      exporters: [debug]\n    logs:\n      receivers: [otlp]\n      processors: [memory_limiter]\n      exporters: [debug]\n\n  extensions: [zpages]\n"
  },
  {
    "path": "exporter/Makefile",
    "content": "include ../Makefile.Common\n"
  },
  {
    "path": "exporter/README.md",
    "content": "# General Information\n\nAn exporter defines how the pipeline data leaves the collector.\n\nThis repository hosts the following exporters available in \ntraces, metrics and logs pipelines (sorted alphabetically):\n\n- [Debug](debugexporter/README.md)\n- [OTLP gRPC](otlpexporter/README.md)\n- [OTLP HTTP](otlphttpexporter/README.md)\n\nThe [contrib\nrepository](https://github.com/open-telemetry/opentelemetry-collector-contrib)\nhas more exporters available in its builds.\n\n## Configuring Exporters\n\nExporters are configured via YAML under the top-level `exporters` tag.\n\nThe following is a sample configuration for the `exampleexporter`.\n\n```yaml\nexporters:\n  # Exporter 1.\n  # <exporter type>:\n  exampleexporter:\n    # <setting one>: <value one>\n    endpoint: 1.2.3.4:8080\n    # ...\n  # Exporter 2.\n  # <exporter type>/<name>:\n  exampleexporter/settings:\n    # <setting two>: <value two>\n    endpoint: 0.0.0.0:9211\n```\n\nAn exporter instance is referenced by its full name in other parts of the config,\nsuch as in pipelines. A full name consists of the exporter type, '/' and the\nname appended to the exporter type in the configuration. All exporter full names\nmust be unique.\n\nFor the example above:\n\n- Exporter 1 has full name `exampleexporter`.\n- Exporter 2 has full name `exampleexporter/settings`.\n\nExporters are enabled upon being added to a pipeline. For example:\n\n```yaml\nservice:\n  pipelines:\n    # Valid pipelines are: traces, metrics or logs\n    # Trace pipeline 1.\n    traces:\n      receivers: [examplereceiver]\n      processors: []\n      exporters: [exampleexporter, exampleexporter/settings]\n    # Trace pipeline 2.\n    traces/another:\n      receivers: [examplereceiver]\n      processors: []\n      exporters: [exampleexporter, exampleexporter/settings]\n```\n\n## Data Ownership\n\nWhen multiple exporters are configured to send the same data (e.g. by configuring multiple\nexporters for the same pipeline):\n* exporters *not* configured to mutate the data will have shared access to the data\n* exporters with the Capabilities to mutate the data will receive a copy of the data\n\nExporters access export data when `ConsumeTraces`/`ConsumeMetrics`/`ConsumeLogs`\nfunction is called. Unless exporter's capabilities include mutation, the exporter MUST NOT modify the `pdata.Traces`/`pdata.Metrics`/`pdata.Logs` argument of\nthese functions. Any approach that does not mutate the original `pdata.Traces`/`pdata.Metrics`/`pdata.Logs` is allowed without the mutation capability.\n\n## Proxy Support\n\nBeyond standard YAML configuration as outlined in the individual READMEs above,\nexporters that leverage the net/http package (all do today) also respect the\nfollowing proxy environment variables:\n\n- HTTP_PROXY\n- HTTPS_PROXY\n- NO_PROXY\n\nIf set at Collector start time then exporters, regardless of protocol,\nwill or will not proxy traffic as defined by these environment variables.\n"
  },
  {
    "path": "exporter/debugexporter/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "exporter/debugexporter/README.md",
    "content": "<!-- status autogenerated section -->\n# Debug Exporter\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [alpha]: traces, metrics, logs, profiles   |\n| Distributions | [core], [contrib], [k8s] |\n| Warnings      | [Unstable Output Format](#warnings) |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Aexporter%2Fdebug%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Aexporter%2Fdebug) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Aexporter%2Fdebug%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Aexporter%2Fdebug) |\n| [Code Owners](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/CONTRIBUTING.md#becoming-a-code-owner)    | [@andrzej-stencel](https://www.github.com/andrzej-stencel) |\n\n[alpha]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#alpha\n[core]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n[k8s]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\n<!-- end autogenerated section -->\n\nOutputs telemetry data to the console for debugging purposes.\n\nSee also the [Troubleshooting][troubleshooting_docs] document for examples on using this exporter.\n\n[troubleshooting_docs]: https://opentelemetry.io/docs/collector/troubleshooting/#local-exporters\n\n## Getting Started\n\nThe following settings are optional:\n\n- `verbosity` (default = `basic`): the verbosity of the debug exporter: `basic`, `normal` or `detailed`.\n  See [Verbosity levels](#verbosity-levels) below for more information.\n- `sampling_initial` (default = `2`): number of messages initially logged each\n  second.\n- `sampling_thereafter` (default = `1`): sampling rate after the initial\n  messages are logged (every Mth message is logged).\n  The default value of `1` means that sampling is disabled.\n  To enable sampling, change `sampling_thereafter` to a value higher than `1`.\n  Refer to [Zap docs](https://godoc.org/go.uber.org/zap/zapcore#NewSampler) for more details\n  on how sampling parameters impact number of messages.\n- `use_internal_logger` (default = `true`): uses the collector's internal logger for output. See [below](#using-the-collectors-internal-logger) for description.\n- `output_paths` (default = `[\"stdout\"]`): a list of file paths to write output to. This option can only be used when `use_internal_logger` is `false`. Special strings \"stdout\" and \"stderr\" are interpreted as [standard output](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)) and [standard error](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)) respectively. All other values are treated as file paths. Setting `output_paths` when `use_internal_logger` is `true` results in a configuration error.\n- `sending_queue` (disabled by default): see [Sending Queue](../exporterhelper/README.md#sending-queue) for the full set of available options.\n\nExample configuration:\n\n```yaml\nexporters:\n  debug:\n    verbosity: detailed\n    sampling_initial: 5\n    sampling_thereafter: 200\n```\n\nExample configuration with custom output path:\n\n```yaml\nexporters:\n  debug:\n    use_internal_logger: false\n    output_paths:\n      - stderr\n```\n\n## Verbosity levels\n\nThe following subsections describe the output from the exporter depending on the configured verbosity level - `basic`, `normal` and `detailed`.\nThe default verbosity level is `basic`.\n\nTo understand how the below example output was generated, see [Generating example output](./generating-example-output.md).\n\n### Basic verbosity\n\nWith `verbosity: basic`, the exporter outputs a single-line summary of received data with a total count of telemetry records for every batch of received logs, metrics or traces.\n\nHere's an example output:\n\n```console\n2025-04-17T10:40:44.559+0200    info    Traces  {\"otelcol.component.id\": \"debug/basic\", \"otelcol.component.kind\": \"Exporter\", \"otelcol.signal\": \"traces\", \"resource spans\": 1, \"spans\": 2}\n```\n\n### Normal verbosity\n\nWith `verbosity: normal`, the exporter outputs about one line for each telemetry record.\nThe \"one line per telemetry record\" is not a strict rule.\nFor example, logs with multiline body will be output as multiple lines.\n\nHere's an example output:\n\n```console\n2025-05-09T19:57:16.332+0200    info    Traces  {\"resource\": {}, \"otelcol.component.id\": \"debug/normal\", \"otelcol.component.kind\": \"exporter\", \"otelcol.signal\": \"traces\", \"resource spans\": 1, \"spans\": 2}\n2025-05-09T19:57:16.332+0200    info    ResourceTraces #0 [https://opentelemetry.io/schemas/1.25.0] service.name=telemetrygen\nScopeTraces #0 telemetrygen\nokey-dokey-0 ab1030bd4ee554af936542b01d7b4807 1d8c93663d043aa8 net.sock.peer.addr=1.2.3.4 peer.service=telemetrygen-client\nlets-go ab1030bd4ee554af936542b01d7b4807 0d238e8a2f97733f net.sock.peer.addr=1.2.3.4 peer.service=telemetrygen-server\n        {\"resource\": {}, \"otelcol.component.id\": \"debug/normal\", \"otelcol.component.kind\": \"exporter\", \"otelcol.signal\": \"traces\"}\n```\n\n### Detailed verbosity\n\nWith `verbosity: detailed`, the exporter outputs all details of every telemetry record, typically writing multiple lines for every telemetry record.\n\nHere's an example output:\n\n```console\n2025-04-17T10:40:44.560+0200    info    Traces  {\"otelcol.component.id\": \"debug/detailed\", \"otelcol.component.kind\": \"Exporter\", \"otelcol.signal\": \"traces\", \"resource spans\": 1, \"spans\": 2}\n2025-04-17T10:40:44.560+0200    info    ResourceSpans #0\nResource SchemaURL: https://opentelemetry.io/schemas/1.25.0\nResource attributes:\n     -> service.name: Str(telemetrygen)\nScopeSpans #0\nScopeSpans SchemaURL: \nInstrumentationScope telemetrygen \nSpan #0\n    Trace ID       : fafdac970271dd2ce89de2442c0518c7\n    Parent ID      : d98de4cb8e2a0ad6\n    ID             : 3875f436d989d0e5\n    Name           : okey-dokey-0\n    Kind           : Server\n    Start time     : 2025-04-17 08:40:44.555461596 +0000 UTC\n    End time       : 2025-04-17 08:40:44.555584596 +0000 UTC\n    Status code    : Unset\n    Status message : \nAttributes:\n     -> net.sock.peer.addr: Str(1.2.3.4)\n     -> peer.service: Str(telemetrygen-client)\nSpan #1\n    Trace ID       : fafdac970271dd2ce89de2442c0518c7\n    Parent ID      : \n    ID             : d98de4cb8e2a0ad6\n    Name           : lets-go\n    Kind           : Client\n    Start time     : 2025-04-17 08:40:44.555461596 +0000 UTC\n    End time       : 2025-04-17 08:40:44.555584596 +0000 UTC\n    Status code    : Unset\n    Status message : \nAttributes:\n     -> net.sock.peer.addr: Str(1.2.3.4)\n     -> peer.service: Str(telemetrygen-server)\n        {\"otelcol.component.id\": \"debug/detailed\", \"otelcol.component.kind\": \"Exporter\", \"otelcol.signal\": \"traces\"}\n```\n\n## Using the collector's internal logger\n\nWhen `use_internal_logger` is set to `true` (the default), the exporter uses the collector's [internal logger][internal_telemetry] for output.\nThis comes with the following consequences:\n\n- The output from the exporter may be annotated by additional output from the collector's logger.\n- The output from the exporter is affected by the collector's [logging configuration][internal_logs_config] specified in `service::telemetry::logs`.\n\nWhen `use_internal_logger` is set to `false`, the exporter does not use the collector's internal logger.\nChanging the values in `service::telemetry::logs` has no effect on the exporter's output.\nThe exporter's output is sent to the paths specified in `output_paths` (default: `[\"stdout\"]`).\nYou can configure `output_paths` to send output to `stderr`, a file, or multiple destinations.\n\n[internal_telemetry]: https://opentelemetry.io/docs/collector/internal-telemetry/\n[internal_logs_config]: https://opentelemetry.io/docs/collector/internal-telemetry/#configure-internal-logs\n\n## Warnings\n\n- Unstable Output Format: The output formats for all verbosity levels is not guaranteed and may be changed at any time without a breaking change.\n"
  },
  {
    "path": "exporter/debugexporter/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage debugexporter // import \"go.opentelemetry.io/collector/exporter/debugexporter\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n)\n\n// supportedLevels in this exporter's configuration.\n// configtelemetry.LevelNone and other future values are not supported.\nvar supportedLevels map[configtelemetry.Level]struct{} = map[configtelemetry.Level]struct{}{\n\tconfigtelemetry.LevelBasic:    {},\n\tconfigtelemetry.LevelNormal:   {},\n\tconfigtelemetry.LevelDetailed: {},\n}\n\n// Config defines configuration for debug exporter.\ntype Config struct {\n\t// Verbosity defines the debug exporter verbosity.\n\tVerbosity configtelemetry.Level `mapstructure:\"verbosity,omitempty\"`\n\n\t// SamplingInitial defines how many samples are initially logged during each second.\n\tSamplingInitial int `mapstructure:\"sampling_initial\"`\n\n\t// SamplingThereafter defines the sampling rate after the initial samples are logged.\n\tSamplingThereafter int `mapstructure:\"sampling_thereafter\"`\n\n\t// UseInternalLogger defines whether the exporter sends the output to the collector's internal logger.\n\tUseInternalLogger bool `mapstructure:\"use_internal_logger\"`\n\n\t// OutputPaths is a list of file paths to write logging output to.\n\t// This option can only be used when use_internal_logger is false.\n\t// Special strings \"stdout\" and \"stderr\" are interpreted as os.Stdout and os.Stderr respectively.\n\t// All other values are treated as file paths.\n\t// If not set, defaults to [\"stdout\"].\n\tOutputPaths []string `mapstructure:\"output_paths\"`\n\n\tQueueConfig configoptional.Optional[exporterhelper.QueueBatchConfig] `mapstructure:\"sending_queue\"`\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\nvar _ component.Config = (*Config)(nil)\n\n// Validate checks if the exporter configuration is valid\nfunc (cfg *Config) Validate() error {\n\tif _, ok := supportedLevels[cfg.Verbosity]; !ok {\n\t\treturn fmt.Errorf(\"verbosity level %q is not supported\", cfg.Verbosity)\n\t}\n\n\t// output_paths is only used when use_internal_logger is false\n\t// If set when use_internal_logger is true, it would be ignored, which is confusing\n\tif cfg.UseInternalLogger && cfg.OutputPaths != nil {\n\t\treturn errors.New(\"output_paths is not supported when use_internal_logger is true\")\n\t}\n\n\t// If use_internal_logger is false and output_paths is explicitly set to empty, error\n\t// (nil output_paths will default to [\"stdout\"] in createCustomLogger)\n\tif !cfg.UseInternalLogger && cfg.OutputPaths != nil && len(cfg.OutputPaths) == 0 {\n\t\treturn errors.New(\"output_paths must not be empty when use_internal_logger is false\")\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "exporter/debugexporter/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage debugexporter\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n)\n\nfunc TestUnmarshalDefaultConfig(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, confmap.New().Unmarshal(&cfg))\n\tassert.Equal(t, factory.CreateDefaultConfig(), cfg)\n}\n\nfunc TestUnmarshalConfig(t *testing.T) {\n\ttests := []struct {\n\t\tfilename             string\n\t\tcfg                  *Config\n\t\texpectedUnmarshalErr string\n\t\texpectedValidateErr  string\n\t}{\n\t\t{\n\t\t\tfilename: \"config_verbosity.yaml\",\n\t\t\tcfg: &Config{\n\t\t\t\tVerbosity:          configtelemetry.LevelDetailed,\n\t\t\t\tSamplingInitial:    10,\n\t\t\t\tSamplingThereafter: 50,\n\t\t\t\tUseInternalLogger:  false,\n\t\t\t\tOutputPaths:        []string{\"stdout\"},\n\t\t\t\tQueueConfig:        configoptional.Default(exporterhelper.NewDefaultQueueConfig()),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tfilename: \"config_output_paths.yaml\",\n\t\t\tcfg: &Config{\n\t\t\t\tVerbosity:          configtelemetry.LevelBasic,\n\t\t\t\tSamplingInitial:    2,\n\t\t\t\tSamplingThereafter: 1,\n\t\t\t\tUseInternalLogger:  false,\n\t\t\t\tOutputPaths:        []string{\"stderr\"},\n\t\t\t\tQueueConfig:        configoptional.Default(exporterhelper.NewDefaultQueueConfig()),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tfilename:            \"config_output_paths_empty.yaml\",\n\t\t\texpectedValidateErr: \"output_paths must not be empty when use_internal_logger is false\",\n\t\t},\n\t\t{\n\t\t\tfilename:             \"config_verbosity_typo.yaml\",\n\t\t\texpectedUnmarshalErr: \"has invalid keys: verBosity\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.filename, func(t *testing.T) {\n\t\t\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", tt.filename))\n\t\t\trequire.NoError(t, err)\n\t\t\tfactory := NewFactory()\n\t\t\tcfg := factory.CreateDefaultConfig()\n\t\t\terr = cm.Unmarshal(&cfg)\n\t\t\tif tt.expectedUnmarshalErr != \"\" {\n\t\t\t\trequire.ErrorContains(t, err, tt.expectedUnmarshalErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\n\t\t\tcfgCasted := cfg.(*Config)\n\t\t\terr = cfgCasted.Validate()\n\t\t\tif tt.expectedValidateErr != \"\" {\n\t\t\t\trequire.ErrorContains(t, err, tt.expectedValidateErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tt.cfg, cfg)\n\t\t})\n\t}\n}\n\nfunc Test_UnmarshalMarshalled(t *testing.T) {\n\tfor name, tc := range map[string]struct {\n\t\tinCfg          *Config\n\t\texpectedConfig *Config\n\t\texpectedErr    string\n\t}{\n\t\t\"Base\": {\n\t\t\tinCfg:          &Config{},\n\t\t\texpectedConfig: &Config{},\n\t\t},\n\t\t\"VerbositySpecified\": {\n\t\t\tinCfg: &Config{\n\t\t\t\tVerbosity: configtelemetry.LevelDetailed,\n\t\t\t},\n\t\t\texpectedConfig: &Config{\n\t\t\t\tVerbosity: configtelemetry.LevelDetailed,\n\t\t\t},\n\t\t},\n\t} {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tconf := confmap.New()\n\t\t\terr := conf.Marshal(tc.inCfg)\n\t\t\trequire.NoError(t, err)\n\n\t\t\traw := conf.ToStringMap()\n\n\t\t\tconf = confmap.NewFromStringMap(raw)\n\n\t\t\toutCfg := &Config{}\n\n\t\t\terr = conf.Unmarshal(outCfg)\n\n\t\t\tif tc.expectedErr == \"\" {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.Equal(t, tc.expectedConfig, outCfg)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.Error(t, err)\n\t\t\tassert.EqualError(t, err, tc.expectedErr)\n\t\t})\n\t}\n}\n\nfunc TestValidate(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tcfg         *Config\n\t\texpectedErr string\n\t}{\n\t\t{\n\t\t\tname: \"verbosity none\",\n\t\t\tcfg: &Config{\n\t\t\t\tVerbosity: configtelemetry.LevelNone,\n\t\t\t},\n\t\t\texpectedErr: \"verbosity level \\\"None\\\" is not supported\",\n\t\t},\n\t\t{\n\t\t\tname: \"verbosity detailed\",\n\t\t\tcfg: &Config{\n\t\t\t\tVerbosity:         configtelemetry.LevelDetailed,\n\t\t\t\tUseInternalLogger: true, // Default behavior\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"empty output_paths when use_internal_logger is false\",\n\t\t\tcfg: &Config{\n\t\t\t\tUseInternalLogger: false,\n\t\t\t\tOutputPaths:       []string{},\n\t\t\t},\n\t\t\texpectedErr: \"output_paths must not be empty when use_internal_logger is false\",\n\t\t},\n\t\t{\n\t\t\tname: \"valid output_paths when use_internal_logger is false\",\n\t\t\tcfg: &Config{\n\t\t\t\tUseInternalLogger: false,\n\t\t\t\tOutputPaths:       []string{\"stdout\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"nil output_paths when use_internal_logger is false (defaults to stdout)\",\n\t\t\tcfg: &Config{\n\t\t\t\tUseInternalLogger: false,\n\t\t\t\tOutputPaths:       nil,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"output_paths set when use_internal_logger is true (not allowed)\",\n\t\t\tcfg: &Config{\n\t\t\t\tUseInternalLogger: true,\n\t\t\t\tOutputPaths:       []string{\"stderr\"},\n\t\t\t},\n\t\t\texpectedErr: \"output_paths is not supported when use_internal_logger is true\",\n\t\t},\n\t\t{\n\t\t\tname: \"nil output_paths when use_internal_logger is true (allowed)\",\n\t\t\tcfg: &Config{\n\t\t\t\tUseInternalLogger: true,\n\t\t\t\tOutputPaths:       nil,\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := tt.cfg.Validate()\n\t\t\tif tt.expectedErr != \"\" {\n\t\t\t\tassert.ErrorContains(t, err, tt.expectedErr)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "exporter/debugexporter/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\n// Package debugexporter exports data to console as logs.\npackage debugexporter // import \"go.opentelemetry.io/collector/exporter/debugexporter\"\n"
  },
  {
    "path": "exporter/debugexporter/exporter.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage debugexporter // import \"go.opentelemetry.io/collector/exporter/debugexporter\"\n\nimport (\n\t\"context\"\n\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/exporter/debugexporter/internal/normal\"\n\t\"go.opentelemetry.io/collector/exporter/debugexporter/internal/otlptext\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\ntype debugExporter struct {\n\tverbosity         configtelemetry.Level\n\tlogger            *zap.Logger\n\tlogsMarshaler     plog.Marshaler\n\tmetricsMarshaler  pmetric.Marshaler\n\ttracesMarshaler   ptrace.Marshaler\n\tprofilesMarshaler pprofile.Marshaler\n}\n\nfunc newDebugExporter(logger *zap.Logger, verbosity configtelemetry.Level) *debugExporter {\n\tvar logsMarshaler plog.Marshaler\n\tvar metricsMarshaler pmetric.Marshaler\n\tvar tracesMarshaler ptrace.Marshaler\n\tvar profilesMarshaler pprofile.Marshaler\n\tif verbosity == configtelemetry.LevelDetailed {\n\t\tlogsMarshaler = otlptext.NewTextLogsMarshaler()\n\t\tmetricsMarshaler = otlptext.NewTextMetricsMarshaler()\n\t\ttracesMarshaler = otlptext.NewTextTracesMarshaler()\n\t\tprofilesMarshaler = otlptext.NewTextProfilesMarshaler()\n\t} else {\n\t\tlogsMarshaler = normal.NewNormalLogsMarshaler()\n\t\tmetricsMarshaler = normal.NewNormalMetricsMarshaler()\n\t\ttracesMarshaler = normal.NewNormalTracesMarshaler()\n\t\tprofilesMarshaler = normal.NewNormalProfilesMarshaler()\n\t}\n\treturn &debugExporter{\n\t\tverbosity:         verbosity,\n\t\tlogger:            logger,\n\t\tlogsMarshaler:     logsMarshaler,\n\t\tmetricsMarshaler:  metricsMarshaler,\n\t\ttracesMarshaler:   tracesMarshaler,\n\t\tprofilesMarshaler: profilesMarshaler,\n\t}\n}\n\nfunc (s *debugExporter) pushTraces(_ context.Context, td ptrace.Traces) error {\n\ts.logger.Info(\"Traces\",\n\t\tzap.Int(\"resource spans\", td.ResourceSpans().Len()),\n\t\tzap.Int(\"spans\", td.SpanCount()))\n\tif s.verbosity == configtelemetry.LevelBasic {\n\t\treturn nil\n\t}\n\n\tbuf, err := s.tracesMarshaler.MarshalTraces(td)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.logger.Info(string(buf))\n\treturn nil\n}\n\nfunc (s *debugExporter) pushMetrics(_ context.Context, md pmetric.Metrics) error {\n\ts.logger.Info(\"Metrics\",\n\t\tzap.Int(\"resource metrics\", md.ResourceMetrics().Len()),\n\t\tzap.Int(\"metrics\", md.MetricCount()),\n\t\tzap.Int(\"data points\", md.DataPointCount()))\n\tif s.verbosity == configtelemetry.LevelBasic {\n\t\treturn nil\n\t}\n\n\tbuf, err := s.metricsMarshaler.MarshalMetrics(md)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.logger.Info(string(buf))\n\treturn nil\n}\n\nfunc (s *debugExporter) pushLogs(_ context.Context, ld plog.Logs) error {\n\ts.logger.Info(\"Logs\",\n\t\tzap.Int(\"resource logs\", ld.ResourceLogs().Len()),\n\t\tzap.Int(\"log records\", ld.LogRecordCount()))\n\n\tif s.verbosity == configtelemetry.LevelBasic {\n\t\treturn nil\n\t}\n\n\tbuf, err := s.logsMarshaler.MarshalLogs(ld)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.logger.Info(string(buf))\n\treturn nil\n}\n\nfunc (s *debugExporter) pushProfiles(_ context.Context, pd pprofile.Profiles) error {\n\ts.logger.Info(\"Profiles\",\n\t\tzap.Int(\"resource profiles\", pd.ResourceProfiles().Len()),\n\t\tzap.Int(\"sample records\", pd.SampleCount()))\n\n\tif s.verbosity == configtelemetry.LevelBasic {\n\t\treturn nil\n\t}\n\n\tbuf, err := s.profilesMarshaler.MarshalProfiles(pd)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.logger.Info(string(buf))\n\treturn nil\n}\n"
  },
  {
    "path": "exporter/debugexporter/exporter_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage debugexporter // import \"go.opentelemetry.io/collector/exporter/debugexporter\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap/zaptest\"\n\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/exporter/debugexporter/internal/metadata\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestTracesNoErrors(t *testing.T) {\n\tfor _, tc := range createTestCases() {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tlte, err := createTraces(context.Background(), exportertest.NewNopSettings(metadata.Type), tc.config)\n\t\t\trequire.NotNil(t, lte)\n\t\t\tassert.NoError(t, err)\n\n\t\t\tassert.NoError(t, lte.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n\t\t\tassert.NoError(t, lte.ConsumeTraces(context.Background(), testdata.GenerateTraces(10)))\n\n\t\t\tassert.NoError(t, lte.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nfunc TestMetricsNoErrors(t *testing.T) {\n\tfor _, tc := range createTestCases() {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tlme, err := createMetrics(context.Background(), exportertest.NewNopSettings(metadata.Type), tc.config)\n\t\t\trequire.NotNil(t, lme)\n\t\t\tassert.NoError(t, err)\n\n\t\t\tassert.NoError(t, lme.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n\t\t\tassert.NoError(t, lme.ConsumeMetrics(context.Background(), testdata.GenerateMetricsAllTypes()))\n\t\t\tassert.NoError(t, lme.ConsumeMetrics(context.Background(), testdata.GenerateMetricsAllTypesEmpty()))\n\t\t\tassert.NoError(t, lme.ConsumeMetrics(context.Background(), testdata.GenerateMetricsMetricTypeInvalid()))\n\t\t\tassert.NoError(t, lme.ConsumeMetrics(context.Background(), testdata.GenerateMetrics(10)))\n\n\t\t\tassert.NoError(t, lme.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nfunc TestLogsNoErrors(t *testing.T) {\n\tfor _, tc := range createTestCases() {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tlle, err := createLogs(context.Background(), exportertest.NewNopSettings(metadata.Type), tc.config)\n\t\t\trequire.NotNil(t, lle)\n\t\t\tassert.NoError(t, err)\n\n\t\t\tassert.NoError(t, lle.ConsumeLogs(context.Background(), plog.NewLogs()))\n\t\t\tassert.NoError(t, lle.ConsumeLogs(context.Background(), testdata.GenerateLogs(10)))\n\n\t\t\tassert.NoError(t, lle.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nfunc TestProfilesNoErrors(t *testing.T) {\n\tfor _, tc := range createTestCases() {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tlle, err := createProfiles(context.Background(), exportertest.NewNopSettings(metadata.Type), tc.config)\n\t\t\trequire.NotNil(t, lle)\n\t\t\tassert.NoError(t, err)\n\n\t\t\tassert.NoError(t, lle.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n\t\t\tassert.NoError(t, lle.ConsumeProfiles(context.Background(), testdata.GenerateProfiles(10)))\n\n\t\t\tassert.NoError(t, lle.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nfunc TestErrors(t *testing.T) {\n\tle := newDebugExporter(zaptest.NewLogger(t), configtelemetry.LevelDetailed)\n\trequire.NotNil(t, le)\n\n\terrWant := errors.New(\"my error\")\n\tle.tracesMarshaler = &errMarshaler{err: errWant}\n\tle.metricsMarshaler = &errMarshaler{err: errWant}\n\tle.logsMarshaler = &errMarshaler{err: errWant}\n\tle.profilesMarshaler = &errMarshaler{err: errWant}\n\tassert.Equal(t, errWant, le.pushTraces(context.Background(), ptrace.NewTraces()))\n\tassert.Equal(t, errWant, le.pushMetrics(context.Background(), pmetric.NewMetrics()))\n\tassert.Equal(t, errWant, le.pushLogs(context.Background(), plog.NewLogs()))\n\tassert.Equal(t, errWant, le.pushProfiles(context.Background(), pprofile.NewProfiles()))\n}\n\ntype testCase struct {\n\tname   string\n\tconfig *Config\n}\n\nfunc createTestCases() []testCase {\n\treturn []testCase{\n\t\t{\n\t\t\tname: \"default config\",\n\t\t\tconfig: func() *Config {\n\t\t\t\tc := createDefaultConfig().(*Config)\n\t\t\t\tc.QueueConfig = configoptional.Some(exporterhelper.NewDefaultQueueConfig())\n\t\t\t\tc.QueueConfig.Get().QueueSize = 10\n\t\t\t\treturn c\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"don't use internal logger\",\n\t\t\tconfig: func() *Config {\n\t\t\t\tcfg := createDefaultConfig().(*Config)\n\t\t\t\tcfg.QueueConfig = configoptional.Some(exporterhelper.NewDefaultQueueConfig())\n\t\t\t\tcfg.QueueConfig.Get().QueueSize = 10\n\t\t\t\tcfg.UseInternalLogger = false\n\t\t\t\treturn cfg\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"custom output paths\",\n\t\t\tconfig: func() *Config {\n\t\t\t\tcfg := createDefaultConfig().(*Config)\n\t\t\t\tqueueCfg := exporterhelper.NewDefaultQueueConfig()\n\t\t\t\tqueueCfg.QueueSize = 10\n\t\t\t\tcfg.QueueConfig = configoptional.Some(queueCfg)\n\t\t\t\tcfg.UseInternalLogger = false\n\t\t\t\tcfg.OutputPaths = []string{\"stderr\"}\n\t\t\t\treturn cfg\n\t\t\t}(),\n\t\t},\n\t}\n}\n\ntype errMarshaler struct {\n\terr error\n}\n\nfunc (e errMarshaler) MarshalLogs(plog.Logs) ([]byte, error) {\n\treturn nil, e.err\n}\n\nfunc (e errMarshaler) MarshalMetrics(pmetric.Metrics) ([]byte, error) {\n\treturn nil, e.err\n}\n\nfunc (e errMarshaler) MarshalTraces(ptrace.Traces) ([]byte, error) {\n\treturn nil, e.err\n}\n\nfunc (e errMarshaler) MarshalProfiles(pprofile.Profiles) ([]byte, error) {\n\treturn nil, e.err\n}\n"
  },
  {
    "path": "exporter/debugexporter/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage debugexporter // import \"go.opentelemetry.io/collector/exporter/debugexporter\"\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/debugexporter/internal/metadata\"\n\t\"go.opentelemetry.io/collector/exporter/debugexporter/internal/otlptext\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n)\n\n// The value of \"type\" key in configuration.\nvar componentType = component.MustNewType(\"debug\")\n\nconst (\n\tdefaultSamplingInitial    = 2\n\tdefaultSamplingThereafter = 1\n)\n\n// NewFactory creates and returns a new factory for the Debug exporter.\nfunc NewFactory() exporter.Factory {\n\treturn xexporter.NewFactory(\n\t\tcomponentType,\n\t\tcreateDefaultConfig,\n\t\txexporter.WithTraces(createTraces, metadata.TracesStability),\n\t\txexporter.WithMetrics(createMetrics, metadata.MetricsStability),\n\t\txexporter.WithLogs(createLogs, metadata.LogsStability),\n\t\txexporter.WithProfiles(createProfiles, metadata.ProfilesStability),\n\t)\n}\n\nfunc createDefaultConfig() component.Config {\n\treturn &Config{\n\t\tVerbosity:          configtelemetry.LevelBasic,\n\t\tSamplingInitial:    defaultSamplingInitial,\n\t\tSamplingThereafter: defaultSamplingThereafter,\n\t\tUseInternalLogger:  true,\n\t\tQueueConfig:        configoptional.Default(exporterhelper.NewDefaultQueueConfig()),\n\t}\n}\n\nfunc createTraces(ctx context.Context, set exporter.Settings, config component.Config) (exporter.Traces, error) {\n\tcfg := config.(*Config)\n\texporterLogger := createLogger(cfg, set.Logger)\n\tdebug := newDebugExporter(exporterLogger, cfg.Verbosity)\n\treturn exporterhelper.NewTraces(ctx, set, config,\n\t\tdebug.pushTraces,\n\t\texporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),\n\t\texporterhelper.WithQueue(cfg.QueueConfig),\n\t\texporterhelper.WithTimeout(exporterhelper.TimeoutConfig{Timeout: 0}),\n\t\texporterhelper.WithShutdown(otlptext.LoggerSync(exporterLogger)),\n\t)\n}\n\nfunc createMetrics(ctx context.Context, set exporter.Settings, config component.Config) (exporter.Metrics, error) {\n\tcfg := config.(*Config)\n\texporterLogger := createLogger(cfg, set.Logger)\n\tdebug := newDebugExporter(exporterLogger, cfg.Verbosity)\n\treturn exporterhelper.NewMetrics(ctx, set, config,\n\t\tdebug.pushMetrics,\n\t\texporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),\n\t\texporterhelper.WithQueue(cfg.QueueConfig),\n\t\texporterhelper.WithTimeout(exporterhelper.TimeoutConfig{Timeout: 0}),\n\t\texporterhelper.WithShutdown(otlptext.LoggerSync(exporterLogger)),\n\t)\n}\n\nfunc createLogs(ctx context.Context, set exporter.Settings, config component.Config) (exporter.Logs, error) {\n\tcfg := config.(*Config)\n\texporterLogger := createLogger(cfg, set.Logger)\n\tdebug := newDebugExporter(exporterLogger, cfg.Verbosity)\n\treturn exporterhelper.NewLogs(ctx, set, config,\n\t\tdebug.pushLogs,\n\t\texporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),\n\t\texporterhelper.WithQueue(cfg.QueueConfig),\n\t\texporterhelper.WithTimeout(exporterhelper.TimeoutConfig{Timeout: 0}),\n\t\texporterhelper.WithShutdown(otlptext.LoggerSync(exporterLogger)),\n\t)\n}\n\nfunc createProfiles(ctx context.Context, set exporter.Settings, config component.Config) (xexporter.Profiles, error) {\n\tcfg := config.(*Config)\n\texporterLogger := createLogger(cfg, set.Logger)\n\tdebug := newDebugExporter(exporterLogger, cfg.Verbosity)\n\treturn xexporterhelper.NewProfiles(ctx, set, config,\n\t\tdebug.pushProfiles,\n\t\texporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),\n\t\texporterhelper.WithQueue(cfg.QueueConfig),\n\t\texporterhelper.WithTimeout(exporterhelper.TimeoutConfig{Timeout: 0}),\n\t\texporterhelper.WithShutdown(otlptext.LoggerSync(exporterLogger)),\n\t)\n}\n\nfunc createLogger(cfg *Config, logger *zap.Logger) *zap.Logger {\n\tvar exporterLogger *zap.Logger\n\tif cfg.UseInternalLogger {\n\t\tcore := zapcore.NewSamplerWithOptions(\n\t\t\tlogger.Core(),\n\t\t\t1*time.Second,\n\t\t\tcfg.SamplingInitial,\n\t\t\tcfg.SamplingThereafter,\n\t\t)\n\t\texporterLogger = zap.New(core)\n\t} else {\n\t\texporterLogger = createCustomLogger(cfg)\n\t}\n\treturn exporterLogger\n}\n\nfunc createCustomLogger(exporterConfig *Config) *zap.Logger {\n\tencoderConfig := zap.NewDevelopmentEncoderConfig()\n\t// Do not prefix the output with log level (`info`)\n\tencoderConfig.LevelKey = \"\"\n\t// Do not prefix the output with current timestamp.\n\tencoderConfig.TimeKey = \"\"\n\toutputPaths := exporterConfig.OutputPaths\n\tif outputPaths == nil {\n\t\toutputPaths = []string{\"stdout\"}\n\t}\n\tzapConfig := zap.Config{\n\t\tLevel:         zap.NewAtomicLevelAt(zap.InfoLevel),\n\t\tDisableCaller: true,\n\t\tSampling: &zap.SamplingConfig{\n\t\t\tInitial:    exporterConfig.SamplingInitial,\n\t\t\tThereafter: exporterConfig.SamplingThereafter,\n\t\t},\n\t\tEncoding:      \"console\",\n\t\tEncoderConfig: encoderConfig,\n\t\tOutputPaths:   outputPaths,\n\t}\n\treturn zap.Must(zapConfig.Build())\n}\n"
  },
  {
    "path": "exporter/debugexporter/factory_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage debugexporter\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n)\n\nfunc TestCreateDefaultConfig(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tassert.NotNil(t, cfg, \"failed to create default config\")\n\trequire.NoError(t, componenttest.CheckConfigStruct(cfg))\n\n\tconfig := cfg.(*Config)\n\tassert.True(t, config.UseInternalLogger)\n\t// OutputPaths is nil by default (only used when UseInternalLogger is false,\n\t// where it defaults to [\"stdout\"] in createCustomLogger if not set)\n\tassert.Nil(t, config.OutputPaths)\n}\n\nfunc TestCreateMetrics(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\n\tme, err := factory.CreateMetrics(context.Background(), exportertest.NewNopSettings(factory.Type()), cfg)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, me)\n}\n\nfunc TestCreateTraces(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\n\tte, err := factory.CreateTraces(context.Background(), exportertest.NewNopSettings(factory.Type()), cfg)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, te)\n}\n\nfunc TestCreateLogs(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\n\tte, err := factory.CreateLogs(context.Background(), exportertest.NewNopSettings(factory.Type()), cfg)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, te)\n}\n\nfunc TestCreateFactoryProfiles(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\n\tte, err := factory.(xexporter.Factory).CreateProfiles(context.Background(), exportertest.NewNopSettings(factory.Type()), cfg)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, te)\n}\n\nfunc TestCreateCustomLogger(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\toutputPaths []string\n\t}{\n\t\t{\n\t\t\tname:        \"stdout\",\n\t\t\toutputPaths: []string{\"stdout\"},\n\t\t},\n\t\t{\n\t\t\tname:        \"stderr\",\n\t\t\toutputPaths: []string{\"stderr\"},\n\t\t},\n\t\t{\n\t\t\tname:        \"multiple paths\",\n\t\t\toutputPaths: []string{\"stdout\", \"stderr\"},\n\t\t},\n\t\t{\n\t\t\tname:        \"nil defaults to stdout\",\n\t\t\toutputPaths: nil,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tconfig := &Config{\n\t\t\t\tOutputPaths:        tt.outputPaths,\n\t\t\t\tSamplingInitial:    2,\n\t\t\t\tSamplingThereafter: 1,\n\t\t\t}\n\t\t\tlogger := createCustomLogger(config)\n\t\t\trequire.NotNil(t, logger)\n\t\t\tlogger.Info(\"test message\")\n\t\t\t// Sync may return an error for stdout/stderr in test environments\n\t\t\t_ = logger.Sync()\n\t\t})\n\t}\n}\n\nfunc TestCreateCustomLoggerWithFileOutput(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"Skipping on Windows due to file locking issues with t.TempDir() cleanup\")\n\t}\n\n\ttmpDir := t.TempDir()\n\tfilePath := filepath.Clean(filepath.Join(tmpDir, \"debug.log\"))\n\n\tconfig := &Config{\n\t\tOutputPaths:        []string{filePath},\n\t\tSamplingInitial:    2,\n\t\tSamplingThereafter: 1,\n\t}\n\n\tlogger := createCustomLogger(config)\n\trequire.NotNil(t, logger)\n\n\tlogger.Info(\"test message to file\")\n\trequire.NoError(t, logger.Sync())\n\n\t// Verify file was created and contains content\n\tcontent, err := os.ReadFile(filePath)\n\trequire.NoError(t, err)\n\tassert.Contains(t, string(content), \"test message to file\")\n}\n\nfunc TestCreateLogger(t *testing.T) {\n\ttests := []struct {\n\t\tname   string\n\t\tconfig *Config\n\t}{\n\t\t{\n\t\t\tname: \"use internal logger\",\n\t\t\tconfig: &Config{\n\t\t\t\tUseInternalLogger:  true,\n\t\t\t\tSamplingInitial:    2,\n\t\t\t\tSamplingThereafter: 1,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"use custom logger with stdout\",\n\t\t\tconfig: &Config{\n\t\t\t\tUseInternalLogger:  false,\n\t\t\t\tOutputPaths:        []string{\"stdout\"},\n\t\t\t\tSamplingInitial:    2,\n\t\t\t\tSamplingThereafter: 1,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"use custom logger with nil output paths defaults to stdout\",\n\t\t\tconfig: &Config{\n\t\t\t\tUseInternalLogger:  false,\n\t\t\t\tOutputPaths:        nil,\n\t\t\t\tSamplingInitial:    2,\n\t\t\t\tSamplingThereafter: 1,\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tbaseLogger := zap.NewNop()\n\t\t\tlogger := createLogger(tt.config, baseLogger)\n\t\t\trequire.NotNil(t, logger)\n\t\t\tlogger.Info(\"test message\")\n\t\t\t_ = logger.Sync()\n\t\t})\n\t}\n}\n\nfunc TestCreateLoggerWithInternalLogger(t *testing.T) {\n\tconfig := &Config{\n\t\tUseInternalLogger:  true,\n\t\tSamplingInitial:    10,\n\t\tSamplingThereafter: 50,\n\t\tVerbosity:          configtelemetry.LevelDetailed,\n\t}\n\n\tbaseLogger := zap.NewNop()\n\tlogger := createLogger(config, baseLogger)\n\trequire.NotNil(t, logger)\n\n\tlogger.Info(\"test message\")\n\t_ = logger.Sync()\n}\n"
  },
  {
    "path": "exporter/debugexporter/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage debugexporter\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nvar typ = component.MustNewType(\"debug\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct {\n\t\tcreateFn func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error)\n\t\tname     string\n\t}{\n\n\t\t{\n\t\t\tname: \"logs\",\n\t\t\tcreateFn: func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateLogs(ctx, set, cfg)\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg)\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"traces\",\n\t\t\tcreateFn: func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateTraces(ctx, set, cfg)\n\t\t\t},\n\t\t},\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name+\"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), exportertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\tt.Run(tt.name+\"-lifecycle\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), exportertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := newMdatagenNopHost()\n\t\t\terr = c.Start(context.Background(), host)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NotPanics(t, func() {\n\t\t\t\tswitch tt.name {\n\t\t\t\tcase \"logs\":\n\t\t\t\t\te, ok := c.(exporter.Logs)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tlogs := generateLifecycleTestLogs()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tlogs.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeLogs(context.Background(), logs)\n\t\t\t\tcase \"metrics\":\n\t\t\t\t\te, ok := c.(exporter.Metrics)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tmetrics := generateLifecycleTestMetrics()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tmetrics.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeMetrics(context.Background(), metrics)\n\t\t\t\tcase \"traces\":\n\t\t\t\t\te, ok := c.(exporter.Traces)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\ttraces := generateLifecycleTestTraces()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\ttraces.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeTraces(context.Background(), traces)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\trequire.NoError(t, err)\n\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t}\n}\n\nfunc generateLifecycleTestLogs() plog.Logs {\n\tlogs := plog.NewLogs()\n\trl := logs.ResourceLogs().AppendEmpty()\n\trl.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tl := rl.ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\tl.Body().SetStr(\"test log message\")\n\tl.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn logs\n}\n\nfunc generateLifecycleTestMetrics() pmetric.Metrics {\n\tmetrics := pmetric.NewMetrics()\n\trm := metrics.ResourceMetrics().AppendEmpty()\n\trm.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tm := rm.ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\tm.SetName(\"test_metric\")\n\tdp := m.SetEmptyGauge().DataPoints().AppendEmpty()\n\tdp.Attributes().PutStr(\"test_attr\", \"value_1\")\n\tdp.SetIntValue(123)\n\tdp.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn metrics\n}\n\nfunc generateLifecycleTestTraces() ptrace.Traces {\n\ttraces := ptrace.NewTraces()\n\trs := traces.ResourceSpans().AppendEmpty()\n\trs.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tspan := rs.ScopeSpans().AppendEmpty().Spans().AppendEmpty()\n\tspan.Attributes().PutStr(\"test_attr\", \"value_1\")\n\tspan.SetName(\"test_span\")\n\tspan.SetStartTimestamp(pcommon.NewTimestampFromTime(time.Now().Add(-1 * time.Second)))\n\tspan.SetEndTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn traces\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "exporter/debugexporter/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage debugexporter\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "exporter/debugexporter/generating-example-output.md",
    "content": "# Generating example output\n\nThis document describes how to generate the example output used in the [README](./README.md)'s [Verbosity levels](./README.md#verbosity-levels) section.\n\n1. Prepare the configuration of the Collector.\n\n   ```yaml\n   exporters:\n     debug/basic:\n       verbosity: basic\n     debug/normal:\n       verbosity: normal\n     debug/detailed:\n       verbosity: detailed\n\n   receivers:\n     otlp:\n       protocols:\n         grpc:\n\n   service:\n     pipelines:\n       traces:\n         exporters:\n           - debug/basic\n           - debug/normal\n           - debug/detailed\n         receivers:\n           - otlp\n   ```\n\n2. Run the Collector (download latest version from <https://github.com/open-telemetry/opentelemetry-collector-releases/releases>).\n\n   ```console\n   otelcol --config config.yaml\n   ```\n\n3. Run the `telemetrygen` tool (install latest version with `go install github.com/open-telemetry/opentelemetry-collector-contrib/cmd/telemetrygen@latest`).\n\n   ```console\n   telemetrygen traces --otlp-insecure\n   ```\n"
  },
  {
    "path": "exporter/debugexporter/go.mod",
    "content": "module go.opentelemetry.io/collector/exporter/debugexporter\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/config/configoptional v1.54.0\n\tgo.opentelemetry.io/collector/config/configtelemetry v0.148.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/exporter v1.54.0\n\tgo.opentelemetry.io/collector/exporter/exporterhelper v0.148.0\n\tgo.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper v0.148.0\n\tgo.opentelemetry.io/collector/exporter/exportertest v0.148.0\n\tgo.opentelemetry.io/collector/exporter/xexporter v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.opentelemetry.io/collector/pdata/xpdata v0.148.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/zap v1.27.1\n\tgolang.org/x/sys v0.42.0\n)\n\nrequire (\n\tgithub.com/cenkalti/backoff/v5 v5.0.3 // indirect\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/hashicorp/golang-lru/v2 v2.0.7 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/client v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configretry v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumererror/xconsumererror v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/xextension v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/receivertest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/exporter => ../\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/receiver => ../../receiver\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../../receiver/receivertest\n\nreplace go.opentelemetry.io/collector/extension => ../../extension\n\nreplace go.opentelemetry.io/collector/config/configtelemetry => ../../config/configtelemetry\n\nreplace go.opentelemetry.io/collector/config/configretry => ../../config/configretry\n\nreplace go.opentelemetry.io/collector/consumer/consumererror/xconsumererror => ../../consumer/consumererror/xconsumererror\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/exporter/xexporter => ../xexporter\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper => ../exporterhelper/xexporterhelper\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/exporter/exportertest => ../exportertest\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../../extension/extensiontest\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/extension/xextension => ../../extension/xextension\n\nreplace go.opentelemetry.io/collector/client => ../../client\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../../config/configoptional\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper => ../exporterhelper\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "exporter/debugexporter/go.sum",
    "content": "github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=\ngithub.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=\ngolang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "exporter/debugexporter/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"debug\")\n\tScopeName = \"go.opentelemetry.io/collector/exporter/debugexporter\"\n)\n\nconst (\n\tTracesStability   = component.StabilityLevelAlpha\n\tMetricsStability  = component.StabilityLevelAlpha\n\tLogsStability     = component.StabilityLevelAlpha\n\tProfilesStability = component.StabilityLevelAlpha\n)\n"
  },
  {
    "path": "exporter/debugexporter/internal/normal/common.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage normal // import \"go.opentelemetry.io/collector/exporter/debugexporter/internal/normal\"\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// writeAttributes returns a slice of strings in the form \"attrKey=attrValue\"\nfunc writeAttributes(attributes pcommon.Map) (attributeStrings []string) {\n\tfor k, v := range attributes.All() {\n\t\tattribute := fmt.Sprintf(\"%s=%s\", k, v.AsString())\n\t\tattributeStrings = append(attributeStrings, attribute)\n\t}\n\treturn attributeStrings\n}\n\n// writeAttributesString returns a string in the form \" attrKey=attrValue attr2=value2\"\nfunc writeAttributesString(attributesMap pcommon.Map) (attributesString string) {\n\tattributes := writeAttributes(attributesMap)\n\tif len(attributes) > 0 {\n\t\tattributesString = \" \" + strings.Join(attributes, \" \")\n\t}\n\treturn attributesString\n}\n\nfunc writeResourceDetails(schemaURL string) (resourceDetails string) {\n\tif schemaURL != \"\" {\n\t\tresourceDetails = \" [\" + schemaURL + \"]\"\n\t}\n\treturn resourceDetails\n}\n\nfunc writeScopeDetails(name, version, schemaURL string) (scopeDetails string) {\n\tif name != \"\" {\n\t\tscopeDetails += name\n\t}\n\tif version != \"\" {\n\t\tscopeDetails += \"@\" + version\n\t}\n\tif schemaURL != \"\" {\n\t\tif scopeDetails != \"\" {\n\t\t\tscopeDetails += \" \"\n\t\t}\n\t\tscopeDetails += \"[\" + schemaURL + \"]\"\n\t}\n\tif scopeDetails != \"\" {\n\t\tscopeDetails = \" \" + scopeDetails\n\t}\n\treturn scopeDetails\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/normal/logs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage normal // import \"go.opentelemetry.io/collector/exporter/debugexporter/internal/normal\"\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\ntype normalLogsMarshaler struct{}\n\n// Ensure normalLogsMarshaller implements interface plog.Marshaler\nvar _ plog.Marshaler = normalLogsMarshaler{}\n\n// NewNormalLogsMarshaler returns a plog.Marshaler for normal verbosity. It writes one line of text per log record\nfunc NewNormalLogsMarshaler() plog.Marshaler {\n\treturn normalLogsMarshaler{}\n}\n\nfunc (normalLogsMarshaler) MarshalLogs(ld plog.Logs) ([]byte, error) {\n\tvar buffer bytes.Buffer\n\tfor i := 0; i < ld.ResourceLogs().Len(); i++ {\n\t\tresourceLog := ld.ResourceLogs().At(i)\n\n\t\tbuffer.WriteString(fmt.Sprintf(\"ResourceLog #%d%s%s\\n\", i, writeResourceDetails(resourceLog.SchemaUrl()), writeAttributesString(resourceLog.Resource().Attributes())))\n\n\t\tfor j := 0; j < resourceLog.ScopeLogs().Len(); j++ {\n\t\t\tscopeLog := resourceLog.ScopeLogs().At(j)\n\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"ScopeLog #%d%s%s\\n\", i, writeScopeDetails(scopeLog.Scope().Name(), scopeLog.Scope().Version(), scopeLog.SchemaUrl()), writeAttributesString(scopeLog.Scope().Attributes())))\n\n\t\t\tfor k := 0; k < scopeLog.LogRecords().Len(); k++ {\n\t\t\t\tlogRecord := scopeLog.LogRecords().At(k)\n\t\t\t\tlogAttributes := writeAttributes(logRecord.Attributes())\n\n\t\t\t\tlogString := fmt.Sprintf(\"%s %s\", logRecord.Body().AsString(), strings.Join(logAttributes, \" \"))\n\t\t\t\tbuffer.WriteString(logString)\n\t\t\t\tbuffer.WriteString(\"\\n\")\n\t\t\t}\n\t\t}\n\t}\n\treturn buffer.Bytes(), nil\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/normal/logs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage normal\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\nfunc TestMarshalLogs(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    plog.Logs\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"empty logs\",\n\t\t\tinput:    plog.NewLogs(),\n\t\t\texpected: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"one log record\",\n\t\t\tinput: func() plog.Logs {\n\t\t\t\tlogs := plog.NewLogs()\n\t\t\t\tlogRecord := logs.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\t\t\t\tlogRecord.SetTimestamp(pcommon.NewTimestampFromTime(time.Date(2024, 1, 23, 17, 54, 41, 153, time.UTC)))\n\t\t\t\tlogRecord.SetSeverityNumber(plog.SeverityNumberInfo)\n\t\t\t\tlogRecord.SetSeverityText(\"INFO\")\n\t\t\t\tlogRecord.Body().SetStr(\"Single line log message\")\n\t\t\t\tlogRecord.Attributes().PutStr(\"key1\", \"value1\")\n\t\t\t\tlogRecord.Attributes().PutStr(\"key2\", \"value2\")\n\t\t\t\treturn logs\n\t\t\t}(),\n\t\t\texpected: `ResourceLog #0\nScopeLog #0\nSingle line log message key1=value1 key2=value2\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"one log record with resource and scope attributes\",\n\t\t\tinput: func() plog.Logs {\n\t\t\t\tlogs := plog.NewLogs()\n\t\t\t\tresourceLogs := logs.ResourceLogs().AppendEmpty()\n\t\t\t\tresourceLogs.SetSchemaUrl(\"https://opentelemetry.io/resource-schema-url\")\n\t\t\t\tresourceLogs.Resource().Attributes().PutStr(\"resourceKey1\", \"resourceValue1\")\n\t\t\t\tresourceLogs.Resource().Attributes().PutBool(\"resourceKey2\", false)\n\t\t\t\tscopeLogs := resourceLogs.ScopeLogs().AppendEmpty()\n\t\t\t\tscopeLogs.SetSchemaUrl(\"http://opentelemetry.io/scope-schema-url\")\n\t\t\t\tscopeLogs.Scope().SetName(\"scope-name\")\n\t\t\t\tscopeLogs.Scope().SetVersion(\"1.2.3\")\n\t\t\t\tscopeLogs.Scope().Attributes().PutStr(\"scopeKey1\", \"scopeValue1\")\n\t\t\t\tscopeLogs.Scope().Attributes().PutBool(\"scopeKey2\", true)\n\t\t\t\tlogRecord := scopeLogs.LogRecords().AppendEmpty()\n\t\t\t\tlogRecord.SetTimestamp(pcommon.NewTimestampFromTime(time.Date(2024, 1, 23, 17, 54, 41, 153, time.UTC)))\n\t\t\t\tlogRecord.SetSeverityNumber(plog.SeverityNumberInfo)\n\t\t\t\tlogRecord.SetSeverityText(\"INFO\")\n\t\t\t\tlogRecord.Body().SetStr(\"Single line log message\")\n\t\t\t\tlogRecord.Attributes().PutStr(\"key1\", \"value1\")\n\t\t\t\tlogRecord.Attributes().PutStr(\"key2\", \"value2\")\n\t\t\t\treturn logs\n\t\t\t}(),\n\t\t\texpected: `ResourceLog #0 [https://opentelemetry.io/resource-schema-url] resourceKey1=resourceValue1 resourceKey2=false\nScopeLog #0 scope-name@1.2.3 [http://opentelemetry.io/scope-schema-url] scopeKey1=scopeValue1 scopeKey2=true\nSingle line log message key1=value1 key2=value2\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"multiline log\",\n\t\t\tinput: func() plog.Logs {\n\t\t\t\tlogs := plog.NewLogs()\n\t\t\t\tlogRecord := logs.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\t\t\t\tlogRecord.SetTimestamp(pcommon.NewTimestampFromTime(time.Date(2024, 1, 23, 17, 54, 41, 153, time.UTC)))\n\t\t\t\tlogRecord.SetSeverityNumber(plog.SeverityNumberInfo)\n\t\t\t\tlogRecord.SetSeverityText(\"INFO\")\n\t\t\t\tlogRecord.Body().SetStr(\"First line of the log message\\n  second line of the log message\")\n\t\t\t\tlogRecord.Attributes().PutStr(\"key1\", \"value1\")\n\t\t\t\tlogRecord.Attributes().PutStr(\"key2\", \"value2\")\n\t\t\t\treturn logs\n\t\t\t}(),\n\t\t\texpected: `ResourceLog #0\nScopeLog #0\nFirst line of the log message\n  second line of the log message key1=value1 key2=value2\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"two log records\",\n\t\t\tinput: func() plog.Logs {\n\t\t\t\tlogs := plog.NewLogs()\n\t\t\t\tlogRecords := logs.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords()\n\n\t\t\t\tlogRecord := logRecords.AppendEmpty()\n\t\t\t\tlogRecord.SetTimestamp(pcommon.NewTimestampFromTime(time.Date(2024, 1, 23, 17, 54, 41, 153, time.UTC)))\n\t\t\t\tlogRecord.SetSeverityNumber(plog.SeverityNumberInfo)\n\t\t\t\tlogRecord.SetSeverityText(\"INFO\")\n\t\t\t\tlogRecord.Body().SetStr(\"Single line log message\")\n\t\t\t\tlogRecord.Attributes().PutStr(\"key1\", \"value1\")\n\t\t\t\tlogRecord.Attributes().PutStr(\"key2\", \"value2\")\n\n\t\t\t\tlogRecord = logRecords.AppendEmpty()\n\t\t\t\tlogRecord.Body().SetStr(\"Multi-line\\nlog message\")\n\t\t\t\tlogRecord.Attributes().PutStr(\"mykey2\", \"myvalue2\")\n\t\t\t\tlogRecord.Attributes().PutStr(\"mykey1\", \"myvalue1\")\n\t\t\t\treturn logs\n\t\t\t}(),\n\t\t\texpected: `ResourceLog #0\nScopeLog #0\nSingle line log message key1=value1 key2=value2\nMulti-line\nlog message mykey2=myvalue2 mykey1=myvalue1\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"log with maps in body and attributes\",\n\t\t\tinput: func() plog.Logs {\n\t\t\t\tlogs := plog.NewLogs()\n\t\t\t\tlogRecord := logs.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\t\t\t\tlogRecord.SetTimestamp(pcommon.NewTimestampFromTime(time.Date(2020, 2, 11, 20, 26, 13, 789, time.UTC)))\n\t\t\t\tlogRecord.SetSeverityNumber(plog.SeverityNumberInfo)\n\t\t\t\tlogRecord.SetSeverityText(\"INFO\")\n\t\t\t\tbody := logRecord.Body().SetEmptyMap()\n\t\t\t\tbody.PutStr(\"app\", \"CurrencyConverter\")\n\t\t\t\tbodyEvent := body.PutEmptyMap(\"event\")\n\t\t\t\tbodyEvent.PutStr(\"operation\", \"convert\")\n\t\t\t\tbodyEvent.PutStr(\"result\", \"success\")\n\t\t\t\tconversionAttr := logRecord.Attributes().PutEmptyMap(\"conversion\")\n\t\t\t\tconversionSourceAttr := conversionAttr.PutEmptyMap(\"source\")\n\t\t\t\tconversionSourceAttr.PutStr(\"currency\", \"USD\")\n\t\t\t\tconversionSourceAttr.PutDouble(\"amount\", 34.22)\n\t\t\t\tconversionDestinationAttr := conversionAttr.PutEmptyMap(\"destination\")\n\t\t\t\tconversionDestinationAttr.PutStr(\"currency\", \"EUR\")\n\t\t\t\tlogRecord.Attributes().PutStr(\"service\", \"payments\")\n\t\t\t\treturn logs\n\t\t\t}(),\n\t\t\texpected: `ResourceLog #0\nScopeLog #0\n{\"app\":\"CurrencyConverter\",\"event\":{\"operation\":\"convert\",\"result\":\"success\"}} conversion={\"destination\":{\"currency\":\"EUR\"},\"source\":{\"amount\":34.22,\"currency\":\"USD\"}} service=payments\n`,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\toutput, err := NewNormalLogsMarshaler().MarshalLogs(tt.input)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tt.expected, string(output))\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/normal/metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage normal // import \"go.opentelemetry.io/collector/exporter/debugexporter/internal/normal\"\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\ntype normalMetricsMarshaler struct{}\n\n// Ensure normalMetricsMarshaller implements interface pmetric.Marshaler\nvar _ pmetric.Marshaler = normalMetricsMarshaler{}\n\n// NewNormalMetricsMarshaler returns a pmetric.Marshaler for normal verbosity. It writes one line of text per log record\nfunc NewNormalMetricsMarshaler() pmetric.Marshaler {\n\treturn normalMetricsMarshaler{}\n}\n\nfunc (normalMetricsMarshaler) MarshalMetrics(md pmetric.Metrics) ([]byte, error) {\n\tvar buffer bytes.Buffer\n\tfor i := 0; i < md.ResourceMetrics().Len(); i++ {\n\t\tresourceMetrics := md.ResourceMetrics().At(i)\n\n\t\tbuffer.WriteString(fmt.Sprintf(\"ResourceMetrics #%d%s%s\\n\", i, writeResourceDetails(resourceMetrics.SchemaUrl()), writeAttributesString(resourceMetrics.Resource().Attributes())))\n\n\t\tfor j := 0; j < resourceMetrics.ScopeMetrics().Len(); j++ {\n\t\t\tscopeMetrics := resourceMetrics.ScopeMetrics().At(j)\n\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"ScopeMetrics #%d%s%s\\n\", i, writeScopeDetails(scopeMetrics.Scope().Name(), scopeMetrics.Scope().Version(), scopeMetrics.SchemaUrl()), writeAttributesString(scopeMetrics.Scope().Attributes())))\n\n\t\t\tfor k := 0; k < scopeMetrics.Metrics().Len(); k++ {\n\t\t\t\tmetric := scopeMetrics.Metrics().At(k)\n\n\t\t\t\tvar dataPointLines []string\n\t\t\t\tswitch metric.Type() {\n\t\t\t\tcase pmetric.MetricTypeGauge:\n\t\t\t\t\tdataPointLines = writeNumberDataPoints(metric, metric.Gauge().DataPoints())\n\t\t\t\tcase pmetric.MetricTypeSum:\n\t\t\t\t\tdataPointLines = writeNumberDataPoints(metric, metric.Sum().DataPoints())\n\t\t\t\tcase pmetric.MetricTypeHistogram:\n\t\t\t\t\tdataPointLines = writeHistogramDataPoints(metric)\n\t\t\t\tcase pmetric.MetricTypeExponentialHistogram:\n\t\t\t\t\tdataPointLines = writeExponentialHistogramDataPoints(metric)\n\t\t\t\tcase pmetric.MetricTypeSummary:\n\t\t\t\t\tdataPointLines = writeSummaryDataPoints(metric)\n\t\t\t\t}\n\t\t\t\tfor _, line := range dataPointLines {\n\t\t\t\t\tbuffer.WriteString(line)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn buffer.Bytes(), nil\n}\n\nfunc writeNumberDataPoints(metric pmetric.Metric, dataPoints pmetric.NumberDataPointSlice) (lines []string) {\n\tfor i := 0; i < dataPoints.Len(); i++ {\n\t\tdataPoint := dataPoints.At(i)\n\t\tdataPointAttributes := writeAttributes(dataPoint.Attributes())\n\n\t\tvar value string\n\t\tswitch dataPoint.ValueType() {\n\t\tcase pmetric.NumberDataPointValueTypeInt:\n\t\t\tvalue = strconv.FormatInt(dataPoint.IntValue(), 10)\n\t\tcase pmetric.NumberDataPointValueTypeDouble:\n\t\t\tvalue = fmt.Sprintf(\"%v\", dataPoint.DoubleValue())\n\t\t}\n\n\t\tdataPointLine := fmt.Sprintf(\"%s{%s} %s\\n\", metric.Name(), strings.Join(dataPointAttributes, \",\"), value)\n\t\tlines = append(lines, dataPointLine)\n\t}\n\treturn lines\n}\n\nfunc writeHistogramDataPoints(metric pmetric.Metric) (lines []string) {\n\tfor i := 0; i < metric.Histogram().DataPoints().Len(); i++ {\n\t\tdataPoint := metric.Histogram().DataPoints().At(i)\n\t\tdataPointAttributes := writeAttributes(dataPoint.Attributes())\n\n\t\tvar value strings.Builder\n\t\tfmt.Fprintf(&value, \"count=%d\", dataPoint.Count())\n\t\tif dataPoint.HasSum() {\n\t\t\tfmt.Fprintf(&value, \" sum=%v\", dataPoint.Sum())\n\t\t}\n\t\tif dataPoint.HasMin() {\n\t\t\tfmt.Fprintf(&value, \" min=%v\", dataPoint.Min())\n\t\t}\n\t\tif dataPoint.HasMax() {\n\t\t\tfmt.Fprintf(&value, \" max=%v\", dataPoint.Max())\n\t\t}\n\n\t\tfor bucketIndex := 0; bucketIndex < dataPoint.BucketCounts().Len(); bucketIndex++ {\n\t\t\tbucketBound := \"\"\n\t\t\tif bucketIndex < dataPoint.ExplicitBounds().Len() {\n\t\t\t\tbucketBound = fmt.Sprintf(\"le%v=\", dataPoint.ExplicitBounds().At(bucketIndex))\n\t\t\t}\n\t\t\tbucketCount := dataPoint.BucketCounts().At(bucketIndex)\n\t\t\tfmt.Fprintf(&value, \" %s%d\", bucketBound, bucketCount)\n\t\t}\n\n\t\tdataPointLine := fmt.Sprintf(\"%s{%s} %s\\n\", metric.Name(), strings.Join(dataPointAttributes, \",\"), value.String())\n\t\tlines = append(lines, dataPointLine)\n\t}\n\treturn lines\n}\n\nfunc writeExponentialHistogramDataPoints(metric pmetric.Metric) (lines []string) {\n\tfor i := 0; i < metric.ExponentialHistogram().DataPoints().Len(); i++ {\n\t\tdataPoint := metric.ExponentialHistogram().DataPoints().At(i)\n\t\tdataPointAttributes := writeAttributes(dataPoint.Attributes())\n\n\t\tvar value strings.Builder\n\t\tfmt.Fprintf(&value, \"count=%d\", dataPoint.Count())\n\t\tif dataPoint.HasSum() {\n\t\t\tfmt.Fprintf(&value, \" sum=%v\", dataPoint.Sum())\n\t\t}\n\t\tif dataPoint.HasMin() {\n\t\t\tfmt.Fprintf(&value, \" min=%v\", dataPoint.Min())\n\t\t}\n\t\tif dataPoint.HasMax() {\n\t\t\tfmt.Fprintf(&value, \" max=%v\", dataPoint.Max())\n\t\t}\n\n\t\tfactor := math.Ldexp(math.Ln2, -int(dataPoint.Scale()))\n\n\t\tnegB := dataPoint.Negative()\n\t\tfor j := negB.BucketCounts().Len() - 1; j >= 0; j-- {\n\t\t\tindex := float64(negB.Offset()) + float64(j)\n\t\t\tupperBound := -math.Exp(index * factor)\n\t\t\tfmt.Fprintf(&value, \" le%v=%d\", upperBound, negB.BucketCounts().At(j))\n\t\t}\n\n\t\tif dataPoint.ZeroCount() != 0 {\n\t\t\tfmt.Fprintf(&value, \" zero=%d\", dataPoint.ZeroCount())\n\t\t}\n\n\t\tposB := dataPoint.Positive()\n\t\tfor j := 0; j < posB.BucketCounts().Len(); j++ {\n\t\t\tindex := float64(posB.Offset()) + float64(j)\n\t\t\tupperBound := math.Exp((index + 1) * factor)\n\t\t\tfmt.Fprintf(&value, \" le%v=%d\", upperBound, posB.BucketCounts().At(j))\n\t\t}\n\n\t\tdataPointLine := fmt.Sprintf(\"%s{%s} %s\\n\", metric.Name(), strings.Join(dataPointAttributes, \",\"), value.String())\n\t\tlines = append(lines, dataPointLine)\n\t}\n\treturn lines\n}\n\nfunc writeSummaryDataPoints(metric pmetric.Metric) (lines []string) {\n\tfor i := 0; i < metric.Summary().DataPoints().Len(); i++ {\n\t\tdataPoint := metric.Summary().DataPoints().At(i)\n\t\tdataPointAttributes := writeAttributes(dataPoint.Attributes())\n\n\t\tvar value strings.Builder\n\t\tfmt.Fprintf(&value, \"count=%d\", dataPoint.Count())\n\t\tfmt.Fprintf(&value, \" sum=%f\", dataPoint.Sum())\n\n\t\tfor quantileIndex := 0; quantileIndex < dataPoint.QuantileValues().Len(); quantileIndex++ {\n\t\t\tquantile := dataPoint.QuantileValues().At(quantileIndex)\n\t\t\tfmt.Fprintf(&value, \" q%v=%v\", quantile.Quantile(), quantile.Value())\n\t\t}\n\n\t\tdataPointLine := fmt.Sprintf(\"%s{%s} %s\\n\", metric.Name(), strings.Join(dataPointAttributes, \",\"), value.String())\n\t\tlines = append(lines, dataPointLine)\n\t}\n\treturn lines\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/normal/metrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage normal\n\nimport (\n\t\"fmt\"\n\t\"math\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\nfunc TestMarshalMetrics(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    pmetric.Metrics\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"empty metrics\",\n\t\t\tinput:    pmetric.NewMetrics(),\n\t\t\texpected: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"sum data point\",\n\t\t\tinput: func() pmetric.Metrics {\n\t\t\t\tmetrics := pmetric.NewMetrics()\n\t\t\t\tmetric := metrics.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\t\t\t\tmetric.SetName(\"system.cpu.time\")\n\t\t\t\tdataPoint := metric.SetEmptySum().DataPoints().AppendEmpty()\n\t\t\t\tdataPoint.SetDoubleValue(123.456)\n\t\t\t\tdataPoint.Attributes().PutStr(\"state\", \"user\")\n\t\t\t\tdataPoint.Attributes().PutStr(\"cpu\", \"0\")\n\t\t\t\treturn metrics\n\t\t\t}(),\n\t\t\texpected: `ResourceMetrics #0\nScopeMetrics #0\nsystem.cpu.time{state=user,cpu=0} 123.456\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"data point with resource and scope attributes\",\n\t\t\tinput: func() pmetric.Metrics {\n\t\t\t\tmetrics := pmetric.NewMetrics()\n\t\t\t\tresourceMetrics := metrics.ResourceMetrics().AppendEmpty()\n\t\t\t\tresourceMetrics.SetSchemaUrl(\"https://opentelemetry.io/resource-schema-url\")\n\t\t\t\tresourceMetrics.Resource().Attributes().PutStr(\"resourceKey1\", \"resourceValue1\")\n\t\t\t\tresourceMetrics.Resource().Attributes().PutBool(\"resourceKey2\", false)\n\t\t\t\tscopeMetrics := resourceMetrics.ScopeMetrics().AppendEmpty()\n\t\t\t\tscopeMetrics.SetSchemaUrl(\"http://opentelemetry.io/scope-schema-url\")\n\t\t\t\tscopeMetrics.Scope().SetName(\"scope-name\")\n\t\t\t\tscopeMetrics.Scope().SetVersion(\"1.2.3\")\n\t\t\t\tscopeMetrics.Scope().Attributes().PutStr(\"scopeKey1\", \"scopeValue1\")\n\t\t\t\tscopeMetrics.Scope().Attributes().PutBool(\"scopeKey2\", true)\n\t\t\t\tmetric := scopeMetrics.Metrics().AppendEmpty()\n\t\t\t\tmetric.SetName(\"system.cpu.time\")\n\t\t\t\tdataPoint := metric.SetEmptySum().DataPoints().AppendEmpty()\n\t\t\t\tdataPoint.SetDoubleValue(123.456)\n\t\t\t\tdataPoint.Attributes().PutStr(\"state\", \"user\")\n\t\t\t\tdataPoint.Attributes().PutStr(\"cpu\", \"0\")\n\t\t\t\treturn metrics\n\t\t\t}(),\n\t\t\texpected: `ResourceMetrics #0 [https://opentelemetry.io/resource-schema-url] resourceKey1=resourceValue1 resourceKey2=false\nScopeMetrics #0 scope-name@1.2.3 [http://opentelemetry.io/scope-schema-url] scopeKey1=scopeValue1 scopeKey2=true\nsystem.cpu.time{state=user,cpu=0} 123.456\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"gauge data point\",\n\t\t\tinput: func() pmetric.Metrics {\n\t\t\t\tmetrics := pmetric.NewMetrics()\n\t\t\t\tmetric := metrics.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\t\t\t\tmetric.SetName(\"system.cpu.utilization\")\n\t\t\t\tdataPoint := metric.SetEmptyGauge().DataPoints().AppendEmpty()\n\t\t\t\tdataPoint.SetDoubleValue(78.901234567)\n\t\t\t\tdataPoint.Attributes().PutStr(\"state\", \"free\")\n\t\t\t\tdataPoint.Attributes().PutStr(\"cpu\", \"8\")\n\t\t\t\treturn metrics\n\t\t\t}(),\n\t\t\texpected: `ResourceMetrics #0\nScopeMetrics #0\nsystem.cpu.utilization{state=free,cpu=8} 78.901234567\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"histogram\",\n\t\t\tinput: func() pmetric.Metrics {\n\t\t\t\tmetrics := pmetric.NewMetrics()\n\t\t\t\tmetric := metrics.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\t\t\t\tmetric.SetName(\"http.server.request.duration\")\n\t\t\t\tdataPoint := metric.SetEmptyHistogram().DataPoints().AppendEmpty()\n\t\t\t\tdataPoint.Attributes().PutInt(\"http.response.status_code\", 200)\n\t\t\t\tdataPoint.Attributes().PutStr(\"http.request.method\", \"GET\")\n\t\t\t\tdataPoint.ExplicitBounds().FromRaw([]float64{0.125, 0.5, 1, 3})\n\t\t\t\tdataPoint.BucketCounts().FromRaw([]uint64{1324, 13, 0, 2, 1})\n\t\t\t\tdataPoint.SetCount(1340)\n\t\t\t\tdataPoint.SetSum(99.573)\n\t\t\t\tdataPoint.SetMin(0.017)\n\t\t\t\tdataPoint.SetMax(8.13)\n\t\t\t\treturn metrics\n\t\t\t}(),\n\t\t\texpected: `ResourceMetrics #0\nScopeMetrics #0\nhttp.server.request.duration{http.response.status_code=200,http.request.method=GET} count=1340 sum=99.573 min=0.017 max=8.13 le0.125=1324 le0.5=13 le1=0 le3=2 1\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"exponential histogram without buckets\",\n\t\t\tinput: func() pmetric.Metrics {\n\t\t\t\tmetrics := pmetric.NewMetrics()\n\t\t\t\tmetric := metrics.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\t\t\t\tmetric.SetName(\"http.server.request.duration\")\n\t\t\t\tdataPoint := metric.SetEmptyExponentialHistogram().DataPoints().AppendEmpty()\n\t\t\t\tdataPoint.Attributes().PutInt(\"http.response.status_code\", 200)\n\t\t\t\tdataPoint.Attributes().PutStr(\"http.request.method\", \"GET\")\n\t\t\t\tdataPoint.SetCount(1340)\n\t\t\t\tdataPoint.SetSum(99.573)\n\t\t\t\tdataPoint.SetMin(0.017)\n\t\t\t\tdataPoint.SetMax(8.13)\n\t\t\t\treturn metrics\n\t\t\t}(),\n\t\t\texpected: `ResourceMetrics #0\nScopeMetrics #0\nhttp.server.request.duration{http.response.status_code=200,http.request.method=GET} count=1340 sum=99.573 min=0.017 max=8.13\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"exponential histogram with buckets\",\n\t\t\tinput: func() pmetric.Metrics {\n\t\t\t\tmetrics := pmetric.NewMetrics()\n\t\t\t\tmetric := metrics.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\t\t\t\tmetric.SetName(\"http.server.request.duration\")\n\t\t\t\tdataPoint := metric.SetEmptyExponentialHistogram().DataPoints().AppendEmpty()\n\t\t\t\tdataPoint.Attributes().PutInt(\"http.response.status_code\", 200)\n\t\t\t\tdataPoint.Attributes().PutStr(\"http.request.method\", \"GET\")\n\t\t\t\tdataPoint.SetCount(1340)\n\t\t\t\tdataPoint.SetSum(99.573)\n\t\t\t\tdataPoint.SetMin(0.017)\n\t\t\t\tdataPoint.SetMax(8.13)\n\t\t\t\tdataPoint.SetScale(3)\n\t\t\t\tdataPoint.SetZeroCount(3)\n\t\t\t\tdataPoint.Negative().SetOffset(-2)\n\t\t\t\tdataPoint.Negative().BucketCounts().FromRaw([]uint64{10, 20})\n\t\t\t\tdataPoint.Positive().SetOffset(1)\n\t\t\t\tdataPoint.Positive().BucketCounts().FromRaw([]uint64{40, 50, 60})\n\t\t\t\treturn metrics\n\t\t\t}(),\n\t\t\texpected: func() string {\n\t\t\t\tf := math.Ldexp(math.Ln2, -3)\n\t\t\t\treturn fmt.Sprintf(\"ResourceMetrics #0\\nScopeMetrics #0\\n\"+\n\t\t\t\t\t\"http.server.request.duration{http.response.status_code=200,http.request.method=GET}\"+\n\t\t\t\t\t\" count=1340 sum=99.573 min=0.017 max=8.13\"+\n\t\t\t\t\t\" le%v=20 le%v=10 zero=3 le%v=40 le%v=50 le%v=60\\n\",\n\t\t\t\t\t-math.Exp(-1*f), -math.Exp(-2*f),\n\t\t\t\t\tmath.Exp(2*f), math.Exp(3*f), math.Exp(4*f))\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"exponential histogram with positive buckets only\",\n\t\t\tinput: func() pmetric.Metrics {\n\t\t\t\tmetrics := pmetric.NewMetrics()\n\t\t\t\tmetric := metrics.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\t\t\t\tmetric.SetName(\"latency\")\n\t\t\t\tdataPoint := metric.SetEmptyExponentialHistogram().DataPoints().AppendEmpty()\n\t\t\t\tdataPoint.SetCount(2)\n\t\t\t\tdataPoint.SetScale(1)\n\t\t\t\tdataPoint.Positive().SetOffset(1)\n\t\t\t\tdataPoint.Positive().BucketCounts().FromRaw([]uint64{1, 1})\n\t\t\t\treturn metrics\n\t\t\t}(),\n\t\t\texpected: func() string {\n\t\t\t\tf := math.Ldexp(math.Ln2, -1)\n\t\t\t\treturn fmt.Sprintf(\"ResourceMetrics #0\\nScopeMetrics #0\\n\"+\n\t\t\t\t\t\"latency{} count=2 le%v=1 le%v=1\\n\",\n\t\t\t\t\tmath.Exp(2*f), math.Exp(3*f))\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"summary\",\n\t\t\tinput: func() pmetric.Metrics {\n\t\t\t\tmetrics := pmetric.NewMetrics()\n\t\t\t\tmetric := metrics.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\t\t\t\tmetric.SetName(\"summary\")\n\t\t\t\tdataPoint := metric.SetEmptySummary().DataPoints().AppendEmpty()\n\t\t\t\tdataPoint.Attributes().PutInt(\"http.response.status_code\", 200)\n\t\t\t\tdataPoint.Attributes().PutStr(\"http.request.method\", \"GET\")\n\t\t\t\tdataPoint.SetCount(1340)\n\t\t\t\tdataPoint.SetSum(99.573)\n\t\t\t\tquantile := dataPoint.QuantileValues().AppendEmpty()\n\t\t\t\tquantile.SetQuantile(0.01)\n\t\t\t\tquantile.SetValue(15)\n\t\t\t\treturn metrics\n\t\t\t}(),\n\t\t\texpected: `ResourceMetrics #0\nScopeMetrics #0\nsummary{http.response.status_code=200,http.request.method=GET} count=1340 sum=99.573000 q0.01=15\n`,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\toutput, err := NewNormalMetricsMarshaler().MarshalMetrics(tt.input)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tt.expected, string(output))\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/normal/profiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage normal // import \"go.opentelemetry.io/collector/exporter/debugexporter/internal/normal\"\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n)\n\ntype normalProfilesMarshaler struct{}\n\n// Ensure normalProfilesMarshaller implements interface pprofile.Marshaler\nvar _ pprofile.Marshaler = normalProfilesMarshaler{}\n\n// NewNormalProfilesMarshaler returns a pprofile.Marshaler for normal verbosity. It writes one line of text per log record\nfunc NewNormalProfilesMarshaler() pprofile.Marshaler {\n\treturn normalProfilesMarshaler{}\n}\n\nfunc (normalProfilesMarshaler) MarshalProfiles(pd pprofile.Profiles) ([]byte, error) {\n\tvar buffer bytes.Buffer\n\tdic := pd.Dictionary()\n\n\tfor i := 0; i < pd.ResourceProfiles().Len(); i++ {\n\t\tresourceProfiles := pd.ResourceProfiles().At(i)\n\n\t\tbuffer.WriteString(fmt.Sprintf(\"ResourceProfiles #%d%s%s\\n\", i, writeResourceDetails(resourceProfiles.SchemaUrl()), writeAttributesString(resourceProfiles.Resource().Attributes())))\n\n\t\tfor j := 0; j < resourceProfiles.ScopeProfiles().Len(); j++ {\n\t\t\tscopeProfiles := resourceProfiles.ScopeProfiles().At(j)\n\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"ScopeProfiles #%d%s%s\\n\", i, writeScopeDetails(scopeProfiles.Scope().Name(), scopeProfiles.Scope().Version(), scopeProfiles.SchemaUrl()), writeAttributesString(scopeProfiles.Scope().Attributes())))\n\n\t\t\tfor k := 0; k < scopeProfiles.Profiles().Len(); k++ {\n\t\t\t\tprofile := scopeProfiles.Profiles().At(k)\n\n\t\t\t\tbuffer.WriteString(profile.ProfileID().String())\n\n\t\t\t\tbuffer.WriteString(\" samples=\")\n\t\t\t\tbuffer.WriteString(strconv.Itoa(profile.Samples().Len()))\n\n\t\t\t\tif profile.AttributeIndices().Len() > 0 {\n\t\t\t\t\tattrs := []string{}\n\t\t\t\t\tfor _, i := range profile.AttributeIndices().AsRaw() {\n\t\t\t\t\t\ta := dic.AttributeTable().At(int(i))\n\t\t\t\t\t\tattrs = append(attrs, fmt.Sprintf(\"%s=%s\", dic.StringTable().At(int(a.KeyStrindex())), a.Value().AsString()))\n\t\t\t\t\t}\n\n\t\t\t\t\tbuffer.WriteString(\" \")\n\t\t\t\t\tbuffer.WriteString(strings.Join(attrs, \" \"))\n\t\t\t\t}\n\n\t\t\t\tbuffer.WriteString(\"\\n\")\n\t\t\t}\n\t\t}\n\t}\n\treturn buffer.Bytes(), nil\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/normal/profiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage normal\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n)\n\nfunc TestMarshalProfiles(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    pprofile.Profiles\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"empty profile\",\n\t\t\tinput:    pprofile.NewProfiles(),\n\t\t\texpected: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"one profile\",\n\t\t\tinput: func() pprofile.Profiles {\n\t\t\t\tprofiles := pprofile.NewProfiles()\n\t\t\t\tdic := profiles.Dictionary()\n\t\t\t\tdic.StringTable().Append(\"\")\n\t\t\t\tdic.StringTable().Append(\"key1\")\n\n\t\t\t\ta := dic.AttributeTable().AppendEmpty()\n\t\t\t\ta.SetKeyStrindex(1)\n\t\t\t\ta.Value().SetStr(\"value1\")\n\n\t\t\t\tprofile := profiles.ResourceProfiles().AppendEmpty().ScopeProfiles().AppendEmpty().Profiles().AppendEmpty()\n\t\t\t\tprofiles.ResourceProfiles().At(0).SetSchemaUrl(\"https://example.com/resource\")\n\t\t\t\tprofiles.ResourceProfiles().At(0).Resource().Attributes().PutStr(\"resourceKey\", \"resourceValue\")\n\t\t\t\tprofiles.ResourceProfiles().At(0).ScopeProfiles().At(0).SetSchemaUrl(\"https://example.com/scope\")\n\t\t\t\tprofiles.ResourceProfiles().At(0).ScopeProfiles().At(0).Scope().SetName(\"scope-name\")\n\t\t\t\tprofiles.ResourceProfiles().At(0).ScopeProfiles().At(0).Scope().SetVersion(\"1.2.3\")\n\t\t\t\tprofiles.ResourceProfiles().At(0).ScopeProfiles().At(0).Scope().Attributes().PutStr(\"scopeKey\", \"scopeValue\")\n\t\t\t\tprofile.SetProfileID([16]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10})\n\t\t\t\tprofile.Samples().AppendEmpty()\n\t\t\t\tprofile.Samples().AppendEmpty()\n\t\t\t\tprofile.AttributeIndices().Append(0)\n\t\t\t\treturn profiles\n\t\t\t}(),\n\t\t\texpected: `ResourceProfiles #0 [https://example.com/resource] resourceKey=resourceValue\nScopeProfiles #0 scope-name@1.2.3 [https://example.com/scope] scopeKey=scopeValue\n0102030405060708090a0b0c0d0e0f10 samples=2 key1=value1\n`,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\toutput, err := NewNormalProfilesMarshaler().MarshalProfiles(tt.input)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tt.expected, string(output))\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/normal/traces.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage normal // import \"go.opentelemetry.io/collector/exporter/debugexporter/internal/normal\"\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\ntype normalTracesMarshaler struct{}\n\n// Ensure normalTracesMarshaller implements interface ptrace.Marshaler\nvar _ ptrace.Marshaler = normalTracesMarshaler{}\n\n// NewNormalTracesMarshaler returns a ptrace.Marshaler for normal verbosity. It writes one line of text per log record\nfunc NewNormalTracesMarshaler() ptrace.Marshaler {\n\treturn normalTracesMarshaler{}\n}\n\nfunc (normalTracesMarshaler) MarshalTraces(md ptrace.Traces) ([]byte, error) {\n\tvar buffer bytes.Buffer\n\tfor i := 0; i < md.ResourceSpans().Len(); i++ {\n\t\tresourceTraces := md.ResourceSpans().At(i)\n\n\t\tbuffer.WriteString(fmt.Sprintf(\"ResourceTraces #%d%s%s\\n\", i, writeResourceDetails(resourceTraces.SchemaUrl()), writeAttributesString(resourceTraces.Resource().Attributes())))\n\n\t\tfor j := 0; j < resourceTraces.ScopeSpans().Len(); j++ {\n\t\t\tscopeTraces := resourceTraces.ScopeSpans().At(j)\n\n\t\t\tbuffer.WriteString(fmt.Sprintf(\"ScopeTraces #%d%s%s\\n\", i, writeScopeDetails(scopeTraces.Scope().Name(), scopeTraces.Scope().Version(), scopeTraces.SchemaUrl()), writeAttributesString(scopeTraces.Scope().Attributes())))\n\n\t\t\tfor k := 0; k < scopeTraces.Spans().Len(); k++ {\n\t\t\t\tspan := scopeTraces.Spans().At(k)\n\n\t\t\t\tbuffer.WriteString(span.Name())\n\n\t\t\t\tbuffer.WriteString(\" \")\n\t\t\t\tbuffer.WriteString(span.TraceID().String())\n\n\t\t\t\tbuffer.WriteString(\" \")\n\t\t\t\tbuffer.WriteString(span.SpanID().String())\n\n\t\t\t\tif span.Attributes().Len() > 0 {\n\t\t\t\t\tspanAttributes := writeAttributes(span.Attributes())\n\t\t\t\t\tbuffer.WriteString(\" \")\n\t\t\t\t\tbuffer.WriteString(strings.Join(spanAttributes, \" \"))\n\t\t\t\t}\n\n\t\t\t\tbuffer.WriteString(\"\\n\")\n\t\t\t}\n\t\t}\n\t}\n\treturn buffer.Bytes(), nil\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/normal/traces_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage normal\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nfunc TestMarshalTraces(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    ptrace.Traces\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"empty traces\",\n\t\t\tinput:    ptrace.NewTraces(),\n\t\t\texpected: \"\",\n\t\t},\n\t\t{\n\t\t\tname: \"one span with resource and scope attributes\",\n\t\t\tinput: func() ptrace.Traces {\n\t\t\t\ttraces := ptrace.NewTraces()\n\t\t\t\tresourceSpans := traces.ResourceSpans().AppendEmpty()\n\t\t\t\tresourceSpans.SetSchemaUrl(\"https://opentelemetry.io/resource-schema-url\")\n\t\t\t\tresourceSpans.Resource().Attributes().PutStr(\"resourceKey1\", \"resourceValue1\")\n\t\t\t\tresourceSpans.Resource().Attributes().PutBool(\"resourceKey2\", false)\n\t\t\t\tscopeSpans := resourceSpans.ScopeSpans().AppendEmpty()\n\t\t\t\tscopeSpans.SetSchemaUrl(\"http://opentelemetry.io/scope-schema-url\")\n\t\t\t\tscopeSpans.Scope().SetName(\"scope-name\")\n\t\t\t\tscopeSpans.Scope().SetVersion(\"1.2.3\")\n\t\t\t\tscopeSpans.Scope().Attributes().PutStr(\"scopeKey1\", \"scopeValue1\")\n\t\t\t\tscopeSpans.Scope().Attributes().PutBool(\"scopeKey2\", true)\n\t\t\t\tspan := scopeSpans.Spans().AppendEmpty()\n\t\t\t\tspan.SetName(\"span-name\")\n\t\t\t\tspan.SetTraceID([16]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10})\n\t\t\t\tspan.SetSpanID([8]byte{0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18})\n\t\t\t\tspan.Attributes().PutStr(\"key1\", \"value1\")\n\t\t\t\tspan.Attributes().PutStr(\"key2\", \"value2\")\n\t\t\t\treturn traces\n\t\t\t}(),\n\t\t\texpected: `ResourceTraces #0 [https://opentelemetry.io/resource-schema-url] resourceKey1=resourceValue1 resourceKey2=false\nScopeTraces #0 scope-name@1.2.3 [http://opentelemetry.io/scope-schema-url] scopeKey1=scopeValue1 scopeKey2=true\nspan-name 0102030405060708090a0b0c0d0e0f10 1112131415161718 key1=value1 key2=value2\n`,\n\t\t},\n\t\t{\n\t\t\tname: \"one span\",\n\t\t\tinput: func() ptrace.Traces {\n\t\t\t\ttraces := ptrace.NewTraces()\n\t\t\t\tspan := traces.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty()\n\t\t\t\tspan.SetName(\"span-name\")\n\t\t\t\tspan.SetTraceID([16]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10})\n\t\t\t\tspan.SetSpanID([8]byte{0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18})\n\t\t\t\tspan.Attributes().PutStr(\"key1\", \"value1\")\n\t\t\t\tspan.Attributes().PutStr(\"key2\", \"value2\")\n\t\t\t\treturn traces\n\t\t\t}(),\n\t\t\texpected: `ResourceTraces #0\nScopeTraces #0\nspan-name 0102030405060708090a0b0c0d0e0f10 1112131415161718 key1=value1 key2=value2\n`,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\toutput, err := NewNormalTracesMarshaler().MarshalTraces(tt.input)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tt.expected, string(output))\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/databuffer.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlptext // import \"go.opentelemetry.io/collector/exporter/debugexporter/internal/otlptext\"\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"math\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/entity\"\n)\n\ntype dataBuffer struct {\n\tbuf bytes.Buffer\n}\n\nfunc (b *dataBuffer) logEntry(format string, a ...any) {\n\tb.buf.WriteString(fmt.Sprintf(format, a...))\n\tb.buf.WriteString(\"\\n\")\n}\n\nfunc (b *dataBuffer) logAttr(attr string, value any) {\n\tb.logEntry(\"    %-15s: %s\", attr, value)\n}\n\nfunc (b *dataBuffer) logAttributes(header string, m pcommon.Map) {\n\tif m.Len() == 0 {\n\t\treturn\n\t}\n\n\tb.logEntry(\"%s:\", header)\n\tattrPrefix := \"     ->\"\n\n\t// Add offset to attributes if needed.\n\theaderParts := strings.Split(header, \"->\")\n\tif len(headerParts) > 1 {\n\t\tattrPrefix = headerParts[0] + attrPrefix\n\t}\n\n\tfor k, v := range m.All() {\n\t\tb.logEntry(\"%s %s: %s\", attrPrefix, k, valueToString(v))\n\t}\n}\n\nfunc (b *dataBuffer) logEntityRefs(resource pcommon.Resource) {\n\tentityRefs := entity.ResourceEntityRefs(resource)\n\tif entityRefs.Len() == 0 {\n\t\treturn\n\t}\n\n\tb.logEntry(\"Resource entity refs:\")\n\tfor i := 0; i < entityRefs.Len(); i++ {\n\t\tentityRef := entityRefs.At(i)\n\t\tb.logEntry(\"     -> Entity ref #%d:\", i)\n\t\tb.logEntry(\"          -> Type: %s\", entityRef.Type())\n\t\tif entityRef.SchemaUrl() != \"\" {\n\t\t\tb.logEntry(\"          -> Schema URL: %s\", entityRef.SchemaUrl())\n\t\t}\n\n\t\tidKeys := entityRef.IdKeys()\n\t\tif idKeys.Len() > 0 {\n\t\t\tb.logEntry(\"          -> ID keys:\")\n\t\t\tfor j := 0; j < idKeys.Len(); j++ {\n\t\t\t\tb.logEntry(\"               -> %s\", idKeys.At(j))\n\t\t\t}\n\t\t}\n\n\t\tdescKeys := entityRef.DescriptionKeys()\n\t\tif descKeys.Len() > 0 {\n\t\t\tb.logEntry(\"          -> Description keys:\")\n\t\t\tfor j := 0; j < descKeys.Len(); j++ {\n\t\t\t\tb.logEntry(\"               -> %s\", descKeys.At(j))\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (b *dataBuffer) logAttributesWithIndentation(header string, m pcommon.Map, indentVal int) {\n\tif m.Len() == 0 {\n\t\treturn\n\t}\n\n\tindent := strings.Repeat(\" \", indentVal)\n\n\tb.logEntry(\"%s%s:\", indent, header)\n\tattrPrefix := indent + \"     ->\"\n\n\t// Add offset to attributes if needed.\n\theaderParts := strings.Split(header, \"->\")\n\tif len(headerParts) > 1 {\n\t\tattrPrefix = headerParts[0] + attrPrefix\n\t}\n\n\tfor k, v := range m.All() {\n\t\tb.logEntry(\"%s %s: %s\", attrPrefix, k, valueToString(v))\n\t}\n}\n\nfunc (b *dataBuffer) logInstrumentationScope(il pcommon.InstrumentationScope) {\n\tb.logEntry(\n\t\t\"InstrumentationScope %s %s\",\n\t\til.Name(),\n\t\til.Version())\n\tb.logAttributes(\"InstrumentationScope attributes\", il.Attributes())\n}\n\nfunc (b *dataBuffer) logMetricDescriptor(md pmetric.Metric) {\n\tb.logEntry(\"Descriptor:\")\n\tb.logEntry(\"     -> Name: %s\", md.Name())\n\tb.logEntry(\"     -> Description: %s\", md.Description())\n\tb.logEntry(\"     -> Unit: %s\", md.Unit())\n\tb.logEntry(\"     -> DataType: %s\", md.Type().String())\n\tb.logAttributes(\"     -> Metadata\", md.Metadata())\n}\n\nfunc (b *dataBuffer) logMetricDataPoints(m pmetric.Metric) {\n\tswitch m.Type() {\n\tcase pmetric.MetricTypeEmpty:\n\t\treturn\n\tcase pmetric.MetricTypeGauge:\n\t\tb.logNumberDataPoints(m.Gauge().DataPoints())\n\tcase pmetric.MetricTypeSum:\n\t\tdata := m.Sum()\n\t\tb.logEntry(\"     -> IsMonotonic: %t\", data.IsMonotonic())\n\t\tb.logEntry(\"     -> AggregationTemporality: %s\", data.AggregationTemporality().String())\n\t\tb.logNumberDataPoints(data.DataPoints())\n\tcase pmetric.MetricTypeHistogram:\n\t\tdata := m.Histogram()\n\t\tb.logEntry(\"     -> AggregationTemporality: %s\", data.AggregationTemporality().String())\n\t\tb.logHistogramDataPoints(data.DataPoints())\n\tcase pmetric.MetricTypeExponentialHistogram:\n\t\tdata := m.ExponentialHistogram()\n\t\tb.logEntry(\"     -> AggregationTemporality: %s\", data.AggregationTemporality().String())\n\t\tb.logExponentialHistogramDataPoints(data.DataPoints())\n\tcase pmetric.MetricTypeSummary:\n\t\tdata := m.Summary()\n\t\tb.logDoubleSummaryDataPoints(data.DataPoints())\n\t}\n}\n\nfunc (b *dataBuffer) logNumberDataPoints(ps pmetric.NumberDataPointSlice) {\n\tfor i := 0; i < ps.Len(); i++ {\n\t\tp := ps.At(i)\n\t\tb.logEntry(\"NumberDataPoints #%d\", i)\n\t\tb.logDataPointAttributes(p.Attributes())\n\n\t\tb.logEntry(\"StartTimestamp: %s\", p.StartTimestamp())\n\t\tb.logEntry(\"Timestamp: %s\", p.Timestamp())\n\t\tswitch p.ValueType() {\n\t\tcase pmetric.NumberDataPointValueTypeInt:\n\t\t\tb.logEntry(\"Value: %d\", p.IntValue())\n\t\tcase pmetric.NumberDataPointValueTypeDouble:\n\t\t\tb.logEntry(\"Value: %f\", p.DoubleValue())\n\t\t}\n\n\t\tb.logExemplars(\"Exemplars\", p.Exemplars())\n\t}\n}\n\nfunc (b *dataBuffer) logHistogramDataPoints(ps pmetric.HistogramDataPointSlice) {\n\tfor i := 0; i < ps.Len(); i++ {\n\t\tp := ps.At(i)\n\t\tb.logEntry(\"HistogramDataPoints #%d\", i)\n\t\tb.logDataPointAttributes(p.Attributes())\n\n\t\tb.logEntry(\"StartTimestamp: %s\", p.StartTimestamp())\n\t\tb.logEntry(\"Timestamp: %s\", p.Timestamp())\n\t\tb.logEntry(\"Count: %d\", p.Count())\n\n\t\tif p.HasSum() {\n\t\t\tb.logEntry(\"Sum: %f\", p.Sum())\n\t\t}\n\n\t\tif p.HasMin() {\n\t\t\tb.logEntry(\"Min: %f\", p.Min())\n\t\t}\n\n\t\tif p.HasMax() {\n\t\t\tb.logEntry(\"Max: %f\", p.Max())\n\t\t}\n\n\t\tfor i := 0; i < p.ExplicitBounds().Len(); i++ {\n\t\t\tb.logEntry(\"ExplicitBounds #%d: %f\", i, p.ExplicitBounds().At(i))\n\t\t}\n\n\t\tfor j := 0; j < p.BucketCounts().Len(); j++ {\n\t\t\tb.logEntry(\"Buckets #%d, Count: %d\", j, p.BucketCounts().At(j))\n\t\t}\n\n\t\tb.logExemplars(\"Exemplars\", p.Exemplars())\n\t}\n}\n\nfunc (b *dataBuffer) logExponentialHistogramDataPoints(ps pmetric.ExponentialHistogramDataPointSlice) {\n\tfor i := 0; i < ps.Len(); i++ {\n\t\tp := ps.At(i)\n\t\tb.logEntry(\"ExponentialHistogramDataPoints #%d\", i)\n\t\tb.logDataPointAttributes(p.Attributes())\n\n\t\tb.logEntry(\"StartTimestamp: %s\", p.StartTimestamp())\n\t\tb.logEntry(\"Timestamp: %s\", p.Timestamp())\n\t\tb.logEntry(\"Count: %d\", p.Count())\n\n\t\tif p.HasSum() {\n\t\t\tb.logEntry(\"Sum: %f\", p.Sum())\n\t\t}\n\n\t\tif p.HasMin() {\n\t\t\tb.logEntry(\"Min: %f\", p.Min())\n\t\t}\n\n\t\tif p.HasMax() {\n\t\t\tb.logEntry(\"Max: %f\", p.Max())\n\t\t}\n\n\t\tscale := int(p.Scale())\n\t\tfactor := math.Ldexp(math.Ln2, -scale)\n\t\t// Note: the equation used here, which is\n\t\t//   math.Exp(index * factor)\n\t\t// reports +Inf as the _lower_ boundary of the bucket nearest\n\t\t// infinity, which is incorrect and can be addressed in various\n\t\t// ways.  The OTel-Go implementation of this histogram pending\n\t\t// in https://github.com/open-telemetry/opentelemetry-go/pull/2393\n\t\t// uses a lookup table for the last finite boundary, which can be\n\t\t// easily computed using `math/big` (for scales up to 20).\n\n\t\tnegB := p.Negative().BucketCounts()\n\t\tposB := p.Positive().BucketCounts()\n\n\t\tfor i := 0; i < negB.Len(); i++ {\n\t\t\tpos := negB.Len() - i - 1\n\t\t\tindex := float64(p.Negative().Offset()) + float64(pos)\n\t\t\tlower := math.Exp(index * factor)\n\t\t\tupper := math.Exp((index + 1) * factor)\n\t\t\tb.logEntry(\"Bucket [%f, %f), Count: %d\", -upper, -lower, negB.At(pos))\n\t\t}\n\n\t\tif p.ZeroCount() != 0 {\n\t\t\tb.logEntry(\"Bucket [0, 0], Count: %d\", p.ZeroCount())\n\t\t}\n\n\t\tfor pos := 0; pos < posB.Len(); pos++ {\n\t\t\tindex := float64(p.Positive().Offset()) + float64(pos)\n\t\t\tlower := math.Exp(index * factor)\n\t\t\tupper := math.Exp((index + 1) * factor)\n\t\t\tb.logEntry(\"Bucket (%f, %f], Count: %d\", lower, upper, posB.At(pos))\n\t\t}\n\n\t\tb.logExemplars(\"Exemplars\", p.Exemplars())\n\t}\n}\n\nfunc (b *dataBuffer) logDoubleSummaryDataPoints(ps pmetric.SummaryDataPointSlice) {\n\tfor i := 0; i < ps.Len(); i++ {\n\t\tp := ps.At(i)\n\t\tb.logEntry(\"SummaryDataPoints #%d\", i)\n\t\tb.logDataPointAttributes(p.Attributes())\n\n\t\tb.logEntry(\"StartTimestamp: %s\", p.StartTimestamp())\n\t\tb.logEntry(\"Timestamp: %s\", p.Timestamp())\n\t\tb.logEntry(\"Count: %d\", p.Count())\n\t\tb.logEntry(\"Sum: %f\", p.Sum())\n\n\t\tquantiles := p.QuantileValues()\n\t\tfor i := 0; i < quantiles.Len(); i++ {\n\t\t\tquantile := quantiles.At(i)\n\t\t\tb.logEntry(\"QuantileValue #%d: Quantile %f, Value %f\", i, quantile.Quantile(), quantile.Value())\n\t\t}\n\t}\n}\n\nfunc (b *dataBuffer) logDataPointAttributes(attributes pcommon.Map) {\n\tb.logAttributes(\"Data point attributes\", attributes)\n}\n\nfunc (b *dataBuffer) logEvents(description string, se ptrace.SpanEventSlice) {\n\tif se.Len() == 0 {\n\t\treturn\n\t}\n\n\tb.logEntry(\"%s:\", description)\n\tfor i := 0; i < se.Len(); i++ {\n\t\te := se.At(i)\n\t\tb.logEntry(\"SpanEvent #%d\", i)\n\t\tb.logEntry(\"     -> Name: %s\", e.Name())\n\t\tb.logEntry(\"     -> Timestamp: %s\", e.Timestamp())\n\t\tb.logEntry(\"     -> DroppedAttributesCount: %d\", e.DroppedAttributesCount())\n\t\tb.logAttributes(\"     -> Attributes:\", e.Attributes())\n\t}\n}\n\nfunc (b *dataBuffer) logLinks(description string, sl ptrace.SpanLinkSlice) {\n\tif sl.Len() == 0 {\n\t\treturn\n\t}\n\n\tb.logEntry(\"%s:\", description)\n\n\tfor i := 0; i < sl.Len(); i++ {\n\t\tl := sl.At(i)\n\t\tb.logEntry(\"SpanLink #%d\", i)\n\t\tb.logEntry(\"     -> Trace ID: %s\", l.TraceID())\n\t\tb.logEntry(\"     -> ID: %s\", l.SpanID())\n\t\tb.logEntry(\"     -> TraceState: %s\", l.TraceState().AsRaw())\n\t\tb.logEntry(\"     -> DroppedAttributesCount: %d\", l.DroppedAttributesCount())\n\t\tb.logAttributes(\"     -> Attributes:\", l.Attributes())\n\t}\n}\n\nfunc (b *dataBuffer) logExemplars(description string, se pmetric.ExemplarSlice) {\n\tif se.Len() == 0 {\n\t\treturn\n\t}\n\n\tb.logEntry(\"%s:\", description)\n\n\tfor i := 0; i < se.Len(); i++ {\n\t\te := se.At(i)\n\t\tb.logEntry(\"Exemplar #%d\", i)\n\t\tb.logEntry(\"     -> Trace ID: %s\", e.TraceID())\n\t\tb.logEntry(\"     -> Span ID: %s\", e.SpanID())\n\t\tb.logEntry(\"     -> Timestamp: %s\", e.Timestamp())\n\t\tswitch e.ValueType() {\n\t\tcase pmetric.ExemplarValueTypeInt:\n\t\t\tb.logEntry(\"     -> Value: %d\", e.IntValue())\n\t\tcase pmetric.ExemplarValueTypeDouble:\n\t\t\tb.logEntry(\"     -> Value: %f\", e.DoubleValue())\n\t\t}\n\t\tb.logAttributes(\"     -> FilteredAttributes\", e.FilteredAttributes())\n\t}\n}\n\nfunc (b *dataBuffer) logProfileSamples(ss pprofile.SampleSlice, dic pprofile.ProfilesDictionary) {\n\tif ss.Len() == 0 {\n\t\treturn\n\t}\n\n\tfor i := 0; i < ss.Len(); i++ {\n\t\tb.logEntry(\"    Sample #%d\", i)\n\t\tsample := ss.At(i)\n\n\t\tb.logEntry(\"        Values: %d\", sample.Values().AsRaw())\n\n\t\tif lai := sample.AttributeIndices().Len(); lai > 0 {\n\t\t\tb.logEntry(\"        Attributes:\")\n\t\t\tfor j := range lai {\n\t\t\t\tattr := dic.AttributeTable().At(int(sample.AttributeIndices().At(j)))\n\t\t\t\tb.logEntry(\"             -> %s: %s\", dic.StringTable().At(int(attr.KeyStrindex())), attr.Value().AsRaw())\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc (b *dataBuffer) logProfileMappings(ms pprofile.MappingSlice) {\n\tif ms.Len() == 0 {\n\t\treturn\n\t}\n\n\tfor i := 0; i < ms.Len(); i++ {\n\t\tb.logEntry(\"Mapping #%d\", i)\n\t\tmapping := ms.At(i)\n\n\t\tb.logEntry(\"    Memory start: %d\", mapping.MemoryStart())\n\t\tb.logEntry(\"    Memory limit: %d\", mapping.MemoryLimit())\n\t\tb.logEntry(\"    File offset: %d\", mapping.FileOffset())\n\t\tb.logEntry(\"    File name: %d\", mapping.FilenameStrindex())\n\t\tb.logEntry(\"    Attributes: %d\", mapping.AttributeIndices().AsRaw())\n\t}\n}\n\nfunc (b *dataBuffer) logProfileLocations(ls pprofile.LocationSlice) {\n\tif ls.Len() == 0 {\n\t\treturn\n\t}\n\n\tfor i := 0; i < ls.Len(); i++ {\n\t\tb.logEntry(\"Location #%d\", i)\n\t\tlocation := ls.At(i)\n\n\t\tb.logEntry(\"    Mapping index: %d\", location.MappingIndex())\n\t\tb.logEntry(\"    Address: %d\", location.Address())\n\t\tif ll := location.Lines().Len(); ll > 0 {\n\t\t\tfor j := range ll {\n\t\t\t\tb.logEntry(\"    Line #%d\", j)\n\t\t\t\tline := location.Lines().At(j)\n\t\t\t\tb.logEntry(\"        Function index: %d\", line.FunctionIndex())\n\t\t\t\tb.logEntry(\"        Line: %d\", line.Line())\n\t\t\t\tb.logEntry(\"        Column: %d\", line.Column())\n\t\t\t}\n\t\t}\n\t\tb.logEntry(\"    Attributes: %d\", location.AttributeIndices().AsRaw())\n\t}\n}\n\nfunc (b *dataBuffer) logProfileFunctions(fs pprofile.FunctionSlice) {\n\tif fs.Len() == 0 {\n\t\treturn\n\t}\n\n\tfor i := 0; i < fs.Len(); i++ {\n\t\tb.logEntry(\"Function #%d\", i)\n\t\tfunction := fs.At(i)\n\n\t\tb.logEntry(\"    Name: %d\", function.NameStrindex())\n\t\tb.logEntry(\"    System name: %d\", function.SystemNameStrindex())\n\t\tb.logEntry(\"    Filename: %d\", function.FilenameStrindex())\n\t\tb.logEntry(\"    Start line: %d\", function.StartLine())\n\t}\n}\n\nfunc (b *dataBuffer) logStringTable(ss pcommon.StringSlice) {\n\tif ss.Len() == 0 {\n\t\treturn\n\t}\n\n\tb.logEntry(\"String table:\")\n\tfor i := 0; i < ss.Len(); i++ {\n\t\tb.logEntry(\"    %s\", ss.At(i))\n\t}\n}\n\nfunc keyValueAndUnitsToMap(aus pprofile.KeyValueAndUnitSlice) pcommon.Map {\n\tm := pcommon.NewMap()\n\tfor i := 0; i < aus.Len(); i++ {\n\t\tau := aus.At(i)\n\t\tm.PutInt(\"Key\", int64(au.KeyStrindex()))\n\t\tm.PutStr(\"Value\", au.Value().AsString())\n\t\tm.PutInt(\"unit\", int64(au.UnitStrindex()))\n\t}\n\treturn m\n}\n\nfunc linkTableToMap(ls pprofile.LinkSlice) pcommon.Map {\n\tm := pcommon.NewMap()\n\tfor i := 0; i < ls.Len(); i++ {\n\t\tl := ls.At(i)\n\t\tm.PutStr(\"Trace ID\", l.TraceID().String())\n\t\tm.PutStr(\"Span ID\", l.SpanID().String())\n\t}\n\treturn m\n}\n\nfunc valueToString(v pcommon.Value) string {\n\treturn fmt.Sprintf(\"%s(%s)\", v.Type().String(), v.AsString())\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/databuffer_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlptext\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestNestedArraySerializesCorrectly(t *testing.T) {\n\tava := pcommon.NewValueSlice()\n\tava.Slice().AppendEmpty().SetStr(\"foo\")\n\tava.Slice().AppendEmpty().SetInt(42)\n\tava.Slice().AppendEmpty().SetEmptySlice().AppendEmpty().SetStr(\"bar\")\n\tava.Slice().AppendEmpty().SetBool(true)\n\tava.Slice().AppendEmpty().SetDouble(5.5)\n\n\tassert.Equal(t, `Slice([\"foo\",42,[\"bar\"],true,5.5])`, valueToString(ava))\n}\n\nfunc TestNestedMapSerializesCorrectly(t *testing.T) {\n\tava := pcommon.NewValueMap()\n\tav := ava.Map()\n\tav.PutStr(\"foo\", \"test\")\n\tav.PutEmptyMap(\"zoo\").PutInt(\"bar\", 13)\n\n\tassert.Equal(t, `Map({\"foo\":\"test\",\"zoo\":{\"bar\":13}})`, valueToString(ava))\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/known_sync_error.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build linux || darwin\n\npackage otlptext // import \"go.opentelemetry.io/collector/exporter/debugexporter/internal/otlptext\"\n\nimport (\n\t\"errors\"\n\t\"syscall\"\n)\n\nvar knownSyncErrors = []error{\n\t// sync /dev/stdout: invalid argument\n\tsyscall.EINVAL,\n\t// sync /dev/stdout: not supported\n\tsyscall.ENOTSUP,\n\t// sync /dev/stdout: inappropriate ioctl for device\n\tsyscall.ENOTTY,\n\t// sync /dev/stdout: bad file descriptor\n\tsyscall.EBADF,\n}\n\n// knownSyncError returns true if the given error is one of the known\n// non-actionable errors returned by Sync on Linux and macOS.\nfunc knownSyncError(err error) bool {\n\tfor _, syncError := range knownSyncErrors {\n\t\tif errors.Is(err, syncError) {\n\t\t\treturn true\n\t\t}\n\t}\n\n\treturn false\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/known_sync_error_other.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build !linux && !darwin && !windows\n\npackage otlptext // import \"go.opentelemetry.io/collector/exporter/debugexporter/internal/otlptext\"\n\n// knownSyncError returns true if the given error is one of the known\n// non-actionable errors returned by Sync on Plan 9.\nfunc knownSyncError(err error) bool {\n\treturn false\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/known_sync_error_windows.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build windows\n\npackage otlptext // import \"go.opentelemetry.io/collector/exporter/debugexporter/internal/otlptext\"\n\nimport (\n\t\"errors\"\n\n\t\"golang.org/x/sys/windows\"\n)\n\n// knownSyncError returns true if the given error is one of the known\n// non-actionable errors returned by Sync on Windows:\n//\n// - sync /dev/stderr: The handle is invalid.\nfunc knownSyncError(err error) bool {\n\treturn errors.Is(err, windows.ERROR_INVALID_HANDLE)\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/logs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlptext // import \"go.opentelemetry.io/collector/exporter/debugexporter/internal/otlptext\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\n// NewTextLogsMarshaler returns a plog.Marshaler to encode to OTLP text bytes.\nfunc NewTextLogsMarshaler() plog.Marshaler {\n\treturn textLogsMarshaler{}\n}\n\ntype textLogsMarshaler struct{}\n\n// MarshalLogs plog.Logs to OTLP text.\nfunc (textLogsMarshaler) MarshalLogs(ld plog.Logs) ([]byte, error) {\n\tbuf := dataBuffer{}\n\trls := ld.ResourceLogs()\n\tfor i := 0; i < rls.Len(); i++ {\n\t\tbuf.logEntry(\"ResourceLog #%d\", i)\n\t\trl := rls.At(i)\n\t\tbuf.logEntry(\"Resource SchemaURL: %s\", rl.SchemaUrl())\n\t\tbuf.logAttributes(\"Resource attributes\", rl.Resource().Attributes())\n\t\tbuf.logEntityRefs(rl.Resource())\n\t\tills := rl.ScopeLogs()\n\t\tfor j := 0; j < ills.Len(); j++ {\n\t\t\tbuf.logEntry(\"ScopeLogs #%d\", j)\n\t\t\tils := ills.At(j)\n\t\t\tbuf.logEntry(\"ScopeLogs SchemaURL: %s\", ils.SchemaUrl())\n\t\t\tbuf.logInstrumentationScope(ils.Scope())\n\n\t\t\tlogs := ils.LogRecords()\n\t\t\tfor k := 0; k < logs.Len(); k++ {\n\t\t\t\tbuf.logEntry(\"LogRecord #%d\", k)\n\t\t\t\tlr := logs.At(k)\n\t\t\t\tbuf.logEntry(\"ObservedTimestamp: %s\", lr.ObservedTimestamp())\n\t\t\t\tbuf.logEntry(\"Timestamp: %s\", lr.Timestamp())\n\t\t\t\tbuf.logEntry(\"SeverityText: %s\", lr.SeverityText())\n\t\t\t\tbuf.logEntry(\"SeverityNumber: %s(%d)\", lr.SeverityNumber(), lr.SeverityNumber())\n\t\t\t\tif lr.EventName() != \"\" {\n\t\t\t\t\tbuf.logEntry(\"EventName: %s\", lr.EventName())\n\t\t\t\t}\n\t\t\t\tbuf.logEntry(\"Body: %s\", valueToString(lr.Body()))\n\t\t\t\tbuf.logAttributes(\"Attributes\", lr.Attributes())\n\t\t\t\tbuf.logEntry(\"Trace ID: %s\", lr.TraceID())\n\t\t\t\tbuf.logEntry(\"Span ID: %s\", lr.SpanID())\n\t\t\t\tbuf.logEntry(\"Flags: %d\", lr.Flags())\n\t\t\t}\n\t\t}\n\t}\n\n\treturn buf.buf.Bytes(), nil\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/logs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlptext\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestLogsText(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tin   plog.Logs\n\t\tout  string\n\t}{\n\t\t{\n\t\t\tname: \"empty_logs\",\n\t\t\tin:   plog.NewLogs(),\n\t\t\tout:  \"empty.out\",\n\t\t},\n\t\t{\n\t\t\tname: \"logs_with_one_record\",\n\t\t\tin:   testdata.GenerateLogs(1),\n\t\t\tout:  \"one_record.out\",\n\t\t},\n\t\t{\n\t\t\tname: \"logs_with_two_records\",\n\t\t\tin:   testdata.GenerateLogs(2),\n\t\t\tout:  \"two_records.out\",\n\t\t},\n\t\t{\n\t\t\tname: \"log_with_event_name\",\n\t\t\tin: func() plog.Logs {\n\t\t\t\tls := plog.NewLogs()\n\t\t\t\tl := ls.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\t\t\t\tl.SetTimestamp(pcommon.NewTimestampFromTime(time.Date(2020, 2, 11, 20, 26, 13, 789, time.UTC)))\n\t\t\t\tl.SetSeverityNumber(plog.SeverityNumberInfo)\n\t\t\t\tl.SetSeverityText(\"Info\")\n\t\t\t\tl.SetEventName(\"event_name\")\n\t\t\t\tl.Body().SetStr(\"This is a log message\")\n\t\t\t\tattrs := l.Attributes()\n\t\t\t\tattrs.PutStr(\"app\", \"server\")\n\t\t\t\tattrs.PutInt(\"instance_num\", 1)\n\t\t\t\tl.SetSpanID([8]byte{0x01, 0x02, 0x04, 0x08})\n\t\t\t\tl.SetTraceID([16]byte{0x08, 0x04, 0x02, 0x01})\n\t\t\t\treturn ls\n\t\t\t}(),\n\t\t\tout: \"log_with_event_name.out\",\n\t\t},\n\t\t{\n\t\t\tname: \"logs_with_embedded_maps\",\n\t\t\tin: func() plog.Logs {\n\t\t\t\tls := plog.NewLogs()\n\t\t\t\tl := ls.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\t\t\t\tl.SetTimestamp(pcommon.NewTimestampFromTime(time.Date(2020, 2, 11, 20, 26, 13, 789, time.UTC)))\n\t\t\t\tl.SetSeverityNumber(plog.SeverityNumberInfo)\n\t\t\t\tl.SetSeverityText(\"INFO\")\n\t\t\t\tbm := l.Body().SetEmptyMap()\n\t\t\t\tbm.PutStr(\"key1\", \"val1\")\n\t\t\t\tbmm := bm.PutEmptyMap(\"key2\")\n\t\t\t\tbmm.PutStr(\"key21\", \"val21\")\n\t\t\t\tbmm.PutStr(\"key22\", \"val22\")\n\t\t\t\tam := l.Attributes().PutEmptyMap(\"key1\")\n\t\t\t\tam.PutStr(\"key11\", \"val11\")\n\t\t\t\tam.PutStr(\"key12\", \"val12\")\n\t\t\t\tam.PutEmptyMap(\"key13\").PutStr(\"key131\", \"val131\")\n\t\t\t\tl.Attributes().PutStr(\"key2\", \"val2\")\n\t\t\t\treturn ls\n\t\t\t}(),\n\t\t\tout: \"embedded_maps.out\",\n\t\t},\n\t\t{\n\t\t\tname: \"logs_with_entity_refs\",\n\t\t\tin:   generateLogsWithEntityRefs(),\n\t\t\tout:  \"logs_with_entity_refs.out\",\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot, err := NewTextLogsMarshaler().MarshalLogs(tt.in)\n\t\t\trequire.NoError(t, err)\n\t\t\tout, err := os.ReadFile(filepath.Join(\"testdata\", \"logs\", tt.out))\n\t\t\trequire.NoError(t, err)\n\t\t\texpected := strings.ReplaceAll(string(out), \"\\r\", \"\")\n\t\t\tassert.Equal(t, expected, string(got))\n\t\t})\n\t}\n}\n\nfunc generateLogsWithEntityRefs() plog.Logs {\n\tld := plog.NewLogs()\n\trl := ld.ResourceLogs().AppendEmpty()\n\n\tsetupResourceWithEntityRefs(rl.Resource())\n\n\tsl := rl.ScopeLogs().AppendEmpty()\n\tsl.Scope().SetName(\"test-scope\")\n\tlr := sl.LogRecords().AppendEmpty()\n\tlr.SetTimestamp(pcommon.NewTimestampFromTime(time.Date(2020, 2, 11, 20, 26, 13, 789, time.UTC)))\n\tlr.SetSeverityNumber(plog.SeverityNumberInfo)\n\tlr.SetSeverityText(\"Info\")\n\tlr.Body().SetStr(\"This is a test log message\")\n\tlr.Attributes().PutStr(\"test.attribute\", \"test-value\")\n\n\treturn ld\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlptext // import \"go.opentelemetry.io/collector/exporter/debugexporter/internal/otlptext\"\n\nimport \"go.opentelemetry.io/collector/pdata/pmetric\"\n\n// NewTextMetricsMarshaler returns a pmetric.Marshaler to encode to OTLP text bytes.\nfunc NewTextMetricsMarshaler() pmetric.Marshaler {\n\treturn textMetricsMarshaler{}\n}\n\ntype textMetricsMarshaler struct{}\n\n// MarshalMetrics pmetric.Metrics to OTLP text.\nfunc (textMetricsMarshaler) MarshalMetrics(md pmetric.Metrics) ([]byte, error) {\n\tbuf := dataBuffer{}\n\trms := md.ResourceMetrics()\n\tfor i := 0; i < rms.Len(); i++ {\n\t\tbuf.logEntry(\"ResourceMetrics #%d\", i)\n\t\trm := rms.At(i)\n\t\tbuf.logEntry(\"Resource SchemaURL: %s\", rm.SchemaUrl())\n\t\tbuf.logAttributes(\"Resource attributes\", rm.Resource().Attributes())\n\t\tbuf.logEntityRefs(rm.Resource())\n\t\tilms := rm.ScopeMetrics()\n\t\tfor j := 0; j < ilms.Len(); j++ {\n\t\t\tbuf.logEntry(\"ScopeMetrics #%d\", j)\n\t\t\tilm := ilms.At(j)\n\t\t\tbuf.logEntry(\"ScopeMetrics SchemaURL: %s\", ilm.SchemaUrl())\n\t\t\tbuf.logInstrumentationScope(ilm.Scope())\n\t\t\tmetrics := ilm.Metrics()\n\t\t\tfor k := 0; k < metrics.Len(); k++ {\n\t\t\t\tbuf.logEntry(\"Metric #%d\", k)\n\t\t\t\tmetric := metrics.At(k)\n\t\t\t\tbuf.logMetricDescriptor(metric)\n\t\t\t\tbuf.logMetricDataPoints(metric)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn buf.buf.Bytes(), nil\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/metrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlptext\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestMetricsText(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tin   pmetric.Metrics\n\t\tout  string\n\t}{\n\t\t{\n\t\t\tname: \"empty_metrics\",\n\t\t\tin:   pmetric.NewMetrics(),\n\t\t\tout:  \"empty.out\",\n\t\t},\n\t\t{\n\t\t\tname: \"metrics_with_all_types\",\n\t\t\tin:   testdata.GenerateMetricsAllTypes(),\n\t\t\tout:  \"metrics_with_all_types.out\",\n\t\t},\n\t\t{\n\t\t\tname: \"two_metrics\",\n\t\t\tin:   testdata.GenerateMetrics(2),\n\t\t\tout:  \"two_metrics.out\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid_metric_type\",\n\t\t\tin:   testdata.GenerateMetricsMetricTypeInvalid(),\n\t\t\tout:  \"invalid_metric_type.out\",\n\t\t},\n\t\t{\n\t\t\tname: \"metrics_with_entity_refs\",\n\t\t\tin:   generateMetricsWithEntityRefs(),\n\t\t\tout:  \"metrics_with_entity_refs.out\",\n\t\t},\n\t\t{\n\t\t\tname: \"metrics_with_metadata\",\n\t\t\tin:   generateMetricsWithMetadata(),\n\t\t\tout:  \"metrics_with_metadata.out\",\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot, err := NewTextMetricsMarshaler().MarshalMetrics(tt.in)\n\t\t\trequire.NoError(t, err)\n\t\t\tout, err := os.ReadFile(filepath.Join(\"testdata\", \"metrics\", tt.out))\n\t\t\trequire.NoError(t, err)\n\t\t\texpected := strings.ReplaceAll(string(out), \"\\r\", \"\")\n\t\t\tassert.Equal(t, expected, string(got))\n\t\t})\n\t}\n}\n\nfunc generateMetricsWithEntityRefs() pmetric.Metrics {\n\tmd := pmetric.NewMetrics()\n\trm := md.ResourceMetrics().AppendEmpty()\n\n\tsetupResourceWithEntityRefs(rm.Resource())\n\n\tsm := rm.ScopeMetrics().AppendEmpty()\n\tsm.Scope().SetName(\"test-scope\")\n\tmetric := sm.Metrics().AppendEmpty()\n\tmetric.SetName(\"test-metric\")\n\tmetric.SetDescription(\"A test metric\")\n\tmetric.SetUnit(\"1\")\n\n\tgauge := metric.SetEmptyGauge()\n\tdp := gauge.DataPoints().AppendEmpty()\n\tdp.SetDoubleValue(123.45)\n\tdp.Attributes().PutStr(\"test.attribute\", \"test-value\")\n\n\treturn md\n}\n\nfunc generateMetricsWithMetadata() pmetric.Metrics {\n\tmd := pmetric.NewMetrics()\n\trm := md.ResourceMetrics().AppendEmpty()\n\trm.Resource().Attributes().PutStr(\"service.name\", \"test-service\")\n\n\tsm := rm.ScopeMetrics().AppendEmpty()\n\tsm.Scope().SetName(\"test-scope\")\n\n\tmetric := sm.Metrics().AppendEmpty()\n\tmetric.SetName(\"test-metric-metadata\")\n\tmetric.SetDescription(\"A test metric with metadata\")\n\tmetric.SetUnit(\"1\")\n\n\tmetric.Metadata().PutStr(\"meta.key\", \"meta-value\")\n\tmetric.Metadata().PutInt(\"meta.id\", 101)\n\n\tgauge := metric.SetEmptyGauge()\n\tdp := gauge.DataPoints().AppendEmpty()\n\tdp.SetIntValue(1)\n\n\treturn md\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlptext\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/profiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlptext // import \"go.opentelemetry.io/collector/exporter/debugexporter/internal/otlptext\"\n\nimport (\n\t\"strconv\"\n\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n)\n\n// NewTextProfilesMarshaler returns a pprofile.Marshaler to encode to OTLP text bytes.\nfunc NewTextProfilesMarshaler() pprofile.Marshaler {\n\treturn textProfilesMarshaler{}\n}\n\ntype textProfilesMarshaler struct{}\n\n// MarshalProfiles pprofile.Profiles to OTLP text.\nfunc (textProfilesMarshaler) MarshalProfiles(pd pprofile.Profiles) ([]byte, error) {\n\tbuf := dataBuffer{}\n\tdic := pd.Dictionary()\n\trps := pd.ResourceProfiles()\n\n\tbuf.logProfileMappings(dic.MappingTable())\n\tbuf.logProfileLocations(dic.LocationTable())\n\tbuf.logProfileFunctions(dic.FunctionTable())\n\tbuf.logAttributesWithIndentation(\n\t\t\"Attribute table\",\n\t\tkeyValueAndUnitsToMap(dic.AttributeTable()),\n\t\t0)\n\n\tbuf.logAttributesWithIndentation(\n\t\t\"Link table\",\n\t\tlinkTableToMap(dic.LinkTable()),\n\t\t0)\n\n\tbuf.logStringTable(dic.StringTable())\n\n\tfor i := 0; i < rps.Len(); i++ {\n\t\tbuf.logEntry(\"ResourceProfiles #%d\", i)\n\t\trp := rps.At(i)\n\t\tbuf.logEntry(\"Resource SchemaURL: %s\", rp.SchemaUrl())\n\t\tbuf.logAttributes(\"Resource attributes\", rp.Resource().Attributes())\n\t\tbuf.logEntityRefs(rp.Resource())\n\t\tilps := rp.ScopeProfiles()\n\t\tfor j := 0; j < ilps.Len(); j++ {\n\t\t\tbuf.logEntry(\"ScopeProfiles #%d\", j)\n\t\t\tilp := ilps.At(j)\n\t\t\tbuf.logEntry(\"ScopeProfiles SchemaURL: %s\", ilp.SchemaUrl())\n\t\t\tbuf.logInstrumentationScope(ilp.Scope())\n\t\t\tprofiles := ilp.Profiles()\n\t\t\tfor k := 0; k < profiles.Len(); k++ {\n\t\t\t\tbuf.logEntry(\"Profile #%d\", k)\n\t\t\t\tprofile := profiles.At(k)\n\t\t\t\tbuf.logAttr(\"Profile ID\", profile.ProfileID())\n\t\t\t\tbuf.logAttr(\"Start time\", profile.Time().String())\n\t\t\t\tbuf.logAttr(\"DurationNano\", strconv.FormatUint(profile.DurationNano(), 10))\n\t\t\t\tbuf.logAttr(\"Dropped attributes count\", strconv.FormatUint(uint64(profile.DroppedAttributesCount()), 10))\n\n\t\t\t\tbuf.logProfileSamples(profile.Samples(), dic)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn buf.buf.Bytes(), nil\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/profiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlptext\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestProfilesText(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tin   pprofile.Profiles\n\t\tout  string\n\t}{\n\t\t{\n\t\t\tname: \"empty_profiles\",\n\t\t\tin:   pprofile.NewProfiles(),\n\t\t\tout:  \"empty.out\",\n\t\t},\n\t\t{\n\t\t\tname: \"two_profiles\",\n\t\t\tin:   extendProfiles(testdata.GenerateProfiles(2)),\n\t\t\tout:  \"two_profiles.out\",\n\t\t},\n\t\t{\n\t\t\tname: \"profiles_with_entity_refs\",\n\t\t\tin:   generateProfilesWithEntityRefs(),\n\t\t\tout:  \"profiles_with_entity_refs.out\",\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot, err := NewTextProfilesMarshaler().MarshalProfiles(tt.in)\n\t\t\trequire.NoError(t, err)\n\t\t\tout, err := os.ReadFile(filepath.Join(\"testdata\", \"profiles\", tt.out))\n\t\t\trequire.NoError(t, err)\n\t\t\texpected := strings.ReplaceAll(string(out), \"\\r\", \"\")\n\t\t\tassert.Equal(t, expected, string(got))\n\t\t})\n\t}\n}\n\n// GenerateExtendedProfiles generates dummy profiling data with extended values for tests\nfunc extendProfiles(profiles pprofile.Profiles) pprofile.Profiles {\n\tdic := profiles.Dictionary()\n\tlocation := dic.LocationTable().AppendEmpty()\n\tlocation.SetMappingIndex(3)\n\tlocation.SetAddress(4)\n\tline := location.Lines().AppendEmpty()\n\tline.SetFunctionIndex(1)\n\tline.SetLine(2)\n\tline.SetColumn(3)\n\tlocation.AttributeIndices().FromRaw([]int32{6, 7})\n\tdic.StringTable().Append(\"intValue\")\n\tat := dic.AttributeTable()\n\ta := at.AppendEmpty()\n\ta.SetKeyStrindex(1)\n\ta.Value().SetInt(42)\n\tattributeUnits := dic.AttributeTable().AppendEmpty()\n\tattributeUnits.SetKeyStrindex(2)\n\tattributeUnits.SetUnitStrindex(5)\n\tdic.StringTable().Append(\"foobar\")\n\tmapping := dic.MappingTable().AppendEmpty()\n\tmapping.SetMemoryStart(2)\n\tmapping.SetMemoryLimit(3)\n\tmapping.SetFileOffset(4)\n\tmapping.SetFilenameStrindex(5)\n\tmapping.AttributeIndices().FromRaw([]int32{7, 8})\n\tfunction := dic.FunctionTable().AppendEmpty()\n\tfunction.SetNameStrindex(2)\n\tfunction.SetSystemNameStrindex(3)\n\tfunction.SetFilenameStrindex(4)\n\tfunction.SetStartLine(5)\n\n\tlinkTable := dic.LinkTable().AppendEmpty()\n\tlinkTable.SetTraceID([16]byte{0x03, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10})\n\tlinkTable.SetSpanID([8]byte{0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18})\n\n\tsc := profiles.ResourceProfiles().At(0).ScopeProfiles().At(0)\n\tprofilesCount := profiles.ResourceProfiles().At(0).ScopeProfiles().At(0).Profiles().Len()\n\tfor i := range profilesCount {\n\t\tif i%2 == 0 {\n\t\t\tprofile := sc.Profiles().At(i)\n\t\t\tprofile.AttributeIndices().FromRaw([]int32{1})\n\t\t}\n\t}\n\treturn profiles\n}\n\nfunc generateProfilesWithEntityRefs() pprofile.Profiles {\n\tpd := pprofile.NewProfiles()\n\trp := pd.ResourceProfiles().AppendEmpty()\n\n\tsetupResourceWithEntityRefs(rp.Resource())\n\n\tsp := rp.ScopeProfiles().AppendEmpty()\n\tsp.Scope().SetName(\"test-scope\")\n\tprofile := sp.Profiles().AppendEmpty()\n\n\tsample := profile.Samples().AppendEmpty()\n\tsample.Values().Append(100)\n\n\tdic := pd.Dictionary()\n\tdic.StringTable().Append(\"\")\n\tdic.StringTable().Append(\"cpu\")\n\tdic.StringTable().Append(\"nanoseconds\")\n\n\tsampleType := profile.SampleType()\n\tsampleType.SetTypeStrindex(1)\n\tsampleType.SetUnitStrindex(2)\n\n\treturn pd\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/sync.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlptext // import \"go.opentelemetry.io/collector/exporter/debugexporter/internal/otlptext\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"os\"\n\n\t\"go.uber.org/zap\"\n)\n\nfunc LoggerSync(logger *zap.Logger) func(context.Context) error {\n\treturn func(context.Context) error {\n\t\t// Currently Sync() return a different error depending on the OS.\n\t\t// Since these are not actionable ignore them.\n\t\terr := logger.Sync()\n\t\tosErr := &os.PathError{}\n\t\tif errors.As(err, &osErr) {\n\t\t\twrappedErr := osErr.Unwrap()\n\t\t\tif knownSyncError(wrappedErr) {\n\t\t\t\terr = nil\n\t\t\t}\n\t\t}\n\t\treturn err\n\t}\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/test_helpers.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlptext // import \"go.opentelemetry.io/collector/exporter/debugexporter/internal/otlptext\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/entity\"\n)\n\nfunc addEntityRefsToResource(resource pcommon.Resource) {\n\tentityRefs := entity.ResourceEntityRefs(resource)\n\n\tserviceRef := entityRefs.AppendEmpty()\n\tserviceRef.SetType(\"service\")\n\tserviceRef.SetSchemaUrl(\"https://opentelemetry.io/schemas/1.21.0\")\n\tserviceRef.IdKeys().Append(\"service.name\")\n\tserviceRef.DescriptionKeys().Append(\"service.version\")\n\n\tif _, exists := resource.Attributes().Get(\"host.name\"); exists {\n\t\thostRef := entityRefs.AppendEmpty()\n\t\thostRef.SetType(\"host\")\n\t\thostRef.IdKeys().Append(\"host.name\")\n\t}\n}\n\nfunc setupResourceWithEntityRefs(resource pcommon.Resource) {\n\tresource.Attributes().PutStr(\"service.name\", \"my-service\")\n\tresource.Attributes().PutStr(\"service.version\", \"1.0.0\")\n\tresource.Attributes().PutStr(\"host.name\", \"server-01\")\n\n\taddEntityRefsToResource(resource)\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/logs/embedded_maps.out",
    "content": "ResourceLog #0\nResource SchemaURL: \nScopeLogs #0\nScopeLogs SchemaURL: \nInstrumentationScope  \nLogRecord #0\nObservedTimestamp: 1970-01-01 00:00:00 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nSeverityText: INFO\nSeverityNumber: Info(9)\nBody: Map({\"key1\":\"val1\",\"key2\":{\"key21\":\"val21\",\"key22\":\"val22\"}})\nAttributes:\n     -> key1: Map({\"key11\":\"val11\",\"key12\":\"val12\",\"key13\":{\"key131\":\"val131\"}})\n     -> key2: Str(val2)\nTrace ID: \nSpan ID: \nFlags: 0\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/logs/empty.out",
    "content": ""
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/logs/log_with_event_name.out",
    "content": "ResourceLog #0\nResource SchemaURL: \nScopeLogs #0\nScopeLogs SchemaURL: \nInstrumentationScope  \nLogRecord #0\nObservedTimestamp: 1970-01-01 00:00:00 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nSeverityText: Info\nSeverityNumber: Info(9)\nEventName: event_name\nBody: Str(This is a log message)\nAttributes:\n     -> app: Str(server)\n     -> instance_num: Int(1)\nTrace ID: 08040201000000000000000000000000\nSpan ID: 0102040800000000\nFlags: 0\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/logs/logs_with_entity_refs.out",
    "content": "ResourceLog #0\nResource SchemaURL: \nResource attributes:\n     -> service.name: Str(my-service)\n     -> service.version: Str(1.0.0)\n     -> host.name: Str(server-01)\nResource entity refs:\n     -> Entity ref #0:\n          -> Type: service\n          -> Schema URL: https://opentelemetry.io/schemas/1.21.0\n          -> ID keys:\n               -> service.name\n          -> Description keys:\n               -> service.version\n     -> Entity ref #1:\n          -> Type: host\n          -> ID keys:\n               -> host.name\nScopeLogs #0\nScopeLogs SchemaURL: \nInstrumentationScope test-scope \nLogRecord #0\nObservedTimestamp: 1970-01-01 00:00:00 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nSeverityText: Info\nSeverityNumber: Info(9)\nBody: Str(This is a test log message)\nAttributes:\n     -> test.attribute: Str(test-value)\nTrace ID: \nSpan ID: \nFlags: 0\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/logs/one_record.out",
    "content": "ResourceLog #0\nResource SchemaURL: \nResource attributes:\n     -> resource-attr: Str(resource-attr-val-1)\nScopeLogs #0\nScopeLogs SchemaURL: \nInstrumentationScope  \nLogRecord #0\nObservedTimestamp: 1970-01-01 00:00:00 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nSeverityText: Info\nSeverityNumber: Info(9)\nBody: Str(This is a log message)\nAttributes:\n     -> app: Str(server)\n     -> instance_num: Int(1)\nTrace ID: 08040201000000000000000000000000\nSpan ID: 0102040800000000\nFlags: 0\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/logs/two_records.out",
    "content": "ResourceLog #0\nResource SchemaURL: \nResource attributes:\n     -> resource-attr: Str(resource-attr-val-1)\nScopeLogs #0\nScopeLogs SchemaURL: \nInstrumentationScope  \nLogRecord #0\nObservedTimestamp: 1970-01-01 00:00:00 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nSeverityText: Info\nSeverityNumber: Info(9)\nBody: Str(This is a log message)\nAttributes:\n     -> app: Str(server)\n     -> instance_num: Int(1)\nTrace ID: 08040201000000000000000000000000\nSpan ID: 0102040800000000\nFlags: 0\nLogRecord #1\nObservedTimestamp: 1970-01-01 00:00:00 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nSeverityText: Info\nSeverityNumber: Info(9)\nBody: Str(something happened)\nAttributes:\n     -> customer: Str(acme)\n     -> env: Str(dev)\nTrace ID: \nSpan ID: \nFlags: 0\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/metrics/empty.out",
    "content": ""
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/metrics/invalid_metric_type.out",
    "content": "ResourceMetrics #0\nResource SchemaURL: \nResource attributes:\n     -> resource-attr: Str(resource-attr-val-1)\nScopeMetrics #0\nScopeMetrics SchemaURL: \nInstrumentationScope  \nMetric #0\nDescriptor:\n     -> Name: sum-int\n     -> Description: \n     -> Unit: 1\n     -> DataType: Empty\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/metrics/metrics_with_all_types.out",
    "content": "ResourceMetrics #0\nResource SchemaURL: \nResource attributes:\n     -> resource-attr: Str(resource-attr-val-1)\nScopeMetrics #0\nScopeMetrics SchemaURL: \nInstrumentationScope  \nMetric #0\nDescriptor:\n     -> Name: gauge-int\n     -> Description: \n     -> Unit: 1\n     -> DataType: Gauge\nNumberDataPoints #0\nData point attributes:\n     -> label-1: Str(label-value-1)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nValue: 123\nNumberDataPoints #1\nData point attributes:\n     -> label-2: Str(label-value-2)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nValue: 456\nMetric #1\nDescriptor:\n     -> Name: gauge-double\n     -> Description: \n     -> Unit: 1\n     -> DataType: Gauge\nNumberDataPoints #0\nData point attributes:\n     -> label-1: Str(label-value-1)\n     -> label-2: Str(label-value-2)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nValue: 1.230000\nNumberDataPoints #1\nData point attributes:\n     -> label-1: Str(label-value-1)\n     -> label-3: Str(label-value-3)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nValue: 4.560000\nMetric #2\nDescriptor:\n     -> Name: sum-int\n     -> Description: \n     -> Unit: 1\n     -> DataType: Sum\n     -> IsMonotonic: true\n     -> AggregationTemporality: Cumulative\nNumberDataPoints #0\nData point attributes:\n     -> label-1: Str(label-value-1)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nValue: 123\nNumberDataPoints #1\nData point attributes:\n     -> label-2: Str(label-value-2)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nValue: 456\nMetric #3\nDescriptor:\n     -> Name: sum-double\n     -> Description: \n     -> Unit: 1\n     -> DataType: Sum\n     -> IsMonotonic: true\n     -> AggregationTemporality: Cumulative\nNumberDataPoints #0\nData point attributes:\n     -> label-1: Str(label-value-1)\n     -> label-2: Str(label-value-2)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nValue: 1.230000\nNumberDataPoints #1\nData point attributes:\n     -> label-1: Str(label-value-1)\n     -> label-3: Str(label-value-3)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nValue: 4.560000\nMetric #4\nDescriptor:\n     -> Name: histogram\n     -> Description: \n     -> Unit: 1\n     -> DataType: Histogram\n     -> AggregationTemporality: Cumulative\nHistogramDataPoints #0\nData point attributes:\n     -> label-1: Str(label-value-1)\n     -> label-3: Str(label-value-3)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nCount: 1\nSum: 15.000000\nHistogramDataPoints #1\nData point attributes:\n     -> label-2: Str(label-value-2)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nCount: 1\nSum: 15.000000\nMin: 15.000000\nMax: 15.000000\nExplicitBounds #0: 1.000000\nBuckets #0, Count: 0\nBuckets #1, Count: 1\nExemplars:\nExemplar #0\n     -> Trace ID: 0102030405060708090a0b0c0d0e0f10\n     -> Span ID: 1112131415161718\n     -> Timestamp: 2020-02-11 20:26:13.000000123 +0000 UTC\n     -> Value: 15.000000\n     -> FilteredAttributes:\n          -> exemplar-attachment: Str(exemplar-attachment-value)\nMetric #5\nDescriptor:\n     -> Name: exponential-histogram\n     -> Description: \n     -> Unit: 1\n     -> DataType: ExponentialHistogram\n     -> AggregationTemporality: Delta\nExponentialHistogramDataPoints #0\nData point attributes:\n     -> label-1: Str(label-value-1)\n     -> label-3: Str(label-value-3)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nCount: 5\nSum: 0.150000\nBucket [-1.414214, -1.000000), Count: 1\nBucket [-1.000000, -0.707107), Count: 1\nBucket [0, 0], Count: 1\nBucket (1.414214, 2.000000], Count: 1\nBucket (2.000000, 2.828427], Count: 1\nExponentialHistogramDataPoints #1\nData point attributes:\n     -> label-2: Str(label-value-2)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nCount: 3\nSum: 1.250000\nMin: 0.000000\nMax: 1.000000\nBucket [0, 0], Count: 1\nBucket (0.250000, 1.000000], Count: 1\nBucket (1.000000, 4.000000], Count: 1\nExemplars:\nExemplar #0\n     -> Trace ID: 0102030405060708090a0b0c0d0e0f10\n     -> Span ID: 1112131415161718\n     -> Timestamp: 2020-02-11 20:26:13.000000123 +0000 UTC\n     -> Value: 15\n     -> FilteredAttributes:\n          -> exemplar-attachment: Str(exemplar-attachment-value)\nMetric #6\nDescriptor:\n     -> Name: summary\n     -> Description: \n     -> Unit: 1\n     -> DataType: Summary\nSummaryDataPoints #0\nData point attributes:\n     -> label-1: Str(label-value-1)\n     -> label-3: Str(label-value-3)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nCount: 1\nSum: 15.000000\nSummaryDataPoints #1\nData point attributes:\n     -> label-2: Str(label-value-2)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nCount: 1\nSum: 15.000000\nQuantileValue #0: Quantile 0.010000, Value 15.000000\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/metrics/metrics_with_entity_refs.out",
    "content": "ResourceMetrics #0\nResource SchemaURL: \nResource attributes:\n     -> service.name: Str(my-service)\n     -> service.version: Str(1.0.0)\n     -> host.name: Str(server-01)\nResource entity refs:\n     -> Entity ref #0:\n          -> Type: service\n          -> Schema URL: https://opentelemetry.io/schemas/1.21.0\n          -> ID keys:\n               -> service.name\n          -> Description keys:\n               -> service.version\n     -> Entity ref #1:\n          -> Type: host\n          -> ID keys:\n               -> host.name\nScopeMetrics #0\nScopeMetrics SchemaURL: \nInstrumentationScope test-scope \nMetric #0\nDescriptor:\n     -> Name: test-metric\n     -> Description: A test metric\n     -> Unit: 1\n     -> DataType: Gauge\nNumberDataPoints #0\nData point attributes:\n     -> test.attribute: Str(test-value)\nStartTimestamp: 1970-01-01 00:00:00 +0000 UTC\nTimestamp: 1970-01-01 00:00:00 +0000 UTC\nValue: 123.450000\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/metrics/metrics_with_metadata.out",
    "content": "ResourceMetrics #0\nResource SchemaURL: \nResource attributes:\n     -> service.name: Str(test-service)\nScopeMetrics #0\nScopeMetrics SchemaURL: \nInstrumentationScope test-scope \nMetric #0\nDescriptor:\n     -> Name: test-metric-metadata\n     -> Description: A test metric with metadata\n     -> Unit: 1\n     -> DataType: Gauge\n     -> Metadata:\n          -> meta.key: Str(meta-value)\n          -> meta.id: Int(101)\nNumberDataPoints #0\nStartTimestamp: 1970-01-01 00:00:00 +0000 UTC\nTimestamp: 1970-01-01 00:00:00 +0000 UTC\nValue: 1\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/metrics/two_metrics.out",
    "content": "ResourceMetrics #0\nResource SchemaURL: \nResource attributes:\n     -> resource-attr: Str(resource-attr-val-1)\nScopeMetrics #0\nScopeMetrics SchemaURL: \nInstrumentationScope  \nMetric #0\nDescriptor:\n     -> Name: gauge-int\n     -> Description: \n     -> Unit: 1\n     -> DataType: Gauge\nNumberDataPoints #0\nData point attributes:\n     -> label-1: Str(label-value-1)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nValue: 123\nNumberDataPoints #1\nData point attributes:\n     -> label-2: Str(label-value-2)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nValue: 456\nMetric #1\nDescriptor:\n     -> Name: gauge-double\n     -> Description: \n     -> Unit: 1\n     -> DataType: Gauge\nNumberDataPoints #0\nData point attributes:\n     -> label-1: Str(label-value-1)\n     -> label-2: Str(label-value-2)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nValue: 1.230000\nNumberDataPoints #1\nData point attributes:\n     -> label-1: Str(label-value-1)\n     -> label-3: Str(label-value-3)\nStartTimestamp: 2020-02-11 20:26:12.000000321 +0000 UTC\nTimestamp: 2020-02-11 20:26:13.000000789 +0000 UTC\nValue: 4.560000\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/profiles/empty.out",
    "content": ""
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/profiles/profiles_with_entity_refs.out",
    "content": "String table:\n    \n    cpu\n    nanoseconds\nResourceProfiles #0\nResource SchemaURL: \nResource attributes:\n     -> service.name: Str(my-service)\n     -> service.version: Str(1.0.0)\n     -> host.name: Str(server-01)\nResource entity refs:\n     -> Entity ref #0:\n          -> Type: service\n          -> Schema URL: https://opentelemetry.io/schemas/1.21.0\n          -> ID keys:\n               -> service.name\n          -> Description keys:\n               -> service.version\n     -> Entity ref #1:\n          -> Type: host\n          -> ID keys:\n               -> host.name\nScopeProfiles #0\nScopeProfiles SchemaURL: \nInstrumentationScope test-scope \nProfile #0\n    Profile ID     : \n    Start time     : 1970-01-01 00:00:00 +0000 UTC\n    DurationNano   : 0\n    Dropped attributes count: 0\n    Sample #0\n        Values: [100]\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/profiles/two_profiles.out",
    "content": "Mapping #0\n    Memory start: 2\n    Memory limit: 3\n    File offset: 4\n    File name: 5\n    Attributes: [7 8]\nLocation #0\n    Mapping index: 0\n    Address: 1\n    Attributes: []\nLocation #1\n    Mapping index: 0\n    Address: 2\n    Attributes: []\nLocation #2\n    Mapping index: 3\n    Address: 4\n    Line #0\n        Function index: 1\n        Line: 2\n        Column: 3\n    Attributes: [6 7]\nFunction #0\n    Name: 2\n    System name: 3\n    Filename: 4\n    Start line: 5\nAttribute table:\n     -> Key: Int(2)\n     -> Value: Str()\n     -> unit: Int(5)\nLink table:\n     -> Trace ID: Str(0302030405060708090a0b0c0d0e0f10)\n     -> Span ID: Str(1112131415161718)\nString table:\n    \n    key\n    intValue\n    foobar\nResourceProfiles #0\nResource SchemaURL: \nResource attributes:\n     -> resource-attr: Str(resource-attr-val-1)\nScopeProfiles #0\nScopeProfiles SchemaURL: \nInstrumentationScope  \nProfile #0\n    Profile ID     : 0102030405060708090a0b0c0d0e0f10\n    Start time     : 2020-02-11 20:26:12.000000321 +0000 UTC\n    DurationNano   : 1000000000\n    Dropped attributes count: 1\n    Sample #0\n        Values: [4]\n        Attributes:\n             -> key: value-1\nProfile #1\n    Profile ID     : 0202030405060708090a0b0c0d0e0f10\n    Start time     : 2020-02-11 20:26:12.000000321 +0000 UTC\n    DurationNano   : 1000000000\n    Dropped attributes count: 0\n    Sample #0\n        Values: [9]\n        Attributes:\n             -> key: value-2\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/traces/empty.out",
    "content": ""
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/traces/traces_with_entity_refs.out",
    "content": "ResourceSpans #0\nResource SchemaURL: \nResource attributes:\n     -> service.name: Str(my-service)\n     -> service.version: Str(1.0.0)\n     -> host.name: Str(server-01)\nResource entity refs:\n     -> Entity ref #0:\n          -> Type: service\n          -> Schema URL: https://opentelemetry.io/schemas/1.21.0\n          -> ID keys:\n               -> service.name\n          -> Description keys:\n               -> service.version\n     -> Entity ref #1:\n          -> Type: host\n          -> ID keys:\n               -> host.name\nScopeSpans #0\nScopeSpans SchemaURL: \nInstrumentationScope test-scope \nSpan #0\n    Trace ID       : 0102030405060708090a0b0c0d0e0f10\n    Parent ID      : \n    ID             : 0102030405060708\n    Name           : test-span\n    Kind           : Unspecified\n    Start time     : 1970-01-01 00:00:00 +0000 UTC\n    End time       : 1970-01-01 00:00:00 +0000 UTC\n    Status code    : Unset\n    Status message : \n    DroppedAttributesCount: 0\n    DroppedEventsCount: 0\n    DroppedLinksCount: 0\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/testdata/traces/two_spans.out",
    "content": "ResourceSpans #0\nResource SchemaURL: \nResource attributes:\n     -> resource-attr: Str(resource-attr-val-1)\nScopeSpans #0\nScopeSpans SchemaURL: \nInstrumentationScope  \nSpan #0\n    Trace ID       : 0102030405060708090a0b0c0d0e0f10\n    Parent ID      : \n    ID             : 1112131415161718\n    Name           : operationA\n    Kind           : Unspecified\n    TraceState     : ot=th:0\n    Start time     : 2020-02-11 20:26:12.000000321 +0000 UTC\n    End time       : 2020-02-11 20:26:13.000000789 +0000 UTC\n    Status code    : Error\n    Status message : status-cancelled\n    DroppedAttributesCount: 1\n    DroppedEventsCount: 1\n    DroppedLinksCount: 0\nEvents:\nSpanEvent #0\n     -> Name: event-with-attr\n     -> Timestamp: 2020-02-11 20:26:13.000000123 +0000 UTC\n     -> DroppedAttributesCount: 2\n     -> Attributes::\n          -> span-event-attr: Str(span-event-attr-val)\nSpanEvent #1\n     -> Name: event\n     -> Timestamp: 2020-02-11 20:26:13.000000123 +0000 UTC\n     -> DroppedAttributesCount: 2\nSpan #1\n    Trace ID       : \n    Parent ID      : \n    ID             : \n    Name           : operationB\n    Kind           : Unspecified\n    Start time     : 2020-02-11 20:26:12.000000321 +0000 UTC\n    End time       : 2020-02-11 20:26:13.000000789 +0000 UTC\n    Status code    : Unset\n    Status message : \n    DroppedAttributesCount: 0\n    DroppedEventsCount: 0\n    DroppedLinksCount: 3\nLinks:\nSpanLink #0\n     -> Trace ID: \n     -> ID: \n     -> TraceState: \n     -> DroppedAttributesCount: 4\n     -> Attributes::\n          -> span-link-attr: Str(span-link-attr-val)\nSpanLink #1\n     -> Trace ID: \n     -> ID: \n     -> TraceState: \n     -> DroppedAttributesCount: 4\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/traces.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlptext // import \"go.opentelemetry.io/collector/exporter/debugexporter/internal/otlptext\"\n\nimport (\n\t\"strconv\"\n\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\n// NewTextTracesMarshaler returns a ptrace.Marshaler to encode to OTLP text bytes.\nfunc NewTextTracesMarshaler() ptrace.Marshaler {\n\treturn textTracesMarshaler{}\n}\n\ntype textTracesMarshaler struct{}\n\n// MarshalTraces ptrace.Traces to OTLP text.\nfunc (textTracesMarshaler) MarshalTraces(td ptrace.Traces) ([]byte, error) {\n\tbuf := dataBuffer{}\n\trss := td.ResourceSpans()\n\tfor i := 0; i < rss.Len(); i++ {\n\t\tbuf.logEntry(\"ResourceSpans #%d\", i)\n\t\trs := rss.At(i)\n\t\tbuf.logEntry(\"Resource SchemaURL: %s\", rs.SchemaUrl())\n\t\tbuf.logAttributes(\"Resource attributes\", rs.Resource().Attributes())\n\t\tbuf.logEntityRefs(rs.Resource())\n\t\tilss := rs.ScopeSpans()\n\t\tfor j := 0; j < ilss.Len(); j++ {\n\t\t\tbuf.logEntry(\"ScopeSpans #%d\", j)\n\t\t\tils := ilss.At(j)\n\t\t\tbuf.logEntry(\"ScopeSpans SchemaURL: %s\", ils.SchemaUrl())\n\t\t\tbuf.logInstrumentationScope(ils.Scope())\n\n\t\t\tspans := ils.Spans()\n\t\t\tfor k := 0; k < spans.Len(); k++ {\n\t\t\t\tbuf.logEntry(\"Span #%d\", k)\n\t\t\t\tspan := spans.At(k)\n\t\t\t\tbuf.logAttr(\"Trace ID\", span.TraceID())\n\t\t\t\tbuf.logAttr(\"Parent ID\", span.ParentSpanID())\n\t\t\t\tbuf.logAttr(\"ID\", span.SpanID())\n\t\t\t\tbuf.logAttr(\"Name\", span.Name())\n\t\t\t\tbuf.logAttr(\"Kind\", span.Kind().String())\n\t\t\t\tif ts := span.TraceState().AsRaw(); ts != \"\" {\n\t\t\t\t\tbuf.logAttr(\"TraceState\", ts)\n\t\t\t\t}\n\t\t\t\tbuf.logAttr(\"Start time\", span.StartTimestamp().String())\n\t\t\t\tbuf.logAttr(\"End time\", span.EndTimestamp().String())\n\n\t\t\t\tbuf.logAttr(\"Status code\", span.Status().Code().String())\n\t\t\t\tbuf.logAttr(\"Status message\", span.Status().Message())\n\n\t\t\t\tbuf.logAttr(\"DroppedAttributesCount\", strconv.FormatUint(uint64(span.DroppedAttributesCount()), 10))\n\t\t\t\tbuf.logAttr(\"DroppedEventsCount\", strconv.FormatUint(uint64(span.DroppedEventsCount()), 10))\n\t\t\t\tbuf.logAttr(\"DroppedLinksCount\", strconv.FormatUint(uint64(span.DroppedLinksCount()), 10))\n\n\t\t\t\tbuf.logAttributes(\"Attributes\", span.Attributes())\n\t\t\t\tbuf.logEvents(\"Events\", span.Events())\n\t\t\t\tbuf.logLinks(\"Links\", span.Links())\n\t\t\t}\n\t\t}\n\t}\n\n\treturn buf.buf.Bytes(), nil\n}\n"
  },
  {
    "path": "exporter/debugexporter/internal/otlptext/traces_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlptext\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestTracesText(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tin   ptrace.Traces\n\t\tout  string\n\t}{\n\t\t{\n\t\t\tname: \"empty_traces\",\n\t\t\tin:   ptrace.NewTraces(),\n\t\t\tout:  \"empty.out\",\n\t\t},\n\t\t{\n\t\t\tname: \"two_spans\",\n\t\t\tin:   testdata.GenerateTraces(2),\n\t\t\tout:  \"two_spans.out\",\n\t\t},\n\t\t{\n\t\t\tname: \"traces_with_entity_refs\",\n\t\t\tin:   generateTracesWithEntityRefs(),\n\t\t\tout:  \"traces_with_entity_refs.out\",\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot, err := NewTextTracesMarshaler().MarshalTraces(tt.in)\n\t\t\trequire.NoError(t, err)\n\t\t\tout, err := os.ReadFile(filepath.Join(\"testdata\", \"traces\", tt.out))\n\t\t\trequire.NoError(t, err)\n\t\t\texpected := strings.ReplaceAll(string(out), \"\\r\", \"\")\n\t\t\tassert.Equal(t, expected, string(got))\n\t\t})\n\t}\n}\n\nfunc generateTracesWithEntityRefs() ptrace.Traces {\n\ttd := ptrace.NewTraces()\n\trs := td.ResourceSpans().AppendEmpty()\n\n\tsetupResourceWithEntityRefs(rs.Resource())\n\n\tss := rs.ScopeSpans().AppendEmpty()\n\tss.Scope().SetName(\"test-scope\")\n\tspan := ss.Spans().AppendEmpty()\n\tspan.SetName(\"test-span\")\n\tspan.SetSpanID([8]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08})\n\tspan.SetTraceID([16]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10})\n\n\treturn td\n}\n"
  },
  {
    "path": "exporter/debugexporter/metadata.yaml",
    "content": "display_name: Debug Exporter\ntype: debug\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  codeowners:\n    active:\n      - andrzej-stencel\n  class: exporter\n  stability:\n    alpha: [traces, metrics, logs, profiles]\n  distributions: [core, contrib, k8s]\n  warnings: [Unstable Output Format]\n"
  },
  {
    "path": "exporter/debugexporter/testdata/config_output_paths.yaml",
    "content": "use_internal_logger: false\noutput_paths:\n  - stderr\n\n"
  },
  {
    "path": "exporter/debugexporter/testdata/config_output_paths_empty.yaml",
    "content": "use_internal_logger: false\noutput_paths: []\n\n"
  },
  {
    "path": "exporter/debugexporter/testdata/config_verbosity.yaml",
    "content": "verbosity: detailed\nsampling_initial: 10\nsampling_thereafter: 50\nuse_internal_logger: false\noutput_paths:\n  - stdout\n"
  },
  {
    "path": "exporter/debugexporter/testdata/config_verbosity_typo.yaml",
    "content": "# Typo in the configuration that assumes that this property is camelcase\nverBosity: detailed\n"
  },
  {
    "path": "exporter/example_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exporter_test\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configretry\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\n// typeStr defines the unique type identifier for the exporter.\nvar typeStr = component.MustNewType(\"example\")\n\n// exampleConfig holds configuration settings for the exporter.\ntype exampleConfig struct {\n\tQueueSettings configoptional.Optional[exporterhelper.QueueBatchConfig]\n\tBackOffConfig configretry.BackOffConfig\n}\n\n// exampleExporter implements the OpenTelemetry exporter interface.\ntype exampleExporter struct {\n\tcancel context.CancelFunc\n\tconfig exampleConfig\n\tclient *loggerClient\n}\n\n// loggerClient wraps a Zap logger to provide logging functionality.\ntype loggerClient struct {\n\tlogger *zap.Logger\n}\n\n// Example demonstrates the usage of the exporter factory.\nfunc Example() {\n\t// Instantiate the exporter factory and print its type.\n\texampleExporter := NewFactory()\n\tfmt.Println(exampleExporter.Type())\n\n\t// Output:\n\t// example\n}\n\n// NewFactory creates a new exporter factory.\nfunc NewFactory() exporter.Factory {\n\treturn exporter.NewFactory(\n\t\ttypeStr,\n\t\tcreateDefaultConfig,\n\t\texporter.WithMetrics(createExampleExporter, component.StabilityLevelAlpha),\n\t)\n}\n\n// createDefaultConfig returns the default configuration for the exporter.\nfunc createDefaultConfig() component.Config {\n\treturn &exampleConfig{}\n}\n\n// createExampleExporter initializes an instance of the example exporter.\nfunc createExampleExporter(ctx context.Context, params exporter.Settings, baseCfg component.Config) (exporter.Metrics, error) {\n\t// Convert baseCfg to the correct type.\n\tcfg := baseCfg.(*exampleConfig)\n\n\t// Create a new exporter instance.\n\txptr := newExampleExporter(ctx, cfg, params)\n\n\t// Wrap the exporter with the helper utilities.\n\treturn exporterhelper.NewMetrics(\n\t\tctx,\n\t\tparams,\n\t\tcfg,\n\t\txptr.consumeMetrics,\n\t\texporterhelper.WithQueue(cfg.QueueSettings),\n\t\texporterhelper.WithRetry(cfg.BackOffConfig),\n\t\texporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),\n\t\texporterhelper.WithShutdown(xptr.shutdown),\n\t)\n}\n\n// newExampleExporter constructs a new instance of the example exporter.\nfunc newExampleExporter(ctx context.Context, cfg *exampleConfig, params exporter.Settings) *exampleExporter {\n\txptr := &exampleExporter{\n\t\tconfig: *cfg,\n\t\tclient: &loggerClient{logger: params.Logger},\n\t}\n\n\t// Create a cancelable context.\n\t_, xptr.cancel = context.WithCancel(ctx)\n\n\treturn xptr\n}\n\n// consumeMetrics processes incoming metric data and logs it.\nfunc (xptr *exampleExporter) consumeMetrics(_ context.Context, md pmetric.Metrics) error {\n\txptr.client.Push(md)\n\treturn nil\n}\n\n// Shutdown properly stops the exporter and releases resources.\nfunc (xptr *exampleExporter) shutdown(_ context.Context) error {\n\txptr.cancel()\n\treturn nil\n}\n\n// Push logs the received metric data.\nfunc (client *loggerClient) Push(md pmetric.Metrics) {\n\tclient.logger.Info(\"Exporting metrics\", zap.Any(\"metrics\", md))\n}\n"
  },
  {
    "path": "exporter/exporter.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exporter // import \"go.opentelemetry.io/collector/exporter\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\n// Traces is an exporter that can consume traces.\ntype Traces interface {\n\tcomponent.Component\n\tconsumer.Traces\n}\n\n// Metrics is an exporter that can consume metrics.\ntype Metrics interface {\n\tcomponent.Component\n\tconsumer.Metrics\n}\n\n// Logs is an exporter that can consume logs.\ntype Logs interface {\n\tcomponent.Component\n\tconsumer.Logs\n}\n\n// Settings configures exporter creators.\ntype Settings struct {\n\t// ID returns the ID of the component that will be created.\n\tID component.ID\n\n\tcomponent.TelemetrySettings\n\n\t// BuildInfo can be used by components for informational purposes\n\tBuildInfo component.BuildInfo\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// Factory is factory interface for exporters.\n//\n// This interface cannot be directly implemented. Implementations must\n// use the NewFactory to implement it.\ntype Factory interface {\n\tcomponent.Factory\n\n\t// CreateTraces creates a Traces exporter based on this config.\n\t// If the exporter type does not support tracing,\n\t// this function returns the error [pipeline.ErrSignalNotSupported].\n\tCreateTraces(ctx context.Context, set Settings, cfg component.Config) (Traces, error)\n\n\t// TracesStability gets the stability level of the Traces exporter.\n\tTracesStability() component.StabilityLevel\n\n\t// CreateMetrics creates a Metrics exporter based on this config.\n\t// If the exporter type does not support metrics,\n\t// this function returns the error [pipeline.ErrSignalNotSupported].\n\tCreateMetrics(ctx context.Context, set Settings, cfg component.Config) (Metrics, error)\n\n\t// MetricsStability gets the stability level of the Metrics exporter.\n\tMetricsStability() component.StabilityLevel\n\n\t// CreateLogs creates a Logs exporter based on the config.\n\t// If the exporter type does not support logs,\n\t// this function returns the error [pipeline.ErrSignalNotSupported].\n\tCreateLogs(ctx context.Context, set Settings, cfg component.Config) (Logs, error)\n\n\t// LogsStability gets the stability level of the Logs exporter.\n\tLogsStability() component.StabilityLevel\n\n\tunexportedFactoryFunc()\n}\n\n// FactoryOption apply changes to Factory.\ntype FactoryOption interface {\n\t// applyOption applies the option.\n\tapplyOption(o *factory)\n}\n\nvar _ FactoryOption = (*factoryOptionFunc)(nil)\n\n// factoryOptionFunc is an FactoryOption created through a function.\ntype factoryOptionFunc func(*factory)\n\nfunc (f factoryOptionFunc) applyOption(o *factory) {\n\tf(o)\n}\n\n// CreateTracesFunc is the equivalent of Factory.CreateTraces.\ntype CreateTracesFunc func(context.Context, Settings, component.Config) (Traces, error)\n\n// CreateMetricsFunc is the equivalent of Factory.CreateMetrics.\ntype CreateMetricsFunc func(context.Context, Settings, component.Config) (Metrics, error)\n\n// CreateLogsFunc is the equivalent of Factory.CreateLogs.\ntype CreateLogsFunc func(context.Context, Settings, component.Config) (Logs, error)\n\ntype factory struct {\n\tcfgType component.Type\n\tcomponent.CreateDefaultConfigFunc\n\tcomponentalias.TypeAliasHolder\n\tcreateTracesFunc      CreateTracesFunc\n\ttracesStabilityLevel  component.StabilityLevel\n\tcreateMetricsFunc     CreateMetricsFunc\n\tmetricsStabilityLevel component.StabilityLevel\n\tcreateLogsFunc        CreateLogsFunc\n\tlogsStabilityLevel    component.StabilityLevel\n}\n\nfunc (f *factory) Type() component.Type {\n\treturn f.cfgType\n}\n\nfunc (f *factory) unexportedFactoryFunc() {}\n\nfunc (f *factory) TracesStability() component.StabilityLevel {\n\treturn f.tracesStabilityLevel\n}\n\nfunc (f *factory) MetricsStability() component.StabilityLevel {\n\treturn f.metricsStabilityLevel\n}\n\nfunc (f *factory) LogsStability() component.StabilityLevel {\n\treturn f.logsStabilityLevel\n}\n\nfunc (f *factory) CreateTraces(ctx context.Context, set Settings, cfg component.Config) (Traces, error) {\n\tif f.createTracesFunc == nil {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createTracesFunc(ctx, set, cfg)\n}\n\nfunc (f *factory) CreateMetrics(ctx context.Context, set Settings, cfg component.Config) (Metrics, error) {\n\tif f.createMetricsFunc == nil {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createMetricsFunc(ctx, set, cfg)\n}\n\nfunc (f *factory) CreateLogs(ctx context.Context, set Settings, cfg component.Config) (Logs, error) {\n\tif f.createLogsFunc == nil {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createLogsFunc(ctx, set, cfg)\n}\n\n// WithTraces overrides the default \"error not supported\" implementation for Factory.CreateTraces and the default \"undefined\" stability level.\nfunc WithTraces(createTraces CreateTracesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.tracesStabilityLevel = sl\n\t\to.createTracesFunc = createTraces\n\t})\n}\n\n// WithMetrics overrides the default \"error not supported\" implementation for Factory.CreateMetrics and the default \"undefined\" stability level.\nfunc WithMetrics(createMetrics CreateMetricsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.metricsStabilityLevel = sl\n\t\to.createMetricsFunc = createMetrics\n\t})\n}\n\n// WithLogs overrides the default \"error not supported\" implementation for Factory.CreateLogs and the default \"undefined\" stability level.\nfunc WithLogs(createLogs CreateLogsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.logsStabilityLevel = sl\n\t\to.createLogsFunc = createLogs\n\t})\n}\n\n// NewFactory returns a Factory.\nfunc NewFactory(cfgType component.Type, createDefaultConfig component.CreateDefaultConfigFunc, options ...FactoryOption) Factory {\n\tf := &factory{\n\t\tcfgType:                 cfgType,\n\t\tCreateDefaultConfigFunc: createDefaultConfig,\n\t\tTypeAliasHolder:         componentalias.NewTypeAliasHolder(),\n\t}\n\tfor _, opt := range options {\n\t\topt.applyOption(f)\n\t}\n\treturn f\n}\n"
  },
  {
    "path": "exporter/exporter_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exporter\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/exporter/internal/experr\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\nvar (\n\ttestType = component.MustNewType(\"test\")\n\ttestID   = component.NewID(testType)\n)\n\nfunc TestNewFactory(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tf := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg })\n\tassert.Equal(t, testType, f.Type())\n\tassert.EqualValues(t, &defaultCfg, f.CreateDefaultConfig())\n\t_, err := f.CreateTraces(context.Background(), Settings{ID: testID}, &defaultCfg)\n\trequire.ErrorIs(t, err, pipeline.ErrSignalNotSupported)\n\t_, err = f.CreateMetrics(context.Background(), Settings{ID: testID}, &defaultCfg)\n\trequire.ErrorIs(t, err, pipeline.ErrSignalNotSupported)\n\t_, err = f.CreateLogs(context.Background(), Settings{ID: testID}, &defaultCfg)\n\trequire.ErrorIs(t, err, pipeline.ErrSignalNotSupported)\n}\n\nfunc TestNewFactoryWithOptions(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tf := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg },\n\t\tWithTraces(createTraces, component.StabilityLevelDevelopment),\n\t\tWithMetrics(createMetrics, component.StabilityLevelAlpha),\n\t\tWithLogs(createLogs, component.StabilityLevelDeprecated))\n\tassert.Equal(t, testType, f.Type())\n\tassert.EqualValues(t, &defaultCfg, f.CreateDefaultConfig())\n\n\twrongID := component.MustNewID(\"wrong\")\n\twrongIDErrStr := experr.ErrIDMismatch(wrongID, testType).Error()\n\n\tassert.Equal(t, component.StabilityLevelDevelopment, f.TracesStability())\n\t_, err := f.CreateTraces(context.Background(), Settings{ID: testID}, &defaultCfg)\n\trequire.NoError(t, err)\n\t_, err = f.CreateTraces(context.Background(), Settings{ID: wrongID}, &defaultCfg)\n\trequire.EqualError(t, err, wrongIDErrStr)\n\n\tassert.Equal(t, component.StabilityLevelAlpha, f.MetricsStability())\n\t_, err = f.CreateMetrics(context.Background(), Settings{ID: testID}, &defaultCfg)\n\trequire.NoError(t, err)\n\t_, err = f.CreateMetrics(context.Background(), Settings{ID: wrongID}, &defaultCfg)\n\trequire.EqualError(t, err, wrongIDErrStr)\n\n\tassert.Equal(t, component.StabilityLevelDeprecated, f.LogsStability())\n\t_, err = f.CreateLogs(context.Background(), Settings{ID: testID}, &defaultCfg)\n\trequire.NoError(t, err)\n\t_, err = f.CreateLogs(context.Background(), Settings{ID: wrongID}, &defaultCfg)\n\trequire.EqualError(t, err, wrongIDErrStr)\n}\n\nvar nopInstance = &nop{\n\tConsumer: consumertest.NewNop(),\n}\n\n// nop stores consumed traces and metrics for testing purposes.\ntype nop struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumertest.Consumer\n}\n\nfunc createTraces(context.Context, Settings, component.Config) (Traces, error) {\n\treturn nopInstance, nil\n}\n\nfunc createMetrics(context.Context, Settings, component.Config) (Metrics, error) {\n\treturn nopInstance, nil\n}\n\nfunc createLogs(context.Context, Settings, component.Config) (Logs, error) {\n\treturn nopInstance, nil\n}\n"
  },
  {
    "path": "exporter/exporterhelper/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "exporter/exporterhelper/README.md",
    "content": "# Exporter Helper\n\nThis package provides reusable implementations of common capabilities for exporters.\nCurrently, this includes queuing, batching, timeouts, and retries.\n\n## Configuration\n\nThe following configuration options can be modified:\n\n### Retry on Failure\n\n- `retry_on_failure`\n  - `enabled` (default = true)\n  - `initial_interval` (default = 5s): Time to wait after the first failure before retrying; ignored if `enabled` is `false`\n  - `max_interval` (default = 30s): Is the upper bound on backoff; ignored if `enabled` is `false`\n  - `max_elapsed_time` (default = 300s): Is the maximum amount of time spent trying to send a batch; ignored if `enabled` is `false`. If set to 0, the retries are never stopped.\n  - `multiplier` (default = 1.5): Factor by which the retry interval is multiplied on each attempt; ignored if `enabled` is `false`\n\n### Sending Queue\n\n- `sending_queue`\n  - `enabled` (default = true)\n  - `num_consumers` (default = 10): Number of consumers that dequeue batches; ignored if `enabled` is `false`\n  - `wait_for_result` (default = false): determines if incoming requests are blocked until the request is processed or not.\n  - `block_on_overflow` (default = false): If true, blocks the request until the queue has space otherwise rejects the data immediately; ignored if `enabled` is `false`\n  - `sizer` (default = requests): How the queue and batching is measured. Available options: \n    - `requests`: number of incoming batches of metrics, logs, traces (the most performant option);\n    - `items`: number of the smallest parts of each signal (spans, metric data points, log records);\n    - `bytes`: the size of serialized data in bytes (the least performant option).\n  - `queue_size` (default = 1000): Maximum size the queue can accept. Measured in units defined by `sizer`\n  - `batch`: see below.\n\n**Failure behavior**: If data cannot be added to the sending queue, it is typically dropped. This occurs when the queue has reached its configured capacity or, for persistent queues, when the underlying storage cannot accept additional data (for example, due to insufficient disk space or I/O errors).\n\nWhen `block_on_overflow` is enabled, the caller may instead wait until space becomes available, and the request may still be enqueued if capacity frees up before the timeout.\n\nIf data is rejected before entering the queue, it does not reach the exporter retry logic. Such enqueue failures are reported by the `otelcol_exporter_enqueue_failed_*` metrics.\n\n#### Sending queue batch settings\n\nBatch settings are available in the sending queue. Batching is disabled, by default. To enable default\nbatch settings, use `batch: {}`. When `batch` is defined, the settings are:\n\n- `flush_timeout` (default = 200 ms): time after which a batch will be sent regardless of its size. Must be a non-zero value;\n- `min_size` (default = 8192): the minimum size of a batch; should be less than or equal to the `sending_queue::queue_size` if `sending_queue::batch::sizer` matches `sending_queue::sizer`.\n- `max_size` (default = 0): the maximum size of a batch, enables batch splitting. The maximum size of a batch should be greater than or equal to the minimum size of a batch. If set to zero, there is no maximum size;\n- `sizer`: see below.\n- `partition`: see below.\n\nThe `batch::sizer` field is given special treatment because the queue itself also defines a `sizer`. This field supports using different size limits for the queue and batch-related logic. \n\nIf the `batch::sizer` field is not set, it takes its value from the parent structure. \n\nIf `sending_queue::sizer` is not set, `batch::sizer` defaults to `items`. \n\nAvailable `batch::sizer` options:\n\n- `items`: number of the smallest parts of each signal (spans, metric data points, log records);\n- `bytes`: the size of serialized data in bytes (the least performant option).\n\nThe `batch::partition` configuration defines the partitioning of the batches.\n\nAvailable `batch::partition` options:\n\n- `metadata_keys`: a list of `client.Metadata` keys used to partition data into\n  separate batches. When empty, a single batcher instance is used. When set, one batcher will be used\n  per distinct combination of values for the listed metadata keys. Empty value and unset metadata are\n  treated as distinct cases. Entries are case-insensitive. Duplicated entries will trigger a validation error. Default is empty.\n\n### Timeout\n\n- `timeout` (default = 5s): Time to wait per individual attempt to send data to a backend\n\nThe `initial_interval`, `max_interval`, `max_elapsed_time`, and `timeout` options accept \n[duration strings](https://pkg.go.dev/time#ParseDuration),\nvalid time units are \"ns\", \"us\" (or \"µs\"), \"ms\", \"s\", \"m\", \"h\".\n\n### Persistent Queue\n\nTo use the persistent queue, the following setting needs to be set:\n\n- `sending_queue`\n  - `storage` (default = none): When set, enables persistence and uses the component specified as a storage extension for the persistent queue.\n    There is no in-memory queue when set.\n\nThe maximum number of batches stored to disk can be controlled using `sending_queue.queue_size` parameter (which,\nsimilarly as for in-memory buffering, defaults to 1000 batches).\n\nWhen persistent queue is enabled, the batches are being buffered using the provided storage extension - [filestorage] is a popular and safe choice. If the collector instance is killed while having some items in the persistent queue, on restart the items will be picked and the exporting is continued.\n\n**Context Propagation**: Request context (including client metadata and span context) is preserved when using persistent queues. However, context set by Auth extensions is **not** propagated through the persistent queue. Auth extension context is ignored when data is persisted to disk, which means authentication/authorization information will not be available when the persisted data is processed.\n\n```\n                                                              ┌─Consumer #1─┐\n                                                              │    ┌───┐    │\n                              ──────Deleted──────        ┌───►│    │ 1 │    ├───► Success\n        Waiting in channel    x           x     x        │    │    └───┘    │\n        for consumer ───┐     x           x     x        │    │             │\n                        │     x           x     x        │    └─────────────┘\n                        ▼     x           x     x        │\n┌─────────────────────────────────────────x─────x───┐    │    ┌─Consumer #2─┐\n│                             x           x     x   │    │    │    ┌───┐    │\n│     ┌───┐     ┌───┐ ┌───┐ ┌─x─┐ ┌───┐ ┌─x─┐ ┌─x─┐ │    │    │    │ 2 │    ├───► Permanent -> X\n│ n+1 │ n │ ... │ 6 │ │ 5 │ │ 4 │ │ 3 │ │ 2 │ │ 1 │ ├────┼───►│    └───┘    │      failure\n│     └───┘     └───┘ └───┘ └───┘ └───┘ └───┘ └───┘ │    │    │             │\n│                                                   │    │    └─────────────┘\n└───────────────────────────────────────────────────┘    │\n   ▲              ▲     ▲           ▲                    │    ┌─Consumer #3─┐\n   │              │     │           │                    │    │    ┌───┐    │\n   │              │     │           │                    │    │    │ 3 │    ├───► (in progress)\n write          read    └─────┬─────┘                    ├───►│    └───┘    │\n index          index         │                          │    │             │\n                              │                          │    └─────────────┘\n                              │                          │\n                          currently                      │    ┌─Consumer #4─┐\n                          dispatched                     │    │    ┌───┐    │     Temporary\n                                                         └───►│    │ 4 │    ├───►  failure\n                                                              │    └───┘    │         │\n                                                              │             │         │\n                                                              └─────────────┘         │\n                                                                     ▲                │\n                                                                     └── Retry ───────┤\n                                                                                      │\n                                                                                      │\n                                                   X  ◄────── Retry limit exceeded ───┘\n```\n\nExample:\n\n```\nreceivers:\n  otlp:\n    protocols:\n      grpc:\nexporters:\n  otlp_grpc:\n    endpoint: <ENDPOINT>\n    sending_queue:\n      storage: file_storage/otc\nextensions:\n  file_storage/otc:\n    directory: /var/lib/storage/otc\n    timeout: 10s\nservice:\n  extensions: [file_storage]\n  pipelines:\n    metrics:\n      receivers: [otlp]\n      exporters: [otlp]\n    logs:\n      receivers: [otlp]\n      exporters: [otlp]\n    traces:\n      receivers: [otlp]\n      exporters: [otlp]\n\n```\n\n[filestorage]: https://github.com/open-telemetry/opentelemetry-collector-contrib/tree/main/extension/storage/filestorage\n"
  },
  {
    "path": "exporter/exporterhelper/common.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exporterhelper // import \"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configretry\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n)\n\n// Option apply changes to BaseExporter.\ntype Option = internal.Option\n\n// WithStart overrides the default Start function for an exporter.\n// The default start function does nothing and always returns nil.\nfunc WithStart(start component.StartFunc) Option {\n\treturn internal.WithStart(start)\n}\n\n// WithShutdown overrides the default Shutdown function for an exporter.\n// The default shutdown function does nothing and always returns nil.\nfunc WithShutdown(shutdown component.ShutdownFunc) Option {\n\treturn internal.WithShutdown(shutdown)\n}\n\n// WithTimeout overrides the default TimeoutConfig for an exporter.\n// The default TimeoutConfig is 5 seconds.\nfunc WithTimeout(timeoutConfig TimeoutConfig) Option {\n\treturn internal.WithTimeout(timeoutConfig)\n}\n\n// WithRetry overrides the default configretry.BackOffConfig for an exporter.\n// The default configretry.BackOffConfig is to disable retries.\nfunc WithRetry(config configretry.BackOffConfig) Option {\n\treturn internal.WithRetry(config)\n}\n\n// WithCapabilities overrides the default Capabilities() function for a Consumer.\n// The default is non-mutable data.\n// TODO: Verify if we can change the default to be mutable as we do for processors.\nfunc WithCapabilities(capabilities consumer.Capabilities) Option {\n\treturn internal.WithCapabilities(capabilities)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/config.schema.yaml",
    "content": "$defs:\n  batch_config:\n    description: BatchConfig defines a configuration for batching requests based on a timeout and a minimum number of items.\n    $ref: ./internal/queuebatch.batch_config\n  option:\n    description: Option apply changes to BaseExporter.\n    $ref: ./internal.option\n  queue_batch_config:\n    description: QueueBatchConfig defines configuration for queueing and batching for the exporter.\n    $ref: ./internal/queuebatch.config\n  request_sizer_type:\n    $ref: ./internal/request.sizer_type\n  timeout_config:\n    $ref: ./internal.timeout_config\n"
  },
  {
    "path": "exporter/exporterhelper/constants.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exporterhelper // import \"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\nimport (\n\t\"errors\"\n)\n\nvar (\n\t// errNilConfig is returned when an empty name is given.\n\terrNilConfig = errors.New(\"nil config\")\n\t// errNilLogger is returned when a logger is nil\n\terrNilLogger = errors.New(\"nil logger\")\n\t// errNilPushTraces is returned when a nil PushTraces is given.\n\terrNilPushTraces = errors.New(\"nil PushTraces\")\n\t// errNilPushMetrics is returned when a nil PushMetrics is given.\n\terrNilPushMetrics = errors.New(\"nil PushMetrics\")\n\t// errNilPushLogs is returned when a nil PushLogs is given.\n\terrNilPushLogs = errors.New(\"nil PushLogs\")\n)\n"
  },
  {
    "path": "exporter/exporterhelper/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\n// Package exporterhelper provides helper functions for exporters.\npackage exporterhelper // import \"go.opentelemetry.io/collector/exporter/exporterhelper\"\n"
  },
  {
    "path": "exporter/exporterhelper/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# exporterhelper\n\n## Internal Telemetry\n\nThe following telemetry is emitted by this component.\n\n### otelcol_exporter_enqueue_failed_log_records\n\nNumber of log records failed to be added to the sending queue.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {record} | Sum | Int | true | Alpha |\n\n### otelcol_exporter_enqueue_failed_metric_points\n\nNumber of metric points failed to be added to the sending queue.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {datapoint} | Sum | Int | true | Alpha |\n\n### otelcol_exporter_enqueue_failed_profile_samples\n\nNumber of profile samples failed to be added to the sending queue.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {sample} | Sum | Int | true | Development |\n\n### otelcol_exporter_enqueue_failed_spans\n\nNumber of spans failed to be added to the sending queue.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {span} | Sum | Int | true | Alpha |\n\n### otelcol_exporter_queue_batch_send_size\n\nNumber of units in the batch\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| {unit} | Histogram | Int | Development |\n\n### otelcol_exporter_queue_batch_send_size_bytes\n\nNumber of bytes in batch that was sent. Only available on detailed level.\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| By | Histogram | Int | Development |\n\n### otelcol_exporter_queue_capacity\n\nFixed capacity of the retry queue (in batches).\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| {batch} | Gauge | Int | Alpha |\n\n### otelcol_exporter_queue_size\n\nCurrent size of the retry queue (in batches).\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| {batch} | Gauge | Int | Alpha |\n\n### otelcol_exporter_send_failed_log_records\n\nNumber of log records in failed attempts to send to destination. At detailed telemetry level, includes attributes: error.type (semantic convention), error.permanent.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {record} | Sum | Int | true | Alpha |\n\n### otelcol_exporter_send_failed_metric_points\n\nNumber of metric points in failed attempts to send to destination. At detailed telemetry level, includes attributes: error.type (semantic convention), error.permanent.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {datapoint} | Sum | Int | true | Alpha |\n\n### otelcol_exporter_send_failed_profile_samples\n\nNumber of profile samples in failed attempts to send to destination. At detailed telemetry level, includes attributes: error.type (semantic convention), error.permanent.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {sample} | Sum | Int | true | Development |\n\n### otelcol_exporter_send_failed_spans\n\nNumber of spans in failed attempts to send to destination. At detailed telemetry level, includes attributes: error.type (semantic convention), error.permanent.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {span} | Sum | Int | true | Alpha |\n\n### otelcol_exporter_sent_log_records\n\nNumber of log record successfully sent to destination.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {record} | Sum | Int | true | Alpha |\n\n### otelcol_exporter_sent_metric_points\n\nNumber of metric points successfully sent to destination.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {datapoint} | Sum | Int | true | Alpha |\n\n### otelcol_exporter_sent_profile_samples\n\nNumber of profile samples successfully sent to destination.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {sample} | Sum | Int | true | Development |\n\n### otelcol_exporter_sent_spans\n\nNumber of spans successfully sent to destination.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {span} | Sum | Int | true | Alpha |\n\n## Feature Gates\n\nThis component has the following feature gates:\n\n| Feature Gate | Stage | Description | From Version | To Version | Reference |\n| ------------ | ----- | ----------- | ------------ | ---------- | --------- |\n| `exporter.PersistRequestContext` | beta | controls whether context should be stored alongside requests in the persistent queue | v0.128.0 | N/A | [Link](https://github.com/open-telemetry/opentelemetry-collector/pull/13188) |\n\nFor more information about feature gates, see the [Feature Gates](https://github.com/open-telemetry/opentelemetry-collector/blob/main/featuregate/README.md) documentation.\n"
  },
  {
    "path": "exporter/exporterhelper/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage exporterhelper\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/go.mod",
    "content": "module go.opentelemetry.io/collector/exporter/exporterhelper\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/cenkalti/backoff/v5 v5.0.3\n\tgithub.com/hashicorp/golang-lru/v2 v2.0.7\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/client v1.54.0\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/config/configoptional v1.54.0\n\tgo.opentelemetry.io/collector/config/configretry v1.54.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/exporter v1.54.0\n\tgo.opentelemetry.io/collector/exporter/exportertest v0.148.0\n\tgo.opentelemetry.io/collector/extension/extensiontest v0.148.0\n\tgo.opentelemetry.io/collector/extension/xextension v0.148.0\n\tgo.opentelemetry.io/collector/featuregate v1.54.0\n\tgo.opentelemetry.io/collector/internal/testutil v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.opentelemetry.io/collector/pdata/xpdata v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0\n\tgo.opentelemetry.io/otel v1.42.0\n\tgo.opentelemetry.io/otel/metric v1.42.0\n\tgo.opentelemetry.io/otel/sdk v1.42.0\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0\n\tgo.opentelemetry.io/otel/trace v1.42.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/multierr v1.11.0\n\tgo.uber.org/zap v1.27.1\n\tgoogle.golang.org/grpc v1.79.3\n\tgoogle.golang.org/protobuf v1.36.11\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/exporter/xexporter v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/receivertest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/extension => ../../extension\n\nreplace go.opentelemetry.io/collector/exporter => ../\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/receiver => ../../receiver\n\nreplace go.opentelemetry.io/collector/config/configretry => ../../config/configretry\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../../receiver/receivertest\n\nreplace go.opentelemetry.io/collector/exporter/xexporter => ../xexporter\n\nreplace go.opentelemetry.io/collector/exporter/exportertest => ../exportertest\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../../extension/extensiontest\n\nreplace go.opentelemetry.io/collector/extension/xextension => ../../extension/xextension\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/client => ../../client\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../../config/configoptional\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n"
  },
  {
    "path": "exporter/exporterhelper/go.sum",
    "content": "github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=\ngithub.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "exporter/exporterhelper/internal/base_exporter.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"go.uber.org/multierr\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configretry\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\n// Option apply changes to BaseExporter.\ntype Option func(*BaseExporter) error\n\n// BaseExporter contains common fields between different exporter types.\ntype BaseExporter struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\n\tSet exporter.Settings\n\n\t// Message for the user to be added with an export failure message.\n\tExportFailureMessage string\n\n\t// Chain of senders that the exporter helper applies before passing the data to the actual exporter.\n\t// The data is handled by each sender in the respective order starting from the QueueBatch.\n\t// Most of the senders are optional, and initialized with a no-op path-through sender.\n\tQueueSender sender.Sender[request.Request]\n\tRetrySender sender.Sender[request.Request]\n\n\tfirstSender sender.Sender[request.Request]\n\n\tConsumerOptions []consumer.Option\n\n\ttimeoutCfg TimeoutConfig\n\tretryCfg   configretry.BackOffConfig\n\n\tqueueBatchSettings queuebatch.Settings[request.Request]\n\tqueueCfg           configoptional.Optional[queuebatch.Config]\n}\n\nfunc NewBaseExporter(set exporter.Settings, signal pipeline.Signal, pusher sender.SendFunc[request.Request], options ...Option) (*BaseExporter, error) {\n\tbe := &BaseExporter{\n\t\tSet:        set,\n\t\ttimeoutCfg: NewDefaultTimeoutConfig(),\n\t}\n\n\tfor _, op := range options {\n\t\tif err := op(be); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\t// Consumer Sender is always initialized.\n\tbe.firstSender = sender.NewSender(pusher)\n\n\t// Next setup the timeout Sender since we want the timeout to control only the export functionality.\n\t// Only initialize if not explicitly disabled.\n\tif be.timeoutCfg.Timeout != 0 {\n\t\tbe.firstSender = newTimeoutSender(be.timeoutCfg, be.firstSender)\n\t}\n\n\tif be.retryCfg.Enabled {\n\t\tbe.RetrySender = newRetrySender(be.retryCfg, set, be.firstSender)\n\t\tbe.firstSender = be.RetrySender\n\t}\n\n\tvar err error\n\tbe.firstSender, err = newObsReportSender(set, signal, be.firstSender)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tif be.queueCfg.HasValue() && be.queueCfg.Get().Batch.HasValue() {\n\t\t// Batcher mutates the data.\n\t\tbe.ConsumerOptions = append(be.ConsumerOptions, consumer.WithCapabilities(consumer.Capabilities{MutatesData: true}))\n\t}\n\n\tif be.queueCfg.HasValue() {\n\t\tqSet := queuebatch.AllSettings[request.Request]{\n\t\t\tSettings:  be.queueBatchSettings,\n\t\t\tSignal:    signal,\n\t\t\tID:        set.ID,\n\t\t\tTelemetry: set.TelemetrySettings,\n\t\t}\n\t\tbe.QueueSender, err = NewQueueSender(qSet, *be.queueCfg.Get(), be.ExportFailureMessage, be.firstSender)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tbe.firstSender = be.QueueSender\n\t}\n\n\treturn be, nil\n}\n\n// Send sends the request using the first sender in the chain.\nfunc (be *BaseExporter) Send(ctx context.Context, req request.Request) error {\n\t// Have to read the number of items before sending the request since the request can\n\t// be modified by the downstream components like the batcher.\n\titemsCount := req.ItemsCount()\n\terr := be.firstSender.Send(ctx, req)\n\tif err != nil {\n\t\tbe.Set.Logger.Error(\"Exporting failed. Rejecting data.\"+be.ExportFailureMessage,\n\t\t\tzap.Error(err), zap.Int(\"rejected_items\", itemsCount))\n\t}\n\treturn err\n}\n\nfunc (be *BaseExporter) Start(ctx context.Context, host component.Host) error {\n\t// First start the wrapped exporter.\n\tif err := be.StartFunc.Start(ctx, host); err != nil {\n\t\treturn err\n\t}\n\n\t// Last start the QueueBatch.\n\tif be.QueueSender != nil {\n\t\treturn be.QueueSender.Start(ctx, host)\n\t}\n\n\treturn nil\n}\n\nfunc (be *BaseExporter) Shutdown(ctx context.Context) error {\n\tvar err error\n\n\t// First shutdown the retry sender, so the queue sender can flush the queue without retries.\n\tif be.RetrySender != nil {\n\t\terr = multierr.Append(err, be.RetrySender.Shutdown(ctx))\n\t}\n\n\t// Then shutdown the queue sender.\n\tif be.QueueSender != nil {\n\t\terr = multierr.Append(err, be.QueueSender.Shutdown(ctx))\n\t}\n\n\t// Last shutdown the wrapped exporter itself.\n\treturn multierr.Append(err, be.ShutdownFunc.Shutdown(ctx))\n}\n\n// WithStart overrides the default Start function for an exporter.\n// The default start function does nothing and always returns nil.\nfunc WithStart(start component.StartFunc) Option {\n\treturn func(o *BaseExporter) error {\n\t\to.StartFunc = start\n\t\treturn nil\n\t}\n}\n\n// WithShutdown overrides the default Shutdown function for an exporter.\n// The default shutdown function does nothing and always returns nil.\nfunc WithShutdown(shutdown component.ShutdownFunc) Option {\n\treturn func(o *BaseExporter) error {\n\t\to.ShutdownFunc = shutdown\n\t\treturn nil\n\t}\n}\n\n// WithTimeout overrides the default TimeoutConfig for an exporter.\n// The default TimeoutConfig is 5 seconds.\nfunc WithTimeout(timeoutConfig TimeoutConfig) Option {\n\treturn func(o *BaseExporter) error {\n\t\to.timeoutCfg = timeoutConfig\n\t\treturn nil\n\t}\n}\n\n// WithRetry overrides the default configretry.BackOffConfig for an exporter.\n// The default configretry.BackOffConfig is to disable retries.\nfunc WithRetry(config configretry.BackOffConfig) Option {\n\treturn func(o *BaseExporter) error {\n\t\tif !config.Enabled {\n\t\t\to.ExportFailureMessage += \" Try enabling retry_on_failure config option to retry on retryable errors.\"\n\t\t\treturn nil\n\t\t}\n\t\to.retryCfg = config\n\t\treturn nil\n\t}\n}\n\n// WithQueue overrides the default queuebatch.Config for an exporter.\n// The default queuebatch.Config is to disable queueing.\n// This option cannot be used with the new exporter helpers New[Traces|Metrics|Logs]RequestExporter.\nfunc WithQueue(cfg configoptional.Optional[queuebatch.Config]) Option {\n\treturn func(o *BaseExporter) error {\n\t\tif o.queueBatchSettings.Encoding == nil {\n\t\t\treturn errors.New(\"WithQueue option is not available for the new request exporters, use WithQueueBatch instead\")\n\t\t}\n\t\treturn WithQueueBatch(cfg, o.queueBatchSettings)(o)\n\t}\n}\n\n// WithQueueBatch enables queueing for an exporter.\n// This option should be used with the new exporter helpers New[Traces|Metrics|Logs]RequestExporter.\n// If batch.partition.MetadataKeys is set, it will automatically configure the partitioner and merge function\n// to partition batches based on the specified metadata keys.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\nfunc WithQueueBatch(cfg configoptional.Optional[queuebatch.Config], set queuebatch.Settings[request.Request]) Option {\n\treturn func(o *BaseExporter) error {\n\t\tif !cfg.HasValue() {\n\t\t\to.ExportFailureMessage += \" Try enabling sending_queue to survive temporary failures.\"\n\t\t\treturn nil\n\t\t}\n\t\tif cfg.Get().StorageID != nil && set.Encoding == nil {\n\t\t\treturn errors.New(\"`Settings.Encoding` must not be nil when persistent queue is enabled\")\n\t\t}\n\t\t// Automatically configure partitioner if MetadataKeys is set\n\t\tif cfg.Get().Batch.HasValue() && len(cfg.Get().Batch.Get().Partition.MetadataKeys) > 0 {\n\t\t\tif set.Partitioner != nil {\n\t\t\t\treturn errors.New(\"cannot use metadata_keys when a custom partitioner is already configured\")\n\t\t\t}\n\t\t\tif set.MergeCtx != nil {\n\t\t\t\treturn errors.New(\"cannot use metadata_keys when a custom merge function is already configured\")\n\t\t\t}\n\t\t\tset.Partitioner = queuebatch.NewMetadataKeysPartitioner(cfg.Get().Batch.Get().Partition.MetadataKeys)\n\t\t\tset.MergeCtx = queuebatch.NewMetadataKeysMergeCtx(cfg.Get().Batch.Get().Partition.MetadataKeys)\n\t\t}\n\t\to.queueBatchSettings = set\n\t\to.queueCfg = cfg\n\t\treturn nil\n\t}\n}\n\n// WithCapabilities overrides the default Capabilities() function for a Consumer.\n// The default is non-mutable data.\n// TODO: Verify if we can change the default to be mutable as we do for processors.\nfunc WithCapabilities(capabilities consumer.Capabilities) Option {\n\treturn func(o *BaseExporter) error {\n\t\to.ConsumerOptions = append(o.ConsumerOptions, consumer.WithCapabilities(capabilities))\n\t\treturn nil\n\t}\n}\n\n// WithQueueBatchSettings is used to set the queuebatch.Settings for the new request based exporter helper.\n// It must be provided as the first option when creating a new exporter helper.\nfunc WithQueueBatchSettings(set queuebatch.Settings[request.Request]) Option {\n\treturn func(o *BaseExporter) error {\n\t\to.queueBatchSettings = set\n\t\treturn nil\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/base_exporter_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configretry\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\nfunc TestBaseExporter(t *testing.T) {\n\tbe, err := NewBaseExporter(exportertest.NewNopSettings(exportertest.NopType), pipeline.SignalMetrics, noopExport)\n\trequire.NoError(t, err)\n\trequire.NoError(t, be.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.NoError(t, be.Shutdown(context.Background()))\n}\n\nfunc TestBaseExporterWithOptions(t *testing.T) {\n\twant := errors.New(\"my error\")\n\tbe, err := NewBaseExporter(\n\t\texportertest.NewNopSettings(exportertest.NopType), pipeline.SignalMetrics, noopExport,\n\t\tWithStart(func(context.Context, component.Host) error { return want }),\n\t\tWithShutdown(func(context.Context) error { return want }),\n\t\tWithTimeout(NewDefaultTimeoutConfig()),\n\t)\n\trequire.NoError(t, err)\n\trequire.Equal(t, want, be.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.Equal(t, want, be.Shutdown(context.Background()))\n}\n\nfunc TestQueueOptionsWithRequestExporter(t *testing.T) {\n\tbs, err := NewBaseExporter(exportertest.NewNopSettings(exportertest.NopType), pipeline.SignalMetrics, noopExport,\n\t\tWithRetry(configretry.NewDefaultBackOffConfig()))\n\trequire.NoError(t, err)\n\trequire.Nil(t, bs.queueBatchSettings.Encoding)\n\t_, err = NewBaseExporter(exportertest.NewNopSettings(exportertest.NopType), pipeline.SignalMetrics, noopExport,\n\t\tWithRetry(configretry.NewDefaultBackOffConfig()), WithQueue(configoptional.Some(NewDefaultQueueConfig())))\n\trequire.Error(t, err)\n\n\tqCfg := NewDefaultQueueConfig()\n\tstorageID := component.NewID(component.MustNewType(\"test\"))\n\tqCfg.StorageID = &storageID\n\t_, err = NewBaseExporter(exportertest.NewNopSettings(exportertest.NopType), pipeline.SignalMetrics, noopExport,\n\t\tWithQueueBatchSettings(newFakeQueueBatch()),\n\t\tWithRetry(configretry.NewDefaultBackOffConfig()),\n\t\tWithQueueBatch(configoptional.Some(qCfg), queuebatch.Settings[request.Request]{}))\n\trequire.Error(t, err)\n}\n\nfunc TestBaseExporterLogging(t *testing.T) {\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tlogger, observed := observer.New(zap.DebugLevel)\n\tset.Logger = zap.New(logger)\n\trCfg := configretry.NewDefaultBackOffConfig()\n\trCfg.Enabled = false\n\tqCfg := NewDefaultQueueConfig()\n\tqCfg.WaitForResult = true\n\tbs, err := NewBaseExporter(set, pipeline.SignalMetrics, errExport,\n\t\tWithQueueBatchSettings(newFakeQueueBatch()),\n\t\tWithQueue(configoptional.Some(qCfg)),\n\t\tWithRetry(rCfg))\n\trequire.NoError(t, err)\n\trequire.NoError(t, bs.Start(context.Background(), componenttest.NewNopHost()))\n\tsendErr := bs.Send(context.Background(), &requesttest.FakeRequest{Items: 2})\n\trequire.Error(t, sendErr)\n\n\terrorLogs := observed.FilterLevelExact(zap.ErrorLevel).All()\n\trequire.Len(t, errorLogs, 2)\n\tassert.Contains(t, errorLogs[0].Message, \"Exporting failed. Dropping data.\")\n\tassert.Equal(t, \"my error\", errorLogs[0].ContextMap()[\"error\"])\n\tassert.Contains(t, errorLogs[1].Message, \"Exporting failed. Rejecting data.\")\n\tassert.Equal(t, \"my error\", errorLogs[1].ContextMap()[\"error\"])\n\trequire.NoError(t, bs.Shutdown(context.Background()))\n}\n\nfunc TestWithQueue_MetadataKeys(t *testing.T) {\n\tt.Run(\"with MetadataKeys - configures partitioner and merge function\", func(t *testing.T) {\n\t\tqCfg := NewDefaultQueueConfig()\n\t\tqCfg.Batch.GetOrInsertDefault().Partition.MetadataKeys = []string{\"key1\", \"key2\"}\n\n\t\tbe, err := NewBaseExporter(\n\t\t\texportertest.NewNopSettings(exportertest.NopType),\n\t\t\tpipeline.SignalMetrics,\n\t\t\tnoopExport,\n\t\t\tWithQueueBatchSettings(newFakeQueueBatch()),\n\t\t\tWithQueue(configoptional.Some(qCfg)),\n\t\t)\n\t\trequire.NoError(t, err)\n\t\tassert.NotNil(t, be)\n\n\t\t// Verify partitioner and merge function are configured\n\t\tassert.NotNil(t, be.queueBatchSettings.Partitioner, \"Partitioner should be set when MetadataKeys is provided\")\n\t\tassert.NotNil(t, be.queueBatchSettings.MergeCtx, \"MergeCtx should be set when MetadataKeys is provided\")\n\t})\n\n\tt.Run(\"without MetadataKeys - does not configure partitioner\", func(t *testing.T) {\n\t\ttests := []struct {\n\t\t\tname         string\n\t\t\tmetadataKeys []string\n\t\t}{\n\t\t\t{\"empty slice\", []string{}},\n\t\t\t{\"nil\", nil},\n\t\t}\n\n\t\tfor _, tt := range tests {\n\t\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t\tqCfg := NewDefaultQueueConfig()\n\t\t\t\tqCfg.Batch.GetOrInsertDefault().Partition.MetadataKeys = tt.metadataKeys\n\n\t\t\t\tbe, err := NewBaseExporter(\n\t\t\t\t\texportertest.NewNopSettings(exportertest.NopType),\n\t\t\t\t\tpipeline.SignalMetrics,\n\t\t\t\t\tnoopExport,\n\t\t\t\t\tWithQueueBatchSettings(newFakeQueueBatch()),\n\t\t\t\t\tWithQueue(configoptional.Some(qCfg)),\n\t\t\t\t)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.NotNil(t, be)\n\n\t\t\t\t// Verify partitioner and merge function are NOT configured\n\t\t\t\tassert.Nil(t, be.queueBatchSettings.Partitioner, \"Partitioner should not be set when MetadataKeys is %s\", tt.name)\n\t\t\t\tassert.Nil(t, be.queueBatchSettings.MergeCtx, \"MergeCtx should not be set when MetadataKeys is %s\", tt.name)\n\t\t\t})\n\t\t}\n\t})\n\n\tt.Run(\"error when custom partitioner already set and metadata_keys used\", func(t *testing.T) {\n\t\tqCfg := NewDefaultQueueConfig()\n\t\tqCfg.Batch.GetOrInsertDefault().Partition.MetadataKeys = []string{\"key1\", \"key2\"}\n\n\t\t// Set up queue batch settings with a custom partitioner already configured\n\t\tcustomSettings := newFakeQueueBatch()\n\t\tcustomPartitioner := queuebatch.NewPartitioner(\n\t\t\tfunc(context.Context, request.Request) string {\n\t\t\t\treturn \"custom\"\n\t\t\t},\n\t\t)\n\t\tcustomSettings.Partitioner = customPartitioner\n\n\t\t_, err := NewBaseExporter(\n\t\t\texportertest.NewNopSettings(exportertest.NopType),\n\t\t\tpipeline.SignalMetrics,\n\t\t\tnoopExport,\n\t\t\tWithQueueBatchSettings(customSettings),\n\t\t\tWithQueue(configoptional.Some(qCfg)),\n\t\t)\n\t\trequire.Error(t, err)\n\t\tassert.Contains(t, err.Error(), \"cannot use metadata_keys when a custom partitioner is already configured\")\n\t})\n\n\tt.Run(\"error when custom merge function already set and metadata_keys used\", func(t *testing.T) {\n\t\tqCfg := NewDefaultQueueConfig()\n\t\tqCfg.Batch.GetOrInsertDefault().Partition.MetadataKeys = []string{\"key1\", \"key2\"}\n\n\t\t// Set up queue batch settings with a custom merge function already configured\n\t\tcustomSettings := newFakeQueueBatch()\n\t\tcustomSettings.MergeCtx = func(context.Context, context.Context) context.Context {\n\t\t\treturn context.Background()\n\t\t}\n\n\t\t_, err := NewBaseExporter(\n\t\t\texportertest.NewNopSettings(exportertest.NopType),\n\t\t\tpipeline.SignalMetrics,\n\t\t\tnoopExport,\n\t\t\tWithQueueBatchSettings(customSettings),\n\t\t\tWithQueue(configoptional.Some(qCfg)),\n\t\t)\n\t\trequire.Error(t, err)\n\t\tassert.Contains(t, err.Error(), \"cannot use metadata_keys when a custom merge function is already configured\")\n\t})\n}\n\nfunc TestQueueRetryWithDisabledQueue(t *testing.T) {\n\ttests := []struct {\n\t\tname         string\n\t\tqueueOptions []Option\n\t}{\n\t\t{\n\t\t\tname: \"WithQueue\",\n\t\t\tqueueOptions: []Option{\n\t\t\t\tWithQueueBatchSettings(newFakeQueueBatch()),\n\t\t\t\tfunc() Option {\n\t\t\t\t\treturn WithQueue(configoptional.None[queuebatch.Config]())\n\t\t\t\t}(),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"WithRequestQueue\",\n\t\t\tqueueOptions: []Option{\n\t\t\t\tfunc() Option {\n\t\t\t\t\treturn WithQueueBatch(configoptional.None[queuebatch.Config](), newFakeQueueBatch())\n\t\t\t\t}(),\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tset := exportertest.NewNopSettings(exportertest.NopType)\n\t\t\tlogger, observed := observer.New(zap.ErrorLevel)\n\t\t\tset.Logger = zap.New(logger)\n\t\t\tbe, err := NewBaseExporter(set, pipeline.SignalLogs, errExport, tt.queueOptions...)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, be.Start(context.Background(), componenttest.NewNopHost()))\n\t\t\tmockR := &requesttest.FakeRequest{Items: 2}\n\t\t\trequire.Error(t, be.Send(context.Background(), mockR))\n\t\t\tassert.Len(t, observed.All(), 1)\n\t\t\tassert.Equal(t, \"Exporting failed. Rejecting data. Try enabling sending_queue to survive temporary failures.\", observed.All()[0].Message)\n\t\t\trequire.NoError(t, be.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nfunc errExport(context.Context, request.Request) error {\n\treturn errors.New(\"my error\")\n}\n\nfunc noopExport(context.Context, request.Request) error {\n\treturn nil\n}\n\nfunc newFakeQueueBatch() queuebatch.Settings[request.Request] {\n\treturn queuebatch.Settings[request.Request]{\n\t\tEncoding: fakeEncoding{},\n\t}\n}\n\ntype fakeEncoding struct{}\n\nfunc (f fakeEncoding) Marshal(context.Context, request.Request) ([]byte, error) {\n\treturn []byte(\"mockRequest\"), nil\n}\n\nfunc (f fakeEncoding) Unmarshal([]byte) (context.Context, request.Request, error) {\n\treturn context.Background(), &requesttest.FakeRequest{}, nil\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/config.schema.yaml",
    "content": "$defs:\n  timeout_config:\n    description: TimeoutConfig for timeout. The timeout applies to individual attempts to send data to the backend.\n    type: object\n    properties:\n      timeout:\n        description: Timeout is the timeout for every attempt to send data to the backend. A zero timeout means no timeout.\n        type: string\n        x-customType: time.Duration\n        format: duration\n"
  },
  {
    "path": "exporter/exporterhelper/internal/constants.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\nimport \"errors\"\n\nvar (\n\t// errNilLogger is returned when a logger is nil\n\terrNilLogger = errors.New(\"nil logger\")\n\t// errNilConsumeRequest is returned when a nil PushTraces is given.\n\terrNilConsumeRequest = errors.New(\"nil RequestConsumeFunc\")\n\t// errNilTracesConverter is returned when a nil RequestFromTracesFunc is given.\n\terrNilTracesConverter = errors.New(\"nil RequestFromTracesFunc\")\n\t// errNilMetricsConverter is returned when a nil RequestFromMetricsFunc is given.\n\terrNilMetricsConverter = errors.New(\"nil RequestFromMetricsFunc\")\n\t// errNilLogsConverter is returned when a nil RequestFromLogsFunc is given.\n\terrNilLogsConverter = errors.New(\"nil RequestFromLogsFunc\")\n)\n"
  },
  {
    "path": "exporter/exporterhelper/internal/experr/err.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage experr // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/experr\"\n\nimport (\n\t\"errors\"\n)\n\ntype shutdownErr struct {\n\terr error\n}\n\nfunc NewShutdownErr(err error) error {\n\treturn shutdownErr{err: err}\n}\n\nfunc (s shutdownErr) Error() string {\n\treturn \"interrupted due to shutdown: \" + s.err.Error()\n}\n\nfunc (s shutdownErr) Unwrap() error {\n\treturn s.err\n}\n\nfunc IsShutdownErr(err error) bool {\n\tvar sdErr shutdownErr\n\treturn errors.As(err, &sdErr)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/experr/err_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage experr\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestNewShutdownErr(t *testing.T) {\n\terr := NewShutdownErr(errors.New(\"some error\"))\n\tassert.Equal(t, \"interrupted due to shutdown: some error\", err.Error())\n}\n\nfunc TestIsShutdownErr(t *testing.T) {\n\terr := errors.New(\"testError\")\n\trequire.False(t, IsShutdownErr(err))\n\terr = NewShutdownErr(err)\n\trequire.True(t, IsShutdownErr(err))\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/hosttest/hosttest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage hosttest // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/hosttest\"\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc NewHost(ext map[component.ID]component.Component) component.Host {\n\treturn &mockHost{ext: ext}\n}\n\ntype mockHost struct {\n\text map[component.ID]component.Component\n}\n\nfunc (nh *mockHost) GetExtensions() map[component.ID]component.Component {\n\treturn nh.ext\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/hosttest/hosttest_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage hosttest\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\n// nopExtension acts as an extension for testing purposes.\ntype nopExtension struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n}\n\nfunc TestMockHost(t *testing.T) {\n\tcomponenttest.NewNopHost()\n\text := map[component.ID]component.Component{\n\t\tcomponent.MustNewID(\"test\"): &nopExtension{},\n\t}\n\thost := NewHost(ext)\n\tassert.Equal(t, ext, host.GetExtensions())\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/metadata/generated_feature_gates.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\nvar ExporterPersistRequestContextFeatureGate = featuregate.GlobalRegistry().MustRegister(\n\t\"exporter.PersistRequestContext\",\n\tfeaturegate.StageBeta,\n\tfeaturegate.WithRegisterDescription(\"controls whether context should be stored alongside requests in the persistent queue\"),\n\tfeaturegate.WithRegisterReferenceURL(\"https://github.com/open-telemetry/opentelemetry-collector/pull/13188\"),\n\tfeaturegate.WithRegisterFromVersion(\"v0.128.0\"),\n)\n"
  },
  {
    "path": "exporter/exporterhelper/internal/metadata/generated_telemetry.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/metric/embedded\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc Meter(settings component.TelemetrySettings) metric.Meter {\n\treturn settings.MeterProvider.Meter(\"go.opentelemetry.io/collector/exporter/exporterhelper\")\n}\n\nfunc Tracer(settings component.TelemetrySettings) trace.Tracer {\n\treturn settings.TracerProvider.Tracer(\"go.opentelemetry.io/collector/exporter/exporterhelper\")\n}\n\n// TelemetryBuilder provides an interface for components to report telemetry\n// as defined in metadata and user config.\ntype TelemetryBuilder struct {\n\tmeter                               metric.Meter\n\tmu                                  sync.Mutex\n\tregistrations                       []metric.Registration\n\tExporterEnqueueFailedLogRecords     metric.Int64Counter\n\tExporterEnqueueFailedMetricPoints   metric.Int64Counter\n\tExporterEnqueueFailedProfileSamples metric.Int64Counter\n\tExporterEnqueueFailedSpans          metric.Int64Counter\n\tExporterQueueBatchSendSize          metric.Int64Histogram\n\tExporterQueueBatchSendSizeBytes     metric.Int64Histogram\n\tExporterQueueCapacity               metric.Int64ObservableGauge\n\tExporterQueueSize                   metric.Int64ObservableGauge\n\tExporterSendFailedLogRecords        metric.Int64Counter\n\tExporterSendFailedMetricPoints      metric.Int64Counter\n\tExporterSendFailedProfileSamples    metric.Int64Counter\n\tExporterSendFailedSpans             metric.Int64Counter\n\tExporterSentLogRecords              metric.Int64Counter\n\tExporterSentMetricPoints            metric.Int64Counter\n\tExporterSentProfileSamples          metric.Int64Counter\n\tExporterSentSpans                   metric.Int64Counter\n}\n\n// TelemetryBuilderOption applies changes to default builder.\ntype TelemetryBuilderOption interface {\n\tapply(*TelemetryBuilder)\n}\n\ntype telemetryBuilderOptionFunc func(mb *TelemetryBuilder)\n\nfunc (tbof telemetryBuilderOptionFunc) apply(mb *TelemetryBuilder) {\n\ttbof(mb)\n}\n\n// RegisterExporterQueueCapacityCallback sets callback for observable ExporterQueueCapacity metric.\nfunc (builder *TelemetryBuilder) RegisterExporterQueueCapacityCallback(cb metric.Int64Callback) error {\n\treg, err := builder.meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {\n\t\tcb(ctx, &observerInt64{inst: builder.ExporterQueueCapacity, obs: o})\n\t\treturn nil\n\t}, builder.ExporterQueueCapacity)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tbuilder.registrations = append(builder.registrations, reg)\n\treturn nil\n}\n\n// RegisterExporterQueueSizeCallback sets callback for observable ExporterQueueSize metric.\nfunc (builder *TelemetryBuilder) RegisterExporterQueueSizeCallback(cb metric.Int64Callback) error {\n\treg, err := builder.meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {\n\t\tcb(ctx, &observerInt64{inst: builder.ExporterQueueSize, obs: o})\n\t\treturn nil\n\t}, builder.ExporterQueueSize)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tbuilder.registrations = append(builder.registrations, reg)\n\treturn nil\n}\n\ntype observerInt64 struct {\n\tembedded.Int64Observer\n\tinst metric.Int64Observable\n\tobs  metric.Observer\n}\n\nfunc (oi *observerInt64) Observe(value int64, opts ...metric.ObserveOption) {\n\toi.obs.ObserveInt64(oi.inst, value, opts...)\n}\n\n// Shutdown unregister all registered callbacks for async instruments.\nfunc (builder *TelemetryBuilder) Shutdown() {\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tfor _, reg := range builder.registrations {\n\t\treg.Unregister()\n\t}\n}\n\n// NewTelemetryBuilder provides a struct with methods to update all internal telemetry\n// for a component\nfunc NewTelemetryBuilder(settings component.TelemetrySettings, options ...TelemetryBuilderOption) (*TelemetryBuilder, error) {\n\tbuilder := TelemetryBuilder{}\n\tfor _, op := range options {\n\t\top.apply(&builder)\n\t}\n\tbuilder.meter = Meter(settings)\n\tvar err, errs error\n\tbuilder.ExporterEnqueueFailedLogRecords, err = builder.meter.Int64Counter(\n\t\t\"otelcol_exporter_enqueue_failed_log_records\",\n\t\tmetric.WithDescription(\"Number of log records failed to be added to the sending queue. [Alpha]\"),\n\t\tmetric.WithUnit(\"{record}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ExporterEnqueueFailedMetricPoints, err = builder.meter.Int64Counter(\n\t\t\"otelcol_exporter_enqueue_failed_metric_points\",\n\t\tmetric.WithDescription(\"Number of metric points failed to be added to the sending queue. [Alpha]\"),\n\t\tmetric.WithUnit(\"{datapoint}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ExporterEnqueueFailedProfileSamples, err = builder.meter.Int64Counter(\n\t\t\"otelcol_exporter_enqueue_failed_profile_samples\",\n\t\tmetric.WithDescription(\"Number of profile samples failed to be added to the sending queue. [Development]\"),\n\t\tmetric.WithUnit(\"{sample}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ExporterEnqueueFailedSpans, err = builder.meter.Int64Counter(\n\t\t\"otelcol_exporter_enqueue_failed_spans\",\n\t\tmetric.WithDescription(\"Number of spans failed to be added to the sending queue. [Alpha]\"),\n\t\tmetric.WithUnit(\"{span}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ExporterQueueBatchSendSize, err = builder.meter.Int64Histogram(\n\t\t\"otelcol_exporter_queue_batch_send_size\",\n\t\tmetric.WithDescription(\"Number of units in the batch [Development]\"),\n\t\tmetric.WithUnit(\"{unit}\"),\n\t\tmetric.WithExplicitBucketBoundaries([]float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, 100000}...),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ExporterQueueBatchSendSizeBytes, err = builder.meter.Int64Histogram(\n\t\t\"otelcol_exporter_queue_batch_send_size_bytes\",\n\t\tmetric.WithDescription(\"Number of bytes in batch that was sent. Only available on detailed level. [Development]\"),\n\t\tmetric.WithUnit(\"By\"),\n\t\tmetric.WithExplicitBucketBoundaries([]float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000}...),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ExporterQueueCapacity, err = builder.meter.Int64ObservableGauge(\n\t\t\"otelcol_exporter_queue_capacity\",\n\t\tmetric.WithDescription(\"Fixed capacity of the retry queue (in batches). [Alpha]\"),\n\t\tmetric.WithUnit(\"{batch}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ExporterQueueSize, err = builder.meter.Int64ObservableGauge(\n\t\t\"otelcol_exporter_queue_size\",\n\t\tmetric.WithDescription(\"Current size of the retry queue (in batches). [Alpha]\"),\n\t\tmetric.WithUnit(\"{batch}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ExporterSendFailedLogRecords, err = builder.meter.Int64Counter(\n\t\t\"otelcol_exporter_send_failed_log_records\",\n\t\tmetric.WithDescription(\"Number of log records in failed attempts to send to destination. At detailed telemetry level, includes attributes: error.type (semantic convention), error.permanent. [Alpha]\"),\n\t\tmetric.WithUnit(\"{record}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ExporterSendFailedMetricPoints, err = builder.meter.Int64Counter(\n\t\t\"otelcol_exporter_send_failed_metric_points\",\n\t\tmetric.WithDescription(\"Number of metric points in failed attempts to send to destination. At detailed telemetry level, includes attributes: error.type (semantic convention), error.permanent. [Alpha]\"),\n\t\tmetric.WithUnit(\"{datapoint}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ExporterSendFailedProfileSamples, err = builder.meter.Int64Counter(\n\t\t\"otelcol_exporter_send_failed_profile_samples\",\n\t\tmetric.WithDescription(\"Number of profile samples in failed attempts to send to destination. At detailed telemetry level, includes attributes: error.type (semantic convention), error.permanent. [Development]\"),\n\t\tmetric.WithUnit(\"{sample}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ExporterSendFailedSpans, err = builder.meter.Int64Counter(\n\t\t\"otelcol_exporter_send_failed_spans\",\n\t\tmetric.WithDescription(\"Number of spans in failed attempts to send to destination. At detailed telemetry level, includes attributes: error.type (semantic convention), error.permanent. [Alpha]\"),\n\t\tmetric.WithUnit(\"{span}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ExporterSentLogRecords, err = builder.meter.Int64Counter(\n\t\t\"otelcol_exporter_sent_log_records\",\n\t\tmetric.WithDescription(\"Number of log record successfully sent to destination. [Alpha]\"),\n\t\tmetric.WithUnit(\"{record}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ExporterSentMetricPoints, err = builder.meter.Int64Counter(\n\t\t\"otelcol_exporter_sent_metric_points\",\n\t\tmetric.WithDescription(\"Number of metric points successfully sent to destination. [Alpha]\"),\n\t\tmetric.WithUnit(\"{datapoint}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ExporterSentProfileSamples, err = builder.meter.Int64Counter(\n\t\t\"otelcol_exporter_sent_profile_samples\",\n\t\tmetric.WithDescription(\"Number of profile samples successfully sent to destination. [Development]\"),\n\t\tmetric.WithUnit(\"{sample}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ExporterSentSpans, err = builder.meter.Int64Counter(\n\t\t\"otelcol_exporter_sent_spans\",\n\t\tmetric.WithDescription(\"Number of spans successfully sent to destination. [Alpha]\"),\n\t\tmetric.WithUnit(\"{span}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\treturn &builder, errs\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/metadata/generated_telemetry_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/metric\"\n\tembeddedmetric \"go.opentelemetry.io/otel/metric/embedded\"\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\t\"go.opentelemetry.io/otel/trace\"\n\tembeddedtrace \"go.opentelemetry.io/otel/trace/embedded\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\ntype mockMeter struct {\n\tnoopmetric.Meter\n\tname string\n}\ntype mockMeterProvider struct {\n\tembeddedmetric.MeterProvider\n}\n\nfunc (m mockMeterProvider) Meter(name string, opts ...metric.MeterOption) metric.Meter {\n\treturn mockMeter{name: name}\n}\n\ntype mockTracer struct {\n\tnooptrace.Tracer\n\tname string\n}\n\ntype mockTracerProvider struct {\n\tembeddedtrace.TracerProvider\n}\n\nfunc (m mockTracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer {\n\treturn mockTracer{name: name}\n}\n\nfunc TestProviders(t *testing.T) {\n\tset := component.TelemetrySettings{\n\t\tMeterProvider:  mockMeterProvider{},\n\t\tTracerProvider: mockTracerProvider{},\n\t}\n\n\tmeter := Meter(set)\n\tif m, ok := meter.(mockMeter); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/exporter/exporterhelper\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockMeter\")\n\t}\n\n\ttracer := Tracer(set)\n\tif m, ok := tracer.(mockTracer); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/exporter/exporterhelper\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockTracer\")\n\t}\n}\n\nfunc TestNewTelemetryBuilder(t *testing.T) {\n\tset := componenttest.NewNopTelemetrySettings()\n\tapplied := false\n\t_, err := NewTelemetryBuilder(set, telemetryBuilderOptionFunc(func(b *TelemetryBuilder) {\n\t\tapplied = true\n\t}))\n\trequire.NoError(t, err)\n\trequire.True(t, applied)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/metadatatest/generated_telemetrytest.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\nfunc AssertEqualExporterEnqueueFailedLogRecords(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_exporter_enqueue_failed_log_records\",\n\t\tDescription: \"Number of log records failed to be added to the sending queue. [Alpha]\",\n\t\tUnit:        \"{record}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_exporter_enqueue_failed_log_records\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualExporterEnqueueFailedMetricPoints(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_exporter_enqueue_failed_metric_points\",\n\t\tDescription: \"Number of metric points failed to be added to the sending queue. [Alpha]\",\n\t\tUnit:        \"{datapoint}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_exporter_enqueue_failed_metric_points\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualExporterEnqueueFailedProfileSamples(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_exporter_enqueue_failed_profile_samples\",\n\t\tDescription: \"Number of profile samples failed to be added to the sending queue. [Development]\",\n\t\tUnit:        \"{sample}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_exporter_enqueue_failed_profile_samples\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualExporterEnqueueFailedSpans(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_exporter_enqueue_failed_spans\",\n\t\tDescription: \"Number of spans failed to be added to the sending queue. [Alpha]\",\n\t\tUnit:        \"{span}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_exporter_enqueue_failed_spans\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualExporterQueueBatchSendSize(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.HistogramDataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_exporter_queue_batch_send_size\",\n\t\tDescription: \"Number of units in the batch [Development]\",\n\t\tUnit:        \"{unit}\",\n\t\tData: metricdata.Histogram[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_exporter_queue_batch_send_size\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualExporterQueueBatchSendSizeBytes(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.HistogramDataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_exporter_queue_batch_send_size_bytes\",\n\t\tDescription: \"Number of bytes in batch that was sent. Only available on detailed level. [Development]\",\n\t\tUnit:        \"By\",\n\t\tData: metricdata.Histogram[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_exporter_queue_batch_send_size_bytes\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualExporterQueueCapacity(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_exporter_queue_capacity\",\n\t\tDescription: \"Fixed capacity of the retry queue (in batches). [Alpha]\",\n\t\tUnit:        \"{batch}\",\n\t\tData: metricdata.Gauge[int64]{\n\t\t\tDataPoints: dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_exporter_queue_capacity\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualExporterQueueSize(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_exporter_queue_size\",\n\t\tDescription: \"Current size of the retry queue (in batches). [Alpha]\",\n\t\tUnit:        \"{batch}\",\n\t\tData: metricdata.Gauge[int64]{\n\t\t\tDataPoints: dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_exporter_queue_size\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualExporterSendFailedLogRecords(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_exporter_send_failed_log_records\",\n\t\tDescription: \"Number of log records in failed attempts to send to destination. At detailed telemetry level, includes attributes: error.type (semantic convention), error.permanent. [Alpha]\",\n\t\tUnit:        \"{record}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_exporter_send_failed_log_records\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualExporterSendFailedMetricPoints(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_exporter_send_failed_metric_points\",\n\t\tDescription: \"Number of metric points in failed attempts to send to destination. At detailed telemetry level, includes attributes: error.type (semantic convention), error.permanent. [Alpha]\",\n\t\tUnit:        \"{datapoint}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_exporter_send_failed_metric_points\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualExporterSendFailedProfileSamples(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_exporter_send_failed_profile_samples\",\n\t\tDescription: \"Number of profile samples in failed attempts to send to destination. At detailed telemetry level, includes attributes: error.type (semantic convention), error.permanent. [Development]\",\n\t\tUnit:        \"{sample}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_exporter_send_failed_profile_samples\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualExporterSendFailedSpans(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_exporter_send_failed_spans\",\n\t\tDescription: \"Number of spans in failed attempts to send to destination. At detailed telemetry level, includes attributes: error.type (semantic convention), error.permanent. [Alpha]\",\n\t\tUnit:        \"{span}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_exporter_send_failed_spans\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualExporterSentLogRecords(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_exporter_sent_log_records\",\n\t\tDescription: \"Number of log record successfully sent to destination. [Alpha]\",\n\t\tUnit:        \"{record}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_exporter_sent_log_records\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualExporterSentMetricPoints(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_exporter_sent_metric_points\",\n\t\tDescription: \"Number of metric points successfully sent to destination. [Alpha]\",\n\t\tUnit:        \"{datapoint}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_exporter_sent_metric_points\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualExporterSentProfileSamples(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_exporter_sent_profile_samples\",\n\t\tDescription: \"Number of profile samples successfully sent to destination. [Development]\",\n\t\tUnit:        \"{sample}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_exporter_sent_profile_samples\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualExporterSentSpans(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_exporter_sent_spans\",\n\t\tDescription: \"Number of spans successfully sent to destination. [Alpha]\",\n\t\tUnit:        \"{span}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_exporter_sent_spans\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/metadatatest/generated_telemetrytest_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/metadata\"\n)\n\nfunc TestSetupTelemetry(t *testing.T) {\n\ttestTel := componenttest.NewTelemetry()\n\ttb, err := metadata.NewTelemetryBuilder(testTel.NewTelemetrySettings())\n\trequire.NoError(t, err)\n\tdefer tb.Shutdown()\n\trequire.NoError(t, tb.RegisterExporterQueueCapacityCallback(func(_ context.Context, observer metric.Int64Observer) error {\n\t\tobserver.Observe(1)\n\t\treturn nil\n\t}))\n\trequire.NoError(t, tb.RegisterExporterQueueSizeCallback(func(_ context.Context, observer metric.Int64Observer) error {\n\t\tobserver.Observe(1)\n\t\treturn nil\n\t}))\n\ttb.ExporterEnqueueFailedLogRecords.Add(context.Background(), 1)\n\ttb.ExporterEnqueueFailedMetricPoints.Add(context.Background(), 1)\n\ttb.ExporterEnqueueFailedProfileSamples.Add(context.Background(), 1)\n\ttb.ExporterEnqueueFailedSpans.Add(context.Background(), 1)\n\ttb.ExporterQueueBatchSendSize.Record(context.Background(), 1)\n\ttb.ExporterQueueBatchSendSizeBytes.Record(context.Background(), 1)\n\ttb.ExporterSendFailedLogRecords.Add(context.Background(), 1)\n\ttb.ExporterSendFailedMetricPoints.Add(context.Background(), 1)\n\ttb.ExporterSendFailedProfileSamples.Add(context.Background(), 1)\n\ttb.ExporterSendFailedSpans.Add(context.Background(), 1)\n\ttb.ExporterSentLogRecords.Add(context.Background(), 1)\n\ttb.ExporterSentMetricPoints.Add(context.Background(), 1)\n\ttb.ExporterSentProfileSamples.Add(context.Background(), 1)\n\ttb.ExporterSentSpans.Add(context.Background(), 1)\n\tAssertEqualExporterEnqueueFailedLogRecords(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualExporterEnqueueFailedMetricPoints(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualExporterEnqueueFailedProfileSamples(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualExporterEnqueueFailedSpans(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualExporterQueueBatchSendSize(t, testTel,\n\t\t[]metricdata.HistogramDataPoint[int64]{{}}, metricdatatest.IgnoreValue(),\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualExporterQueueBatchSendSizeBytes(t, testTel,\n\t\t[]metricdata.HistogramDataPoint[int64]{{}}, metricdatatest.IgnoreValue(),\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualExporterQueueCapacity(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualExporterQueueSize(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualExporterSendFailedLogRecords(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualExporterSendFailedMetricPoints(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualExporterSendFailedProfileSamples(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualExporterSendFailedSpans(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualExporterSentLogRecords(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualExporterSentMetricPoints(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualExporterSentProfileSamples(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualExporterSentSpans(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\n\trequire.NoError(t, testTel.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/new_request.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\nimport (\n\t\"context\"\n\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\ntype logsExporter struct {\n\t*BaseExporter\n\tconsumer.Logs\n}\n\n// NewLogsRequest creates new logs exporter based on custom LogsConverter and Sender.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\nfunc NewLogsRequest(\n\t_ context.Context,\n\tset exporter.Settings,\n\tconverter request.RequestConverterFunc[plog.Logs],\n\tpusher request.RequestConsumeFunc,\n\toptions ...Option,\n) (exporter.Logs, error) {\n\tif set.Logger == nil {\n\t\treturn nil, errNilLogger\n\t}\n\n\tif converter == nil {\n\t\treturn nil, errNilLogsConverter\n\t}\n\n\tif pusher == nil {\n\t\treturn nil, errNilConsumeRequest\n\t}\n\n\tbe, err := NewBaseExporter(set, pipeline.SignalLogs, pusher, options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlc, err := consumer.NewLogs(newConsumeLogs(converter, be, set.Logger), be.ConsumerOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &logsExporter{BaseExporter: be, Logs: lc}, nil\n}\n\nfunc newConsumeLogs(converter request.RequestConverterFunc[plog.Logs], be *BaseExporter, logger *zap.Logger) consumer.ConsumeLogsFunc {\n\treturn func(ctx context.Context, ld plog.Logs) error {\n\t\treq, err := converter(ctx, ld)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Failed to convert logs. Dropping data.\",\n\t\t\t\tzap.Int(\"dropped_log_records\", ld.LogRecordCount()),\n\t\t\t\tzap.Error(err))\n\t\t\treturn consumererror.NewPermanent(err)\n\t\t}\n\t\treturn be.Send(ctx, req)\n\t}\n}\n\ntype tracesExporter struct {\n\t*BaseExporter\n\tconsumer.Traces\n}\n\n// NewTracesRequest creates a new traces exporter based on a custom TracesConverter and Sender.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\nfunc NewTracesRequest(\n\t_ context.Context,\n\tset exporter.Settings,\n\tconverter request.RequestConverterFunc[ptrace.Traces],\n\tpusher request.RequestConsumeFunc,\n\toptions ...Option,\n) (exporter.Traces, error) {\n\tif set.Logger == nil {\n\t\treturn nil, errNilLogger\n\t}\n\n\tif converter == nil {\n\t\treturn nil, errNilTracesConverter\n\t}\n\n\tif pusher == nil {\n\t\treturn nil, errNilConsumeRequest\n\t}\n\n\tbe, err := NewBaseExporter(set, pipeline.SignalTraces, pusher, options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttc, err := consumer.NewTraces(newConsumeTraces(converter, be, set.Logger), be.ConsumerOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &tracesExporter{BaseExporter: be, Traces: tc}, nil\n}\n\nfunc newConsumeTraces(converter request.RequestConverterFunc[ptrace.Traces], be *BaseExporter, logger *zap.Logger) consumer.ConsumeTracesFunc {\n\treturn func(ctx context.Context, td ptrace.Traces) error {\n\t\treq, err := converter(ctx, td)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Failed to convert traces. Dropping data.\",\n\t\t\t\tzap.Int(\"dropped_spans\", td.SpanCount()),\n\t\t\t\tzap.Error(err))\n\t\t\treturn consumererror.NewPermanent(err)\n\t\t}\n\t\treturn be.Send(ctx, req)\n\t}\n}\n\ntype metricsExporter struct {\n\t*BaseExporter\n\tconsumer.Metrics\n}\n\n// NewMetricsRequest creates a new metrics exporter based on a custom MetricsConverter and Sender.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\nfunc NewMetricsRequest(\n\t_ context.Context,\n\tset exporter.Settings,\n\tconverter request.RequestConverterFunc[pmetric.Metrics],\n\tpusher request.RequestConsumeFunc,\n\toptions ...Option,\n) (exporter.Metrics, error) {\n\tif set.Logger == nil {\n\t\treturn nil, errNilLogger\n\t}\n\n\tif converter == nil {\n\t\treturn nil, errNilMetricsConverter\n\t}\n\n\tif pusher == nil {\n\t\treturn nil, errNilConsumeRequest\n\t}\n\n\tbe, err := NewBaseExporter(set, pipeline.SignalMetrics, pusher, options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmc, err := consumer.NewMetrics(newConsumeMetrics(converter, be, set.Logger), be.ConsumerOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &metricsExporter{BaseExporter: be, Metrics: mc}, nil\n}\n\nfunc newConsumeMetrics(converter request.RequestConverterFunc[pmetric.Metrics], be *BaseExporter, logger *zap.Logger) consumer.ConsumeMetricsFunc {\n\treturn func(ctx context.Context, md pmetric.Metrics) error {\n\t\treq, err := converter(ctx, md)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Failed to convert metrics. Dropping data.\",\n\t\t\t\tzap.Int(\"dropped_data_points\", md.DataPointCount()),\n\t\t\t\tzap.Error(err))\n\t\t\treturn consumererror.NewPermanent(err)\n\t\t}\n\t\treturn be.Send(ctx, req)\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/new_request_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sendertest\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nfunc TestLogsRequest_NilLogger(t *testing.T) {\n\tle, err := NewLogsRequest(context.Background(), exporter.Settings{}, requesttest.RequestFromLogsFunc(nil), sendertest.NewNopSenderFunc[request.Request]())\n\trequire.Nil(t, le)\n\trequire.Equal(t, errNilLogger, err)\n}\n\nfunc TestLogsRequest_NilLogsConverter(t *testing.T) {\n\tle, err := NewLogsRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType), nil, sendertest.NewNopSenderFunc[request.Request]())\n\trequire.Nil(t, le)\n\trequire.Equal(t, errNilLogsConverter, err)\n}\n\nfunc TestLogsRequest_NilPushLogsData(t *testing.T) {\n\tle, err := NewLogsRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType), requesttest.RequestFromLogsFunc(nil), nil)\n\trequire.Nil(t, le)\n\trequire.Equal(t, errNilConsumeRequest, err)\n}\n\nfunc TestLogsRequest_Default(t *testing.T) {\n\tld := plog.NewLogs()\n\tle, err := NewLogsRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromLogsFunc(nil), sendertest.NewNopSenderFunc[request.Request]())\n\tassert.NotNil(t, le)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, consumer.Capabilities{MutatesData: false}, le.Capabilities())\n\tassert.NoError(t, le.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, le.ConsumeLogs(context.Background(), ld))\n\tassert.NoError(t, le.Shutdown(context.Background()))\n}\n\nfunc TestLogsRequest_WithCapabilities(t *testing.T) {\n\tcapabilities := consumer.Capabilities{MutatesData: true}\n\tle, err := NewLogsRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromLogsFunc(nil), sendertest.NewNopSenderFunc[request.Request](), WithCapabilities(capabilities))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\n\tassert.Equal(t, capabilities, le.Capabilities())\n}\n\nfunc TestLogsRequest_WithShutdown(t *testing.T) {\n\tshutdownCalled := false\n\tshutdown := func(context.Context) error { shutdownCalled = true; return nil }\n\n\tle, err := NewLogsRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromLogsFunc(nil), sendertest.NewNopSenderFunc[request.Request](), WithShutdown(shutdown))\n\tassert.NotNil(t, le)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, le.Shutdown(context.Background()))\n\tassert.True(t, shutdownCalled)\n}\n\nfunc TestLogsRequest_Default_ConvertError(t *testing.T) {\n\tld := plog.NewLogs()\n\twant := errors.New(\"convert_error\")\n\tle, err := NewLogsRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromLogsFunc(want), sendertest.NewNopSenderFunc[request.Request]())\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\trequire.Equal(t, consumererror.NewPermanent(want), le.ConsumeLogs(context.Background(), ld))\n}\n\nfunc TestLogsRequest_Default_ExportError(t *testing.T) {\n\tld := plog.NewLogs()\n\twant := errors.New(\"export_error\")\n\tle, err := NewLogsRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromLogsFunc(nil), sendertest.NewErrSenderFunc[request.Request](want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\trequire.Equal(t, want, le.ConsumeLogs(context.Background(), ld))\n}\n\nfunc TestLogsRequest_WithShutdown_ReturnError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tshutdownErr := func(context.Context) error { return want }\n\n\tle, err := NewLogsRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromLogsFunc(nil), sendertest.NewNopSenderFunc[request.Request](), WithShutdown(shutdownErr))\n\tassert.NotNil(t, le)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, want, le.Shutdown(context.Background()))\n}\n\nfunc TestTracesRequest_NilLogger(t *testing.T) {\n\tte, err := NewTracesRequest(context.Background(), exporter.Settings{}, requesttest.RequestFromTracesFunc(nil), sendertest.NewNopSenderFunc[request.Request]())\n\trequire.Nil(t, te)\n\trequire.Equal(t, errNilLogger, err)\n}\n\nfunc TestTracesRequest_NilTracesConverter(t *testing.T) {\n\tte, err := NewTracesRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType), nil, sendertest.NewNopSenderFunc[request.Request]())\n\trequire.Nil(t, te)\n\trequire.Equal(t, errNilTracesConverter, err)\n}\n\nfunc TestTracesRequest_NilPushTraceData(t *testing.T) {\n\tte, err := NewTracesRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType), requesttest.RequestFromTracesFunc(nil), nil)\n\trequire.Nil(t, te)\n\trequire.Equal(t, errNilConsumeRequest, err)\n}\n\nfunc TestTracesRequest_Default(t *testing.T) {\n\ttd := ptrace.NewTraces()\n\tte, err := NewTracesRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromTracesFunc(nil), sendertest.NewNopSenderFunc[request.Request]())\n\tassert.NotNil(t, te)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, consumer.Capabilities{MutatesData: false}, te.Capabilities())\n\tassert.NoError(t, te.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, te.ConsumeTraces(context.Background(), td))\n\tassert.NoError(t, te.Shutdown(context.Background()))\n}\n\nfunc TestTracesRequest_WithCapabilities(t *testing.T) {\n\tcapabilities := consumer.Capabilities{MutatesData: true}\n\tte, err := NewTracesRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromTracesFunc(nil), sendertest.NewNopSenderFunc[request.Request](), WithCapabilities(capabilities))\n\tassert.NotNil(t, te)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, capabilities, te.Capabilities())\n}\n\nfunc TestTracesRequest_Default_ConvertError(t *testing.T) {\n\ttd := ptrace.NewTraces()\n\twant := errors.New(\"convert_error\")\n\tte, err := NewTracesRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromTracesFunc(want), sendertest.NewNopSenderFunc[request.Request]())\n\trequire.NoError(t, err)\n\trequire.NotNil(t, te)\n\trequire.Equal(t, consumererror.NewPermanent(want), te.ConsumeTraces(context.Background(), td))\n}\n\nfunc TestTracesRequest_Default_ExportError(t *testing.T) {\n\ttd := ptrace.NewTraces()\n\twant := errors.New(\"export_error\")\n\tte, err := NewTracesRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromTracesFunc(nil), sendertest.NewErrSenderFunc[request.Request](want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, te)\n\trequire.Equal(t, want, te.ConsumeTraces(context.Background(), td))\n}\n\nfunc TestTracesRequest_WithShutdown(t *testing.T) {\n\tshutdownCalled := false\n\tshutdown := func(context.Context) error { shutdownCalled = true; return nil }\n\n\tte, err := NewTracesRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromTracesFunc(nil), sendertest.NewNopSenderFunc[request.Request](), WithShutdown(shutdown))\n\tassert.NotNil(t, te)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, te.Shutdown(context.Background()))\n\tassert.True(t, shutdownCalled)\n}\n\nfunc TestTracesRequest_WithShutdown_ReturnError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tshutdownErr := func(context.Context) error { return want }\n\n\tte, err := NewTracesRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromTracesFunc(nil), sendertest.NewNopSenderFunc[request.Request](), WithShutdown(shutdownErr))\n\tassert.NotNil(t, te)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, want, te.Shutdown(context.Background()))\n}\n\nfunc TestMetricsRequest_NilLogger(t *testing.T) {\n\tme, err := NewMetricsRequest(context.Background(), exporter.Settings{}, requesttest.RequestFromMetricsFunc(nil), sendertest.NewNopSenderFunc[request.Request]())\n\trequire.Nil(t, me)\n\trequire.Equal(t, errNilLogger, err)\n}\n\nfunc TestMetricsRequest_NilMetricsConverter(t *testing.T) {\n\tme, err := NewMetricsRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType), nil, sendertest.NewNopSenderFunc[request.Request]())\n\trequire.Nil(t, me)\n\trequire.Equal(t, errNilMetricsConverter, err)\n}\n\nfunc TestMetricsRequest_NilPushMetricsData(t *testing.T) {\n\tme, err := NewMetricsRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType), requesttest.RequestFromMetricsFunc(nil), nil)\n\trequire.Nil(t, me)\n\trequire.Equal(t, errNilConsumeRequest, err)\n}\n\nfunc TestMetricsRequest_Default(t *testing.T) {\n\tmd := pmetric.NewMetrics()\n\tme, err := NewMetricsRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromMetricsFunc(nil), sendertest.NewNopSenderFunc[request.Request]())\n\trequire.NoError(t, err)\n\tassert.NotNil(t, me)\n\n\tassert.Equal(t, consumer.Capabilities{MutatesData: false}, me.Capabilities())\n\tassert.NoError(t, me.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, me.ConsumeMetrics(context.Background(), md))\n\tassert.NoError(t, me.Shutdown(context.Background()))\n}\n\nfunc TestMetricsRequest_WithCapabilities(t *testing.T) {\n\tcapabilities := consumer.Capabilities{MutatesData: true}\n\tme, err := NewMetricsRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromMetricsFunc(nil), sendertest.NewNopSenderFunc[request.Request](), WithCapabilities(capabilities))\n\trequire.NoError(t, err)\n\tassert.NotNil(t, me)\n\n\tassert.Equal(t, capabilities, me.Capabilities())\n}\n\nfunc TestMetricsRequest_Default_ConvertError(t *testing.T) {\n\tmd := pmetric.NewMetrics()\n\twant := errors.New(\"convert_error\")\n\tme, err := NewMetricsRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromMetricsFunc(want), sendertest.NewNopSenderFunc[request.Request]())\n\trequire.NoError(t, err)\n\trequire.NotNil(t, me)\n\trequire.Equal(t, consumererror.NewPermanent(want), me.ConsumeMetrics(context.Background(), md))\n}\n\nfunc TestMetricsRequest_Default_ExportError(t *testing.T) {\n\tmd := pmetric.NewMetrics()\n\twant := errors.New(\"export_error\")\n\tme, err := NewMetricsRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromMetricsFunc(nil), sendertest.NewErrSenderFunc[request.Request](want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, me)\n\trequire.Equal(t, want, me.ConsumeMetrics(context.Background(), md))\n}\n\nfunc TestMetricsRequest_WithShutdown(t *testing.T) {\n\tshutdownCalled := false\n\tshutdown := func(context.Context) error { shutdownCalled = true; return nil }\n\n\tme, err := NewMetricsRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromMetricsFunc(nil), sendertest.NewNopSenderFunc[request.Request](), WithShutdown(shutdown))\n\tassert.NotNil(t, me)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, me.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, me.Shutdown(context.Background()))\n\tassert.True(t, shutdownCalled)\n}\n\nfunc TestMetricsRequest_WithShutdown_ReturnError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tshutdownErr := func(context.Context) error { return want }\n\n\tme, err := NewMetricsRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequesttest.RequestFromMetricsFunc(nil), sendertest.NewNopSenderFunc[request.Request](), WithShutdown(shutdownErr))\n\tassert.NotNil(t, me)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, me.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.Equal(t, want, me.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/obs_report_sender.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n\totelcodes \"go.opentelemetry.io/otel/codes\"\n\t\"go.opentelemetry.io/otel/metric\"\n\tsemconv \"go.opentelemetry.io/otel/semconv/v1.38.0\"\n\t\"go.opentelemetry.io/otel/trace\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/experr\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/metadata\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n)\n\nconst (\n\t// spanNameSep is duplicate between receiver and exporter.\n\tspanNameSep = \"/\"\n\n\t// ExporterKey used to identify exporters in metrics and traces.\n\tExporterKey = \"exporter\"\n\n\t// DataTypeKey used to identify the data type in the queue size metric.\n\tDataTypeKey = \"data_type\"\n\n\t// ItemsSent used to track number of items sent by exporters.\n\tItemsSent = \"items.sent\"\n\t// ItemsFailed used to track number of items that failed to be sent by exporters.\n\tItemsFailed = \"items.failed\"\n\n\t// ErrorPermanentKey indicates whether the error is permanent (non-retryable).\n\tErrorPermanentKey = \"error.permanent\"\n)\n\ntype obsReportSender[K request.Request] struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\n\tspanName        string\n\ttracer          trace.Tracer\n\tspanAttrs       trace.SpanStartEventOption\n\tmetricAttr      metric.MeasurementOption\n\titemsSentInst   metric.Int64Counter\n\titemsFailedInst metric.Int64Counter\n\tnext            sender.Sender[K]\n}\n\nfunc newObsReportSender[K request.Request](set exporter.Settings, signal pipeline.Signal, next sender.Sender[K]) (sender.Sender[K], error) {\n\ttelemetryBuilder, err := metadata.NewTelemetryBuilder(set.TelemetrySettings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tidStr := set.ID.String()\n\texpAttr := attribute.String(ExporterKey, idStr)\n\n\tor := &obsReportSender[K]{\n\t\tspanName:   ExporterKey + spanNameSep + idStr + spanNameSep + signal.String(),\n\t\ttracer:     metadata.Tracer(set.TelemetrySettings),\n\t\tspanAttrs:  trace.WithAttributes(expAttr, attribute.String(DataTypeKey, signal.String())),\n\t\tmetricAttr: metric.WithAttributeSet(attribute.NewSet(expAttr)),\n\t\tnext:       next,\n\t}\n\n\tswitch signal {\n\tcase pipeline.SignalTraces:\n\t\tor.itemsSentInst = telemetryBuilder.ExporterSentSpans\n\t\tor.itemsFailedInst = telemetryBuilder.ExporterSendFailedSpans\n\n\tcase pipeline.SignalMetrics:\n\t\tor.itemsSentInst = telemetryBuilder.ExporterSentMetricPoints\n\t\tor.itemsFailedInst = telemetryBuilder.ExporterSendFailedMetricPoints\n\n\tcase pipeline.SignalLogs:\n\t\tor.itemsSentInst = telemetryBuilder.ExporterSentLogRecords\n\t\tor.itemsFailedInst = telemetryBuilder.ExporterSendFailedLogRecords\n\tcase xpipeline.SignalProfiles:\n\t\tor.itemsSentInst = telemetryBuilder.ExporterSentProfileSamples\n\t\tor.itemsFailedInst = telemetryBuilder.ExporterSendFailedProfileSamples\n\t}\n\n\treturn or, nil\n}\n\nfunc (ors *obsReportSender[K]) Send(ctx context.Context, req K) error {\n\t// Have to read the number of items before sending the request since the request can\n\t// be modified by the downstream components like the batcher.\n\tc := ors.startOp(ctx)\n\titems := req.ItemsCount()\n\t// Forward the data to the next consumer (this pusher is the next).\n\terr := ors.next.Send(c, req)\n\tors.endOp(c, items, err)\n\treturn err\n}\n\n// StartOp creates the span used to trace the operation. Returning\n// the updated context and the created span.\nfunc (ors *obsReportSender[K]) startOp(ctx context.Context) context.Context {\n\tctx, _ = ors.tracer.Start(ctx,\n\t\tors.spanName,\n\t\tors.spanAttrs,\n\t\ttrace.WithLinks(queuebatch.LinksFromContext(ctx)...))\n\treturn ctx\n}\n\n// EndOp completes the export operation that was started with StartOp.\nfunc (ors *obsReportSender[K]) endOp(ctx context.Context, numRecords int, err error) {\n\tnumSent, numFailedToSend := toNumItems(numRecords, err)\n\n\tif ors.itemsSentInst != nil {\n\t\tors.itemsSentInst.Add(ctx, numSent, ors.metricAttr)\n\t}\n\n\tif ors.itemsFailedInst != nil && numFailedToSend > 0 {\n\t\twithFailedAttrs := metric.WithAttributeSet(extractFailureAttributes(err))\n\t\tors.itemsFailedInst.Add(ctx, numFailedToSend, ors.metricAttr, withFailedAttrs)\n\t}\n\n\tspan := trace.SpanFromContext(ctx)\n\tdefer span.End()\n\t// End the span according to errors.\n\tif span.IsRecording() {\n\t\tspan.SetAttributes(\n\t\t\tattribute.Int64(ItemsSent, numSent),\n\t\t\tattribute.Int64(ItemsFailed, numFailedToSend),\n\t\t)\n\t\tif err != nil {\n\t\t\tspan.SetStatus(otelcodes.Error, err.Error())\n\t\t}\n\t}\n}\n\nfunc toNumItems(numExportedItems int, err error) (int64, int64) {\n\tif err != nil {\n\t\treturn 0, int64(numExportedItems)\n\t}\n\treturn int64(numExportedItems), 0\n}\n\nfunc extractFailureAttributes(err error) attribute.Set {\n\tif err == nil {\n\t\treturn attribute.NewSet()\n\t}\n\n\tattrs := []attribute.KeyValue{}\n\n\terrorType := determineErrorType(err)\n\tattrs = append(attrs, attribute.String(string(semconv.ErrorTypeKey), errorType))\n\n\tisPermanent := consumererror.IsPermanent(err)\n\tattrs = append(attrs, attribute.Bool(ErrorPermanentKey, isPermanent))\n\n\treturn attribute.NewSet(attrs...)\n}\n\nfunc determineErrorType(err error) string {\n\tif experr.IsShutdownErr(err) {\n\t\treturn \"Shutdown\"\n\t}\n\n\tif errors.Is(err, context.Canceled) {\n\t\treturn \"Canceled\"\n\t}\n\tif errors.Is(err, context.DeadlineExceeded) {\n\t\treturn \"Deadline_Exceeded\"\n\t}\n\n\tif st, ok := status.FromError(err); ok && st.Code() != codes.OK {\n\t\treturn st.Code().String()\n\t}\n\n\treturn \"_OTHER\"\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/obs_report_sender_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/codes\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\tsemconv \"go.opentelemetry.io/otel/semconv/v1.38.0\"\n\tgrpccodes \"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/experr\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/metadatatest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n)\n\nvar (\n\texporterID = component.MustNewID(\"fakeExporter\")\n\n\terrFake = errors.New(\"errFake\")\n)\n\nfunc TestExportTraceFailureAttributes(t *testing.T) {\n\ttests := []struct {\n\t\tname         string\n\t\terr          error\n\t\tnumItems     int\n\t\texpectedType string\n\t\texpectedPerm bool\n\t\tuseCustomCtx bool\n\t\tctxSetup     func() context.Context\n\t}{\n\t\t{\n\t\t\tname:         \"PermanentError\",\n\t\t\terr:          consumererror.NewPermanent(errors.New(\"bad data\")),\n\t\t\tnumItems:     5,\n\t\t\texpectedType: \"_OTHER\",\n\t\t\texpectedPerm: true,\n\t\t},\n\t\t{\n\t\t\tname:         \"ShutdownError\",\n\t\t\terr:          experr.NewShutdownErr(errors.New(\"shutting down\")),\n\t\t\tnumItems:     3,\n\t\t\texpectedType: \"Shutdown\",\n\t\t\texpectedPerm: false,\n\t\t},\n\t\t{\n\t\t\tname:         \"ContextCanceled\",\n\t\t\terr:          context.Canceled,\n\t\t\tnumItems:     2,\n\t\t\texpectedType: \"Canceled\",\n\t\t\texpectedPerm: false,\n\t\t\tuseCustomCtx: true,\n\t\t\tctxSetup: func() context.Context {\n\t\t\t\tctx, cancel := context.WithCancel(context.Background())\n\t\t\t\tcancel()\n\t\t\t\treturn ctx\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:         \"ContextDeadlineExceeded\",\n\t\t\terr:          context.DeadlineExceeded,\n\t\t\tnumItems:     4,\n\t\t\texpectedType: \"Deadline_Exceeded\",\n\t\t\texpectedPerm: false,\n\t\t},\n\t\t{\n\t\t\tname:         \"UnknownError\",\n\t\t\terr:          errFake,\n\t\t\tnumItems:     8,\n\t\t\texpectedType: \"_OTHER\",\n\t\t\texpectedPerm: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttelemetry := componenttest.NewTelemetry()\n\t\t\tt.Cleanup(func() { require.NoError(t, telemetry.Shutdown(context.Background())) })\n\n\t\t\tobsrep, err := newObsReportSender(\n\t\t\t\texporter.Settings{ID: exporterID, TelemetrySettings: telemetry.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t\t\t\tpipeline.SignalTraces,\n\t\t\t\tsender.NewSender(func(context.Context, request.Request) error {\n\t\t\t\t\treturn tt.err\n\t\t\t\t}),\n\t\t\t)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tctx := context.Background()\n\t\t\tif tt.useCustomCtx && tt.ctxSetup != nil {\n\t\t\t\tctx = tt.ctxSetup()\n\t\t\t}\n\n\t\t\treq := &requesttest.FakeRequest{Items: tt.numItems}\n\t\t\tsendErr := obsrep.Send(ctx, req)\n\t\t\trequire.Error(t, sendErr)\n\n\t\t\twantAttrs := attribute.NewSet(\n\t\t\t\tattribute.String(\"exporter\", exporterID.String()),\n\t\t\t\tattribute.String(string(semconv.ErrorTypeKey), tt.expectedType),\n\t\t\t\tattribute.Bool(ErrorPermanentKey, tt.expectedPerm),\n\t\t\t)\n\n\t\t\tmetadatatest.AssertEqualExporterSendFailedSpans(t, telemetry,\n\t\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t\t{\n\t\t\t\t\t\tAttributes: wantAttrs,\n\t\t\t\t\t\tValue:      int64(req.Items),\n\t\t\t\t\t},\n\t\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t\t})\n\t}\n}\n\nfunc TestExportTraceFailureAttributesGRPCError(t *testing.T) {\n\ttests := []struct {\n\t\tname         string\n\t\tgrpcCode     grpccodes.Code\n\t\texpectedType string\n\t\tisPermanent  bool\n\t}{\n\t\t{\n\t\t\tname:         \"Unavailable\",\n\t\t\tgrpcCode:     grpccodes.Unavailable,\n\t\t\texpectedType: \"Unavailable\",\n\t\t\tisPermanent:  false,\n\t\t},\n\t\t{\n\t\t\tname:         \"ResourceExhausted\",\n\t\t\tgrpcCode:     grpccodes.ResourceExhausted,\n\t\t\texpectedType: \"ResourceExhausted\",\n\t\t\tisPermanent:  false,\n\t\t},\n\t\t{\n\t\t\tname:         \"DataLoss\",\n\t\t\tgrpcCode:     grpccodes.DataLoss,\n\t\t\texpectedType: \"DataLoss\",\n\t\t\tisPermanent:  false,\n\t\t},\n\t\t{\n\t\t\tname:         \"InvalidArgument\",\n\t\t\tgrpcCode:     grpccodes.InvalidArgument,\n\t\t\texpectedType: \"InvalidArgument\",\n\t\t\tisPermanent:  false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ttelemetry := componenttest.NewTelemetry()\n\t\t\tt.Cleanup(func() { require.NoError(t, telemetry.Shutdown(context.Background())) })\n\n\t\t\tgrpcErr := status.Error(tt.grpcCode, \"test error\")\n\t\t\tobsrep, err := newObsReportSender(\n\t\t\t\texporter.Settings{ID: exporterID, TelemetrySettings: telemetry.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t\t\t\tpipeline.SignalTraces,\n\t\t\t\tsender.NewSender(func(context.Context, request.Request) error {\n\t\t\t\t\treturn grpcErr\n\t\t\t\t}),\n\t\t\t)\n\t\t\trequire.NoError(t, err)\n\n\t\t\treq := &requesttest.FakeRequest{Items: 10}\n\t\t\tsendErr := obsrep.Send(context.Background(), req)\n\t\t\trequire.Error(t, sendErr)\n\n\t\t\twantAttrs := attribute.NewSet(\n\t\t\t\tattribute.String(\"exporter\", exporterID.String()),\n\t\t\t\tattribute.String(string(semconv.ErrorTypeKey), tt.expectedType),\n\t\t\t\tattribute.Bool(ErrorPermanentKey, tt.isPermanent),\n\t\t\t)\n\n\t\t\tmetadatatest.AssertEqualExporterSendFailedSpans(t, telemetry,\n\t\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t\t{\n\t\t\t\t\t\tAttributes: wantAttrs,\n\t\t\t\t\t\tValue:      int64(req.Items),\n\t\t\t\t\t},\n\t\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t\t})\n\t}\n}\n\nfunc TestExportTraceDataOp(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tparentCtx, parentSpan := tt.NewTelemetrySettings().TracerProvider.Tracer(\"test\").Start(context.Background(), t.Name())\n\tdefer parentSpan.End()\n\n\tvar exporterErr error\n\tobsrep, err := newObsReportSender(\n\t\texporter.Settings{ID: exporterID, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t\tpipeline.SignalTraces,\n\t\tsender.NewSender(func(context.Context, request.Request) error { return exporterErr }),\n\t)\n\trequire.NoError(t, err)\n\n\tparams := []testParams{\n\t\t{items: 22, err: nil},\n\t\t{items: 14, err: errFake},\n\t}\n\tfor i := range params {\n\t\texporterErr = params[i].err\n\t\trequire.ErrorIs(t, obsrep.Send(parentCtx, &requesttest.FakeRequest{Items: params[i].items}), params[i].err)\n\t}\n\n\tspans := tt.SpanRecorder.Ended()\n\trequire.Len(t, spans, len(params))\n\n\tvar sentSpans, failedToSendSpans int\n\tfor i, span := range spans {\n\t\tassert.Equal(t, \"exporter/\"+exporterID.String()+\"/traces\", span.Name())\n\t\tswitch {\n\t\tcase params[i].err == nil:\n\t\t\tsentSpans += params[i].items\n\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: ItemsSent, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: ItemsFailed, Value: attribute.Int64Value(0)})\n\t\t\tassert.Equal(t, codes.Unset, span.Status().Code)\n\t\tcase errors.Is(params[i].err, errFake):\n\t\t\tfailedToSendSpans += params[i].items\n\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: ItemsSent, Value: attribute.Int64Value(0)})\n\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: ItemsFailed, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\tassert.Equal(t, codes.Error, span.Status().Code)\n\t\t\tassert.Equal(t, params[i].err.Error(), span.Status().Description)\n\t\tdefault:\n\t\t\tt.Fatalf(\"unexpected error: %v\", params[i].err)\n\t\t}\n\t}\n\n\tmetadatatest.AssertEqualExporterSentSpans(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(\"exporter\", exporterID.String())),\n\t\t\t\tValue: int64(sentSpans),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\tvar expectedDataPoints []metricdata.DataPoint[int64]\n\tif failedToSendSpans > 0 {\n\t\twantAttrs := attribute.NewSet(\n\t\t\tattribute.String(\"exporter\", exporterID.String()),\n\t\t\tattribute.String(string(semconv.ErrorTypeKey), \"_OTHER\"),\n\t\t\tattribute.Bool(ErrorPermanentKey, false),\n\t\t)\n\t\texpectedDataPoints = []metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: wantAttrs,\n\t\t\t\tValue:      int64(failedToSendSpans),\n\t\t\t},\n\t\t}\n\t}\n\tmetadatatest.AssertEqualExporterSendFailedSpans(t, tt, expectedDataPoints,\n\t\tmetricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\nfunc TestExportMetricsOp(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tparentCtx, parentSpan := tt.NewTelemetrySettings().TracerProvider.Tracer(\"test\").Start(context.Background(), t.Name())\n\tdefer parentSpan.End()\n\n\tvar exporterErr error\n\tobsrep, err := newObsReportSender(\n\t\texporter.Settings{ID: exporterID, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t\tpipeline.SignalMetrics,\n\t\tsender.NewSender(func(context.Context, request.Request) error { return exporterErr }),\n\t)\n\trequire.NoError(t, err)\n\n\tparams := []testParams{\n\t\t{items: 17, err: nil},\n\t\t{items: 23, err: errFake},\n\t}\n\tfor i := range params {\n\t\texporterErr = params[i].err\n\t\trequire.ErrorIs(t, obsrep.Send(parentCtx, &requesttest.FakeRequest{Items: params[i].items}), params[i].err)\n\t}\n\n\tspans := tt.SpanRecorder.Ended()\n\trequire.Len(t, spans, len(params))\n\n\tvar sentMetricPoints, failedToSendMetricPoints int\n\tfor i, span := range spans {\n\t\tassert.Equal(t, \"exporter/\"+exporterID.String()+\"/metrics\", span.Name())\n\t\tswitch {\n\t\tcase params[i].err == nil:\n\t\t\tsentMetricPoints += params[i].items\n\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: ItemsSent, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: ItemsFailed, Value: attribute.Int64Value(0)})\n\t\t\tassert.Equal(t, codes.Unset, span.Status().Code)\n\t\tcase errors.Is(params[i].err, errFake):\n\t\t\tfailedToSendMetricPoints += params[i].items\n\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: ItemsSent, Value: attribute.Int64Value(0)})\n\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: ItemsFailed, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\tassert.Equal(t, codes.Error, span.Status().Code)\n\t\t\tassert.Equal(t, params[i].err.Error(), span.Status().Description)\n\t\tdefault:\n\t\t\tt.Fatalf(\"unexpected error: %v\", params[i].err)\n\t\t}\n\t}\n\n\tmetadatatest.AssertEqualExporterSentMetricPoints(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(\"exporter\", exporterID.String())),\n\t\t\t\tValue: int64(sentMetricPoints),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\tvar expectedDataPoints []metricdata.DataPoint[int64]\n\tif failedToSendMetricPoints > 0 {\n\t\twantAttrs := attribute.NewSet(\n\t\t\tattribute.String(\"exporter\", exporterID.String()),\n\t\t\tattribute.String(string(semconv.ErrorTypeKey), \"_OTHER\"),\n\t\t\tattribute.Bool(ErrorPermanentKey, false),\n\t\t)\n\t\texpectedDataPoints = []metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: wantAttrs,\n\t\t\t\tValue:      int64(failedToSendMetricPoints),\n\t\t\t},\n\t\t}\n\t}\n\tmetadatatest.AssertEqualExporterSendFailedMetricPoints(t, tt, expectedDataPoints,\n\t\tmetricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\nfunc TestExportLogsOp(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tparentCtx, parentSpan := tt.NewTelemetrySettings().TracerProvider.Tracer(\"test\").Start(context.Background(), t.Name())\n\tdefer parentSpan.End()\n\n\tvar exporterErr error\n\tobsrep, err := newObsReportSender(\n\t\texporter.Settings{ID: exporterID, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t\tpipeline.SignalLogs,\n\t\tsender.NewSender(func(context.Context, request.Request) error { return exporterErr }),\n\t)\n\trequire.NoError(t, err)\n\n\tparams := []testParams{\n\t\t{items: 17, err: nil},\n\t\t{items: 23, err: errFake},\n\t}\n\tfor i := range params {\n\t\texporterErr = params[i].err\n\t\trequire.ErrorIs(t, obsrep.Send(parentCtx, &requesttest.FakeRequest{Items: params[i].items}), params[i].err)\n\t}\n\n\tspans := tt.SpanRecorder.Ended()\n\trequire.Len(t, spans, len(params))\n\n\tvar sentLogRecords, failedToSendLogRecords int\n\tfor i, span := range spans {\n\t\tassert.Equal(t, \"exporter/\"+exporterID.String()+\"/logs\", span.Name())\n\t\tswitch {\n\t\tcase params[i].err == nil:\n\t\t\tsentLogRecords += params[i].items\n\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: ItemsSent, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: ItemsFailed, Value: attribute.Int64Value(0)})\n\t\t\tassert.Equal(t, codes.Unset, span.Status().Code)\n\t\tcase errors.Is(params[i].err, errFake):\n\t\t\tfailedToSendLogRecords += params[i].items\n\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: ItemsSent, Value: attribute.Int64Value(0)})\n\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: ItemsFailed, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\tassert.Equal(t, codes.Error, span.Status().Code)\n\t\t\tassert.Equal(t, params[i].err.Error(), span.Status().Description)\n\t\tdefault:\n\t\t\tt.Fatalf(\"unexpected error: %v\", params[i].err)\n\t\t}\n\t}\n\n\tmetadatatest.AssertEqualExporterSentLogRecords(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(\"exporter\", exporterID.String())),\n\t\t\t\tValue: int64(sentLogRecords),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\tvar expectedDataPoints []metricdata.DataPoint[int64]\n\tif failedToSendLogRecords > 0 {\n\t\twantAttrs := attribute.NewSet(\n\t\t\tattribute.String(\"exporter\", exporterID.String()),\n\t\t\tattribute.String(string(semconv.ErrorTypeKey), \"_OTHER\"),\n\t\t\tattribute.Bool(ErrorPermanentKey, false),\n\t\t)\n\t\texpectedDataPoints = []metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: wantAttrs,\n\t\t\t\tValue:      int64(failedToSendLogRecords),\n\t\t\t},\n\t\t}\n\t}\n\tmetadatatest.AssertEqualExporterSendFailedLogRecords(t, tt, expectedDataPoints,\n\t\tmetricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\n// TestDetermineErrorType tests the determineErrorType function directly\nfunc TestDetermineErrorType(t *testing.T) {\n\ttests := []struct {\n\t\tname              string\n\t\terr               error\n\t\texpectedErrorType string\n\t}{\n\t\t{\n\t\t\tname:              \"shutdown error\",\n\t\t\terr:               experr.NewShutdownErr(errors.New(\"shutting down\")),\n\t\t\texpectedErrorType: \"Shutdown\",\n\t\t},\n\t\t{\n\t\t\tname:              \"context canceled\",\n\t\t\terr:               context.Canceled,\n\t\t\texpectedErrorType: \"Canceled\",\n\t\t},\n\t\t{\n\t\t\tname:              \"context deadline exceeded\",\n\t\t\terr:               context.DeadlineExceeded,\n\t\t\texpectedErrorType: \"Deadline_Exceeded\",\n\t\t},\n\t\t{\n\t\t\tname:              \"unknown error\",\n\t\t\terr:               errors.New(\"some error\"),\n\t\t\texpectedErrorType: \"_OTHER\",\n\t\t},\n\t\t{\n\t\t\tname:              \"wrapped context canceled\",\n\t\t\terr:               fmt.Errorf(\"failed: %w\", context.Canceled),\n\t\t\texpectedErrorType: \"Canceled\",\n\t\t},\n\t\t{\n\t\t\tname:              \"wrapped context deadline exceeded\",\n\t\t\terr:               fmt.Errorf(\"timeout: %w\", context.DeadlineExceeded),\n\t\t\texpectedErrorType: \"Deadline_Exceeded\",\n\t\t},\n\t\t{\n\t\t\tname:              \"gRPC Unavailable\",\n\t\t\terr:               status.Error(grpccodes.Unavailable, \"service unavailable\"),\n\t\t\texpectedErrorType: \"Unavailable\",\n\t\t},\n\t\t{\n\t\t\tname:              \"gRPC ResourceExhausted\",\n\t\t\terr:               status.Error(grpccodes.ResourceExhausted, \"quota exceeded\"),\n\t\t\texpectedErrorType: \"ResourceExhausted\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terrorType := determineErrorType(tt.err)\n\t\t\tassert.Equal(t, tt.expectedErrorType, errorType, \"error.type mismatch\")\n\t\t})\n\t}\n}\n\n// TestExtractFailureAttributes tests the extractFailureAttributes function directly\nfunc TestExtractFailureAttributes(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\terr      error\n\t\texpected attribute.Set\n\t}{\n\t\t{\n\t\t\tname: \"permanent error\",\n\t\t\terr:  consumererror.NewPermanent(errors.New(\"bad data\")),\n\t\t\texpected: attribute.NewSet(\n\t\t\t\tattribute.String(string(semconv.ErrorTypeKey), \"_OTHER\"),\n\t\t\t\tattribute.Bool(ErrorPermanentKey, true),\n\t\t\t),\n\t\t},\n\t\t{\n\t\t\tname: \"non-permanent error\",\n\t\t\terr:  errors.New(\"transient error\"),\n\t\t\texpected: attribute.NewSet(\n\t\t\t\tattribute.String(string(semconv.ErrorTypeKey), \"_OTHER\"),\n\t\t\t\tattribute.Bool(ErrorPermanentKey, false),\n\t\t\t),\n\t\t},\n\t\t{\n\t\t\tname: \"shutdown error\",\n\t\t\terr:  experr.NewShutdownErr(errors.New(\"shutdown\")),\n\t\t\texpected: attribute.NewSet(\n\t\t\t\tattribute.String(string(semconv.ErrorTypeKey), \"Shutdown\"),\n\t\t\t\tattribute.Bool(ErrorPermanentKey, false),\n\t\t\t),\n\t\t},\n\t\t{\n\t\t\tname: \"context canceled\",\n\t\t\terr:  context.Canceled,\n\t\t\texpected: attribute.NewSet(\n\t\t\t\tattribute.String(string(semconv.ErrorTypeKey), \"Canceled\"),\n\t\t\t\tattribute.Bool(ErrorPermanentKey, false),\n\t\t\t),\n\t\t},\n\t\t{\n\t\t\tname: \"context deadline exceeded\",\n\t\t\terr:  context.DeadlineExceeded,\n\t\t\texpected: attribute.NewSet(\n\t\t\t\tattribute.String(string(semconv.ErrorTypeKey), \"Deadline_Exceeded\"),\n\t\t\t\tattribute.Bool(ErrorPermanentKey, false),\n\t\t\t),\n\t\t},\n\t\t{\n\t\t\tname: \"gRPC Unavailable\",\n\t\t\terr:  status.Error(grpccodes.Unavailable, \"service unavailable\"),\n\t\t\texpected: attribute.NewSet(\n\t\t\t\tattribute.String(string(semconv.ErrorTypeKey), \"Unavailable\"),\n\t\t\t\tattribute.Bool(ErrorPermanentKey, false),\n\t\t\t),\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := extractFailureAttributes(tt.err)\n\t\t\tassert.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestExportProfilesOp(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tparentCtx, parentSpan := tt.NewTelemetrySettings().TracerProvider.Tracer(\"test\").Start(context.Background(), t.Name())\n\tdefer parentSpan.End()\n\n\tvar exporterErr error\n\tobsrep, err := newObsReportSender(\n\t\texporter.Settings{ID: exporterID, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t\txpipeline.SignalProfiles,\n\t\tsender.NewSender(func(context.Context, request.Request) error { return exporterErr }),\n\t)\n\trequire.NoError(t, err)\n\n\tparams := []testParams{\n\t\t{items: 17, err: nil},\n\t\t{items: 23, err: errFake},\n\t}\n\tfor i := range params {\n\t\texporterErr = params[i].err\n\t\trequire.ErrorIs(t, obsrep.Send(parentCtx, &requesttest.FakeRequest{Items: params[i].items}), params[i].err)\n\t}\n\n\tspans := tt.SpanRecorder.Ended()\n\trequire.Len(t, spans, len(params))\n\n\tvar sentProfileRecords, failedToSendProfileRecords int\n\tfor i, span := range spans {\n\t\tassert.Equal(t, \"exporter/\"+exporterID.String()+\"/profiles\", span.Name())\n\t\tswitch {\n\t\tcase params[i].err == nil:\n\t\t\tsentProfileRecords += params[i].items\n\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: ItemsSent, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: ItemsFailed, Value: attribute.Int64Value(0)})\n\t\t\tassert.Equal(t, codes.Unset, span.Status().Code)\n\t\tcase errors.Is(params[i].err, errFake):\n\t\t\tfailedToSendProfileRecords += params[i].items\n\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: ItemsSent, Value: attribute.Int64Value(0)})\n\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: ItemsFailed, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\tassert.Equal(t, codes.Error, span.Status().Code)\n\t\t\tassert.Equal(t, params[i].err.Error(), span.Status().Description)\n\t\tdefault:\n\t\t\tt.Fatalf(\"unexpected error: %v\", params[i].err)\n\t\t}\n\t}\n\n\tmetadatatest.AssertEqualExporterSentProfileSamples(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(\"exporter\", exporterID.String())),\n\t\t\t\tValue: int64(sentProfileRecords),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\tvar expectedDataPoints []metricdata.DataPoint[int64]\n\tif failedToSendProfileRecords > 0 {\n\t\twantAttrs := attribute.NewSet(\n\t\t\tattribute.String(\"exporter\", exporterID.String()),\n\t\t\tattribute.String(string(semconv.ErrorTypeKey), \"_OTHER\"),\n\t\t\tattribute.Bool(ErrorPermanentKey, false),\n\t\t)\n\t\texpectedDataPoints = []metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: wantAttrs,\n\t\t\t\tValue:      int64(failedToSendProfileRecords),\n\t\t\t},\n\t\t}\n\t}\n\tmetadatatest.AssertEqualExporterSendFailedProfileSamples(t, tt, expectedDataPoints,\n\t\tmetricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\ntype testParams struct {\n\titems int\n\terr   error\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/oteltest/tracetest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage oteltest // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/oteltest\"\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/codes\"\n\tsdktrace \"go.opentelemetry.io/otel/sdk/trace\"\n\t\"go.opentelemetry.io/otel/trace\"\n)\n\nfunc CheckStatus(t *testing.T, sd sdktrace.ReadOnlySpan, err error) {\n\tif err != nil {\n\t\trequire.Equal(t, codes.Error, sd.Status().Code)\n\t\trequire.EqualError(t, err, sd.Status().Description)\n\t} else {\n\t\trequire.Equal(t, codes.Unset, sd.Status().Code)\n\t}\n}\n\nfunc FakeSpanContext(t *testing.T) trace.SpanContext {\n\ttraceID, err := trace.TraceIDFromHex(\"0102030405060708090a0b0c0d0e0f10\")\n\trequire.NoError(t, err)\n\tspanID, err := trace.SpanIDFromHex(\"0102030405060708\")\n\trequire.NoError(t, err)\n\treturn trace.NewSpanContext(trace.SpanContextConfig{\n\t\tTraceID:    traceID,\n\t\tSpanID:     spanID,\n\t\tTraceFlags: 0x01,\n\t\tTraceState: trace.TraceState{},\n\t\tRemote:     true,\n\t})\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queue/async_queue.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queue // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\ntype asyncQueue[T any] struct {\n\treadableQueue[T]\n\tnumConsumers int\n\trefCounter   ReferenceCounter[T]\n\tconsumeFunc  ConsumeFunc[T]\n\tstopWG       sync.WaitGroup\n}\n\nfunc newAsyncQueue[T any](q readableQueue[T], numConsumers int, consumeFunc ConsumeFunc[T], refCounter ReferenceCounter[T]) Queue[T] {\n\treturn &asyncQueue[T]{\n\t\treadableQueue: q,\n\t\tnumConsumers:  numConsumers,\n\t\trefCounter:    refCounter,\n\t\tconsumeFunc:   consumeFunc,\n\t}\n}\n\n// Start ensures that queue and all consumers are started.\nfunc (qc *asyncQueue[T]) Start(ctx context.Context, host component.Host) error {\n\tif err := qc.readableQueue.Start(ctx, host); err != nil {\n\t\treturn err\n\t}\n\tvar startWG sync.WaitGroup\n\tfor i := 0; i < qc.numConsumers; i++ {\n\t\tstartWG.Add(1)\n\t\tqc.stopWG.Go(func() { //nolint:contextcheck\n\t\t\tstartWG.Done()\n\t\t\tfor {\n\t\t\t\tctx, req, done, ok := qc.Read(context.Background())\n\t\t\t\tif !ok {\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tqc.consumeFunc(ctx, req, done)\n\t\t\t\tif qc.refCounter != nil {\n\t\t\t\t\tqc.refCounter.Unref(req)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\tstartWG.Wait()\n\n\treturn nil\n}\n\nfunc (qc *asyncQueue[T]) Offer(ctx context.Context, req T) error {\n\tspan := trace.SpanFromContext(ctx)\n\tif err := qc.readableQueue.Offer(ctx, req); err != nil {\n\t\tspan.AddEvent(\"Failed to enqueue item.\")\n\t\treturn err\n\t}\n\n\tspan.AddEvent(\"Enqueued item.\")\n\treturn nil\n}\n\n// Shutdown ensures that queue and all consumers are stopped.\nfunc (qc *asyncQueue[T]) Shutdown(ctx context.Context) error {\n\terr := qc.readableQueue.Shutdown(ctx)\n\tqc.stopWG.Wait()\n\treturn err\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queue/async_queue_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queue\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n)\n\nfunc TestAsyncMemoryQueue(t *testing.T) {\n\tconsumed := &atomic.Int64{}\n\n\tset := newSettings(request.SizerTypeItems, 100)\n\tac := newAsyncQueue(newMemoryQueue[intRequest](set),\n\t\t1, func(_ context.Context, _ intRequest, done Done) {\n\t\t\tconsumed.Add(1)\n\t\t\tdone.OnDone(nil)\n\t\t}, set.ReferenceCounter)\n\trequire.NoError(t, ac.Start(context.Background(), componenttest.NewNopHost()))\n\tfor range 10 {\n\t\trequire.NoError(t, ac.Offer(context.Background(), 10))\n\t}\n\trequire.NoError(t, ac.Shutdown(context.Background()))\n\tassert.EqualValues(t, 10, consumed.Load())\n}\n\nfunc TestAsyncMemoryQueueBlocking(t *testing.T) {\n\tconsumed := &atomic.Int64{}\n\tset := newSettings(request.SizerTypeItems, 100)\n\tset.BlockOnOverflow = true\n\tac := newAsyncQueue(newMemoryQueue[intRequest](set),\n\t\t4, func(_ context.Context, _ intRequest, done Done) {\n\t\t\tconsumed.Add(1)\n\t\t\tdone.OnDone(nil)\n\t\t}, set.ReferenceCounter)\n\trequire.NoError(t, ac.Start(context.Background(), componenttest.NewNopHost()))\n\twg := &sync.WaitGroup{}\n\tfor range 10 {\n\t\twg.Go(func() {\n\t\t\tfor range 100_000 {\n\t\t\t\tassert.NoError(t, ac.Offer(context.Background(), 10))\n\t\t\t}\n\t\t})\n\t}\n\twg.Wait()\n\trequire.NoError(t, ac.Shutdown(context.Background()))\n\tassert.EqualValues(t, 1_000_000, consumed.Load())\n}\n\nfunc TestAsyncMemoryWaitForResultQueueBlocking(t *testing.T) {\n\tconsumed := &atomic.Int64{}\n\tset := newSettings(request.SizerTypeItems, 100)\n\tset.BlockOnOverflow = true\n\tset.WaitForResult = true\n\tac := newAsyncQueue(newMemoryQueue[intRequest](set),\n\t\t4, func(_ context.Context, _ intRequest, done Done) {\n\t\t\tconsumed.Add(1)\n\t\t\tdone.OnDone(nil)\n\t\t}, set.ReferenceCounter)\n\trequire.NoError(t, ac.Start(context.Background(), componenttest.NewNopHost()))\n\twg := &sync.WaitGroup{}\n\tfor range 10 {\n\t\twg.Go(func() {\n\t\t\tfor range 100_000 {\n\t\t\t\tassert.NoError(t, ac.Offer(context.Background(), 10))\n\t\t\t}\n\t\t})\n\t}\n\twg.Wait()\n\trequire.NoError(t, ac.Shutdown(context.Background()))\n\tassert.EqualValues(t, 1_000_000, consumed.Load())\n}\n\nfunc TestAsyncMemoryQueueBlockingCancelled(t *testing.T) {\n\tstop := make(chan struct{})\n\tset := newSettings(request.SizerTypeItems, 10)\n\tset.BlockOnOverflow = true\n\tac := newAsyncQueue(newMemoryQueue[intRequest](set),\n\t\t1, func(_ context.Context, _ intRequest, done Done) {\n\t\t\t<-stop\n\t\t\tdone.OnDone(nil)\n\t\t}, set.ReferenceCounter)\n\trequire.NoError(t, ac.Start(context.Background(), componenttest.NewNopHost()))\n\n\tctx, cancel := context.WithCancel(context.Background())\n\twg := sync.WaitGroup{}\n\twg.Go(func() {\n\t\tfor range 10 {\n\t\t\trequire.NoError(t, ac.Offer(ctx, 1))\n\t\t}\n\t\tassert.ErrorIs(t, ac.Offer(ctx, 3), context.Canceled)\n\t})\n\t// Sleep some time so that the go-routine blocks, it doesn't have to but even if it\n\t// does things will work.\n\t<-time.After(1 * time.Second)\n\tcancel()\n\twg.Wait()\n\n\tclose(stop)\n\trequire.NoError(t, ac.Shutdown(context.Background()))\n}\n\nfunc BenchmarkAsyncMemoryQueue(b *testing.B) {\n\tb.Skip(\"Consistently fails with 'sending queue is full'\")\n\tconsumed := &atomic.Int64{}\n\tset := newSettings(request.SizerTypeItems, int64(10*b.N))\n\tac := newAsyncQueue(newMemoryQueue[intRequest](set), 1, func(_ context.Context, _ intRequest, done Done) {\n\t\tconsumed.Add(1)\n\t\tdone.OnDone(nil)\n\t}, set.ReferenceCounter)\n\trequire.NoError(b, ac.Start(context.Background(), componenttest.NewNopHost()))\n\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\trequire.NoError(b, ac.Offer(context.Background(), 10))\n\t}\n\trequire.NoError(b, ac.Shutdown(context.Background()))\n\tassert.EqualValues(b, b.N, consumed.Load())\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queue/cond.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queue // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\nimport (\n\t\"context\"\n\t\"sync\"\n)\n\n// cond is equivalent with sync.Cond, but context.Context aware.\n// Which means Wait() will return if context is done before any signal is received.\n// Also, it requires the caller to hold the c.L during all calls.\ntype cond struct {\n\tL       sync.Locker\n\tch      chan struct{}\n\twaiting int64\n}\n\nfunc newCond(l sync.Locker) *cond {\n\treturn &cond{L: l, ch: make(chan struct{}, 1)}\n}\n\n// Signal wakes one goroutine waiting on c, if there is any.\n// It requires for the caller to hold c.L during the call.\nfunc (c *cond) Signal() {\n\tif c.waiting == 0 {\n\t\treturn\n\t}\n\tc.waiting--\n\tc.ch <- struct{}{}\n}\n\n// Broadcast wakes all goroutines waiting on c.\n// It requires for the caller to hold c.L during the call.\nfunc (c *cond) Broadcast() {\n\tfor ; c.waiting > 0; c.waiting-- {\n\t\tc.ch <- struct{}{}\n\t}\n}\n\n// Wait atomically unlocks c.L and suspends execution of the calling goroutine. After later resuming execution, Wait locks c.L before returning.\nfunc (c *cond) Wait(ctx context.Context) error {\n\tc.waiting++\n\tc.L.Unlock()\n\tselect {\n\tcase <-ctx.Done():\n\t\tc.L.Lock()\n\t\tif c.waiting == 0 {\n\t\t\t// If waiting is 0, it means that there was a signal sent and nobody else waits for it.\n\t\t\t// Consume it, so that we don't unblock other consumer unnecessary,\n\t\t\t// or we don't block the producer because the channel buffer is full.\n\t\t\t<-c.ch\n\t\t} else {\n\t\t\t// Decrease the number of waiting routines.\n\t\t\tc.waiting--\n\t\t}\n\t\treturn ctx.Err()\n\tcase <-c.ch:\n\t\tc.L.Lock()\n\t\treturn nil\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queue/fg.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queue // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\nimport \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/metadata\"\n\n// assign the feature gate to separate functions to make it possible to override the behavior in tests\n// on write and read paths separately.\nvar (\n\tPersistRequestContextOnRead  = metadata.ExporterPersistRequestContextFeatureGate.IsEnabled\n\tPersistRequestContextOnWrite = metadata.ExporterPersistRequestContextFeatureGate.IsEnabled\n)\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queue/memory_queue.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queue // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n)\n\nvar blockingDonePool = sync.Pool{\n\tNew: func() any {\n\t\treturn &blockingDone{\n\t\t\tch: make(chan error, 1),\n\t\t}\n\t},\n}\n\nvar (\n\terrInvalidSize  = errors.New(\"invalid element size\")\n\terrSizeTooLarge = errors.New(\"element size too large\")\n)\n\n// memoryQueue is an in-memory implementation of a Queue.\ntype memoryQueue[T request.Request] struct {\n\tcomponent.StartFunc\n\trefCounter ReferenceCounter[T]\n\tsizer      request.Sizer\n\tcap        int64\n\n\tmu              sync.Mutex\n\thasMoreElements *sync.Cond\n\thasMoreSpace    *cond\n\titems           *linkedQueue[T]\n\tsize            int64\n\tstopped         bool\n\twaitForResult   bool\n\tblockOnOverflow bool\n}\n\n// newMemoryQueue creates a sized elements channel. Each element is assigned a size by the provided sizer.\n// capacity is the capacity of the queue.\nfunc newMemoryQueue[T request.Request](set Settings[T]) readableQueue[T] {\n\tsq := &memoryQueue[T]{\n\t\trefCounter:      set.ReferenceCounter,\n\t\tsizer:           request.NewSizer(set.SizerType),\n\t\tcap:             set.Capacity,\n\t\titems:           &linkedQueue[T]{},\n\t\twaitForResult:   set.WaitForResult,\n\t\tblockOnOverflow: set.BlockOnOverflow,\n\t}\n\tsq.hasMoreElements = sync.NewCond(&sq.mu)\n\tsq.hasMoreSpace = newCond(&sq.mu)\n\treturn sq\n}\n\n// Offer puts the element into the queue with the given sized if there is enough capacity.\n// Returns an error if the queue is full.\nfunc (mq *memoryQueue[T]) Offer(ctx context.Context, el T) error {\n\telSize := mq.sizer.Sizeof(el)\n\t// Ignore empty requests, see https://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md#empty-telemetry-envelopes\n\tif elSize == 0 {\n\t\treturn nil\n\t}\n\n\tif elSize <= 0 {\n\t\treturn errInvalidSize\n\t}\n\n\t// If element larger than the capacity, will never been able to add it.\n\tif elSize > mq.cap {\n\t\treturn errSizeTooLarge\n\t}\n\n\tif mq.refCounter != nil {\n\t\tmq.refCounter.Ref(el)\n\t}\n\n\tdone, err := mq.add(ctx, el, elSize)\n\tif err != nil {\n\t\t// Unref in case of an error since there will not be any async worker to pick it up.\n\t\tif mq.refCounter != nil {\n\t\t\tmq.refCounter.Unref(el)\n\t\t}\n\t\treturn err\n\t}\n\n\tif mq.waitForResult {\n\t\t// Only re-add the blockingDone instance back to the pool if successfully received the\n\t\t// message from the consumer which guarantees consumer will not use that anymore,\n\t\t// otherwise no guarantee about when the consumer will add the message to the channel so cannot reuse or close.\n\t\tselect {\n\t\tcase doneErr := <-done.ch:\n\t\t\tblockingDonePool.Put(done)\n\t\t\treturn doneErr\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (mq *memoryQueue[T]) add(ctx context.Context, el T, elSize int64) (*blockingDone, error) {\n\tmq.mu.Lock()\n\tdefer mq.mu.Unlock()\n\n\tfor mq.size+elSize > mq.cap {\n\t\tif !mq.blockOnOverflow {\n\t\t\treturn nil, ErrQueueIsFull\n\t\t}\n\t\t// Wait for more space or before the ctx is Done.\n\t\tif err := mq.hasMoreSpace.Wait(ctx); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\n\tmq.size += elSize\n\tdone := blockingDonePool.Get().(*blockingDone)\n\tdone.reset(elSize, mq)\n\n\tif !mq.waitForResult {\n\t\t// Prevent cancellation and deadline to propagate to the context stored in the queue.\n\t\t// The grpc/http based receivers will cancel the request context after this function returns.\n\t\tctx = context.WithoutCancel(ctx)\n\t}\n\n\tmq.items.push(ctx, el, done)\n\t// Signal one consumer if any.\n\tmq.hasMoreElements.Signal()\n\treturn done, nil\n}\n\n// Read removes the element from the queue and returns it.\n// The call blocks until there is an item available or the queue is stopped.\n// The function returns true when an item is consumed or false if the queue is stopped and emptied.\nfunc (mq *memoryQueue[T]) Read(context.Context) (context.Context, T, Done, bool) {\n\tmq.mu.Lock()\n\tdefer mq.mu.Unlock()\n\n\tfor {\n\t\tif mq.items.hasElements() {\n\t\t\telCtx, el, done := mq.items.pop()\n\t\t\treturn elCtx, el, done, true\n\t\t}\n\n\t\tif mq.stopped {\n\t\t\tvar el T\n\t\t\treturn context.Background(), el, nil, false\n\t\t}\n\n\t\t// TODO: Need to change the Queue interface to return an error to allow distinguish between shutdown and context canceled.\n\t\t//  Until then use the sync.Cond.\n\t\tmq.hasMoreElements.Wait()\n\t}\n}\n\nfunc (mq *memoryQueue[T]) onDone(bd *blockingDone, err error) {\n\tmq.mu.Lock()\n\tdefer mq.mu.Unlock()\n\tmq.size -= bd.elSize\n\tmq.hasMoreSpace.Signal()\n\tif mq.waitForResult {\n\t\t// In this case the done will be added back to the queue by the waiter.\n\t\tbd.ch <- err\n\t\treturn\n\t}\n\tblockingDonePool.Put(bd)\n}\n\n// Shutdown closes the queue channel to initiate draining of the queue.\nfunc (mq *memoryQueue[T]) Shutdown(context.Context) error {\n\tmq.mu.Lock()\n\tdefer mq.mu.Unlock()\n\tmq.stopped = true\n\tmq.hasMoreElements.Broadcast()\n\treturn nil\n}\n\nfunc (mq *memoryQueue[T]) Size() int64 {\n\tmq.mu.Lock()\n\tdefer mq.mu.Unlock()\n\treturn mq.size\n}\n\nfunc (mq *memoryQueue[T]) Capacity() int64 {\n\treturn mq.cap\n}\n\ntype node[T any] struct {\n\tctx  context.Context\n\tdata T\n\tdone Done\n\tnext *node[T]\n}\n\ntype linkedQueue[T any] struct {\n\thead *node[T]\n\ttail *node[T]\n}\n\nfunc (l *linkedQueue[T]) push(ctx context.Context, data T, done Done) {\n\tn := &node[T]{ctx: ctx, data: data, done: done}\n\t// If tail is nil means list is empty so update both head and tail to point to same element.\n\tif l.tail == nil {\n\t\tl.head = n\n\t\tl.tail = n\n\t\treturn\n\t}\n\tl.tail.next = n\n\tl.tail = n\n}\n\nfunc (l *linkedQueue[T]) hasElements() bool {\n\treturn l.head != nil\n}\n\nfunc (l *linkedQueue[T]) pop() (context.Context, T, Done) {\n\tn := l.head\n\tl.head = n.next\n\t// If it gets to the last element, then update tail as well.\n\tif l.head == nil {\n\t\tl.tail = nil\n\t}\n\tn.next = nil\n\treturn n.ctx, n.data, n.done\n}\n\ntype blockingDone struct {\n\tqueue interface {\n\t\tonDone(*blockingDone, error)\n\t}\n\telSize int64\n\tch     chan error\n}\n\nfunc (bd *blockingDone) reset(elSize int64, queue interface{ onDone(*blockingDone, error) }) {\n\tbd.elSize = elSize\n\tbd.queue = queue\n}\n\nfunc (bd *blockingDone) OnDone(err error) {\n\tbd.queue.onDone(bd, err)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queue/memory_queue_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queue\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n)\n\nfunc TestMemoryQueue(t *testing.T) {\n\tset := newSettings(request.SizerTypeItems, 7)\n\tq := newMemoryQueue[intRequest](set)\n\trequire.NoError(t, q.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.NoError(t, q.Offer(context.Background(), 1))\n\tassert.EqualValues(t, 1, q.Size())\n\tassert.EqualValues(t, 7, q.Capacity())\n\n\trequire.NoError(t, q.Offer(context.Background(), 3))\n\tassert.EqualValues(t, 4, q.Size())\n\n\t// should not be able to send to the full queue\n\trequire.ErrorIs(t, q.Offer(context.Background(), 4), ErrQueueIsFull)\n\tassert.EqualValues(t, 4, q.Size())\n\n\tassert.True(t, consume(q, func(_ context.Context, el intRequest) error {\n\t\tassert.EqualValues(t, 1, el)\n\t\treturn nil\n\t}))\n\tassert.EqualValues(t, 3, q.Size())\n\n\tassert.True(t, consume(q, func(_ context.Context, el intRequest) error {\n\t\tassert.EqualValues(t, 3, el)\n\t\treturn nil\n\t}))\n\tassert.EqualValues(t, 0, q.Size())\n\n\trequire.NoError(t, q.Shutdown(context.Background()))\n\tassert.False(t, consume(q, func(context.Context, intRequest) error { t.FailNow(); return nil }))\n\trequire.NoError(t, q.Shutdown(context.Background()))\n}\n\nfunc TestMemoryQueueBlockingCancelled(t *testing.T) {\n\tset := newSettings(request.SizerTypeItems, 5)\n\tset.BlockOnOverflow = true\n\tq := newMemoryQueue[intRequest](set)\n\trequire.NoError(t, q.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.NoError(t, q.Offer(context.Background(), 3))\n\tctx, cancel := context.WithCancel(context.Background())\n\twg := sync.WaitGroup{}\n\twg.Go(func() {\n\t\tassert.ErrorIs(t, q.Offer(ctx, 3), context.Canceled)\n\t})\n\tcancel()\n\twg.Wait()\n\tassert.EqualValues(t, 3, q.Size())\n\tassert.True(t, consume(q, func(_ context.Context, el intRequest) error {\n\t\tassert.EqualValues(t, 3, el)\n\t\treturn nil\n\t}))\n\trequire.NoError(t, q.Shutdown(context.Background()))\n}\n\nfunc TestMemoryQueueDrainWhenShutdown(t *testing.T) {\n\tset := newSettings(request.SizerTypeItems, 7)\n\tq := newMemoryQueue[intRequest](set)\n\trequire.NoError(t, q.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.NoError(t, q.Offer(context.Background(), 1))\n\trequire.NoError(t, q.Offer(context.Background(), 3))\n\n\tassert.True(t, consume(q, func(_ context.Context, el intRequest) error {\n\t\tassert.EqualValues(t, 1, el)\n\t\treturn nil\n\t}))\n\tassert.EqualValues(t, 3, q.Size())\n\trequire.NoError(t, q.Shutdown(context.Background()))\n\tassert.EqualValues(t, 3, q.Size())\n\tassert.True(t, consume(q, func(_ context.Context, el intRequest) error {\n\t\tassert.EqualValues(t, 3, el)\n\t\treturn nil\n\t}))\n\tassert.EqualValues(t, 0, q.Size())\n\tassert.False(t, consume(q, func(context.Context, intRequest) error { t.FailNow(); return nil }))\n\trequire.NoError(t, q.Shutdown(context.Background()))\n}\n\nfunc TestMemoryQueueOfferInvalidSize(t *testing.T) {\n\tset := newSettings(request.SizerTypeItems, 1)\n\tq := newMemoryQueue[intRequest](set)\n\trequire.NoError(t, q.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.ErrorIs(t, q.Offer(context.Background(), -1), errInvalidSize)\n\trequire.NoError(t, q.Shutdown(context.Background()))\n}\n\nfunc TestMemoryQueueRejectOverCapacityElements(t *testing.T) {\n\tset := newSettings(request.SizerTypeItems, 1)\n\tset.BlockOnOverflow = true\n\tq := newMemoryQueue[intRequest](set)\n\trequire.NoError(t, q.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.ErrorIs(t, q.Offer(context.Background(), 8), errSizeTooLarge)\n\trequire.NoError(t, q.Shutdown(context.Background()))\n}\n\nfunc TestMemoryQueueOfferZeroSize(t *testing.T) {\n\tset := newSettings(request.SizerTypeItems, 1)\n\tq := newMemoryQueue[intRequest](set)\n\trequire.NoError(t, q.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.NoError(t, q.Offer(context.Background(), 0))\n\trequire.NoError(t, q.Shutdown(context.Background()))\n\t// Because the size 0 is ignored, nothing to drain.\n\tassert.False(t, consume(q, func(context.Context, intRequest) error { t.FailNow(); return nil }))\n}\n\nfunc TestMemoryQueueOverflow(t *testing.T) {\n\tset := newSettings(request.SizerTypeItems, 1)\n\tq := newMemoryQueue[intRequest](set)\n\trequire.NoError(t, q.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.NoError(t, q.Offer(context.Background(), 1))\n\trequire.ErrorIs(t, q.Offer(context.Background(), 1), ErrQueueIsFull)\n\trequire.NoError(t, q.Shutdown(context.Background()))\n}\n\nfunc TestMemoryQueueWaitForResultPassErrorBack(t *testing.T) {\n\twg := sync.WaitGroup{}\n\tmyErr := errors.New(\"test error\")\n\tset := newSettings(request.SizerTypeItems, 100)\n\tset.WaitForResult = true\n\tq := newMemoryQueue[intRequest](set)\n\trequire.NoError(t, q.Start(context.Background(), componenttest.NewNopHost()))\n\twg.Go(func() {\n\t\t_, req, done, ok := q.Read(context.Background())\n\t\tassert.True(t, ok)\n\t\tassert.EqualValues(t, 1, req)\n\t\tdone.OnDone(myErr)\n\t})\n\trequire.ErrorIs(t, q.Offer(context.Background(), intRequest(1)), myErr)\n\trequire.NoError(t, q.Shutdown(context.Background()))\n\twg.Wait()\n}\n\nfunc TestMemoryQueueWaitForResultCancelIncomingRequest(t *testing.T) {\n\twg := sync.WaitGroup{}\n\tstop := make(chan struct{})\n\tset := newSettings(request.SizerTypeItems, 100)\n\tset.WaitForResult = true\n\tq := newMemoryQueue[intRequest](set)\n\trequire.NoError(t, q.Start(context.Background(), componenttest.NewNopHost()))\n\n\t// Consume async new data.\n\twg.Go(func() {\n\t\t_, _, done, ok := q.Read(context.Background())\n\t\tassert.True(t, ok)\n\t\t<-stop\n\t\tdone.OnDone(nil)\n\t})\n\n\tctx, cancel := context.WithCancel(context.Background())\n\twg.Go(func() {\n\t\t<-time.After(time.Second)\n\t\tcancel()\n\t})\n\trequire.ErrorIs(t, q.Offer(ctx, intRequest(1)), context.Canceled)\n\tclose(stop)\n\trequire.NoError(t, q.Shutdown(context.Background()))\n\twg.Wait()\n}\n\nfunc TestMemoryQueueWaitForResultSizeAndCapacity(t *testing.T) {\n\twg := sync.WaitGroup{}\n\tstop := make(chan struct{})\n\tset := newSettings(request.SizerTypeItems, 100)\n\tset.WaitForResult = true\n\tq := newMemoryQueue[intRequest](set)\n\trequire.NoError(t, q.Start(context.Background(), componenttest.NewNopHost()))\n\n\t// Consume async new data.\n\twg.Go(func() {\n\t\t_, _, done, ok := q.Read(context.Background())\n\t\tassert.True(t, ok)\n\t\t<-stop\n\t\tdone.OnDone(nil)\n\t})\n\n\tassert.EqualValues(t, 0, q.Size())\n\tassert.EqualValues(t, 100, q.Capacity())\n\twg.Go(func() {\n\t\tassert.NoError(t, q.Offer(context.Background(), intRequest(1)))\n\t})\n\tassert.Eventually(t, func() bool { return q.Size() == 1 }, 1*time.Second, 10*time.Millisecond)\n\tassert.EqualValues(t, 100, q.Capacity())\n\tclose(stop)\n\trequire.NoError(t, q.Shutdown(context.Background()))\n\twg.Wait()\n}\n\nfunc BenchmarkMemoryQueueWaitForResult(b *testing.B) {\n\twg := sync.WaitGroup{}\n\tconsumed := &atomic.Int64{}\n\tset := newSettings(request.SizerTypeItems, 100)\n\tset.WaitForResult = true\n\tq := newMemoryQueue[intRequest](set)\n\trequire.NoError(b, q.Start(context.Background(), componenttest.NewNopHost()))\n\n\t// Consume async new data.\n\twg.Go(func() {\n\t\tfor {\n\t\t\t_, req, done, ok := q.Read(context.Background())\n\t\t\tif !ok {\n\t\t\t\treturn\n\t\t\t}\n\t\t\tconsumed.Add(int64(req))\n\t\t\tdone.OnDone(nil)\n\t\t}\n\t})\n\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tfor range 100 {\n\t\t\trequire.NoError(b, q.Offer(context.Background(), intRequest(1)))\n\t\t}\n\t}\n\trequire.NoError(b, q.Shutdown(context.Background()))\n\tassert.Equal(b, int64(b.N)*100, consumed.Load())\n}\n\nfunc consume[T any](q readableQueue[T], consumeFunc func(context.Context, T) error) bool {\n\tctx, req, done, ok := q.Read(context.Background())\n\tif !ok {\n\t\treturn false\n\t}\n\tdone.OnDone(consumeFunc(ctx, req))\n\treturn true\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queue/meta.pb.go",
    "content": "// Code generated by protoc-gen-go. DO NOT EDIT.\n// versions:\n// \tprotoc-gen-go v1.26.0\n// \tprotoc        v3.21.6\n// source: exporter/exporterhelper/internal/queue/meta.proto\n\npackage queue\n\nimport (\n\treflect \"reflect\"\n\tsync \"sync\"\n\n\tprotoreflect \"google.golang.org/protobuf/reflect/protoreflect\"\n\tprotoimpl \"google.golang.org/protobuf/runtime/protoimpl\"\n)\n\nconst (\n\t// Verify that this generated code is sufficiently up-to-date.\n\t_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)\n\t// Verify that runtime/protoimpl is sufficiently up-to-date.\n\t_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)\n)\n\n// PersistentMetadata holds all persistent metadata for the queue.\n// The items and bytes sizes are recorded explicitly,\n// the requests size can be calculated as (write_index - read_index + len(currently_dispatched_items)).\ntype PersistentMetadata struct {\n\tstate         protoimpl.MessageState\n\tsizeCache     protoimpl.SizeCache\n\tunknownFields protoimpl.UnknownFields\n\n\t// Current total items size of the queue.\n\tItemsSize int64 `protobuf:\"fixed64,1,opt,name=items_size,json=itemsSize,proto3\" json:\"items_size,omitempty\"`\n\t// Current total bytes size of the queue.\n\tBytesSize int64 `protobuf:\"fixed64,2,opt,name=bytes_size,json=bytesSize,proto3\" json:\"bytes_size,omitempty\"`\n\t// Index of the next item to be read from the queue.\n\tReadIndex uint64 `protobuf:\"fixed64,3,opt,name=read_index,json=readIndex,proto3\" json:\"read_index,omitempty\"`\n\t// Index where the next item will be written to the queue.\n\tWriteIndex uint64 `protobuf:\"fixed64,4,opt,name=write_index,json=writeIndex,proto3\" json:\"write_index,omitempty\"`\n\t// List of item indices currently being processed by consumers.\n\tCurrentlyDispatchedItems []uint64 `protobuf:\"fixed64,5,rep,packed,name=currently_dispatched_items,json=currentlyDispatchedItems,proto3\" json:\"currently_dispatched_items,omitempty\"`\n}\n\nfunc (x *PersistentMetadata) Reset() {\n\t*x = PersistentMetadata{}\n\tif protoimpl.UnsafeEnabled {\n\t\tmi := &file_exporter_exporterhelper_internal_queue_meta_proto_msgTypes[0]\n\t\tms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))\n\t\tms.StoreMessageInfo(mi)\n\t}\n}\n\nfunc (x *PersistentMetadata) String() string {\n\treturn protoimpl.X.MessageStringOf(x)\n}\n\nfunc (*PersistentMetadata) ProtoMessage() {}\n\nfunc (x *PersistentMetadata) ProtoReflect() protoreflect.Message {\n\tmi := &file_exporter_exporterhelper_internal_queue_meta_proto_msgTypes[0]\n\tif protoimpl.UnsafeEnabled && x != nil {\n\t\tms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))\n\t\tif ms.LoadMessageInfo() == nil {\n\t\t\tms.StoreMessageInfo(mi)\n\t\t}\n\t\treturn ms\n\t}\n\treturn mi.MessageOf(x)\n}\n\n// Deprecated: Use PersistentMetadata.ProtoReflect.Descriptor instead.\nfunc (*PersistentMetadata) Descriptor() ([]byte, []int) {\n\treturn file_exporter_exporterhelper_internal_queue_meta_proto_rawDescGZIP(), []int{0}\n}\n\nfunc (x *PersistentMetadata) GetItemsSize() int64 {\n\tif x != nil {\n\t\treturn x.ItemsSize\n\t}\n\treturn 0\n}\n\nfunc (x *PersistentMetadata) GetBytesSize() int64 {\n\tif x != nil {\n\t\treturn x.BytesSize\n\t}\n\treturn 0\n}\n\nfunc (x *PersistentMetadata) GetReadIndex() uint64 {\n\tif x != nil {\n\t\treturn x.ReadIndex\n\t}\n\treturn 0\n}\n\nfunc (x *PersistentMetadata) GetWriteIndex() uint64 {\n\tif x != nil {\n\t\treturn x.WriteIndex\n\t}\n\treturn 0\n}\n\nfunc (x *PersistentMetadata) GetCurrentlyDispatchedItems() []uint64 {\n\tif x != nil {\n\t\treturn x.CurrentlyDispatchedItems\n\t}\n\treturn nil\n}\n\nvar File_exporter_exporterhelper_internal_queue_meta_proto protoreflect.FileDescriptor\n\nvar file_exporter_exporterhelper_internal_queue_meta_proto_rawDesc = []byte{\n\t0x0a, 0x31, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x72, 0x2f, 0x65, 0x78, 0x70, 0x6f, 0x72,\n\t0x74, 0x65, 0x72, 0x68, 0x65, 0x6c, 0x70, 0x65, 0x72, 0x2f, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e,\n\t0x61, 0x6c, 0x2f, 0x71, 0x75, 0x65, 0x75, 0x65, 0x2f, 0x6d, 0x65, 0x74, 0x61, 0x2e, 0x70, 0x72,\n\t0x6f, 0x74, 0x6f, 0x12, 0x3e, 0x6f, 0x70, 0x65, 0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74,\n\t0x72, 0x79, 0x2e, 0x63, 0x6f, 0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2e, 0x65, 0x78, 0x70,\n\t0x6f, 0x72, 0x74, 0x65, 0x72, 0x2e, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x72, 0x68, 0x65,\n\t0x6c, 0x70, 0x65, 0x72, 0x2e, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2e, 0x71, 0x75,\n\t0x65, 0x75, 0x65, 0x22, 0xd0, 0x01, 0x0a, 0x12, 0x50, 0x65, 0x72, 0x73, 0x69, 0x73, 0x74, 0x65,\n\t0x6e, 0x74, 0x4d, 0x65, 0x74, 0x61, 0x64, 0x61, 0x74, 0x61, 0x12, 0x1d, 0x0a, 0x0a, 0x69, 0x74,\n\t0x65, 0x6d, 0x73, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x01, 0x20, 0x01, 0x28, 0x10, 0x52, 0x09,\n\t0x69, 0x74, 0x65, 0x6d, 0x73, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x62, 0x79, 0x74,\n\t0x65, 0x73, 0x5f, 0x73, 0x69, 0x7a, 0x65, 0x18, 0x02, 0x20, 0x01, 0x28, 0x10, 0x52, 0x09, 0x62,\n\t0x79, 0x74, 0x65, 0x73, 0x53, 0x69, 0x7a, 0x65, 0x12, 0x1d, 0x0a, 0x0a, 0x72, 0x65, 0x61, 0x64,\n\t0x5f, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x18, 0x03, 0x20, 0x01, 0x28, 0x06, 0x52, 0x09, 0x72, 0x65,\n\t0x61, 0x64, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x12, 0x1f, 0x0a, 0x0b, 0x77, 0x72, 0x69, 0x74, 0x65,\n\t0x5f, 0x69, 0x6e, 0x64, 0x65, 0x78, 0x18, 0x04, 0x20, 0x01, 0x28, 0x06, 0x52, 0x0a, 0x77, 0x72,\n\t0x69, 0x74, 0x65, 0x49, 0x6e, 0x64, 0x65, 0x78, 0x12, 0x3c, 0x0a, 0x1a, 0x63, 0x75, 0x72, 0x72,\n\t0x65, 0x6e, 0x74, 0x6c, 0x79, 0x5f, 0x64, 0x69, 0x73, 0x70, 0x61, 0x74, 0x63, 0x68, 0x65, 0x64,\n\t0x5f, 0x69, 0x74, 0x65, 0x6d, 0x73, 0x18, 0x05, 0x20, 0x03, 0x28, 0x06, 0x52, 0x18, 0x63, 0x75,\n\t0x72, 0x72, 0x65, 0x6e, 0x74, 0x6c, 0x79, 0x44, 0x69, 0x73, 0x70, 0x61, 0x74, 0x63, 0x68, 0x65,\n\t0x64, 0x49, 0x74, 0x65, 0x6d, 0x73, 0x42, 0x46, 0x5a, 0x44, 0x67, 0x6f, 0x2e, 0x6f, 0x70, 0x65,\n\t0x6e, 0x74, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x74, 0x72, 0x79, 0x2e, 0x69, 0x6f, 0x2f, 0x63, 0x6f,\n\t0x6c, 0x6c, 0x65, 0x63, 0x74, 0x6f, 0x72, 0x2f, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x72,\n\t0x2f, 0x65, 0x78, 0x70, 0x6f, 0x72, 0x74, 0x65, 0x72, 0x68, 0x65, 0x6c, 0x70, 0x65, 0x72, 0x2f,\n\t0x69, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x61, 0x6c, 0x2f, 0x71, 0x75, 0x65, 0x75, 0x65, 0x62, 0x06,\n\t0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33,\n}\n\nvar (\n\tfile_exporter_exporterhelper_internal_queue_meta_proto_rawDescOnce sync.Once\n\tfile_exporter_exporterhelper_internal_queue_meta_proto_rawDescData = file_exporter_exporterhelper_internal_queue_meta_proto_rawDesc\n)\n\nfunc file_exporter_exporterhelper_internal_queue_meta_proto_rawDescGZIP() []byte {\n\tfile_exporter_exporterhelper_internal_queue_meta_proto_rawDescOnce.Do(func() {\n\t\tfile_exporter_exporterhelper_internal_queue_meta_proto_rawDescData = protoimpl.X.CompressGZIP(file_exporter_exporterhelper_internal_queue_meta_proto_rawDescData)\n\t})\n\treturn file_exporter_exporterhelper_internal_queue_meta_proto_rawDescData\n}\n\nvar file_exporter_exporterhelper_internal_queue_meta_proto_msgTypes = make([]protoimpl.MessageInfo, 1)\nvar file_exporter_exporterhelper_internal_queue_meta_proto_goTypes = []interface{}{\n\t(*PersistentMetadata)(nil), // 0: opentelemetry.collector.exporter.exporterhelper.internal.queue.PersistentMetadata\n}\nvar file_exporter_exporterhelper_internal_queue_meta_proto_depIdxs = []int32{\n\t0, // [0:0] is the sub-list for method output_type\n\t0, // [0:0] is the sub-list for method input_type\n\t0, // [0:0] is the sub-list for extension type_name\n\t0, // [0:0] is the sub-list for extension extendee\n\t0, // [0:0] is the sub-list for field type_name\n}\n\nfunc init() { file_exporter_exporterhelper_internal_queue_meta_proto_init() }\nfunc file_exporter_exporterhelper_internal_queue_meta_proto_init() {\n\tif File_exporter_exporterhelper_internal_queue_meta_proto != nil {\n\t\treturn\n\t}\n\tif !protoimpl.UnsafeEnabled {\n\t\tfile_exporter_exporterhelper_internal_queue_meta_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} {\n\t\t\tswitch v := v.(*PersistentMetadata); i {\n\t\t\tcase 0:\n\t\t\t\treturn &v.state\n\t\t\tcase 1:\n\t\t\t\treturn &v.sizeCache\n\t\t\tcase 2:\n\t\t\t\treturn &v.unknownFields\n\t\t\tdefault:\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t}\n\ttype x struct{}\n\tout := protoimpl.TypeBuilder{\n\t\tFile: protoimpl.DescBuilder{\n\t\t\tGoPackagePath: reflect.TypeOf(x{}).PkgPath(),\n\t\t\tRawDescriptor: file_exporter_exporterhelper_internal_queue_meta_proto_rawDesc,\n\t\t\tNumEnums:      0,\n\t\t\tNumMessages:   1,\n\t\t\tNumExtensions: 0,\n\t\t\tNumServices:   0,\n\t\t},\n\t\tGoTypes:           file_exporter_exporterhelper_internal_queue_meta_proto_goTypes,\n\t\tDependencyIndexes: file_exporter_exporterhelper_internal_queue_meta_proto_depIdxs,\n\t\tMessageInfos:      file_exporter_exporterhelper_internal_queue_meta_proto_msgTypes,\n\t}.Build()\n\tFile_exporter_exporterhelper_internal_queue_meta_proto = out.File\n\tfile_exporter_exporterhelper_internal_queue_meta_proto_rawDesc = nil\n\tfile_exporter_exporterhelper_internal_queue_meta_proto_goTypes = nil\n\tfile_exporter_exporterhelper_internal_queue_meta_proto_depIdxs = nil\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queue/meta.proto",
    "content": "syntax = \"proto3\";\n\npackage opentelemetry.collector.exporter.exporterhelper.internal.queue;\n\noption go_package = \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\";\n\n// PersistentMetadata holds all persistent metadata for the queue.\n// The items and bytes sizes are recorded explicitly,\n// the requests size can be calculated as (write_index - read_index + len(currently_dispatched_items)).\nmessage PersistentMetadata{\n  // Current total items size of the queue.\n  sfixed64 items_size = 1;\n\n  // Current total bytes size of the queue.\n  sfixed64 bytes_size = 2;\n\n  // Index of the next item to be read from the queue.\n  fixed64 read_index = 3;\n\n  // Index where the next item will be written to the queue.\n  fixed64 write_index = 4;\n\n  // List of item indices currently being processed by consumers.\n  repeated fixed64 currently_dispatched_items = 5;\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queue/obs_queue.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queue // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/metadata\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n)\n\nconst (\n\t// ExporterKey used to identify exporters in metrics and traces.\n\texporterKey = \"exporter\"\n\n\t// DataTypeKey used to identify the data type in the queue size metric.\n\tdataTypeKey = \"data_type\"\n)\n\n// obsQueue is a helper to add observability to a queue.\ntype obsQueue[T request.Request] struct {\n\tQueue[T]\n\ttb                      *metadata.TelemetryBuilder\n\tmetricAttr              metric.MeasurementOption\n\tenqueueFailedInst       metric.Int64Counter\n\tqueueBatchSizeInst      metric.Int64Histogram\n\tqueueBatchSizeBytesInst metric.Int64Histogram\n\ttracer                  trace.Tracer\n}\n\nfunc newObsQueue[T request.Request](set Settings[T], delegate Queue[T]) (Queue[T], error) {\n\ttb, err := metadata.NewTelemetryBuilder(set.Telemetry)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\texporterAttr := attribute.String(exporterKey, set.ID.String())\n\tasyncAttr := metric.WithAttributeSet(attribute.NewSet(exporterAttr, attribute.String(dataTypeKey, set.Signal.String())))\n\terr = tb.RegisterExporterQueueSizeCallback(func(_ context.Context, o metric.Int64Observer) error {\n\t\to.Observe(delegate.Size(), asyncAttr)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\terr = tb.RegisterExporterQueueCapacityCallback(func(_ context.Context, o metric.Int64Observer) error {\n\t\to.Observe(delegate.Capacity(), asyncAttr)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttracer := metadata.Tracer(set.Telemetry)\n\n\tor := &obsQueue[T]{\n\t\tQueue:      delegate,\n\t\ttb:         tb,\n\t\tmetricAttr: metric.WithAttributeSet(attribute.NewSet(exporterAttr)),\n\t\ttracer:     tracer,\n\t}\n\n\tswitch set.Signal {\n\tcase pipeline.SignalTraces:\n\t\tor.enqueueFailedInst = tb.ExporterEnqueueFailedSpans\n\tcase pipeline.SignalMetrics:\n\t\tor.enqueueFailedInst = tb.ExporterEnqueueFailedMetricPoints\n\tcase pipeline.SignalLogs:\n\t\tor.enqueueFailedInst = tb.ExporterEnqueueFailedLogRecords\n\tcase xpipeline.SignalProfiles:\n\t\tor.enqueueFailedInst = tb.ExporterEnqueueFailedProfileSamples\n\t}\n\n\tor.queueBatchSizeInst = tb.ExporterQueueBatchSendSize\n\tor.queueBatchSizeBytesInst = tb.ExporterQueueBatchSendSizeBytes\n\n\treturn or, nil\n}\n\nfunc (or *obsQueue[T]) Shutdown(ctx context.Context) error {\n\tdefer or.tb.Shutdown()\n\treturn or.Queue.Shutdown(ctx)\n}\n\nfunc (or *obsQueue[T]) Offer(ctx context.Context, req T) error {\n\t// Have to read the number of items before sending the request since the request can\n\t// be modified by the downstream components like the batcher.\n\tnumItems := req.ItemsCount()\n\n\tor.queueBatchSizeInst.Record(ctx, int64(numItems), or.metricAttr)\n\tor.queueBatchSizeBytesInst.Record(ctx, int64(req.BytesSize()), or.metricAttr)\n\n\tctx, span := or.tracer.Start(ctx, \"exporter/enqueue\")\n\terr := or.Queue.Offer(ctx, req)\n\tspan.End()\n\n\t// No metrics recorded for profiles, remove enqueueFailedInst check with nil when profiles metrics available.\n\tif err != nil && or.enqueueFailedInst != nil {\n\t\tor.enqueueFailedInst.Add(ctx, int64(numItems), or.metricAttr)\n\t}\n\treturn err\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queue/obs_queue_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queue\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/metadatatest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n)\n\nvar exporterID = component.NewID(exportertest.NopType)\n\ntype fakeQueue[T any] struct {\n\tQueue[T]\n\tofferErr error\n\tsize     int64\n\tcapacity int64\n}\n\nfunc (fq *fakeQueue[T]) Size() int64 {\n\treturn fq.size\n}\n\nfunc (fq *fakeQueue[T]) Capacity() int64 {\n\treturn fq.capacity\n}\n\nfunc (fq *fakeQueue[T]) Offer(context.Context, T) error {\n\treturn fq.offerErr\n}\n\nfunc newFakeQueue[T request.Request](offerErr error, size, capacity int64) Queue[T] {\n\treturn &fakeQueue[T]{offerErr: offerErr, size: size, capacity: capacity}\n}\n\nfunc TestObsQueueLogsSizeCapacity(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tte, err := newObsQueue[request.Request](Settings[request.Request]{\n\t\tSignal:    pipeline.SignalLogs,\n\t\tID:        exporterID,\n\t\tTelemetry: tt.NewTelemetrySettings(),\n\t}, newFakeQueue[request.Request](nil, 7, 9))\n\trequire.NoError(t, err)\n\trequire.NoError(t, te.Offer(context.Background(), &requesttest.FakeRequest{Items: 2}))\n\tmetadatatest.AssertEqualExporterQueueSize(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(exporterKey, exporterID.String()),\n\t\t\t\t\tattribute.String(dataTypeKey, pipeline.SignalLogs.String())),\n\t\t\t\tValue: int64(7),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\tmetadatatest.AssertEqualExporterQueueCapacity(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(exporterKey, exporterID.String()),\n\t\t\t\t\tattribute.String(dataTypeKey, pipeline.SignalLogs.String())),\n\t\t\t\tValue: int64(9),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n}\n\nfunc TestObsQueueLogsFailure(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tte, err := newObsQueue[request.Request](Settings[request.Request]{\n\t\tSignal:    pipeline.SignalLogs,\n\t\tID:        exporterID,\n\t\tTelemetry: tt.NewTelemetrySettings(),\n\t}, newFakeQueue[request.Request](errors.New(\"my error\"), 7, 9))\n\trequire.NoError(t, err)\n\trequire.Error(t, te.Offer(context.Background(), &requesttest.FakeRequest{Items: 2}))\n\tmetadatatest.AssertEqualExporterEnqueueFailedLogRecords(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(exporterKey, exporterID.String())),\n\t\t\t\tValue: int64(2),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\nfunc TestObsQueueTracesSizeCapacity(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tte, err := newObsQueue[request.Request](Settings[request.Request]{\n\t\tSignal:    pipeline.SignalTraces,\n\t\tID:        exporterID,\n\t\tTelemetry: tt.NewTelemetrySettings(),\n\t}, newFakeQueue[request.Request](nil, 17, 19))\n\trequire.NoError(t, err)\n\trequire.NoError(t, te.Offer(context.Background(), &requesttest.FakeRequest{Items: 12}))\n\tmetadatatest.AssertEqualExporterQueueSize(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(exporterKey, exporterID.String()),\n\t\t\t\t\tattribute.String(dataTypeKey, pipeline.SignalTraces.String())),\n\t\t\t\tValue: int64(17),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\tmetadatatest.AssertEqualExporterQueueCapacity(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(exporterKey, exporterID.String()),\n\t\t\t\t\tattribute.String(dataTypeKey, pipeline.SignalTraces.String())),\n\t\t\t\tValue: int64(19),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n}\n\nfunc TestObsQueueTracesFailure(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tte, err := newObsQueue[request.Request](Settings[request.Request]{\n\t\tSignal:    pipeline.SignalTraces,\n\t\tID:        exporterID,\n\t\tTelemetry: tt.NewTelemetrySettings(),\n\t}, newFakeQueue[request.Request](errors.New(\"my error\"), 0, 0))\n\trequire.NoError(t, err)\n\trequire.Error(t, te.Offer(context.Background(), &requesttest.FakeRequest{Items: 12}))\n\tmetadatatest.AssertEqualExporterEnqueueFailedSpans(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(exporterKey, exporterID.String())),\n\t\t\t\tValue: int64(12),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\nfunc TestObsQueueMetrics(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tte, err := newObsQueue[request.Request](Settings[request.Request]{\n\t\tSignal:    pipeline.SignalMetrics,\n\t\tID:        exporterID,\n\t\tTelemetry: tt.NewTelemetrySettings(),\n\t}, newFakeQueue[request.Request](nil, 27, 29))\n\trequire.NoError(t, err)\n\trequire.NoError(t, te.Offer(context.Background(), &requesttest.FakeRequest{Items: 22}))\n\tmetadatatest.AssertEqualExporterQueueSize(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(exporterKey, exporterID.String()),\n\t\t\t\t\tattribute.String(dataTypeKey, pipeline.SignalMetrics.String())),\n\t\t\t\tValue: int64(27),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\tmetadatatest.AssertEqualExporterQueueCapacity(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(exporterKey, exporterID.String()),\n\t\t\t\t\tattribute.String(dataTypeKey, pipeline.SignalMetrics.String())),\n\t\t\t\tValue: int64(29),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n}\n\nfunc TestObsQueueMetricsFailure(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tte, err := newObsQueue[request.Request](Settings[request.Request]{\n\t\tSignal:    pipeline.SignalMetrics,\n\t\tID:        exporterID,\n\t\tTelemetry: tt.NewTelemetrySettings(),\n\t}, newFakeQueue[request.Request](errors.New(\"my error\"), 0, 0))\n\trequire.NoError(t, err)\n\trequire.Error(t, te.Offer(context.Background(), &requesttest.FakeRequest{Items: 22}))\n\tmetadatatest.AssertEqualExporterEnqueueFailedMetricPoints(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(exporterKey, exporterID.String())),\n\t\t\t\tValue: int64(22),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\nfunc TestObsQueueProfiles(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tte, err := newObsQueue[request.Request](Settings[request.Request]{\n\t\tSignal:    xpipeline.SignalProfiles,\n\t\tID:        exporterID,\n\t\tTelemetry: tt.NewTelemetrySettings(),\n\t}, newFakeQueue[request.Request](nil, 27, 29))\n\trequire.NoError(t, err)\n\trequire.NoError(t, te.Offer(context.Background(), &requesttest.FakeRequest{Items: 22}))\n\tmetadatatest.AssertEqualExporterQueueSize(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(exporterKey, exporterID.String()),\n\t\t\t\t\tattribute.String(dataTypeKey, xpipeline.SignalProfiles.String())),\n\t\t\t\tValue: int64(27),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\tmetadatatest.AssertEqualExporterQueueCapacity(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(exporterKey, exporterID.String()),\n\t\t\t\t\tattribute.String(dataTypeKey, xpipeline.SignalProfiles.String())),\n\t\t\t\tValue: int64(29),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n}\n\nfunc TestObsQueueProfilesFailure(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tte, err := newObsQueue[request.Request](Settings[request.Request]{\n\t\tSignal:    xpipeline.SignalProfiles,\n\t\tID:        exporterID,\n\t\tTelemetry: tt.NewTelemetrySettings(),\n\t}, newFakeQueue[request.Request](errors.New(\"my error\"), 0, 0))\n\trequire.NoError(t, err)\n\trequire.Error(t, te.Offer(context.Background(), &requesttest.FakeRequest{Items: 22}))\n\tmetadatatest.AssertEqualExporterEnqueueFailedProfileSamples(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(exporterKey, exporterID.String())),\n\t\t\t\tValue: int64(22),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\nfunc TestObsQueueLogsBatchSize(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tte, err := newObsQueue[request.Request](Settings[request.Request]{\n\t\tSignal:    pipeline.SignalLogs,\n\t\tID:        exporterID,\n\t\tTelemetry: tt.NewTelemetrySettings(),\n\t}, newFakeQueue[request.Request](nil, 7, 9))\n\trequire.NoError(t, err)\n\trequire.NoError(t, te.Offer(context.Background(), &requesttest.FakeRequest{Items: 2, Bytes: 100}))\n\tmetadatatest.AssertEqualExporterQueueBatchSendSize(t, tt,\n\t\t[]metricdata.HistogramDataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(exporterKey, exporterID.String())),\n\t\t\t\tCount:        1,\n\t\t\t\tBounds:       []float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, 100000},\n\t\t\t\tBucketCounts: []uint64{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\tMin:          metricdata.NewExtrema[int64](2),\n\t\t\t\tMax:          metricdata.NewExtrema[int64](2),\n\t\t\t\tSum:          2,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n}\n\nfunc TestObsQueueTracesBatchSize(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tte, err := newObsQueue[request.Request](Settings[request.Request]{\n\t\tSignal:    pipeline.SignalTraces,\n\t\tID:        exporterID,\n\t\tTelemetry: tt.NewTelemetrySettings(),\n\t}, newFakeQueue[request.Request](nil, 17, 19))\n\trequire.NoError(t, err)\n\trequire.NoError(t, te.Offer(context.Background(), &requesttest.FakeRequest{Items: 12, Bytes: 200}))\n\tmetadatatest.AssertEqualExporterQueueBatchSendSize(t, tt,\n\t\t[]metricdata.HistogramDataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(exporterKey, exporterID.String())),\n\t\t\t\tCount:        1,\n\t\t\t\tBounds:       []float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, 100000},\n\t\t\t\tBucketCounts: []uint64{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\tMin:          metricdata.NewExtrema[int64](12),\n\t\t\t\tMax:          metricdata.NewExtrema[int64](12),\n\t\t\t\tSum:          12,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n}\n\nfunc TestObsQueueMetricsBatchSize(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tte, err := newObsQueue[request.Request](Settings[request.Request]{\n\t\tSignal:    pipeline.SignalMetrics,\n\t\tID:        exporterID,\n\t\tTelemetry: tt.NewTelemetrySettings(),\n\t}, newFakeQueue[request.Request](nil, 27, 29))\n\trequire.NoError(t, err)\n\trequire.NoError(t, te.Offer(context.Background(), &requesttest.FakeRequest{Items: 22, Bytes: 300}))\n\tmetadatatest.AssertEqualExporterQueueBatchSendSize(t, tt,\n\t\t[]metricdata.HistogramDataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(exporterKey, exporterID.String())),\n\t\t\t\tCount:        1,\n\t\t\t\tBounds:       []float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, 100000},\n\t\t\t\tBucketCounts: []uint64{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\tMin:          metricdata.NewExtrema[int64](22),\n\t\t\t\tMax:          metricdata.NewExtrema[int64](22),\n\t\t\t\tSum:          22,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n}\n\nfunc TestObsQueueProfilesBatchSize(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tte, err := newObsQueue[request.Request](Settings[request.Request]{\n\t\tSignal:    xpipeline.SignalProfiles,\n\t\tID:        exporterID,\n\t\tTelemetry: tt.NewTelemetrySettings(),\n\t}, newFakeQueue[request.Request](nil, 27, 29))\n\trequire.NoError(t, err)\n\trequire.NoError(t, te.Offer(context.Background(), &requesttest.FakeRequest{Items: 22, Bytes: 300}))\n\tmetadatatest.AssertEqualExporterQueueBatchSendSize(t, tt,\n\t\t[]metricdata.HistogramDataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(exporterKey, exporterID.String())),\n\t\t\t\tCount:        1,\n\t\t\t\tBounds:       []float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, 100000},\n\t\t\t\tBucketCounts: []uint64{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\tMin:          metricdata.NewExtrema[int64](22),\n\t\t\t\tMax:          metricdata.NewExtrema[int64](22),\n\t\t\t\tSum:          22,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queue/persistent_queue.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queue // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\nimport (\n\t\"context\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"sync\"\n\n\t\"go.uber.org/zap\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/experr\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/extension/xextension/storage\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\nconst (\n\tzapKey           = \"key\"\n\tzapErrorCount    = \"errorCount\"\n\tzapNumberOfItems = \"numberOfItems\"\n\n\tlegacyReadIndexKey                = \"ri\"\n\tlegacyWriteIndexKey               = \"wi\"\n\tlegacyCurrentlyDispatchedItemsKey = \"di\"\n\n\t// metadataKey is the new single key for all queue metadata.\n\tmetadataKey = \"qmv0\"\n)\n\nvar (\n\terrValueNotSet        = errors.New(\"value not set\")\n\terrInvalidValue       = errors.New(\"invalid value\")\n\terrNoStorageClient    = errors.New(\"no storage client extension found\")\n\terrWrongExtensionType = errors.New(\"requested extension is not a storage extension\")\n)\n\nvar indexDonePool = sync.Pool{\n\tNew: func() any {\n\t\treturn &indexDone{}\n\t},\n}\n\n// persistentQueue provides a persistent queue implementation backed by file storage extension\n//\n// Write index describes the position at which next item is going to be stored.\n// Read index describes which item needs to be read next.\n// When Write index = Read index, no elements are in the queue.\n//\n// The items currently dispatched by consumers are not deleted until the processing is finished.\n// Their list is stored under a separate key.\n//\n//\t┌───────file extension-backed queue───────┐\n//\t│                                         │\n//\t│     ┌───┐     ┌───┐ ┌───┐ ┌───┐ ┌───┐   │\n//\t│ n+1 │ n │ ... │ 4 │ │ 3 │ │ 2 │ │ 1 │   │\n//\t│     └───┘     └───┘ └─x─┘ └─|─┘ └─x─┘   │\n//\t│                       x     |     x     │\n//\t└───────────────────────x─────|─────x─────┘\n//\t   ▲              ▲     x     |     x\n//\t   │              │     x     |     xxxx deleted\n//\t   │              │     x     |\n//\t write          read    x     └── currently dispatched item\n//\t index          index   x\n//\t                        xxxx deleted\ntype persistentQueue[T request.Request] struct {\n\tlogger      *zap.Logger\n\tclient      storage.Client\n\tencoding    Encoding[T]\n\tcapacity    int64\n\tsizerType   request.SizerType\n\tactiveSizer request.Sizer\n\titemsSizer  request.Sizer\n\tbytesSizer  request.Sizer\n\tstorageID   component.ID\n\tid          component.ID\n\tsignal      pipeline.Signal\n\n\t// mu guards everything declared below.\n\tmu              sync.Mutex\n\thasMoreElements *sync.Cond\n\thasMoreSpace    *cond\n\tmetadata        PersistentMetadata\n\trefClient       int64\n\tstopped         bool\n\n\tblockOnOverflow bool\n}\n\n// newPersistentQueue creates a new queue backed by file storage; name and signal must be a unique combination that identifies the queue storage\nfunc newPersistentQueue[T request.Request](set Settings[T]) readableQueue[T] {\n\tpq := &persistentQueue[T]{\n\t\tlogger:          set.Telemetry.Logger,\n\t\tencoding:        set.Encoding,\n\t\tcapacity:        set.Capacity,\n\t\tsizerType:       set.SizerType,\n\t\tactiveSizer:     request.NewSizer(set.SizerType),\n\t\titemsSizer:      request.NewItemsSizer(),\n\t\tbytesSizer:      request.NewBytesSizer(),\n\t\tstorageID:       *set.StorageID,\n\t\tid:              set.ID,\n\t\tsignal:          set.Signal,\n\t\tblockOnOverflow: set.BlockOnOverflow,\n\t}\n\tpq.hasMoreElements = sync.NewCond(&pq.mu)\n\tpq.hasMoreSpace = newCond(&pq.mu)\n\treturn pq\n}\n\n// Start starts the persistentQueue with the given number of consumers.\nfunc (pq *persistentQueue[T]) Start(ctx context.Context, host component.Host) error {\n\tstorageClient, err := toStorageClient(ctx, pq.storageID, host, pq.id, pq.signal)\n\tif err != nil {\n\t\treturn err\n\t}\n\tpq.initClient(ctx, storageClient)\n\treturn nil\n}\n\nfunc (pq *persistentQueue[T]) Size() int64 {\n\tpq.mu.Lock()\n\tdefer pq.mu.Unlock()\n\treturn pq.internalSize()\n}\n\nfunc (pq *persistentQueue[T]) internalSize() int64 {\n\tswitch pq.sizerType {\n\tcase request.SizerTypeBytes:\n\t\treturn pq.metadata.BytesSize\n\tcase request.SizerTypeItems:\n\t\treturn pq.metadata.ItemsSize\n\tdefault:\n\t\treturn pq.requestSize()\n\t}\n}\n\nfunc (pq *persistentQueue[T]) requestSize() int64 {\n\treturn int64(pq.metadata.WriteIndex-pq.metadata.ReadIndex) + int64(len(pq.metadata.CurrentlyDispatchedItems))\n}\n\nfunc (pq *persistentQueue[T]) Capacity() int64 {\n\treturn pq.capacity\n}\n\nfunc (pq *persistentQueue[T]) initClient(ctx context.Context, client storage.Client) {\n\tpq.client = client\n\t// Start with a reference 1 which is the reference we use for the producer goroutines and initialization.\n\tpq.refClient = 1\n\n\t// Try to load from new consolidated metadata first\n\terr := pq.loadQueueMetadata(ctx)\n\tswitch {\n\tcase err == nil:\n\t\tpq.enqueueNotDispatchedReqs(ctx, pq.metadata.CurrentlyDispatchedItems)\n\t\tpq.metadata.CurrentlyDispatchedItems = nil\n\tcase !errors.Is(err, errValueNotSet):\n\t\tpq.logger.Error(\"Failed getting metadata, starting with new ones\", zap.Error(err))\n\t\tpq.metadata = PersistentMetadata{}\n\tdefault:\n\t\tpq.logger.Info(\"New queue metadata key not found, attempting to load legacy format.\")\n\t\tpq.loadLegacyMetadata(ctx)\n\t}\n}\n\n// loadQueueMetadata loads queue metadata from the consolidated key\nfunc (pq *persistentQueue[T]) loadQueueMetadata(ctx context.Context) error {\n\tbuf, err := pq.client.Get(ctx, metadataKey)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif len(buf) == 0 {\n\t\treturn errValueNotSet\n\t}\n\n\tif err := proto.Unmarshal(buf, &pq.metadata); err != nil {\n\t\treturn err\n\t}\n\n\tpq.logger.Info(\"Loaded queue metadata\",\n\t\tzap.Uint64(\"readIndex\", pq.metadata.ReadIndex),\n\t\tzap.Uint64(\"writeIndex\", pq.metadata.WriteIndex),\n\t\tzap.Int64(\"itemsSize\", pq.metadata.ItemsSize),\n\t\tzap.Int64(\"bytesSize\", pq.metadata.BytesSize),\n\t\tzap.Int(\"dispatchedItems\", len(pq.metadata.CurrentlyDispatchedItems)))\n\n\treturn nil\n}\n\n// TODO: Remove legacy format support after 6 months (target: December 2025)\nfunc (pq *persistentQueue[T]) loadLegacyMetadata(ctx context.Context) {\n\t// Fallback to legacy individual keys for backward compatibility\n\triOp := storage.GetOperation(legacyReadIndexKey)\n\twiOp := storage.GetOperation(legacyWriteIndexKey)\n\n\terr := pq.client.Batch(ctx, riOp, wiOp)\n\tif err == nil {\n\t\tpq.metadata.ReadIndex, err = bytesToItemIndex(riOp.Value)\n\t}\n\n\tif err == nil {\n\t\tpq.metadata.WriteIndex, err = bytesToItemIndex(wiOp.Value)\n\t}\n\n\tif err != nil {\n\t\tif errors.Is(err, errValueNotSet) {\n\t\t\tpq.logger.Info(\"Initializing new persistent queue\")\n\t\t} else {\n\t\t\tpq.logger.Error(\"Failed getting read/write index, starting with new ones\", zap.Error(err))\n\t\t}\n\t\tpq.metadata.ReadIndex = 0\n\t\tpq.metadata.WriteIndex = 0\n\t}\n\n\tpq.retrieveAndEnqueueNotDispatchedReqs(ctx)\n\n\t// Save to a new format and clean up legacy keys\n\tmetadataBytes, err := proto.Marshal(&pq.metadata)\n\tif err != nil {\n\t\tpq.logger.Error(\"Failed to marshal metadata\", zap.Error(err))\n\t\treturn\n\t}\n\n\tif err = pq.client.Set(ctx, metadataKey, metadataBytes); err != nil {\n\t\tpq.logger.Error(\"Failed to persist current metadata to storage\", zap.Error(err))\n\t\treturn\n\t}\n\n\tif err = pq.client.Batch(ctx,\n\t\tstorage.DeleteOperation(legacyReadIndexKey),\n\t\tstorage.DeleteOperation(legacyWriteIndexKey),\n\t\tstorage.DeleteOperation(legacyCurrentlyDispatchedItemsKey)); err != nil {\n\t\tpq.logger.Warn(\"Failed to cleanup legacy metadata keys\", zap.Error(err))\n\t} else {\n\t\tpq.logger.Info(\"Successfully migrated to consolidated metadata format\")\n\t}\n}\n\nfunc (pq *persistentQueue[T]) Shutdown(ctx context.Context) error {\n\t// If the queue is not initialized, there is nothing to shut down.\n\tif pq.client == nil {\n\t\treturn nil\n\t}\n\n\tpq.mu.Lock()\n\tdefer pq.mu.Unlock()\n\t// Mark this queue as stopped, so consumer don't start any more work.\n\tpq.stopped = true\n\tpq.hasMoreElements.Broadcast()\n\treturn pq.unrefClient(ctx)\n}\n\n// unrefClient unrefs the client, and closes if no more references. Callers MUST hold the mutex.\n// This is needed because consumers of the queue may still process the requests while the queue is shutting down or immediately after.\nfunc (pq *persistentQueue[T]) unrefClient(ctx context.Context) error {\n\tpq.refClient--\n\tif pq.refClient == 0 {\n\t\treturn pq.client.Close(ctx)\n\t}\n\treturn nil\n}\n\n// Offer inserts the specified element into this queue if it is possible to do so immediately\n// without violating capacity restrictions. If success returns no error.\n// It returns ErrQueueIsFull if no space is currently available.\nfunc (pq *persistentQueue[T]) Offer(ctx context.Context, req T) error {\n\tpq.mu.Lock()\n\tdefer pq.mu.Unlock()\n\n\tsize := pq.activeSizer.Sizeof(req)\n\tfor pq.internalSize()+size > pq.capacity {\n\t\tif !pq.blockOnOverflow {\n\t\t\treturn ErrQueueIsFull\n\t\t}\n\t\tif err := pq.hasMoreSpace.Wait(ctx); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tpq.metadata.ItemsSize += pq.itemsSizer.Sizeof(req)\n\tpq.metadata.BytesSize += pq.bytesSizer.Sizeof(req)\n\n\treturn pq.putInternal(ctx, req)\n}\n\n// putInternal adds the request to the storage without updating items/bytes sizes.\nfunc (pq *persistentQueue[T]) putInternal(ctx context.Context, req T) error {\n\tpq.metadata.WriteIndex++\n\n\tmetadataBuf, err := proto.Marshal(&pq.metadata)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treqBuf, err := pq.encoding.Marshal(ctx, req)\n\tif err != nil {\n\t\treturn err\n\t}\n\t// Carry out a transaction where we both add the item and update the write index\n\tops := []*storage.Operation{\n\t\tstorage.SetOperation(metadataKey, metadataBuf),\n\t\tstorage.SetOperation(getItemKey(pq.metadata.WriteIndex-1), reqBuf),\n\t}\n\tif err := pq.client.Batch(ctx, ops...); err != nil {\n\t\t// At this moment, metadata may be updated in the storage, so we cannot just revert changes to the\n\t\t// metadata, rely on the sizes being fixed on complete draining.\n\t\treturn err\n\t}\n\n\tpq.hasMoreElements.Signal()\n\n\treturn nil\n}\n\nfunc (pq *persistentQueue[T]) Read(ctx context.Context) (context.Context, T, Done, bool) {\n\tpq.mu.Lock()\n\tdefer pq.mu.Unlock()\n\n\tfor {\n\t\tif pq.stopped {\n\t\t\tvar req T\n\t\t\treturn context.Background(), req, nil, false\n\t\t}\n\n\t\t// Read until either a successful retrieved element or no more elements in the storage.\n\t\tfor pq.metadata.ReadIndex != pq.metadata.WriteIndex {\n\t\t\tindex, req, reqCtx, consumed := pq.getNextItem(ctx)\n\t\t\t// Ensure the used size are in sync when queue is drained.\n\t\t\tif pq.requestSize() == 0 {\n\t\t\t\tpq.metadata.BytesSize = 0\n\t\t\t\tpq.metadata.ItemsSize = 0\n\t\t\t}\n\t\t\tif consumed {\n\t\t\t\tid := indexDonePool.Get().(*indexDone)\n\t\t\t\tid.reset(index, pq.itemsSizer.Sizeof(req), pq.bytesSizer.Sizeof(req), pq)\n\t\t\t\treturn reqCtx, req, id, true\n\t\t\t}\n\t\t\t// More space available, data was dropped.\n\t\t\tpq.hasMoreSpace.Signal()\n\t\t}\n\n\t\t// TODO: Need to change the Queue interface to return an error to allow distinguish between shutdown and context canceled.\n\t\t//  Until then use the sync.Cond.\n\t\tpq.hasMoreElements.Wait()\n\t}\n}\n\n// getNextItem pulls the next available item from the persistent storage along with its index. Once processing is\n// finished, the index should be called with onDone to clean up the storage. If no new item is available,\n// returns false.\nfunc (pq *persistentQueue[T]) getNextItem(ctx context.Context) (uint64, T, context.Context, bool) {\n\tindex := pq.metadata.ReadIndex\n\t// Increase here, so even if errors happen below, it always iterates\n\tpq.metadata.ReadIndex++\n\tpq.metadata.CurrentlyDispatchedItems = append(pq.metadata.CurrentlyDispatchedItems, index)\n\n\tvar req T\n\trestoredCtx := context.Background()\n\tmetadataBytes, err := proto.Marshal(&pq.metadata)\n\tif err != nil {\n\t\treturn 0, req, restoredCtx, false\n\t}\n\n\tgetOp := storage.GetOperation(getItemKey(index))\n\terr = pq.client.Batch(ctx, storage.SetOperation(metadataKey, metadataBytes), getOp)\n\tif err == nil {\n\t\trestoredCtx, req, err = pq.encoding.Unmarshal(getOp.Value)\n\t}\n\n\tif err != nil {\n\t\tpq.logger.Debug(\"Failed to dispatch item\", zap.Error(err))\n\t\t// We need to make sure that currently dispatched items list is cleaned\n\t\tif err = pq.itemDispatchingFinish(ctx, index); err != nil {\n\t\t\tpq.logger.Error(\"Error deleting item from queue\", zap.Error(err))\n\t\t}\n\n\t\treturn 0, req, restoredCtx, false\n\t}\n\n\t// Increase the reference count, so the client is not closed while the request is being processed.\n\t// The client cannot be closed because we hold the lock since last we checked `stopped`.\n\tpq.refClient++\n\n\treturn index, req, restoredCtx, true\n}\n\n// onDone should be called to remove the item of the given index from the queue once processing is finished.\nfunc (pq *persistentQueue[T]) onDone(index uint64, itemsSize, bytesSize int64, consumeErr error) {\n\t// Delete the item from the persistent storage after it was processed.\n\tpq.mu.Lock()\n\t// Always unref client even if the consumer is shutdown because we always ref it for every valid request.\n\tdefer func() {\n\t\tif err := pq.unrefClient(context.Background()); err != nil {\n\t\t\tpq.logger.Error(\"Error closing the storage client\", zap.Error(err))\n\t\t}\n\t\tpq.mu.Unlock()\n\t}()\n\n\tif experr.IsShutdownErr(consumeErr) {\n\t\t// The queue is shutting down, don't mark the item as dispatched, so it's picked up again after restart.\n\t\t// TODO: Handle partially delivered requests by updating their values in the storage.\n\t\treturn\n\t}\n\n\tpq.metadata.BytesSize -= bytesSize\n\tif pq.metadata.BytesSize < 0 {\n\t\tpq.metadata.BytesSize = 0\n\t}\n\tpq.metadata.ItemsSize -= itemsSize\n\tif pq.metadata.ItemsSize < 0 {\n\t\tpq.metadata.ItemsSize = 0\n\t}\n\n\tif err := pq.itemDispatchingFinish(context.Background(), index); err != nil {\n\t\tpq.logger.Error(\"Error deleting item from queue\", zap.Error(err))\n\t}\n\n\t// More space available after data are removed from the storage.\n\tpq.hasMoreSpace.Signal()\n}\n\n// retrieveAndEnqueueNotDispatchedReqs gets the items for which sending was not finished, cleans the storage\n// and moves the items at the back of the queue.\nfunc (pq *persistentQueue[T]) retrieveAndEnqueueNotDispatchedReqs(ctx context.Context) {\n\tvar dispatchedItems []uint64\n\n\tpq.mu.Lock()\n\tdefer pq.mu.Unlock()\n\tpq.logger.Debug(\"Checking if there are items left for dispatch by consumers\")\n\titemKeysBuf, err := pq.client.Get(ctx, legacyCurrentlyDispatchedItemsKey)\n\tif err == nil {\n\t\tdispatchedItems, err = bytesToItemIndexArray(itemKeysBuf)\n\t}\n\tif err != nil {\n\t\tpq.logger.Error(\"Could not fetch items left for dispatch by consumers\", zap.Error(err))\n\t\treturn\n\t}\n\n\tpq.enqueueNotDispatchedReqs(ctx, dispatchedItems)\n}\n\nfunc (pq *persistentQueue[T]) enqueueNotDispatchedReqs(ctx context.Context, dispatchedItems []uint64) {\n\tif len(dispatchedItems) == 0 {\n\t\tpq.logger.Debug(\"No items left for dispatch by consumers\")\n\t\treturn\n\t}\n\n\tpq.logger.Info(\"Fetching items left for dispatch by consumers\", zap.Int(zapNumberOfItems,\n\t\tlen(dispatchedItems)))\n\tretrieveBatch := make([]*storage.Operation, len(dispatchedItems))\n\tcleanupBatch := make([]*storage.Operation, len(dispatchedItems))\n\tfor i, it := range dispatchedItems {\n\t\tkey := getItemKey(it)\n\t\tretrieveBatch[i] = storage.GetOperation(key)\n\t\tcleanupBatch[i] = storage.DeleteOperation(key)\n\t}\n\tretrieveErr := pq.client.Batch(ctx, retrieveBatch...)\n\tcleanupErr := pq.client.Batch(ctx, cleanupBatch...)\n\n\tif cleanupErr != nil {\n\t\tpq.logger.Debug(\"Failed cleaning items left by consumers\", zap.Error(cleanupErr))\n\t}\n\n\tif retrieveErr != nil {\n\t\tpq.logger.Warn(\"Failed retrieving items left by consumers\", zap.Error(retrieveErr))\n\t\treturn\n\t}\n\n\terrCount := 0\n\tfor _, op := range retrieveBatch {\n\t\tif op.Value == nil {\n\t\t\tpq.logger.Warn(\"Failed retrieving item\", zap.String(zapKey, op.Key), zap.Error(errValueNotSet))\n\t\t\tcontinue\n\t\t}\n\t\treqCtx, req, err := pq.encoding.Unmarshal(op.Value)\n\t\t// If error happened or item is nil, it will be efficiently ignored\n\t\tif err != nil {\n\t\t\tpq.logger.Warn(\"Failed unmarshalling item\", zap.String(zapKey, op.Key), zap.Error(err))\n\t\t\tcontinue\n\t\t}\n\t\tif pq.putInternal(reqCtx, req) != nil { //nolint:contextcheck\n\t\t\terrCount++\n\t\t}\n\t}\n\n\tif errCount > 0 {\n\t\tpq.logger.Error(\"Errors occurred while moving items for dispatching back to queue\",\n\t\t\tzap.Int(zapNumberOfItems, len(retrieveBatch)), zap.Int(zapErrorCount, errCount))\n\t} else {\n\t\tpq.logger.Info(\"Moved items for dispatching back to queue\",\n\t\t\tzap.Int(zapNumberOfItems, len(retrieveBatch)))\n\t}\n}\n\n// itemDispatchingFinish removes the item from the list of currently dispatched items and deletes it from the persistent queue\nfunc (pq *persistentQueue[T]) itemDispatchingFinish(ctx context.Context, index uint64) error {\n\tlenCDI := len(pq.metadata.CurrentlyDispatchedItems)\n\tfor i := range lenCDI {\n\t\tif pq.metadata.CurrentlyDispatchedItems[i] == index {\n\t\t\tpq.metadata.CurrentlyDispatchedItems[i] = pq.metadata.CurrentlyDispatchedItems[lenCDI-1]\n\t\t\tpq.metadata.CurrentlyDispatchedItems = pq.metadata.CurrentlyDispatchedItems[:lenCDI-1]\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Ensure the used size are in sync when queue is drained.\n\tif pq.requestSize() == 0 {\n\t\tpq.metadata.BytesSize = 0\n\t\tpq.metadata.ItemsSize = 0\n\t}\n\n\tmetadataBytes, err := proto.Marshal(&pq.metadata)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tsetOp := storage.SetOperation(metadataKey, metadataBytes)\n\tdeleteOp := storage.DeleteOperation(getItemKey(index))\n\terr = pq.client.Batch(ctx, setOp, deleteOp)\n\tif err == nil {\n\t\t// Everything ok, exit\n\t\treturn nil\n\t}\n\n\t// got an error, try to gracefully handle it\n\tpq.logger.Warn(\"Failed updating currently dispatched items, trying to delete the item first\",\n\t\tzap.Error(err))\n\n\tif err = pq.client.Batch(ctx, deleteOp); err != nil {\n\t\t// Return an error here, as this indicates an issue with the underlying storage medium\n\t\treturn fmt.Errorf(\"failed deleting item from queue, got error from storage: %w\", err)\n\t}\n\n\tif err = pq.client.Batch(ctx, setOp); err != nil {\n\t\t// even if this fails, we still have the right dispatched items in memory\n\t\t// at worst, we'll have the wrong list in storage, and we'll discard the nonexistent items during startup\n\t\treturn fmt.Errorf(\"failed updating currently dispatched items, but deleted item successfully: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc toStorageClient(ctx context.Context, storageID component.ID, host component.Host, ownerID component.ID, signal pipeline.Signal) (storage.Client, error) {\n\text, found := host.GetExtensions()[storageID]\n\tif !found {\n\t\treturn nil, errNoStorageClient\n\t}\n\n\tstorageExt, ok := ext.(storage.Extension)\n\tif !ok {\n\t\treturn nil, errWrongExtensionType\n\t}\n\n\treturn storageExt.GetClient(ctx, component.KindExporter, ownerID, signal.String())\n}\n\nfunc getItemKey(index uint64) string {\n\treturn strconv.FormatUint(index, 10)\n}\n\nfunc bytesToItemIndex(buf []byte) (uint64, error) {\n\tif buf == nil {\n\t\treturn uint64(0), errValueNotSet\n\t}\n\t// The sizeof uint64 in binary is 8.\n\tif len(buf) < 8 {\n\t\treturn 0, errInvalidValue\n\t}\n\treturn binary.LittleEndian.Uint64(buf), nil\n}\n\nfunc bytesToItemIndexArray(buf []byte) ([]uint64, error) {\n\tif len(buf) == 0 {\n\t\treturn nil, nil\n\t}\n\n\t// The sizeof uint32 in binary is 4.\n\tif len(buf) < 4 {\n\t\treturn nil, errInvalidValue\n\t}\n\tsize := int(binary.LittleEndian.Uint32(buf))\n\tif size == 0 {\n\t\treturn nil, nil\n\t}\n\n\tbuf = buf[4:]\n\t// The sizeof uint64 in binary is 8, so we need to have size*8 bytes.\n\tif len(buf) < size*8 {\n\t\treturn nil, errInvalidValue\n\t}\n\n\tval := make([]uint64, size)\n\tfor i := range size {\n\t\tval[i] = binary.LittleEndian.Uint64(buf)\n\t\tbuf = buf[8:]\n\t}\n\treturn val, nil\n}\n\ntype indexDone struct {\n\tindex     uint64\n\titemsSize int64\n\tbytesSize int64\n\tqueue     interface {\n\t\tonDone(uint64, int64, int64, error)\n\t}\n}\n\nfunc (id *indexDone) reset(index uint64, itemsSize, bytesSize int64, queue interface {\n\tonDone(uint64, int64, int64, error)\n},\n) {\n\tid.index = index\n\tid.itemsSize = itemsSize\n\tid.bytesSize = bytesSize\n\tid.queue = queue\n}\n\nfunc (id *indexDone) OnDone(err error) {\n\tid.queue.onDone(id.index, id.itemsSize, id.bytesSize, err)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queue/persistent_queue_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queue\n\nimport (\n\t\"context\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"syscall\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/experr\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/hosttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/storagetest\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/extension/extensiontest\"\n\t\"go.opentelemetry.io/collector/extension/xextension/storage\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\ntype intRequest int64\n\nfunc (i intRequest) MergeSplit(context.Context, int, request.SizerType, request.Request) ([]request.Request, error) {\n\tpanic(\"implement me\")\n}\n\nfunc (i intRequest) ItemsCount() int {\n\treturn int(i)\n}\n\nfunc (i intRequest) BytesSize() int {\n\treturn int(i) * 10\n}\n\ntype int64Encoding struct {\n\trc ReferenceCounter[intRequest]\n}\n\nfunc (int64Encoding) Marshal(_ context.Context, val intRequest) ([]byte, error) {\n\tstr := strconv.FormatInt(int64(val), 10)\n\treturn []byte(str), nil\n}\n\nfunc (ie int64Encoding) Unmarshal(bytes []byte) (context.Context, intRequest, error) {\n\tval, err := strconv.ParseInt(string(bytes), 10, 64)\n\tif err != nil {\n\t\treturn context.Background(), 0, err\n\t}\n\tie.rc.Ref(intRequest(val))\n\treturn context.Background(), intRequest(val), nil\n}\n\nfunc newFakeBoundedStorageClient(maxSizeInBytes int) *fakeBoundedStorageClient {\n\treturn &fakeBoundedStorageClient{\n\t\tst:             map[string][]byte{},\n\t\tmaxSizeInBytes: maxSizeInBytes,\n\t}\n}\n\n// fakeBoundedStorageClient storage client mimics the behavior of actual storage engines with limited\n// storage space available in general, real storage engines often have a per-write-transaction\n// storage overhead, needing to keep both the old and the new value stored until the transaction\n// is committed this is useful for testing the persistent queue behavior with a full disk.\ntype fakeBoundedStorageClient struct {\n\tmaxSizeInBytes int\n\tst             map[string][]byte\n\tsizeInBytes    int\n\tmux            sync.Mutex\n}\n\nfunc (m *fakeBoundedStorageClient) Get(ctx context.Context, key string) ([]byte, error) {\n\top := storage.GetOperation(key)\n\tif err := m.Batch(ctx, op); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn op.Value, nil\n}\n\nfunc (m *fakeBoundedStorageClient) Set(ctx context.Context, key string, value []byte) error {\n\treturn m.Batch(ctx, storage.SetOperation(key, value))\n}\n\nfunc (m *fakeBoundedStorageClient) Delete(ctx context.Context, key string) error {\n\treturn m.Batch(ctx, storage.DeleteOperation(key))\n}\n\nfunc (m *fakeBoundedStorageClient) Close(context.Context) error {\n\treturn nil\n}\n\nfunc (m *fakeBoundedStorageClient) Batch(_ context.Context, ops ...*storage.Operation) error {\n\tm.mux.Lock()\n\tdefer m.mux.Unlock()\n\n\ttotalAdded, totalRemoved := m.getTotalSizeChange(ops)\n\n\t// the assumption here is that the new data needs to coexist with the old data on disk\n\t// for the transaction to succeed\n\t// this seems to be true for the file storage extension at least\n\tif m.sizeInBytes+totalAdded-totalRemoved > m.maxSizeInBytes {\n\t\treturn fmt.Errorf(\"insufficient space available: %w\", syscall.ENOSPC)\n\t}\n\n\tfor _, op := range ops {\n\t\tswitch op.Type {\n\t\tcase storage.Get:\n\t\t\top.Value = m.st[op.Key]\n\t\tcase storage.Set:\n\t\t\tm.st[op.Key] = op.Value\n\t\tcase storage.Delete:\n\t\t\tdelete(m.st, op.Key)\n\t\tdefault:\n\t\t\treturn errors.New(\"wrong operation type\")\n\t\t}\n\t}\n\n\tm.sizeInBytes += totalAdded - totalRemoved\n\n\treturn nil\n}\n\nfunc (m *fakeBoundedStorageClient) SetMaxSizeInBytes(newMaxSize int) {\n\tm.mux.Lock()\n\tdefer m.mux.Unlock()\n\tm.maxSizeInBytes = newMaxSize\n}\n\nfunc (m *fakeBoundedStorageClient) GetSizeInBytes() int {\n\tm.mux.Lock()\n\tdefer m.mux.Unlock()\n\treturn m.sizeInBytes\n}\n\nfunc (m *fakeBoundedStorageClient) getTotalSizeChange(ops []*storage.Operation) (totalAdded, totalRemoved int) {\n\ttotalAdded, totalRemoved = 0, 0\n\tfor _, op := range ops {\n\t\tswitch op.Type {\n\t\tcase storage.Set:\n\t\t\tif oldValue, ok := m.st[op.Key]; ok {\n\t\t\t\ttotalRemoved += len(oldValue)\n\t\t\t} else {\n\t\t\t\ttotalAdded += len(op.Key)\n\t\t\t}\n\t\t\ttotalAdded += len(op.Value)\n\t\tcase storage.Delete:\n\t\t\tif value, ok := m.st[op.Key]; ok {\n\t\t\t\ttotalRemoved += len(op.Key)\n\t\t\t\ttotalRemoved += len(value)\n\t\t\t}\n\t\tdefault:\n\t\t}\n\t}\n\treturn totalAdded, totalRemoved\n}\n\nfunc newFakeStorageClientWithErrors(errors []error) *fakeStorageClientWithErrors {\n\treturn &fakeStorageClientWithErrors{\n\t\terrors: errors,\n\t}\n}\n\n// this storage client just returns errors from a list in order\n// used for testing error handling\ntype fakeStorageClientWithErrors struct {\n\terrors         []error\n\tnextErrorIndex int\n\tmux            sync.Mutex\n}\n\nfunc (m *fakeStorageClientWithErrors) Get(ctx context.Context, key string) ([]byte, error) {\n\top := storage.GetOperation(key)\n\terr := m.Batch(ctx, op)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn op.Value, nil\n}\n\nfunc (m *fakeStorageClientWithErrors) Set(ctx context.Context, key string, value []byte) error {\n\treturn m.Batch(ctx, storage.SetOperation(key, value))\n}\n\nfunc (m *fakeStorageClientWithErrors) Delete(ctx context.Context, key string) error {\n\treturn m.Batch(ctx, storage.DeleteOperation(key))\n}\n\nfunc (m *fakeStorageClientWithErrors) Close(context.Context) error {\n\treturn nil\n}\n\nfunc (m *fakeStorageClientWithErrors) Batch(context.Context, ...*storage.Operation) error {\n\tm.mux.Lock()\n\tdefer m.mux.Unlock()\n\n\tif m.nextErrorIndex >= len(m.errors) {\n\t\treturn nil\n\t}\n\n\tm.nextErrorIndex++\n\treturn m.errors[m.nextErrorIndex-1]\n}\n\nfunc (m *fakeStorageClientWithErrors) Reset() {\n\tm.mux.Lock()\n\tdefer m.mux.Unlock()\n\tm.nextErrorIndex = 0\n}\n\ntype fakeReferenceCounter struct {\n\tmu  sync.Mutex\n\tref int64\n}\n\nfunc (f *fakeReferenceCounter) Ref(intRequest) {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\tf.ref++\n}\n\nfunc (f *fakeReferenceCounter) Unref(intRequest) {\n\tf.mu.Lock()\n\tdefer f.mu.Unlock()\n\tf.ref--\n\tif f.ref < 0 {\n\t\tpanic(\"this should never happen\")\n\t}\n}\n\nfunc newSettings(sizerType request.SizerType, capacity int64) Settings[intRequest] {\n\trc := &fakeReferenceCounter{}\n\treturn Settings[intRequest]{\n\t\tReferenceCounter: rc,\n\t\tSizerType:        sizerType,\n\t\tCapacity:         capacity,\n\t\tSignal:           pipeline.SignalTraces,\n\t\tEncoding:         int64Encoding{rc},\n\t\tID:               component.NewID(exportertest.NopType),\n\t\tTelemetry:        componenttest.NewNopTelemetrySettings(),\n\t}\n}\n\nfunc newSettingsWithStorage(sizerType request.SizerType, capacity int64) Settings[intRequest] {\n\tset := newSettings(sizerType, capacity)\n\tstorageID := component.ID{}\n\tset.StorageID = &storageID\n\treturn set\n}\n\nfunc createTestPersistentQueueWithClient(client storage.Client) *persistentQueue[intRequest] {\n\tpq := newPersistentQueue[intRequest](newSettingsWithStorage(request.SizerTypeRequests, 1000)).(*persistentQueue[intRequest])\n\tpq.initClient(context.Background(), client)\n\treturn pq\n}\n\nfunc createTestPersistentQueueWithRequestsSizer(tb testing.TB, ext storage.Extension, capacity int64) *persistentQueue[intRequest] {\n\treturn createTestPersistentQueue(tb, ext, request.SizerTypeRequests, capacity)\n}\n\nfunc createTestPersistentQueueWithItemsSizer(tb testing.TB, ext storage.Extension, capacity int64) *persistentQueue[intRequest] {\n\treturn createTestPersistentQueue(tb, ext, request.SizerTypeItems, capacity)\n}\n\nfunc createTestPersistentQueue(tb testing.TB, ext storage.Extension, sizerType request.SizerType, capacity int64) *persistentQueue[intRequest] {\n\tpq := newPersistentQueue[intRequest](newSettingsWithStorage(sizerType, capacity))\n\trequire.NoError(tb, pq.Start(context.Background(), hosttest.NewHost(map[component.ID]component.Component{{}: ext})))\n\treturn pq.(*persistentQueue[intRequest])\n}\n\nfunc TestPersistentQueue_FullCapacity(t *testing.T) {\n\ttests := []struct {\n\t\tname           string\n\t\tsizerType      request.SizerType\n\t\tcapacity       int64\n\t\tsizeMultiplier int64\n\t}{\n\t\t{\n\t\t\tname:           \"requests_capacity\",\n\t\t\tsizerType:      request.SizerTypeRequests,\n\t\t\tcapacity:       5,\n\t\t\tsizeMultiplier: 1,\n\t\t},\n\t\t{\n\t\t\tname:           \"items_capacity\",\n\t\t\tsizerType:      request.SizerTypeItems,\n\t\t\tcapacity:       55,\n\t\t\tsizeMultiplier: 10,\n\t\t},\n\t\t{\n\t\t\tname:           \"bytes_capacity\",\n\t\t\tsizerType:      request.SizerTypeBytes,\n\t\t\tcapacity:       550,\n\t\t\tsizeMultiplier: 100,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\text := storagetest.NewMockStorageExtension(nil)\n\t\t\tpq := createTestPersistentQueue(t, ext, tt.sizerType, tt.capacity)\n\t\t\tassert.Equal(t, int64(0), pq.Size())\n\n\t\t\t// The consumer picks first request. Wait until the consumer is blocked on done.\n\t\t\trequire.NoError(t, pq.Offer(context.Background(), intRequest(10)))\n\t\t\tassert.Equal(t, 1*tt.sizeMultiplier, pq.Size())\n\t\t\t_, _, done, ok := pq.Read(context.Background())\n\t\t\tassert.True(t, ok)\n\t\t\tdone.OnDone(nil)\n\t\t\tassert.Equal(t, int64(0), pq.Size())\n\n\t\t\tfor i := range 10 {\n\t\t\t\tresult := pq.Offer(context.Background(), intRequest(10))\n\t\t\t\tif i < 5 {\n\t\t\t\t\trequire.NoError(t, result)\n\t\t\t\t} else {\n\t\t\t\t\trequire.ErrorIs(t, result, ErrQueueIsFull)\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert.Equal(t, 5*tt.sizeMultiplier, pq.Size())\n\t\t\trequire.NoError(t, pq.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nfunc TestPersistentQueue_Shutdown(t *testing.T) {\n\text := storagetest.NewMockStorageExtension(nil)\n\tpq := createTestPersistentQueue(t, ext, request.SizerTypeRequests, 1001)\n\treq := intRequest(10)\n\n\tfor range 1000 {\n\t\trequire.NoError(t, pq.Offer(context.Background(), req))\n\t}\n\trequire.NoError(t, pq.Shutdown(context.Background()))\n}\n\nfunc TestPersistentQueue_ConsumersProducers(t *testing.T) {\n\tcases := []struct {\n\t\tnumMessagesProduced int\n\t\tnumConsumers        int\n\t}{\n\t\t{\n\t\t\tnumMessagesProduced: 1,\n\t\t\tnumConsumers:        1,\n\t\t},\n\t\t{\n\t\t\tnumMessagesProduced: 100,\n\t\t\tnumConsumers:        1,\n\t\t},\n\t\t{\n\t\t\tnumMessagesProduced: 100,\n\t\t\tnumConsumers:        3,\n\t\t},\n\t\t{\n\t\t\tnumMessagesProduced: 1,\n\t\t\tnumConsumers:        100,\n\t\t},\n\t\t{\n\t\t\tnumMessagesProduced: 100,\n\t\t\tnumConsumers:        100,\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tt.Run(fmt.Sprintf(\"#messages: %d #consumers: %d\", c.numMessagesProduced, c.numConsumers), func(t *testing.T) {\n\t\t\tconsumed := &atomic.Int64{}\n\n\t\t\tpq := newPersistentQueue[intRequest](newSettingsWithStorage(request.SizerTypeRequests, 1000))\n\t\t\taq := newAsyncQueue[intRequest](pq, c.numConsumers, func(_ context.Context, _ intRequest, done Done) {\n\t\t\t\tconsumed.Add(int64(1))\n\t\t\t\tdone.OnDone(nil)\n\t\t\t}, nil)\n\t\t\trequire.NoError(t, aq.Start(context.Background(), hosttest.NewHost(map[component.ID]component.Component{\n\t\t\t\t{}: storagetest.NewMockStorageExtension(nil),\n\t\t\t},\n\t\t\t)))\n\n\t\t\tfor i := 0; i < c.numMessagesProduced; i++ {\n\t\t\t\trequire.NoError(t, aq.Offer(context.Background(), intRequest(10)))\n\t\t\t}\n\n\t\t\t// Because the persistent queue is not draining after Shutdown, need to wait here for the drain.\n\t\t\tassert.Eventually(t, func() bool {\n\t\t\t\treturn c.numMessagesProduced == int(consumed.Load())\n\t\t\t}, 5*time.Second, 10*time.Millisecond)\n\n\t\t\trequire.NoError(t, aq.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nfunc TestPersistentBlockingQueue(t *testing.T) {\n\ttests := []struct {\n\t\tname      string\n\t\tsizerType request.SizerType\n\t}{\n\t\t{\n\t\t\tname:      \"requests_based\",\n\t\t\tsizerType: request.SizerTypeRequests,\n\t\t},\n\t\t{\n\t\t\tname:      \"items_based\",\n\t\t\tsizerType: request.SizerTypeItems,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tset := newSettingsWithStorage(tt.sizerType, 1000)\n\t\t\tset.BlockOnOverflow = true\n\t\t\tpq := newPersistentQueue[intRequest](set)\n\t\t\tconsumed := &atomic.Int64{}\n\t\t\tac := newAsyncQueue(pq, 10, func(_ context.Context, _ intRequest, done Done) {\n\t\t\t\tconsumed.Add(1)\n\t\t\t\tdone.OnDone(nil)\n\t\t\t}, set.ReferenceCounter)\n\t\t\trequire.NoError(t, ac.Start(context.Background(), hosttest.NewHost(map[component.ID]component.Component{\n\t\t\t\t{}: storagetest.NewMockStorageExtension(nil),\n\t\t\t})))\n\n\t\t\ttd := intRequest(10)\n\t\t\twg := &sync.WaitGroup{}\n\t\t\tfor range 10 {\n\t\t\t\twg.Go(func() {\n\t\t\t\t\tfor range 100_000 {\n\t\t\t\t\t\tassert.NoError(t, pq.Offer(context.Background(), td))\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t}\n\t\t\twg.Wait()\n\t\t\t// Because the persistent queue is not draining after Shutdown, need to wait here for the drain.\n\t\t\tassert.Eventually(t, func() bool {\n\t\t\t\treturn int(consumed.Load()) == 1_000_000\n\t\t\t}, 5*time.Second, 10*time.Millisecond)\n\t\t\trequire.NoError(t, ac.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nfunc TestToStorageClient(t *testing.T) {\n\tgetStorageClientError := errors.New(\"unable to create storage client\")\n\ttestCases := []struct {\n\t\tname           string\n\t\tstorage        storage.Extension\n\t\tnumStorages    int\n\t\tstorageIndex   int\n\t\texpectedError  error\n\t\tgetClientError error\n\t}{\n\t\t{\n\t\t\tname:          \"obtain storage extension by name\",\n\t\t\tnumStorages:   2,\n\t\t\tstorageIndex:  0,\n\t\t\texpectedError: nil,\n\t\t},\n\t\t{\n\t\t\tname:          \"fail on not existing storage extension\",\n\t\t\tnumStorages:   2,\n\t\t\tstorageIndex:  100,\n\t\t\texpectedError: errNoStorageClient,\n\t\t},\n\t\t{\n\t\t\tname:          \"invalid extension type\",\n\t\t\tnumStorages:   2,\n\t\t\tstorageIndex:  100,\n\t\t\texpectedError: errNoStorageClient,\n\t\t},\n\t\t{\n\t\t\tname:           \"fail on error getting storage client from extension\",\n\t\t\tnumStorages:    1,\n\t\t\tstorageIndex:   0,\n\t\t\texpectedError:  getStorageClientError,\n\t\t\tgetClientError: getStorageClientError,\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tstorageID := component.MustNewIDWithName(\"file_storage\", strconv.Itoa(tt.storageIndex))\n\n\t\t\textensions := map[component.ID]component.Component{}\n\t\t\tfor i := 0; i < tt.numStorages; i++ {\n\t\t\t\textensions[component.MustNewIDWithName(\"file_storage\", strconv.Itoa(i))] = storagetest.NewMockStorageExtension(tt.getClientError)\n\t\t\t}\n\t\t\thost := hosttest.NewHost(extensions)\n\t\t\townerID := component.MustNewID(\"foo_exporter\")\n\n\t\t\t// execute\n\t\t\tclient, err := toStorageClient(context.Background(), storageID, host, ownerID, pipeline.SignalTraces)\n\n\t\t\t// verify\n\t\t\tif tt.expectedError != nil {\n\t\t\t\trequire.ErrorIs(t, err, tt.expectedError)\n\t\t\t\tassert.Nil(t, client)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.NotNil(t, client)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestInvalidStorageExtensionType(t *testing.T) {\n\tstorageID := component.MustNewIDWithName(\"extension\", \"extension\")\n\n\t// make a test extension\n\tfactory := extensiontest.NewNopFactory()\n\textConfig := factory.CreateDefaultConfig()\n\tsettings := extensiontest.NewNopSettings(factory.Type())\n\textension, err := factory.Create(context.Background(), settings, extConfig)\n\trequire.NoError(t, err)\n\textensions := map[component.ID]component.Component{\n\t\tstorageID: extension,\n\t}\n\thost := hosttest.NewHost(extensions)\n\townerID := component.MustNewID(\"foo_exporter\")\n\n\t// execute\n\tclient, err := toStorageClient(context.Background(), storageID, host, ownerID, pipeline.SignalTraces)\n\n\t// we should get an error about the extension type\n\trequire.ErrorIs(t, err, errWrongExtensionType)\n\tassert.Nil(t, client)\n}\n\nfunc TestPersistentQueue_StopAfterBadStart(t *testing.T) {\n\tstorageID := component.ID{}\n\tpq := newPersistentQueue[intRequest](Settings[intRequest]{StorageID: &storageID})\n\t// verify that stopping a un-start/started w/error queue does not panic\n\tassert.NoError(t, pq.Shutdown(context.Background()))\n}\n\nfunc TestPersistentQueue_CorruptedData(t *testing.T) {\n\tcases := []struct {\n\t\tname               string\n\t\tcorruptAllData     bool\n\t\tcorruptSomeData    bool\n\t\tcorruptMetadataKey bool\n\t\tdesiredQueueSize   int64\n\t}{\n\t\t{\n\t\t\tname:             \"corrupted no items\",\n\t\t\tdesiredQueueSize: 3,\n\t\t},\n\t\t{\n\t\t\tname:             \"corrupted all items\",\n\t\t\tcorruptAllData:   true,\n\t\t\tdesiredQueueSize: 2, // - the dispatched item which was corrupted.\n\t\t},\n\t\t{\n\t\t\tname:             \"corrupted some items\",\n\t\t\tcorruptSomeData:  true,\n\t\t\tdesiredQueueSize: 2, // - the dispatched item which was corrupted.\n\t\t},\n\t\t{\n\t\t\tname:               \"corrupted metadata\",\n\t\t\tcorruptMetadataKey: true,\n\t\t\tdesiredQueueSize:   0,\n\t\t},\n\t\t{\n\t\t\tname:               \"corrupted everything\",\n\t\t\tcorruptAllData:     true,\n\t\t\tcorruptMetadataKey: true,\n\t\t\tdesiredQueueSize:   0,\n\t\t},\n\t}\n\n\tbadBytes := []byte{0, 1, 2}\n\n\tfor _, c := range cases {\n\t\tt.Run(c.name, func(t *testing.T) {\n\t\t\text := storagetest.NewMockStorageExtension(nil)\n\t\t\tps := createTestPersistentQueueWithRequestsSizer(t, ext, 1000)\n\n\t\t\t// Put some items, make sure they are loaded and shutdown the storage...\n\t\t\tfor range 3 {\n\t\t\t\trequire.NoError(t, ps.Offer(context.Background(), intRequest(50)))\n\t\t\t}\n\t\t\tassert.Equal(t, int64(3), ps.Size())\n\t\t\trequire.True(t, consume(ps, func(context.Context, intRequest) error {\n\t\t\t\treturn experr.NewShutdownErr(nil)\n\t\t\t}))\n\t\t\tassert.Equal(t, int64(3), ps.Size())\n\n\t\t\t// We can corrupt data (in several ways) and not worry since we return ShutdownErr client will not be touched.\n\t\t\tif c.corruptAllData || c.corruptSomeData {\n\t\t\t\trequire.NoError(t, ps.client.Set(context.Background(), \"0\", badBytes))\n\t\t\t}\n\t\t\tif c.corruptAllData {\n\t\t\t\trequire.NoError(t, ps.client.Set(context.Background(), \"1\", badBytes))\n\t\t\t\trequire.NoError(t, ps.client.Set(context.Background(), \"2\", badBytes))\n\t\t\t}\n\n\t\t\tif c.corruptMetadataKey {\n\t\t\t\trequire.NoError(t, ps.client.Set(context.Background(), metadataKey, badBytes))\n\t\t\t}\n\n\t\t\t// Cannot close until we corrupt the data because the\n\t\t\trequire.NoError(t, ps.Shutdown(context.Background()))\n\n\t\t\t// Reload\n\t\t\tnewPs := createTestPersistentQueueWithRequestsSizer(t, ext, 1000)\n\t\t\tassert.Equal(t, c.desiredQueueSize, newPs.Size())\n\t\t\trequire.NoError(t, newPs.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nfunc TestPersistentQueue_CurrentlyProcessedItems(t *testing.T) {\n\treq := intRequest(50)\n\n\text := storagetest.NewMockStorageExtension(nil)\n\tps := createTestPersistentQueueWithRequestsSizer(t, ext, 1000)\n\n\tfor range 5 {\n\t\trequire.NoError(t, ps.Offer(context.Background(), req))\n\t}\n\n\trequireCurrentlyDispatchedItemsEqual(t, ps, []uint64{})\n\n\t// Takes index 0 in process.\n\t_, readReq, _, found := ps.Read(context.Background())\n\trequire.True(t, found)\n\tassert.Equal(t, req, readReq)\n\trequireCurrentlyDispatchedItemsEqual(t, ps, []uint64{0})\n\n\t// This takes item 1 to process.\n\t_, secondReadReq, secondDone, found := ps.Read(context.Background())\n\trequire.True(t, found)\n\tassert.Equal(t, req, secondReadReq)\n\trequireCurrentlyDispatchedItemsEqual(t, ps, []uint64{0, 1})\n\n\t// Lets mark item 1 as finished, it will remove it from the currently dispatched items list.\n\tsecondDone.OnDone(nil)\n\trequireCurrentlyDispatchedItemsEqual(t, ps, []uint64{0})\n\n\t// Reload the storage. Since items 0 was not finished, this should be re-enqueued at the end.\n\t// The queue should be essentially {3,4,0,2}.\n\tnewPs := createTestPersistentQueueWithRequestsSizer(t, ext, 1000)\n\tassert.Equal(t, int64(4), newPs.Size())\n\trequireCurrentlyDispatchedItemsEqual(t, newPs, []uint64{})\n\n\t// We should be able to pull all remaining items now\n\tfor range 4 {\n\t\tconsume(newPs, func(_ context.Context, val intRequest) error {\n\t\t\tassert.Equal(t, req, val)\n\t\t\treturn nil\n\t\t})\n\t}\n\n\t// The queue should be now empty\n\trequireCurrentlyDispatchedItemsEqual(t, newPs, []uint64{})\n\tassert.Equal(t, int64(0), newPs.Size())\n\t// The writeIndex should be now set accordingly\n\trequire.EqualValues(t, 6, newPs.metadata.WriteIndex)\n\n\t// There should be no items left in the storage\n\tfor i := uint64(0); i < newPs.metadata.WriteIndex; i++ {\n\t\tbb, err := newPs.client.Get(context.Background(), getItemKey(i))\n\t\trequire.NoError(t, err)\n\t\trequire.Nil(t, bb)\n\t}\n}\n\n// this test attempts to check if all the invariants are kept if the queue is recreated while\n// close to full and with some items dispatched\nfunc TestPersistentQueueStartWithNonDispatched(t *testing.T) {\n\treq := intRequest(50)\n\n\text := storagetest.NewMockStorageExtension(nil)\n\tps := createTestPersistentQueueWithRequestsSizer(t, ext, 5)\n\n\t// Put in items up to capacity\n\tfor range 5 {\n\t\trequire.NoError(t, ps.Offer(context.Background(), req))\n\t}\n\trequire.Equal(t, int64(5), ps.Size())\n\n\trequire.True(t, consume(ps, func(context.Context, intRequest) error {\n\t\t// Check that size is still full even when consuming the element.\n\t\trequire.Equal(t, int64(5), ps.Size())\n\t\treturn experr.NewShutdownErr(nil)\n\t}))\n\trequire.NoError(t, ps.Shutdown(context.Background()))\n\n\t// Reload with extra capacity to make sure we re-enqueue in-progress items.\n\tnewPs := createTestPersistentQueueWithRequestsSizer(t, ext, 5)\n\trequire.Equal(t, int64(5), newPs.Size())\n}\n\nfunc TestPersistentQueueStartWithNonDispatchedConcurrent(t *testing.T) {\n\treq := intRequest(1)\n\n\text := storagetest.NewMockStorageExtensionWithDelay(nil, 20*time.Nanosecond)\n\tpq := createTestPersistentQueueWithItemsSizer(t, ext, 25)\n\n\tproWg := sync.WaitGroup{}\n\t// Sending small amount of data as windows test can't handle the test fast enough\n\tfor range 5 {\n\t\tproWg.Go(func() {\n\t\t\t// Put in items up to capacity\n\t\t\tfor range 10 {\n\t\t\t\tfor {\n\t\t\t\t\t// retry infinitely so the exact amount of items are added to the queue eventually\n\t\t\t\t\tif err := pq.Offer(context.Background(), req); err == nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t\ttime.Sleep(50 * time.Nanosecond)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n\n\tconWg := sync.WaitGroup{}\n\tfor range 5 {\n\t\tconWg.Go(func() {\n\t\t\tfor range 10 {\n\t\t\t\tassert.True(t, consume(pq, func(context.Context, intRequest) error { return nil }))\n\t\t\t}\n\t\t})\n\t}\n\n\tconDone := make(chan struct{})\n\tgo func() {\n\t\tdefer close(conDone)\n\t\tconWg.Wait()\n\t}()\n\n\tproDone := make(chan struct{})\n\tgo func() {\n\t\tdefer close(proDone)\n\t\tproWg.Wait()\n\t}()\n\n\tdoneCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancel()\n\tselect {\n\tcase <-conDone:\n\tcase <-doneCtx.Done():\n\t\tassert.Fail(t, \"timed out waiting for consumers to complete\")\n\t}\n\n\tselect {\n\tcase <-proDone:\n\tcase <-doneCtx.Done():\n\t\tassert.Fail(t, \"timed out waiting for producers to complete\")\n\t}\n\tassert.Zero(t, pq.Size())\n}\n\nfunc TestPersistentQueue_PutCloseReadClose(t *testing.T) {\n\treq := intRequest(50)\n\text := storagetest.NewMockStorageExtension(nil)\n\tps := createTestPersistentQueueWithRequestsSizer(t, ext, 1000)\n\tassert.Equal(t, int64(0), ps.Size())\n\n\t// Put two elements and close the extension\n\trequire.NoError(t, ps.Offer(context.Background(), req))\n\trequire.NoError(t, ps.Offer(context.Background(), req))\n\tassert.Equal(t, int64(2), ps.Size())\n\t// TODO: Remove this, after the initialization writes the readIndex.\n\t_, _, _, _ = ps.Read(context.Background())\n\trequire.NoError(t, ps.Shutdown(context.Background()))\n\n\tnewPs := createTestPersistentQueueWithRequestsSizer(t, ext, 1000)\n\trequire.Equal(t, int64(2), newPs.Size())\n\n\t// Let's read both of the elements we put\n\tconsume(newPs, func(_ context.Context, val intRequest) error {\n\t\trequire.Equal(t, req, val)\n\t\treturn nil\n\t})\n\tassert.Equal(t, int64(1), newPs.Size())\n\n\tconsume(newPs, func(_ context.Context, val intRequest) error {\n\t\trequire.Equal(t, req, val)\n\t\treturn nil\n\t})\n\trequire.Equal(t, int64(0), newPs.Size())\n\trequire.NoError(t, newPs.Shutdown(context.Background()))\n}\n\nfunc BenchmarkPersistentQueue(b *testing.B) {\n\text := storagetest.NewMockStorageExtension(nil)\n\tps := createTestPersistentQueueWithRequestsSizer(b, ext, 10000000)\n\n\treq := intRequest(100)\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tfor range 100 {\n\t\t\trequire.NoError(b, ps.Offer(context.Background(), req))\n\t\t}\n\t\tfor range 100 {\n\t\t\trequire.True(b, consume(ps, func(context.Context, intRequest) error { return nil }))\n\t\t}\n\t}\n\trequire.NoError(b, ext.Shutdown(context.Background()))\n}\n\nfunc TestItemIndexMarshaling(t *testing.T) {\n\tcases := []struct {\n\t\tin  uint64\n\t\tout uint64\n\t}{\n\t\t{\n\t\t\tin:  0,\n\t\t\tout: 0,\n\t\t},\n\t\t{\n\t\t\tin:  1,\n\t\t\tout: 1,\n\t\t},\n\t\t{\n\t\t\tin:  0xFFFFFFFFFFFFFFFF,\n\t\t\tout: 0xFFFFFFFFFFFFFFFF,\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tt.Run(fmt.Sprintf(\"#elements:%v\", c.in), func(*testing.T) {\n\t\t\tbuf := binary.LittleEndian.AppendUint64([]byte{}, c.in)\n\t\t\tout, err := bytesToItemIndex(buf)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, c.out, out)\n\t\t})\n\t}\n}\n\nfunc TestItemIndexArrayMarshaling(t *testing.T) {\n\tcases := []struct {\n\t\tin  []uint64\n\t\tout []uint64\n\t}{\n\t\t{\n\t\t\tin:  []uint64{0, 1, 2},\n\t\t\tout: []uint64{0, 1, 2},\n\t\t},\n\t\t{\n\t\t\tin:  []uint64{},\n\t\t\tout: nil,\n\t\t},\n\t\t{\n\t\t\tin:  nil,\n\t\t\tout: nil,\n\t\t},\n\t}\n\n\tfor _, c := range cases {\n\t\tt.Run(fmt.Sprintf(\"#elements:%v\", c.in), func(_ *testing.T) {\n\t\t\tbuf := itemIndexArrayToBytes(c.in)\n\t\t\tout, err := bytesToItemIndexArray(buf)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, c.out, out)\n\t\t})\n\t}\n}\n\nfunc TestPersistentQueue_ShutdownWhileConsuming(t *testing.T) {\n\tps := createTestPersistentQueueWithRequestsSizer(t, storagetest.NewMockStorageExtension(nil), 1000)\n\n\tassert.Equal(t, int64(0), ps.Size())\n\tassert.False(t, ps.client.(*storagetest.MockStorageClient).IsClosed())\n\n\trequire.NoError(t, ps.Offer(context.Background(), intRequest(50)))\n\n\t_, _, done, ok := ps.Read(context.Background())\n\trequire.True(t, ok)\n\tassert.False(t, ps.client.(*storagetest.MockStorageClient).IsClosed())\n\trequire.NoError(t, ps.Shutdown(context.Background()))\n\tassert.False(t, ps.client.(*storagetest.MockStorageClient).IsClosed())\n\tdone.OnDone(nil)\n\tassert.True(t, ps.client.(*storagetest.MockStorageClient).IsClosed())\n}\n\nfunc TestPersistentQueue_StorageFull(t *testing.T) {\n\tmarshaled, err := int64Encoding{}.Marshal(context.Background(), intRequest(50))\n\trequire.NoError(t, err)\n\tmaxSizeInBytes := len(marshaled)*5 + 60 // arbitrary small number\n\n\tclient := newFakeBoundedStorageClient(maxSizeInBytes)\n\tps := createTestPersistentQueueWithClient(client)\n\n\t// Put enough items in to fill the underlying storage\n\treqCount := 0\n\tfor {\n\t\treqCount++\n\t\terr = ps.Offer(context.Background(), intRequest(50))\n\t\tif errors.Is(err, syscall.ENOSPC) {\n\t\t\tbreak\n\t\t}\n\t\trequire.NoError(t, err)\n\t}\n\n\t// Check that the size is correct\n\trequire.EqualValues(t, reqCount, ps.Size(), \"Size must be equal to the number of items inserted\")\n\n\t// Manually set the storage to support writing the dispatch value.\n\tclient.SetMaxSizeInBytes(client.GetSizeInBytes() + 19)\n\n\t// Take out all the items except last. Last one is there only in metadata because the data write failed.\n\tfor i := 0; i < reqCount-1; i++ {\n\t\trequire.True(t, consume(ps, func(_ context.Context, val intRequest) error {\n\t\t\trequire.Equal(t, intRequest(50), val)\n\t\t\treturn nil\n\t\t}))\n\t}\n\trequire.Equal(t, int64(1), ps.Size())\n\t// Add one more element, and then read (drain) so metadata will be fixed.\n\trequire.NoError(t, ps.Offer(context.Background(), intRequest(50)))\n\trequire.True(t, consume(ps, func(_ context.Context, val intRequest) error {\n\t\trequire.Equal(t, intRequest(50), val)\n\t\treturn nil\n\t}))\n\trequire.Equal(t, int64(0), ps.Size())\n}\n\nfunc TestPersistentQueue_ItemDispatchingFinish_ErrorHandling(t *testing.T) {\n\terrDeletingItem := errors.New(\"error deleting item\")\n\terrUpdatingDispatched := errors.New(\"error updating dispatched items\")\n\ttestCases := []struct {\n\t\tstorageErrors []error\n\t\texpectedError error\n\t\tname          string\n\t}{\n\t\t{\n\t\t\tname:          \"no errors\",\n\t\t\tstorageErrors: []error{},\n\t\t\texpectedError: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"error on first transaction, success afterwards\",\n\t\t\tstorageErrors: []error{\n\t\t\t\terrUpdatingDispatched,\n\t\t\t},\n\t\t\texpectedError: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"error on first and second transaction\",\n\t\t\tstorageErrors: []error{\n\t\t\t\terrUpdatingDispatched,\n\t\t\t\terrDeletingItem,\n\t\t\t},\n\t\t\texpectedError: errDeletingItem,\n\t\t},\n\t\t{\n\t\t\tname: \"error on first and third transaction\",\n\t\t\tstorageErrors: []error{\n\t\t\t\terrUpdatingDispatched,\n\t\t\t\tnil,\n\t\t\t\terrUpdatingDispatched,\n\t\t\t},\n\t\t\texpectedError: errUpdatingDispatched,\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tclient := newFakeStorageClientWithErrors(tt.storageErrors)\n\t\t\tps := createTestPersistentQueueWithClient(client)\n\t\t\tclient.Reset()\n\n\t\t\trequire.ErrorIs(t, ps.itemDispatchingFinish(context.Background(), 0), tt.expectedError)\n\t\t})\n\t}\n}\n\nfunc TestPersistentQueue_ItemsCapacityUsageRestoredOnShutdown(t *testing.T) {\n\text := storagetest.NewMockStorageExtension(nil)\n\tpq := createTestPersistentQueueWithItemsSizer(t, ext, 100)\n\n\tassert.Equal(t, int64(0), pq.Size())\n\n\t// Fill the queue up to the capacity.\n\trequire.NoError(t, pq.Offer(context.Background(), intRequest(40)))\n\trequire.NoError(t, pq.Offer(context.Background(), intRequest(40)))\n\trequire.NoError(t, pq.Offer(context.Background(), intRequest(20)))\n\tassert.Equal(t, int64(100), pq.Size())\n\n\trequire.ErrorIs(t, pq.Offer(context.Background(), intRequest(25)), ErrQueueIsFull)\n\tassert.Equal(t, int64(100), pq.Size())\n\n\tassert.True(t, consume(pq, func(_ context.Context, val intRequest) error {\n\t\tassert.Equal(t, intRequest(40), val)\n\t\treturn nil\n\t}))\n\tassert.Equal(t, int64(60), pq.Size())\n\n\trequire.NoError(t, pq.Shutdown(context.Background()))\n\n\tnewPQ := createTestPersistentQueueWithItemsSizer(t, ext, 100)\n\n\t// The queue should be restored to the previous size.\n\tassert.Equal(t, int64(60), newPQ.Size())\n\n\trequire.NoError(t, newPQ.Offer(context.Background(), intRequest(10)))\n\n\t// Check the combined queue size.\n\tassert.Equal(t, int64(70), newPQ.Size())\n\n\tassert.True(t, consume(newPQ, func(_ context.Context, val intRequest) error {\n\t\tassert.Equal(t, intRequest(40), val)\n\t\treturn nil\n\t}))\n\tassert.Equal(t, int64(30), newPQ.Size())\n\n\tassert.True(t, consume(newPQ, func(_ context.Context, val intRequest) error {\n\t\tassert.Equal(t, intRequest(20), val)\n\t\treturn nil\n\t}))\n\tassert.Equal(t, int64(10), newPQ.Size())\n\n\trequire.NoError(t, newPQ.Shutdown(context.Background()))\n}\n\nfunc TestPersistentQueue_ItemsCapacityIsAlwyasRecorder(t *testing.T) {\n\text := storagetest.NewMockStorageExtension(nil)\n\tpq := createTestPersistentQueueWithRequestsSizer(t, ext, 100)\n\n\tassert.Equal(t, int64(0), pq.Size())\n\n\trequire.NoError(t, pq.Offer(context.Background(), intRequest(40)))\n\trequire.NoError(t, pq.Offer(context.Background(), intRequest(20)))\n\trequire.NoError(t, pq.Offer(context.Background(), intRequest(25)))\n\tassert.Equal(t, int64(3), pq.Size())\n\n\tassert.True(t, consume(pq, func(_ context.Context, val intRequest) error {\n\t\tassert.Equal(t, intRequest(40), val)\n\t\treturn nil\n\t}))\n\tassert.Equal(t, int64(2), pq.Size())\n\n\trequire.NoError(t, pq.Shutdown(context.Background()))\n\n\tnewPQ := createTestPersistentQueueWithItemsSizer(t, ext, 100)\n\n\t// The queue items size cannot be restored.\n\tassert.Equal(t, int64(45), newPQ.Size())\n\n\trequire.NoError(t, newPQ.Offer(context.Background(), intRequest(10)))\n\n\t// Only new items are correctly reflected\n\tassert.Equal(t, int64(55), newPQ.Size())\n\n\t// Consuming a restored request should reduce the restored size by 20 but it should not go to below zero\n\tassert.True(t, consume(newPQ, func(_ context.Context, val intRequest) error {\n\t\tassert.Equal(t, intRequest(20), val)\n\t\treturn nil\n\t}))\n\tassert.Equal(t, int64(35), newPQ.Size())\n\n\t// Consuming another restored request should not affect the restored size since it's already dropped to 0.\n\tassert.True(t, consume(newPQ, func(_ context.Context, val intRequest) error {\n\t\tassert.Equal(t, intRequest(25), val)\n\t\treturn nil\n\t}))\n\tassert.Equal(t, int64(10), newPQ.Size())\n\n\t// Adding another batch should update the size accordingly\n\trequire.NoError(t, newPQ.Offer(context.Background(), intRequest(25)))\n\tassert.Equal(t, int64(35), newPQ.Size())\n\n\tassert.True(t, consume(newPQ, func(_ context.Context, val intRequest) error {\n\t\tassert.Equal(t, intRequest(10), val)\n\t\treturn nil\n\t}))\n\tassert.Equal(t, int64(25), newPQ.Size())\n\n\trequire.NoError(t, newPQ.Shutdown(context.Background()))\n}\n\n// This test covers the case when the queue is restarted with the less capacity than needed to restore the queued items.\n// In that case, the queue has to be restored anyway even if it exceeds the capacity limit.\nfunc TestPersistentQueue_RequestCapacityLessAfterRestart(t *testing.T) {\n\text := storagetest.NewMockStorageExtension(nil)\n\tpq := createTestPersistentQueueWithRequestsSizer(t, ext, 100)\n\n\tassert.Equal(t, int64(0), pq.Size())\n\n\trequire.NoError(t, pq.Offer(context.Background(), intRequest(40)))\n\trequire.NoError(t, pq.Offer(context.Background(), intRequest(20)))\n\trequire.NoError(t, pq.Offer(context.Background(), intRequest(25)))\n\trequire.NoError(t, pq.Offer(context.Background(), intRequest(5)))\n\n\t// Read the first request just to populate the read index in the storage.\n\t// Otherwise, the write index won't be restored either.\n\tassert.True(t, consume(pq, func(_ context.Context, val intRequest) error {\n\t\tassert.Equal(t, intRequest(40), val)\n\t\treturn nil\n\t}))\n\tassert.Equal(t, int64(3), pq.Size())\n\n\trequire.NoError(t, pq.Shutdown(context.Background()))\n\n\t// The queue is restarted with the less capacity than needed to restore the queued items, but with the same\n\t// underlying storage. No need to drop requests that are over capacity since they are already in the storage.\n\tnewPQ := createTestPersistentQueueWithRequestsSizer(t, ext, 2)\n\n\t// The queue items size cannot be restored, fall back to request-based size\n\tassert.Equal(t, int64(3), newPQ.Size())\n\n\t// Queue is full\n\trequire.Error(t, newPQ.Offer(context.Background(), intRequest(10)))\n\n\tassert.True(t, consume(newPQ, func(_ context.Context, val intRequest) error {\n\t\tassert.Equal(t, intRequest(20), val)\n\t\treturn nil\n\t}))\n\tassert.Equal(t, int64(2), newPQ.Size())\n\n\t// Still full\n\trequire.Error(t, newPQ.Offer(context.Background(), intRequest(10)))\n\n\tassert.True(t, consume(newPQ, func(_ context.Context, val intRequest) error {\n\t\tassert.Equal(t, intRequest(25), val)\n\t\treturn nil\n\t}))\n\tassert.Equal(t, int64(1), newPQ.Size())\n\n\t// Now it can accept new items\n\trequire.NoError(t, newPQ.Offer(context.Background(), intRequest(10)))\n\n\trequire.NoError(t, newPQ.Shutdown(context.Background()))\n}\n\n// This test covers the case when the persistent storage is recovered from a snapshot which has\n// bigger value for the used size than the size of the actual items in the storage.\nfunc TestPersistentQueue_RestoredUsedSizeIsCorrectedOnDrain(t *testing.T) {\n\text := storagetest.NewMockStorageExtension(nil)\n\tpq := createTestPersistentQueueWithItemsSizer(t, ext, 1000)\n\n\tassert.Equal(t, int64(0), pq.Size())\n\n\tfor range 6 {\n\t\trequire.NoError(t, pq.Offer(context.Background(), intRequest(10)))\n\t}\n\tassert.Equal(t, int64(60), pq.Size())\n\n\t// Consume 30 items\n\tfor range 3 {\n\t\tassert.True(t, consume(pq, func(context.Context, intRequest) error { return nil }))\n\t}\n\tassert.Equal(t, int64(30), pq.Size())\n\n\t// Corrupt the size, in reality the size is 30.\n\t// Once the queue is drained, it will be updated to the correct size.\n\tpq.metadata.ItemsSize = 50\n\tassert.Equal(t, int64(50), pq.Size())\n\n\tassert.True(t, consume(pq, func(context.Context, intRequest) error { return nil }))\n\tassert.True(t, consume(pq, func(context.Context, intRequest) error { return nil }))\n\tassert.Equal(t, int64(30), pq.Size())\n\n\t// Now the size must be correctly reflected\n\tassert.True(t, consume(pq, func(context.Context, intRequest) error { return nil }))\n\tassert.Equal(t, int64(0), pq.Size())\n\n\trequire.NoError(t, pq.Shutdown(context.Background()))\n}\n\nfunc requireCurrentlyDispatchedItemsEqual(t *testing.T, pq *persistentQueue[intRequest], compare []uint64) {\n\tpq.mu.Lock()\n\tdefer pq.mu.Unlock()\n\tassert.ElementsMatch(t, compare, pq.metadata.CurrentlyDispatchedItems)\n}\n\nfunc itemIndexArrayToBytes(arr []uint64) []byte {\n\tsize := len(arr)\n\tbuf := make([]byte, 0, 4+size*8)\n\tbuf = binary.LittleEndian.AppendUint32(buf, uint32(size))\n\tfor _, item := range arr {\n\t\tbuf = binary.LittleEndian.AppendUint64(buf, item)\n\t}\n\treturn buf\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queue/queue.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queue // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\n// ReferenceCounter is an optional interface that can be implemented to provide a way for the request data\n// to manage internal locally allocated memory and re-use across multiple requests, etc.\n//\n// The queue will only call Ref and Unref when requests are executed asynchronously, otherwise these\n// funcs are not called.\ntype ReferenceCounter[T any] interface {\n\tRef(T)\n\tUnref(T)\n}\n\ntype Encoding[T any] interface {\n\t// Marshal is a function that can marshal a request into bytes.\n\tMarshal(context.Context, T) ([]byte, error)\n\n\t// Unmarshal is a function that can unmarshal bytes into a request.\n\tUnmarshal([]byte) (context.Context, T, error)\n}\n\n// ErrQueueIsFull is the error returned when an item is offered to the Queue and the queue is full and setup to\n// not block.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\nvar ErrQueueIsFull = errors.New(\"sending queue is full\")\n\n// Done represents the callback that will be called when the read request is completely processed by the\n// downstream components.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\ntype Done interface {\n\t// OnDone needs to be called when processing of the queue item is done.\n\tOnDone(error)\n}\n\ntype ConsumeFunc[T any] func(context.Context, T, Done)\n\n// Queue defines a producer-consumer exchange which can be backed by e.g. the memory-based ring buffer queue\n// (boundedMemoryQueue) or via a disk-based queue (persistentQueue)\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\ntype Queue[T any] interface {\n\tcomponent.Component\n\t// Offer inserts the specified element into this queue if it is possible to do so immediately\n\t// without violating capacity restrictions. If success returns no error.\n\t// It returns ErrQueueIsFull if no space is currently available.\n\tOffer(ctx context.Context, item T) error\n\t// Size returns the current Size of the queue\n\tSize() int64\n\t// Capacity returns the capacity of the queue.\n\tCapacity() int64\n}\n\n// Settings define internal parameters for a new Queue creation.\ntype Settings[T request.Request] struct {\n\tSizerType        request.SizerType\n\tCapacity         int64\n\tNumConsumers     int\n\tWaitForResult    bool\n\tBlockOnOverflow  bool\n\tSignal           pipeline.Signal\n\tStorageID        *component.ID\n\tReferenceCounter ReferenceCounter[T]\n\tEncoding         Encoding[T]\n\tID               component.ID\n\tTelemetry        component.TelemetrySettings\n}\n\nfunc NewQueue[T request.Request](set Settings[T], next ConsumeFunc[T]) (Queue[T], error) {\n\tq := newBaseQueue(set)\n\toq, err := newObsQueue(set, newAsyncQueue(q, set.NumConsumers, next, set.ReferenceCounter))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn oq, nil\n}\n\nfunc newBaseQueue[T request.Request](set Settings[T]) readableQueue[T] {\n\t// Configure memory queue or persistent based on the config.\n\tif set.StorageID == nil {\n\t\treturn newMemoryQueue[T](set)\n\t}\n\n\treturn newPersistentQueue[T](set)\n}\n\n// TODO: Investigate why linter \"unused\" fails if add a private \"read\" func on the Queue.\ntype readableQueue[T any] interface {\n\tQueue[T]\n\t// Read pulls the next available item from the queue along with its done callback. Once processing is\n\t// finished, the done callback must be called to clean up the storage.\n\t// The function blocks until an item is available or if the queue is stopped.\n\t// If the queue is stopped returns false, otherwise true.\n\tRead(context.Context) (context.Context, T, Done, bool)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queue_sender.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender\"\n)\n\n// NewDefaultQueueConfig returns the default config for queuebatch.Config.\n// By default:\n//\n// - the queue stores 1000 requests of telemetry\n// - is non-blocking when full\n// - concurrent exports limited to 10\n// - emits batches of 8192 items, timeout 200ms\nfunc NewDefaultQueueConfig() queuebatch.Config {\n\treturn queuebatch.Config{\n\t\tSizer:           request.SizerTypeRequests,\n\t\tNumConsumers:    10,\n\t\tQueueSize:       1_000,\n\t\tBlockOnOverflow: false,\n\t\tBatch: configoptional.Default(queuebatch.BatchConfig{\n\t\t\tFlushTimeout: 200 * time.Millisecond,\n\t\t\tSizer:        request.SizerTypeItems,\n\t\t\tMinSize:      8192,\n\t\t}),\n\t}\n}\n\nfunc NewQueueSender(\n\tqSet queuebatch.AllSettings[request.Request],\n\tqCfg queuebatch.Config,\n\texportFailureMessage string,\n\tnext sender.Sender[request.Request],\n) (sender.Sender[request.Request], error) {\n\texportFunc := func(ctx context.Context, req request.Request) error {\n\t\t// Have to read the number of items before sending the request since the request can\n\t\t// be modified by the downstream components like the batcher.\n\t\titemsCount := req.ItemsCount()\n\t\tif errSend := next.Send(ctx, req); errSend != nil {\n\t\t\tqSet.Telemetry.Logger.Error(\"Exporting failed. Dropping data.\"+exportFailureMessage,\n\t\t\t\tzap.Error(errSend), zap.Int(\"dropped_items\", itemsCount))\n\t\t\treturn errSend\n\t\t}\n\t\treturn nil\n\t}\n\n\treturn queuebatch.NewQueueBatch(qSet, qCfg, exportFunc)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queue_sender_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\nfunc TestNewQueueSenderFailedRequestDropped(t *testing.T) {\n\tqSet := queuebatch.AllSettings[request.Request]{\n\t\tSignal:    pipeline.SignalMetrics,\n\t\tID:        component.NewID(exportertest.NopType),\n\t\tTelemetry: componenttest.NewNopTelemetrySettings(),\n\t}\n\tlogger, observed := observer.New(zap.ErrorLevel)\n\tqSet.Telemetry.Logger = zap.New(logger)\n\tqCfg := NewDefaultQueueConfig()\n\tbe, err := NewQueueSender(\n\t\tqSet, qCfg, \"\", sender.NewSender(func(context.Context, request.Request) error { return errors.New(\"some error\") }))\n\trequire.NoError(t, err)\n\n\trequire.NoError(t, be.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.NoError(t, be.Send(context.Background(), &requesttest.FakeRequest{Items: 2}))\n\trequire.NoError(t, be.Shutdown(context.Background()))\n\tassert.Len(t, observed.All(), 1)\n\tassert.Equal(t, \"Exporting failed. Dropping data.\", observed.All()[0].Message)\n}\n\nfunc TestQueueConfig_Validate(t *testing.T) {\n\tqCfg := NewDefaultQueueConfig()\n\trequire.NoError(t, qCfg.Validate())\n\n\tqCfg.NumConsumers = 0\n\trequire.EqualError(t, qCfg.Validate(), \"`num_consumers` must be positive\")\n\n\tqCfg = NewDefaultQueueConfig()\n\tqCfg.QueueSize = 0\n\trequire.EqualError(t, qCfg.Validate(), \"`queue_size` must be positive\")\n\n\t// Confirm Validate doesn't return error with invalid config when feature is disabled\n\tnoCfg := configoptional.None[queuebatch.Config]()\n\tassert.NoError(t, noCfg.Validate())\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/batch_context.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/otel/trace\"\n)\n\ntype traceContextKeyType int\n\nconst batchSpanLinksKey traceContextKeyType = iota\n\n// LinksFromContext returns a list of trace links registered in the context.\nfunc LinksFromContext(ctx context.Context) []trace.Link {\n\tif ctx == nil {\n\t\treturn []trace.Link{}\n\t}\n\tif links, ok := ctx.Value(batchSpanLinksKey).([]trace.Link); ok {\n\t\treturn links\n\t}\n\treturn []trace.Link{}\n}\n\nfunc parentsFromContext(ctx context.Context) []trace.Link {\n\tif spanCtx := trace.SpanContextFromContext(ctx); spanCtx.IsValid() {\n\t\treturn []trace.Link{{SpanContext: spanCtx}}\n\t}\n\treturn LinksFromContext(ctx)\n}\n\nfunc contextWithMergedLinks(mergedCtx, ctx1, ctx2 context.Context) context.Context {\n\treturn context.WithValue(\n\t\tmergedCtx,\n\t\tbatchSpanLinksKey,\n\t\tappend(parentsFromContext(ctx1), parentsFromContext(ctx2)...))\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/batch_context_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\ntype testTimestampKeyType int\n\nconst testTimestampKey testTimestampKeyType = iota\n\n// mergeCtxFunc corresponds to user specified mergeCtx function in the batcher settings.\n// This specific merge Context function keeps the greater of timestamps from two contexts.\nfunc mergeCtxFunc(ctx1, ctx2 context.Context) context.Context {\n\ttimestamp1 := ctx1.Value(testTimestampKey)\n\ttimestamp2 := ctx2.Value(testTimestampKey)\n\tif timestamp1 != nil && timestamp2 != nil {\n\t\tif timestamp1.(int) > timestamp2.(int) {\n\t\t\treturn context.WithValue(context.Background(), testTimestampKey, timestamp1)\n\t\t}\n\t\treturn context.WithValue(context.Background(), testTimestampKey, timestamp2)\n\t}\n\tif timestamp1 != nil {\n\t\treturn context.WithValue(context.Background(), testTimestampKey, timestamp1)\n\t}\n\treturn context.WithValue(context.Background(), testTimestampKey, timestamp2)\n}\n\n// mergeContextHelper performs the same operation done during batching.\nfunc mergeContextHelper(ctx1, ctx2 context.Context) context.Context {\n\treturn contextWithMergedLinks(mergeCtxFunc(ctx1, ctx2), ctx1, ctx2)\n}\n\nfunc TestBatchContextLink(t *testing.T) {\n\ttracerProvider := componenttest.NewTelemetry().NewTelemetrySettings().TracerProvider\n\ttracer := tracerProvider.Tracer(\"go.opentelemetry.io/collector/exporter/exporterhelper\")\n\n\tctx1 := context.Background()\n\n\tctx2, span2 := tracer.Start(ctx1, \"span2\")\n\tdefer span2.End()\n\n\tctx3, span3 := tracer.Start(ctx1, \"span3\")\n\tdefer span3.End()\n\n\tctx4, span4 := tracer.Start(ctx1, \"span4\")\n\tdefer span4.End()\n\n\tbatchContext := mergeContextHelper(ctx2, ctx3)\n\tbatchContext = mergeContextHelper(batchContext, ctx4)\n\n\tactualLinks := LinksFromContext(batchContext)\n\trequire.Len(t, actualLinks, 3)\n\trequire.Equal(t, trace.SpanContextFromContext(ctx2), actualLinks[0].SpanContext)\n\trequire.Equal(t, trace.SpanContextFromContext(ctx3), actualLinks[1].SpanContext)\n\trequire.Equal(t, trace.SpanContextFromContext(ctx4), actualLinks[2].SpanContext)\n}\n\nfunc TestMergedContext_GetValue(t *testing.T) {\n\tctx1 := context.WithValue(context.Background(), testTimestampKey, 1234)\n\tctx2 := context.WithValue(context.Background(), testTimestampKey, 2345)\n\tbatchContext := mergeContextHelper(ctx1, ctx2)\n\trequire.Equal(t, 2345, batchContext.Value(testTimestampKey))\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/batcher.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender\"\n)\n\n// Batcher is in charge of reading items from the queue and send them out asynchronously.\ntype Batcher[T any] interface {\n\tcomponent.Component\n\tConsume(context.Context, T, queue.Done)\n}\n\ntype batcherSettings[T any] struct {\n\tpartitioner Partitioner[T]\n\tmergeCtx    func(context.Context, context.Context) context.Context\n\tnext        sender.SendFunc[T]\n\tmaxWorkers  int\n\tlogger      *zap.Logger\n}\n\nfunc NewBatcher(cfg configoptional.Optional[BatchConfig], set batcherSettings[request.Request]) (Batcher[request.Request], error) {\n\tif !cfg.HasValue() {\n\t\treturn newDisabledBatcher(set.next), nil\n\t}\n\n\tsizer := request.NewSizer(cfg.Get().Sizer)\n\tif sizer == nil {\n\t\treturn nil, fmt.Errorf(\"queue_batch: unsupported sizer %q\", cfg.Get().Sizer)\n\t}\n\n\tif set.partitioner == nil {\n\t\treturn newPartitionBatcher(*cfg.Get(), sizer, set.mergeCtx, newWorkerPool(set.maxWorkers), set.next, set.logger, nil), nil\n\t}\n\n\tmb, err := newMultiBatcher(*cfg.Get(), sizer, newWorkerPool(set.maxWorkers), set.partitioner, set.mergeCtx, set.next, set.logger)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error during creating multi batcher: %w\", err)\n\t}\n\treturn mb, nil\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n)\n\n// Config defines configuration for queueing and batching incoming requests.\ntype Config struct {\n\t// WaitForResult determines if incoming requests are blocked until the request is processed or not.\n\t// Currently, this option is not available when persistent queue is configured using the storage configuration.\n\tWaitForResult bool `mapstructure:\"wait_for_result\"`\n\n\t// Sizer determines the type of size measurement used by this component.\n\t// It accepts \"requests\", \"items\", or \"bytes\".\n\tSizer request.SizerType `mapstructure:\"sizer\"`\n\n\t// QueueSize represents the maximum data size allowed for concurrent storage and processing.\n\tQueueSize int64 `mapstructure:\"queue_size\"`\n\n\t// BlockOnOverflow determines the behavior when the component's TotalSize limit is reached.\n\t// If true, the component will wait for space; otherwise, operations will immediately return a retryable error.\n\tBlockOnOverflow bool `mapstructure:\"block_on_overflow\"`\n\n\t// StorageID if not empty, enables the persistent storage and uses the component specified\n\t// as a storage extension for the persistent queue.\n\t// TODO: This will be changed to Optional when available.\n\t// See https://github.com/open-telemetry/opentelemetry-collector/issues/13822\n\tStorageID *component.ID `mapstructure:\"storage\"`\n\n\t// NumConsumers is the maximum number of concurrent consumers from the queue.\n\t// This applies across all different optional configurations from above (e.g. wait_for_result, block_on_overflow, storage, etc.).\n\tNumConsumers int `mapstructure:\"num_consumers\"`\n\n\t// BatchConfig it configures how the requests are consumed from the queue and batch together during consumption.\n\tBatch configoptional.Optional[BatchConfig] `mapstructure:\"batch\"`\n}\n\nfunc (cfg *Config) Unmarshal(conf *confmap.Conf) error {\n\tif err := conf.Unmarshal(cfg); err != nil {\n\t\treturn err\n\t}\n\n\t// If all of the following hold:\n\t// 1. the sizer is set,\n\t// 2. the batch sizer is not set and\n\t// 3. the batch section is nonempty,\n\t// then use the same value as the queue sizer.\n\tif conf.IsSet(\"sizer\") && !conf.IsSet(\"batch::sizer\") && conf.IsSet(\"batch\") && conf.Get(\"batch\") != nil {\n\t\tcfg.Batch.Get().Sizer = cfg.Sizer\n\t}\n\treturn nil\n}\n\n// Validate checks if the Config is valid\nfunc (cfg *Config) Validate() error {\n\tif cfg.NumConsumers <= 0 {\n\t\treturn errors.New(\"`num_consumers` must be positive\")\n\t}\n\n\tif cfg.QueueSize <= 0 {\n\t\treturn errors.New(\"`queue_size` must be positive\")\n\t}\n\n\t// Only support request sizer for persistent queue at this moment.\n\tif cfg.StorageID != nil && cfg.WaitForResult {\n\t\treturn errors.New(\"`wait_for_result` is not supported with a persistent queue configured with `storage`\")\n\t}\n\n\tif cfg.Batch.HasValue() && cfg.Batch.Get().Sizer == cfg.Sizer {\n\t\t// Avoid situations where the queue is not able to hold any data.\n\t\tif cfg.Batch.Get().MinSize > cfg.QueueSize {\n\t\t\treturn errors.New(\"`min_size` must be less than or equal to `queue_size`\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// BatchConfig defines a configuration for batching requests based on a timeout and a minimum number of items.\ntype BatchConfig struct {\n\t// FlushTimeout sets the time after which a batch will be sent regardless of its size.\n\tFlushTimeout time.Duration `mapstructure:\"flush_timeout\"`\n\n\t// Sizer determines the type of size measurement used by the batch.\n\t// If not configured, use the same configuration as the queue.\n\t// It accepts \"requests\", \"items\", or \"bytes\".\n\tSizer request.SizerType `mapstructure:\"sizer\"`\n\n\t// MinSize defines the configuration for the minimum size of a batch.\n\tMinSize int64 `mapstructure:\"min_size\"`\n\n\t// MaxSize defines the configuration for the maximum size of a batch.\n\tMaxSize int64 `mapstructure:\"max_size\"`\n\n\t// Partition defines the partitioning of the batches configuration.\n\tPartition PartitionConfig `mapstructure:\"partition\"`\n}\n\n// PartitionConfig defines a configuration for partitioning requests based on metadata keys.\ntype PartitionConfig struct {\n\t// MetadataKeys is a list of client.Metadata keys that will be used to partition\n\t// the data into batches. If this setting is empty, a single batcher instance\n\t// will be used. When this setting is not empty, one batcher will be used per\n\t// distinct combination of values for the listed metadata keys.\n\t//\n\t// Empty value and unset metadata are treated as distinct cases.\n\t//\n\t// Entries are case-insensitive. Duplicated entries will trigger a validation error.\n\tMetadataKeys []string `mapstructure:\"metadata_keys\"`\n}\n\nfunc (cfg *BatchConfig) Validate() error {\n\tif cfg == nil {\n\t\treturn nil\n\t}\n\n\t// Only support items or bytes sizer for batch at this moment.\n\tif cfg.Sizer != request.SizerTypeItems && cfg.Sizer != request.SizerTypeBytes {\n\t\treturn fmt.Errorf(\"`batch` supports only `items` or `bytes` sizer, found %q\", cfg.Sizer.String())\n\t}\n\n\tif cfg.FlushTimeout <= 0 {\n\t\treturn fmt.Errorf(\"`flush_timeout` must be positive, found %d\", cfg.FlushTimeout)\n\t}\n\n\tif cfg.MinSize < 0 {\n\t\treturn fmt.Errorf(\"`min_size` must be non-negative, found %d\", cfg.MinSize)\n\t}\n\n\tif cfg.MaxSize < 0 {\n\t\treturn fmt.Errorf(\"`max_size` must be non-negative, found %d\", cfg.MaxSize)\n\t}\n\n\tif cfg.MaxSize > 0 && cfg.MaxSize < cfg.MinSize {\n\t\treturn fmt.Errorf(\"`max_size` (%d) must be greater or equal to `min_size` (%d)\", cfg.MaxSize, cfg.MinSize)\n\t}\n\n\treturn nil\n}\n\nfunc (cfg *PartitionConfig) Validate() error {\n\tif cfg == nil {\n\t\treturn nil\n\t}\n\n\t// Validate metadata_keys for duplicates (case-insensitive)\n\tuniq := map[string]bool{}\n\tfor _, k := range cfg.MetadataKeys {\n\t\tl := strings.ToLower(k)\n\t\tif _, has := uniq[l]; has {\n\t\t\treturn fmt.Errorf(\"duplicate entry in metadata_keys: %q (case-insensitive)\", l)\n\t\t}\n\t\tuniq[l] = true\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/config.schema.yaml",
    "content": "$defs:\n  batch_config:\n    description: BatchConfig defines a configuration for batching requests based on a timeout and a minimum number of items.\n    type: object\n    properties:\n      flush_timeout:\n        description: FlushTimeout sets the time after which a batch will be sent regardless of its size.\n        type: string\n        x-customType: time.Duration\n        format: duration\n      max_size:\n        description: MaxSize defines the configuration for the maximum size of a batch.\n        type: integer\n        x-customType: int64\n      min_size:\n        description: MinSize defines the configuration for the minimum size of a batch.\n        type: integer\n        x-customType: int64\n      partition:\n        description: Partition defines the partitioning of the batches configuration.\n        $ref: partition_config\n      sizer:\n        description: Sizer determines the type of size measurement used by the batch. If not configured, use the same configuration as the queue. It accepts \"requests\", \"items\", or \"bytes\".\n        type: string\n        x-customType: go.opentelemetry.io/collector/exporter/exporterhelper/internal/request.SizerType\n  partition_config:\n    description: PartitionConfig defines a configuration for partitioning requests based on metadata keys.\n    type: object\n    properties:\n      metadata_keys:\n        description: MetadataKeys is a list of client.Metadata keys that will be used to partition the data into batches. If this setting is empty, a single batcher instance will be used. When this setting is not empty, one batcher will be used per distinct combination of values for the listed metadata keys. Empty value and unset metadata are treated as distinct cases. Entries are case-insensitive. Duplicated entries will trigger a validation error.\n        type: array\n        items:\n          type: string\n  config:\n    description: Config defines configuration for queueing and batching incoming requests.\n    type: object\n    properties:\n      batch:\n        description: BatchConfig it configures how the requests are consumed from the queue and batch together during consumption.\n        x-optional: true\n        $ref: batch_config\n      block_on_overflow:\n        description: BlockOnOverflow determines the behavior when the component's TotalSize limit is reached. If true, the component will wait for space; otherwise, operations will immediately return a retryable error.\n        type: boolean\n      enabled:\n        description: Enabled indicates whether to not enqueue and batch before exporting.\n        type: boolean\n      num_consumers:\n        description: NumConsumers is the maximum number of concurrent consumers from the queue. This applies across all different optional configurations from above (e.g. wait_for_result, block_on_overflow, storage, etc.).\n        type: integer\n      queue_size:\n        description: QueueSize represents the maximum data size allowed for concurrent storage and processing.\n        type: integer\n        x-customType: int64\n      sizer:\n        description: Sizer determines the type of size measurement used by this component. It accepts \"requests\", \"items\", or \"bytes\".\n        type: string\n        x-customType: go.opentelemetry.io/collector/exporter/exporterhelper/internal/request.SizerType\n      storage:\n        description: 'StorageID if not empty, enables the persistent storage and uses the component specified as a storage extension for the persistent queue. TODO: This will be changed to Optional when available. See https://github.com/open-telemetry/opentelemetry-collector/issues/13822'\n        x-pointer: true\n        type: string\n        x-customType: go.opentelemetry.io/collector/component.ID\n      wait_for_result:\n        description: WaitForResult determines if incoming requests are blocked until the request is processed or not. Currently, this option is not available when persistent queue is configured using the storage configuration.\n        type: boolean\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n)\n\nfunc TestConfig_Validate(t *testing.T) {\n\tcfg := newTestConfig()\n\trequire.NoError(t, xconfmap.Validate(cfg))\n\n\tcfg.NumConsumers = 0\n\trequire.EqualError(t, xconfmap.Validate(cfg), \"`num_consumers` must be positive\")\n\n\tcfg = newTestConfig()\n\tcfg.QueueSize = 0\n\trequire.EqualError(t, xconfmap.Validate(cfg), \"`queue_size` must be positive\")\n\n\tcfg = newTestConfig()\n\tcfg.QueueSize = 0\n\trequire.EqualError(t, xconfmap.Validate(cfg), \"`queue_size` must be positive\")\n\n\tstorageID := component.MustNewID(\"test\")\n\tcfg = newTestConfig()\n\tcfg.WaitForResult = true\n\tcfg.StorageID = &storageID\n\trequire.EqualError(t, xconfmap.Validate(cfg), \"`wait_for_result` is not supported with a persistent queue configured with `storage`\")\n\n\tcfg = newTestConfig()\n\tcfg.QueueSize = cfg.Batch.Get().MinSize - 1\n\trequire.EqualError(t, xconfmap.Validate(cfg), \"`min_size` must be less than or equal to `queue_size`\")\n\n\tcfg = newTestConfig()\n\tcfg.Batch.Get().Sizer = request.SizerType{}\n\trequire.EqualError(t, xconfmap.Validate(cfg), \"batch: `batch` supports only `items` or `bytes` sizer, found \\\"\\\"\")\n\n\tcfg = newTestConfig()\n\tcfg.Sizer = request.SizerTypeBytes\n\trequire.NoError(t, xconfmap.Validate(cfg))\n}\n\nfunc TestBatchConfig_Validate_MetadataKeys(t *testing.T) {\n\tt.Run(\"no duplicates - valid\", func(t *testing.T) {\n\t\tcfg := newTestBatchConfig()\n\t\tcfg.Partition.MetadataKeys = []string{\"key1\", \"key2\", \"key3\"}\n\t\trequire.NoError(t, xconfmap.Validate(cfg))\n\t})\n\n\tt.Run(\"duplicate keys mixed case - invalid\", func(t *testing.T) {\n\t\tcfg := newTestBatchConfig()\n\t\tcfg.Partition.MetadataKeys = []string{\"Key1\", \"kEy1\", \"key2\"}\n\t\terr := xconfmap.Validate(cfg)\n\t\trequire.Error(t, err)\n\t\tassert.Contains(t, err.Error(), \"duplicate entry in metadata_keys\")\n\t\tassert.Contains(t, err.Error(), \"key1\")\n\t\tassert.Contains(t, err.Error(), \"case-insensitive\")\n\t})\n\n\tt.Run(\"empty metadata_keys - valid\", func(t *testing.T) {\n\t\tcfg := newTestBatchConfig()\n\t\tcfg.Partition.MetadataKeys = []string{}\n\t\trequire.NoError(t, xconfmap.Validate(cfg))\n\t})\n\n\tt.Run(\"nil metadata_keys - valid\", func(t *testing.T) {\n\t\tcfg := newTestBatchConfig()\n\t\tcfg.Partition.MetadataKeys = nil\n\t\trequire.NoError(t, xconfmap.Validate(cfg))\n\t})\n\n\tt.Run(\"multiple duplicates - reports first duplicate\", func(t *testing.T) {\n\t\tcfg := newTestBatchConfig()\n\t\tcfg.Partition.MetadataKeys = []string{\"key1\", \"key2\", \"key1\", \"key2\"}\n\t\terr := xconfmap.Validate(cfg)\n\t\trequire.Error(t, err)\n\t\tassert.Contains(t, err.Error(), \"duplicate entry in metadata_keys\")\n\t\tassert.Contains(t, err.Error(), \"key1\")\n\t})\n}\n\nfunc TestBatchConfig_Validate(t *testing.T) {\n\tcfg := newTestBatchConfig()\n\trequire.NoError(t, xconfmap.Validate(cfg))\n\n\tcfg = newTestBatchConfig()\n\tcfg.FlushTimeout = 0\n\trequire.EqualError(t, xconfmap.Validate(cfg), \"`flush_timeout` must be positive, found 0\")\n\n\tcfg = newTestBatchConfig()\n\tcfg.MinSize = -1\n\trequire.EqualError(t, xconfmap.Validate(cfg), \"`min_size` must be non-negative, found -1\")\n\n\tcfg = newTestBatchConfig()\n\tcfg.MaxSize = -1\n\trequire.EqualError(t, xconfmap.Validate(cfg), \"`max_size` must be non-negative, found -1\")\n\n\tcfg = newTestBatchConfig()\n\tcfg.Sizer = request.SizerTypeRequests\n\trequire.EqualError(t, xconfmap.Validate(cfg), \"`batch` supports only `items` or `bytes` sizer, found \\\"requests\\\"\")\n\n\tcfg = newTestBatchConfig()\n\tcfg.Sizer = request.SizerType{}\n\trequire.EqualError(t, xconfmap.Validate(cfg), \"`batch` supports only `items` or `bytes` sizer, found \\\"\\\"\")\n\n\tcfg = newTestBatchConfig()\n\tcfg.MinSize = 2048\n\tcfg.MaxSize = 1024\n\trequire.EqualError(t, xconfmap.Validate(cfg), \"`max_size` (1024) must be greater or equal to `min_size` (2048)\")\n}\n\nfunc newTestBatchConfig() BatchConfig {\n\treturn BatchConfig{\n\t\tFlushTimeout: 200 * time.Millisecond,\n\t\tSizer:        request.SizerTypeItems,\n\t\tMinSize:      2048,\n\t\tMaxSize:      0,\n\t}\n}\n\nfunc TestUnmarshal(t *testing.T) {\n\tnewBaseCfg := func() configoptional.Optional[Config] {\n\t\treturn configoptional.Some(Config{\n\t\t\tSizer:        request.SizerTypeRequests,\n\t\t\tNumConsumers: 10,\n\t\t\tQueueSize:    1_000,\n\t\t\tBatch: configoptional.Default(BatchConfig{\n\t\t\t\tFlushTimeout: 200 * time.Millisecond,\n\t\t\t\tSizer:        request.SizerTypeItems,\n\t\t\t\tMinSize:      8192,\n\t\t\t}),\n\t\t})\n\t}\n\ttests := []struct {\n\t\tpath        string\n\t\texpectedErr string\n\t\texpectedCfg func() configoptional.Optional[Config]\n\t}{\n\t\t{\n\t\t\tpath: \"batch_set_empty_explicit_sizer.yaml\",\n\t\t\texpectedCfg: func() configoptional.Optional[Config] {\n\t\t\t\tcfg := newBaseCfg()\n\t\t\t\tcfg.Get().Sizer = request.SizerTypeBytes\n\t\t\t\t// Batch is set, sizer is not overridden\n\t\t\t\tcfg.Get().Batch.GetOrInsertDefault()\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tpath: \"batch_set_empty_no_explicit_sizer.yaml\",\n\t\t\texpectedCfg: func() configoptional.Optional[Config] {\n\t\t\t\tcfg := newBaseCfg()\n\t\t\t\tcfg.Get().Batch.GetOrInsertDefault()\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tpath: \"batch_set_nonempty_explicit_sizer.yaml\",\n\t\t\texpectedCfg: func() configoptional.Optional[Config] {\n\t\t\t\tcfg := newBaseCfg()\n\t\t\t\tcfg.Get().Sizer = request.SizerTypeBytes\n\t\t\t\tcfg.Get().QueueSize = 2000\n\t\t\t\tcfg.Get().Batch = configoptional.Some(BatchConfig{\n\t\t\t\t\tFlushTimeout: 200 * time.Millisecond,\n\t\t\t\t\t// Sizer has been overridden by parent sizer\n\t\t\t\t\tSizer:   request.SizerTypeBytes,\n\t\t\t\t\tMinSize: 100,\n\t\t\t\t})\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tpath: \"batch_set_nonempty_no_explicit_sizer.yaml\",\n\t\t\texpectedCfg: func() configoptional.Optional[Config] {\n\t\t\t\tcfg := newBaseCfg()\n\t\t\t\tcfg.Get().QueueSize = 2000\n\t\t\t\tcfg.Get().Batch = configoptional.Some(BatchConfig{\n\t\t\t\t\tFlushTimeout: 200 * time.Millisecond,\n\t\t\t\t\t// Sizer has NOT been overridden by parent sizer\n\t\t\t\t\tSizer:   request.SizerTypeItems,\n\t\t\t\t\tMinSize: 100,\n\t\t\t\t})\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tpath: \"batch_unset.yaml\",\n\t\t\t// Batch remains unset, sizer override does not apply.\n\t\t\texpectedCfg: newBaseCfg,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.path, func(t *testing.T) {\n\t\t\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", tt.path))\n\t\t\trequire.NoError(t, err)\n\n\t\t\tcfg := newBaseCfg()\n\t\t\terr = cm.Unmarshal(&cfg)\n\t\t\tif tt.expectedErr != \"\" {\n\t\t\t\tassert.ErrorContains(t, err, tt.expectedErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tt.expectedCfg(), cfg)\n\t\t\tassert.NoError(t, xconfmap.Validate(cfg))\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/disabled_batcher.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender\"\n)\n\n// disabledBatcher is a special-case of Batcher that has no size limit for sending. Any items read from the queue will\n// be sent out (asynchronously) immediately regardless of the size.\ntype disabledBatcher[T any] struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumeFunc sender.SendFunc[T]\n}\n\nfunc (db *disabledBatcher[T]) Consume(ctx context.Context, req T, done queue.Done) {\n\tdone.OnDone(db.consumeFunc(ctx, req))\n}\n\nfunc newDisabledBatcher[T any](consumeFunc sender.SendFunc[T]) Batcher[T] {\n\treturn &disabledBatcher[T]{consumeFunc: consumeFunc}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/disabled_batcher_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n)\n\nfunc TestDisabledBatcher(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\tmaxWorkers int\n\t}{\n\t\t{\n\t\t\tname:       \"one_worker\",\n\t\t\tmaxWorkers: 1,\n\t\t},\n\t\t{\n\t\t\tname:       \"three_workers\",\n\t\t\tmaxWorkers: 3,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsink := requesttest.NewSink()\n\t\t\tba := newDisabledBatcher(sink.Export)\n\n\t\t\tq, err := queue.NewQueue(queue.Settings[request.Request]{\n\t\t\t\tCapacity:        1000,\n\t\t\t\tBlockOnOverflow: true,\n\t\t\t\tNumConsumers:    tt.maxWorkers,\n\t\t\t\tTelemetry:       componenttest.NewNopTelemetrySettings(),\n\t\t\t}, ba.Consume)\n\t\t\trequire.NoError(t, err)\n\n\t\t\trequire.NoError(t, q.Start(context.Background(), componenttest.NewNopHost()))\n\t\t\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n\t\t\tt.Cleanup(func() {\n\t\t\t\trequire.NoError(t, q.Shutdown(context.Background()))\n\t\t\t\trequire.NoError(t, ba.Shutdown(context.Background()))\n\t\t\t})\n\n\t\t\trequire.NoError(t, q.Offer(context.Background(), &requesttest.FakeRequest{Items: 8}))\n\t\t\tsink.SetExportErr(errors.New(\"transient error\"))\n\t\t\trequire.NoError(t, q.Offer(context.Background(), &requesttest.FakeRequest{Items: 8}))\n\t\t\trequire.NoError(t, q.Offer(context.Background(), &requesttest.FakeRequest{Items: 17}))\n\t\t\trequire.NoError(t, q.Offer(context.Background(), &requesttest.FakeRequest{Items: 13}))\n\t\t\trequire.NoError(t, q.Offer(context.Background(), &requesttest.FakeRequest{Items: 35}))\n\t\t\trequire.NoError(t, q.Offer(context.Background(), &requesttest.FakeRequest{Items: 2}))\n\t\t\tassert.Eventually(t, func() bool {\n\t\t\t\treturn sink.RequestsCount() == 5 && sink.ItemsCount() == 75\n\t\t\t}, 1*time.Second, 10*time.Millisecond)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\n// Package queuebatch provides helper functions for exporter's queueing and batching.\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/encoding.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport \"context\"\n\n// encoding defines the encoding to be used if persistent queue is configured.\n// Duplicate definition with exporterhelper.QueueBatchEncoding since aliasing generics is not supported by default.\ntype encoding[T any] interface {\n\t// Marshal is a function that can marshal a request and its context into bytes.\n\tMarshal(context.Context, T) ([]byte, error)\n\n\t// Unmarshal is a function that can unmarshal bytes into a request and its context.\n\tUnmarshal([]byte) (context.Context, T, error)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage queuebatch\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/logs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n\tpdatareq \"go.opentelemetry.io/collector/pdata/xpdata/request\"\n)\n\nvar (\n\tlogsMarshaler   = &plog.ProtoMarshaler{}\n\tlogsUnmarshaler = &plog.ProtoUnmarshaler{}\n)\n\n// NewLogsQueueBatchSettings returns a new QueueBatchSettings to configure to WithQueueBatch when using plog.Logs.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\nfunc NewLogsQueueBatchSettings() Settings[request.Request] {\n\treturn Settings[request.Request]{\n\t\tReferenceCounter: logsReferenceCounter{},\n\t\tEncoding:         logsEncoding{},\n\t}\n}\n\nvar (\n\t_ request.Request      = (*logsRequest)(nil)\n\t_ request.ErrorHandler = (*logsRequest)(nil)\n)\n\ntype logsRequest struct {\n\tld         plog.Logs\n\tcachedSize int\n}\n\nfunc newLogsRequest(ld plog.Logs) request.Request {\n\treturn &logsRequest{\n\t\tld:         ld,\n\t\tcachedSize: -1,\n\t}\n}\n\ntype logsEncoding struct{}\n\nvar _ encoding[request.Request] = logsEncoding{}\n\nfunc (logsEncoding) Unmarshal(bytes []byte) (context.Context, request.Request, error) {\n\tif queue.PersistRequestContextOnRead() {\n\t\tctx, logs, err := pdatareq.UnmarshalLogs(bytes)\n\t\tif errors.Is(err, pdatareq.ErrInvalidFormat) {\n\t\t\t// fall back to unmarshaling without context\n\t\t\tlogs, err = logsUnmarshaler.UnmarshalLogs(bytes)\n\t\t}\n\t\treturn ctx, newLogsRequest(logs), err\n\t}\n\n\tlogs, err := logsUnmarshaler.UnmarshalLogs(bytes)\n\tif err != nil {\n\t\tvar req request.Request\n\t\treturn context.Background(), req, err\n\t}\n\treturn context.Background(), newLogsRequest(logs), nil\n}\n\nfunc (logsEncoding) Marshal(ctx context.Context, req request.Request) ([]byte, error) {\n\tlogs := req.(*logsRequest).ld\n\tif queue.PersistRequestContextOnWrite() {\n\t\treturn pdatareq.MarshalLogs(ctx, logs)\n\t}\n\treturn logsMarshaler.MarshalLogs(logs)\n}\n\nvar _ queue.ReferenceCounter[request.Request] = logsReferenceCounter{}\n\ntype logsReferenceCounter struct{}\n\nfunc (logsReferenceCounter) Ref(req request.Request) {\n\tpref.RefLogs(req.(*logsRequest).ld)\n}\n\nfunc (logsReferenceCounter) Unref(req request.Request) {\n\tpref.UnrefLogs(req.(*logsRequest).ld)\n}\n\nfunc (req *logsRequest) OnError(err error) request.Request {\n\tvar logError consumererror.Logs\n\tif errors.As(err, &logError) {\n\t\t// TODO: Add logic to unref the new request created here.\n\t\treturn newLogsRequest(logError.Data())\n\t}\n\treturn req\n}\n\nfunc (req *logsRequest) ItemsCount() int {\n\treturn req.ld.LogRecordCount()\n}\n\nfunc (req *logsRequest) size(sizer sizer.LogsSizer) int {\n\tif req.cachedSize == -1 {\n\t\treq.cachedSize = sizer.LogsSize(req.ld)\n\t}\n\treturn req.cachedSize\n}\n\nfunc (req *logsRequest) setCachedSize(size int) {\n\treq.cachedSize = size\n}\n\nfunc (req *logsRequest) BytesSize() int {\n\treturn logsMarshaler.LogsSize(req.ld)\n}\n\n// RequestConsumeFromLogs returns a RequestConsumeFunc that consumes plog.Logs.\nfunc RequestConsumeFromLogs(pusher consumer.ConsumeLogsFunc) request.RequestConsumeFunc {\n\treturn func(ctx context.Context, request request.Request) error {\n\t\treturn pusher.ConsumeLogs(ctx, request.(*logsRequest).ld)\n\t}\n}\n\n// RequestFromLogs returns a RequestFromLogsFunc that converts plog.Logs into a Request.\nfunc RequestFromLogs() request.RequestConverterFunc[plog.Logs] {\n\treturn func(_ context.Context, ld plog.Logs) (request.Request, error) {\n\t\treturn newLogsRequest(ld), nil\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/logs_batch.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\n// MergeSplit splits and/or merges the provided logs request and the current request into one or more requests\n// conforming with the MaxSizeConfig.\nfunc (req *logsRequest) MergeSplit(_ context.Context, maxSize int, szt request.SizerType, r2 request.Request) ([]request.Request, error) {\n\tvar sz sizer.LogsSizer\n\tswitch szt {\n\tcase request.SizerTypeItems:\n\t\tsz = &sizer.LogsCountSizer{}\n\tcase request.SizerTypeBytes:\n\t\tsz = &sizer.LogsBytesSizer{}\n\tdefault:\n\t\treturn nil, errors.New(\"unknown sizer type\")\n\t}\n\tif r2 != nil {\n\t\treq2, ok := r2.(*logsRequest)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"invalid input type\")\n\t\t}\n\t\treq2.mergeTo(req, sz)\n\t}\n\n\t// If no limit we can simply merge the new request into the current and return.\n\tif maxSize == 0 {\n\t\treturn []request.Request{req}, nil\n\t}\n\n\treturn req.split(maxSize, sz)\n}\n\nfunc (req *logsRequest) mergeTo(dst *logsRequest, sz sizer.LogsSizer) {\n\tif sz != nil {\n\t\tdst.setCachedSize(dst.size(sz) + req.size(sz))\n\t\treq.setCachedSize(0)\n\t}\n\treq.ld.ResourceLogs().MoveAndAppendTo(dst.ld.ResourceLogs())\n}\n\nfunc (req *logsRequest) split(maxSize int, sz sizer.LogsSizer) ([]request.Request, error) {\n\tvar res []request.Request\n\tfor req.size(sz) > maxSize {\n\t\tld, removedSize := extractLogs(req.ld, maxSize, sz)\n\t\tif ld.LogRecordCount() == 0 {\n\t\t\treturn res, fmt.Errorf(\"one log record size is greater than max size, dropping items: %d\", req.ld.LogRecordCount())\n\t\t}\n\t\treq.setCachedSize(req.size(sz) - removedSize)\n\t\tres = append(res, newLogsRequest(ld))\n\t}\n\tres = append(res, req)\n\treturn res, nil\n}\n\n// extractLogs extracts logs from the input logs and returns a new logs with the specified number of log records.\nfunc extractLogs(srcLogs plog.Logs, capacity int, sz sizer.LogsSizer) (plog.Logs, int) {\n\tdestLogs := plog.NewLogs()\n\tcapacityLeft := capacity - sz.LogsSize(destLogs)\n\tremovedSize := 0\n\tsrcLogs.ResourceLogs().RemoveIf(func(srcRL plog.ResourceLogs) bool {\n\t\t// If the no more capacity left just return.\n\t\tif capacityLeft == 0 {\n\t\t\treturn false\n\t\t}\n\t\trawRlSize := sz.ResourceLogsSize(srcRL)\n\t\trlSize := sz.DeltaSize(rawRlSize)\n\t\tif rlSize > capacityLeft {\n\t\t\textSrcRL, extRlSize := extractResourceLogs(srcRL, capacityLeft, sz)\n\t\t\t// This cannot make it to exactly 0 for the bytes,\n\t\t\t// force it to be 0 since that is the stopping condition.\n\t\t\tcapacityLeft = 0\n\t\t\tremovedSize += extRlSize\n\t\t\t// There represents the delta between the delta sizes.\n\t\t\tremovedSize += rlSize - rawRlSize - (sz.DeltaSize(rawRlSize-extRlSize) - (rawRlSize - extRlSize))\n\t\t\t// It is possible that for the bytes scenario, the extracted field contains no log records.\n\t\t\t// Do not add it to the destination if that is the case.\n\t\t\tif extSrcRL.ScopeLogs().Len() > 0 {\n\t\t\t\textSrcRL.MoveTo(destLogs.ResourceLogs().AppendEmpty())\n\t\t\t}\n\t\t\treturn extSrcRL.ScopeLogs().Len() != 0\n\t\t}\n\t\tcapacityLeft -= rlSize\n\t\tremovedSize += rlSize\n\t\tsrcRL.MoveTo(destLogs.ResourceLogs().AppendEmpty())\n\t\treturn true\n\t})\n\treturn destLogs, removedSize\n}\n\n// extractResourceLogs extracts resource logs and returns a new resource logs with the specified number of log records.\nfunc extractResourceLogs(srcRL plog.ResourceLogs, capacity int, sz sizer.LogsSizer) (plog.ResourceLogs, int) {\n\tdestRL := plog.NewResourceLogs()\n\tdestRL.SetSchemaUrl(srcRL.SchemaUrl())\n\tsrcRL.Resource().CopyTo(destRL.Resource())\n\t// Take into account that this can have max \"capacity\", so when added to the parent will need space for the extra delta size.\n\tcapacityLeft := capacity - (sz.DeltaSize(capacity) - capacity) - sz.ResourceLogsSize(destRL)\n\tremovedSize := 0\n\tsrcRL.ScopeLogs().RemoveIf(func(srcSL plog.ScopeLogs) bool {\n\t\t// If the no more capacity left just return.\n\t\tif capacityLeft == 0 {\n\t\t\treturn false\n\t\t}\n\t\trawSlSize := sz.ScopeLogsSize(srcSL)\n\t\tslSize := sz.DeltaSize(rawSlSize)\n\t\tif slSize > capacityLeft {\n\t\t\textSrcSL, extSlSize := extractScopeLogs(srcSL, capacityLeft, sz)\n\t\t\t// This cannot make it to exactly 0 for the bytes,\n\t\t\t// force it to be 0 since that is the stopping condition.\n\t\t\tcapacityLeft = 0\n\t\t\tremovedSize += extSlSize\n\t\t\t// There represents the delta between the delta sizes.\n\t\t\tremovedSize += slSize - rawSlSize - (sz.DeltaSize(rawSlSize-extSlSize) - (rawSlSize - extSlSize))\n\t\t\t// It is possible that for the bytes scenario, the extracted field contains no log records.\n\t\t\t// Do not add it to the destination if that is the case.\n\t\t\tif extSrcSL.LogRecords().Len() > 0 {\n\t\t\t\textSrcSL.MoveTo(destRL.ScopeLogs().AppendEmpty())\n\t\t\t}\n\t\t\treturn extSrcSL.LogRecords().Len() != 0\n\t\t}\n\t\tcapacityLeft -= slSize\n\t\tremovedSize += slSize\n\t\tsrcSL.MoveTo(destRL.ScopeLogs().AppendEmpty())\n\t\treturn true\n\t})\n\treturn destRL, removedSize\n}\n\n// extractScopeLogs extracts scope logs and returns a new scope logs with the specified number of log records.\nfunc extractScopeLogs(srcSL plog.ScopeLogs, capacity int, sz sizer.LogsSizer) (plog.ScopeLogs, int) {\n\tdestSL := plog.NewScopeLogs()\n\tdestSL.SetSchemaUrl(srcSL.SchemaUrl())\n\tsrcSL.Scope().CopyTo(destSL.Scope())\n\t// Take into account that this can have max \"capacity\", so when added to the parent will need space for the extra delta size.\n\tcapacityLeft := capacity - (sz.DeltaSize(capacity) - capacity) - sz.ScopeLogsSize(destSL)\n\tremovedSize := 0\n\tsrcSL.LogRecords().RemoveIf(func(srcLR plog.LogRecord) bool {\n\t\t// If the no more capacity left just return.\n\t\tif capacityLeft == 0 {\n\t\t\treturn false\n\t\t}\n\t\trlSize := sz.DeltaSize(sz.LogRecordSize(srcLR))\n\t\tif rlSize > capacityLeft {\n\t\t\t// This cannot make it to exactly 0 for the bytes,\n\t\t\t// force it to be 0 since that is the stopping condition.\n\t\t\tcapacityLeft = 0\n\t\t\treturn false\n\t\t}\n\t\tcapacityLeft -= rlSize\n\t\tremovedSize += rlSize\n\t\tsrcLR.MoveTo(destSL.LogRecords().AppendEmpty())\n\t\treturn true\n\t})\n\treturn destSL, removedSize\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/logs_batch_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestMergeLogs(t *testing.T) {\n\tlr1 := newLogsRequest(testdata.GenerateLogs(2))\n\tlr2 := newLogsRequest(testdata.GenerateLogs(3))\n\tres, err := lr1.MergeSplit(context.Background(), 0, request.SizerTypeItems, lr2)\n\trequire.NoError(t, err)\n\trequire.Equal(t, 5, res[0].ItemsCount())\n}\n\nfunc TestMergeSplitLogs(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tszt      request.SizerType\n\t\tmaxSize  int\n\t\tlr1      request.Request\n\t\tlr2      request.Request\n\t\texpected []request.Request\n\t}{\n\t\t{\n\t\t\tname: \"both_requests_empty\",\n\t\t\tszt:  request.SizerTypeItems, maxSize: 10,\n\t\t\tlr1:      newLogsRequest(plog.NewLogs()),\n\t\t\tlr2:      newLogsRequest(plog.NewLogs()),\n\t\t\texpected: []request.Request{newLogsRequest(plog.NewLogs())},\n\t\t},\n\t\t{\n\t\t\tname: \"first_request_empty\",\n\t\t\tszt:  request.SizerTypeItems, maxSize: 10,\n\t\t\tlr1:      newLogsRequest(plog.NewLogs()),\n\t\t\tlr2:      newLogsRequest(testdata.GenerateLogs(5)),\n\t\t\texpected: []request.Request{newLogsRequest(testdata.GenerateLogs(5))},\n\t\t},\n\t\t{\n\t\t\tname: \"first_empty_second_nil\",\n\t\t\tszt:  request.SizerTypeItems, maxSize: 10,\n\t\t\tlr1:      newLogsRequest(plog.NewLogs()),\n\t\t\tlr2:      nil,\n\t\t\texpected: []request.Request{newLogsRequest(plog.NewLogs())},\n\t\t},\n\t\t{\n\t\t\tname:    \"merge_only\",\n\t\t\tszt:     request.SizerTypeItems,\n\t\t\tmaxSize: 10,\n\t\t\tlr1:     newLogsRequest(testdata.GenerateLogs(4)),\n\t\t\tlr2:     newLogsRequest(testdata.GenerateLogs(6)),\n\t\t\texpected: []request.Request{newLogsRequest(func() plog.Logs {\n\t\t\t\tlogs := testdata.GenerateLogs(4)\n\t\t\t\ttestdata.GenerateLogs(6).ResourceLogs().MoveAndAppendTo(logs.ResourceLogs())\n\t\t\t\treturn logs\n\t\t\t}())},\n\t\t},\n\t\t{\n\t\t\tname:    \"split_only\",\n\t\t\tszt:     request.SizerTypeItems,\n\t\t\tmaxSize: 4,\n\t\t\tlr1:     newLogsRequest(plog.NewLogs()),\n\t\t\tlr2:     newLogsRequest(testdata.GenerateLogs(10)),\n\t\t\texpected: []request.Request{\n\t\t\t\tnewLogsRequest(testdata.GenerateLogs(4)),\n\t\t\t\tnewLogsRequest(testdata.GenerateLogs(4)),\n\t\t\t\tnewLogsRequest(testdata.GenerateLogs(2)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"merge_and_split\",\n\t\t\tszt:     request.SizerTypeItems,\n\t\t\tmaxSize: 10,\n\t\t\tlr1:     newLogsRequest(testdata.GenerateLogs(8)),\n\t\t\tlr2:     newLogsRequest(testdata.GenerateLogs(20)),\n\t\t\texpected: []request.Request{\n\t\t\t\tnewLogsRequest(func() plog.Logs {\n\t\t\t\t\tlogs := testdata.GenerateLogs(8)\n\t\t\t\t\ttestdata.GenerateLogs(2).ResourceLogs().MoveAndAppendTo(logs.ResourceLogs())\n\t\t\t\t\treturn logs\n\t\t\t\t}()),\n\t\t\t\tnewLogsRequest(testdata.GenerateLogs(10)),\n\t\t\t\tnewLogsRequest(testdata.GenerateLogs(8)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"scope_logs_split\",\n\t\t\tszt:     request.SizerTypeItems,\n\t\t\tmaxSize: 4,\n\t\t\tlr1: newLogsRequest(func() plog.Logs {\n\t\t\t\tld := testdata.GenerateLogs(4)\n\t\t\t\tld.ResourceLogs().At(0).ScopeLogs().AppendEmpty().LogRecords().AppendEmpty().Body().SetStr(\"extra log\")\n\t\t\t\treturn ld\n\t\t\t}()),\n\t\t\tlr2: newLogsRequest(testdata.GenerateLogs(2)),\n\t\t\texpected: []request.Request{\n\t\t\t\tnewLogsRequest(testdata.GenerateLogs(4)),\n\t\t\t\tnewLogsRequest(func() plog.Logs {\n\t\t\t\t\tld := testdata.GenerateLogs(0)\n\t\t\t\t\tld.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().AppendEmpty().Body().SetStr(\"extra log\")\n\t\t\t\t\ttestdata.GenerateLogs(2).ResourceLogs().MoveAndAppendTo(ld.ResourceLogs())\n\t\t\t\t\treturn ld\n\t\t\t\t}()),\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tres, err := tt.lr1.MergeSplit(context.Background(), tt.maxSize, tt.szt, tt.lr2)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Len(t, res, len(tt.expected))\n\t\t\tfor i := range res {\n\t\t\t\tassert.Equal(t, tt.expected[i].(*logsRequest).ld, res[i].(*logsRequest).ld)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMergeSplitLogsBasedOnByteSize(t *testing.T) {\n\ttests := []struct {\n\t\tname               string\n\t\tszt                request.SizerType\n\t\tmaxSize            int\n\t\tlr1                request.Request\n\t\tlr2                request.Request\n\t\texpected           []request.Request\n\t\texpectPartialError bool\n\t}{\n\t\t{\n\t\t\tname:     \"both_requests_empty\",\n\t\t\tszt:      request.SizerTypeBytes,\n\t\t\tmaxSize:  logsMarshaler.LogsSize(testdata.GenerateLogs(10)),\n\t\t\tlr1:      newLogsRequest(plog.NewLogs()),\n\t\t\tlr2:      newLogsRequest(plog.NewLogs()),\n\t\t\texpected: []request.Request{newLogsRequest(plog.NewLogs())},\n\t\t},\n\t\t{\n\t\t\tname:     \"first_request_empty\",\n\t\t\tszt:      request.SizerTypeBytes,\n\t\t\tmaxSize:  logsMarshaler.LogsSize(testdata.GenerateLogs(10)),\n\t\t\tlr1:      newLogsRequest(plog.NewLogs()),\n\t\t\tlr2:      newLogsRequest(testdata.GenerateLogs(5)),\n\t\t\texpected: []request.Request{newLogsRequest(testdata.GenerateLogs(5))},\n\t\t},\n\t\t{\n\t\t\tname:     \"first_empty_second_nil\",\n\t\t\tszt:      request.SizerTypeBytes,\n\t\t\tmaxSize:  logsMarshaler.LogsSize(testdata.GenerateLogs(10)),\n\t\t\tlr1:      newLogsRequest(plog.NewLogs()),\n\t\t\tlr2:      nil,\n\t\t\texpected: []request.Request{newLogsRequest(plog.NewLogs())},\n\t\t},\n\t\t{\n\t\t\tname:    \"merge_only\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: logsMarshaler.LogsSize(testdata.GenerateLogs(11)),\n\t\t\tlr1:     newLogsRequest(testdata.GenerateLogs(4)),\n\t\t\tlr2:     newLogsRequest(testdata.GenerateLogs(6)),\n\t\t\texpected: []request.Request{newLogsRequest(func() plog.Logs {\n\t\t\t\tlogs := testdata.GenerateLogs(4)\n\t\t\t\ttestdata.GenerateLogs(6).ResourceLogs().MoveAndAppendTo(logs.ResourceLogs())\n\t\t\t\treturn logs\n\t\t\t}())},\n\t\t},\n\t\t{\n\t\t\tname:    \"split_only\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: logsMarshaler.LogsSize(testdata.GenerateLogs(4)),\n\t\t\tlr1:     newLogsRequest(plog.NewLogs()),\n\t\t\tlr2:     newLogsRequest(testdata.GenerateLogs(10)),\n\t\t\texpected: []request.Request{\n\t\t\t\tnewLogsRequest(testdata.GenerateLogs(4)),\n\t\t\t\tnewLogsRequest(testdata.GenerateLogs(4)),\n\t\t\t\tnewLogsRequest(testdata.GenerateLogs(2)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"merge_and_split\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: logsMarshaler.LogsSize(testdata.GenerateLogs(10))/2 + logsMarshaler.LogsSize(testdata.GenerateLogs(11))/2,\n\t\t\tlr1:     newLogsRequest(testdata.GenerateLogs(8)),\n\t\t\tlr2:     newLogsRequest(testdata.GenerateLogs(20)),\n\t\t\texpected: []request.Request{\n\t\t\t\tnewLogsRequest(func() plog.Logs {\n\t\t\t\t\tlogs := testdata.GenerateLogs(8)\n\t\t\t\t\ttestdata.GenerateLogs(2).ResourceLogs().MoveAndAppendTo(logs.ResourceLogs())\n\t\t\t\t\treturn logs\n\t\t\t\t}()),\n\t\t\t\tnewLogsRequest(testdata.GenerateLogs(10)),\n\t\t\t\tnewLogsRequest(testdata.GenerateLogs(8)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"scope_logs_split\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: logsMarshaler.LogsSize(testdata.GenerateLogs(4)),\n\t\t\tlr1: newLogsRequest(func() plog.Logs {\n\t\t\t\tld := testdata.GenerateLogs(4)\n\t\t\t\tld.ResourceLogs().At(0).ScopeLogs().AppendEmpty().LogRecords().AppendEmpty().Body().SetStr(\"extra log\")\n\t\t\t\treturn ld\n\t\t\t}()),\n\t\t\tlr2: newLogsRequest(testdata.GenerateLogs(2)),\n\t\t\texpected: []request.Request{\n\t\t\t\tnewLogsRequest(testdata.GenerateLogs(4)),\n\t\t\t\tnewLogsRequest(func() plog.Logs {\n\t\t\t\t\tld := testdata.GenerateLogs(0)\n\t\t\t\t\tld.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().AppendEmpty().Body().SetStr(\"extra log\")\n\t\t\t\t\ttestdata.GenerateLogs(2).ResourceLogs().MoveAndAppendTo(ld.ResourceLogs())\n\t\t\t\t\treturn ld\n\t\t\t\t}()),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"unsplittable_large_log\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: 10,\n\t\t\tlr1: newLogsRequest(func() plog.Logs {\n\t\t\t\tld := testdata.GenerateLogs(1)\n\t\t\t\tld.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(0).Body().SetStr(string(make([]byte, 100)))\n\t\t\t\treturn ld\n\t\t\t}()),\n\t\t\tlr2:                nil,\n\t\t\texpected:           []request.Request{},\n\t\t\texpectPartialError: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"splittable_then_unsplittable_log\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: 1000,\n\t\t\tlr1: newLogsRequest(func() plog.Logs {\n\t\t\t\tld := testdata.GenerateLogs(2)\n\t\t\t\tld.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(0).Body().SetStr(string(make([]byte, 10)))\n\t\t\t\tld.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(1).Body().SetStr(string(make([]byte, 1001)))\n\t\t\t\treturn ld\n\t\t\t}()),\n\t\t\tlr2: nil,\n\t\t\texpected: []request.Request{newLogsRequest(func() plog.Logs {\n\t\t\t\tld := testdata.GenerateLogs(1)\n\t\t\t\tld.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(0).Body().SetStr(string(make([]byte, 10)))\n\t\t\t\treturn ld\n\t\t\t}())},\n\t\t\texpectPartialError: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tres, err := tt.lr1.MergeSplit(context.Background(), tt.maxSize, tt.szt, tt.lr2)\n\t\t\tif tt.expectPartialError {\n\t\t\t\trequire.ErrorContains(t, err, \"one log record size is greater than max size, dropping\")\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\t\t\tassert.Len(t, res, len(tt.expected))\n\t\t\tfor i := range res {\n\t\t\t\tassert.Equal(t, tt.expected[i].(*logsRequest).ld, res[i].(*logsRequest).ld)\n\t\t\t\tassert.Equal(t,\n\t\t\t\t\tlogsMarshaler.LogsSize(tt.expected[i].(*logsRequest).ld),\n\t\t\t\t\tlogsMarshaler.LogsSize(res[i].(*logsRequest).ld))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMergeSplitLogsInputNotModifiedIfErrorReturned(t *testing.T) {\n\tr1 := newLogsRequest(testdata.GenerateLogs(18))\n\tr2 := newTracesRequest(testdata.GenerateTraces(3))\n\t_, err := r1.MergeSplit(context.Background(), 10, request.SizerTypeItems, r2)\n\trequire.Error(t, err)\n\tassert.Equal(t, 18, r1.ItemsCount())\n}\n\nfunc TestExtractLogs(t *testing.T) {\n\tfor i := range 10 {\n\t\tld := testdata.GenerateLogs(10)\n\t\textractedLogs, _ := extractLogs(ld, i, &sizer.LogsCountSizer{})\n\t\tassert.Equal(t, i, extractedLogs.LogRecordCount())\n\t\tassert.Equal(t, 10-i, ld.LogRecordCount())\n\t}\n}\n\nfunc TestMergeSplitManySmallLogs(t *testing.T) {\n\t// All requests merge into a single batch.\n\tmerged := []request.Request{newLogsRequest(testdata.GenerateLogs(1))}\n\tfor range 1000 {\n\t\tlr2 := newLogsRequest(testdata.GenerateLogs(10))\n\t\tres, _ := merged[len(merged)-1].MergeSplit(context.Background(), 10000, request.SizerTypeItems, lr2)\n\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t}\n\tassert.Len(t, merged, 2)\n}\n\nfunc TestLogsMergeSplitExactBytes(t *testing.T) {\n\tpb := plog.ProtoMarshaler{}\n\t// Set max size off by 1, so forces every log to be it's own batch.\n\tlr := newLogsRequest(testdata.GenerateLogs(4))\n\tmerged, err := lr.MergeSplit(context.Background(), pb.LogsSize(testdata.GenerateLogs(2))-1, request.SizerTypeBytes, nil)\n\trequire.NoError(t, err)\n\tassert.Len(t, merged, 4)\n}\n\nfunc TestLogsMergeSplitExactItems(t *testing.T) {\n\t// Set max size off by 1, so forces every log to be it's own batch.\n\tlr := newLogsRequest(testdata.GenerateLogs(4))\n\tmerged, err := lr.MergeSplit(context.Background(), 1, request.SizerTypeItems, nil)\n\trequire.NoError(t, err)\n\tassert.Len(t, merged, 4)\n}\n\nfunc TestLogsMergeSplitUnknownSizerType(t *testing.T) {\n\treq := newLogsRequest(plog.NewLogs())\n\t// Call MergeSplit with invalid sizer\n\t_, err := req.MergeSplit(context.Background(), 0, request.SizerType{}, nil)\n\trequire.EqualError(t, err, \"unknown sizer type\")\n}\n\nfunc BenchmarkSplittingBasedOnItemCountManySmallLogs(b *testing.B) {\n\ttestutil.SkipGCHeavyBench(b)\n\t// All requests merge into a single batch.\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tmerged := []request.Request{newLogsRequest(testdata.GenerateLogs(10))}\n\t\tfor range 1000 {\n\t\t\tlr2 := newLogsRequest(testdata.GenerateLogs(10))\n\t\t\tres, _ := merged[len(merged)-1].MergeSplit(context.Background(), 10010, request.SizerTypeItems, lr2)\n\t\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t\t}\n\t\tassert.Len(b, merged, 1)\n\t}\n}\n\nfunc BenchmarkSplittingBasedOnByteSizeManySmallLogs(b *testing.B) {\n\ttestutil.SkipGCHeavyBench(b)\n\t// All requests merge into a single batch.\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tmerged := []request.Request{newLogsRequest(testdata.GenerateLogs(10))}\n\t\tfor range 1000 {\n\t\t\tlr2 := newLogsRequest(testdata.GenerateLogs(10))\n\t\t\tres, _ := merged[len(merged)-1].MergeSplit(context.Background(), logsMarshaler.LogsSize(testdata.GenerateLogs(11000)), request.SizerTypeBytes, lr2)\n\t\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t\t}\n\t\tassert.Len(b, merged, 1)\n\t}\n}\n\nfunc BenchmarkSplittingBasedOnItemCountManyLogsSlightlyAboveLimit(b *testing.B) {\n\ttestutil.SkipGCHeavyBench(b)\n\t// Every incoming request results in a split.\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tmerged := []request.Request{newLogsRequest(testdata.GenerateLogs(0))}\n\t\tfor range 10 {\n\t\t\tlr2 := newLogsRequest(testdata.GenerateLogs(10001))\n\t\t\tres, _ := merged[len(merged)-1].MergeSplit(context.Background(), 10000, request.SizerTypeItems, lr2)\n\t\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t\t}\n\t\tassert.Len(b, merged, 11)\n\t}\n}\n\nfunc BenchmarkSplittingBasedOnByteSizeManyLogsSlightlyAboveLimit(b *testing.B) {\n\ttestutil.SkipGCHeavyBench(b)\n\t// Every incoming request results in a split.\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tmerged := []request.Request{newLogsRequest(testdata.GenerateLogs(0))}\n\t\tfor range 10 {\n\t\t\tlr2 := newLogsRequest(testdata.GenerateLogs(10001))\n\t\t\tres, _ := merged[len(merged)-1].MergeSplit(context.Background(), logsMarshaler.LogsSize(testdata.GenerateLogs(10000)), request.SizerTypeBytes, lr2)\n\t\t\tassert.Len(b, res, 2)\n\t\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t\t}\n\t\tassert.Len(b, merged, 11)\n\t}\n}\n\nfunc BenchmarkSplittingBasedOnItemCountHugeLogs(b *testing.B) {\n\ttestutil.SkipGCHeavyBench(b)\n\t// One request splits into many batches.\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tmerged := []request.Request{newLogsRequest(testdata.GenerateLogs(0))}\n\t\tlr2 := newLogsRequest(testdata.GenerateLogs(100000))\n\t\tres, _ := merged[len(merged)-1].MergeSplit(context.Background(), 10000, request.SizerTypeItems, lr2)\n\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t\tassert.Len(b, merged, 10)\n\t}\n}\n\nfunc BenchmarkSplittingBasedOnByteSizeHugeLogs(b *testing.B) {\n\ttestutil.SkipGCHeavyBench(b)\n\t// One request splits into many batches.\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tmerged := []request.Request{newLogsRequest(testdata.GenerateLogs(0))}\n\t\tlr2 := newLogsRequest(testdata.GenerateLogs(100000))\n\t\tres, _ := merged[len(merged)-1].MergeSplit(context.Background(), logsMarshaler.LogsSize(testdata.GenerateLogs(10010)), request.SizerTypeBytes, lr2)\n\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t\tassert.Len(b, merged, 10)\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/logs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestLogsRequest(t *testing.T) {\n\tlr := newLogsRequest(testdata.GenerateLogs(1))\n\n\tlogErr := consumererror.NewLogs(errors.New(\"some error\"), plog.NewLogs())\n\tassert.Equal(\n\t\tt,\n\t\tnewLogsRequest(plog.NewLogs()),\n\t\tlr.(request.ErrorHandler).OnError(logErr),\n\t)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/metadata.yaml",
    "content": "type: queuebatch\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  stability:\n    beta: [traces, metrics, logs]\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/metadata_partitioner.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/client\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n)\n\n// metadataKeysPartitioner partitions requests based on client metadata keys.\ntype metadataKeysPartitioner struct {\n\tkeys []string\n}\n\n// NewMetadataKeysPartitioner creates a new partitioner that partitions requests\n// based on the specified metadata keys. If keys is empty, returns nil.\nfunc NewMetadataKeysPartitioner(keys []string) Partitioner[request.Request] {\n\tif len(keys) == 0 {\n\t\treturn nil\n\t}\n\treturn &metadataKeysPartitioner{keys: keys}\n}\n\n// GetKey returns a partition key based on the metadata keys configured.\nfunc (p *metadataKeysPartitioner) GetKey(\n\tctx context.Context,\n\t_ request.Request,\n) string {\n\tvar kb bytes.Buffer\n\tmeta := client.FromContext(ctx).Metadata\n\n\tvar afterFirst bool\n\tfor _, k := range p.keys {\n\t\tif values := meta.Get(k); len(values) != 0 {\n\t\t\tif afterFirst {\n\t\t\t\tkb.WriteByte(0)\n\t\t\t}\n\t\t\tkb.WriteString(k)\n\t\t\tafterFirst = true\n\t\t\tfor _, val := range values {\n\t\t\t\tkb.WriteByte(0)\n\t\t\t\tkb.WriteString(val)\n\t\t\t}\n\t\t}\n\t}\n\treturn kb.String()\n}\n\n// NewMetadataKeysMergeCtx creates a merge function for contexts that merges\n// metadata based on the specified keys. If keys is empty, returns nil.\nfunc NewMetadataKeysMergeCtx(keys []string) func(context.Context, context.Context) context.Context {\n\tif len(keys) == 0 {\n\t\treturn nil\n\t}\n\treturn func(ctx1, _ context.Context) context.Context {\n\t\tm1 := client.FromContext(ctx1).Metadata\n\n\t\tm := make(map[string][]string, len(keys))\n\t\tfor _, key := range keys {\n\t\t\tv1 := m1.Get(key)\n\t\t\tif len(v1) > 0 {\n\t\t\t\tm[key] = v1\n\t\t\t}\n\t\t}\n\t\treturn client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{Metadata: client.NewMetadata(m)},\n\t\t)\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/metadata_partitioner_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/client\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n)\n\nfunc TestMetadataKeysPartitioner_MergeCtx(t *testing.T) {\n\tt.Run(\"merge contexts with same metadata key values\", func(t *testing.T) {\n\t\tmergeCtx := NewMetadataKeysMergeCtx([]string{\"key1\", \"key2\"})\n\n\t\tctx1 := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value1\"},\n\t\t\t\t\t\"key2\": {\"value2\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tctx2 := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value1\"},\n\t\t\t\t\t\"key2\": {\"value2\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tmergedCtx := mergeCtx(ctx1, ctx2)\n\t\trequire.NotNil(t, mergedCtx)\n\n\t\tmergedMeta := client.FromContext(mergedCtx).Metadata\n\t\tassert.Equal(t, []string{\"value1\"}, mergedMeta.Get(\"key1\"))\n\t\tassert.Equal(t, []string{\"value2\"}, mergedMeta.Get(\"key2\"))\n\t})\n\n\tt.Run(\"merge contexts with same metadata key values and additional keys\", func(t *testing.T) {\n\t\tmergeCtx := NewMetadataKeysMergeCtx([]string{\"key1\"})\n\n\t\tctx1 := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\":  {\"value1\"},\n\t\t\t\t\t\"other\": {\"other1\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tctx2 := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\":  {\"value1\"},\n\t\t\t\t\t\"other\": {\"other2\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tmergedCtx := mergeCtx(ctx1, ctx2)\n\t\trequire.NotNil(t, mergedCtx)\n\n\t\tmergedMeta := client.FromContext(mergedCtx).Metadata\n\t\tassert.Equal(t, []string{\"value1\"}, mergedMeta.Get(\"key1\"))\n\t\t// Other keys should not be in merged metadata since they're not in partitioner keys\n\t\tassert.Empty(t, mergedMeta.Get(\"other\"))\n\t})\n\n\tt.Run(\"merge contexts with empty metadata\", func(t *testing.T) {\n\t\tmergeCtx := NewMetadataKeysMergeCtx([]string{\"key1\"})\n\n\t\tctx1 := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{}),\n\t\t\t},\n\t\t)\n\n\t\tctx2 := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{}),\n\t\t\t},\n\t\t)\n\n\t\tmergedCtx := mergeCtx(ctx1, ctx2)\n\t\trequire.NotNil(t, mergedCtx)\n\n\t\tmergedMeta := client.FromContext(mergedCtx).Metadata\n\t\tassert.Empty(t, mergedMeta.Get(\"key1\"))\n\t})\n\n\tt.Run(\"merge when one context has metadata and other is empty\", func(t *testing.T) {\n\t\tmergeCtx := NewMetadataKeysMergeCtx([]string{\"key1\"})\n\n\t\tctx1 := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value1\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tctx2 := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{}),\n\t\t\t},\n\t\t)\n\n\t\tmergedCtx := mergeCtx(ctx1, ctx2)\n\t\trequire.NotNil(t, mergedCtx)\n\t\tmergedMeta := client.FromContext(mergedCtx).Metadata\n\t\tassert.Equal(t, []string{\"value1\"}, mergedMeta.Get(\"key1\"))\n\t})\n\n\tt.Run(\"merge when contexts have different metadata key values\", func(t *testing.T) {\n\t\tmergeCtx := NewMetadataKeysMergeCtx([]string{\"key1\"})\n\n\t\tctx1 := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value1\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tctx2 := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value2\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tmergedCtx := mergeCtx(ctx1, ctx2)\n\t\trequire.NotNil(t, mergedCtx)\n\t\tmergedMeta := client.FromContext(mergedCtx).Metadata\n\t\tassert.Equal(t, []string{\"value1\"}, mergedMeta.Get(\"key1\"))\n\t})\n\n\tt.Run(\"merge when contexts have different metadata key values for multiple keys\", func(t *testing.T) {\n\t\tmergeCtx := NewMetadataKeysMergeCtx([]string{\"key1\", \"key2\"})\n\n\t\tctx1 := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value1\"},\n\t\t\t\t\t\"key2\": {\"value2\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tctx2 := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value1\"},\n\t\t\t\t\t\"key2\": {\"different\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tmergedCtx := mergeCtx(ctx1, ctx2)\n\t\trequire.NotNil(t, mergedCtx)\n\t\tmergedMeta := client.FromContext(mergedCtx).Metadata\n\t\tassert.Equal(t, []string{\"value1\"}, mergedMeta.Get(\"key1\"))\n\t\tassert.Equal(t, []string{\"value2\"}, mergedMeta.Get(\"key2\"))\n\t})\n\n\tt.Run(\"merge contexts with multiple values for same key\", func(t *testing.T) {\n\t\tmergeCtx := NewMetadataKeysMergeCtx([]string{\"key1\"})\n\n\t\tctx1 := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value1\", \"value2\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tctx2 := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value1\", \"value2\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tmergedCtx := mergeCtx(ctx1, ctx2)\n\t\trequire.NotNil(t, mergedCtx)\n\n\t\tmergedMeta := client.FromContext(mergedCtx).Metadata\n\t\tassert.Equal(t, []string{\"value1\", \"value2\"}, mergedMeta.Get(\"key1\"))\n\t})\n\n\tt.Run(\"merge when contexts have different multiple values for same key\", func(t *testing.T) {\n\t\tmergeCtx := NewMetadataKeysMergeCtx([]string{\"key1\"})\n\n\t\tctx1 := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value1\", \"value2\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tctx2 := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value1\", \"value3\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tmergedCtx := mergeCtx(ctx1, ctx2)\n\t\trequire.NotNil(t, mergedCtx)\n\t\tmergedMeta := client.FromContext(mergedCtx).Metadata\n\t\tassert.Equal(t, []string{\"value1\", \"value2\"}, mergedMeta.Get(\"key1\"))\n\t})\n}\n\nfunc TestMetadataKeysPartitioner_GetKey(t *testing.T) {\n\tt.Run(\"single key with single value\", func(t *testing.T) {\n\t\tpartitioner := NewMetadataKeysPartitioner([]string{\"key1\"})\n\n\t\tctx := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value1\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tkey := partitioner.GetKey(ctx, &requesttest.FakeRequest{})\n\t\texpected := \"key1\\x00value1\"\n\t\tassert.Equal(t, expected, key)\n\t})\n\n\tt.Run(\"single key with multiple values\", func(t *testing.T) {\n\t\tpartitioner := NewMetadataKeysPartitioner([]string{\"key1\"})\n\n\t\tctx := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value1\", \"value2\", \"value3\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tkey := partitioner.GetKey(ctx, &requesttest.FakeRequest{})\n\t\t// Format: key1\\0value1\\0value2\\0value3\n\t\texpected := \"key1\\x00value1\\x00value2\\x00value3\"\n\t\tassert.Equal(t, expected, key)\n\t})\n\n\tt.Run(\"multiple keys with values\", func(t *testing.T) {\n\t\tpartitioner := NewMetadataKeysPartitioner([]string{\"key1\", \"key2\"})\n\n\t\tctx := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value1\"},\n\t\t\t\t\t\"key2\": {\"value2\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tkey := partitioner.GetKey(ctx, &requesttest.FakeRequest{})\n\t\t// Format: key1\\0value1\\0key2\\0value2 (separator between keys)\n\t\texpected := \"key1\\x00value1\\x00key2\\x00value2\"\n\t\tassert.Equal(t, expected, key)\n\t})\n\n\tt.Run(\"multiple keys with multiple values\", func(t *testing.T) {\n\t\tpartitioner := NewMetadataKeysPartitioner([]string{\"key1\", \"key2\"})\n\n\t\tctx := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value1\", \"value1b\"},\n\t\t\t\t\t\"key2\": {\"value2\", \"value2b\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tkey := partitioner.GetKey(ctx, &requesttest.FakeRequest{})\n\t\t// Format: key1\\0value1\\0value1b\\0key2\\0value2\\0value2b\n\t\texpected := \"key1\\x00value1\\x00value1b\\x00key2\\x00value2\\x00value2b\"\n\t\tassert.Equal(t, expected, key)\n\t})\n\n\tt.Run(\"keys that don't exist in metadata are skipped\", func(t *testing.T) {\n\t\tpartitioner := NewMetadataKeysPartitioner([]string{\"key1\", \"key2\", \"key3\"})\n\n\t\tctx := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value1\"},\n\t\t\t\t\t// key2 is missing\n\t\t\t\t\t\"key3\": {\"value3\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tkey := partitioner.GetKey(ctx, &requesttest.FakeRequest{})\n\t\t// Format: key1\\0value1\\0key3\\0value3 (key2 is skipped)\n\t\texpected := \"key1\\x00value1\\x00key3\\x00value3\"\n\t\tassert.Equal(t, expected, key)\n\t})\n\n\tt.Run(\"empty metadata returns empty string\", func(t *testing.T) {\n\t\tpartitioner := NewMetadataKeysPartitioner([]string{\"key1\", \"key2\"})\n\n\t\tctx := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{}),\n\t\t\t},\n\t\t)\n\n\t\tkey := partitioner.GetKey(ctx, &requesttest.FakeRequest{})\n\t\tassert.Empty(t, key)\n\t})\n\n\tt.Run(\"keys with empty values are skipped\", func(t *testing.T) {\n\t\tpartitioner := NewMetadataKeysPartitioner([]string{\"key1\", \"key2\", \"key3\"})\n\n\t\tctx := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value1\"},\n\t\t\t\t\t\"key2\": {}, // empty slice\n\t\t\t\t\t\"key3\": {\"value3\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tkey := partitioner.GetKey(ctx, &requesttest.FakeRequest{})\n\t\t// Format: key1\\0value1\\0key3\\0value3 (key2 is skipped)\n\t\texpected := \"key1\\x00value1\\x00key3\\x00value3\"\n\t\tassert.Equal(t, expected, key)\n\t})\n\n\tt.Run(\"keys in order respect partitioner key order\", func(t *testing.T) {\n\t\tpartitioner := NewMetadataKeysPartitioner([]string{\"key3\", \"key1\", \"key2\"})\n\n\t\tctx := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\": {\"value1\"},\n\t\t\t\t\t\"key2\": {\"value2\"},\n\t\t\t\t\t\"key3\": {\"value3\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tkey := partitioner.GetKey(ctx, &requesttest.FakeRequest{})\n\t\t// Format should follow partitioner order: key3\\0value3\\0key1\\0value1\\0key2\\0value2\n\t\texpected := \"key3\\x00value3\\x00key1\\x00value1\\x00key2\\x00value2\"\n\t\tassert.Equal(t, expected, key)\n\t})\n\n\tt.Run(\"additional metadata keys not in partitioner are ignored\", func(t *testing.T) {\n\t\tpartitioner := NewMetadataKeysPartitioner([]string{\"key1\"})\n\n\t\tctx := client.NewContext(\n\t\t\tcontext.Background(),\n\t\t\tclient.Info{\n\t\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\t\"key1\":  {\"value1\"},\n\t\t\t\t\t\"other\": {\"other1\"},\n\t\t\t\t\t\"extra\": {\"extra1\"},\n\t\t\t\t}),\n\t\t\t},\n\t\t)\n\n\t\tkey := partitioner.GetKey(ctx, &requesttest.FakeRequest{})\n\t\t// Format: key1\\0value1 (other keys are ignored)\n\t\texpected := \"key1\\x00value1\"\n\t\tassert.Equal(t, expected, key)\n\t})\n\n\tt.Run(\"returns nil partitioner when keys are empty\", func(t *testing.T) {\n\t\tpartitioner := NewMetadataKeysPartitioner([]string{})\n\t\tassert.Nil(t, partitioner)\n\t})\n\n\tt.Run(\"returns nil merge function when keys are empty\", func(t *testing.T) {\n\t\tmergeCtx := NewMetadataKeysMergeCtx([]string{})\n\t\tassert.Nil(t, mergeCtx)\n\t})\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n\tpdatareq \"go.opentelemetry.io/collector/pdata/xpdata/request\"\n)\n\nvar (\n\tmetricsMarshaler   = &pmetric.ProtoMarshaler{}\n\tmetricsUnmarshaler = &pmetric.ProtoUnmarshaler{}\n)\n\nfunc NewMetricsQueueBatchSettings() Settings[request.Request] {\n\treturn Settings[request.Request]{\n\t\tReferenceCounter: metricsReferenceCounter{},\n\t\tEncoding:         metricsEncoding{},\n\t}\n}\n\nvar (\n\t_ request.Request      = (*metricsRequest)(nil)\n\t_ request.ErrorHandler = (*metricsRequest)(nil)\n)\n\ntype metricsRequest struct {\n\tmd         pmetric.Metrics\n\tcachedSize int\n}\n\nfunc newMetricsRequest(md pmetric.Metrics) request.Request {\n\treturn &metricsRequest{\n\t\tmd:         md,\n\t\tcachedSize: -1,\n\t}\n}\n\ntype metricsEncoding struct{}\n\nvar _ encoding[request.Request] = metricsEncoding{}\n\nfunc (metricsEncoding) Unmarshal(bytes []byte) (context.Context, request.Request, error) {\n\tif queue.PersistRequestContextOnRead() {\n\t\tctx, metrics, err := pdatareq.UnmarshalMetrics(bytes)\n\t\tif errors.Is(err, pdatareq.ErrInvalidFormat) {\n\t\t\t// fall back to unmarshaling without context\n\t\t\tmetrics, err = metricsUnmarshaler.UnmarshalMetrics(bytes)\n\t\t}\n\t\treturn ctx, newMetricsRequest(metrics), err\n\t}\n\tmetrics, err := metricsUnmarshaler.UnmarshalMetrics(bytes)\n\tif err != nil {\n\t\tvar req request.Request\n\t\treturn context.Background(), req, err\n\t}\n\treturn context.Background(), newMetricsRequest(metrics), nil\n}\n\nfunc (metricsEncoding) Marshal(ctx context.Context, req request.Request) ([]byte, error) {\n\tmetrics := req.(*metricsRequest).md\n\tif queue.PersistRequestContextOnWrite() {\n\t\treturn pdatareq.MarshalMetrics(ctx, metrics)\n\t}\n\treturn metricsMarshaler.MarshalMetrics(metrics)\n}\n\nvar _ queue.ReferenceCounter[request.Request] = metricsReferenceCounter{}\n\ntype metricsReferenceCounter struct{}\n\nfunc (metricsReferenceCounter) Ref(req request.Request) {\n\tpref.RefMetrics(req.(*metricsRequest).md)\n}\n\nfunc (metricsReferenceCounter) Unref(req request.Request) {\n\tpref.UnrefMetrics(req.(*metricsRequest).md)\n}\n\nfunc (req *metricsRequest) OnError(err error) request.Request {\n\tvar metricsError consumererror.Metrics\n\tif errors.As(err, &metricsError) {\n\t\t// TODO: Add logic to unref the new request created here.\n\t\treturn newMetricsRequest(metricsError.Data())\n\t}\n\treturn req\n}\n\nfunc (req *metricsRequest) ItemsCount() int {\n\treturn req.md.DataPointCount()\n}\n\nfunc (req *metricsRequest) size(sizer sizer.MetricsSizer) int {\n\tif req.cachedSize == -1 {\n\t\treq.cachedSize = sizer.MetricsSize(req.md)\n\t}\n\treturn req.cachedSize\n}\n\nfunc (req *metricsRequest) setCachedSize(count int) {\n\treq.cachedSize = count\n}\n\nfunc (req *metricsRequest) BytesSize() int {\n\treturn metricsMarshaler.MetricsSize(req.md)\n}\n\n// RequestFromMetrics returns a RequestFromMetricsFunc that converts pdata.Metrics into a Request.\nfunc RequestFromMetrics() request.RequestConverterFunc[pmetric.Metrics] {\n\treturn func(_ context.Context, md pmetric.Metrics) (request.Request, error) {\n\t\treturn newMetricsRequest(md), nil\n\t}\n}\n\n// RequestConsumeFromMetrics returns a RequestConsumeFunc that consumes pmetric.Metrics.\nfunc RequestConsumeFromMetrics(pusher consumer.ConsumeMetricsFunc) request.RequestConsumeFunc {\n\treturn func(ctx context.Context, request request.Request) error {\n\t\treturn pusher.ConsumeMetrics(ctx, request.(*metricsRequest).md)\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/metrics_batch.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\n// MergeSplit splits and/or merges the provided metrics request and the current request into one or more requests\n// conforming with the MaxSizeConfig.\nfunc (req *metricsRequest) MergeSplit(_ context.Context, maxSize int, szt request.SizerType, r2 request.Request) ([]request.Request, error) {\n\tvar sz sizer.MetricsSizer\n\tswitch szt {\n\tcase request.SizerTypeItems:\n\t\tsz = &sizer.MetricsCountSizer{}\n\tcase request.SizerTypeBytes:\n\t\tsz = &sizer.MetricsBytesSizer{}\n\tdefault:\n\t\treturn nil, errors.New(\"unknown sizer type\")\n\t}\n\n\tif r2 != nil {\n\t\treq2, ok := r2.(*metricsRequest)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"invalid input type\")\n\t\t}\n\t\treq2.mergeTo(req, sz)\n\t}\n\n\t// If no limit we can simply merge the new request into the current and return.\n\tif maxSize == 0 {\n\t\treturn []request.Request{req}, nil\n\t}\n\treturn req.split(maxSize, sz)\n}\n\nfunc (req *metricsRequest) mergeTo(dst *metricsRequest, sz sizer.MetricsSizer) {\n\tif sz != nil {\n\t\tdst.setCachedSize(dst.size(sz) + req.size(sz))\n\t\treq.setCachedSize(0)\n\t}\n\treq.md.ResourceMetrics().MoveAndAppendTo(dst.md.ResourceMetrics())\n}\n\nfunc (req *metricsRequest) split(maxSize int, sz sizer.MetricsSizer) ([]request.Request, error) {\n\tvar res []request.Request\n\tfor req.size(sz) > maxSize {\n\t\tmd, rmSize := extractMetrics(req.md, maxSize, sz)\n\t\tif md.DataPointCount() == 0 {\n\t\t\treturn res, fmt.Errorf(\"one datapoint size is greater than max size, dropping items: %d\", req.md.DataPointCount())\n\t\t}\n\t\treq.setCachedSize(req.size(sz) - rmSize)\n\t\tres = append(res, newMetricsRequest(md))\n\t}\n\tres = append(res, req)\n\treturn res, nil\n}\n\n// extractMetrics extracts metrics from srcMetrics until capacity is reached.\nfunc extractMetrics(srcMetrics pmetric.Metrics, capacity int, sz sizer.MetricsSizer) (pmetric.Metrics, int) {\n\tdestMetrics := pmetric.NewMetrics()\n\tcapacityLeft := capacity - sz.MetricsSize(destMetrics)\n\tremovedSize := 0\n\tsrcMetrics.ResourceMetrics().RemoveIf(func(srcRM pmetric.ResourceMetrics) bool {\n\t\t// If the no more capacity left just return.\n\t\tif capacityLeft == 0 {\n\t\t\treturn false\n\t\t}\n\t\trawRlSize := sz.ResourceMetricsSize(srcRM)\n\t\trlSize := sz.DeltaSize(rawRlSize)\n\t\tif rlSize > capacityLeft {\n\t\t\textSrcRM, extRmSize := extractResourceMetrics(srcRM, capacityLeft, sz)\n\t\t\t// This cannot make it to exactly 0 for the bytes,\n\t\t\t// force it to be 0 since that is the stopping condition.\n\t\t\tcapacityLeft = 0\n\t\t\tremovedSize += extRmSize\n\t\t\t// There represents the delta between the delta sizes.\n\t\t\tremovedSize += rlSize - rawRlSize - (sz.DeltaSize(rawRlSize-extRmSize) - (rawRlSize - extRmSize))\n\t\t\t// It is possible that for the bytes scenario, the extracted field contains no scope metrics.\n\t\t\t// Do not add it to the destination if that is the case.\n\t\t\tif extSrcRM.ScopeMetrics().Len() > 0 {\n\t\t\t\textSrcRM.MoveTo(destMetrics.ResourceMetrics().AppendEmpty())\n\t\t\t}\n\t\t\treturn extSrcRM.ScopeMetrics().Len() != 0\n\t\t}\n\t\tcapacityLeft -= rlSize\n\t\tremovedSize += rlSize\n\t\tsrcRM.MoveTo(destMetrics.ResourceMetrics().AppendEmpty())\n\t\treturn true\n\t})\n\treturn destMetrics, removedSize\n}\n\n// extractResourceMetrics extracts resource metrics and returns a new resource metrics with the specified number of data points.\nfunc extractResourceMetrics(srcRM pmetric.ResourceMetrics, capacity int, sz sizer.MetricsSizer) (pmetric.ResourceMetrics, int) {\n\tdestRM := pmetric.NewResourceMetrics()\n\tdestRM.SetSchemaUrl(srcRM.SchemaUrl())\n\tsrcRM.Resource().CopyTo(destRM.Resource())\n\t// Take into account that this can have max \"capacity\", so when added to the parent will need space for the extra delta size.\n\tcapacityLeft := capacity - (sz.DeltaSize(capacity) - capacity) - sz.ResourceMetricsSize(destRM)\n\tremovedSize := 0\n\tsrcRM.ScopeMetrics().RemoveIf(func(srcSM pmetric.ScopeMetrics) bool {\n\t\t// If the no more capacity left just return.\n\t\tif capacityLeft == 0 {\n\t\t\treturn false\n\t\t}\n\t\trawSmSize := sz.ScopeMetricsSize(srcSM)\n\t\tsmSize := sz.DeltaSize(rawSmSize)\n\t\tif smSize > capacityLeft {\n\t\t\textSrcSM, extSmSize := extractScopeMetrics(srcSM, capacityLeft, sz)\n\t\t\t// This cannot make it to exactly 0 for the bytes,\n\t\t\t// force it to be 0 since that is the stopping condition.\n\t\t\tcapacityLeft = 0\n\t\t\tremovedSize += extSmSize\n\t\t\t// There represents the delta between the delta sizes.\n\t\t\tremovedSize += smSize - rawSmSize - (sz.DeltaSize(rawSmSize-extSmSize) - (rawSmSize - extSmSize))\n\t\t\t// It is possible that for the bytes scenario, the extracted field contains no scope metrics.\n\t\t\t// Do not add it to the destination if that is the case.\n\t\t\tif extSrcSM.Metrics().Len() > 0 {\n\t\t\t\textSrcSM.MoveTo(destRM.ScopeMetrics().AppendEmpty())\n\t\t\t}\n\t\t\treturn extSrcSM.Metrics().Len() != 0\n\t\t}\n\t\tcapacityLeft -= smSize\n\t\tremovedSize += smSize\n\t\tsrcSM.MoveTo(destRM.ScopeMetrics().AppendEmpty())\n\t\treturn true\n\t})\n\treturn destRM, removedSize\n}\n\n// extractScopeMetrics extracts scope metrics and returns a new scope metrics with the specified number of data points.\nfunc extractScopeMetrics(srcSM pmetric.ScopeMetrics, capacity int, sz sizer.MetricsSizer) (pmetric.ScopeMetrics, int) {\n\tdestSM := pmetric.NewScopeMetrics()\n\tdestSM.SetSchemaUrl(srcSM.SchemaUrl())\n\tsrcSM.Scope().CopyTo(destSM.Scope())\n\t// Take into account that this can have max \"capacity\", so when added to the parent will need space for the extra delta size.\n\tcapacityLeft := capacity - (sz.DeltaSize(capacity) - capacity) - sz.ScopeMetricsSize(destSM)\n\tremovedSize := 0\n\tsrcSM.Metrics().RemoveIf(func(srcSM pmetric.Metric) bool {\n\t\t// If the no more capacity left just return.\n\t\tif capacityLeft == 0 {\n\t\t\treturn false\n\t\t}\n\t\trawRmSize := sz.MetricSize(srcSM)\n\t\trmSize := sz.DeltaSize(rawRmSize)\n\t\tif rmSize > capacityLeft {\n\t\t\textSrcDP, extRmSize := extractMetricDataPoints(srcSM, capacityLeft, sz)\n\t\t\t// This cannot make it to exactly 0 for the bytes,\n\t\t\t// force it to be 0 since that is the stopping condition.\n\t\t\tcapacityLeft = 0\n\t\t\tremovedSize += extRmSize\n\t\t\t// There represents the delta between the delta sizes.\n\t\t\tremovedSize += rmSize - rawRmSize - (sz.DeltaSize(rawRmSize-extRmSize) - (rawRmSize - extRmSize))\n\t\t\t// It is possible that for the bytes scenario, the extracted field contains no datapoints.\n\t\t\t// Do not add it to the destination if that is the case.\n\t\t\tif dataPointsLen(extSrcDP) > 0 {\n\t\t\t\textSrcDP.MoveTo(destSM.Metrics().AppendEmpty())\n\t\t\t}\n\t\t\treturn dataPointsLen(extSrcDP) != 0\n\t\t}\n\t\tcapacityLeft -= rmSize\n\t\tremovedSize += rmSize\n\t\tsrcSM.MoveTo(destSM.Metrics().AppendEmpty())\n\t\treturn true\n\t})\n\treturn destSM, removedSize\n}\n\nfunc extractMetricDataPoints(srcMetric pmetric.Metric, capacity int, sz sizer.MetricsSizer) (pmetric.Metric, int) {\n\tdestMetric := pmetric.NewMetric()\n\tdestMetric.SetName(srcMetric.Name())\n\tdestMetric.SetDescription(srcMetric.Description())\n\tdestMetric.SetUnit(srcMetric.Unit())\n\tsrcMetric.Metadata().CopyTo(destMetric.Metadata())\n\n\tvar removedSize int\n\tswitch srcMetric.Type() {\n\tcase pmetric.MetricTypeGauge:\n\t\tremovedSize = extractGaugeDataPoints(srcMetric.Gauge(), destMetric, capacity, sz)\n\tcase pmetric.MetricTypeSum:\n\t\tremovedSize = extractSumDataPoints(srcMetric.Sum(), destMetric, capacity, sz)\n\t\tdestMetric.Sum().SetIsMonotonic(srcMetric.Sum().IsMonotonic())\n\t\tdestMetric.Sum().SetAggregationTemporality(srcMetric.Sum().AggregationTemporality())\n\tcase pmetric.MetricTypeHistogram:\n\t\tremovedSize = extractHistogramDataPoints(srcMetric.Histogram(), destMetric, capacity, sz)\n\t\tdestMetric.Histogram().SetAggregationTemporality(srcMetric.Histogram().AggregationTemporality())\n\tcase pmetric.MetricTypeExponentialHistogram:\n\t\tremovedSize = extractExponentialHistogramDataPoints(srcMetric.ExponentialHistogram(), destMetric, capacity, sz)\n\t\tdestMetric.ExponentialHistogram().SetAggregationTemporality(srcMetric.ExponentialHistogram().AggregationTemporality())\n\tcase pmetric.MetricTypeSummary:\n\t\tremovedSize = extractSummaryDataPoints(srcMetric.Summary(), destMetric, capacity, sz)\n\t}\n\treturn destMetric, removedSize\n}\n\nfunc dataPointsLen(m pmetric.Metric) int {\n\tswitch m.Type() {\n\tcase pmetric.MetricTypeGauge:\n\t\treturn m.Gauge().DataPoints().Len()\n\tcase pmetric.MetricTypeSum:\n\t\treturn m.Sum().DataPoints().Len()\n\tcase pmetric.MetricTypeHistogram:\n\t\treturn m.Histogram().DataPoints().Len()\n\tcase pmetric.MetricTypeExponentialHistogram:\n\t\treturn m.ExponentialHistogram().DataPoints().Len()\n\tcase pmetric.MetricTypeSummary:\n\t\treturn m.Summary().DataPoints().Len()\n\t}\n\treturn 0\n}\n\nfunc extractGaugeDataPoints(srcGauge pmetric.Gauge, destMetric pmetric.Metric, capacity int, sz sizer.MetricsSizer) int {\n\tdestGauge := destMetric.SetEmptyGauge()\n\n\t// Take into account that this can have max \"capacity\", so when added to the parent will need space for the extra delta size.\n\tcapacityLeft := capacity - (sz.DeltaSize(capacity) - capacity) - sz.MetricSize(destMetric)\n\tremovedSize := 0\n\n\tsrcGauge.DataPoints().RemoveIf(func(srcDP pmetric.NumberDataPoint) bool {\n\t\t// If the no more capacity left just return.\n\t\tif capacityLeft == 0 {\n\t\t\treturn false\n\t\t}\n\n\t\trdSize := sz.DeltaSize(sz.NumberDataPointSize(srcDP))\n\t\tif rdSize > capacityLeft {\n\t\t\t// This cannot make it to exactly 0 for the bytes,\n\t\t\t// force it to be 0 since that is the stopping condition.\n\t\t\tcapacityLeft = 0\n\t\t\treturn false\n\t\t}\n\t\tcapacityLeft -= rdSize\n\t\tremovedSize += rdSize\n\t\tsrcDP.MoveTo(destGauge.DataPoints().AppendEmpty())\n\t\treturn true\n\t})\n\treturn removedSize\n}\n\nfunc extractSumDataPoints(srcSum pmetric.Sum, destMetric pmetric.Metric, capacity int, sz sizer.MetricsSizer) int {\n\tdestSum := destMetric.SetEmptySum()\n\t// Take into account that this can have max \"capacity\", so when added to the parent will need space for the extra delta size.\n\tcapacityLeft := capacity - (sz.DeltaSize(capacity) - capacity) - sz.MetricSize(destMetric)\n\tremovedSize := 0\n\tsrcSum.DataPoints().RemoveIf(func(srcDP pmetric.NumberDataPoint) bool {\n\t\t// If the no more capacity left just return.\n\t\tif capacityLeft == 0 {\n\t\t\treturn false\n\t\t}\n\n\t\trdSize := sz.DeltaSize(sz.NumberDataPointSize(srcDP))\n\t\tif rdSize > capacityLeft {\n\t\t\t// This cannot make it to exactly 0 for the bytes,\n\t\t\t// force it to be 0 since that is the stopping condition.\n\t\t\tcapacityLeft = 0\n\t\t\treturn false\n\t\t}\n\t\tcapacityLeft -= rdSize\n\t\tremovedSize += rdSize\n\t\tsrcDP.MoveTo(destSum.DataPoints().AppendEmpty())\n\t\treturn true\n\t})\n\treturn removedSize\n}\n\nfunc extractHistogramDataPoints(srcHistogram pmetric.Histogram, destMetric pmetric.Metric, capacity int, sz sizer.MetricsSizer) int {\n\tdestHistogram := destMetric.SetEmptyHistogram()\n\t// Take into account that this can have max \"capacity\", so when added to the parent will need space for the extra delta size.\n\tcapacityLeft := capacity - (sz.DeltaSize(capacity) - capacity) - sz.MetricSize(destMetric)\n\tremovedSize := 0\n\tsrcHistogram.DataPoints().RemoveIf(func(srcDP pmetric.HistogramDataPoint) bool {\n\t\t// If the no more capacity left just return.\n\t\tif capacityLeft == 0 {\n\t\t\treturn false\n\t\t}\n\n\t\trdSize := sz.DeltaSize(sz.HistogramDataPointSize(srcDP))\n\t\tif rdSize > capacityLeft {\n\t\t\t// This cannot make it to exactly 0 for the bytes,\n\t\t\t// force it to be 0 since that is the stopping condition.\n\t\t\tcapacityLeft = 0\n\t\t\treturn false\n\t\t}\n\t\tcapacityLeft -= rdSize\n\t\tremovedSize += rdSize\n\t\tsrcDP.MoveTo(destHistogram.DataPoints().AppendEmpty())\n\t\treturn true\n\t})\n\treturn removedSize\n}\n\nfunc extractExponentialHistogramDataPoints(srcExponentialHistogram pmetric.ExponentialHistogram, destMetric pmetric.Metric, capacity int, sz sizer.MetricsSizer) int {\n\tdestExponentialHistogram := destMetric.SetEmptyExponentialHistogram()\n\t// Take into account that this can have max \"capacity\", so when added to the parent will need space for the extra delta size.\n\tcapacityLeft := capacity - (sz.DeltaSize(capacity) - capacity) - sz.MetricSize(destMetric)\n\tremovedSize := 0\n\tsrcExponentialHistogram.DataPoints().RemoveIf(func(srcDP pmetric.ExponentialHistogramDataPoint) bool {\n\t\t// If the no more capacity left just return.\n\t\tif capacityLeft == 0 {\n\t\t\treturn false\n\t\t}\n\n\t\trdSize := sz.DeltaSize(sz.ExponentialHistogramDataPointSize(srcDP))\n\t\tif rdSize > capacityLeft {\n\t\t\t// This cannot make it to exactly 0 for the bytes,\n\t\t\t// force it to be 0 since that is the stopping condition.\n\t\t\tcapacityLeft = 0\n\t\t\treturn false\n\t\t}\n\t\tcapacityLeft -= rdSize\n\t\tremovedSize += rdSize\n\t\tsrcDP.MoveTo(destExponentialHistogram.DataPoints().AppendEmpty())\n\t\treturn true\n\t})\n\treturn removedSize\n}\n\nfunc extractSummaryDataPoints(srcSummary pmetric.Summary, destMetric pmetric.Metric, capacity int, sz sizer.MetricsSizer) int {\n\tdestSummary := destMetric.SetEmptySummary()\n\t// Take into account that this can have max \"capacity\", so when added to the parent will need space for the extra delta size.\n\tcapacityLeft := capacity - (sz.DeltaSize(capacity) - capacity) - sz.MetricSize(destMetric)\n\tremovedSize := 0\n\tsrcSummary.DataPoints().RemoveIf(func(srcDP pmetric.SummaryDataPoint) bool {\n\t\t// If the no more capacity left just return.\n\t\tif capacityLeft == 0 {\n\t\t\treturn false\n\t\t}\n\n\t\trdSize := sz.DeltaSize(sz.SummaryDataPointSize(srcDP))\n\t\tif rdSize > capacityLeft {\n\t\t\t// This cannot make it to exactly 0 for the bytes,\n\t\t\t// force it to be 0 since that is the stopping condition.\n\t\t\tcapacityLeft = 0\n\t\t\treturn false\n\t\t}\n\t\tcapacityLeft -= rdSize\n\t\tremovedSize += rdSize\n\t\tsrcDP.MoveTo(destSummary.DataPoints().AppendEmpty())\n\t\treturn true\n\t})\n\treturn removedSize\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/metrics_batch_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestMergeMetrics(t *testing.T) {\n\tmr1 := newMetricsRequest(testdata.GenerateMetrics(2))\n\tmr2 := newMetricsRequest(testdata.GenerateMetrics(3))\n\tres, err := mr1.MergeSplit(context.Background(), 0, request.SizerTypeItems, mr2)\n\trequire.NoError(t, err)\n\t// Every metric has 2 data points.\n\tassert.Equal(t, 2*5, res[0].ItemsCount())\n}\n\nfunc TestMergeSplitMetrics(t *testing.T) {\n\ts := sizer.MetricsCountSizer{}\n\ttests := []struct {\n\t\tname     string\n\t\tszt      request.SizerType\n\t\tmaxSize  int\n\t\tmr1      request.Request\n\t\tmr2      request.Request\n\t\texpected []request.Request\n\t}{\n\t\t{\n\t\t\tname:     \"both_requests_empty\",\n\t\t\tszt:      request.SizerTypeItems,\n\t\t\tmaxSize:  10,\n\t\t\tmr1:      newMetricsRequest(pmetric.NewMetrics()),\n\t\t\tmr2:      newMetricsRequest(pmetric.NewMetrics()),\n\t\t\texpected: []request.Request{newMetricsRequest(pmetric.NewMetrics())},\n\t\t},\n\t\t{\n\t\t\tname:     \"first_request_empty\",\n\t\t\tszt:      request.SizerTypeItems,\n\t\t\tmaxSize:  10,\n\t\t\tmr1:      newMetricsRequest(pmetric.NewMetrics()),\n\t\t\tmr2:      newMetricsRequest(testdata.GenerateMetrics(5)),\n\t\t\texpected: []request.Request{newMetricsRequest(testdata.GenerateMetrics(5))},\n\t\t},\n\t\t{\n\t\t\tname:     \"first_empty_second_nil\",\n\t\t\tszt:      request.SizerTypeItems,\n\t\t\tmaxSize:  10,\n\t\t\tmr1:      newMetricsRequest(pmetric.NewMetrics()),\n\t\t\tmr2:      nil,\n\t\t\texpected: []request.Request{newMetricsRequest(pmetric.NewMetrics())},\n\t\t},\n\t\t{\n\t\t\tname:    \"merge_only\",\n\t\t\tszt:     request.SizerTypeItems,\n\t\t\tmaxSize: 60,\n\t\t\tmr1:     newMetricsRequest(testdata.GenerateMetrics(10)),\n\t\t\tmr2:     newMetricsRequest(testdata.GenerateMetrics(14)),\n\t\t\texpected: []request.Request{newMetricsRequest(func() pmetric.Metrics {\n\t\t\t\tmetrics := testdata.GenerateMetrics(10)\n\t\t\t\ttestdata.GenerateMetrics(14).ResourceMetrics().MoveAndAppendTo(metrics.ResourceMetrics())\n\t\t\t\treturn metrics\n\t\t\t}())},\n\t\t},\n\t\t{\n\t\t\tname:    \"split_only\",\n\t\t\tszt:     request.SizerTypeItems,\n\t\t\tmaxSize: 14,\n\t\t\tmr1:     newMetricsRequest(pmetric.NewMetrics()),\n\t\t\tmr2:     newMetricsRequest(testdata.GenerateMetrics(15)), // 15 metrics, 30 data points\n\t\t\texpected: []request.Request{\n\t\t\t\tnewMetricsRequest(testdata.GenerateMetrics(7)), // 7 metrics, 14 data points\n\t\t\t\tnewMetricsRequest(testdata.GenerateMetrics(7)), // 7 metrics, 14 data points\n\t\t\t\tnewMetricsRequest(testdata.GenerateMetrics(1)), // 1 metric, 2 data points\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"split_and_merge\",\n\t\t\tszt:     request.SizerTypeItems,\n\t\t\tmaxSize: 28,\n\t\t\tmr1:     newMetricsRequest(testdata.GenerateMetrics(7)),  // 7 metrics, 14 data points\n\t\t\tmr2:     newMetricsRequest(testdata.GenerateMetrics(25)), // 25 metrics, 50 data points\n\t\t\texpected: []request.Request{\n\t\t\t\tnewMetricsRequest(func() pmetric.Metrics {\n\t\t\t\t\tmetrics := testdata.GenerateMetrics(7)\n\t\t\t\t\ttestdata.GenerateMetrics(7).ResourceMetrics().MoveAndAppendTo(metrics.ResourceMetrics())\n\t\t\t\t\treturn metrics\n\t\t\t\t}()),\n\t\t\t\tnewMetricsRequest(testdata.GenerateMetrics(14)), // 14 metrics, 28 data points\n\t\t\t\tnewMetricsRequest(testdata.GenerateMetrics(4)),  // 4 metrics, 8 data points\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"scope_metrics_split\",\n\t\t\tszt:     request.SizerTypeItems,\n\t\t\tmaxSize: 8,\n\t\t\tmr1: newMetricsRequest(func() pmetric.Metrics {\n\t\t\t\tmd := testdata.GenerateMetrics(4)\n\t\t\t\textraScopeMetrics := md.ResourceMetrics().At(0).ScopeMetrics().AppendEmpty()\n\t\t\t\ttestdata.GenerateMetrics(4).ResourceMetrics().At(0).ScopeMetrics().At(0).MoveTo(extraScopeMetrics)\n\t\t\t\textraScopeMetrics.Scope().SetName(\"extra scope\")\n\t\t\t\treturn md\n\t\t\t}()),\n\t\t\tmr2: nil,\n\t\t\texpected: []request.Request{\n\t\t\t\tnewMetricsRequest(testdata.GenerateMetrics(4)),\n\t\t\t\tnewMetricsRequest(func() pmetric.Metrics {\n\t\t\t\t\tmd := testdata.GenerateMetrics(4)\n\t\t\t\t\tmd.ResourceMetrics().At(0).ScopeMetrics().At(0).Scope().SetName(\"extra scope\")\n\t\t\t\t\treturn md\n\t\t\t\t}()),\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tres, err := tt.mr1.MergeSplit(context.Background(), tt.maxSize, tt.szt, tt.mr2)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Len(t, res, len(tt.expected))\n\t\t\tfor i := range res {\n\t\t\t\texpected := tt.expected[i].(*metricsRequest)\n\t\t\t\tactual := res[i].(*metricsRequest)\n\t\t\t\tassert.Equal(t, expected.size(&s), actual.size(&s))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestSplitMetricsWithDataPointSplit(t *testing.T) {\n\tgenerateTestMetrics := func(metricType pmetric.MetricType) pmetric.Metrics {\n\t\tmd := pmetric.NewMetrics()\n\t\tm := md.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\t\tm.SetName(\"test_metric\")\n\t\tm.SetDescription(\"test_description\")\n\t\tm.SetUnit(\"test_unit\")\n\t\tm.Metadata().PutStr(\"test_metadata_key\", \"test_metadata_value\")\n\n\t\tconst numDataPoints = 2\n\n\t\tswitch metricType {\n\t\tcase pmetric.MetricTypeSum:\n\t\t\tsum := m.SetEmptySum()\n\t\t\tfor i := range numDataPoints {\n\t\t\t\tsum.DataPoints().AppendEmpty().SetIntValue(int64(i + 1))\n\t\t\t}\n\t\tcase pmetric.MetricTypeGauge:\n\t\t\tgauge := m.SetEmptyGauge()\n\t\t\tfor i := range numDataPoints {\n\t\t\t\tgauge.DataPoints().AppendEmpty().SetIntValue(int64(i + 1))\n\t\t\t}\n\t\tcase pmetric.MetricTypeHistogram:\n\t\t\thist := m.SetEmptyHistogram()\n\t\t\tfor i := range uint64(numDataPoints) {\n\t\t\t\thist.DataPoints().AppendEmpty().SetCount(i + 1)\n\t\t\t}\n\t\tcase pmetric.MetricTypeExponentialHistogram:\n\t\t\texpHist := m.SetEmptyExponentialHistogram()\n\t\t\tfor i := range uint64(numDataPoints) {\n\t\t\t\texpHist.DataPoints().AppendEmpty().SetCount(i + 1)\n\t\t\t}\n\t\tcase pmetric.MetricTypeSummary:\n\t\t\tsummary := m.SetEmptySummary()\n\t\t\tfor i := range uint64(numDataPoints) {\n\t\t\t\tsummary.DataPoints().AppendEmpty().SetCount(i + 1)\n\t\t\t}\n\t\t}\n\t\treturn md\n\t}\n\n\ttests := []struct {\n\t\tname       string\n\t\tmetricType pmetric.MetricType\n\t}{\n\t\t{\n\t\t\tname:       \"sum\",\n\t\t\tmetricType: pmetric.MetricTypeSum,\n\t\t},\n\t\t{\n\t\t\tname:       \"gauge\",\n\t\t\tmetricType: pmetric.MetricTypeGauge,\n\t\t},\n\t\t{\n\t\t\tname:       \"histogram\",\n\t\t\tmetricType: pmetric.MetricTypeHistogram,\n\t\t},\n\t\t{\n\t\t\tname:       \"exponential_histogram\",\n\t\t\tmetricType: pmetric.MetricTypeExponentialHistogram,\n\t\t},\n\t\t{\n\t\t\tname:       \"summary\",\n\t\t\tmetricType: pmetric.MetricTypeSummary,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// Generate metrics with 2 data points.\n\t\t\tmr1 := newMetricsRequest(generateTestMetrics(tt.metricType))\n\n\t\t\t// Split by data point, so maxSize is 1.\n\t\t\tres, err := mr1.MergeSplit(context.Background(), 1, request.SizerTypeItems, nil)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Len(t, res, 2)\n\n\t\t\tfor _, req := range res {\n\t\t\t\tactualRequest := req.(*metricsRequest)\n\t\t\t\t// Each split request should contain one data point.\n\t\t\t\tassert.Equal(t, 1, actualRequest.ItemsCount())\n\t\t\t\tm := actualRequest.md.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0)\n\t\t\t\tassert.Equal(t, \"test_metric\", m.Name())\n\t\t\t\tassert.Equal(t, \"test_description\", m.Description())\n\t\t\t\tassert.Equal(t, \"test_unit\", m.Unit())\n\t\t\t\tassert.Equal(t, 1, m.Metadata().Len())\n\t\t\t\tval, ok := m.Metadata().Get(\"test_metadata_key\")\n\t\t\t\tassert.True(t, ok)\n\t\t\t\tassert.Equal(t, \"test_metadata_value\", val.AsString())\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMergeSplitMetricsInputNotModifiedIfErrorReturned(t *testing.T) {\n\tr1 := newMetricsRequest(testdata.GenerateMetrics(18)) // 18 metrics, 36 data points\n\tr2 := newLogsRequest(testdata.GenerateLogs(3))\n\t_, err := r1.MergeSplit(context.Background(), 10, request.SizerTypeItems, r2)\n\trequire.Error(t, err)\n\tassert.Equal(t, 36, r1.ItemsCount())\n}\n\nfunc TestExtractMetrics(t *testing.T) {\n\tfor i := range 20 {\n\t\tmd := testdata.GenerateMetrics(10)\n\t\textractedMetrics, _ := extractMetrics(md, i, &sizer.MetricsCountSizer{})\n\t\tassert.Equal(t, i, extractedMetrics.DataPointCount())\n\t\tassert.Equal(t, 20-i, md.DataPointCount())\n\t}\n}\n\nfunc TestExtractMetricsInvalidMetric(t *testing.T) {\n\tmd := testdata.GenerateMetricsMetricTypeInvalid()\n\textractedMetrics, _ := extractMetrics(md, 10, &sizer.MetricsCountSizer{})\n\tassert.Equal(t, testdata.GenerateMetricsMetricTypeInvalid(), extractedMetrics)\n\tassert.Equal(t, 0, md.ResourceMetrics().Len())\n}\n\nfunc TestMergeSplitManySmallMetrics(t *testing.T) {\n\t// All requests merge into a single batch.\n\tmerged := []request.Request{newMetricsRequest(testdata.GenerateMetrics(1))}\n\tfor range 1000 {\n\t\tlr2 := newMetricsRequest(testdata.GenerateMetrics(10))\n\t\tres, _ := merged[len(merged)-1].MergeSplit(context.Background(), 20000, request.SizerTypeItems, lr2)\n\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t}\n\tassert.Len(t, merged, 2)\n}\n\nfunc BenchmarkSplittingBasedOnItemCountManySmallMetrics(b *testing.B) {\n\ttestutil.SkipGCHeavyBench(b)\n\t// All requests merge into a single batch.\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tmerged := []request.Request{newMetricsRequest(testdata.GenerateMetrics(10))}\n\t\tfor range 1000 {\n\t\t\tlr2 := newMetricsRequest(testdata.GenerateMetrics(10))\n\t\t\tres, _ := merged[len(merged)-1].MergeSplit(context.Background(), 20020, request.SizerTypeItems, lr2)\n\t\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t\t}\n\t\tassert.Len(b, merged, 1)\n\t}\n}\n\nfunc BenchmarkSplittingBasedOnItemCountManyMetricsSlightlyAboveLimit(b *testing.B) {\n\ttestutil.SkipGCHeavyBench(b)\n\t// Every incoming request results in a split.\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tmerged := []request.Request{newMetricsRequest(testdata.GenerateMetrics(0))}\n\t\tfor range 10 {\n\t\t\tlr2 := newMetricsRequest(testdata.GenerateMetrics(10001))\n\t\t\tres, _ := merged[len(merged)-1].MergeSplit(context.Background(), 20000, request.SizerTypeItems, lr2)\n\t\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t\t}\n\t\tassert.Len(b, merged, 11)\n\t}\n}\n\nfunc BenchmarkSplittingBasedOnItemCountHugeMetrics(b *testing.B) {\n\ttestutil.SkipGCHeavyBench(b)\n\t// One request splits into many batches.\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tmerged := []request.Request{newMetricsRequest(testdata.GenerateMetrics(0))}\n\t\tlr2 := newMetricsRequest(testdata.GenerateMetrics(100000))\n\t\tres, _ := merged[len(merged)-1].MergeSplit(context.Background(), 20000, request.SizerTypeItems, lr2)\n\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t\tassert.Len(b, merged, 10)\n\t}\n}\n\nfunc TestMergeSplitMetricsBasedOnByteSize(t *testing.T) {\n\ttests := []struct {\n\t\tname             string\n\t\tszt              request.SizerType\n\t\tmaxSize          int\n\t\tmr1              request.Request\n\t\tmr2              request.Request\n\t\texpected         []request.Request\n\t\texpectSplitError bool\n\t}{\n\t\t{\n\t\t\tname:     \"both_requests_empty\",\n\t\t\tszt:      request.SizerTypeBytes,\n\t\t\tmaxSize:  metricsMarshaler.MetricsSize(testdata.GenerateMetrics(10)),\n\t\t\tmr1:      newMetricsRequest(pmetric.NewMetrics()),\n\t\t\tmr2:      newMetricsRequest(pmetric.NewMetrics()),\n\t\t\texpected: []request.Request{newMetricsRequest(pmetric.NewMetrics())},\n\t\t},\n\t\t{\n\t\t\tname:     \"first_request_empty\",\n\t\t\tszt:      request.SizerTypeBytes,\n\t\t\tmaxSize:  metricsMarshaler.MetricsSize(testdata.GenerateMetrics(10)),\n\t\t\tmr1:      newMetricsRequest(pmetric.NewMetrics()),\n\t\t\tmr2:      newMetricsRequest(testdata.GenerateMetrics(5)),\n\t\t\texpected: []request.Request{newMetricsRequest(testdata.GenerateMetrics(5))},\n\t\t},\n\t\t{\n\t\t\tname:     \"first_empty_second_nil\",\n\t\t\tszt:      request.SizerTypeBytes,\n\t\t\tmaxSize:  metricsMarshaler.MetricsSize(testdata.GenerateMetrics(10)),\n\t\t\tmr1:      newMetricsRequest(pmetric.NewMetrics()),\n\t\t\tmr2:      nil,\n\t\t\texpected: []request.Request{newMetricsRequest(pmetric.NewMetrics())},\n\t\t},\n\t\t{\n\t\t\tname:    \"merge_only\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: metricsMarshaler.MetricsSize(testdata.GenerateMetrics(15)) - 1,\n\t\t\tmr1:     newMetricsRequest(testdata.GenerateMetrics(7)),\n\t\t\tmr2:     newMetricsRequest(testdata.GenerateMetrics(7)),\n\t\t\texpected: []request.Request{newMetricsRequest(func() pmetric.Metrics {\n\t\t\t\tmd := testdata.GenerateMetrics(7)\n\t\t\t\ttestdata.GenerateMetrics(7).ResourceMetrics().MoveAndAppendTo(md.ResourceMetrics())\n\t\t\t\treturn md\n\t\t\t}())},\n\t\t},\n\t\t{\n\t\t\tname:    \"split_only\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: metricsMarshaler.MetricsSize(testdata.GenerateMetrics(7)) + 1,\n\t\t\tmr1:     newMetricsRequest(pmetric.NewMetrics()),\n\t\t\tmr2:     newMetricsRequest(testdata.GenerateMetrics(17)),\n\t\t\texpected: []request.Request{\n\t\t\t\tnewMetricsRequest(testdata.GenerateMetrics(7)),\n\t\t\t\tnewMetricsRequest(testdata.GenerateMetrics(7)),\n\t\t\t\tnewMetricsRequest(testdata.GenerateMetrics(3)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"merge_and_split\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: metricsMarshaler.MetricsSize(testdata.GenerateMetrics(7)) + 1,\n\t\t\tmr1:     newMetricsRequest(testdata.GenerateMetrics(14)),\n\t\t\tmr2:     newMetricsRequest(testdata.GenerateMetrics(11)),\n\t\t\texpected: []request.Request{\n\t\t\t\tnewMetricsRequest(testdata.GenerateMetrics(7)),\n\t\t\t\tnewMetricsRequest(testdata.GenerateMetrics(7)),\n\t\t\t\tnewMetricsRequest(testdata.GenerateMetrics(7)),\n\t\t\t\tnewMetricsRequest(testdata.GenerateMetrics(4)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"scope_metrics_split\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: metricsMarshaler.MetricsSize(testdata.GenerateMetrics(7)) + 1,\n\t\t\tmr1: newMetricsRequest(func() pmetric.Metrics {\n\t\t\t\tmd := testdata.GenerateMetrics(7)\n\t\t\t\textraScopeMetrics := md.ResourceMetrics().At(0).ScopeMetrics().AppendEmpty()\n\t\t\t\ttestdata.GenerateMetrics(7).ResourceMetrics().At(0).ScopeMetrics().At(0).MoveTo(extraScopeMetrics)\n\t\t\t\textraScopeMetrics.Scope().SetName(\"extra scope\")\n\t\t\t\treturn md\n\t\t\t}()),\n\t\t\tmr2: nil,\n\t\t\texpected: []request.Request{\n\t\t\t\tnewMetricsRequest(testdata.GenerateMetrics(7)),\n\t\t\t\tnewMetricsRequest(func() pmetric.Metrics {\n\t\t\t\t\tmd := testdata.GenerateMetrics(7)\n\t\t\t\t\tmd.ResourceMetrics().At(0).ScopeMetrics().At(0).Scope().SetName(\"extra scope\")\n\t\t\t\t\t// Remove last data point.\n\t\t\t\t\tlastDP := md.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(6).Summary().DataPoints().Len()\n\t\t\t\t\tidx := 0\n\t\t\t\t\tmd.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(6).Summary().DataPoints().RemoveIf(func(pmetric.SummaryDataPoint) bool {\n\t\t\t\t\t\tidx++\n\t\t\t\t\t\treturn idx == lastDP\n\t\t\t\t\t})\n\t\t\t\t\treturn md\n\t\t\t\t}()),\n\t\t\t\tnewMetricsRequest(func() pmetric.Metrics {\n\t\t\t\t\tmd := testdata.GenerateMetrics(7)\n\t\t\t\t\tmd.ResourceMetrics().At(0).ScopeMetrics().At(0).Scope().SetName(\"extra scope\")\n\t\t\t\t\t// Remove all metrics but last one\n\t\t\t\t\tlastM := md.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().Len()\n\t\t\t\t\tidx := 0\n\t\t\t\t\tmd.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().RemoveIf(func(pmetric.Metric) bool {\n\t\t\t\t\t\tidx++\n\t\t\t\t\t\treturn idx != lastM\n\t\t\t\t\t})\n\t\t\t\t\t// Remove all data points but last one\n\t\t\t\t\tlastDP := md.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Summary().DataPoints().Len()\n\t\t\t\t\tidx = 0\n\t\t\t\t\tmd.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Summary().DataPoints().RemoveIf(func(pmetric.SummaryDataPoint) bool {\n\t\t\t\t\t\tidx++\n\t\t\t\t\t\treturn idx != lastDP\n\t\t\t\t\t})\n\t\t\t\t\treturn md\n\t\t\t\t}()),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"unsplittable_large_metric\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: 10,\n\t\t\tmr1: newMetricsRequest(func() pmetric.Metrics {\n\t\t\t\tmd := testdata.GenerateMetrics(1)\n\t\t\t\tmd.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).SetDescription(string(make([]byte, 100)))\n\t\t\t\treturn md\n\t\t\t}()),\n\t\t\tmr2:              nil,\n\t\t\texpected:         []request.Request{},\n\t\t\texpectSplitError: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"splittable_then_unsplittable_metric\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: 1000,\n\t\t\tmr1: newMetricsRequest(func() pmetric.Metrics {\n\t\t\t\tmd := testdata.GenerateMetrics(2)\n\t\t\t\tmd.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).SetDescription(string(make([]byte, 10)))\n\t\t\t\tmd.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(1).SetDescription(string(make([]byte, 1001)))\n\t\t\t\treturn md\n\t\t\t}()),\n\t\t\tmr2: nil,\n\t\t\texpected: []request.Request{newMetricsRequest(func() pmetric.Metrics {\n\t\t\t\tmd := testdata.GenerateMetrics(1)\n\t\t\t\tmd.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).SetDescription(string(make([]byte, 10)))\n\t\t\t\treturn md\n\t\t\t}())},\n\t\t\texpectSplitError: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tres, err := tt.mr1.MergeSplit(context.Background(), tt.maxSize, tt.szt, tt.mr2)\n\t\t\tif tt.expectSplitError {\n\t\t\t\trequire.ErrorContains(t, err, \"one datapoint size is greater than max size, dropping items:\")\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\t\t\trequire.Len(t, res, len(tt.expected))\n\t\t\tfor i := range res {\n\t\t\t\tassert.Equal(t, tt.expected[i].(*metricsRequest).md, res[i].(*metricsRequest).md, i)\n\t\t\t\tassert.Equal(t,\n\t\t\t\t\tmetricsMarshaler.MetricsSize(tt.expected[i].(*metricsRequest).md),\n\t\t\t\t\tmetricsMarshaler.MetricsSize(res[i].(*metricsRequest).md))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestExtractGaugeDataPoints(t *testing.T) {\n\ttests := []struct {\n\t\tname           string\n\t\tcapacity       int\n\t\tnumDataPoints  int\n\t\texpectedPoints int\n\t}{\n\t\t{\n\t\t\tname:           \"extract_all_points\",\n\t\t\tcapacity:       100,\n\t\t\tnumDataPoints:  2,\n\t\t\texpectedPoints: 2,\n\t\t},\n\t\t{\n\t\t\tname:           \"extract_partial_points\",\n\t\t\tcapacity:       1,\n\t\t\tnumDataPoints:  2,\n\t\t\texpectedPoints: 1,\n\t\t},\n\t\t{\n\t\t\tname:           \"no_capacity\",\n\t\t\tcapacity:       0,\n\t\t\tnumDataPoints:  2,\n\t\t\texpectedPoints: 0,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsrcMetric := pmetric.NewMetric()\n\t\t\tgauge := srcMetric.SetEmptyGauge()\n\t\t\tfor i := 0; i < tt.numDataPoints; i++ {\n\t\t\t\tdp := gauge.DataPoints().AppendEmpty()\n\t\t\t\tdp.SetIntValue(int64(i))\n\t\t\t}\n\n\t\t\tsz := &mockMetricsSizer{dpSize: 1}\n\n\t\t\tdestMetric := pmetric.NewMetric()\n\t\t\tremovedSize := extractGaugeDataPoints(gauge, destMetric, tt.capacity, sz)\n\n\t\t\tassert.Equal(t, tt.expectedPoints, destMetric.Gauge().DataPoints().Len())\n\t\t\tif tt.expectedPoints > 0 {\n\t\t\t\tassert.Equal(t, tt.expectedPoints, removedSize)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestExtractSumDataPoints(t *testing.T) {\n\ttests := []struct {\n\t\tname           string\n\t\tcapacity       int\n\t\tnumDataPoints  int\n\t\texpectedPoints int\n\t}{\n\t\t{\n\t\t\tname:           \"extract_all_points\",\n\t\t\tcapacity:       100,\n\t\t\tnumDataPoints:  2,\n\t\t\texpectedPoints: 2,\n\t\t},\n\t\t{\n\t\t\tname:           \"extract_partial_points\",\n\t\t\tcapacity:       1,\n\t\t\tnumDataPoints:  2,\n\t\t\texpectedPoints: 1,\n\t\t},\n\t\t{\n\t\t\tname:           \"no_capacity\",\n\t\t\tcapacity:       0,\n\t\t\tnumDataPoints:  2,\n\t\t\texpectedPoints: 0,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsrcMetric := pmetric.NewMetric()\n\t\t\tsum := srcMetric.SetEmptySum()\n\t\t\tfor i := 0; i < tt.numDataPoints; i++ {\n\t\t\t\tdp := sum.DataPoints().AppendEmpty()\n\t\t\t\tdp.SetIntValue(int64(i))\n\t\t\t}\n\n\t\t\tsz := &mockMetricsSizer{dpSize: 1}\n\n\t\t\tdestMetric := pmetric.NewMetric()\n\t\t\tremovedSize := extractSumDataPoints(sum, destMetric, tt.capacity, sz)\n\n\t\t\tassert.Equal(t, tt.expectedPoints, destMetric.Sum().DataPoints().Len())\n\t\t\tif tt.expectedPoints > 0 {\n\t\t\t\tassert.Equal(t, tt.expectedPoints, removedSize)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestExtractHistogramDataPoints(t *testing.T) {\n\ttests := []struct {\n\t\tname           string\n\t\tcapacity       int\n\t\tnumDataPoints  int\n\t\texpectedPoints int\n\t}{\n\t\t{\n\t\t\tname:           \"extract_all_points\",\n\t\t\tcapacity:       100,\n\t\t\tnumDataPoints:  2,\n\t\t\texpectedPoints: 2,\n\t\t},\n\t\t{\n\t\t\tname:           \"extract_partial_points\",\n\t\t\tcapacity:       1,\n\t\t\tnumDataPoints:  2,\n\t\t\texpectedPoints: 1,\n\t\t},\n\t\t{\n\t\t\tname:           \"no_capacity\",\n\t\t\tcapacity:       0,\n\t\t\tnumDataPoints:  2,\n\t\t\texpectedPoints: 0,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsrcMetric := pmetric.NewMetric()\n\t\t\thistogram := srcMetric.SetEmptyHistogram()\n\n\t\t\tfor i := 0; i < tt.numDataPoints; i++ {\n\t\t\t\tdp := histogram.DataPoints().AppendEmpty()\n\t\t\t\tdp.SetCount(uint64(i))\n\t\t\t}\n\n\t\t\tsz := &mockMetricsSizer{dpSize: 1}\n\n\t\t\tdestMetric := pmetric.NewMetric()\n\t\t\tremovedSize := extractHistogramDataPoints(histogram, destMetric, tt.capacity, sz)\n\n\t\t\tassert.Equal(t, tt.expectedPoints, destMetric.Histogram().DataPoints().Len())\n\t\t\tif tt.expectedPoints > 0 {\n\t\t\t\tassert.Equal(t, tt.expectedPoints, removedSize)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestExtractExponentialHistogramDataPoints(t *testing.T) {\n\ttests := []struct {\n\t\tname           string\n\t\tcapacity       int\n\t\tnumDataPoints  int\n\t\texpectedPoints int\n\t}{\n\t\t{\n\t\t\tname:           \"extract_all_points\",\n\t\t\tcapacity:       100,\n\t\t\tnumDataPoints:  2,\n\t\t\texpectedPoints: 2,\n\t\t},\n\t\t{\n\t\t\tname:           \"extract_partial_points\",\n\t\t\tcapacity:       1,\n\t\t\tnumDataPoints:  2,\n\t\t\texpectedPoints: 1,\n\t\t},\n\t\t{\n\t\t\tname:           \"no_capacity\",\n\t\t\tcapacity:       0,\n\t\t\tnumDataPoints:  2,\n\t\t\texpectedPoints: 0,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsrcMetric := pmetric.NewMetric()\n\t\t\texpHistogram := srcMetric.SetEmptyExponentialHistogram()\n\t\t\tfor i := 0; i < tt.numDataPoints; i++ {\n\t\t\t\tdp := expHistogram.DataPoints().AppendEmpty()\n\t\t\t\tdp.SetCount(uint64(i))\n\t\t\t}\n\n\t\t\tsz := &mockMetricsSizer{dpSize: 1}\n\n\t\t\tdestMetric := pmetric.NewMetric()\n\t\t\tremovedSize := extractExponentialHistogramDataPoints(expHistogram, destMetric, tt.capacity, sz)\n\n\t\t\tassert.Equal(t, tt.expectedPoints, destMetric.ExponentialHistogram().DataPoints().Len())\n\t\t\tif tt.expectedPoints > 0 {\n\t\t\t\tassert.Equal(t, tt.expectedPoints, removedSize)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestExtractSummaryDataPoints(t *testing.T) {\n\ttests := []struct {\n\t\tname           string\n\t\tcapacity       int\n\t\tnumDataPoints  int\n\t\texpectedPoints int\n\t}{\n\t\t{\n\t\t\tname:           \"extract_all_points\",\n\t\t\tcapacity:       100,\n\t\t\tnumDataPoints:  2,\n\t\t\texpectedPoints: 2,\n\t\t},\n\t\t{\n\t\t\tname:           \"extract_partial_points\",\n\t\t\tcapacity:       1,\n\t\t\tnumDataPoints:  2,\n\t\t\texpectedPoints: 1,\n\t\t},\n\t\t{\n\t\t\tname:           \"no_capacity\",\n\t\t\tcapacity:       0,\n\t\t\tnumDataPoints:  2,\n\t\t\texpectedPoints: 0,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsrcMetric := pmetric.NewMetric()\n\t\t\tsummary := srcMetric.SetEmptySummary()\n\t\t\tfor i := 0; i < tt.numDataPoints; i++ {\n\t\t\t\tdp := summary.DataPoints().AppendEmpty()\n\t\t\t\tdp.SetCount(uint64(i))\n\t\t\t}\n\n\t\t\tsz := &mockMetricsSizer{dpSize: 1}\n\n\t\t\tdestMetric := pmetric.NewMetric()\n\t\t\tremovedSize := extractSummaryDataPoints(summary, destMetric, tt.capacity, sz)\n\n\t\t\tassert.Equal(t, tt.expectedPoints, destMetric.Summary().DataPoints().Len())\n\t\t\tif tt.expectedPoints > 0 {\n\t\t\t\tassert.Equal(t, tt.expectedPoints, removedSize)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMetricsMergeSplitUnknownSizerType(t *testing.T) {\n\treq := newMetricsRequest(pmetric.NewMetrics())\n\t// Call MergeSplit with invalid sizer\n\t_, err := req.MergeSplit(context.Background(), 0, request.SizerType{}, nil)\n\trequire.EqualError(t, err, \"unknown sizer type\")\n}\n\n// mockMetricsSizer implements sizer.MetricsSizer interface for testing\ntype mockMetricsSizer struct {\n\tdpSize int\n}\n\nfunc (m *mockMetricsSizer) MetricsSize(_ pmetric.Metrics) int {\n\treturn 0\n}\n\nfunc (m *mockMetricsSizer) MetricSize(_ pmetric.Metric) int {\n\treturn 0\n}\n\nfunc (m *mockMetricsSizer) NumberDataPointSize(_ pmetric.NumberDataPoint) int {\n\treturn m.dpSize\n}\n\nfunc (m *mockMetricsSizer) HistogramDataPointSize(_ pmetric.HistogramDataPoint) int {\n\treturn m.dpSize\n}\n\nfunc (m *mockMetricsSizer) ExponentialHistogramDataPointSize(_ pmetric.ExponentialHistogramDataPoint) int {\n\treturn m.dpSize\n}\n\nfunc (m *mockMetricsSizer) SummaryDataPointSize(_ pmetric.SummaryDataPoint) int {\n\treturn m.dpSize\n}\n\nfunc (m *mockMetricsSizer) ResourceMetricsSize(_ pmetric.ResourceMetrics) int {\n\treturn 0\n}\n\nfunc (m *mockMetricsSizer) ScopeMetricsSize(_ pmetric.ScopeMetrics) int {\n\treturn 0\n}\n\nfunc (m *mockMetricsSizer) DeltaSize(size int) int {\n\treturn size\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/metrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestMetricsRequest(t *testing.T) {\n\tmr := newMetricsRequest(testdata.GenerateMetrics(1))\n\n\tmetricsErr := consumererror.NewMetrics(errors.New(\"some error\"), pmetric.NewMetrics())\n\tassert.Equal(\n\t\tt,\n\t\tnewMetricsRequest(pmetric.NewMetrics()),\n\t\tmr.(request.ErrorHandler).OnError(metricsErr),\n\t)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/multi_batcher.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\nimport (\n\t\"context\"\n\t\"sync\"\n\n\tlru \"github.com/hashicorp/golang-lru/v2/simplelru\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender\"\n)\n\ntype multiBatcher struct {\n\tcfg         BatchConfig\n\twp          *workerPool\n\tsizer       request.Sizer\n\tpartitioner Partitioner[request.Request]\n\tmergeCtx    func(context.Context, context.Context) context.Context\n\tconsumeFunc sender.SendFunc[request.Request]\n\tpartitions  *lru.LRU[string, *partitionBatcher]\n\tlogger      *zap.Logger\n\tlock        sync.Mutex\n}\n\nfunc newMultiBatcher(\n\tbCfg BatchConfig,\n\tsizer request.Sizer,\n\twp *workerPool,\n\tpartitioner Partitioner[request.Request],\n\tmergeCtx func(context.Context, context.Context) context.Context,\n\tnext sender.SendFunc[request.Request],\n\tlogger *zap.Logger,\n) (*multiBatcher, error) {\n\tmb := &multiBatcher{\n\t\tcfg:         bCfg,\n\t\twp:          wp,\n\t\tsizer:       sizer,\n\t\tpartitioner: partitioner,\n\t\tmergeCtx:    mergeCtx,\n\t\tconsumeFunc: next,\n\t\tlogger:      logger,\n\t}\n\n\t// Create LRU cache with eviction callback\n\t// TODO: make maxActivePartitionsCount configurable\n\tcache, err := lru.NewLRU[string, *partitionBatcher](10000, func(_ string, pb *partitionBatcher) {\n\t\t// Flush the partition when evicted\n\t\tmb.wp.execute(pb.shutdownInternal)\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tmb.partitions = cache\n\treturn mb, nil\n}\n\nfunc (mb *multiBatcher) getPartition(ctx context.Context, req request.Request) *partitionBatcher {\n\tkey := mb.partitioner.GetKey(ctx, req)\n\n\tmb.lock.Lock()\n\tdefer mb.lock.Unlock()\n\n\t// Fast path: partition already exists\n\tif pb, ok := mb.partitions.Get(key); ok {\n\t\treturn pb\n\t}\n\n\t// Create new partition with onEmpty callback to remove from LRU after idle timeout\n\tnewPB := newPartitionBatcher(mb.cfg, mb.sizer, mb.mergeCtx, mb.wp, mb.consumeFunc, mb.logger, func() {\n\t\tmb.lock.Lock()\n\t\tdefer mb.lock.Unlock()\n\t\tmb.partitions.Remove(key)\n\t})\n\t_ = mb.partitions.Add(key, newPB)\n\t_ = newPB.Start(ctx, nil)\n\treturn newPB\n}\n\nfunc (mb *multiBatcher) Start(context.Context, component.Host) error {\n\treturn nil\n}\n\nfunc (mb *multiBatcher) Consume(ctx context.Context, req request.Request, done queue.Done) {\n\tshard := mb.getPartition(ctx, req)\n\tshard.Consume(ctx, req, done)\n}\n\n// getActivePartitionsCount is test only method\nfunc (mb *multiBatcher) getActivePartitionsCount() int64 {\n\tmb.lock.Lock()\n\tdefer mb.lock.Unlock()\n\treturn int64(mb.partitions.Len())\n}\n\nfunc (mb *multiBatcher) Shutdown(ctx context.Context) error {\n\tvar wg sync.WaitGroup\n\tmb.lock.Lock()\n\tdefer mb.lock.Unlock()\n\tfor _, key := range mb.partitions.Keys() {\n\t\tif pb, ok := mb.partitions.Peek(key); ok {\n\t\t\twg.Go(func() {\n\t\t\t\t_ = pb.Shutdown(ctx)\n\t\t\t})\n\t\t}\n\t}\n\twg.Wait()\n\tmb.partitions.Purge()\n\treturn nil\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/multi_batcher_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n)\n\nfunc TestMultiBatcher_NoTimeout(t *testing.T) {\n\tcfg := BatchConfig{\n\t\tFlushTimeout: 0,\n\t\tSizer:        request.SizerTypeItems,\n\t\tMinSize:      10,\n\t}\n\tsink := requesttest.NewSink()\n\n\ttype partitionKey struct{}\n\n\tba, err := newMultiBatcher(cfg,\n\t\trequest.NewItemsSizer(),\n\t\tnewWorkerPool(1),\n\t\tNewPartitioner(func(ctx context.Context, _ request.Request) string {\n\t\t\treturn ctx.Value(partitionKey{}).(string)\n\t\t}),\n\t\tnil,\n\t\tsink.Export,\n\t\tzap.NewNop(),\n\t)\n\n\trequire.NoError(t, err)\n\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, ba.Shutdown(context.Background()))\n\t})\n\n\tdone := newFakeDone()\n\tassert.Equal(t, int64(0), ba.getActivePartitionsCount())\n\tba.Consume(context.WithValue(context.Background(), partitionKey{}, \"p1\"), &requesttest.FakeRequest{Items: 8}, done)\n\tassert.Equal(t, int64(1), ba.getActivePartitionsCount())\n\tba.Consume(context.WithValue(context.Background(), partitionKey{}, \"p2\"), &requesttest.FakeRequest{Items: 6}, done)\n\tassert.Equal(t, int64(2), ba.getActivePartitionsCount())\n\n\t// Neither batch should be flushed since they haven't reached min threshold.\n\tassert.Equal(t, 0, sink.RequestsCount())\n\tassert.Equal(t, 0, sink.ItemsCount())\n\n\tba.Consume(context.WithValue(context.Background(), partitionKey{}, \"p1\"), &requesttest.FakeRequest{Items: 8}, done)\n\n\tassert.Eventually(t, func() bool {\n\t\treturn sink.RequestsCount() == 1 && sink.ItemsCount() == 16\n\t}, 500*time.Millisecond, 10*time.Millisecond)\n\n\tba.Consume(context.WithValue(context.Background(), partitionKey{}, \"p2\"), &requesttest.FakeRequest{Items: 6}, done)\n\n\tassert.Eventually(t, func() bool {\n\t\treturn sink.RequestsCount() == 2 && sink.ItemsCount() == 28\n\t}, 500*time.Millisecond, 10*time.Millisecond)\n\n\t// Check that done callback is called for the right amount of times.\n\tassert.EqualValues(t, 0, done.errors.Load())\n\tassert.EqualValues(t, 4, done.success.Load())\n\n\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n}\n\nfunc TestMultiBatcher_Timeout(t *testing.T) {\n\tcfg := BatchConfig{\n\t\tFlushTimeout: 100 * time.Millisecond,\n\t\tSizer:        request.SizerTypeItems,\n\t\tMinSize:      100,\n\t}\n\tsink := requesttest.NewSink()\n\n\ttype partitionKey struct{}\n\n\tba, err := newMultiBatcher(cfg,\n\t\trequest.NewItemsSizer(),\n\t\tnewWorkerPool(1),\n\t\tNewPartitioner(func(ctx context.Context, _ request.Request) string {\n\t\t\treturn ctx.Value(partitionKey{}).(string)\n\t\t}),\n\t\tnil,\n\t\tsink.Export,\n\t\tzap.NewNop(),\n\t)\n\n\trequire.NoError(t, err)\n\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, ba.Shutdown(context.Background()))\n\t})\n\n\tdone := newFakeDone()\n\tba.Consume(context.WithValue(context.Background(), partitionKey{}, \"p1\"), &requesttest.FakeRequest{Items: 8}, done)\n\tba.Consume(context.WithValue(context.Background(), partitionKey{}, \"p2\"), &requesttest.FakeRequest{Items: 6}, done)\n\n\t// Neither batch should be flushed since they haven't reached min threshold.\n\tassert.Equal(t, 0, sink.RequestsCount())\n\tassert.Equal(t, 0, sink.ItemsCount())\n\n\tba.Consume(context.WithValue(context.Background(), partitionKey{}, \"p1\"), &requesttest.FakeRequest{Items: 8}, done)\n\tba.Consume(context.WithValue(context.Background(), partitionKey{}, \"p2\"), &requesttest.FakeRequest{Items: 6}, done)\n\n\tassert.Eventually(t, func() bool {\n\t\treturn sink.RequestsCount() == 2 && sink.ItemsCount() == 28\n\t}, 1*time.Second, 10*time.Millisecond)\n\t// Check that done callback is called for the right amount of times.\n\tassert.EqualValues(t, 0, done.errors.Load())\n\tassert.EqualValues(t, 4, done.success.Load())\n\n\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n}\n\nfunc TestMultiBatcher_PartitionRemovedAfterIdleTimeout(t *testing.T) {\n\t// Use a short FlushTimeout so the idle threshold (partitionIdleCycles*FlushTimeout) is reached quickly.\n\tcfg := BatchConfig{\n\t\tFlushTimeout: 10 * time.Millisecond,\n\t\tSizer:        request.SizerTypeItems,\n\t\tMinSize:      100, // High min size to prevent immediate flush\n\t}\n\tsink := requesttest.NewSink()\n\n\ttype partitionKey struct{}\n\n\tba, err := newMultiBatcher(cfg,\n\t\trequest.NewItemsSizer(),\n\t\tnewWorkerPool(1),\n\t\tNewPartitioner(func(ctx context.Context, _ request.Request) string {\n\t\t\treturn ctx.Value(partitionKey{}).(string)\n\t\t}),\n\t\tnil,\n\t\tsink.Export,\n\t\tzap.NewNop(),\n\t)\n\n\trequire.NoError(t, err)\n\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, ba.Shutdown(context.Background()))\n\t})\n\n\tdone := newFakeDone()\n\n\t// Create a partition\n\tba.Consume(context.WithValue(context.Background(), partitionKey{}, \"p1\"), &requesttest.FakeRequest{Items: 5}, done)\n\tassert.Equal(t, int64(1), ba.getActivePartitionsCount())\n\n\t// Wait for the batch to flush via timeout\n\tassert.Eventually(t, func() bool {\n\t\treturn sink.RequestsCount() == 1\n\t}, 500*time.Millisecond, 10*time.Millisecond)\n\n\t// Wait for idle timeout (partitionIdleCycles * FlushTimeout = 10 * 10ms = 100ms)\n\t// After this, the partition should be removed from the LRU cache.\n\tassert.Eventually(t, func() bool {\n\t\treturn ba.getActivePartitionsCount() == 0\n\t}, 500*time.Millisecond, 10*time.Millisecond)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/partition_batcher.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\t\"go.uber.org/multierr\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender\"\n)\n\n// partitionIdleCycles*FlushTimeout is the duration after which an empty partition is removed.\n// TODO make this configurable.\nconst partitionIdleCycles = 10\n\nvar _ Batcher[request.Request] = (*partitionBatcher)(nil)\n\ntype batch struct {\n\tctx  context.Context\n\treq  request.Request\n\tdone multiDone\n}\n\n// partitionBatcher continuously batch incoming requests and flushes asynchronously if minimum size limit is met or on timeout.\ntype partitionBatcher struct {\n\tcfg            BatchConfig\n\twp             *workerPool\n\tsizer          request.Sizer\n\tmergeCtx       func(context.Context, context.Context) context.Context\n\tconsumeFunc    sender.SendFunc[request.Request]\n\tstopWG         sync.WaitGroup\n\tcurrentBatchMu sync.Mutex\n\tcurrentBatch   *batch\n\ttimer          *time.Timer\n\tshutdownCh     chan struct{}\n\tlogger         *zap.Logger\n\tonEmpty        func()    // callback triggered when partition is idle for given time period.\n\tlastDataTime   time.Time // tracks when data was last present\n\tactive         bool      // indicates if partition is still active i.e timer is running and shutdown is not called yet. If Consume is called on inactive partition then data is flushed sync because timer is not running.\n}\n\nfunc newPartitionBatcher(\n\tcfg BatchConfig,\n\tsizer request.Sizer,\n\tmergeCtx func(context.Context, context.Context) context.Context,\n\twp *workerPool,\n\tnext sender.SendFunc[request.Request],\n\tlogger *zap.Logger,\n\tonEmpty func(),\n) *partitionBatcher {\n\treturn &partitionBatcher{\n\t\tcfg:          cfg,\n\t\twp:           wp,\n\t\tsizer:        sizer,\n\t\tmergeCtx:     mergeCtx,\n\t\tconsumeFunc:  next,\n\t\tshutdownCh:   make(chan struct{}, 1),\n\t\tlogger:       logger,\n\t\tonEmpty:      onEmpty,\n\t\tlastDataTime: time.Now(),\n\t\tactive:       true,\n\t}\n}\n\nfunc (qb *partitionBatcher) resetTimer() {\n\tif qb.cfg.FlushTimeout > 0 {\n\t\tqb.timer.Reset(qb.cfg.FlushTimeout)\n\t}\n}\n\nfunc (qb *partitionBatcher) consumeInternal(ctx context.Context, req request.Request, done queue.Done) bool {\n\tqb.currentBatchMu.Lock()\n\tisActive := qb.active\n\tqb.lastDataTime = time.Now()\n\tif qb.currentBatch == nil {\n\t\treqList, mergeSplitErr := req.MergeSplit(ctx, int(qb.cfg.MaxSize), qb.cfg.Sizer, nil)\n\t\tif mergeSplitErr != nil {\n\t\t\t// Do not return in case of error if there are data, try to export as much as possible.\n\t\t\tqb.logger.Warn(\"Failed to split request.\", zap.Error(mergeSplitErr))\n\t\t}\n\n\t\tif len(reqList) == 0 {\n\t\t\tdone.OnDone(mergeSplitErr)\n\t\t\tqb.currentBatchMu.Unlock()\n\t\t\treturn isActive\n\t\t}\n\n\t\t// If more than one flush is required for this request, call done only when all flushes are done.\n\t\tnumRefs := len(reqList)\n\t\t// Need to also inform about the mergeSplitErr, consider the errored data as 1 batch.\n\t\tif mergeSplitErr != nil {\n\t\t\tnumRefs++\n\t\t}\n\t\tif numRefs > 1 {\n\t\t\tdone = newRefCountDone(done, int64(numRefs))\n\t\t\tif mergeSplitErr != nil {\n\t\t\t\tdone.OnDone(mergeSplitErr)\n\t\t\t}\n\t\t}\n\n\t\t// We have at least one result in the reqList. Last in the list may not have enough data to be flushed.\n\t\t// Find if it has at least MinSize, and if it does then move that as the current batch.\n\t\tlastReq := reqList[len(reqList)-1]\n\t\tif qb.sizer.Sizeof(lastReq) < qb.cfg.MinSize {\n\t\t\t// Do not flush the last item and add it to the current batch.\n\t\t\treqList = reqList[:len(reqList)-1]\n\t\t\tqb.currentBatch = &batch{\n\t\t\t\tctx:  ctx,\n\t\t\t\treq:  lastReq,\n\t\t\t\tdone: multiDone{done},\n\t\t\t}\n\t\t\tqb.resetTimer()\n\t\t}\n\n\t\tqb.currentBatchMu.Unlock()\n\t\tfor i := 0; i < len(reqList); i++ {\n\t\t\tqb.flush(ctx, reqList[i], done)\n\t\t}\n\n\t\treturn isActive\n\t}\n\n\treqList, mergeSplitErr := qb.currentBatch.req.MergeSplit(ctx, int(qb.cfg.MaxSize), qb.cfg.Sizer, req)\n\t// If failed to merge signal all Done callbacks from the current batch as well as the current request and reset the current batch.\n\tif mergeSplitErr != nil {\n\t\t// Do not return in case of error if there are data, try to export as much as possible.\n\t\tqb.logger.Warn(\"Failed to split request.\", zap.Error(mergeSplitErr))\n\t}\n\n\tif len(reqList) == 0 {\n\t\tdone.OnDone(mergeSplitErr)\n\t\tqb.currentBatchMu.Unlock()\n\t\treturn isActive\n\t}\n\n\t// If more than one flush is required for this request, call done only when all flushes are done.\n\tnumRefs := len(reqList)\n\t// Need to also inform about the mergeSplitErr, consider the errored data as 1 batch.\n\tif mergeSplitErr != nil {\n\t\tnumRefs++\n\t}\n\tif numRefs > 1 {\n\t\tdone = newRefCountDone(done, int64(numRefs))\n\t\tif mergeSplitErr != nil {\n\t\t\tdone.OnDone(mergeSplitErr)\n\t\t}\n\t}\n\n\t// We have at least one result in the reqList, if more results here is what that means:\n\t// - First result will contain items from the current batch + some results from the current request.\n\t// - All other results except first will contain items only from the current request.\n\t// - Last result may not have enough data to be flushed.\n\n\t// Logic on how to deal with the current batch:\n\tqb.currentBatch.req = reqList[0]\n\tqb.currentBatch.done = append(qb.currentBatch.done, done)\n\n\tmergedCtx := context.Background() //nolint:contextcheck\n\tif qb.mergeCtx != nil {\n\t\tmergedCtx = qb.mergeCtx(qb.currentBatch.ctx, ctx)\n\t}\n\tqb.currentBatch.ctx = contextWithMergedLinks(mergedCtx, qb.currentBatch.ctx, ctx)\n\n\t// Save the \"currentBatch\" if we need to flush it, because we want to execute flush without holding the lock, and\n\t// cannot unlock and re-lock because we are not done processing all the responses.\n\tvar firstBatch *batch\n\t// Need to check the currentBatch if more than 1 result returned or if 1 result return but larger than MinSize.\n\tif len(reqList) > 1 || qb.sizer.Sizeof(qb.currentBatch.req) >= qb.cfg.MinSize {\n\t\tfirstBatch = qb.currentBatch\n\t\tqb.currentBatch = nil\n\t}\n\t// At this moment we dealt with the first result which is iter in the currentBatch or in the `firstBatch` we will flush.\n\treqList = reqList[1:]\n\n\t// If we still have results to process, then we need to check if the last result has enough data to flush, or we add it to the currentBatch.\n\tif len(reqList) > 0 {\n\t\tlastReq := reqList[len(reqList)-1]\n\t\tif qb.sizer.Sizeof(lastReq) < qb.cfg.MinSize {\n\t\t\t// Do not flush the last item and add it to the current batch.\n\t\t\treqList = reqList[:len(reqList)-1]\n\t\t\tqb.currentBatch = &batch{\n\t\t\t\tctx:  ctx,\n\t\t\t\treq:  lastReq,\n\t\t\t\tdone: multiDone{done},\n\t\t\t}\n\t\t\tqb.resetTimer()\n\t\t}\n\t}\n\n\tqb.currentBatchMu.Unlock()\n\tif firstBatch != nil {\n\t\tqb.flush(firstBatch.ctx, firstBatch.req, firstBatch.done)\n\t}\n\tfor i := 0; i < len(reqList); i++ {\n\t\tqb.flush(ctx, reqList[i], done)\n\t}\n\treturn isActive\n}\n\nfunc (qb *partitionBatcher) Consume(ctx context.Context, req request.Request, done queue.Done) {\n\tif !qb.consumeInternal(ctx, req, done) {\n\t\t// Not active partition then flush else let the timer/Shutdown do it's work.\n\t\tqb.flushCurrentBatchOrRemovePartition()\n\t}\n}\n\n// Start starts the goroutine that reads from the queue and flushes asynchronously.\nfunc (qb *partitionBatcher) Start(context.Context, component.Host) error {\n\tif qb.cfg.FlushTimeout <= 0 {\n\t\treturn nil\n\t}\n\tqb.timer = time.NewTimer(qb.cfg.FlushTimeout)\n\tqb.stopWG.Go(func() {\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-qb.shutdownCh:\n\t\t\t\treturn\n\t\t\tcase <-qb.timer.C:\n\t\t\t\tqb.flushCurrentBatchOrRemovePartition()\n\t\t\t}\n\t\t}\n\t})\n\treturn nil\n}\n\n// shutdownInternal ensures that queue and all Batcher are stopped.\nfunc (qb *partitionBatcher) shutdownInternal() {\n\tqb.currentBatchMu.Lock()\n\tif !qb.active {\n\t\tqb.currentBatchMu.Unlock()\n\t\treturn\n\t}\n\tqb.active = false\n\t// don't need to trigger onEmpty during shutdown as partitionBatcher will be purged anyway.\n\tqb.onEmpty = nil\n\tqb.currentBatchMu.Unlock()\n\tclose(qb.shutdownCh)\n\t// Make sure execute one last flush if necessary.\n\tqb.flushCurrentBatchOrRemovePartition()\n\tqb.stopWG.Wait()\n}\n\n// Shutdown ensures that queue and all Batcher are stopped.\nfunc (qb *partitionBatcher) Shutdown(context.Context) error {\n\tqb.shutdownInternal()\n\treturn nil\n}\n\n// flushCurrentBatchOrRemovePartition flushes the current batch if not empty,\n// or removes the partition from the parent if it's been idle for too long.\nfunc (qb *partitionBatcher) flushCurrentBatchOrRemovePartition() {\n\tqb.currentBatchMu.Lock()\n\tif qb.currentBatch == nil {\n\t\t// No data to flush - check if idle for too long AND no one holding a reference\n\t\tidleDuration := time.Since(qb.lastDataTime)\n\n\t\tif idleDuration >= (partitionIdleCycles*qb.cfg.FlushTimeout) && qb.onEmpty != nil {\n\t\t\tqb.currentBatchMu.Unlock()\n\t\t\tqb.onEmpty()\n\t\t\treturn\n\t\t}\n\t\tif qb.timer != nil {\n\t\t\tqb.resetTimer()\n\t\t}\n\t\tqb.currentBatchMu.Unlock()\n\t\treturn\n\t}\n\n\t// Has data to flush - update lastDataTime\n\tqb.lastDataTime = time.Now()\n\tbatchToFlush := qb.currentBatch\n\tqb.currentBatch = nil\n\t// Reset timer while holding the lock to prevent data race with Consume() which\n\t// also calls resetTimer() under the same lock.\n\tqb.resetTimer()\n\tqb.currentBatchMu.Unlock()\n\t// flush() blocks until successfully started a goroutine for flushing.\n\tqb.flush(batchToFlush.ctx, batchToFlush.req, batchToFlush.done)\n}\n\n// flush starts a goroutine that calls consumeFunc. It blocks until a worker is available if necessary.\nfunc (qb *partitionBatcher) flush(ctx context.Context, req request.Request, done queue.Done) {\n\tqb.stopWG.Add(1)\n\tqb.wp.execute(func() {\n\t\tdefer qb.stopWG.Done()\n\t\tdone.OnDone(qb.consumeFunc(ctx, req))\n\t})\n}\n\ntype workerPool struct {\n\tworkers chan struct{}\n}\n\nfunc newWorkerPool(maxWorkers int) *workerPool {\n\tworkers := make(chan struct{}, maxWorkers)\n\tfor range maxWorkers {\n\t\tworkers <- struct{}{}\n\t}\n\treturn &workerPool{workers: workers}\n}\n\nfunc (wp *workerPool) execute(f func()) {\n\t<-wp.workers\n\tgo func() {\n\t\tdefer func() {\n\t\t\twp.workers <- struct{}{}\n\t\t}()\n\t\tf()\n\t}()\n}\n\ntype multiDone []queue.Done\n\nfunc (mdc multiDone) OnDone(err error) {\n\tfor _, d := range mdc {\n\t\td.OnDone(err)\n\t}\n}\n\ntype refCountDone struct {\n\tdone     queue.Done\n\tmu       sync.Mutex\n\trefCount int64\n\terr      error\n}\n\nfunc newRefCountDone(done queue.Done, refCount int64) queue.Done {\n\treturn &refCountDone{\n\t\tdone:     done,\n\t\trefCount: refCount,\n\t}\n}\n\nfunc (rcd *refCountDone) OnDone(err error) {\n\trcd.mu.Lock()\n\tdefer rcd.mu.Unlock()\n\trcd.err = multierr.Append(rcd.err, err)\n\trcd.refCount--\n\tif rcd.refCount == 0 {\n\t\t// No more references, call done.\n\t\trcd.done.OnDone(rcd.err)\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/partition_batcher_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"runtime\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n)\n\ntype testContextKey string\n\nconst timestampKey testContextKey = \"timestamp\"\n\nfunc TestPartitionBatcher_NoSplit_MinThresholdZero_TimeoutDisabled(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\tsizerType  request.SizerType\n\t\tsizer      request.Sizer\n\t\tmaxWorkers int\n\t}{\n\t\t{\n\t\t\tname:       \"items/one_worker\",\n\t\t\tsizerType:  request.SizerTypeItems,\n\t\t\tsizer:      request.NewItemsSizer(),\n\t\t\tmaxWorkers: 1,\n\t\t},\n\t\t{\n\t\t\tname:       \"items/three_workers\",\n\t\t\tsizerType:  request.SizerTypeItems,\n\t\t\tsizer:      request.NewItemsSizer(),\n\t\t\tmaxWorkers: 3,\n\t\t},\n\t\t{\n\t\t\tname:       \"bytes/one_worker\",\n\t\t\tsizerType:  request.SizerTypeBytes,\n\t\t\tsizer:      request.NewBytesSizer(),\n\t\t\tmaxWorkers: 1,\n\t\t},\n\t\t{\n\t\t\tname:       \"bytes/three_workers\",\n\t\t\tsizerType:  request.SizerTypeBytes,\n\t\t\tsizer:      request.NewBytesSizer(),\n\t\t\tmaxWorkers: 3,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := BatchConfig{\n\t\t\t\tFlushTimeout: 0,\n\t\t\t\tSizer:        tt.sizerType,\n\t\t\t\tMinSize:      0,\n\t\t\t}\n\n\t\t\tsink := requesttest.NewSink()\n\t\t\tba := newPartitionBatcher(cfg, tt.sizer, nil, newWorkerPool(tt.maxWorkers), sink.Export, zap.NewNop(), nil)\n\t\t\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n\t\t\tt.Cleanup(func() {\n\t\t\t\trequire.NoError(t, ba.Shutdown(context.Background()))\n\t\t\t})\n\n\t\t\tdone := newFakeDone()\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 8, Bytes: 8}, done)\n\t\t\tsink.SetExportErr(errors.New(\"transient error\"))\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 8, Bytes: 8}, done)\n\t\t\t<-time.After(10 * time.Millisecond)\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 17, Bytes: 17}, done)\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 13, Bytes: 13}, done)\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 35, Bytes: 35}, done)\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 2, Bytes: 2}, done)\n\t\t\tassert.Eventually(t, func() bool {\n\t\t\t\treturn sink.RequestsCount() == 5 && (sink.ItemsCount() == 75 || sink.BytesCount() == 75)\n\t\t\t}, 1*time.Second, 10*time.Millisecond)\n\t\t\t// Check that done callback is called for the right number of times.\n\t\t\tassert.EqualValues(t, 1, done.errors.Load())\n\t\t\tassert.EqualValues(t, 5, done.success.Load())\n\t\t})\n\t}\n}\n\nfunc TestPartitionBatcher_NoSplit_TimeoutDisabled(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\tsizerType  request.SizerType\n\t\tsizer      request.Sizer\n\t\tmaxWorkers int\n\t}{\n\t\t{\n\t\t\tname:       \"items/one_worker\",\n\t\t\tsizerType:  request.SizerTypeItems,\n\t\t\tsizer:      request.NewItemsSizer(),\n\t\t\tmaxWorkers: 1,\n\t\t},\n\t\t{\n\t\t\tname:       \"items/three_workers\",\n\t\t\tsizerType:  request.SizerTypeItems,\n\t\t\tsizer:      request.NewItemsSizer(),\n\t\t\tmaxWorkers: 3,\n\t\t},\n\t\t{\n\t\t\tname:       \"bytes/one_worker\",\n\t\t\tsizerType:  request.SizerTypeBytes,\n\t\t\tsizer:      request.NewBytesSizer(),\n\t\t\tmaxWorkers: 1,\n\t\t},\n\t\t{\n\t\t\tname:       \"bytes/three_workers\",\n\t\t\tsizerType:  request.SizerTypeBytes,\n\t\t\tsizer:      request.NewBytesSizer(),\n\t\t\tmaxWorkers: 3,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := BatchConfig{\n\t\t\t\tFlushTimeout: 0,\n\t\t\t\tSizer:        tt.sizerType,\n\t\t\t\tMinSize:      10,\n\t\t\t}\n\n\t\t\tsink := requesttest.NewSink()\n\t\t\tba := newPartitionBatcher(cfg, tt.sizer, nil, newWorkerPool(tt.maxWorkers), sink.Export, zap.NewNop(), nil)\n\t\t\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n\n\t\t\tdone := newFakeDone()\n\t\t\t// These two requests will be dropped because of export error.\n\t\t\tsink.SetExportErr(errors.New(\"transient error\"))\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 8, Bytes: 8}, done)\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 8, Bytes: 8}, done)\n\t\t\t<-time.After(10 * time.Millisecond)\n\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 7, Bytes: 7}, done)\n\t\t\t// This requests will be dropped because of merge error.\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 8, Bytes: 8, MergeErr: errors.New(\"transient error\")}, done)\n\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 13, Bytes: 13}, done)\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 35, Bytes: 35}, done)\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 2, Bytes: 2}, done)\n\n\t\t\t// Only the requests with 7+13 and 35 will be flushed.\n\t\t\tassert.Eventually(t, func() bool {\n\t\t\t\treturn sink.RequestsCount() == 2 && (sink.ItemsCount() == 55 || sink.BytesCount() == 55)\n\t\t\t}, 1*time.Second, 10*time.Millisecond)\n\n\t\t\trequire.NoError(t, ba.Shutdown(context.Background()))\n\n\t\t\t// After shutdown the pending \"current batch\" is also flushed.\n\t\t\tassert.Equal(t, 3, sink.RequestsCount())\n\t\t\tassert.True(t, sink.ItemsCount() == 57 || sink.BytesCount() == 57)\n\n\t\t\t// Check that done callback is called for the right number of times.\n\t\t\tassert.EqualValues(t, 3, done.errors.Load())\n\t\t\tassert.EqualValues(t, 4, done.success.Load())\n\t\t})\n\t}\n}\n\nfunc TestPartitionBatcher_NoSplit_WithTimeout(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"Skipping test on Windows, see https://github.com/open-telemetry/opentelemetry-collector/issues/11869\")\n\t}\n\n\ttests := []struct {\n\t\tname       string\n\t\tsizerType  request.SizerType\n\t\tsizer      request.Sizer\n\t\tmaxWorkers int\n\t}{\n\t\t{\n\t\t\tname:       \"items/one_worker\",\n\t\t\tsizerType:  request.SizerTypeItems,\n\t\t\tsizer:      request.NewItemsSizer(),\n\t\t\tmaxWorkers: 1,\n\t\t},\n\t\t{\n\t\t\tname:       \"items/three_workers\",\n\t\t\tsizerType:  request.SizerTypeItems,\n\t\t\tsizer:      request.NewItemsSizer(),\n\t\t\tmaxWorkers: 3,\n\t\t},\n\t\t{\n\t\t\tname:       \"bytes/one_worker\",\n\t\t\tsizerType:  request.SizerTypeBytes,\n\t\t\tsizer:      request.NewBytesSizer(),\n\t\t\tmaxWorkers: 1,\n\t\t},\n\t\t{\n\t\t\tname:       \"bytes/three_workers\",\n\t\t\tsizerType:  request.SizerTypeBytes,\n\t\t\tsizer:      request.NewBytesSizer(),\n\t\t\tmaxWorkers: 3,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := BatchConfig{\n\t\t\t\tFlushTimeout: 50 * time.Millisecond,\n\t\t\t\tSizer:        tt.sizerType,\n\t\t\t\tMinSize:      100,\n\t\t\t}\n\n\t\t\tsink := requesttest.NewSink()\n\t\t\tba := newPartitionBatcher(cfg, tt.sizer, nil, newWorkerPool(tt.maxWorkers), sink.Export, zap.NewNop(), nil)\n\t\t\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n\t\t\tt.Cleanup(func() {\n\t\t\t\trequire.NoError(t, ba.Shutdown(context.Background()))\n\t\t\t})\n\n\t\t\tdone := newFakeDone()\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 8, Bytes: 8}, done)\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 17, Bytes: 17}, done)\n\t\t\t// This requests will be dropped because of merge error.\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 8, Bytes: 8, MergeErr: errors.New(\"transient error\")}, done)\n\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 13, Bytes: 13}, done)\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 35, Bytes: 35}, done)\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 2, Bytes: 2}, done)\n\t\t\tassert.Eventually(t, func() bool {\n\t\t\t\treturn sink.RequestsCount() == 1 && (sink.ItemsCount() == 75 || sink.BytesCount() == 75)\n\t\t\t}, 1*time.Second, 10*time.Millisecond)\n\n\t\t\t// Check that done callback is called for the right number of times.\n\t\t\tassert.EqualValues(t, 1, done.errors.Load())\n\t\t\tassert.EqualValues(t, 5, done.success.Load())\n\t\t})\n\t}\n}\n\nfunc TestPartitionBatcher_Split_TimeoutDisabled(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"Skipping test on Windows, see https://github.com/open-telemetry/opentelemetry-collector/issues/11847\")\n\t}\n\n\ttests := []struct {\n\t\tname       string\n\t\tsizerType  request.SizerType\n\t\tsizer      request.Sizer\n\t\tmaxWorkers int\n\t}{\n\t\t{\n\t\t\tname:       \"items/one_worker\",\n\t\t\tsizerType:  request.SizerTypeItems,\n\t\t\tsizer:      request.NewItemsSizer(),\n\t\t\tmaxWorkers: 1,\n\t\t},\n\t\t{\n\t\t\tname:       \"items/three_workers\",\n\t\t\tsizerType:  request.SizerTypeItems,\n\t\t\tsizer:      request.NewItemsSizer(),\n\t\t\tmaxWorkers: 3,\n\t\t},\n\t\t{\n\t\t\tname:       \"bytes/one_worker\",\n\t\t\tsizerType:  request.SizerTypeBytes,\n\t\t\tsizer:      request.NewBytesSizer(),\n\t\t\tmaxWorkers: 1,\n\t\t},\n\t\t{\n\t\t\tname:       \"bytes/three_workers\",\n\t\t\tsizerType:  request.SizerTypeBytes,\n\t\t\tsizer:      request.NewBytesSizer(),\n\t\t\tmaxWorkers: 3,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := BatchConfig{\n\t\t\t\tFlushTimeout: 0,\n\t\t\t\tSizer:        tt.sizerType,\n\t\t\t\tMinSize:      100,\n\t\t\t\tMaxSize:      100,\n\t\t\t}\n\n\t\t\tsink := requesttest.NewSink()\n\t\t\tba := newPartitionBatcher(cfg, tt.sizer, nil, newWorkerPool(tt.maxWorkers), sink.Export, zap.NewNop(), nil)\n\t\t\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n\n\t\t\tdone := newFakeDone()\n\t\t\t// This requests will be dropped because of merge error.\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 8, Bytes: 8, MergeErr: errors.New(\"transient error\")}, done)\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 8, Bytes: 8}, done)\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 17, Bytes: 17}, done)\n\t\t\t// This requests will be dropped because of merge error.\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 8, Bytes: 8, MergeErr: errors.New(\"transient error\")}, done)\n\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 13, Bytes: 13}, done)\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 35, Bytes: 35}, done)\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 2, Bytes: 2}, done)\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 30, Bytes: 30}, done)\n\t\t\tassert.Eventually(t, func() bool {\n\t\t\t\treturn sink.RequestsCount() == 1 && (sink.ItemsCount() == 100 || sink.BytesCount() == 100)\n\t\t\t}, 1*time.Second, 10*time.Millisecond)\n\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 900, Bytes: 900}, done)\n\t\t\tassert.Eventually(t, func() bool {\n\t\t\t\treturn sink.RequestsCount() == 10 && (sink.ItemsCount() == 1000 || sink.BytesCount() == 1000)\n\t\t\t}, 1*time.Second, 10*time.Millisecond)\n\n\t\t\t// At this point the 7th not failing request is still pending.\n\t\t\tassert.EqualValues(t, 6, done.success.Load())\n\n\t\t\trequire.NoError(t, ba.Shutdown(context.Background()))\n\n\t\t\t// After shutdown the pending \"current batch\" is also flushed.\n\t\t\tassert.Equal(t, 11, sink.RequestsCount())\n\t\t\tassert.True(t, sink.ItemsCount() == 1005 || sink.BytesCount() == 1005)\n\n\t\t\t// Check that done callback is called for the right number of times.\n\t\t\tassert.EqualValues(t, 2, done.errors.Load())\n\t\t\tassert.EqualValues(t, 7, done.success.Load())\n\t\t})\n\t}\n}\n\nfunc TestPartitionBatcher_Shutdown(t *testing.T) {\n\tcfg := BatchConfig{\n\t\tFlushTimeout: 100 * time.Second,\n\t\tSizer:        request.SizerTypeItems,\n\t\tMinSize:      10,\n\t}\n\n\tsink := requesttest.NewSink()\n\tba := newPartitionBatcher(cfg, request.NewItemsSizer(), nil, newWorkerPool(2), sink.Export, zap.NewNop(), nil)\n\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n\n\tdone := newFakeDone()\n\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 1, Bytes: 1}, done)\n\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 2, Bytes: 2}, done)\n\n\tassert.Equal(t, 0, sink.RequestsCount())\n\tassert.Equal(t, 0, sink.ItemsCount())\n\n\trequire.NoError(t, ba.Shutdown(context.Background()))\n\n\tassert.Equal(t, 1, sink.RequestsCount())\n\tassert.Equal(t, 3, sink.ItemsCount())\n\n\t// Check that done callback is called for the right number of times.\n\tassert.EqualValues(t, 0, done.errors.Load())\n\tassert.EqualValues(t, 2, done.success.Load())\n}\n\nfunc TestPartitionBatcher_MergeError(t *testing.T) {\n\tcfg := BatchConfig{\n\t\tFlushTimeout: 200 * time.Second,\n\t\tSizer:        request.SizerTypeItems,\n\t\tMinSize:      5,\n\t\tMaxSize:      7,\n\t}\n\n\tsink := requesttest.NewSink()\n\tba := newPartitionBatcher(cfg, request.NewItemsSizer(), nil, newWorkerPool(2), sink.Export, zap.NewNop(), nil)\n\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, ba.Shutdown(context.Background()))\n\t})\n\n\tdone := newFakeDone()\n\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 9, Bytes: 9}, done)\n\tassert.Eventually(t, func() bool {\n\t\treturn sink.RequestsCount() == 1 && sink.ItemsCount() == 7\n\t}, 1*time.Second, 10*time.Millisecond)\n\n\tsink.SetExportErr(errors.New(\"transient error\"))\n\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 4, Bytes: 4}, done)\n\tassert.Eventually(t, func() bool {\n\t\treturn done.errors.Load() == 2\n\t}, 1*time.Second, 10*time.Millisecond)\n\n\t// Check that done callback is called for the right number of times.\n\tassert.EqualValues(t, 2, done.errors.Load())\n\tassert.EqualValues(t, 0, done.success.Load())\n}\n\nfunc TestPartitionBatcher_PartialSuccessError(t *testing.T) {\n\tcfg := BatchConfig{\n\t\tFlushTimeout: 0,\n\t\tSizer:        request.SizerTypeBytes,\n\t\tMinSize:      10,\n\t\tMaxSize:      15,\n\t}\n\n\tcore, observed := observer.New(zap.WarnLevel)\n\tlogger := zap.New(core)\n\tsink := requesttest.NewSink()\n\tba := newPartitionBatcher(cfg, request.NewItemsSizer(), nil, newWorkerPool(1), sink.Export, logger, nil)\n\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n\n\tdone := newFakeDone()\n\treq := &requesttest.FakeRequest{\n\t\tItems:          100,\n\t\tBytes:          100,\n\t\tMergeErr:       errors.New(\"split error\"),\n\t\tMergeErrResult: []request.Request{&requesttest.FakeRequest{Items: 10, Bytes: 15}},\n\t}\n\tba.Consume(context.Background(), req, done)\n\n\tassert.Eventually(t, func() bool {\n\t\tlogs := observed.All()\n\t\tif len(logs) == 0 {\n\t\t\treturn false\n\t\t}\n\t\tlog := logs[0]\n\t\treturn log.Level == zap.WarnLevel &&\n\t\t\tlog.Message == \"Failed to split request.\"\n\t}, time.Second, 10*time.Millisecond)\n\n\trequire.NoError(t, ba.Shutdown(context.Background()))\n\n\t// Verify that done callback was called with the returned batch and error for the split.\n\tassert.Equal(t, int64(1), done.errors.Load())\n\tassert.Equal(t, 1, sink.RequestsCount())\n\tassert.Equal(t, 10, sink.ItemsCount())\n\tassert.Equal(t, 15, sink.BytesCount())\n}\n\nfunc TestSPartitionBatcher_PartialSuccessError_AfterOkRequest(t *testing.T) {\n\tcfg := BatchConfig{\n\t\tFlushTimeout: 0,\n\t\tSizer:        request.SizerTypeBytes,\n\t\tMinSize:      10,\n\t\tMaxSize:      15,\n\t}\n\n\tcore, observed := observer.New(zap.WarnLevel)\n\tlogger := zap.New(core)\n\tsink := requesttest.NewSink()\n\tba := newPartitionBatcher(cfg, request.NewItemsSizer(), nil, newWorkerPool(1), sink.Export, logger, nil)\n\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n\n\tdone := newFakeDone()\n\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 5, Bytes: 5}, done)\n\treq := &requesttest.FakeRequest{\n\t\tItems:          100,\n\t\tBytes:          100,\n\t\tMergeErr:       errors.New(\"split error\"),\n\t\tMergeErrResult: []request.Request{&requesttest.FakeRequest{Items: 10, Bytes: 15}},\n\t}\n\tba.Consume(context.Background(), req, done)\n\n\tassert.Eventually(t, func() bool {\n\t\tlogs := observed.All()\n\t\tif len(logs) == 0 {\n\t\t\treturn false\n\t\t}\n\t\tlog := logs[0]\n\t\treturn log.Level == zap.WarnLevel &&\n\t\t\tlog.Message == \"Failed to split request.\"\n\t}, time.Second, 10*time.Millisecond)\n\n\trequire.NoError(t, ba.Shutdown(context.Background()))\n\n\t// Verify that done callback was called with the success for the returned batch and error for the split.\n\tassert.Equal(t, int64(1), done.errors.Load())\n\tassert.Equal(t, int64(1), done.success.Load())\n\tassert.Equal(t, 1, sink.RequestsCount())\n\tassert.Equal(t, 10, sink.ItemsCount())\n\tassert.Equal(t, 15, sink.BytesCount())\n}\n\ntype fakeDone struct {\n\terrors  *atomic.Int64\n\tsuccess *atomic.Int64\n}\n\nfunc newFakeDone() fakeDone {\n\treturn fakeDone{\n\t\terrors:  &atomic.Int64{},\n\t\tsuccess: &atomic.Int64{},\n\t}\n}\n\nfunc (fd fakeDone) OnDone(err error) {\n\tif err != nil {\n\t\tfd.errors.Add(1)\n\t} else {\n\t\tfd.success.Add(1)\n\t}\n}\n\nfunc TestShardBatcher_EmptyRequestList(t *testing.T) {\n\tcfg := BatchConfig{\n\t\tFlushTimeout: 0,\n\t\tMinSize:      0,\n\t}\n\n\tsink := requesttest.NewSink()\n\tba := newPartitionBatcher(cfg, request.NewItemsSizer(), nil, newWorkerPool(1), sink.Export, zap.NewNop(), nil)\n\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, ba.Shutdown(context.Background()))\n\t})\n\n\tdone := newFakeDone()\n\treq := &requesttest.FakeRequest{\n\t\tItems:    1,\n\t\tMergeErr: errors.New(\"force empty list\"),\n\t}\n\tba.Consume(context.Background(), req, done)\n\n\tassert.Eventually(t, func() bool {\n\t\treturn done.errors.Load() == 1\n\t}, time.Second, 10*time.Millisecond)\n\tassert.Equal(t, int64(0), done.success.Load())\n\tassert.Equal(t, 0, sink.RequestsCount())\n}\n\nfunc TestPartitionBatcher_ContextMerging(t *testing.T) {\n\ttests := []struct {\n\t\tname         string\n\t\tmergeCtxFunc func(ctx1, ctx2 context.Context) context.Context\n\t}{\n\t\t{\n\t\t\tname: \"merge_context_with_timestamp\",\n\t\t\tmergeCtxFunc: func(ctx1, _ context.Context) context.Context {\n\t\t\t\treturn context.WithValue(ctx1, timestampKey, 1234)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"merge_context_returns_background\",\n\t\t\tmergeCtxFunc: func(_, _ context.Context) context.Context {\n\t\t\t\treturn context.Background()\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:         \"nil_merge_context\",\n\t\t\tmergeCtxFunc: nil,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := BatchConfig{\n\t\t\t\tFlushTimeout: 0,\n\t\t\t\tSizer:        request.SizerTypeItems,\n\t\t\t\tMinSize:      10,\n\t\t\t}\n\t\t\tsink := requesttest.NewSink()\n\t\t\tba := newPartitionBatcher(cfg, request.NewItemsSizer(), tt.mergeCtxFunc, newWorkerPool(1), sink.Export, zap.NewNop(), nil)\n\t\t\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n\n\t\t\tdone := newFakeDone()\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 8, Bytes: 8}, done)\n\t\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 8, Bytes: 8}, done)\n\t\t\t<-time.After(10 * time.Millisecond)\n\t\t\tassert.Equal(t, 1, sink.RequestsCount())\n\t\t\tassert.EqualValues(t, 2, done.success.Load())\n\t\t})\n\t}\n}\n\nfunc TestPartitionBatcher_OnEmptyCallbackTriggered(t *testing.T) {\n\t// Use a very short FlushTimeout so the idle threshold (partitionIdleCycles*FlushTimeout) is reached quickly.\n\tcfg := BatchConfig{\n\t\tFlushTimeout: 10 * time.Millisecond,\n\t\tSizer:        request.SizerTypeItems,\n\t\tMinSize:      100, // High min size to ensure data doesn't flush immediately\n\t}\n\n\tsink := requesttest.NewSink()\n\tonEmptyCalled := &atomic.Int64{}\n\tonEmpty := func() {\n\t\tonEmptyCalled.Add(1)\n\t}\n\n\tba := newPartitionBatcher(cfg, request.NewItemsSizer(), nil, newWorkerPool(1), sink.Export, zap.NewNop(), onEmpty)\n\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, ba.Shutdown(context.Background()))\n\t})\n\n\t// Consume some data below min threshold so it stays in currentBatch\n\tdone := newFakeDone()\n\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 5}, done)\n\n\t// Wait for the batch to be flushed by timeout\n\tassert.Eventually(t, func() bool {\n\t\treturn sink.RequestsCount() == 1\n\t}, 500*time.Millisecond, 10*time.Millisecond)\n\n\t// Now wait for idle timeout (partitionIdleCycles * FlushTimeout = 10 * 10ms = 100ms)\n\t// The onEmpty callback should be called after the partition is idle for this duration.\n\tassert.Eventually(t, func() bool {\n\t\treturn onEmptyCalled.Load() >= 1\n\t}, 500*time.Millisecond, 10*time.Millisecond)\n}\n\nfunc TestPartitionBatcher_OnEmptyNotCalledWithActiveData(t *testing.T) {\n\t// Test that onEmpty is NOT called when data keeps flowing\n\tcfg := BatchConfig{\n\t\tFlushTimeout: 20 * time.Millisecond,\n\t\tSizer:        request.SizerTypeItems,\n\t\tMinSize:      5,\n\t}\n\n\tsink := requesttest.NewSink()\n\tonEmptyCalled := &atomic.Int64{}\n\tonEmpty := func() {\n\t\tonEmptyCalled.Add(1)\n\t}\n\n\tba := newPartitionBatcher(cfg, request.NewItemsSizer(), nil, newWorkerPool(1), sink.Export, zap.NewNop(), onEmpty)\n\trequire.NoError(t, ba.Start(context.Background(), componenttest.NewNopHost()))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, ba.Shutdown(context.Background()))\n\t})\n\n\tdone := newFakeDone()\n\t// Keep sending data to prevent idle timeout\n\tfor range 5 {\n\t\tba.Consume(context.Background(), &requesttest.FakeRequest{Items: 5}, done)\n\t\ttime.Sleep(15 * time.Millisecond)\n\t}\n\n\t// Data was flowing, onEmpty should not have been called\n\tassert.Equal(t, int64(0), onEmptyCalled.Load())\n\t// But data should have been flushed\n\tassert.GreaterOrEqual(t, sink.RequestsCount(), 1)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/partitioner.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n)\n\n// Partitioner is an interface that returns the the partition key of the given element.\ntype Partitioner[T any] interface {\n\tGetKey(context.Context, T) string\n}\n\ntype GetKeyFunc[T any] func(context.Context, T) string\n\nfunc (f GetKeyFunc[T]) GetKey(ctx context.Context, t T) string {\n\treturn f(ctx, t)\n}\n\ntype basePartitioner struct {\n\tGetKeyFunc[request.Request]\n}\n\nfunc NewPartitioner(\n\tgetKeyFunc GetKeyFunc[request.Request],\n) Partitioner[request.Request] {\n\treturn &basePartitioner{\n\t\tGetKeyFunc: getKeyFunc,\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/partitioner_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch\n\nimport (\n\t\"context\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/client\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n)\n\nfunc TestPartitioner_GetKeyFromRequest(t *testing.T) {\n\tpartitioner := NewPartitioner(func(_ context.Context, req request.Request) string {\n\t\treturn strconv.Itoa(req.(*requesttest.FakeRequest).ItemsCount())\n\t})\n\n\trequire.Equal(t, \"2\", partitioner.GetKey(context.Background(), &requesttest.FakeRequest{Items: 2}))\n\trequire.Equal(t, \"3\", partitioner.GetKey(context.Background(), &requesttest.FakeRequest{Items: 3}))\n\trequire.Equal(t, \"4\", partitioner.GetKey(context.Background(), &requesttest.FakeRequest{Items: 4}))\n}\n\nfunc TestPartitioner_GetKeyFromContext(t *testing.T) {\n\tpartitioner := NewPartitioner(func(ctx context.Context, _ request.Request) string {\n\t\treturn client.FromContext(ctx).Metadata.Get(\"metadata_key\")[0]\n\t})\n\n\tctx1 := client.NewContext(context.Background(), client.Info{\n\t\tMetadata: client.NewMetadata(map[string][]string{\"metadata_key\": {\"partition1\"}}),\n\t})\n\trequire.Equal(t, \"partition1\", partitioner.GetKey(ctx1, &requesttest.FakeRequest{Items: 2}))\n\n\tctx2 := client.NewContext(context.Background(), client.Info{\n\t\tMetadata: client.NewMetadata(map[string][]string{\"metadata_key\": {\"partition2\"}}),\n\t})\n\trequire.Equal(t, \"partition2\", partitioner.GetKey(ctx2, &requesttest.FakeRequest{Items: 2}))\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/queue_batch.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\n// Settings is a subset of the queuebatch.Settings that are needed when used within an Exporter.\ntype Settings[T any] struct {\n\tReferenceCounter queue.ReferenceCounter[T]\n\tEncoding         queue.Encoding[T]\n\tPartitioner      Partitioner[T]\n\tMergeCtx         func(context.Context, context.Context) context.Context\n}\n\n// AllSettings defines settings for creating a QueueBatch.\ntype AllSettings[T any] struct {\n\tSettings[T]\n\tSignal    pipeline.Signal\n\tID        component.ID\n\tTelemetry component.TelemetrySettings\n}\n\ntype QueueBatch struct {\n\tqueue   queue.Queue[request.Request]\n\tbatcher Batcher[request.Request]\n}\n\nfunc NewQueueBatch(\n\tset AllSettings[request.Request],\n\tcfg Config,\n\tnext sender.SendFunc[request.Request],\n) (*QueueBatch, error) {\n\tb, err := NewBatcher(cfg.Batch, batcherSettings[request.Request]{\n\t\tpartitioner: set.Partitioner,\n\t\tmergeCtx:    set.MergeCtx,\n\t\tnext:        next,\n\t\tmaxWorkers:  cfg.NumConsumers,\n\t\tlogger:      set.Telemetry.Logger,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif cfg.Batch.HasValue() && set.Partitioner == nil {\n\t\t// If batching is enabled and partitioner is not defined then keep the number of queue consumers to 1.\n\t\t// see: https://github.com/open-telemetry/opentelemetry-collector/issues/12473\n\t\tcfg.NumConsumers = 1\n\t}\n\n\tq, err := queue.NewQueue(queue.Settings[request.Request]{\n\t\tSizerType:        cfg.Sizer,\n\t\tCapacity:         cfg.QueueSize,\n\t\tNumConsumers:     cfg.NumConsumers,\n\t\tWaitForResult:    cfg.WaitForResult,\n\t\tBlockOnOverflow:  cfg.BlockOnOverflow,\n\t\tSignal:           set.Signal,\n\t\tStorageID:        cfg.StorageID,\n\t\tReferenceCounter: set.ReferenceCounter,\n\t\tEncoding:         set.Encoding,\n\t\tID:               set.ID,\n\t\tTelemetry:        set.Telemetry,\n\t}, b.Consume)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &QueueBatch{queue: q, batcher: b}, nil\n}\n\n// Start is invoked during service startup.\nfunc (qs *QueueBatch) Start(ctx context.Context, host component.Host) error {\n\tif err := qs.batcher.Start(ctx, host); err != nil {\n\t\treturn err\n\t}\n\tif err := qs.queue.Start(ctx, host); err != nil {\n\t\treturn errors.Join(err, qs.batcher.Shutdown(ctx))\n\t}\n\treturn nil\n}\n\n// Shutdown is invoked during service shutdown.\nfunc (qs *QueueBatch) Shutdown(ctx context.Context) error {\n\t// Stop the queue and batcher, this will drain the queue and will call the retry (which is stopped) that will only\n\t// try once every request.\n\treturn errors.Join(qs.queue.Shutdown(ctx), qs.batcher.Shutdown(ctx))\n}\n\n// Send implements the requestSender interface. It puts the request in the queue.\nfunc (qs *QueueBatch) Send(ctx context.Context, req request.Request) error {\n\treturn qs.queue.Offer(ctx, req)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/queue_batch_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"runtime\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/experr\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/hosttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sendertest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/storagetest\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\nfunc newFakeRequestSettings() AllSettings[request.Request] {\n\treturn AllSettings[request.Request]{\n\t\tSignal:    pipeline.SignalMetrics,\n\t\tID:        component.NewID(exportertest.NopType),\n\t\tTelemetry: componenttest.NewNopTelemetrySettings(),\n\t\tSettings: Settings[request.Request]{\n\t\t\tEncoding: newFakeEncoding(&requesttest.FakeRequest{}),\n\t\t},\n\t}\n}\n\ntype fakeEncoding struct {\n\tmr request.Request\n}\n\nfunc (f fakeEncoding) Marshal(context.Context, request.Request) ([]byte, error) {\n\treturn []byte(\"mockRequest\"), nil\n}\n\nfunc (f fakeEncoding) Unmarshal([]byte) (context.Context, request.Request, error) {\n\treturn context.Background(), f.mr, nil\n}\n\nfunc newFakeEncoding(mr request.Request) queue.Encoding[request.Request] {\n\treturn &fakeEncoding{mr: mr}\n}\n\nfunc TestQueueBatchStopWhileWaiting(t *testing.T) {\n\tsink := requesttest.NewSink()\n\tcfg := newTestConfig()\n\tcfg.NumConsumers = 1\n\tcfg.Batch = configoptional.Optional[BatchConfig]{}\n\tqb, err := NewQueueBatch(newFakeRequestSettings(), cfg, sink.Export)\n\trequire.NoError(t, err)\n\trequire.NoError(t, qb.Start(context.Background(), componenttest.NewNopHost()))\n\tsink.SetExportErr(errors.New(\"transient error\"))\n\trequire.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 4}))\n\t// Enqueue another request to ensure when calling shutdown we drain the queue.\n\trequire.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 3, Delay: 100 * time.Millisecond}))\n\trequire.LessOrEqual(t, int64(1), qb.queue.Size())\n\n\trequire.NoError(t, qb.Shutdown(context.Background()))\n\tassert.Equal(t, 1, sink.RequestsCount())\n\tassert.Equal(t, 3, sink.ItemsCount())\n\trequire.Zero(t, qb.queue.Size())\n}\n\nfunc TestQueueBatchDoNotPreserveCancellation(t *testing.T) {\n\tsink := requesttest.NewSink()\n\tcfg := newTestConfig()\n\tcfg.NumConsumers = 1\n\tqb, err := NewQueueBatch(newFakeRequestSettings(), cfg, sink.Export)\n\trequire.NoError(t, err)\n\trequire.NoError(t, qb.Start(context.Background(), componenttest.NewNopHost()))\n\n\tctx, cancelFunc := context.WithCancel(context.Background())\n\tcancelFunc()\n\n\trequire.NoError(t, qb.Send(ctx, &requesttest.FakeRequest{Items: 4}))\n\trequire.NoError(t, qb.Shutdown(context.Background()))\n\n\tassert.Equal(t, 1, sink.RequestsCount())\n\tassert.Equal(t, 4, sink.ItemsCount())\n\trequire.Zero(t, qb.queue.Size())\n}\n\nfunc TestQueueBatchHappyPath(t *testing.T) {\n\tcfg := newTestConfig()\n\tcfg.BlockOnOverflow = false\n\tcfg.QueueSize = 56\n\tsink := requesttest.NewSink()\n\tqb, err := NewQueueBatch(newFakeRequestSettings(), cfg, sink.Export)\n\trequire.NoError(t, err)\n\n\tfor i := range 10 {\n\t\trequire.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: i + 1}))\n\t}\n\n\t// expect queue to be full\n\trequire.Error(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 2}))\n\n\trequire.NoError(t, qb.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.Eventually(t, func() bool {\n\t\t// Because batching is used, cannot guarantee that will be 1 batch or multiple because of the flush interval.\n\t\t// Check only for total items count.\n\t\treturn sink.ItemsCount() == 55\n\t}, 1*time.Second, 10*time.Millisecond)\n\trequire.NoError(t, qb.Shutdown(context.Background()))\n}\n\nfunc TestQueueBatchDifferentSizers(t *testing.T) {\n\t// Set up the config so that the request is accepted in the queue\n\t// because the bytes size is used for the queue,\n\t// but split because the items size is used for batch.\n\tcfg := Config{\n\t\tWaitForResult:   false,\n\t\tSizer:           request.SizerTypeBytes,\n\t\tQueueSize:       100,\n\t\tBlockOnOverflow: false,\n\t\tNumConsumers:    1,\n\t\tBatch: configoptional.Some(BatchConfig{\n\t\t\tFlushTimeout: 200 * time.Millisecond,\n\t\t\tSizer:        request.SizerTypeItems,\n\t\t\tMinSize:      100,\n\t\t\tMaxSize:      200,\n\t\t}),\n\t}\n\tsink := requesttest.NewSink()\n\tqb, err := NewQueueBatch(newFakeRequestSettings(), cfg, sink.Export)\n\trequire.NoError(t, err)\n\trequire.NoError(t, qb.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 1000, Bytes: 100}))\n\tassert.Eventually(t, func() bool {\n\t\treturn sink.RequestsCount() == 5 && sink.ItemsCount() == 1000\n\t}, 1*time.Second, 10*time.Millisecond)\n\trequire.NoError(t, qb.Shutdown(context.Background()))\n}\n\nfunc TestQueueBatchPersistenceEnabled(t *testing.T) {\n\tcfg := newTestConfig()\n\tstorageID := component.MustNewIDWithName(\"file_storage\", \"storage\")\n\tcfg.StorageID = &storageID\n\tqb, err := NewQueueBatch(newFakeRequestSettings(), cfg, sendertest.NewNopSenderFunc[request.Request]())\n\trequire.NoError(t, err)\n\n\thost := hosttest.NewHost(map[component.ID]component.Component{\n\t\tstorageID: storagetest.NewMockStorageExtension(nil),\n\t})\n\n\t// we start correctly with a file storage extension\n\trequire.NoError(t, qb.Start(context.Background(), host))\n\trequire.NoError(t, qb.Shutdown(context.Background()))\n}\n\nfunc TestQueueBatchPersistenceEnabledStorageError(t *testing.T) {\n\tstorageError := errors.New(\"could not get storage client\")\n\tcfg := newTestConfig()\n\tstorageID := component.MustNewIDWithName(\"file_storage\", \"storage\")\n\tcfg.StorageID = &storageID\n\tqb, err := NewQueueBatch(newFakeRequestSettings(), cfg, sendertest.NewNopSenderFunc[request.Request]())\n\trequire.NoError(t, err)\n\n\thost := hosttest.NewHost(map[component.ID]component.Component{\n\t\tstorageID: storagetest.NewMockStorageExtension(storageError),\n\t})\n\n\t// we fail to start if we get an error creating the storage client\n\trequire.Error(t, qb.Start(context.Background(), host), \"could not get storage client\")\n}\n\nfunc TestQueueBatchPersistentEnabled_NoDataLossOnShutdown(t *testing.T) {\n\tcfg := newTestConfig()\n\tcfg.NumConsumers = 1\n\tstorageID := component.MustNewIDWithName(\"file_storage\", \"storage\")\n\tcfg.StorageID = &storageID\n\n\tmockReq := &requesttest.FakeRequest{Items: 2}\n\tqSet := newFakeRequestSettings()\n\tqSet.Encoding = newFakeEncoding(mockReq)\n\n\tconsumed := &atomic.Bool{}\n\tdone := make(chan struct{})\n\tqb, err := NewQueueBatch(qSet, cfg, func(context.Context, request.Request) error {\n\t\tconsumed.Store(true)\n\t\t<-done\n\t\treturn experr.NewShutdownErr(errors.New(\"could not export data\"))\n\t})\n\trequire.NoError(t, err)\n\n\thost := hosttest.NewHost(map[component.ID]component.Component{\n\t\tstorageID: storagetest.NewMockStorageExtension(nil),\n\t})\n\n\trequire.NoError(t, qb.Start(context.Background(), host))\n\n\t// Invoke queuedRetrySender so the producer will put the item for consumer to poll\n\trequire.NoError(t, qb.Send(context.Background(), mockReq))\n\n\t// first wait for the item to be consumed from the queue\n\tassert.Eventually(t, func() bool {\n\t\treturn consumed.Load()\n\t}, 1*time.Second, 10*time.Millisecond)\n\n\t// shuts down the exporter, unsent data should be preserved as in-flight data in the persistent queue.\n\tclose(done)\n\trequire.NoError(t, qb.Shutdown(context.Background()))\n\n\t// start the exporter again replacing the preserved mockRequest in the unmarshaler with a new one that doesn't fail.\n\tsink := requesttest.NewSink()\n\treplacedReq := &requesttest.FakeRequest{Items: 7}\n\tqSet.Encoding = newFakeEncoding(replacedReq)\n\tqb, err = NewQueueBatch(qSet, cfg, sink.Export)\n\trequire.NoError(t, err)\n\trequire.NoError(t, qb.Start(context.Background(), host))\n\n\tassert.Eventually(t, func() bool {\n\t\treturn sink.ItemsCount() == 7 && sink.RequestsCount() == 1\n\t}, 1*time.Second, 10*time.Millisecond)\n\trequire.NoError(t, qb.Shutdown(context.Background()))\n}\n\nfunc TestQueueBatchNoStartShutdown(t *testing.T) {\n\tqs, err := NewQueueBatch(newFakeRequestSettings(), newTestConfig(), sendertest.NewNopSenderFunc[request.Request]())\n\trequire.NoError(t, err)\n\tassert.NoError(t, qs.Shutdown(context.Background()))\n}\n\nfunc TestQueueBatch_Merge(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"skipping flaky test on Windows, see https://github.com/open-telemetry/opentelemetry-collector/issues/10758\")\n\t}\n\n\ttests := []struct {\n\t\tname     string\n\t\tbatchCfg BatchConfig\n\t}{\n\t\t{\n\t\t\tname: \"split_disabled\",\n\t\t\tbatchCfg: BatchConfig{\n\t\t\t\tFlushTimeout: 100 * time.Millisecond,\n\t\t\t\tSizer:        request.SizerTypeItems,\n\t\t\t\tMinSize:      10,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"split_high_limit\",\n\t\t\tbatchCfg: BatchConfig{\n\t\t\t\tFlushTimeout: 100 * time.Millisecond,\n\t\t\t\tSizer:        request.SizerTypeItems,\n\t\t\t\tMinSize:      10,\n\t\t\t\tMaxSize:      1000,\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsink := requesttest.NewSink()\n\t\t\tcfg := newTestConfig()\n\t\t\tcfg.Batch = configoptional.Some(tt.batchCfg)\n\t\t\tqb, err := NewQueueBatch(newFakeRequestSettings(), cfg, sink.Export)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, qb.Start(context.Background(), componenttest.NewNopHost()))\n\t\t\tt.Cleanup(func() {\n\t\t\t\trequire.NoError(t, qb.Shutdown(context.Background()))\n\t\t\t})\n\n\t\t\trequire.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 8}))\n\t\t\trequire.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 3}))\n\n\t\t\t// the first two requests should be merged into one and sent by reaching the minimum items size\n\t\t\tassert.Eventually(t, func() bool {\n\t\t\t\treturn sink.RequestsCount() == 1 && sink.ItemsCount() == 11\n\t\t\t}, 50*time.Millisecond, 10*time.Millisecond)\n\n\t\t\trequire.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 3}))\n\t\t\trequire.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 1}))\n\n\t\t\t// the third and fifth requests should be sent by reaching the timeout\n\t\t\t// the fourth request should be ignored because of the merge error.\n\t\t\ttime.Sleep(50 * time.Millisecond)\n\n\t\t\t// should be ignored because of the merge error.\n\t\t\trequire.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{\n\t\t\t\tItems:    3,\n\t\t\t\tMergeErr: errors.New(\"merge error\"),\n\t\t\t}))\n\n\t\t\tassert.Equal(t, 1, sink.RequestsCount())\n\t\t\tassert.Eventually(t, func() bool {\n\t\t\t\treturn sink.RequestsCount() == 2 && sink.ItemsCount() == 15\n\t\t\t}, 1*time.Second, 10*time.Millisecond)\n\t\t})\n\t}\n}\n\nfunc TestQueueBatch_BatchExportError(t *testing.T) {\n\ttests := []struct {\n\t\tname             string\n\t\tbatchCfg         BatchConfig\n\t\texpectedRequests int\n\t\texpectedItems    int\n\t}{\n\t\t{\n\t\t\tname: \"merge_only\",\n\t\t\tbatchCfg: BatchConfig{\n\t\t\t\tFlushTimeout: 200 * time.Millisecond,\n\t\t\t\tSizer:        request.SizerTypeItems,\n\t\t\t\tMinSize:      10,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"merge_without_split_triggered\",\n\t\t\tbatchCfg: BatchConfig{\n\t\t\t\tFlushTimeout: 200 * time.Millisecond,\n\t\t\t\tSizer:        request.SizerTypeItems,\n\t\t\t\tMinSize:      10,\n\t\t\t\tMaxSize:      200,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"merge_with_split_triggered\",\n\t\t\tbatchCfg: BatchConfig{\n\t\t\t\tFlushTimeout: 200 * time.Millisecond,\n\t\t\t\tSizer:        request.SizerTypeItems,\n\t\t\t\tMinSize:      10,\n\t\t\t\tMaxSize:      20,\n\t\t\t},\n\t\t\texpectedRequests: 1,\n\t\t\texpectedItems:    8,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsink := requesttest.NewSink()\n\t\t\tcfg := newTestConfig()\n\t\t\tcfg.Batch = configoptional.Some(tt.batchCfg)\n\t\t\tqb, err := NewQueueBatch(newFakeRequestSettings(), cfg, sink.Export)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, qb.Start(context.Background(), componenttest.NewNopHost()))\n\n\t\t\trequire.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 4}))\n\t\t\trequire.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 4}))\n\n\t\t\t// the first two requests should be blocked by the batchSender.\n\t\t\ttime.Sleep(50 * time.Millisecond)\n\t\t\tassert.Equal(t, 0, sink.RequestsCount())\n\n\t\t\t// the third request should trigger the export and cause an error.\n\t\t\tsink.SetExportErr(errors.New(\"transient error\"))\n\t\t\terrReq := &requesttest.FakeRequest{Items: 20}\n\t\t\trequire.NoError(t, qb.Send(context.Background(), errReq))\n\n\t\t\t// the batch should be dropped since the queue doesn't have re-queuing enabled.\n\t\t\tassert.Eventually(t, func() bool {\n\t\t\t\treturn sink.RequestsCount() == tt.expectedRequests &&\n\t\t\t\t\tsink.ItemsCount() == tt.expectedItems &&\n\t\t\t\t\tqb.queue.Size() == 0\n\t\t\t}, 1*time.Second, 10*time.Millisecond)\n\n\t\t\trequire.NoError(t, qb.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nfunc TestQueueBatch_MergeOrSplit(t *testing.T) {\n\tsink := requesttest.NewSink()\n\tcfg := newTestConfig()\n\tcfg.Batch = configoptional.Some(BatchConfig{\n\t\tFlushTimeout: 100 * time.Millisecond,\n\t\tSizer:        request.SizerTypeItems,\n\t\tMinSize:      5,\n\t\tMaxSize:      10,\n\t})\n\tqb, err := NewQueueBatch(newFakeRequestSettings(), cfg, sink.Export)\n\trequire.NoError(t, err)\n\trequire.NoError(t, qb.Start(context.Background(), componenttest.NewNopHost()))\n\n\t// should be sent right away by reaching the minimum items size.\n\trequire.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 8}))\n\tassert.Eventually(t, func() bool {\n\t\treturn sink.RequestsCount() == 1 && sink.ItemsCount() == 8\n\t}, 1*time.Second, 10*time.Millisecond)\n\n\t// big request should be broken down into two requests, both are sent right away.\n\trequire.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 17}))\n\tassert.Eventually(t, func() bool {\n\t\treturn sink.RequestsCount() == 3 && sink.ItemsCount() == 25\n\t}, 1*time.Second, 10*time.Millisecond)\n\n\t// request that cannot be split should be dropped.\n\trequire.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{\n\t\tItems:    11,\n\t\tMergeErr: errors.New(\"split error\"),\n\t}))\n\n\t// big request should be broken down into two requests, both are sent right away.\n\trequire.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 13}))\n\tassert.Eventually(t, func() bool {\n\t\treturn sink.RequestsCount() == 5 && sink.ItemsCount() == 38\n\t}, 1*time.Second, 10*time.Millisecond)\n\trequire.NoError(t, qb.Shutdown(context.Background()))\n}\n\nfunc TestQueueBatch_MergeOrSplit_Multibatch(t *testing.T) {\n\tsink := requesttest.NewSink()\n\tcfg := newTestConfig()\n\tcfg.Batch = configoptional.Some(BatchConfig{\n\t\tFlushTimeout: 100 * time.Millisecond,\n\t\tSizer:        request.SizerTypeItems,\n\t\tMinSize:      10,\n\t})\n\n\ttype partitionKey struct{}\n\tset := newFakeRequestSettings()\n\tset.Partitioner = NewPartitioner(func(ctx context.Context, _ request.Request) string {\n\t\tkey := ctx.Value(partitionKey{}).(string)\n\t\treturn key\n\t})\n\n\tqb, err := NewQueueBatch(set, cfg, sink.Export)\n\trequire.NoError(t, err)\n\trequire.NoError(t, qb.Start(context.Background(), componenttest.NewNopHost()))\n\n\t// should be sent right away by reaching the minimum items size.\n\trequire.NoError(t, qb.Send(context.WithValue(context.Background(), partitionKey{}, \"p1\"), &requesttest.FakeRequest{Items: 8}))\n\trequire.NoError(t, qb.Send(context.WithValue(context.Background(), partitionKey{}, \"p2\"), &requesttest.FakeRequest{Items: 6}))\n\n\t// Neither batch should be flushed since they haven't reached min threshold.\n\tassert.Equal(t, 0, sink.RequestsCount())\n\tassert.Equal(t, 0, sink.ItemsCount())\n\n\trequire.NoError(t, qb.Send(context.WithValue(context.Background(), partitionKey{}, \"p1\"), &requesttest.FakeRequest{Items: 8}))\n\n\tassert.Eventually(t, func() bool {\n\t\treturn sink.RequestsCount() == 1 && sink.ItemsCount() == 16\n\t}, 500*time.Millisecond, 10*time.Millisecond)\n\n\trequire.NoError(t, qb.Send(context.WithValue(context.Background(), partitionKey{}, \"p2\"), &requesttest.FakeRequest{Items: 6}))\n\n\tassert.Eventually(t, func() bool {\n\t\treturn sink.RequestsCount() == 2 && sink.ItemsCount() == 28\n\t}, 500*time.Millisecond, 10*time.Millisecond)\n\n\trequire.NoError(t, qb.Shutdown(context.Background()))\n}\n\nfunc TestQueueBatch_Shutdown(t *testing.T) {\n\tsink := requesttest.NewSink()\n\tqb, err := NewQueueBatch(newFakeRequestSettings(), newTestConfig(), sink.Export)\n\trequire.NoError(t, err)\n\trequire.NoError(t, qb.Start(context.Background(), componenttest.NewNopHost()))\n\n\trequire.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 3}))\n\n\t// To make the request reached the batchSender before shutdown.\n\ttime.Sleep(50 * time.Millisecond)\n\n\trequire.NoError(t, qb.Shutdown(context.Background()))\n\n\t// shutdown should force sending the batch\n\tassert.Equal(t, 1, sink.RequestsCount())\n\tassert.Equal(t, 3, sink.ItemsCount())\n}\n\nfunc TestQueueBatch_BatchBlocking(t *testing.T) {\n\tsink := requesttest.NewSink()\n\tcfg := newTestConfig()\n\tcfg.WaitForResult = true\n\tcfg.Batch = configoptional.Some(BatchConfig{Sizer: request.SizerTypeItems, MinSize: 3})\n\tqb, err := NewQueueBatch(newFakeRequestSettings(), cfg, sink.Export)\n\trequire.NoError(t, err)\n\trequire.NoError(t, qb.Start(context.Background(), componenttest.NewNopHost()))\n\n\t// send 6 blockOnOverflow requests\n\twg := sync.WaitGroup{}\n\tfor range 6 {\n\t\twg.Go(func() {\n\t\t\tassert.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 1, Delay: 10 * time.Millisecond}))\n\t\t})\n\t}\n\twg.Wait()\n\n\t// should be sent in two batches since the batch size is 3\n\tassert.Equal(t, 2, sink.RequestsCount())\n\tassert.Equal(t, 6, sink.ItemsCount())\n\n\trequire.NoError(t, qb.Shutdown(context.Background()))\n}\n\nfunc TestQueueBatch_DrainActiveRequests(t *testing.T) {\n\tsink := requesttest.NewSink()\n\tcfg := newTestConfig()\n\tcfg.WaitForResult = true\n\tcfg.Batch = configoptional.Some(BatchConfig{Sizer: request.SizerTypeItems, MinSize: 2})\n\tqb, err := NewQueueBatch(newFakeRequestSettings(), cfg, sink.Export)\n\trequire.NoError(t, err)\n\trequire.NoError(t, qb.Start(context.Background(), componenttest.NewNopHost()))\n\n\t// send 3 blockOnOverflow requests with a timeout\n\tgo func() {\n\t\tassert.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 1, Delay: 40 * time.Millisecond}))\n\t}()\n\tgo func() {\n\t\tassert.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 1, Delay: 40 * time.Millisecond}))\n\t}()\n\tgo func() {\n\t\tassert.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 1, Delay: 40 * time.Millisecond}))\n\t}()\n\n\t// give time for the first two requests to be batched\n\ttime.Sleep(20 * time.Millisecond)\n\n\t// Shutdown should force the active batch to be dispatched and wait for all batches to be delivered.\n\t// It should take 120 milliseconds to complete.\n\trequire.NoError(t, qb.Shutdown(context.Background()))\n\n\tassert.Equal(t, 2, sink.RequestsCount())\n\tassert.Equal(t, 3, sink.ItemsCount())\n}\n\nfunc TestQueueBatchTimerResetNoConflict(t *testing.T) {\n\tsink := requesttest.NewSink()\n\tcfg := newTestConfig()\n\tcfg.WaitForResult = true\n\tcfg.Batch = configoptional.Some(BatchConfig{FlushTimeout: 100 * time.Millisecond, MinSize: 8})\n\tqb, err := NewQueueBatch(newFakeRequestSettings(), cfg, sink.Export)\n\trequire.NoError(t, err)\n\trequire.NoError(t, qb.Start(context.Background(), componenttest.NewNopHost()))\n\n\t// Send 2 concurrent requests that should be merged in one batch in the same interval as the flush timer\n\tgo func() {\n\t\tassert.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 4}))\n\t}()\n\ttime.Sleep(30 * time.Millisecond)\n\tgo func() {\n\t\tassert.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 4}))\n\t}()\n\n\t// The batch should be sent either with the flush interval or by reaching the minimum items size with no conflict\n\tassert.EventuallyWithT(t, func(c *assert.CollectT) {\n\t\tassert.LessOrEqual(c, 1, sink.RequestsCount())\n\t\tassert.Equal(c, 8, sink.ItemsCount())\n\t}, 1*time.Second, 10*time.Millisecond)\n\n\trequire.NoError(t, qb.Shutdown(context.Background()))\n}\n\nfunc TestQueueBatchTimerFlush(t *testing.T) {\n\tif runtime.GOOS == \"windows\" {\n\t\tt.Skip(\"skipping flaky test on Windows, see https://github.com/open-telemetry/opentelemetry-collector/issues/10802\")\n\t}\n\tsink := requesttest.NewSink()\n\tcfg := newTestConfig()\n\tcfg.WaitForResult = true\n\tcfg.Batch = configoptional.Some(BatchConfig{FlushTimeout: 100 * time.Millisecond, Sizer: request.SizerTypeItems, MinSize: 8})\n\tqb, err := NewQueueBatch(newFakeRequestSettings(), cfg, sink.Export)\n\trequire.NoError(t, err)\n\trequire.NoError(t, qb.Start(context.Background(), componenttest.NewNopHost()))\n\ttime.Sleep(50 * time.Millisecond)\n\n\t// Send 2 concurrent requests that should be merged in one batch and sent immediately\n\tgo func() {\n\t\tassert.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 4}))\n\t}()\n\tgo func() {\n\t\tassert.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 4}))\n\t}()\n\tassert.EventuallyWithT(t, func(c *assert.CollectT) {\n\t\tassert.LessOrEqual(c, 1, sink.RequestsCount())\n\t\tassert.Equal(c, 8, sink.ItemsCount())\n\t}, 30*time.Millisecond, 5*time.Millisecond)\n\n\t// Send another request that should be flushed after 100ms instead of 50ms since last flush\n\tgo func() {\n\t\tassert.NoError(t, qb.Send(context.Background(), &requesttest.FakeRequest{Items: 4}))\n\t}()\n\n\t// Confirm that it is not flushed in 50ms\n\ttime.Sleep(60 * time.Millisecond)\n\tassert.LessOrEqual(t, 1, sink.RequestsCount())\n\tassert.Equal(t, 8, sink.ItemsCount())\n\n\t// Confirm that it is flushed after 100ms (using 60+50=110 here to be safe)\n\ttime.Sleep(50 * time.Millisecond)\n\tassert.LessOrEqual(t, 2, sink.RequestsCount())\n\tassert.Equal(t, 12, sink.ItemsCount())\n\trequire.NoError(t, qb.Shutdown(context.Background()))\n}\n\nfunc newTestConfig() Config {\n\treturn Config{\n\t\tWaitForResult:   false,\n\t\tSizer:           request.SizerTypeItems,\n\t\tNumConsumers:    runtime.NumCPU(),\n\t\tQueueSize:       100_000,\n\t\tBlockOnOverflow: true,\n\t\tBatch: configoptional.Some(BatchConfig{\n\t\t\tFlushTimeout: 200 * time.Millisecond,\n\t\t\tSizer:        request.SizerTypeItems,\n\t\t\tMinSize:      2048,\n\t\t}),\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/testdata/batch_set_empty_explicit_sizer.yaml",
    "content": "sizer: bytes\n# Batch is set but empty, do not override sizer\nbatch:\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/testdata/batch_set_empty_no_explicit_sizer.yaml",
    "content": "enabled: true\nbatch:\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/testdata/batch_set_nonempty_explicit_sizer.yaml",
    "content": "enabled: true\nsizer: bytes\nqueue_size: 2000 \nbatch:\n  # sizer is overridden here by parent sizer\n  min_size: 100 \n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/testdata/batch_set_nonempty_no_explicit_sizer.yaml",
    "content": "enabled: true\nqueue_size: 2000 \nbatch:\n  # sizer is NOT overridden here by parent sizer, since parent sizer is not set\n  min_size: 100 \n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/testdata/batch_unset.yaml",
    "content": "enabled: true\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/traces.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n\tpdatareq \"go.opentelemetry.io/collector/pdata/xpdata/request\"\n)\n\nvar (\n\ttracesMarshaler   = &ptrace.ProtoMarshaler{}\n\ttracesUnmarshaler = &ptrace.ProtoUnmarshaler{}\n)\n\n// NewTracesQueueBatchSettings returns a new QueueBatchSettings to configure to WithQueueBatch when using ptrace.Traces.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\nfunc NewTracesQueueBatchSettings() Settings[request.Request] {\n\treturn Settings[request.Request]{\n\t\tReferenceCounter: tracesReferenceCounter{},\n\t\tEncoding:         tracesEncoding{},\n\t}\n}\n\nvar (\n\t_ request.Request      = (*tracesRequest)(nil)\n\t_ request.ErrorHandler = (*tracesRequest)(nil)\n)\n\ntype tracesRequest struct {\n\ttd         ptrace.Traces\n\tcachedSize int\n}\n\nfunc newTracesRequest(td ptrace.Traces) request.Request {\n\treturn &tracesRequest{\n\t\ttd:         td,\n\t\tcachedSize: -1,\n\t}\n}\n\ntype tracesEncoding struct{}\n\nvar _ encoding[request.Request] = tracesEncoding{}\n\nfunc (tracesEncoding) Unmarshal(bytes []byte) (context.Context, request.Request, error) {\n\tif queue.PersistRequestContextOnRead() {\n\t\tctx, traces, err := pdatareq.UnmarshalTraces(bytes)\n\t\tif errors.Is(err, pdatareq.ErrInvalidFormat) {\n\t\t\t// fall back to unmarshaling without context\n\t\t\ttraces, err = tracesUnmarshaler.UnmarshalTraces(bytes)\n\t\t}\n\t\treturn ctx, newTracesRequest(traces), err\n\t}\n\ttraces, err := tracesUnmarshaler.UnmarshalTraces(bytes)\n\tif err != nil {\n\t\tvar req request.Request\n\t\treturn context.Background(), req, err\n\t}\n\treturn context.Background(), newTracesRequest(traces), nil\n}\n\nfunc (tracesEncoding) Marshal(ctx context.Context, req request.Request) ([]byte, error) {\n\ttraces := req.(*tracesRequest).td\n\tif queue.PersistRequestContextOnWrite() {\n\t\treturn pdatareq.MarshalTraces(ctx, traces)\n\t}\n\treturn tracesMarshaler.MarshalTraces(traces)\n}\n\nvar _ queue.ReferenceCounter[request.Request] = tracesReferenceCounter{}\n\ntype tracesReferenceCounter struct{}\n\nfunc (tracesReferenceCounter) Ref(req request.Request) {\n\tpref.RefTraces(req.(*tracesRequest).td)\n}\n\nfunc (tracesReferenceCounter) Unref(req request.Request) {\n\tpref.UnrefTraces(req.(*tracesRequest).td)\n}\n\nfunc (req *tracesRequest) OnError(err error) request.Request {\n\tvar traceError consumererror.Traces\n\tif errors.As(err, &traceError) {\n\t\t// TODO: Add logic to unref the new request created here.\n\t\treturn newTracesRequest(traceError.Data())\n\t}\n\treturn req\n}\n\nfunc (req *tracesRequest) ItemsCount() int {\n\treturn req.td.SpanCount()\n}\n\nfunc (req *tracesRequest) size(sizer sizer.TracesSizer) int {\n\tif req.cachedSize == -1 {\n\t\treq.cachedSize = sizer.TracesSize(req.td)\n\t}\n\treturn req.cachedSize\n}\n\nfunc (req *tracesRequest) setCachedSize(size int) {\n\treq.cachedSize = size\n}\n\nfunc (req *tracesRequest) BytesSize() int {\n\treturn tracesMarshaler.TracesSize(req.td)\n}\n\n// RequestConsumeFromTraces returns a RequestConsumeFunc that consumes ptrace.Traces.\nfunc RequestConsumeFromTraces(pusher consumer.ConsumeTracesFunc) request.RequestConsumeFunc {\n\treturn func(ctx context.Context, request request.Request) error {\n\t\treturn pusher.ConsumeTraces(ctx, request.(*tracesRequest).td)\n\t}\n}\n\n// RequestFromTraces returns a RequestConverterFunc that converts ptrace.Traces into a Request.\nfunc RequestFromTraces() request.RequestConverterFunc[ptrace.Traces] {\n\treturn func(_ context.Context, traces ptrace.Traces) (request.Request, error) {\n\t\treturn newTracesRequest(traces), nil\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/traces_batch.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\n// MergeSplit splits and/or merges the provided traces request and the current request into one or more requests\n// conforming with the MaxSizeConfig.\nfunc (req *tracesRequest) MergeSplit(_ context.Context, maxSize int, szt request.SizerType, r2 request.Request) ([]request.Request, error) {\n\tvar sz sizer.TracesSizer\n\tswitch szt {\n\tcase request.SizerTypeItems:\n\t\tsz = &sizer.TracesCountSizer{}\n\tcase request.SizerTypeBytes:\n\t\tsz = &sizer.TracesBytesSizer{}\n\tdefault:\n\t\treturn nil, errors.New(\"unknown sizer type\")\n\t}\n\n\tif r2 != nil {\n\t\treq2, ok := r2.(*tracesRequest)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"invalid input type\")\n\t\t}\n\t\treq2.mergeTo(req, sz)\n\t}\n\n\t// If no limit we can simply merge the new request into the current and return.\n\tif maxSize == 0 {\n\t\treturn []request.Request{req}, nil\n\t}\n\treturn req.split(maxSize, sz)\n}\n\nfunc (req *tracesRequest) mergeTo(dst *tracesRequest, sz sizer.TracesSizer) {\n\tif sz != nil {\n\t\tdst.setCachedSize(dst.size(sz) + req.size(sz))\n\t\treq.setCachedSize(0)\n\t}\n\treq.td.ResourceSpans().MoveAndAppendTo(dst.td.ResourceSpans())\n}\n\nfunc (req *tracesRequest) split(maxSize int, sz sizer.TracesSizer) ([]request.Request, error) {\n\tvar res []request.Request\n\tfor req.size(sz) > maxSize {\n\t\ttd, rmSize := extractTraces(req.td, maxSize, sz)\n\t\tif td.SpanCount() == 0 {\n\t\t\treturn res, fmt.Errorf(\"one span size is greater than max size, dropping items: %d\", req.td.SpanCount())\n\t\t}\n\t\treq.setCachedSize(req.size(sz) - rmSize)\n\t\tres = append(res, newTracesRequest(td))\n\t}\n\tres = append(res, req)\n\treturn res, nil\n}\n\n// extractTraces extracts a new traces with a maximum number of spans.\nfunc extractTraces(srcTraces ptrace.Traces, capacity int, sz sizer.TracesSizer) (ptrace.Traces, int) {\n\tdestTraces := ptrace.NewTraces()\n\tcapacityLeft := capacity - sz.TracesSize(destTraces)\n\tremovedSize := 0\n\tsrcTraces.ResourceSpans().RemoveIf(func(srcRS ptrace.ResourceSpans) bool {\n\t\t// If the no more capacity left just return.\n\t\tif capacityLeft == 0 {\n\t\t\treturn false\n\t\t}\n\t\trawRsSize := sz.ResourceSpansSize(srcRS)\n\t\trsSize := sz.DeltaSize(rawRsSize)\n\n\t\tif rsSize > capacityLeft {\n\t\t\textSrcRS, extRsSize := extractResourceSpans(srcRS, capacityLeft, sz)\n\t\t\t// This cannot make it to exactly 0 for the bytes,\n\t\t\t// force it to be 0 since that is the stopping condition.\n\t\t\tcapacityLeft = 0\n\t\t\tremovedSize += extRsSize\n\t\t\t// There represents the delta between the delta sizes.\n\t\t\tremovedSize += rsSize - rawRsSize - (sz.DeltaSize(rawRsSize-extRsSize) - (rawRsSize - extRsSize))\n\t\t\t// It is possible that for the bytes scenario, the extracted field contains no spans.\n\t\t\t// Do not add it to the destination if that is the case.\n\t\t\tif extSrcRS.ScopeSpans().Len() > 0 {\n\t\t\t\textSrcRS.MoveTo(destTraces.ResourceSpans().AppendEmpty())\n\t\t\t}\n\t\t\treturn extSrcRS.ScopeSpans().Len() != 0\n\t\t}\n\t\tcapacityLeft -= rsSize\n\t\tremovedSize += rsSize\n\n\t\tsrcRS.MoveTo(destTraces.ResourceSpans().AppendEmpty())\n\t\treturn true\n\t})\n\treturn destTraces, removedSize\n}\n\n// extractResourceSpans extracts spans and returns a new resource spans with the specified number of spans.\nfunc extractResourceSpans(srcRS ptrace.ResourceSpans, capacity int, sz sizer.TracesSizer) (ptrace.ResourceSpans, int) {\n\tdestRS := ptrace.NewResourceSpans()\n\tdestRS.SetSchemaUrl(srcRS.SchemaUrl())\n\tsrcRS.Resource().CopyTo(destRS.Resource())\n\t// Take into account that this can have max \"capacity\", so when added to the parent will need space for the extra delta size.\n\tcapacityLeft := capacity - (sz.DeltaSize(capacity) - capacity) - sz.ResourceSpansSize(destRS)\n\tremovedSize := 0\n\tsrcRS.ScopeSpans().RemoveIf(func(srcSS ptrace.ScopeSpans) bool {\n\t\t// If the no more capacity left just return.\n\t\tif capacityLeft == 0 {\n\t\t\treturn false\n\t\t}\n\n\t\trawSlSize := sz.ScopeSpansSize(srcSS)\n\t\tssSize := sz.DeltaSize(rawSlSize)\n\t\tif ssSize > capacityLeft {\n\t\t\textSrcSS, extSsSize := extractScopeSpans(srcSS, capacityLeft, sz)\n\t\t\t// This cannot make it to exactly 0 for the bytes,\n\t\t\t// force it to be 0 since that is the stopping condition.\n\t\t\tcapacityLeft = 0\n\t\t\tremovedSize += extSsSize\n\t\t\t// There represents the delta between the delta sizes.\n\t\t\tremovedSize += ssSize - rawSlSize - (sz.DeltaSize(rawSlSize-extSsSize) - (rawSlSize - extSsSize))\n\t\t\t// It is possible that for the bytes scenario, the extracted field contains no spans.\n\t\t\t// Do not add it to the destination if that is the case.\n\t\t\tif extSrcSS.Spans().Len() > 0 {\n\t\t\t\textSrcSS.MoveTo(destRS.ScopeSpans().AppendEmpty())\n\t\t\t}\n\t\t\treturn extSrcSS.Spans().Len() != 0\n\t\t}\n\t\tcapacityLeft -= ssSize\n\t\tremovedSize += ssSize\n\n\t\tsrcSS.MoveTo(destRS.ScopeSpans().AppendEmpty())\n\t\treturn true\n\t})\n\treturn destRS, removedSize\n}\n\n// extractScopeSpans extracts spans and returns a new scope spans with the specified number of spans.\nfunc extractScopeSpans(srcSS ptrace.ScopeSpans, capacity int, sz sizer.TracesSizer) (ptrace.ScopeSpans, int) {\n\tdestSS := ptrace.NewScopeSpans()\n\tdestSS.SetSchemaUrl(srcSS.SchemaUrl())\n\tsrcSS.Scope().CopyTo(destSS.Scope())\n\t// Take into account that this can have max \"capacity\", so when added to the parent will need space for the extra delta size.\n\tcapacityLeft := capacity - (sz.DeltaSize(capacity) - capacity) - sz.ScopeSpansSize(destSS)\n\tremovedSize := 0\n\tsrcSS.Spans().RemoveIf(func(srcSpan ptrace.Span) bool {\n\t\t// If the no more capacity left just return.\n\t\tif capacityLeft == 0 {\n\t\t\treturn false\n\t\t}\n\t\trsSize := sz.DeltaSize(sz.SpanSize(srcSpan))\n\t\tif rsSize > capacityLeft {\n\t\t\t// This cannot make it to exactly 0 for the bytes,\n\t\t\t// force it to be 0 since that is the stopping condition.\n\t\t\tcapacityLeft = 0\n\t\t\treturn false\n\t\t}\n\n\t\tcapacityLeft -= rsSize\n\t\tremovedSize += rsSize\n\t\tsrcSpan.MoveTo(destSS.Spans().AppendEmpty())\n\t\treturn true\n\t})\n\treturn destSS, removedSize\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/traces_batch_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestMergeTraces(t *testing.T) {\n\ttr1 := newTracesRequest(testdata.GenerateTraces(2))\n\ttr2 := newTracesRequest(testdata.GenerateTraces(3))\n\tres, err := tr1.MergeSplit(context.Background(), 0, request.SizerTypeItems, tr2)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 5, res[0].ItemsCount())\n}\n\nfunc TestMergeSplitTraces(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tszt      request.SizerType\n\t\tmaxSize  int\n\t\ttr1      request.Request\n\t\ttr2      request.Request\n\t\texpected []request.Request\n\t}{\n\t\t{\n\t\t\tname:     \"both_requests_empty\",\n\t\t\tszt:      request.SizerTypeItems,\n\t\t\tmaxSize:  10,\n\t\t\ttr1:      newTracesRequest(ptrace.NewTraces()),\n\t\t\ttr2:      newTracesRequest(ptrace.NewTraces()),\n\t\t\texpected: []request.Request{newTracesRequest(ptrace.NewTraces())},\n\t\t},\n\t\t{\n\t\t\tname:     \"first_request_empty\",\n\t\t\tszt:      request.SizerTypeItems,\n\t\t\tmaxSize:  10,\n\t\t\ttr1:      newTracesRequest(ptrace.NewTraces()),\n\t\t\ttr2:      newTracesRequest(testdata.GenerateTraces(5)),\n\t\t\texpected: []request.Request{newTracesRequest(testdata.GenerateTraces(5))},\n\t\t},\n\t\t{\n\t\t\tname:     \"second_request_empty\",\n\t\t\tszt:      request.SizerTypeItems,\n\t\t\tmaxSize:  10,\n\t\t\ttr1:      newTracesRequest(testdata.GenerateTraces(5)),\n\t\t\ttr2:      newTracesRequest(ptrace.NewTraces()),\n\t\t\texpected: []request.Request{newTracesRequest(testdata.GenerateTraces(5))},\n\t\t},\n\t\t{\n\t\t\tname:     \"first_empty_second_nil\",\n\t\t\tszt:      request.SizerTypeItems,\n\t\t\tmaxSize:  10,\n\t\t\ttr1:      newTracesRequest(ptrace.NewTraces()),\n\t\t\ttr2:      nil,\n\t\t\texpected: []request.Request{newTracesRequest(ptrace.NewTraces())},\n\t\t},\n\t\t{\n\t\t\tname:    \"merge_only\",\n\t\t\tszt:     request.SizerTypeItems,\n\t\t\tmaxSize: 10,\n\t\t\ttr1:     newTracesRequest(testdata.GenerateTraces(5)),\n\t\t\ttr2:     newTracesRequest(testdata.GenerateTraces(5)),\n\t\t\texpected: []request.Request{newTracesRequest(func() ptrace.Traces {\n\t\t\t\ttd := testdata.GenerateTraces(5)\n\t\t\t\ttestdata.GenerateTraces(5).ResourceSpans().MoveAndAppendTo(td.ResourceSpans())\n\t\t\t\treturn td\n\t\t\t}())},\n\t\t},\n\t\t{\n\t\t\tname:    \"split_only\",\n\t\t\tszt:     request.SizerTypeItems,\n\t\t\tmaxSize: 4,\n\t\t\ttr1:     newTracesRequest(ptrace.NewTraces()),\n\t\t\ttr2:     newTracesRequest(testdata.GenerateTraces(10)),\n\t\t\texpected: []request.Request{\n\t\t\t\tnewTracesRequest(testdata.GenerateTraces(4)),\n\t\t\t\tnewTracesRequest(testdata.GenerateTraces(4)),\n\t\t\t\tnewTracesRequest(testdata.GenerateTraces(2)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"split_and_merge\",\n\t\t\tszt:     request.SizerTypeItems,\n\t\t\tmaxSize: 10,\n\t\t\ttr1:     newTracesRequest(testdata.GenerateTraces(4)),\n\t\t\ttr2:     newTracesRequest(testdata.GenerateTraces(20)),\n\t\t\texpected: []request.Request{\n\t\t\t\tnewTracesRequest(func() ptrace.Traces {\n\t\t\t\t\ttd := testdata.GenerateTraces(4)\n\t\t\t\t\ttestdata.GenerateTraces(6).ResourceSpans().MoveAndAppendTo(td.ResourceSpans())\n\t\t\t\t\treturn td\n\t\t\t\t}()),\n\t\t\t\tnewTracesRequest(testdata.GenerateTraces(10)),\n\t\t\t\tnewTracesRequest(testdata.GenerateTraces(4)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"scope_spans_split\",\n\t\t\tszt:     request.SizerTypeItems,\n\t\t\tmaxSize: 10,\n\t\t\ttr1: newTracesRequest(func() ptrace.Traces {\n\t\t\t\ttd := testdata.GenerateTraces(10)\n\t\t\t\textraScopeTraces := testdata.GenerateTraces(5)\n\t\t\t\textraScopeTraces.ResourceSpans().At(0).ScopeSpans().At(0).Scope().SetName(\"extra scope\")\n\t\t\t\textraScopeTraces.ResourceSpans().MoveAndAppendTo(td.ResourceSpans())\n\t\t\t\treturn td\n\t\t\t}()),\n\t\t\ttr2: nil,\n\t\t\texpected: []request.Request{\n\t\t\t\tnewTracesRequest(testdata.GenerateTraces(10)),\n\t\t\t\tnewTracesRequest(func() ptrace.Traces {\n\t\t\t\t\ttd := testdata.GenerateTraces(5)\n\t\t\t\t\ttd.ResourceSpans().At(0).ScopeSpans().At(0).Scope().SetName(\"extra scope\")\n\t\t\t\t\treturn td\n\t\t\t\t}()),\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tres, err := tt.tr1.MergeSplit(context.Background(), tt.maxSize, tt.szt, tt.tr2)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Len(t, res, len(tt.expected))\n\t\t\tfor i := range res {\n\t\t\t\tassert.Equal(t, tt.expected[i].(*tracesRequest).td, res[i].(*tracesRequest).td)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMergeSplitTracesBasedOnByteSize(t *testing.T) {\n\ttests := []struct {\n\t\tname               string\n\t\tszt                request.SizerType\n\t\tmaxSize            int\n\t\tlr1                request.Request\n\t\tlr2                request.Request\n\t\texpected           []request.Request\n\t\texpectPartialError bool\n\t}{\n\t\t{\n\t\t\tname:     \"both_requests_empty\",\n\t\t\tszt:      request.SizerTypeBytes,\n\t\t\tmaxSize:  tracesMarshaler.TracesSize(testdata.GenerateTraces(10)),\n\t\t\tlr1:      newTracesRequest(ptrace.NewTraces()),\n\t\t\tlr2:      newTracesRequest(ptrace.NewTraces()),\n\t\t\texpected: []request.Request{newTracesRequest(ptrace.NewTraces())},\n\t\t},\n\t\t{\n\t\t\tname:     \"first_request_empty\",\n\t\t\tszt:      request.SizerTypeBytes,\n\t\t\tmaxSize:  tracesMarshaler.TracesSize(testdata.GenerateTraces(10)),\n\t\t\tlr1:      newTracesRequest(ptrace.NewTraces()),\n\t\t\tlr2:      newTracesRequest(testdata.GenerateTraces(5)),\n\t\t\texpected: []request.Request{newTracesRequest(testdata.GenerateTraces(5))},\n\t\t},\n\t\t{\n\t\t\tname:     \"first_empty_second_nil\",\n\t\t\tszt:      request.SizerTypeBytes,\n\t\t\tmaxSize:  tracesMarshaler.TracesSize(testdata.GenerateTraces(10)),\n\t\t\tlr1:      newTracesRequest(ptrace.NewTraces()),\n\t\t\tlr2:      nil,\n\t\t\texpected: []request.Request{newTracesRequest(ptrace.NewTraces())},\n\t\t},\n\t\t{\n\t\t\tname:    \"merge_only\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: tracesMarshaler.TracesSize(testdata.GenerateTraces(10)),\n\t\t\tlr1:     newTracesRequest(testdata.GenerateTraces(1)),\n\t\t\tlr2:     newTracesRequest(testdata.GenerateTraces(6)),\n\t\t\texpected: []request.Request{newTracesRequest(func() ptrace.Traces {\n\t\t\t\ttraces := testdata.GenerateTraces(1)\n\t\t\t\ttestdata.GenerateTraces(6).ResourceSpans().MoveAndAppendTo(traces.ResourceSpans())\n\t\t\t\treturn traces\n\t\t\t}())},\n\t\t},\n\t\t{\n\t\t\tname:    \"split_only\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: tracesMarshaler.TracesSize(testdata.GenerateTraces(4)),\n\t\t\tlr1:     newTracesRequest(ptrace.NewTraces()),\n\t\t\tlr2:     newTracesRequest(testdata.GenerateTraces(10)),\n\t\t\texpected: []request.Request{\n\t\t\t\tnewTracesRequest(testdata.GenerateTraces(4)),\n\t\t\t\tnewTracesRequest(testdata.GenerateTraces(4)),\n\t\t\t\tnewTracesRequest(testdata.GenerateTraces(2)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"merge_and_split\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: tracesMarshaler.TracesSize(testdata.GenerateTraces(10))/2 + tracesMarshaler.TracesSize(testdata.GenerateTraces(11))/2,\n\t\t\tlr1:     newTracesRequest(testdata.GenerateTraces(8)),\n\t\t\tlr2:     newTracesRequest(testdata.GenerateTraces(20)),\n\t\t\texpected: []request.Request{\n\t\t\t\tnewTracesRequest(func() ptrace.Traces {\n\t\t\t\t\ttraces := testdata.GenerateTraces(8)\n\t\t\t\t\ttestdata.GenerateTraces(2).ResourceSpans().MoveAndAppendTo(traces.ResourceSpans())\n\t\t\t\t\treturn traces\n\t\t\t\t}()),\n\t\t\t\tnewTracesRequest(testdata.GenerateTraces(10)),\n\t\t\t\tnewTracesRequest(testdata.GenerateTraces(8)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"scope_spans_split\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: tracesMarshaler.TracesSize(testdata.GenerateTraces(4)),\n\t\t\tlr1: newTracesRequest(func() ptrace.Traces {\n\t\t\t\tld := testdata.GenerateTraces(4)\n\t\t\t\tld.ResourceSpans().At(0).ScopeSpans().AppendEmpty().Spans().AppendEmpty().Attributes().PutStr(\"attr\", \"attrvalue\")\n\t\t\t\treturn ld\n\t\t\t}()),\n\t\t\tlr2: newTracesRequest(testdata.GenerateTraces(2)),\n\t\t\texpected: []request.Request{\n\t\t\t\tnewTracesRequest(testdata.GenerateTraces(4)),\n\t\t\t\tnewTracesRequest(func() ptrace.Traces {\n\t\t\t\t\tld := testdata.GenerateTraces(0)\n\t\t\t\t\tld.ResourceSpans().At(0).ScopeSpans().At(0).Spans().AppendEmpty().Attributes().PutStr(\"attr\", \"attrvalue\")\n\t\t\t\t\ttestdata.GenerateTraces(2).ResourceSpans().MoveAndAppendTo(ld.ResourceSpans())\n\t\t\t\t\treturn ld\n\t\t\t\t}()),\n\t\t\t},\n\t\t\texpectPartialError: false,\n\t\t},\n\t\t{\n\t\t\tname:    \"unsplittable_large_trace\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: 10,\n\t\t\tlr1: newTracesRequest(func() ptrace.Traces {\n\t\t\t\tld := testdata.GenerateTraces(1)\n\t\t\t\tld.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).Attributes().PutStr(\"large_attr\", string(make([]byte, 100)))\n\t\t\t\treturn ld\n\t\t\t}()),\n\t\t\tlr2:                nil,\n\t\t\texpected:           []request.Request{},\n\t\t\texpectPartialError: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"splittable_then_unsplittable_trace\",\n\t\t\tszt:     request.SizerTypeBytes,\n\t\t\tmaxSize: 1000,\n\t\t\tlr1: newTracesRequest(func() ptrace.Traces {\n\t\t\t\tld := testdata.GenerateTraces(2)\n\t\t\t\tld.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).Attributes().PutStr(\"large_attr\", string(make([]byte, 10)))\n\t\t\t\tld.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(1).Attributes().PutStr(\"large_attr\", string(make([]byte, 1001)))\n\t\t\t\treturn ld\n\t\t\t}()),\n\t\t\tlr2: nil,\n\t\t\texpected: []request.Request{newTracesRequest(func() ptrace.Traces {\n\t\t\t\tld := testdata.GenerateTraces(1)\n\t\t\t\tld.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).Attributes().PutStr(\"large_attr\", string(make([]byte, 10)))\n\t\t\t\treturn ld\n\t\t\t}())},\n\t\t\texpectPartialError: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tres, err := tt.lr1.MergeSplit(context.Background(), tt.maxSize, tt.szt, tt.lr2)\n\t\t\tif tt.expectPartialError {\n\t\t\t\trequire.ErrorContains(t, err, \"one span size is greater than max size, dropping items:\")\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\t\t\tassert.Len(t, res, len(tt.expected))\n\t\t\tfor i := range res {\n\t\t\t\tassert.Equal(t, tt.expected[i].(*tracesRequest).td, res[i].(*tracesRequest).td)\n\t\t\t\tassert.Equal(t,\n\t\t\t\t\ttracesMarshaler.TracesSize(tt.expected[i].(*tracesRequest).td),\n\t\t\t\t\ttracesMarshaler.TracesSize(res[i].(*tracesRequest).td))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMergeSplitTracesInputNotModifiedIfErrorReturned(t *testing.T) {\n\tr1 := newTracesRequest(testdata.GenerateTraces(18))\n\tr2 := newLogsRequest(testdata.GenerateLogs(3))\n\t_, err := r1.MergeSplit(context.Background(), 10, request.SizerTypeItems, r2)\n\trequire.Error(t, err)\n\tassert.Equal(t, 18, r1.ItemsCount())\n}\n\nfunc TestExtractTraces(t *testing.T) {\n\tfor i := range 10 {\n\t\ttd := testdata.GenerateTraces(10)\n\t\textractedTraces, removedSize := extractTraces(td, i, &sizer.TracesCountSizer{})\n\t\tassert.Equal(t, i, extractedTraces.SpanCount())\n\t\tassert.Equal(t, 10-i, td.SpanCount())\n\t\tassert.Equal(t, i, removedSize)\n\t}\n}\n\nfunc TestMergeSplitManySmallTraces(t *testing.T) {\n\tmerged := []request.Request{newTracesRequest(testdata.GenerateTraces(1))}\n\tfor range 1000 {\n\t\tlr2 := newTracesRequest(testdata.GenerateTraces(10))\n\t\tres, _ := merged[len(merged)-1].MergeSplit(context.Background(), 10000, request.SizerTypeItems, lr2)\n\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t}\n\tassert.Len(t, merged, 2)\n}\n\nfunc TestTracesMergeSplitExactBytes(t *testing.T) {\n\tpb := ptrace.ProtoMarshaler{}\n\t// Set max size off by 1, so forces every log to be it's own batch.\n\tlr := newTracesRequest(testdata.GenerateTraces(4))\n\tmerged, err := lr.MergeSplit(context.Background(), pb.TracesSize(testdata.GenerateTraces(2))-1, request.SizerTypeBytes, nil)\n\trequire.NoError(t, err)\n\tassert.Len(t, merged, 4)\n}\n\nfunc TestTracesMergeSplitExactItems(t *testing.T) {\n\t// Set max size off by 1, so forces every log to be it's own batch.\n\tlr := newTracesRequest(testdata.GenerateTraces(4))\n\tmerged, err := lr.MergeSplit(context.Background(), 1, request.SizerTypeItems, nil)\n\trequire.NoError(t, err)\n\tassert.Len(t, merged, 4)\n}\n\nfunc TestTracesMergeSplitUnknownSizerType(t *testing.T) {\n\treq := newTracesRequest(ptrace.NewTraces())\n\t// Call MergeSplit with invalid sizer\n\t_, err := req.MergeSplit(context.Background(), 0, request.SizerType{}, nil)\n\trequire.EqualError(t, err, \"unknown sizer type\")\n}\n\nfunc BenchmarkSplittingBasedOnItemCountManySmallTraces(b *testing.B) {\n\ttestutil.SkipGCHeavyBench(b)\n\t// All requests merge into a single batch.\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tmerged := []request.Request{newTracesRequest(testdata.GenerateTraces(10))}\n\t\tfor range 1000 {\n\t\t\tlr2 := newTracesRequest(testdata.GenerateTraces(10))\n\t\t\tres, _ := merged[len(merged)-1].MergeSplit(context.Background(), 10010, request.SizerTypeItems, lr2)\n\t\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t\t}\n\t\tassert.Len(b, merged, 1)\n\t}\n}\n\nfunc BenchmarkSplittingBasedOnItemCountManyTracesSlightlyAboveLimit(b *testing.B) {\n\ttestutil.SkipGCHeavyBench(b)\n\t// Every incoming request results in a split.\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tmerged := []request.Request{newTracesRequest(testdata.GenerateTraces(0))}\n\t\tfor range 10 {\n\t\t\tlr2 := newTracesRequest(testdata.GenerateTraces(10001))\n\t\t\tres, _ := merged[len(merged)-1].MergeSplit(context.Background(), 10000, request.SizerTypeItems, lr2)\n\t\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t\t}\n\t\tassert.Len(b, merged, 11)\n\t}\n}\n\nfunc BenchmarkSplittingBasedOnItemCountHugeTraces(b *testing.B) {\n\ttestutil.SkipGCHeavyBench(b)\n\t// One request splits into many batches.\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tmerged := []request.Request{newTracesRequest(testdata.GenerateTraces(0))}\n\t\tlr2 := newTracesRequest(testdata.GenerateTraces(100000))\n\t\tres, _ := merged[len(merged)-1].MergeSplit(context.Background(), 10000, request.SizerTypeItems, lr2)\n\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t\tassert.Len(b, merged, 10)\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/queuebatch/traces_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage queuebatch // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestTracesRequest(t *testing.T) {\n\tmr := newTracesRequest(testdata.GenerateTraces(1))\n\n\ttraceErr := consumererror.NewTraces(errors.New(\"some error\"), ptrace.NewTraces())\n\tassert.Equal(t, newTracesRequest(ptrace.NewTraces()), mr.(request.ErrorHandler).OnError(traceErr))\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/request/request.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage request // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender\"\n)\n\n// Request represents a single request that can be sent to an external endpoint.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\ntype Request interface {\n\t// ItemsCount returns a number of basic items in the request where item is the smallest piece of data that can be\n\t// sent. For example, for OTLP exporter, this value represents the number of spans,\n\t// metric data points or log records.\n\tItemsCount() int\n\t// MergeSplit is a function that merge and/or splits this request with another one into multiple requests based on the\n\t// configured limit provided in maxSize.\n\t// MergeSplit does not split if maxSize is zero.\n\t// All the returned requests MUST have a number of items that does not exceed the maximum number of items.\n\t// Size of the last returned request MUST be less or equal than the size of any other returned request.\n\t// The original request MUST not be mutated if error is returned after mutation or if the exporter is\n\t// marked as not mutable. The length of the returned slice MUST not be 0.\n\t// Experimental: This API is at the early stage of development and may change without backward compatibility\n\t// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\n\tMergeSplit(ctx context.Context, maxSize int, sizerType SizerType, req Request) ([]Request, error)\n\t// BytesSize returns the size of the request in bytes.\n\tBytesSize() int\n}\n\n// ErrorHandler is an optional interface that can be implemented by Request to provide a way handle partial\n// temporary failures. For example, if some items failed to process and can be retried, this interface allows to\n// return a new Request that contains the items left to be sent. Otherwise, the original Request should be returned.\n// If not implemented, the original Request will be returned assuming the error is applied to the whole Request.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\ntype ErrorHandler interface {\n\tRequest\n\t// OnError returns a new Request may contain the items left to be sent if some items failed to process and can be retried.\n\t// Otherwise, it should return the original Request.\n\tOnError(error) Request\n}\n\ntype RequestConverterFunc[T any] func(context.Context, T) (Request, error)\n\n// RequestConsumeFunc processes the request. After the function returns, the request is no longer accessible,\n// and accessing it is considered undefined behavior.\ntype RequestConsumeFunc = sender.SendFunc[Request]\n"
  },
  {
    "path": "exporter/exporterhelper/internal/request/sizer.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage request // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\nimport (\n\t\"encoding\"\n\t\"fmt\"\n)\n\n// TODO: Move this back to queuebatch when remove the circular dependency.\n\nvar (\n\t_ encoding.TextMarshaler   = (*SizerType)(nil)\n\t_ encoding.TextUnmarshaler = (*SizerType)(nil)\n)\n\ntype SizerType struct {\n\tval string\n}\n\nconst (\n\tsizerTypeBytes    = \"bytes\"\n\tsizerTypeItems    = \"items\"\n\tsizerTypeRequests = \"requests\"\n)\n\nvar (\n\tSizerTypeBytes    = SizerType{val: sizerTypeBytes}\n\tSizerTypeItems    = SizerType{val: sizerTypeItems}\n\tSizerTypeRequests = SizerType{val: sizerTypeRequests}\n)\n\n// UnmarshalText implements TextUnmarshaler interface.\nfunc (s *SizerType) UnmarshalText(text []byte) error {\n\tswitch str := string(text); str {\n\tcase sizerTypeItems:\n\t\t*s = SizerTypeItems\n\tcase sizerTypeBytes:\n\t\t*s = SizerTypeBytes\n\tcase sizerTypeRequests:\n\t\t*s = SizerTypeRequests\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid sizer: %q\", str)\n\t}\n\treturn nil\n}\n\nfunc (s *SizerType) MarshalText() ([]byte, error) {\n\treturn []byte(s.val), nil\n}\n\nfunc (s *SizerType) String() string {\n\treturn s.val\n}\n\n// Sizer is an interface that returns the size of the given element.\ntype Sizer interface {\n\tSizeof(Request) int64\n}\n\nfunc NewSizer(sizerType SizerType) Sizer {\n\tswitch sizerType {\n\tcase SizerTypeBytes:\n\t\treturn NewBytesSizer()\n\tcase SizerTypeItems:\n\t\treturn NewItemsSizer()\n\tdefault:\n\t\treturn RequestsSizer{}\n\t}\n}\n\n// RequestsSizer is a Sizer implementation that returns the size of a queue element as one request.\ntype RequestsSizer struct{}\n\nfunc (rs RequestsSizer) Sizeof(Request) int64 {\n\treturn 1\n}\n\ntype itemsSizer struct{}\n\nfunc (itemsSizer) Sizeof(req Request) int64 {\n\treturn int64(req.ItemsCount())\n}\n\ntype bytesSizer struct{}\n\nfunc (bytesSizer) Sizeof(req Request) int64 {\n\treturn int64(req.BytesSize())\n}\n\nfunc NewItemsSizer() Sizer {\n\treturn itemsSizer{}\n}\n\nfunc NewBytesSizer() Sizer {\n\treturn bytesSizer{}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/request/sizer_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage request_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n)\n\nfunc TestItemsSizer(t *testing.T) {\n\tsz := request.NewItemsSizer()\n\tassert.EqualValues(t, 3, sz.Sizeof(&requesttest.FakeRequest{Items: 3}))\n}\n\nfunc TestSizeTypeUnmarshalText(t *testing.T) {\n\tvar sizer request.SizerType\n\trequire.NoError(t, sizer.UnmarshalText([]byte(\"bytes\")))\n\trequire.NoError(t, sizer.UnmarshalText([]byte(\"items\")))\n\trequire.NoError(t, sizer.UnmarshalText([]byte(\"requests\")))\n\trequire.Error(t, sizer.UnmarshalText([]byte(\"invalid\")))\n}\n\nfunc TestSizeTypeMarshalText(t *testing.T) {\n\tval, err := request.SizerTypeBytes.MarshalText()\n\trequire.NoError(t, err)\n\tassert.Equal(t, []byte(\"bytes\"), val)\n\n\tval, err = request.SizerTypeItems.MarshalText()\n\trequire.NoError(t, err)\n\tassert.Equal(t, []byte(\"items\"), val)\n\n\tval, err = request.SizerTypeRequests.MarshalText()\n\trequire.NoError(t, err)\n\tassert.Equal(t, []byte(\"requests\"), val)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/requesttest/request.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage requesttest // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\ntype errorPartial struct {\n\tfr *FakeRequest\n}\n\nfunc (e errorPartial) Error() string {\n\treturn fmt.Sprintf(\"items: %d\", e.fr.Items)\n}\n\ntype FakeRequest struct {\n\tItems          int\n\tBytes          int\n\tPartial        int\n\tMergeErr       error\n\tMergeErrResult []request.Request\n\tDelay          time.Duration\n}\n\nfunc (r *FakeRequest) OnError(err error) request.Request {\n\tvar pErr errorPartial\n\tif errors.As(err, &pErr) {\n\t\treturn pErr.fr\n\t}\n\treturn r\n}\n\nfunc (r *FakeRequest) ItemsCount() int {\n\treturn r.Items\n}\n\nfunc (r *FakeRequest) BytesSize() int {\n\treturn r.Bytes\n}\n\nfunc (r *FakeRequest) MergeSplit(_ context.Context, maxSize int, szt request.SizerType, r2 request.Request) ([]request.Request, error) {\n\tif r.MergeErr != nil {\n\t\treturn r.MergeErrResult, r.MergeErr\n\t}\n\n\tif r2 != nil {\n\t\tfr2 := r2.(*FakeRequest)\n\t\tif fr2.MergeErr != nil {\n\t\t\treturn fr2.MergeErrResult, fr2.MergeErr\n\t\t}\n\t\tfr2.mergeTo(r)\n\t}\n\n\tif maxSize == 0 {\n\t\treturn []request.Request{r}, nil\n\t}\n\n\tvar res []request.Request\n\tswitch szt {\n\tcase request.SizerTypeItems:\n\t\tfor r.Items != 0 {\n\t\t\tif r.Items <= maxSize {\n\t\t\t\tres = append(res, r)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tres = append(res, &FakeRequest{Items: maxSize, Bytes: -1, Delay: r.Delay})\n\t\t\tr.Items -= maxSize\n\t\t\tr.Bytes = -1\n\t\t}\n\tcase request.SizerTypeBytes:\n\t\tfor r.Bytes != 0 {\n\t\t\tif r.Bytes <= maxSize {\n\t\t\t\tres = append(res, r)\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tres = append(res, &FakeRequest{Items: -1, Bytes: maxSize, Delay: r.Delay})\n\t\t\tr.Items = -1\n\t\t\tr.Bytes -= maxSize\n\t\t}\n\t}\n\n\treturn res, nil\n}\n\nfunc (r *FakeRequest) mergeTo(dst *FakeRequest) {\n\tdst.Items += r.Items\n\tdst.Bytes += r.Bytes\n\tdst.Delay += r.Delay\n}\n\nfunc RequestFromMetricsFunc(err error) func(context.Context, pmetric.Metrics) (request.Request, error) {\n\treturn func(_ context.Context, md pmetric.Metrics) (request.Request, error) {\n\t\treturn &FakeRequest{Items: md.DataPointCount()}, err\n\t}\n}\n\nfunc RequestFromTracesFunc(err error) func(context.Context, ptrace.Traces) (request.Request, error) {\n\treturn func(_ context.Context, td ptrace.Traces) (request.Request, error) {\n\t\treturn &FakeRequest{Items: td.SpanCount()}, err\n\t}\n}\n\nfunc RequestFromLogsFunc(err error) func(context.Context, plog.Logs) (request.Request, error) {\n\treturn func(_ context.Context, ld plog.Logs) (request.Request, error) {\n\t\treturn &FakeRequest{Items: ld.LogRecordCount()}, err\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/requesttest/sink.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage requesttest // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n)\n\nfunc NewSink() *Sink {\n\treturn &Sink{}\n}\n\ntype Sink struct {\n\trequestsCount int\n\titemsCount    int\n\tbytesCount    int\n\tmu            sync.Mutex\n\texportErr     error\n}\n\nfunc (s *Sink) Export(ctx context.Context, req request.Request) error {\n\tr := req.(*FakeRequest)\n\tselect {\n\tcase <-ctx.Done():\n\t\treturn ctx.Err()\n\tcase <-time.After(r.Delay):\n\t}\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\tif s.exportErr != nil {\n\t\terr := s.exportErr\n\t\ts.exportErr = nil\n\t\treturn err\n\t}\n\tif r.Partial > 0 {\n\t\ts.requestsCount++\n\t\ts.itemsCount += r.Items - r.Partial\n\t\treturn errorPartial{fr: &FakeRequest{\n\t\t\tItems:    r.Partial,\n\t\t\tPartial:  0,\n\t\t\tMergeErr: r.MergeErr,\n\t\t\tDelay:    r.Delay,\n\t\t}}\n\t}\n\ts.requestsCount++\n\ts.itemsCount += r.Items\n\ts.bytesCount += r.Bytes\n\treturn nil\n}\n\nfunc (s *Sink) SetExportErr(err error) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\ts.exportErr = err\n}\n\nfunc (s *Sink) RequestsCount() int {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.requestsCount\n}\n\nfunc (s *Sink) ItemsCount() int {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.itemsCount\n}\n\nfunc (s *Sink) BytesCount() int {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.bytesCount\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/retry_sender.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/cenkalti/backoff/v5\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/trace\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configretry\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/experr\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender\"\n)\n\n// TODO: Clean this by forcing all exporters to return an internal error type that always include the information about retries.\ntype throttleRetry struct {\n\terr   error\n\tdelay time.Duration\n}\n\nfunc (t throttleRetry) Error() string {\n\treturn \"Throttle (\" + t.delay.String() + \"), error: \" + t.err.Error()\n}\n\nfunc (t throttleRetry) Unwrap() error {\n\treturn t.err\n}\n\n// NewThrottleRetry creates a new throttle retry error.\nfunc NewThrottleRetry(err error, delay time.Duration) error {\n\treturn throttleRetry{\n\t\terr:   err,\n\t\tdelay: delay,\n\t}\n}\n\ntype retrySender struct {\n\tcomponent.StartFunc\n\tcfg    configretry.BackOffConfig\n\tstopCh chan struct{}\n\tlogger *zap.Logger\n\tnext   sender.Sender[request.Request]\n}\n\nfunc newRetrySender(config configretry.BackOffConfig, set exporter.Settings, next sender.Sender[request.Request]) *retrySender {\n\treturn &retrySender{\n\t\tcfg:    config,\n\t\tstopCh: make(chan struct{}),\n\t\tlogger: set.Logger,\n\t\tnext:   next,\n\t}\n}\n\nfunc (rs *retrySender) Shutdown(context.Context) error {\n\tclose(rs.stopCh)\n\treturn nil\n}\n\n// Send implements the requestSender interface\nfunc (rs *retrySender) Send(ctx context.Context, req request.Request) error {\n\t// Do not use NewExponentialBackOff since it calls Reset and the code here must\n\t// call Reset after changing the InitialInterval (this saves an unnecessary call to Now).\n\texpBackoff := backoff.ExponentialBackOff{\n\t\tInitialInterval:     rs.cfg.InitialInterval,\n\t\tRandomizationFactor: rs.cfg.RandomizationFactor,\n\t\tMultiplier:          rs.cfg.Multiplier,\n\t\tMaxInterval:         rs.cfg.MaxInterval,\n\t}\n\tspan := trace.SpanFromContext(ctx)\n\tretryNum := int64(0)\n\tvar maxElapsedTime time.Time\n\tif rs.cfg.MaxElapsedTime > 0 {\n\t\tmaxElapsedTime = time.Now().Add(rs.cfg.MaxElapsedTime)\n\t}\n\tfor {\n\t\tspan.AddEvent(\n\t\t\t\"Sending request.\",\n\t\t\ttrace.WithAttributes(attribute.Int64(\"retry_num\", retryNum)))\n\n\t\terr := rs.next.Send(ctx, req)\n\t\tif err == nil {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Immediately drop data on permanent errors.\n\t\tif consumererror.IsPermanent(err) {\n\t\t\treturn fmt.Errorf(\"not retryable error: %w\", err)\n\t\t}\n\n\t\tif errReq, ok := req.(request.ErrorHandler); ok {\n\t\t\treq = errReq.OnError(err)\n\t\t}\n\n\t\tbackoffDelay := expBackoff.NextBackOff()\n\t\tif backoffDelay == backoff.Stop {\n\t\t\treturn fmt.Errorf(\"no more retries left: %w\", err)\n\t\t}\n\n\t\tthrottleErr := throttleRetry{}\n\t\tif errors.As(err, &throttleErr) {\n\t\t\tbackoffDelay = max(backoffDelay, throttleErr.delay)\n\t\t}\n\n\t\tnextRetryTime := time.Now().Add(backoffDelay)\n\t\tif !maxElapsedTime.IsZero() && maxElapsedTime.Before(nextRetryTime) {\n\t\t\t// The delay is longer than the maxElapsedTime.\n\t\t\treturn fmt.Errorf(\"no more retries left: %w\", err)\n\t\t}\n\n\t\tif deadline, has := ctx.Deadline(); has && deadline.Before(nextRetryTime) {\n\t\t\t// The delay is longer than the deadline.  There is no point in\n\t\t\t// waiting for cancelation.\n\t\t\treturn fmt.Errorf(\"request will be cancelled before next retry: %w\", err)\n\t\t}\n\n\t\tbackoffDelayStr := backoffDelay.String()\n\t\tspan.AddEvent(\n\t\t\t\"Exporting failed. Will retry the request after interval.\",\n\t\t\ttrace.WithAttributes(\n\t\t\t\tattribute.String(\"interval\", backoffDelayStr),\n\t\t\t\tattribute.String(\"error\", err.Error())))\n\t\trs.logger.Info(\n\t\t\t\"Exporting failed. Will retry the request after interval.\",\n\t\t\tzap.Error(err),\n\t\t\tzap.String(\"interval\", backoffDelayStr),\n\t\t)\n\t\tretryNum++\n\n\t\t// back-off, but get interrupted when shutting down or request is cancelled or timed out.\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn fmt.Errorf(\"request is cancelled or timed out: %w\", err)\n\t\tcase <-rs.stopCh:\n\t\t\treturn experr.NewShutdownErr(err)\n\t\tcase <-time.After(backoffDelay):\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/retry_sender_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configretry\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n)\n\nfunc TestRetrySenderDropOnPermanentError(t *testing.T) {\n\trCfg := configretry.NewDefaultBackOffConfig()\n\tsink := requesttest.NewSink()\n\texpErr := consumererror.NewPermanent(errors.New(\"bad data\"))\n\trs := newRetrySender(rCfg, exportertest.NewNopSettings(exportertest.NopType), sender.NewSender(sink.Export))\n\trequire.NoError(t, rs.Start(context.Background(), componenttest.NewNopHost()))\n\tsink.SetExportErr(expErr)\n\trequire.ErrorIs(t, rs.Send(context.Background(), &requesttest.FakeRequest{Items: 2}), expErr)\n\tsink.SetExportErr(expErr)\n\trequire.ErrorIs(t, rs.Send(context.Background(), &requesttest.FakeRequest{Items: 3}), expErr)\n\tassert.Equal(t, 0, sink.ItemsCount())\n\tassert.Equal(t, 0, sink.RequestsCount())\n\trequire.NoError(t, rs.Shutdown(context.Background()))\n}\n\nfunc TestRetrySenderSimpleRetry(t *testing.T) {\n\trCfg := configretry.NewDefaultBackOffConfig()\n\trCfg.InitialInterval = 0\n\tsink := requesttest.NewSink()\n\texpErr := errors.New(\"transient error\")\n\trs := newRetrySender(rCfg, exportertest.NewNopSettings(exportertest.NopType), sender.NewSender(sink.Export))\n\trequire.NoError(t, rs.Start(context.Background(), componenttest.NewNopHost()))\n\tsink.SetExportErr(expErr)\n\trequire.NoError(t, rs.Send(context.Background(), &requesttest.FakeRequest{Items: 2}))\n\tassert.Equal(t, 2, sink.ItemsCount())\n\tassert.Equal(t, 1, sink.RequestsCount())\n\trequire.NoError(t, rs.Shutdown(context.Background()))\n}\n\nfunc TestRetrySenderRetryPartial(t *testing.T) {\n\trCfg := configretry.NewDefaultBackOffConfig()\n\trCfg.InitialInterval = 0\n\tsink := requesttest.NewSink()\n\trs := newRetrySender(rCfg, exportertest.NewNopSettings(exportertest.NopType), sender.NewSender(sink.Export))\n\trequire.NoError(t, rs.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.NoError(t, rs.Send(context.Background(), &requesttest.FakeRequest{Items: 5, Partial: 3}))\n\tassert.Equal(t, 5, sink.ItemsCount())\n\tassert.Equal(t, 2, sink.RequestsCount())\n\trequire.NoError(t, rs.Shutdown(context.Background()))\n}\n\nfunc TestRetrySenderMaxElapsedTime(t *testing.T) {\n\trCfg := configretry.NewDefaultBackOffConfig()\n\trCfg.InitialInterval = time.Millisecond\n\trCfg.MaxElapsedTime = 100 * time.Millisecond\n\texpErr := errors.New(\"transient error\")\n\trs := newRetrySender(rCfg, exportertest.NewNopSettings(exportertest.NopType), sender.NewSender(func(context.Context, request.Request) error { return expErr }))\n\trequire.NoError(t, rs.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.ErrorIs(t, rs.Send(context.Background(), &requesttest.FakeRequest{Items: 2}), expErr)\n\trequire.NoError(t, rs.Shutdown(context.Background()))\n}\n\nfunc TestRetrySenderThrottleError(t *testing.T) {\n\trCfg := configretry.NewDefaultBackOffConfig()\n\trCfg.InitialInterval = 10 * time.Millisecond\n\tsink := requesttest.NewSink()\n\trs := newRetrySender(rCfg, exportertest.NewNopSettings(exportertest.NopType), sender.NewSender(sink.Export))\n\trequire.NoError(t, rs.Start(context.Background(), componenttest.NewNopHost()))\n\tretry := fmt.Errorf(\"wrappe error: %w\", NewThrottleRetry(errors.New(\"throttle error\"), 100*time.Millisecond))\n\tstart := time.Now()\n\tsink.SetExportErr(retry)\n\trequire.NoError(t, rs.Send(context.Background(), &requesttest.FakeRequest{Items: 5}))\n\t// The initial backoff is 10ms, but because of the throttle this should wait at least 100ms.\n\tassert.Less(t, 100*time.Millisecond, time.Since(start))\n\tassert.Equal(t, 5, sink.ItemsCount())\n\tassert.Equal(t, 1, sink.RequestsCount())\n\trequire.NoError(t, rs.Shutdown(context.Background()))\n}\n\nfunc TestRetrySenderWithContextTimeout(t *testing.T) {\n\tconst testTimeout = 10 * time.Second\n\trCfg := configretry.NewDefaultBackOffConfig()\n\trCfg.Enabled = true\n\t// First attempt after 100ms is attempted\n\trCfg.InitialInterval = 100 * time.Millisecond\n\trCfg.RandomizationFactor = 0\n\t// Second attempt is at twice the testTimeout\n\trCfg.Multiplier = float64(2 * testTimeout / rCfg.InitialInterval)\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tlogger, observed := observer.New(zap.InfoLevel)\n\tset.Logger = zap.New(logger)\n\trs := newRetrySender(rCfg, set, sender.NewSender(func(context.Context, request.Request) error { return errors.New(\"transient error\") }))\n\trequire.NoError(t, rs.Start(context.Background(), componenttest.NewNopHost()))\n\tstart := time.Now()\n\tctx, cancel := context.WithTimeout(context.Background(), testTimeout)\n\tdefer cancel()\n\trequire.ErrorContains(t,\n\t\trs.Send(ctx, &requesttest.FakeRequest{Items: 2}),\n\t\t\"request will be cancelled before next retry: transient error\")\n\tassert.Len(t, observed.All(), 1)\n\tassert.Equal(t, \"Exporting failed. Will retry the request after interval.\", observed.All()[0].Message)\n\trequire.Less(t, time.Since(start), testTimeout/2)\n\trequire.NoError(t, rs.Shutdown(context.Background()))\n}\n\nfunc TestRetrySenderWithCancelledContext(t *testing.T) {\n\trCfg := configretry.NewDefaultBackOffConfig()\n\trCfg.Enabled = true\n\t// First attempt after 1s is attempted\n\trCfg.InitialInterval = 1 * time.Second\n\trs := newRetrySender(rCfg, exportertest.NewNopSettings(exportertest.NopType), sender.NewSender(func(context.Context, request.Request) error { return errors.New(\"transient error\") }))\n\trequire.NoError(t, rs.Start(context.Background(), componenttest.NewNopHost()))\n\tstart := time.Now()\n\tctx, cancel := context.WithCancelCause(context.Background())\n\tgo func() {\n\t\t<-time.After(100 * time.Millisecond)\n\t\tcancel(errors.New(\"my reason\"))\n\t}()\n\trequire.ErrorContains(t,\n\t\trs.Send(ctx, &requesttest.FakeRequest{Items: 2}),\n\t\t\"request is cancelled or timed out: transient error\")\n\trequire.Less(t, time.Since(start), 1*time.Second)\n\trequire.NoError(t, rs.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/sender/sender.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage sender // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\ntype Sender[T any] interface {\n\tcomponent.Component\n\tSend(context.Context, T) error\n}\n\ntype SendFunc[T any] func(ctx context.Context, data T) error\n\nfunc NewSender[T any](consFunc SendFunc[T]) Sender[T] {\n\treturn &sender[T]{consFunc: consFunc}\n}\n\n// sender is a Sender that emits the incoming request to the exporter consumer func.\ntype sender[T any] struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsFunc SendFunc[T]\n}\n\nfunc (es *sender[T]) Send(ctx context.Context, req T) error {\n\treturn es.consFunc(ctx, req)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/sender/sender_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage sender\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestExportSenderRightArguments(t *testing.T) {\n\tes := NewSender[int64](func(_ context.Context, data int64) error {\n\t\tassert.Equal(t, int64(1), data)\n\t\treturn nil\n\t})\n\trequire.NoError(t, es.Send(context.Background(), int64(1)))\n}\n\nfunc TestExportSenderReturnsError(t *testing.T) {\n\terr := errors.New(\"test error\")\n\tes := NewSender[int64](func(_ context.Context, data int64) error {\n\t\tassert.Equal(t, int64(1), data)\n\t\treturn err\n\t})\n\trequire.ErrorIs(t, es.Send(context.Background(), int64(1)), err)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/sendertest/sendertest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage sendertest // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sendertest\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender\"\n)\n\nfunc NewNopSenderFunc[T any]() sender.SendFunc[T] {\n\treturn func(context.Context, T) error {\n\t\treturn nil\n\t}\n}\n\nfunc NewErrSenderFunc[T any](err error) sender.SendFunc[T] {\n\treturn func(context.Context, T) error {\n\t\treturn err\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/sendertest/sendertest_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage sendertest\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestNewNopSenderFunc(t *testing.T) {\n\tsender := NewNopSenderFunc[int]()\n\trequire.NoError(t, sender(context.Background(), 1))\n}\n\nfunc TestNewErrSenderFunc(t *testing.T) {\n\terr := errors.New(\"test\")\n\tsender := NewErrSenderFunc[int](err)\n\trequire.ErrorIs(t, sender(context.Background(), 1), err)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/sizer/logs_sizer.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage sizer // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\ntype LogsSizer interface {\n\tLogsSize(ld plog.Logs) int\n\tResourceLogsSize(rl plog.ResourceLogs) int\n\tScopeLogsSize(sl plog.ScopeLogs) int\n\tLogRecordSize(lr plog.LogRecord) int\n\n\t// DeltaSize returns the delta size when a ResourceLog, ScopeLog or LogRecord is added.\n\tDeltaSize(newItemSize int) int\n}\n\n// LogsBytesSizer returns the byte size of serialized protos.\ntype LogsBytesSizer struct {\n\tplog.ProtoMarshaler\n\tprotoDeltaSizer\n}\n\n// LogsCountSizer returns the nunmber of logs entries.\ntype LogsCountSizer struct{}\n\nfunc (s *LogsCountSizer) LogsSize(ld plog.Logs) int {\n\treturn ld.LogRecordCount()\n}\n\nfunc (s *LogsCountSizer) ResourceLogsSize(rl plog.ResourceLogs) int {\n\tcount := 0\n\tfor k := 0; k < rl.ScopeLogs().Len(); k++ {\n\t\tcount += rl.ScopeLogs().At(k).LogRecords().Len()\n\t}\n\treturn count\n}\n\nfunc (s *LogsCountSizer) ScopeLogsSize(sl plog.ScopeLogs) int {\n\treturn sl.LogRecords().Len()\n}\n\nfunc (s *LogsCountSizer) LogRecordSize(_ plog.LogRecord) int {\n\treturn 1\n}\n\nfunc (s *LogsCountSizer) DeltaSize(newItemSize int) int {\n\treturn newItemSize\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/sizer/logs_sizer_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\npackage sizer // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestLogsCountSizer(t *testing.T) {\n\tld := testdata.GenerateLogs(5)\n\tsizer := LogsCountSizer{}\n\trequire.Equal(t, 5, sizer.LogsSize(ld))\n\n\trl := ld.ResourceLogs().At(0)\n\trequire.Equal(t, 5, sizer.ResourceLogsSize(rl))\n\n\tsl := rl.ScopeLogs().At(0)\n\trequire.Equal(t, 5, sizer.ScopeLogsSize(sl))\n\n\trequire.Equal(t, 1, sizer.LogRecordSize(sl.LogRecords().At(0)))\n\trequire.Equal(t, 1, sizer.LogRecordSize(sl.LogRecords().At(1)))\n\trequire.Equal(t, 1, sizer.LogRecordSize(sl.LogRecords().At(2)))\n\trequire.Equal(t, 1, sizer.LogRecordSize(sl.LogRecords().At(3)))\n\trequire.Equal(t, 1, sizer.LogRecordSize(sl.LogRecords().At(4)))\n\n\tprevSize := sizer.ScopeLogsSize(sl)\n\tlr := sl.LogRecords().At(2)\n\tlr.CopyTo(sl.LogRecords().AppendEmpty())\n\trequire.Equal(t, sizer.ScopeLogsSize(sl), prevSize+sizer.DeltaSize(sizer.LogRecordSize(lr)))\n}\n\nfunc TestLogsBytesSizer(t *testing.T) {\n\tld := testdata.GenerateLogs(5)\n\tsizer := LogsBytesSizer{}\n\trequire.Equal(t, 545, sizer.LogsSize(ld))\n\n\trl := ld.ResourceLogs().At(0)\n\trequire.Equal(t, 542, sizer.ResourceLogsSize(rl))\n\n\tsl := rl.ScopeLogs().At(0)\n\trequire.Equal(t, 497, sizer.ScopeLogsSize(sl))\n\n\trequire.Equal(t, 109, sizer.LogRecordSize(sl.LogRecords().At(0)))\n\trequire.Equal(t, 79, sizer.LogRecordSize(sl.LogRecords().At(1)))\n\trequire.Equal(t, 109, sizer.LogRecordSize(sl.LogRecords().At(2)))\n\trequire.Equal(t, 79, sizer.LogRecordSize(sl.LogRecords().At(3)))\n\trequire.Equal(t, 109, sizer.LogRecordSize(sl.LogRecords().At(4)))\n\n\tprevSize := sizer.ScopeLogsSize(sl)\n\tlr := sl.LogRecords().At(2)\n\tlr.CopyTo(sl.LogRecords().AppendEmpty())\n\trequire.Equal(t, sizer.ScopeLogsSize(sl), prevSize+sizer.DeltaSize(sizer.LogRecordSize(lr)))\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/sizer/metrics_sizer.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage sizer // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n) // MetricsCountSizer returns the nunmber of metrics entries.\n\ntype MetricsSizer interface {\n\tMetricsSize(md pmetric.Metrics) (count int)\n\tResourceMetricsSize(rm pmetric.ResourceMetrics) (count int)\n\tScopeMetricsSize(sm pmetric.ScopeMetrics) (count int)\n\tMetricSize(m pmetric.Metric) int\n\tDeltaSize(newItemSize int) int\n\tNumberDataPointSize(ndp pmetric.NumberDataPoint) int\n\tHistogramDataPointSize(hdp pmetric.HistogramDataPoint) int\n\tExponentialHistogramDataPointSize(ehdp pmetric.ExponentialHistogramDataPoint) int\n\tSummaryDataPointSize(sdps pmetric.SummaryDataPoint) int\n}\n\ntype MetricsBytesSizer struct {\n\tpmetric.ProtoMarshaler\n\tprotoDeltaSizer\n}\n\nvar _ MetricsSizer = &MetricsBytesSizer{}\n\ntype MetricsCountSizer struct{}\n\nvar _ MetricsSizer = &MetricsCountSizer{}\n\nfunc (s *MetricsCountSizer) MetricsSize(md pmetric.Metrics) int {\n\treturn md.DataPointCount()\n}\n\nfunc (s *MetricsCountSizer) ResourceMetricsSize(rm pmetric.ResourceMetrics) (count int) {\n\tfor i := 0; i < rm.ScopeMetrics().Len(); i++ {\n\t\tcount += s.ScopeMetricsSize(rm.ScopeMetrics().At(i))\n\t}\n\treturn count\n}\n\nfunc (s *MetricsCountSizer) ScopeMetricsSize(sm pmetric.ScopeMetrics) (count int) {\n\tfor i := 0; i < sm.Metrics().Len(); i++ {\n\t\tcount += s.MetricSize(sm.Metrics().At(i))\n\t}\n\treturn count\n}\n\nfunc (s *MetricsCountSizer) MetricSize(m pmetric.Metric) int {\n\tswitch m.Type() {\n\tcase pmetric.MetricTypeGauge:\n\t\treturn m.Gauge().DataPoints().Len()\n\tcase pmetric.MetricTypeSum:\n\t\treturn m.Sum().DataPoints().Len()\n\tcase pmetric.MetricTypeHistogram:\n\t\treturn m.Histogram().DataPoints().Len()\n\tcase pmetric.MetricTypeExponentialHistogram:\n\t\treturn m.ExponentialHistogram().DataPoints().Len()\n\tcase pmetric.MetricTypeSummary:\n\t\treturn m.Summary().DataPoints().Len()\n\t}\n\treturn 0\n}\n\nfunc (s *MetricsCountSizer) DeltaSize(newItemSize int) int {\n\treturn newItemSize\n}\n\nfunc (s *MetricsCountSizer) NumberDataPointSize(_ pmetric.NumberDataPoint) int {\n\treturn 1\n}\n\nfunc (s *MetricsCountSizer) HistogramDataPointSize(_ pmetric.HistogramDataPoint) int {\n\treturn 1\n}\n\nfunc (s *MetricsCountSizer) ExponentialHistogramDataPointSize(_ pmetric.ExponentialHistogramDataPoint) int {\n\treturn 1\n}\n\nfunc (s *MetricsCountSizer) SummaryDataPointSize(_ pmetric.SummaryDataPoint) int {\n\treturn 1\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/sizer/metrics_sizer_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\npackage sizer // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestMetricsCountSizer(t *testing.T) {\n\tmd := testdata.GenerateMetrics(7)\n\tsizer := MetricsCountSizer{}\n\trequire.Equal(t, 14, sizer.MetricsSize(md))\n\n\trm := md.ResourceMetrics().At(0)\n\trequire.Equal(t, 14, sizer.ResourceMetricsSize(rm))\n\n\tsm := rm.ScopeMetrics().At(0)\n\trequire.Equal(t, 14, sizer.ScopeMetricsSize(sm))\n\n\t// Test different metric types\n\trequire.Equal(t, 2, sizer.MetricSize(sm.Metrics().At(0)))\n\n\t// Test data point sizes\n\trequire.Equal(t, 1, sizer.NumberDataPointSize(sm.Metrics().At(0).Gauge().DataPoints().At(0)))\n\trequire.Equal(t, 1, sizer.NumberDataPointSize(sm.Metrics().At(1).Gauge().DataPoints().At(0)))\n\trequire.Equal(t, 1, sizer.NumberDataPointSize(sm.Metrics().At(2).Sum().DataPoints().At(0)))\n\trequire.Equal(t, 1, sizer.NumberDataPointSize(sm.Metrics().At(3).Sum().DataPoints().At(0)))\n\trequire.Equal(t, 1, sizer.HistogramDataPointSize(sm.Metrics().At(4).Histogram().DataPoints().At(0)))\n\trequire.Equal(t, 1, sizer.ExponentialHistogramDataPointSize(sm.Metrics().At(5).ExponentialHistogram().DataPoints().At(0)))\n\trequire.Equal(t, 1, sizer.SummaryDataPointSize(sm.Metrics().At(6).Summary().DataPoints().At(0)))\n\n\tprevSize := sizer.ScopeMetricsSize(sm)\n\tsm.Metrics().At(0).CopyTo(sm.Metrics().AppendEmpty())\n\trequire.Equal(t, sizer.ScopeMetricsSize(sm), prevSize+sizer.DeltaSize(sizer.MetricSize(sm.Metrics().At(0))))\n}\n\nfunc TestMetricsBytesSizer(t *testing.T) {\n\tmd := testdata.GenerateMetrics(7)\n\tsizer := MetricsBytesSizer{}\n\trequire.Equal(t, 1594, sizer.MetricsSize(md))\n\n\trm := md.ResourceMetrics().At(0)\n\trequire.Equal(t, 1591, sizer.ResourceMetricsSize(rm))\n\n\tsm := rm.ScopeMetrics().At(0)\n\trequire.Equal(t, 1546, sizer.ScopeMetricsSize(sm))\n\n\t// Test different metric types\n\trequire.Equal(t, 130, sizer.MetricSize(sm.Metrics().At(0)))\n\n\t// Test data point sizes\n\trequire.Equal(t, 55, sizer.NumberDataPointSize(sm.Metrics().At(0).Gauge().DataPoints().At(0)))\n\trequire.Equal(t, 83, sizer.NumberDataPointSize(sm.Metrics().At(1).Gauge().DataPoints().At(0)))\n\trequire.Equal(t, 55, sizer.NumberDataPointSize(sm.Metrics().At(2).Sum().DataPoints().At(0)))\n\trequire.Equal(t, 83, sizer.NumberDataPointSize(sm.Metrics().At(3).Sum().DataPoints().At(0)))\n\trequire.Equal(t, 92, sizer.HistogramDataPointSize(sm.Metrics().At(4).Histogram().DataPoints().At(0)))\n\trequire.Equal(t, 119, sizer.ExponentialHistogramDataPointSize(sm.Metrics().At(5).ExponentialHistogram().DataPoints().At(0)))\n\trequire.Equal(t, 92, sizer.SummaryDataPointSize(sm.Metrics().At(6).Summary().DataPoints().At(0)))\n\n\tprevSize := sizer.ScopeMetricsSize(sm)\n\tsm.Metrics().At(0).CopyTo(sm.Metrics().AppendEmpty())\n\trequire.Equal(t, sizer.ScopeMetricsSize(sm), prevSize+sizer.DeltaSize(sizer.MetricSize(sm.Metrics().At(0))))\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/sizer/profiles_sizer.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage sizer // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n)\n\ntype ProfilesSizer interface {\n\tProfilesSize(pd pprofile.Profiles) int\n\tResourceProfilesSize(rp pprofile.ResourceProfiles) int\n\tScopeProfilesSize(sp pprofile.ScopeProfiles) int\n\tProfileSize(p pprofile.Profile) int\n\tDeltaSize(newItemSize int) int\n}\n\n// TracesBytesSizer returns the byte size of serialized protos.\ntype ProfilesBytesSizer struct {\n\tpprofile.ProtoMarshaler\n\tprotoDeltaSizer\n}\n\nvar _ ProfilesSizer = (*ProfilesBytesSizer)(nil)\n\n// ProfilesCountSizer returns the number of profiles in the profiles.\ntype ProfilesCountSizer struct{}\n\nvar _ ProfilesSizer = (*ProfilesCountSizer)(nil)\n\nfunc (s *ProfilesCountSizer) ProfilesSize(pd pprofile.Profiles) int {\n\treturn pd.SampleCount()\n}\n\nfunc (s *ProfilesCountSizer) ResourceProfilesSize(rp pprofile.ResourceProfiles) int {\n\tcount := 0\n\tfor k := 0; k < rp.ScopeProfiles().Len(); k++ {\n\t\tcount += rp.ScopeProfiles().At(k).Profiles().Len()\n\t}\n\treturn count\n}\n\nfunc (s *ProfilesCountSizer) ScopeProfilesSize(sp pprofile.ScopeProfiles) int {\n\treturn sp.Profiles().Len()\n}\n\nfunc (s *ProfilesCountSizer) ProfileSize(_ pprofile.Profile) int {\n\treturn 1\n}\n\nfunc (s *ProfilesCountSizer) DeltaSize(newItemSize int) int {\n\treturn newItemSize\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/sizer/proto_delta_sizer.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage sizer // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\nimport (\n\tmath_bits \"math/bits\"\n)\n\ntype protoDeltaSizer struct{}\n\n// DeltaSize() returns the delta size of a proto slice when a new item is added.\n// Example:\n//\n//\tprevSize := proto1.Size()\n//\tproto1.RepeatedField().AppendEmpty() = proto2\n//\n// Then currSize of proto1 can be calculated as\n//\n//\tcurrSize := (prevSize + sizer.DeltaSize(proto2.Size()))\n//\n// This is derived from:\n// - opentelemetry-collector/pdata/internal/data/protogen/metrics/v1/metrics.pb.go\n// - opentelemetry-collector/pdata/internal/data/protogen/logs/v1/logs.pb.go\n// - opentelemetry-collector/pdata/internal/data/protogen/traces/v1/traces.pb.go\n// - opentelemetry-collector/pdata/internal/data/protogen/profiles/v1development/profiles.pb.go\n// which is generated with gogo/protobuf.\nfunc (s *protoDeltaSizer) DeltaSize(newItemSize int) int {\n\treturn 1 + newItemSize + sov(uint64(newItemSize))\n}\n\nfunc sov(x uint64) int {\n\treturn (math_bits.Len64(x|1) + 6) / 7\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/sizer/proto_delta_sizer_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage sizer\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestMetricsBytesDeltaSize(t *testing.T) {\n\tsizer := protoDeltaSizer{}\n\trequire.Equal(t, 129, sizer.DeltaSize(127))\n\trequire.Equal(t, 131, sizer.DeltaSize(128))\n\trequire.Equal(t, 242, sizer.DeltaSize(239))\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/sizer/traces_sizer.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage sizer // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\ntype TracesSizer interface {\n\tTracesSize(ld ptrace.Traces) int\n\tResourceSpansSize(rs ptrace.ResourceSpans) int\n\tScopeSpansSize(ss ptrace.ScopeSpans) int\n\tSpanSize(span ptrace.Span) int\n\t// DeltaSize() returns the delta size when a span is added.\n\tDeltaSize(newItemSize int) int\n}\n\n// TracesBytesSizer returns the byte size of serialized protos.\ntype TracesBytesSizer struct {\n\tptrace.ProtoMarshaler\n\tprotoDeltaSizer\n}\n\n// TracesCountSizer returns the number of spans in the traces.\ntype TracesCountSizer struct{}\n\nfunc (s *TracesCountSizer) TracesSize(td ptrace.Traces) int {\n\treturn td.SpanCount()\n}\n\nfunc (s *TracesCountSizer) ResourceSpansSize(rs ptrace.ResourceSpans) int {\n\tcount := 0\n\tfor k := 0; k < rs.ScopeSpans().Len(); k++ {\n\t\tcount += rs.ScopeSpans().At(k).Spans().Len()\n\t}\n\treturn count\n}\n\nfunc (s *TracesCountSizer) ScopeSpansSize(ss ptrace.ScopeSpans) int {\n\treturn ss.Spans().Len()\n}\n\nfunc (s *TracesCountSizer) SpanSize(_ ptrace.Span) int {\n\treturn 1\n}\n\nfunc (s *TracesCountSizer) DeltaSize(newItemSize int) int {\n\treturn newItemSize\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/sizer/traces_sizer_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\npackage sizer\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestTracesCountSizer(t *testing.T) {\n\ttd := testdata.GenerateTraces(5)\n\tsizer := TracesCountSizer{}\n\trequire.Equal(t, 5, sizer.TracesSize(td))\n\n\trs := td.ResourceSpans().At(0)\n\trequire.Equal(t, 5, sizer.ResourceSpansSize(rs))\n\n\tss := rs.ScopeSpans().At(0)\n\trequire.Equal(t, 5, sizer.ScopeSpansSize(ss))\n\n\trequire.Equal(t, 1, sizer.SpanSize(ss.Spans().At(0)))\n\trequire.Equal(t, 1, sizer.SpanSize(ss.Spans().At(1)))\n\trequire.Equal(t, 1, sizer.SpanSize(ss.Spans().At(2)))\n\trequire.Equal(t, 1, sizer.SpanSize(ss.Spans().At(3)))\n\trequire.Equal(t, 1, sizer.SpanSize(ss.Spans().At(4)))\n\n\tprevSize := sizer.ScopeSpansSize(ss)\n\tspan := ss.Spans().At(2)\n\tspan.CopyTo(ss.Spans().AppendEmpty())\n\trequire.Equal(t, sizer.ScopeSpansSize(ss), prevSize+sizer.DeltaSize(sizer.SpanSize(span)))\n}\n\nfunc TestTracesBytesSizer(t *testing.T) {\n\ttd := testdata.GenerateTraces(2)\n\tsizer := TracesBytesSizer{}\n\trequire.Equal(t, 338, sizer.TracesSize(td))\n\n\trs := td.ResourceSpans().At(0)\n\trequire.Equal(t, 335, sizer.ResourceSpansSize(rs))\n\n\tss := rs.ScopeSpans().At(0)\n\trequire.Equal(t, 290, sizer.ScopeSpansSize(ss))\n\n\trequire.Equal(t, 187, sizer.SpanSize(ss.Spans().At(0)))\n\trequire.Equal(t, 96, sizer.SpanSize(ss.Spans().At(1)))\n\n\tprevSize := sizer.ScopeSpansSize(ss)\n\tspan := ss.Spans().At(1)\n\tspanSize := sizer.SpanSize(span)\n\tspan.CopyTo(ss.Spans().AppendEmpty())\n\tds := sizer.DeltaSize(spanSize)\n\trequire.Equal(t, prevSize+ds, sizer.ScopeSpansSize(ss))\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/storagetest/mock_storage.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage storagetest // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/storagetest\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/extension/xextension/storage\"\n)\n\ntype mockStorageExtension struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tst             sync.Map\n\tgetClientError error\n\texecutionDelay time.Duration\n}\n\nfunc (m *mockStorageExtension) GetClient(context.Context, component.Kind, component.ID, string) (storage.Client, error) {\n\tif m.getClientError != nil {\n\t\treturn nil, m.getClientError\n\t}\n\treturn &MockStorageClient{st: &m.st, closed: &atomic.Bool{}, executionDelay: m.executionDelay}, nil\n}\n\nfunc NewMockStorageExtension(getClientError error) storage.Extension {\n\treturn NewMockStorageExtensionWithDelay(getClientError, 0)\n}\n\nfunc NewMockStorageExtensionWithDelay(getClientError error, executionDelay time.Duration) storage.Extension {\n\treturn &mockStorageExtension{\n\t\tgetClientError: getClientError,\n\t\texecutionDelay: executionDelay,\n\t}\n}\n\ntype MockStorageClient struct {\n\tst             *sync.Map\n\tclosed         *atomic.Bool\n\texecutionDelay time.Duration // simulate real storage client delay\n}\n\nfunc (m *MockStorageClient) Get(ctx context.Context, s string) ([]byte, error) {\n\tgetOp := storage.GetOperation(s)\n\terr := m.Batch(ctx, getOp)\n\treturn getOp.Value, err\n}\n\nfunc (m *MockStorageClient) Set(ctx context.Context, s string, bytes []byte) error {\n\treturn m.Batch(ctx, storage.SetOperation(s, bytes))\n}\n\nfunc (m *MockStorageClient) Delete(ctx context.Context, s string) error {\n\treturn m.Batch(ctx, storage.DeleteOperation(s))\n}\n\nfunc (m *MockStorageClient) Close(context.Context) error {\n\tm.closed.Store(true)\n\treturn nil\n}\n\nfunc (m *MockStorageClient) Batch(_ context.Context, ops ...*storage.Operation) error {\n\tif m.IsClosed() {\n\t\tpanic(\"client already closed\")\n\t}\n\tif m.executionDelay != 0 {\n\t\ttime.Sleep(m.executionDelay)\n\t}\n\tfor _, op := range ops {\n\t\tswitch op.Type {\n\t\tcase storage.Get:\n\t\t\tval, found := m.st.Load(op.Key)\n\t\t\tif !found {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\top.Value = val.([]byte)\n\t\tcase storage.Set:\n\t\t\tm.st.Store(op.Key, op.Value)\n\t\tcase storage.Delete:\n\t\t\tm.st.Delete(op.Key)\n\t\tdefault:\n\t\t\treturn errors.New(\"wrong operation type\")\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc (m *MockStorageClient) IsClosed() bool {\n\treturn m.closed.Load()\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/timeout_sender.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender\"\n)\n\n// TimeoutConfig for timeout. The timeout applies to individual attempts to send data to the backend.\ntype TimeoutConfig struct {\n\t// Timeout is the timeout for every attempt to send data to the backend.\n\t// A zero timeout means no timeout.\n\tTimeout time.Duration `mapstructure:\"timeout\"`\n}\n\nfunc (ts *TimeoutConfig) Validate() error {\n\t// Negative timeouts are not acceptable, since all sends will fail.\n\tif ts.Timeout < 0 {\n\t\treturn errors.New(\"'timeout' must be non-negative\")\n\t}\n\treturn nil\n}\n\n// NewDefaultTimeoutConfig returns the default config for TimeoutConfig.\nfunc NewDefaultTimeoutConfig() TimeoutConfig {\n\treturn TimeoutConfig{\n\t\tTimeout: 5 * time.Second,\n\t}\n}\n\n// timeoutSender is a requestSender that adds a `timeout` to every request that passes this sender.\ntype timeoutSender[T any] struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tcfg  TimeoutConfig\n\tnext sender.Sender[T]\n}\n\nfunc newTimeoutSender[T any](cfg TimeoutConfig, next sender.Sender[T]) sender.Sender[T] {\n\treturn &timeoutSender[T]{cfg: cfg, next: next}\n}\n\nfunc (ts *timeoutSender[T]) Send(ctx context.Context, req T) error {\n\t// Intentionally don't overwrite the context inside the request, because in case of retries deadline will not be\n\t// updated because this deadline most likely is before the next one.\n\ttCtx, cancelFunc := context.WithTimeout(ctx, ts.cfg.Timeout)\n\tdefer cancelFunc()\n\treturn ts.next.Send(tCtx, req)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/internal/timeout_sender_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sender\"\n)\n\nfunc TestNewDefaultTimeoutConfig(t *testing.T) {\n\tcfg := NewDefaultTimeoutConfig()\n\trequire.NoError(t, cfg.Validate())\n\tassert.Equal(t, TimeoutConfig{Timeout: 5 * time.Second}, cfg)\n}\n\nfunc TestInvalidTimeout(t *testing.T) {\n\tcfg := NewDefaultTimeoutConfig()\n\trequire.NoError(t, cfg.Validate())\n\tcfg.Timeout = -1\n\tassert.Error(t, cfg.Validate())\n}\n\nfunc TestNewTimeoutSender(t *testing.T) {\n\tcfg := TimeoutConfig{Timeout: 5 * time.Second}\n\tts := newTimeoutSender(cfg, sender.NewSender(func(ctx context.Context, data int64) error {\n\t\tdeadline, ok := ctx.Deadline()\n\t\tassert.True(t, ok)\n\t\ttimeout := time.Since(deadline)\n\t\tassert.LessOrEqual(t, timeout, 5*time.Second)\n\t\tassert.GreaterOrEqual(t, 4*time.Second, timeout)\n\t\tassert.Equal(t, int64(7), data)\n\t\treturn nil\n\t}))\n\trequire.NoError(t, ts.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.NoError(t, ts.Send(context.Background(), 7))\n\trequire.NoError(t, ts.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "exporter/exporterhelper/logs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exporterhelper // import \"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n)\n\n// NewLogs creates an exporter.Logs that records observability logs and wraps every request with a Span.\nfunc NewLogs(\n\tctx context.Context,\n\tset exporter.Settings,\n\tcfg component.Config,\n\tpusher consumer.ConsumeLogsFunc,\n\toptions ...Option,\n) (exporter.Logs, error) {\n\tif cfg == nil {\n\t\treturn nil, errNilConfig\n\t}\n\tif pusher == nil {\n\t\treturn nil, errNilPushLogs\n\t}\n\treturn internal.NewLogsRequest(ctx, set, queuebatch.RequestFromLogs(), queuebatch.RequestConsumeFromLogs(pusher),\n\t\tappend([]Option{internal.WithQueueBatchSettings(queuebatch.NewLogsQueueBatchSettings())}, options...)...)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/logs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exporterhelper\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\tsdktrace \"go.opentelemetry.io/otel/sdk/trace\"\n\t\"go.opentelemetry.io/otel/sdk/trace/tracetest\"\n\tsemconv \"go.opentelemetry.io/otel/semconv/v1.38.0\"\n\t\"go.opentelemetry.io/otel/trace\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/hosttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/metadatatest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/oteltest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sendertest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/storagetest\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nconst (\n\tfakeLogsParentSpanName = \"fake_logs_parent_span_name\"\n)\n\nvar (\n\tfakeLogsName   = component.MustNewIDWithName(\"fake_logs_exporter\", \"with_name\")\n\tfakeLogsConfig = struct{}{}\n)\n\nfunc TestLogs_InvalidName(t *testing.T) {\n\tle, err := NewLogs(context.Background(), exportertest.NewNopSettings(exportertest.NopType), nil, newPushLogsData(nil))\n\trequire.Nil(t, le)\n\trequire.Equal(t, errNilConfig, err)\n}\n\nfunc TestLogs_NilLogger(t *testing.T) {\n\tle, err := NewLogs(context.Background(), exporter.Settings{}, &fakeLogsConfig, newPushLogsData(nil))\n\trequire.Nil(t, le)\n\trequire.Equal(t, errNilLogger, err)\n}\n\nfunc TestLogs_NilPushLogsData(t *testing.T) {\n\tle, err := NewLogs(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeLogsConfig, nil)\n\trequire.Nil(t, le)\n\trequire.Equal(t, errNilPushLogs, err)\n}\n\nfunc TestLogs_Default(t *testing.T) {\n\tld := plog.NewLogs()\n\tle, err := NewLogs(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeLogsConfig, newPushLogsData(nil))\n\tassert.NotNil(t, le)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, consumer.Capabilities{MutatesData: false}, le.Capabilities())\n\tassert.NoError(t, le.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, le.ConsumeLogs(context.Background(), ld))\n\tassert.NoError(t, le.Shutdown(context.Background()))\n}\n\nfunc TestLogs_WithCapabilities(t *testing.T) {\n\tcapabilities := consumer.Capabilities{MutatesData: true}\n\tle, err := NewLogs(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeLogsConfig, newPushLogsData(nil), WithCapabilities(capabilities))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\n\tassert.Equal(t, capabilities, le.Capabilities())\n}\n\nfunc TestLogs_Default_ReturnError(t *testing.T) {\n\tld := plog.NewLogs()\n\twant := errors.New(\"my_error\")\n\tle, err := NewLogs(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeLogsConfig, newPushLogsData(want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\trequire.Equal(t, want, le.ConsumeLogs(context.Background(), ld))\n}\n\nfunc TestLogs_WithPersistentQueue(t *testing.T) {\n\tfgOrigReadState := queue.PersistRequestContextOnRead\n\tfgOrigWriteState := queue.PersistRequestContextOnWrite\n\tqCfg := configoptional.Some(NewDefaultQueueConfig())\n\tstorageID := component.MustNewIDWithName(\"file_storage\", \"storage\")\n\tqCfg.Get().StorageID = &storageID\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tset.ID = component.MustNewIDWithName(\"test_logs\", \"with_persistent_queue\")\n\thost := hosttest.NewHost(map[component.ID]component.Component{\n\t\tstorageID: storagetest.NewMockStorageExtension(nil),\n\t})\n\tspanCtx := oteltest.FakeSpanContext(t)\n\n\ttests := []struct {\n\t\tname             string\n\t\tfgEnabledOnWrite bool\n\t\tfgEnabledOnRead  bool\n\t\twantData         bool\n\t\twantSpanCtx      bool\n\t}{\n\t\t{\n\t\t\tname:     \"feature_gate_disabled_on_write_and_read\",\n\t\t\twantData: true,\n\t\t},\n\t\t{\n\t\t\tname:             \"feature_gate_enabled_on_write_and_read\",\n\t\t\tfgEnabledOnWrite: true,\n\t\t\tfgEnabledOnRead:  true,\n\t\t\twantData:         true,\n\t\t\twantSpanCtx:      true,\n\t\t},\n\t\t{\n\t\t\tname:            \"feature_gate_disabled_on_write_enabled_on_read\",\n\t\t\twantData:        true,\n\t\t\tfgEnabledOnRead: true,\n\t\t},\n\t\t{\n\t\t\tname:             \"feature_gate_enabled_on_write_disabled_on_read\",\n\t\t\tfgEnabledOnWrite: true,\n\t\t\twantData:         false, // going back from enabled to disabled feature gate isn't supported\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tqueue.PersistRequestContextOnRead = func() bool { return tt.fgEnabledOnRead }\n\t\t\tqueue.PersistRequestContextOnWrite = func() bool { return tt.fgEnabledOnWrite }\n\t\t\tt.Cleanup(func() {\n\t\t\t\tqueue.PersistRequestContextOnRead = fgOrigReadState\n\t\t\t\tqueue.PersistRequestContextOnWrite = fgOrigWriteState\n\t\t\t})\n\n\t\t\tls := consumertest.LogsSink{}\n\t\t\tte, err := NewLogs(context.Background(), set, &fakeLogsConfig, ls.ConsumeLogs, WithQueue(qCfg))\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, te.Start(context.Background(), host))\n\t\t\tt.Cleanup(func() { require.NoError(t, te.Shutdown(context.Background())) })\n\n\t\t\tlogs := testdata.GenerateLogs(2)\n\t\t\trequire.NoError(t, te.ConsumeLogs(trace.ContextWithSpanContext(context.Background(), spanCtx), logs))\n\t\t\tif tt.wantData {\n\t\t\t\trequire.Eventually(t, func() bool {\n\t\t\t\t\treturn len(ls.AllLogs()) == 1 && ls.LogRecordCount() == 2\n\t\t\t\t}, 500*time.Millisecond, 10*time.Millisecond)\n\t\t\t}\n\n\t\t\t// check that the span context is persisted if the feature gate is enabled\n\t\t\tif tt.wantSpanCtx {\n\t\t\t\tassert.Len(t, ls.Contexts(), 1)\n\t\t\t\tassert.Equal(t, spanCtx, trace.SpanContextFromContext(ls.Contexts()[0]))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestLogs_WithRecordMetrics(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tle, err := NewLogs(context.Background(), exporter.Settings{ID: fakeLogsName, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, &fakeLogsConfig, newPushLogsData(nil))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\n\tcheckRecordedMetricsForLogs(t, tt, fakeLogsName, le, nil)\n}\n\nfunc TestLogs_pLogModifiedDownStream_WithRecordMetrics(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tle, err := NewLogs(context.Background(), exporter.Settings{ID: fakeLogsName, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, &fakeLogsConfig, newPushLogsDataModifiedDownstream(nil), WithCapabilities(consumer.Capabilities{MutatesData: true}))\n\tassert.NotNil(t, le)\n\trequire.NoError(t, err)\n\tld := testdata.GenerateLogs(2)\n\n\trequire.NoError(t, le.ConsumeLogs(context.Background(), ld))\n\tassert.Equal(t, 0, ld.LogRecordCount())\n\n\tmetadatatest.AssertEqualExporterSentLogRecords(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(\"exporter\", fakeLogsName.String())),\n\t\t\t\tValue: int64(2),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\nfunc TestLogsRequest_WithRecordMetrics(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tle, err := internal.NewLogsRequest(context.Background(),\n\t\texporter.Settings{ID: fakeLogsName, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t\trequesttest.RequestFromLogsFunc(nil), sendertest.NewNopSenderFunc[request.Request]())\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\n\tcheckRecordedMetricsForLogs(t, tt, fakeLogsName, le, nil)\n}\n\nfunc TestLogs_WithRecordMetrics_ReturnError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tle, err := NewLogs(context.Background(), exporter.Settings{ID: fakeLogsName, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, &fakeLogsConfig, newPushLogsData(want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\n\tcheckRecordedMetricsForLogs(t, tt, fakeLogsName, le, want)\n}\n\nfunc TestLogsRequest_WithRecordMetrics_ExportError(t *testing.T) {\n\twant := errors.New(\"export_error\")\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tle, err := internal.NewLogsRequest(context.Background(), exporter.Settings{ID: fakeLogsName, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t\trequesttest.RequestFromLogsFunc(nil), sendertest.NewErrSenderFunc[request.Request](want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\n\tcheckRecordedMetricsForLogs(t, tt, fakeLogsName, le, want)\n}\n\nfunc TestLogs_WithSpan(t *testing.T) {\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tsr := new(tracetest.SpanRecorder)\n\tset.TracerProvider = sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))\n\totel.SetTracerProvider(set.TracerProvider)\n\tdefer otel.SetTracerProvider(nooptrace.NewTracerProvider())\n\n\tle, err := NewLogs(context.Background(), set, &fakeLogsConfig, newPushLogsData(nil))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\tcheckWrapSpanForLogs(t, sr, set.TracerProvider.Tracer(\"test\"), le, nil)\n}\n\nfunc TestLogsRequest_WithSpan(t *testing.T) {\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tsr := new(tracetest.SpanRecorder)\n\tset.TracerProvider = sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))\n\totel.SetTracerProvider(set.TracerProvider)\n\tdefer otel.SetTracerProvider(nooptrace.NewTracerProvider())\n\n\tle, err := internal.NewLogsRequest(context.Background(), set, requesttest.RequestFromLogsFunc(nil), sendertest.NewNopSenderFunc[request.Request]())\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\tcheckWrapSpanForLogs(t, sr, set.TracerProvider.Tracer(\"test\"), le, nil)\n}\n\nfunc TestLogs_WithSpan_ReturnError(t *testing.T) {\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tsr := new(tracetest.SpanRecorder)\n\tset.TracerProvider = sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))\n\totel.SetTracerProvider(set.TracerProvider)\n\tdefer otel.SetTracerProvider(nooptrace.NewTracerProvider())\n\n\twant := errors.New(\"my_error\")\n\tle, err := NewLogs(context.Background(), set, &fakeLogsConfig, newPushLogsData(want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\tcheckWrapSpanForLogs(t, sr, set.TracerProvider.Tracer(\"test\"), le, want)\n}\n\nfunc TestLogsRequest_WithSpan_ReturnError(t *testing.T) {\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tsr := new(tracetest.SpanRecorder)\n\tset.TracerProvider = sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))\n\totel.SetTracerProvider(set.TracerProvider)\n\tdefer otel.SetTracerProvider(nooptrace.NewTracerProvider())\n\n\twant := errors.New(\"my_error\")\n\tle, err := internal.NewLogsRequest(context.Background(), set, requesttest.RequestFromLogsFunc(nil), sendertest.NewErrSenderFunc[request.Request](want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\tcheckWrapSpanForLogs(t, sr, set.TracerProvider.Tracer(\"test\"), le, want)\n}\n\nfunc TestLogs_WithShutdown(t *testing.T) {\n\tshutdownCalled := false\n\tshutdown := func(context.Context) error { shutdownCalled = true; return nil }\n\n\tle, err := NewLogs(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeLogsConfig, newPushLogsData(nil), WithShutdown(shutdown))\n\tassert.NotNil(t, le)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, le.Shutdown(context.Background()))\n\tassert.True(t, shutdownCalled)\n}\n\nfunc TestLogs_WithShutdown_ReturnError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tshutdownErr := func(context.Context) error { return want }\n\n\tle, err := NewLogs(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeLogsConfig, newPushLogsData(nil), WithShutdown(shutdownErr))\n\tassert.NotNil(t, le)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, want, le.Shutdown(context.Background()))\n}\n\nfunc newPushLogsDataModifiedDownstream(retError error) consumer.ConsumeLogsFunc {\n\treturn func(_ context.Context, log plog.Logs) error {\n\t\tlog.ResourceLogs().MoveAndAppendTo(plog.NewResourceLogsSlice())\n\t\treturn retError\n\t}\n}\n\nfunc newPushLogsData(retError error) consumer.ConsumeLogsFunc {\n\treturn func(_ context.Context, _ plog.Logs) error {\n\t\treturn retError\n\t}\n}\n\nfunc checkRecordedMetricsForLogs(t *testing.T, tt *componenttest.Telemetry, id component.ID, le exporter.Logs, wantError error) {\n\tld := testdata.GenerateLogs(2)\n\tconst numBatches = 7\n\tfor range numBatches {\n\t\trequire.Equal(t, wantError, le.ConsumeLogs(context.Background(), ld))\n\t}\n\n\t// TODO: When the new metrics correctly count partial dropped fix this.\n\tif wantError != nil {\n\t\tmetadatatest.AssertEqualExporterSendFailedLogRecords(t, tt,\n\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t{\n\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\tattribute.String(\"exporter\", id.String()),\n\t\t\t\t\t\tattribute.String(string(semconv.ErrorTypeKey), \"_OTHER\"),\n\t\t\t\t\t\tattribute.Bool(internal.ErrorPermanentKey, false)),\n\t\t\t\t\tValue: int64(numBatches * ld.LogRecordCount()),\n\t\t\t\t},\n\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t} else {\n\t\tmetadatatest.AssertEqualExporterSentLogRecords(t, tt,\n\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t{\n\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\tattribute.String(\"exporter\", id.String())),\n\t\t\t\t\tValue: int64(numBatches * ld.LogRecordCount()),\n\t\t\t\t},\n\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t}\n}\n\nfunc generateLogsTraffic(t *testing.T, tracer trace.Tracer, le exporter.Logs, numRequests int, wantError error) {\n\tld := testdata.GenerateLogs(1)\n\tctx, span := tracer.Start(context.Background(), fakeLogsParentSpanName)\n\tdefer span.End()\n\tfor range numRequests {\n\t\trequire.Equal(t, wantError, le.ConsumeLogs(ctx, ld))\n\t}\n}\n\nfunc checkWrapSpanForLogs(t *testing.T, sr *tracetest.SpanRecorder, tracer trace.Tracer, le exporter.Logs, wantError error) {\n\tconst numRequests = 5\n\tgenerateLogsTraffic(t, tracer, le, numRequests, wantError)\n\n\t// Inspection time!\n\tgotSpanData := sr.Ended()\n\trequire.Len(t, gotSpanData, numRequests+1)\n\n\tparentSpan := gotSpanData[numRequests]\n\trequire.Equalf(t, fakeLogsParentSpanName, parentSpan.Name(), \"SpanData %v\", parentSpan)\n\tfor _, sd := range gotSpanData[:numRequests] {\n\t\trequire.Equalf(t, parentSpan.SpanContext(), sd.Parent(), \"Exporter span not a child\\nSpanData %v\", sd)\n\t\toteltest.CheckStatus(t, sd, wantError)\n\n\t\tsentLogRecords := int64(1)\n\t\tfailedToSendLogRecords := int64(0)\n\t\tif wantError != nil {\n\t\t\tsentLogRecords = 0\n\t\t\tfailedToSendLogRecords = 1\n\t\t}\n\t\trequire.Containsf(t, sd.Attributes(), attribute.KeyValue{Key: internal.ItemsSent, Value: attribute.Int64Value(sentLogRecords)}, \"SpanData %v\", sd)\n\t\trequire.Containsf(t, sd.Attributes(), attribute.KeyValue{Key: internal.ItemsFailed, Value: attribute.Int64Value(failedToSendLogRecords)}, \"SpanData %v\", sd)\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/metadata.yaml",
    "content": "type: exporterhelper\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  codeowners:\n    active:\n      - bogdandrutu\n      - dmitryax\n  class: pkg\n  stability:\n    beta: [traces, metrics, logs]\n\ntelemetry:\n  metrics:\n    exporter_enqueue_failed_log_records:\n      enabled: true\n      stability: alpha\n      description: Number of log records failed to be added to the sending queue.\n      unit: \"{record}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    exporter_enqueue_failed_metric_points:\n      enabled: true\n      stability: alpha\n      description: Number of metric points failed to be added to the sending queue.\n      unit: \"{datapoint}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    exporter_enqueue_failed_profile_samples:\n      enabled: true\n      stability: development\n      description: Number of profile samples failed to be added to the sending queue.\n      unit: \"{sample}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    exporter_enqueue_failed_spans:\n      enabled: true\n      stability: alpha\n      description: Number of spans failed to be added to the sending queue.\n      unit: \"{span}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    exporter_queue_batch_send_size:\n      enabled: true\n      description: Number of units in the batch\n      stability: development\n      unit: \"{unit}\"\n      histogram:\n        value_type: int\n        bucket_boundaries:\n          [\n            10,\n            25,\n            50,\n            75,\n            100,\n            250,\n            500,\n            750,\n            1000,\n            2000,\n            3000,\n            4000,\n            5000,\n            6000,\n            7000,\n            8000,\n            9000,\n            10000,\n            20000,\n            30000,\n            50000,\n            100000,\n          ]\n\n    exporter_queue_batch_send_size_bytes:\n      enabled: true\n      description: Number of bytes in batch that was sent. Only available on detailed level.\n      stability: development\n      unit: By\n      histogram:\n        value_type: int\n        bucket_boundaries:\n          [\n            10,\n            25,\n            50,\n            75,\n            100,\n            250,\n            500,\n            750,\n            1000,\n            2000,\n            3000,\n            4000,\n            5000,\n            6000,\n          ]\n\n    exporter_queue_capacity:\n      enabled: true\n      stability: alpha\n      description: Fixed capacity of the retry queue (in batches).\n      unit: \"{batch}\"\n      gauge:\n        value_type: int\n        async: true\n\n    exporter_queue_size:\n      enabled: true\n      stability: alpha\n      description: Current size of the retry queue (in batches).\n      unit: \"{batch}\"\n      gauge:\n        value_type: int\n        async: true\n\n    exporter_send_failed_log_records:\n      enabled: true\n      stability: alpha\n      description: \"Number of log records in failed attempts to send to destination. At detailed telemetry level, includes attributes: error.type (semantic convention), error.permanent.\"\n      unit: \"{record}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    exporter_send_failed_metric_points:\n      enabled: true\n      stability: alpha\n      description: \"Number of metric points in failed attempts to send to destination. At detailed telemetry level, includes attributes: error.type (semantic convention), error.permanent.\"\n      unit: \"{datapoint}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    exporter_send_failed_profile_samples:\n      enabled: true\n      stability: development\n      description: \"Number of profile samples in failed attempts to send to destination. At detailed telemetry level, includes attributes: error.type (semantic convention), error.permanent.\"\n      unit: \"{sample}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    exporter_send_failed_spans:\n      enabled: true\n      stability: alpha\n      description: \"Number of spans in failed attempts to send to destination. At detailed telemetry level, includes attributes: error.type (semantic convention), error.permanent.\"\n      unit: \"{span}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    exporter_sent_log_records:\n      enabled: true\n      stability: alpha\n      description: Number of log record successfully sent to destination.\n      unit: \"{record}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    exporter_sent_metric_points:\n      enabled: true\n      stability: alpha\n      description: Number of metric points successfully sent to destination.\n      unit: \"{datapoint}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    exporter_sent_profile_samples:\n      enabled: true\n      stability: development\n      description: Number of profile samples successfully sent to destination.\n      unit: \"{sample}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    exporter_sent_spans:\n      enabled: true\n      stability: alpha\n      description: Number of spans successfully sent to destination.\n      unit: \"{span}\"\n      sum:\n        value_type: int\n        monotonic: true\n\nfeature_gates:\n  - id: exporter.PersistRequestContext\n    description: 'controls whether context should be stored alongside requests in the persistent queue'\n    stage: beta\n    from_version: 'v0.128.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/pull/13188'\n"
  },
  {
    "path": "exporter/exporterhelper/metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exporterhelper // import \"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n)\n\n// NewMetrics creates an exporter.Metrics that records observability metrics and wraps every request with a Span.\nfunc NewMetrics(\n\tctx context.Context,\n\tset exporter.Settings,\n\tcfg component.Config,\n\tpusher consumer.ConsumeMetricsFunc,\n\toptions ...Option,\n) (exporter.Metrics, error) {\n\tif cfg == nil {\n\t\treturn nil, errNilConfig\n\t}\n\tif pusher == nil {\n\t\treturn nil, errNilPushMetrics\n\t}\n\treturn internal.NewMetricsRequest(ctx, set, queuebatch.RequestFromMetrics(), queuebatch.RequestConsumeFromMetrics(pusher),\n\t\tappend([]Option{internal.WithQueueBatchSettings(queuebatch.NewMetricsQueueBatchSettings())}, options...)...)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/metrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exporterhelper\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\tsdktrace \"go.opentelemetry.io/otel/sdk/trace\"\n\t\"go.opentelemetry.io/otel/sdk/trace/tracetest\"\n\tsemconv \"go.opentelemetry.io/otel/semconv/v1.38.0\"\n\t\"go.opentelemetry.io/otel/trace\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/hosttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/metadatatest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/oteltest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sendertest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/storagetest\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nconst (\n\tfakeMetricsParentSpanName = \"fake_metrics_parent_span_name\"\n)\n\nvar (\n\tfakeMetricsName   = component.MustNewIDWithName(\"fake_metrics_exporter\", \"with_name\")\n\tfakeMetricsConfig = struct{}{}\n)\n\nfunc TestMetrics_NilConfig(t *testing.T) {\n\tme, err := NewMetrics(context.Background(), exportertest.NewNopSettings(exportertest.NopType), nil, newPushMetricsData(nil))\n\trequire.Nil(t, me)\n\trequire.Equal(t, errNilConfig, err)\n}\n\nfunc TestMetrics_NilLogger(t *testing.T) {\n\tme, err := NewMetrics(context.Background(), exporter.Settings{}, &fakeMetricsConfig, newPushMetricsData(nil))\n\trequire.Nil(t, me)\n\trequire.Equal(t, errNilLogger, err)\n}\n\nfunc TestMetrics_NilPushMetricsData(t *testing.T) {\n\tme, err := NewMetrics(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeMetricsConfig, nil)\n\trequire.Nil(t, me)\n\trequire.Equal(t, errNilPushMetrics, err)\n}\n\nfunc TestMetrics_Default(t *testing.T) {\n\tmd := pmetric.NewMetrics()\n\tme, err := NewMetrics(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeMetricsConfig, newPushMetricsData(nil))\n\trequire.NoError(t, err)\n\tassert.NotNil(t, me)\n\n\tassert.Equal(t, consumer.Capabilities{MutatesData: false}, me.Capabilities())\n\tassert.NoError(t, me.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, me.ConsumeMetrics(context.Background(), md))\n\tassert.NoError(t, me.Shutdown(context.Background()))\n}\n\nfunc TestMetrics_WithCapabilities(t *testing.T) {\n\tcapabilities := consumer.Capabilities{MutatesData: true}\n\tme, err := NewMetrics(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeMetricsConfig, newPushMetricsData(nil), WithCapabilities(capabilities))\n\trequire.NoError(t, err)\n\tassert.NotNil(t, me)\n\n\tassert.Equal(t, capabilities, me.Capabilities())\n}\n\nfunc TestMetrics_Default_ReturnError(t *testing.T) {\n\tmd := pmetric.NewMetrics()\n\twant := errors.New(\"my_error\")\n\tme, err := NewMetrics(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeMetricsConfig, newPushMetricsData(want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, me)\n\trequire.Equal(t, want, me.ConsumeMetrics(context.Background(), md))\n}\n\nfunc TestMetrics_WithPersistentQueue(t *testing.T) {\n\tfgOrigReadState := queue.PersistRequestContextOnRead\n\tfgOrigWriteState := queue.PersistRequestContextOnWrite\n\tqCfg := NewDefaultQueueConfig()\n\tstorageID := component.MustNewIDWithName(\"file_storage\", \"storage\")\n\tqCfg.StorageID = &storageID\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tset.ID = component.MustNewIDWithName(\"test_metrics\", \"with_persistent_queue\")\n\thost := hosttest.NewHost(map[component.ID]component.Component{\n\t\tstorageID: storagetest.NewMockStorageExtension(nil),\n\t})\n\tspanCtx := oteltest.FakeSpanContext(t)\n\n\ttests := []struct {\n\t\tname             string\n\t\tfgEnabledOnWrite bool\n\t\tfgEnabledOnRead  bool\n\t\twantData         bool\n\t\twantSpanCtx      bool\n\t}{\n\t\t{\n\t\t\tname:     \"feature_gate_disabled_on_write_and_read\",\n\t\t\twantData: true,\n\t\t},\n\t\t{\n\t\t\tname:             \"feature_gate_enabled_on_write_and_read\",\n\t\t\tfgEnabledOnWrite: true,\n\t\t\tfgEnabledOnRead:  true,\n\t\t\twantData:         true,\n\t\t\twantSpanCtx:      true,\n\t\t},\n\t\t{\n\t\t\tname:            \"feature_gate_disabled_on_write_enabled_on_read\",\n\t\t\twantData:        true,\n\t\t\tfgEnabledOnRead: true,\n\t\t},\n\t\t{\n\t\t\tname:             \"feature_gate_enabled_on_write_disabled_on_read\",\n\t\t\tfgEnabledOnWrite: true,\n\t\t\twantData:         false, // going back from enabled to disabled feature gate isn't supported\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tqueue.PersistRequestContextOnRead = func() bool { return tt.fgEnabledOnRead }\n\t\t\tqueue.PersistRequestContextOnWrite = func() bool { return tt.fgEnabledOnWrite }\n\t\t\tt.Cleanup(func() {\n\t\t\t\tqueue.PersistRequestContextOnRead = fgOrigReadState\n\t\t\t\tqueue.PersistRequestContextOnWrite = fgOrigWriteState\n\t\t\t})\n\n\t\t\tms := consumertest.MetricsSink{}\n\t\t\tte, err := NewMetrics(context.Background(), set, &fakeMetricsConfig, ms.ConsumeMetrics, WithQueue(configoptional.Some(qCfg)))\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, te.Start(context.Background(), host))\n\t\t\tt.Cleanup(func() { require.NoError(t, te.Shutdown(context.Background())) })\n\n\t\t\ttraces := testdata.GenerateMetrics(2)\n\t\t\trequire.NoError(t, te.ConsumeMetrics(trace.ContextWithSpanContext(context.Background(), spanCtx), traces))\n\t\t\tif tt.wantData {\n\t\t\t\trequire.Eventually(t, func() bool {\n\t\t\t\t\treturn len(ms.AllMetrics()) == 1 && ms.DataPointCount() == 4\n\t\t\t\t}, 500*time.Millisecond, 10*time.Millisecond)\n\t\t\t}\n\n\t\t\t// check that the span context is persisted if the feature gate is enabled\n\t\t\tif tt.wantSpanCtx {\n\t\t\t\tassert.Len(t, ms.Contexts(), 1)\n\t\t\t\tassert.Equal(t, spanCtx, trace.SpanContextFromContext(ms.Contexts()[0]))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMetrics_WithRecordMetrics(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tme, err := NewMetrics(context.Background(), exporter.Settings{ID: fakeMetricsName, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, &fakeMetricsConfig, newPushMetricsData(nil))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, me)\n\n\tcheckRecordedMetricsForMetrics(t, tt, fakeMetricsName, me, nil)\n}\n\nfunc TestMetrics_pMetricModifiedDownStream_WithRecordMetrics(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tme, err := NewMetrics(context.Background(), exporter.Settings{ID: fakeMetricsName, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, &fakeMetricsConfig, newPushMetricsDataModifiedDownstream(nil), WithCapabilities(consumer.Capabilities{MutatesData: true}))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, me)\n\tmd := testdata.GenerateMetrics(2)\n\n\trequire.NoError(t, me.ConsumeMetrics(context.Background(), md))\n\tassert.Equal(t, 0, md.MetricCount())\n\n\tmetadatatest.AssertEqualExporterSentMetricPoints(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(internal.ExporterKey, fakeMetricsName.String())),\n\t\t\t\tValue: int64(4),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\nfunc TestMetricsRequest_WithRecordMetrics(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tme, err := internal.NewMetricsRequest(context.Background(),\n\t\texporter.Settings{ID: fakeMetricsName, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t\trequesttest.RequestFromMetricsFunc(nil), sendertest.NewNopSenderFunc[request.Request]())\n\trequire.NoError(t, err)\n\trequire.NotNil(t, me)\n\n\tcheckRecordedMetricsForMetrics(t, tt, fakeMetricsName, me, nil)\n}\n\nfunc TestMetrics_WithRecordMetrics_ReturnError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tme, err := NewMetrics(context.Background(), exporter.Settings{ID: fakeMetricsName, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, &fakeMetricsConfig, newPushMetricsData(want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, me)\n\n\tcheckRecordedMetricsForMetrics(t, tt, fakeMetricsName, me, want)\n}\n\nfunc TestMetricsRequest_WithRecordMetrics_ExportError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tme, err := internal.NewMetricsRequest(context.Background(),\n\t\texporter.Settings{ID: fakeMetricsName, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t\trequesttest.RequestFromMetricsFunc(nil), sendertest.NewErrSenderFunc[request.Request](want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, me)\n\n\tcheckRecordedMetricsForMetrics(t, tt, fakeMetricsName, me, want)\n}\n\nfunc TestMetrics_WithSpan(t *testing.T) {\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tsr := new(tracetest.SpanRecorder)\n\tset.TracerProvider = sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))\n\totel.SetTracerProvider(set.TracerProvider)\n\tdefer otel.SetTracerProvider(nooptrace.NewTracerProvider())\n\n\tme, err := NewMetrics(context.Background(), set, &fakeMetricsConfig, newPushMetricsData(nil))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, me)\n\tcheckWrapSpanForMetrics(t, sr, set.TracerProvider.Tracer(\"test\"), me, nil)\n}\n\nfunc TestMetricsRequest_WithSpan(t *testing.T) {\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tsr := new(tracetest.SpanRecorder)\n\tset.TracerProvider = sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))\n\totel.SetTracerProvider(set.TracerProvider)\n\tdefer otel.SetTracerProvider(nooptrace.NewTracerProvider())\n\n\tme, err := internal.NewMetricsRequest(context.Background(), set, requesttest.RequestFromMetricsFunc(nil), sendertest.NewNopSenderFunc[request.Request]())\n\trequire.NoError(t, err)\n\trequire.NotNil(t, me)\n\tcheckWrapSpanForMetrics(t, sr, set.TracerProvider.Tracer(\"test\"), me, nil)\n}\n\nfunc TestMetrics_WithSpan_ReturnError(t *testing.T) {\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tsr := new(tracetest.SpanRecorder)\n\tset.TracerProvider = sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))\n\totel.SetTracerProvider(set.TracerProvider)\n\tdefer otel.SetTracerProvider(nooptrace.NewTracerProvider())\n\n\twant := errors.New(\"my_error\")\n\tme, err := NewMetrics(context.Background(), set, &fakeMetricsConfig, newPushMetricsData(want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, me)\n\tcheckWrapSpanForMetrics(t, sr, set.TracerProvider.Tracer(\"test\"), me, want)\n}\n\nfunc TestMetricsRequest_WithSpan_ExportError(t *testing.T) {\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tsr := new(tracetest.SpanRecorder)\n\tset.TracerProvider = sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))\n\totel.SetTracerProvider(set.TracerProvider)\n\tdefer otel.SetTracerProvider(nooptrace.NewTracerProvider())\n\n\twant := errors.New(\"my_error\")\n\tme, err := internal.NewMetricsRequest(context.Background(), set, requesttest.RequestFromMetricsFunc(nil), sendertest.NewErrSenderFunc[request.Request](want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, me)\n\tcheckWrapSpanForMetrics(t, sr, set.TracerProvider.Tracer(\"test\"), me, want)\n}\n\nfunc TestMetrics_WithShutdown(t *testing.T) {\n\tshutdownCalled := false\n\tshutdown := func(context.Context) error { shutdownCalled = true; return nil }\n\n\tme, err := NewMetrics(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeMetricsConfig, newPushMetricsData(nil), WithShutdown(shutdown))\n\tassert.NotNil(t, me)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, me.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, me.Shutdown(context.Background()))\n\tassert.True(t, shutdownCalled)\n}\n\nfunc TestMetrics_WithShutdown_ReturnError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tshutdownErr := func(context.Context) error { return want }\n\n\tme, err := NewMetrics(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeMetricsConfig, newPushMetricsData(nil), WithShutdown(shutdownErr))\n\tassert.NotNil(t, me)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, me.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.Equal(t, want, me.Shutdown(context.Background()))\n}\n\nfunc newPushMetricsData(retError error) consumer.ConsumeMetricsFunc {\n\treturn func(_ context.Context, _ pmetric.Metrics) error {\n\t\treturn retError\n\t}\n}\n\nfunc newPushMetricsDataModifiedDownstream(retError error) consumer.ConsumeMetricsFunc {\n\treturn func(_ context.Context, metric pmetric.Metrics) error {\n\t\tmetric.ResourceMetrics().MoveAndAppendTo(pmetric.NewResourceMetricsSlice())\n\t\treturn retError\n\t}\n}\n\nfunc checkRecordedMetricsForMetrics(t *testing.T, tt *componenttest.Telemetry, id component.ID, me exporter.Metrics, wantError error) {\n\tmd := testdata.GenerateMetrics(2)\n\tconst numBatches = 7\n\tfor range numBatches {\n\t\trequire.Equal(t, wantError, me.ConsumeMetrics(context.Background(), md))\n\t}\n\n\t// TODO: When the new metrics correctly count partial dropped fix this.\n\tnumPoints := int64(numBatches * md.MetricCount() * 2) /* 2 points per metric*/\n\tif wantError != nil {\n\t\tmetadatatest.AssertEqualExporterSendFailedMetricPoints(t, tt,\n\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t{\n\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\tattribute.String(internal.ExporterKey, id.String()),\n\t\t\t\t\t\tattribute.String(string(semconv.ErrorTypeKey), \"_OTHER\"),\n\t\t\t\t\t\tattribute.Bool(internal.ErrorPermanentKey, false)),\n\t\t\t\t\tValue: numPoints,\n\t\t\t\t},\n\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t} else {\n\t\tmetadatatest.AssertEqualExporterSentMetricPoints(t, tt,\n\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t{\n\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\tattribute.String(internal.ExporterKey, id.String())),\n\t\t\t\t\tValue: numPoints,\n\t\t\t\t},\n\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t}\n}\n\nfunc generateMetricsTraffic(t *testing.T, tracer trace.Tracer, me exporter.Metrics, numRequests int, wantError error) {\n\tmd := testdata.GenerateMetrics(1)\n\tctx, span := tracer.Start(context.Background(), fakeMetricsParentSpanName)\n\tdefer span.End()\n\tfor range numRequests {\n\t\trequire.Equal(t, wantError, me.ConsumeMetrics(ctx, md))\n\t}\n}\n\nfunc checkWrapSpanForMetrics(t *testing.T, sr *tracetest.SpanRecorder, tracer trace.Tracer, me exporter.Metrics, wantError error) {\n\tconst numRequests = 5\n\tgenerateMetricsTraffic(t, tracer, me, numRequests, wantError)\n\n\t// Inspection time!\n\tgotSpanData := sr.Ended()\n\trequire.Len(t, gotSpanData, numRequests+1)\n\n\tparentSpan := gotSpanData[numRequests]\n\trequire.Equalf(t, fakeMetricsParentSpanName, parentSpan.Name(), \"SpanData %v\", parentSpan)\n\tfor _, sd := range gotSpanData[:numRequests] {\n\t\trequire.Equalf(t, parentSpan.SpanContext(), sd.Parent(), \"Exporter span not a child\\nSpanData %v\", sd)\n\t\toteltest.CheckStatus(t, sd, wantError)\n\n\t\tsentMetricPoints := int64(2)\n\t\tfailedToSendMetricPoints := int64(0)\n\t\tif wantError != nil {\n\t\t\tsentMetricPoints = 0\n\t\t\tfailedToSendMetricPoints = 2\n\t\t}\n\t\trequire.Containsf(t, sd.Attributes(), attribute.KeyValue{Key: internal.ItemsSent, Value: attribute.Int64Value(sentMetricPoints)}, \"SpanData %v\", sd)\n\t\trequire.Containsf(t, sd.Attributes(), attribute.KeyValue{Key: internal.ItemsFailed, Value: attribute.Int64Value(failedToSendMetricPoints)}, \"SpanData %v\", sd)\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/queue_batch.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exporterhelper // import \"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n)\n\n// WithQueue overrides the default QueueBatchConfig for an exporter.\n// The default QueueBatchConfig is to disable queueing.\n// This option cannot be used with the new exporter helpers New[Traces|Metrics|Logs]RequestExporter.\nfunc WithQueue(config configoptional.Optional[QueueBatchConfig]) Option {\n\treturn internal.WithQueue(config)\n}\n\n// QueueBatchConfig defines configuration for queueing and batching for the exporter.\ntype QueueBatchConfig = queuebatch.Config\n\n// BatchConfig defines a configuration for batching requests based on a timeout and a minimum number of items.\ntype BatchConfig = queuebatch.BatchConfig\n\n// QueueBatchEncoding defines the encoding to be used if persistent queue is configured.\n// Duplicate definition with queuebatch.Encoding since aliasing generics is not supported by default.\ntype QueueBatchEncoding[T any] interface {\n\t// Marshal is a function that can marshal a request and its context into bytes.\n\tMarshal(context.Context, T) ([]byte, error)\n\n\t// Unmarshal is a function that can unmarshal bytes into a request and its context.\n\tUnmarshal([]byte) (context.Context, T, error)\n}\n\nvar ErrQueueIsFull = queue.ErrQueueIsFull\n\n// NewDefaultQueueConfig returns the default config for QueueBatchConfig.\n// By default, the queue stores 1000 requests of telemetry and is non-blocking when full.\nvar NewDefaultQueueConfig = internal.NewDefaultQueueConfig\n"
  },
  {
    "path": "exporter/exporterhelper/request.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exporterhelper // import \"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\nimport (\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n)\n\ntype RequestSizerType = request.SizerType\n\nvar (\n\tRequestSizerTypeBytes    = request.SizerTypeBytes\n\tRequestSizerTypeItems    = request.SizerTypeItems\n\tRequestSizerTypeRequests = request.SizerTypeRequests\n)\n"
  },
  {
    "path": "exporter/exporterhelper/retry_sender.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exporterhelper // import \"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\nimport (\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n)\n\n// NewThrottleRetry creates a new throttle retry error.\nfunc NewThrottleRetry(err error, delay time.Duration) error {\n\treturn internal.NewThrottleRetry(err, delay)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/timeout_sender.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exporterhelper // import \"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\nimport (\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n)\n\ntype TimeoutConfig = internal.TimeoutConfig\n\n// NewDefaultTimeoutConfig returns the default config for TimeoutConfig.\nfunc NewDefaultTimeoutConfig() TimeoutConfig {\n\treturn internal.NewDefaultTimeoutConfig()\n}\n"
  },
  {
    "path": "exporter/exporterhelper/traces.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exporterhelper // import \"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n)\n\n// NewTraces creates an exporter.Traces that records observability metrics and wraps every request with a Span.\nfunc NewTraces(\n\tctx context.Context,\n\tset exporter.Settings,\n\tcfg component.Config,\n\tpusher consumer.ConsumeTracesFunc,\n\toptions ...Option,\n) (exporter.Traces, error) {\n\tif cfg == nil {\n\t\treturn nil, errNilConfig\n\t}\n\tif pusher == nil {\n\t\treturn nil, errNilPushTraces\n\t}\n\treturn internal.NewTracesRequest(ctx, set, queuebatch.RequestFromTraces(), queuebatch.RequestConsumeFromTraces(pusher),\n\t\tappend([]Option{internal.WithQueueBatchSettings(queuebatch.NewTracesQueueBatchSettings())}, options...)...)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/traces_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exporterhelper\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\tsdktrace \"go.opentelemetry.io/otel/sdk/trace\"\n\t\"go.opentelemetry.io/otel/sdk/trace/tracetest\"\n\tsemconv \"go.opentelemetry.io/otel/semconv/v1.38.0\"\n\t\"go.opentelemetry.io/otel/trace\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/hosttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/metadatatest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/oteltest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sendertest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/storagetest\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nconst (\n\tfakeTraceParentSpanName = \"fake_trace_parent_span_name\"\n)\n\nvar (\n\tfakeTracesName   = component.MustNewIDWithName(\"fake_traces_exporter\", \"with_name\")\n\tfakeTracesConfig = struct{}{}\n)\n\nfunc TestTraces_InvalidName(t *testing.T) {\n\tte, err := NewTraces(context.Background(), exportertest.NewNopSettings(exportertest.NopType), nil, newTraceDataPusher(nil))\n\trequire.Nil(t, te)\n\trequire.Equal(t, errNilConfig, err)\n}\n\nfunc TestTraces_NilLogger(t *testing.T) {\n\tte, err := NewTraces(context.Background(), exporter.Settings{}, &fakeTracesConfig, newTraceDataPusher(nil))\n\trequire.Nil(t, te)\n\trequire.Equal(t, errNilLogger, err)\n}\n\nfunc TestTraces_NilPushTraceData(t *testing.T) {\n\tte, err := NewTraces(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeTracesConfig, nil)\n\trequire.Nil(t, te)\n\trequire.Equal(t, errNilPushTraces, err)\n}\n\nfunc TestTraces_Default(t *testing.T) {\n\ttd := ptrace.NewTraces()\n\tte, err := NewTraces(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeTracesConfig, newTraceDataPusher(nil))\n\tassert.NotNil(t, te)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, consumer.Capabilities{MutatesData: false}, te.Capabilities())\n\tassert.NoError(t, te.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, te.ConsumeTraces(context.Background(), td))\n\tassert.NoError(t, te.Shutdown(context.Background()))\n}\n\nfunc TestTraces_WithCapabilities(t *testing.T) {\n\tcapabilities := consumer.Capabilities{MutatesData: true}\n\tte, err := NewTraces(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeTracesConfig, newTraceDataPusher(nil), WithCapabilities(capabilities))\n\tassert.NotNil(t, te)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, capabilities, te.Capabilities())\n}\n\nfunc TestTraces_Default_ReturnError(t *testing.T) {\n\ttd := ptrace.NewTraces()\n\twant := errors.New(\"my_error\")\n\tte, err := NewTraces(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeTracesConfig, newTraceDataPusher(want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, te)\n\n\terr = te.ConsumeTraces(context.Background(), td)\n\trequire.Equal(t, want, err)\n}\n\nfunc TestTraces_WithPersistentQueue(t *testing.T) {\n\tfgOrigReadState := queue.PersistRequestContextOnRead\n\tfgOrigWriteState := queue.PersistRequestContextOnWrite\n\tqCfg := NewDefaultQueueConfig()\n\tstorageID := component.MustNewIDWithName(\"file_storage\", \"storage\")\n\tqCfg.StorageID = &storageID\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tset.ID = component.MustNewIDWithName(\"test_logs\", \"with_persistent_queue\")\n\thost := hosttest.NewHost(map[component.ID]component.Component{\n\t\tstorageID: storagetest.NewMockStorageExtension(nil),\n\t})\n\tspanCtx := oteltest.FakeSpanContext(t)\n\n\ttests := []struct {\n\t\tname             string\n\t\tfgEnabledOnWrite bool\n\t\tfgEnabledOnRead  bool\n\t\twantData         bool\n\t\twantSpanCtx      bool\n\t}{\n\t\t{\n\t\t\tname:     \"feature_gate_disabled_on_write_and_read\",\n\t\t\twantData: true,\n\t\t},\n\t\t{\n\t\t\tname:             \"feature_gate_enabled_on_write_and_read\",\n\t\t\tfgEnabledOnWrite: true,\n\t\t\tfgEnabledOnRead:  true,\n\t\t\twantData:         true,\n\t\t\twantSpanCtx:      true,\n\t\t},\n\t\t{\n\t\t\tname:            \"feature_gate_disabled_on_write_enabled_on_read\",\n\t\t\twantData:        true,\n\t\t\tfgEnabledOnRead: true,\n\t\t},\n\t\t{\n\t\t\tname:             \"feature_gate_enabled_on_write_disabled_on_read\",\n\t\t\tfgEnabledOnWrite: true,\n\t\t\twantData:         false, // going back from enabled to disabled feature gate isn't supported\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tqueue.PersistRequestContextOnRead = func() bool { return tt.fgEnabledOnRead }\n\t\t\tqueue.PersistRequestContextOnWrite = func() bool { return tt.fgEnabledOnWrite }\n\t\t\tt.Cleanup(func() {\n\t\t\t\tqueue.PersistRequestContextOnRead = fgOrigReadState\n\t\t\t\tqueue.PersistRequestContextOnWrite = fgOrigWriteState\n\t\t\t})\n\n\t\t\tts := consumertest.TracesSink{}\n\t\t\tte, err := NewTraces(context.Background(), set, &fakeTracesConfig, ts.ConsumeTraces, WithQueue(configoptional.Some(qCfg)))\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, te.Start(context.Background(), host))\n\t\t\tt.Cleanup(func() { require.NoError(t, te.Shutdown(context.Background())) })\n\n\t\t\ttraces := testdata.GenerateTraces(2)\n\t\t\trequire.NoError(t, te.ConsumeTraces(trace.ContextWithSpanContext(context.Background(), spanCtx), traces))\n\t\t\tif tt.wantData {\n\t\t\t\trequire.Eventually(t, func() bool {\n\t\t\t\t\treturn len(ts.AllTraces()) == 1 && ts.SpanCount() == 2\n\t\t\t\t}, 500*time.Millisecond, 10*time.Millisecond)\n\t\t\t}\n\n\t\t\t// check that the span context is persisted if the feature gate is enabled\n\t\t\tif tt.wantSpanCtx {\n\t\t\t\tassert.Len(t, ts.Contexts(), 1)\n\t\t\t\tassert.Equal(t, spanCtx, trace.SpanContextFromContext(ts.Contexts()[0]))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestTraces_WithRecordMetrics(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tte, err := NewTraces(context.Background(), exporter.Settings{ID: fakeTracesName, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, &fakeTracesConfig, newTraceDataPusher(nil))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, te)\n\n\tcheckRecordedMetricsForTraces(t, tt, fakeTracesName, te, nil)\n}\n\nfunc TestTraces_pLogModifiedDownStream_WithRecordMetrics(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tte, err := NewTraces(context.Background(), exporter.Settings{ID: fakeTracesName, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, &fakeTracesConfig, newTraceDataPusherModifiedDownstream(nil), WithCapabilities(consumer.Capabilities{MutatesData: true}))\n\tassert.NotNil(t, te)\n\trequire.NoError(t, err)\n\ttd := testdata.GenerateTraces(2)\n\n\trequire.NoError(t, te.ConsumeTraces(context.Background(), td))\n\tassert.Equal(t, 0, td.SpanCount())\n\n\tmetadatatest.AssertEqualExporterSentSpans(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(internal.ExporterKey, fakeTracesName.String())),\n\t\t\t\tValue: int64(2),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\nfunc TestTracesRequest_WithRecordMetrics(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tte, err := internal.NewTracesRequest(context.Background(),\n\t\texporter.Settings{ID: fakeTracesName, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t\trequesttest.RequestFromTracesFunc(nil), sendertest.NewNopSenderFunc[request.Request]())\n\trequire.NoError(t, err)\n\trequire.NotNil(t, te)\n\n\tcheckRecordedMetricsForTraces(t, tt, fakeTracesName, te, nil)\n}\n\nfunc TestTraces_WithRecordMetrics_ReturnError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tte, err := NewTraces(context.Background(), exporter.Settings{ID: fakeTracesName, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()}, &fakeTracesConfig, newTraceDataPusher(want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, te)\n\n\tcheckRecordedMetricsForTraces(t, tt, fakeTracesName, te, want)\n}\n\nfunc TestTracesRequest_WithRecordMetrics_RequestSenderError(t *testing.T) {\n\twant := errors.New(\"export_error\")\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tte, err := internal.NewTracesRequest(context.Background(),\n\t\texporter.Settings{ID: fakeTracesName, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t\trequesttest.RequestFromTracesFunc(nil), sendertest.NewErrSenderFunc[request.Request](want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, te)\n\n\tcheckRecordedMetricsForTraces(t, tt, fakeTracesName, te, want)\n}\n\nfunc TestTraces_WithSpan(t *testing.T) {\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tsr := new(tracetest.SpanRecorder)\n\tset.TracerProvider = sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))\n\totel.SetTracerProvider(set.TracerProvider)\n\tdefer otel.SetTracerProvider(nooptrace.NewTracerProvider())\n\n\tte, err := NewTraces(context.Background(), set, &fakeTracesConfig, newTraceDataPusher(nil))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, te)\n\n\tcheckWrapSpanForTraces(t, sr, set.TracerProvider.Tracer(\"test\"), te, nil)\n}\n\nfunc TestTracesRequest_WithSpan(t *testing.T) {\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tsr := new(tracetest.SpanRecorder)\n\tset.TracerProvider = sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))\n\totel.SetTracerProvider(set.TracerProvider)\n\tdefer otel.SetTracerProvider(nooptrace.NewTracerProvider())\n\n\tte, err := internal.NewTracesRequest(context.Background(), set, requesttest.RequestFromTracesFunc(nil), sendertest.NewNopSenderFunc[request.Request]())\n\trequire.NoError(t, err)\n\trequire.NotNil(t, te)\n\n\tcheckWrapSpanForTraces(t, sr, set.TracerProvider.Tracer(\"test\"), te, nil)\n}\n\nfunc TestTraces_WithSpan_ReturnError(t *testing.T) {\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tsr := new(tracetest.SpanRecorder)\n\tset.TracerProvider = sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))\n\totel.SetTracerProvider(set.TracerProvider)\n\tdefer otel.SetTracerProvider(nooptrace.NewTracerProvider())\n\n\twant := errors.New(\"my_error\")\n\tte, err := NewTraces(context.Background(), set, &fakeTracesConfig, newTraceDataPusher(want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, te)\n\n\tcheckWrapSpanForTraces(t, sr, set.TracerProvider.Tracer(\"test\"), te, want)\n}\n\nfunc TestTracesRequest_WithSpan_ExportError(t *testing.T) {\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tsr := new(tracetest.SpanRecorder)\n\tset.TracerProvider = sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))\n\totel.SetTracerProvider(set.TracerProvider)\n\tdefer otel.SetTracerProvider(nooptrace.NewTracerProvider())\n\n\twant := errors.New(\"export_error\")\n\tte, err := internal.NewTracesRequest(context.Background(), set, requesttest.RequestFromTracesFunc(nil), sendertest.NewErrSenderFunc[request.Request](want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, te)\n\n\tcheckWrapSpanForTraces(t, sr, set.TracerProvider.Tracer(\"test\"), te, want)\n}\n\nfunc TestTraces_WithShutdown(t *testing.T) {\n\tshutdownCalled := false\n\tshutdown := func(context.Context) error { shutdownCalled = true; return nil }\n\n\tte, err := NewTraces(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeTracesConfig, newTraceDataPusher(nil), WithShutdown(shutdown))\n\tassert.NotNil(t, te)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, te.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, te.Shutdown(context.Background()))\n\tassert.True(t, shutdownCalled)\n}\n\nfunc TestTraces_WithShutdown_ReturnError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tshutdownErr := func(context.Context) error { return want }\n\n\tte, err := NewTraces(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeTracesConfig, newTraceDataPusher(nil), WithShutdown(shutdownErr))\n\tassert.NotNil(t, te)\n\tassert.NoError(t, err)\n\n\tassert.NoError(t, te.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.Equal(t, want, te.Shutdown(context.Background()))\n}\n\nfunc newTraceDataPusher(retError error) consumer.ConsumeTracesFunc {\n\treturn func(context.Context, ptrace.Traces) error {\n\t\treturn retError\n\t}\n}\n\nfunc newTraceDataPusherModifiedDownstream(retError error) consumer.ConsumeTracesFunc {\n\treturn func(_ context.Context, trace ptrace.Traces) error {\n\t\ttrace.ResourceSpans().MoveAndAppendTo(ptrace.NewResourceSpansSlice())\n\t\treturn retError\n\t}\n}\n\nfunc checkRecordedMetricsForTraces(t *testing.T, tt *componenttest.Telemetry, id component.ID, te exporter.Traces, wantError error) {\n\ttd := testdata.GenerateTraces(2)\n\tconst numBatches = 7\n\tfor range numBatches {\n\t\trequire.Equal(t, wantError, te.ConsumeTraces(context.Background(), td))\n\t}\n\n\t// TODO: When the new metrics correctly count partial dropped fix this.\n\tif wantError != nil {\n\t\tmetadatatest.AssertEqualExporterSendFailedSpans(t, tt,\n\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t{\n\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\tattribute.String(internal.ExporterKey, id.String()),\n\t\t\t\t\t\tattribute.String(string(semconv.ErrorTypeKey), \"_OTHER\"),\n\t\t\t\t\t\tattribute.Bool(internal.ErrorPermanentKey, false)),\n\t\t\t\t\tValue: int64(numBatches * td.SpanCount()),\n\t\t\t\t},\n\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t} else {\n\t\tmetadatatest.AssertEqualExporterSentSpans(t, tt,\n\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t{\n\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\tattribute.String(internal.ExporterKey, id.String())),\n\t\t\t\t\tValue: int64(numBatches * td.SpanCount()),\n\t\t\t\t},\n\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t}\n}\n\nfunc generateTraceTraffic(t *testing.T, tracer trace.Tracer, te exporter.Traces, numRequests int, wantError error) {\n\ttd := ptrace.NewTraces()\n\ttd.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty()\n\tctx, span := tracer.Start(context.Background(), fakeTraceParentSpanName)\n\tdefer span.End()\n\tfor range numRequests {\n\t\trequire.Equal(t, wantError, te.ConsumeTraces(ctx, td))\n\t}\n}\n\nfunc checkWrapSpanForTraces(t *testing.T, sr *tracetest.SpanRecorder, tracer trace.Tracer, te exporter.Traces, wantError error) {\n\tconst numRequests = 5\n\tgenerateTraceTraffic(t, tracer, te, numRequests, wantError)\n\n\t// Inspection time!\n\tgotSpanData := sr.Ended()\n\trequire.Len(t, gotSpanData, numRequests+1)\n\n\tparentSpan := gotSpanData[numRequests]\n\trequire.Equalf(t, fakeTraceParentSpanName, parentSpan.Name(), \"SpanData %v\", parentSpan)\n\n\tfor _, sd := range gotSpanData[:numRequests] {\n\t\trequire.Equalf(t, parentSpan.SpanContext(), sd.Parent(), \"Exporter span not a child\\nSpanData %v\", sd)\n\t\toteltest.CheckStatus(t, sd, wantError)\n\n\t\tsentSpans := int64(1)\n\t\tfailedToSendSpans := int64(0)\n\t\tif wantError != nil {\n\t\t\tsentSpans = 0\n\t\t\tfailedToSendSpans = 1\n\t\t}\n\t\trequire.Containsf(t, sd.Attributes(), attribute.KeyValue{Key: internal.ItemsSent, Value: attribute.Int64Value(sentSpans)}, \"SpanData %v\", sd)\n\t\trequire.Containsf(t, sd.Attributes(), attribute.KeyValue{Key: internal.ItemsFailed, Value: attribute.Int64Value(failedToSendSpans)}, \"SpanData %v\", sd)\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/xexporterhelper/Makefile",
    "content": "include ../../../Makefile.Common\n"
  },
  {
    "path": "exporter/exporterhelper/xexporterhelper/constants.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xexporterhelper // import \"go.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper\"\n\nimport (\n\t\"errors\"\n)\n\nvar (\n\t// errNilConfig is returned when an empty name is given.\n\terrNilConfig = errors.New(\"nil config\")\n\t// errNilLogger is returned when a logger is nil\n\terrNilLogger = errors.New(\"nil logger\")\n\t// errNilConsumeRequest is returned when a nil PushTraces is given.\n\terrNilConsumeRequest = errors.New(\"nil RequestConsumeFunc\")\n\t// errNilPushProfileData is returned when a nil PushProfiles is given.\n\terrNilPushProfileData = errors.New(\"nil PushProfiles\")\n\t// errNilProfilesConverter is returned when a nil RequestFromProfilesFunc is given.\n\terrNilProfilesConverter = errors.New(\"nil RequestFromProfilesFunc\")\n)\n"
  },
  {
    "path": "exporter/exporterhelper/xexporterhelper/go.mod",
    "content": "module go.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/config/configoptional v1.54.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0\n\tgo.opentelemetry.io/collector/consumer/consumererror/xconsumererror v0.148.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/exporter v1.54.0\n\tgo.opentelemetry.io/collector/exporter/exporterhelper v0.148.0\n\tgo.opentelemetry.io/collector/exporter/exportertest v0.148.0\n\tgo.opentelemetry.io/collector/exporter/xexporter v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.opentelemetry.io/collector/pdata/xpdata v0.148.0\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0\n\tgo.opentelemetry.io/otel v1.42.0\n\tgo.opentelemetry.io/otel/sdk v1.42.0\n\tgo.opentelemetry.io/otel/trace v1.42.0\n\tgo.uber.org/zap v1.27.1\n)\n\nrequire (\n\tgithub.com/cenkalti/backoff/v5 v5.0.3 // indirect\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/hashicorp/golang-lru/v2 v2.0.7 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/client v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configretry v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/confmap v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/xextension v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/receiver v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/receivertest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/exporter => ../../\n\nreplace go.opentelemetry.io/collector/consumer => ../../../consumer\n\nreplace go.opentelemetry.io/collector/consumer/consumererror/xconsumererror => ../../../consumer/consumererror/xconsumererror\n\nreplace go.opentelemetry.io/collector/receiver => ../../../receiver\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/component => ../../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../../component/componenttest\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../../../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../../../receiver/receivertest\n\nreplace go.opentelemetry.io/collector/extension => ../../../extension\n\nreplace go.opentelemetry.io/collector/pdata => ../../../pdata\n\nreplace go.opentelemetry.io/collector/exporter/xexporter => ../../xexporter\n\nreplace go.opentelemetry.io/collector/config/configretry => ../../../config/configretry\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/pipeline => ../../../pipeline\n\nreplace go.opentelemetry.io/collector/exporter/exportertest => ../../exportertest\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../../../extension/extensiontest\n\nreplace go.opentelemetry.io/collector/extension/xextension => ../../../extension/xextension\n\nreplace go.opentelemetry.io/collector/featuregate => ../../../featuregate\n\nreplace go.opentelemetry.io/collector/client => ../../../client\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../../../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../../../config/configoptional\n\nreplace go.opentelemetry.io/collector/confmap => ../../../confmap\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper => ../\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../../internal/componentalias\n"
  },
  {
    "path": "exporter/exporterhelper/xexporterhelper/go.sum",
    "content": "github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=\ngithub.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "exporter/exporterhelper/xexporterhelper/metadata.yaml",
    "content": "type: xexporterhelper\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  codeowners:\n    active:\n      - mx-psi\n      - dmathieu\n  stability:\n    alpha: [profiles]\n"
  },
  {
    "path": "exporter/exporterhelper/xexporterhelper/new_request.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xexporterhelper // import \"go.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queuebatch\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\n// NewLogsRequest creates new logs exporter based on custom LogsConverter and Sender.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\nfunc NewLogsRequest(\n\tctx context.Context,\n\tset exporter.Settings,\n\tconverter RequestConverterFunc[plog.Logs],\n\tpusher RequestConsumeFunc,\n\toptions ...exporterhelper.Option,\n) (exporter.Logs, error) {\n\treturn internal.NewLogsRequest(ctx, set, converter, pusher, options...)\n}\n\n// NewMetricsRequest creates new metrics exporter based on custom MetricsConverter and Sender.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\nfunc NewMetricsRequest(\n\tctx context.Context,\n\tset exporter.Settings,\n\tconverter RequestConverterFunc[pmetric.Metrics],\n\tpusher RequestConsumeFunc,\n\toptions ...exporterhelper.Option,\n) (exporter.Metrics, error) {\n\treturn internal.NewMetricsRequest(ctx, set, converter, pusher, options...)\n}\n\n// NewTracesRequest creates new traces exporter based on custom TracesConverter and Sender.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\nfunc NewTracesRequest(\n\tctx context.Context,\n\tset exporter.Settings,\n\tconverter RequestConverterFunc[ptrace.Traces],\n\tpusher RequestConsumeFunc,\n\toptions ...exporterhelper.Option,\n) (exporter.Traces, error) {\n\treturn internal.NewTracesRequest(ctx, set, converter, pusher, options...)\n}\n\n// QueueBatchSettings are settings for the QueueBatch component.\n// They include things line Encoding to be used with persistent queue, or the available Sizers, etc.\ntype QueueBatchSettings = queuebatch.Settings[Request]\n\n// NewMetricsQueueBatchSettings returns a new QueueBatchSettings to configure to WithQueueBatch when using pmetric.Metrics.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\nfunc NewMetricsQueueBatchSettings() QueueBatchSettings {\n\treturn queuebatch.NewMetricsQueueBatchSettings()\n}\n\n// NewLogsQueueBatchSettings returns a new QueueBatchSettings to configure to WithQueueBatch when using plog.Logs.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\nfunc NewLogsQueueBatchSettings() QueueBatchSettings {\n\treturn queuebatch.NewLogsQueueBatchSettings()\n}\n\n// NewTracesQueueBatchSettings returns a new QueueBatchSettings to configure to WithQueueBatch when using ptrace.Traces.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\nfunc NewTracesQueueBatchSettings() QueueBatchSettings {\n\treturn queuebatch.NewTracesQueueBatchSettings()\n}\n\n// WithQueueBatch enables queueing and batching for an exporter.\n// This option should be used with the new exporter helpers New[Traces|Metrics|Logs]RequestExporter.\n// If batch.partition.MetadataKeys is set, it will automatically configure the partitioner and merge function\n// to partition batches based on the specified metadata keys.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\nfunc WithQueueBatch(cfg configoptional.Optional[exporterhelper.QueueBatchConfig], set QueueBatchSettings) exporterhelper.Option {\n\treturn internal.WithQueueBatch(cfg, set)\n}\n"
  },
  {
    "path": "exporter/exporterhelper/xexporterhelper/profiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xexporterhelper // import \"go.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror/xconsumererror\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n\tpdatareq \"go.opentelemetry.io/collector/pdata/xpdata/request\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n)\n\nvar (\n\tprofilesMarshaler   = &pprofile.ProtoMarshaler{}\n\tprofilesUnmarshaler = &pprofile.ProtoUnmarshaler{}\n)\n\n// NewProfilesQueueBatchSettings returns a new QueueBatchSettings to configure to WithQueueBatch when using pprofile.Profiles.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\nfunc NewProfilesQueueBatchSettings() QueueBatchSettings {\n\treturn QueueBatchSettings{\n\t\tReferenceCounter: profilesReferenceCounter{},\n\t\tEncoding:         profilesEncoding{},\n\t}\n}\n\nvar (\n\t_ request.Request      = (*profilesRequest)(nil)\n\t_ request.ErrorHandler = (*profilesRequest)(nil)\n)\n\ntype profilesRequest struct {\n\tpd         pprofile.Profiles\n\tcachedSize int\n}\n\nfunc newProfilesRequest(pd pprofile.Profiles) Request {\n\treturn &profilesRequest{\n\t\tpd:         pd,\n\t\tcachedSize: -1,\n\t}\n}\n\ntype profilesEncoding struct{}\n\nvar _ exporterhelper.QueueBatchEncoding[request.Request] = profilesEncoding{}\n\nfunc (profilesEncoding) Unmarshal(bytes []byte) (context.Context, request.Request, error) {\n\tif queue.PersistRequestContextOnRead() {\n\t\tctx, profiles, err := pdatareq.UnmarshalProfiles(bytes)\n\t\tif errors.Is(err, pdatareq.ErrInvalidFormat) {\n\t\t\t// fall back to unmarshaling without context\n\t\t\tprofiles, err = profilesUnmarshaler.UnmarshalProfiles(bytes)\n\t\t}\n\t\treturn ctx, newProfilesRequest(profiles), err\n\t}\n\tprofiles, err := profilesUnmarshaler.UnmarshalProfiles(bytes)\n\tif err != nil {\n\t\tvar req request.Request\n\t\treturn context.Background(), req, err\n\t}\n\treturn context.Background(), newProfilesRequest(profiles), nil\n}\n\nfunc (profilesEncoding) Marshal(ctx context.Context, req request.Request) ([]byte, error) {\n\tprofiles := req.(*profilesRequest).pd\n\tif queue.PersistRequestContextOnWrite() {\n\t\treturn pdatareq.MarshalProfiles(ctx, profiles)\n\t}\n\treturn profilesMarshaler.MarshalProfiles(profiles)\n}\n\nvar _ queue.ReferenceCounter[request.Request] = profilesReferenceCounter{}\n\ntype profilesReferenceCounter struct{}\n\nfunc (profilesReferenceCounter) Ref(req request.Request) {\n\tpref.RefProfiles(req.(*profilesRequest).pd)\n}\n\nfunc (profilesReferenceCounter) Unref(req request.Request) {\n\tpref.UnrefProfiles(req.(*profilesRequest).pd)\n}\n\nfunc (req *profilesRequest) OnError(err error) Request {\n\tvar profileError xconsumererror.Profiles\n\tif errors.As(err, &profileError) {\n\t\t// TODO: Add logic to unref the new request created here.\n\t\treturn newProfilesRequest(profileError.Data())\n\t}\n\treturn req\n}\n\nfunc (req *profilesRequest) ItemsCount() int {\n\treturn req.pd.SampleCount()\n}\n\nfunc (req *profilesRequest) size(sizer sizer.ProfilesSizer) int {\n\tif req.cachedSize == -1 {\n\t\treq.cachedSize = sizer.ProfilesSize(req.pd)\n\t}\n\treturn req.cachedSize\n}\n\nfunc (req *profilesRequest) setCachedSize(size int) {\n\treq.cachedSize = size\n}\n\nfunc (req *profilesRequest) BytesSize() int {\n\treturn profilesMarshaler.ProfilesSize(req.pd)\n}\n\ntype profileExporter struct {\n\t*internal.BaseExporter\n\txconsumer.Profiles\n}\n\n// NewProfiles creates an xexporter.Profiles that records observability metrics and wraps every request with a Span.\nfunc NewProfiles(\n\tctx context.Context,\n\tset exporter.Settings,\n\tcfg component.Config,\n\tpusher xconsumer.ConsumeProfilesFunc,\n\toptions ...exporterhelper.Option,\n) (xexporter.Profiles, error) {\n\tif cfg == nil {\n\t\treturn nil, errNilConfig\n\t}\n\tif pusher == nil {\n\t\treturn nil, errNilPushProfileData\n\t}\n\treturn NewProfilesRequest(ctx, set, requestFromProfiles(), requestConsumeFromProfiles(pusher),\n\t\tappend([]exporterhelper.Option{internal.WithQueueBatchSettings(NewProfilesQueueBatchSettings())}, options...)...)\n}\n\n// requestConsumeFromProfiles returns a RequestConsumeFunc that consumes pprofile.Profiles.\nfunc requestConsumeFromProfiles(pusher xconsumer.ConsumeProfilesFunc) RequestConsumeFunc {\n\treturn func(ctx context.Context, request Request) error {\n\t\treturn pusher.ConsumeProfiles(ctx, request.(*profilesRequest).pd)\n\t}\n}\n\n// requestFromProfiles returns a RequestFromProfilesFunc that converts pprofile.Profiles into a Request.\nfunc requestFromProfiles() RequestConverterFunc[pprofile.Profiles] {\n\treturn func(_ context.Context, profiles pprofile.Profiles) (Request, error) {\n\t\treturn newProfilesRequest(profiles), nil\n\t}\n}\n\n// NewProfilesRequest creates a new profiles exporter based on a custom ProfilesConverter and Sender.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\nfunc NewProfilesRequest(\n\t_ context.Context,\n\tset exporter.Settings,\n\tconverter RequestConverterFunc[pprofile.Profiles],\n\tpusher RequestConsumeFunc,\n\toptions ...exporterhelper.Option,\n) (xexporter.Profiles, error) {\n\tif set.Logger == nil {\n\t\treturn nil, errNilLogger\n\t}\n\n\tif converter == nil {\n\t\treturn nil, errNilProfilesConverter\n\t}\n\n\tif pusher == nil {\n\t\treturn nil, errNilConsumeRequest\n\t}\n\n\tbe, err := internal.NewBaseExporter(set, xpipeline.SignalProfiles, pusher, options...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\ttc, err := xconsumer.NewProfiles(newConsumeProfiles(converter, be, set.Logger), be.ConsumerOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &profileExporter{BaseExporter: be, Profiles: tc}, nil\n}\n\nfunc newConsumeProfiles(converter RequestConverterFunc[pprofile.Profiles], be *internal.BaseExporter, logger *zap.Logger) xconsumer.ConsumeProfilesFunc {\n\treturn func(ctx context.Context, pd pprofile.Profiles) error {\n\t\treq, err := converter(ctx, pd)\n\t\tif err != nil {\n\t\t\tlogger.Error(\"Failed to convert profiles. Dropping data.\",\n\t\t\t\tzap.Int(\"dropped_samples\", pd.SampleCount()),\n\t\t\t\tzap.Error(err))\n\t\t\treturn consumererror.NewPermanent(err)\n\t\t}\n\t\treturn be.Send(ctx, req)\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/xexporterhelper/profiles_batch.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xexporterhelper // import \"go.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n)\n\n// MergeSplit splits and/or merges the profiles into multiple requests based on the MaxSizeConfig.\n//\n// Following the OTLP 1.7.0 upgrade, this is currently a noop.\n// See https://github.com/open-telemetry/opentelemetry-collector/issues/13106\nfunc (req *profilesRequest) MergeSplit(_ context.Context, maxSize int, szt exporterhelper.RequestSizerType, r2 Request) ([]Request, error) {\n\tvar sz sizer.ProfilesSizer\n\tswitch szt {\n\tcase exporterhelper.RequestSizerTypeItems:\n\t\tsz = &sizer.ProfilesCountSizer{}\n\tcase exporterhelper.RequestSizerTypeBytes:\n\t\tsz = &sizer.ProfilesBytesSizer{}\n\tdefault:\n\t\treturn nil, errors.New(\"unknown sizer type\")\n\t}\n\n\tif r2 != nil && r2.ItemsCount() > 0 {\n\t\treq2, ok := r2.(*profilesRequest)\n\t\tif !ok {\n\t\t\treturn nil, errors.New(\"invalid input type\")\n\t\t}\n\t\terr := req2.mergeTo(req, sz)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed merging profiles; %w\", err)\n\t\t}\n\t}\n\n\t// If no limit we can simply merge the new request into the current and return.\n\tif maxSize == 0 {\n\t\treturn []Request{req}, nil\n\t}\n\treturn req.split(maxSize, sz)\n}\n\nfunc (req *profilesRequest) mergeTo(dst *profilesRequest, sz sizer.ProfilesSizer) error {\n\tif sz != nil {\n\t\tdst.setCachedSize(dst.size(sz) + req.size(sz))\n\t\treq.setCachedSize(0)\n\t}\n\treturn req.pd.MergeTo(dst.pd)\n}\n\nfunc (req *profilesRequest) split(maxSize int, sz sizer.ProfilesSizer) ([]Request, error) {\n\tvar res []Request\n\tfor req.size(sz) > maxSize {\n\t\tpd, rmSize := extractProfiles(req.pd, maxSize, sz)\n\t\tif pd.SampleCount() == 0 {\n\t\t\treturn res, fmt.Errorf(\"one sample size is greater than max size, dropping items: %d\", req.pd.SampleCount())\n\t\t}\n\t\treq.setCachedSize(req.size(sz) - rmSize)\n\t\tres = append(res, newProfilesRequest(pd))\n\t}\n\n\tres = append(res, req)\n\treturn res, nil\n}\n\n// extractProfiles extracts a new profiles with a maximum number of samples.\nfunc extractProfiles(srcProfiles pprofile.Profiles, capacity int, sz sizer.ProfilesSizer) (pprofile.Profiles, int) {\n\tdestProfiles := pprofile.NewProfiles()\n\tcapacityLeft := capacity - sz.ProfilesSize(destProfiles)\n\tremovedSize := 0\n\n\tsrcProfiles.Dictionary().CopyTo(destProfiles.Dictionary())\n\tsrcProfiles.ResourceProfiles().RemoveIf(func(srcRP pprofile.ResourceProfiles) bool {\n\t\t// If the no more capacity left just return.\n\t\tif capacityLeft == 0 {\n\t\t\treturn false\n\t\t}\n\t\trawRpSize := sz.ResourceProfilesSize(srcRP)\n\t\trpSize := sz.DeltaSize(rawRpSize)\n\n\t\tif rpSize > capacityLeft {\n\t\t\textSrcRP, extRpSize := extractResourceProfiles(srcRP, capacityLeft, sz)\n\t\t\t// This cannot make it to exactly 0 for the bytes,\n\t\t\t// force it to be 0 since that is the stopping condition.\n\t\t\tcapacityLeft = 0\n\t\t\tremovedSize += extRpSize\n\t\t\t// There represents the delta between the delta sizes.\n\t\t\tremovedSize += rpSize - rawRpSize - (sz.DeltaSize(rawRpSize-extRpSize) - (rawRpSize - extRpSize))\n\t\t\t// It is possible that for the bytes scenario, the extracted field contains no profiles.\n\t\t\t// Do not add it to the destination if that is the case.\n\t\t\tif extSrcRP.ScopeProfiles().Len() > 0 {\n\t\t\t\textSrcRP.MoveTo(destProfiles.ResourceProfiles().AppendEmpty())\n\t\t\t}\n\t\t\treturn extSrcRP.ScopeProfiles().Len() != 0\n\t\t}\n\t\tcapacityLeft -= rpSize\n\t\tremovedSize += rpSize\n\t\tsrcRP.MoveTo(destProfiles.ResourceProfiles().AppendEmpty())\n\t\treturn true\n\t})\n\treturn destProfiles, removedSize\n}\n\n// extractResourceProfiles extracts profiles and returns a new resource profiles with the specified number of profiles.\nfunc extractResourceProfiles(srcRP pprofile.ResourceProfiles, capacity int, sz sizer.ProfilesSizer) (pprofile.ResourceProfiles, int) {\n\tdestRP := pprofile.NewResourceProfiles()\n\tdestRP.SetSchemaUrl(srcRP.SchemaUrl())\n\tsrcRP.Resource().CopyTo(destRP.Resource())\n\t// Take into account that this can have max \"capacity\", so when added to the parent will need space for the extra delta size.\n\tcapacityLeft := capacity - (sz.DeltaSize(capacity) - capacity) - sz.ResourceProfilesSize(destRP)\n\tremovedSize := 0\n\n\tsrcRP.ScopeProfiles().RemoveIf(func(srcSS pprofile.ScopeProfiles) bool {\n\t\t// If the no more capacity left just return.\n\t\tif capacityLeft == 0 {\n\t\t\treturn false\n\t\t}\n\n\t\trawSlSize := sz.ScopeProfilesSize(srcSS)\n\t\tssSize := sz.DeltaSize(rawSlSize)\n\t\tif ssSize > capacityLeft {\n\t\t\textSrcSS, extSsSize := extractScopeProfiles(srcSS, capacityLeft, sz)\n\t\t\t// This cannot make it to exactly 0 for the bytes,\n\t\t\t// force it to be 0 since that is the stopping condition.\n\t\t\tcapacityLeft = 0\n\t\t\tremovedSize += extSsSize\n\t\t\t// There represents the delta between the delta sizes.\n\t\t\tremovedSize += ssSize - rawSlSize - (sz.DeltaSize(rawSlSize-extSsSize) - (rawSlSize - extSsSize))\n\t\t\t// It is possible that for the bytes scenario, the extracted field contains no profiles.\n\t\t\t// Do not add it to the destination if that is the case.\n\t\t\tif extSrcSS.Profiles().Len() > 0 {\n\t\t\t\textSrcSS.MoveTo(destRP.ScopeProfiles().AppendEmpty())\n\t\t\t}\n\t\t\treturn extSrcSS.Profiles().Len() != 0\n\t\t}\n\t\tcapacityLeft -= ssSize\n\t\tremovedSize += ssSize\n\t\tsrcSS.MoveTo(destRP.ScopeProfiles().AppendEmpty())\n\t\treturn true\n\t})\n\n\treturn destRP, removedSize\n}\n\n// extractScopeProfiles extracts profiles and returns a new scope profiles with the specified number of profiles.\nfunc extractScopeProfiles(srcSS pprofile.ScopeProfiles, capacity int, sz sizer.ProfilesSizer) (pprofile.ScopeProfiles, int) {\n\tdestSS := pprofile.NewScopeProfiles()\n\tdestSS.SetSchemaUrl(srcSS.SchemaUrl())\n\tsrcSS.Scope().CopyTo(destSS.Scope())\n\t// Take into account that this can have max \"capacity\", so when added to the parent will need space for the extra delta size.\n\tcapacityLeft := capacity - (sz.DeltaSize(capacity) - capacity) - sz.ScopeProfilesSize(destSS)\n\tremovedSize := 0\n\tsrcSS.Profiles().RemoveIf(func(srcProfile pprofile.Profile) bool {\n\t\t// If the no more capacity left just return.\n\t\tif capacityLeft == 0 {\n\t\t\treturn false\n\t\t}\n\t\trsSize := sz.DeltaSize(sz.ProfileSize(srcProfile))\n\t\tif rsSize > capacityLeft {\n\t\t\t// This cannot make it to exactly 0 for the bytes,\n\t\t\t// force it to be 0 since that is the stopping condition.\n\t\t\tcapacityLeft = 0\n\t\t\treturn false\n\t\t}\n\t\tcapacityLeft -= rsSize\n\t\tremovedSize += rsSize\n\t\tsrcProfile.MoveTo(destSS.Profiles().AppendEmpty())\n\t\treturn true\n\t})\n\treturn destSS, removedSize\n}\n"
  },
  {
    "path": "exporter/exporterhelper/xexporterhelper/profiles_batch_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xexporterhelper\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sizer\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestMergeProfiles(t *testing.T) {\n\tpr1 := newProfilesRequest(testdata.GenerateProfiles(2))\n\tpr2 := newProfilesRequest(testdata.GenerateProfiles(3))\n\tres, err := pr1.MergeSplit(context.Background(), 0, exporterhelper.RequestSizerTypeItems, pr2)\n\trequire.NoError(t, err)\n\tassert.Len(t, res, 1)\n\tassert.Equal(t, 5, res[0].ItemsCount())\n}\n\nfunc TestMergeProfilesInvalidInput(t *testing.T) {\n\tpr2 := newProfilesRequest(testdata.GenerateProfiles(3))\n\t_, err := pr2.MergeSplit(context.Background(), 0, exporterhelper.RequestSizerTypeItems, &requesttest.FakeRequest{Items: 1})\n\trequire.Error(t, err)\n}\n\nfunc TestMergeSplitProfiles(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tszt      exporterhelper.RequestSizerType\n\t\tmaxSize  int\n\t\tpr1      Request\n\t\tpr2      Request\n\t\texpected []Request\n\t}{\n\t\t{\n\t\t\tname:     \"both_requests_empty\",\n\t\t\tszt:      exporterhelper.RequestSizerTypeItems,\n\t\t\tmaxSize:  10,\n\t\t\tpr1:      newProfilesRequest(pprofile.NewProfiles()),\n\t\t\tpr2:      newProfilesRequest(pprofile.NewProfiles()),\n\t\t\texpected: []Request{newProfilesRequest(pprofile.NewProfiles())},\n\t\t},\n\t\t{\n\t\t\tname:    \"first_request_empty\",\n\t\t\tszt:     exporterhelper.RequestSizerTypeItems,\n\t\t\tmaxSize: 10,\n\t\t\tpr1:     newProfilesRequest(testdata.GenerateProfiles(0)),\n\t\t\tpr2:     newProfilesRequest(testdata.GenerateProfiles(5)),\n\t\t\texpected: []Request{newProfilesRequest(func() pprofile.Profiles {\n\t\t\t\tprofiles := testdata.GenerateProfiles(0)\n\t\t\t\t_ = testdata.GenerateProfiles(5).MergeTo(profiles)\n\t\t\t\treturn profiles\n\t\t\t}())},\n\t\t},\n\t\t{\n\t\t\tname:     \"first_empty_second_nil\",\n\t\t\tszt:      exporterhelper.RequestSizerTypeItems,\n\t\t\tmaxSize:  10,\n\t\t\tpr1:      newProfilesRequest(pprofile.NewProfiles()),\n\t\t\tpr2:      nil,\n\t\t\texpected: []Request{newProfilesRequest(pprofile.NewProfiles())},\n\t\t},\n\t\t{\n\t\t\tname:    \"merge_only\",\n\t\t\tszt:     exporterhelper.RequestSizerTypeItems,\n\t\t\tmaxSize: 10,\n\t\t\tpr1:     newProfilesRequest(testdata.GenerateProfiles(4)),\n\t\t\tpr2:     newProfilesRequest(testdata.GenerateProfiles(6)),\n\t\t\texpected: []Request{newProfilesRequest(func() pprofile.Profiles {\n\t\t\t\tprofiles := testdata.GenerateProfiles(4)\n\t\t\t\ttestdata.GenerateProfiles(6).ResourceProfiles().MoveAndAppendTo(profiles.ResourceProfiles())\n\t\t\t\treturn profiles\n\t\t\t}())},\n\t\t},\n\t\t{\n\t\t\tname:    \"split_only\",\n\t\t\tszt:     exporterhelper.RequestSizerTypeItems,\n\t\t\tmaxSize: 4,\n\t\t\tpr1:     newProfilesRequest(testdata.GenerateProfiles(10)),\n\t\t\tpr2:     nil,\n\t\t\texpected: []Request{\n\t\t\t\tnewProfilesRequest(testdata.GenerateProfiles(4)),\n\t\t\t\tnewProfilesRequest(testdata.GenerateProfiles(4)),\n\t\t\t\tnewProfilesRequest(testdata.GenerateProfiles(2)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"merge_and_split\",\n\t\t\tszt:     exporterhelper.RequestSizerTypeItems,\n\t\t\tmaxSize: 10,\n\t\t\tpr1:     newProfilesRequest(testdata.GenerateProfiles(8)),\n\t\t\tpr2:     newProfilesRequest(testdata.GenerateProfiles(20)),\n\t\t\texpected: []Request{\n\t\t\t\tnewProfilesRequest(func() pprofile.Profiles {\n\t\t\t\t\tprofiles := testdata.GenerateProfiles(8)\n\t\t\t\t\ttestdata.GenerateProfiles(2).ResourceProfiles().MoveAndAppendTo(profiles.ResourceProfiles())\n\t\t\t\t\treturn profiles\n\t\t\t\t}()),\n\t\t\t\tnewProfilesRequest(testdata.GenerateProfiles(10)),\n\t\t\t\tnewProfilesRequest(testdata.GenerateProfiles(8)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"scope_profiles_split\",\n\t\t\tszt:     exporterhelper.RequestSizerTypeItems,\n\t\t\tmaxSize: 4,\n\t\t\tpr1: newProfilesRequest(func() pprofile.Profiles {\n\t\t\t\treturn testdata.GenerateProfiles(6)\n\t\t\t}()),\n\t\t\tpr2: nil,\n\t\t\texpected: []Request{\n\t\t\t\tnewProfilesRequest(testdata.GenerateProfiles(4)),\n\t\t\t\tnewProfilesRequest(func() pprofile.Profiles {\n\t\t\t\t\treturn testdata.GenerateProfiles(2)\n\t\t\t\t}()),\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tres, err := tt.pr1.MergeSplit(context.Background(), tt.maxSize, tt.szt, tt.pr2)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Len(t, res, len(tt.expected))\n\t\t\tfor i, r := range res {\n\t\t\t\tassert.Equal(t, tt.expected[i].(*profilesRequest).pd, r.(*profilesRequest).pd)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMergeSplitProfilesBasedOnByteSize(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tszt      exporterhelper.RequestSizerType\n\t\tmaxSize  int\n\t\tpr1      Request\n\t\tpr2      Request\n\t\texpected []Request\n\t}{\n\t\t{\n\t\t\tname:     \"both_requests_empty\",\n\t\t\tszt:      exporterhelper.RequestSizerTypeItems,\n\t\t\tmaxSize:  10,\n\t\t\tpr1:      newProfilesRequest(pprofile.NewProfiles()),\n\t\t\tpr2:      newProfilesRequest(pprofile.NewProfiles()),\n\t\t\texpected: []Request{newProfilesRequest(pprofile.NewProfiles())},\n\t\t},\n\t\t{\n\t\t\tname:     \"first_request_empty\",\n\t\t\tszt:      exporterhelper.RequestSizerTypeItems,\n\t\t\tmaxSize:  10,\n\t\t\tpr1:      newProfilesRequest(pprofile.NewProfiles()),\n\t\t\tpr2:      newProfilesRequest(testdata.GenerateProfiles(5)),\n\t\t\texpected: []Request{newProfilesRequest(testdata.GenerateProfiles(5))},\n\t\t},\n\t\t{\n\t\t\tname:     \"first_empty_second_nil\",\n\t\t\tszt:      exporterhelper.RequestSizerTypeItems,\n\t\t\tmaxSize:  10,\n\t\t\tpr1:      newProfilesRequest(pprofile.NewProfiles()),\n\t\t\tpr2:      nil,\n\t\t\texpected: []Request{newProfilesRequest(pprofile.NewProfiles())},\n\t\t},\n\t\t{\n\t\t\tname:    \"merge_only\",\n\t\t\tszt:     exporterhelper.RequestSizerTypeItems,\n\t\t\tmaxSize: 10,\n\t\t\tpr1:     newProfilesRequest(testdata.GenerateProfiles(4)),\n\t\t\tpr2:     newProfilesRequest(testdata.GenerateProfiles(6)),\n\t\t\texpected: []Request{newProfilesRequest(func() pprofile.Profiles {\n\t\t\t\tprofiles := testdata.GenerateProfiles(4)\n\t\t\t\ttestdata.GenerateProfiles(6).ResourceProfiles().MoveAndAppendTo(profiles.ResourceProfiles())\n\t\t\t\treturn profiles\n\t\t\t}())},\n\t\t},\n\t\t{\n\t\t\tname:    \"split_only\",\n\t\t\tszt:     exporterhelper.RequestSizerTypeItems,\n\t\t\tmaxSize: 4,\n\t\t\tpr1:     newProfilesRequest(testdata.GenerateProfiles(10)),\n\t\t\tpr2:     nil,\n\t\t\texpected: []Request{\n\t\t\t\tnewProfilesRequest(testdata.GenerateProfiles(4)),\n\t\t\t\tnewProfilesRequest(testdata.GenerateProfiles(4)),\n\t\t\t\tnewProfilesRequest(testdata.GenerateProfiles(2)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"merge_and_split\",\n\t\t\tszt:     exporterhelper.RequestSizerTypeItems,\n\t\t\tmaxSize: 10,\n\t\t\tpr1:     newProfilesRequest(testdata.GenerateProfiles(8)),\n\t\t\tpr2:     newProfilesRequest(testdata.GenerateProfiles(20)),\n\t\t\texpected: []Request{\n\t\t\t\tnewProfilesRequest(func() pprofile.Profiles {\n\t\t\t\t\tprofiles := testdata.GenerateProfiles(8)\n\t\t\t\t\ttestdata.GenerateProfiles(2).ResourceProfiles().MoveAndAppendTo(profiles.ResourceProfiles())\n\t\t\t\t\treturn profiles\n\t\t\t\t}()),\n\t\t\t\tnewProfilesRequest(testdata.GenerateProfiles(10)),\n\t\t\t\tnewProfilesRequest(testdata.GenerateProfiles(8)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"scope_profiles_split\",\n\t\t\tszt:     exporterhelper.RequestSizerTypeItems,\n\t\t\tmaxSize: 4,\n\t\t\tpr1: newProfilesRequest(func() pprofile.Profiles {\n\t\t\t\treturn testdata.GenerateProfiles(6)\n\t\t\t}()),\n\t\t\tpr2: nil,\n\t\t\texpected: []Request{\n\t\t\t\tnewProfilesRequest(testdata.GenerateProfiles(4)),\n\t\t\t\tnewProfilesRequest(func() pprofile.Profiles {\n\t\t\t\t\treturn testdata.GenerateProfiles(2)\n\t\t\t\t}()),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:     \"both_requests_empty\",\n\t\t\tszt:      exporterhelper.RequestSizerTypeBytes,\n\t\t\tmaxSize:  profilesMarshaler.ProfilesSize(testdata.GenerateProfiles(10)),\n\t\t\tpr1:      newProfilesRequest(pprofile.NewProfiles()),\n\t\t\tpr2:      newProfilesRequest(pprofile.NewProfiles()),\n\t\t\texpected: []Request{newProfilesRequest(pprofile.NewProfiles())},\n\t\t},\n\t\t{\n\t\t\tname:     \"first_request_empty\",\n\t\t\tszt:      exporterhelper.RequestSizerTypeBytes,\n\t\t\tmaxSize:  profilesMarshaler.ProfilesSize(testdata.GenerateProfiles(10)),\n\t\t\tpr1:      newProfilesRequest(pprofile.NewProfiles()),\n\t\t\tpr2:      newProfilesRequest(testdata.GenerateProfiles(5)),\n\t\t\texpected: []Request{newProfilesRequest(testdata.GenerateProfiles(5))},\n\t\t},\n\t\t{\n\t\t\tname:     \"first_empty_second_nil\",\n\t\t\tszt:      exporterhelper.RequestSizerTypeBytes,\n\t\t\tmaxSize:  profilesMarshaler.ProfilesSize(testdata.GenerateProfiles(10)),\n\t\t\tpr1:      newProfilesRequest(pprofile.NewProfiles()),\n\t\t\tpr2:      nil,\n\t\t\texpected: []Request{newProfilesRequest(pprofile.NewProfiles())},\n\t\t},\n\t\t{\n\t\t\tname:    \"merge_only\",\n\t\t\tszt:     exporterhelper.RequestSizerTypeBytes,\n\t\t\tmaxSize: profilesMarshaler.ProfilesSize(testdata.GenerateProfiles(13)),\n\t\t\tpr1:     newProfilesRequest(testdata.GenerateProfiles(4)),\n\t\t\tpr2:     newProfilesRequest(testdata.GenerateProfiles(6)),\n\t\t\texpected: []Request{newProfilesRequest(func() pprofile.Profiles {\n\t\t\t\tprofiles := testdata.GenerateProfiles(4)\n\t\t\t\ttestdata.GenerateProfiles(6).ResourceProfiles().MoveAndAppendTo(profiles.ResourceProfiles())\n\t\t\t\treturn profiles\n\t\t\t}())},\n\t\t},\n\t\t{\n\t\t\tname:    \"split_only\",\n\t\t\tszt:     exporterhelper.RequestSizerTypeBytes,\n\t\t\tmaxSize: profilesMarshaler.ProfilesSize(testdata.GenerateProfiles(4)),\n\t\t\tpr1:     newProfilesRequest(testdata.GenerateProfiles(0)),\n\t\t\tpr2:     newProfilesRequest(testdata.GenerateProfiles(10)),\n\t\t\texpected: []Request{\n\t\t\t\tnewProfilesRequest(testdata.GenerateProfiles(4)),\n\t\t\t\tnewProfilesRequest(testdata.GenerateProfiles(5)),\n\t\t\t\tnewProfilesRequest(testdata.GenerateProfiles(1)),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"merge_and_split\",\n\t\t\tszt:     exporterhelper.RequestSizerTypeBytes,\n\t\t\tmaxSize: profilesMarshaler.ProfilesSize(testdata.GenerateProfiles(10)),\n\t\t\tpr1:     newProfilesRequest(testdata.GenerateProfiles(8)),\n\t\t\tpr2:     newProfilesRequest(testdata.GenerateProfiles(20)),\n\t\t\texpected: []Request{\n\t\t\t\tnewProfilesRequest(func() pprofile.Profiles {\n\t\t\t\t\tprofiles := testdata.GenerateProfiles(7)\n\t\t\t\t\ttestdata.GenerateProfiles(3).ResourceProfiles().MoveAndAppendTo(profiles.ResourceProfiles())\n\t\t\t\t\treturn profiles\n\t\t\t\t}()),\n\t\t\t\tnewProfilesRequest(testdata.GenerateProfiles(11)),\n\t\t\t\tnewProfilesRequest(testdata.GenerateProfiles(7)),\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tres, err := tt.pr1.MergeSplit(context.Background(), tt.maxSize, tt.szt, tt.pr2)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Len(t, res, len(tt.expected))\n\t\t\tfor i, r := range res {\n\t\t\t\tassert.Equal(t, tt.expected[i].(*profilesRequest).pd.SampleCount(), r.(*profilesRequest).pd.SampleCount(), i)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestExtractProfiles(t *testing.T) {\n\tfor i := range 10 {\n\t\tld := testdata.GenerateProfiles(10)\n\t\textractedProfiles, _ := extractProfiles(ld, i, &sizer.ProfilesCountSizer{})\n\t\tassert.Equal(t, i, extractedProfiles.SampleCount())\n\t\tassert.Equal(t, 10-i, ld.SampleCount())\n\t}\n}\n\nfunc TestMergeSplitManySmallProfiles(t *testing.T) {\n\t// All requests merge into a single batch.\n\tmerged := []Request{newProfilesRequest(testdata.GenerateProfiles(1))}\n\tfor range 1000 {\n\t\tpr2 := newProfilesRequest(testdata.GenerateProfiles(10))\n\t\tres, _ := merged[len(merged)-1].MergeSplit(context.Background(), 10000, exporterhelper.RequestSizerTypeItems, pr2)\n\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t}\n\tassert.Len(t, merged, 2)\n}\n\nfunc BenchmarkSplittingBasedOnByteSizeManySmallProfiles(b *testing.B) {\n\t// All requests merge into a single batch.\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tmerged := []Request{newProfilesRequest(testdata.GenerateProfiles(10))}\n\t\tfor range 1000 {\n\t\t\tpr2 := newProfilesRequest(testdata.GenerateProfiles(10))\n\t\t\tres, _ := merged[len(merged)-1].MergeSplit(\n\t\t\t\tcontext.Background(),\n\t\t\t\tprofilesMarshaler.ProfilesSize(testdata.GenerateProfiles(11000)),\n\t\t\t\texporterhelper.RequestSizerTypeBytes,\n\t\t\t\tpr2,\n\t\t\t)\n\t\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t\t}\n\t\tassert.Len(b, merged, 2)\n\t}\n}\n\nfunc BenchmarkSplittingBasedOnByteSizeManyProfilesSlightlyAboveLimit(b *testing.B) {\n\t// Every incoming request results in a split.\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tmerged := []Request{newProfilesRequest(testdata.GenerateProfiles(0))}\n\t\tfor range 10 {\n\t\t\tpr2 := newProfilesRequest(testdata.GenerateProfiles(10001))\n\t\t\tres, _ := merged[len(merged)-1].MergeSplit(\n\t\t\t\tcontext.Background(),\n\t\t\t\tprofilesMarshaler.ProfilesSize(testdata.GenerateProfiles(10000)),\n\t\t\t\texporterhelper.RequestSizerTypeBytes,\n\t\t\t\tpr2,\n\t\t\t)\n\t\t\tassert.Len(b, res, 2)\n\t\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t\t}\n\t\tassert.Len(b, merged, 11)\n\t}\n}\n\nfunc BenchmarkSplittingBasedOnByteSizeHugeProfiles(b *testing.B) {\n\t// One request splits into many batches.\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tmerged := []Request{newProfilesRequest(testdata.GenerateProfiles(0))}\n\t\tpr2 := newProfilesRequest(testdata.GenerateProfiles(100000))\n\t\tres, _ := merged[len(merged)-1].MergeSplit(\n\t\t\tcontext.Background(),\n\t\t\tprofilesMarshaler.ProfilesSize(testdata.GenerateProfiles(10010)),\n\t\t\texporterhelper.RequestSizerTypeBytes,\n\t\t\tpr2,\n\t\t)\n\t\tmerged = append(merged[0:len(merged)-1], res...)\n\t\tassert.Len(b, merged, 10)\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/xexporterhelper/profiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xexporterhelper\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\tsdktrace \"go.opentelemetry.io/otel/sdk/trace\"\n\t\"go.opentelemetry.io/otel/sdk/trace/tracetest\"\n\t\"go.opentelemetry.io/otel/trace\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror/xconsumererror\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/hosttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/oteltest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/queue\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/requesttest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/sendertest\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/internal/storagetest\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nconst (\n\tfakeProfilesParentSpanName = \"fake_profiles_parent_span_name\"\n)\n\nvar fakeProfilesExporterConfig = struct{}{}\n\nfunc TestProfilesRequest(t *testing.T) {\n\tlr := newProfilesRequest(testdata.GenerateProfiles(1))\n\n\tprofileErr := xconsumererror.NewProfiles(errors.New(\"some error\"), pprofile.NewProfiles())\n\tassert.Equal(\n\t\tt,\n\t\tnewProfilesRequest(pprofile.NewProfiles()),\n\t\tlr.(RequestErrorHandler).OnError(profileErr),\n\t)\n}\n\nfunc TestProfilesExporter_InvalidName(t *testing.T) {\n\tle, err := NewProfiles(context.Background(), exportertest.NewNopSettings(exportertest.NopType), nil, newPushProfilesData(nil))\n\trequire.Nil(t, le)\n\trequire.Equal(t, errNilConfig, err)\n}\n\nfunc TestProfilesExporter_NilLogger(t *testing.T) {\n\tle, err := NewProfiles(context.Background(), exporter.Settings{}, &fakeProfilesExporterConfig, newPushProfilesData(nil))\n\trequire.Nil(t, le)\n\trequire.Equal(t, errNilLogger, err)\n}\n\nfunc TestProfilesRequestExporter_NilLogger(t *testing.T) {\n\tle, err := NewProfilesRequest(context.Background(), exporter.Settings{}, requestFromProfilesFunc(nil), sendertest.NewNopSenderFunc[Request]())\n\trequire.Nil(t, le)\n\trequire.Equal(t, errNilLogger, err)\n}\n\nfunc TestProfilesExporter_NilPushProfilesData(t *testing.T) {\n\tle, err := NewProfiles(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeProfilesExporterConfig, nil)\n\trequire.Nil(t, le)\n\trequire.Equal(t, errNilPushProfileData, err)\n}\n\nfunc TestProfilesExporter_NilProfilesConverter(t *testing.T) {\n\tte, err := NewProfilesRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType), nil, sendertest.NewNopSenderFunc[Request]())\n\trequire.Nil(t, te)\n\trequire.Equal(t, errNilProfilesConverter, err)\n}\n\nfunc TestProfilesRequestExporter_NilProfilesConverter(t *testing.T) {\n\tle, err := NewProfilesRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType), requestFromProfilesFunc(nil), nil)\n\trequire.Nil(t, le)\n\trequire.Equal(t, errNilConsumeRequest, err)\n}\n\nfunc TestProfilesExporter_Default(t *testing.T) {\n\tld := pprofile.NewProfiles()\n\tle, err := NewProfiles(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeProfilesExporterConfig, newPushProfilesData(nil))\n\tassert.NotNil(t, le)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, consumer.Capabilities{MutatesData: false}, le.Capabilities())\n\trequire.NoError(t, le.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.NoError(t, le.ConsumeProfiles(context.Background(), ld))\n\trequire.NoError(t, le.Shutdown(context.Background()))\n}\n\nfunc TestProfilesRequestExporter_Default(t *testing.T) {\n\tld := pprofile.NewProfiles()\n\tle, err := NewProfilesRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequestFromProfilesFunc(nil), sendertest.NewNopSenderFunc[Request]())\n\tassert.NotNil(t, le)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, consumer.Capabilities{MutatesData: false}, le.Capabilities())\n\trequire.NoError(t, le.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.NoError(t, le.ConsumeProfiles(context.Background(), ld))\n\trequire.NoError(t, le.Shutdown(context.Background()))\n}\n\nfunc TestProfilesExporter_WithCapabilities(t *testing.T) {\n\tcapabilities := consumer.Capabilities{MutatesData: true}\n\tle, err := NewProfiles(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeProfilesExporterConfig, newPushProfilesData(nil), exporterhelper.WithCapabilities(capabilities))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\n\tassert.Equal(t, capabilities, le.Capabilities())\n}\n\nfunc TestProfilesRequestExporter_WithCapabilities(t *testing.T) {\n\tcapabilities := consumer.Capabilities{MutatesData: true}\n\tle, err := NewProfilesRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequestFromProfilesFunc(nil), sendertest.NewNopSenderFunc[Request](), exporterhelper.WithCapabilities(capabilities))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\n\tassert.Equal(t, capabilities, le.Capabilities())\n}\n\nfunc TestProfilesExporter_Default_ReturnError(t *testing.T) {\n\tld := pprofile.NewProfiles()\n\twant := errors.New(\"my_error\")\n\tle, err := NewProfiles(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeProfilesExporterConfig, newPushProfilesData(want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\trequire.Equal(t, want, le.ConsumeProfiles(context.Background(), ld))\n}\n\nfunc TestProfilesRequestExporter_Default_ConvertError(t *testing.T) {\n\tld := pprofile.NewProfiles()\n\twant := errors.New(\"convert_error\")\n\tle, err := NewProfilesRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequestFromProfilesFunc(want), sendertest.NewNopSenderFunc[Request]())\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\trequire.Equal(t, consumererror.NewPermanent(want), le.ConsumeProfiles(context.Background(), ld))\n}\n\nfunc TestProfilesRequestExporter_Default_ExportError(t *testing.T) {\n\tld := pprofile.NewProfiles()\n\twant := errors.New(\"export_error\")\n\tle, err := NewProfilesRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequestFromProfilesFunc(nil), sendertest.NewErrSenderFunc[Request](want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\trequire.Equal(t, want, le.ConsumeProfiles(context.Background(), ld))\n}\n\nfunc TestProfiles_WithPersistentQueue(t *testing.T) {\n\tfgOrigReadState := queue.PersistRequestContextOnRead\n\tfgOrigWriteState := queue.PersistRequestContextOnWrite\n\tqCfg := exporterhelper.NewDefaultQueueConfig()\n\tstorageID := component.MustNewIDWithName(\"file_storage\", \"storage\")\n\tqCfg.StorageID = &storageID\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tset.ID = component.MustNewIDWithName(\"test_logs\", \"with_persistent_queue\")\n\thost := hosttest.NewHost(map[component.ID]component.Component{\n\t\tstorageID: storagetest.NewMockStorageExtension(nil),\n\t})\n\tspanCtx := oteltest.FakeSpanContext(t)\n\n\ttests := []struct {\n\t\tname             string\n\t\tfgEnabledOnWrite bool\n\t\tfgEnabledOnRead  bool\n\t\twantData         bool\n\t\twantSpanCtx      bool\n\t}{\n\t\t{\n\t\t\tname:     \"feature_gate_disabled_on_write_and_read\",\n\t\t\twantData: true,\n\t\t},\n\t\t{\n\t\t\tname:             \"feature_gate_enabled_on_write_and_read\",\n\t\t\tfgEnabledOnWrite: true,\n\t\t\tfgEnabledOnRead:  true,\n\t\t\twantData:         true,\n\t\t\twantSpanCtx:      true,\n\t\t},\n\t\t{\n\t\t\tname:            \"feature_gate_disabled_on_write_enabled_on_read\",\n\t\t\twantData:        true,\n\t\t\tfgEnabledOnRead: true,\n\t\t},\n\t\t{\n\t\t\tname:             \"feature_gate_enabled_on_write_disabled_on_read\",\n\t\t\tfgEnabledOnWrite: true,\n\t\t\twantData:         false, // going back from enabled to disabled feature gate isn't supported\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tqueue.PersistRequestContextOnRead = func() bool { return tt.fgEnabledOnRead }\n\t\t\tqueue.PersistRequestContextOnWrite = func() bool { return tt.fgEnabledOnWrite }\n\t\t\tt.Cleanup(func() {\n\t\t\t\tqueue.PersistRequestContextOnRead = fgOrigReadState\n\t\t\t\tqueue.PersistRequestContextOnWrite = fgOrigWriteState\n\t\t\t})\n\n\t\t\tts := consumertest.ProfilesSink{}\n\t\t\tte, err := NewProfiles(context.Background(), set, &fakeProfilesExporterConfig, ts.ConsumeProfiles, exporterhelper.WithQueue(configoptional.Some(qCfg)))\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, te.Start(context.Background(), host))\n\t\t\tt.Cleanup(func() { require.NoError(t, te.Shutdown(context.Background())) })\n\n\t\t\tprofiles := testdata.GenerateProfiles(2)\n\t\t\trequire.NoError(t, te.ConsumeProfiles(trace.ContextWithSpanContext(context.Background(), spanCtx), profiles))\n\t\t\tif tt.wantData {\n\t\t\t\trequire.Eventually(t, func() bool {\n\t\t\t\t\treturn len(ts.AllProfiles()) == 1 && ts.SampleCount() == 2\n\t\t\t\t}, 500*time.Millisecond, 10*time.Millisecond)\n\t\t\t}\n\n\t\t\t// check that the span context is persisted if the feature gate is enabled\n\t\t\tif tt.wantSpanCtx {\n\t\t\t\tassert.Len(t, ts.Contexts(), 1)\n\t\t\t\tassert.Equal(t, spanCtx, trace.SpanContextFromContext(ts.Contexts()[0]))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestProfilesExporter_WithSpan(t *testing.T) {\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tsr := new(tracetest.SpanRecorder)\n\tset.TracerProvider = sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))\n\totel.SetTracerProvider(set.TracerProvider)\n\tdefer otel.SetTracerProvider(nooptrace.NewTracerProvider())\n\n\tle, err := NewProfiles(context.Background(), set, &fakeProfilesExporterConfig, newPushProfilesData(nil))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\tcheckWrapSpanForProfilesExporter(t, sr, set.TracerProvider.Tracer(\"test\"), le, nil)\n}\n\nfunc TestProfilesRequestExporter_WithSpan(t *testing.T) {\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tsr := new(tracetest.SpanRecorder)\n\tset.TracerProvider = sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))\n\totel.SetTracerProvider(set.TracerProvider)\n\tdefer otel.SetTracerProvider(nooptrace.NewTracerProvider())\n\n\tle, err := NewProfilesRequest(context.Background(), set, requestFromProfilesFunc(nil), sendertest.NewNopSenderFunc[Request]())\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\tcheckWrapSpanForProfilesExporter(t, sr, set.TracerProvider.Tracer(\"test\"), le, nil)\n}\n\nfunc TestProfilesExporter_WithSpan_ReturnError(t *testing.T) {\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tsr := new(tracetest.SpanRecorder)\n\tset.TracerProvider = sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))\n\totel.SetTracerProvider(set.TracerProvider)\n\tdefer otel.SetTracerProvider(nooptrace.NewTracerProvider())\n\n\twant := errors.New(\"my_error\")\n\tle, err := NewProfiles(context.Background(), set, &fakeProfilesExporterConfig, newPushProfilesData(want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\tcheckWrapSpanForProfilesExporter(t, sr, set.TracerProvider.Tracer(\"test\"), le, want)\n}\n\nfunc TestProfilesRequestExporter_WithSpan_ReturnError(t *testing.T) {\n\tset := exportertest.NewNopSettings(exportertest.NopType)\n\tsr := new(tracetest.SpanRecorder)\n\tset.TracerProvider = sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))\n\totel.SetTracerProvider(set.TracerProvider)\n\tdefer otel.SetTracerProvider(nooptrace.NewTracerProvider())\n\n\twant := errors.New(\"my_error\")\n\tle, err := NewProfilesRequest(context.Background(), set, requestFromProfilesFunc(nil), sendertest.NewErrSenderFunc[Request](want))\n\trequire.NoError(t, err)\n\trequire.NotNil(t, le)\n\tcheckWrapSpanForProfilesExporter(t, sr, set.TracerProvider.Tracer(\"test\"), le, want)\n}\n\nfunc TestProfilesExporter_WithShutdown(t *testing.T) {\n\tshutdownCalled := false\n\tshutdown := func(context.Context) error { shutdownCalled = true; return nil }\n\n\tle, err := NewProfiles(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeProfilesExporterConfig, newPushProfilesData(nil), exporterhelper.WithShutdown(shutdown))\n\tassert.NotNil(t, le)\n\trequire.NoError(t, err)\n\n\trequire.NoError(t, le.Shutdown(context.Background()))\n\tassert.True(t, shutdownCalled)\n}\n\nfunc TestProfilesRequestExporter_WithShutdown(t *testing.T) {\n\tshutdownCalled := false\n\tshutdown := func(context.Context) error { shutdownCalled = true; return nil }\n\n\tle, err := NewProfilesRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequestFromProfilesFunc(nil), sendertest.NewNopSenderFunc[Request](), exporterhelper.WithShutdown(shutdown))\n\tassert.NotNil(t, le)\n\trequire.NoError(t, err)\n\n\trequire.NoError(t, le.Shutdown(context.Background()))\n\tassert.True(t, shutdownCalled)\n}\n\nfunc TestProfilesExporter_WithShutdown_ReturnError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tshutdownErr := func(context.Context) error { return want }\n\n\tle, err := NewProfiles(context.Background(), exportertest.NewNopSettings(exportertest.NopType), &fakeProfilesExporterConfig, newPushProfilesData(nil), exporterhelper.WithShutdown(shutdownErr))\n\tassert.NotNil(t, le)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, want, le.Shutdown(context.Background()))\n}\n\nfunc TestProfilesRequestExporter_WithShutdown_ReturnError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tshutdownErr := func(context.Context) error { return want }\n\n\tle, err := NewProfilesRequest(context.Background(), exportertest.NewNopSettings(exportertest.NopType),\n\t\trequestFromProfilesFunc(nil), sendertest.NewNopSenderFunc[Request](), exporterhelper.WithShutdown(shutdownErr))\n\tassert.NotNil(t, le)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, want, le.Shutdown(context.Background()))\n}\n\nfunc newPushProfilesData(retError error) xconsumer.ConsumeProfilesFunc {\n\treturn func(_ context.Context, _ pprofile.Profiles) error {\n\t\treturn retError\n\t}\n}\n\nfunc generateProfilesTraffic(t *testing.T, tracer trace.Tracer, le xexporter.Profiles, numRequests int, wantError error) {\n\tld := testdata.GenerateProfiles(1)\n\tctx, span := tracer.Start(context.Background(), fakeProfilesParentSpanName)\n\tdefer span.End()\n\tfor range numRequests {\n\t\trequire.Equal(t, wantError, le.ConsumeProfiles(ctx, ld))\n\t}\n}\n\nfunc checkWrapSpanForProfilesExporter(t *testing.T, sr *tracetest.SpanRecorder, tracer trace.Tracer, le xexporter.Profiles, wantError error) {\n\tconst numRequests = 5\n\tgenerateProfilesTraffic(t, tracer, le, numRequests, wantError)\n\n\t// Inspection time!\n\tgotSpanData := sr.Ended()\n\trequire.Len(t, gotSpanData, numRequests+1)\n\n\tparentSpan := gotSpanData[numRequests]\n\trequire.Equalf(t, fakeProfilesParentSpanName, parentSpan.Name(), \"SpanData %v\", parentSpan)\n\tfor _, sd := range gotSpanData[:numRequests] {\n\t\trequire.Equalf(t, parentSpan.SpanContext(), sd.Parent(), \"Exporter span not a child\\nSpanData %v\", sd)\n\t\toteltest.CheckStatus(t, sd, wantError)\n\n\t\tsentSampleRecords := int64(1)\n\t\tfailedToSendSampleRecords := int64(0)\n\t\tif wantError != nil {\n\t\t\tsentSampleRecords = 0\n\t\t\tfailedToSendSampleRecords = 1\n\t\t}\n\t\trequire.Containsf(t, sd.Attributes(), attribute.KeyValue{Key: internal.ItemsSent, Value: attribute.Int64Value(sentSampleRecords)}, \"SpanData %v\", sd)\n\t\trequire.Containsf(t, sd.Attributes(), attribute.KeyValue{Key: internal.ItemsFailed, Value: attribute.Int64Value(failedToSendSampleRecords)}, \"SpanData %v\", sd)\n\t}\n}\n\nfunc requestFromProfilesFunc(err error) func(context.Context, pprofile.Profiles) (Request, error) {\n\treturn func(_ context.Context, pd pprofile.Profiles) (Request, error) {\n\t\treturn &requesttest.FakeRequest{Items: pd.SampleCount()}, err\n\t}\n}\n"
  },
  {
    "path": "exporter/exporterhelper/xexporterhelper/request.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xexporterhelper // import \"go.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper\"\n\nimport \"go.opentelemetry.io/collector/exporter/exporterhelper/internal/request\" // Request represents a single request that can be sent to an external endpoint.\n\n// Request represents a single request that can be sent to an external endpoint.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\ntype Request = request.Request\n\n// RequestErrorHandler is an optional interface that can be implemented by Request to provide a way handle partial\n// temporary failures. For example, if some items failed to process and can be retried, this interface allows to\n// return a new Request that contains the items left to be sent. Otherwise, the original Request should be returned.\n// If not implemented, the original Request will be returned assuming the error is applied to the whole Request.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\ntype RequestErrorHandler = request.ErrorHandler\n\n// RequestConverterFunc converts pdata telemetry into a user-defined Request.\n// Experimental: This API is at the early stage of development and may change without backward compatibility\n// until https://github.com/open-telemetry/opentelemetry-collector/issues/8122 is resolved.\ntype RequestConverterFunc[T any] = request.RequestConverterFunc[T]\n\n// RequestConsumeFunc processes the request. After the function returns, the request is no longer accessible,\n// and accessing it is considered undefined behavior.\ntype RequestConsumeFunc = request.RequestConsumeFunc\n"
  },
  {
    "path": "exporter/exportertest/Makefile",
    "content": "include ../../Makefile.Common"
  },
  {
    "path": "exporter/exportertest/contract_checker.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exportertest // import \"go.opentelemetry.io/collector/exporter/exportertest\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strconv\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\n// uniqueIDAttrName is the attribute name that is used in log records/spans/datapoints as the unique identifier.\nconst uniqueIDAttrName = \"test_id\"\n\n// uniqueIDAttrVal is the value type of the uniqueIDAttrName.\ntype uniqueIDAttrVal string\n\ntype CheckConsumeContractParams struct {\n\tT                    *testing.T\n\tNumberOfTestElements int\n\tSignal               pipeline.Signal\n\t// ExporterFactory to create an exporter to be tested.\n\tExporterFactory exporter.Factory\n\tExporterConfig  component.Config\n\t// ReceiverFactory to create a mock receiver.\n\tReceiverFactory receiver.Factory\n\tReceiverConfig  component.Config\n}\n\nfunc CheckConsumeContract(params CheckConsumeContractParams) {\n\t// Different scenarios to test for.\n\t// The decision function defines the testing scenario (i.e. to test for\n\t// success case or for error case or a mix of both). See for example randomErrorsConsumeDecision.\n\tscenarios := []struct {\n\t\tname              string\n\t\tdecisionFunc      func() error\n\t\tcheckIfTestPassed func(*testing.T, int, requestCounter)\n\t}{\n\t\t{\n\t\t\tname: \"always_succeed\",\n\t\t\t// Always succeed. We expect all data to be delivered as is.\n\t\t\tdecisionFunc:      func() error { return nil },\n\t\t\tcheckIfTestPassed: alwaysSucceedsPassed,\n\t\t},\n\t\t{\n\t\t\tname:              \"random_non_permanent_error\",\n\t\t\tdecisionFunc:      randomNonPermanentErrorConsumeDecision,\n\t\t\tcheckIfTestPassed: randomNonPermanentErrorConsumeDecisionPassed,\n\t\t},\n\t\t{\n\t\t\tname:              \"random_permanent_error\",\n\t\t\tdecisionFunc:      randomPermanentErrorConsumeDecision,\n\t\t\tcheckIfTestPassed: randomPermanentErrorConsumeDecisionPassed,\n\t\t},\n\t\t{\n\t\t\tname:              \"random_error\",\n\t\t\tdecisionFunc:      randomErrorsConsumeDecision,\n\t\t\tcheckIfTestPassed: randomErrorConsumeDecisionPassed,\n\t\t},\n\t}\n\tfor _, scenario := range scenarios {\n\t\tparams.T.Run(\n\t\t\tscenario.name, func(t *testing.T) {\n\t\t\t\tcheckConsumeContractScenario(t, params, scenario.decisionFunc, scenario.checkIfTestPassed)\n\t\t\t},\n\t\t)\n\t}\n}\n\nfunc checkConsumeContractScenario(t *testing.T, params CheckConsumeContractParams, decisionFunc func() error, checkIfTestPassed func(*testing.T, int, requestCounter)) {\n\tmockConsumerInstance := newMockConsumer(decisionFunc)\n\tswitch params.Signal {\n\tcase pipeline.SignalLogs:\n\t\tr, err := params.ReceiverFactory.CreateLogs(context.Background(), receivertest.NewNopSettings(params.ReceiverFactory.Type()), params.ReceiverConfig, &mockConsumerInstance)\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, r.Start(context.Background(), componenttest.NewNopHost()))\n\t\tcheckLogs(t, params, r, &mockConsumerInstance, checkIfTestPassed)\n\tcase pipeline.SignalTraces:\n\t\tr, err := params.ReceiverFactory.CreateTraces(context.Background(), receivertest.NewNopSettings(params.ReceiverFactory.Type()), params.ReceiverConfig, &mockConsumerInstance)\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, r.Start(context.Background(), componenttest.NewNopHost()))\n\t\tcheckTraces(t, params, r, &mockConsumerInstance, checkIfTestPassed)\n\tcase pipeline.SignalMetrics:\n\t\tr, err := params.ReceiverFactory.CreateMetrics(context.Background(), receivertest.NewNopSettings(params.ReceiverFactory.Type()), params.ReceiverConfig, &mockConsumerInstance)\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, r.Start(context.Background(), componenttest.NewNopHost()))\n\t\tcheckMetrics(t, params, r, &mockConsumerInstance, checkIfTestPassed)\n\tdefault:\n\t\trequire.FailNow(t, \"must specify a valid DataType to test for\")\n\t}\n}\n\nfunc checkMetrics(t *testing.T, params CheckConsumeContractParams, mockReceiver component.Component,\n\tmockConsumer *mockConsumer, checkIfTestPassed func(*testing.T, int, requestCounter),\n) {\n\tctx := context.Background()\n\tvar exp exporter.Metrics\n\tvar err error\n\texp, err = params.ExporterFactory.CreateMetrics(ctx, NewNopSettings(params.ExporterFactory.Type()), params.ExporterConfig)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, exp)\n\n\terr = exp.Start(ctx, componenttest.NewNopHost())\n\trequire.NoError(t, err)\n\n\tdefer func(exp exporter.Metrics, ctx context.Context) {\n\t\terr = exp.Shutdown(ctx)\n\t\trequire.NoError(t, err)\n\t\terr = mockReceiver.Shutdown(ctx)\n\t\trequire.NoError(t, err)\n\t\tmockConsumer.clear()\n\t}(exp, ctx)\n\n\tfor i := 0; i < params.NumberOfTestElements; i++ {\n\t\tid := uniqueIDAttrVal(strconv.Itoa(i))\n\t\tdata := createOneMetricWithID(id)\n\n\t\terr = exp.ConsumeMetrics(ctx, data)\n\t}\n\n\treqCounter := mockConsumer.getRequestCounter()\n\t// The overall number of requests sent by exporter\n\tfmt.Printf(\"Number of export tries: %d\\n\", reqCounter.total)\n\t// Successfully delivered items\n\tfmt.Printf(\"Total items received successfully: %d\\n\", reqCounter.success)\n\t// Number of errors that happened\n\tfmt.Printf(\"Number of permanent errors: %d\\n\", reqCounter.error.permanent)\n\tfmt.Printf(\"Number of non-permanent errors: %d\\n\", reqCounter.error.nonpermanent)\n\n\tassert.EventuallyWithT(t, func(*assert.CollectT) {\n\t\tcheckIfTestPassed(t, params.NumberOfTestElements, *reqCounter)\n\t}, 2*time.Second, 100*time.Millisecond)\n}\n\nfunc checkTraces(t *testing.T, params CheckConsumeContractParams, mockReceiver component.Component, mockConsumer *mockConsumer, checkIfTestPassed func(*testing.T, int, requestCounter)) {\n\tctx := context.Background()\n\tvar exp exporter.Traces\n\tvar err error\n\texp, err = params.ExporterFactory.CreateTraces(ctx, NewNopSettings(params.ExporterFactory.Type()), params.ExporterConfig)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, exp)\n\n\terr = exp.Start(ctx, componenttest.NewNopHost())\n\trequire.NoError(t, err)\n\n\tdefer func(exp exporter.Traces, ctx context.Context) {\n\t\terr = exp.Shutdown(ctx)\n\t\trequire.NoError(t, err)\n\t\terr = mockReceiver.Shutdown(ctx)\n\t\trequire.NoError(t, err)\n\t\tmockConsumer.clear()\n\t}(exp, ctx)\n\n\tfor i := 0; i < params.NumberOfTestElements; i++ {\n\t\tid := uniqueIDAttrVal(strconv.Itoa(i))\n\t\tdata := createOneTraceWithID(id)\n\n\t\terr = exp.ConsumeTraces(ctx, data)\n\t}\n\n\treqCounter := mockConsumer.getRequestCounter()\n\t// The overall number of requests sent by exporter\n\tfmt.Printf(\"Number of export tries: %d\\n\", reqCounter.total)\n\t// Successfully delivered items\n\tfmt.Printf(\"Total items received successfully: %d\\n\", reqCounter.success)\n\t// Number of errors that happened\n\tfmt.Printf(\"Number of permanent errors: %d\\n\", reqCounter.error.permanent)\n\tfmt.Printf(\"Number of non-permanent errors: %d\\n\", reqCounter.error.nonpermanent)\n\n\tassert.EventuallyWithT(t, func(*assert.CollectT) {\n\t\tcheckIfTestPassed(t, params.NumberOfTestElements, *reqCounter)\n\t}, 2*time.Second, 100*time.Millisecond)\n}\n\nfunc checkLogs(t *testing.T, params CheckConsumeContractParams, mockReceiver component.Component, mockConsumer *mockConsumer, checkIfTestPassed func(*testing.T, int, requestCounter)) {\n\tctx := context.Background()\n\tvar exp exporter.Logs\n\tvar err error\n\texp, err = params.ExporterFactory.CreateLogs(ctx, NewNopSettings(params.ExporterFactory.Type()), params.ExporterConfig)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, exp)\n\n\terr = exp.Start(ctx, componenttest.NewNopHost())\n\trequire.NoError(t, err)\n\n\tdefer func(exp exporter.Logs, ctx context.Context) {\n\t\terr = exp.Shutdown(ctx)\n\t\trequire.NoError(t, err)\n\t\terr = mockReceiver.Shutdown(ctx)\n\t\trequire.NoError(t, err)\n\t\tmockConsumer.clear()\n\t}(exp, ctx)\n\n\tfor i := 0; i < params.NumberOfTestElements; i++ {\n\t\tid := uniqueIDAttrVal(strconv.Itoa(i))\n\t\tdata := createOneLogWithID(id)\n\n\t\terr = exp.ConsumeLogs(ctx, data)\n\t}\n\treqCounter := mockConsumer.getRequestCounter()\n\t// The overall number of requests sent by exporter\n\tfmt.Printf(\"Number of export tries: %d\\n\", reqCounter.total)\n\t// Successfully delivered items\n\tfmt.Printf(\"Total items received successfully: %d\\n\", reqCounter.success)\n\t// Number of errors that happened\n\tfmt.Printf(\"Number of permanent errors: %d\\n\", reqCounter.error.permanent)\n\tfmt.Printf(\"Number of non-permanent errors: %d\\n\", reqCounter.error.nonpermanent)\n\n\tassert.EventuallyWithT(t, func(*assert.CollectT) {\n\t\tcheckIfTestPassed(t, params.NumberOfTestElements, *reqCounter)\n\t}, 2*time.Second, 100*time.Millisecond)\n}\n\n// Test is successful if all the elements were received successfully and no error was returned\nfunc alwaysSucceedsPassed(t *testing.T, allRecordsNumber int, reqCounter requestCounter) {\n\trequire.Equal(t, allRecordsNumber, reqCounter.success)\n\trequire.Equal(t, allRecordsNumber, reqCounter.total)\n\trequire.Equal(t, 0, reqCounter.error.nonpermanent)\n\trequire.Equal(t, 0, reqCounter.error.permanent)\n}\n\n// Test is successful if all the elements were retried on non-permanent errors\nfunc randomNonPermanentErrorConsumeDecisionPassed(t *testing.T, allRecordsNumber int, reqCounter requestCounter) {\n\t// more or equal tries than successes\n\trequire.GreaterOrEqual(t, reqCounter.total, reqCounter.success)\n\t// it is retried on every error\n\trequire.Equal(t, reqCounter.total-reqCounter.error.nonpermanent, reqCounter.success)\n\trequire.Equal(t, allRecordsNumber+reqCounter.error.nonpermanent, reqCounter.total)\n}\n\n// Test is successful if the calls are not retried on permanent errors\nfunc randomPermanentErrorConsumeDecisionPassed(t *testing.T, allRecordsNumber int, reqCounter requestCounter) {\n\trequire.Equal(t, allRecordsNumber-reqCounter.error.permanent, reqCounter.success)\n\trequire.Equal(t, reqCounter.total, allRecordsNumber)\n}\n\n// Test is successful if the calls are not retried on permanent errors\nfunc randomErrorConsumeDecisionPassed(t *testing.T, allRecordsNumber int, reqCounter requestCounter) {\n\trequire.Equal(t, allRecordsNumber-reqCounter.error.permanent, reqCounter.success)\n\trequire.Equal(t, reqCounter.total, allRecordsNumber+reqCounter.error.nonpermanent)\n}\n\nfunc createOneLogWithID(id uniqueIDAttrVal) plog.Logs {\n\tdata := plog.NewLogs()\n\tdata.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty().Attributes().PutStr(\n\t\tuniqueIDAttrName,\n\t\tstring(id),\n\t)\n\treturn data\n}\n\nfunc createOneTraceWithID(id uniqueIDAttrVal) ptrace.Traces {\n\tdata := ptrace.NewTraces()\n\tdata.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty().Attributes().PutStr(\n\t\tuniqueIDAttrName,\n\t\tstring(id),\n\t)\n\treturn data\n}\n\nfunc createOneMetricWithID(id uniqueIDAttrVal) pmetric.Metrics {\n\tdata := pmetric.NewMetrics()\n\tdata.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptyHistogram().\n\t\tDataPoints().AppendEmpty().Attributes().PutStr(uniqueIDAttrName, string(id))\n\treturn data\n}\n"
  },
  {
    "path": "exporter/exportertest/contract_checker_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exportertest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configretry\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/receiver\"\n)\n\n// retryConfig is a configuration to quickly retry failed exports.\nvar retryConfig = func() configretry.BackOffConfig {\n\tc := configretry.NewDefaultBackOffConfig()\n\tc.InitialInterval = time.Millisecond\n\treturn c\n}()\n\n// mockReceiver is a receiver with pass-through consumers.\ntype mockReceiver struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumer.Traces\n\tconsumer.Metrics\n\tconsumer.Logs\n}\n\n// mockFactory is a factory to create exporters sending data to the mockReceiver.\ntype mockFactory struct {\n\tmr *mockReceiver\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n}\n\nfunc (mef *mockFactory) createMockTraces(\n\tctx context.Context,\n\tset exporter.Settings,\n\tcfg component.Config,\n) (exporter.Traces, error) {\n\treturn exporterhelper.NewTraces(ctx, set, cfg,\n\t\tmef.mr.ConsumeTraces,\n\t\texporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),\n\t\texporterhelper.WithRetry(retryConfig),\n\t)\n}\n\nfunc (mef *mockFactory) createMockMetrics(\n\tctx context.Context,\n\tset exporter.Settings,\n\tcfg component.Config,\n) (exporter.Metrics, error) {\n\treturn exporterhelper.NewMetrics(ctx, set, cfg,\n\t\tmef.mr.ConsumeMetrics,\n\t\texporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),\n\t\texporterhelper.WithRetry(retryConfig),\n\t)\n}\n\nfunc (mef *mockFactory) createMockLogs(\n\tctx context.Context,\n\tset exporter.Settings,\n\tcfg component.Config,\n) (exporter.Logs, error) {\n\treturn exporterhelper.NewLogs(ctx, set, cfg,\n\t\tmef.mr.ConsumeLogs,\n\t\texporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),\n\t\texporterhelper.WithRetry(retryConfig),\n\t)\n}\n\nfunc newMockFactory(mr *mockReceiver) exporter.Factory {\n\tmef := &mockFactory{mr: mr}\n\treturn exporter.NewFactory(\n\t\tcomponent.MustNewType(\"pass_through_exporter\"),\n\t\tfunc() component.Config { return &nopConfig{} },\n\t\texporter.WithTraces(mef.createMockTraces, component.StabilityLevelBeta),\n\t\texporter.WithMetrics(mef.createMockMetrics, component.StabilityLevelBeta),\n\t\texporter.WithLogs(mef.createMockLogs, component.StabilityLevelBeta),\n\t)\n}\n\nfunc newMockReceiverFactory(mr *mockReceiver) receiver.Factory {\n\treturn receiver.NewFactory(component.MustNewType(\"pass_through_receiver\"),\n\t\tfunc() component.Config { return &nopConfig{} },\n\t\treceiver.WithTraces(func(_ context.Context, _ receiver.Settings, _ component.Config, c consumer.Traces) (receiver.Traces, error) {\n\t\t\tmr.Traces = c\n\t\t\treturn mr, nil\n\t\t}, component.StabilityLevelStable),\n\t\treceiver.WithMetrics(func(_ context.Context, _ receiver.Settings, _ component.Config, c consumer.Metrics) (receiver.Metrics, error) {\n\t\t\tmr.Metrics = c\n\t\t\treturn mr, nil\n\t\t}, component.StabilityLevelStable),\n\t\treceiver.WithLogs(func(_ context.Context, _ receiver.Settings, _ component.Config, c consumer.Logs) (receiver.Logs, error) {\n\t\t\tmr.Logs = c\n\t\t\treturn mr, nil\n\t\t}, component.StabilityLevelStable),\n\t)\n}\n\nfunc TestCheckConsumeContractLogs(t *testing.T) {\n\tmr := &mockReceiver{}\n\tparams := CheckConsumeContractParams{\n\t\tT:                    t,\n\t\tExporterFactory:      newMockFactory(mr),\n\t\tSignal:               pipeline.SignalLogs,\n\t\tExporterConfig:       nopConfig{},\n\t\tNumberOfTestElements: 10,\n\t\tReceiverFactory:      newMockReceiverFactory(mr),\n\t}\n\n\tCheckConsumeContract(params)\n}\n\nfunc TestCheckConsumeContractMetrics(t *testing.T) {\n\tmr := &mockReceiver{}\n\tCheckConsumeContract(CheckConsumeContractParams{\n\t\tT:                    t,\n\t\tExporterFactory:      newMockFactory(mr),\n\t\tSignal:               pipeline.SignalMetrics, // Change to the appropriate data type\n\t\tExporterConfig:       nopConfig{},\n\t\tNumberOfTestElements: 10,\n\t\tReceiverFactory:      newMockReceiverFactory(mr),\n\t})\n}\n\nfunc TestCheckConsumeContractTraces(t *testing.T) {\n\tmr := &mockReceiver{}\n\tCheckConsumeContract(CheckConsumeContractParams{\n\t\tT:                    t,\n\t\tExporterFactory:      newMockFactory(mr),\n\t\tSignal:               pipeline.SignalTraces,\n\t\tExporterConfig:       nopConfig{},\n\t\tNumberOfTestElements: 10,\n\t\tReceiverFactory:      newMockReceiverFactory(mr),\n\t})\n}\n"
  },
  {
    "path": "exporter/exportertest/go.mod",
    "content": "module go.opentelemetry.io/collector/exporter/exportertest\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/google/uuid v1.6.0\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/config/configretry v1.54.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/exporter v1.54.0\n\tgo.opentelemetry.io/collector/exporter/exporterhelper v0.148.0\n\tgo.opentelemetry.io/collector/exporter/xexporter v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/receiver v1.54.0\n\tgo.opentelemetry.io/collector/receiver/receivertest v0.148.0\n\tgoogle.golang.org/grpc v1.79.3\n)\n\nrequire (\n\tgithub.com/cenkalti/backoff/v5 v5.0.3 // indirect\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/hashicorp/golang-lru/v2 v2.0.7 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/client v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configoptional v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/confmap v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/xextension v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/xpdata v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/exporter => ../../exporter\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/receiver => ../../receiver\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../../receiver/receivertest\n\nreplace go.opentelemetry.io/collector/extension => ../../extension\n\nreplace go.opentelemetry.io/collector/config/configretry => ../../config/configretry\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/exporter/xexporter => ../xexporter\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../../extension/extensiontest\n\nreplace go.opentelemetry.io/collector/extension/xextension => ../../extension/xextension\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/client => ../../client\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../../config/configoptional\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper => ../exporterhelper\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n"
  },
  {
    "path": "exporter/exportertest/go.sum",
    "content": "github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=\ngithub.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "exporter/exportertest/metadata.yaml",
    "content": "type: exporter/exportertest\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "exporter/exportertest/mock_consumer.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\npackage exportertest // import \"go.opentelemetry.io/collector/exporter/exportertest\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math/rand/v2\"\n\t\"sync\"\n\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nvar (\n\terrNonPermanent = status.Error(codes.DeadlineExceeded, \"non Permanent error\")\n\terrPermanent    = status.Error(codes.Internal, \"Permanent error\")\n)\n\n// // randomNonPermanentErrorConsumeDecision is a decision function that succeeds approximately\n// // half of the time and fails with a non-permanent error the rest of the time.\nfunc randomNonPermanentErrorConsumeDecision() error {\n\tif rand.Float32() < 0.5 {\n\t\treturn errNonPermanent\n\t}\n\treturn nil\n}\n\n// randomPermanentErrorConsumeDecision is a decision function that succeeds approximately\n// half of the time and fails with a permanent error the rest of the time.\nfunc randomPermanentErrorConsumeDecision() error {\n\tif rand.Float32() < 0.5 {\n\t\treturn consumererror.NewPermanent(errPermanent)\n\t}\n\treturn nil\n}\n\n// randomErrorsConsumeDecision is a decision function that succeeds approximately\n// a third of the time, fails with a permanent error the third of the time and fails with\n// a non-permanent error the rest of the time.\nfunc randomErrorsConsumeDecision() error {\n\tr := rand.Float64()\n\tthird := 1.0 / 3.0\n\tif r < third {\n\t\treturn consumererror.NewPermanent(errPermanent)\n\t}\n\tif r < 2*third {\n\t\treturn errNonPermanent\n\t}\n\treturn nil\n}\n\ntype mockConsumer struct {\n\tconsumer.Traces\n\tconsumer.Logs\n\tconsumer.Metrics\n\treqCounter          *requestCounter\n\tmux                 sync.Mutex\n\texportErrorFunction func() error\n\treceivedTraces      []ptrace.Traces\n\treceivedMetrics     []pmetric.Metrics\n\treceivedLogs        []plog.Logs\n}\n\nfunc newMockConsumer(decisionFunc func() error) mockConsumer {\n\treturn mockConsumer{\n\t\treqCounter:          newRequestCounter(),\n\t\tmux:                 sync.Mutex{},\n\t\texportErrorFunction: decisionFunc,\n\t\treceivedTraces:      nil,\n\t\treceivedMetrics:     nil,\n\t\treceivedLogs:        nil,\n\t}\n}\n\nfunc (r *mockConsumer) ConsumeLogs(_ context.Context, ld plog.Logs) error {\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\tr.reqCounter.total++\n\tgeneratedError := r.exportErrorFunction()\n\tif generatedError != nil {\n\t\tr.processError(generatedError)\n\t\treturn generatedError\n\t}\n\tr.reqCounter.success++\n\tr.receivedLogs = append(r.receivedLogs, ld)\n\treturn nil\n}\n\nfunc (r *mockConsumer) ConsumeTraces(_ context.Context, td ptrace.Traces) error {\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\tr.reqCounter.total++\n\tgeneratedError := r.exportErrorFunction()\n\tif generatedError != nil {\n\t\tr.processError(generatedError)\n\t\treturn generatedError\n\t}\n\tr.reqCounter.success++\n\tr.receivedTraces = append(r.receivedTraces, td)\n\treturn nil\n}\n\nfunc (r *mockConsumer) ConsumeMetrics(_ context.Context, md pmetric.Metrics) error {\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\tr.reqCounter.total++\n\tgeneratedError := r.exportErrorFunction()\n\tif generatedError != nil {\n\t\tr.processError(generatedError)\n\t\treturn generatedError\n\t}\n\tr.reqCounter.success++\n\tr.receivedMetrics = append(r.receivedMetrics, md)\n\treturn nil\n}\n\nfunc (r *mockConsumer) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{}\n}\n\nfunc (r *mockConsumer) processError(err error) {\n\tif consumererror.IsPermanent(err) {\n\t\tr.reqCounter.error.permanent++\n\t} else {\n\t\tr.reqCounter.error.nonpermanent++\n\t}\n}\n\nfunc (r *mockConsumer) clear() {\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\tr.reqCounter = newRequestCounter()\n}\n\nfunc (r *mockConsumer) getRequestCounter() *requestCounter {\n\treturn r.reqCounter\n}\n\ntype requestCounter struct {\n\tsuccess int\n\terror   errorCounter\n\ttotal   int\n}\n\ntype errorCounter struct {\n\tpermanent    int\n\tnonpermanent int\n}\n\nfunc newErrorCounter() errorCounter {\n\treturn errorCounter{\n\t\tpermanent:    0,\n\t\tnonpermanent: 0,\n\t}\n}\n\nfunc newRequestCounter() *requestCounter {\n\treturn &requestCounter{\n\t\tsuccess: 0,\n\t\terror:   newErrorCounter(),\n\t\ttotal:   0,\n\t}\n}\n\nfunc idFromLogs(data plog.Logs) (string, error) {\n\tvar logID string\n\trss := data.ResourceLogs()\n\tkey, exists := rss.At(0).ScopeLogs().At(0).LogRecords().At(0).Attributes().Get(uniqueIDAttrName)\n\tif !exists {\n\t\treturn \"\", fmt.Errorf(\"invalid data element, attribute %q is missing\", uniqueIDAttrName)\n\t}\n\tif key.Type() != pcommon.ValueTypeStr {\n\t\treturn \"\", fmt.Errorf(\"invalid data element, attribute %q is wrong type %v\", uniqueIDAttrName, key.Type())\n\t}\n\tlogID = key.Str()\n\treturn logID, nil\n}\n\nfunc idFromTraces(data ptrace.Traces) (string, error) {\n\tvar traceID string\n\trss := data.ResourceSpans()\n\tkey, exists := rss.At(0).ScopeSpans().At(0).Spans().At(0).Attributes().Get(uniqueIDAttrName)\n\tif !exists {\n\t\treturn \"\", fmt.Errorf(\"invalid data element, attribute %q is missing\", uniqueIDAttrName)\n\t}\n\tif key.Type() != pcommon.ValueTypeStr {\n\t\treturn \"\", fmt.Errorf(\"invalid data element, attribute %q is wrong type %v\", uniqueIDAttrName, key.Type())\n\t}\n\ttraceID = key.Str()\n\treturn traceID, nil\n}\n\nfunc idFromMetrics(data pmetric.Metrics) (string, error) {\n\tvar metricID string\n\trss := data.ResourceMetrics()\n\tkey, exists := rss.At(0).ScopeMetrics().At(0).Metrics().At(0).Histogram().DataPoints().At(0).Attributes().Get(\n\t\tuniqueIDAttrName)\n\tif !exists {\n\t\treturn \"\", fmt.Errorf(\"invalid data element, attribute %q is missing\", uniqueIDAttrName)\n\t}\n\tif key.Type() != pcommon.ValueTypeStr {\n\t\treturn \"\", fmt.Errorf(\"invalid data element, attribute %q is wrong type %v\", uniqueIDAttrName, key.Type())\n\t}\n\tmetricID = key.Str()\n\treturn metricID, nil\n}\n"
  },
  {
    "path": "exporter/exportertest/mock_consumer_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exportertest\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nfunc createLog(id string) plog.Logs {\n\tvalidData := plog.NewLogs()\n\tvalidData.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty().Attributes().PutStr(\n\t\tuniqueIDAttrName,\n\t\tid,\n\t)\n\treturn validData\n}\n\nfunc createTrace(id string) ptrace.Traces {\n\tvalidData := ptrace.NewTraces()\n\tvalidData.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty().Attributes().PutStr(\n\t\tuniqueIDAttrName,\n\t\tid,\n\t)\n\treturn validData\n}\n\nfunc createMetric(id string) pmetric.Metrics {\n\tvalidData := pmetric.NewMetrics()\n\tvalidData.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptyHistogram().DataPoints().AppendEmpty().Attributes().PutStr(uniqueIDAttrName, id)\n\treturn validData\n}\n\nfunc TestIDFromMetrics(t *testing.T) {\n\t// Test case 1: Valid data\n\tid := \"metric_id\"\n\tvalidData := createMetric(id)\n\tmetricID, err := idFromMetrics(validData)\n\tassert.Equal(t, metricID, id)\n\trequire.NoError(t, err)\n\n\t// Test case 2: Missing uniqueIDAttrName attribute\n\tinvalidData := pmetric.NewMetrics() // Create an invalid pmetric.Metrics object with missing attribute\n\tinvalidData.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptyHistogram().DataPoints().AppendEmpty().Attributes()\n\t_, err = idFromMetrics(invalidData)\n\trequire.EqualError(t, err, fmt.Sprintf(\"invalid data element, attribute %q is missing\", uniqueIDAttrName))\n\n\t// Test case 3: Wrong attribute type\n\tvar intID int64 = 12\n\twrongAttribute := pmetric.NewMetrics() // Create a valid pmetric.Metrics object\n\twrongAttribute.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().\n\t\tSetEmptyHistogram().DataPoints().AppendEmpty().Attributes().PutInt(uniqueIDAttrName, intID)\n\t_, err = idFromMetrics(wrongAttribute)\n\tassert.EqualError(t, err, fmt.Sprintf(\"invalid data element, attribute %q is wrong type Int\", uniqueIDAttrName))\n}\n\nfunc TestIDFromTraces(t *testing.T) {\n\t// Test case 1: Valid data\n\tid := \"trace_id\"\n\tvalidData := createTrace(id)\n\ttraceID, err := idFromTraces(validData)\n\tassert.Equal(t, traceID, id)\n\trequire.NoError(t, err)\n\n\t// Test case 2: Missing uniqueIDAttrName attribute\n\tinvalidData := ptrace.NewTraces()\n\tinvalidData.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty().Attributes()\n\t_, err = idFromTraces(invalidData)\n\trequire.EqualError(t, err, fmt.Sprintf(\"invalid data element, attribute %q is missing\", uniqueIDAttrName))\n\n\t// Test case 3: Wrong attribute type\n\tvar intID int64 = 12\n\twrongAttribute := ptrace.NewTraces()\n\twrongAttribute.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty().Attributes().\n\t\tPutInt(uniqueIDAttrName, intID)\n\t_, err = idFromTraces(wrongAttribute)\n\tassert.EqualError(t, err, fmt.Sprintf(\"invalid data element, attribute %q is wrong type Int\", uniqueIDAttrName))\n}\n\nfunc TestIDFromLogs(t *testing.T) {\n\t// Test case 1: Valid data\n\tid := \"log_id\"\n\tvalidData := createLog(id)\n\tlogID, err := idFromLogs(validData)\n\tassert.Equal(t, logID, id)\n\trequire.NoError(t, err)\n\n\t// Test case 2: Missing uniqueIDAttrName attribute\n\tinvalidData := plog.NewLogs()\n\tinvalidData.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty().Attributes()\n\t_, err = idFromLogs(invalidData)\n\trequire.EqualError(t, err, fmt.Sprintf(\"invalid data element, attribute %q is missing\", uniqueIDAttrName))\n\n\t// Test case 3: Wrong attribute type\n\tvar intID int64 = 12\n\twrongAttribute := plog.NewLogs() // Create a valid plog.Metrics object\n\twrongAttribute.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty().Attributes().\n\t\tPutInt(uniqueIDAttrName, intID)\n\t_, err = idFromLogs(wrongAttribute)\n\tassert.EqualError(t, err, fmt.Sprintf(\"invalid data element, attribute %q is wrong type Int\", uniqueIDAttrName))\n}\n\nfunc returnNonPermanentError() error {\n\treturn errNonPermanent\n}\n\nfunc returnPermanentError() error {\n\treturn errPermanent\n}\n\nfunc TestConsumeLogsNonPermanent(t *testing.T) {\n\tmc := newMockConsumer(returnNonPermanentError)\n\tvalidData := createLog(\"logId\")\n\terr := mc.ConsumeLogs(context.Background(), validData)\n\tif err != nil {\n\t\treturn\n\t}\n\tassert.Equal(t, 1, mc.reqCounter.error.nonpermanent)\n\tassert.Equal(t, 0, mc.reqCounter.error.permanent)\n\tassert.Equal(t, 0, mc.reqCounter.success)\n\tassert.Equal(t, 1, mc.reqCounter.total)\n}\n\nfunc TestConsumeLogsPermanent(t *testing.T) {\n\tmc := newMockConsumer(returnPermanentError)\n\tvalidData := createLog(\"logId\")\n\terr := mc.ConsumeLogs(context.Background(), validData)\n\tif err != nil {\n\t\treturn\n\t}\n\tassert.Equal(t, 0, mc.reqCounter.error.nonpermanent)\n\tassert.Equal(t, 1, mc.reqCounter.error.permanent)\n\tassert.Equal(t, 0, mc.reqCounter.success)\n\tassert.Equal(t, 1, mc.reqCounter.total)\n}\n\nfunc TestConsumeLogsSuccess(t *testing.T) {\n\tmc := newMockConsumer(func() error { return nil })\n\tvalidData := createLog(\"logId\")\n\terr := mc.ConsumeLogs(context.Background(), validData)\n\tif err != nil {\n\t\treturn\n\t}\n\tassert.Equal(t, 0, mc.reqCounter.error.nonpermanent)\n\tassert.Equal(t, 0, mc.reqCounter.error.permanent)\n\tassert.Equal(t, 1, mc.reqCounter.success)\n\tassert.Equal(t, 1, mc.reqCounter.total)\n}\n\nfunc TestConsumeTracesNonPermanent(t *testing.T) {\n\tmc := newMockConsumer(returnNonPermanentError)\n\tvalidData := createTrace(\"traceId\")\n\terr := mc.ConsumeTraces(context.Background(), validData)\n\tif err != nil {\n\t\treturn\n\t}\n\tassert.Equal(t, 1, mc.reqCounter.error.nonpermanent)\n\tassert.Equal(t, 0, mc.reqCounter.error.permanent)\n\tassert.Equal(t, 0, mc.reqCounter.success)\n\tassert.Equal(t, 1, mc.reqCounter.total)\n}\n\nfunc TestConsumeTracesPermanent(t *testing.T) {\n\tmc := newMockConsumer(returnPermanentError)\n\tvalidData := createTrace(\"traceId\")\n\terr := mc.ConsumeTraces(context.Background(), validData)\n\tif err != nil {\n\t\treturn\n\t}\n\tassert.Equal(t, 0, mc.reqCounter.error.nonpermanent)\n\tassert.Equal(t, 1, mc.reqCounter.error.permanent)\n\tassert.Equal(t, 0, mc.reqCounter.success)\n\tassert.Equal(t, 1, mc.reqCounter.total)\n}\n\nfunc TestConsumeTracesSuccess(t *testing.T) {\n\tmc := newMockConsumer(func() error { return nil })\n\tvalidData := createTrace(\"traceId\")\n\terr := mc.ConsumeTraces(context.Background(), validData)\n\tif err != nil {\n\t\treturn\n\t}\n\tassert.Equal(t, 0, mc.reqCounter.error.nonpermanent)\n\tassert.Equal(t, 0, mc.reqCounter.error.permanent)\n\tassert.Equal(t, 1, mc.reqCounter.success)\n\tassert.Equal(t, 1, mc.reqCounter.total)\n}\n\nfunc TestConsumeMetricsNonPermanent(t *testing.T) {\n\tmc := newMockConsumer(returnNonPermanentError)\n\tvalidData := createMetric(\"metricId\")\n\terr := mc.ConsumeMetrics(context.Background(), validData)\n\tif err != nil {\n\t\treturn\n\t}\n\tassert.Equal(t, 1, mc.reqCounter.error.nonpermanent)\n\tassert.Equal(t, 0, mc.reqCounter.error.permanent)\n\tassert.Equal(t, 0, mc.reqCounter.success)\n\tassert.Equal(t, 1, mc.reqCounter.total)\n}\n\nfunc TestConsumeMetricsPermanent(t *testing.T) {\n\tmc := newMockConsumer(returnPermanentError)\n\tvalidData := createMetric(\"metricId\")\n\terr := mc.ConsumeMetrics(context.Background(), validData)\n\tif err != nil {\n\t\treturn\n\t}\n\tassert.Equal(t, 0, mc.reqCounter.error.nonpermanent)\n\tassert.Equal(t, 1, mc.reqCounter.error.permanent)\n\tassert.Equal(t, 0, mc.reqCounter.success)\n\tassert.Equal(t, 1, mc.reqCounter.total)\n}\n\nfunc TestConsumeMetricsSuccess(t *testing.T) {\n\tmc := newMockConsumer(func() error { return nil })\n\tvalidData := createMetric(\"metricId\")\n\terr := mc.ConsumeMetrics(context.Background(), validData)\n\tif err != nil {\n\t\treturn\n\t}\n\tassert.Equal(t, 0, mc.reqCounter.error.nonpermanent)\n\tassert.Equal(t, 0, mc.reqCounter.error.permanent)\n\tassert.Equal(t, 1, mc.reqCounter.success)\n\tassert.Equal(t, 1, mc.reqCounter.total)\n}\n\nfunc TestCapabilities(t *testing.T) {\n\tmc := newMockConsumer(func() error { return nil })\n\tassert.Equal(t, consumer.Capabilities{}, mc.Capabilities())\n}\n"
  },
  {
    "path": "exporter/exportertest/nop_exporter.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exportertest // import \"go.opentelemetry.io/collector/exporter/exportertest\"\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/uuid\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n)\n\nvar NopType = component.MustNewType(\"nop\")\n\n// NewNopSettings returns a new nop settings for Create* functions with the given type.\nfunc NewNopSettings(typ component.Type) exporter.Settings {\n\treturn exporter.Settings{\n\t\tID:                component.NewIDWithName(typ, uuid.NewString()),\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t\tBuildInfo:         component.NewDefaultBuildInfo(),\n\t}\n}\n\n// NewNopFactory returns an exporter.Factory that constructs nop exporters.\nfunc NewNopFactory() exporter.Factory {\n\treturn xexporter.NewFactory(\n\t\tNopType,\n\t\tfunc() component.Config { return &nopConfig{} },\n\t\txexporter.WithTraces(createTraces, component.StabilityLevelStable),\n\t\txexporter.WithMetrics(createMetrics, component.StabilityLevelStable),\n\t\txexporter.WithLogs(createLogs, component.StabilityLevelStable),\n\t\txexporter.WithProfiles(createProfiles, component.StabilityLevelAlpha),\n\t)\n}\n\nfunc createTraces(context.Context, exporter.Settings, component.Config) (exporter.Traces, error) {\n\treturn nopInstance, nil\n}\n\nfunc createMetrics(context.Context, exporter.Settings, component.Config) (exporter.Metrics, error) {\n\treturn nopInstance, nil\n}\n\nfunc createLogs(context.Context, exporter.Settings, component.Config) (exporter.Logs, error) {\n\treturn nopInstance, nil\n}\n\nfunc createProfiles(context.Context, exporter.Settings, component.Config) (xexporter.Profiles, error) {\n\treturn nopInstance, nil\n}\n\ntype nopConfig struct{}\n\nvar nopInstance = &nop{\n\tConsumer: consumertest.NewNop(),\n}\n\n// nop stores consumed traces, metrics, logs and profiles for testing purposes.\ntype nop struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumertest.Consumer\n}\n"
  },
  {
    "path": "exporter/exportertest/nop_exporter_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exportertest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nfunc TestNewNopFactory(t *testing.T) {\n\tfactory := NewNopFactory()\n\trequire.NotNil(t, factory)\n\tassert.Equal(t, component.MustNewType(\"nop\"), factory.Type())\n\tcfg := factory.CreateDefaultConfig()\n\tassert.Equal(t, &nopConfig{}, cfg)\n\n\ttraces, err := factory.CreateTraces(context.Background(), NewNopSettings(NopType), cfg)\n\trequire.NoError(t, err)\n\tassert.NoError(t, traces.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, traces.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n\tassert.NoError(t, traces.Shutdown(context.Background()))\n\n\tmetrics, err := factory.CreateMetrics(context.Background(), NewNopSettings(NopType), cfg)\n\trequire.NoError(t, err)\n\tassert.NoError(t, metrics.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, metrics.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n\tassert.NoError(t, metrics.Shutdown(context.Background()))\n\n\tlogs, err := factory.CreateLogs(context.Background(), NewNopSettings(NopType), cfg)\n\trequire.NoError(t, err)\n\tassert.NoError(t, logs.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, logs.ConsumeLogs(context.Background(), plog.NewLogs()))\n\tassert.NoError(t, logs.Shutdown(context.Background()))\n\n\tprofiles, err := factory.(xexporter.Factory).CreateProfiles(context.Background(), NewNopSettings(NopType), cfg)\n\trequire.NoError(t, err)\n\tassert.NoError(t, profiles.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, profiles.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n\tassert.NoError(t, profiles.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "exporter/go.mod",
    "content": "module go.opentelemetry.io/collector/exporter\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/config/configoptional v1.54.0\n\tgo.opentelemetry.io/collector/config/configretry v1.54.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/exporter/exporterhelper v0.148.0\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/zap v1.27.1\n)\n\nrequire (\n\tgithub.com/cenkalti/backoff/v5 v5.0.3 // indirect\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/hashicorp/golang-lru/v2 v2.0.7 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/client v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/confmap v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/xextension v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/xpdata v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../component/componenttest\n\nreplace go.opentelemetry.io/collector/consumer => ../consumer\n\nreplace go.opentelemetry.io/collector/extension => ../extension\n\nreplace go.opentelemetry.io/collector/pdata => ../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/pipeline => ../pipeline\n\nreplace go.opentelemetry.io/collector/receiver => ../receiver\n\nretract v0.76.0 // Depends on retracted pdata v1.0.0-rc10 module\n\nreplace go.opentelemetry.io/collector/config/configretry => ../config/configretry\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../receiver/receivertest\n\nreplace go.opentelemetry.io/collector/exporter/xexporter => ./xexporter\n\nreplace go.opentelemetry.io/collector/exporter/exportertest => ./exportertest\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../extension/extensiontest\n\nreplace go.opentelemetry.io/collector/extension/xextension => ../extension/xextension\n\nreplace go.opentelemetry.io/collector/featuregate => ../featuregate\n\nreplace go.opentelemetry.io/collector/client => ../client\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/confmap => ../confmap\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../config/configoptional\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper => ./exporterhelper\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../internal/componentalias\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../pipeline/xpipeline\n"
  },
  {
    "path": "exporter/go.sum",
    "content": "github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=\ngithub.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "exporter/internal/experr/err.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage experr // import \"go.opentelemetry.io/collector/exporter/internal/experr\"\n\nimport (\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc ErrIDMismatch(id component.ID, typ component.Type) error {\n\treturn fmt.Errorf(\"component type mismatch: component ID %q does not have type %q\", id, typ)\n}\n"
  },
  {
    "path": "exporter/metadata.yaml",
    "content": "type: exporter\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "exporter/nopexporter/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "exporter/nopexporter/README.md",
    "content": "<!-- status autogenerated section -->\n# No-op Exporter\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [alpha]: profiles   |\n|               | [beta]: traces, metrics, logs   |\n| Distributions | [core], [contrib], [k8s] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Aexporter%2Fnop%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Aexporter%2Fnop) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Aexporter%2Fnop%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Aexporter%2Fnop) |\n| [Code Owners](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/CONTRIBUTING.md#becoming-a-code-owner)    | [@evan-bradley](https://www.github.com/evan-bradley) |\n\n[alpha]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#alpha\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[core]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n[k8s]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\n<!-- end autogenerated section -->\n\nServes as a placeholder exporter in a pipeline. This can be useful if you want\nto e.g. start a Collector with only extensions enabled, or for testing Collector\npipeline throughput without worrying about an exporter.\n\n## Getting Started\n\nAll that is required to enable the No-op exporter is to include it in the\nexporter definitions. It takes no configuration.\n\n```yaml\nexporters:\n  nop: {} # Explicitly set in case the config is re-serialized (e.g. with the Operator)\n```\n"
  },
  {
    "path": "exporter/nopexporter/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\n// Package nopexporter serves as a placeholder exporter.\npackage nopexporter // import \"go.opentelemetry.io/collector/exporter/nopexporter\"\n"
  },
  {
    "path": "exporter/nopexporter/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage nopexporter\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nvar typ = component.MustNewType(\"nop\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct {\n\t\tcreateFn func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error)\n\t\tname     string\n\t}{\n\n\t\t{\n\t\t\tname: \"logs\",\n\t\t\tcreateFn: func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateLogs(ctx, set, cfg)\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg)\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"traces\",\n\t\t\tcreateFn: func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateTraces(ctx, set, cfg)\n\t\t\t},\n\t\t},\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name+\"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), exportertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\tt.Run(tt.name+\"-lifecycle\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), exportertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := newMdatagenNopHost()\n\t\t\terr = c.Start(context.Background(), host)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NotPanics(t, func() {\n\t\t\t\tswitch tt.name {\n\t\t\t\tcase \"logs\":\n\t\t\t\t\te, ok := c.(exporter.Logs)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tlogs := generateLifecycleTestLogs()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tlogs.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeLogs(context.Background(), logs)\n\t\t\t\tcase \"metrics\":\n\t\t\t\t\te, ok := c.(exporter.Metrics)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tmetrics := generateLifecycleTestMetrics()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tmetrics.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeMetrics(context.Background(), metrics)\n\t\t\t\tcase \"traces\":\n\t\t\t\t\te, ok := c.(exporter.Traces)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\ttraces := generateLifecycleTestTraces()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\ttraces.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeTraces(context.Background(), traces)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\trequire.NoError(t, err)\n\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t}\n}\n\nfunc generateLifecycleTestLogs() plog.Logs {\n\tlogs := plog.NewLogs()\n\trl := logs.ResourceLogs().AppendEmpty()\n\trl.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tl := rl.ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\tl.Body().SetStr(\"test log message\")\n\tl.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn logs\n}\n\nfunc generateLifecycleTestMetrics() pmetric.Metrics {\n\tmetrics := pmetric.NewMetrics()\n\trm := metrics.ResourceMetrics().AppendEmpty()\n\trm.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tm := rm.ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\tm.SetName(\"test_metric\")\n\tdp := m.SetEmptyGauge().DataPoints().AppendEmpty()\n\tdp.Attributes().PutStr(\"test_attr\", \"value_1\")\n\tdp.SetIntValue(123)\n\tdp.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn metrics\n}\n\nfunc generateLifecycleTestTraces() ptrace.Traces {\n\ttraces := ptrace.NewTraces()\n\trs := traces.ResourceSpans().AppendEmpty()\n\trs.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tspan := rs.ScopeSpans().AppendEmpty().Spans().AppendEmpty()\n\tspan.Attributes().PutStr(\"test_attr\", \"value_1\")\n\tspan.SetName(\"test_span\")\n\tspan.SetStartTimestamp(pcommon.NewTimestampFromTime(time.Now().Add(-1 * time.Second)))\n\tspan.SetEndTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn traces\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "exporter/nopexporter/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage nopexporter\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "exporter/nopexporter/go.mod",
    "content": "module go.opentelemetry.io/collector/exporter/nopexporter\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/exporter v1.54.0\n\tgo.opentelemetry.io/collector/exporter/exportertest v0.148.0\n\tgo.opentelemetry.io/collector/exporter/xexporter v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/consumer v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/receiver v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/receivertest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/exporter => ../\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/config/configretry => ../../config/configretry\n\nreplace go.opentelemetry.io/collector/receiver => ../../receiver\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/extension => ../../extension\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../../receiver/receivertest\n\nreplace go.opentelemetry.io/collector/exporter/xexporter => ../xexporter\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/exporter/exportertest => ../exportertest\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../../extension/extensiontest\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/extension/xextension => ../../extension/xextension\n\nreplace go.opentelemetry.io/collector/client => ../../client\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../../config/configoptional\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper => ../exporterhelper\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n"
  },
  {
    "path": "exporter/nopexporter/go.sum",
    "content": "github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=\ngithub.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "exporter/nopexporter/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"nop\")\n\tScopeName = \"go.opentelemetry.io/collector/exporter/nopexporter\"\n)\n\nconst (\n\tProfilesStability = component.StabilityLevelAlpha\n\tTracesStability   = component.StabilityLevelBeta\n\tMetricsStability  = component.StabilityLevelBeta\n\tLogsStability     = component.StabilityLevelBeta\n)\n"
  },
  {
    "path": "exporter/nopexporter/metadata.yaml",
    "content": "display_name: No-op Exporter\ntype: nop\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  codeowners:\n    active:\n      - evan-bradley\n  class: exporter\n  stability:\n    beta: [traces, metrics, logs]\n    alpha: [profiles]\n  distributions: [core, contrib, k8s]\n"
  },
  {
    "path": "exporter/nopexporter/nop_exporter.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage nopexporter // import \"go.opentelemetry.io/collector/exporter/nopexporter\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/nopexporter/internal/metadata\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n)\n\n// NewFactory returns an exporter.Factory that constructs nop exporters.\nfunc NewFactory() exporter.Factory {\n\treturn xexporter.NewFactory(\n\t\tmetadata.Type,\n\t\tfunc() component.Config { return &struct{}{} },\n\t\txexporter.WithTraces(createTraces, metadata.TracesStability),\n\t\txexporter.WithMetrics(createMetrics, metadata.MetricsStability),\n\t\txexporter.WithLogs(createLogs, metadata.LogsStability),\n\t\txexporter.WithProfiles(createProfiles, metadata.ProfilesStability),\n\t)\n}\n\nfunc createTraces(context.Context, exporter.Settings, component.Config) (exporter.Traces, error) {\n\treturn nopInstance, nil\n}\n\nfunc createMetrics(context.Context, exporter.Settings, component.Config) (exporter.Metrics, error) {\n\treturn nopInstance, nil\n}\n\nfunc createLogs(context.Context, exporter.Settings, component.Config) (exporter.Logs, error) {\n\treturn nopInstance, nil\n}\n\nfunc createProfiles(context.Context, exporter.Settings, component.Config) (xexporter.Profiles, error) {\n\treturn nopInstance, nil\n}\n\nvar nopInstance = &nop{\n\tConsumer: consumertest.NewNop(),\n}\n\ntype nop struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumertest.Consumer\n}\n"
  },
  {
    "path": "exporter/nopexporter/nop_exporter_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage nopexporter\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nfunc TestNewNopFactory(t *testing.T) {\n\tfactory := NewFactory()\n\trequire.NotNil(t, factory)\n\tassert.Equal(t, component.MustNewType(\"nop\"), factory.Type())\n\tcfg := factory.CreateDefaultConfig()\n\tassert.Equal(t, &struct{}{}, cfg)\n\n\ttraces, err := factory.CreateTraces(context.Background(), exportertest.NewNopSettings(factory.Type()), cfg)\n\trequire.NoError(t, err)\n\tassert.NoError(t, traces.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, traces.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n\tassert.NoError(t, traces.Shutdown(context.Background()))\n\n\tmetrics, err := factory.CreateMetrics(context.Background(), exportertest.NewNopSettings(factory.Type()), cfg)\n\trequire.NoError(t, err)\n\tassert.NoError(t, metrics.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, metrics.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n\tassert.NoError(t, metrics.Shutdown(context.Background()))\n\n\tlogs, err := factory.CreateLogs(context.Background(), exportertest.NewNopSettings(factory.Type()), cfg)\n\trequire.NoError(t, err)\n\tassert.NoError(t, logs.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, logs.ConsumeLogs(context.Background(), plog.NewLogs()))\n\tassert.NoError(t, logs.Shutdown(context.Background()))\n\n\tprofiles, err := factory.(xexporter.Factory).CreateProfiles(context.Background(), exportertest.NewNopSettings(factory.Type()), cfg)\n\trequire.NoError(t, err)\n\tassert.NoError(t, profiles.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, profiles.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n\tassert.NoError(t, profiles.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "exporter/otlpexporter/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "exporter/otlpexporter/README.md",
    "content": "<!-- status autogenerated section -->\n# OTLP gRPC Exporter\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [alpha]: profiles   |\n|               | [stable]: traces, metrics, logs   |\n| Distributions | [core], [contrib], [k8s], [otlp] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Aexporter%2Fotlp%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Aexporter%2Fotlp) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Aexporter%2Fotlp%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Aexporter%2Fotlp) |\n\n[alpha]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#alpha\n[stable]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stable\n[core]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n[k8s]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\n[otlp]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-otlp\n<!-- end autogenerated section -->\n\nExport data via gRPC using [OTLP](\nhttps://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md)\nformat. By default, this exporter requires TLS and offers queued retry capabilities.\n\n## Getting Started\n\nThe following settings are required:\n\n- `endpoint` (no default): host:port to which the exporter is going to send OTLP trace data,\nusing the gRPC protocol. The valid syntax is described\n[here](https://github.com/grpc/grpc/blob/master/doc/naming.md).\nIf a scheme of `https` is used then client transport security is enabled and overrides the `insecure` setting.\n- `tls`: see [TLS Configuration Settings](../../config/configtls/README.md) for the full set of available options.\n- `retry_on_failure`:  see [Retry on Failure](../exporterhelper/README.md#retry-on-failure) for the full set of available options.\n- `sending_queue`: see [Sending Queue](../exporterhelper/README.md#sending-queue) for the full set of available options.\n- `timeout` (default = 5s): Time to wait per individual attempt to send data to a backend.\n\nExample:\n\n```yaml\nexporters:\n  otlp_grpc:\n    endpoint: otelcol2:4317\n    tls:\n      cert_file: file.cert\n      key_file: file.key\n  otlp/2:\n    endpoint: otelcol2:4317\n    tls:\n      insecure: true\n```\n\nBy default, `gzip` compression is enabled. See [compression comparison](../../config/configgrpc/README.md#compression-comparison) for details benchmark information. To disable, configure as follows:\n\n```yaml\nexporters:\n  otlp_grpc:\n    ...\n    compression: none\n```\n\n## Advanced Configuration\n\nSeveral helper files are leveraged to provide additional capabilities automatically:\n\n- [gRPC settings](https://github.com/open-telemetry/opentelemetry-collector/blob/main/config/configgrpc/README.md)\n- [TLS and mTLS settings](https://github.com/open-telemetry/opentelemetry-collector/blob/main/config/configtls/README.md)\n- [Queuing, batching, retry and timeout settings](https://github.com/open-telemetry/opentelemetry-collector/blob/main/exporter/exporterhelper/README.md)\n"
  },
  {
    "path": "exporter/otlpexporter/cfg-schema.yaml",
    "content": "type: '*otlpexporter.Config'\nfields:\n- name: timeout\n  type: time.Duration\n  kind: int64\n  default: 5s\n  doc: |\n    Timeout is the timeout for every attempt to send data to the backend.\n- name: sending_queue\n  type: exporterhelper.QueueConfig\n  kind: struct\n  fields:\n  - name: enabled\n    kind: bool\n    default: true\n    doc: |\n      Enabled indicates whether to not enqueue batches before sending to the consumerSender.\n  - name: num_consumers\n    kind: int\n    default: 10\n    doc: |\n      NumConsumers is the number of consumers from the queue.\n  - name: queue_size\n    kind: int\n    default: 1000\n    doc: |\n      QueueSize is the maximum number of batches allowed in queue at a given time.\n- name: retry_on_failure\n  type: exporterhelper.RetrySettings\n  kind: struct\n  fields:\n  - name: enabled\n    kind: bool\n    default: true\n    doc: |\n      Enabled indicates whether to not retry sending batches in case of export failure.\n  - name: initial_interval\n    type: time.Duration\n    kind: int64\n    default: 5s\n    doc: |\n      InitialInterval the time to wait after the first failure before retrying.\n  - name: randomization_factor\n    kind: float64\n    default: 0.5\n    doc: |\n      RandomizationFactor is a random factor used to calculate next backoffs.\n      Randomized interval = RetryInterval * (1 ± RandomizationFactor)\n  - name: multiplier\n    kind: float64\n    default: 1.5\n    doc: |\n      Multiplier is the value multiplied by the backoff interval bounds\n  - name: max_interval\n    type: time.Duration\n    kind: int64\n    default: 30s\n    doc: |\n      MaxInterval is the upper bound on backoff interval. Once this value is reached the delay between\n      consecutive retries will always be `MaxInterval`.\n  - name: max_elapsed_time\n    type: time.Duration\n    kind: int64\n    default: 5m0s\n    doc: |\n      MaxElapsedTime is the maximum amount of time (including retries) spent trying to send a request/batch.\n      Once this value is reached, the data is discarded.\n- name: endpoint\n  kind: string\n  doc: |\n    The target to which the exporter is going to send traces, metrics, logs or\n    profiles using the gRPC protocol. The valid syntax is described at\n    https://github.com/grpc/grpc/blob/master/doc/naming.md.\n- name: compression\n  kind: string\n  doc: |\n    The compression key for supported compression types within\n    collector. Supports `gzip`, `snappy` and `zstd`.\n- name: ca_file\n  kind: string\n  doc: |\n    Path to the CA cert. For a client this verifies the server certificate.\n    For a server this verifies client certificates. If empty uses system root CA.\n    (optional)\n- name: cert_file\n  kind: string\n  doc: |\n    Path to the TLS cert to use for TLS required connections. (optional)\n- name: key_file\n  kind: string\n  doc: |\n    Path to the TLS key to use for TLS required connections. (optional)\n- name: insecure\n  kind: bool\n  doc: |\n    In gRPC when set to true, this is used to disable the client transport security.\n    See https://godoc.org/google.golang.org/grpc#WithInsecure.\n    In HTTP, this disables verifying the server's certificate chain and host name\n    (InsecureSkipVerify in the tls Config). Please refer to\n    https://godoc.org/crypto/tls#Config for more information.\n    (optional, default false)\n- name: server_name_override\n  kind: string\n  doc: |\n    ServerName requested by client for virtual hosting.\n    This sets the ServerName in the TLSConfig. Please refer to\n    https://godoc.org/crypto/tls#Config for more information. (optional)\n- name: keepalive\n  type: '*configgrpc.KeepaliveClientConfig'\n  kind: ptr\n  doc: |\n    The keepalive parameters for gRPC client. See grpc.WithKeepaliveParams\n    (https://godoc.org/google.golang.org/grpc#WithKeepaliveParams).\n  fields:\n  - name: time\n    type: time.Duration\n    kind: int64\n  - name: timeout\n    type: time.Duration\n    kind: int64\n  - name: permit_without_stream\n    kind: bool\n- name: read_buffer_size\n  kind: int\n  doc: |\n    ReadBufferSize for gRPC client. See grpc.WithReadBufferSize\n    (https://godoc.org/google.golang.org/grpc#WithReadBufferSize).\n- name: write_buffer_size\n  kind: int\n  default: 524288\n  doc: |\n    WriteBufferSize for gRPC gRPC. See grpc.WithWriteBufferSize\n    (https://godoc.org/google.golang.org/grpc#WithWriteBufferSize).\n- name: wait_for_ready\n  kind: bool\n  doc: |\n    WaitForReady parameter configures client to wait for ready state before sending data.\n    (https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md)\n- name: headers\n  type: map[string]string\n  kind: map\n  doc: |\n    The headers associated with gRPC requests.\n- name: per_rpc_auth\n  type: '*configgrpc.PerRPCAuthConfig'\n  kind: ptr\n  doc: |\n    PerRPCAuth parameter configures the client to send authentication data on a per-RPC basis.\n  fields:\n  - name: type\n    kind: string\n    doc: |\n      AuthType represents the authentication type to use. Currently, only 'bearer' is supported.\n  - name: bearer_token\n    kind: string\n    doc: |\n      BearerToken specifies the bearer token to use for every RPC.\n- name: balancer_name\n  kind: string\n  doc: |\n    Sets the balancer in grpclb_policy to discover the servers. Default is pick_first\n    https://github.com/grpc/grpc-go/blob/master/examples/features/load_balancing/README.md\n"
  },
  {
    "path": "exporter/otlpexporter/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlpexporter // import \"go.opentelemetry.io/collector/exporter/otlpexporter\"\n\nimport (\n\t\"errors\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configgrpc\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configretry\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n)\n\n// Config defines configuration for OTLP exporter.\ntype Config struct {\n\tTimeoutConfig exporterhelper.TimeoutConfig                             `mapstructure:\",squash\"` // squash ensures fields are correctly decoded in embedded struct.\n\tQueueConfig   configoptional.Optional[exporterhelper.QueueBatchConfig] `mapstructure:\"sending_queue\"`\n\tRetryConfig   configretry.BackOffConfig                                `mapstructure:\"retry_on_failure\"`\n\tClientConfig  configgrpc.ClientConfig                                  `mapstructure:\",squash\"` // squash ensures fields are correctly decoded in embedded struct.\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\nvar (\n\t_ component.Config   = (*Config)(nil)\n\t_ xconfmap.Validator = (*Config)(nil)\n)\n\nfunc (c *Config) Validate() error {\n\tif endpoint := c.sanitizedEndpoint(); endpoint == \"\" {\n\t\treturn errors.New(`requires a non-empty \"endpoint\"`)\n\t}\n\treturn nil\n}\n\nfunc (c *Config) sanitizedEndpoint() string {\n\tswitch {\n\tcase strings.HasPrefix(c.ClientConfig.Endpoint, \"http://\"):\n\t\treturn strings.TrimPrefix(c.ClientConfig.Endpoint, \"http://\")\n\tcase strings.HasPrefix(c.ClientConfig.Endpoint, \"https://\"):\n\t\treturn strings.TrimPrefix(c.ClientConfig.Endpoint, \"https://\")\n\tcase strings.HasPrefix(c.ClientConfig.Endpoint, \"dns://\"):\n\t\tr := regexp.MustCompile(`^dns:///?`)\n\t\treturn r.ReplaceAllString(c.ClientConfig.Endpoint, \"\")\n\tdefault:\n\t\treturn c.ClientConfig.Endpoint\n\t}\n}\n"
  },
  {
    "path": "exporter/otlpexporter/config.yaml",
    "content": "description: Config defines configuration for OTLP exporter.\ntype: object\nproperties:\n  retry_on_failure:\n    $ref: go.opentelemetry.io/collector/config/configretry.back_off_config\n  sending_queue:\n    x-optional: true\n    $ref: go.opentelemetry.io/collector/exporter/exporterhelper.queue_batch_config\nallOf:\n  - $ref: go.opentelemetry.io/collector/exporter/exporterhelper.timeout_config\n  - $ref: go.opentelemetry.io/collector/config/configgrpc.client_config\n"
  },
  {
    "path": "exporter/otlpexporter/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlpexporter\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configauth\"\n\t\"go.opentelemetry.io/collector/config/configgrpc\"\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configretry\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n)\n\nfunc TestUnmarshalDefaultConfig(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, confmap.New().Unmarshal(&cfg))\n\tassert.Equal(t, factory.CreateDefaultConfig(), cfg)\n}\n\nfunc TestUnmarshalConfig(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\trequire.NoError(t, xconfmap.Validate(&cfg))\n\tassert.Equal(t,\n\t\t&Config{\n\t\t\tTimeoutConfig: exporterhelper.TimeoutConfig{\n\t\t\t\tTimeout: 10 * time.Second,\n\t\t\t},\n\t\t\tRetryConfig: configretry.BackOffConfig{\n\t\t\t\tEnabled:             true,\n\t\t\t\tInitialInterval:     10 * time.Second,\n\t\t\t\tRandomizationFactor: 0.7,\n\t\t\t\tMultiplier:          1.3,\n\t\t\t\tMaxInterval:         1 * time.Minute,\n\t\t\t\tMaxElapsedTime:      10 * time.Minute,\n\t\t\t},\n\t\t\tQueueConfig: configoptional.Some(exporterhelper.QueueBatchConfig{\n\t\t\t\tSizer:        exporterhelper.RequestSizerTypeItems,\n\t\t\t\tNumConsumers: 2,\n\t\t\t\tQueueSize:    100000,\n\t\t\t\tBatch: configoptional.Some(exporterhelper.BatchConfig{\n\t\t\t\t\tFlushTimeout: 200 * time.Millisecond,\n\t\t\t\t\tSizer:        exporterhelper.RequestSizerTypeItems,\n\t\t\t\t\tMinSize:      1000,\n\t\t\t\t\tMaxSize:      10000,\n\t\t\t\t}),\n\t\t\t}),\n\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\tHeaders: configopaque.MapList{\n\t\t\t\t\t{Name: \"another\", Value: \"somevalue\"},\n\t\t\t\t\t{Name: \"can you have a . here?\", Value: \"F0000000-0000-0000-0000-000000000000\"},\n\t\t\t\t\t{Name: \"header1\", Value: \"234\"},\n\t\t\t\t},\n\t\t\t\tEndpoint:    \"1.2.3.4:1234\",\n\t\t\t\tCompression: \"gzip\",\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\tCAFile: \"/var/lib/mycert.pem\",\n\t\t\t\t\t},\n\t\t\t\t\tInsecure: false,\n\t\t\t\t},\n\t\t\t\tKeepalive: configoptional.Some(configgrpc.KeepaliveClientConfig{\n\t\t\t\t\tTime:                20 * time.Second,\n\t\t\t\t\tPermitWithoutStream: true,\n\t\t\t\t\tTimeout:             30 * time.Second,\n\t\t\t\t}),\n\t\t\t\tWriteBufferSize: 512 * 1024,\n\t\t\t\tBalancerName:    \"round_robin\",\n\t\t\t\tAuth:            configoptional.Some(configauth.Config{AuthenticatorID: component.MustNewID(\"nop\")}),\n\t\t\t},\n\t\t}, cfg)\n}\n\nfunc TestUnmarshalDefaultBatchConfig(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"default-batch.yaml\"))\n\trequire.NoError(t, err)\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\trequire.NoError(t, xconfmap.Validate(&cfg))\n\tassert.Equal(t,\n\t\t&Config{\n\t\t\tTimeoutConfig: exporterhelper.TimeoutConfig{\n\t\t\t\tTimeout: 10 * time.Second,\n\t\t\t},\n\t\t\tRetryConfig: configretry.NewDefaultBackOffConfig(),\n\t\t\tQueueConfig: configoptional.Some(exporterhelper.QueueBatchConfig{\n\t\t\t\tSizer:        exporterhelper.RequestSizerTypeRequests,\n\t\t\t\tQueueSize:    1000,\n\t\t\t\tNumConsumers: 10,\n\t\t\t\tBatch: configoptional.Some(exporterhelper.BatchConfig{\n\t\t\t\t\tFlushTimeout: 200 * time.Millisecond,\n\t\t\t\t\tSizer:        exporterhelper.RequestSizerTypeItems,\n\t\t\t\t\tMinSize:      8192,\n\t\t\t\t}),\n\t\t\t}),\n\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\tEndpoint:        \"1.2.3.4:1234\",\n\t\t\t\tBalancerName:    \"round_robin\",\n\t\t\t\tCompression:     \"gzip\",\n\t\t\t\tWriteBufferSize: 512 * 1024,\n\t\t\t},\n\t\t}, cfg)\n}\n\nfunc TestUnmarshalInvalidConfig(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"invalid_configs.yaml\"))\n\trequire.NoError(t, err)\n\tfactory := NewFactory()\n\tfor _, tt := range []struct {\n\t\tname     string\n\t\terrorMsg string\n\t}{\n\t\t{\n\t\t\tname:     \"no_endpoint\",\n\t\t\terrorMsg: `requires a non-empty \"endpoint\"`,\n\t\t},\n\t\t{\n\t\t\tname:     \"https_endpoint\",\n\t\t\terrorMsg: `requires a non-empty \"endpoint\"`,\n\t\t},\n\t\t{\n\t\t\tname:     \"http_endpoint\",\n\t\t\terrorMsg: `requires a non-empty \"endpoint\"`,\n\t\t},\n\t\t{\n\t\t\tname:     \"invalid_timeout\",\n\t\t\terrorMsg: `'timeout' must be non-negative`,\n\t\t},\n\t\t{\n\t\t\tname:     \"invalid_retry\",\n\t\t\terrorMsg: `'randomization_factor' must be within [0, 1]`,\n\t\t},\n\t\t{\n\t\t\tname:     \"invalid_tls\",\n\t\t\terrorMsg: `invalid TLS min_version: unsupported TLS version: \"asd\"`,\n\t\t},\n\t\t{\n\t\t\tname:     \"missing_port\",\n\t\t\terrorMsg: `missing port in address`,\n\t\t},\n\t\t{\n\t\t\tname:     \"invalid_port\",\n\t\t\terrorMsg: `invalid port \"port\"`,\n\t\t},\n\t\t{\n\t\t\tname:     \"invalid_unix_socket\",\n\t\t\terrorMsg: \"unix socket path cannot be empty\",\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := factory.CreateDefaultConfig()\n\t\t\tsub, err := cm.Sub(tt.name)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.NoError(t, sub.Unmarshal(&cfg))\n\t\t\tassert.ErrorContains(t, xconfmap.Validate(cfg), tt.errorMsg)\n\t\t})\n\t}\n}\n\nfunc TestValidDNSEndpoint(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.ClientConfig.Endpoint = \"dns://authority/backend.example.com:4317\"\n\tassert.NoError(t, xconfmap.Validate(cfg))\n}\n\nfunc TestValidUnixSocketEndpoint(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.ClientConfig.Endpoint = \"unix:///my/unix/socket.sock\"\n\tassert.NoError(t, xconfmap.Validate(cfg))\n}\n"
  },
  {
    "path": "exporter/otlpexporter/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\n// Package otlpexporter exports data by using the OTLP format to a gRPC endpoint.\npackage otlpexporter // import \"go.opentelemetry.io/collector/exporter/otlpexporter\"\n"
  },
  {
    "path": "exporter/otlpexporter/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlpexporter // import \"go.opentelemetry.io/collector/exporter/otlpexporter\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configcompression\"\n\t\"go.opentelemetry.io/collector/config/configgrpc\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configretry\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/otlpexporter/internal/metadata\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n)\n\n// NewFactory creates a factory for OTLP exporter.\nfunc NewFactory() exporter.Factory {\n\treturn xexporter.NewFactory(\n\t\tmetadata.Type,\n\t\tcreateDefaultConfig,\n\t\txexporter.WithDeprecatedTypeAlias(metadata.DeprecatedType),\n\t\txexporter.WithTraces(createTraces, metadata.TracesStability),\n\t\txexporter.WithMetrics(createMetrics, metadata.MetricsStability),\n\t\txexporter.WithLogs(createLogs, metadata.LogsStability),\n\t\txexporter.WithProfiles(createProfilesExporter, metadata.ProfilesStability),\n\t)\n}\n\nfunc createDefaultConfig() component.Config {\n\tclientCfg := configgrpc.NewDefaultClientConfig()\n\t// Default to gzip compression\n\tclientCfg.Compression = configcompression.TypeGzip\n\t// We almost read 0 bytes, so no need to tune ReadBufferSize.\n\tclientCfg.WriteBufferSize = 512 * 1024\n\t// For backward compatibility:\n\tclientCfg.Keepalive = configoptional.None[configgrpc.KeepaliveClientConfig]()\n\n\treturn &Config{\n\t\tTimeoutConfig: exporterhelper.NewDefaultTimeoutConfig(),\n\t\tRetryConfig:   configretry.NewDefaultBackOffConfig(),\n\t\tQueueConfig:   configoptional.Some(exporterhelper.NewDefaultQueueConfig()),\n\t\tClientConfig:  clientCfg,\n\t}\n}\n\nfunc createTraces(\n\tctx context.Context,\n\tset exporter.Settings,\n\tcfg component.Config,\n) (exporter.Traces, error) {\n\toce := newExporter(cfg, set)\n\toCfg := cfg.(*Config)\n\treturn exporterhelper.NewTraces(ctx, set, cfg,\n\t\toce.pushTraces,\n\t\texporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),\n\t\texporterhelper.WithTimeout(oCfg.TimeoutConfig),\n\t\texporterhelper.WithRetry(oCfg.RetryConfig),\n\t\texporterhelper.WithQueue(oCfg.QueueConfig),\n\t\texporterhelper.WithStart(oce.start),\n\t\texporterhelper.WithShutdown(oce.shutdown),\n\t)\n}\n\nfunc createMetrics(\n\tctx context.Context,\n\tset exporter.Settings,\n\tcfg component.Config,\n) (exporter.Metrics, error) {\n\toce := newExporter(cfg, set)\n\toCfg := cfg.(*Config)\n\treturn exporterhelper.NewMetrics(ctx, set, cfg,\n\t\toce.pushMetrics,\n\t\texporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),\n\t\texporterhelper.WithTimeout(oCfg.TimeoutConfig),\n\t\texporterhelper.WithRetry(oCfg.RetryConfig),\n\t\texporterhelper.WithQueue(oCfg.QueueConfig),\n\t\texporterhelper.WithStart(oce.start),\n\t\texporterhelper.WithShutdown(oce.shutdown),\n\t)\n}\n\nfunc createLogs(\n\tctx context.Context,\n\tset exporter.Settings,\n\tcfg component.Config,\n) (exporter.Logs, error) {\n\toce := newExporter(cfg, set)\n\toCfg := cfg.(*Config)\n\treturn exporterhelper.NewLogs(ctx, set, cfg,\n\t\toce.pushLogs,\n\t\texporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),\n\t\texporterhelper.WithTimeout(oCfg.TimeoutConfig),\n\t\texporterhelper.WithRetry(oCfg.RetryConfig),\n\t\texporterhelper.WithQueue(oCfg.QueueConfig),\n\t\texporterhelper.WithStart(oce.start),\n\t\texporterhelper.WithShutdown(oce.shutdown),\n\t)\n}\n\nfunc createProfilesExporter(\n\tctx context.Context,\n\tset exporter.Settings,\n\tcfg component.Config,\n) (xexporter.Profiles, error) {\n\toce := newExporter(cfg, set)\n\toCfg := cfg.(*Config)\n\treturn xexporterhelper.NewProfiles(ctx, set, cfg,\n\t\toce.pushProfiles,\n\t\texporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),\n\t\texporterhelper.WithTimeout(oCfg.TimeoutConfig),\n\t\texporterhelper.WithRetry(oCfg.RetryConfig),\n\t\texporterhelper.WithQueue(oCfg.QueueConfig),\n\t\texporterhelper.WithStart(oce.start),\n\t\texporterhelper.WithShutdown(oce.shutdown),\n\t)\n}\n"
  },
  {
    "path": "exporter/otlpexporter/factory_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlpexporter\n\nimport (\n\t\"context\"\n\t\"path/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configcompression\"\n\t\"go.opentelemetry.io/collector/config/configgrpc\"\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configretry\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc TestCreateDefaultConfig(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tassert.NotNil(t, cfg, \"failed to create default config\")\n\trequire.NoError(t, componenttest.CheckConfigStruct(cfg))\n\tocfg, ok := factory.CreateDefaultConfig().(*Config)\n\tassert.True(t, ok)\n\tassert.Equal(t, configretry.NewDefaultBackOffConfig(), ocfg.RetryConfig)\n\tassert.Equal(t, configoptional.Some(exporterhelper.NewDefaultQueueConfig()), ocfg.QueueConfig)\n\tassert.Equal(t, exporterhelper.NewDefaultTimeoutConfig(), ocfg.TimeoutConfig)\n\tassert.Equal(t, configcompression.TypeGzip, ocfg.ClientConfig.Compression)\n\tassert.Equal(t, configgrpc.BalancerName(), ocfg.ClientConfig.BalancerName)\n}\n\nfunc TestCreateMetrics(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.ClientConfig.Endpoint = testutil.GetAvailableLocalAddress(t)\n\n\tset := exportertest.NewNopSettings(factory.Type())\n\toexp, err := factory.CreateMetrics(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, oexp)\n}\n\nfunc TestCreateTraces(t *testing.T) {\n\tendpoint := testutil.GetAvailableLocalAddress(t)\n\ttests := []struct {\n\t\tname            string\n\t\tconfig          *Config\n\t\tmustFailOnStart bool\n\t}{\n\t\t{\n\t\t\tname: \"UseSecure\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint: endpoint,\n\t\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\t\tInsecure: false,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Keepalive\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint: endpoint,\n\t\t\t\t\tKeepalive: configoptional.Some(configgrpc.KeepaliveClientConfig{\n\t\t\t\t\t\tTime:                30 * time.Second,\n\t\t\t\t\t\tTimeout:             25 * time.Second,\n\t\t\t\t\t\tPermitWithoutStream: true,\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"NoneCompression\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint:    endpoint,\n\t\t\t\t\tCompression: \"none\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"GzipCompression\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint:    endpoint,\n\t\t\t\t\tCompression: configcompression.TypeGzip,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"SnappyCompression\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint:    endpoint,\n\t\t\t\t\tCompression: configcompression.TypeSnappy,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"ZstdCompression\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint:    endpoint,\n\t\t\t\t\tCompression: configcompression.TypeZstd,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Headers\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint: endpoint,\n\t\t\t\t\tHeaders: configopaque.MapList{\n\t\t\t\t\t\t{Name: \"hdr1\", Value: \"val1\"},\n\t\t\t\t\t\t{Name: \"hdr2\", Value: \"val2\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"NumConsumers\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint: endpoint,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"CaCert\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint: endpoint,\n\t\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\t\tCAFile: filepath.Join(\"testdata\", \"test_cert.pem\"),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"CertPemFileError\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint: endpoint,\n\t\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\t\tCAFile: \"nosuchfile\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tmustFailOnStart: true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tfactory := NewFactory()\n\t\t\tset := exportertest.NewNopSettings(factory.Type())\n\t\t\tconsumer, err := factory.CreateTraces(context.Background(), set, tt.config)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.NotNil(t, consumer)\n\t\t\terr = consumer.Start(context.Background(), componenttest.NewNopHost())\n\t\t\tif tt.mustFailOnStart {\n\t\t\t\trequire.Error(t, err)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\t\t\t// Shutdown is called even when Start fails\n\t\t\terr = consumer.Shutdown(context.Background())\n\t\t\tif err != nil {\n\t\t\t\t// Since the endpoint of OTLP exporter doesn't actually exist,\n\t\t\t\t// exporter may already stop because it cannot connect.\n\t\t\t\tassert.Equal(t, \"rpc error: code = Canceled desc = grpc: the client connection is closing\", err.Error())\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCreateLogs(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.ClientConfig.Endpoint = testutil.GetAvailableLocalAddress(t)\n\n\tset := exportertest.NewNopSettings(factory.Type())\n\toexp, err := factory.CreateLogs(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, oexp)\n}\n\nfunc TestCreateProfiles(t *testing.T) {\n\tendpoint := testutil.GetAvailableLocalAddress(t)\n\ttests := []struct {\n\t\tname            string\n\t\tconfig          *Config\n\t\tmustFailOnStart bool\n\t}{\n\t\t{\n\t\t\tname: \"UseSecure\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint: endpoint,\n\t\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\t\tInsecure: false,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Keepalive\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint: endpoint,\n\t\t\t\t\tKeepalive: configoptional.Some(configgrpc.KeepaliveClientConfig{\n\t\t\t\t\t\tTime:                30 * time.Second,\n\t\t\t\t\t\tTimeout:             25 * time.Second,\n\t\t\t\t\t\tPermitWithoutStream: true,\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"NoneCompression\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint:    endpoint,\n\t\t\t\t\tCompression: \"none\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"GzipCompression\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint:    endpoint,\n\t\t\t\t\tCompression: configcompression.TypeGzip,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"SnappyCompression\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint:    endpoint,\n\t\t\t\t\tCompression: configcompression.TypeSnappy,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"ZstdCompression\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint:    endpoint,\n\t\t\t\t\tCompression: configcompression.TypeZstd,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Headers\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint: endpoint,\n\t\t\t\t\tHeaders: configopaque.MapList{\n\t\t\t\t\t\t{Name: \"hdr1\", Value: \"val1\"},\n\t\t\t\t\t\t{Name: \"hdr2\", Value: \"val2\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"NumConsumers\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint: endpoint,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"CaCert\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint: endpoint,\n\t\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\t\tCAFile: filepath.Join(\"testdata\", \"test_cert.pem\"),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"CertPemFileError\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\t\t\tEndpoint: endpoint,\n\t\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\t\tCAFile: \"nosuchfile\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tmustFailOnStart: true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tfactory := NewFactory()\n\t\t\tset := exportertest.NewNopSettings(factory.Type())\n\t\t\tconsumer, err := factory.(xexporter.Factory).CreateProfiles(context.Background(), set, tt.config)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.NotNil(t, consumer)\n\t\t\terr = consumer.Start(context.Background(), componenttest.NewNopHost())\n\t\t\tif tt.mustFailOnStart {\n\t\t\t\trequire.Error(t, err)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\t\t\t// Shutdown is called even when Start fails\n\t\t\terr = consumer.Shutdown(context.Background())\n\t\t\tif err != nil {\n\t\t\t\t// Since the endpoint of OTLP exporter doesn't actually exist,\n\t\t\t\t// exporter may already stop because it cannot connect.\n\t\t\t\tassert.Equal(t, \"rpc error: code = Canceled desc = grpc: the client connection is closing\", err.Error())\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "exporter/otlpexporter/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage otlpexporter\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nvar typ = component.MustNewType(\"otlp_grpc\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct {\n\t\tcreateFn func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error)\n\t\tname     string\n\t}{\n\n\t\t{\n\t\t\tname: \"logs\",\n\t\t\tcreateFn: func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateLogs(ctx, set, cfg)\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg)\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"traces\",\n\t\t\tcreateFn: func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateTraces(ctx, set, cfg)\n\t\t\t},\n\t\t},\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name+\"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), exportertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\tt.Run(tt.name+\"-lifecycle\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), exportertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := newMdatagenNopHost()\n\t\t\terr = c.Start(context.Background(), host)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NotPanics(t, func() {\n\t\t\t\tswitch tt.name {\n\t\t\t\tcase \"logs\":\n\t\t\t\t\te, ok := c.(exporter.Logs)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tlogs := generateLifecycleTestLogs()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tlogs.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeLogs(context.Background(), logs)\n\t\t\t\tcase \"metrics\":\n\t\t\t\t\te, ok := c.(exporter.Metrics)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tmetrics := generateLifecycleTestMetrics()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tmetrics.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeMetrics(context.Background(), metrics)\n\t\t\t\tcase \"traces\":\n\t\t\t\t\te, ok := c.(exporter.Traces)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\ttraces := generateLifecycleTestTraces()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\ttraces.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeTraces(context.Background(), traces)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\trequire.NoError(t, err)\n\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t}\n}\n\nfunc generateLifecycleTestLogs() plog.Logs {\n\tlogs := plog.NewLogs()\n\trl := logs.ResourceLogs().AppendEmpty()\n\trl.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tl := rl.ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\tl.Body().SetStr(\"test log message\")\n\tl.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn logs\n}\n\nfunc generateLifecycleTestMetrics() pmetric.Metrics {\n\tmetrics := pmetric.NewMetrics()\n\trm := metrics.ResourceMetrics().AppendEmpty()\n\trm.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tm := rm.ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\tm.SetName(\"test_metric\")\n\tdp := m.SetEmptyGauge().DataPoints().AppendEmpty()\n\tdp.Attributes().PutStr(\"test_attr\", \"value_1\")\n\tdp.SetIntValue(123)\n\tdp.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn metrics\n}\n\nfunc generateLifecycleTestTraces() ptrace.Traces {\n\ttraces := ptrace.NewTraces()\n\trs := traces.ResourceSpans().AppendEmpty()\n\trs.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tspan := rs.ScopeSpans().AppendEmpty().Spans().AppendEmpty()\n\tspan.Attributes().PutStr(\"test_attr\", \"value_1\")\n\tspan.SetName(\"test_span\")\n\tspan.SetStartTimestamp(pcommon.NewTimestampFromTime(time.Now().Add(-1 * time.Second)))\n\tspan.SetEndTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn traces\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "exporter/otlpexporter/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage otlpexporter\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "exporter/otlpexporter/go.mod",
    "content": "module go.opentelemetry.io/collector/exporter/otlpexporter\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector v0.148.0\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/config/configauth v1.54.0\n\tgo.opentelemetry.io/collector/config/configcompression v1.54.0\n\tgo.opentelemetry.io/collector/config/configgrpc v0.148.0\n\tgo.opentelemetry.io/collector/config/configopaque v1.54.0\n\tgo.opentelemetry.io/collector/config/configoptional v1.54.0\n\tgo.opentelemetry.io/collector/config/configretry v1.54.0\n\tgo.opentelemetry.io/collector/config/configtls v1.54.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0\n\tgo.opentelemetry.io/collector/exporter v1.54.0\n\tgo.opentelemetry.io/collector/exporter/exporterhelper v0.148.0\n\tgo.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper v0.148.0\n\tgo.opentelemetry.io/collector/exporter/exportertest v0.148.0\n\tgo.opentelemetry.io/collector/exporter/xexporter v0.148.0\n\tgo.opentelemetry.io/collector/internal/testutil v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/zap v1.27.1\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171\n\tgoogle.golang.org/grpc v1.79.3\n\tgoogle.golang.org/protobuf v1.36.11\n)\n\nrequire (\n\tgithub.com/cenkalti/backoff/v5 v5.0.3 // indirect\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f // indirect\n\tgithub.com/fsnotify/fsnotify v1.9.0 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/golang/snappy v0.0.4 // indirect\n\tgithub.com/google/go-tpm v0.9.8 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/hashicorp/golang-lru/v2 v2.0.7 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/klauspost/compress v1.17.11 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/mostynb/go-grpc-compression v1.2.3 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/client v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configmiddleware v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/confignet v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumererror/xconsumererror v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionauth v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionmiddleware v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension/xextension v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/xpdata v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/receivertest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0 // indirect\n\tgo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/crypto v0.48.0 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/config/configcompression => ../../config/configcompression\n\nreplace go.opentelemetry.io/collector/config/configauth => ../../config/configauth\n\nreplace go.opentelemetry.io/collector/config/configgrpc => ../../config/configgrpc\n\nreplace go.opentelemetry.io/collector/config/confignet => ../../config/confignet\n\nreplace go.opentelemetry.io/collector/config/configopaque => ../../config/configopaque\n\nreplace go.opentelemetry.io/collector/config/configtls => ../../config/configtls\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/exporter => ../\n\nreplace go.opentelemetry.io/collector/extension => ../../extension\n\nreplace go.opentelemetry.io/collector/extension/extensionauth => ../../extension/extensionauth\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/receiver => ../../receiver\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/client => ../../client\n\nreplace go.opentelemetry.io/collector/config/configretry => ../../config/configretry\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../../receiver/receivertest\n\nreplace go.opentelemetry.io/collector/exporter/xexporter => ../xexporter\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector => ../..\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper => ../exporterhelper/xexporterhelper\n\nreplace go.opentelemetry.io/collector/consumer/consumererror/xconsumererror => ../../consumer/consumererror/xconsumererror\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nretract (\n\tv0.76.0 // Depends on retracted pdata v1.0.0-rc10 module, use v0.76.1\n\tv0.69.0 // Release failed, use v0.69.1\n)\n\nreplace go.opentelemetry.io/collector/exporter/exportertest => ../exportertest\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../../extension/extensiontest\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/extension/xextension => ../../extension/xextension\n\nreplace go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest => ../../extension/extensionauth/extensionauthtest\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ../../extension/extensionmiddleware\n\nreplace go.opentelemetry.io/collector/config/configmiddleware => ../../config/configmiddleware\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest => ../../extension/extensionmiddleware/extensionmiddlewaretest\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../../config/configoptional\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper => ../exporterhelper\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "exporter/otlpexporter/go.sum",
    "content": "github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=\ngithub.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f h1:RJ+BDPLSHQO7cSjKBqjPJSbi1qfk9WcsjQDtZiw3dZw=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f/go.mod h1:VHbbch/X4roIY22jL1s3qRbZhCiRIgUAF/PdSUcx2io=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM=\ngithub.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=\ngithub.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=\ngithub.com/google/go-tpm-tools v0.4.7 h1:J3ycC8umYxM9A4eF73EofRZu4BxY0jjQnUnkhIBbvws=\ngithub.com/google/go-tpm-tools v0.4.7/go.mod h1:gSyXTZHe3fgbzb6WEGd90QucmsnT1SRdlye82gH8QjQ=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/klauspost/compress v1.17.11 h1:In6xLpyWOi1+C7tXUUWv2ot1QvBjxevKAaI6IXrJmUc=\ngithub.com/klauspost/compress v1.17.11/go.mod h1:pMDklpSncoRMuLFrf1W9Ss9KT+0rH90U12bZKk7uwG0=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/mostynb/go-grpc-compression v1.2.3 h1:42/BKWMy0KEJGSdWvzqIyOZ95YcR9mLPqKctH7Uo//I=\ngithub.com/mostynb/go-grpc-compression v1.2.3/go.mod h1:AghIxF3P57umzqM9yz795+y1Vjs47Km/Y2FE6ouQ7Lg=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 h1:yI1/OhfEPy7J9eoa6Sj051C7n5dvpj0QX8g4sRchg04=\ngo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0/go.mod h1:NoUCKYWK+3ecatC4HjkRktREheMeEtrXoQxrqYFeHSc=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=\ngolang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=\ngonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "exporter/otlpexporter/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType           = component.MustNewType(\"otlp_grpc\")\n\tDeprecatedType = component.MustNewType(\"otlp\")\n\tScopeName      = \"go.opentelemetry.io/collector/exporter/otlpexporter\"\n)\n\nconst (\n\tProfilesStability = component.StabilityLevelAlpha\n\tTracesStability   = component.StabilityLevelStable\n\tMetricsStability  = component.StabilityLevelStable\n\tLogsStability     = component.StabilityLevelStable\n)\n"
  },
  {
    "path": "exporter/otlpexporter/metadata.yaml",
    "content": "display_name: OTLP gRPC Exporter\ntype: otlp_grpc\ndeprecated_type: otlp\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: exporter\n  stability:\n    stable: [traces, metrics, logs]\n    alpha: [profiles]\n  distributions: [core, contrib, k8s, otlp]\n\ntests:\n  config:\n    endpoint: otelcol:4317\n"
  },
  {
    "path": "exporter/otlpexporter/otlp.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlpexporter // import \"go.opentelemetry.io/collector/exporter/otlpexporter\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"runtime\"\n\n\t\"go.uber.org/zap\"\n\t\"google.golang.org/genproto/googleapis/rpc/errdetails\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/metadata\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configgrpc\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/internal/statusutil\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/plog/plogotlp\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n)\n\ntype baseExporter struct {\n\t// Input configuration.\n\tconfig *Config\n\n\t// gRPC clients and connection.\n\ttraceExporter   ptraceotlp.GRPCClient\n\tmetricExporter  pmetricotlp.GRPCClient\n\tlogExporter     plogotlp.GRPCClient\n\tprofileExporter pprofileotlp.GRPCClient\n\tclientConn      *grpc.ClientConn\n\tmetadata        metadata.MD\n\tcallOptions     []grpc.CallOption\n\n\tsettings component.TelemetrySettings\n\n\t// Default user-agent header.\n\tuserAgent string\n}\n\nfunc newExporter(cfg component.Config, set exporter.Settings) *baseExporter {\n\toCfg := cfg.(*Config)\n\n\tuserAgent := fmt.Sprintf(\"%s/%s (%s/%s)\",\n\t\tset.BuildInfo.Description, set.BuildInfo.Version, runtime.GOOS, runtime.GOARCH)\n\n\treturn &baseExporter{config: oCfg, settings: set.TelemetrySettings, userAgent: userAgent}\n}\n\n// start actually creates the gRPC connection. The client construction is deferred till this point as this\n// is the only place we get hold of Extensions which are required to construct auth round tripper.\nfunc (e *baseExporter) start(ctx context.Context, host component.Host) (err error) {\n\tagentOpt := configgrpc.WithGrpcDialOption(grpc.WithUserAgent(e.userAgent))\n\tif e.clientConn, err = e.config.ClientConfig.ToClientConn(ctx, host.GetExtensions(), e.settings, agentOpt); err != nil {\n\t\treturn err\n\t}\n\te.traceExporter = ptraceotlp.NewGRPCClient(e.clientConn)\n\te.metricExporter = pmetricotlp.NewGRPCClient(e.clientConn)\n\te.logExporter = plogotlp.NewGRPCClient(e.clientConn)\n\te.profileExporter = pprofileotlp.NewGRPCClient(e.clientConn)\n\theaders := map[string]string{}\n\tfor k, v := range e.config.ClientConfig.Headers.Iter {\n\t\theaders[k] = string(v)\n\t}\n\te.metadata = metadata.New(headers)\n\te.callOptions = []grpc.CallOption{\n\t\tgrpc.WaitForReady(e.config.ClientConfig.WaitForReady),\n\t}\n\n\treturn err\n}\n\nfunc (e *baseExporter) shutdown(context.Context) error {\n\tif e.clientConn != nil {\n\t\treturn e.clientConn.Close()\n\t}\n\treturn nil\n}\n\nfunc (e *baseExporter) pushTraces(ctx context.Context, td ptrace.Traces) error {\n\tif e.traceExporter == nil {\n\t\treturn errors.New(\"otlp exporter not started\")\n\t}\n\n\treq := ptraceotlp.NewExportRequestFromTraces(td)\n\tresp, respErr := e.traceExporter.Export(ctx, req, e.callOptions...)\n\tif err := processError(respErr); err != nil {\n\t\treturn err\n\t}\n\tpartialSuccess := resp.PartialSuccess()\n\tif partialSuccess.ErrorMessage() != \"\" || partialSuccess.RejectedSpans() != 0 {\n\t\te.settings.Logger.Warn(\"Partial success response\",\n\t\t\tzap.String(\"message\", resp.PartialSuccess().ErrorMessage()),\n\t\t\tzap.Int64(\"dropped_spans\", resp.PartialSuccess().RejectedSpans()),\n\t\t)\n\t}\n\treturn nil\n}\n\nfunc (e *baseExporter) pushMetrics(ctx context.Context, md pmetric.Metrics) error {\n\tif e.metricExporter == nil {\n\t\treturn errors.New(\"otlp exporter not started\")\n\t}\n\n\treq := pmetricotlp.NewExportRequestFromMetrics(md)\n\tresp, respErr := e.metricExporter.Export(ctx, req, e.callOptions...)\n\tif err := processError(respErr); err != nil {\n\t\treturn err\n\t}\n\tpartialSuccess := resp.PartialSuccess()\n\tif partialSuccess.ErrorMessage() != \"\" || partialSuccess.RejectedDataPoints() != 0 {\n\t\te.settings.Logger.Warn(\"Partial success response\",\n\t\t\tzap.String(\"message\", resp.PartialSuccess().ErrorMessage()),\n\t\t\tzap.Int64(\"dropped_data_points\", resp.PartialSuccess().RejectedDataPoints()),\n\t\t)\n\t}\n\treturn nil\n}\n\nfunc (e *baseExporter) pushLogs(ctx context.Context, ld plog.Logs) error {\n\tif e.logExporter == nil {\n\t\treturn errors.New(\"otlp exporter not started\")\n\t}\n\n\treq := plogotlp.NewExportRequestFromLogs(ld)\n\tresp, respErr := e.logExporter.Export(ctx, req, e.callOptions...)\n\tif err := processError(respErr); err != nil {\n\t\treturn err\n\t}\n\tpartialSuccess := resp.PartialSuccess()\n\tif partialSuccess.ErrorMessage() != \"\" || partialSuccess.RejectedLogRecords() != 0 {\n\t\te.settings.Logger.Warn(\"Partial success response\",\n\t\t\tzap.String(\"message\", resp.PartialSuccess().ErrorMessage()),\n\t\t\tzap.Int64(\"dropped_log_records\", resp.PartialSuccess().RejectedLogRecords()),\n\t\t)\n\t}\n\treturn nil\n}\n\nfunc (e *baseExporter) pushProfiles(ctx context.Context, td pprofile.Profiles) error {\n\tif e.profileExporter == nil {\n\t\treturn errors.New(\"otlp exporter not started\")\n\t}\n\n\treq := pprofileotlp.NewExportRequestFromProfiles(td)\n\tresp, respErr := e.profileExporter.Export(ctx, req, e.callOptions...)\n\tif err := processError(respErr); err != nil {\n\t\treturn err\n\t}\n\tpartialSuccess := resp.PartialSuccess()\n\tif partialSuccess.ErrorMessage() != \"\" || partialSuccess.RejectedProfiles() != 0 {\n\t\te.settings.Logger.Warn(\"Partial success response\",\n\t\t\tzap.String(\"message\", resp.PartialSuccess().ErrorMessage()),\n\t\t\tzap.Int64(\"dropped_profiles\", resp.PartialSuccess().RejectedProfiles()),\n\t\t)\n\t}\n\treturn nil\n}\n\nfunc processError(err error) error {\n\tif err == nil {\n\t\t// Request is successful, we are done.\n\t\treturn nil\n\t}\n\n\t// We have an error, check gRPC status code.\n\tst := status.Convert(err)\n\tif st.Code() == codes.OK {\n\t\t// Not really an error, still success.\n\t\treturn nil\n\t}\n\n\t// Now, this is a real error.\n\tretryInfo := statusutil.GetRetryInfo(st)\n\n\tif !shouldRetry(st.Code(), retryInfo) {\n\t\t// It is not a retryable error, we should not retry.\n\t\treturn consumererror.NewPermanent(err)\n\t}\n\n\t// Check if server returned throttling information.\n\tthrottleDuration := retryInfo.GetRetryDelay().AsDuration()\n\tif throttleDuration != 0 {\n\t\t// We are throttled. Wait before retrying as requested by the server.\n\t\treturn exporterhelper.NewThrottleRetry(err, throttleDuration)\n\t}\n\n\t// Need to retry.\n\treturn err\n}\n\nfunc shouldRetry(code codes.Code, retryInfo *errdetails.RetryInfo) bool {\n\tswitch code {\n\tcase codes.Canceled,\n\t\tcodes.DeadlineExceeded,\n\t\tcodes.Aborted,\n\t\tcodes.OutOfRange,\n\t\tcodes.Unavailable,\n\t\tcodes.DataLoss:\n\t\t// These are retryable errors.\n\t\treturn true\n\tcase codes.ResourceExhausted:\n\t\t// Retry only if RetryInfo was supplied by the server.\n\t\t// This indicates that the server can still recover from resource exhaustion.\n\t\treturn retryInfo != nil\n\t}\n\t// Don't retry on any other code.\n\treturn false\n}\n"
  },
  {
    "path": "exporter/otlpexporter/otlp_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlpexporter\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\t\"google.golang.org/genproto/googleapis/rpc/errdetails\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/credentials\"\n\t\"google.golang.org/grpc/metadata\"\n\t\"google.golang.org/grpc/status\"\n\t\"google.golang.org/protobuf/types/known/durationpb\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configgrpc\"\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/plog/plogotlp\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\ntype mockReceiver struct {\n\tsrv          *grpc.Server\n\trequestCount *atomic.Int64\n\ttotalItems   *atomic.Int64\n\tmux          sync.Mutex\n\tmetadata     metadata.MD\n\texportError  error\n}\n\nfunc (r *mockReceiver) getMetadata() metadata.MD {\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\treturn r.metadata\n}\n\nfunc (r *mockReceiver) setExportError(err error) {\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\tr.exportError = err\n}\n\nvar _ ptraceotlp.GRPCServer = &mockTracesReceiver{}\n\ntype mockTracesReceiver struct {\n\tptraceotlp.UnimplementedGRPCServer\n\tmockReceiver\n\texportResponse func() ptraceotlp.ExportResponse\n\tlastRequest    ptrace.Traces\n}\n\nfunc (r *mockTracesReceiver) Export(ctx context.Context, req ptraceotlp.ExportRequest) (ptraceotlp.ExportResponse, error) {\n\tr.requestCount.Add(1)\n\ttd := req.Traces()\n\tr.totalItems.Add(int64(td.SpanCount()))\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\tr.lastRequest = td\n\tr.metadata, _ = metadata.FromIncomingContext(ctx)\n\treturn r.exportResponse(), r.exportError\n}\n\nfunc (r *mockTracesReceiver) getLastRequest() ptrace.Traces {\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\treturn r.lastRequest\n}\n\nfunc (r *mockTracesReceiver) setExportResponse(fn func() ptraceotlp.ExportResponse) {\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\tr.exportResponse = fn\n}\n\nfunc otlpTracesReceiverOnGRPCServer(ln net.Listener, useTLS bool) (*mockTracesReceiver, error) {\n\tsopts := []grpc.ServerOption{}\n\n\tif useTLS {\n\t\t_, currentFile, _, _ := runtime.Caller(0)\n\t\tbasepath := filepath.Dir(currentFile)\n\t\tcertpath := filepath.Join(basepath, filepath.Join(\"testdata\", \"test_cert.pem\"))\n\t\tkeypath := filepath.Join(basepath, filepath.Join(\"testdata\", \"test_key.pem\"))\n\n\t\tcreds, err := credentials.NewServerTLSFromFile(certpath, keypath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsopts = append(sopts, grpc.Creds(creds))\n\t}\n\n\trcv := &mockTracesReceiver{\n\t\tmockReceiver: mockReceiver{\n\t\t\tsrv:          grpc.NewServer(sopts...),\n\t\t\trequestCount: new(atomic.Int64),\n\t\t\ttotalItems:   new(atomic.Int64),\n\t\t},\n\t\texportResponse: ptraceotlp.NewExportResponse,\n\t}\n\n\t// Now run it as a gRPC server\n\tptraceotlp.RegisterGRPCServer(rcv.srv, rcv)\n\tgo func() {\n\t\t_ = rcv.srv.Serve(ln)\n\t}()\n\n\treturn rcv, nil\n}\n\nvar _ plogotlp.GRPCServer = &mockLogsReceiver{}\n\ntype mockLogsReceiver struct {\n\tplogotlp.UnimplementedGRPCServer\n\tmockReceiver\n\texportResponse func() plogotlp.ExportResponse\n\tlastRequest    plog.Logs\n}\n\nfunc (r *mockLogsReceiver) Export(ctx context.Context, req plogotlp.ExportRequest) (plogotlp.ExportResponse, error) {\n\tr.requestCount.Add(1)\n\tld := req.Logs()\n\tr.totalItems.Add(int64(ld.LogRecordCount()))\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\tr.lastRequest = ld\n\tr.metadata, _ = metadata.FromIncomingContext(ctx)\n\treturn r.exportResponse(), r.exportError\n}\n\nfunc (r *mockLogsReceiver) getLastRequest() plog.Logs {\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\treturn r.lastRequest\n}\n\nfunc (r *mockLogsReceiver) setExportResponse(fn func() plogotlp.ExportResponse) {\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\tr.exportResponse = fn\n}\n\nfunc otlpLogsReceiverOnGRPCServer(ln net.Listener) *mockLogsReceiver {\n\trcv := &mockLogsReceiver{\n\t\tmockReceiver: mockReceiver{\n\t\t\tsrv:          grpc.NewServer(),\n\t\t\trequestCount: new(atomic.Int64),\n\t\t\ttotalItems:   new(atomic.Int64),\n\t\t},\n\t\texportResponse: plogotlp.NewExportResponse,\n\t}\n\n\t// Now run it as a gRPC server\n\tplogotlp.RegisterGRPCServer(rcv.srv, rcv)\n\tgo func() {\n\t\t_ = rcv.srv.Serve(ln)\n\t}()\n\n\treturn rcv\n}\n\nvar _ pmetricotlp.GRPCServer = &mockMetricsReceiver{}\n\ntype mockMetricsReceiver struct {\n\tpmetricotlp.UnimplementedGRPCServer\n\tmockReceiver\n\texportResponse func() pmetricotlp.ExportResponse\n\tlastRequest    pmetric.Metrics\n}\n\nfunc (r *mockMetricsReceiver) Export(ctx context.Context, req pmetricotlp.ExportRequest) (pmetricotlp.ExportResponse, error) {\n\tmd := req.Metrics()\n\tr.requestCount.Add(1)\n\tr.totalItems.Add(int64(md.DataPointCount()))\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\tr.lastRequest = md\n\tr.metadata, _ = metadata.FromIncomingContext(ctx)\n\treturn r.exportResponse(), r.exportError\n}\n\nfunc (r *mockMetricsReceiver) getLastRequest() pmetric.Metrics {\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\treturn r.lastRequest\n}\n\nfunc (r *mockMetricsReceiver) setExportResponse(fn func() pmetricotlp.ExportResponse) {\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\tr.exportResponse = fn\n}\n\nfunc otlpMetricsReceiverOnGRPCServer(ln net.Listener) *mockMetricsReceiver {\n\trcv := &mockMetricsReceiver{\n\t\tmockReceiver: mockReceiver{\n\t\t\tsrv:          grpc.NewServer(),\n\t\t\trequestCount: new(atomic.Int64),\n\t\t\ttotalItems:   new(atomic.Int64),\n\t\t},\n\t\texportResponse: pmetricotlp.NewExportResponse,\n\t}\n\n\t// Now run it as a gRPC server\n\tpmetricotlp.RegisterGRPCServer(rcv.srv, rcv)\n\tgo func() {\n\t\t_ = rcv.srv.Serve(ln)\n\t}()\n\n\treturn rcv\n}\n\ntype mockProfilesReceiver struct {\n\tpprofileotlp.UnimplementedGRPCServer\n\tmockReceiver\n\texportResponse func() pprofileotlp.ExportResponse\n\tlastRequest    pprofile.Profiles\n}\n\nfunc (r *mockProfilesReceiver) Export(ctx context.Context, req pprofileotlp.ExportRequest) (pprofileotlp.ExportResponse, error) {\n\tr.requestCount.Add(1)\n\ttd := req.Profiles()\n\tr.totalItems.Add(int64(td.SampleCount()))\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\tr.lastRequest = td\n\tr.metadata, _ = metadata.FromIncomingContext(ctx)\n\treturn r.exportResponse(), r.exportError\n}\n\nfunc (r *mockProfilesReceiver) getLastRequest() pprofile.Profiles {\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\treturn r.lastRequest\n}\n\nfunc (r *mockProfilesReceiver) setExportResponse(fn func() pprofileotlp.ExportResponse) {\n\tr.mux.Lock()\n\tdefer r.mux.Unlock()\n\tr.exportResponse = fn\n}\n\nfunc otlpProfilesReceiverOnGRPCServer(ln net.Listener, useTLS bool) (*mockProfilesReceiver, error) {\n\tsopts := []grpc.ServerOption{}\n\n\tif useTLS {\n\t\t_, currentFile, _, _ := runtime.Caller(0)\n\t\tbasepath := filepath.Dir(currentFile)\n\t\tcertpath := filepath.Join(basepath, filepath.Join(\"testdata\", \"test_cert.pem\"))\n\t\tkeypath := filepath.Join(basepath, filepath.Join(\"testdata\", \"test_key.pem\"))\n\n\t\tcreds, err := credentials.NewServerTLSFromFile(certpath, keypath)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tsopts = append(sopts, grpc.Creds(creds))\n\t}\n\n\trcv := &mockProfilesReceiver{\n\t\tmockReceiver: mockReceiver{\n\t\t\trequestCount: &atomic.Int64{},\n\t\t\ttotalItems:   &atomic.Int64{},\n\t\t\tsrv:          grpc.NewServer(sopts...),\n\t\t},\n\t\texportResponse: pprofileotlp.NewExportResponse,\n\t}\n\n\t// Now run it as a gRPC server\n\tpprofileotlp.RegisterGRPCServer(rcv.srv, rcv)\n\tgo func() {\n\t\t_ = rcv.srv.Serve(ln)\n\t}()\n\n\treturn rcv, nil\n}\n\nfunc TestSendTraces(t *testing.T) {\n\t// Start an OTLP-compatible receiver.\n\tln, err := net.Listen(\"tcp\", \"localhost:\")\n\trequire.NoError(t, err, \"Failed to find an available address to run the gRPC server: %v\", err)\n\trcv, _ := otlpTracesReceiverOnGRPCServer(ln, false)\n\t// Also closes the connection.\n\tdefer rcv.srv.GracefulStop()\n\n\t// Start an OTLP exporter and point to the receiver.\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\t// Disable queuing to ensure that we execute the request when calling ConsumeTraces\n\t// otherwise we will not see any errors.\n\tcfg.QueueConfig = configoptional.None[exporterhelper.QueueBatchConfig]()\n\tcfg.ClientConfig = configgrpc.ClientConfig{\n\t\tEndpoint: ln.Addr().String(),\n\t\tTLS: configtls.ClientConfig{\n\t\t\tInsecure: true,\n\t\t},\n\t\tHeaders: configopaque.MapList{\n\t\t\t{Name: \"header\", Value: \"header-value\"},\n\t\t},\n\t}\n\tset := exportertest.NewNopSettings(factory.Type())\n\tset.BuildInfo.Description = \"Collector\"\n\tset.BuildInfo.Version = \"1.2.3test\"\n\n\t// For testing the \"Partial success\" warning.\n\tlogger, observed := observer.New(zap.DebugLevel)\n\tset.Logger = zap.New(logger)\n\n\texp, err := factory.CreateTraces(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, exp)\n\n\tdefer func() {\n\t\tassert.NoError(t, exp.Shutdown(context.Background()))\n\t}()\n\n\thost := componenttest.NewNopHost()\n\trequire.NoError(t, exp.Start(context.Background(), host))\n\n\t// Ensure that initially there is no data in the receiver.\n\tassert.EqualValues(t, 0, rcv.requestCount.Load())\n\n\t// Send empty trace.\n\ttd := ptrace.NewTraces()\n\trequire.NoError(t, exp.ConsumeTraces(context.Background(), td))\n\n\t// Wait until it is received.\n\tassert.Eventually(t, func() bool {\n\t\treturn rcv.requestCount.Load() > 0\n\t}, 10*time.Second, 5*time.Millisecond)\n\n\t// Ensure it was received empty.\n\tassert.EqualValues(t, 0, rcv.totalItems.Load())\n\n\t// A trace with 2 spans.\n\ttd = testdata.GenerateTraces(2)\n\n\terr = exp.ConsumeTraces(context.Background(), td)\n\trequire.NoError(t, err)\n\n\t// Wait until it is received.\n\tassert.Eventually(t, func() bool {\n\t\treturn rcv.requestCount.Load() > 1\n\t}, 10*time.Second, 5*time.Millisecond)\n\n\texpectedHeader := []string{\"header-value\"}\n\n\t// Verify received span.\n\tassert.EqualValues(t, 2, rcv.totalItems.Load())\n\tassert.EqualValues(t, 2, rcv.requestCount.Load())\n\tassert.Equal(t, td, rcv.getLastRequest())\n\n\tmd := rcv.getMetadata()\n\trequire.Equal(t, expectedHeader, md.Get(\"header\"))\n\trequire.Len(t, md.Get(\"User-Agent\"), 1)\n\trequire.Contains(t, md.Get(\"User-Agent\")[0], \"Collector/1.2.3test\")\n\n\t// Return partial success\n\trcv.setExportResponse(func() ptraceotlp.ExportResponse {\n\t\tresponse := ptraceotlp.NewExportResponse()\n\t\tpartialSuccess := response.PartialSuccess()\n\t\tpartialSuccess.SetErrorMessage(\"Some spans were not ingested\")\n\t\tpartialSuccess.SetRejectedSpans(1)\n\n\t\treturn response\n\t})\n\n\t// A request with 2 Trace entries.\n\ttd = testdata.GenerateTraces(2)\n\n\terr = exp.ConsumeTraces(context.Background(), td)\n\trequire.NoError(t, err)\n\tassert.Len(t, observed.FilterLevelExact(zap.WarnLevel).All(), 1)\n\tassert.Contains(t, observed.FilterLevelExact(zap.WarnLevel).All()[0].Message, \"Partial success\")\n}\n\nfunc TestSendTracesWhenEndpointHasHTTPScheme(t *testing.T) {\n\ttests := []struct {\n\t\tname               string\n\t\tuseTLS             bool\n\t\tscheme             string\n\t\tgRPCClientSettings configgrpc.ClientConfig\n\t}{\n\t\t{\n\t\t\tname:               \"Use https scheme\",\n\t\t\tuseTLS:             true,\n\t\t\tscheme:             \"https://\",\n\t\t\tgRPCClientSettings: configgrpc.ClientConfig{},\n\t\t},\n\t\t{\n\t\t\tname:   \"Use http scheme\",\n\t\t\tuseTLS: false,\n\t\t\tscheme: \"http://\",\n\t\t\tgRPCClientSettings: configgrpc.ClientConfig{\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tInsecure: true,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t// Start an OTLP-compatible receiver.\n\t\t\tln, err := net.Listen(\"tcp\", \"localhost:\")\n\t\t\trequire.NoError(t, err, \"Failed to find an available address to run the gRPC server: %v\", err)\n\t\t\trcv, err := otlpTracesReceiverOnGRPCServer(ln, test.useTLS)\n\t\t\trequire.NoError(t, err, \"Failed to start mock OTLP receiver\")\n\t\t\t// Also closes the connection.\n\t\t\tdefer rcv.srv.GracefulStop()\n\n\t\t\t// Start an OTLP exporter and point to the receiver.\n\t\t\tfactory := NewFactory()\n\t\t\tcfg := factory.CreateDefaultConfig().(*Config)\n\t\t\tcfg.ClientConfig = test.gRPCClientSettings\n\t\t\tcfg.ClientConfig.Endpoint = test.scheme + ln.Addr().String()\n\t\t\tif test.useTLS {\n\t\t\t\tcfg.ClientConfig.TLS.InsecureSkipVerify = true\n\t\t\t}\n\t\t\tset := exportertest.NewNopSettings(factory.Type())\n\t\t\texp, err := factory.CreateTraces(context.Background(), set, cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NotNil(t, exp)\n\n\t\t\tdefer func() {\n\t\t\t\tassert.NoError(t, exp.Shutdown(context.Background()))\n\t\t\t}()\n\n\t\t\thost := componenttest.NewNopHost()\n\t\t\trequire.NoError(t, exp.Start(context.Background(), host))\n\n\t\t\t// Ensure that initially there is no data in the receiver.\n\t\t\tassert.EqualValues(t, 0, rcv.requestCount.Load())\n\n\t\t\t// Send empty trace.\n\t\t\ttd := ptrace.NewTraces()\n\t\t\trequire.NoError(t, exp.ConsumeTraces(context.Background(), td))\n\n\t\t\t// Wait until it is received.\n\t\t\tassert.Eventually(t, func() bool {\n\t\t\t\treturn rcv.requestCount.Load() > 0\n\t\t\t}, 10*time.Second, 5*time.Millisecond)\n\n\t\t\t// Ensure it was received empty.\n\t\t\tassert.EqualValues(t, 0, rcv.totalItems.Load())\n\t\t})\n\t}\n}\n\nfunc TestSendMetrics(t *testing.T) {\n\t// Start an OTLP-compatible receiver.\n\tln, err := net.Listen(\"tcp\", \"localhost:\")\n\trequire.NoError(t, err, \"Failed to find an available address to run the gRPC server: %v\", err)\n\trcv := otlpMetricsReceiverOnGRPCServer(ln)\n\t// Also closes the connection.\n\tdefer rcv.srv.GracefulStop()\n\n\t// Start an OTLP exporter and point to the receiver.\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\t// Disable queuing to ensure that we execute the request when calling ConsumeMetrics\n\t// otherwise we will not see any errors.\n\tcfg.QueueConfig = configoptional.None[exporterhelper.QueueBatchConfig]()\n\tcfg.ClientConfig = configgrpc.ClientConfig{\n\t\tEndpoint: ln.Addr().String(),\n\t\tTLS: configtls.ClientConfig{\n\t\t\tInsecure: true,\n\t\t},\n\t\tHeaders: configopaque.MapList{\n\t\t\t{Name: \"header\", Value: \"header-value\"},\n\t\t},\n\t}\n\tset := exportertest.NewNopSettings(factory.Type())\n\tset.BuildInfo.Description = \"Collector\"\n\tset.BuildInfo.Version = \"1.2.3test\"\n\n\t// For testing the \"Partial success\" warning.\n\tlogger, observed := observer.New(zap.DebugLevel)\n\tset.Logger = zap.New(logger)\n\n\texp, err := factory.CreateMetrics(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, exp)\n\tdefer func() {\n\t\tassert.NoError(t, exp.Shutdown(context.Background()))\n\t}()\n\n\thost := componenttest.NewNopHost()\n\n\trequire.NoError(t, exp.Start(context.Background(), host))\n\n\t// Ensure that initially there is no data in the receiver.\n\tassert.EqualValues(t, 0, rcv.requestCount.Load())\n\n\t// Send empty metric.\n\tmd := pmetric.NewMetrics()\n\trequire.NoError(t, exp.ConsumeMetrics(context.Background(), md))\n\n\t// Wait until it is received.\n\tassert.Eventually(t, func() bool {\n\t\treturn rcv.requestCount.Load() > 0\n\t}, 10*time.Second, 5*time.Millisecond)\n\n\t// Ensure it was received empty.\n\tassert.EqualValues(t, 0, rcv.totalItems.Load())\n\n\t// Send two metrics.\n\tmd = testdata.GenerateMetrics(2)\n\n\terr = exp.ConsumeMetrics(context.Background(), md)\n\trequire.NoError(t, err)\n\n\t// Wait until it is received.\n\tassert.Eventually(t, func() bool {\n\t\treturn rcv.requestCount.Load() > 1\n\t}, 10*time.Second, 5*time.Millisecond)\n\n\texpectedHeader := []string{\"header-value\"}\n\n\t// Verify received metrics.\n\tassert.EqualValues(t, 2, rcv.requestCount.Load())\n\tassert.EqualValues(t, 4, rcv.totalItems.Load())\n\tassert.Equal(t, md, rcv.getLastRequest())\n\n\tmdata := rcv.getMetadata()\n\trequire.Equal(t, expectedHeader, mdata.Get(\"header\"))\n\trequire.Len(t, mdata.Get(\"User-Agent\"), 1)\n\trequire.Contains(t, mdata.Get(\"User-Agent\")[0], \"Collector/1.2.3test\")\n\n\tst := status.New(codes.InvalidArgument, \"Invalid argument\")\n\trcv.setExportError(st.Err())\n\n\t// Send two metrics..\n\tmd = testdata.GenerateMetrics(2)\n\n\terr = exp.ConsumeMetrics(context.Background(), md)\n\trequire.Error(t, err)\n\n\trcv.setExportError(nil)\n\n\t// Return partial success\n\trcv.setExportResponse(func() pmetricotlp.ExportResponse {\n\t\tresponse := pmetricotlp.NewExportResponse()\n\t\tpartialSuccess := response.PartialSuccess()\n\t\tpartialSuccess.SetErrorMessage(\"Some data points were not ingested\")\n\t\tpartialSuccess.SetRejectedDataPoints(1)\n\n\t\treturn response\n\t})\n\n\t// Send two metrics.\n\tmd = testdata.GenerateMetrics(2)\n\trequire.NoError(t, exp.ConsumeMetrics(context.Background(), md))\n\tassert.Len(t, observed.FilterLevelExact(zap.WarnLevel).All(), 1)\n\tassert.Contains(t, observed.FilterLevelExact(zap.WarnLevel).All()[0].Message, \"Partial success\")\n}\n\nfunc TestSendTraceDataServerDownAndUp(t *testing.T) {\n\t// Find the addr, but don't start the server.\n\tln, err := net.Listen(\"tcp\", \"localhost:\")\n\trequire.NoError(t, err, \"Failed to find an available address to run the gRPC server: %v\", err)\n\n\t// Start an OTLP exporter and point to the receiver.\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\t// Disable queuing to ensure that we execute the request when calling ConsumeTraces\n\t// otherwise we will not see the error.\n\tcfg.QueueConfig = configoptional.None[exporterhelper.QueueBatchConfig]()\n\tcfg.ClientConfig = configgrpc.ClientConfig{\n\t\tEndpoint: ln.Addr().String(),\n\t\tTLS: configtls.ClientConfig{\n\t\t\tInsecure: true,\n\t\t},\n\t\t// Need to wait for every request blocking until either request timeouts or succeed.\n\t\t// Do not rely on external retry logic here, if that is intended set InitialInterval to 100ms.\n\t\tWaitForReady: true,\n\t}\n\tset := exportertest.NewNopSettings(factory.Type())\n\texp, err := factory.CreateTraces(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, exp)\n\tdefer func() {\n\t\tassert.NoError(t, exp.Shutdown(context.Background()))\n\t}()\n\n\thost := componenttest.NewNopHost()\n\n\trequire.NoError(t, exp.Start(context.Background(), host))\n\n\t// A trace with 2 spans.\n\ttd := testdata.GenerateTraces(2)\n\tctx, cancel := context.WithTimeout(context.Background(), 1*time.Second)\n\trequire.Error(t, exp.ConsumeTraces(ctx, td))\n\tassert.Equal(t, context.DeadlineExceeded, ctx.Err())\n\tcancel()\n\n\tctx, cancel = context.WithTimeout(context.Background(), 1*time.Second)\n\trequire.Error(t, exp.ConsumeTraces(ctx, td))\n\tassert.Equal(t, context.DeadlineExceeded, ctx.Err())\n\tcancel()\n\n\tstartServerAndMakeRequest(t, exp, td, ln)\n\n\tctx, cancel = context.WithTimeout(context.Background(), 1*time.Second)\n\trequire.Error(t, exp.ConsumeTraces(ctx, td))\n\tassert.Equal(t, context.DeadlineExceeded, ctx.Err())\n\tcancel()\n\n\t// First call to startServerAndMakeRequest closed the connection. There is a race condition here that the\n\t// port may be reused, if this gets flaky rethink what to do.\n\tln, err = net.Listen(\"tcp\", ln.Addr().String())\n\trequire.NoError(t, err, \"Failed to find an available address to run the gRPC server: %v\", err)\n\tstartServerAndMakeRequest(t, exp, td, ln)\n\n\tctx, cancel = context.WithTimeout(context.Background(), 1*time.Second)\n\trequire.Error(t, exp.ConsumeTraces(ctx, td))\n\tassert.Equal(t, context.DeadlineExceeded, ctx.Err())\n\tcancel()\n}\n\nfunc TestSendTraceDataServerStartWhileRequest(t *testing.T) {\n\t// Find the addr, but don't start the server.\n\tln, err := net.Listen(\"tcp\", \"localhost:\")\n\trequire.NoError(t, err, \"Failed to find an available address to run the gRPC server: %v\", err)\n\n\t// Start an OTLP exporter and point to the receiver.\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.ClientConfig = configgrpc.ClientConfig{\n\t\tEndpoint: ln.Addr().String(),\n\t\tTLS: configtls.ClientConfig{\n\t\t\tInsecure: true,\n\t\t},\n\t}\n\tset := exportertest.NewNopSettings(factory.Type())\n\texp, err := factory.CreateTraces(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, exp)\n\tdefer func() {\n\t\tassert.NoError(t, exp.Shutdown(context.Background()))\n\t}()\n\n\thost := componenttest.NewNopHost()\n\n\trequire.NoError(t, exp.Start(context.Background(), host))\n\n\t// A trace with 2 spans.\n\ttd := testdata.GenerateTraces(2)\n\tdone := make(chan bool, 1)\n\tdefer close(done)\n\tctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)\n\tgo func() {\n\t\tassert.NoError(t, exp.ConsumeTraces(ctx, td))\n\t\tdone <- true\n\t}()\n\n\ttime.Sleep(2 * time.Second)\n\trcv, _ := otlpTracesReceiverOnGRPCServer(ln, false)\n\tdefer rcv.srv.GracefulStop()\n\t// Wait until one of the conditions below triggers.\n\tselect {\n\tcase <-ctx.Done():\n\t\tt.Fail()\n\tcase <-done:\n\t\trequire.NoError(t, ctx.Err())\n\t}\n\tcancel()\n}\n\nfunc TestSendTracesOnResourceExhaustion(t *testing.T) {\n\tln, err := net.Listen(\"tcp\", \"localhost:\")\n\trequire.NoError(t, err)\n\trcv, _ := otlpTracesReceiverOnGRPCServer(ln, false)\n\trcv.setExportError(status.Error(codes.ResourceExhausted, \"resource exhausted\"))\n\tdefer rcv.srv.GracefulStop()\n\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.RetryConfig.InitialInterval = 0\n\tcfg.ClientConfig = configgrpc.ClientConfig{\n\t\tEndpoint: ln.Addr().String(),\n\t\tTLS: configtls.ClientConfig{\n\t\t\tInsecure: true,\n\t\t},\n\t}\n\tset := exportertest.NewNopSettings(factory.Type())\n\texp, err := factory.CreateTraces(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, exp)\n\n\tdefer func() {\n\t\tassert.NoError(t, exp.Shutdown(context.Background()))\n\t}()\n\n\thost := componenttest.NewNopHost()\n\trequire.NoError(t, exp.Start(context.Background(), host))\n\n\tassert.EqualValues(t, 0, rcv.requestCount.Load())\n\n\ttd := ptrace.NewTraces()\n\trequire.NoError(t, exp.ConsumeTraces(context.Background(), td))\n\n\tassert.Never(t, func() bool {\n\t\treturn rcv.requestCount.Load() > 1\n\t}, 1*time.Second, 5*time.Millisecond, \"Should not retry if RetryInfo is not included into status details by the server.\")\n\n\trcv.requestCount.Swap(0)\n\n\tst := status.New(codes.ResourceExhausted, \"resource exhausted\")\n\tst, _ = st.WithDetails(&errdetails.RetryInfo{\n\t\tRetryDelay: durationpb.New(100 * time.Millisecond),\n\t})\n\trcv.setExportError(st.Err())\n\n\trequire.NoError(t, exp.ConsumeTraces(context.Background(), td))\n\n\tassert.Eventually(t, func() bool {\n\t\treturn rcv.requestCount.Load() > 1\n\t}, 10*time.Second, 5*time.Millisecond, \"Should retry if RetryInfo is included into status details by the server.\")\n}\n\nfunc startServerAndMakeRequest(t *testing.T, exp exporter.Traces, td ptrace.Traces, ln net.Listener) {\n\trcv, _ := otlpTracesReceiverOnGRPCServer(ln, false)\n\tdefer rcv.srv.GracefulStop()\n\t// Ensure that initially there is no data in the receiver.\n\tassert.EqualValues(t, 0, rcv.requestCount.Load())\n\n\t// Clone the request and store as expected.\n\texpectedData := ptrace.NewTraces()\n\ttd.CopyTo(expectedData)\n\n\t// Resend the request, this should succeed.\n\tctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)\n\trequire.NoError(t, exp.ConsumeTraces(ctx, td))\n\tcancel()\n\n\t// Wait until it is received.\n\tassert.Eventually(t, func() bool {\n\t\treturn rcv.requestCount.Load() > 0\n\t}, 10*time.Second, 5*time.Millisecond)\n\n\t// Verify received span.\n\tassert.EqualValues(t, 2, rcv.totalItems.Load())\n\tassert.Equal(t, expectedData, rcv.getLastRequest())\n}\n\nfunc TestSendLogData(t *testing.T) {\n\t// Start an OTLP-compatible receiver.\n\tln, err := net.Listen(\"tcp\", \"localhost:\")\n\trequire.NoError(t, err, \"Failed to find an available address to run the gRPC server: %v\", err)\n\trcv := otlpLogsReceiverOnGRPCServer(ln)\n\t// Also closes the connection.\n\tdefer rcv.srv.GracefulStop()\n\n\t// Start an OTLP exporter and point to the receiver.\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\t// Disable queuing to ensure that we execute the request when calling ConsumeLogs\n\t// otherwise we will not see any errors.\n\tcfg.QueueConfig = configoptional.None[exporterhelper.QueueBatchConfig]()\n\tcfg.ClientConfig = configgrpc.ClientConfig{\n\t\tEndpoint: ln.Addr().String(),\n\t\tTLS: configtls.ClientConfig{\n\t\t\tInsecure: true,\n\t\t},\n\t}\n\tset := exportertest.NewNopSettings(factory.Type())\n\tset.BuildInfo.Description = \"Collector\"\n\tset.BuildInfo.Version = \"1.2.3test\"\n\n\t// For testing the \"Partial success\" warning.\n\tlogger, observed := observer.New(zap.DebugLevel)\n\tset.Logger = zap.New(logger)\n\n\texp, err := factory.CreateLogs(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, exp)\n\tdefer func() {\n\t\tassert.NoError(t, exp.Shutdown(context.Background()))\n\t}()\n\n\thost := componenttest.NewNopHost()\n\n\trequire.NoError(t, exp.Start(context.Background(), host))\n\n\t// Ensure that initially there is no data in the receiver.\n\tassert.EqualValues(t, 0, rcv.requestCount.Load())\n\n\t// Send empty request.\n\tld := plog.NewLogs()\n\trequire.NoError(t, exp.ConsumeLogs(context.Background(), ld))\n\n\t// Wait until it is received.\n\tassert.Eventually(t, func() bool {\n\t\treturn rcv.requestCount.Load() > 0\n\t}, 10*time.Second, 5*time.Millisecond)\n\n\t// Ensure it was received empty.\n\tassert.EqualValues(t, 0, rcv.totalItems.Load())\n\n\t// A request with 2 log entries.\n\tld = testdata.GenerateLogs(2)\n\n\terr = exp.ConsumeLogs(context.Background(), ld)\n\trequire.NoError(t, err)\n\n\t// Wait until it is received.\n\tassert.Eventually(t, func() bool {\n\t\treturn rcv.requestCount.Load() > 1\n\t}, 10*time.Second, 5*time.Millisecond)\n\n\t// Verify received logs.\n\tassert.EqualValues(t, 2, rcv.requestCount.Load())\n\tassert.EqualValues(t, 2, rcv.totalItems.Load())\n\tassert.Equal(t, ld, rcv.getLastRequest())\n\n\tmd := rcv.getMetadata()\n\trequire.Len(t, md.Get(\"User-Agent\"), 1)\n\trequire.Contains(t, md.Get(\"User-Agent\")[0], \"Collector/1.2.3test\")\n\n\tst := status.New(codes.InvalidArgument, \"Invalid argument\")\n\trcv.setExportError(st.Err())\n\n\t// A request with 2 log entries.\n\tld = testdata.GenerateLogs(2)\n\n\terr = exp.ConsumeLogs(context.Background(), ld)\n\trequire.Error(t, err)\n\n\trcv.setExportError(nil)\n\n\t// Return partial success\n\trcv.setExportResponse(func() plogotlp.ExportResponse {\n\t\tresponse := plogotlp.NewExportResponse()\n\t\tpartialSuccess := response.PartialSuccess()\n\t\tpartialSuccess.SetErrorMessage(\"Some log records were not ingested\")\n\t\tpartialSuccess.SetRejectedLogRecords(1)\n\n\t\treturn response\n\t})\n\n\t// A request with 2 log entries.\n\tld = testdata.GenerateLogs(2)\n\n\terr = exp.ConsumeLogs(context.Background(), ld)\n\trequire.NoError(t, err)\n\tassert.Len(t, observed.FilterLevelExact(zap.WarnLevel).All(), 1)\n\tassert.Contains(t, observed.FilterLevelExact(zap.WarnLevel).All()[0].Message, \"Partial success\")\n}\n\nfunc TestSendProfiles(t *testing.T) {\n\t// Start an OTLP-compatible receiver.\n\tln, err := net.Listen(\"tcp\", \"localhost:\")\n\trequire.NoError(t, err, \"Failed to find an available address to run the gRPC server: %v\", err)\n\trcv, _ := otlpProfilesReceiverOnGRPCServer(ln, false)\n\t// Also closes the connection.\n\tdefer rcv.srv.GracefulStop()\n\n\t// Start an OTLP exporter and point to the receiver.\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\t// Disable queuing to ensure that we execute the request when calling ConsumeProfiles\n\t// otherwise we will not see any errors.\n\tcfg.QueueConfig = configoptional.None[exporterhelper.QueueBatchConfig]()\n\tcfg.ClientConfig = configgrpc.ClientConfig{\n\t\tEndpoint: ln.Addr().String(),\n\t\tTLS: configtls.ClientConfig{\n\t\t\tInsecure: true,\n\t\t},\n\t\tHeaders: configopaque.MapList{\n\t\t\t{Name: \"header\", Value: \"header-value\"},\n\t\t},\n\t}\n\tset := exportertest.NewNopSettings(factory.Type())\n\tset.BuildInfo.Description = \"Collector\"\n\tset.BuildInfo.Version = \"1.2.3test\"\n\n\t// For testing the \"Partial success\" warning.\n\tlogger, observed := observer.New(zap.DebugLevel)\n\tset.Logger = zap.New(logger)\n\n\texp, err := factory.(xexporter.Factory).CreateProfiles(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, exp)\n\n\tdefer func() {\n\t\trequire.NoError(t, exp.Shutdown(context.Background()))\n\t}()\n\n\thost := componenttest.NewNopHost()\n\trequire.NoError(t, exp.Start(context.Background(), host))\n\n\t// Ensure that initially there is no data in the receiver.\n\tassert.EqualValues(t, 0, rcv.requestCount.Load())\n\n\t// Send empty profile.\n\ttd := pprofile.NewProfiles()\n\trequire.NoError(t, exp.ConsumeProfiles(context.Background(), td))\n\n\t// Wait until it is received.\n\tassert.Eventually(t, func() bool {\n\t\treturn rcv.requestCount.Load() > 0\n\t}, 10*time.Second, 5*time.Millisecond)\n\n\t// Ensure it was received empty.\n\tassert.EqualValues(t, 0, rcv.totalItems.Load())\n\n\t// A request with 2 profiles.\n\ttd = testdata.GenerateProfiles(2)\n\n\terr = exp.ConsumeProfiles(context.Background(), td)\n\trequire.NoError(t, err)\n\n\t// Wait until it is received.\n\tassert.Eventually(t, func() bool {\n\t\treturn rcv.requestCount.Load() > 1\n\t}, 10*time.Second, 5*time.Millisecond)\n\n\texpectedHeader := []string{\"header-value\"}\n\n\t// Verify received span.\n\tassert.EqualValues(t, 2, rcv.totalItems.Load())\n\tassert.EqualValues(t, 2, rcv.requestCount.Load())\n\tassert.Equal(t, td, rcv.getLastRequest())\n\n\tmd := rcv.getMetadata()\n\trequire.Equal(t, expectedHeader, md.Get(\"header\"))\n\trequire.Len(t, md.Get(\"User-Agent\"), 1)\n\trequire.Contains(t, md.Get(\"User-Agent\")[0], \"Collector/1.2.3test\")\n\n\t// Return partial success\n\trcv.setExportResponse(func() pprofileotlp.ExportResponse {\n\t\tresponse := pprofileotlp.NewExportResponse()\n\t\tpartialSuccess := response.PartialSuccess()\n\t\tpartialSuccess.SetErrorMessage(\"Some spans were not ingested\")\n\t\tpartialSuccess.SetRejectedProfiles(1)\n\n\t\treturn response\n\t})\n\n\t// A request with 2 Profile entries.\n\ttd = testdata.GenerateProfiles(2)\n\n\terr = exp.ConsumeProfiles(context.Background(), td)\n\trequire.NoError(t, err)\n\tassert.Len(t, observed.FilterLevelExact(zap.WarnLevel).All(), 1)\n\tassert.Contains(t, observed.FilterLevelExact(zap.WarnLevel).All()[0].Message, \"Partial success\")\n}\n\nfunc TestPushTracesBeforeStart(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tset := exportertest.NewNopSettings(factory.Type())\n\texp := newExporter(cfg, set)\n\terr := exp.pushTraces(context.Background(), ptrace.NewTraces())\n\trequire.Error(t, err)\n\tassert.Contains(t, err.Error(), \"not started\")\n}\n\nfunc TestPushMetricsBeforeStart(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tset := exportertest.NewNopSettings(factory.Type())\n\texp := newExporter(cfg, set)\n\terr := exp.pushMetrics(context.Background(), pmetric.NewMetrics())\n\trequire.Error(t, err)\n\tassert.Contains(t, err.Error(), \"not started\")\n}\n\nfunc TestPushLogsBeforeStart(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tset := exportertest.NewNopSettings(factory.Type())\n\texp := newExporter(cfg, set)\n\terr := exp.pushLogs(context.Background(), plog.NewLogs())\n\trequire.Error(t, err)\n\tassert.Contains(t, err.Error(), \"not started\")\n}\n\nfunc TestPushProfilesBeforeStart(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tset := exportertest.NewNopSettings(factory.Type())\n\texp := newExporter(cfg, set)\n\terr := exp.pushProfiles(context.Background(), pprofile.NewProfiles())\n\trequire.Error(t, err)\n\tassert.Contains(t, err.Error(), \"not started\")\n}\n\nfunc TestSendProfilesWhenEndpointHasHTTPScheme(t *testing.T) {\n\ttests := []struct {\n\t\tname               string\n\t\tuseTLS             bool\n\t\tscheme             string\n\t\tgRPCClientSettings configgrpc.ClientConfig\n\t}{\n\t\t{\n\t\t\tname:               \"Use https scheme\",\n\t\t\tuseTLS:             true,\n\t\t\tscheme:             \"https://\",\n\t\t\tgRPCClientSettings: configgrpc.ClientConfig{},\n\t\t},\n\t\t{\n\t\t\tname:   \"Use http scheme\",\n\t\t\tuseTLS: false,\n\t\t\tscheme: \"http://\",\n\t\t\tgRPCClientSettings: configgrpc.ClientConfig{\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tInsecure: true,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t// Start an OTLP-compatible receiver.\n\t\t\tln, err := net.Listen(\"tcp\", \"localhost:\")\n\t\t\trequire.NoError(t, err, \"Failed to find an available address to run the gRPC server: %v\", err)\n\t\t\trcv, err := otlpProfilesReceiverOnGRPCServer(ln, test.useTLS)\n\t\t\trequire.NoError(t, err, \"Failed to start mock OTLP receiver\")\n\t\t\t// Also closes the connection.\n\t\t\tdefer rcv.srv.GracefulStop()\n\n\t\t\t// Start an OTLP exporter and point to the receiver.\n\t\t\tfactory := NewFactory()\n\t\t\tcfg := factory.CreateDefaultConfig().(*Config)\n\t\t\tcfg.ClientConfig = test.gRPCClientSettings\n\t\t\tcfg.ClientConfig.Endpoint = test.scheme + ln.Addr().String()\n\t\t\tif test.useTLS {\n\t\t\t\tcfg.ClientConfig.TLS.InsecureSkipVerify = true\n\t\t\t}\n\t\t\tset := exportertest.NewNopSettings(factory.Type())\n\t\t\texp, err := factory.(xexporter.Factory).CreateProfiles(context.Background(), set, cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NotNil(t, exp)\n\n\t\t\tdefer func() {\n\t\t\t\trequire.NoError(t, exp.Shutdown(context.Background()))\n\t\t\t}()\n\n\t\t\thost := componenttest.NewNopHost()\n\t\t\trequire.NoError(t, exp.Start(context.Background(), host))\n\n\t\t\t// Ensure that initially there is no data in the receiver.\n\t\t\tassert.EqualValues(t, 0, rcv.requestCount.Load())\n\n\t\t\t// Send empty profile.\n\t\t\ttd := pprofile.NewProfiles()\n\t\t\trequire.NoError(t, exp.ConsumeProfiles(context.Background(), td))\n\n\t\t\t// Wait until it is received.\n\t\t\tassert.Eventually(t, func() bool {\n\t\t\t\treturn rcv.requestCount.Load() > 0\n\t\t\t}, 10*time.Second, 5*time.Millisecond)\n\n\t\t\t// Ensure it was received empty.\n\t\t\tassert.EqualValues(t, 0, rcv.totalItems.Load())\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "exporter/otlpexporter/testdata/config.yaml",
    "content": "endpoint: \"1.2.3.4:1234\"\ncompression: \"gzip\"\ntls:\n  ca_file: /var/lib/mycert.pem\ntimeout: 10s\nsending_queue:\n  enabled: true\n  sizer: \"items\"\n  num_consumers: 2\n  queue_size: 100000\n  batch:\n    flush_timeout: 200ms\n    min_size: 1000\n    max_size: 10000\nretry_on_failure:\n  enabled: true\n  initial_interval: 10s\n  randomization_factor: 0.7\n  multiplier: 1.3\n  max_interval: 60s\n  max_elapsed_time: 10m\nauth:\n  authenticator: nop\nheaders:\n  \"can you have a . here?\": \"F0000000-0000-0000-0000-000000000000\"\n  header1: \"234\"\n  another: \"somevalue\"\nkeepalive:\n  time: 20s\n  timeout: 30s\n  permit_without_stream: true\nbalancer_name: \"round_robin\"\n"
  },
  {
    "path": "exporter/otlpexporter/testdata/default-batch.yaml",
    "content": "endpoint: \"1.2.3.4:1234\"\ntimeout: 10s\nsending_queue:\n  batch:\n"
  },
  {
    "path": "exporter/otlpexporter/testdata/invalid_configs.yaml",
    "content": "no_endpoint:\n  timeout: 10s\n  sending_queue:\n    enabled: true\n    num_consumers: 2\n    queue_size: 10\n  retry_on_failure:\n    enabled: true\n    initial_interval: 10s\n    randomization_factor: 0.7\n    multiplier: 1.3\n    max_interval: 60s\n    max_elapsed_time: 10m\nhttps_endpoint:\n  endpoint: https://\nhttp_endpoint:\n  endpoint: http://\n  timeout: 10s\n  sending_queue:\n    enabled: true\n    num_consumers: 2\n    queue_size: 10\n  retry_on_failure:\n    enabled: true\n    initial_interval: 10s\n    randomization_factor: 0.7\n    multiplier: 1.3\n    max_interval: 60s\n    max_elapsed_time: 10m\ninvalid_timeout:\n  endpoint: example.com:443\n  timeout: -5s\n  sending_queue:\n    enabled: true\n    num_consumers: 2\n    queue_size: 10\n  retry_on_failure:\n    enabled: true\n    initial_interval: 10s\n    randomization_factor: 0.7\n    multiplier: 1.3\n    max_interval: 60s\n    max_elapsed_time: 10m\ninvalid_retry:\n  endpoint: example.com:443\n  timeout: 30s\n  sending_queue:\n    enabled: true\n    num_consumers: 2\n    queue_size: 10\n  retry_on_failure:\n    enabled: true\n    initial_interval: 10s\n    randomization_factor: -5\n    multiplier: 1.3\n    max_interval: 60s\n    max_elapsed_time: 10m\ninvalid_tls:\n  tls:\n    min_version: asd\n  endpoint: example.com:443\n  timeout: 10s\n  sending_queue:\n    enabled: true\n    num_consumers: 2\n    queue_size: 10\n  retry_on_failure:\n    enabled: true\n    initial_interval: 10s\n    randomization_factor: 0.7\n    multiplier: 1.3\n    max_interval: 60s\n    max_elapsed_time: 10m\nmissing_port:\n  endpoint: example.com\n  timeout: 10s\n  sending_queue:\n    enabled: true\n    num_consumers: 2\n    queue_size: 10\n  retry_on_failure:\n    enabled: true\n    initial_interval: 10s\n    randomization_factor: 0.7\n    multiplier: 1.3\n    max_interval: 60s\n    max_elapsed_time: 10m\ninvalid_port:\n  endpoint: example.com:port\n  timeout: 10s\n  sending_queue:\n    enabled: true\n    num_consumers: 2\n    queue_size: 10\n  retry_on_failure:\n    enabled: true\n    initial_interval: 10s\n    randomization_factor: 0.7\n    multiplier: 1.3\n    max_interval: 60s\n    max_elapsed_time: 10m\ninvalid_unix_socket:\n  endpoint: unix://\n  timeout: 10s\n  sending_queue:\n    enabled: true\n    num_consumers: 2\n    queue_size: 10\n  retry_on_failure:\n    enabled: true\n    initial_interval: 10s\n    randomization_factor: 0.7\n    multiplier: 1.3\n    max_interval: 60s\n    max_elapsed_time: 10m"
  },
  {
    "path": "exporter/otlpexporter/testdata/test_cert.pem",
    "content": "-----BEGIN CERTIFICATE-----\nMIICpDCCAYwCCQC5oaFsqLW3GTANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAls\nb2NhbGhvc3QwHhcNMjEwNzE0MDAxMzU2WhcNMzEwNzEyMDAxMzU2WjAUMRIwEAYD\nVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDO\nmKaE1qg5VLMwaUnSzufT23rRJFbuy/HDXwsH63yZVSsISQkGjkBYBgrqAMtVnsI/\nl4gXtBWkZtJFs68Sbo9ps3W0PdB5+d12R5NUNA1rkZtx3jtEN33dpGhifug/TIZe\n7Zr0G1z6gNoaEezk0Jpg4KsH7QpIeHPRhIZMyWeqddgD/qL4/ukaU4NOORuF3WoT\noo2LpI3jUq66mz2N2Inq0V/OX7BYB4Ur6EtjWh2baiUuw9fq+oLUlgZd6ypnugC/\n+YfgYqvWtRntmEr0Z+O4Kz81P2IpH/0h1RFhWyK6thVGa9cx6aseCp3V2cMXfGfc\nz4n3Uvz87v+bZvGbcse/AgMBAAEwDQYJKoZIhvcNAQELBQADggEBAAlvNBNoqXUQ\nohR0eozIHGeJ94U7WK5zXf2NSvmRlwHzHXvUq6GKd+8Bv1foMjI6OpSOZmjtRGsc\nrWET1WjSyQddRfqYazhWp1IyYu5LfATwPS+RXJAkWixKVfG+Ta2x6u+aT/bSZwEg\nNwRerc6pyqv5UG8Z7Pe1kAxbgOwZv5KXAewIgTSbEkmIp1Dg8GhGeWD5pjYNCkJV\nNa2KMAUWP3PeQzdSBKmBNpsRUALuSTxb5u7pl+PA7FLInTtDeyZn8xpO1GPBhbJE\ntrDbmTbj5YexOXEaQtGtZ6fwRw2jnUm8nqtXozxIomnVTBO8vLmZAUgyJ71trRw0\ngE9tH5Ndlug=\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "exporter/otlpexporter/testdata/test_key.pem",
    "content": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDOmKaE1qg5VLMw\naUnSzufT23rRJFbuy/HDXwsH63yZVSsISQkGjkBYBgrqAMtVnsI/l4gXtBWkZtJF\ns68Sbo9ps3W0PdB5+d12R5NUNA1rkZtx3jtEN33dpGhifug/TIZe7Zr0G1z6gNoa\nEezk0Jpg4KsH7QpIeHPRhIZMyWeqddgD/qL4/ukaU4NOORuF3WoToo2LpI3jUq66\nmz2N2Inq0V/OX7BYB4Ur6EtjWh2baiUuw9fq+oLUlgZd6ypnugC/+YfgYqvWtRnt\nmEr0Z+O4Kz81P2IpH/0h1RFhWyK6thVGa9cx6aseCp3V2cMXfGfcz4n3Uvz87v+b\nZvGbcse/AgMBAAECggEADeR39iDVKR3H+u5pl3JwZm+w35V4/w/ZzxB6FmtAcrMm\ndKUspTM1onWtkDTDd5t4ZnxTG3zxo5+Cbkt571xd6na16Ivrk/g4aza+8n+Zk200\nLcEK7ThqD1h56H2uMmt78bA6pkWcx/+YKv6flndsmi0hcyP+eAcZirJFsa4teWna\nP6rhI9zThc9OcecqGZIlmzJQ4cLbIO86QqkWW6yjKYg6riOb2g+i3e97ZngMCTcV\nlni+sksLlXBNKPqh1AkiUFe4pInRBh4LGQ5rNSYswEqlQY0iW0u4Hs3HNou0On+8\n1T8m5wzKQ+23AN+vVRJ/MHssQiB/TPK92jXVgEz6eQKBgQD2GEb7NzDIxsAQZBQo\ntt3jYitNcAEqMWeT7wxCMMue4wIrT6Fp6NuG5NMVqLglzx72m6TXg7YzZxPrAnlH\njblWI4sxwVC8BjjYyGud7qMuhUIZmI8aS9HuYW0ODSxkcpVVXd4HDUYKg7PafAkl\ncj745E5KGD+qW44KASTTQ1SwRQKBgQDW6WLp/nPVPO5YEK4nzS7b1RRC8ypHiKd6\nLzhA2izgcsmO3F3Y5ZZ5rzeFbjgZiGFTUB/r1mgomI8kZyIGP1AN6o8oY9I89gHY\n/DEEagIsFK5jAEoMeN0qbgqasOXpi+uUHCNidWa7OWOL9Rsh7dyVT54xcqMC2Qak\nVpoy5miiMwKBgQDuOHH9nF9M+5fQRhB9mQcRpWXlgBagkVKCkVR8fl+dXoIrCtpl\ne1OGMNtki/42G1kNv3zCYm1tNMrDI5HjAf32tFF5yHguipdcwiXqq6aq0bQ6ssNT\n4TFGYGkAwR/H3GNST5stmFvEsdjYFlmENiNfKyHd97spXZcReCn9l5/TQQKBgDRG\nPpYWG4zBrmPjYskxonU8ZhpG1YDi34Hb3H4B06qgoSBLv9QTPD/K++FLxv+G6c1/\nDtSpqVo+iYrcPy1v1wQbisjTRv8nA5oI9c9SDcc1HJneJyTTfVBlxdSMtM/TBfFX\nys+XKO7fbbRMYVYmamIzJJJ4hOgba/8rRYSeANN7AoGBAMDdrT+ig3aDMratbAvY\nlqsfN3AtxoZ+ZVQYyUbzTSZPZ/to9eNuBzhRKcQ3QfG95nrHb7OnWHa7+1kc4p/Q\njMgzJgRpajlES+F3CCMPgJIJg7Ev+yiSCJLP9ZOsC+E96bK265hUcDyCXwb3Wzmg\n4L9sc1QsQW80QO/RnaEzGO51\n-----END PRIVATE KEY-----\n"
  },
  {
    "path": "exporter/otlphttpexporter/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "exporter/otlphttpexporter/README.md",
    "content": "<!-- status autogenerated section -->\n# OTLP HTTP Exporter\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [alpha]: profiles   |\n|               | [stable]: traces, metrics, logs   |\n| Distributions | [core], [contrib], [k8s], [otlp] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Aexporter%2Fotlphttp%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Aexporter%2Fotlphttp) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Aexporter%2Fotlphttp%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Aexporter%2Fotlphttp) |\n\n[alpha]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#alpha\n[stable]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stable\n[core]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n[k8s]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\n[otlp]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-otlp\n<!-- end autogenerated section -->\n\nThe `otlp_http` exporter sends logs, metrics, profiles and traces via HTTP using [OTLP](\nhttps://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md)\nformat.\n\nThe `otlphttp` deprecated alias exists for the component name. It will be removed in a future version.\nIf you use the deprecated alias `otlphttp` in your configuration, change it to `otlp_http`.\n\nThe following settings are required:\n\n- `endpoint` (no default): The target base URL to send data to (e.g.: https://example.com:4318).\n  To send each signal a corresponding path will be added to this base URL, i.e. for traces\n  \"/v1/traces\" will appended, for metrics \"/v1/metrics\" will be appended, for logs\n  \"/v1/logs\" will be appended. \n\nThe following settings can be optionally configured:\n\n- `traces_endpoint` (no default): The target URL to send trace data to (e.g.: https://example.com:4318/v1/traces).\n   If this setting is present the `endpoint` setting is ignored for traces.\n- `metrics_endpoint` (no default): The target URL to send metric data to (e.g.: https://example.com:4318/v1/metrics).\n   If this setting is present the `endpoint` setting is ignored for metrics.\n- `logs_endpoint` (no default): The target URL to send log data to (e.g.: https://example.com:4318/v1/logs).\n- `profiles_endpoint` (no default): The target URL to send profile data to (e.g.: https://example.com:4318/v1development/profiles).\n   If this setting is present the `endpoint` setting is ignored for logs.\n- `tls`: see [TLS Configuration Settings](../../config/configtls/README.md) for the full set of available options.\n- `timeout` (default = 30s): HTTP request time limit. For details see https://golang.org/pkg/net/http/#Client\n- `read_buffer_size` (default = 0): ReadBufferSize for HTTP client.\n- `write_buffer_size` (default = 512 * 1024): WriteBufferSize for HTTP client.\n- `encoding` (default = proto): The encoding to use for the messages (valid options: `proto`, `json`)\n- `retry_on_failure`:  see [Retry on Failure](../exporterhelper/README.md#retry-on-failure) for the full set of available options.\n- `sending_queue`: see [Sending Queue](../exporterhelper/README.md#sending-queue) for the full set of available options.\n\nExample:\n\n```yaml\nexporters:\n  otlp_http:\n    endpoint: https://example.com:4318\n```\n\nBy default `gzip` compression is enabled. See [compression comparison](../../config/configgrpc/README.md#compression-comparison) for details benchmark information. To disable, configure as follows:\n\n```yaml\nexporters:\n  otlp_http:\n    ...\n    compression: none\n```\n\nBy default `proto` encoding is used, to change the content encoding of the message configure it as follows:\n\n```yaml\nexporters:\n  otlp_http:\n    ...\n    encoding: json\n```\n\nThe full list of settings exposed for this exporter are documented [here](./config.go)\nwith detailed sample configurations [here](./testdata/config.yaml).\n"
  },
  {
    "path": "exporter/otlphttpexporter/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlphttpexporter // import \"go.opentelemetry.io/collector/exporter/otlphttpexporter\"\n\nimport (\n\t\"encoding\"\n\t\"errors\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configretry\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n)\n\n// EncodingType defines the type for content encoding\ntype EncodingType string\n\nconst (\n\tEncodingProto EncodingType = \"proto\"\n\tEncodingJSON  EncodingType = \"json\"\n)\n\nvar _ encoding.TextUnmarshaler = (*EncodingType)(nil)\n\n// UnmarshalText unmarshalls text to an EncodingType.\nfunc (e *EncodingType) UnmarshalText(text []byte) error {\n\tif e == nil {\n\t\treturn errors.New(\"cannot unmarshal to a nil *EncodingType\")\n\t}\n\n\tstr := string(text)\n\tswitch str {\n\tcase string(EncodingProto):\n\t\t*e = EncodingProto\n\tcase string(EncodingJSON):\n\t\t*e = EncodingJSON\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid encoding type: %s\", str)\n\t}\n\n\treturn nil\n}\n\n// Config defines configuration for OTLP/HTTP exporter.\ntype Config struct {\n\tClientConfig confighttp.ClientConfig                                  `mapstructure:\",squash\"` // squash ensures fields are correctly decoded in embedded struct.\n\tQueueConfig  configoptional.Optional[exporterhelper.QueueBatchConfig] `mapstructure:\"sending_queue\"`\n\tRetryConfig  configretry.BackOffConfig                                `mapstructure:\"retry_on_failure\"`\n\n\t// The URL to send traces to. If omitted the Endpoint + \"/v1/traces\" will be used.\n\tTracesEndpoint string `mapstructure:\"traces_endpoint\"`\n\n\t// The URL to send metrics to. If omitted the Endpoint + \"/v1/metrics\" will be used.\n\tMetricsEndpoint string `mapstructure:\"metrics_endpoint\"`\n\n\t// The URL to send logs to. If omitted the Endpoint + \"/v1/logs\" will be used.\n\tLogsEndpoint string `mapstructure:\"logs_endpoint\"`\n\n\t// The URL to send profiles to. If omitted the Endpoint + \"/v1development/profiles\" will be used.\n\tProfilesEndpoint string `mapstructure:\"profiles_endpoint\"`\n\n\t// The encoding to export telemetry (default: \"proto\")\n\tEncoding EncodingType `mapstructure:\"encoding\"`\n}\n\nvar _ component.Config = (*Config)(nil)\n\n// Validate checks if the exporter configuration is valid\nfunc (cfg *Config) Validate() error {\n\tif cfg.ClientConfig.Endpoint == \"\" && cfg.TracesEndpoint == \"\" && cfg.MetricsEndpoint == \"\" && cfg.LogsEndpoint == \"\" && cfg.ProfilesEndpoint == \"\" {\n\t\treturn errors.New(\"at least one endpoint must be specified\")\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "exporter/otlphttpexporter/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlphttpexporter\n\nimport (\n\t\"net/http\"\n\t\"path/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configretry\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n)\n\nfunc TestUnmarshalDefaultConfig(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, confmap.New().Unmarshal(&cfg))\n\tassert.Equal(t, factory.CreateDefaultConfig(), cfg)\n\t// Default/Empty config is invalid.\n\tassert.Error(t, xconfmap.Validate(cfg))\n}\n\nfunc TestUnmarshalConfig(t *testing.T) {\n\tdefaultMaxIdleConns := http.DefaultTransport.(*http.Transport).MaxIdleConns\n\tdefaultMaxIdleConnsPerHost := http.DefaultTransport.(*http.Transport).MaxIdleConnsPerHost\n\tdefaultMaxConnsPerHost := http.DefaultTransport.(*http.Transport).MaxConnsPerHost\n\tdefaultIdleConnTimeout := http.DefaultTransport.(*http.Transport).IdleConnTimeout\n\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\tassert.Equal(t,\n\t\t&Config{\n\t\t\tRetryConfig: configretry.BackOffConfig{\n\t\t\t\tEnabled:             true,\n\t\t\t\tInitialInterval:     10 * time.Second,\n\t\t\t\tRandomizationFactor: 0.7,\n\t\t\t\tMultiplier:          1.3,\n\t\t\t\tMaxInterval:         1 * time.Minute,\n\t\t\t\tMaxElapsedTime:      10 * time.Minute,\n\t\t\t},\n\t\t\tQueueConfig: configoptional.Some(exporterhelper.QueueBatchConfig{\n\t\t\t\tSizer:        exporterhelper.RequestSizerTypeRequests,\n\t\t\t\tNumConsumers: 2,\n\t\t\t\tQueueSize:    10,\n\t\t\t\tBatch: configoptional.Default(exporterhelper.BatchConfig{\n\t\t\t\t\tSizer:        exporterhelper.RequestSizerTypeItems,\n\t\t\t\t\tFlushTimeout: 200 * time.Millisecond,\n\t\t\t\t\tMinSize:      8192,\n\t\t\t\t}),\n\t\t\t}),\n\t\t\tEncoding: EncodingProto,\n\t\t\tClientConfig: confighttp.ClientConfig{\n\t\t\t\tHeaders: configopaque.MapList{\n\t\t\t\t\t{Name: \"another\", Value: \"somevalue\"},\n\t\t\t\t\t{Name: \"can you have a . here?\", Value: \"F0000000-0000-0000-0000-000000000000\"},\n\t\t\t\t\t{Name: \"header1\", Value: \"234\"},\n\t\t\t\t},\n\t\t\t\tEndpoint: \"https://1.2.3.4:1234\",\n\t\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\tCAFile:   \"/var/lib/mycert.pem\",\n\t\t\t\t\t\tCertFile: \"certfile\",\n\t\t\t\t\t\tKeyFile:  \"keyfile\",\n\t\t\t\t\t},\n\t\t\t\t\tInsecure: true,\n\t\t\t\t},\n\t\t\t\tReadBufferSize:      123,\n\t\t\t\tWriteBufferSize:     345,\n\t\t\t\tTimeout:             time.Second * 10,\n\t\t\t\tCompression:         \"gzip\",\n\t\t\t\tMaxIdleConns:        defaultMaxIdleConns,\n\t\t\t\tMaxIdleConnsPerHost: defaultMaxIdleConnsPerHost,\n\t\t\t\tMaxConnsPerHost:     defaultMaxConnsPerHost,\n\t\t\t\tIdleConnTimeout:     defaultIdleConnTimeout,\n\t\t\t\tForceAttemptHTTP2:   true,\n\t\t\t},\n\t\t\tProfilesEndpoint: \"https://custom.profiles.endpoint:8080/v1development/profiles\",\n\t\t}, cfg)\n}\n\nfunc TestUnmarshalConfigInvalidEncoding(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"bad_invalid_encoding.yaml\"))\n\trequire.NoError(t, err)\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tassert.Error(t, cm.Unmarshal(&cfg))\n}\n\nfunc TestUnmarshalEncoding(t *testing.T) {\n\ttests := []struct {\n\t\tname          string\n\t\tencodingBytes []byte\n\t\texpected      EncodingType\n\t\tshouldError   bool\n\t}{\n\t\t{\n\t\t\tname:          \"UnmarshalEncodingProto\",\n\t\t\tencodingBytes: []byte(\"proto\"),\n\t\t\texpected:      EncodingProto,\n\t\t\tshouldError:   false,\n\t\t},\n\t\t{\n\t\t\tname:          \"UnmarshalEncodingJson\",\n\t\t\tencodingBytes: []byte(\"json\"),\n\t\t\texpected:      EncodingJSON,\n\t\t\tshouldError:   false,\n\t\t},\n\t\t{\n\t\t\tname:          \"UnmarshalEmptyEncoding\",\n\t\t\tencodingBytes: []byte(\"\"),\n\t\t\tshouldError:   true,\n\t\t},\n\t\t{\n\t\t\tname:          \"UnmarshalInvalidEncoding\",\n\t\t\tencodingBytes: []byte(\"invalid\"),\n\t\t\tshouldError:   true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvar encoding EncodingType\n\t\t\terr := encoding.UnmarshalText(tt.encodingBytes)\n\n\t\t\tif tt.shouldError {\n\t\t\t\tassert.Error(t, err)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.Equal(t, tt.expected, encoding)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestConfigValidate(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tcfg     *Config\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname: \"no endpoints specified\",\n\t\t\tcfg: &Config{\n\t\t\t\tClientConfig: confighttp.ClientConfig{},\n\t\t\t},\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname: \"main endpoint specified\",\n\t\t\tcfg: &Config{\n\t\t\t\tClientConfig: confighttp.ClientConfig{\n\t\t\t\t\tEndpoint: \"http://localhost:4318\",\n\t\t\t\t},\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"only traces endpoint specified\",\n\t\t\tcfg: &Config{\n\t\t\t\tClientConfig:   confighttp.ClientConfig{},\n\t\t\t\tTracesEndpoint: \"http://localhost:4318/v1/traces\",\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"only profiles endpoint specified\",\n\t\t\tcfg: &Config{\n\t\t\t\tClientConfig:     confighttp.ClientConfig{},\n\t\t\t\tProfilesEndpoint: \"http://localhost:4318/v1development/profiles\",\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t\t{\n\t\t\tname: \"multiple endpoints specified\",\n\t\t\tcfg: &Config{\n\t\t\t\tClientConfig:     confighttp.ClientConfig{},\n\t\t\t\tTracesEndpoint:   \"http://localhost:4318/v1/traces\",\n\t\t\t\tMetricsEndpoint:  \"http://localhost:4318/v1/metrics\",\n\t\t\t\tLogsEndpoint:     \"http://localhost:4318/v1/logs\",\n\t\t\t\tProfilesEndpoint: \"http://localhost:4318/v1development/profiles\",\n\t\t\t},\n\t\t\twantErr: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := tt.cfg.Validate()\n\t\t\tif tt.wantErr {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\tassert.Contains(t, err.Error(), \"at least one endpoint must be specified\")\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "exporter/otlphttpexporter/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\n// Package otlphttpexporter exports data by using the OTLP format to an HTTP endpoint.\npackage otlphttpexporter // import \"go.opentelemetry.io/collector/exporter/otlphttpexporter\"\n"
  },
  {
    "path": "exporter/otlphttpexporter/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlphttpexporter // import \"go.opentelemetry.io/collector/exporter/otlphttpexporter\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net/url\"\n\t\"strings\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configcompression\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configretry\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/otlphttpexporter/internal/metadata\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n)\n\n// NewFactory creates a factory for OTLP exporter.\nfunc NewFactory() exporter.Factory {\n\treturn xexporter.NewFactory(\n\t\tmetadata.Type,\n\t\tcreateDefaultConfig,\n\t\txexporter.WithDeprecatedTypeAlias(metadata.DeprecatedType),\n\t\txexporter.WithTraces(createTraces, metadata.TracesStability),\n\t\txexporter.WithMetrics(createMetrics, metadata.MetricsStability),\n\t\txexporter.WithLogs(createLogs, metadata.LogsStability),\n\t\txexporter.WithProfiles(createProfiles, metadata.ProfilesStability),\n\t)\n}\n\nfunc createDefaultConfig() component.Config {\n\tclientConfig := confighttp.NewDefaultClientConfig()\n\tclientConfig.Timeout = 30 * time.Second\n\t// Default to gzip compression\n\tclientConfig.Compression = configcompression.TypeGzip\n\t// We almost read 0 bytes, so no need to tune ReadBufferSize.\n\tclientConfig.WriteBufferSize = 512 * 1024\n\n\treturn &Config{\n\t\tRetryConfig:  configretry.NewDefaultBackOffConfig(),\n\t\tQueueConfig:  configoptional.Some(exporterhelper.NewDefaultQueueConfig()),\n\t\tEncoding:     EncodingProto,\n\t\tClientConfig: clientConfig,\n\t}\n}\n\n// composeSignalURL composes the final URL for the signal (traces, metrics, logs) based on the configuration.\n// oCfg is the configuration of the exporter.\n// signalOverrideURL is the URL specified in the signal specific configuration (empty if not specified).\n// signalName is the name of the signal, e.g. \"traces\", \"metrics\", \"logs\".\n// signalVersion is the version of the signal, e.g. \"v1\" or \"v1development\".\nfunc composeSignalURL(oCfg *Config, signalOverrideURL, signalName, signalVersion string) (string, error) {\n\tswitch {\n\tcase signalOverrideURL != \"\":\n\t\t_, err := url.Parse(signalOverrideURL)\n\t\tif err != nil {\n\t\t\treturn \"\", fmt.Errorf(\"%s_endpoint must be a valid URL\", signalName)\n\t\t}\n\t\treturn signalOverrideURL, nil\n\tcase oCfg.ClientConfig.Endpoint == \"\":\n\t\treturn \"\", fmt.Errorf(\"either endpoint or %s_endpoint must be specified\", signalName)\n\tdefault:\n\t\tif strings.HasSuffix(oCfg.ClientConfig.Endpoint, \"/\") {\n\t\t\treturn oCfg.ClientConfig.Endpoint + signalVersion + \"/\" + signalName, nil\n\t\t}\n\t\treturn oCfg.ClientConfig.Endpoint + \"/\" + signalVersion + \"/\" + signalName, nil\n\t}\n}\n\nfunc createTraces(\n\tctx context.Context,\n\tset exporter.Settings,\n\tcfg component.Config,\n) (exporter.Traces, error) {\n\toce, err := newExporter(cfg, set)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toCfg := cfg.(*Config)\n\n\toce.tracesURL, err = composeSignalURL(oCfg, oCfg.TracesEndpoint, \"traces\", \"v1\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn exporterhelper.NewTraces(ctx, set, cfg,\n\t\toce.pushTraces,\n\t\texporterhelper.WithStart(oce.start),\n\t\texporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),\n\t\t// explicitly disable since we rely on http.Client timeout logic.\n\t\texporterhelper.WithTimeout(exporterhelper.TimeoutConfig{Timeout: 0}),\n\t\texporterhelper.WithRetry(oCfg.RetryConfig),\n\t\texporterhelper.WithQueue(oCfg.QueueConfig))\n}\n\nfunc createMetrics(\n\tctx context.Context,\n\tset exporter.Settings,\n\tcfg component.Config,\n) (exporter.Metrics, error) {\n\toce, err := newExporter(cfg, set)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toCfg := cfg.(*Config)\n\n\toce.metricsURL, err = composeSignalURL(oCfg, oCfg.MetricsEndpoint, \"metrics\", \"v1\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn exporterhelper.NewMetrics(ctx, set, cfg,\n\t\toce.pushMetrics,\n\t\texporterhelper.WithStart(oce.start),\n\t\texporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),\n\t\t// explicitly disable since we rely on http.Client timeout logic.\n\t\texporterhelper.WithTimeout(exporterhelper.TimeoutConfig{Timeout: 0}),\n\t\texporterhelper.WithRetry(oCfg.RetryConfig),\n\t\texporterhelper.WithQueue(oCfg.QueueConfig))\n}\n\nfunc createLogs(\n\tctx context.Context,\n\tset exporter.Settings,\n\tcfg component.Config,\n) (exporter.Logs, error) {\n\toce, err := newExporter(cfg, set)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toCfg := cfg.(*Config)\n\toce.logsURL, err = composeSignalURL(oCfg, oCfg.LogsEndpoint, \"logs\", \"v1\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn exporterhelper.NewLogs(ctx, set, cfg,\n\t\toce.pushLogs,\n\t\texporterhelper.WithStart(oce.start),\n\t\texporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),\n\t\t// explicitly disable since we rely on http.Client timeout logic.\n\t\texporterhelper.WithTimeout(exporterhelper.TimeoutConfig{Timeout: 0}),\n\t\texporterhelper.WithRetry(oCfg.RetryConfig),\n\t\texporterhelper.WithQueue(oCfg.QueueConfig))\n}\n\nfunc createProfiles(\n\tctx context.Context,\n\tset exporter.Settings,\n\tcfg component.Config,\n) (xexporter.Profiles, error) {\n\toce, err := newExporter(cfg, set)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\toCfg := cfg.(*Config)\n\n\toce.profilesURL, err = composeSignalURL(oCfg, oCfg.ProfilesEndpoint, \"profiles\", \"v1development\")\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn xexporterhelper.NewProfiles(ctx, set, cfg,\n\t\toce.pushProfiles,\n\t\texporterhelper.WithStart(oce.start),\n\t\texporterhelper.WithCapabilities(consumer.Capabilities{MutatesData: false}),\n\t\t// explicitly disable since we rely on http.Client timeout logic.\n\t\texporterhelper.WithTimeout(exporterhelper.TimeoutConfig{Timeout: 0}),\n\t\texporterhelper.WithRetry(oCfg.RetryConfig),\n\t\texporterhelper.WithQueue(oCfg.QueueConfig))\n}\n"
  },
  {
    "path": "exporter/otlphttpexporter/factory_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlphttpexporter\n\nimport (\n\t\"context\"\n\t\"path/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configcompression\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc TestCreateDefaultConfig(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tassert.NotNil(t, cfg, \"failed to create default config\")\n\trequire.NoError(t, componenttest.CheckConfigStruct(cfg))\n\tocfg, ok := factory.CreateDefaultConfig().(*Config)\n\tassert.True(t, ok)\n\tassert.Empty(t, ocfg.ClientConfig.Endpoint)\n\tassert.Equal(t, 30*time.Second, ocfg.ClientConfig.Timeout, \"default timeout is 30 second\")\n\tassert.True(t, ocfg.RetryConfig.Enabled, \"default retry is enabled\")\n\tassert.Equal(t, 300*time.Second, ocfg.RetryConfig.MaxElapsedTime, \"default retry MaxElapsedTime\")\n\tassert.Equal(t, 5*time.Second, ocfg.RetryConfig.InitialInterval, \"default retry InitialInterval\")\n\tassert.Equal(t, 30*time.Second, ocfg.RetryConfig.MaxInterval, \"default retry MaxInterval\")\n\tassert.True(t, ocfg.QueueConfig.HasValue(), \"default sending queue is enabled\")\n\tassert.Equal(t, EncodingProto, ocfg.Encoding)\n\tassert.Equal(t, configcompression.TypeGzip, ocfg.ClientConfig.Compression)\n}\n\nfunc TestCreateMetrics(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.ClientConfig.Endpoint = \"http://\" + testutil.GetAvailableLocalAddress(t)\n\n\tset := exportertest.NewNopSettings(factory.Type())\n\toexp, err := factory.CreateMetrics(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, oexp)\n}\n\nfunc clientConfig(endpoint string, headers configopaque.MapList, tlsSetting configtls.ClientConfig, compression configcompression.Type) confighttp.ClientConfig {\n\tclientConfig := confighttp.NewDefaultClientConfig()\n\tclientConfig.TLS = tlsSetting\n\tclientConfig.Compression = compression\n\tif endpoint != \"\" {\n\t\tclientConfig.Endpoint = endpoint\n\t}\n\tif headers != nil {\n\t\tclientConfig.Headers = headers\n\t}\n\treturn clientConfig\n}\n\nfunc TestCreateTraces(t *testing.T) {\n\tvar configCompression configcompression.Type\n\tendpoint := \"http://\" + testutil.GetAvailableLocalAddress(t)\n\n\ttests := []struct {\n\t\tname             string\n\t\tconfig           *Config\n\t\tmustFailOnCreate bool\n\t\tmustFailOnStart  bool\n\t}{\n\t\t{\n\t\t\tname: \"NoEndpoint\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: clientConfig(\"\", nil, configtls.ClientConfig{}, configCompression),\n\t\t\t},\n\t\t\tmustFailOnCreate: true,\n\t\t},\n\t\t{\n\t\t\tname: \"UseSecure\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: clientConfig(endpoint, nil, configtls.ClientConfig{\n\t\t\t\t\tInsecure: false,\n\t\t\t\t}, configCompression),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Headers\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: clientConfig(endpoint, configopaque.MapList{\n\t\t\t\t\t{Name: \"hdr1\", Value: \"val1\"},\n\t\t\t\t\t{Name: \"hdr2\", Value: \"val2\"},\n\t\t\t\t}, configtls.ClientConfig{}, configCompression),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"CaCert\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: clientConfig(endpoint, nil, configtls.ClientConfig{\n\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\tCAFile: filepath.Join(\"testdata\", \"test_cert.pem\"),\n\t\t\t\t\t},\n\t\t\t\t}, configCompression),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"CertPemFileError\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: clientConfig(endpoint, nil, configtls.ClientConfig{\n\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\tCAFile: \"nosuchfile\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\tconfigCompression),\n\t\t\t},\n\t\t\tmustFailOnCreate: false,\n\t\t\tmustFailOnStart:  true,\n\t\t},\n\t\t{\n\t\t\tname: \"NoneCompression\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: clientConfig(endpoint, nil, configtls.ClientConfig{}, \"none\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"GzipCompression\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: clientConfig(endpoint, nil, configtls.ClientConfig{}, configcompression.TypeGzip),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"SnappyCompression\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: clientConfig(endpoint, nil, configtls.ClientConfig{}, configcompression.TypeSnappy),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"ZstdCompression\",\n\t\t\tconfig: &Config{\n\t\t\t\tClientConfig: clientConfig(endpoint, nil, configtls.ClientConfig{}, configcompression.TypeZstd),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"ProtoEncoding\",\n\t\t\tconfig: &Config{\n\t\t\t\tEncoding:     EncodingProto,\n\t\t\t\tClientConfig: clientConfig(endpoint, nil, configtls.ClientConfig{}, configCompression),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"JSONEncoding\",\n\t\t\tconfig: &Config{\n\t\t\t\tEncoding:     EncodingJSON,\n\t\t\t\tClientConfig: clientConfig(endpoint, nil, configtls.ClientConfig{}, configCompression),\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tfactory := NewFactory()\n\t\t\tset := exportertest.NewNopSettings(factory.Type())\n\t\t\tconsumer, err := factory.CreateTraces(context.Background(), set, tt.config)\n\n\t\t\tif tt.mustFailOnCreate {\n\t\t\t\tassert.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.NotNil(t, consumer)\n\t\t\terr = consumer.Start(context.Background(), componenttest.NewNopHost())\n\t\t\tif tt.mustFailOnStart {\n\t\t\t\trequire.Error(t, err)\n\t\t\t}\n\n\t\t\terr = consumer.Shutdown(context.Background())\n\t\t\tif err != nil {\n\t\t\t\t// Since the endpoint of OTLP exporter doesn't actually exist,\n\t\t\t\t// exporter may already stop because it cannot connect.\n\t\t\t\tassert.Equal(t, \"rpc error: code = Canceled desc = grpc: the client connection is closing\", err.Error())\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCreateLogs(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.ClientConfig.Endpoint = \"http://\" + testutil.GetAvailableLocalAddress(t)\n\n\tset := exportertest.NewNopSettings(factory.Type())\n\toexp, err := factory.CreateLogs(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, oexp)\n}\n\nfunc TestCreateProfiles(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.ClientConfig.Endpoint = \"http://\" + testutil.GetAvailableLocalAddress(t)\n\n\tset := exportertest.NewNopSettings(factory.Type())\n\toexp, err := factory.(xexporter.Factory).CreateProfiles(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, oexp)\n}\n\nfunc TestCreateProfilesWithCustomEndpoint(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.ProfilesEndpoint = \"http://\" + testutil.GetAvailableLocalAddress(t) + \"/custom/profiles\"\n\n\tset := exportertest.NewNopSettings(factory.Type())\n\toexp, err := factory.(xexporter.Factory).CreateProfiles(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, oexp)\n}\n\nfunc TestComposeSignalURL(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\n\t// Has slash at end\n\tcfg.ClientConfig.Endpoint = \"http://localhost:4318/\"\n\turl, err := composeSignalURL(cfg, \"\", \"traces\", \"v1\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"http://localhost:4318/v1/traces\", url)\n\n\t// No slash at end\n\tcfg.ClientConfig.Endpoint = \"http://localhost:4318\"\n\turl, err = composeSignalURL(cfg, \"\", \"traces\", \"v1\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"http://localhost:4318/v1/traces\", url)\n\n\t// Different version\n\tcfg.ClientConfig.Endpoint = \"http://localhost:4318\"\n\turl, err = composeSignalURL(cfg, \"\", \"traces\", \"v2\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"http://localhost:4318/v2/traces\", url)\n\n\t// Test profiles endpoint with v1development\n\tcfg.ClientConfig.Endpoint = \"http://localhost:4318\"\n\turl, err = composeSignalURL(cfg, \"\", \"profiles\", \"v1development\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"http://localhost:4318/v1development/profiles\", url)\n\n\t// Test with custom profiles endpoint override\n\tcfg.ClientConfig.Endpoint = \"http://localhost:4318\"\n\turl, err = composeSignalURL(cfg, \"http://custom:9090/profiles\", \"profiles\", \"v1development\")\n\trequire.NoError(t, err)\n\tassert.Equal(t, \"http://custom:9090/profiles\", url)\n}\n"
  },
  {
    "path": "exporter/otlphttpexporter/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage otlphttpexporter\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nvar typ = component.MustNewType(\"otlp_http\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct {\n\t\tcreateFn func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error)\n\t\tname     string\n\t}{\n\n\t\t{\n\t\t\tname: \"logs\",\n\t\t\tcreateFn: func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateLogs(ctx, set, cfg)\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg)\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"traces\",\n\t\t\tcreateFn: func(ctx context.Context, set exporter.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateTraces(ctx, set, cfg)\n\t\t\t},\n\t\t},\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name+\"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), exportertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\tt.Run(tt.name+\"-lifecycle\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), exportertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := newMdatagenNopHost()\n\t\t\terr = c.Start(context.Background(), host)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NotPanics(t, func() {\n\t\t\t\tswitch tt.name {\n\t\t\t\tcase \"logs\":\n\t\t\t\t\te, ok := c.(exporter.Logs)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tlogs := generateLifecycleTestLogs()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tlogs.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeLogs(context.Background(), logs)\n\t\t\t\tcase \"metrics\":\n\t\t\t\t\te, ok := c.(exporter.Metrics)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tmetrics := generateLifecycleTestMetrics()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tmetrics.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeMetrics(context.Background(), metrics)\n\t\t\t\tcase \"traces\":\n\t\t\t\t\te, ok := c.(exporter.Traces)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\ttraces := generateLifecycleTestTraces()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\ttraces.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeTraces(context.Background(), traces)\n\t\t\t\t}\n\t\t\t})\n\n\t\t\trequire.NoError(t, err)\n\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t}\n}\n\nfunc generateLifecycleTestLogs() plog.Logs {\n\tlogs := plog.NewLogs()\n\trl := logs.ResourceLogs().AppendEmpty()\n\trl.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tl := rl.ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\tl.Body().SetStr(\"test log message\")\n\tl.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn logs\n}\n\nfunc generateLifecycleTestMetrics() pmetric.Metrics {\n\tmetrics := pmetric.NewMetrics()\n\trm := metrics.ResourceMetrics().AppendEmpty()\n\trm.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tm := rm.ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\tm.SetName(\"test_metric\")\n\tdp := m.SetEmptyGauge().DataPoints().AppendEmpty()\n\tdp.Attributes().PutStr(\"test_attr\", \"value_1\")\n\tdp.SetIntValue(123)\n\tdp.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn metrics\n}\n\nfunc generateLifecycleTestTraces() ptrace.Traces {\n\ttraces := ptrace.NewTraces()\n\trs := traces.ResourceSpans().AppendEmpty()\n\trs.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tspan := rs.ScopeSpans().AppendEmpty().Spans().AppendEmpty()\n\tspan.Attributes().PutStr(\"test_attr\", \"value_1\")\n\tspan.SetName(\"test_span\")\n\tspan.SetStartTimestamp(pcommon.NewTimestampFromTime(time.Now().Add(-1 * time.Second)))\n\tspan.SetEndTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn traces\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "exporter/otlphttpexporter/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage otlphttpexporter\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "exporter/otlphttpexporter/go.mod",
    "content": "module go.opentelemetry.io/collector/exporter/otlphttpexporter\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector v0.148.0\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/config/configcompression v1.54.0\n\tgo.opentelemetry.io/collector/config/confighttp v0.148.0\n\tgo.opentelemetry.io/collector/config/configopaque v1.54.0\n\tgo.opentelemetry.io/collector/config/configoptional v1.54.0\n\tgo.opentelemetry.io/collector/config/configretry v1.54.0\n\tgo.opentelemetry.io/collector/config/configtls v1.54.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0\n\tgo.opentelemetry.io/collector/exporter v1.54.0\n\tgo.opentelemetry.io/collector/exporter/exporterhelper v0.148.0\n\tgo.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper v0.148.0\n\tgo.opentelemetry.io/collector/exporter/exportertest v0.148.0\n\tgo.opentelemetry.io/collector/exporter/xexporter v0.148.0\n\tgo.opentelemetry.io/collector/internal/testutil v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/zap v1.27.1\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b\n\tgoogle.golang.org/grpc v1.79.3\n\tgoogle.golang.org/protobuf v1.36.11\n)\n\nrequire (\n\tgithub.com/cenkalti/backoff/v5 v5.0.3 // indirect\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/felixge/httpsnoop v1.0.4 // indirect\n\tgithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f // indirect\n\tgithub.com/fsnotify/fsnotify v1.9.0 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/golang/snappy v1.0.0 // indirect\n\tgithub.com/google/go-tpm v0.9.8 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/hashicorp/golang-lru/v2 v2.0.7 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/klauspost/compress v1.18.4 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pierrec/lz4/v4 v4.1.26 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/rs/cors v1.11.1 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/client v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configauth v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configmiddleware v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/confignet v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumererror/xconsumererror v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionauth v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionmiddleware v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension/xextension v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/xpdata v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/receivertest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0 // indirect\n\tgo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/crypto v0.48.0 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector => ../../\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/config/configauth => ../../config/configauth\n\nreplace go.opentelemetry.io/collector/config/configcompression => ../../config/configcompression\n\nreplace go.opentelemetry.io/collector/config/confighttp => ../../config/confighttp\n\nreplace go.opentelemetry.io/collector/config/configopaque => ../../config/configopaque\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../../config/configoptional\n\nreplace go.opentelemetry.io/collector/config/configtls => ../../config/configtls\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/exporter => ../\n\nreplace go.opentelemetry.io/collector/extension => ../../extension\n\nreplace go.opentelemetry.io/collector/extension/extensionauth => ../../extension/extensionauth\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/receiver => ../../receiver\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/config/configretry => ../../config/configretry\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/client => ../../client\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../../receiver/receivertest\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/consumer/consumererror/xconsumererror => ../../consumer/consumererror/xconsumererror\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper => ../exporterhelper/xexporterhelper\n\nreplace go.opentelemetry.io/collector/exporter/xexporter => ../xexporter\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nretract (\n\tv0.76.0 // Depends on retracted pdata v1.0.0-rc10 module, use v0.76.1\n\tv0.69.0 // Release failed, use v0.69.1\n)\n\nreplace go.opentelemetry.io/collector/exporter/exportertest => ../exportertest\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../../extension/extensiontest\n\nreplace go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest => ../../extension/extensionauth/extensionauthtest\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/extension/xextension => ../../extension/xextension\n\nreplace go.opentelemetry.io/collector/config/configmiddleware => ../../config/configmiddleware\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ../../extension/extensionmiddleware\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest => ../../extension/extensionmiddleware/extensionmiddlewaretest\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper => ../exporterhelper\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n\nreplace go.opentelemetry.io/collector/config/confignet => ../../config/confignet\n"
  },
  {
    "path": "exporter/otlphttpexporter/go.sum",
    "content": "github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=\ngithub.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=\ngithub.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f h1:RJ+BDPLSHQO7cSjKBqjPJSbi1qfk9WcsjQDtZiw3dZw=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f/go.mod h1:VHbbch/X4roIY22jL1s3qRbZhCiRIgUAF/PdSUcx2io=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=\ngithub.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=\ngithub.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=\ngithub.com/google/go-tpm-tools v0.4.7 h1:J3ycC8umYxM9A4eF73EofRZu4BxY0jjQnUnkhIBbvws=\ngithub.com/google/go-tpm-tools v0.4.7/go.mod h1:gSyXTZHe3fgbzb6WEGd90QucmsnT1SRdlye82gH8QjQ=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=\ngithub.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=\ngithub.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=\ngithub.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=\ngolang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=\ngonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "exporter/otlphttpexporter/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType           = component.MustNewType(\"otlp_http\")\n\tDeprecatedType = component.MustNewType(\"otlphttp\")\n\tScopeName      = \"go.opentelemetry.io/collector/exporter/otlphttpexporter\"\n)\n\nconst (\n\tProfilesStability = component.StabilityLevelAlpha\n\tTracesStability   = component.StabilityLevelStable\n\tMetricsStability  = component.StabilityLevelStable\n\tLogsStability     = component.StabilityLevelStable\n)\n"
  },
  {
    "path": "exporter/otlphttpexporter/metadata.yaml",
    "content": "display_name: OTLP HTTP Exporter\ntype: otlp_http\ndeprecated_type: otlphttp\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: exporter\n  stability:\n    stable: [traces, metrics, logs]\n    alpha: [profiles]\n  distributions: [core, contrib, k8s, otlp]\n\ntests:\n  config:\n    # use an endpoint that does not resolve, to ensure\n    # connection attempts fail quickly in tests\n    endpoint: \"https://testing.invalid:1234\"\n"
  },
  {
    "path": "exporter/otlphttpexporter/otlp.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlphttpexporter // import \"go.opentelemetry.io/collector/exporter/otlphttpexporter\"\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/url\"\n\t\"runtime\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"go.uber.org/zap\"\n\t\"google.golang.org/genproto/googleapis/rpc/status\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/internal/statusutil\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/plog/plogotlp\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n)\n\ntype baseExporter struct {\n\t// Input configuration.\n\tconfig      *Config\n\tclient      *http.Client\n\ttracesURL   string\n\tmetricsURL  string\n\tlogsURL     string\n\tprofilesURL string\n\tlogger      *zap.Logger\n\tsettings    component.TelemetrySettings\n\t// Default user-agent header.\n\tuserAgent string\n}\n\nconst (\n\theaderRetryAfter         = \"Retry-After\"\n\tmaxHTTPResponseReadBytes = 64 * 1024\n\n\tjsonContentType     = \"application/json\"\n\tprotobufContentType = \"application/x-protobuf\"\n)\n\n// Create new exporter.\nfunc newExporter(cfg component.Config, set exporter.Settings) (*baseExporter, error) {\n\toCfg := cfg.(*Config)\n\n\tif oCfg.ClientConfig.Endpoint != \"\" {\n\t\t_, err := url.Parse(oCfg.ClientConfig.Endpoint)\n\t\tif err != nil {\n\t\t\treturn nil, errors.New(\"endpoint must be a valid URL\")\n\t\t}\n\t}\n\n\tuserAgent := fmt.Sprintf(\"%s/%s (%s/%s)\",\n\t\tset.BuildInfo.Description, set.BuildInfo.Version, runtime.GOOS, runtime.GOARCH)\n\n\t// client construction is deferred to start\n\treturn &baseExporter{\n\t\tconfig:    oCfg,\n\t\tlogger:    set.Logger,\n\t\tuserAgent: userAgent,\n\t\tsettings:  set.TelemetrySettings,\n\t}, nil\n}\n\n// start actually creates the HTTP client. The client construction is deferred till this point as this\n// is the only place we get hold of Extensions which are required to construct auth round tripper.\nfunc (e *baseExporter) start(ctx context.Context, host component.Host) error {\n\tclient, err := e.config.ClientConfig.ToClient(ctx, host.GetExtensions(), e.settings)\n\tif err != nil {\n\t\treturn err\n\t}\n\te.client = client\n\treturn nil\n}\n\nfunc (e *baseExporter) pushTraces(ctx context.Context, td ptrace.Traces) error {\n\ttr := ptraceotlp.NewExportRequestFromTraces(td)\n\n\tvar err error\n\tvar request []byte\n\tswitch e.config.Encoding {\n\tcase EncodingJSON:\n\t\trequest, err = tr.MarshalJSON()\n\tcase EncodingProto:\n\t\trequest, err = tr.MarshalProto()\n\tdefault:\n\t\terr = fmt.Errorf(\"invalid encoding: %s\", e.config.Encoding)\n\t}\n\n\tif err != nil {\n\t\treturn consumererror.NewPermanent(err)\n\t}\n\n\treturn e.export(ctx, e.tracesURL, request, e.tracesPartialSuccessHandler)\n}\n\nfunc (e *baseExporter) pushMetrics(ctx context.Context, md pmetric.Metrics) error {\n\ttr := pmetricotlp.NewExportRequestFromMetrics(md)\n\n\tvar err error\n\tvar request []byte\n\tswitch e.config.Encoding {\n\tcase EncodingJSON:\n\t\trequest, err = tr.MarshalJSON()\n\tcase EncodingProto:\n\t\trequest, err = tr.MarshalProto()\n\tdefault:\n\t\terr = fmt.Errorf(\"invalid encoding: %s\", e.config.Encoding)\n\t}\n\n\tif err != nil {\n\t\treturn consumererror.NewPermanent(err)\n\t}\n\treturn e.export(ctx, e.metricsURL, request, e.metricsPartialSuccessHandler)\n}\n\nfunc (e *baseExporter) pushLogs(ctx context.Context, ld plog.Logs) error {\n\ttr := plogotlp.NewExportRequestFromLogs(ld)\n\n\tvar err error\n\tvar request []byte\n\tswitch e.config.Encoding {\n\tcase EncodingJSON:\n\t\trequest, err = tr.MarshalJSON()\n\tcase EncodingProto:\n\t\trequest, err = tr.MarshalProto()\n\tdefault:\n\t\terr = fmt.Errorf(\"invalid encoding: %s\", e.config.Encoding)\n\t}\n\n\tif err != nil {\n\t\treturn consumererror.NewPermanent(err)\n\t}\n\n\treturn e.export(ctx, e.logsURL, request, e.logsPartialSuccessHandler)\n}\n\nfunc (e *baseExporter) pushProfiles(ctx context.Context, td pprofile.Profiles) error {\n\ttr := pprofileotlp.NewExportRequestFromProfiles(td)\n\n\tvar err error\n\tvar request []byte\n\tswitch e.config.Encoding {\n\tcase EncodingJSON:\n\t\trequest, err = tr.MarshalJSON()\n\tcase EncodingProto:\n\t\trequest, err = tr.MarshalProto()\n\tdefault:\n\t\terr = fmt.Errorf(\"invalid encoding: %s\", e.config.Encoding)\n\t}\n\n\tif err != nil {\n\t\treturn consumererror.NewPermanent(err)\n\t}\n\n\treturn e.export(ctx, e.profilesURL, request, e.profilesPartialSuccessHandler)\n}\n\nfunc (e *baseExporter) export(ctx context.Context, requestURL string, request []byte, partialSuccessHandler partialSuccessHandler) error {\n\te.logger.Debug(\"Preparing to make HTTP request\", zap.String(\"url\", requestURL))\n\treq, err := http.NewRequestWithContext(ctx, http.MethodPost, requestURL, bytes.NewReader(request))\n\tif err != nil {\n\t\treturn consumererror.NewPermanent(err)\n\t}\n\n\tswitch e.config.Encoding {\n\tcase EncodingJSON:\n\t\treq.Header.Set(\"Content-Type\", jsonContentType)\n\tcase EncodingProto:\n\t\treq.Header.Set(\"Content-Type\", protobufContentType)\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid encoding: %s\", e.config.Encoding)\n\t}\n\n\treq.Header.Set(\"User-Agent\", e.userAgent)\n\n\tresp, err := e.client.Do(req)\n\tif err != nil {\n\t\tvar urlErr *url.Error\n\t\tif errors.As(err, &urlErr) {\n\t\t\turlErr.URL = req.URL.String()\n\t\t}\n\t\treturn fmt.Errorf(\"failed to make an HTTP request: %w\", err)\n\t}\n\n\tdefer func() {\n\t\t// Discard any remaining response body when we are done reading.\n\t\t_, _ = io.CopyN(io.Discard, resp.Body, maxHTTPResponseReadBytes)\n\t\tresp.Body.Close()\n\t}()\n\n\tif resp.StatusCode >= 200 && resp.StatusCode <= 299 {\n\t\treturn handlePartialSuccessResponse(resp, partialSuccessHandler)\n\t}\n\n\trespStatus := readResponseStatus(resp)\n\n\t// Format the error message. Use the status if it is present in the response.\n\tvar errString string\n\tvar formattedErr error\n\tif respStatus != nil {\n\t\terrString = fmt.Sprintf(\n\t\t\t\"error exporting items, request to %s responded with HTTP Status Code %d, Message=%s, Details=%v\",\n\t\t\trequestURL, resp.StatusCode, respStatus.Message, respStatus.Details)\n\t} else {\n\t\terrString = fmt.Sprintf(\n\t\t\t\"error exporting items, request to %s responded with HTTP Status Code %d\",\n\t\t\trequestURL, resp.StatusCode)\n\t}\n\tformattedErr = statusutil.NewStatusFromMsgAndHTTPCode(errString, resp.StatusCode).Err()\n\n\tif !isRetryableStatusCode(resp.StatusCode) {\n\t\treturn consumererror.NewPermanent(formattedErr)\n\t}\n\n\t// Check if the server is overwhelmed.\n\t// See spec https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/otlp.md#otlphttp-throttling\n\tisThrottleError := resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode == http.StatusServiceUnavailable\n\tif isThrottleError {\n\t\t// Use Values to check if the header is present, and if present even if it is empty return ThrottleRetry.\n\t\tvalues := resp.Header.Values(headerRetryAfter)\n\t\tif len(values) == 0 {\n\t\t\treturn formattedErr\n\t\t}\n\t\t// The value of Retry-After field can be either an HTTP-date or a number of\n\t\t// seconds to delay after the response is received. See https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.3\n\t\t//\n\t\t// Retry-After = HTTP-date / delay-seconds\n\t\t//\n\t\t// First try to parse delay-seconds, since that is what the receiver will send.\n\t\tif seconds, err := strconv.Atoi(values[0]); err == nil {\n\t\t\treturn exporterhelper.NewThrottleRetry(formattedErr, time.Duration(seconds)*time.Second)\n\t\t}\n\t\tif date, err := time.Parse(time.RFC1123, values[0]); err == nil {\n\t\t\treturn exporterhelper.NewThrottleRetry(formattedErr, time.Until(date))\n\t\t}\n\t}\n\treturn formattedErr\n}\n\n// Determine if the status code is retryable according to the specification.\n// For more, see https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/otlp.md#failures-1\nfunc isRetryableStatusCode(code int) bool {\n\tswitch code {\n\tcase http.StatusTooManyRequests:\n\t\treturn true\n\tcase http.StatusBadGateway:\n\t\treturn true\n\tcase http.StatusServiceUnavailable:\n\t\treturn true\n\tcase http.StatusGatewayTimeout:\n\t\treturn true\n\tdefault:\n\t\treturn false\n\t}\n}\n\nfunc readResponseBody(resp *http.Response) ([]byte, error) {\n\tif resp.ContentLength == 0 {\n\t\treturn nil, nil\n\t}\n\n\tmaxRead := resp.ContentLength\n\n\t// if maxRead == -1, the ContentLength header has not been sent, so read up to\n\t// the maximum permitted body size. If it is larger than the permitted body\n\t// size, still try to read from the body in case the value is an error. If the\n\t// body is larger than the maximum size, proto unmarshaling will likely fail.\n\tif maxRead == -1 || maxRead > maxHTTPResponseReadBytes {\n\t\tmaxRead = maxHTTPResponseReadBytes\n\t}\n\tprotoBytes := make([]byte, maxRead)\n\tn, err := io.ReadFull(resp.Body, protoBytes)\n\n\t// No bytes read and an EOF error indicates there is no body to read.\n\tif n == 0 && (err == nil || errors.Is(err, io.EOF)) {\n\t\treturn nil, nil\n\t}\n\n\t// io.ReadFull will return io.ErrorUnexpectedEOF if the Content-Length header\n\t// wasn't set, since we will try to read past the length of the body. If this\n\t// is the case, the body will still have the full message in it, so we want to\n\t// ignore the error and parse the message.\n\tif err != nil && !errors.Is(err, io.ErrUnexpectedEOF) {\n\t\treturn nil, err\n\t}\n\n\treturn protoBytes[:n], nil\n}\n\n// Read the response and decode the status.Status from the body.\n// Returns nil if the response is empty or cannot be decoded.\nfunc readResponseStatus(resp *http.Response) *status.Status {\n\tvar respStatus *status.Status\n\tif resp.StatusCode >= 400 && resp.StatusCode <= 599 {\n\t\t// Request failed. Read the body. OTLP spec says:\n\t\t// \"Response body for all HTTP 4xx and HTTP 5xx responses MUST be a\n\t\t// Protobuf-encoded Status message that describes the problem.\"\n\t\trespBytes, err := readResponseBody(resp)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\n\t\t// Decode it as Status struct. See https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/otlp.md#failures\n\t\trespStatus = &status.Status{}\n\t\terr = proto.Unmarshal(respBytes, respStatus)\n\t\tif err != nil {\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn respStatus\n}\n\nfunc handlePartialSuccessResponse(resp *http.Response, partialSuccessHandler partialSuccessHandler) error {\n\tbodyBytes, err := readResponseBody(resp)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\treturn partialSuccessHandler(bodyBytes, resp.Header.Get(\"Content-Type\"))\n}\n\ntype partialSuccessHandler func(bytes []byte, contentType string) error\n\nfunc (e *baseExporter) tracesPartialSuccessHandler(protoBytes []byte, contentType string) error {\n\tif protoBytes == nil {\n\t\treturn nil\n\t}\n\texportResponse := ptraceotlp.NewExportResponse()\n\tswitch contentType {\n\tcase protobufContentType:\n\t\terr := exportResponse.UnmarshalProto(protoBytes)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error parsing protobuf response: %w\", err)\n\t\t}\n\tcase jsonContentType:\n\t\terr := exportResponse.UnmarshalJSON(protoBytes)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error parsing json response: %w\", err)\n\t\t}\n\tdefault:\n\t\treturn nil\n\t}\n\n\tpartialSuccess := exportResponse.PartialSuccess()\n\tif partialSuccess.ErrorMessage() != \"\" || partialSuccess.RejectedSpans() != 0 {\n\t\te.logger.Warn(\"Partial success response\",\n\t\t\tzap.String(\"message\", exportResponse.PartialSuccess().ErrorMessage()),\n\t\t\tzap.Int64(\"dropped_spans\", exportResponse.PartialSuccess().RejectedSpans()),\n\t\t)\n\t}\n\treturn nil\n}\n\nfunc (e *baseExporter) metricsPartialSuccessHandler(protoBytes []byte, contentType string) error {\n\tif protoBytes == nil {\n\t\treturn nil\n\t}\n\texportResponse := pmetricotlp.NewExportResponse()\n\tswitch contentType {\n\tcase protobufContentType:\n\t\terr := exportResponse.UnmarshalProto(protoBytes)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error parsing protobuf response: %w\", err)\n\t\t}\n\tcase jsonContentType:\n\t\terr := exportResponse.UnmarshalJSON(protoBytes)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error parsing json response: %w\", err)\n\t\t}\n\tdefault:\n\t\treturn nil\n\t}\n\n\tpartialSuccess := exportResponse.PartialSuccess()\n\tif partialSuccess.ErrorMessage() != \"\" || partialSuccess.RejectedDataPoints() != 0 {\n\t\te.logger.Warn(\"Partial success response\",\n\t\t\tzap.String(\"message\", exportResponse.PartialSuccess().ErrorMessage()),\n\t\t\tzap.Int64(\"dropped_data_points\", exportResponse.PartialSuccess().RejectedDataPoints()),\n\t\t)\n\t}\n\treturn nil\n}\n\nfunc (e *baseExporter) logsPartialSuccessHandler(protoBytes []byte, contentType string) error {\n\tif protoBytes == nil {\n\t\treturn nil\n\t}\n\texportResponse := plogotlp.NewExportResponse()\n\tswitch contentType {\n\tcase protobufContentType:\n\t\terr := exportResponse.UnmarshalProto(protoBytes)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error parsing protobuf response: %w\", err)\n\t\t}\n\tcase jsonContentType:\n\t\terr := exportResponse.UnmarshalJSON(protoBytes)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error parsing json response: %w\", err)\n\t\t}\n\tdefault:\n\t\treturn nil\n\t}\n\n\tpartialSuccess := exportResponse.PartialSuccess()\n\tif partialSuccess.ErrorMessage() != \"\" || partialSuccess.RejectedLogRecords() != 0 {\n\t\te.logger.Warn(\"Partial success response\",\n\t\t\tzap.String(\"message\", exportResponse.PartialSuccess().ErrorMessage()),\n\t\t\tzap.Int64(\"dropped_log_records\", exportResponse.PartialSuccess().RejectedLogRecords()),\n\t\t)\n\t}\n\treturn nil\n}\n\nfunc (e *baseExporter) profilesPartialSuccessHandler(protoBytes []byte, contentType string) error {\n\tif protoBytes == nil {\n\t\treturn nil\n\t}\n\texportResponse := pprofileotlp.NewExportResponse()\n\tswitch contentType {\n\tcase protobufContentType:\n\t\terr := exportResponse.UnmarshalProto(protoBytes)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error parsing protobuf response: %w\", err)\n\t\t}\n\tcase jsonContentType:\n\t\terr := exportResponse.UnmarshalJSON(protoBytes)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error parsing json response: %w\", err)\n\t\t}\n\tdefault:\n\t\treturn nil\n\t}\n\n\tpartialSuccess := exportResponse.PartialSuccess()\n\tif partialSuccess.ErrorMessage() != \"\" || partialSuccess.RejectedProfiles() != 0 {\n\t\te.logger.Warn(\"Partial success response\",\n\t\t\tzap.String(\"message\", exportResponse.PartialSuccess().ErrorMessage()),\n\t\t\tzap.Int64(\"dropped_samples\", exportResponse.PartialSuccess().RejectedProfiles()),\n\t\t)\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "exporter/otlphttpexporter/otlp_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlphttpexporter\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/exporter/otlphttpexporter/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/plog/plogotlp\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n)\n\nconst (\n\ttracesTelemetryType   = \"traces\"\n\tmetricsTelemetryType  = \"metrics\"\n\tlogsTelemetryType     = \"logs\"\n\tprofilesTelemetryType = \"profiles\"\n)\n\ntype responseSerializer interface {\n\tMarshalJSON() ([]byte, error)\n\tMarshalProto() ([]byte, error)\n}\n\ntype responseSerializerProvider = func() responseSerializer\n\nfunc provideTracesResponseSerializer() responseSerializer {\n\tresponse := ptraceotlp.NewExportResponse()\n\tpartial := response.PartialSuccess()\n\tpartial.SetErrorMessage(\"hello\")\n\tpartial.SetRejectedSpans(1)\n\treturn response\n}\n\nfunc provideMetricsResponseSerializer() responseSerializer {\n\tresponse := pmetricotlp.NewExportResponse()\n\tpartial := response.PartialSuccess()\n\tpartial.SetErrorMessage(\"hello\")\n\tpartial.SetRejectedDataPoints(1)\n\treturn response\n}\n\nfunc provideLogsResponseSerializer() responseSerializer {\n\tresponse := plogotlp.NewExportResponse()\n\tpartial := response.PartialSuccess()\n\tpartial.SetErrorMessage(\"hello\")\n\tpartial.SetRejectedLogRecords(1)\n\treturn response\n}\n\nfunc provideProfilesResponseSerializer() responseSerializer {\n\tresponse := pprofileotlp.NewExportResponse()\n\tpartial := response.PartialSuccess()\n\tpartial.SetErrorMessage(\"hello\")\n\tpartial.SetRejectedProfiles(1)\n\treturn response\n}\n\nfunc TestErrorResponses(t *testing.T) {\n\terrMsgPrefix := func(srv *httptest.Server) string {\n\t\treturn fmt.Sprintf(\"error exporting items, request to %s/v1/traces responded with HTTP Status Code \", srv.URL)\n\t}\n\n\ttests := []struct {\n\t\tname           string\n\t\tresponseStatus int\n\t\tresponseBody   *status.Status\n\t\tcheckErr       func(t *testing.T, err error, srv *httptest.Server)\n\t\theaders        map[string]string\n\t}{\n\t\t{\n\t\t\tname:           \"400\",\n\t\t\tresponseStatus: http.StatusBadRequest,\n\t\t\tresponseBody:   status.New(codes.InvalidArgument, \"Bad field\"),\n\t\t\tcheckErr: func(t *testing.T, err error, _ *httptest.Server) {\n\t\t\t\tassert.True(t, consumererror.IsPermanent(err))\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:           \"402\",\n\t\t\tresponseStatus: http.StatusPaymentRequired,\n\t\t\tresponseBody:   status.New(codes.InvalidArgument, \"Bad field\"),\n\t\t\tcheckErr: func(t *testing.T, err error, _ *httptest.Server) {\n\t\t\t\tassert.True(t, consumererror.IsPermanent(err))\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:           \"404\",\n\t\t\tresponseStatus: http.StatusNotFound,\n\t\t\tresponseBody:   status.New(codes.InvalidArgument, \"Bad field\"),\n\t\t\tcheckErr: func(t *testing.T, err error, _ *httptest.Server) {\n\t\t\t\tassert.True(t, consumererror.IsPermanent(err))\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:           \"405\",\n\t\t\tresponseStatus: http.StatusMethodNotAllowed,\n\t\t\tresponseBody:   status.New(codes.InvalidArgument, \"Bad field\"),\n\t\t\tcheckErr: func(t *testing.T, err error, _ *httptest.Server) {\n\t\t\t\tassert.True(t, consumererror.IsPermanent(err))\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:           \"413\",\n\t\t\tresponseStatus: http.StatusRequestEntityTooLarge,\n\t\t\tresponseBody:   status.New(codes.InvalidArgument, \"Bad field\"),\n\t\t\tcheckErr: func(t *testing.T, err error, _ *httptest.Server) {\n\t\t\t\tassert.True(t, consumererror.IsPermanent(err))\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:           \"414\",\n\t\t\tresponseStatus: http.StatusRequestURITooLong,\n\t\t\tresponseBody:   status.New(codes.InvalidArgument, \"Bad field\"),\n\t\t\tcheckErr: func(t *testing.T, err error, _ *httptest.Server) {\n\t\t\t\tassert.True(t, consumererror.IsPermanent(err))\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:           \"431\",\n\t\t\tresponseStatus: http.StatusRequestHeaderFieldsTooLarge,\n\t\t\tresponseBody:   status.New(codes.InvalidArgument, \"Bad field\"),\n\t\t\tcheckErr: func(t *testing.T, err error, _ *httptest.Server) {\n\t\t\t\tassert.True(t, consumererror.IsPermanent(err))\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:           \"429\",\n\t\t\tresponseStatus: http.StatusTooManyRequests,\n\t\t\tresponseBody:   status.New(codes.ResourceExhausted, \"Quota exceeded\"),\n\t\t\tcheckErr: func(t *testing.T, err error, srv *httptest.Server) {\n\t\t\t\trequire.EqualError(t, err, status.New(codes.ResourceExhausted, errMsgPrefix(srv)+\"429, Message=Quota exceeded, Details=[]\").String())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:           \"429-Retry-After\",\n\t\t\tresponseStatus: http.StatusTooManyRequests,\n\t\t\tresponseBody:   status.New(codes.InvalidArgument, \"Quota exceeded\"),\n\t\t\theaders:        map[string]string{\"Retry-After\": \"Mon, 09 Feb 2025 15:04:05 GMT\"},\n\t\t\tcheckErr: func(t *testing.T, err error, srv *httptest.Server) {\n\t\t\t\t// Cannot test for the delay part since it depends on now. Check first part (which has a negative duration) and last part:\n\t\t\t\trequire.ErrorContains(t, err, \"Throttle (-\")\n\t\t\t\trequire.ErrorContains(t, err, \"), error: \"+status.New(codes.ResourceExhausted, errMsgPrefix(srv)+\"429, Message=Quota exceeded, Details=[]\").String())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:           \"429-Retry-After-Malformed\",\n\t\t\tresponseStatus: http.StatusTooManyRequests,\n\t\t\tresponseBody:   status.New(codes.InvalidArgument, \"Quota exceeded\"),\n\t\t\theaders:        map[string]string{\"Retry-After\": \"Malformed\"},\n\t\t\tcheckErr: func(t *testing.T, err error, srv *httptest.Server) {\n\t\t\t\t// Cannot test for the delay part since it depends on now. Check first part (which has a negative duration) and last part:\n\t\t\t\trequire.EqualError(t, err, status.New(codes.ResourceExhausted, errMsgPrefix(srv)+\"429, Message=Quota exceeded, Details=[]\").String())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:           \"500\",\n\t\t\tresponseStatus: http.StatusInternalServerError,\n\t\t\tresponseBody:   status.New(codes.InvalidArgument, \"Internal server error\"),\n\t\t\tcheckErr: func(t *testing.T, err error, _ *httptest.Server) {\n\t\t\t\tassert.True(t, consumererror.IsPermanent(err))\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:           \"502\",\n\t\t\tresponseStatus: http.StatusBadGateway,\n\t\t\tresponseBody:   status.New(codes.InvalidArgument, \"Bad gateway\"),\n\t\t\tcheckErr: func(t *testing.T, err error, srv *httptest.Server) {\n\t\t\t\trequire.EqualError(t, err, status.New(codes.Unavailable, errMsgPrefix(srv)+\"502, Message=Bad gateway, Details=[]\").String())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:           \"503\",\n\t\t\tresponseStatus: http.StatusServiceUnavailable,\n\t\t\tresponseBody:   status.New(codes.InvalidArgument, \"Server overloaded\"),\n\t\t\tcheckErr: func(t *testing.T, err error, srv *httptest.Server) {\n\t\t\t\trequire.EqualError(t, err, status.New(codes.Unavailable, errMsgPrefix(srv)+\"503, Message=Server overloaded, Details=[]\").String())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:           \"503-Retry-After\",\n\t\t\tresponseStatus: http.StatusServiceUnavailable,\n\t\t\tresponseBody:   status.New(codes.InvalidArgument, \"Server overloaded\"),\n\t\t\theaders:        map[string]string{\"Retry-After\": \"30\"},\n\t\t\tcheckErr: func(t *testing.T, err error, srv *httptest.Server) {\n\t\t\t\trequire.EqualError(t, err, exporterhelper.NewThrottleRetry(\n\t\t\t\t\tstatus.New(codes.Unavailable, errMsgPrefix(srv)+\"503, Message=Server overloaded, Details=[]\").Err(),\n\t\t\t\t\ttime.Duration(30)*time.Second).Error())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:           \"504\",\n\t\t\tresponseStatus: http.StatusGatewayTimeout,\n\t\t\tresponseBody:   status.New(codes.InvalidArgument, \"Gateway timeout\"),\n\t\t\tcheckErr: func(t *testing.T, err error, srv *httptest.Server) {\n\t\t\t\trequire.EqualError(t, err, status.New(codes.Unavailable, errMsgPrefix(srv)+\"504, Message=Gateway timeout, Details=[]\").String())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:           \"Bad response payload\",\n\t\t\tresponseStatus: http.StatusServiceUnavailable,\n\t\t\tresponseBody:   status.New(codes.InvalidArgument, strings.Repeat(\"a\", maxHTTPResponseReadBytes+1)),\n\t\t\tcheckErr: func(t *testing.T, err error, srv *httptest.Server) {\n\t\t\t\trequire.EqualError(t, err, status.New(codes.Unavailable, errMsgPrefix(srv)+\"503\").String())\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tsrv := createBackend(\"/v1/traces\", func(writer http.ResponseWriter, _ *http.Request) {\n\t\t\t\tfor k, v := range test.headers {\n\t\t\t\t\twriter.Header().Add(k, v)\n\t\t\t\t}\n\t\t\t\twriter.WriteHeader(test.responseStatus)\n\t\t\t\tif test.responseBody != nil {\n\t\t\t\t\tmsg, err := proto.Marshal(test.responseBody.Proto())\n\t\t\t\t\tassert.NoError(t, err)\n\t\t\t\t\t_, err = writer.Write(msg)\n\t\t\t\t\tassert.NoError(t, err)\n\t\t\t\t}\n\t\t\t})\n\t\t\tdefer srv.Close()\n\n\t\t\tcfg := &Config{\n\t\t\t\tEncoding:       EncodingProto,\n\t\t\t\tTracesEndpoint: srv.URL + \"/v1/traces\",\n\t\t\t\t// Create without QueueConfig and RetryConfig so that ConsumeTraces\n\t\t\t\t// returns the errors that we want to check immediately.\n\t\t\t}\n\t\t\texp, err := createTraces(context.Background(), exportertest.NewNopSettings(metadata.Type), cfg)\n\t\t\trequire.NoError(t, err)\n\n\t\t\t// start the exporter\n\t\t\terr = exp.Start(context.Background(), componenttest.NewNopHost())\n\t\t\trequire.NoError(t, err)\n\t\t\tt.Cleanup(func() {\n\t\t\t\trequire.NoError(t, exp.Shutdown(context.Background()))\n\t\t\t})\n\n\t\t\t// generate traces\n\t\t\ttraces := ptrace.NewTraces()\n\t\t\terr = exp.ConsumeTraces(context.Background(), traces)\n\t\t\trequire.Error(t, err)\n\t\t\ttest.checkErr(t, err, srv)\n\t\t})\n\t}\n}\n\nfunc TestErrorResponseInvalidResponseBody(t *testing.T) {\n\tresp := &http.Response{\n\t\tStatusCode:    http.StatusBadRequest,\n\t\tBody:          io.NopCloser(badReader{}),\n\t\tContentLength: 100,\n\t}\n\tassert.Nil(t, readResponseStatus(resp))\n}\n\nfunc TestUserAgent(t *testing.T) {\n\tset := exportertest.NewNopSettings(metadata.Type)\n\tset.BuildInfo.Description = \"Collector\"\n\tset.BuildInfo.Version = \"1.2.3test\"\n\n\ttests := []struct {\n\t\tname       string\n\t\theaders    configopaque.MapList\n\t\texpectedUA string\n\t}{\n\t\t{\n\t\t\tname:       \"default_user_agent\",\n\t\t\texpectedUA: \"Collector/1.2.3test\",\n\t\t},\n\t\t{\n\t\t\tname:       \"custom_user_agent\",\n\t\t\theaders:    configopaque.MapList{{Name: \"User-Agent\", Value: \"My Custom Agent\"}},\n\t\t\texpectedUA: \"My Custom Agent\",\n\t\t},\n\t\t{\n\t\t\tname:       \"custom_user_agent_lowercase\",\n\t\t\theaders:    configopaque.MapList{{Name: \"user-agent\", Value: \"My Custom Agent\"}},\n\t\t\texpectedUA: \"My Custom Agent\",\n\t\t},\n\t}\n\n\tt.Run(\"traces\", func(t *testing.T) {\n\t\tfor _, tt := range tests {\n\t\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t\tsrv := createBackend(\"/v1/traces\", func(writer http.ResponseWriter, request *http.Request) {\n\t\t\t\t\tassert.Contains(t, request.Header.Get(\"user-agent\"), tt.expectedUA)\n\t\t\t\t\twriter.WriteHeader(http.StatusOK)\n\t\t\t\t})\n\t\t\t\tdefer srv.Close()\n\n\t\t\t\tcfg := &Config{\n\t\t\t\t\tEncoding:       EncodingProto,\n\t\t\t\t\tTracesEndpoint: srv.URL + \"/v1/traces\",\n\t\t\t\t\tClientConfig: confighttp.ClientConfig{\n\t\t\t\t\t\tHeaders: tt.headers,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\texp, err := createTraces(context.Background(), set, cfg)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\t// start the exporter\n\t\t\t\terr = exp.Start(context.Background(), componenttest.NewNopHost())\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tt.Cleanup(func() {\n\t\t\t\t\trequire.NoError(t, exp.Shutdown(context.Background()))\n\t\t\t\t})\n\n\t\t\t\t// generate data\n\t\t\t\ttraces := ptrace.NewTraces()\n\t\t\t\terr = exp.ConsumeTraces(context.Background(), traces)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t})\n\t\t}\n\t})\n\n\tt.Run(\"metrics\", func(t *testing.T) {\n\t\tfor _, tt := range tests {\n\t\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t\tsrv := createBackend(\"/v1/metrics\", func(writer http.ResponseWriter, request *http.Request) {\n\t\t\t\t\tassert.Contains(t, request.Header.Get(\"user-agent\"), tt.expectedUA)\n\t\t\t\t\twriter.WriteHeader(http.StatusOK)\n\t\t\t\t})\n\t\t\t\tdefer srv.Close()\n\n\t\t\t\tcfg := &Config{\n\t\t\t\t\tEncoding:        EncodingProto,\n\t\t\t\t\tMetricsEndpoint: srv.URL + \"/v1/metrics\",\n\t\t\t\t\tClientConfig: confighttp.ClientConfig{\n\t\t\t\t\t\tHeaders: tt.headers,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\texp, err := createMetrics(context.Background(), set, cfg)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\t// start the exporter\n\t\t\t\terr = exp.Start(context.Background(), componenttest.NewNopHost())\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tt.Cleanup(func() {\n\t\t\t\t\trequire.NoError(t, exp.Shutdown(context.Background()))\n\t\t\t\t})\n\n\t\t\t\t// generate data\n\t\t\t\tmetrics := pmetric.NewMetrics()\n\t\t\t\terr = exp.ConsumeMetrics(context.Background(), metrics)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t})\n\t\t}\n\t})\n\n\tt.Run(\"logs\", func(t *testing.T) {\n\t\tfor _, tt := range tests {\n\t\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t\tsrv := createBackend(\"/v1/logs\", func(writer http.ResponseWriter, request *http.Request) {\n\t\t\t\t\tassert.Contains(t, request.Header.Get(\"user-agent\"), tt.expectedUA)\n\t\t\t\t\twriter.WriteHeader(http.StatusOK)\n\t\t\t\t})\n\t\t\t\tdefer srv.Close()\n\n\t\t\t\tcfg := &Config{\n\t\t\t\t\tEncoding:     EncodingProto,\n\t\t\t\t\tLogsEndpoint: srv.URL + \"/v1/logs\",\n\t\t\t\t\tClientConfig: confighttp.ClientConfig{\n\t\t\t\t\t\tHeaders: tt.headers,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\texp, err := createLogs(context.Background(), set, cfg)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\t// start the exporter\n\t\t\t\terr = exp.Start(context.Background(), componenttest.NewNopHost())\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tt.Cleanup(func() {\n\t\t\t\t\trequire.NoError(t, exp.Shutdown(context.Background()))\n\t\t\t\t})\n\n\t\t\t\t// generate data\n\t\t\t\tlogs := plog.NewLogs()\n\t\t\t\terr = exp.ConsumeLogs(context.Background(), logs)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\tsrv.Close()\n\t\t\t})\n\t\t}\n\t})\n\n\tt.Run(\"profiles\", func(t *testing.T) {\n\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tsrv := createBackend(\"/v1development/profiles\", func(writer http.ResponseWriter, request *http.Request) {\n\t\t\t\t\tassert.Contains(t, request.Header.Get(\"user-agent\"), test.expectedUA)\n\t\t\t\t\twriter.WriteHeader(http.StatusOK)\n\t\t\t\t})\n\t\t\t\tdefer srv.Close()\n\n\t\t\t\tcfg := &Config{\n\t\t\t\t\tEncoding: EncodingProto,\n\t\t\t\t\tClientConfig: confighttp.ClientConfig{\n\t\t\t\t\t\tEndpoint: srv.URL,\n\t\t\t\t\t\tHeaders:  test.headers,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\texp, err := createProfiles(context.Background(), set, cfg)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\t// start the exporter\n\t\t\t\terr = exp.Start(context.Background(), componenttest.NewNopHost())\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tt.Cleanup(func() {\n\t\t\t\t\trequire.NoError(t, exp.Shutdown(context.Background()))\n\t\t\t\t})\n\n\t\t\t\t// generate data\n\t\t\t\tprofiles := pprofile.NewProfiles()\n\t\t\t\terr = exp.ConsumeProfiles(context.Background(), profiles)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t})\n\t\t}\n\t})\n}\n\nfunc TestPartialSuccessInvalidBody(t *testing.T) {\n\tcfg := createDefaultConfig()\n\tset := exportertest.NewNopSettings(metadata.Type)\n\texp, err := newExporter(cfg, set)\n\trequire.NoError(t, err)\n\tinvalidBodyCases := []struct {\n\t\ttelemetryType string\n\t\thandler       partialSuccessHandler\n\t}{\n\t\t{\n\t\t\ttelemetryType: \"traces\",\n\t\t\thandler:       exp.tracesPartialSuccessHandler,\n\t\t},\n\t\t{\n\t\t\ttelemetryType: \"metrics\",\n\t\t\thandler:       exp.metricsPartialSuccessHandler,\n\t\t},\n\t\t{\n\t\t\ttelemetryType: \"logs\",\n\t\t\thandler:       exp.logsPartialSuccessHandler,\n\t\t},\n\t\t{\n\t\t\ttelemetryType: \"profiles\",\n\t\t\thandler:       exp.profilesPartialSuccessHandler,\n\t\t},\n\t}\n\tfor _, tt := range invalidBodyCases {\n\t\tt.Run(\"Invalid response body_\"+tt.telemetryType, func(t *testing.T) {\n\t\t\terr := tt.handler([]byte{1}, \"application/x-protobuf\")\n\t\t\tassert.ErrorContains(t, err, \"error parsing protobuf response:\")\n\t\t})\n\t}\n}\n\nfunc TestPartialSuccessUnsupportedContentType(t *testing.T) {\n\tcfg := createDefaultConfig()\n\tset := exportertest.NewNopSettings(metadata.Type)\n\texp, err := newExporter(cfg, set)\n\trequire.NoError(t, err)\n\tunsupportedContentTypeCases := []struct {\n\t\tcontentType string\n\t}{\n\t\t{\n\t\t\tcontentType: \"text/plain\",\n\t\t},\n\t\t{\n\t\t\tcontentType: \"application/octet-stream\",\n\t\t},\n\t}\n\tfor _, telemetryType := range []string{\"logs\", \"metrics\", \"traces\", \"profiles\"} {\n\t\tfor _, tt := range unsupportedContentTypeCases {\n\t\t\tt.Run(\"Unsupported content type \"+tt.contentType+\" \"+telemetryType, func(t *testing.T) {\n\t\t\t\tvar handler func(b []byte, contentType string) error\n\t\t\t\tswitch telemetryType {\n\t\t\t\tcase \"logs\":\n\t\t\t\t\thandler = exp.logsPartialSuccessHandler\n\t\t\t\tcase \"metrics\":\n\t\t\t\t\thandler = exp.metricsPartialSuccessHandler\n\t\t\t\tcase \"traces\":\n\t\t\t\t\thandler = exp.tracesPartialSuccessHandler\n\t\t\t\tcase \"profiles\":\n\t\t\t\t\thandler = exp.profilesPartialSuccessHandler\n\t\t\t\tdefault:\n\t\t\t\t\tpanic(telemetryType)\n\t\t\t\t}\n\t\t\t\texportResponse := ptraceotlp.NewExportResponse()\n\t\t\t\texportResponse.PartialSuccess().SetErrorMessage(\"foo\")\n\t\t\t\texportResponse.PartialSuccess().SetRejectedSpans(42)\n\t\t\t\tb, err := exportResponse.MarshalProto()\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\terr = handler(b, tt.contentType)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestPartialSuccess_logs(t *testing.T) {\n\tsrv := createBackend(\"/v1/logs\", func(writer http.ResponseWriter, _ *http.Request) {\n\t\tresponse := plogotlp.NewExportResponse()\n\t\tpartial := response.PartialSuccess()\n\t\tpartial.SetErrorMessage(\"hello\")\n\t\tpartial.SetRejectedLogRecords(1)\n\t\tb, err := response.MarshalProto()\n\t\tassert.NoError(t, err)\n\t\twriter.Header().Set(\"Content-Type\", \"application/x-protobuf\")\n\t\t_, err = writer.Write(b)\n\t\tassert.NoError(t, err)\n\t})\n\tdefer srv.Close()\n\n\tcfg := &Config{\n\t\tEncoding:     EncodingProto,\n\t\tLogsEndpoint: srv.URL + \"/v1/logs\",\n\t\tClientConfig: confighttp.ClientConfig{},\n\t}\n\tset := exportertest.NewNopSettings(metadata.Type)\n\n\tlogger, observed := observer.New(zap.DebugLevel)\n\tset.Logger = zap.New(logger)\n\n\texp, err := createLogs(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\n\t// start the exporter\n\terr = exp.Start(context.Background(), componenttest.NewNopHost())\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, exp.Shutdown(context.Background()))\n\t})\n\n\t// generate data\n\tlogs := plog.NewLogs()\n\terr = exp.ConsumeLogs(context.Background(), logs)\n\trequire.NoError(t, err)\n\trequire.Len(t, observed.FilterLevelExact(zap.WarnLevel).All(), 1)\n\trequire.Contains(t, observed.FilterLevelExact(zap.WarnLevel).All()[0].Message, \"Partial success\")\n}\n\nfunc TestPartialResponse_missingHeaderButHasBody(t *testing.T) {\n\tcfg := createDefaultConfig()\n\tset := exportertest.NewNopSettings(metadata.Type)\n\texp, err := newExporter(cfg, set)\n\trequire.NoError(t, err)\n\n\tcontentTypes := []struct {\n\t\tcontentType string\n\t}{\n\t\t{contentType: protobufContentType},\n\t\t{contentType: jsonContentType},\n\t}\n\n\ttelemetryTypes := []struct {\n\t\ttelemetryType string\n\t\thandler       partialSuccessHandler\n\t\tserializer    responseSerializerProvider\n\t}{\n\t\t{\n\t\t\ttelemetryType: tracesTelemetryType,\n\t\t\thandler:       exp.tracesPartialSuccessHandler,\n\t\t\tserializer:    provideTracesResponseSerializer,\n\t\t},\n\t\t{\n\t\t\ttelemetryType: metricsTelemetryType,\n\t\t\thandler:       exp.metricsPartialSuccessHandler,\n\t\t\tserializer:    provideMetricsResponseSerializer,\n\t\t},\n\t\t{\n\t\t\ttelemetryType: logsTelemetryType,\n\t\t\thandler:       exp.logsPartialSuccessHandler,\n\t\t\tserializer:    provideLogsResponseSerializer,\n\t\t},\n\t\t{\n\t\t\ttelemetryType: profilesTelemetryType,\n\t\t\thandler:       exp.profilesPartialSuccessHandler,\n\t\t\tserializer:    provideProfilesResponseSerializer,\n\t\t},\n\t}\n\n\tfor _, ct := range contentTypes {\n\t\tfor _, tt := range telemetryTypes {\n\t\t\tt.Run(tt.telemetryType+\" \"+ct.contentType, func(t *testing.T) {\n\t\t\t\tserializer := tt.serializer()\n\n\t\t\t\tvar data []byte\n\t\t\t\tvar err error\n\n\t\t\t\tswitch ct.contentType {\n\t\t\t\tcase jsonContentType:\n\t\t\t\t\tdata, err = serializer.MarshalJSON()\n\t\t\t\tcase protobufContentType:\n\t\t\t\t\tdata, err = serializer.MarshalProto()\n\t\t\t\tdefault:\n\t\t\t\t\trequire.Failf(t, \"unsupported content type: %s\", ct.contentType)\n\t\t\t\t}\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\tresp := &http.Response{\n\t\t\t\t\t// `-1` indicates a missing Content-Length header in the Go http standard library\n\t\t\t\t\tContentLength: -1,\n\t\t\t\t\tBody:          io.NopCloser(bytes.NewReader(data)),\n\t\t\t\t\tHeader: map[string][]string{\n\t\t\t\t\t\t\"Content-Type\": {ct.contentType},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\terr = handlePartialSuccessResponse(resp, tt.handler)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestPartialResponse_missingHeaderAndBody(t *testing.T) {\n\tcfg := createDefaultConfig()\n\tset := exportertest.NewNopSettings(metadata.Type)\n\texp, err := newExporter(cfg, set)\n\trequire.NoError(t, err)\n\n\tcontentTypes := []struct {\n\t\tcontentType string\n\t}{\n\t\t{contentType: protobufContentType},\n\t\t{contentType: jsonContentType},\n\t}\n\n\ttelemetryTypes := []struct {\n\t\ttelemetryType string\n\t\thandler       partialSuccessHandler\n\t}{\n\t\t{\n\t\t\ttelemetryType: tracesTelemetryType,\n\t\t\thandler:       exp.tracesPartialSuccessHandler,\n\t\t},\n\t\t{\n\t\t\ttelemetryType: metricsTelemetryType,\n\t\t\thandler:       exp.metricsPartialSuccessHandler,\n\t\t},\n\t\t{\n\t\t\ttelemetryType: logsTelemetryType,\n\t\t\thandler:       exp.logsPartialSuccessHandler,\n\t\t},\n\t\t{\n\t\t\ttelemetryType: profilesTelemetryType,\n\t\t\thandler:       exp.profilesPartialSuccessHandler,\n\t\t},\n\t}\n\n\tfor _, ct := range contentTypes {\n\t\tfor _, tt := range telemetryTypes {\n\t\t\tt.Run(tt.telemetryType+\" \"+ct.contentType, func(t *testing.T) {\n\t\t\t\tresp := &http.Response{\n\t\t\t\t\t// `-1` indicates a missing Content-Length header in the Go http standard library\n\t\t\t\t\tContentLength: -1,\n\t\t\t\t\tBody:          io.NopCloser(bytes.NewReader([]byte{})),\n\t\t\t\t\tHeader: map[string][]string{\n\t\t\t\t\t\t\"Content-Type\": {ct.contentType},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\terr = handlePartialSuccessResponse(resp, tt.handler)\n\t\t\t\tassert.NoError(t, err)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestPartialResponse_nonErrUnexpectedEOFError(t *testing.T) {\n\tcfg := createDefaultConfig()\n\tset := exportertest.NewNopSettings(metadata.Type)\n\texp, err := newExporter(cfg, set)\n\trequire.NoError(t, err)\n\n\tresp := &http.Response{\n\t\t// `-1` indicates a missing Content-Length header in the Go http standard library\n\t\tContentLength: -1,\n\t\tBody:          io.NopCloser(badReader{}),\n\t}\n\terr = handlePartialSuccessResponse(resp, exp.tracesPartialSuccessHandler)\n\tassert.Error(t, err)\n}\n\nfunc TestPartialSuccess_shortContentLengthHeader(t *testing.T) {\n\tcfg := createDefaultConfig()\n\tset := exportertest.NewNopSettings(metadata.Type)\n\texp, err := newExporter(cfg, set)\n\trequire.NoError(t, err)\n\n\tcontentTypes := []struct {\n\t\tcontentType string\n\t}{\n\t\t{contentType: protobufContentType},\n\t\t{contentType: jsonContentType},\n\t}\n\n\ttelemetryTypes := []struct {\n\t\ttelemetryType string\n\t\thandler       partialSuccessHandler\n\t\tserializer    responseSerializerProvider\n\t}{\n\t\t{\n\t\t\ttelemetryType: tracesTelemetryType,\n\t\t\thandler:       exp.tracesPartialSuccessHandler,\n\t\t\tserializer:    provideTracesResponseSerializer,\n\t\t},\n\t\t{\n\t\t\ttelemetryType: metricsTelemetryType,\n\t\t\thandler:       exp.metricsPartialSuccessHandler,\n\t\t\tserializer:    provideMetricsResponseSerializer,\n\t\t},\n\t\t{\n\t\t\ttelemetryType: logsTelemetryType,\n\t\t\thandler:       exp.logsPartialSuccessHandler,\n\t\t\tserializer:    provideLogsResponseSerializer,\n\t\t},\n\t\t{\n\t\t\ttelemetryType: profilesTelemetryType,\n\t\t\thandler:       exp.profilesPartialSuccessHandler,\n\t\t\tserializer:    provideProfilesResponseSerializer,\n\t\t},\n\t}\n\n\tfor _, ct := range contentTypes {\n\t\tfor _, tt := range telemetryTypes {\n\t\t\tt.Run(tt.telemetryType+\" \"+ct.contentType, func(t *testing.T) {\n\t\t\t\tserializer := tt.serializer()\n\n\t\t\t\tvar data []byte\n\t\t\t\tvar err error\n\n\t\t\t\tswitch ct.contentType {\n\t\t\t\tcase jsonContentType:\n\t\t\t\t\tdata, err = serializer.MarshalJSON()\n\t\t\t\tcase protobufContentType:\n\t\t\t\t\tdata, err = serializer.MarshalProto()\n\t\t\t\tdefault:\n\t\t\t\t\trequire.Failf(t, \"unsupported content type: %s\", ct.contentType)\n\t\t\t\t}\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\tresp := &http.Response{\n\t\t\t\t\tContentLength: 3,\n\t\t\t\t\tBody:          io.NopCloser(bytes.NewReader(data)),\n\t\t\t\t\tHeader: map[string][]string{\n\t\t\t\t\t\t\"Content-Type\": {ct.contentType},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\t// For short content-length, a real error happens.\n\t\t\t\terr = handlePartialSuccessResponse(resp, tt.handler)\n\t\t\t\tassert.Error(t, err)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestPartialSuccess_longContentLengthHeader(t *testing.T) {\n\tcontentTypes := []struct {\n\t\tcontentType string\n\t}{\n\t\t{contentType: protobufContentType},\n\t\t{contentType: jsonContentType},\n\t}\n\n\ttelemetryTypes := []struct {\n\t\ttelemetryType string\n\t\tserializer    responseSerializerProvider\n\t}{\n\t\t{\n\t\t\ttelemetryType: tracesTelemetryType,\n\t\t\tserializer:    provideTracesResponseSerializer,\n\t\t},\n\t\t{\n\t\t\ttelemetryType: metricsTelemetryType,\n\t\t\tserializer:    provideMetricsResponseSerializer,\n\t\t},\n\t\t{\n\t\t\ttelemetryType: logsTelemetryType,\n\t\t\tserializer:    provideLogsResponseSerializer,\n\t\t},\n\t\t{\n\t\t\ttelemetryType: profilesTelemetryType,\n\t\t\tserializer:    provideProfilesResponseSerializer,\n\t\t},\n\t}\n\n\tfor _, ct := range contentTypes {\n\t\tfor _, tt := range telemetryTypes {\n\t\t\tt.Run(tt.telemetryType+\" \"+ct.contentType, func(t *testing.T) {\n\t\t\t\tcfg := createDefaultConfig()\n\t\t\t\tset := exportertest.NewNopSettings(metadata.Type)\n\t\t\t\tlogger, observed := observer.New(zap.DebugLevel)\n\t\t\t\tset.Logger = zap.New(logger)\n\t\t\t\texp, err := newExporter(cfg, set)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\tserializer := tt.serializer()\n\n\t\t\t\tvar handler partialSuccessHandler\n\n\t\t\t\tswitch tt.telemetryType {\n\t\t\t\tcase tracesTelemetryType:\n\t\t\t\t\thandler = exp.tracesPartialSuccessHandler\n\t\t\t\tcase metricsTelemetryType:\n\t\t\t\t\thandler = exp.metricsPartialSuccessHandler\n\t\t\t\tcase logsTelemetryType:\n\t\t\t\t\thandler = exp.logsPartialSuccessHandler\n\t\t\t\tcase profilesTelemetryType:\n\t\t\t\t\thandler = exp.profilesPartialSuccessHandler\n\t\t\t\tdefault:\n\t\t\t\t\trequire.Failf(t, \"unsupported telemetry type: %s\", ct.contentType)\n\t\t\t\t}\n\n\t\t\t\tvar data []byte\n\n\t\t\t\tswitch ct.contentType {\n\t\t\t\tcase jsonContentType:\n\t\t\t\t\tdata, err = serializer.MarshalJSON()\n\t\t\t\tcase protobufContentType:\n\t\t\t\t\tdata, err = serializer.MarshalProto()\n\t\t\t\tdefault:\n\t\t\t\t\trequire.Failf(t, \"unsupported content type: %s\", ct.contentType)\n\t\t\t\t}\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\tresp := &http.Response{\n\t\t\t\t\tContentLength: 4096,\n\t\t\t\t\tBody:          io.NopCloser(bytes.NewReader(data)),\n\t\t\t\t\tHeader: map[string][]string{\n\t\t\t\t\t\t\"Content-Type\": {ct.contentType},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\t// No real error happens for long content length, so the partial\n\t\t\t\t// success is handled as success with a warning.\n\t\t\t\terr = handlePartialSuccessResponse(resp, handler)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.Len(t, observed.FilterLevelExact(zap.WarnLevel).All(), 1)\n\t\t\t\tassert.Contains(t, observed.FilterLevelExact(zap.WarnLevel).All()[0].Message, \"Partial success\")\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestPartialSuccessInvalidResponseBody(t *testing.T) {\n\tcfg := createDefaultConfig()\n\tset := exportertest.NewNopSettings(metadata.Type)\n\texp, err := newExporter(cfg, set)\n\trequire.NoError(t, err)\n\n\tresp := &http.Response{\n\t\tBody:          io.NopCloser(badReader{}),\n\t\tContentLength: 100,\n\t\tHeader: map[string][]string{\n\t\t\t\"Content-Type\": {protobufContentType},\n\t\t},\n\t}\n\terr = handlePartialSuccessResponse(resp, exp.tracesPartialSuccessHandler)\n\tassert.Error(t, err)\n}\n\nfunc TestPartialSuccess_traces(t *testing.T) {\n\tsrv := createBackend(\"/v1/traces\", func(writer http.ResponseWriter, _ *http.Request) {\n\t\tresponse := ptraceotlp.NewExportResponse()\n\t\tpartial := response.PartialSuccess()\n\t\tpartial.SetErrorMessage(\"hello\")\n\t\tpartial.SetRejectedSpans(1)\n\t\tbytes, err := response.MarshalProto()\n\t\tassert.NoError(t, err)\n\t\twriter.Header().Set(\"Content-Type\", \"application/x-protobuf\")\n\t\t_, err = writer.Write(bytes)\n\t\tassert.NoError(t, err)\n\t})\n\tdefer srv.Close()\n\n\tcfg := &Config{\n\t\tEncoding:       EncodingProto,\n\t\tTracesEndpoint: srv.URL + \"/v1/traces\",\n\t\tClientConfig:   confighttp.ClientConfig{},\n\t}\n\tset := exportertest.NewNopSettings(metadata.Type)\n\tlogger, observed := observer.New(zap.DebugLevel)\n\tset.Logger = zap.New(logger)\n\texp, err := createTraces(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\n\t// start the exporter\n\terr = exp.Start(context.Background(), componenttest.NewNopHost())\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, exp.Shutdown(context.Background()))\n\t})\n\n\t// generate data\n\ttraces := ptrace.NewTraces()\n\terr = exp.ConsumeTraces(context.Background(), traces)\n\trequire.NoError(t, err)\n\trequire.Len(t, observed.FilterLevelExact(zap.WarnLevel).All(), 1)\n\trequire.Contains(t, observed.FilterLevelExact(zap.WarnLevel).All()[0].Message, \"Partial success\")\n}\n\nfunc TestPartialSuccess_metrics(t *testing.T) {\n\tsrv := createBackend(\"/v1/metrics\", func(writer http.ResponseWriter, _ *http.Request) {\n\t\tresponse := pmetricotlp.NewExportResponse()\n\t\tpartial := response.PartialSuccess()\n\t\tpartial.SetErrorMessage(\"hello\")\n\t\tpartial.SetRejectedDataPoints(1)\n\t\tbytes, err := response.MarshalProto()\n\t\tassert.NoError(t, err)\n\t\twriter.Header().Set(\"Content-Type\", \"application/x-protobuf\")\n\t\t_, err = writer.Write(bytes)\n\t\tassert.NoError(t, err)\n\t})\n\tdefer srv.Close()\n\n\tcfg := &Config{\n\t\tEncoding:        EncodingProto,\n\t\tMetricsEndpoint: srv.URL + \"/v1/metrics\",\n\t\tClientConfig:    confighttp.ClientConfig{},\n\t}\n\tset := exportertest.NewNopSettings(metadata.Type)\n\tlogger, observed := observer.New(zap.DebugLevel)\n\tset.Logger = zap.New(logger)\n\texp, err := createMetrics(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\n\t// start the exporter\n\terr = exp.Start(context.Background(), componenttest.NewNopHost())\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, exp.Shutdown(context.Background()))\n\t})\n\n\t// generate data\n\tmetrics := pmetric.NewMetrics()\n\terr = exp.ConsumeMetrics(context.Background(), metrics)\n\trequire.NoError(t, err)\n\trequire.Len(t, observed.FilterLevelExact(zap.WarnLevel).All(), 1)\n\trequire.Contains(t, observed.FilterLevelExact(zap.WarnLevel).All()[0].Message, \"Partial success\")\n}\n\nfunc TestPartialSuccess_profiles(t *testing.T) {\n\tsrv := createBackend(\"/v1development/profiles\", func(writer http.ResponseWriter, _ *http.Request) {\n\t\tresponse := pprofileotlp.NewExportResponse()\n\t\tpartial := response.PartialSuccess()\n\t\tpartial.SetErrorMessage(\"hello\")\n\t\tpartial.SetRejectedProfiles(1)\n\t\tbytes, err := response.MarshalProto()\n\t\tassert.NoError(t, err)\n\t\twriter.Header().Set(\"Content-Type\", \"application/x-protobuf\")\n\t\t_, err = writer.Write(bytes)\n\t\tassert.NoError(t, err)\n\t})\n\tdefer srv.Close()\n\n\tcfg := &Config{\n\t\tEncoding: EncodingProto,\n\t\tClientConfig: confighttp.ClientConfig{\n\t\t\tEndpoint: srv.URL,\n\t\t},\n\t}\n\tset := exportertest.NewNopSettings(metadata.Type)\n\tlogger, observed := observer.New(zap.DebugLevel)\n\tset.Logger = zap.New(logger)\n\texp, err := createProfiles(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\n\t// start the exporter\n\terr = exp.Start(context.Background(), componenttest.NewNopHost())\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, exp.Shutdown(context.Background()))\n\t})\n\n\t// generate data\n\tprofiles := pprofile.NewProfiles()\n\terr = exp.ConsumeProfiles(context.Background(), profiles)\n\trequire.NoError(t, err)\n\trequire.Len(t, observed.FilterLevelExact(zap.WarnLevel).All(), 1)\n\trequire.Contains(t, observed.FilterLevelExact(zap.WarnLevel).All()[0].Message, \"Partial success\")\n}\n\nfunc TestEncoding(t *testing.T) {\n\tset := exportertest.NewNopSettings(metadata.Type)\n\tset.BuildInfo.Description = \"Collector\"\n\tset.BuildInfo.Version = \"1.2.3test\"\n\n\ttests := []struct {\n\t\tname             string\n\t\tencoding         EncodingType\n\t\texpectedEncoding EncodingType\n\t}{\n\t\t{\n\t\t\tname:             \"proto_encoding\",\n\t\t\tencoding:         EncodingProto,\n\t\t\texpectedEncoding: \"application/x-protobuf\",\n\t\t},\n\t\t{\n\t\t\tname:             \"json_encoding\",\n\t\t\tencoding:         EncodingJSON,\n\t\t\texpectedEncoding: \"application/json\",\n\t\t},\n\t}\n\n\tt.Run(\"traces\", func(t *testing.T) {\n\t\tfor _, tt := range tests {\n\t\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t\tsrv := createBackend(\"/v1/traces\", func(writer http.ResponseWriter, request *http.Request) {\n\t\t\t\t\tassert.Contains(t, request.Header.Get(\"content-type\"), tt.expectedEncoding)\n\t\t\t\t\twriter.WriteHeader(http.StatusOK)\n\t\t\t\t})\n\t\t\t\tdefer srv.Close()\n\n\t\t\t\tcfg := &Config{\n\t\t\t\t\tTracesEndpoint: srv.URL + \"/v1/traces\",\n\t\t\t\t\tEncoding:       tt.encoding,\n\t\t\t\t}\n\t\t\t\texp, err := createTraces(context.Background(), set, cfg)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\t// start the exporter\n\t\t\t\terr = exp.Start(context.Background(), componenttest.NewNopHost())\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tt.Cleanup(func() {\n\t\t\t\t\trequire.NoError(t, exp.Shutdown(context.Background()))\n\t\t\t\t})\n\n\t\t\t\t// generate data\n\t\t\t\ttraces := ptrace.NewTraces()\n\t\t\t\terr = exp.ConsumeTraces(context.Background(), traces)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t})\n\t\t}\n\t})\n\n\tt.Run(\"metrics\", func(t *testing.T) {\n\t\tfor _, tt := range tests {\n\t\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t\tsrv := createBackend(\"/v1/metrics\", func(writer http.ResponseWriter, request *http.Request) {\n\t\t\t\t\tassert.Contains(t, request.Header.Get(\"content-type\"), tt.expectedEncoding)\n\t\t\t\t\twriter.WriteHeader(http.StatusOK)\n\t\t\t\t})\n\t\t\t\tdefer srv.Close()\n\n\t\t\t\tcfg := &Config{\n\t\t\t\t\tMetricsEndpoint: srv.URL + \"/v1/metrics\",\n\t\t\t\t\tEncoding:        tt.encoding,\n\t\t\t\t}\n\t\t\t\texp, err := createMetrics(context.Background(), set, cfg)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\t// start the exporter\n\t\t\t\terr = exp.Start(context.Background(), componenttest.NewNopHost())\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tt.Cleanup(func() {\n\t\t\t\t\trequire.NoError(t, exp.Shutdown(context.Background()))\n\t\t\t\t})\n\n\t\t\t\t// generate data\n\t\t\t\tmetrics := pmetric.NewMetrics()\n\t\t\t\terr = exp.ConsumeMetrics(context.Background(), metrics)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t})\n\t\t}\n\t})\n\n\tt.Run(\"logs\", func(t *testing.T) {\n\t\tfor _, tt := range tests {\n\t\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t\tsrv := createBackend(\"/v1/logs\", func(writer http.ResponseWriter, request *http.Request) {\n\t\t\t\t\tassert.Contains(t, request.Header.Get(\"content-type\"), tt.expectedEncoding)\n\t\t\t\t\twriter.WriteHeader(http.StatusOK)\n\t\t\t\t})\n\t\t\t\tdefer srv.Close()\n\n\t\t\t\tcfg := &Config{\n\t\t\t\t\tLogsEndpoint: srv.URL + \"/v1/logs\",\n\t\t\t\t\tEncoding:     tt.encoding,\n\t\t\t\t}\n\t\t\t\texp, err := createLogs(context.Background(), set, cfg)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\t// start the exporter\n\t\t\t\terr = exp.Start(context.Background(), componenttest.NewNopHost())\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tt.Cleanup(func() {\n\t\t\t\t\trequire.NoError(t, exp.Shutdown(context.Background()))\n\t\t\t\t})\n\n\t\t\t\t// generate data\n\t\t\t\tlogs := plog.NewLogs()\n\t\t\t\terr = exp.ConsumeLogs(context.Background(), logs)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\tsrv.Close()\n\t\t\t})\n\t\t}\n\t})\n\n\tt.Run(\"profiles\", func(t *testing.T) {\n\t\tfor _, test := range tests {\n\t\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t\tsrv := createBackend(\"/v1development/profiles\", func(writer http.ResponseWriter, request *http.Request) {\n\t\t\t\t\tassert.Contains(t, request.Header.Get(\"content-type\"), test.expectedEncoding)\n\t\t\t\t\twriter.WriteHeader(http.StatusOK)\n\t\t\t\t})\n\t\t\t\tdefer srv.Close()\n\n\t\t\t\tcfg := &Config{\n\t\t\t\t\tClientConfig: confighttp.ClientConfig{\n\t\t\t\t\t\tEndpoint: srv.URL,\n\t\t\t\t\t},\n\t\t\t\t\tEncoding: test.encoding,\n\t\t\t\t}\n\t\t\t\texp, err := createProfiles(context.Background(), set, cfg)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\t// start the exporter\n\t\t\t\terr = exp.Start(context.Background(), componenttest.NewNopHost())\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tt.Cleanup(func() {\n\t\t\t\t\trequire.NoError(t, exp.Shutdown(context.Background()))\n\t\t\t\t})\n\n\t\t\t\t// generate data\n\t\t\t\tprofiles := pprofile.NewProfiles()\n\t\t\t\terr = exp.ConsumeProfiles(context.Background(), profiles)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t})\n\t\t}\n\t})\n}\n\nfunc createBackend(endpoint string, handler func(writer http.ResponseWriter, request *http.Request)) *httptest.Server {\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(endpoint, handler)\n\n\tsrv := httptest.NewServer(mux)\n\n\treturn srv\n}\n\ntype badReader struct{}\n\nfunc (b badReader) Read([]byte) (int, error) {\n\treturn 0, errors.New(\"Bad read\")\n}\n\ntype mockTransport struct {\n\troundTripFunc func(req *http.Request) (*http.Response, error)\n}\n\nfunc (t *mockTransport) RoundTrip(req *http.Request) (*http.Response, error) {\n\treturn t.roundTripFunc(req)\n}\n\nfunc TestExport_ErrorShowsModifiedURL(t *testing.T) {\n\toriginalURL := \"http://localhost:4318/v1/logs\"\n\tmodifiedURL := \"https://actual-destination.example.com/v1/logs\"\n\n\ttransport := &mockTransport{\n\t\troundTripFunc: func(req *http.Request) (*http.Response, error) {\n\t\t\tparsedModified, err := url.Parse(modifiedURL)\n\t\t\trequire.NoError(t, err)\n\t\t\treq.URL = parsedModified\n\n\t\t\treturn nil, errors.New(\"we need an error logged\")\n\t\t},\n\t}\n\n\tclient := &http.Client{Transport: transport}\n\n\tlogger, _ := observer.New(zap.DebugLevel)\n\texp := &baseExporter{\n\t\tclient: client,\n\t\tlogger: zap.New(logger),\n\t\tconfig: &Config{\n\t\t\tEncoding: EncodingProto,\n\t\t},\n\t}\n\n\terr := exp.export(context.Background(), originalURL, []byte(\"test data\"), nil)\n\n\trequire.Error(t, err)\n\tassert.Contains(t, err.Error(), modifiedURL, \"Error message should contain the modified destination URL\")\n\tassert.NotContains(t, err.Error(), originalURL, \"Error message should NOT contain the original placeholder URL\")\n}\n"
  },
  {
    "path": "exporter/otlphttpexporter/testdata/bad_empty_config.yaml",
    "content": "receivers:\n  nop:\n\nprocessors:\n  nop:\n\nexporters:\n  otlp_http:\n\nservice:\n  pipelines:\n    traces:\n      receivers: [nop]\n      processors: [nop]\n      exporters: [otlp_http]\n"
  },
  {
    "path": "exporter/otlphttpexporter/testdata/bad_invalid_encoding.yaml",
    "content": "encoding: invalid\n"
  },
  {
    "path": "exporter/otlphttpexporter/testdata/config.yaml",
    "content": "endpoint: \"https://1.2.3.4:1234\"\ntls:\n  ca_file: /var/lib/mycert.pem\n  cert_file: certfile\n  key_file: keyfile\n  insecure: true\ntimeout: 10s\nread_buffer_size: 123\nwrite_buffer_size: 345\nsending_queue:\n  enabled: true\n  num_consumers: 2\n  queue_size: 10\nretry_on_failure:\n  enabled: true\n  initial_interval: 10s\n  randomization_factor: 0.7\n  multiplier: 1.3\n  max_interval: 60s\n  max_elapsed_time: 10m\nheaders:\n  \"can you have a . here?\": \"F0000000-0000-0000-0000-000000000000\"\n  header1: \"234\"\n  another: \"somevalue\"\ncompression: gzip\nprofiles_endpoint: \"https://custom.profiles.endpoint:8080/v1development/profiles\"\n"
  },
  {
    "path": "exporter/otlphttpexporter/testdata/test_cert.pem",
    "content": "-----BEGIN CERTIFICATE-----\nMIIE6jCCAtICCQDVU4PtqpqADTANBgkqhkiG9w0BAQsFADA3MQswCQYDVQQGEwJV\nUzETMBEGA1UECAwKY2FsaWZvcm5pYTETMBEGA1UECgwKb3BlbmNlbnN1czAeFw0x\nOTAzMDQxODA3MjZaFw0yMDAzMDMxODA3MjZaMDcxCzAJBgNVBAYTAlVTMRMwEQYD\nVQQIDApjYWxpZm9ybmlhMRMwEQYDVQQKDApvcGVuY2Vuc3VzMIICIjANBgkqhkiG\n9w0BAQEFAAOCAg8AMIICCgKCAgEAy9JQiAOMzArcdiS4szbTuzg5yYijSSY6SvGj\nXMs4/LEFLxgGmFfyHXxoVQzV26lTu/AiUFlZi4JY2qlkZyPwmmmSg4fmzikpVPiC\nVv9pvSIojs8gs0sHaOt40Q8ym43bNt3Mh8rYrs+XMERi6Ol9//j4LnfePkNU5uEo\nqC8KQamckaMR6UEHFNunyOwvNBsipgTPldQUPGVnCsNKk8olYGAXS7DR25bgbPli\n4T9VCSElsSPAODmyo+2MEDagVXa1vVYxKyO2k6oeBS0lsvdRqRTmGggcg0B/dk+a\nH1CL9ful0cu9P3dQif+hfGay8udPkwDLPEq1+WnjJFut3Pmbk3SqUCas5iWt76kK\neKFh4k8fCy4yiaZxzvSbm9+bEBHAl0ZXd8pjvAsBfCKe6G9SBzE1DK4FjWiiEGCb\n5dGsyTKr33q3DekLvT3LF8ZeON/13d9toucX9PqG2HDwMP/Fb4WjQIzOc/H9wIak\npf7u6QBDGUiCMmoDrp1d8RsI1RPbEhoywH0YlLmwgf+cr1dU7vlISf576EsGxFz4\n+/sZjIBvZBHn/x0MH+bs4J8V3vMujfDoRdhL07bK7q/AkEALUxljKEfoWeqiuVzK\nF9BVv3xNhiua2kgPVbMNWPrQ5uotkNp8IykJ3QOuQ3p5pzxdGfpLd6f8gmJDmcbi\nAI9dWTcCAwEAATANBgkqhkiG9w0BAQsFAAOCAgEAVVi4t/Sumre+AGTaU7np9dl2\ntpllbES5ixe6m2uezt5wAzYNNyuQ2mMG2XrSkMy5gvBZRT9nRNSmLV8VEcxZihG0\nYHS5soXnLL3Jdlwxp98WTDPvM1ntxcHyEyqrrg9YDfKn4sOrr5vo2yZzoKwtxtc7\nlue9JormVx7GxMi7NwaUtCbnwAIcqJJpFjt1EhmJOxGqTJPgUvTBdeGvRj30c6fk\npqpUdPbZ7RKPEtbLoMoCBujKnErv+H0G6Vp9WyCHN+Mi9uTMsGwH14cmJjmfwGDC\n8/WF4LdlawFnf/arIp9YcVwcP91d4ywyvbuuo2M7qdosQ7k4uRZ3tyggLYShS3RW\nBMEhMRDz9dM0oKGF+HnaS824BIh6O6Hn82Vt8uCKS7IbEX99/kkN1KcqqQe6Lwjq\ntG/lm4K5yf+FJVDivpZ9mYTvqTBjhTaOp6m3HYSNJfS0hLQVvEuBNXd8bHiXkcLp\nrmFOYUWsjxV1Qku3U5Rner0UpB2Fuw9nJcXuDgWG0gjwzAZ83y3du1VIZp0Ad8Vv\nIYpaucbImGJszMtNXn3l72K1wvQVIhm9eRwYc3QteJzweHaDsbytZEoS/GhTrZIT\nwRe5ZGrjJBJngRANRSm1BH8j6PjLem9mzPb2eytwJJA0lLhUk4vYproVvXcx0vow\n5F+5VB1YB8/tbWePmpo=\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "exporter/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage exporter\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "exporter/xexporter/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "exporter/xexporter/exporter.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xexporter // import \"go.opentelemetry.io/collector/exporter/xexporter\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\n// Profiles is an exporter that can consume profiles.\ntype Profiles interface {\n\tcomponent.Component\n\txconsumer.Profiles\n}\n\ntype Factory interface {\n\texporter.Factory\n\n\t// CreateProfiles creates a Profiles exporter based on this config.\n\t// If the exporter type does not support tracing,\n\t// this function returns the error [pipeline.ErrSignalNotSupported].\n\tCreateProfiles(ctx context.Context, set exporter.Settings, cfg component.Config) (Profiles, error)\n\n\t// ProfilesStability gets the stability level of the Profiles exporter.\n\tProfilesStability() component.StabilityLevel\n}\n\n// FactoryOption apply changes to ReceiverOptions.\ntype FactoryOption interface {\n\t// applyOption applies the option.\n\tapplyOption(o *factory)\n}\n\n// factoryOptionFunc is an ReceiverFactoryOption created through a function.\ntype factoryOptionFunc func(*factory)\n\nfunc (f factoryOptionFunc) applyOption(o *factory) {\n\tf(o)\n}\n\n// CreateProfilesFunc is the equivalent of Factory.CreateProfiles.\ntype CreateProfilesFunc func(context.Context, exporter.Settings, component.Config) (Profiles, error)\n\n// WithTraces overrides the default \"error not supported\" implementation for CreateTraces and the default \"undefined\" stability level.\nfunc WithTraces(createTraces exporter.CreateTracesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, exporter.WithTraces(createTraces, sl))\n\t})\n}\n\n// WithMetrics overrides the default \"error not supported\" implementation for CreateMetrics and the default \"undefined\" stability level.\nfunc WithMetrics(createMetrics exporter.CreateMetricsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, exporter.WithMetrics(createMetrics, sl))\n\t})\n}\n\n// WithLogs overrides the default \"error not supported\" implementation for CreateLogs and the default \"undefined\" stability level.\nfunc WithLogs(createLogs exporter.CreateLogsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, exporter.WithLogs(createLogs, sl))\n\t})\n}\n\n// WithProfiles overrides the default \"error not supported\" implementation for CreateProfilesExporter and the default \"undefined\" stability level.\nfunc WithProfiles(createProfiles CreateProfilesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.profilesStabilityLevel = sl\n\t\to.createProfilesFunc = createProfiles\n\t})\n}\n\n// WithDeprecatedTypeAlias configures a deprecated type alias for the exporter. Only one alias is supported per exporter.\n// When the alias is used in configuration, a deprecation warning is automatically logged.\nfunc WithDeprecatedTypeAlias(alias component.Type) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.SetDeprecatedAlias(alias)\n\t})\n}\n\ntype factory struct {\n\texporter.Factory\n\tcomponentalias.TypeAliasHolder\n\topts                   []exporter.FactoryOption\n\tcreateProfilesFunc     CreateProfilesFunc\n\tprofilesStabilityLevel component.StabilityLevel\n}\n\nfunc (f *factory) ProfilesStability() component.StabilityLevel {\n\treturn f.profilesStabilityLevel\n}\n\nfunc (f *factory) CreateProfiles(ctx context.Context, set exporter.Settings, cfg component.Config) (Profiles, error) {\n\tif f.createProfilesFunc == nil {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\tif err := componentalias.ValidateComponentType(f.Factory, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.createProfilesFunc(ctx, set, cfg)\n}\n\n// NewFactory creates a wrapped exporter.Factory with experimental capabilities.\nfunc NewFactory(cfgType component.Type, createDefaultConfig component.CreateDefaultConfigFunc, options ...FactoryOption) Factory {\n\tf := &factory{TypeAliasHolder: componentalias.NewTypeAliasHolder()}\n\tfor _, opt := range options {\n\t\topt.applyOption(f)\n\t}\n\tf.Factory = exporter.NewFactory(cfgType, createDefaultConfig, f.opts...)\n\tf.Factory.(componentalias.TypeAliasHolder).SetDeprecatedAlias(f.DeprecatedAlias())\n\treturn f\n}\n"
  },
  {
    "path": "exporter/xexporter/exporter_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xexporter\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/internal/experr\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n)\n\nvar testID = component.MustNewID(\"test\")\n\nfunc TestNewFactoryWithProfiles(t *testing.T) {\n\ttestType := component.MustNewType(\"test\")\n\tdefaultCfg := struct{}{}\n\tfactory := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg },\n\t\tWithProfiles(createProfiles, component.StabilityLevelDevelopment),\n\t)\n\tassert.Equal(t, testType, factory.Type())\n\tassert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())\n\n\tassert.Equal(t, component.StabilityLevelDevelopment, factory.ProfilesStability())\n\t_, err := factory.CreateProfiles(context.Background(), exporter.Settings{ID: testID}, &defaultCfg)\n\trequire.NoError(t, err)\n\n\twrongID := component.MustNewID(\"wrong\")\n\twrongIDErrStr := experr.ErrIDMismatch(wrongID, testType).Error()\n\t_, err = factory.CreateProfiles(context.Background(), exporter.Settings{ID: wrongID}, &defaultCfg)\n\tassert.EqualError(t, err, wrongIDErrStr)\n}\n\nvar nopInstance = &nop{\n\tConsumer: consumertest.NewNop(),\n}\n\n// nop stores consumed profiles for testing purposes.\ntype nop struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumertest.Consumer\n}\n\nfunc createProfiles(context.Context, exporter.Settings, component.Config) (Profiles, error) {\n\treturn nopInstance, nil\n}\n\nfunc TestNewFactoryWithDeprecatedAlias(t *testing.T) {\n\ttestType := component.MustNewType(\"newname\")\n\taliasType := component.MustNewType(\"oldname\")\n\tdefaultCfg := struct{}{}\n\n\tf := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg },\n\t\tWithProfiles(createProfiles, component.StabilityLevelAlpha),\n\t\tWithDeprecatedTypeAlias(aliasType),\n\t)\n\n\tassert.Equal(t, testType, f.Type())\n\tassert.Equal(t, aliasType, f.(*factory).Factory.(componentalias.TypeAliasHolder).DeprecatedAlias())\n\tassert.EqualValues(t, &defaultCfg, f.CreateDefaultConfig())\n\n\t_, err := f.CreateProfiles(context.Background(), exporter.Settings{ID: component.MustNewID(\"newname\")}, &defaultCfg)\n\trequire.NoError(t, err)\n\t_, err = f.CreateProfiles(context.Background(), exporter.Settings{ID: component.MustNewID(\"oldname\")}, &defaultCfg)\n\trequire.NoError(t, err)\n\t_, err = f.CreateProfiles(context.Background(), exporter.Settings{ID: component.MustNewID(\"wrongname\")}, &defaultCfg)\n\trequire.Error(t, err)\n}\n"
  },
  {
    "path": "exporter/xexporter/go.mod",
    "content": "module go.opentelemetry.io/collector/exporter/xexporter\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/exporter v1.54.0\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/consumer v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/extension => ../../extension\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/config/configretry => ../../config/configretry\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/receiver => ../../receiver\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/exporter => ../\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/exporter/exportertest => ../exportertest\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../../receiver/receivertest\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../../extension/extensiontest\n\nreplace go.opentelemetry.io/collector/extension/xextension => ../../extension/xextension\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/client => ../../client\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../../config/configoptional\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper => ../exporterhelper\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n"
  },
  {
    "path": "exporter/xexporter/go.sum",
    "content": "github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=\ngithub.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "exporter/xexporter/metadata.yaml",
    "content": "type: xexporter\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  codeowners:\n    active:\n      - mx-psi\n      - dmathieu\n  stability:\n    alpha: [profiles]\n"
  },
  {
    "path": "extension/Makefile",
    "content": "include ../Makefile.Common\n"
  },
  {
    "path": "extension/README.md",
    "content": "# General Information\n\nExtensions provide capabilities on top of the primary functionality of the\ncollector. Generally, extensions are used for implementing components that can\nbe added to the Collector, but which do not require direct access to telemetry\ndata and are not part of the pipelines (like receivers, processors or\nexporters). Example extensions are: Memory Limiter extension that prevents\nout of memory situations or zPages extension that provides live data for \ndebugging different components.\n\nSupported service extensions (sorted alphabetically):\n\n- [Memory Limiter](memorylimiterextension/README.md)\n- [zPages](zpagesextension/README.md)\n\nThe [contributors\nrepository](https://github.com/open-telemetry/opentelemetry-collector-contrib)\nmay have more extensions that can be added to custom builds of the Collector.\n\n## Ordering Extensions\n\nThe order extensions are specified for the service is important as this is the\norder in which each extension will be started and the reverse order in which they\nwill be shutdown. The ordering is determined in the `extensions` tag under the\n`service` tag in the configuration file, example:\n\n```yaml\nservice:\n  # Extensions specified below are going to be loaded by the service in the\n  # order given below, and shutdown on reverse order.\n  extensions: [extension1, extension2]\n```\n"
  },
  {
    "path": "extension/extension.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extension // import \"go.opentelemetry.io/collector/extension\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n)\n\n// Extension is the interface for objects hosted by the OpenTelemetry Collector that\n// don't participate directly on data pipelines but provide some functionality\n// to the service, examples: health check endpoint, z-pages, etc.\ntype Extension interface {\n\tcomponent.Component\n}\n\n// Settings is passed to Factory.Create(...) function.\ntype Settings struct {\n\t// ID returns the ID of the component that will be created.\n\tID component.ID\n\n\tcomponent.TelemetrySettings\n\n\t// BuildInfo can be used by components for informational purposes\n\tBuildInfo component.BuildInfo\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// CreateFunc is the equivalent of Factory.Create(...) function.\ntype CreateFunc func(context.Context, Settings, component.Config) (Extension, error)\n\ntype Factory interface {\n\tcomponent.Factory\n\n\t// Create an extension based on the given config.\n\tCreate(ctx context.Context, set Settings, cfg component.Config) (Extension, error)\n\n\t// Stability gets the stability level of the Extension.\n\tStability() component.StabilityLevel\n\n\tunexportedFactoryFunc()\n}\n\ntype factory struct {\n\tcfgType component.Type\n\tcomponent.CreateDefaultConfigFunc\n\tcomponentalias.TypeAliasHolder\n\tcreateFunc         CreateFunc\n\textensionStability component.StabilityLevel\n}\n\nfunc (f *factory) Type() component.Type {\n\treturn f.cfgType\n}\n\nfunc (f *factory) unexportedFactoryFunc() {}\n\nfunc (f *factory) Stability() component.StabilityLevel {\n\treturn f.extensionStability\n}\n\nfunc (f *factory) Create(ctx context.Context, set Settings, cfg component.Config) (Extension, error) {\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createFunc(ctx, set, cfg)\n}\n\n// NewFactory returns a new Factory  based on this configuration.\nfunc NewFactory(\n\tcfgType component.Type,\n\tcreateDefaultConfig component.CreateDefaultConfigFunc,\n\tcreateServiceExtension CreateFunc,\n\tsl component.StabilityLevel,\n) Factory {\n\treturn &factory{\n\t\tcfgType:                 cfgType,\n\t\tCreateDefaultConfigFunc: createDefaultConfig,\n\t\tTypeAliasHolder:         componentalias.NewTypeAliasHolder(),\n\t\tcreateFunc:              createServiceExtension,\n\t\textensionStability:      sl,\n\t}\n}\n"
  },
  {
    "path": "extension/extension_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extension\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\ntype nopExtension struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tSettings\n}\n\nfunc TestNewFactory(t *testing.T) {\n\ttestType := component.MustNewType(\"test\")\n\tdefaultCfg := struct{}{}\n\tnopExtensionInstance := new(nopExtension)\n\n\tfactory := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg },\n\t\tfunc(context.Context, Settings, component.Config) (Extension, error) {\n\t\t\treturn nopExtensionInstance, nil\n\t\t},\n\t\tcomponent.StabilityLevelDevelopment)\n\tassert.Equal(t, testType, factory.Type())\n\tassert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())\n\n\tassert.Equal(t, component.StabilityLevelDevelopment, factory.Stability())\n\text, err := factory.Create(context.Background(), Settings{ID: component.NewID(testType)}, &defaultCfg)\n\trequire.NoError(t, err)\n\tassert.Same(t, nopExtensionInstance, ext)\n\n\t_, err = factory.Create(context.Background(), Settings{ID: component.NewID(component.MustNewType(\"mismatch\"))}, &defaultCfg)\n\trequire.Error(t, err)\n}\n"
  },
  {
    "path": "extension/extensionauth/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "extension/extensionauth/client.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionauth // import \"go.opentelemetry.io/collector/extension/extensionauth\"\n\nimport (\n\t\"net/http\"\n\n\t\"google.golang.org/grpc/credentials\"\n)\n\n// HTTPClient is an optional Extension interface that can be used as an HTTP authenticator for the configauth.Config option.\n// Authenticators are then included as part of OpenTelemetry Collector builds and can be referenced by their\n// names from the [configauth.Config] configuration.\ntype HTTPClient interface {\n\t// RoundTripper returns a RoundTripper that can be used to authenticate HTTP requests.\n\tRoundTripper(base http.RoundTripper) (http.RoundTripper, error)\n}\n\n// GRPCClient is an optional Extension interface that can be used as a gRPC authenticator for the configauth.Config option.\n// Authenticators are then included as part of OpenTelemetry Collector builds and can be referenced by their\n// names from the [configauth.Config] configuration.\ntype GRPCClient interface {\n\t// PerRPCCredentials returns a PerRPCCredentials that can be used to authenticate gRPC requests.\n\tPerRPCCredentials() (credentials.PerRPCCredentials, error)\n}\n\nvar _ HTTPClient = (*ClientRoundTripperFunc)(nil)\n\n// ClientRoundTripperFunc specifies the function that returns a RoundTripper that can be used to authenticate HTTP requests.\ntype ClientRoundTripperFunc func(base http.RoundTripper) (http.RoundTripper, error)\n\nfunc (f ClientRoundTripperFunc) RoundTripper(base http.RoundTripper) (http.RoundTripper, error) {\n\tif f == nil {\n\t\treturn base, nil\n\t}\n\treturn f(base)\n}\n\nvar _ GRPCClient = (*ClientPerRPCCredentialsFunc)(nil)\n\n// ClientPerRPCCredentialsFunc specifies the function that returns a PerRPCCredentials that can be used to authenticate gRPC requests.\ntype ClientPerRPCCredentialsFunc func() (credentials.PerRPCCredentials, error)\n\nfunc (f ClientPerRPCCredentialsFunc) PerRPCCredentials() (credentials.PerRPCCredentials, error) {\n\tif f == nil {\n\t\treturn nil, nil\n\t}\n\treturn f()\n}\n"
  },
  {
    "path": "extension/extensionauth/client_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionauth\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc/credentials\"\n)\n\nfunc TestRoundTripperFunc(t *testing.T) {\n\tvar called bool\n\tvar httpClient HTTPClient = ClientRoundTripperFunc(func(base http.RoundTripper) (http.RoundTripper, error) {\n\t\tcalled = true\n\t\treturn base, nil\n\t})\n\n\trt, err := httpClient.RoundTripper(http.DefaultTransport)\n\trequire.NoError(t, err)\n\tassert.True(t, called)\n\tassert.Equal(t, http.DefaultTransport, rt)\n}\n\ntype customPerRPCCredentials struct{}\n\nvar _ credentials.PerRPCCredentials = (*customPerRPCCredentials)(nil)\n\nfunc (c *customPerRPCCredentials) GetRequestMetadata(context.Context, ...string) (map[string]string, error) {\n\treturn nil, nil\n}\n\nfunc (c *customPerRPCCredentials) RequireTransportSecurity() bool {\n\treturn true\n}\n\nfunc TestWithPerRPCCredentialsFunc(t *testing.T) {\n\tvar called bool\n\tvar grpcClient GRPCClient = ClientPerRPCCredentialsFunc(func() (credentials.PerRPCCredentials, error) {\n\t\tcalled = true\n\t\treturn &customPerRPCCredentials{}, nil\n\t})\n\n\tcreds, err := grpcClient.PerRPCCredentials()\n\trequire.NoError(t, err)\n\tassert.True(t, called)\n\tassert.NotNil(t, creds)\n}\n"
  },
  {
    "path": "extension/extensionauth/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package auth implements the configuration settings to\n// ensure authentication on incoming requests, and allows\n// exporters to add authentication on outgoing requests.\npackage extensionauth // import \"go.opentelemetry.io/collector/extension/extensionauth\"\n"
  },
  {
    "path": "extension/extensionauth/extensionauthtest/Makefile",
    "content": "include ../../../Makefile.Common\n"
  },
  {
    "path": "extension/extensionauth/extensionauthtest/err.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionauthtest // import \"go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest\"\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"google.golang.org/grpc/credentials\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensionauth\"\n)\n\nvar (\n\t_ extension.Extension      = (*errClient)(nil)\n\t_ extensionauth.HTTPClient = (*errClient)(nil)\n\t_ extensionauth.GRPCClient = (*errClient)(nil)\n)\n\ntype errClient struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\textensionauth.ClientPerRPCCredentialsFunc\n\textensionauth.ClientRoundTripperFunc\n\textensionauth.ServerAuthenticateFunc\n}\n\n// NewErr returns a new [extension.Extension] that implements all\n// extensionauth interface and always returns an error.\nfunc NewErr(err error) extension.Extension {\n\treturn &errClient{\n\t\tClientRoundTripperFunc: func(http.RoundTripper) (http.RoundTripper, error) {\n\t\t\treturn nil, err\n\t\t},\n\t\tClientPerRPCCredentialsFunc: func() (credentials.PerRPCCredentials, error) {\n\t\t\treturn nil, err\n\t\t},\n\t\tServerAuthenticateFunc: func(ctx context.Context, _ map[string][]string) (context.Context, error) { return ctx, err },\n\t}\n}\n"
  },
  {
    "path": "extension/extensionauth/extensionauthtest/err_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionauthtest\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/extension/extensionauth\"\n)\n\nfunc TestErrorClient(t *testing.T) {\n\tclient := NewErr(errors.New(\"error\"))\n\n\thttpClient, ok := client.(extensionauth.HTTPClient)\n\trequire.True(t, ok)\n\t_, err := httpClient.RoundTripper(nil)\n\trequire.Error(t, err)\n\n\tgrpcClient, ok := client.(extensionauth.GRPCClient)\n\trequire.True(t, ok)\n\t_, err = grpcClient.PerRPCCredentials()\n\trequire.Error(t, err)\n\n\tserver, ok := client.(extensionauth.Server)\n\trequire.True(t, ok)\n\t_, err = server.Authenticate(context.Background(), map[string][]string{})\n\trequire.Error(t, err)\n}\n"
  },
  {
    "path": "extension/extensionauth/extensionauthtest/go.mod",
    "content": "module go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/extension v1.54.0\n\tgo.opentelemetry.io/collector/extension/extensionauth v1.54.0\n\tgo.uber.org/goleak v1.3.0\n\tgoogle.golang.org/grpc v1.79.3\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/extension/extensionauth => ..\n\nreplace go.opentelemetry.io/collector/component => ../../../component\n\nreplace go.opentelemetry.io/collector/pdata => ../../../pdata\n\nreplace go.opentelemetry.io/collector/extension => ../..\n\nreplace go.opentelemetry.io/collector/featuregate => ../../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../../internal/componentalias\n"
  },
  {
    "path": "extension/extensionauth/extensionauthtest/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "extension/extensionauth/extensionauthtest/metadata.yaml",
    "content": "type: extensionauth/extensionauthtest\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "extension/extensionauth/extensionauthtest/nop_client.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionauthtest // import \"go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest\"\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensionauth\"\n)\n\nvar (\n\t_ extension.Extension      = (*nopClient)(nil)\n\t_ extensionauth.HTTPClient = (*nopClient)(nil)\n\t_ extensionauth.GRPCClient = (*nopClient)(nil)\n)\n\ntype nopClient struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\textensionauth.ClientRoundTripperFunc\n\textensionauth.ClientPerRPCCredentialsFunc\n}\n\n// NewNopClient returns a new [extension.Extension] that implements the [extensionauth.HTTPClient] and [extensionauth.GRPCClient].\n// For HTTP requests it returns the base RoundTripper and for gRPC requests it returns a nil [credentials.PerRPCCredentials].\nfunc NewNopClient() extension.Extension {\n\treturn &nopClient{}\n}\n"
  },
  {
    "path": "extension/extensionauth/extensionauthtest/nop_client_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionauthtest\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/extension/extensionauth\"\n)\n\nfunc TestNopClient(t *testing.T) {\n\tclient := NewNopClient()\n\n\thttpClient, ok := client.(extensionauth.HTTPClient)\n\trequire.True(t, ok)\n\trt, err := httpClient.RoundTripper(nil)\n\trequire.NoError(t, err)\n\tassert.Nil(t, rt)\n\n\tgrpcClient, ok := client.(extensionauth.GRPCClient)\n\trequire.True(t, ok)\n\tgrpcAuth, err := grpcClient.PerRPCCredentials()\n\trequire.NoError(t, err)\n\tassert.Nil(t, grpcAuth)\n}\n"
  },
  {
    "path": "extension/extensionauth/extensionauthtest/nop_server.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionauthtest // import \"go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensionauth\"\n)\n\nvar (\n\t_ extension.Extension  = (*nopServer)(nil)\n\t_ extensionauth.Server = (*nopServer)(nil)\n)\n\ntype nopServer struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n}\n\n// Authenticate implements extensionauth.Server.\nfunc (n *nopServer) Authenticate(ctx context.Context, _ map[string][]string) (context.Context, error) {\n\treturn ctx, nil\n}\n\n// NewNopServer returns a new extension.Extension that implements the extensionauth.Server.\nfunc NewNopServer() extension.Extension {\n\treturn &nopServer{}\n}\n"
  },
  {
    "path": "extension/extensionauth/extensionauthtest/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionauthtest\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "extension/extensionauth/go.mod",
    "content": "module go.opentelemetry.io/collector/extension/extensionauth\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.uber.org/goleak v1.3.0\n\tgoogle.golang.org/grpc v1.79.3\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/kr/pretty v0.3.1 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/rogpeppe/go-internal v1.13.1 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n"
  },
  {
    "path": "extension/extensionauth/go.sum",
    "content": "github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=\ngithub.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "extension/extensionauth/metadata.yaml",
    "content": "type: extensionauth\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "extension/extensionauth/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionauth\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "extension/extensionauth/server.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionauth // import \"go.opentelemetry.io/collector/extension/extensionauth\"\n\nimport (\n\t\"context\"\n)\n\n// Server is an optional Extension interface that can be used as an authenticator for the configauth.Config option.\n// Authenticators are then included as part of OpenTelemetry Collector builds and can be referenced by their\n// names from the [configauth.Config] configuration. Each Server is free to define its own behavior and configuration options,\n// but note that the expectations that come as part of Extensions exist here as well. For instance, multiple instances of the same\n// authenticator should be possible to exist under different names.\ntype Server interface {\n\t// Authenticate checks whether the given map contains valid auth data. Successfully authenticated calls will always return a nil error.\n\t// When the authentication fails, an error must be returned and the caller must not retry. This function is typically called from interceptors,\n\t// on behalf of receivers, but receivers can still call this directly if the usage of interceptors isn't suitable.\n\t// The deadline and cancellation given to this function must be respected, but note that authentication data has to be part of the map, not context.\n\t// The resulting context should contain the authentication data, such as the principal/username, group membership (if available), and the raw\n\t// authentication data (if possible). This will allow other components in the pipeline to make decisions based on that data, such as routing based\n\t// on tenancy as determined by the group membership, or passing through the authentication data to the next collector/backend.\n\t// The context keys to be used are not defined yet.\n\tAuthenticate(ctx context.Context, sources map[string][]string) (context.Context, error)\n}\n\n// ServerAuthenticateFunc defines the signature for the function responsible for performing the authentication based\n// on the given sources map. See Server.Authenticate.\ntype ServerAuthenticateFunc func(ctx context.Context, sources map[string][]string) (context.Context, error)\n\nfunc (f ServerAuthenticateFunc) Authenticate(ctx context.Context, sources map[string][]string) (context.Context, error) {\n\tif f == nil {\n\t\treturn ctx, nil\n\t}\n\treturn f(ctx, sources)\n}\n"
  },
  {
    "path": "extension/extensionauth/server_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionauth\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestServerAuthenticateFunc(t *testing.T) {\n\tvar called bool\n\tvar server Server = ServerAuthenticateFunc(func(ctx context.Context, _ map[string][]string) (context.Context, error) {\n\t\tcalled = true\n\t\treturn ctx, nil\n\t})\n\n\tctx, err := server.Authenticate(context.Background(), nil)\n\trequire.NoError(t, err)\n\tassert.True(t, called)\n\tassert.NotNil(t, ctx)\n}\n"
  },
  {
    "path": "extension/extensioncapabilities/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "extension/extensioncapabilities/go.mod",
    "content": "module go.opentelemetry.io/collector/extension/extensioncapabilities\n\ngo 1.25.0\n\nrequire (\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/extension v1.54.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n)\n\nreplace go.opentelemetry.io/collector/extension => ../\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "extension/extensioncapabilities/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "extension/extensioncapabilities/interfaces.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package extensioncapabilities provides interfaces that can be implemented by extensions\n// to provide additional capabilities.\npackage extensioncapabilities // import \"go.opentelemetry.io/collector/extension/extensioncapabilities\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/extension\"\n)\n\n// Dependent is an optional interface that can be implemented by extensions\n// that depend on other extensions and must be started only after their dependencies.\n// See https://github.com/open-telemetry/opentelemetry-collector/pull/8768 for examples.\ntype Dependent interface {\n\textension.Extension\n\tDependencies() []component.ID\n}\n\n// PipelineWatcher is an extra interface for Extension hosted by the OpenTelemetry\n// Collector that is to be implemented by extensions interested in changes to pipeline\n// states. Typically this will be used by extensions that change their behavior if data is\n// being ingested or not, e.g.: a k8s readiness probe.\ntype PipelineWatcher interface {\n\t// Ready notifies the Extension that all pipelines were built and the\n\t// receivers were started, i.e.: the service is ready to receive data\n\t// (note that it may already have received data when this method is called).\n\tReady() error\n\n\t// NotReady notifies the Extension that all receivers are about to be stopped,\n\t// i.e.: pipeline receivers will not accept new data.\n\t// This is sent before receivers are stopped, so the Extension can take any\n\t// appropriate actions before that happens.\n\tNotReady() error\n}\n\n// ConfigWatcher is an interface that should be implemented by an extension that\n// wishes to be notified of the Collector's effective configuration.\ntype ConfigWatcher interface {\n\t// NotifyConfig notifies the extension of the Collector's current effective configuration.\n\t// The extension owns the `confmap.Conf`. Callers must ensure that it's safe for\n\t// extensions to store the `conf` pointer and use it concurrently with any other\n\t// instances of `conf`.\n\tNotifyConfig(ctx context.Context, conf *confmap.Conf) error\n}\n"
  },
  {
    "path": "extension/extensioncapabilities/metadata.yaml",
    "content": "type: extensioncapabilities\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "extension/extensionmiddleware/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "extension/extensionmiddleware/README.md",
    "content": "# OpenTelemetry Collector Middleware Extension API\n\nThis package implements interfaces for injecting middleware behavior\nin OpenTelemetry Collector exporters and receivers.  See the\n[associated `configmiddleware` package](../../config/configmiddleware/README.md)\nfor referring to middleware\nextensions in component configurations.\n\n## Overview\n\nMiddleware extensions can be configured on gRPC and HTTP connections,\non both the client and server side.  The term \"middleware\" is defined\nbroadly to cover many ways of intercepting, acting on, and observing\nrequests as they enter and exit and RPC system.\n\nMiddleware details and capabilities are specific to each protocol.  In\nsome cases, these interfaces permit configuring behavior other than\nmiddleware.  Users have to place a trust in the extensions they\nconfigure, since they are capable of subverting security and other RPC\nconfiguration.\n\nMiddleware is generally configured at a level in the code where:\n\n1. the identity of the calling component is not known, because\n   `confighttp` and `configgrpc` interfaces likewise are not configured\n   with the identify of the calling component.\n2. the signal type in use is not known, because a single connection\n   serves multiple signals.\n\n## Interfaces\n\nEach interface has a single function to configure middleware for a\nprotocol on the client or server side.  An error is returned if the\nextension cannot be configured.\n\nNew protocols and new ways to configure middleware can be introduced\nby adding new interfaces.  Note that for each interface, there is a\ncorresponding method to locate a named middleware extension that\nsatisfies the interface in\n[the `configmiddleware` package](../../config/configmiddleware/README.md) .\n\n### HTTP\n\nInterface methods are called once per request to construct a client-\nor server-side middleware object.\n\n- **HTTPClient**: The extension returns a function to create new `http.RoundTripper`s.\n- **HTTPServer**: The extension returns a function to create new `http.Handler`s.\n\n### GRPC\n\nInterface methods are called once at setup to configure the client- or\nserver-side middleware object.\n\n- **GRPCClient**: The extension returns `[]grpc.DialOption`.\n- **GRPCServer**: The extension returns `[]grpc.ServerOption`.\n"
  },
  {
    "path": "extension/extensionmiddleware/client.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionmiddleware // import \"go.opentelemetry.io/collector/extension/extensionmiddleware\"\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"google.golang.org/grpc\"\n)\n\n// HTTPClient is an interface for HTTP client middleware extensions.\ntype HTTPClient interface {\n\t// GetHTTPRoundTripper initializes a client HTTP RoundTripper\n\t// wrapper, this typically called when the Collector\n\t// starts. If there is an error this returns a nil\n\t// function. If the error is nil, the WrapHTTPRoundTripperFunc\n\t// will never be nil.\n\tGetHTTPRoundTripper(context.Context) (WrapHTTPRoundTripperFunc, error)\n}\n\n// GRPCClient is an interface for gRPC client middleware extensions.\ntype GRPCClient interface {\n\t// GetGRPCClientOptions returns the gRPC dial options to use for client connections.\n\tGetGRPCClientOptions(context.Context) ([]grpc.DialOption, error)\n}\n\nvar _ HTTPClient = (*GetHTTPRoundTripperFunc)(nil)\n\n// GetHTTPRoundTripperFunc is a function that implements HTTPClient.\ntype GetHTTPRoundTripperFunc func(context.Context) (WrapHTTPRoundTripperFunc, error)\n\nfunc (f GetHTTPRoundTripperFunc) GetHTTPRoundTripper(ctx context.Context) (WrapHTTPRoundTripperFunc, error) {\n\tif f == nil {\n\t\treturn func(_ context.Context, rt http.RoundTripper) (http.RoundTripper, error) { return rt, nil }, nil\n\t}\n\treturn f(ctx)\n}\n\nvar _ GRPCClient = (*GetGRPCClientOptionsFunc)(nil)\n\n// GetGRPCClientOptionsFunc is a function that implements GRPCClient.\ntype GetGRPCClientOptionsFunc func(context.Context) ([]grpc.DialOption, error)\n\nfunc (f GetGRPCClientOptionsFunc) GetGRPCClientOptions(ctx context.Context) ([]grpc.DialOption, error) {\n\tif f == nil {\n\t\treturn nil, nil\n\t}\n\treturn f(ctx)\n}\n\n// WrapHTTPRoundTripperFunc is called to initialize a new instance of\n// HTTP client middleware.\ntype WrapHTTPRoundTripperFunc = func(context.Context, http.RoundTripper) (http.RoundTripper, error)\n"
  },
  {
    "path": "extension/extensionmiddleware/client_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionmiddleware\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net/http\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc\"\n)\n\nfunc TestGetHTTPRoundTripperFunc(t *testing.T) {\n\t// Create a base round tripper for testing\n\tbaseRT := http.DefaultTransport\n\ttestctx := context.Background()\n\n\tt.Run(\"nil function\", func(t *testing.T) {\n\t\tvar nilFunc GetHTTPRoundTripperFunc\n\t\trtfunc, err := nilFunc.GetHTTPRoundTripper(testctx)\n\t\trequire.NoError(t, err)\n\n\t\trt, err := rtfunc(testctx, baseRT)\n\t\trequire.NoError(t, err)\n\t\trequire.Equal(t, baseRT, rt)\n\t})\n\n\tt.Run(\"identity function\", func(t *testing.T) {\n\t\tidentityFunc := GetHTTPRoundTripperFunc(nil)\n\t\trtfunc, err := identityFunc.GetHTTPRoundTripper(testctx)\n\t\trequire.NoError(t, err)\n\t\trt, err := rtfunc(testctx, baseRT)\n\t\trequire.NoError(t, err)\n\t\trequire.Equal(t, baseRT, rt)\n\t})\n\n\tt.Run(\"error function\", func(t *testing.T) {\n\t\texpectedErr := errors.New(\"round tripper error\")\n\t\terrorFunc := GetHTTPRoundTripperFunc(func(_ context.Context) (WrapHTTPRoundTripperFunc, error) {\n\t\t\treturn nil, expectedErr\n\t\t})\n\t\trtfunc, err := errorFunc.GetHTTPRoundTripper(testctx)\n\t\trequire.Error(t, err)\n\t\trequire.Equal(t, expectedErr, err)\n\t\trequire.Nil(t, rtfunc)\n\t})\n}\n\nfunc TestGetGRPCClientOptionsFunc(t *testing.T) {\n\ttype testCtx struct{}\n\tvar (\n\t\tkey   = testCtx{}\n\t\tvalue = \"testval\"\n\t)\n\ttestctx := context.WithValue(context.Background(), key, value)\n\n\tt.Run(\"nil function\", func(t *testing.T) {\n\t\tvar nilFunc GetGRPCClientOptionsFunc\n\t\toptions, err := nilFunc.GetGRPCClientOptions(testctx)\n\t\trequire.NoError(t, err)\n\t\trequire.Nil(t, options)\n\t})\n\n\tt.Run(\"options function\", func(t *testing.T) {\n\t\tdialOpt1 := grpc.WithAuthority(\"test-authority\")\n\t\tdialOpt2 := grpc.WithDisableRetry()\n\n\t\toptionsFunc := GetGRPCClientOptionsFunc(func(ctx context.Context) ([]grpc.DialOption, error) {\n\t\t\trequire.Equal(t, ctx.Value(key), value)\n\t\t\treturn []grpc.DialOption{dialOpt1, dialOpt2}, nil\n\t\t})\n\n\t\toptions, err := optionsFunc.GetGRPCClientOptions(testctx)\n\t\trequire.NoError(t, err)\n\t\trequire.Len(t, options, 2)\n\t})\n\n\tt.Run(\"error function\", func(t *testing.T) {\n\t\texpectedErr := errors.New(\"grpc options error\")\n\t\terrorFunc := GetGRPCClientOptionsFunc(func(ctx context.Context) ([]grpc.DialOption, error) {\n\t\t\trequire.Equal(t, ctx.Value(key), value)\n\t\t\treturn nil, expectedErr\n\t\t})\n\n\t\toptions, err := errorFunc.GetGRPCClientOptions(testctx)\n\t\trequire.Error(t, err)\n\t\trequire.Equal(t, expectedErr, err)\n\t\trequire.Nil(t, options)\n\t})\n}\n"
  },
  {
    "path": "extension/extensionmiddleware/extensionmiddlewaretest/Makefile",
    "content": "include ../../../Makefile.Common\n"
  },
  {
    "path": "extension/extensionmiddleware/extensionmiddlewaretest/err.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionmiddlewaretest // import \"go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest\"\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensionmiddleware\"\n)\n\nvar (\n\t_ extension.Extension            = (*baseExtension)(nil)\n\t_ extensionmiddleware.HTTPClient = (*baseExtension)(nil)\n\t_ extensionmiddleware.GRPCClient = (*baseExtension)(nil)\n\t_ extensionmiddleware.HTTPServer = (*baseExtension)(nil)\n\t_ extensionmiddleware.GRPCServer = (*baseExtension)(nil)\n)\n\ntype baseExtension struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\textensionmiddleware.GetHTTPHandlerFunc\n\textensionmiddleware.GetGRPCServerOptionsFunc\n\textensionmiddleware.GetHTTPRoundTripperFunc\n\textensionmiddleware.GetGRPCClientOptionsFunc\n}\n\n// NewErr returns a new [extension.Extension] that implements all\n// extensionmiddleware interface and always returns an error.\nfunc NewErr(err error) extension.Extension {\n\treturn &baseExtension{\n\t\tGetHTTPRoundTripperFunc: func(context.Context) (extensionmiddleware.WrapHTTPRoundTripperFunc, error) {\n\t\t\treturn nil, err\n\t\t},\n\t\tGetGRPCClientOptionsFunc: func(context.Context) ([]grpc.DialOption, error) {\n\t\t\treturn nil, err\n\t\t},\n\t\tGetHTTPHandlerFunc: func(context.Context) (extensionmiddleware.WrapHTTPHandlerFunc, error) {\n\t\t\treturn nil, err\n\t\t},\n\t\tGetGRPCServerOptionsFunc: func(context.Context) ([]grpc.ServerOption, error) {\n\t\t\treturn nil, err\n\t\t},\n\t}\n}\n"
  },
  {
    "path": "extension/extensionmiddleware/extensionmiddlewaretest/err_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionmiddlewaretest\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/extension/extensionmiddleware\"\n)\n\nfunc TestErrClient(t *testing.T) {\n\tclient := NewErr(errors.New(\"error\"))\n\n\thttpClient, ok := client.(extensionmiddleware.HTTPClient)\n\trequire.True(t, ok)\n\t_, err := httpClient.GetHTTPRoundTripper(context.Background())\n\trequire.Error(t, err)\n\n\tgrpcClient, ok := client.(extensionmiddleware.GRPCClient)\n\trequire.True(t, ok)\n\t_, err = grpcClient.GetGRPCClientOptions(context.Background())\n\trequire.Error(t, err)\n}\n\nfunc TestErrServer(t *testing.T) {\n\tserver := NewErr(errors.New(\"error\"))\n\ttestctx := context.Background()\n\n\thttpServer, ok := server.(extensionmiddleware.HTTPServer)\n\trequire.True(t, ok)\n\t_, err := httpServer.GetHTTPHandler(testctx)\n\trequire.Error(t, err)\n\n\tgrpcServer, ok := server.(extensionmiddleware.GRPCServer)\n\trequire.True(t, ok)\n\t_, err = grpcServer.GetGRPCServerOptions(context.Background())\n\trequire.Error(t, err)\n}\n"
  },
  {
    "path": "extension/extensionmiddleware/extensionmiddlewaretest/go.mod",
    "content": "module go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/extension v1.54.0\n\tgo.opentelemetry.io/collector/extension/extensionmiddleware v0.148.0\n\tgoogle.golang.org/grpc v1.79.3\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ..\n\nreplace go.opentelemetry.io/collector/component => ../../../component\n\nreplace go.opentelemetry.io/collector/pdata => ../../../pdata\n\nreplace go.opentelemetry.io/collector/extension => ../..\n\nreplace go.opentelemetry.io/collector/featuregate => ../../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../../internal/componentalias\n"
  },
  {
    "path": "extension/extensionmiddleware/extensionmiddlewaretest/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18=\ngo.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE=\ngo.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8=\ngo.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=\ngonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "extension/extensionmiddleware/extensionmiddlewaretest/metadata.yaml",
    "content": "type: extensionmiddleware/extensionmiddlewaretest\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "extension/extensionmiddleware/extensionmiddlewaretest/nop.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionmiddlewaretest // import \"go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest\"\n\nimport (\n\t\"net/http\"\n\n\t\"go.opentelemetry.io/collector/extension\"\n)\n\n// NewNop returns a new [extension.Extension] that implements\n// the all the extensionmiddleware interfaces.  For HTTP requests it\n// returns the base RoundTripper and for gRPC requests it returns an\n// empty slice of options.\nfunc NewNop() extension.Extension {\n\treturn &baseExtension{}\n}\n\n// RoundTripperFunc implements an HTTP client middleware function.  This\n// is the equivalent of net/http.HandlerFunc for creating a\n// net/http.RoundTripper from a function.\ntype RoundTripperFunc func(*http.Request) (*http.Response, error)\n\nfunc (f RoundTripperFunc) RoundTrip(req *http.Request) (*http.Response, error) {\n\treturn f(req)\n}\n"
  },
  {
    "path": "extension/extensionmiddleware/extensionmiddlewaretest/nop_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionmiddlewaretest\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/extension/extensionmiddleware\"\n)\n\nfunc TestNopClient(t *testing.T) {\n\ttestctx := context.Background()\n\tclient := NewNop()\n\n\thttpClient, ok := client.(extensionmiddleware.HTTPClient)\n\trequire.True(t, ok)\n\trtfunc, err := httpClient.GetHTTPRoundTripper(context.Background())\n\trequire.NoError(t, err)\n\n\trt, err := rtfunc(testctx, nil)\n\trequire.NoError(t, err)\n\trequire.Nil(t, rt)\n\n\tgrpcClient, ok := client.(extensionmiddleware.GRPCClient)\n\trequire.True(t, ok)\n\tgrpcOpts, err := grpcClient.GetGRPCClientOptions(context.Background())\n\trequire.NoError(t, err)\n\trequire.Nil(t, grpcOpts)\n}\n\nfunc TestNopServer(t *testing.T) {\n\tclient := NewNop()\n\ttestctx := context.Background()\n\n\thttpServer, ok := client.(extensionmiddleware.HTTPServer)\n\trequire.True(t, ok)\n\thfunc, err := httpServer.GetHTTPHandler(testctx)\n\trequire.NoError(t, err)\n\n\thandler, err := hfunc(testctx, nil)\n\trequire.NoError(t, err)\n\trequire.Nil(t, handler)\n\n\tgrpcServer, ok := client.(extensionmiddleware.GRPCServer)\n\trequire.True(t, ok)\n\tgrpcOpts, err := grpcServer.GetGRPCServerOptions(context.Background())\n\trequire.NoError(t, err)\n\trequire.Nil(t, grpcOpts)\n}\n\nfunc TestRoundTripperFunc(t *testing.T) {\n\tcalled := false\n\treq := &http.Request{}\n\tresp := &http.Response{}\n\n\tf := RoundTripperFunc(func(r *http.Request) (*http.Response, error) {\n\t\trequire.Equal(t, r, req)\n\t\tcalled = true\n\t\treturn resp, nil\n\t})\n\n\tresult, _ := f.RoundTrip(req)\n\trequire.True(t, called)\n\trequire.Equal(t, resp, result)\n}\n"
  },
  {
    "path": "extension/extensionmiddleware/go.mod",
    "content": "module go.opentelemetry.io/collector/extension/extensionmiddleware\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgoogle.golang.org/grpc v1.79.3\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n"
  },
  {
    "path": "extension/extensionmiddleware/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48=\ngo.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8=\ngo.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0=\ngo.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs=\ngo.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18=\ngo.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE=\ngo.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8=\ngo.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew=\ngo.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI=\ngo.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=\ngonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "extension/extensionmiddleware/metadata.yaml",
    "content": "type: extensionmiddleware\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "extension/extensionmiddleware/server.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionmiddleware // import \"go.opentelemetry.io/collector/extension/extensionmiddleware\"\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"google.golang.org/grpc\"\n)\n\n// HTTPServer defines the interface for HTTP server middleware extensions.\ntype HTTPServer interface {\n\t// GetHTTPHandler wraps the provided base http.Handler.\n\tGetHTTPHandler(_ context.Context) (WrapHTTPHandlerFunc, error)\n}\n\n// GRPCServer defines the interface for gRPC server middleware extensions.\ntype GRPCServer interface {\n\t// GetGRPCServerOptions returns options for a gRPC server.\n\tGetGRPCServerOptions(context.Context) ([]grpc.ServerOption, error)\n}\n\nvar _ HTTPServer = (*GetHTTPHandlerFunc)(nil)\n\n// GetHTTPHandlerFunc is a function that implements HTTPServer.\ntype GetHTTPHandlerFunc func(_ context.Context) (WrapHTTPHandlerFunc, error)\n\nfunc (f GetHTTPHandlerFunc) GetHTTPHandler(ctx context.Context) (WrapHTTPHandlerFunc, error) {\n\tif f == nil {\n\t\treturn func(_ context.Context, h http.Handler) (http.Handler, error) {\n\t\t\treturn h, nil\n\t\t}, nil\n\t}\n\treturn f(ctx)\n}\n\nvar _ GRPCServer = (*GetGRPCServerOptionsFunc)(nil)\n\n// GetGRPCServerOptionsFunc is a function that implements GRPCServer.\ntype GetGRPCServerOptionsFunc func(context.Context) ([]grpc.ServerOption, error)\n\nfunc (f GetGRPCServerOptionsFunc) GetGRPCServerOptions(ctx context.Context) ([]grpc.ServerOption, error) {\n\tif f == nil {\n\t\treturn nil, nil\n\t}\n\treturn f(ctx)\n}\n\n// WrapHTTPHandlerFunc is called to initialize a new instance of\n// HTTP server middleware at runtime.\ntype WrapHTTPHandlerFunc = func(context.Context, http.Handler) (http.Handler, error)\n"
  },
  {
    "path": "extension/extensionmiddleware/server_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensionmiddleware\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc\"\n)\n\nfunc TestGetHTTPHandlerFunc(t *testing.T) {\n\ttestctx := context.Background()\n\n\tt.Run(\"nil_function\", func(t *testing.T) {\n\t\tvar f GetHTTPHandlerFunc\n\t\tbaseHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\t\tw.WriteHeader(http.StatusNoContent)\n\t\t})\n\n\t\thfunc, err := f.GetHTTPHandler(testctx)\n\t\trequire.NoError(t, err)\n\n\t\thandler, err := hfunc(testctx, baseHandler)\n\t\trequire.NoError(t, err)\n\n\t\trr := httptest.NewRecorder()\n\t\thandler.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, \"/\", http.NoBody))\n\t\trequire.Equal(t, http.StatusNoContent, rr.Code)\n\t})\n\n\tt.Run(\"returns_wrapped_handler\", func(t *testing.T) {\n\t\tcalled := false\n\t\tbaseHandler := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t})\n\n\t\tf := GetHTTPHandlerFunc(func(_ context.Context) (WrapHTTPHandlerFunc, error) {\n\t\t\treturn func(_ context.Context, base http.Handler) (http.Handler, error) {\n\t\t\t\treturn http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\t\tcalled = true\n\t\t\t\t\tbase.ServeHTTP(w, r)\n\t\t\t\t}), nil\n\t\t\t}, nil\n\t\t})\n\n\t\thfunc, err := f.GetHTTPHandler(testctx)\n\t\trequire.NoError(t, err)\n\t\trequire.NotNil(t, hfunc)\n\n\t\thandler, err := hfunc(testctx, baseHandler)\n\t\trequire.NoError(t, err)\n\n\t\trr := httptest.NewRecorder()\n\t\thandler.ServeHTTP(rr, httptest.NewRequest(http.MethodGet, \"/\", http.NoBody))\n\t\trequire.True(t, called)\n\t\trequire.Equal(t, http.StatusOK, rr.Code)\n\t})\n\n\tt.Run(\"returns_error\", func(t *testing.T) {\n\t\texpectedErr := errors.New(\"test error\")\n\t\tf := GetHTTPHandlerFunc(func(context.Context) (WrapHTTPHandlerFunc, error) {\n\t\t\treturn nil, expectedErr\n\t\t})\n\n\t\thfunc, err := f.GetHTTPHandler(testctx)\n\t\trequire.Equal(t, expectedErr, err)\n\t\trequire.Nil(t, hfunc)\n\t})\n}\n\nfunc TestGetGRPCServerOptionsFunc(t *testing.T) {\n\ttype testCtx struct{}\n\tvar (\n\t\tkey   = testCtx{}\n\t\tvalue = \"testval\"\n\t)\n\ttestctx := context.WithValue(context.Background(), key, value)\n\n\tt.Run(\"nil_function\", func(t *testing.T) {\n\t\tvar f GetGRPCServerOptionsFunc\n\t\topts, err := f.GetGRPCServerOptions(testctx)\n\t\trequire.NoError(t, err)\n\t\trequire.Nil(t, opts)\n\t})\n\n\tt.Run(\"returns_server_options\", func(t *testing.T) {\n\t\tvar interceptor grpc.UnaryServerInterceptor = func(\n\t\t\tcontext.Context,\n\t\t\tany,\n\t\t\t*grpc.UnaryServerInfo,\n\t\t\tgrpc.UnaryHandler,\n\t\t) (resp any, err error) {\n\t\t\treturn nil, nil\n\t\t}\n\t\texpectedOpts := []grpc.ServerOption{grpc.UnaryInterceptor(interceptor)}\n\n\t\tf := GetGRPCServerOptionsFunc(func(ctx context.Context) ([]grpc.ServerOption, error) {\n\t\t\trequire.Equal(t, ctx.Value(key), value)\n\t\t\treturn expectedOpts, nil\n\t\t})\n\n\t\topts, err := f.GetGRPCServerOptions(testctx)\n\t\trequire.NoError(t, err)\n\t\trequire.Equal(t, expectedOpts, opts)\n\t})\n\n\tt.Run(\"returns_error\", func(t *testing.T) {\n\t\texpectedErr := errors.New(\"test error\")\n\t\tf := GetGRPCServerOptionsFunc(func(ctx context.Context) ([]grpc.ServerOption, error) {\n\t\t\trequire.Equal(t, ctx.Value(key), value)\n\t\t\treturn nil, expectedErr\n\t\t})\n\n\t\topts, err := f.GetGRPCServerOptions(testctx)\n\t\trequire.Equal(t, expectedErr, err)\n\t\trequire.Nil(t, opts)\n\t})\n}\n"
  },
  {
    "path": "extension/extensiontest/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "extension/extensiontest/go.mod",
    "content": "module go.opentelemetry.io/collector/extension/extensiontest\n\ngo 1.25.0\n\nreplace go.opentelemetry.io/collector/extension => ..\n\nrequire (\n\tgithub.com/google/uuid v1.6.0\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/extension v1.54.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "extension/extensiontest/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "extension/extensiontest/metadata.yaml",
    "content": "type: extension/extensiontest\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "extension/extensiontest/nop_extension.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensiontest // import \"go.opentelemetry.io/collector/extension/extensiontest\"\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/uuid\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/extension\"\n)\n\n// NopType is the type of the nop extension.\nvar NopType = component.MustNewType(\"nop\")\n\n// NewNopSettings returns a new nop settings for extension.Factory Create* functions with the given type.\nfunc NewNopSettings(typ component.Type) extension.Settings {\n\treturn extension.Settings{\n\t\tID:                component.NewIDWithName(typ, uuid.NewString()),\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t\tBuildInfo:         component.NewDefaultBuildInfo(),\n\t}\n}\n\n// NewNopFactory returns an extension.Factory that constructs nop extensions.\nfunc NewNopFactory() extension.Factory {\n\treturn extension.NewFactory(\n\t\tNopType,\n\t\tfunc() component.Config {\n\t\t\treturn &nopConfig{}\n\t\t},\n\t\tfunc(context.Context, extension.Settings, component.Config) (extension.Extension, error) {\n\t\t\treturn nopInstance, nil\n\t\t},\n\t\tcomponent.StabilityLevelStable)\n}\n\ntype nopConfig struct{}\n\nvar nopInstance = &nopExtension{}\n\n// nopExtension acts as an extension for testing purposes.\ntype nopExtension struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n}\n"
  },
  {
    "path": "extension/extensiontest/nop_extension_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensiontest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\nfunc TestNewNopFactory(t *testing.T) {\n\tfactory := NewNopFactory()\n\trequire.NotNil(t, factory)\n\tassert.Equal(t, component.MustNewType(\"nop\"), factory.Type())\n\tcfg := factory.CreateDefaultConfig()\n\tassert.Equal(t, &nopConfig{}, cfg)\n\n\ttraces, err := factory.Create(context.Background(), NewNopSettings(NopType), cfg)\n\trequire.NoError(t, err)\n\tassert.NoError(t, traces.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, traces.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "extension/go.mod",
    "content": "module go.opentelemetry.io/collector/extension\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../component\n\nreplace go.opentelemetry.io/collector/pdata => ../pdata\n\nreplace go.opentelemetry.io/collector/featuregate => ../featuregate\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../internal/componentalias\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../internal/testutil\n"
  },
  {
    "path": "extension/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "extension/memorylimiterextension/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "extension/memorylimiterextension/README.md",
    "content": "<!-- status autogenerated section -->\n# Memory Limiter Extension\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [development]  |\n| Distributions | [] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Aextension%2Fmemorylimiter%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Aextension%2Fmemorylimiter) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Aextension%2Fmemorylimiter%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Aextension%2Fmemorylimiter) |\n\n[development]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#development\n<!-- end autogenerated section -->\n\nThe memory limiter extension is used to prevent out of memory situations on\nthe collector. The extension will potentially replace the Memory Limiter Processor. \nIt provides better guarantees from running out of memory as it will be used by the \nreceivers to reject requests before converting them into OTLP. All the configurations \nare the same as Memory Limiter Processor. \n\n\nThis extension can be used as an extension for all HTTP and gRPC receivers that\nare configured through the standard `confighttp` and `configgrpc` libraries. For\nexample, to configure this extension in the OTLP receiver:\n\n```\nreceivers:\n  otlp:\n    protocols:\n      grpc:\n        middlewares:\n          - id: memory_limiter\n      http:\n        middlewares:\n          - id: memory_limiter\n\nextensions:\n  memory_limiter:\n    check_interval: 1s\n    limit_percentage: 1\n    spike_limit_percentage: 0.05\n```\n\nsee [memorylimiterprocessor](../../processor/memorylimiterprocessor/README.md) for additional details\n"
  },
  {
    "path": "extension/memorylimiterextension/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage memorylimiterextension // import \"go.opentelemetry.io/collector/extension/memorylimiterextension\"\n\nimport (\n\t\"go.opentelemetry.io/collector/internal/memorylimiter\"\n)\n\ntype Config = memorylimiter.Config\n"
  },
  {
    "path": "extension/memorylimiterextension/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage memorylimiterextension // import \"go.opentelemetry.io/collector/extension/memorylimiterextension\"\n\n//go:generate mdatagen metadata.yaml\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/memorylimiterextension/internal/metadata\"\n\t\"go.opentelemetry.io/collector/internal/memorylimiter\"\n)\n\n// NewFactory returns a new factory for the Memory Limiter extension.\nfunc NewFactory() extension.Factory {\n\treturn extension.NewFactory(\n\t\tmetadata.Type,\n\t\tcreateDefaultConfig,\n\t\tcreate,\n\t\tmetadata.ExtensionStability)\n}\n\n// CreateDefaultConfig creates the default configuration for extension. Notice\n// that the default configuration is expected to fail for this extension.\nfunc createDefaultConfig() component.Config {\n\treturn memorylimiter.NewDefaultConfig()\n}\n\nfunc create(_ context.Context, set extension.Settings, cfg component.Config) (extension.Extension, error) {\n\treturn newMemoryLimiter(cfg.(*Config), set.Logger)\n}\n"
  },
  {
    "path": "extension/memorylimiterextension/factory_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage memorylimiterextension\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/extension/extensiontest\"\n)\n\nfunc TestCreateDefaultConfig(t *testing.T) {\n\tfactory := NewFactory()\n\trequire.NotNil(t, factory)\n\n\tcfg := factory.CreateDefaultConfig()\n\tassert.NotNil(t, cfg, \"failed to create default config\")\n\tassert.NoError(t, componenttest.CheckConfigStruct(cfg))\n}\n\nfunc TestCreate(t *testing.T) {\n\tfactory := NewFactory()\n\trequire.NotNil(t, factory)\n\n\tcfg := factory.CreateDefaultConfig()\n\n\t// Create extension with a valid config.\n\tpCfg := cfg.(*Config)\n\tpCfg.MemoryLimitMiB = 5722\n\tpCfg.MemorySpikeLimitMiB = 1907\n\tpCfg.CheckInterval = 100 * time.Millisecond\n\n\tset := extensiontest.NewNopSettings(factory.Type())\n\tset.ID = component.NewID(factory.Type())\n\n\ttp, err := factory.Create(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, tp)\n\t// test if we can shutdown a monitoring routine that has not started\n\trequire.NoError(t, tp.Shutdown(context.Background()))\n\tassert.NoError(t, tp.Start(context.Background(), componenttest.NewNopHost()))\n\n\tassert.NoError(t, tp.Shutdown(context.Background()))\n\t// verify that shutdown twice works:\n\tassert.NoError(t, tp.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "extension/memorylimiterextension/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage memorylimiterextension\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/extension/extensiontest\"\n)\n\nvar typ = component.MustNewType(\"memory_limiter\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\tt.Run(\"shutdown\", func(t *testing.T) {\n\t\te, err := factory.Create(context.Background(), extensiontest.NewNopSettings(typ), cfg)\n\t\trequire.NoError(t, err)\n\t\terr = e.Shutdown(context.Background())\n\t\trequire.NoError(t, err)\n\t})\n\tt.Run(\"lifecycle\", func(t *testing.T) {\n\t\tfirstExt, err := factory.Create(context.Background(), extensiontest.NewNopSettings(typ), cfg)\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, firstExt.Start(context.Background(), newMdatagenNopHost()))\n\t\trequire.NoError(t, firstExt.Shutdown(context.Background()))\n\n\t\tsecondExt, err := factory.Create(context.Background(), extensiontest.NewNopSettings(typ), cfg)\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, secondExt.Start(context.Background(), newMdatagenNopHost()))\n\t\trequire.NoError(t, secondExt.Shutdown(context.Background()))\n\t})\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "extension/memorylimiterextension/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage memorylimiterextension\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "extension/memorylimiterextension/go.mod",
    "content": "module go.opentelemetry.io/collector/extension/memorylimiterextension\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/extension v1.54.0\n\tgo.opentelemetry.io/collector/extension/extensionmiddleware v0.148.0\n\tgo.opentelemetry.io/collector/extension/extensiontest v0.148.0\n\tgo.opentelemetry.io/collector/internal/memorylimiter v0.148.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/zap v1.27.1\n\tgoogle.golang.org/grpc v1.79.3\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/ebitengine/purego v0.10.0 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-ole/go-ole v1.2.6 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect\n\tgithub.com/shirou/gopsutil/v4 v4.26.2 // indirect\n\tgithub.com/tklauser/go-sysconf v0.3.16 // indirect\n\tgithub.com/tklauser/numcpus v0.11.0 // indirect\n\tgithub.com/yusufpapurcu/wmi v1.2.4 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/extension => ../../extension\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/internal/memorylimiter => ../../internal/memorylimiter\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../../extension/extensiontest\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ../../extension/extensionmiddleware\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "extension/memorylimiterextension/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=\ngithub.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=\ngithub.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3 h1:PwQumkgq4/acIiZhtifTV5OUqqiP82UAl0h87xj/l9k=\ngithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/shirou/gopsutil/v4 v4.26.2 h1:X8i6sicvUFih4BmYIGT1m2wwgw2VG9YgrDTi7cIRGUI=\ngithub.com/shirou/gopsutil/v4 v4.26.2/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngithub.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYICU0nA=\ngithub.com/tklauser/go-sysconf v0.3.16/go.mod h1:/qNL9xxDhc7tx3HSRsLWNnuzbVfh3e7gh/BmM179nYI=\ngithub.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9RXw=\ngithub.com/tklauser/numcpus v0.11.0/go.mod h1:z+LwcLq54uWZTX0u/bGobaV34u6V7KNlTZejzM6/3MQ=\ngithub.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=\ngithub.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=\ngonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "extension/memorylimiterextension/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"memory_limiter\")\n\tScopeName = \"go.opentelemetry.io/collector/extension/memorylimiterextension\"\n)\n\nconst (\n\tExtensionStability = component.StabilityLevelDevelopment\n)\n"
  },
  {
    "path": "extension/memorylimiterextension/memorylimiter.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage memorylimiterextension // import \"go.opentelemetry.io/collector/extension/memorylimiterextension\"\n\nimport (\n\t\"context\"\n\t\"net/http\"\n\n\t\"go.uber.org/zap\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/extension/extensionmiddleware\"\n\t\"go.opentelemetry.io/collector/internal/memorylimiter\"\n)\n\nvar (\n\t_ extensionmiddleware.GRPCServer = (*memoryLimiterExtension)(nil)\n\t_ extensionmiddleware.HTTPServer = (*memoryLimiterExtension)(nil)\n)\n\ntype memoryLimiterExtension struct {\n\tmemLimiter *memorylimiter.MemoryLimiter\n}\n\n// newMemoryLimiter returns a new memorylimiter extension.\nfunc newMemoryLimiter(cfg *Config, logger *zap.Logger) (*memoryLimiterExtension, error) {\n\tml, err := memorylimiter.NewMemoryLimiter(cfg, logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &memoryLimiterExtension{memLimiter: ml}, nil\n}\n\nfunc (ml *memoryLimiterExtension) Start(ctx context.Context, host component.Host) error {\n\treturn ml.memLimiter.Start(ctx, host)\n}\n\nfunc (ml *memoryLimiterExtension) Shutdown(ctx context.Context) error {\n\treturn ml.memLimiter.Shutdown(ctx)\n}\n\n// MustRefuse returns if the caller should deny because memory has reached it's configured limits\nfunc (ml *memoryLimiterExtension) MustRefuse() bool {\n\treturn ml.memLimiter.MustRefuse()\n}\n\n// GetHTTPHandler implements extensionmiddleware.HTTPServer\nfunc (ml *memoryLimiterExtension) GetHTTPHandler(_ context.Context) (extensionmiddleware.WrapHTTPHandlerFunc, error) {\n\treturn ml.wrapHTTPHandler, nil\n}\n\nfunc (ml *memoryLimiterExtension) wrapHTTPHandler(_ context.Context, base http.Handler) (http.Handler, error) {\n\treturn http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {\n\t\tif ml.MustRefuse() {\n\t\t\thttp.Error(resp, http.StatusText(http.StatusTooManyRequests), http.StatusTooManyRequests)\n\t\t\treturn\n\t\t}\n\t\tbase.ServeHTTP(resp, req)\n\t}), nil\n}\n\nfunc (ml *memoryLimiterExtension) GetGRPCServerOptions(_ context.Context) ([]grpc.ServerOption, error) {\n\treturn []grpc.ServerOption{\n\t\tgrpc.ChainUnaryInterceptor(\n\t\t\tfunc(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp any, err error) {\n\t\t\t\tif ml.MustRefuse() {\n\t\t\t\t\treturn nil, status.Errorf(codes.ResourceExhausted, \"RESOURCE_EXHAUSTED\")\n\t\t\t\t}\n\t\t\t\treturn handler(ctx, req)\n\t\t\t}),\n\t\tgrpc.ChainStreamInterceptor(\n\t\t\tfunc(srv any, ss grpc.ServerStream, _ *grpc.StreamServerInfo, handler grpc.StreamHandler) error {\n\t\t\t\tif ml.MustRefuse() {\n\t\t\t\t\treturn status.Errorf(codes.ResourceExhausted, \"RESOURCE_EXHAUSTED\")\n\t\t\t\t}\n\t\t\t\treturn handler(srv, ss)\n\t\t\t}),\n\t}, nil\n}\n"
  },
  {
    "path": "extension/memorylimiterextension/memorylimiter_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage memorylimiterextension\n\nimport (\n\t\"context\"\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/internal/memorylimiter\"\n\t\"go.opentelemetry.io/collector/internal/memorylimiter/iruntime\"\n)\n\nfunc TestMemoryPressureResponse(t *testing.T) {\n\tctx := context.Background()\n\n\ttests := []struct {\n\t\tname        string\n\t\tmlCfg       *Config\n\t\tmemAlloc    uint64\n\t\texpectError bool\n\t}{\n\t\t{\n\t\t\tname: \"Below memAllocLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 1,\n\t\t\t},\n\t\t\tmemAlloc:    800,\n\t\t\texpectError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Above memAllocLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 1,\n\t\t\t},\n\t\t\tmemAlloc:    1800,\n\t\t\texpectError: true,\n\t\t},\n\t\t{\n\t\t\tname: \"Below memSpikeLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 10,\n\t\t\t},\n\t\t\tmemAlloc:    800,\n\t\t\texpectError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Above memSpikeLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 11,\n\t\t\t},\n\t\t\tmemAlloc:    800,\n\t\t\texpectError: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tmemorylimiter.GetMemoryFn = func() (uint64, error) {\n\t\t\t\treturn uint64(2048), nil\n\t\t\t}\n\t\t\tmemorylimiter.ReadMemStatsFn = func(ms *runtime.MemStats) {\n\t\t\t\tms.Alloc = tt.memAlloc\n\t\t\t}\n\t\t\tt.Cleanup(func() {\n\t\t\t\tmemorylimiter.GetMemoryFn = iruntime.TotalMemory\n\t\t\t\tmemorylimiter.ReadMemStatsFn = runtime.ReadMemStats\n\t\t\t})\n\t\t\tml, err := newMemoryLimiter(tt.mlCfg, zap.NewNop())\n\t\t\tassert.NoError(t, err)\n\n\t\t\tassert.NoError(t, ml.Start(ctx, componenttest.NewNopHost()))\n\t\t\tml.memLimiter.CheckMemLimits()\n\t\t\tmustRefuse := ml.MustRefuse()\n\t\t\tif tt.expectError {\n\t\t\t\tassert.True(t, mustRefuse)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\t\t\tassert.NoError(t, ml.Shutdown(ctx))\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "extension/memorylimiterextension/metadata.yaml",
    "content": "display_name: Memory Limiter Extension\ntype: memory_limiter\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: extension\n  stability:\n    development: [extension]\n  distributions: []\n\ntests:\n  config:\n    check_interval: 5s\n    limit_mib: 400\n    spike_limit_mib: 50\n"
  },
  {
    "path": "extension/memorylimiterextension/testdata/config.yaml",
    "content": "# check_interval is the time between measurements of memory usage for the\n# purposes of avoiding going over the limits. Defaults to zero, so no\n# checks will be performed. Values below 1 second are not recommended since\n# it can result in unnecessary CPU consumption.\ncheck_interval: 5s\n\n# Maximum amount of memory, in MiB, targeted to be allocated by the process heap.\n# Note that typically the total memory usage of process will be about 50MiB higher\n# than this value.\nlimit_mib: 4000\n\n# The maximum, in MiB, spike expected between the measurements of memory usage.\nspike_limit_mib: 500\n\n# the maximum amount of memory, in %, targeted to be allocated by the process\nlimit_percentage: 0\n\n# the maximum, in percents against the total memory, spike expected between the measurements of memory usage.\nspike_limit_percentage: 0"
  },
  {
    "path": "extension/metadata.yaml",
    "content": "type: extension\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "extension/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extension\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "extension/xextension/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "extension/xextension/extension.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xextension // import \"go.opentelemetry.io/collector/extension/xextension\"\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n)\n\ntype Factory interface {\n\textension.Factory\n}\n\ntype FactoryOption interface {\n\tapplyOption(o *factory)\n}\n\ntype factoryOptionFunc func(*factory)\n\nfunc (f factoryOptionFunc) applyOption(o *factory) {\n\tf(o)\n}\n\ntype factory struct {\n\textension.Factory\n\tcomponentalias.TypeAliasHolder\n}\n\nfunc WithDeprecatedTypeAlias(alias component.Type) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.SetDeprecatedAlias(alias)\n\t})\n}\n\nfunc NewFactory(\n\tcfgType component.Type,\n\tcreateDefaultConfig component.CreateDefaultConfigFunc,\n\tcreateServiceExtension extension.CreateFunc,\n\tsl component.StabilityLevel,\n\toptions ...FactoryOption,\n) Factory {\n\tf := &factory{TypeAliasHolder: componentalias.NewTypeAliasHolder()}\n\tfor _, opt := range options {\n\t\topt.applyOption(f)\n\t}\n\tf.Factory = extension.NewFactory(cfgType, createDefaultConfig, createServiceExtension, sl)\n\tf.Factory.(componentalias.TypeAliasHolder).SetDeprecatedAlias(f.DeprecatedAlias())\n\treturn f\n}\n"
  },
  {
    "path": "extension/xextension/extension_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xextension\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/extension\"\n)\n\ntype nopExtension struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n}\n\nfunc TestWithDeprecatedTypeAlias(t *testing.T) {\n\toriginalType := component.MustNewType(\"original\")\n\taliasType := component.MustNewType(\"alias\")\n\tnopExtensionInstance := new(nopExtension)\n\n\tfactory := NewFactory(\n\t\toriginalType,\n\t\tfunc() component.Config { return &struct{}{} },\n\t\tfunc(context.Context, extension.Settings, component.Config) (extension.Extension, error) {\n\t\t\treturn nopExtensionInstance, nil\n\t\t},\n\t\tcomponent.StabilityLevelAlpha,\n\t\tWithDeprecatedTypeAlias(aliasType),\n\t)\n\n\tassert.Equal(t, originalType, factory.Type())\n\n\text, err := factory.Create(context.Background(), extension.Settings{\n\t\tID:                component.NewID(originalType),\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t}, factory.CreateDefaultConfig())\n\trequire.NoError(t, err)\n\trequire.NotNil(t, ext)\n\n\text, err = factory.Create(context.Background(), extension.Settings{\n\t\tID:                component.NewID(aliasType),\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t}, factory.CreateDefaultConfig())\n\trequire.NoError(t, err)\n\trequire.NotNil(t, ext)\n\n\text, err = factory.Create(context.Background(), extension.Settings{\n\t\tID:                component.NewID(component.MustNewType(\"wrong\")),\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t}, factory.CreateDefaultConfig())\n\trequire.Error(t, err)\n\trequire.Nil(t, ext)\n}\n"
  },
  {
    "path": "extension/xextension/go.mod",
    "content": "module go.opentelemetry.io/collector/extension/xextension\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/extension v1.54.0\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/extension => ../\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n"
  },
  {
    "path": "extension/xextension/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "extension/xextension/metadata.yaml",
    "content": "type: xextension\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  codeowners:\n  stability:\n    alpha: [profiles]\n"
  },
  {
    "path": "extension/xextension/storage/README.md",
    "content": "# Storage\n\n**Status: under development; This is currently just the interface**\n\nA storage extension persists state beyond the collector process. Other components can request a storage client from the storage extension and use it to manage state. \n\nThe `storage.Extension` interface extends `component.Extension` by adding the following method:\n```\nGetClient(context.Context, component.Kind, component.ID, string) (Client, error)\n```\n\nThe `storage.Client` interface contains the following methods:\n```\nGet(context.Context, string) ([]byte, error)\nSet(context.Context, string, []byte) error\nDelete(context.Context, string) error\nClose(context.Context) error\n```\n\nIt is possible to execute several operations in a single transaction via `Batch`. The method takes a collection of\n`Operation` arguments (each of which contains `Key`, `Value` and `Type` properties):\n```\nBatch(context.Context, ...Operation) error\n```\n\nThe elements itself can be created using:\n\n```\nSetOperation(string, []byte) Operation\nGetOperation(string) Operation\nDeleteOperation(string) Operation\n```\n\nGet operation results are stored in-place into the given Operation and can be retrieved using its `Value` property.\n\nNote: All methods should return error only if a problem occurred. (For example, if a file is no longer accessible, or if a remote service is unavailable.)\n\nNote: It is the responsibility of each component to `Close` a storage client that it has requested.\n"
  },
  {
    "path": "extension/xextension/storage/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package storage implements an extension that can\n// persist state beyond the collector process.\npackage storage // import \"go.opentelemetry.io/collector/extension/xextension/storage\"\n"
  },
  {
    "path": "extension/xextension/storage/metadata.yaml",
    "content": "type: xextension/storage\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  codeowners:\n    active:\n      - swiatekm\n  stability:\n    alpha: [profiles]\n"
  },
  {
    "path": "extension/xextension/storage/nop_client.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage storage // import \"go.opentelemetry.io/collector/extension/xextension/storage\"\n\nimport \"context\"\n\ntype nopClient struct{}\n\nvar nopClientInstance Client = &nopClient{}\n\n// NewNopClient returns a nop client\nfunc NewNopClient() Client {\n\treturn nopClientInstance\n}\n\n// Get does nothing, and returns nil, nil\nfunc (c nopClient) Get(context.Context, string) ([]byte, error) {\n\treturn nil, nil // no result, but no problem\n}\n\n// Set does nothing and returns nil\nfunc (c nopClient) Set(context.Context, string, []byte) error {\n\treturn nil // no problem\n}\n\n// Delete does nothing and returns nil\nfunc (c nopClient) Delete(context.Context, string) error {\n\treturn nil // no problem\n}\n\n// Close does nothing and returns nil\nfunc (c nopClient) Close(context.Context) error {\n\treturn nil\n}\n\n// Batch does nothing, and returns nil, nil\nfunc (c nopClient) Batch(context.Context, ...*Operation) error {\n\treturn nil // no result, but no problem\n}\n"
  },
  {
    "path": "extension/xextension/storage/storage.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage storage // import \"go.opentelemetry.io/collector/extension/xextension/storage\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/extension\"\n)\n\n// Extension is the interface that storage extensions must implement\ntype Extension interface {\n\textension.Extension\n\n\t// GetClient will create a client for use by the specified component.\n\t// Each component can have multiple storages (e.g. one for each signal),\n\t// which can be identified using storageName parameter.\n\t// The component can use the client to manage state\n\tGetClient(ctx context.Context, kind component.Kind, id component.ID, storageName string) (Client, error)\n}\n\n// Client is the interface that storage clients must implement\n// All methods should return error only if a problem occurred.\n// This mirrors the behavior of a golang map:\n//   - Set doesn't error if a key already exists - it just overwrites the value.\n//   - Get doesn't error if a key is not found - it just returns nil.\n//   - Delete doesn't error if the key doesn't exist - it just no-ops.\n//\n// Similarly:\n//   - Batch doesn't error if any of the above happens for either retrieved or updated keys\n//\n// This also provides a way to differentiate data operations\n//\n//\t[overwrite | not-found | no-op] from \"real\" problems\ntype Client interface {\n\t// Get will retrieve data from storage that corresponds to the\n\t// specified key. It should return (nil, nil) if not found\n\tGet(ctx context.Context, key string) ([]byte, error)\n\n\t// Set will store data. The data can be retrieved by the same\n\t// component after a process restart, using the same key\n\tSet(ctx context.Context, key string, value []byte) error\n\n\t// Delete will delete data associated with the specified key\n\tDelete(ctx context.Context, key string) error\n\n\t// Batch handles specified operations in batch. Get operation results are put in-place\n\tBatch(ctx context.Context, ops ...*Operation) error\n\n\t// Close will release any resources held by the client\n\tClose(ctx context.Context) error\n}\n\ntype OpType int\n\nconst (\n\tGet OpType = iota\n\tSet\n\tDelete\n)\n\ntype Operation struct {\n\t// Key specifies key which is going to be get/set/deleted\n\tKey string\n\t// Value specifies value that is going to be set or holds result of get operation\n\tValue []byte\n\t// Type describes the operation type\n\tType OpType\n}\n\nfunc SetOperation(key string, value []byte) *Operation {\n\treturn &Operation{\n\t\tKey:   key,\n\t\tValue: value,\n\t\tType:  Set,\n\t}\n}\n\nfunc GetOperation(key string) *Operation {\n\treturn &Operation{\n\t\tKey:  key,\n\t\tType: Get,\n\t}\n}\n\nfunc DeleteOperation(key string) *Operation {\n\treturn &Operation{\n\t\tKey:  key,\n\t\tType: Delete,\n\t}\n}\n\nvar ErrStorageFull = errors.New(\"the storage extension has run out of available space\")\n"
  },
  {
    "path": "extension/zpagesextension/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "extension/zpagesextension/README.md",
    "content": "<!-- status autogenerated section -->\n# zPages Extension\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [beta]  |\n| Distributions | [core], [contrib], [k8s] |\n| Warnings      | [The zPages extension is incompatible with `service::telemetry::traces::level` set to `none`](#warnings) |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Aextension%2Fzpages%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Aextension%2Fzpages) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Aextension%2Fzpages%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Aextension%2Fzpages) |\n\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[core]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n[k8s]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\n<!-- end autogenerated section -->\n\nEnables an extension that serves zPages, an HTTP endpoint that provides live\ndata for debugging different components that were properly instrumented for such.\nAll core exporters and receivers provide some zPage instrumentation.\n\nzPages are useful for in-process diagnostics without having to depend on any\nbackend to examine traces or metrics. \n\nThe following settings are required:\n\n- `endpoint` (default = localhost:55679): Specifies the HTTP endpoint that serves\nzPages. Use localhost:<port> to make it available only locally, or \":<port>\" to\nmake it available on all network interfaces.\n\nThe following settings can be optionally configured:\n\n- `expvar`\n  - `enabled` (default = false): Enable the expvar services. For detail see [ExpvarZ](#expvarz).\n\nExample:\n```yaml\nextensions:\n  zpages:\n```\n\nThe full list of settings exposed for this extension are documented [here](./config.go)\nwith detailed sample configurations [here](./testdata/config.yaml).\n\n## Exposed zPages routes\n\nThe collector exposes the following zPage routes:\n\n### ServiceZ\n\nServiceZ gives an overview of the collector services and quick access to the\n`pipelinez`, `extensionz`, and `featurez` zPages.  The page also provides build \nand runtime information.\n\nExample URL: http://localhost:55679/debug/servicez\n\n### PipelineZ\n\nPipelineZ brings insight on the running pipelines running in the collector. You can\nfind information on type, if data is mutated and the receivers, processors and exporters\nthat are used for each pipeline.\n\nExample URL: http://localhost:55679/debug/pipelinez\n\n### ExtensionZ\n\nExtensionZ shows the extensions that are active in the collector.\n\nExample URL: http://localhost:55679/debug/extensionz\n\n### FeatureZ\n\nFeatureZ lists the feature gates available along with their current status \nand description.\n\nExample URL: http://localhost:55679/debug/featurez\n\n### TraceZ\nThe TraceZ route is available to examine and bucketize spans by latency buckets for \nexample\n\n(0us, 10us, 100us, 1ms, 10ms, 100ms, 1s, 10s, 1m]\nThey also allow you to quickly examine error samples\n\nExample URL: http://localhost:55679/debug/tracez\n\n### ExpvarZ\n\nThe ExpvarZ exposes the useful information about Go runtime, OTel components could leverage [expvar](https://pkg.go.dev/expvar) library to expose their own state.\n\nExample URL: http://localhost:55679/debug/expvarz\n\n## Warnings\n\nThis extension registers a SpanProcessor to record all the spans created inside\nthe Collector. This depends on a TracerProvider that supports\nthe SDK methods RegisterSpanProcessor and UnregisterSpanProcessor. Setting\n`service::telemetry::traces::level` to `none` configures a No-Op\nTracerProvider that does not support these methods, and therefore the zPages\nextension cannot work in this mode.\n"
  },
  {
    "path": "extension/zpagesextension/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage zpagesextension // import \"go.opentelemetry.io/collector/extension/zpagesextension\"\n\nimport (\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n)\n\n// Config has the configuration for the extension enabling the zPages extension.\ntype Config struct {\n\tconfighttp.ServerConfig `mapstructure:\",squash\"`\n\n\tExpvar ExpvarConfig `mapstructure:\"expvar\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// ExpvarConfig has the configuration for the expvar service.\ntype ExpvarConfig struct {\n\t// Enabled indicates whether to enable expvar service.\n\t// (default = false)\n\tEnabled bool `mapstructure:\"enabled\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\nvar _ component.Config = (*Config)(nil)\n\n// Validate checks if the extension configuration is valid\nfunc (cfg *Config) Validate() error {\n\tif cfg.NetAddr.Endpoint == \"\" {\n\t\treturn errors.New(\"\\\"endpoint\\\" is required when using the \\\"zpages\\\" extension\")\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "extension/zpagesextension/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage zpagesextension\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n)\n\nfunc TestUnmarshalDefaultConfig(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, confmap.New().Unmarshal(&cfg))\n\tassert.Equal(t, factory.CreateDefaultConfig(), cfg)\n}\n\nfunc TestInvalidConfig(t *testing.T) {\n\tassert.Error(t, (&Config{}).Validate())\n}\n\nfunc TestUnmarshalConfig(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\n\texpectedServerConfig := confighttp.NewDefaultServerConfig()\n\texpectedServerConfig.NetAddr.Endpoint = \"localhost:56888\"\n\n\tassert.Equal(t, &Config{ServerConfig: expectedServerConfig}, cfg)\n}\n"
  },
  {
    "path": "extension/zpagesextension/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\n// Package zpagesextension implements an extension that exposes zPages of\n// properly instrumented components.\npackage zpagesextension // import \"go.opentelemetry.io/collector/extension/zpagesextension\"\n"
  },
  {
    "path": "extension/zpagesextension/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage zpagesextension // import \"go.opentelemetry.io/collector/extension/zpagesextension\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/zpagesextension/internal/metadata\"\n)\n\nconst (\n\tdefaultEndpoint = \"localhost:55679\"\n)\n\n// NewFactory creates a factory for Z-Pages extension.\nfunc NewFactory() extension.Factory {\n\treturn extension.NewFactory(metadata.Type, createDefaultConfig, create, metadata.ExtensionStability)\n}\n\nfunc createDefaultConfig() component.Config {\n\tserverConfig := confighttp.NewDefaultServerConfig()\n\tserverConfig.NetAddr.Endpoint = defaultEndpoint\n\treturn &Config{\n\t\tServerConfig: serverConfig,\n\t}\n}\n\n// create creates the extension based on this config.\nfunc create(_ context.Context, set extension.Settings, cfg component.Config) (extension.Extension, error) {\n\treturn newServer(cfg.(*Config), set.TelemetrySettings), nil\n}\n"
  },
  {
    "path": "extension/zpagesextension/factory_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage zpagesextension\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/extension/extensiontest\"\n\t\"go.opentelemetry.io/collector/extension/zpagesextension/internal/metadata\"\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc TestFactory_CreateDefaultConfig(t *testing.T) {\n\texpectedServerConfig := confighttp.NewDefaultServerConfig()\n\texpectedServerConfig.NetAddr.Endpoint = \"localhost:55679\"\n\n\tcfg := createDefaultConfig()\n\tassert.Equal(t, &Config{ServerConfig: expectedServerConfig}, cfg)\n\n\trequire.NoError(t, componenttest.CheckConfigStruct(cfg))\n\text, err := create(context.Background(), extensiontest.NewNopSettings(metadata.Type), cfg)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, ext)\n}\n\nfunc TestFactoryCreate(t *testing.T) {\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.NetAddr.Endpoint = testutil.GetAvailableLocalAddress(t)\n\n\tset := extensiontest.NewNopSettings(extensiontest.NopType)\n\tset.ID = component.NewID(NewFactory().Type())\n\text, err := create(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, ext)\n}\n"
  },
  {
    "path": "extension/zpagesextension/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage zpagesextension\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/extension/extensiontest\"\n)\n\nvar typ = component.MustNewType(\"zpages\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\tt.Run(\"shutdown\", func(t *testing.T) {\n\t\te, err := factory.Create(context.Background(), extensiontest.NewNopSettings(typ), cfg)\n\t\trequire.NoError(t, err)\n\t\terr = e.Shutdown(context.Background())\n\t\trequire.NoError(t, err)\n\t})\n\tt.Run(\"lifecycle\", func(t *testing.T) {\n\t\tfirstExt, err := factory.Create(context.Background(), extensiontest.NewNopSettings(typ), cfg)\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, firstExt.Start(context.Background(), newMdatagenNopHost()))\n\t\trequire.NoError(t, firstExt.Shutdown(context.Background()))\n\n\t\tsecondExt, err := factory.Create(context.Background(), extensiontest.NewNopSettings(typ), cfg)\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, secondExt.Start(context.Background(), newMdatagenNopHost()))\n\t\trequire.NoError(t, secondExt.Shutdown(context.Background()))\n\t})\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "extension/zpagesextension/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage zpagesextension\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "extension/zpagesextension/go.mod",
    "content": "module go.opentelemetry.io/collector/extension/zpagesextension\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componentstatus v0.148.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/config/configauth v1.54.0\n\tgo.opentelemetry.io/collector/config/confighttp v0.148.0\n\tgo.opentelemetry.io/collector/config/confignet v1.54.0\n\tgo.opentelemetry.io/collector/config/configoptional v1.54.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/extension v1.54.0\n\tgo.opentelemetry.io/collector/extension/extensiontest v0.148.0\n\tgo.opentelemetry.io/collector/internal/testutil v0.148.0\n\tgo.opentelemetry.io/contrib/zpages v0.67.0\n\tgo.opentelemetry.io/otel/sdk v1.42.0\n\tgo.opentelemetry.io/otel/trace v1.42.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/zap v1.27.1\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/felixge/httpsnoop v1.0.4 // indirect\n\tgithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f // indirect\n\tgithub.com/fsnotify/fsnotify v1.9.0 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/golang/snappy v1.0.0 // indirect\n\tgithub.com/google/go-tpm v0.9.8 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/klauspost/compress v1.18.4 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pierrec/lz4/v4 v4.1.26 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/rs/cors v1.11.1 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/client v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configcompression v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configmiddleware v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configopaque v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configtls v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionauth v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionmiddleware v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline v1.54.0 // indirect\n\tgo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/crypto v0.48.0 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/extension => ../\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../extensiontest\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/config/configopaque => ../../config/configopaque\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../../config/configoptional\n\nreplace go.opentelemetry.io/collector/config/configtls => ../../config/configtls\n\nreplace go.opentelemetry.io/collector/config/configcompression => ../../config/configcompression\n\nreplace go.opentelemetry.io/collector/config/configauth => ../../config/configauth\n\nreplace go.opentelemetry.io/collector/extension/extensionauth => ../extensionauth\n\nreplace go.opentelemetry.io/collector/config/confighttp => ../../config/confighttp\n\nreplace go.opentelemetry.io/collector/config/confignet => ../../config/confignet\n\nreplace go.opentelemetry.io/collector/client => ../../client\n\nreplace go.opentelemetry.io/collector/component/componentstatus => ../../component/componentstatus\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nretract (\n\tv0.76.0 // Depends on retracted pdata v1.0.0-rc10 module, use v0.76.1\n\tv0.69.0 // Release failed, use v0.69.1\n)\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest => ../../extension/extensionauth/extensionauthtest\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ../extensionmiddleware\n\nreplace go.opentelemetry.io/collector/config/configmiddleware => ../../config/configmiddleware\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest => ../extensionmiddleware/extensionmiddlewaretest\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "extension/zpagesextension/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=\ngithub.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f h1:RJ+BDPLSHQO7cSjKBqjPJSbi1qfk9WcsjQDtZiw3dZw=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f/go.mod h1:VHbbch/X4roIY22jL1s3qRbZhCiRIgUAF/PdSUcx2io=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=\ngithub.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=\ngithub.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=\ngithub.com/google/go-tpm-tools v0.4.7 h1:J3ycC8umYxM9A4eF73EofRZu4BxY0jjQnUnkhIBbvws=\ngithub.com/google/go-tpm-tools v0.4.7/go.mod h1:gSyXTZHe3fgbzb6WEGd90QucmsnT1SRdlye82gH8QjQ=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=\ngithub.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=\ngithub.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=\ngithub.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=\ngo.opentelemetry.io/contrib/zpages v0.67.0 h1:cIUwWSVDovuLEbDIKreptjdxMuIhGiqwq0uL8YNaq1c=\ngo.opentelemetry.io/contrib/zpages v0.67.0/go.mod h1:vK8fsYHgPYg4Z/XDbFSEvItSGZDbjWTvjBOu8+AiDhc=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=\ngolang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=\ngonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "extension/zpagesextension/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"zpages\")\n\tScopeName = \"go.opentelemetry.io/collector/extension/zpagesextension\"\n)\n\nconst (\n\tExtensionStability = component.StabilityLevelBeta\n)\n"
  },
  {
    "path": "extension/zpagesextension/metadata.yaml",
    "content": "display_name: zPages Extension\ntype: zpages\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: extension\n  stability:\n    beta: [extension]\n  distributions: [core, contrib, k8s]\n  warnings:\n    - The zPages extension is incompatible with `service::telemetry::traces::level` set to `none`\n"
  },
  {
    "path": "extension/zpagesextension/testdata/config.yaml",
    "content": "endpoint: \"localhost:56888\"\ntransport: tcp\n"
  },
  {
    "path": "extension/zpagesextension/zpagesextension.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage zpagesextension // import \"go.opentelemetry.io/collector/extension/zpagesextension\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"expvar\"\n\t\"net/http\"\n\t\"path\"\n\n\t\"go.opentelemetry.io/contrib/zpages\"\n\ttraceSdk \"go.opentelemetry.io/otel/sdk/trace\"\n\t\"go.opentelemetry.io/otel/trace\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componentstatus\"\n)\n\nconst (\n\ttracezPath  = \"tracez\"\n\texpvarzPath = \"expvarz\"\n)\n\ntype zpagesExtension struct {\n\tconfig              *Config\n\ttelemetry           component.TelemetrySettings\n\tzpagesSpanProcessor *zpages.SpanProcessor\n\tserver              *http.Server\n\tstopCh              chan struct{}\n}\n\n// registerableTracerProvider is a tracer that supports\n// the SDK methods RegisterSpanProcessor and UnregisterSpanProcessor.\n//\n// We use an interface instead of casting to the SDK tracer type to support tracer providers\n// that extend the SDK.\ntype registerableTracerProvider interface {\n\t// RegisterSpanProcessor adds the given SpanProcessor to the list of SpanProcessors.\n\t// https://pkg.go.dev/go.opentelemetry.io/otel/sdk/trace#TracerProvider.RegisterSpanProcessor.\n\tRegisterSpanProcessor(SpanProcessor traceSdk.SpanProcessor)\n\n\t// UnregisterSpanProcessor removes the given SpanProcessor from the list of SpanProcessors.\n\t// https://pkg.go.dev/go.opentelemetry.io/otel/sdk/trace#TracerProvider.UnregisterSpanProcessor.\n\tUnregisterSpanProcessor(SpanProcessor traceSdk.SpanProcessor)\n}\n\nfunc (zpe *zpagesExtension) Start(ctx context.Context, host component.Host) error {\n\tzPagesMux := http.NewServeMux()\n\n\ttp := zpe.telemetry.TracerProvider\n\t// If the TracerProvider was wrapped by the service implementation, access the underlying SDK provider\n\tfor {\n\t\twrapped, ok := tp.(interface{ Unwrap() trace.TracerProvider })\n\t\tif !ok {\n\t\t\tbreak\n\t\t}\n\t\ttp = wrapped.Unwrap()\n\t}\n\n\tsdktracer, ok := tp.(registerableTracerProvider)\n\tif ok {\n\t\tsdktracer.RegisterSpanProcessor(zpe.zpagesSpanProcessor)\n\t\tzPagesMux.Handle(path.Join(\"/debug\", tracezPath), zpages.NewTracezHandler(zpe.zpagesSpanProcessor))\n\t\tzpe.telemetry.Logger.Info(\"Registered zPages span processor on tracer provider\")\n\t} else {\n\t\tzpe.telemetry.Logger.Warn(\"zPages span processor registration is not available\")\n\t}\n\n\tif zpe.config.Expvar.Enabled {\n\t\tzPagesMux.Handle(path.Join(\"/debug\", expvarzPath), expvar.Handler())\n\t\tzpe.telemetry.Logger.Info(\"Registered zPages expvar handler\")\n\t}\n\n\thostZPages, ok := host.(interface {\n\t\tRegisterZPages(mux *http.ServeMux, pathPrefix string)\n\t})\n\tif ok {\n\t\thostZPages.RegisterZPages(zPagesMux, \"/debug\")\n\t\tzpe.telemetry.Logger.Info(\"Registered Host's zPages\")\n\t} else {\n\t\tzpe.telemetry.Logger.Warn(\"Host's zPages not available\")\n\t}\n\n\t// Start the listener here so we can have earlier failure if port is\n\t// already in use.\n\tln, err := zpe.config.ToListener(ctx)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tzpe.telemetry.Logger.Info(\"Starting zPages extension\", zap.Any(\"config\", zpe.config))\n\tzpe.server, err = zpe.config.ToServer(ctx, host.GetExtensions(), zpe.telemetry, zPagesMux)\n\tif err != nil {\n\t\treturn err\n\t}\n\tzpe.stopCh = make(chan struct{})\n\tgo func() {\n\t\tdefer close(zpe.stopCh)\n\n\t\tif errHTTP := zpe.server.Serve(ln); errHTTP != nil && !errors.Is(errHTTP, http.ErrServerClosed) {\n\t\t\tcomponentstatus.ReportStatus(host, componentstatus.NewFatalErrorEvent(errHTTP))\n\t\t}\n\t}()\n\n\treturn nil\n}\n\nfunc (zpe *zpagesExtension) Shutdown(context.Context) error {\n\tif zpe.server == nil {\n\t\treturn nil\n\t}\n\terr := zpe.server.Close()\n\tif zpe.stopCh != nil {\n\t\t<-zpe.stopCh\n\t}\n\n\tsdktracer, ok := zpe.telemetry.TracerProvider.(registerableTracerProvider)\n\tif ok {\n\t\tsdktracer.UnregisterSpanProcessor(zpe.zpagesSpanProcessor)\n\t\tzpe.telemetry.Logger.Info(\"Unregistered zPages span processor on tracer provider\")\n\t} else {\n\t\tzpe.telemetry.Logger.Warn(\"zPages span processor registration is not available\")\n\t}\n\n\treturn err\n}\n\nfunc newServer(config *Config, telemetry component.TelemetrySettings) *zpagesExtension {\n\treturn &zpagesExtension{\n\t\tconfig:              config,\n\t\ttelemetry:           telemetry,\n\t\tzpagesSpanProcessor: zpages.NewSpanProcessor(),\n\t}\n}\n"
  },
  {
    "path": "extension/zpagesextension/zpagesextension_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage zpagesextension\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"net/http\"\n\t\"runtime\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\tsdktrace \"go.opentelemetry.io/otel/sdk/trace\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configauth\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\ntype zpagesHost struct {\n\tcomponent.Host\n}\n\nfunc newZPagesHost() *zpagesHost {\n\treturn &zpagesHost{Host: componenttest.NewNopHost()}\n}\n\nfunc (*zpagesHost) RegisterZPages(*http.ServeMux, string) {}\n\nvar (\n\t_ registerableTracerProvider = (*registerableProvider)(nil)\n\t_ registerableTracerProvider = sdktrace.NewTracerProvider()\n)\n\ntype registerableProvider struct {\n\ttrace.TracerProvider\n}\n\nfunc (*registerableProvider) RegisterSpanProcessor(sdktrace.SpanProcessor)   {}\nfunc (*registerableProvider) UnregisterSpanProcessor(sdktrace.SpanProcessor) {}\n\nfunc newZpagesTelemetrySettings() component.TelemetrySettings {\n\tset := componenttest.NewNopTelemetrySettings()\n\tset.TracerProvider = &registerableProvider{set.TracerProvider}\n\treturn set\n}\n\nfunc TestZPagesExtensionUsage(t *testing.T) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\tcfg := &Config{\n\t\tServerConfig: confighttp.ServerConfig{\n\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\tEndpoint:  addr,\n\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t},\n\t\t},\n\t}\n\n\tzpagesExt := newServer(cfg, newZpagesTelemetrySettings())\n\trequire.NotNil(t, zpagesExt)\n\n\trequire.NoError(t, zpagesExt.Start(context.Background(), newZPagesHost()))\n\tt.Cleanup(func() { require.NoError(t, zpagesExt.Shutdown(context.Background())) })\n\n\t// Give a chance for the server goroutine to run.\n\truntime.Gosched()\n\n\tclient := &http.Client{}\n\tresp, err := client.Get(\"http://\" + addr + \"/debug/tracez\")\n\trequire.NoError(t, err)\n\tdefer resp.Body.Close()\n\n\trequire.Equal(t, http.StatusOK, resp.StatusCode)\n}\n\nfunc TestZPagesExtensionBadAuthExtension(t *testing.T) {\n\tcfg := &Config{\n\t\tServerConfig: confighttp.ServerConfig{\n\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\tEndpoint:  \"localhost:0\",\n\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t},\n\t\t\tAuth: configoptional.Some(confighttp.AuthConfig{\n\t\t\t\tConfig: configauth.Config{\n\t\t\t\t\tAuthenticatorID: component.MustNewIDWithName(\"foo\", \"bar\"),\n\t\t\t\t},\n\t\t\t}),\n\t\t},\n\t}\n\tzpagesExt := newServer(cfg, newZpagesTelemetrySettings())\n\trequire.EqualError(t, zpagesExt.Start(context.Background(), componenttest.NewNopHost()), `failed to resolve authenticator \"foo/bar\": authenticator not found`)\n}\n\nfunc TestZPagesExtensionPortAlreadyInUse(t *testing.T) {\n\tendpoint := testutil.GetAvailableLocalAddress(t)\n\tln, err := net.Listen(\"tcp\", endpoint)\n\trequire.NoError(t, err)\n\tdefer ln.Close()\n\n\tcfg := &Config{\n\t\tServerConfig: confighttp.ServerConfig{\n\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\tEndpoint:  endpoint,\n\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t},\n\t\t},\n\t}\n\tzpagesExt := newServer(cfg, newZpagesTelemetrySettings())\n\trequire.NotNil(t, zpagesExt)\n\n\trequire.Error(t, zpagesExt.Start(context.Background(), componenttest.NewNopHost()))\n}\n\nfunc TestZPagesMultipleStarts(t *testing.T) {\n\tcfg := &Config{\n\t\tServerConfig: confighttp.ServerConfig{\n\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\tEndpoint:  testutil.GetAvailableLocalAddress(t),\n\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t},\n\t\t},\n\t}\n\n\tzpagesExt := newServer(cfg, newZpagesTelemetrySettings())\n\trequire.NotNil(t, zpagesExt)\n\n\trequire.NoError(t, zpagesExt.Start(context.Background(), componenttest.NewNopHost()))\n\tt.Cleanup(func() { require.NoError(t, zpagesExt.Shutdown(context.Background())) })\n\n\t// Try to start it again, it will fail since it is on the same endpoint.\n\trequire.Error(t, zpagesExt.Start(context.Background(), componenttest.NewNopHost()))\n}\n\nfunc TestZPagesMultipleShutdowns(t *testing.T) {\n\tcfg := &Config{\n\t\tServerConfig: confighttp.ServerConfig{\n\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\tEndpoint:  testutil.GetAvailableLocalAddress(t),\n\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t},\n\t\t},\n\t}\n\n\tzpagesExt := newServer(cfg, newZpagesTelemetrySettings())\n\trequire.NotNil(t, zpagesExt)\n\n\trequire.NoError(t, zpagesExt.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.NoError(t, zpagesExt.Shutdown(context.Background()))\n\trequire.NoError(t, zpagesExt.Shutdown(context.Background()))\n}\n\nfunc TestZPagesShutdownWithoutStart(t *testing.T) {\n\tcfg := &Config{\n\t\tServerConfig: confighttp.ServerConfig{\n\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\tEndpoint:  testutil.GetAvailableLocalAddress(t),\n\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t},\n\t\t},\n\t}\n\n\tzpagesExt := newServer(cfg, newZpagesTelemetrySettings())\n\trequire.NotNil(t, zpagesExt)\n\n\trequire.NoError(t, zpagesExt.Shutdown(context.Background()))\n}\n\nfunc TestZPagesEnableExpvar(t *testing.T) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\tcfg := &Config{\n\t\tServerConfig: confighttp.ServerConfig{\n\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\tEndpoint:  addr,\n\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t},\n\t\t},\n\t\tExpvar: ExpvarConfig{\n\t\t\tEnabled: true,\n\t\t},\n\t}\n\n\tzpagesExt := newServer(cfg, newZpagesTelemetrySettings())\n\trequire.NotNil(t, zpagesExt)\n\n\trequire.NoError(t, zpagesExt.Start(context.Background(), newZPagesHost()))\n\tt.Cleanup(func() { require.NoError(t, zpagesExt.Shutdown(context.Background())) })\n\n\t// Give a chance for the server goroutine to run.\n\truntime.Gosched()\n\n\tclient := &http.Client{}\n\tresp, err := client.Get(\"http://\" + addr + \"/debug/expvarz\")\n\trequire.NoError(t, err)\n\tdefer resp.Body.Close()\n\n\trequire.Equal(t, http.StatusOK, resp.StatusCode)\n}\n"
  },
  {
    "path": "featuregate/Makefile",
    "content": "include ../Makefile.Common\n"
  },
  {
    "path": "featuregate/README.md",
    "content": "# Collector Feature Gates\n\nThis package provides a mechanism that allows operators to enable and disable\nexperimental or transitional features at deployment time. These flags should\nbe able to govern the behavior of the application starting as early as possible\nand should be available to every component such that decisions may be made\nbased on flags at the component level.\n\n## Usage\n\n### With mdatagen\n\nIn components that use mdatagen, feature gates should be defined in the\ncomponent's `metadata.yml`.\n\n```yaml\nfeature_gates:\n\t- id: namespaced.uniqueIdentifier\n\t\tdescription: A brief description of what the gate controls\n\t\tstage: stable\n\t\tfrom_version: 'v0.65.0'\n\t\treference_url: 'https://github.com/open-telemetry/opentelemetry-collector/issues/6167'\n```\n\nRunning the mdatagen code generator with this configuration will initialize the\nfeature flag in the `internal/metadata` submodule.\nThe status of the gate can later be checked by calling that submodule:\n\n```go\nif metadata.NamespacedUniqueIdentifierFeatureGate.IsEnabled() {\n\tsetupNewFeature()\n}\n```\n\n### In code\n\nIn components that don't use mdatagen, feature gates can be defined and\nregistered with the global registry in an `init()` function.  This makes the\n`Gate` available to be configured and queried with the defined\n[`Stage`](#feature-lifecycle) default value.\nA `Gate` can have a list of associated issues that allow users to refer to\nthe issue and report any additional problems or understand the context of the `Gate`.\nOnce a `Gate` has been marked as `Stable`, it must have a `RemovalVersion` set.\n\n```go\nvar myFeatureGate = featuregate.GlobalRegistry().MustRegister(\n\t\"namespaced.uniqueIdentifier\",\n\tfeaturegate.Stable,\n    featuregate.WithRegisterFromVersion(\"v0.65.0\")\n\tfeaturegate.WithRegisterDescription(\"A brief description of what the gate controls\"),\n\tfeaturegate.WithRegisterReferenceURL(\"https://github.com/open-telemetry/opentelemetry-collector/issues/6167\"),\n\tfeaturegate.WithRegisterToVersion(\"v0.70.0\"))\n```\n\nThe status of the gate may later be checked by interrogating the global\nfeature gate registry:\n\n```go\nif myFeatureGate.IsEnabled() {\n\tsetupNewFeature()\n}\n```\n\nNote that querying the registry takes a read lock and accesses a map, so it\nshould be done once and the result cached for local use if repeated checks\nare required.  Avoid querying the registry in a loop.\n\n## Controlling Gates\n\nFeature gates can be enabled or disabled via the CLI, with the\n`--feature-gates` flag. When using the CLI flag, gate\nidentifiers must be presented as a comma-delimited list. Gate identifiers\nprefixed with `-` will disable the gate and prefixing with `+` or with no\nprefix will enable the gate.\n\n```shell\notelcol --config=config.yaml --feature-gates=gate1,-gate2,+gate3\n```\n\nThis will enable `gate1` and `gate3` and disable `gate2`.\n\n## Feature Lifecycle\n\nFeatures controlled by a `Gate` should follow a three-stage lifecycle,\nmodeled after the [system used by Kubernetes](https://kubernetes.io/docs/reference/command-line-tools-reference/feature-gates/#feature-stages):\n\n1. An `alpha` stage where the feature is disabled by default and must be enabled\n   through a `Gate`.\n2. A `beta` stage where the feature has been well tested and is enabled by\n   default but can be disabled through a `Gate`.\n3. A generally available or `stable` stage where the feature is permanently enabled. At this stage\n   the gate should no longer be explicitly used. Disabling the gate will produce an error and\n   explicitly enabling will produce a warning log.\n4. A `stable` feature gate will be removed in the version specified by its `ToVersion` value.\n\nFeatures that prove unworkable in the `alpha` stage may be discontinued\nwithout proceeding to the `beta` stage. Instead, they will proceed to the\n`deprecated` stage, which will feature is permanently disabled. A feature gate will\nbe removed once it has been `deprecated` for at least 2 releases of the collector.\n\nFeatures that make it to the `beta` stage are intended to reach general availability but may still be discontinued.\nIf, after wider use, it is determined that the gate should be discontinued it will be reverted to the `alpha` stage\nfor 2 releases and then proceed to the `deprecated` stage. If instead it is ready for general availability it will\nproceed to the `stable` stage.\n"
  },
  {
    "path": "featuregate/examples_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage featuregate_test\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\nfunc ExampleRegistry_Register() {\n\treg := featuregate.NewRegistry()\n\tgate := reg.MustRegister(\n\t\t\"featuregate.example.gate\",\n\t\tfeaturegate.StageAlpha,\n\t\tfeaturegate.WithRegisterDescription(\"Example gate\"),\n\t)\n\n\t// By default an alpha feature gate is disabled.\n\tfmt.Println(gate.IsEnabled())\n\tif err := reg.Set(gate.ID(), true); err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t\treturn\n\t}\n\t// Alpha feature gates can be modified so the gate is now enabled.\n\tfmt.Println(gate.IsEnabled())\n\n\t// Output:\n\t// false\n\t// true\n}\n\nfunc ExampleRegistry_RegisterFlags() {\n\treg := featuregate.NewRegistry()\n\talphaGate := reg.MustRegister(\"featuregate.example.alpha\", featuregate.StageAlpha)\n\tbetaGate := reg.MustRegister(\"featuregate.example.beta\", featuregate.StageBeta)\n\n\tfs := flag.NewFlagSet(\"example\", flag.ContinueOnError)\n\t// RegisterFlags registers the `--feature-gates` flag on the FlagSet.\n\treg.RegisterFlags(fs)\n\tif err := fs.Parse([]string{\"--feature-gates=featuregate.example.alpha,-featuregate.example.beta\"}); err != nil {\n\t\tfmt.Println(\"error:\", err)\n\t\treturn\n\t}\n\n\tfmt.Printf(\"featuregate.example.alpha=%v\\n\", alphaGate.IsEnabled())\n\tfmt.Printf(\"featuregate.example.beta=%v\\n\", betaGate.IsEnabled())\n\n\t// Output:\n\t// featuregate.example.alpha=true\n\t// featuregate.example.beta=false\n}\n"
  },
  {
    "path": "featuregate/flag.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage featuregate // import \"go.opentelemetry.io/collector/featuregate\"\n\nimport (\n\t\"flag\"\n\t\"strings\"\n\n\t\"go.uber.org/multierr\"\n)\n\nconst (\n\tfeatureGatesFlag            = \"feature-gates\"\n\tfeatureGatesFlagDescription = \"Comma-delimited list of feature gate identifiers. Prefix with '-' to disable the feature. '+' or no prefix will enable the feature.\"\n)\n\n// RegisterFlagsOption is an option for RegisterFlags.\ntype RegisterFlagsOption interface {\n\tprivate()\n}\n\n// RegisterFlags that directly applies feature gate statuses to a Registry.\nfunc (r *Registry) RegisterFlags(flagSet *flag.FlagSet, _ ...RegisterFlagsOption) {\n\tflagSet.Var(&flagValue{reg: r}, featureGatesFlag, featureGatesFlagDescription)\n}\n\n// flagValue implements the flag.Value interface and directly applies feature gate statuses to a Registry.\ntype flagValue struct {\n\treg *Registry\n}\n\nfunc (f *flagValue) String() string {\n\t// This function can be called by isZeroValue https://github.com/golang/go/blob/go1.23.3/src/flag/flag.go#L630\n\t// which creates an instance of flagValue using reflect.New. In this case, the field `reg` is nil.\n\tif f.reg == nil {\n\t\treturn \"\"\n\t}\n\n\tvar ids []string\n\tf.reg.VisitAll(func(g *Gate) {\n\t\tid := g.ID()\n\t\tif !g.IsEnabled() {\n\t\t\tid = \"-\" + id\n\t\t}\n\t\tids = append(ids, id)\n\t})\n\treturn strings.Join(ids, \",\")\n}\n\nfunc (f *flagValue) Set(s string) error {\n\tif s == \"\" {\n\t\treturn nil\n\t}\n\n\tvar errs error\n\tids := strings.Split(s, \",\")\n\tfor i := range ids {\n\t\tid := ids[i]\n\t\tval := true\n\t\tswitch id[0] {\n\t\tcase '-':\n\t\t\tid = id[1:]\n\t\t\tval = false\n\t\tcase '+':\n\t\t\tid = id[1:]\n\t\t}\n\t\terrs = multierr.Append(errs, f.reg.Set(id, val))\n\t}\n\treturn errs\n}\n"
  },
  {
    "path": "featuregate/flag_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage featuregate\n\nimport (\n\t\"flag\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestNewFlag(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname           string\n\t\tinput          string\n\t\texpectedSetErr bool\n\t\texpected       map[string]bool\n\t\texpectedStr    string\n\t}{\n\t\t{\n\t\t\tname:        \"empty item\",\n\t\t\tinput:       \"\",\n\t\t\texpected:    map[string]bool{\"alpha\": false, \"beta\": true, \"deprecated\": false, \"stable\": true},\n\t\t\texpectedStr: \"-alpha,beta,-deprecated,stable\",\n\t\t},\n\t\t{\n\t\t\tname:        \"simple enable alpha\",\n\t\t\tinput:       \"alpha\",\n\t\t\texpected:    map[string]bool{\"alpha\": true, \"beta\": true, \"deprecated\": false, \"stable\": true},\n\t\t\texpectedStr: \"alpha,beta,-deprecated,stable\",\n\t\t},\n\t\t{\n\t\t\tname:        \"plus enable alpha\",\n\t\t\tinput:       \"+alpha\",\n\t\t\texpected:    map[string]bool{\"alpha\": true, \"beta\": true, \"deprecated\": false, \"stable\": true},\n\t\t\texpectedStr: \"alpha,beta,-deprecated,stable\",\n\t\t},\n\t\t{\n\t\t\tname:        \"disabled beta\",\n\t\t\tinput:       \"-beta\",\n\t\t\texpected:    map[string]bool{\"alpha\": false, \"beta\": false, \"deprecated\": false, \"stable\": true},\n\t\t\texpectedStr: \"-alpha,-beta,-deprecated,stable\",\n\t\t},\n\t\t{\n\t\t\tname:        \"multiple items\",\n\t\t\tinput:       \"-beta,alpha\",\n\t\t\texpected:    map[string]bool{\"alpha\": true, \"beta\": false, \"deprecated\": false, \"stable\": true},\n\t\t\texpectedStr: \"alpha,-beta,-deprecated,stable\",\n\t\t},\n\t\t{\n\t\t\tname:        \"multiple items with plus\",\n\t\t\tinput:       \"-beta,+alpha\",\n\t\t\texpected:    map[string]bool{\"alpha\": true, \"beta\": false, \"deprecated\": false, \"stable\": true},\n\t\t\texpectedStr: \"alpha,-beta,-deprecated,stable\",\n\t\t},\n\t\t{\n\t\t\tname:        \"repeated items\",\n\t\t\tinput:       \"alpha,-beta,-alpha\",\n\t\t\texpected:    map[string]bool{\"alpha\": false, \"beta\": false, \"deprecated\": false, \"stable\": true},\n\t\t\texpectedStr: \"-alpha,-beta,-deprecated,stable\",\n\t\t},\n\t\t{\n\t\t\tname:        \"multiple plus items\",\n\t\t\tinput:       \"+alpha,+beta\",\n\t\t\texpected:    map[string]bool{\"alpha\": true, \"beta\": true, \"deprecated\": false, \"stable\": true},\n\t\t\texpectedStr: \"alpha,beta,-deprecated,stable\",\n\t\t},\n\t\t{\n\t\t\tname:        \"enable stable\",\n\t\t\tinput:       \"stable\",\n\t\t\texpected:    map[string]bool{\"alpha\": false, \"beta\": true, \"deprecated\": false, \"stable\": true},\n\t\t\texpectedStr: \"-alpha,beta,-deprecated,stable\",\n\t\t},\n\t\t{\n\t\t\tname:           \"disable stable\",\n\t\t\tinput:          \"-stable\",\n\t\t\texpectedSetErr: true,\n\t\t\texpected:       map[string]bool{\"alpha\": false, \"beta\": true, \"deprecated\": false, \"stable\": true},\n\t\t\texpectedStr:    \"-alpha,beta,-deprecated,stable\",\n\t\t},\n\t\t{\n\t\t\tname:           \"enable deprecated\",\n\t\t\tinput:          \"deprecated\",\n\t\t\texpectedSetErr: true,\n\t\t\texpected:       map[string]bool{\"alpha\": false, \"beta\": true, \"deprecated\": false, \"stable\": true},\n\t\t\texpectedStr:    \"-alpha,beta,-deprecated,stable\",\n\t\t},\n\t\t{\n\t\t\tname:        \"disable deprecated\",\n\t\t\tinput:       \"-deprecated\",\n\t\t\texpected:    map[string]bool{\"alpha\": false, \"beta\": true, \"deprecated\": false, \"stable\": true},\n\t\t\texpectedStr: \"-alpha,beta,-deprecated,stable\",\n\t\t},\n\t\t{\n\t\t\tname:           \"enable missing\",\n\t\t\tinput:          \"missing\",\n\t\t\texpectedSetErr: true,\n\t\t\texpected:       map[string]bool{\"alpha\": false, \"beta\": true, \"deprecated\": false, \"stable\": true},\n\t\t\texpectedStr:    \"-alpha,beta,-deprecated,stable\",\n\t\t},\n\t\t{\n\t\t\tname:           \"disable missing\",\n\t\t\tinput:          \"missing\",\n\t\t\texpectedSetErr: true,\n\t\t\texpected:       map[string]bool{\"alpha\": false, \"beta\": true, \"deprecated\": false, \"stable\": true},\n\t\t\texpectedStr:    \"-alpha,beta,-deprecated,stable\",\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\treg := NewRegistry()\n\t\t\treg.MustRegister(\"alpha\", StageAlpha)\n\t\t\treg.MustRegister(\"beta\", StageBeta)\n\t\t\treg.MustRegister(\"deprecated\", StageDeprecated, WithRegisterToVersion(\"1.0.0\"))\n\t\t\treg.MustRegister(\"stable\", StageStable, WithRegisterToVersion(\"1.0.0\"))\n\t\t\tfs := flag.NewFlagSet(\"test\", flag.ContinueOnError)\n\t\t\treg.RegisterFlags(fs)\n\t\t\tregistrationFlag := fs.Lookup(featureGatesFlag)\n\t\t\trequire.NotNil(t, registrationFlag)\n\t\t\tif tt.expectedSetErr {\n\t\t\t\trequire.Error(t, registrationFlag.Value.Set(tt.input))\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, registrationFlag.Value.Set(tt.input))\n\t\t\t}\n\t\t\tgot := map[string]bool{}\n\t\t\treg.VisitAll(func(g *Gate) {\n\t\t\t\tgot[g.ID()] = g.IsEnabled()\n\t\t\t})\n\t\t\tassert.Equal(t, tt.expected, got)\n\t\t\tassert.Equal(t, tt.expectedStr, registrationFlag.Value.String())\n\t\t})\n\t}\n}\n\nfunc TestFlagStringNotInitialize(t *testing.T) {\n\tflag := &flagValue{}\n\tassert.Empty(t, flag.String())\n}\n"
  },
  {
    "path": "featuregate/gate.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage featuregate // import \"go.opentelemetry.io/collector/featuregate\"\n\nimport (\n\t\"fmt\"\n\t\"sync/atomic\"\n\n\t\"github.com/hashicorp/go-version\"\n)\n\n// Gate is an immutable object that is owned by the Registry and represents an individual feature that\n// may be enabled or disabled based on the lifecycle state of the feature and CLI flags specified by the user.\ntype Gate struct {\n\tid           string\n\tdescription  string\n\treferenceURL string\n\tfromVersion  *version.Version\n\ttoVersion    *version.Version\n\tstage        Stage\n\tenabled      *atomic.Bool\n}\n\n// ID returns the id of the Gate.\nfunc (g *Gate) ID() string {\n\treturn g.id\n}\n\n// IsEnabled returns true if the feature described by the Gate is enabled.\nfunc (g *Gate) IsEnabled() bool {\n\treturn g.enabled.Load()\n}\n\n// Description returns the description for the Gate.\nfunc (g *Gate) Description() string {\n\treturn g.description\n}\n\n// Stage returns the Gate's lifecycle stage.\nfunc (g *Gate) Stage() Stage {\n\treturn g.stage\n}\n\n// ReferenceURL returns the URL to the contextual information about the Gate.\nfunc (g *Gate) ReferenceURL() string {\n\treturn g.referenceURL\n}\n\n// FromVersion returns the version information when the Gate's was added.\nfunc (g *Gate) FromVersion() string {\n\treturn fmt.Sprintf(\"v%s\", g.fromVersion)\n}\n\n// ToVersion returns the version information when Gate's in StageStable.\nfunc (g *Gate) ToVersion() string {\n\treturn fmt.Sprintf(\"v%s\", g.toVersion)\n}\n"
  },
  {
    "path": "featuregate/gate_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage featuregate\n\nimport (\n\t\"sync/atomic\"\n\t\"testing\"\n\n\t\"github.com/hashicorp/go-version\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestGate(t *testing.T) {\n\tenabled := &atomic.Bool{}\n\tenabled.Store(true)\n\tfrom, err := version.NewVersion(\"v0.61.0\")\n\trequire.NoError(t, err)\n\tto, err := version.NewVersion(\"v0.64.0\")\n\trequire.NoError(t, err)\n\n\tg := &Gate{\n\t\tid:           \"test\",\n\t\tdescription:  \"test gate\",\n\t\tenabled:      enabled,\n\t\tstage:        StageAlpha,\n\t\treferenceURL: \"http://example.com\",\n\t\tfromVersion:  from,\n\t\ttoVersion:    to,\n\t}\n\n\tassert.Equal(t, \"test\", g.ID())\n\tassert.Equal(t, \"test gate\", g.Description())\n\tassert.True(t, g.IsEnabled())\n\tassert.Equal(t, StageAlpha, g.Stage())\n\tassert.Equal(t, \"http://example.com\", g.ReferenceURL())\n\tassert.Equal(t, \"v0.61.0\", g.FromVersion())\n\tassert.Equal(t, \"v0.64.0\", g.ToVersion())\n}\n"
  },
  {
    "path": "featuregate/go.mod",
    "content": "module go.opentelemetry.io/collector/featuregate\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/hashicorp/go-version v1.8.0\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/multierr v1.11.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/kr/pretty v0.3.1 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/rogpeppe/go-internal v1.10.0 // indirect\n\tgopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nretract (\n\tv0.76.0 // Depends on retracted pdata v1.0.0-rc10 module, use v0.76.1\n\tv0.69.0 // Release failed, use v0.69.1\n)\n"
  },
  {
    "path": "featuregate/go.sum",
    "content": "github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=\ngithub.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "featuregate/metadata.yaml",
    "content": "type: featuregate\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "featuregate/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage featuregate\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "featuregate/registry.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage featuregate // import \"go.opentelemetry.io/collector/featuregate\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"net/url\"\n\t\"regexp\"\n\t\"sort\"\n\t\"sync\"\n\t\"sync/atomic\"\n\n\t\"github.com/hashicorp/go-version\"\n)\n\nvar (\n\tglobalRegistry = NewRegistry()\n\n\t// idRegexp is used to validate the ID of a Gate.\n\t// IDs' characters must be alphanumeric or dots.\n\tidRegexp = regexp.MustCompile(`^[0-9a-zA-Z.]*$`)\n)\n\n// ErrAlreadyRegistered is returned when adding a Gate that is already registered.\nvar ErrAlreadyRegistered = errors.New(\"gate is already registered\")\n\n// GlobalRegistry returns the global Registry.\nfunc GlobalRegistry() *Registry {\n\treturn globalRegistry\n}\n\ntype Registry struct {\n\tgates sync.Map\n}\n\n// NewRegistry returns a new empty Registry.\nfunc NewRegistry() *Registry {\n\treturn &Registry{}\n}\n\n// RegisterOption allows to configure additional information about a Gate during registration.\ntype RegisterOption interface {\n\tapply(g *Gate) error\n}\n\ntype registerOptionFunc func(g *Gate) error\n\nfunc (ro registerOptionFunc) apply(g *Gate) error {\n\treturn ro(g)\n}\n\n// WithRegisterDescription adds description for the Gate.\nfunc WithRegisterDescription(description string) RegisterOption {\n\treturn registerOptionFunc(func(g *Gate) error {\n\t\tg.description = description\n\t\treturn nil\n\t})\n}\n\n// WithRegisterReferenceURL adds a URL that has all the contextual information about the Gate.\n// referenceURL must be a valid URL as defined by `net/url.Parse`.\nfunc WithRegisterReferenceURL(referenceURL string) RegisterOption {\n\treturn registerOptionFunc(func(g *Gate) error {\n\t\tif _, err := url.Parse(referenceURL); err != nil {\n\t\t\treturn fmt.Errorf(\"WithRegisterReferenceURL: invalid reference URL %q: %w\", referenceURL, err)\n\t\t}\n\n\t\tg.referenceURL = referenceURL\n\t\treturn nil\n\t})\n}\n\n// WithRegisterFromVersion is used to set the Gate \"FromVersion\".\n// The \"FromVersion\" contains the Collector release when a feature is introduced.\n// fromVersion must be a valid version string: it may start with 'v' and must be in the format Major.Minor.Patch[-PreRelease].\n// PreRelease is optional and may have dashes, tildes and ASCII alphanumeric characters.\nfunc WithRegisterFromVersion(fromVersion string) RegisterOption {\n\treturn registerOptionFunc(func(g *Gate) error {\n\t\tfrom, err := version.NewVersion(fromVersion)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"WithRegisterFromVersion: invalid version %q: %w\", fromVersion, err)\n\t\t}\n\n\t\tg.fromVersion = from\n\t\treturn nil\n\t})\n}\n\n// WithRegisterToVersion is used to set the Gate \"ToVersion\".\n// The \"ToVersion\", if not empty, contains the last Collector release in which you can still use a feature gate.\n// If the feature stage is either \"Deprecated\" or \"Stable\", the \"ToVersion\" is the Collector release when the feature is removed.\n// toVersion must be a valid version string: it may start with 'v' and must be in the format Major.Minor.Patch[-PreRelease].\n// PreRelease is optional and may have dashes, tildes and ASCII alphanumeric characters.\nfunc WithRegisterToVersion(toVersion string) RegisterOption {\n\treturn registerOptionFunc(func(g *Gate) error {\n\t\tto, err := version.NewVersion(toVersion)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"WithRegisterToVersion: invalid version %q:  %w\", toVersion, err)\n\t\t}\n\n\t\tg.toVersion = to\n\t\treturn nil\n\t})\n}\n\n// MustRegister like Register but panics if an invalid ID or gate options are provided.\nfunc (r *Registry) MustRegister(id string, stage Stage, opts ...RegisterOption) *Gate {\n\tg, err := r.Register(id, stage, opts...)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn g\n}\n\nfunc validateID(id string) error {\n\tif id == \"\" {\n\t\treturn errors.New(\"empty ID\")\n\t}\n\n\tif !idRegexp.MatchString(id) {\n\t\treturn errors.New(\"invalid character(s) in ID\")\n\t}\n\treturn nil\n}\n\n// Register a Gate and return it. The returned Gate can be used to check if is enabled or not.\n// id must be an ASCII alphanumeric nonempty string. Dots are allowed for namespacing.\nfunc (r *Registry) Register(id string, stage Stage, opts ...RegisterOption) (*Gate, error) {\n\tif err := validateID(id); err != nil {\n\t\treturn nil, fmt.Errorf(\"invalid ID %q: %w\", id, err)\n\t}\n\n\tg := &Gate{\n\t\tid:    id,\n\t\tstage: stage,\n\t}\n\tfor _, opt := range opts {\n\t\terr := opt.apply(g)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to apply option: %w\", err)\n\t\t}\n\t}\n\tswitch g.stage {\n\tcase StageAlpha, StageDeprecated:\n\t\tg.enabled = &atomic.Bool{}\n\tcase StageBeta, StageStable:\n\t\tenabled := &atomic.Bool{}\n\t\tenabled.Store(true)\n\t\tg.enabled = enabled\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown stage value %q for gate %q\", stage, id)\n\t}\n\tif (g.stage == StageStable || g.stage == StageDeprecated) && g.toVersion == nil {\n\t\treturn nil, fmt.Errorf(\"no removal version set for %v gate %q\", g.stage.String(), id)\n\t}\n\n\tif g.fromVersion != nil && g.toVersion != nil && g.toVersion.LessThan(g.fromVersion) {\n\t\treturn nil, fmt.Errorf(\"toVersion %q is before fromVersion %q\", g.toVersion, g.fromVersion)\n\t}\n\n\tif _, loaded := r.gates.LoadOrStore(id, g); loaded {\n\t\treturn nil, fmt.Errorf(\"failed to register %q: %w\", id, ErrAlreadyRegistered)\n\t}\n\treturn g, nil\n}\n\n// Set the enabled valued for a Gate identified by the given id.\nfunc (r *Registry) Set(id string, enabled bool) error {\n\tv, ok := r.gates.Load(id)\n\tif !ok {\n\t\tvalidGates := []string{}\n\t\tr.VisitAll(func(g *Gate) {\n\t\t\tvalidGates = append(validGates, g.ID())\n\t\t})\n\t\treturn fmt.Errorf(\"no such feature gate %q. valid gates: %v\", id, validGates)\n\t}\n\tg := v.(*Gate)\n\n\tswitch g.stage {\n\tcase StageStable:\n\t\tif !enabled {\n\t\t\treturn fmt.Errorf(\"feature gate %q is stable, can not be disabled\", id)\n\t\t}\n\t\tfmt.Printf(\"Feature gate %q is stable and already enabled. It will be removed in version %v and continued use of the gate after version %v will result in an error.\\n\", id, g.toVersion, g.toVersion)\n\tcase StageDeprecated:\n\t\tif enabled {\n\t\t\treturn fmt.Errorf(\"feature gate %q is deprecated, can not be enabled\", id)\n\t\t}\n\t\tfmt.Printf(\"Feature gate %q is deprecated and already disabled. It will be removed in version %v and continued use of the gate after version %v will result in an error.\\n\", id, g.toVersion, g.toVersion)\n\tdefault:\n\t\tg.enabled.Store(enabled)\n\t}\n\treturn nil\n}\n\n// VisitAll visits all the gates in lexicographical order, calling fn for each.\nfunc (r *Registry) VisitAll(fn func(*Gate)) {\n\tvar gates []*Gate\n\tr.gates.Range(func(_, value any) bool {\n\t\tgates = append(gates, value.(*Gate))\n\t\treturn true\n\t})\n\tsort.Slice(gates, func(i, j int) bool {\n\t\treturn gates[i].ID() < gates[j].ID()\n\t})\n\tfor i := range gates {\n\t\tfn(gates[i])\n\t}\n}\n"
  },
  {
    "path": "featuregate/registry_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage featuregate\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestGlobalRegistry(t *testing.T) {\n\tassert.Same(t, globalRegistry, GlobalRegistry())\n}\n\nfunc TestRegistry(t *testing.T) {\n\tr := NewRegistry()\n\t// Expect that no gates to visit.\n\tr.VisitAll(func(*Gate) {\n\t\tt.FailNow()\n\t})\n\n\tconst id = \"foo\"\n\tg, err := r.Register(id, StageBeta, WithRegisterDescription(\"Test Gate\"))\n\trequire.NoError(t, err)\n\tr.VisitAll(func(gate *Gate) {\n\t\tassert.Equal(t, id, gate.ID())\n\t})\n\tassert.True(t, g.IsEnabled())\n\n\trequire.NoError(t, r.Set(id, false))\n\tassert.False(t, g.IsEnabled())\n\n\t_, err = r.Register(id, StageBeta)\n\trequire.ErrorIs(t, err, ErrAlreadyRegistered)\n\tassert.Panics(t, func() {\n\t\tr.MustRegister(id, StageBeta)\n\t})\n}\n\nfunc TestRegistryApplyError(t *testing.T) {\n\tr := NewRegistry()\n\trequire.Error(t, r.Set(\"foo\", true))\n\tr.MustRegister(\"bar\", StageAlpha)\n\n\trequire.Error(t, r.Set(\"foo\", true))\n\t_, err := r.Register(\"foo\", StageStable)\n\trequire.Error(t, err)\n\trequire.Error(t, r.Set(\"foo\", true))\n\tr.MustRegister(\"foo\", StageStable, WithRegisterToVersion(\"v1.0.0\"))\n\trequire.Error(t, r.Set(\"foo\", false))\n\n\trequire.Error(t, r.Set(\"deprecated\", true))\n\t_, err = r.Register(\"deprecated\", StageDeprecated)\n\trequire.Error(t, err)\n\trequire.Error(t, r.Set(\"deprecated\", true))\n\tr.MustRegister(\"deprecated\", StageDeprecated, WithRegisterToVersion(\"v1.0.0\"))\n\tassert.Error(t, r.Set(\"deprecated\", true))\n}\n\nfunc TestRegistryApply(t *testing.T) {\n\tr := NewRegistry()\n\tfooGate := r.MustRegister(\"foo\", StageAlpha, WithRegisterDescription(\"Test Gate\"))\n\tassert.False(t, fooGate.IsEnabled())\n\trequire.NoError(t, r.Set(fooGate.ID(), true))\n\tassert.True(t, fooGate.IsEnabled())\n}\n\nfunc TestRegisterGateLifecycle(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tname      string\n\t\tid        string\n\t\tstage     Stage\n\t\topts      []RegisterOption\n\t\tenabled   bool\n\t\tshouldErr bool\n\t}{\n\t\t{\n\t\t\tname:      \"StageAlpha Flag\",\n\t\t\tid:        \"test.gate\",\n\t\t\tstage:     StageAlpha,\n\t\t\tenabled:   false,\n\t\t\tshouldErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"StageAlpha Flag with all options\",\n\t\t\tid:    \"test.gate\",\n\t\t\tstage: StageAlpha,\n\t\t\topts: []RegisterOption{\n\t\t\t\tWithRegisterDescription(\"test.gate\"),\n\t\t\t\tWithRegisterReferenceURL(\"http://example.com/issue/1\"),\n\t\t\t\tWithRegisterToVersion(\"v0.88.0\"),\n\t\t\t},\n\t\t\tenabled:   false,\n\t\t\tshouldErr: false,\n\t\t},\n\t\t{\n\t\t\tname:      \"StageBeta Flag\",\n\t\t\tid:        \"test.gate\",\n\t\t\tstage:     StageBeta,\n\t\t\tenabled:   true,\n\t\t\tshouldErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"StageStable Flag\",\n\t\t\tid:    \"test.gate\",\n\t\t\tstage: StageStable,\n\t\t\topts: []RegisterOption{\n\t\t\t\tWithRegisterToVersion(\"v1.0.0-rcv.0014\"),\n\t\t\t},\n\t\t\tenabled:   true,\n\t\t\tshouldErr: false,\n\t\t},\n\t\t{\n\t\t\tname:  \"StageDeprecated Flag\",\n\t\t\tid:    \"test.gate\",\n\t\t\tstage: StageDeprecated,\n\t\t\topts: []RegisterOption{\n\t\t\t\tWithRegisterToVersion(\"v0.89.0\"),\n\t\t\t},\n\t\t\tenabled:   false,\n\t\t\tshouldErr: false,\n\t\t},\n\t\t{\n\t\t\tname:      \"Invalid stage\",\n\t\t\tid:        \"test.gate\",\n\t\t\tstage:     Stage(-1),\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"StageStable gate missing removal version\",\n\t\t\tid:        \"test.gate\",\n\t\t\tstage:     StageStable,\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"StageDeprecated gate missing removal version\",\n\t\t\tid:        \"test.gate\",\n\t\t\tstage:     StageDeprecated,\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"Duplicate gate\",\n\t\t\tid:        \"existing.gate\",\n\t\t\tstage:     StageStable,\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"Invalid gate name\",\n\t\t\tid:        \"+invalid.gate.name\",\n\t\t\tstage:     StageAlpha,\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"Invalid empty gate\",\n\t\t\tid:        \"\",\n\t\t\tstage:     StageAlpha,\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"Invalid gate to version\",\n\t\t\tid:        \"invalid.gate.to.version\",\n\t\t\tstage:     StageAlpha,\n\t\t\topts:      []RegisterOption{WithRegisterToVersion(\"invalid-version\")},\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"Invalid gate from version\",\n\t\t\tid:        \"invalid.gate.from.version\",\n\t\t\tstage:     StageAlpha,\n\t\t\topts:      []RegisterOption{WithRegisterFromVersion(\"invalid-version\")},\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"Invalid gate reference URL\",\n\t\t\tid:        \"invalid.gate.reference.URL\",\n\t\t\tstage:     StageAlpha,\n\t\t\topts:      []RegisterOption{WithRegisterReferenceURL(\":invalid-url\")},\n\t\t\tshouldErr: true,\n\t\t},\n\t\t{\n\t\t\tname:  \"Empty version range\",\n\t\t\tid:    \"invalid.gate.version.range\",\n\t\t\tstage: StageAlpha,\n\t\t\topts: []RegisterOption{\n\t\t\t\tWithRegisterFromVersion(\"v0.88.0\"),\n\t\t\t\tWithRegisterToVersion(\"v0.87.0\"),\n\t\t\t},\n\t\t\tshouldErr: true,\n\t\t},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tr := NewRegistry()\n\t\t\tr.MustRegister(\"existing.gate\", StageBeta)\n\t\t\tif tc.shouldErr {\n\t\t\t\t_, err := r.Register(tc.id, tc.stage, tc.opts...)\n\t\t\t\trequire.Error(t, err)\n\t\t\t\tassert.Panics(t, func() {\n\t\t\t\t\tr.MustRegister(tc.id, tc.stage, tc.opts...)\n\t\t\t\t})\n\t\t\t\treturn\n\t\t\t}\n\t\t\tg, err := r.Register(tc.id, tc.stage, tc.opts...)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tc.enabled, g.IsEnabled())\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "featuregate/stage.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage featuregate // import \"go.opentelemetry.io/collector/featuregate\"\n\n// Stage represents the Gate's lifecycle and what is the expected state of it.\ntype Stage int8\n\nconst (\n\t// StageAlpha is used when creating a new feature and the Gate must be explicitly enabled\n\t// by the operator.\n\t//\n\t// The Gate will be disabled by default.\n\tStageAlpha Stage = iota\n\t// StageBeta is used when the feature gate is well tested and is enabled by default,\n\t// but can be disabled by a Gate.\n\t//\n\t// The Gate will be enabled by default.\n\tStageBeta\n\t// StageStable is used when feature is permanently enabled and can not be disabled by a Gate.\n\t// This value is used to provide feedback to the user that the gate will be removed in the next versions.\n\t//\n\t// The Gate will be enabled by default and will return an error if disabled.\n\tStageStable\n\t// StageDeprecated is used when feature is permanently disabled and can not be enabled by a Gate.\n\t// This value is used to provide feedback to the user that the gate will be removed in the next versions.\n\t//\n\t// The Gate will be disabled by default and will return an error if modified.\n\tStageDeprecated\n)\n\nfunc (s Stage) String() string {\n\tswitch s {\n\tcase StageAlpha:\n\t\treturn \"Alpha\"\n\tcase StageBeta:\n\t\treturn \"Beta\"\n\tcase StageStable:\n\t\treturn \"Stable\"\n\tcase StageDeprecated:\n\t\treturn \"Deprecated\"\n\t}\n\treturn \"Unknown\"\n}\n"
  },
  {
    "path": "featuregate/stage_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage featuregate\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestStageString(t *testing.T) {\n\tassert.Equal(t, \"Alpha\", StageAlpha.String())\n\tassert.Equal(t, \"Beta\", StageBeta.String())\n\tassert.Equal(t, \"Stable\", StageStable.String())\n\tassert.Equal(t, \"Deprecated\", StageDeprecated.String())\n\tassert.Equal(t, \"Unknown\", Stage(-1).String())\n}\n"
  },
  {
    "path": "filter/Makefile",
    "content": "include ../Makefile.Common\n"
  },
  {
    "path": "filter/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage filter // import \"go.opentelemetry.io/collector/filter\"\n\nimport (\n\t\"errors\"\n\t\"regexp\"\n)\n\n// Config configures the matching behavior of a Filter.\ntype Config struct {\n\tStrict string `mapstructure:\"strict\"`\n\tRegex  string `mapstructure:\"regexp\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\nfunc (c Config) Validate() error {\n\tif c.Strict == \"\" && c.Regex == \"\" {\n\t\treturn errors.New(\"must specify either strict or regex\")\n\t}\n\tif c.Strict != \"\" && c.Regex != \"\" {\n\t\treturn errors.New(\"strict and regex cannot be used together\")\n\t}\n\n\tif c.Regex != \"\" {\n\t\t_, err := regexp.Compile(c.Regex)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n\ntype combinedFilter struct {\n\tstricts map[any]struct{}\n\tregexes []*regexp.Regexp\n}\n\n// CreateFilter creates a Filter out of a set of Config configuration objects.\nfunc CreateFilter(configs []Config) Filter {\n\tcf := &combinedFilter{\n\t\tstricts: make(map[any]struct{}),\n\t}\n\tfor _, config := range configs {\n\t\tif config.Strict != \"\" {\n\t\t\tcf.stricts[config.Strict] = struct{}{}\n\t\t}\n\n\t\tif config.Regex != \"\" {\n\t\t\t// Validate() call above ensures that the regex is valid.\n\t\t\tre := regexp.MustCompile(config.Regex)\n\t\t\tcf.regexes = append(cf.regexes, re)\n\t\t}\n\t}\n\treturn cf\n}\n\nfunc (cf *combinedFilter) Matches(toMatch any) bool {\n\t_, ok := cf.stricts[toMatch]\n\tif ok {\n\t\treturn ok\n\t}\n\tif str, ok := toMatch.(string); ok {\n\t\tfor _, re := range cf.regexes {\n\t\t\tif re.MatchString(str) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t}\n\t}\n\treturn false\n}\n"
  },
  {
    "path": "filter/config.schema.yaml",
    "content": "$defs:\n  config:\n    description: Config configures the matching behavior of a Filter.\n    type: object\n    properties:\n      regexp:\n        type: string\n      strict:\n        type: string\n"
  },
  {
    "path": "filter/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage filter\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n)\n\nfunc readTestdataConfigYamls(t *testing.T, filename string) map[string][]Config {\n\ttestFile := filepath.Join(\"testdata\", filename)\n\tv, err := confmaptest.LoadConf(testFile)\n\trequire.NoError(t, err)\n\n\tcfgs := map[string][]Config{}\n\trequire.NoErrorf(t, v.Unmarshal(&cfgs, confmap.WithIgnoreUnused()), \"unable to unmarshal yaml from file %v\", testFile)\n\treturn cfgs\n}\n\nfunc TestConfig(t *testing.T) {\n\tactualConfigs := readTestdataConfigYamls(t, \"config.yaml\")\n\texpectedConfigs := map[string][]Config{\n\t\t\"regexp/default\": {\n\t\t\t{\n\t\t\t\tRegex: \"one|two\",\n\t\t\t},\n\t\t},\n\t\t\"strict/default\": {\n\t\t\t{\n\t\t\t\tStrict: \"strict\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor testName, actualCfg := range actualConfigs {\n\t\tt.Run(testName, func(t *testing.T) {\n\t\t\texpCfg, ok := expectedConfigs[testName]\n\t\t\tassert.True(t, ok)\n\t\t\tassert.Equal(t, expCfg, actualCfg)\n\n\t\t\tfor _, cfg := range actualCfg {\n\t\t\t\trequire.NoError(t, cfg.Validate())\n\t\t\t}\n\t\t\tfs := CreateFilter(actualCfg)\n\t\t\tassert.NotNil(t, fs)\n\t\t})\n\t}\n}\n\nfunc TestMatches(t *testing.T) {\n\tcfg := []Config{\n\t\t{\n\t\t\tStrict: \"a\",\n\t\t},\n\t\t{\n\t\t\tStrict: \"b\",\n\t\t},\n\t\t{\n\t\t\tRegex: \"a|b|c\",\n\t\t},\n\t}\n\n\tfor _, c := range cfg {\n\t\trequire.NoError(t, c.Validate())\n\t}\n\tfs := CreateFilter(cfg)\n\n\tassert.True(t, fs.Matches(\"a\"))\n\tassert.True(t, fs.Matches(\"b\"))\n\tassert.True(t, fs.Matches(\"c\"))\n}\n\nfunc TestConfigInvalid(t *testing.T) {\n\tactualConfigs := readTestdataConfigYamls(t, \"config_invalid.yaml\")\n\texpectedConfigs := map[string][]Config{\n\t\t\"invalid/regexp\": {\n\t\t\t{\n\t\t\t\tRegex: \"(.*[\",\n\t\t\t},\n\t\t},\n\t\t\"invalid/config_empty\": {\n\t\t\t{\n\t\t\t\tRegex:  \"\",\n\t\t\t\tStrict: \"\",\n\t\t\t},\n\t\t},\n\t\t\"invalid/config_both_set\": {\n\t\t\t{\n\t\t\t\tRegex:  \"1\",\n\t\t\t\tStrict: \"1\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor testName, actualCfg := range actualConfigs {\n\t\tt.Run(testName, func(t *testing.T) {\n\t\t\texpCfg, ok := expectedConfigs[testName]\n\t\t\tassert.True(t, ok)\n\t\t\tassert.Equal(t, expCfg, actualCfg)\n\n\t\t\tfor _, cfg := range actualCfg {\n\t\t\t\tassert.Error(t, cfg.Validate())\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "filter/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package filter provides an interface for matching strings against a set of string filters.\npackage filter // import \"go.opentelemetry.io/collector/filter\"\n"
  },
  {
    "path": "filter/filter.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage filter // import \"go.opentelemetry.io/collector/filter\"\n\n// Filter is an interface for matching values against a set of filters.\ntype Filter interface {\n\t// Matches returns true if the given value matches at least one\n\t// of the filters encapsulated by the Filter.\n\tMatches(any) bool\n}\n"
  },
  {
    "path": "filter/go.mod",
    "content": "module go.opentelemetry.io/collector/filter\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/confmap => ../confmap\n\nreplace go.opentelemetry.io/collector/featuregate => ../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../internal/testutil\n"
  },
  {
    "path": "filter/go.sum",
    "content": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "filter/metadata.yaml",
    "content": "type: filter\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "filter/testdata/config.yaml",
    "content": "# Yaml form of the configuration for Filters\n# This configuration can be embedded into other component's yamls\n# The top level here are just test names and do not represent part of the actual configuration.\n\nregexp/default:\n  - regexp: \"one|two\"\nstrict/default:\n  - strict: \"strict\"\n"
  },
  {
    "path": "filter/testdata/config_invalid.yaml",
    "content": "# Yaml form of the configuration for Filters\n# This configuration can be embedded into other component's yamls\n# The top level here are just test names and do not represent part of the actual configuration.\n\ninvalid/regexp:\n  - regexp: \"(.*[\"\ninvalid/config_empty:\n  - regexp: \"\"\n    strict: \"\"\ninvalid/config_both_set:\n  - regexp: \"1\"\n    strict: \"1\"\n"
  },
  {
    "path": "go.mod",
    "content": "module go.opentelemetry.io/collector\n\n// NOTE:\n// This go.mod is NOT used to build any official binary.\n// To see the builder manifests used for official binaries,\n// check https://github.com/open-telemetry/opentelemetry-collector-releases\n//\n// For the OpenTelemetry Collector Core distribution specifically, see\n// https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217\n\tgoogle.golang.org/grpc v1.79.3\n\tgoogle.golang.org/protobuf v1.36.11\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/kr/pretty v0.3.1 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/rogpeppe/go-internal v1.13.1 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nretract (\n\tv0.76.0 // Depends on retracted pdata v1.0.0-rc10 module, use v0.76.1\n\tv0.69.0 // Release failed, use v0.69.1\n\tv0.57.1 // Release failed, use v0.57.2\n\tv0.57.0 // Release failed, use v0.57.2\n\tv0.32.0 // Contains incomplete metrics transition to proto 0.9.0, random components are not working.\n)\n"
  },
  {
    "path": "go.sum",
    "content": "github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=\ngithub.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217 h1:gRkg/vSppuSQoDjxyiGfN4Upv/h/DQmIR10ZU8dh4Ww=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251202230838-ff82c1b0f217/go.mod h1:7i2o+ce6H/6BluujYR+kqX3GKH+dChPTQU19wjRPiGk=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "internal/buildscripts/compare-apidiff.sh",
    "content": "#!/usr/bin/env bash\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n\n# This script is used to compare API state snapshots to the current package state in order to validate releases are not breaking backwards compatibility.\n\nusage() {\n  echo \"Usage: $0\"\n  echo\n  echo \"-c  Check-incompatibility mode. Script will fail if an incompatible change is found. Default: 'false'\"\n  echo \"-p  Package to generate API state snapshot of. Default: ''\"\n  echo \"-d  directory where prior states will be read from. Default: './internal/data/apidiff'\"\n  exit 1\n}\n\npackage=\"\"\ninput_dir=\"./internal/data/apidiff\"\ncheck_only=false\nrepo_toplevel=\"$( git rev-parse --show-toplevel )\"\ntools_mod_file=\"${repo_toplevel}/internal/tools/go.mod\"\n\nwhile getopts \"cp:d:\" o; do\n    case \"${o}\" in\n        c)\n            check_only=true\n            ;;\n        p)\n            package=$OPTARG\n            ;;\n        d)\n            input_dir=$OPTARG\n            ;;\n        *)\n            usage\n            ;;\n    esac\ndone\nshift $((OPTIND-1))\n\nif [ -z \"$package\" ]; then\n  usage\nfi\n\nset -e\n\nif [ -e \"$input_dir\"/\"$package\"/apidiff.state ]; then\n  changes=$(go tool -modfile \"${tools_mod_file}\" apidiff \"$input_dir\"/\"$package\"/apidiff.state \"$package\")\n  if [ -n \"$changes\" ] && [ \"$changes\" != \" \" ]; then\n    SUB='Incompatible changes:'\n    if [ $check_only = true ] && [[ \"$changes\" =~ .*\"$SUB\".* ]]; then\n      echo \"Incompatible Changes Found.\"\n      echo \"Check the logs in the GitHub Action log group: 'Compare-States'.\"\n      exit 1\n    else\n      echo \"Changes found in $package:\"\n      echo \"$changes\"\n    fi\n  fi\nfi\n"
  },
  {
    "path": "internal/buildscripts/gen-apidiff.sh",
    "content": "#!/usr/bin/env bash\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n\n# This script is used to create API state snapshots used to validate releases are not breaking backwards compatibility.\n\nusage() {\n  echo \"Usage: $0\"\n  echo\n  echo \"-d  Dry-run mode. No project files will not be modified. Default: 'false'\"\n  echo \"-p  Package to generate API state snapshot of. Default: ''\"\n  echo \"-o  Output directory where state will be written to. Default: './internal/data/apidiff'\"\n  exit 1\n}\n\ndry_run=false\npackage=\"\"\noutput_dir=\"./internal/data/apidiff\"\nrepo_toplevel=\"$( git rev-parse --show-toplevel )\"\ntools_mod_file=\"${repo_toplevel}/internal/tools/go.mod\"\n\nwhile getopts \"dp:o:\" o; do\n    case \"${o}\" in\n        d)\n            dry_run=true\n            ;;\n        p)\n            package=$OPTARG\n            ;;\n        o)\n            output_dir=$OPTARG\n            ;;\n        *)\n            usage\n            ;;\n    esac\ndone\nshift $((OPTIND-1))\n\nif [ -z \"$package\" ]; then\n  usage\nfi\n\nset -ex\n\n# Create temp dir for generated files.\n# Source: https://unix.stackexchange.com/a/84980\ntmp_dir=$(mktemp -d 2>/dev/null || mktemp -d -t 'apidiff')\nclean_up() {\n    ARG=$?\n    if [ $dry_run = true ]; then\n      echo \"Dry-run complete. Generated files can be found in $tmp_dir\"\n    else\n      rm -rf \"$tmp_dir\"\n    fi\n    exit $ARG\n}\ntrap clean_up EXIT\n\nmkdir -p \"$tmp_dir/$package\"\n\ngo tool -modfile \"${tools_mod_file}\" apidiff -w \"$tmp_dir\"/\"$package\"/apidiff.state \"$package\"\n\n# Copy files if not in dry-run mode.\nif [ $dry_run = false ]; then\n  mkdir -p \"$output_dir/$package\" && \\\n  cp \"$tmp_dir/$package/apidiff.state\" \\\n     \"$output_dir/$package\"\nfi\n"
  },
  {
    "path": "internal/buildscripts/gen-certs.sh",
    "content": "#!/usr/bin/env bash\n#\n# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n\n# This script is used to create the CA, server and client's certificates and keys required by unit tests.\n# These certificates use the Subject Alternative Name extension rather than the Common Name, which will be unsupported from Go 1.15.\n\nusage() {\n  echo \"Usage: $0 [-d]\"\n  echo\n  echo \"-d  Dry-run mode. No project files will not be modified. Default: 'false'\"\n  echo \"-m  Domain name to use in the certificate. Default: 'localhost'\"\n  echo \"-o  Output directory where certificates will be written to. Default: '.'; the current directory\"\n  echo \"-s  A suffix for the generated certificate. Default: \\\"\\\"; an empty string\"\n  exit 1\n}\n\ndry_run=false\ndomain=\"localhost\"\noutput_dir=\".\"\nsuffix=\"\"\n\nwhile getopts \"dm:o:s:\" o; do\n    case \"${o}\" in\n        d)\n            dry_run=true\n            ;;\n        m)\n            domain=$OPTARG\n            ;;\n        o)\n            output_dir=$OPTARG\n            ;;\n        s)\n            suffix=$OPTARG\n            ;;\n        *)\n            usage\n            ;;\n    esac\ndone\nshift $((OPTIND-1))\n\nset -ex\n\n# Create temp dir for generated files.\ntmp_dir=$(mktemp -d -t certificatesXXX)\nclean_up() {\n    ARG=$?\n    if [ $dry_run = true ]; then\n      echo \"Dry-run complete. Generated files can be found in $tmp_dir\"\n    else\n      rm -rf \"$tmp_dir\"\n    fi\n    exit $ARG\n}\ntrap clean_up EXIT\n\ngen_ssl_conf() {\n  domain_name=$1\n  output_file=$2\n\n  cat << EOF > \"$output_file\"\n[ req ]\nprompt              = no\ndefault_bits        = 2048\ndistinguished_name  = req_distinguished_name\nreq_extensions      = req_ext\n\n[ req_distinguished_name ]\ncountryName         = AU\nstateOrProvinceName = Australia\nlocalityName        = Sydney\norganizationName    = MyOrgName\ncommonName          = MyCommonName\n\n[ req_ext ]\nsubjectAltName      = @alt_names\n\n[alt_names]\nDNS.1               = $domain_name\nEOF\n}\n\n# Generate config files.\ngen_ssl_conf \"$domain\" \"$tmp_dir/ssl.conf\"\n\n# Create CA (accept defaults from prompts).\nopenssl genrsa -out \"$tmp_dir/ca${suffix}.key\"  2048\nopenssl req -new -key \"$tmp_dir/ca${suffix}.key\" -x509 -days 3650 -out \"$tmp_dir/ca${suffix}.crt\" -config \"$tmp_dir/ssl.conf\"\n\n# Create client and server keys.\nopenssl genrsa -out \"$tmp_dir/server${suffix}.key\" 2048\nopenssl genrsa -out \"$tmp_dir/client${suffix}.key\" 2048\n\n# Create certificate sign request using the above created keys.\nopenssl req -new -nodes -key \"$tmp_dir/server${suffix}.key\" -out \"$tmp_dir/server${suffix}.csr\" -config \"$tmp_dir/ssl.conf\"\nopenssl req -new -nodes -key \"$tmp_dir/client${suffix}.key\" -out \"$tmp_dir/client${suffix}.csr\" -config \"$tmp_dir/ssl.conf\"\n\n# Creating the client and server certificates.\nopenssl x509 -req \\\n             -sha256 \\\n             -days 3650 \\\n             -in \"$tmp_dir/server${suffix}.csr\" \\\n             -out \"$tmp_dir/server${suffix}.crt\" \\\n             -extensions req_ext \\\n             -CA \"$tmp_dir/ca${suffix}.crt\" \\\n             -CAkey \"$tmp_dir/ca${suffix}.key\" \\\n             -CAcreateserial \\\n             -extfile \"$tmp_dir/ssl.conf\"\nopenssl x509 -req \\\n             -sha256 \\\n             -days 3650 \\\n             -in \"$tmp_dir/client${suffix}.csr\" \\\n             -out \"$tmp_dir/client${suffix}.crt\" \\\n             -extensions req_ext \\\n             -CA \"$tmp_dir/ca${suffix}.crt\" \\\n             -CAkey \"$tmp_dir/ca${suffix}.key\" \\\n             -CAcreateserial \\\n             -extfile \"$tmp_dir/ssl.conf\"\n\n# Copy files if not in dry-run mode.\nif [ $dry_run = false ]; then\n  cp \"$tmp_dir/ca${suffix}.crt\" \\\n     \"$tmp_dir/client${suffix}.crt\" \\\n     \"$tmp_dir/client${suffix}.key\" \\\n     \"$tmp_dir/server${suffix}.crt\" \\\n     \"$tmp_dir/server${suffix}.key\" \\\n     \"$output_dir\"\nfi\n"
  },
  {
    "path": "internal/cmd/pdatagen/Makefile",
    "content": "include ../../../Makefile.Common\n"
  },
  {
    "path": "internal/cmd/pdatagen/go.mod",
    "content": "module go.opentelemetry.io/collector/internal/cmd/pdatagen\n\ngo 1.25.0\n\nrequire github.com/ettle/strcase v0.2.0\n"
  },
  {
    "path": "internal/cmd/pdatagen/go.sum",
    "content": "github.com/ettle/strcase v0.2.0 h1:fGNiVF21fHXpX1niBgk0aROov1LagYsOwV/xqKDKR/Q=\ngithub.com/ettle/strcase v0.2.0/go.mod h1:DajmHElDSaX76ITe3/VHVyMin4LWSJN5Z909Wp+ED1A=\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/base_slices.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\n\nimport (\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\ntype baseSlice interface {\n\tgetName() string\n\tgetHasWrapper() bool\n\tgetOriginFullName() string\n\tgetElementOriginName() string\n\tgetElementNullable() bool\n\tgetPackageName() string\n}\n\n// messageSlice generates code for a slice of pointer fields. The generated structs cannot be used from other packages.\ntype messageSlice struct {\n\tstructName      string\n\tpackageName     string\n\telementNullable bool\n\telement         *messageStruct\n}\n\nfunc (ss *messageSlice) getProtoMessage() *proto.Message {\n\treturn nil\n}\n\nfunc (ss *messageSlice) getName() string {\n\treturn ss.structName\n}\n\nfunc (ss *messageSlice) getPackageName() string {\n\treturn ss.packageName\n}\n\nfunc (ss *messageSlice) generate(packageInfo *PackageInfo) []byte {\n\treturn []byte(tmplutil.Execute(sliceTemplate, ss.templateFields(packageInfo)))\n}\n\nfunc (ss *messageSlice) generateTests(packageInfo *PackageInfo) []byte {\n\treturn []byte(tmplutil.Execute(sliceTestTemplate, ss.templateFields(packageInfo)))\n}\n\nfunc (ss *messageSlice) generateInternal(packageInfo *PackageInfo) []byte {\n\treturn []byte(tmplutil.Execute(sliceInternalTemplate, ss.templateFields(packageInfo)))\n}\n\nfunc (ss *messageSlice) templateFields(packageInfo *PackageInfo) map[string]any {\n\thasWrapper := usedByOtherDataTypes(ss.packageName)\n\treturn map[string]any{\n\t\t\"hasWrapper\":        usedByOtherDataTypes(ss.packageName),\n\t\t\"structName\":        ss.structName,\n\t\t\"elementName\":       ss.element.getName(),\n\t\t\"elementOriginName\": ss.getElementOriginName(),\n\t\t\"elementNullable\":   ss.elementNullable,\n\t\t\"origAccessor\":      origAccessor(hasWrapper),\n\t\t\"stateAccessor\":     stateAccessor(hasWrapper),\n\t\t\"packageName\":       packageInfo.name,\n\t\t\"imports\":           packageInfo.imports,\n\t\t\"testImports\":       packageInfo.testImports,\n\t}\n}\n\nfunc (ss *messageSlice) getOriginName() string {\n\treturn ss.element.getOriginName() + \"Slice\"\n}\n\nfunc (ss *messageSlice) getOriginFullName() string {\n\treturn ss.element.getOriginFullName()\n}\n\nfunc (ss *messageSlice) getHasWrapper() bool {\n\treturn usedByOtherDataTypes(ss.packageName)\n}\n\nfunc (ss *messageSlice) getHasOnlyInternal() bool {\n\treturn false\n}\n\nfunc (ss *messageSlice) getElementOriginName() string {\n\treturn ss.element.getOriginName()\n}\n\nfunc (ss *messageSlice) getElementNullable() bool {\n\treturn ss.elementNullable\n}\n\nvar _ baseStruct = (*messageSlice)(nil)\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/base_struct.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\n\nimport (\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\ntype baseStruct interface {\n\tgetName() string\n\tgetOriginName() string\n\tgetOriginFullName() string\n\tgetHasWrapper() bool\n\tgetHasOnlyInternal() bool\n\tgenerate(packageInfo *PackageInfo) []byte\n\tgenerateTests(packageInfo *PackageInfo) []byte\n\tgenerateInternal(packageInfo *PackageInfo) []byte\n\n\tgetProtoMessage() *proto.Message\n}\n\n// messageStruct generates a struct for a proto message. The struct can be generated both as a common struct\n// that can be used as a field in struct from other packages and as an isolated struct with depending on a package name.\ntype messageStruct struct {\n\tstructName      string\n\tpackageName     string\n\tdescription     string\n\tprotoName       string\n\tupstreamProto   string\n\tfields          []Field\n\thasWrapper      bool\n\thasOnlyInternal bool\n}\n\nfunc (ms *messageStruct) getName() string {\n\treturn ms.structName\n}\n\nfunc (ms *messageStruct) generate(packageInfo *PackageInfo) []byte {\n\treturn []byte(tmplutil.Execute(messageTemplate, ms.templateFields(packageInfo)))\n}\n\nfunc (ms *messageStruct) generateTests(packageInfo *PackageInfo) []byte {\n\treturn []byte(tmplutil.Execute(messageTestTemplate, ms.templateFields(packageInfo)))\n}\n\nfunc (ms *messageStruct) generateInternal(packageInfo *PackageInfo) []byte {\n\treturn []byte(tmplutil.Execute(messageInternalTemplate, ms.templateFields(packageInfo)))\n}\n\nfunc (ms *messageStruct) getProtoMessage() *proto.Message {\n\tfields := make([]proto.FieldInterface, len(ms.fields))\n\tfor i := range ms.fields {\n\t\tfields[i] = ms.fields[i].toProtoField(ms)\n\t}\n\treturn &proto.Message{\n\t\tName:            ms.protoName,\n\t\tDescription:     ms.description,\n\t\tUpstreamMessage: ms.upstreamProto,\n\t\tFields:          fields,\n\t}\n}\n\nfunc (ms *messageStruct) templateFields(packageInfo *PackageInfo) map[string]any {\n\thasWrapper := ms.hasWrapper\n\tif !hasWrapper {\n\t\thasWrapper = usedByOtherDataTypes(ms.packageName)\n\t}\n\treturn map[string]any{\n\t\t\"messageStruct\": ms,\n\t\t\"fields\":        ms.fields,\n\t\t\"structName\":    ms.getName(),\n\t\t\"protoName\":     ms.getOriginFullName(),\n\t\t\"originName\":    ms.getOriginName(),\n\t\t\"description\":   ms.description,\n\t\t\"hasWrapper\":    hasWrapper,\n\t\t\"origAccessor\":  origAccessor(hasWrapper),\n\t\t\"stateAccessor\": stateAccessor(hasWrapper),\n\t\t\"packageName\":   packageInfo.name,\n\t\t\"imports\":       packageInfo.imports,\n\t\t\"testImports\":   packageInfo.testImports,\n\t}\n}\n\nfunc (ms *messageStruct) getHasWrapper() bool {\n\tif ms.hasWrapper {\n\t\treturn true\n\t}\n\tif ms.hasOnlyInternal {\n\t\treturn false\n\t}\n\treturn usedByOtherDataTypes(ms.packageName)\n}\n\nfunc (ms *messageStruct) getHasOnlyInternal() bool {\n\treturn ms.hasOnlyInternal\n}\n\nfunc (ms *messageStruct) getOriginName() string {\n\treturn ms.protoName\n}\n\nfunc (ms *messageStruct) getOriginFullName() string {\n\treturn ms.protoName\n}\n\nvar _ baseStruct = (*messageStruct)(nil)\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/field.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\nimport (\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n)\n\ntype Field interface {\n\tGenerateAccessors(ms *messageStruct) string\n\n\tGenerateAccessorsTest(ms *messageStruct) string\n\n\tGenerateTestValue(ms *messageStruct) string\n\n\ttoProtoField(ms *messageStruct) proto.FieldInterface\n}\n\nfunc origAccessor(hasWrapper bool) string {\n\tif hasWrapper {\n\t\treturn \"getOrig()\"\n\t}\n\treturn \"orig\"\n}\n\nfunc stateAccessor(hasWrapper bool) string {\n\tif hasWrapper {\n\t\treturn \"getState()\"\n\t}\n\treturn \"state\"\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/message_field.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\n\nimport (\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst messageAccessorsTemplate = `// {{ .fieldName }} returns the {{ .lowerFieldName }} associated with this {{ .structName }}.\nfunc (ms {{ .structName }}) {{ .fieldName }}() {{ .packageName }}{{ .returnType }} {\n\t{{- if .messageHasWrapper }}\n\treturn {{ .packageName }}{{ .returnType }}(internal.New{{ .returnType }}Wrapper(&ms.{{ .origAccessor }}.{{ .fieldOriginFullName }}, ms.{{ .stateAccessor }}))\n\t{{- else }}\n\treturn new{{ .returnType }}(&ms.{{ .origAccessor }}.{{ .fieldOriginFullName }}, ms.{{ .stateAccessor }})\n\t{{- end }}\n}`\n\nconst messageAccessorsTestTemplate = `func Test{{ .structName }}_{{ .fieldName }}(t *testing.T) {\n\tms := New{{ .structName }}()\n\tassert.Equal(t, {{ .packageName }}New{{ .returnType }}{{- if eq .returnType \"Value\" }}Empty{{- end }}(), ms.{{ .fieldName }}())\n\tms.{{ .origAccessor }}.{{ .fieldOriginFullName }} = *internal.GenTest{{ .fieldOriginName }}()\n\t{{- if .messageHasWrapper }}\n\tassert.Equal(t, {{ .packageName }}{{ .returnType }}(internal.GenTest{{ .returnType }}Wrapper()), ms.{{ .fieldName }}())\n\t{{- else }}\n\tassert.Equal(t, generateTest{{ .returnType }}(), ms.{{ .fieldName }}())\n\t{{- end }}\n}`\n\nconst messageSetTestTemplate = `orig.{{ .fieldOriginFullName }} = *GenTest{{ .fieldOriginName }}()`\n\ntype MessageField struct {\n\tfieldName     string\n\tprotoID       uint32\n\tnullable      bool\n\treturnMessage *messageStruct\n}\n\nfunc (mf *MessageField) GenerateAccessors(ms *messageStruct) string {\n\tt := tmplutil.Parse(\"messageAccessorsTemplate\", []byte(messageAccessorsTemplate))\n\treturn tmplutil.Execute(t, mf.templateFields(ms))\n}\n\nfunc (mf *MessageField) GenerateAccessorsTest(ms *messageStruct) string {\n\tt := tmplutil.Parse(\"messageAccessorsTestTemplate\", []byte(messageAccessorsTestTemplate))\n\treturn tmplutil.Execute(t, mf.templateFields(ms))\n}\n\nfunc (mf *MessageField) GenerateTestValue(ms *messageStruct) string {\n\tt := tmplutil.Parse(\"messageSetTestTemplate\", []byte(messageSetTestTemplate))\n\treturn tmplutil.Execute(t, mf.templateFields(ms))\n}\n\nfunc (mf *MessageField) toProtoField(ms *messageStruct) proto.FieldInterface {\n\tpt := proto.TypeMessage\n\tif mf.returnMessage.getName() == \"TraceState\" {\n\t\tpt = proto.TypeString\n\t}\n\treturn &proto.Field{\n\t\tType:              pt,\n\t\tID:                mf.protoID,\n\t\tName:              mf.fieldName,\n\t\tMessageName:       mf.returnMessage.getOriginName(),\n\t\tParentMessageName: ms.protoName,\n\t\tNullable:          mf.nullable,\n\t}\n}\n\nfunc (mf *MessageField) templateFields(ms *messageStruct) map[string]any {\n\treturn map[string]any{\n\t\t\"messageHasWrapper\":   usedByOtherDataTypes(mf.returnMessage.packageName),\n\t\t\"structName\":          ms.getName(),\n\t\t\"fieldName\":           mf.fieldName,\n\t\t\"fieldOriginFullName\": mf.fieldName,\n\t\t\"fieldOriginName\":     mf.returnMessage.getOriginName(),\n\t\t\"lowerFieldName\":      strings.ToLower(mf.fieldName),\n\t\t\"returnType\":          mf.returnMessage.getName(),\n\t\t\"packageName\": func() string {\n\t\t\tif mf.returnMessage.packageName != ms.packageName {\n\t\t\t\treturn mf.returnMessage.packageName + \".\"\n\t\t\t}\n\t\t\treturn \"\"\n\t\t}(),\n\t\t\"origAccessor\":  origAccessor(ms.getHasWrapper()),\n\t\t\"stateAccessor\": stateAccessor(ms.getHasWrapper()),\n\t}\n}\n\nvar _ Field = (*MessageField)(nil)\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/one_of_field.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\n\nimport (\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst oneOfAccessorTemplate = `// {{ .typeFuncName }} returns the type of the {{ .lowerOriginFieldName }} for this {{ .structName }}.\n// Calling this function on zero-initialized {{ .structName }} will cause a panic.\nfunc (ms {{ .structName }}) {{ .typeFuncName }}() {{ .typeName }} {\n\tswitch ms.{{ .origAccessor }}.{{ .originFieldName }}.(type) {\n\t\t{{- range .values }}\n\t\t{{ .GenerateType $.baseStruct $.OneOfField }}\n\t\t{{- end }}\n\t}\n\treturn {{ .typeName }}Empty\n}\n\n{{ range .values -}}\n{{ .GenerateAccessors $.baseStruct $.OneOfField }}\n{{- end }}`\n\nconst oneOfAccessorTestTemplate = `func Test{{ .structName }}_{{ .typeFuncName }}(t *testing.T) {\n\ttv := New{{ .structName }}()\n\tassert.Equal(t, {{ .typeName }}Empty, tv.{{ .typeFuncName }}())\n}\n\n{{ range .values -}}\n{{ .GenerateTests $.baseStruct $.OneOfField }}\n{{- end }}\n`\n\nconst oneOfTestFailingUnmarshalProtoValuesTemplate = `\n\t{{ range .fields -}}\n\t{{ .GenTestFailingUnmarshalProtoValues }}\n\t{{- end }}`\n\nconst oneOfTestValuesTemplate = `\n\t{{ range .fields -}}\n\t{{ .GenTestEncodingValues }}\n\t{{- end }}`\n\nconst oneOfPoolOrigTemplate = `\n\t{{ range .fields -}}\n\t{{ .GenPool }}\n\t{{- end }}`\n\nconst oneOfMessageOrigTemplate = `\nfunc (m *{{ .protoName }}) Get{{ .originFieldName }}() any {\n\tif m != nil {\n\t\treturn m.{{ .originFieldName }}\n\t}\n\treturn nil\n}\n\n{{ range .fields -}}\n{{ .GenOneOfMessages }}\n{{- end }}`\n\nconst oneOfDeleteOrigTemplate = `switch ov := orig.{{ .originFieldName }}.(type) {\n\t{{ range .fields -}}\n\tcase *{{ $.protoName }}_{{ .GetName }}:\n\t\t{{ .GenDelete }}\n\t{{ end -}}\n}`\n\nconst oneOfCopyOrigTemplate = `switch t := src.{{ .originFieldName }}.(type) {\n\t{{ range .fields -}}\n\tcase *{{ $.protoName }}_{{ .GetName }}:\n\t\t{{ .GenCopy }}\n\t{{ end -}}\n\tdefault:\n\t\tdest.{{ .originFieldName }} = nil\n}`\n\nconst oneOfMarshalJSONTemplate = `switch orig := orig.{{ .originFieldName }}.(type) {\n\t{{ range .fields -}}\n\tcase *{{ $.protoName }}_{{ .GetName }}:\n\t\t{{ .GenMarshalJSON }}\n\t{{ end -}}\n}`\n\nconst oneOfUnmarshalJSONTemplate = `\n\t{{ range .fields -}}\n\t\t{{ .GenUnmarshalJSON }}\n\t{{- end }}`\n\nconst oneOfSizeProtoTemplate = `switch orig := orig.{{ .originFieldName }}.(type) {\n\tcase nil:\n\t\t_ = orig\n\t\tbreak\n\t{{ range .fields -}}\n\tcase *{{ $.protoName }}_{{ .GetName }}:\n\t\t{{ .GenSizeProto }}\n\t{{ end -}}\n}`\n\nconst oneOfMarshalProtoTemplate = `switch orig := orig.{{ .originFieldName }}.(type) {\n\t{{ range .fields -}}\n\tcase *{{ $.protoName }}_{{ .GetName }}:\n\t\t{{ .GenMarshalProto }}\n\t{{ end -}}\n}`\n\nconst oneOfUnmarshalProtoTemplate = `\n\t{{- range .fields }}\n\t\t{{ .GenUnmarshalProto }}\n\t{{ end }}`\n\ntype OneOfField struct {\n\toriginFieldName            string\n\ttypeName                   string\n\ttestValueIdx               int\n\tvalues                     []oneOfValue\n\tomitOriginFieldNameInNames bool\n}\n\nfunc (of *OneOfField) GenerateAccessors(ms *messageStruct) string {\n\treturn tmplutil.Execute(tmplutil.Parse(\"oneOfAccessorTemplate\", []byte(oneOfAccessorTemplate)), of.templateFields(ms))\n}\n\nfunc (of *OneOfField) typeFuncName() string {\n\tconst typeSuffix = \"Type\"\n\tif of.omitOriginFieldNameInNames {\n\t\treturn typeSuffix\n\t}\n\treturn of.originFieldName + typeSuffix\n}\n\nfunc (of *OneOfField) GenerateAccessorsTest(ms *messageStruct) string {\n\treturn tmplutil.Execute(tmplutil.Parse(\"oneOfAccessorTestTemplate\", []byte(oneOfAccessorTestTemplate)), of.templateFields(ms))\n}\n\nfunc (of *OneOfField) GenerateTestValue(ms *messageStruct) string {\n\treturn of.values[of.testValueIdx].GenerateTestValue(ms, of)\n}\n\nfunc (of *OneOfField) toProtoField(ms *messageStruct) proto.FieldInterface {\n\tfields := make([]proto.FieldInterface, len(of.values))\n\tfor i := range of.values {\n\t\tfields[i] = of.values[i].toProtoField(ms, of)\n\t}\n\treturn &oneOfProtoField{\n\t\toriginFieldName: of.originFieldName,\n\t\tprotoName:       ms.protoName,\n\t\tfields:          fields,\n\t}\n}\n\ntype oneOfProtoField struct {\n\toriginFieldName string\n\tprotoName       string\n\tfields          []proto.FieldInterface\n}\n\nfunc (of *oneOfProtoField) GenMessageField() string {\n\treturn of.originFieldName + \" any\"\n}\n\nfunc (of *oneOfProtoField) GenOneOfMessages() string {\n\treturn tmplutil.Execute(tmplutil.Parse(\"oneOfMessageOrigTemplate\", []byte(oneOfMessageOrigTemplate)), of.templateFields())\n}\n\nfunc (of *oneOfProtoField) GetName() string {\n\treturn of.originFieldName\n}\n\nfunc (of *oneOfProtoField) GoType() string {\n\tpanic(\"implement me\")\n}\n\nfunc (of *oneOfProtoField) DefaultValue() string {\n\tpanic(\"implement me\")\n}\n\nfunc (of *oneOfProtoField) GenTest() string {\n\treturn \"orig.\" + of.GetName() + \" = \" + of.TestValue()\n}\n\nfunc (of *oneOfProtoField) TestValue() string {\n\treturn \"&\" + of.protoName + \"_\" + of.fields[0].GetName() + \"{\" + of.fields[0].GetName() + \": \" + of.fields[0].TestValue() + \"}\"\n}\n\nfunc (of *oneOfProtoField) GenTestFailingUnmarshalProtoValues() string {\n\treturn tmplutil.Execute(tmplutil.Parse(\"oneOfTestFailingUnmarshalProtoValuesTemplate\", []byte(oneOfTestFailingUnmarshalProtoValuesTemplate)), of.templateFields())\n}\n\nfunc (of *oneOfProtoField) GenTestEncodingValues() string {\n\treturn tmplutil.Execute(tmplutil.Parse(\"oneOfTestValuesTemplate\", []byte(oneOfTestValuesTemplate)), of.templateFields())\n}\n\nfunc (of *oneOfProtoField) GenPool() string {\n\treturn tmplutil.Execute(tmplutil.Parse(\"oneOfPoolOrigTemplate\", []byte(oneOfPoolOrigTemplate)), of.templateFields())\n}\n\nfunc (of *oneOfProtoField) GenDelete() string {\n\treturn tmplutil.Execute(tmplutil.Parse(\"oneOfDeleteOrigTemplate\", []byte(oneOfDeleteOrigTemplate)), of.templateFields())\n}\n\nfunc (of *oneOfProtoField) GenCopy() string {\n\treturn tmplutil.Execute(tmplutil.Parse(\"oneOfCopyOrigTemplate\", []byte(oneOfCopyOrigTemplate)), of.templateFields())\n}\n\nfunc (of *oneOfProtoField) GenMarshalJSON() string {\n\treturn tmplutil.Execute(tmplutil.Parse(\"oneOfMarshalJSONTemplate\", []byte(oneOfMarshalJSONTemplate)), of.templateFields())\n}\n\nfunc (of *oneOfProtoField) GenUnmarshalJSON() string {\n\treturn tmplutil.Execute(tmplutil.Parse(\"oneOfUnmarshalJSONTemplate\", []byte(oneOfUnmarshalJSONTemplate)), of.templateFields())\n}\n\nfunc (of *oneOfProtoField) GenSizeProto() string {\n\tt := tmplutil.Parse(\"oneOfSizeProtoTemplate\", []byte(oneOfSizeProtoTemplate))\n\treturn tmplutil.Execute(t, of.templateFields())\n}\n\nfunc (of *oneOfProtoField) GenMarshalProto() string {\n\tt := tmplutil.Parse(\"oneOfMarshalProtoTemplate\", []byte(oneOfMarshalProtoTemplate))\n\treturn tmplutil.Execute(t, of.templateFields())\n}\n\nfunc (of *oneOfProtoField) GenUnmarshalProto() string {\n\tt := tmplutil.Parse(\"oneOfUnmarshalProtoTemplate\", []byte(oneOfUnmarshalProtoTemplate))\n\treturn tmplutil.Execute(t, of.templateFields())\n}\n\nfunc (of *oneOfProtoField) templateFields() map[string]any {\n\treturn map[string]any{\n\t\t\"originFieldName\": of.originFieldName,\n\t\t\"fields\":          of.fields,\n\t\t\"protoName\":       of.protoName,\n\t}\n}\n\nfunc (of *OneOfField) templateFields(ms *messageStruct) map[string]any {\n\treturn map[string]any{\n\t\t\"baseStruct\":           ms,\n\t\t\"OneOfField\":           of,\n\t\t\"packageName\":          \"\",\n\t\t\"structName\":           ms.getName(),\n\t\t\"typeFuncName\":         of.typeFuncName(),\n\t\t\"typeName\":             of.typeName,\n\t\t\"originName\":           ms.getOriginName(),\n\t\t\"originFieldName\":      of.originFieldName,\n\t\t\"lowerOriginFieldName\": strings.ToLower(of.originFieldName),\n\t\t\"origAccessor\":         origAccessor(ms.getHasWrapper()),\n\t\t\"stateAccessor\":        stateAccessor(ms.getHasWrapper()),\n\t\t\"values\":               of.values,\n\t}\n}\n\nvar _ Field = (*OneOfField)(nil)\n\ntype oneOfValue interface {\n\tGetOriginFieldName() string\n\tGenerateAccessors(ms *messageStruct, of *OneOfField) string\n\tGenerateType(ms *messageStruct, of *OneOfField) string\n\tGenerateTests(ms *messageStruct, of *OneOfField) string\n\tGenerateTestValue(ms *messageStruct, of *OneOfField) string\n\ttoProtoField(ms *messageStruct, of *OneOfField) proto.FieldInterface\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/one_of_message_value.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\n\nimport (\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst oneOfMessageAccessorsTemplate = `// {{ .fieldName }} returns the {{ .lowerFieldName }} associated with this {{ .structName }}.\n//\n// Calling this function when {{ .originOneOfTypeFuncName }}() != {{ .typeName }} returns an invalid\n// zero-initialized instance of {{ .returnType }}. Note that using such {{ .returnType }} instance can cause panic.\n//\n// Calling this function on zero-initialized {{ .structName }} will cause a panic.\nfunc (ms {{ .structName }}) {{ .fieldName }}() {{ .returnType }} {\n\tv, ok := ms.orig.Get{{ .originOneOfFieldName }}().(*internal.{{ .originStructType }})\n\tif !ok {\n\t\treturn {{ .returnType }}{}\n\t}\n\treturn new{{ .returnType }}(v.{{ .fieldName }}, ms.state)\n}\n\n// SetEmpty{{ .fieldName }} sets an empty {{ .lowerFieldName }} to this {{ .structName }}.\n//\n// After this, {{ .originOneOfTypeFuncName }}() function will return {{ .typeName }}\".\n//\n// Calling this function on zero-initialized {{ .structName }} will cause a panic.\nfunc (ms {{ .structName }}) SetEmpty{{ .fieldName }}() {{ .returnType }} {\n\tms.state.AssertMutable()\n\tvar ov *internal.{{ .originStructType }}\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\tov = &internal.{{ .originStructType }}{}\n\t} else {\n\t\tov = internal.ProtoPool{{ .oneOfName }}.Get().(*internal.{{ .originStructType }})\n\t}\n\tov.{{ .fieldName }} = internal.New{{ .fieldOriginName }}()\n\tms.orig.{{ .originOneOfFieldName }} = ov\n\treturn new{{ .returnType }}(ov.{{ .fieldName }}, ms.state)\n}`\n\nconst oneOfMessageAccessorsTestTemplate = `func Test{{ .structName }}_{{ .fieldName }}(t *testing.T) {\n\tms := New{{ .structName }}()\n\tms.SetEmpty{{ .fieldName }}()\n\tassert.Equal(t, New{{ .returnType }}(), ms.{{ .fieldName }}())\n\tms.orig.Get{{ .originOneOfFieldName }}().(*internal.{{ .originStructType }}).{{ .fieldName }} = internal.GenTest{{ .returnType }}()\n\tassert.Equal(t, {{ .typeName }}, ms.{{ .originOneOfTypeFuncName }}())\n\tassert.Equal(t, generateTest{{ .returnType }}(), ms.{{ .fieldName }}())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { new{{ .structName }}(internal.New{{ .originStructName }}(), sharedState).SetEmpty{{ .fieldName }}() })\n}\n`\n\nconst oneOfMessageSetTestTemplate = `orig.{{ .originOneOfFieldName }} = &internal.{{ .originStructType }}{ \n{{- .fieldName }}: GenTest{{ .fieldOriginName }}() }`\n\nconst oneOfMessageTypeTemplate = `case *internal.{{ .originStructType }}:\n\treturn {{ .typeName }}`\n\ntype OneOfMessageValue struct {\n\tfieldName     string\n\tprotoID       uint32\n\treturnMessage *messageStruct\n}\n\nfunc (omv *OneOfMessageValue) GetOriginFieldName() string {\n\treturn omv.fieldName\n}\n\nfunc (omv *OneOfMessageValue) GenerateAccessors(ms *messageStruct, of *OneOfField) string {\n\tt := tmplutil.Parse(\"oneOfMessageAccessorsTemplate\", []byte(oneOfMessageAccessorsTemplate))\n\treturn tmplutil.Execute(t, omv.templateFields(ms, of))\n}\n\nfunc (omv *OneOfMessageValue) GenerateTests(ms *messageStruct, of *OneOfField) string {\n\tt := tmplutil.Parse(\"oneOfMessageAccessorsTestTemplate\", []byte(oneOfMessageAccessorsTestTemplate))\n\treturn tmplutil.Execute(t, omv.templateFields(ms, of))\n}\n\nfunc (omv *OneOfMessageValue) GenerateTestValue(ms *messageStruct, of *OneOfField) string {\n\tt := tmplutil.Parse(\"oneOfMessageSetTestTemplate\", []byte(oneOfMessageSetTestTemplate))\n\treturn tmplutil.Execute(t, omv.templateFields(ms, of))\n}\n\nfunc (omv *OneOfMessageValue) GenerateType(ms *messageStruct, of *OneOfField) string {\n\tt := tmplutil.Parse(\"oneOfMessageTypeTemplate\", []byte(oneOfMessageTypeTemplate))\n\treturn tmplutil.Execute(t, omv.templateFields(ms, of))\n}\n\nfunc (omv *OneOfMessageValue) toProtoField(ms *messageStruct, of *OneOfField) proto.FieldInterface {\n\treturn &proto.Field{\n\t\tType:              proto.TypeMessage,\n\t\tID:                omv.protoID,\n\t\tOneOfGroup:        of.originFieldName,\n\t\tOneOfMessageName:  ms.protoName + \"_\" + omv.fieldName,\n\t\tName:              omv.fieldName,\n\t\tMessageName:       omv.returnMessage.getOriginFullName(),\n\t\tParentMessageName: ms.protoName,\n\t\tNullable:          true,\n\t}\n}\n\nfunc (omv *OneOfMessageValue) templateFields(ms *messageStruct, of *OneOfField) map[string]any {\n\treturn map[string]any{\n\t\t\"fieldName\":               omv.fieldName,\n\t\t\"originOneOfFieldName\":    of.originFieldName,\n\t\t\"fieldOriginName\":         omv.returnMessage.getOriginName(),\n\t\t\"typeName\":                of.typeName + omv.fieldName,\n\t\t\"structName\":              ms.getName(),\n\t\t\"returnType\":              omv.returnMessage.getName(),\n\t\t\"originOneOfTypeFuncName\": of.typeFuncName(),\n\t\t\"lowerFieldName\":          strings.ToLower(omv.fieldName),\n\t\t\"originStructName\":        ms.protoName,\n\t\t\"originStructType\":        ms.protoName + \"_\" + omv.fieldName,\n\t\t\"oneOfName\":               proto.ExtractNameFromFull(ms.protoName + \"_\" + omv.fieldName),\n\t}\n}\n\nvar _ oneOfValue = (*OneOfMessageValue)(nil)\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/one_of_primitive_value.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\n\nimport (\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst oneOfPrimitiveAccessorsTemplate = `// {{ .accessorFieldName }} returns the {{ .lowerFieldName }} associated with this {{ .structName }}.\nfunc (ms {{ .structName }}) {{ .accessorFieldName }}() {{ .returnType }} {\n\treturn ms.orig.Get{{ .originFieldName }}()\n}\n\n// Set{{ .accessorFieldName }} replaces the {{ .lowerFieldName }} associated with this {{ .structName }}.\nfunc (ms {{ .structName }}) Set{{ .accessorFieldName }}(v {{ .returnType }}) {\n\tms.state.AssertMutable()\n\tvar ov *internal.{{ .originStructType }}\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\tov = &internal.{{ .originStructType }}{}\n\t} else {\n\t\tov = internal.ProtoPool{{ .oneOfName }}.Get().(*internal.{{ .originStructType }})\n\t}\n\tov.{{ .originFieldName }} = v\n\tms.orig.{{ .originOneOfFieldName }} = ov\n}`\n\nconst oneOfPrimitiveAccessorTestTemplate = `func Test{{ .structName }}_{{ .accessorFieldName }}(t *testing.T) {\n\tms := New{{ .structName }}()\n\t{{- if eq .returnType \"float64\"}}\n\tassert.InDelta(t, {{ .defaultVal }}, ms.{{ .accessorFieldName }}(), 0.01)\n\t{{- else if and (eq .returnType \"string\") (eq .defaultVal \"\\\"\\\"\") }}\n\tassert.Empty(t, ms.{{ .accessorFieldName }}())\n\t{{- else }}\n\tassert.Equal(t, {{ .defaultVal }}, ms.{{ .accessorFieldName }}())\n\t{{- end }}\n\tms.Set{{ .accessorFieldName }}({{ .testValue }})\n\t{{- if eq .returnType \"float64\" }}\n\tassert.InDelta(t, {{ .testValue }}, ms.{{ .accessorFieldName }}(), 0.01)\n\t{{- else if and (eq .returnType \"string\") (eq .testValue \"\\\"\\\"\") }}\n\tassert.Empty(t, ms.{{ .accessorFieldName }}())\n\t{{- else }}\n\tassert.Equal(t, {{ .testValue }}, ms.{{ .accessorFieldName }}())\n\t{{- end }}\n\tassert.Equal(t, {{ .typeName }}, ms.{{ .originOneOfTypeFuncName }}())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { new{{ .structName }}(internal.New{{ .originStructName }}(), sharedState).Set{{ .accessorFieldName }}({{ .testValue }}) })\n}\n`\n\nconst oneOfPrimitiveSetTestTemplate = `orig.{{ .originOneOfFieldName }} = &internal.{{ .originStructType }}{\n{{- .originFieldName }}: {{ .testValue }}}`\n\nconst oneOfPrimitiveTypeTemplate = `case *internal.{{ .originStructType }}:\n\treturn {{ .typeName }}`\n\ntype OneOfPrimitiveValue struct {\n\tfieldName       string\n\tprotoID         uint32\n\tprotoType       proto.Type\n\toriginFieldName string\n}\n\nfunc (opv *OneOfPrimitiveValue) GetOriginFieldName() string {\n\treturn opv.originFieldName\n}\n\nfunc (opv *OneOfPrimitiveValue) GenerateAccessors(ms *messageStruct, of *OneOfField) string {\n\tt := tmplutil.Parse(\"oneOfPrimitiveAccessorsTemplate\", []byte(oneOfPrimitiveAccessorsTemplate))\n\treturn tmplutil.Execute(t, opv.templateFields(ms, of))\n}\n\nfunc (opv *OneOfPrimitiveValue) GenerateTests(ms *messageStruct, of *OneOfField) string {\n\tt := tmplutil.Parse(\"oneOfPrimitiveAccessorTestTemplate\", []byte(oneOfPrimitiveAccessorTestTemplate))\n\treturn tmplutil.Execute(t, opv.templateFields(ms, of))\n}\n\nfunc (opv *OneOfPrimitiveValue) GenerateTestValue(ms *messageStruct, of *OneOfField) string {\n\tt := tmplutil.Parse(\"oneOfPrimitiveSetTestTemplate\", []byte(oneOfPrimitiveSetTestTemplate))\n\treturn tmplutil.Execute(t, opv.templateFields(ms, of))\n}\n\nfunc (opv *OneOfPrimitiveValue) GenerateType(ms *messageStruct, of *OneOfField) string {\n\tt := tmplutil.Parse(\"oneOfPrimitiveCopyOrigTemplate\", []byte(oneOfPrimitiveTypeTemplate))\n\treturn tmplutil.Execute(t, opv.templateFields(ms, of))\n}\n\nfunc (opv *OneOfPrimitiveValue) toProtoField(ms *messageStruct, of *OneOfField) proto.FieldInterface {\n\tpf := &proto.Field{\n\t\tType:              opv.protoType,\n\t\tID:                opv.protoID,\n\t\tOneOfGroup:        of.originFieldName,\n\t\tName:              opv.originFieldName,\n\t\tOneOfMessageName:  ms.protoName + \"_\" + opv.originFieldName,\n\t\tParentMessageName: ms.protoName,\n\t\tNullable:          true,\n\t}\n\treturn pf\n}\n\nfunc (opv *OneOfPrimitiveValue) templateFields(ms *messageStruct, of *OneOfField) map[string]any {\n\tpf := opv.toProtoField(ms, of)\n\treturn map[string]any{\n\t\t\"structName\":              ms.getName(),\n\t\t\"defaultVal\":              pf.DefaultValue(),\n\t\t\"packageName\":             \"\",\n\t\t\"accessorFieldName\":       opv.getAccessorFieldName(of),\n\t\t\"testValue\":               pf.TestValue(),\n\t\t\"originOneOfTypeFuncName\": of.typeFuncName(),\n\t\t\"typeName\":                of.typeName + opv.fieldName,\n\t\t\"lowerFieldName\":          strings.ToLower(opv.fieldName),\n\t\t\"returnType\":              pf.GoType(),\n\t\t\"originFieldName\":         opv.originFieldName,\n\t\t\"originOneOfFieldName\":    of.originFieldName,\n\t\t\"originStructName\":        ms.protoName,\n\t\t\"originStructType\":        ms.protoName + \"_\" + opv.originFieldName,\n\t\t\"oneOfName\":               proto.ExtractNameFromFull(ms.protoName + \"_\" + opv.originFieldName),\n\t}\n}\n\nfunc (opv *OneOfPrimitiveValue) getAccessorFieldName(of *OneOfField) string {\n\tif of.omitOriginFieldNameInNames {\n\t\treturn opv.fieldName\n\t}\n\treturn opv.fieldName + of.originFieldName\n}\n\nvar _ oneOfValue = (*OneOfPrimitiveValue)(nil)\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/optional_primitive_field.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\nimport (\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst optionalPrimitiveAccessorsTemplate = `// {{ .fieldName }} returns the {{ .lowerFieldName }} associated with this {{ .structName }}.\nfunc (ms {{ .structName }}) {{ .fieldName }}() {{ .returnType }} {\n\treturn ms.orig.{{ .fieldName }}\n}\n\n// Has{{ .fieldName }} returns true if the {{ .structName }} contains a\n// {{ .fieldName }} value otherwise.\nfunc (ms {{ .structName }}) Has{{ .fieldName }}() bool {\n\treturn ms.orig.Has{{ .fieldName }}()\n}\n\n// Set{{ .fieldName }} replaces the {{ .lowerFieldName }} associated with this {{ .structName }}.\nfunc (ms {{ .structName }}) Set{{ .fieldName }}(v {{ .returnType }}) {\n\tms.state.AssertMutable()\n\tms.orig.Set{{ .fieldName }}(v)\n}\n\n// Remove{{ .fieldName }} removes the {{ .lowerFieldName }} associated with this {{ .structName }}.\nfunc (ms {{ .structName }}) Remove{{ .fieldName }}() {\n\tms.state.AssertMutable()\n\tms.orig.Remove{{ .fieldName }}()\n}`\n\nconst optionalPrimitiveAccessorsTestTemplate = `func Test{{ .structName }}_{{ .fieldName }}(t *testing.T) {\n\tms := New{{ .structName }}()\n\t{{- if eq .returnType \"float64\" }}\n\tassert.InDelta(t, {{ .defaultVal }}, ms.{{ .fieldName }}() , 0.01)\n\t{{- else }}\n\tassert.Equal(t, {{ .defaultVal }}, ms.{{ .fieldName }}())\n\t{{- end }}\n\tms.Set{{ .fieldName }}({{ .testValue }})\n\tassert.True(t, ms.Has{{ .fieldName }}())\n\t{{- if eq .returnType \"float64\" }}\n\tassert.InDelta(t, {{.testValue }}, ms.{{ .fieldName }}(), 0.01)\n\t{{- else }}\n\tassert.Equal(t, {{ .testValue }}, ms.{{ .fieldName }}())\n\t{{- end }}\n\tms.Remove{{ .fieldName }}()\n\tassert.False(t, ms.Has{{ .fieldName }}())\n\tdest := New{{ .structName }}()\n\tdest.Set{{ .fieldName }}({{ .testValue }})\n\tms.CopyTo(dest)\n\tassert.False(t, dest.Has{{ .fieldName }}())\n}`\n\nconst optionalPrimitiveSetTestTemplate = `orig.{{ .fieldName }}_ = &internal.{{ .originStructType }}{\n{{- .fieldName }}: {{ .testValue }}}`\n\ntype OptionalPrimitiveField struct {\n\tfieldName string\n\tprotoID   uint32\n\tprotoType proto.Type\n}\n\nfunc (opv *OptionalPrimitiveField) GenerateAccessors(ms *messageStruct) string {\n\treturn tmplutil.Execute(tmplutil.Parse(\"optionalPrimitiveAccessorsTemplate\", []byte(optionalPrimitiveAccessorsTemplate)), opv.templateFields(ms))\n}\n\nfunc (opv *OptionalPrimitiveField) GenerateAccessorsTest(ms *messageStruct) string {\n\treturn tmplutil.Execute(tmplutil.Parse(\"optionalPrimitiveAccessorsTestTemplate\", []byte(optionalPrimitiveAccessorsTestTemplate)), opv.templateFields(ms))\n}\n\nfunc (opv *OptionalPrimitiveField) GenerateTestValue(ms *messageStruct) string {\n\treturn tmplutil.Execute(tmplutil.Parse(\"optionalPrimitiveSetTestTemplate\", []byte(optionalPrimitiveSetTestTemplate)), opv.templateFields(ms))\n}\n\nfunc (opv *OptionalPrimitiveField) toProtoField(ms *messageStruct) proto.FieldInterface {\n\treturn &proto.Field{\n\t\tType:              opv.protoType,\n\t\tID:                opv.protoID,\n\t\tName:              opv.fieldName,\n\t\tParentMessageName: ms.protoName,\n\t\tNullable:          true,\n\t}\n}\n\nfunc (opv *OptionalPrimitiveField) templateFields(ms *messageStruct) map[string]any {\n\tpf := opv.toProtoField(ms).(*proto.Field)\n\treturn map[string]any{\n\t\t\"structName\":       ms.getName(),\n\t\t\"defaultVal\":       pf.DefaultValue(),\n\t\t\"fieldName\":        opv.fieldName,\n\t\t\"lowerFieldName\":   strings.ToLower(opv.fieldName),\n\t\t\"testValue\":        pf.TestValue(),\n\t\t\"returnType\":       pf.GoType(),\n\t\t\"originName\":       ms.getOriginName(),\n\t\t\"originStructName\": ms.getOriginFullName(),\n\t\t\"originStructType\": ms.getOriginFullName() + \"_\" + opv.fieldName,\n\t}\n}\n\nvar _ Field = (*OptionalPrimitiveField)(nil)\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/packages.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"slices\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n)\n\nvar nonInternalDeps = []string{\n\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t`\"go.opentelemetry.io/collector/pdata/pcommon\"`,\n\t`\"go.opentelemetry.io/collector/pdata/plog\"`,\n\t`\"go.opentelemetry.io/collector/pdata/pmetric\"`,\n\t`\"go.opentelemetry.io/collector/pdata/pprofile\"`,\n\t`\"go.opentelemetry.io/collector/pdata/ptrace\"`,\n\t`\"go.opentelemetry.io/collector/pdata/xpdata\"`,\n}\n\n// AllPackages is a list of all packages that needs to be generated.\nvar AllPackages = []*Package{\n\tpcommon,\n\tplog,\n\tplogotlp,\n\tpmetric,\n\tpmetricotlp,\n\tptrace,\n\tptraceotlp,\n\tpprofile,\n\tpprofileotlp,\n\txpdataEntity,\n\tprequest,\n}\n\n// Package is a struct used to generate files.\ntype Package struct {\n\tinfo *PackageInfo\n\t// Can be any of sliceStruct, sliceOfValues, messageStruct.\n\tstructs []baseStruct\n\tenums   []*proto.Enum\n}\n\ntype PackageInfo struct {\n\tname        string\n\tpath        string\n\timports     []string\n\ttestImports []string\n}\n\n// Path returns the package path for file generation.\nfunc (p *Package) Path() string {\n\treturn p.info.path\n}\n\n// DeleteGeneratedFiles removes all generated files matching the pattern in the given directory.\nfunc DeleteGeneratedFiles(dir string) error {\n\tmatches, err := filepath.Glob(filepath.Join(dir, \"generated_*.go\"))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tfor _, match := range matches {\n\t\tif err := os.Remove(match); err != nil && !os.IsNotExist(err) {\n\t\t\treturn fmt.Errorf(\"failed to remove %s: %w\", match, err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// GenerateFiles generates files with the configured data structures for this Package.\nfunc (p *Package) GenerateFiles() error {\n\tfor _, s := range p.structs {\n\t\tif s.getHasOnlyInternal() {\n\t\t\tcontinue\n\t\t}\n\t\tpath := filepath.Join(\"pdata\", p.info.path, \"generated_\"+strings.ToLower(s.getName())+\".go\")\n\t\tif err := os.WriteFile(path, s.generate(p.info), 0o600); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// GenerateTestFiles generates files with tests for the configured data structures for this Package.\nfunc (p *Package) GenerateTestFiles() error {\n\tfor _, s := range p.structs {\n\t\tif s.getHasOnlyInternal() {\n\t\t\tcontinue\n\t\t}\n\t\tpath := filepath.Join(\"pdata\", p.info.path, \"generated_\"+strings.ToLower(s.getName())+\"_test.go\")\n\t\tif err := os.WriteFile(path, s.generateTests(p.info), 0o600); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// GenerateInternalFiles generates files with internal structs for this Package.\nfunc (p *Package) GenerateInternalFiles() error {\n\tfor _, s := range p.structs {\n\t\tif !s.getHasWrapper() {\n\t\t\tcontinue\n\t\t}\n\t\tpath := filepath.Join(\"pdata\", \"internal\", \"generated_wrapper_\"+strings.ToLower(s.getOriginName())+\".go\")\n\t\tsaveImports := slices.Clone(p.info.imports)\n\t\tp.info.imports = slices.DeleteFunc(p.info.imports, func(s string) bool {\n\t\t\treturn slices.Contains(nonInternalDeps, s)\n\t\t})\n\t\tif err := os.WriteFile(path, s.generateInternal(p.info), 0o600); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tp.info.imports = saveImports\n\t}\n\treturn nil\n}\n\n// GenerateProtoMessageFiles generates files with proto messages for this Package.\nfunc (p *Package) GenerateProtoMessageFiles() error {\n\tfor _, s := range p.structs {\n\t\tpm := s.getProtoMessage()\n\t\tif pm == nil {\n\t\t\tcontinue\n\t\t}\n\t\tsaveTestImports := slices.Clone(p.info.testImports)\n\t\tp.info.testImports = slices.DeleteFunc(p.info.testImports, func(s string) bool {\n\t\t\treturn slices.Contains(nonInternalDeps, s)\n\t\t})\n\t\tpath := filepath.Join(\"pdata\", \"internal\", \"generated_proto_\"+strings.ToLower(s.getOriginName())+\".go\")\n\t\tif err := os.WriteFile(path, pm.GenerateMessage(p.info.imports, p.info.testImports), 0o600); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tp.info.testImports = saveTestImports\n\t}\n\treturn nil\n}\n\n// GenerateProtoMessageTestsFiles generates files with proto messages tests for this Package.\nfunc (p *Package) GenerateProtoMessageTestsFiles() error {\n\tfor _, s := range p.structs {\n\t\tpm := s.getProtoMessage()\n\t\tif pm == nil {\n\t\t\tcontinue\n\t\t}\n\t\tsaveTestImports := slices.Clone(p.info.testImports)\n\t\tp.info.testImports = slices.DeleteFunc(p.info.testImports, func(s string) bool {\n\t\t\treturn slices.Contains(nonInternalDeps, s)\n\t\t})\n\t\tpath := filepath.Join(\"pdata\", \"internal\", \"generated_proto_\"+strings.ToLower(pm.Name)+\"_test.go\")\n\t\tif err := os.WriteFile(path, pm.GenerateMessageTests(p.info.imports, p.info.testImports), 0o600); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tp.info.testImports = saveTestImports\n\t}\n\treturn nil\n}\n\n// GenerateProtoEnumFiles generates files with proto messages for this Package.\nfunc (p *Package) GenerateProtoEnumFiles() error {\n\tfor _, s := range p.enums {\n\t\tpath := filepath.Join(\"pdata\", \"internal\", \"generated_enum_\"+strings.ToLower(s.Name)+\".go\")\n\t\tif err := os.WriteFile(path, s.GenerateEnum(), 0o600); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// usedByOtherDataTypes defines if the package is used by other data types and orig fields of the package's structs\n// need to be accessible from other pdata packages.\nfunc usedByOtherDataTypes(packageName string) bool {\n\treturn packageName == \"pcommon\" || packageName == \"entity\"\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/pcommon_package.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\nimport (\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n)\n\nvar pcommon = &Package{\n\tinfo: &PackageInfo{\n\t\tname: \"pcommon\",\n\t\tpath: \"pcommon\",\n\t\timports: []string{\n\t\t\t`\"encoding/binary\"`,\n\t\t\t`\"fmt\"`,\n\t\t\t`\"iter\"`,\n\t\t\t`\"math\"`,\n\t\t\t`\"sort\"`,\n\t\t\t`\"sync\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/json\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/proto\"`,\n\t\t},\n\t\ttestImports: []string{\n\t\t\t`\"strconv\"`,\n\t\t\t`\"testing\"`,\n\t\t\t``,\n\t\t\t`\"github.com/stretchr/testify/assert\"`,\n\t\t\t`\"github.com/stretchr/testify/require\"`,\n\t\t\t`\"google.golang.org/protobuf/proto\"`,\n\t\t\t`gootlpcommon \"go.opentelemetry.io/proto/slim/otlp/common/v1\"`,\n\t\t\t`gootlpresource \"go.opentelemetry.io/proto/slim/otlp/resource/v1\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/internal/testutil\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/json\"`,\n\t\t},\n\t},\n\tstructs: []baseStruct{\n\t\tanyValueStruct,\n\t\tarrayValueStruct,\n\t\tkeyValueStruct,\n\t\tkeyValueListStruct,\n\t\tanyValueSlice,\n\t\tscope,\n\t\tresource,\n\t\tbyteSlice,\n\t\tfloat64Slice,\n\t\tuInt64Slice,\n\t\tint64Slice,\n\t\tint32Slice,\n\t\tstringSlice,\n\t},\n}\n\nvar scope = &messageStruct{\n\tstructName:    \"InstrumentationScope\",\n\tpackageName:   \"pcommon\",\n\tdescription:   \"// InstrumentationScope is a message representing the instrumentation scope information.\",\n\tprotoName:     \"InstrumentationScope\",\n\tupstreamProto: \"gootlpcommon.InstrumentationScope\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Name\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Version\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"Attributes\",\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\tprotoID:     3,\n\t\t\treturnSlice: mapStruct,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"DroppedAttributesCount\",\n\t\t\tprotoID:   4,\n\t\t\tprotoType: proto.TypeUint32,\n\t\t},\n\t},\n}\n\n// This will not be generated by this class.\n// Defined here just to be available as returned message for the fields.\nvar mapStruct = &messageSlice{\n\tstructName:      \"Map\",\n\tpackageName:     \"pcommon\",\n\telementNullable: false,\n\telement:         keyValueStruct,\n}\n\nvar keyValueStruct = &messageStruct{\n\tstructName:    \"KeyValue\",\n\tprotoName:     \"KeyValue\",\n\tupstreamProto: \"gootlpcommon.KeyValue\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Key\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t\t&MessageField{\n\t\t\tfieldName:     \"Value\",\n\t\t\tprotoID:       2,\n\t\t\treturnMessage: anyValueClone,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"KeyStrindex\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeInt32,\n\t\t},\n\t},\n\thasOnlyInternal: true,\n}\n\nvar anyValueClone = &messageStruct{\n\tstructName: \"Value\",\n\tprotoName:  \"AnyValue\",\n}\n\n// anyValueStruct needs to be different from anyValue because otherwise we cause initialization circular deps with mapStruct.\nvar anyValueStruct = &messageStruct{\n\tstructName:    \"Value\",\n\tpackageName:   \"pcommon\",\n\tprotoName:     \"AnyValue\",\n\tupstreamProto: \"gootlpcommon.AnyValue\",\n\tfields: []Field{\n\t\t&OneOfField{\n\t\t\ttypeName:                   \"ValueType\",\n\t\t\toriginFieldName:            \"Value\",\n\t\t\ttestValueIdx:               1, //\n\t\t\tomitOriginFieldNameInNames: true,\n\t\t\tvalues: []oneOfValue{\n\t\t\t\t&OneOfPrimitiveValue{\n\t\t\t\t\tfieldName:       \"StringValue\",\n\t\t\t\t\tprotoID:         1,\n\t\t\t\t\toriginFieldName: \"StringValue\",\n\t\t\t\t\tprotoType:       proto.TypeString,\n\t\t\t\t},\n\t\t\t\t&OneOfPrimitiveValue{\n\t\t\t\t\tfieldName:       \"BoolValue\",\n\t\t\t\t\tprotoID:         2,\n\t\t\t\t\toriginFieldName: \"BoolValue\",\n\t\t\t\t\tprotoType:       proto.TypeBool,\n\t\t\t\t},\n\t\t\t\t&OneOfPrimitiveValue{\n\t\t\t\t\tfieldName:       \"IntValue\",\n\t\t\t\t\tprotoID:         3,\n\t\t\t\t\toriginFieldName: \"IntValue\",\n\t\t\t\t\tprotoType:       proto.TypeInt64,\n\t\t\t\t},\n\t\t\t\t&OneOfPrimitiveValue{\n\t\t\t\t\tfieldName:       \"DoubleValue\",\n\t\t\t\t\tprotoID:         4,\n\t\t\t\t\toriginFieldName: \"DoubleValue\",\n\t\t\t\t\tprotoType:       proto.TypeDouble,\n\t\t\t\t},\n\t\t\t\t&OneOfMessageValue{\n\t\t\t\t\tfieldName:     \"ArrayValue\",\n\t\t\t\t\tprotoID:       5,\n\t\t\t\t\treturnMessage: arrayValueStruct,\n\t\t\t\t},\n\t\t\t\t&OneOfMessageValue{\n\t\t\t\t\tfieldName:     \"KvlistValue\",\n\t\t\t\t\tprotoID:       6,\n\t\t\t\t\treturnMessage: keyValueListStruct,\n\t\t\t\t},\n\t\t\t\t&OneOfPrimitiveValue{\n\t\t\t\t\tfieldName:       \"BytesValue\",\n\t\t\t\t\tprotoID:         7,\n\t\t\t\t\toriginFieldName: \"BytesValue\",\n\t\t\t\t\tprotoType:       proto.TypeBytes,\n\t\t\t\t},\n\t\t\t\t&OneOfPrimitiveValue{\n\t\t\t\t\tfieldName:       \"StringValueStrindex\",\n\t\t\t\t\tprotoID:         8,\n\t\t\t\t\toriginFieldName: \"StringValueStrindex\",\n\t\t\t\t\tprotoType:       proto.TypeInt32,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t},\n\thasOnlyInternal: true,\n}\n\nvar keyValueListStruct = &messageStruct{\n\tstructName:    \"KeyValueList\",\n\tdescription:   \"// KeyValueList is a list of KeyValue messages. We need KeyValueList as a message since oneof in AnyValue does not allow repeated fields.\",\n\tprotoName:     \"KeyValueList\",\n\tupstreamProto: \"gootlpcommon.KeyValueList\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"Values\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: mapStruct,\n\t\t},\n\t},\n\thasOnlyInternal: true,\n}\n\nvar arrayValueStruct = &messageStruct{\n\tstructName:    \"ArrayValue\",\n\tdescription:   \"// ArrayValue is a list of AnyValue messages. We need ArrayValue as a message since oneof in AnyValue does not allow repeated fields.\",\n\tprotoName:     \"ArrayValue\",\n\tupstreamProto: \"gootlpcommon.ArrayValue\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"Values\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: anyValueSlice,\n\t\t},\n\t},\n\thasOnlyInternal: true,\n}\n\nvar anyValueSlice = &messageSlice{\n\tstructName:      \"Slice\",\n\tpackageName:     \"pcommon\",\n\telementNullable: false,\n\telement:         anyValueClone,\n}\n\nvar traceState = &messageStruct{\n\tstructName:  \"TraceState\",\n\tpackageName: \"pcommon\",\n\tprotoName:   \"TraceState\", // Fake name to generate correct CopyOrig* name.\n}\n\nvar timestampType = &TypedType{\n\tstructName:  \"Timestamp\",\n\tpackageName: \"pcommon\",\n\tprotoType:   proto.TypeFixed64,\n\tdefaultVal:  \"0\",\n\ttestVal:     \"1234567890\",\n}\n\nvar traceIDType = &TypedType{\n\tstructName:  \"TraceID\",\n\tpackageName: \"pcommon\",\n\tprotoType:   proto.TypeMessage,\n\tmessageName: \"TraceID\",\n\tdefaultVal:  \"TraceID([16]byte{})\",\n\ttestVal:     \"TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1})\",\n}\n\nvar spanIDType = &TypedType{\n\tstructName:  \"SpanID\",\n\tpackageName: \"pcommon\",\n\tprotoType:   proto.TypeMessage,\n\tmessageName: \"SpanID\",\n\tdefaultVal:  \"SpanID([8]byte{})\",\n\ttestVal:     \"SpanID([8]byte{8, 7, 6, 5, 4, 3, 2, 1})\",\n}\n\nvar resource = &messageStruct{\n\tstructName:    \"Resource\",\n\tpackageName:   \"pcommon\",\n\tdescription:   \"// Resource is a message representing the resource information.\",\n\tprotoName:     \"Resource\",\n\tupstreamProto: \"gootlpresource.Resource\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"Attributes\",\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\tprotoID:     1,\n\t\t\treturnSlice: mapStruct,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"DroppedAttributesCount\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeUint32,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"EntityRefs\",\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\tprotoID:     3,\n\t\t\treturnSlice: entityRefSlice,\n\t\t\t// Hide accessors for this field from 1.x public API since the proto field is experimental.\n\t\t\t// It's available via the xpdata/entity.ResourceEntityRefs.\n\t\t\thideAccessors: true,\n\t\t},\n\t},\n}\n\nvar byteSlice = &primitiveSliceStruct{\n\tstructName:           \"ByteSlice\",\n\tpackageName:          \"pcommon\",\n\titemType:             \"byte\",\n\ttestOrigVal:          \"1, 2, 3\",\n\ttestInterfaceOrigVal: []any{1, 2, 3},\n\ttestSetVal:           \"5\",\n\ttestNewVal:           \"1, 5, 3\",\n}\n\nvar float64Slice = &primitiveSliceStruct{\n\tstructName:           \"Float64Slice\",\n\tpackageName:          \"pcommon\",\n\titemType:             \"float64\",\n\ttestOrigVal:          \"1.1, 2.2, 3.3\",\n\ttestInterfaceOrigVal: []any{1.1, 2.2, 3.3},\n\ttestSetVal:           \"5.5\",\n\ttestNewVal:           \"1.1, 5.5, 3.3\",\n}\n\nvar uInt64Slice = &primitiveSliceStruct{\n\tstructName:           \"UInt64Slice\",\n\tpackageName:          \"pcommon\",\n\titemType:             \"uint64\",\n\ttestOrigVal:          \"1, 2, 3\",\n\ttestInterfaceOrigVal: []any{1, 2, 3},\n\ttestSetVal:           \"5\",\n\ttestNewVal:           \"1, 5, 3\",\n}\n\nvar int64Slice = &primitiveSliceStruct{\n\tstructName:           \"Int64Slice\",\n\tpackageName:          \"pcommon\",\n\titemType:             \"int64\",\n\ttestOrigVal:          \"1, 2, 3\",\n\ttestInterfaceOrigVal: []any{1, 2, 3},\n\ttestSetVal:           \"5\",\n\ttestNewVal:           \"1, 5, 3\",\n}\n\nvar int32Slice = &primitiveSliceStruct{\n\tstructName:           \"Int32Slice\",\n\tpackageName:          \"pcommon\",\n\titemType:             \"int32\",\n\ttestOrigVal:          \"1, 2, 3\",\n\ttestInterfaceOrigVal: []any{1, 2, 3},\n\ttestSetVal:           \"5\",\n\ttestNewVal:           \"1, 5, 3\",\n}\n\nvar stringSlice = &primitiveSliceStruct{\n\tstructName:           \"StringSlice\",\n\tpackageName:          \"pcommon\",\n\titemType:             \"string\",\n\ttestOrigVal:          `\"a\", \"b\", \"c\"`,\n\ttestInterfaceOrigVal: []any{`\"a\"`, `\"b\"`, `\"c\"`},\n\ttestSetVal:           `\"d\"`,\n\ttestNewVal:           `\"a\", \"d\", \"c\"`,\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/plog_package.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\nimport (\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n)\n\nvar plog = &Package{\n\tinfo: &PackageInfo{\n\t\tname: \"plog\",\n\t\tpath: \"plog\",\n\t\timports: []string{\n\t\t\t`\"encoding/binary\"`,\n\t\t\t`\"fmt\"`,\n\t\t\t`\"iter\"`,\n\t\t\t`\"math\"`,\n\t\t\t`\"sort\"`,\n\t\t\t`\"sync\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/json\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/proto\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/pcommon\"`,\n\t\t},\n\t\ttestImports: []string{\n\t\t\t`\"strconv\"`,\n\t\t\t`\"testing\"`,\n\t\t\t`\"unsafe\"`,\n\t\t\t``,\n\t\t\t`\"github.com/stretchr/testify/assert\"`,\n\t\t\t`\"github.com/stretchr/testify/require\"`,\n\t\t\t`\"google.golang.org/protobuf/proto\"`,\n\t\t\t`gootlpcollectorlogs \"go.opentelemetry.io/proto/slim/otlp/collector/logs/v1\"`,\n\t\t\t`gootlplogs \"go.opentelemetry.io/proto/slim/otlp/logs/v1\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/json\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/pcommon\"`,\n\t\t},\n\t},\n\tstructs: []baseStruct{\n\t\tlogs,\n\t\tlogsData,\n\t\tresourceLogsSlice,\n\t\tresourceLogs,\n\t\tscopeLogsSlice,\n\t\tscopeLogs,\n\t\tlogSlice,\n\t\tlogRecord,\n\t},\n\tenums: []*proto.Enum{\n\t\tseverityNumberEnum,\n\t},\n}\n\nvar logs = &messageStruct{\n\tstructName:    \"Logs\",\n\tdescription:   \"// Logs is the top-level struct that is propagated through the logs pipeline.\\n// Use NewLogs to create new instance, zero-initialized instance is not valid for use.\",\n\tprotoName:     \"ExportLogsServiceRequest\",\n\tupstreamProto: \"gootlpcollectorlogs.ExportLogsServiceRequest\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"ResourceLogs\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: resourceLogsSlice,\n\t\t},\n\t},\n\thasWrapper: true,\n}\n\nvar logsData = &messageStruct{\n\tstructName:    \"LogsData\",\n\tdescription:   \"// LogsData represents the logs data that can be stored in a persistent storage,\\n// OR can be embedded by other protocols that transfer OTLP logs data but do not\\n// implement the OTLP protocol.\",\n\tprotoName:     \"LogsData\",\n\tupstreamProto: \"gootlplogs.LogsData\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"ResourceLogs\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: resourceLogsSlice,\n\t\t},\n\t},\n\thasOnlyInternal: true,\n}\n\nvar resourceLogsSlice = &messageSlice{\n\tstructName:      \"ResourceLogsSlice\",\n\telementNullable: true,\n\telement:         resourceLogs,\n}\n\nvar resourceLogs = &messageStruct{\n\tstructName:    \"ResourceLogs\",\n\tdescription:   \"// ResourceLogs is a collection of logs from a Resource.\",\n\tprotoName:     \"ResourceLogs\",\n\tupstreamProto: \"gootlplogs.ResourceLogs\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"Resource\",\n\t\t\tprotoID:       1,\n\t\t\treturnMessage: resource,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"ScopeLogs\",\n\t\t\tprotoID:     2,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: scopeLogsSlice,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"SchemaUrl\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"DeprecatedScopeLogs\",\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\tprotoID:     1000,\n\t\t\treturnSlice: scopeLogsSlice,\n\t\t\t// Hide accessors for this field because it is a HACK:\n\t\t\t// Workaround for istio 1.15 / envoy 1.23.1 mistakenly emitting deprecated field.\n\t\t\thideAccessors: true,\n\t\t},\n\t},\n}\n\nvar scopeLogsSlice = &messageSlice{\n\tstructName:      \"ScopeLogsSlice\",\n\telementNullable: true,\n\telement:         scopeLogs,\n}\n\nvar scopeLogs = &messageStruct{\n\tstructName:    \"ScopeLogs\",\n\tdescription:   \"// ScopeLogs is a collection of logs from a LibraryInstrumentation.\",\n\tprotoName:     \"ScopeLogs\",\n\tupstreamProto: \"gootlplogs.ScopeLogs\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"Scope\",\n\t\t\tprotoID:       1,\n\t\t\treturnMessage: scope,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"LogRecords\",\n\t\t\tprotoID:     2,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: logSlice,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"SchemaUrl\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t},\n}\n\nvar logSlice = &messageSlice{\n\tstructName:      \"LogRecordSlice\",\n\telementNullable: true,\n\telement:         logRecord,\n}\n\nvar logRecord = &messageStruct{\n\tstructName:    \"LogRecord\",\n\tdescription:   \"// LogRecord are experimental implementation of OpenTelemetry Log Data Model.\\n\",\n\tprotoName:     \"LogRecord\",\n\tupstreamProto: \"gootlplogs.LogRecord\",\n\tfields: []Field{\n\t\t&TypedField{\n\t\t\tfieldName:       \"Timestamp\",\n\t\t\tprotoID:         1,\n\t\t\toriginFieldName: \"TimeUnixNano\",\n\t\t\treturnType:      timestampType,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"ObservedTimestamp\",\n\t\t\tprotoID:         11,\n\t\t\toriginFieldName: \"ObservedTimeUnixNano\",\n\t\t\treturnType:      timestampType,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName: \"SeverityNumber\",\n\t\t\tprotoID:   2,\n\t\t\treturnType: &TypedType{\n\t\t\t\tstructName:  \"SeverityNumber\",\n\t\t\t\tprotoType:   proto.TypeEnum,\n\t\t\t\tmessageName: \"SeverityNumber\",\n\t\t\t\tdefaultVal:  `SeverityNumber_SEVERITY_NUMBER_UNSPECIFIED`,\n\t\t\t\ttestVal:     `SeverityNumber_SEVERITY_NUMBER_DEBUG`,\n\t\t\t},\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"SeverityText\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t\t&MessageField{\n\t\t\tfieldName:     \"Body\",\n\t\t\tprotoID:       5,\n\t\t\treturnMessage: anyValueStruct,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"Attributes\",\n\t\t\tprotoID:     6,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: mapStruct,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"DroppedAttributesCount\",\n\t\t\tprotoID:   7,\n\t\t\tprotoType: proto.TypeUint32,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName: \"Flags\",\n\t\t\tprotoID:   8,\n\t\t\treturnType: &TypedType{\n\t\t\t\tstructName: \"LogRecordFlags\",\n\t\t\t\tprotoType:  proto.TypeFixed32,\n\t\t\t\tdefaultVal: \"0\",\n\t\t\t\ttestVal:    \"1\",\n\t\t\t},\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"TraceID\",\n\t\t\toriginFieldName: \"TraceId\",\n\t\t\tprotoID:         9,\n\t\t\treturnType:      traceIDType,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"SpanID\",\n\t\t\toriginFieldName: \"SpanId\",\n\t\t\tprotoID:         10,\n\t\t\treturnType:      spanIDType,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"EventName\",\n\t\t\tprotoID:   12,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t},\n}\n\nvar severityNumberEnum = &proto.Enum{\n\tName:        \"SeverityNumber\",\n\tDescription: \"// SeverityNumber represent possible values for LogRecord.SeverityNumber\",\n\tFields: []*proto.EnumField{\n\t\t{Name: \"SEVERITY_NUMBER_UNSPECIFIED\", Value: 0},\n\t\t{Name: \"SEVERITY_NUMBER_TRACE \", Value: 1},\n\t\t{Name: \"SEVERITY_NUMBER_TRACE2\", Value: 2},\n\t\t{Name: \"SEVERITY_NUMBER_TRACE3\", Value: 3},\n\t\t{Name: \"SEVERITY_NUMBER_TRACE4\", Value: 4},\n\t\t{Name: \"SEVERITY_NUMBER_DEBUG\", Value: 5},\n\t\t{Name: \"SEVERITY_NUMBER_DEBUG2\", Value: 6},\n\t\t{Name: \"SEVERITY_NUMBER_DEBUG3\", Value: 7},\n\t\t{Name: \"SEVERITY_NUMBER_DEBUG4\", Value: 8},\n\t\t{Name: \"SEVERITY_NUMBER_INFO\", Value: 9},\n\t\t{Name: \"SEVERITY_NUMBER_INFO2\", Value: 10},\n\t\t{Name: \"SEVERITY_NUMBER_INFO3\", Value: 11},\n\t\t{Name: \"SEVERITY_NUMBER_INFO4\", Value: 12},\n\t\t{Name: \"SEVERITY_NUMBER_WARN\", Value: 13},\n\t\t{Name: \"SEVERITY_NUMBER_WARN2\", Value: 14},\n\t\t{Name: \"SEVERITY_NUMBER_WARN3\", Value: 15},\n\t\t{Name: \"SEVERITY_NUMBER_WARN4\", Value: 16},\n\t\t{Name: \"SEVERITY_NUMBER_ERROR\", Value: 17},\n\t\t{Name: \"SEVERITY_NUMBER_ERROR2\", Value: 18},\n\t\t{Name: \"SEVERITY_NUMBER_ERROR3\", Value: 19},\n\t\t{Name: \"SEVERITY_NUMBER_ERROR4\", Value: 20},\n\t\t{Name: \"SEVERITY_NUMBER_FATAL\", Value: 21},\n\t\t{Name: \"SEVERITY_NUMBER_FATAL2\", Value: 22},\n\t\t{Name: \"SEVERITY_NUMBER_FATAL3\", Value: 23},\n\t\t{Name: \"SEVERITY_NUMBER_FATAL4\", Value: 24},\n\t},\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/plogotlp_package.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\nimport (\n\t\"path/filepath\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n)\n\nvar plogotlp = &Package{\n\tinfo: &PackageInfo{\n\t\tname: \"plogotlp\",\n\t\tpath: filepath.Join(\"plog\", \"plogotlp\"),\n\t\timports: []string{\n\t\t\t`\"encoding/binary\"`,\n\t\t\t`\"fmt\"`,\n\t\t\t`\"iter\"`,\n\t\t\t`\"math\"`,\n\t\t\t`\"sort\"`,\n\t\t\t`\"sync\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t},\n\t\ttestImports: []string{\n\t\t\t`\"strconv\"`,\n\t\t\t`\"testing\"`,\n\t\t\t``,\n\t\t\t`\"github.com/stretchr/testify/assert\"`,\n\t\t\t`\"github.com/stretchr/testify/require\"`,\n\t\t\t`\"google.golang.org/protobuf/proto\"`,\n\t\t\t`gootlpcollectorlogs \"go.opentelemetry.io/proto/slim/otlp/collector/logs/v1\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t},\n\t},\n\tstructs: []baseStruct{\n\t\texportLogsResponse,\n\t\texportLogsPartialSuccess,\n\t},\n}\n\nvar exportLogsResponse = &messageStruct{\n\tstructName:    \"ExportResponse\",\n\tdescription:   \"// ExportResponse represents the response for gRPC/HTTP client/server.\",\n\tprotoName:     \"ExportLogsServiceResponse\",\n\tupstreamProto: \"gootlpcollectorlogs.ExportLogsServiceResponse\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"PartialSuccess\",\n\t\t\tprotoID:       1,\n\t\t\treturnMessage: exportLogsPartialSuccess,\n\t\t},\n\t},\n}\n\nvar exportLogsPartialSuccess = &messageStruct{\n\tstructName:    \"ExportPartialSuccess\",\n\tdescription:   \"// ExportPartialSuccess represents the details of a partially successful export request.\",\n\tprotoName:     \"ExportLogsPartialSuccess\",\n\tupstreamProto: \"gootlpcollectorlogs.ExportLogsPartialSuccess\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"RejectedLogRecords\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeInt64,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"ErrorMessage\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t},\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/pmetric_package.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\nimport (\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n)\n\nvar pmetric = &Package{\n\tinfo: &PackageInfo{\n\t\tname: \"pmetric\",\n\t\tpath: \"pmetric\",\n\t\timports: []string{\n\t\t\t`\"encoding/binary\"`,\n\t\t\t`\"fmt\"`,\n\t\t\t`\"iter\"`,\n\t\t\t`\"math\"`,\n\t\t\t`\"sort\"`,\n\t\t\t`\"sync\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/json\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/proto\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/pcommon\"`,\n\t\t},\n\t\ttestImports: []string{\n\t\t\t`\"strconv\"`,\n\t\t\t`\"testing\"`,\n\t\t\t`\"unsafe\"`,\n\t\t\t``,\n\t\t\t`\"github.com/stretchr/testify/assert\"`,\n\t\t\t`\"github.com/stretchr/testify/require\"`,\n\t\t\t`\"google.golang.org/protobuf/proto\"`,\n\t\t\t`gootlpcollectormetrics \"go.opentelemetry.io/proto/slim/otlp/collector/metrics/v1\"`,\n\t\t\t`gootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/json\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/pcommon\"`,\n\t\t},\n\t},\n\tstructs: []baseStruct{\n\t\tmetrics,\n\t\tmetricsData,\n\t\tresourceMetricsSlice,\n\t\tresourceMetrics,\n\t\tscopeMetricsSlice,\n\t\tscopeMetrics,\n\t\tmetricSlice,\n\t\tmetric,\n\t\tgauge,\n\t\tsum,\n\t\thistogram,\n\t\texponentialHistogram,\n\t\tsummary,\n\t\tnumberDataPointSlice,\n\t\tnumberDataPoint,\n\t\thistogramDataPointSlice,\n\t\thistogramDataPoint,\n\t\texponentialHistogramDataPointSlice,\n\t\texponentialHistogramDataPoint,\n\t\tbucketsValues,\n\t\tsummaryDataPointSlice,\n\t\tsummaryDataPoint,\n\t\tquantileValuesSlice,\n\t\tquantileValues,\n\t\texemplarSlice,\n\t\texemplar,\n\t},\n\tenums: []*proto.Enum{\n\t\taggregationTemporalityEnum,\n\t},\n}\n\nvar metrics = &messageStruct{\n\tstructName:    \"Metrics\",\n\tdescription:   \"// Metrics is the top-level struct that is propagated through the metrics pipeline.\\n// Use NewMetrics to create new instance, zero-initialized instance is not valid for use.\",\n\tprotoName:     \"ExportMetricsServiceRequest\",\n\tupstreamProto: \"gootlpcollectormetrics.ExportMetricsServiceRequest\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"ResourceMetrics\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: resourceMetricsSlice,\n\t\t},\n\t},\n\thasWrapper: true,\n}\n\nvar metricsData = &messageStruct{\n\tstructName:    \"MetricsData\",\n\tdescription:   \"// MetricsData represents the metrics data that can be stored in a persistent storage,\\n// OR can be embedded by other protocols that transfer OTLP metrics data but do not\\n// implement the OTLP protocol..\",\n\tprotoName:     \"MetricsData\",\n\tupstreamProto: \"gootlpmetrics.MetricsData\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"ResourceMetrics\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: resourceMetricsSlice,\n\t\t},\n\t},\n\thasOnlyInternal: true,\n}\n\nvar resourceMetricsSlice = &messageSlice{\n\tstructName:      \"ResourceMetricsSlice\",\n\telementNullable: true,\n\telement:         resourceMetrics,\n}\n\nvar resourceMetrics = &messageStruct{\n\tstructName:    \"ResourceMetrics\",\n\tdescription:   \"// ResourceMetrics is a collection of metrics from a Resource.\",\n\tprotoName:     \"ResourceMetrics\",\n\tupstreamProto: \"gootlpmetrics.ResourceMetrics\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"Resource\",\n\t\t\tprotoID:       1,\n\t\t\treturnMessage: resource,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"ScopeMetrics\",\n\t\t\tprotoID:     2,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: scopeMetricsSlice,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"SchemaUrl\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"DeprecatedScopeMetrics\",\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\tprotoID:     1000,\n\t\t\treturnSlice: scopeMetricsSlice,\n\t\t\t// Hide accessors for this field because it is a HACK:\n\t\t\t// Workaround for istio 1.15 / envoy 1.23.1 mistakenly emitting deprecated field.\n\t\t\thideAccessors: true,\n\t\t},\n\t},\n}\n\nvar scopeMetricsSlice = &messageSlice{\n\tstructName:      \"ScopeMetricsSlice\",\n\telementNullable: true,\n\telement:         scopeMetrics,\n}\n\nvar scopeMetrics = &messageStruct{\n\tstructName:    \"ScopeMetrics\",\n\tdescription:   \"// ScopeMetrics is a collection of metrics from a LibraryInstrumentation.\",\n\tprotoName:     \"ScopeMetrics\",\n\tupstreamProto: \"gootlpmetrics.ScopeMetrics\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"Scope\",\n\t\t\tprotoID:       1,\n\t\t\treturnMessage: scope,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"Metrics\",\n\t\t\tprotoID:     2,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: metricSlice,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"SchemaUrl\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t},\n}\n\nvar metricSlice = &messageSlice{\n\tstructName:      \"MetricSlice\",\n\telementNullable: true,\n\telement:         metric,\n}\n\nvar metric = &messageStruct{\n\tstructName: \"Metric\",\n\tdescription: \"// Metric represents one metric as a collection of datapoints.\\n\" +\n\t\t\"// See Metric definition in OTLP: https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/metrics/v1/metrics.proto\",\n\tprotoName:     \"Metric\",\n\tupstreamProto: \"gootlpmetrics.Metric\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Name\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Description\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Unit\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t\t&OneOfField{\n\t\t\ttypeName:                   \"MetricType\",\n\t\t\toriginFieldName:            \"Data\",\n\t\t\ttestValueIdx:               1, // Sum\n\t\t\tomitOriginFieldNameInNames: true,\n\t\t\tvalues: []oneOfValue{\n\t\t\t\t&OneOfMessageValue{\n\t\t\t\t\tfieldName:     \"Gauge\",\n\t\t\t\t\tprotoID:       5,\n\t\t\t\t\treturnMessage: gauge,\n\t\t\t\t},\n\t\t\t\t&OneOfMessageValue{\n\t\t\t\t\tfieldName:     \"Sum\",\n\t\t\t\t\tprotoID:       7,\n\t\t\t\t\treturnMessage: sum,\n\t\t\t\t},\n\t\t\t\t&OneOfMessageValue{\n\t\t\t\t\tfieldName:     \"Histogram\",\n\t\t\t\t\tprotoID:       9,\n\t\t\t\t\treturnMessage: histogram,\n\t\t\t\t},\n\t\t\t\t&OneOfMessageValue{\n\t\t\t\t\tfieldName:     \"ExponentialHistogram\",\n\t\t\t\t\tprotoID:       10,\n\t\t\t\t\treturnMessage: exponentialHistogram,\n\t\t\t\t},\n\t\t\t\t&OneOfMessageValue{\n\t\t\t\t\tfieldName:     \"Summary\",\n\t\t\t\t\tprotoID:       11,\n\t\t\t\t\treturnMessage: summary,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"Metadata\",\n\t\t\tprotoID:     12,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: mapStruct,\n\t\t},\n\t},\n}\n\nvar gauge = &messageStruct{\n\tstructName:    \"Gauge\",\n\tdescription:   \"// Gauge represents the type of a numeric metric that always exports the \\\"current value\\\" for every data point.\",\n\tprotoName:     \"Gauge\",\n\tupstreamProto: \"gootlpmetrics.Gauge\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"DataPoints\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: numberDataPointSlice,\n\t\t},\n\t},\n}\n\nvar sum = &messageStruct{\n\tstructName:    \"Sum\",\n\tdescription:   \"// Sum represents the type of a numeric metric that is calculated as a sum of all reported measurements over a time interval.\",\n\tprotoName:     \"Sum\",\n\tupstreamProto: \"gootlpmetrics.Sum\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"DataPoints\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: numberDataPointSlice,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:  \"AggregationTemporality\",\n\t\t\tprotoID:    2,\n\t\t\treturnType: aggregationTemporalityType,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"IsMonotonic\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeBool,\n\t\t},\n\t},\n}\n\nvar histogram = &messageStruct{\n\tstructName:    \"Histogram\",\n\tdescription:   \"// Histogram represents the type of a metric that is calculated by aggregating as a Histogram of all reported measurements over a time interval.\",\n\tprotoName:     \"Histogram\",\n\tupstreamProto: \"gootlpmetrics.Histogram\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"DataPoints\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: histogramDataPointSlice,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:  \"AggregationTemporality\",\n\t\t\tprotoID:    2,\n\t\t\treturnType: aggregationTemporalityType,\n\t\t},\n\t},\n}\n\nvar exponentialHistogram = &messageStruct{\n\tstructName: \"ExponentialHistogram\",\n\tdescription: `// ExponentialHistogram represents the type of a metric that is calculated by aggregating\n\t// as a ExponentialHistogram of all reported double measurements over a time interval.`,\n\tprotoName:     \"ExponentialHistogram\",\n\tupstreamProto: \"gootlpmetrics.ExponentialHistogram\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"DataPoints\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: exponentialHistogramDataPointSlice,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:  \"AggregationTemporality\",\n\t\t\tprotoID:    2,\n\t\t\treturnType: aggregationTemporalityType,\n\t\t},\n\t},\n}\n\nvar summary = &messageStruct{\n\tstructName:    \"Summary\",\n\tdescription:   \"// Summary represents the type of a metric that is calculated by aggregating as a Summary of all reported double measurements over a time interval.\",\n\tprotoName:     \"Summary\",\n\tupstreamProto: \"gootlpmetrics.Summary\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"DataPoints\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: summaryDataPointSlice,\n\t\t},\n\t},\n}\n\nvar numberDataPointSlice = &messageSlice{\n\tstructName:      \"NumberDataPointSlice\",\n\telementNullable: true,\n\telement:         numberDataPoint,\n}\n\nvar numberDataPoint = &messageStruct{\n\tstructName:    \"NumberDataPoint\",\n\tdescription:   \"// NumberDataPoint is a single data point in a timeseries that describes the time-varying value of a number metric.\",\n\tprotoName:     \"NumberDataPoint\",\n\tupstreamProto: \"gootlpmetrics.NumberDataPoint\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"Attributes\",\n\t\t\tprotoID:     7,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: mapStruct,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"StartTimestamp\",\n\t\t\toriginFieldName: \"StartTimeUnixNano\",\n\t\t\tprotoID:         2,\n\t\t\treturnType:      timestampType,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"Timestamp\",\n\t\t\toriginFieldName: \"TimeUnixNano\",\n\t\t\tprotoID:         3,\n\t\t\treturnType:      timestampType,\n\t\t},\n\t\t&OneOfField{\n\t\t\ttypeName:        \"NumberDataPointValueType\",\n\t\t\toriginFieldName: \"Value\",\n\t\t\ttestValueIdx:    0, // Double\n\t\t\tvalues: []oneOfValue{\n\t\t\t\t&OneOfPrimitiveValue{\n\t\t\t\t\tfieldName:       \"Double\",\n\t\t\t\t\tprotoID:         4,\n\t\t\t\t\toriginFieldName: \"AsDouble\",\n\t\t\t\t\tprotoType:       proto.TypeDouble,\n\t\t\t\t},\n\t\t\t\t&OneOfPrimitiveValue{\n\t\t\t\t\tfieldName:       \"Int\",\n\t\t\t\t\tprotoID:         6,\n\t\t\t\t\toriginFieldName: \"AsInt\",\n\t\t\t\t\tprotoType:       proto.TypeSFixed64,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"Exemplars\",\n\t\t\tprotoID:     5,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: exemplarSlice,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName: \"Flags\",\n\t\t\tprotoID:   8,\n\t\t\treturnType: &TypedType{\n\t\t\t\tstructName: \"DataPointFlags\",\n\t\t\t\tprotoType:  proto.TypeUint32,\n\t\t\t\tdefaultVal: \"0\",\n\t\t\t\ttestVal:    \"1\",\n\t\t\t},\n\t\t},\n\t},\n}\n\nvar histogramDataPointSlice = &messageSlice{\n\tstructName:      \"HistogramDataPointSlice\",\n\telementNullable: true,\n\telement:         histogramDataPoint,\n}\n\nvar histogramDataPoint = &messageStruct{\n\tstructName:    \"HistogramDataPoint\",\n\tdescription:   \"// HistogramDataPoint is a single data point in a timeseries that describes the time-varying values of a Histogram of values.\",\n\tprotoName:     \"HistogramDataPoint\",\n\tupstreamProto: \"gootlpmetrics.HistogramDataPoint\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"Attributes\",\n\t\t\tprotoID:     9,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: mapStruct,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"StartTimestamp\",\n\t\t\toriginFieldName: \"StartTimeUnixNano\",\n\t\t\tprotoID:         2,\n\t\t\treturnType:      timestampType,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"Timestamp\",\n\t\t\toriginFieldName: \"TimeUnixNano\",\n\t\t\tprotoID:         3,\n\t\t\treturnType:      timestampType,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Count\",\n\t\t\tprotoID:   4,\n\t\t\tprotoType: proto.TypeFixed64,\n\t\t},\n\t\t&OptionalPrimitiveField{\n\t\t\tfieldName: \"Sum\",\n\t\t\tprotoID:   5,\n\t\t\tprotoType: proto.TypeDouble,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"BucketCounts\",\n\t\t\tprotoID:     6,\n\t\t\tprotoType:   proto.TypeFixed64,\n\t\t\treturnSlice: uInt64Slice,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"ExplicitBounds\",\n\t\t\tprotoID:     7,\n\t\t\tprotoType:   proto.TypeDouble,\n\t\t\treturnSlice: float64Slice,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"Exemplars\",\n\t\t\tprotoID:     8,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: exemplarSlice,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName: \"Flags\",\n\t\t\tprotoID:   10,\n\t\t\treturnType: &TypedType{\n\t\t\t\tstructName: \"DataPointFlags\",\n\t\t\t\tprotoType:  proto.TypeUint32,\n\t\t\t\tdefaultVal: \"0\",\n\t\t\t\ttestVal:    \"1\",\n\t\t\t},\n\t\t},\n\t\t&OptionalPrimitiveField{\n\t\t\tfieldName: \"Min\",\n\t\t\tprotoID:   11,\n\t\t\tprotoType: proto.TypeDouble,\n\t\t},\n\t\t&OptionalPrimitiveField{\n\t\t\tfieldName: \"Max\",\n\t\t\tprotoID:   12,\n\t\t\tprotoType: proto.TypeDouble,\n\t\t},\n\t},\n}\n\nvar exponentialHistogramDataPointSlice = &messageSlice{\n\tstructName:      \"ExponentialHistogramDataPointSlice\",\n\telementNullable: true,\n\telement:         exponentialHistogramDataPoint,\n}\n\nvar exponentialHistogramDataPoint = &messageStruct{\n\tstructName: \"ExponentialHistogramDataPoint\",\n\tdescription: `// ExponentialHistogramDataPoint is a single data point in a timeseries that describes the\n\t// time-varying values of a ExponentialHistogram of double values. A ExponentialHistogram contains\n\t// summary statistics for a population of values, it may optionally contain the\n\t// distribution of those values across a set of buckets.`,\n\tprotoName:     \"ExponentialHistogramDataPoint\",\n\tupstreamProto: \"gootlpmetrics.ExponentialHistogramDataPoint\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"Attributes\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: mapStruct,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"StartTimestamp\",\n\t\t\tprotoID:         2,\n\t\t\toriginFieldName: \"StartTimeUnixNano\",\n\t\t\treturnType:      timestampType,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"Timestamp\",\n\t\t\tprotoID:         3,\n\t\t\toriginFieldName: \"TimeUnixNano\",\n\t\t\treturnType:      timestampType,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Count\",\n\t\t\tprotoID:   4,\n\t\t\tprotoType: proto.TypeFixed64,\n\t\t},\n\t\t&OptionalPrimitiveField{\n\t\t\tfieldName: \"Sum\",\n\t\t\tprotoID:   5,\n\t\t\tprotoType: proto.TypeDouble,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Scale\",\n\t\t\tprotoID:   6,\n\t\t\tprotoType: proto.TypeSInt32,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"ZeroCount\",\n\t\t\tprotoID:   7,\n\t\t\tprotoType: proto.TypeFixed64,\n\t\t},\n\t\t&MessageField{\n\t\t\tfieldName:     \"Positive\",\n\t\t\tprotoID:       8,\n\t\t\treturnMessage: bucketsValues,\n\t\t},\n\t\t&MessageField{\n\t\t\tfieldName:     \"Negative\",\n\t\t\tprotoID:       9,\n\t\t\treturnMessage: bucketsValues,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName: \"Flags\",\n\t\t\tprotoID:   10,\n\t\t\treturnType: &TypedType{\n\t\t\t\tstructName: \"DataPointFlags\",\n\t\t\t\tprotoType:  proto.TypeUint32,\n\t\t\t\tdefaultVal: \"0\",\n\t\t\t\ttestVal:    \"1\",\n\t\t\t},\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"Exemplars\",\n\t\t\tprotoID:     11,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: exemplarSlice,\n\t\t},\n\t\t&OptionalPrimitiveField{\n\t\t\tfieldName: \"Min\",\n\t\t\tprotoID:   12,\n\t\t\tprotoType: proto.TypeDouble,\n\t\t},\n\t\t&OptionalPrimitiveField{\n\t\t\tfieldName: \"Max\",\n\t\t\tprotoID:   13,\n\t\t\tprotoType: proto.TypeDouble,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"ZeroThreshold\",\n\t\t\tprotoID:   14,\n\t\t\tprotoType: proto.TypeDouble,\n\t\t},\n\t},\n}\n\nvar bucketsValues = &messageStruct{\n\tstructName:    \"ExponentialHistogramDataPointBuckets\",\n\tdescription:   \"// ExponentialHistogramDataPointBuckets are a set of bucket counts, encoded in a contiguous array of counts.\",\n\tprotoName:     \"ExponentialHistogramDataPointBuckets\",\n\tupstreamProto: \"gootlpmetrics.ExponentialHistogramDataPoint_Buckets\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Offset\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeSInt32,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"BucketCounts\",\n\t\t\tprotoID:     2,\n\t\t\tprotoType:   proto.TypeUint64,\n\t\t\treturnSlice: uInt64Slice,\n\t\t},\n\t},\n}\n\nvar summaryDataPointSlice = &messageSlice{\n\tstructName:      \"SummaryDataPointSlice\",\n\telementNullable: true,\n\telement:         summaryDataPoint,\n}\n\nvar summaryDataPoint = &messageStruct{\n\tstructName:    \"SummaryDataPoint\",\n\tdescription:   \"// SummaryDataPoint is a single data point in a timeseries that describes the time-varying values of a Summary of double values.\",\n\tprotoName:     \"SummaryDataPoint\",\n\tupstreamProto: \"gootlpmetrics.SummaryDataPoint\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"Attributes\",\n\t\t\tprotoID:     7,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: mapStruct,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"StartTimestamp\",\n\t\t\toriginFieldName: \"StartTimeUnixNano\",\n\t\t\tprotoID:         2,\n\t\t\treturnType:      timestampType,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"Timestamp\",\n\t\t\toriginFieldName: \"TimeUnixNano\",\n\t\t\tprotoID:         3,\n\t\t\treturnType:      timestampType,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Count\",\n\t\t\tprotoID:   4,\n\t\t\tprotoType: proto.TypeFixed64,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Sum\",\n\t\t\tprotoID:   5,\n\t\t\tprotoType: proto.TypeDouble,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"QuantileValues\",\n\t\t\tprotoID:     6,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: quantileValuesSlice,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName: \"Flags\",\n\t\t\tprotoID:   8,\n\t\t\treturnType: &TypedType{\n\t\t\t\tstructName: \"DataPointFlags\",\n\t\t\t\tprotoType:  proto.TypeUint32,\n\t\t\t\tdefaultVal: \"0\",\n\t\t\t\ttestVal:    \"1\",\n\t\t\t},\n\t\t},\n\t},\n}\n\nvar quantileValuesSlice = &messageSlice{\n\tstructName:      \"SummaryDataPointValueAtQuantileSlice\",\n\telementNullable: true,\n\telement:         quantileValues,\n}\n\nvar quantileValues = &messageStruct{\n\tstructName:    \"SummaryDataPointValueAtQuantile\",\n\tdescription:   \"// SummaryDataPointValueAtQuantile is a quantile value within a Summary data point.\",\n\tprotoName:     \"SummaryDataPointValueAtQuantile\",\n\tupstreamProto: \"gootlpmetrics.SummaryDataPoint_ValueAtQuantile\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Quantile\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeDouble,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Value\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeDouble,\n\t\t},\n\t},\n}\n\nvar exemplarSlice = &messageSlice{\n\tstructName:      \"ExemplarSlice\",\n\telementNullable: false,\n\telement:         exemplar,\n}\n\nvar exemplar = &messageStruct{\n\tstructName: \"Exemplar\",\n\tdescription: \"// Exemplar is a sample input double measurement.\\n//\\n\" +\n\t\t\"// Exemplars also hold information about the environment when the measurement was recorded,\\n\" +\n\t\t\"// for example the span and trace ID of the active span when the exemplar was recorded.\",\n\tprotoName:     \"Exemplar\",\n\tupstreamProto: \"gootlpmetrics.Exemplar\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"FilteredAttributes\",\n\t\t\tprotoID:     7,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: mapStruct,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"Timestamp\",\n\t\t\toriginFieldName: \"TimeUnixNano\",\n\t\t\tprotoID:         2,\n\t\t\treturnType:      timestampType,\n\t\t},\n\t\t&OneOfField{\n\t\t\ttypeName:        \"ExemplarValueType\",\n\t\t\toriginFieldName: \"Value\",\n\t\t\ttestValueIdx:    1, // Int\n\t\t\tvalues: []oneOfValue{\n\t\t\t\t&OneOfPrimitiveValue{\n\t\t\t\t\tfieldName:       \"Double\",\n\t\t\t\t\toriginFieldName: \"AsDouble\",\n\t\t\t\t\tprotoID:         3,\n\t\t\t\t\tprotoType:       proto.TypeDouble,\n\t\t\t\t},\n\t\t\t\t&OneOfPrimitiveValue{\n\t\t\t\t\tfieldName:       \"Int\",\n\t\t\t\t\toriginFieldName: \"AsInt\",\n\t\t\t\t\tprotoID:         6,\n\t\t\t\t\tprotoType:       proto.TypeSFixed64,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"TraceID\",\n\t\t\toriginFieldName: \"TraceId\",\n\t\t\tprotoID:         5,\n\t\t\treturnType:      traceIDType,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"SpanID\",\n\t\t\toriginFieldName: \"SpanId\",\n\t\t\tprotoID:         4,\n\t\t\treturnType:      spanIDType,\n\t\t},\n\t},\n}\n\nvar aggregationTemporalityType = &TypedType{\n\tstructName:  \"AggregationTemporality\",\n\tprotoType:   proto.TypeEnum,\n\tmessageName: \"AggregationTemporality\",\n\tdefaultVal:  \"AggregationTemporality(0)\",\n\ttestVal:     \"AggregationTemporality(1)\",\n}\n\nvar aggregationTemporalityEnum = &proto.Enum{\n\tName:        \"AggregationTemporality\",\n\tDescription: \"// AggregationTemporality defines how a metric aggregator reports aggregated values.\\n// It describes how those values relate to the time interval over which they are aggregated.\",\n\tFields: []*proto.EnumField{\n\t\t{Name: \"AGGREGATION_TEMPORALITY_UNSPECIFIED\", Value: 0},\n\t\t{Name: \"AGGREGATION_TEMPORALITY_DELTA\", Value: 1},\n\t\t{Name: \"AGGREGATION_TEMPORALITY_CUMULATIVE\", Value: 2},\n\t},\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/pmetricotlp_package.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\n\nimport (\n\t\"path/filepath\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n)\n\nvar pmetricotlp = &Package{\n\tinfo: &PackageInfo{\n\t\tname: \"pmetricotlp\",\n\t\tpath: filepath.Join(\"pmetric\", \"pmetricotlp\"),\n\t\timports: []string{\n\t\t\t`\"encoding/binary\"`,\n\t\t\t`\"fmt\"`,\n\t\t\t`\"iter\"`,\n\t\t\t`\"math\"`,\n\t\t\t`\"sort\"`,\n\t\t\t`\"sync\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t},\n\t\ttestImports: []string{\n\t\t\t`\"strconv\"`,\n\t\t\t`\"testing\"`,\n\t\t\t``,\n\t\t\t`\"github.com/stretchr/testify/assert\"`,\n\t\t\t`\"github.com/stretchr/testify/require\"`,\n\t\t\t`\"google.golang.org/protobuf/proto\"`,\n\t\t\t`gootlpcollectormetrics \"go.opentelemetry.io/proto/slim/otlp/collector/metrics/v1\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t},\n\t},\n\tstructs: []baseStruct{\n\t\texportMetricsResponse,\n\t\texportMetricsPartialSuccess,\n\t},\n}\n\nvar exportMetricsResponse = &messageStruct{\n\tstructName:    \"ExportResponse\",\n\tdescription:   \"// ExportResponse represents the response for gRPC/HTTP client/server.\",\n\tprotoName:     \"ExportMetricsServiceResponse\",\n\tupstreamProto: \"gootlpcollectormetrics.ExportMetricsServiceResponse\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"PartialSuccess\",\n\t\t\tprotoID:       1,\n\t\t\treturnMessage: exportMetricsPartialSuccess,\n\t\t},\n\t},\n}\n\nvar exportMetricsPartialSuccess = &messageStruct{\n\tstructName:    \"ExportPartialSuccess\",\n\tdescription:   \"// ExportPartialSuccess represents the details of a partially successful export request.\",\n\tprotoName:     \"ExportMetricsPartialSuccess\",\n\tupstreamProto: \"gootlpcollectormetrics.ExportMetricsPartialSuccess\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"RejectedDataPoints\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeInt64,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"ErrorMessage\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t},\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/pprofile_package.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\nimport (\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n)\n\nvar pprofile = &Package{\n\tinfo: &PackageInfo{\n\t\tname: \"pprofile\",\n\t\tpath: \"pprofile\",\n\t\timports: []string{\n\t\t\t`\"encoding/binary\"`,\n\t\t\t`\"fmt\"`,\n\t\t\t`\"iter\"`,\n\t\t\t`\"math\"`,\n\t\t\t`\"sort\"`,\n\t\t\t`\"sync\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/json\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/proto\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/pcommon\"`,\n\t\t},\n\t\ttestImports: []string{\n\t\t\t`\"strconv\"`,\n\t\t\t`\"testing\"`,\n\t\t\t`\"unsafe\"`,\n\t\t\t``,\n\t\t\t`\"github.com/stretchr/testify/assert\"`,\n\t\t\t`\"github.com/stretchr/testify/require\"`,\n\t\t\t`\"google.golang.org/protobuf/proto\"`,\n\t\t\t`gootlpcollectorprofiles \"go.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development\"`,\n\t\t\t`gootlpcommon \"go.opentelemetry.io/proto/slim/otlp/common/v1\"`,\n\t\t\t`gootlpprofiles \"go.opentelemetry.io/proto/slim/otlp/profiles/v1development\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/json\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/pcommon\"`,\n\t\t},\n\t},\n\tstructs: []baseStruct{\n\t\tprofiles,\n\t\tprofilesData,\n\t\tresourceProfilesSlice,\n\t\tresourceProfiles,\n\t\tprofilesDictionary,\n\t\tscopeProfilesSlice,\n\t\tscopeProfiles,\n\t\tprofilesSlice,\n\t\tprofile,\n\t\tvalueTypeSlice,\n\t\tvalueType,\n\t\tsampleSlice,\n\t\tsample,\n\t\tmappingSlice,\n\t\tmapping,\n\t\tlocationSlice,\n\t\tlocation,\n\t\tlineSlice,\n\t\tline,\n\t\tfunctionSlice,\n\t\tfunction,\n\t\tkeyValueAndUnitSlice,\n\t\tkeyValueAndUnit,\n\t\tlinkSlice,\n\t\tlink,\n\t\tstackSlice,\n\t\tstack,\n\t},\n}\n\nvar profiles = &messageStruct{\n\tstructName:    \"Profiles\",\n\tdescription:   \"// Profiles is the top-level struct that is propagated through the profiles pipeline.\\n// Use NewProfiles to create new instance, zero-initialized instance is not valid for use.\",\n\tprotoName:     \"ExportProfilesServiceRequest\",\n\tupstreamProto: \"gootlpcollectorprofiles.ExportProfilesServiceRequest\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"ResourceProfiles\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: resourceProfilesSlice,\n\t\t},\n\t\t&MessageField{\n\t\t\tfieldName:     \"Dictionary\",\n\t\t\tprotoID:       2,\n\t\t\treturnMessage: profilesDictionary,\n\t\t},\n\t},\n\thasWrapper: true,\n}\n\nvar profilesData = &messageStruct{\n\tstructName:    \"ProfilesData\",\n\tdescription:   \"// ProfilesData represents the profiles data that can be stored in persistent storage,\\n// OR can be embedded by other protocols that transfer OTLP profiles data but do not\\n// implement the OTLP protocol.\",\n\tprotoName:     \"ProfilesData\",\n\tupstreamProto: \"gootlpprofiles.ProfilesData\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"ResourceProfiles\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: resourceProfilesSlice,\n\t\t},\n\t\t&MessageField{\n\t\t\tfieldName:     \"Dictionary\",\n\t\t\tprotoID:       2,\n\t\t\treturnMessage: profilesDictionary,\n\t\t},\n\t},\n\thasWrapper: true,\n}\n\nvar resourceProfilesSlice = &messageSlice{\n\tstructName:      \"ResourceProfilesSlice\",\n\telementNullable: true,\n\telement:         resourceProfiles,\n}\n\nvar resourceProfiles = &messageStruct{\n\tstructName:    \"ResourceProfiles\",\n\tdescription:   \"// ResourceProfiles is a collection of profiles from a Resource.\",\n\tprotoName:     \"ResourceProfiles\",\n\tupstreamProto: \"gootlpprofiles.ResourceProfiles\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"Resource\",\n\t\t\tprotoID:       1,\n\t\t\treturnMessage: resource,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"ScopeProfiles\",\n\t\t\tprotoID:     2,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: scopeProfilesSlice,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"SchemaUrl\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t},\n}\n\nvar profilesDictionary = &messageStruct{\n\tstructName:    \"ProfilesDictionary\",\n\tdescription:   \"// ProfilesDictionary is the reference table containing all data shared by profiles across the message being sent.\",\n\tprotoName:     \"ProfilesDictionary\",\n\tupstreamProto: \"gootlpprofiles.ProfilesDictionary\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"MappingTable\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: mappingSlice,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"LocationTable\",\n\t\t\tprotoID:     2,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: locationSlice,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"FunctionTable\",\n\t\t\tprotoID:     3,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: functionSlice,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"LinkTable\",\n\t\t\tprotoID:     4,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: linkSlice,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"StringTable\",\n\t\t\tprotoID:     5,\n\t\t\tprotoType:   proto.TypeString,\n\t\t\treturnSlice: stringSlice,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"AttributeTable\",\n\t\t\tprotoID:     6,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: keyValueAndUnitSlice,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"StackTable\",\n\t\t\tprotoID:     7,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: stackSlice,\n\t\t},\n\t},\n}\n\nvar scopeProfilesSlice = &messageSlice{\n\tstructName:      \"ScopeProfilesSlice\",\n\telementNullable: true,\n\telement:         scopeProfiles,\n}\n\nvar scopeProfiles = &messageStruct{\n\tstructName:    \"ScopeProfiles\",\n\tdescription:   \"// ScopeProfiles is a collection of profiles from a LibraryInstrumentation.\",\n\tprotoName:     \"ScopeProfiles\",\n\tupstreamProto: \"gootlpprofiles.ScopeProfiles\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"Scope\",\n\t\t\tprotoID:       1,\n\t\t\treturnMessage: scope,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"Profiles\",\n\t\t\tprotoID:     2,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: profilesSlice,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"SchemaUrl\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t},\n}\n\nvar profilesSlice = &messageSlice{\n\tstructName:      \"ProfilesSlice\",\n\telementNullable: true,\n\telement:         profile,\n}\n\nvar profile = &messageStruct{\n\tstructName:    \"Profile\",\n\tdescription:   \"// Profile are an implementation of the pprofextended data model.\\n\",\n\tprotoName:     \"Profile\",\n\tupstreamProto: \"gootlpprofiles.Profile\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"SampleType\",\n\t\t\tprotoID:       1,\n\t\t\treturnMessage: valueType,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"Samples\",\n\t\t\tprotoID:     2,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: sampleSlice,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"Time\",\n\t\t\toriginFieldName: \"TimeUnixNano\",\n\t\t\tprotoID:         3,\n\t\t\treturnType:      timestampType,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"DurationNano\",\n\t\t\tprotoID:   4,\n\t\t\tprotoType: proto.TypeUint64,\n\t\t},\n\t\t&MessageField{\n\t\t\tfieldName:     \"PeriodType\",\n\t\t\tprotoID:       5,\n\t\t\treturnMessage: valueType,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Period\",\n\t\t\tprotoID:   6,\n\t\t\tprotoType: proto.TypeInt64,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"ProfileID\",\n\t\t\toriginFieldName: \"ProfileId\",\n\t\t\tprotoID:         7,\n\t\t\treturnType: &TypedType{\n\t\t\t\tstructName:  \"ProfileID\",\n\t\t\t\tprotoType:   proto.TypeMessage,\n\t\t\t\tmessageName: \"ProfileID\",\n\t\t\t\tdefaultVal:  \"ProfileID([16]byte{})\",\n\t\t\t\ttestVal:     \"ProfileID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1})\",\n\t\t\t},\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"DroppedAttributesCount\",\n\t\t\tprotoID:   8,\n\t\t\tprotoType: proto.TypeUint32,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"OriginalPayloadFormat\",\n\t\t\tprotoID:   9,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"OriginalPayload\",\n\t\t\tprotoID:     10,\n\t\t\tprotoType:   proto.TypeBytes,\n\t\t\treturnSlice: byteSlice,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"AttributeIndices\",\n\t\t\tprotoID:     11,\n\t\t\tprotoType:   proto.TypeInt32,\n\t\t\treturnSlice: int32Slice,\n\t\t},\n\t},\n}\n\nvar keyValueAndUnitSlice = &messageSlice{\n\tstructName:      \"KeyValueAndUnitSlice\",\n\telementNullable: true,\n\telement:         keyValueAndUnit,\n}\n\nvar keyValueAndUnit = &messageStruct{\n\tstructName: \"KeyValueAndUnit\",\n\tdescription: `// KeyValueAndUnit represents a custom 'dictionary native'\n\t// style of encoding attributes which is more convenient\n\t// for profiles than opentelemetry.proto.common.v1.KeyValue.`,\n\tprotoName:     \"KeyValueAndUnit\",\n\tupstreamProto: \"gootlpprofiles.KeyValueAndUnit\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"KeyStrindex\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeInt32,\n\t\t},\n\t\t&MessageField{\n\t\t\tfieldName:     \"Value\",\n\t\t\tprotoID:       2,\n\t\t\treturnMessage: anyValueStruct,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"UnitStrindex\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeInt32,\n\t\t},\n\t},\n}\n\nvar linkSlice = &messageSlice{\n\tstructName:      \"LinkSlice\",\n\telementNullable: true,\n\telement:         link,\n}\n\nvar link = &messageStruct{\n\tstructName:    \"Link\",\n\tdescription:   \"// Link represents a pointer from a profile Sample to a trace Span.\",\n\tprotoName:     \"Link\",\n\tupstreamProto: \"gootlpprofiles.Link\",\n\tfields: []Field{\n\t\t&TypedField{\n\t\t\tfieldName:       \"TraceID\",\n\t\t\toriginFieldName: \"TraceId\",\n\t\t\tprotoID:         1,\n\t\t\treturnType:      traceIDType,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"SpanID\",\n\t\t\toriginFieldName: \"SpanId\",\n\t\t\tprotoID:         2,\n\t\t\treturnType:      spanIDType,\n\t\t},\n\t},\n}\n\nvar valueTypeSlice = &messageSlice{\n\tstructName:      \"ValueTypeSlice\",\n\telementNullable: true,\n\telement:         valueType,\n}\n\nvar valueType = &messageStruct{\n\tstructName:    \"ValueType\",\n\tdescription:   \"// ValueType describes the type and units of a value.\",\n\tprotoName:     \"ValueType\",\n\tupstreamProto: \"gootlpprofiles.ValueType\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"TypeStrindex\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeInt32,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"UnitStrindex\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeInt32,\n\t\t},\n\t},\n}\n\nvar sampleSlice = &messageSlice{\n\tstructName:      \"SampleSlice\",\n\telementNullable: true,\n\telement:         sample,\n}\n\nvar sample = &messageStruct{\n\tstructName:    \"Sample\",\n\tdescription:   \"// Sample represents each record value encountered within a profiled program.\",\n\tprotoName:     \"Sample\",\n\tupstreamProto: \"gootlpprofiles.Sample\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"StackIndex\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeInt32,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"AttributeIndices\",\n\t\t\tprotoID:     2,\n\t\t\tprotoType:   proto.TypeInt32,\n\t\t\treturnSlice: int32Slice,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"LinkIndex\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeInt32,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"Values\",\n\t\t\tprotoID:     4,\n\t\t\tprotoType:   proto.TypeInt64,\n\t\t\treturnSlice: int64Slice,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"TimestampsUnixNano\",\n\t\t\tprotoID:     5,\n\t\t\tprotoType:   proto.TypeFixed64,\n\t\t\treturnSlice: uInt64Slice,\n\t\t},\n\t},\n}\n\nvar mappingSlice = &messageSlice{\n\tstructName:      \"MappingSlice\",\n\telementNullable: true,\n\telement:         mapping,\n}\n\nvar mapping = &messageStruct{\n\tstructName:    \"Mapping\",\n\tdescription:   \"// Mapping describes the mapping of a binary in memory, including its address range, file offset, and metadata like build ID\",\n\tprotoName:     \"Mapping\",\n\tupstreamProto: \"gootlpprofiles.Mapping\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"MemoryStart\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeUint64,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"MemoryLimit\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeUint64,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"FileOffset\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeUint64,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"FilenameStrindex\",\n\t\t\tprotoID:   4,\n\t\t\tprotoType: proto.TypeInt32,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"AttributeIndices\",\n\t\t\tprotoID:     5,\n\t\t\tprotoType:   proto.TypeInt32,\n\t\t\treturnSlice: int32Slice,\n\t\t},\n\t},\n}\n\nvar locationSlice = &messageSlice{\n\tstructName:      \"LocationSlice\",\n\telementNullable: true,\n\telement:         location,\n}\n\nvar location = &messageStruct{\n\tstructName:    \"Location\",\n\tdescription:   \"// Location describes function and line table debug information.\",\n\tprotoName:     \"Location\",\n\tupstreamProto: \"gootlpprofiles.Location\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"MappingIndex\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeInt32,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Address\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeUint64,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"Lines\",\n\t\t\tprotoID:     3,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: lineSlice,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"AttributeIndices\",\n\t\t\tprotoID:     4,\n\t\t\tprotoType:   proto.TypeInt32,\n\t\t\treturnSlice: int32Slice,\n\t\t},\n\t},\n}\n\nvar lineSlice = &messageSlice{\n\tstructName:      \"LineSlice\",\n\telementNullable: true,\n\telement:         line,\n}\n\nvar line = &messageStruct{\n\tstructName:    \"Line\",\n\tdescription:   \"// Line details a specific line in a source code, linked to a function.\",\n\tprotoName:     \"Line\",\n\tupstreamProto: \"gootlpprofiles.Line\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"FunctionIndex\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeInt32,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Line\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeInt64,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Column\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeInt64,\n\t\t},\n\t},\n}\n\nvar functionSlice = &messageSlice{\n\tstructName:      \"FunctionSlice\",\n\telementNullable: true,\n\telement:         function,\n}\n\nvar function = &messageStruct{\n\tstructName:    \"Function\",\n\tdescription:   \"// Function describes a function, including its human-readable name, system name, source file, and starting line number in the source.\",\n\tprotoName:     \"Function\",\n\tupstreamProto: \"gootlpprofiles.Function\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"NameStrindex\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeInt32,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"SystemNameStrindex\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeInt32,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"FilenameStrindex\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeInt32,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"StartLine\",\n\t\t\tprotoID:   4,\n\t\t\tprotoType: proto.TypeInt64,\n\t\t},\n\t},\n}\n\nvar stackSlice = &messageSlice{\n\tstructName:      \"StackSlice\",\n\telementNullable: true,\n\telement:         stack,\n}\n\nvar stack = &messageStruct{\n\tstructName:    \"Stack\",\n\tdescription:   \"// Stack represents a stack trace as a list of locations.\\n\",\n\tprotoName:     \"Stack\",\n\tupstreamProto: \"gootlpprofiles.Stack\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"LocationIndices\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeInt32,\n\t\t\treturnSlice: int32Slice,\n\t\t},\n\t},\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/pprofileotlp_package.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\nimport (\n\t\"path/filepath\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n)\n\nvar pprofileotlp = &Package{\n\tinfo: &PackageInfo{\n\t\tname: \"pprofileotlp\",\n\t\tpath: filepath.Join(\"pprofile\", \"pprofileotlp\"),\n\t\timports: []string{\n\t\t\t`\"encoding/binary\"`,\n\t\t\t`\"fmt\"`,\n\t\t\t`\"iter\"`,\n\t\t\t`\"math\"`,\n\t\t\t`\"sort\"`,\n\t\t\t`\"sync\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t},\n\t\ttestImports: []string{\n\t\t\t`\"strconv\"`,\n\t\t\t`\"testing\"`,\n\t\t\t``,\n\t\t\t`\"github.com/stretchr/testify/assert\"`,\n\t\t\t`\"github.com/stretchr/testify/require\"`,\n\t\t\t`\"google.golang.org/protobuf/proto\"`,\n\t\t\t`gootlpcollectorprofiles \"go.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t},\n\t},\n\tstructs: []baseStruct{\n\t\texportProfilesResponse,\n\t\texportProfilesPartialSuccess,\n\t},\n}\n\nvar exportProfilesResponse = &messageStruct{\n\tstructName:    \"ExportResponse\",\n\tdescription:   \"// ExportResponse represents the response for gRPC/HTTP client/server.\",\n\tprotoName:     \"ExportProfilesServiceResponse\",\n\tupstreamProto: \"gootlpcollectorprofiles.ExportProfilesServiceResponse\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"PartialSuccess\",\n\t\t\tprotoID:       1,\n\t\t\treturnMessage: exportProfilesPartialSuccess,\n\t\t},\n\t},\n}\n\nvar exportProfilesPartialSuccess = &messageStruct{\n\tstructName:    \"ExportPartialSuccess\",\n\tdescription:   \"// ExportPartialSuccess represents the details of a partially successful export request.\",\n\tprotoName:     \"ExportProfilesPartialSuccess\",\n\tupstreamProto: \"gootlpcollectorprofiles.ExportProfilesPartialSuccess\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"RejectedProfiles\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeInt64,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"ErrorMessage\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t},\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/primitive_field.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\n\nimport (\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst primitiveAccessorsTemplate = `// {{ .fieldName }} returns the {{ .lowerFieldName }} associated with this {{ .structName }}.\nfunc (ms {{ .structName }}) {{ .fieldName }}() {{ .packageName }}{{ .returnType }} {\n\treturn ms.{{ .origAccessor }}.{{ .originFieldName }}\n}\n\n// Set{{ .fieldName }} replaces the {{ .lowerFieldName }} associated with this {{ .structName }}.\nfunc (ms {{ .structName }}) Set{{ .fieldName }}(v {{ .returnType }}) {\n\tms.{{ .stateAccessor }}.AssertMutable()\n\tms.{{ .origAccessor }}.{{ .originFieldName }} = v\n}`\n\nconst primitiveAccessorsTestTemplate = `func Test{{ .structName }}_{{ .fieldName }}(t *testing.T) {\n\tms := New{{ .structName }}()\n\t{{- if eq .returnType \"bool\" }}\n\tassert.{{- if eq .defaultVal \"true\" }}True{{- else }}False{{- end }}(t, ms.{{ .fieldName }}())\n\t{{- else if eq .returnType \"float64\" }}\n\tassert.InDelta(t, {{ .defaultVal }}, ms.{{ .fieldName }}(), 0.01)\n\t{{- else if and (eq .returnType \"string\") (eq .defaultVal \"\\\"\\\"\") }}\n\tassert.Empty(t, ms.{{ .fieldName }}())\n\t{{- else }}\n\tassert.Equal(t, {{ .defaultVal }}, ms.{{ .fieldName }}())\n\t{{- end }}\n\tms.Set{{ .fieldName }}({{ .testValue }})\n\t{{- if eq .returnType \"bool\" }}\n\tassert.{{- if eq .testValue \"true\" }}True{{- else }}False{{- end }}(t, ms.{{ .fieldName }}())\n\t{{- else if eq .returnType \"float64\"}}\n\tassert.InDelta(t, {{ .testValue }}, ms.{{ .fieldName }}(), 0.01)\n\t{{- else if and (eq .returnType \"string\") (eq .testValue \"\\\"\\\"\") }}\n\tassert.Empty(t, ms.{{ .fieldName }}())\n\t{{- else }}\n\tassert.Equal(t, {{ .testValue }}, ms.{{ .fieldName }}())\n\t{{- end }}\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { new{{ .structName }}(internal.New{{ .originStructName }}(), sharedState).Set{{ .fieldName }}({{ .testValue }}) })\n}`\n\nconst primitiveSetTestTemplate = `orig.{{ .originFieldName }} = {{ .testValue }}`\n\ntype PrimitiveField struct {\n\tfieldName string\n\tprotoType proto.Type\n\tprotoID   uint32\n}\n\nfunc (pf *PrimitiveField) GenerateAccessors(ms *messageStruct) string {\n\tt := tmplutil.Parse(\"primitiveAccessorsTemplate\", []byte(primitiveAccessorsTemplate))\n\treturn tmplutil.Execute(t, pf.templateFields(ms))\n}\n\nfunc (pf *PrimitiveField) GenerateAccessorsTest(ms *messageStruct) string {\n\tt := tmplutil.Parse(\"primitiveAccessorsTestTemplate\", []byte(primitiveAccessorsTestTemplate))\n\treturn tmplutil.Execute(t, pf.templateFields(ms))\n}\n\nfunc (pf *PrimitiveField) GenerateTestValue(ms *messageStruct) string {\n\tt := tmplutil.Parse(\"primitiveSetTestTemplate\", []byte(primitiveSetTestTemplate))\n\treturn tmplutil.Execute(t, pf.templateFields(ms))\n}\n\nfunc (pf *PrimitiveField) toProtoField(*messageStruct) proto.FieldInterface {\n\treturn &proto.Field{\n\t\tType: pf.protoType,\n\t\tID:   pf.protoID,\n\t\tName: pf.fieldName,\n\t}\n}\n\nfunc (pf *PrimitiveField) templateFields(ms *messageStruct) map[string]any {\n\tprf := pf.toProtoField(ms)\n\treturn map[string]any{\n\t\t\"structName\":       ms.getName(),\n\t\t\"packageName\":      \"\",\n\t\t\"defaultVal\":       prf.DefaultValue(),\n\t\t\"fieldName\":        pf.fieldName,\n\t\t\"lowerFieldName\":   strings.ToLower(pf.fieldName),\n\t\t\"testValue\":        prf.TestValue(),\n\t\t\"returnType\":       prf.GoType(),\n\t\t\"origAccessor\":     origAccessor(ms.getHasWrapper()),\n\t\t\"stateAccessor\":    stateAccessor(ms.getHasWrapper()),\n\t\t\"originStructName\": ms.protoName,\n\t\t\"originFieldName\":  pf.fieldName,\n\t}\n}\n\nvar _ Field = (*PrimitiveField)(nil)\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/primitive_slice_structs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\n\nimport (\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\n// primitiveSliceStruct generates a struct for a slice of primitive value elements. The structs are always generated\n// in a way that they can be used as fields in structs from other packages (using the internal package).\ntype primitiveSliceStruct struct {\n\tstructName  string\n\tpackageName string\n\titemType    string\n\n\ttestOrigVal          string\n\ttestInterfaceOrigVal []any\n\ttestSetVal           string\n\ttestNewVal           string\n}\n\nfunc (iss *primitiveSliceStruct) getName() string {\n\treturn iss.structName\n}\n\nfunc (iss *primitiveSliceStruct) getPackageName() string {\n\treturn iss.packageName\n}\n\nfunc (iss *primitiveSliceStruct) generate(packageInfo *PackageInfo) []byte {\n\treturn []byte(tmplutil.Execute(primitiveSliceTemplate, iss.templateFields(packageInfo)))\n}\n\nfunc (iss *primitiveSliceStruct) generateTests(packageInfo *PackageInfo) []byte {\n\treturn []byte(tmplutil.Execute(primitiveSliceTestTemplate, iss.templateFields(packageInfo)))\n}\n\nfunc (iss *primitiveSliceStruct) generateInternal(packageInfo *PackageInfo) []byte {\n\treturn []byte(tmplutil.Execute(primitiveSliceInternalTemplate, iss.templateFields(packageInfo)))\n}\n\nfunc (iss *primitiveSliceStruct) getOriginName() string {\n\treturn iss.getName()\n}\n\nfunc (iss *primitiveSliceStruct) getOriginFullName() string {\n\treturn iss.getName()\n}\n\nfunc (iss *primitiveSliceStruct) getHasWrapper() bool {\n\treturn usedByOtherDataTypes(iss.packageName)\n}\n\nfunc (iss *primitiveSliceStruct) getHasOnlyInternal() bool {\n\treturn false\n}\n\nfunc (iss *primitiveSliceStruct) getElementOriginName() string {\n\treturn upperFirst(iss.itemType)\n}\n\nfunc (iss *primitiveSliceStruct) getElementNullable() bool {\n\treturn false\n}\n\nfunc (iss *primitiveSliceStruct) getProtoMessage() *proto.Message {\n\treturn nil\n}\n\nfunc (iss *primitiveSliceStruct) templateFields(packageInfo *PackageInfo) map[string]any {\n\treturn map[string]any{\n\t\t\"structName\":           iss.getName(),\n\t\t\"itemType\":             iss.itemType,\n\t\t\"elementOriginName\":    iss.getElementOriginName(),\n\t\t\"lowerStructName\":      strings.ToLower(iss.structName[:1]) + iss.structName[1:],\n\t\t\"testOrigVal\":          iss.testOrigVal,\n\t\t\"testInterfaceOrigVal\": iss.testInterfaceOrigVal,\n\t\t\"testSetVal\":           iss.testSetVal,\n\t\t\"testNewVal\":           iss.testNewVal,\n\t\t\"packageName\":          packageInfo.name,\n\t\t\"imports\":              packageInfo.imports,\n\t\t\"testImports\":          packageInfo.testImports,\n\t}\n}\n\nfunc upperFirst(s string) string {\n\treturn strings.ToUpper(s[0:1]) + s[1:]\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/ptrace_package.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\nimport (\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n)\n\nvar ptrace = &Package{\n\tinfo: &PackageInfo{\n\t\tname: \"ptrace\",\n\t\tpath: \"ptrace\",\n\t\timports: []string{\n\t\t\t`\"encoding/binary\"`,\n\t\t\t`\"fmt\"`,\n\t\t\t`\"iter\"`,\n\t\t\t`\"math\"`,\n\t\t\t`\"sort\"`,\n\t\t\t`\"sync\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/json\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/proto\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/pcommon\"`,\n\t\t},\n\t\ttestImports: []string{\n\t\t\t`\"strconv\"`,\n\t\t\t`\"testing\"`,\n\t\t\t`\"unsafe\"`,\n\t\t\t``,\n\t\t\t`\"github.com/stretchr/testify/assert\"`,\n\t\t\t`\"github.com/stretchr/testify/require\"`,\n\t\t\t`\"google.golang.org/protobuf/proto\"`,\n\t\t\t`gootlpcollectortrace \"go.opentelemetry.io/proto/slim/otlp/collector/trace/v1\"`,\n\t\t\t`gootlptrace \"go.opentelemetry.io/proto/slim/otlp/trace/v1\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/json\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/pcommon\"`,\n\t\t},\n\t},\n\tstructs: []baseStruct{\n\t\ttraces,\n\t\ttracesData,\n\t\tresourceSpansSlice,\n\t\tresourceSpans,\n\t\tscopeSpansSlice,\n\t\tscopeSpans,\n\t\tspanSlice,\n\t\tspan,\n\t\tspanEventSlice,\n\t\tspanEvent,\n\t\tspanLinkSlice,\n\t\tspanLink,\n\t\tspanStatus,\n\t},\n\tenums: []*proto.Enum{\n\t\tspanKindEnum,\n\t\tstatusCodeEnum,\n\t},\n}\n\nvar traces = &messageStruct{\n\tstructName:    \"Traces\",\n\tdescription:   \"// Traces is the top-level struct that is propagated through the traces pipeline.\\n// Use NewTraces to create new instance, zero-initialized instance is not valid for use.\",\n\tprotoName:     \"ExportTraceServiceRequest\",\n\tupstreamProto: \"gootlpcollectortrace.ExportTraceServiceRequest\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"ResourceSpans\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: resourceSpansSlice,\n\t\t},\n\t},\n\thasWrapper: true,\n}\n\nvar tracesData = &messageStruct{\n\tstructName:    \"TracesData\",\n\tdescription:   \"// TracesData represents the traces data that can be stored in a persistent storage,\\n// OR can be embedded by other protocols that transfer OTLP traces data but do not\\n// implement the OTLP protocol.\",\n\tprotoName:     \"TracesData\",\n\tupstreamProto: \"gootlptrace.TracesData\",\n\tfields: []Field{\n\t\t&SliceField{\n\t\t\tfieldName:   \"ResourceSpans\",\n\t\t\tprotoID:     1,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: resourceSpansSlice,\n\t\t},\n\t},\n\thasOnlyInternal: true,\n}\n\nvar resourceSpansSlice = &messageSlice{\n\tstructName:      \"ResourceSpansSlice\",\n\telementNullable: true,\n\telement:         resourceSpans,\n}\n\nvar resourceSpans = &messageStruct{\n\tstructName:    \"ResourceSpans\",\n\tdescription:   \"// ResourceSpans is a collection of spans from a Resource.\",\n\tprotoName:     \"ResourceSpans\",\n\tupstreamProto: \"gootlptrace.ResourceSpans\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"Resource\",\n\t\t\tprotoID:       1,\n\t\t\treturnMessage: resource,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"ScopeSpans\",\n\t\t\tprotoID:     2,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: scopeSpansSlice,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"SchemaUrl\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"DeprecatedScopeSpans\",\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\tprotoID:     1000,\n\t\t\treturnSlice: scopeSpansSlice,\n\t\t\t// Hide accessors for this field because it is a HACK:\n\t\t\t// Workaround for istio 1.15 / envoy 1.23.1 mistakenly emitting deprecated field.\n\t\t\thideAccessors: true,\n\t\t},\n\t},\n}\n\nvar scopeSpansSlice = &messageSlice{\n\tstructName:      \"ScopeSpansSlice\",\n\telementNullable: true,\n\telement:         scopeSpans,\n}\n\nvar scopeSpans = &messageStruct{\n\tstructName:    \"ScopeSpans\",\n\tdescription:   \"// ScopeSpans is a collection of spans from a LibraryInstrumentation.\",\n\tprotoName:     \"ScopeSpans\",\n\tupstreamProto: \"gootlptrace.ScopeSpans\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"Scope\",\n\t\t\tprotoID:       1,\n\t\t\treturnMessage: scope,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"Spans\",\n\t\t\tprotoID:     2,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: spanSlice,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"SchemaUrl\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t},\n}\n\nvar spanSlice = &messageSlice{\n\tstructName:      \"SpanSlice\",\n\telementNullable: true,\n\telement:         span,\n}\n\nvar span = &messageStruct{\n\tstructName: \"Span\",\n\tdescription: \"// Span represents a single operation within a trace.\\n\" +\n\t\t\"// See Span definition in OTLP: https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/trace/v1/trace.proto\",\n\tprotoName:     \"Span\",\n\tupstreamProto: \"gootlptrace.Span\",\n\tfields: []Field{\n\t\t&TypedField{\n\t\t\tfieldName:       \"TraceID\",\n\t\t\toriginFieldName: \"TraceId\",\n\t\t\tprotoID:         1,\n\t\t\treturnType:      traceIDType,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"SpanID\",\n\t\t\toriginFieldName: \"SpanId\",\n\t\t\tprotoID:         2,\n\t\t\treturnType:      spanIDType,\n\t\t},\n\t\t&MessageField{\n\t\t\tfieldName:     \"TraceState\",\n\t\t\tprotoID:       3,\n\t\t\treturnMessage: traceState,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"ParentSpanID\",\n\t\t\toriginFieldName: \"ParentSpanId\",\n\t\t\tprotoID:         4,\n\t\t\treturnType:      spanIDType,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Flags\",\n\t\t\tprotoID:   16,\n\t\t\tprotoType: proto.TypeFixed32,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Name\",\n\t\t\tprotoID:   5,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName: \"Kind\",\n\t\t\tprotoID:   6,\n\t\t\treturnType: &TypedType{\n\t\t\t\tstructName:  \"SpanKind\",\n\t\t\t\tprotoType:   proto.TypeEnum,\n\t\t\t\tmessageName: \"SpanKind\",\n\t\t\t\tdefaultVal:  \"SpanKind_SPAN_KIND_UNSPECIFIED\",\n\t\t\t\ttestVal:     \"SpanKind_SPAN_KIND_CLIENT\",\n\t\t\t},\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"StartTimestamp\",\n\t\t\toriginFieldName: \"StartTimeUnixNano\",\n\t\t\tprotoID:         7,\n\t\t\treturnType:      timestampType,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"EndTimestamp\",\n\t\t\toriginFieldName: \"EndTimeUnixNano\",\n\t\t\tprotoID:         8,\n\t\t\treturnType:      timestampType,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"Attributes\",\n\t\t\tprotoID:     9,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: mapStruct,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"DroppedAttributesCount\",\n\t\t\tprotoID:   10,\n\t\t\tprotoType: proto.TypeUint32,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"Events\",\n\t\t\tprotoID:     11,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: spanEventSlice,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"DroppedEventsCount\",\n\t\t\tprotoID:   12,\n\t\t\tprotoType: proto.TypeUint32,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"Links\",\n\t\t\tprotoID:     13,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: spanLinkSlice,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"DroppedLinksCount\",\n\t\t\tprotoID:   14,\n\t\t\tprotoType: proto.TypeUint32,\n\t\t},\n\t\t&MessageField{\n\t\t\tfieldName:     \"Status\",\n\t\t\tprotoID:       15,\n\t\t\treturnMessage: spanStatus,\n\t\t},\n\t},\n}\n\nvar spanEventSlice = &messageSlice{\n\tstructName:      \"SpanEventSlice\",\n\telementNullable: true,\n\telement:         spanEvent,\n}\n\nvar spanEvent = &messageStruct{\n\tstructName: \"SpanEvent\",\n\tdescription: \"// SpanEvent is a time-stamped annotation of the span, consisting of user-supplied\\n\" +\n\t\t\"// text description and key-value pairs. See OTLP for event definition.\",\n\tprotoName:     \"SpanEvent\",\n\tupstreamProto: \"gootlptrace.Span_Event\",\n\tfields: []Field{\n\t\t&TypedField{\n\t\t\tfieldName:       \"Timestamp\",\n\t\t\toriginFieldName: \"TimeUnixNano\",\n\t\t\tprotoID:         1,\n\t\t\treturnType:      timestampType,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Name\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"Attributes\",\n\t\t\tprotoID:     3,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: mapStruct,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"DroppedAttributesCount\",\n\t\t\tprotoID:   4,\n\t\t\tprotoType: proto.TypeUint32,\n\t\t},\n\t},\n}\n\nvar spanLinkSlice = &messageSlice{\n\tstructName:      \"SpanLinkSlice\",\n\telementNullable: true,\n\telement:         spanLink,\n}\n\nvar spanLink = &messageStruct{\n\tstructName: \"SpanLink\",\n\tdescription: \"// SpanLink is a pointer from the current span to another span in the same trace or in a\\n\" +\n\t\t\"// different trace.\\n\" +\n\t\t\"// See Link definition in OTLP: https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/trace/v1/trace.proto\",\n\tprotoName:     \"SpanLink\",\n\tupstreamProto: \"gootlptrace.Span_Link\",\n\tfields: []Field{\n\t\t&TypedField{\n\t\t\tfieldName:       \"TraceID\",\n\t\t\toriginFieldName: \"TraceId\",\n\t\t\tprotoID:         1,\n\t\t\treturnType:      traceIDType,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:       \"SpanID\",\n\t\t\toriginFieldName: \"SpanId\",\n\t\t\tprotoID:         2,\n\t\t\treturnType:      spanIDType,\n\t\t},\n\t\t&MessageField{\n\t\t\tfieldName:     \"TraceState\",\n\t\t\tprotoID:       3,\n\t\t\treturnMessage: traceState,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"Attributes\",\n\t\t\tprotoID:     4,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: mapStruct,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"DroppedAttributesCount\",\n\t\t\tprotoID:   5,\n\t\t\tprotoType: proto.TypeUint32,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Flags\",\n\t\t\tprotoID:   6,\n\t\t\tprotoType: proto.TypeFixed32,\n\t\t},\n\t},\n}\n\nvar spanStatus = &messageStruct{\n\tstructName: \"Status\",\n\tdescription: \"// Status is an optional final status for this span. Semantically, when Status was not\\n\" +\n\t\t\"// set, that means the span ended without errors and to assume Status.Ok (code = 0).\",\n\tprotoName:     \"Status\",\n\tupstreamProto: \"gootlptrace.Status\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Message\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName: \"Code\",\n\t\t\tprotoID:   3,\n\t\t\treturnType: &TypedType{\n\t\t\t\tstructName:  \"StatusCode\",\n\t\t\t\tprotoType:   proto.TypeEnum,\n\t\t\t\tmessageName: \"StatusCode\",\n\t\t\t\tdefaultVal:  \"StatusCode_STATUS_CODE_UNSET\",\n\t\t\t\ttestVal:     \"StatusCode_STATUS_CODE_OK\",\n\t\t\t},\n\t\t},\n\t},\n}\n\nvar spanKindEnum = &proto.Enum{\n\tName:        \"SpanKind\",\n\tDescription: \"// SpanKind is the type of span.\\n// Can be used to specify additional relationships between spans in addition to a parent/child relationship.\",\n\tFields: []*proto.EnumField{\n\t\t{Name: \"SPAN_KIND_UNSPECIFIED\", Value: 0},\n\t\t{Name: \"SPAN_KIND_INTERNAL\", Value: 1},\n\t\t{Name: \"SPAN_KIND_SERVER\", Value: 2},\n\t\t{Name: \"SPAN_KIND_CLIENT\", Value: 3},\n\t\t{Name: \"SPAN_KIND_PRODUCER\", Value: 4},\n\t\t{Name: \"SPAN_KIND_CONSUMER\", Value: 5},\n\t},\n}\n\nvar statusCodeEnum = &proto.Enum{\n\tName:        \"StatusCode\",\n\tDescription: \"// StatusCode is the status of the span, for the semantics of codes see\\n// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#set-status\",\n\tFields: []*proto.EnumField{\n\t\t{Name: \"STATUS_CODE_UNSET\", Value: 0},\n\t\t{Name: \"STATUS_CODE_OK\", Value: 1},\n\t\t{Name: \"STATUS_CODE_ERROR\", Value: 2},\n\t},\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/ptraceotlp_package.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\n\nimport (\n\t\"path/filepath\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n)\n\nvar ptraceotlp = &Package{\n\tinfo: &PackageInfo{\n\t\tname: \"ptraceotlp\",\n\t\tpath: filepath.Join(\"ptrace\", \"ptraceotlp\"),\n\t\timports: []string{\n\t\t\t`\"encoding/binary\"`,\n\t\t\t`\"fmt\"`,\n\t\t\t`\"iter\"`,\n\t\t\t`\"math\"`,\n\t\t\t`\"sort\"`,\n\t\t\t`\"sync\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t},\n\t\ttestImports: []string{\n\t\t\t`\"strconv\"`,\n\t\t\t`\"testing\"`,\n\t\t\t``,\n\t\t\t`\"github.com/stretchr/testify/assert\"`,\n\t\t\t`\"github.com/stretchr/testify/require\"`,\n\t\t\t`\"google.golang.org/protobuf/proto\"`,\n\t\t\t`gootlpcollectortrace \"go.opentelemetry.io/proto/slim/otlp/collector/trace/v1\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t},\n\t},\n\tstructs: []baseStruct{\n\t\texportTraceResponse,\n\t\texportTracePartialSuccess,\n\t},\n}\n\nvar exportTraceResponse = &messageStruct{\n\tstructName:    \"ExportResponse\",\n\tdescription:   \"// ExportResponse represents the response for gRPC/HTTP client/server.\",\n\tprotoName:     \"ExportTraceServiceResponse\",\n\tupstreamProto: \"gootlpcollectortrace.ExportTraceServiceResponse\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"PartialSuccess\",\n\t\t\tprotoID:       1,\n\t\t\treturnMessage: exportTracePartialSuccess,\n\t\t},\n\t},\n}\n\nvar exportTracePartialSuccess = &messageStruct{\n\tstructName:    \"ExportPartialSuccess\",\n\tdescription:   \"// ExportPartialSuccess represents the details of a partially successful export request.\",\n\tprotoName:     \"ExportTracePartialSuccess\",\n\tupstreamProto: \"gootlpcollectortrace.ExportTracePartialSuccess\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"RejectedSpans\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeInt64,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"ErrorMessage\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t},\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/request_package.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\n\nimport (\n\t\"path/filepath\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n)\n\nvar prequest = &Package{\n\tinfo: &PackageInfo{\n\t\tname: \"request\",\n\t\tpath: filepath.Join(\"xpdata\", \"request\", \"internal\"),\n\t\timports: []string{\n\t\t\t`\"encoding/binary\"`,\n\t\t\t`\"fmt\"`,\n\t\t\t`\"iter\"`,\n\t\t\t`\"math\"`,\n\t\t\t`\"sort\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/json\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/proto\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/pcommon\"`,\n\t\t},\n\t\ttestImports: []string{\n\t\t\t`\"testing\"`,\n\t\t\t``,\n\t\t\t`\"github.com/stretchr/testify/assert\"`,\n\t\t\t`\"google.golang.org/protobuf/types/known/emptypb\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/json\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/pcommon\"`,\n\t\t},\n\t},\n\tstructs: []baseStruct{\n\t\tspanContext,\n\t\tipAddr,\n\t\ttcpAddr,\n\t\tudpAddr,\n\t\tunixAddr,\n\t\trequestContext,\n\t\ttracesRequest,\n\t\tmetricsRequest,\n\t\tlogsRequest,\n\t\tprofilesRequest,\n\t},\n}\n\nvar spanContext = &messageStruct{\n\tstructName:    \"SpanContext\",\n\tpackageName:   \"request\",\n\tprotoName:     \"SpanContext\",\n\tupstreamProto: \"emptypb.Empty\",\n\tfields: []Field{\n\t\t&TypedField{\n\t\t\tfieldName:  \"TraceID\",\n\t\t\tprotoID:    1,\n\t\t\treturnType: traceIDType,\n\t\t},\n\t\t&TypedField{\n\t\t\tfieldName:  \"SpanID\",\n\t\t\tprotoID:    2,\n\t\t\treturnType: spanIDType,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"TraceFlags\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeFixed32,\n\t\t},\n\t\t&MessageField{\n\t\t\tfieldName:     \"TraceState\",\n\t\t\tprotoID:       4,\n\t\t\treturnMessage: traceState,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Remote\",\n\t\t\tprotoID:   5,\n\t\t\tprotoType: proto.TypeBool,\n\t\t},\n\t},\n\thasOnlyInternal: true,\n}\n\nvar ipAddr = &messageStruct{\n\tstructName:    \"IPAddr\",\n\tpackageName:   \"request\",\n\tprotoName:     \"IPAddr\",\n\tupstreamProto: \"emptypb.Empty\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"IP\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeBytes,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Zone\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t},\n\thasOnlyInternal: true,\n}\n\nvar tcpAddr = &messageStruct{\n\tstructName:    \"TCPAddr\",\n\tpackageName:   \"request\",\n\tprotoName:     \"TCPAddr\",\n\tupstreamProto: \"emptypb.Empty\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"IP\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeBytes,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Port\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeInt64,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Zone\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t},\n\thasOnlyInternal: true,\n}\n\nvar udpAddr = &messageStruct{\n\tstructName:    \"UDPAddr\",\n\tpackageName:   \"request\",\n\tprotoName:     \"UDPAddr\",\n\tupstreamProto: \"emptypb.Empty\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"IP\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeBytes,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Port\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeInt64,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Zone\",\n\t\t\tprotoID:   3,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t},\n\thasOnlyInternal: true,\n}\n\nvar unixAddr = &messageStruct{\n\tstructName:    \"UnixAddr\",\n\tpackageName:   \"request\",\n\tprotoName:     \"UnixAddr\",\n\tupstreamProto: \"emptypb.Empty\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Name\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Net\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t},\n\thasOnlyInternal: true,\n}\n\nvar requestContext = &messageStruct{\n\tstructName:    \"RequestContext\",\n\tpackageName:   \"request\",\n\tprotoName:     \"RequestContext\",\n\tupstreamProto: \"emptypb.Empty\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"SpanContext\",\n\t\t\tprotoID:       1,\n\t\t\tnullable:      true,\n\t\t\treturnMessage: spanContext,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"ClientMetadata\",\n\t\t\tprotoID:     2,\n\t\t\tprotoType:   proto.TypeMessage,\n\t\t\treturnSlice: mapStruct,\n\t\t},\n\t\t&OneOfField{\n\t\t\ttypeName:                   \"ClientAddressType\",\n\t\t\toriginFieldName:            \"ClientAddress\",\n\t\t\ttestValueIdx:               1, //\n\t\t\tomitOriginFieldNameInNames: true,\n\t\t\tvalues: []oneOfValue{\n\t\t\t\t&OneOfMessageValue{\n\t\t\t\t\tfieldName:     \"IP\",\n\t\t\t\t\tprotoID:       3,\n\t\t\t\t\treturnMessage: ipAddr,\n\t\t\t\t},\n\t\t\t\t&OneOfMessageValue{\n\t\t\t\t\tfieldName:     \"TCP\",\n\t\t\t\t\tprotoID:       4,\n\t\t\t\t\treturnMessage: tcpAddr,\n\t\t\t\t},\n\t\t\t\t&OneOfMessageValue{\n\t\t\t\t\tfieldName:     \"UDP\",\n\t\t\t\t\tprotoID:       5,\n\t\t\t\t\treturnMessage: udpAddr,\n\t\t\t\t},\n\t\t\t\t&OneOfMessageValue{\n\t\t\t\t\tfieldName:     \"Unix\",\n\t\t\t\t\tprotoID:       6,\n\t\t\t\t\treturnMessage: unixAddr,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t},\n\thasOnlyInternal: true,\n}\n\nvar tracesRequest = &messageStruct{\n\tstructName:    \"TracesRequest\",\n\tpackageName:   \"request\",\n\tprotoName:     \"TracesRequest\",\n\tupstreamProto: \"emptypb.Empty\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"RequestContext\",\n\t\t\tprotoID:       2,\n\t\t\tnullable:      true,\n\t\t\treturnMessage: requestContext,\n\t\t},\n\t\t&MessageField{\n\t\t\tfieldName:     \"TracesData\",\n\t\t\tprotoID:       3,\n\t\t\treturnMessage: tracesData,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"FormatVersion\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeFixed32,\n\t\t},\n\t},\n\thasOnlyInternal: true,\n}\n\nvar metricsRequest = &messageStruct{\n\tstructName:    \"MetricsRequest\",\n\tpackageName:   \"request\",\n\tprotoName:     \"MetricsRequest\",\n\tupstreamProto: \"emptypb.Empty\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"RequestContext\",\n\t\t\tprotoID:       2,\n\t\t\tnullable:      true,\n\t\t\treturnMessage: requestContext,\n\t\t},\n\t\t&MessageField{\n\t\t\tfieldName:     \"MetricsData\",\n\t\t\tprotoID:       3,\n\t\t\treturnMessage: metricsData,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"FormatVersion\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeFixed32,\n\t\t},\n\t},\n\thasOnlyInternal: true,\n}\n\nvar logsRequest = &messageStruct{\n\tstructName:    \"LogsRequest\",\n\tpackageName:   \"request\",\n\tprotoName:     \"LogsRequest\",\n\tupstreamProto: \"emptypb.Empty\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"RequestContext\",\n\t\t\tprotoID:       2,\n\t\t\tnullable:      true,\n\t\t\treturnMessage: requestContext,\n\t\t},\n\t\t&MessageField{\n\t\t\tfieldName:     \"LogsData\",\n\t\t\tprotoID:       3,\n\t\t\treturnMessage: logsData,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"FormatVersion\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeFixed32,\n\t\t},\n\t},\n\thasOnlyInternal: true,\n}\n\nvar profilesRequest = &messageStruct{\n\tstructName:    \"ProfilesRequest\",\n\tpackageName:   \"request\",\n\tprotoName:     \"ProfilesRequest\",\n\tupstreamProto: \"emptypb.Empty\",\n\tfields: []Field{\n\t\t&MessageField{\n\t\t\tfieldName:     \"RequestContext\",\n\t\t\tprotoID:       2,\n\t\t\tnullable:      true,\n\t\t\treturnMessage: requestContext,\n\t\t},\n\t\t&MessageField{\n\t\t\tfieldName:     \"ProfilesData\",\n\t\t\tprotoID:       3,\n\t\t\treturnMessage: profilesData,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"FormatVersion\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeFixed32,\n\t\t},\n\t},\n\thasOnlyInternal: true,\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/slice_field.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\n\nimport (\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst sliceAccessorTemplate = `// {{ .fieldName }} returns the {{ .fieldName }} associated with this {{ .structName }}.\nfunc (ms {{ .structName }}) {{ .fieldName }}() {{ .packageName }}{{ .returnType }} {\n\t{{- if .elementHasWrapper }}\n\treturn {{ .packageName }}{{ .returnType }}(internal.New{{ .returnType }}Wrapper(&ms.{{ .origAccessor }}.{{ .originFieldName }}, ms.{{ .stateAccessor }}))\n\t{{- else }}\n\treturn new{{ .returnType }}(&ms.{{ .origAccessor }}.{{ .originFieldName }}, ms.{{ .stateAccessor }})\n\t{{- end }}\n}`\n\nconst sliceAccessorsTestTemplate = `func Test{{ .structName }}_{{ .fieldName }}(t *testing.T) {\n\tms := New{{ .structName }}()\n\tassert.Equal(t, {{ .packageName }}New{{ .returnType }}(), ms.{{ .fieldName }}())\n\tms.{{ .origAccessor }}.{{ .originFieldName }} = internal.GenTest{{ .elementOriginName }}{{ if .elementNullable }}Ptr{{ end }}Slice()\n\t{{- if .elementHasWrapper }}\n\tassert.Equal(t, {{ .packageName }}{{ .returnType }}(internal.GenTest{{ .returnType }}Wrapper()), ms.{{ .fieldName }}())\n\t{{- else }}\n\tassert.Equal(t, generateTest{{ .returnType }}(), ms.{{ .fieldName }}())\n\t{{- end }}\n}`\n\nconst sliceSetTestTemplate = `orig.{{ .originFieldName }} = internal.GenTest{{ .elementOriginName }}{{ if .elementNullable }}Ptr{{ end }}Slice()`\n\ntype SliceField struct {\n\tfieldName     string\n\tprotoType     proto.Type\n\tprotoID       uint32\n\treturnSlice   baseSlice\n\thideAccessors bool\n}\n\nfunc (sf *SliceField) GenerateAccessors(ms *messageStruct) string {\n\tif sf.hideAccessors {\n\t\treturn \"\"\n\t}\n\tt := tmplutil.Parse(\"sliceAccessorTemplate\", []byte(sliceAccessorTemplate))\n\treturn tmplutil.Execute(t, sf.templateFields(ms))\n}\n\nfunc (sf *SliceField) GenerateAccessorsTest(ms *messageStruct) string {\n\tif sf.hideAccessors {\n\t\treturn \"\"\n\t}\n\tt := tmplutil.Parse(\"sliceAccessorsTestTemplate\", []byte(sliceAccessorsTestTemplate))\n\treturn tmplutil.Execute(t, sf.templateFields(ms))\n}\n\nfunc (sf *SliceField) GenerateTestValue(ms *messageStruct) string {\n\tt := tmplutil.Parse(\"sliceSetTestTemplate\", []byte(sliceSetTestTemplate))\n\treturn tmplutil.Execute(t, sf.templateFields(ms))\n}\n\nfunc (sf *SliceField) toProtoField(ms *messageStruct) proto.FieldInterface {\n\treturn &proto.Field{\n\t\tType:              sf.protoType,\n\t\tID:                sf.protoID,\n\t\tName:              sf.fieldName,\n\t\tMessageName:       sf.returnSlice.getElementOriginName(),\n\t\tParentMessageName: ms.protoName,\n\t\tRepeated:          sf.protoType != proto.TypeBytes,\n\t\tNullable:          sf.returnSlice.getElementNullable(),\n\t}\n}\n\nfunc (sf *SliceField) templateFields(ms *messageStruct) map[string]any {\n\treturn map[string]any{\n\t\t\"structName\":        ms.getName(),\n\t\t\"fieldName\":         sf.fieldName,\n\t\t\"originFieldName\":   sf.fieldName,\n\t\t\"elementOriginName\": sf.returnSlice.getElementOriginName(),\n\t\t\"packageName\": func() string {\n\t\t\tif sf.returnSlice.getPackageName() != ms.packageName {\n\t\t\t\treturn sf.returnSlice.getPackageName() + \".\"\n\t\t\t}\n\t\t\treturn \"\"\n\t\t}(),\n\t\t\"returnType\":        sf.returnSlice.getName(),\n\t\t\"origAccessor\":      origAccessor(ms.getHasWrapper()),\n\t\t\"stateAccessor\":     stateAccessor(ms.getHasWrapper()),\n\t\t\"elementHasWrapper\": sf.returnSlice.getHasWrapper(),\n\t\t\"elementNullable\":   sf.returnSlice.getElementNullable(),\n\t}\n}\n\nvar _ Field = (*SliceField)(nil)\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/templates/message.go.tmpl",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage {{ .packageName }}\n\nimport (\n\t{{ range $index, $element := .imports -}}\n\t{{ $element }}\n\t{{ end }}\n)\n\n{{ .description }}\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use New{{ .structName }} function to create new instances.\n// Important: zero-initialized instance is not valid for use.\n{{- if .hasWrapper }}\ntype {{ .structName }} internal.{{ .structName }}Wrapper\n{{- else }}\ntype {{ .structName }} struct {\n\torig *internal.{{ .originName }}\n\tstate *internal.State\n}\n{{- end }}\n\nfunc new{{ .structName }}(orig *internal.{{ .originName }}, state *internal.State) {{ .structName }} {\n\t{{- if .hasWrapper }}\n\treturn {{ .structName }}(internal.New{{ .structName }}Wrapper(orig, state))\n\t{{- else }}\n\treturn {{ .structName }}{orig: orig, state: state}\n\t{{- end }}\n}\n\n// New{{ .structName }} creates a new empty {{ .structName }}.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc New{{ .structName }}() {{ .structName }} {\n\treturn new{{ .structName }}(internal.New{{ .originName }}(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms {{ .structName }}) MoveTo(dest {{ .structName }}) {\n\tms.{{ .stateAccessor }}.AssertMutable()\n\tdest.{{ .stateAccessor }}.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.{{ .origAccessor }} == dest.{{ .origAccessor }} {\n\t\treturn\n\t}\n\tinternal.Delete{{ .originName }}(dest.{{ .origAccessor }}, false)\n\t*dest.{{ .origAccessor }}, *ms.{{ .origAccessor }} = *ms.{{ .origAccessor }}, *dest.{{ .origAccessor }}\n}\n\n{{ range .fields -}}\n{{ .GenerateAccessors $.messageStruct }}\n{{ end }}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms {{ .structName }}) CopyTo(dest {{ .structName }}) {\n\tdest.{{ .stateAccessor }}.AssertMutable()\n    internal.Copy{{ .originName }}(dest.{{ .origAccessor }}, ms.{{ .origAccessor }})\n}\n\n{{ if .hasWrapper -}}\nfunc (ms {{ .structName }}) getOrig() *internal.{{ .originName }} {\n\treturn internal.Get{{ .structName }}Orig(internal.{{ .structName }}Wrapper(ms))\n}\n\nfunc (ms {{ .structName }}) getState() *internal.State {\n\treturn internal.Get{{ .structName }}State(internal.{{ .structName }}Wrapper(ms))\n}\n{{- end }}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/templates/message_internal.go.tmpl",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t{{ range $index, $element := .imports -}}\n\t{{ $element }}\n\t{{ end }}\n)\n\ntype {{ .structName }}Wrapper struct {\n\torig *{{ .originName }}\n\tstate *State\n}\n\nfunc Get{{ .structName }}Orig(ms {{ .structName }}Wrapper) *{{ .originName }} {\n\treturn ms.orig\n}\n\nfunc Get{{ .structName }}State(ms {{ .structName }}Wrapper) *State {\n\treturn ms.state\n}\n\nfunc New{{ .structName }}Wrapper(orig *{{ .originName }}, state *State) {{ .structName }}Wrapper {\n\treturn {{ .structName }}Wrapper{orig: orig, state: state}\n}\n\nfunc GenTest{{ .structName }}Wrapper() {{ .structName }}Wrapper {\n    return New{{ .structName }}Wrapper(GenTest{{ .originName }}(), NewState())\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/templates/message_test.go.tmpl",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage {{ .packageName }}\n\nimport (\n\t{{ range $index, $element := .testImports -}}\n\t{{ $element }}\n\t{{ end }}\n)\n\nfunc Test{{ .structName }}_MoveTo(t *testing.T) {\n\tms := generateTest{{ .structName }}()\n\tdest := New{{ .structName }}()\n\tms.MoveTo(dest)\n\tassert.Equal(t, New{{ .structName }}(), ms)\n\tassert.Equal(t, generateTest{{ .structName }}(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTest{{ .structName }}(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(new{{ .structName }}(internal.New{{ .originName }}(), sharedState)) })\n\tassert.Panics(t, func() { new{{ .structName }}(internal.New{{ .originName }}(), sharedState).MoveTo(dest) })\n}\n\nfunc Test{{ .structName }}_CopyTo(t *testing.T) {\n\tms := New{{ .structName }}()\n\torig := New{{ .structName }}()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTest{{ .structName }}()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(new{{ .structName }}(internal.New{{ .originName }}(), sharedState)) })\n}\n\n{{ range .fields }}\n{{ .GenerateAccessorsTest $.messageStruct }}\n{{ end }}\n\nfunc generateTest{{ .structName }}() {{ .structName }} {\n\treturn new{{ .structName }}(internal.GenTest{{ .originName }}(), internal.NewState())\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/templates/primitive_slice.go.tmpl",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage {{ .packageName }}\n\nimport (\n\t{{ range $index, $element := .imports -}}\n\t{{ $element }}\n\t{{ end }}\n)\n\n// {{ .structName }} represents a []{{ .itemType }} slice.\n// The instance of {{ .structName }} can be assigned to multiple objects since it's immutable.\n//\n// Must use New{{ .structName }} function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype {{ .structName }} internal.{{ .structName }}Wrapper\n\nfunc (ms {{ .structName }}) getOrig() *[]{{ .itemType }} {\n\treturn internal.Get{{ .structName }}Orig(internal.{{ .structName }}Wrapper(ms))\n}\n\nfunc (ms {{ .structName }}) getState() *internal.State {\n\treturn internal.Get{{ .structName }}State(internal.{{ .structName }}Wrapper(ms))\n}\n\n// New{{ .structName }} creates a new empty {{ .structName }}.\nfunc New{{ .structName }}() {{ .structName }} {\n\torig := []{{ .itemType }}(nil)\n\treturn {{ .structName }}(internal.New{{ .structName }}Wrapper(&orig, internal.NewState()))\n}\n\n// AsRaw returns a copy of the []{{ .itemType }} slice.\nfunc (ms {{ .structName }}) AsRaw() []{{ .itemType }} {\n\treturn copy{{ .elementOriginName }}Slice(nil, *ms.getOrig())\n}\n\n// FromRaw copies raw []{{ .itemType }} into the slice {{ .structName }}.\nfunc (ms {{ .structName }}) FromRaw(val []{{ .itemType }}) {\n\tms.getState().AssertMutable()\n\t*ms.getOrig() = copy{{ .elementOriginName }}Slice(*ms.getOrig(), val)\n}\n\n// Len returns length of the []{{ .itemType }} slice value.\n// Equivalent of len({{ .lowerStructName }}).\nfunc (ms {{ .structName }}) Len() int {\n\treturn len(*ms.getOrig())\n}\n\n// At returns an item from particular index.\n// Equivalent of {{ .lowerStructName }}[i].\nfunc (ms {{ .structName }}) At(i int) {{ .itemType }} {\n\treturn (*ms.getOrig())[i]\n}\n\n// All returns an iterator over index-value pairs in the slice.\nfunc (ms {{ .structName }}) All() iter.Seq2[int, {{ .itemType }}] {\n\treturn func(yield func(int, {{ .itemType }}) bool) {\n\t\tfor i := 0; i < ms.Len(); i++ {\n\t\t\tif !yield(i, ms.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// SetAt sets {{ .itemType }} item at particular index.\n// Equivalent of {{ .lowerStructName }}[i] = val\nfunc (ms {{ .structName }}) SetAt(i int, val {{ .itemType }}) {\n\tms.getState().AssertMutable()\n\t(*ms.getOrig())[i] = val\n}\n\n// EnsureCapacity ensures {{ .structName }} has at least the specified capacity.\n// 1. If the newCap <= cap, then is no change in capacity.\n// 2. If the newCap > cap, then the slice capacity will be expanded to the provided value which will be equivalent of:\n//\tbuf := make([]{{ .itemType }}, len({{ .lowerStructName }}), newCap)\n//\tcopy(buf, {{ .lowerStructName }})\n//\t{{ .lowerStructName }} = buf\nfunc (ms {{ .structName }}) EnsureCapacity(newCap int) {\n\tms.getState().AssertMutable()\n\toldCap := cap(*ms.getOrig())\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]{{ .itemType }}, len(*ms.getOrig()), newCap)\n\tcopy(newOrig, *ms.getOrig())\n\t*ms.getOrig() = newOrig\n}\n\n// Append appends extra elements to {{ .structName }}.\n// Equivalent of {{ .lowerStructName }} = append({{ .lowerStructName }}, elms...)\nfunc (ms {{ .structName }}) Append(elms ...{{ .itemType }}) {\n\tms.getState().AssertMutable()\n\t*ms.getOrig() = append(*ms.getOrig(), elms...)\n}\n\n// MoveTo moves all elements from the current slice overriding the destination and\n// resetting the current instance to its zero value.\nfunc (ms {{ .structName }}) MoveTo(dest {{ .structName }}) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = *ms.getOrig()\n\t*ms.getOrig() = nil\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (ms {{ .structName }}) MoveAndAppendTo(dest {{ .structName }}) {\n  ms.getState().AssertMutable()\n  dest.getState().AssertMutable()\n  if *dest.getOrig() == nil {\n    // We can simply move the entire vector and avoid any allocations.\n    *dest.getOrig() = *ms.getOrig()\n  } else {\n    *dest.getOrig() = append(*dest.getOrig(), *ms.getOrig()...)\n  }\n  *ms.getOrig() = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (ms {{ .structName }}) RemoveIf(f func({{ .itemType }}) bool) {\n\tms.getState().AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*ms.getOrig()); i++ {\n\t\tif f((*ms.getOrig())[i]) {\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*ms.getOrig())[newLen] = (*ms.getOrig())[i]\n\t\tvar zero {{ .itemType }}\n\t\t(*ms.getOrig())[i] = zero\n\t\tnewLen++\n\t}\n\t*ms.getOrig() = (*ms.getOrig())[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (ms {{ .structName }}) CopyTo(dest {{ .structName }}) {\n\tdest.getState().AssertMutable()\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = copy{{ .elementOriginName }}Slice(*dest.getOrig(), *ms.getOrig())\n}\n\n// Equal checks equality with another {{ .structName }}\nfunc (ms {{ .structName }}) Equal(val {{ .structName }}) bool {\n\treturn slices.Equal(*ms.getOrig(), *val.getOrig())\n}\n\nfunc copy{{ .elementOriginName }}Slice(dst, src []{{ .itemType }}) []{{ .itemType }} {\n\treturn append(dst[:0], src...)\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/templates/primitive_slice_internal.go.tmpl",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t{{ range $index, $element := .imports -}}\n\t{{ $element }}\n\t{{ end }}\n)\n\ntype {{ .structName }}Wrapper struct {\n\torig *[]{{ .itemType }}\n\tstate *State\n}\n\nfunc Get{{ .structName }}Orig(ms {{ .structName }}Wrapper) *[]{{ .itemType }} {\n\treturn ms.orig\n}\n\nfunc Get{{ .structName }}State(ms {{ .structName }}Wrapper) *State {\n\treturn ms.state\n}\n\nfunc New{{ .structName }}Wrapper(orig *[]{{ .itemType }}, state *State) {{ .structName }}Wrapper {\n\treturn {{ .structName }}Wrapper{orig: orig, state: state}\n}\n\nfunc GenTest{{ .structName }}Wrapper() {{ .structName }}Wrapper {\n\torig := []{{ .itemType }}{ {{ .testOrigVal }} }\n\treturn New{{ .structName }}Wrapper(&orig, NewState())\n}\n\nfunc GenTest{{ .elementOriginName }}Slice() []{{ .itemType }} {\n    return []{{ .itemType }}{ {{ .testOrigVal }} }\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/templates/primitive_slice_test.go.tmpl",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage {{ .packageName }}\n\nimport (\n\t{{ range $index, $element := .testImports -}}\n\t{{ $element }}\n\t{{ end }}\n)\n\nfunc TestNew{{ .structName }}(t *testing.T) {\n\tms := New{{ .structName }}()\n\tassert.Equal(t, 0, ms.Len())\n\tms.FromRaw([]{{ .itemType }}{ {{ .testOrigVal }} })\n\tassert.Equal(t, 3, ms.Len())\n\tassert.Equal(t, []{{ .itemType }}{ {{ .testOrigVal }} }, ms.AsRaw())\n\tms.SetAt(1, {{ .itemType }}( {{ .testSetVal }} ))\n\tassert.Equal(t, []{{ .itemType }}{ {{ .testNewVal }} }, ms.AsRaw())\n\tms.FromRaw([]{{ .itemType }}{ {{ index .testInterfaceOrigVal 2 }} })\n\tassert.Equal(t, 1, ms.Len())\n\t{{- if eq .itemType \"float64\" }}\n\tassert.InDelta(t, {{ .itemType }}({{ index .testInterfaceOrigVal 2 }}), ms.At(0), 0.01)\n\t{{- else }}\n\tassert.Equal(t, {{ .itemType }}({{ index .testInterfaceOrigVal 2 }}), ms.At(0))\n\t{{- end }}\n\n\tcp := New{{ .structName }}()\n\tms.CopyTo(cp)\n\tms.SetAt(0, {{ .itemType }}( {{ index .testInterfaceOrigVal 1 }} ))\n\t{{- if eq .itemType \"float64\" }}\n\tassert.InDelta(t, {{ .itemType }}({{ index .testInterfaceOrigVal 1 }}), ms.At(0), 0.01)\n\t{{- else }}\n\tassert.Equal(t, {{ .itemType }}({{ index .testInterfaceOrigVal 1 }}), ms.At(0))\n\t{{- end }}\n\t{{- if eq .itemType \"float64\" }}\n\tassert.InDelta(t, {{ .itemType }}({{ index .testInterfaceOrigVal 2 }}), cp.At(0), 0.01)\n\t{{- else }}\n\tassert.Equal(t, {{ .itemType }}({{ index .testInterfaceOrigVal 2 }}), cp.At(0))\n\t{{- end }}\n\tms.CopyTo(cp)\n\t{{- if eq .itemType \"float64\" }}\n\tassert.InDelta(t, {{ .itemType }}({{ index .testInterfaceOrigVal 1 }}), cp.At(0), 0.01)\n\t{{- else }}\n\tassert.Equal(t, {{ .itemType }}({{ index .testInterfaceOrigVal 1 }}), cp.At(0))\n\t{{- end }}\n\n\tmv := New{{ .structName }}()\n\tms.MoveTo(mv)\n\tassert.Equal(t, 0, ms.Len())\n\tassert.Equal(t, 1, mv.Len())\n\t{{- if eq .itemType \"float64\" }}\n\tassert.InDelta(t, {{ .itemType }}({{index .testInterfaceOrigVal 1 }}), mv.At(0), 0.01)\n\t{{- else }}\n\tassert.Equal(t, {{ .itemType }}({{index .testInterfaceOrigVal 1 }}), mv.At(0))\n\t{{- end }}\n\tms.FromRaw([]{{ .itemType }}{ {{ .testOrigVal }} })\n\tms.MoveTo(mv)\n\tassert.Equal(t, 3, mv.Len())\n\t{{- if eq .itemType \"float64\" }}\n\tassert.InDelta(t, {{ .itemType }}({{index .testInterfaceOrigVal 0 }}), mv.At(0), 0.01)\n\t{{- else }}\n\tassert.Equal(t, {{ .itemType }}({{index .testInterfaceOrigVal 0 }}), mv.At(0))\n\t{{- end }}\n\tmv.MoveTo(mv)\n\tassert.Equal(t, 3, mv.Len())\n\t{{- if eq .itemType \"float64\" }}\n\tassert.InDelta(t, {{ .itemType }}({{index .testInterfaceOrigVal 0 }}), mv.At(0), 0.01)\n\t{{- else }}\n\tassert.Equal(t, {{ .itemType }}({{index .testInterfaceOrigVal 0 }}), mv.At(0))\n\t{{- end }}\n}\n\nfunc Test{{ .structName }}ReadOnly(t *testing.T) {\n\traw := []{{ .itemType }}{ {{ .testOrigVal }}}\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tms := {{ .structName }}(internal.New{{ .structName }}Wrapper(&raw, sharedState))\n\n\tassert.Equal(t, 3, ms.Len())\n\t{{- if eq .itemType \"float64\" }}\n\tassert.InDelta(t, {{ .itemType }}( {{index .testInterfaceOrigVal 0 }} ), ms.At(0), 0.01)\n\t{{- else }}\n\tassert.Equal(t, {{ .itemType }}({{ index .testInterfaceOrigVal 0 }}), ms.At(0))\n\t{{- end }}\n\tassert.Panics(t, func() { ms.Append({{ index .testInterfaceOrigVal 0 }}) })\n\tassert.Panics(t, func() { ms.EnsureCapacity(2) })\n\tassert.Equal(t, raw, ms.AsRaw())\n\tassert.Panics(t, func() { ms.FromRaw(raw) })\n\n\tms2 := New{{ .structName }}()\n\tms.CopyTo(ms2)\n\tassert.Equal(t, ms.AsRaw(), ms2.AsRaw())\n\tassert.Panics(t, func() { ms2.CopyTo(ms) })\n\n\tassert.Panics(t, func() { ms.MoveTo(ms2) })\n\tassert.Panics(t, func() { ms2.MoveTo(ms) })\n}\n\nfunc Test{{ .structName }}Append(t *testing.T) {\n\tms := New{{ .structName }}()\n\tms.FromRaw([]{{ .itemType }}{ {{ .testOrigVal }} })\n\tms.Append({{ .testSetVal }}, {{ .testSetVal }})\n\tassert.Equal(t, 5, ms.Len())\n\t{{- if eq .itemType \"float64\" }}\n\tassert.InDelta(t, {{ .itemType }}({{ .testSetVal }} ), ms.At(4), 0.01)\n\t{{- else }}\n\tassert.Equal(t, {{ .itemType }}({{ .testSetVal }}), ms.At(4))\n\t{{- end }}\n}\n\nfunc Test{{ .structName }}EnsureCapacity(t *testing.T) {\n\tms := New{{ .structName }}()\n\tms.EnsureCapacity(4)\n\tassert.Equal(t, 4, cap(*ms.getOrig()))\n\tms.EnsureCapacity(2)\n\tassert.Equal(t, 4, cap(*ms.getOrig()))\n}\n\nfunc Test{{ .structName }}All(t *testing.T) {\n\tms := New{{ .structName }}()\n\tms.FromRaw([]{{ .itemType }}{ {{ .testOrigVal }} })\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\n\nfunc Test{{ .structName }}MoveAndAppendTo(t *testing.T) {\n  // Test moving from an empty slice\n  ms := New{{ .structName }}()\n  ms2 := New{{ .structName }}()\n  ms.MoveAndAppendTo(ms2)\n  assert.Equal(t, New{{ .structName }}(), ms2)\n  assert.Equal(t, ms.Len(), 0)\n\n  // Test moving to empty slice\n  ms.FromRaw([]{{ .itemType }}{ {{ .testOrigVal }} })\n  ms.MoveAndAppendTo(ms2)\n  assert.Equal(t, ms2.Len(), 3)\n\n  // Test moving to a non empty slice\n  ms.FromRaw([]{{ .itemType }}{ {{ .testOrigVal }} })\n  ms.MoveAndAppendTo(ms2)\n  assert.Equal(t, ms2.Len(), 6)\n}\n\nfunc Test{{ .structName }}RemoveIf(t *testing.T) {\n\temptySlice := New{{ .structName }}()\n\temptySlice.RemoveIf(func(el {{ .itemType }}) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\tms := New{{ .structName }}()\n\tms.FromRaw([]{{ .itemType }}{ {{ .testOrigVal }} })\n\tpos := 0\n\tms.RemoveIf(func(el {{ .itemType }}) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, pos/2, ms.Len())\n}\n\nfunc Test{{ .structName }}RemoveIfAll(t *testing.T) {\n\tms := New{{ .structName }}()\n\tms.FromRaw([]{{ .itemType }}{ {{ .testOrigVal }} })\n\tms.RemoveIf(func(el {{ .itemType }}) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, ms.Len())\n}\n\nfunc Test{{ .structName }}Equal(t *testing.T) {\n\tms := New{{ .structName }}()\n\tms2 := New{{ .structName }}()\n\tassert.True(t, ms.Equal(ms2))\n\n\tms.Append({{ .testOrigVal }})\n\tassert.False(t, ms.Equal(ms2))\n\n\tms2.Append({{ .testOrigVal }})\n\tassert.True(t, ms.Equal(ms2))\n}\n\nfunc Benchmark{{ .structName }}Equal(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\tms := New{{ .structName }}()\n\tms.Append({{ .testOrigVal }})\n\tcmp := New{{ .structName }}()\n\tcmp.Append({{ .testOrigVal }})\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\n\tfor n := 0; n < b.N; n++ {\n\t\t_ = ms.Equal(cmp)\n\t}\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/templates/slice.go.tmpl",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage {{ .packageName }}\n\nimport (\n\t{{ range $index, $element := .imports -}}\n\t{{ $element }}\n\t{{ end }}\n)\n\n// {{ .structName }} logically represents a slice of {{ .elementName }}.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use New{{ .structName }} function to create new instances.\n// Important: zero-initialized instance is not valid for use.\n{{- if .hasWrapper }}\ntype {{ .structName }} internal.{{ .structName }}Wrapper\n{{- else }}\ntype {{ .structName }} struct {\n\torig *[]{{ if .elementNullable }}*{{ end }}internal.{{ .elementOriginName }}\n\tstate *internal.State\n}\n{{- end }}\n\nfunc new{{ .structName }}(orig *[]{{ if .elementNullable }}*{{ end }}internal.{{ .elementOriginName }}, state *internal.State) {{ .structName }} {\n\t{{- if .hasWrapper }}\n\treturn {{ .structName }}(internal.New{{ .structName }}Wrapper(orig, state))\n\t{{- else }}\n\treturn {{ .structName }}{orig: orig, state: state}\n\t{{- end }}\n}\n\n// New{{ .structName }} creates a {{ .structName }}Wrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc New{{ .structName }}() {{ .structName }} {\n\torig := []{{ if .elementNullable }}*{{ end }}internal.{{ .elementOriginName }}(nil)\n\treturn new{{ .structName }}(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"New{{ .structName }}()\".\nfunc (es {{ .structName }}) Len() int {\n\treturn len(*es.{{ .origAccessor }})\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//   for i := 0; i < es.Len(); i++ {\n//       e := es.At(i)\n//       ... // Do something with the element\n//   }\nfunc (es {{ .structName }}) At(i int) {{ .elementName }} {\n\treturn new{{ .elementName }}({{ if not .elementNullable }}&{{ end }}(*es.{{ .origAccessor }})[i], es.{{ .stateAccessor }})\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es {{ .structName }}) All() iter.Seq2[int, {{ .elementName }}] {\n\treturn func(yield func(int, {{ .elementName }}) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new {{ .structName }} can be initialized:\n//   es := New{{ .structName }}()\n//   es.EnsureCapacity(4)\n//   for i := 0; i < 4; i++ {\n//       e := es.AppendEmpty()\n//       // Here should set all the values for e.\n//   }\nfunc (es {{ .structName }}) EnsureCapacity(newCap int) {\n\tes.{{ .stateAccessor }}.AssertMutable()\n\toldCap := cap(*es.{{ .origAccessor }})\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]{{ if .elementNullable }}*{{ end }}internal.{{ .elementOriginName }}, len(*es.{{ .origAccessor }}), newCap)\n\tcopy(newOrig, *es.{{ .origAccessor }})\n\t*es.{{ .origAccessor }} = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty {{ .elementName }}.\n// It returns the newly added {{ .elementName }}.\nfunc (es {{ .structName }}) AppendEmpty() {{ .elementName }} {\n\tes.{{ .stateAccessor }}.AssertMutable()\n\t*es.{{ .origAccessor }} = append(*es.{{ .origAccessor }}, {{- if .elementNullable }}internal.New{{ .elementOriginName }}(){{ else }}internal.{{ .elementOriginName }}{}{{ end }})\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es {{ .structName }}) MoveAndAppendTo(dest {{ .structName }}) {\n\tes.{{ .stateAccessor }}.AssertMutable()\n\tdest.{{ .stateAccessor }}.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.{{ .origAccessor }} == dest.{{ .origAccessor }} {\n\t\treturn\n\t}\n\tif *dest.{{ .origAccessor }} == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.{{ .origAccessor }} = *es.{{ .origAccessor }}\n\t} else {\n\t\t*dest.{{ .origAccessor }} = append(*dest.{{ .origAccessor }}, *es.{{ .origAccessor }}...)\n\t}\n\t*es.{{ .origAccessor }} = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es {{ .structName }}) RemoveIf(f func({{ .elementName }}) bool) {\n\tes.{{ .stateAccessor }}.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.{{ .origAccessor }}); i++ {\n\t\tif f(es.At(i)) {\n\t\t\t{{ if .elementNullable -}}\n\t\t\tinternal.Delete{{ .elementOriginName }}((*es.{{ .origAccessor }})[i], true)\n\t\t\t(*es.{{ .origAccessor }})[i] = nil\n\t\t\t{{ else -}}\n\t\t\tinternal.Delete{{ .elementOriginName }}(&(*es.{{ .origAccessor }})[i], false)\n\t\t\t{{- end }}\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.{{ .origAccessor }})[newLen] = (*es.{{ .origAccessor }})[i]\n\t\t{{ if .elementNullable -}}\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.{{ .origAccessor }})[i] = nil{{ else -}}\n\t\t(*es.{{ .origAccessor }})[i].Reset()\n\t\t{{- end }}\n\t\tnewLen++\n\t}\n\t*es.{{ .origAccessor }} = (*es.{{ .origAccessor }})[:newLen]\n}\n\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es {{ .structName }}) CopyTo(dest {{ .structName }}) {\n\tdest.{{ .stateAccessor }}.AssertMutable()\n\tif es.{{ .origAccessor }} == dest.{{ .origAccessor }} {\n\t\treturn\n\t}\n\t*dest.{{ .origAccessor }} = internal.Copy{{ .elementOriginName }}{{ if .elementNullable }}Ptr{{ end }}Slice(*dest.{{ .origAccessor }}, *es.{{ .origAccessor }})\n}\n\n{{ if .elementNullable -}}\n// Sort sorts the {{ .elementName }} elements within {{ .structName }} given the\n// provided less function so that two instances of {{ .structName }}\n// can be compared.\nfunc (es {{ .structName }}) Sort(less func(a, b {{ .elementName }}) bool) {\n\tes.{{ .stateAccessor }}.AssertMutable()\n\tsort.SliceStable(*es.{{ .origAccessor }}, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n{{- end }}\n\n{{ if .hasWrapper -}}\nfunc (ms {{ .structName }}) getOrig() *[]{{ if .elementNullable }}*{{ end }}internal.{{ .elementOriginName }} {\n\treturn internal.Get{{ .structName }}Orig(internal.{{ .structName }}Wrapper(ms))\n}\n\nfunc (ms {{ .structName }}) getState() *internal.State {\n\treturn internal.Get{{ .structName }}State(internal.{{ .structName }}Wrapper(ms))\n}\n{{- end }}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/templates/slice_internal.go.tmpl",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t{{ range $index, $element := .imports -}}\n\t{{ $element }}\n\t{{ end }}\n)\n\ntype {{ .structName }}Wrapper struct {\n\torig *[]{{ if .elementNullable }}*{{ end }}{{ .elementOriginName }}\n\tstate *State\n}\n\nfunc Get{{ .structName }}Orig(ms {{ .structName }}Wrapper) *[]{{ if .elementNullable }}*{{ end }}{{ .elementOriginName }} {\n\treturn ms.orig\n}\n\nfunc Get{{ .structName }}State(ms {{ .structName }}Wrapper) *State {\n\treturn ms.state\n}\n\nfunc New{{ .structName }}Wrapper(orig *[]{{ if .elementNullable }}*{{ end }}{{ .elementOriginName }}, state *State) {{ .structName }}Wrapper {\n\treturn {{ .structName }}Wrapper{orig: orig, state: state}\n}\n\nfunc GenTest{{ .structName }}Wrapper() {{ .structName }}Wrapper {\n    orig := GenTest{{ .elementOriginName }}{{ if .elementNullable }}Ptr{{ end }}Slice()\n    return New{{ .structName }}Wrapper(&orig, NewState())\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/templates/slice_test.go.tmpl",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage {{ .packageName }}\n\nimport (\n\t{{ range $index, $element := .testImports -}}\n\t{{ $element }}\n\t{{ end }}\n)\n\nfunc Test{{ .structName }}(t *testing.T) {\n\tes := New{{ .structName }}()\n\tassert.Equal(t, 0, es.Len())\n\tes = new{{ .structName }}(&[]{{ if .elementNullable }}*{{ end }}internal.{{ .elementOriginName }}{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\t{{ if eq .elementName \"Value\" -}}\n\temptyVal := New{{ .elementName }}Empty()\n\t{{- else }}\n\temptyVal := New{{ .elementName }}()\n\t{{- end }}\n\t{{- if .hasWrapper }}\n\ttestVal := {{ .elementName }}(internal.GenTest{{ .elementName }}Wrapper())\n\t{{- else }}\n\ttestVal := generateTest{{ .elementName }}()\n\t{{- end }}\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n        (*es.{{ .origAccessor }})[i] = {{ if not .elementNullable }}*{{ end }}internal.GenTest{{ .elementOriginName }}()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc Test{{ .structName }}ReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := new{{ .structName }}(&[]{{ if .elementNullable }}*{{ end }}internal.{{ .elementOriginName }}{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := New{{ .structName }}()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc Test{{ .structName }}_CopyTo(t *testing.T) {\n\tdest := New{{ .structName }}()\n\tsrc := generateTest{{ .structName }}()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTest{{ .structName }}(), dest)\n    dest.CopyTo(dest)\n    assert.Equal(t, generateTest{{ .structName }}(), dest)\n}\n\nfunc Test{{ .structName }}_EnsureCapacity(t *testing.T) {\n\tes := generateTest{{ .structName }}()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.{{ .origAccessor }}))\n\tassert.Equal(t, generateTest{{ .structName }}(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTest{{ .structName }}().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.{{ .origAccessor }}))\n\tassert.Equal(t, generateTest{{ .structName }}(), es)\n}\n\nfunc Test{{ .structName }}_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTest{{ .structName }}()\n\tdest := New{{ .structName }}()\n\tsrc := generateTest{{ .structName }}()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTest{{ .structName }}(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTest{{ .structName }}(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTest{{ .structName }}().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc Test{{ .structName }}_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := New{{ .structName }}()\n\temptySlice.RemoveIf(func(el {{ .elementName }}) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTest{{ .structName }}()\n\tpos := 0\n\tfiltered.RemoveIf(func(el {{ .elementName }}) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc Test{{ .structName }}_RemoveIfAll(t *testing.T) {\n\tgot := generateTest{{ .structName }}()\n\tgot.RemoveIf(func(el {{ .elementName }}) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc Test{{ .structName }}All(t *testing.T) {\n\tms := generateTest{{ .structName }}()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\n{{ if .elementNullable -}}\nfunc Test{{ .structName }}_Sort(t *testing.T) {\n\tes := generateTest{{ .structName }}()\n\tes.Sort(func(a, b {{ .elementName }}) bool {\n\t\treturn uintptr(unsafe.Pointer(a.{{ .origAccessor }})) < uintptr(unsafe.Pointer(b.{{ .origAccessor }}))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).{{ .origAccessor }})), uintptr(unsafe.Pointer(es.At(i).{{ .origAccessor }})))\n\t}\n\tes.Sort(func(a, b {{ .elementName }}) bool {\n\t\treturn uintptr(unsafe.Pointer(a.{{ .origAccessor }})) > uintptr(unsafe.Pointer(b.{{ .origAccessor }}))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).{{ .origAccessor }})), uintptr(unsafe.Pointer(es.At(i).{{ .origAccessor }})))\n\t}\n}\n{{- end }}\n\nfunc generateTest{{ .structName }}() {{ .structName }} {\n\tms := New{{ .structName }}()\n\t*ms.{{ .origAccessor }} = internal.GenTest{{ .elementOriginName }}{{ if .elementNullable }}Ptr{{ end }}Slice()\n\treturn ms\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/templates.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\n\nimport (\n\t_ \"embed\" // Blank import required for go:embed to work.\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nvar (\n\t//go:embed templates/message.go.tmpl\n\tmessageTemplateBytes []byte\n\tmessageTemplate      = tmplutil.Parse(\"message.go\", messageTemplateBytes)\n\n\t//go:embed templates/message_internal.go.tmpl\n\tmessageInternalTemplateBytes []byte\n\tmessageInternalTemplate      = tmplutil.Parse(\"message_internal.go\", messageInternalTemplateBytes)\n\n\t//go:embed templates/message_test.go.tmpl\n\tmessageTestTemplateBytes []byte\n\tmessageTestTemplate      = tmplutil.Parse(\"message_test.go\", messageTestTemplateBytes)\n\n\t//go:embed templates/primitive_slice.go.tmpl\n\tprimitiveSliceTemplateBytes []byte\n\tprimitiveSliceTemplate      = tmplutil.Parse(\"primitive_slice.go\", primitiveSliceTemplateBytes)\n\n\t//go:embed templates/primitive_slice_internal.go.tmpl\n\tprimitiveSliceInternalTemplateBytes []byte\n\tprimitiveSliceInternalTemplate      = tmplutil.Parse(\"primitive_slice_internal.go\", primitiveSliceInternalTemplateBytes)\n\n\t//go:embed templates/primitive_slice_test.go.tmpl\n\tprimitiveSliceTestTemplateBytes []byte\n\tprimitiveSliceTestTemplate      = tmplutil.Parse(\"primitive_slice_test.go\", primitiveSliceTestTemplateBytes)\n\n\t//go:embed templates/slice.go.tmpl\n\tsliceTemplateBytes []byte\n\tsliceTemplate      = tmplutil.Parse(\"slice.go\", sliceTemplateBytes)\n\n\t//go:embed templates/slice_internal.go.tmpl\n\tsliceInternalTemplateBytes []byte\n\tsliceInternalTemplate      = tmplutil.Parse(\"slice_internal.go\", sliceInternalTemplateBytes)\n\n\t//go:embed templates/slice_test.go.tmpl\n\tsliceTestTemplateBytes []byte\n\tsliceTestTemplate      = tmplutil.Parse(\"slice_test.go\", sliceTestTemplateBytes)\n)\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/typed_field.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\n\nimport (\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst typedAccessorsTemplate = `// {{ .fieldName }} returns the {{ .lowerFieldName }} associated with this {{ .structName }}.\nfunc (ms {{ .structName }}) {{ .fieldName }}() {{ .packageName }}{{ .returnType }} {\n\treturn {{ .packageName }}{{ .returnType }}(ms.orig.{{ .originFieldName }})\n}\n\n// Set{{ .fieldName }} replaces the {{ .lowerFieldName }} associated with this {{ .structName }}.\nfunc (ms {{ .structName }}) Set{{ .fieldName }}(v {{ .packageName }}{{ .returnType }}) {\n\tms.state.AssertMutable()\n\tms.orig.{{ .originFieldName }} = {{ .messageType }}(v)\n}`\n\nconst typedAccessorsTestTemplate = `func Test{{ .structName }}_{{ .fieldName }}(t *testing.T) {\n\tms := New{{ .structName }}()\n\tassert.Equal(t, {{ .packageName }}{{ .returnType }}({{ .defaultVal }}), ms.{{ .fieldName }}())\n\ttestVal{{ .fieldName }} := {{ .packageName }}{{ .returnType }}({{ .testValue }})\n\tms.Set{{ .fieldName }}(testVal{{ .fieldName }})\n\tassert.Equal(t, testVal{{ .fieldName }}, ms.{{ .fieldName }}())\n}`\n\nconst typedSetTestTemplate = `orig.{{ .originFieldName }} = {{ .testValue }}`\n\n// TypedField is a field that has defined a custom type (e.g. \"type Timestamp uint64\")\ntype TypedField struct {\n\tfieldName       string\n\toriginFieldName string\n\tprotoID         uint32\n\treturnType      *TypedType\n}\n\ntype TypedType struct {\n\tstructName  string\n\tpackageName string\n\n\tprotoType   proto.Type\n\tmessageName string\n\n\tdefaultVal string\n\ttestVal    string\n}\n\nfunc (ptf *TypedField) GenerateAccessors(ms *messageStruct) string {\n\tt := tmplutil.Parse(\"typedAccessorsTemplate\", []byte(typedAccessorsTemplate))\n\treturn tmplutil.Execute(t, ptf.templateFields(ms))\n}\n\nfunc (ptf *TypedField) GenerateAccessorsTest(ms *messageStruct) string {\n\tt := tmplutil.Parse(\"typedAccessorsTestTemplate\", []byte(typedAccessorsTestTemplate))\n\treturn tmplutil.Execute(t, ptf.templateFields(ms))\n}\n\nfunc (ptf *TypedField) GenerateTestValue(ms *messageStruct) string {\n\tt := tmplutil.Parse(\"typedSetTestTemplate\", []byte(typedSetTestTemplate))\n\treturn tmplutil.Execute(t, ptf.templateFields(ms))\n}\n\ntype ProtoTypedField struct {\n\t*proto.Field\n}\n\nfunc (ptf ProtoTypedField) GenMarshalJSON() string {\n\tif ptf.MessageName == \"TraceID\" || ptf.MessageName == \"SpanID\" || ptf.MessageName == \"ProfileID\" {\n\t\treturn \"if !orig.\" + ptf.Name + \".IsEmpty() {\\n\" + ptf.Field.GenMarshalJSON() + \"\\n}\"\n\t}\n\treturn ptf.Field.GenMarshalJSON()\n}\n\nfunc (ptf *TypedField) toProtoField(ms *messageStruct) proto.FieldInterface {\n\treturn ProtoTypedField{&proto.Field{\n\t\tType:              ptf.returnType.protoType,\n\t\tID:                ptf.protoID,\n\t\tName:              ptf.getOriginFieldName(),\n\t\tMessageName:       ptf.returnType.messageName,\n\t\tParentMessageName: ms.protoName,\n\t}}\n}\n\nfunc (ptf *TypedField) getOriginFieldName() string {\n\tif ptf.originFieldName == \"\" {\n\t\treturn ptf.fieldName\n\t}\n\treturn ptf.originFieldName\n}\n\nfunc (ptf *TypedField) templateFields(ms *messageStruct) map[string]any {\n\tpf := ptf.toProtoField(ms)\n\tmessageType := pf.GoType()\n\tdefaultVal := ptf.returnType.defaultVal\n\ttestVal := ptf.returnType.testVal\n\tif ptf.returnType.protoType == proto.TypeMessage || ptf.returnType.protoType == proto.TypeEnum {\n\t\tmessageType = \"internal.\" + messageType\n\t\tdefaultVal = \"internal.\" + defaultVal\n\t\ttestVal = \"internal.\" + testVal\n\t}\n\treturn map[string]any{\n\t\t\"structName\": ms.getName(),\n\t\t\"defaultVal\": defaultVal,\n\t\t\"packageName\": func() string {\n\t\t\tif ptf.returnType.packageName != ms.packageName {\n\t\t\t\treturn ptf.returnType.packageName + \".\"\n\t\t\t}\n\t\t\treturn \"\"\n\t\t}(),\n\t\t\"hasWrapper\":      usedByOtherDataTypes(ptf.returnType.packageName),\n\t\t\"returnType\":      ptf.returnType.structName,\n\t\t\"fieldName\":       ptf.fieldName,\n\t\t\"originFieldName\": ptf.getOriginFieldName(),\n\t\t\"lowerFieldName\":  strings.ToLower(ptf.fieldName),\n\t\t\"testValue\":       testVal,\n\t\t\"messageType\":     messageType,\n\t}\n}\n\nvar _ Field = (*TypedField)(nil)\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/pdata/xpdata_entity_package.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pdata // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\n\nimport (\n\t\"path/filepath\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n)\n\nvar xpdataEntity = &Package{\n\tinfo: &PackageInfo{\n\t\tname: \"entity\",\n\t\tpath: filepath.Join(\"xpdata\", \"entity\"),\n\t\timports: []string{\n\t\t\t`\"encoding/binary\"`,\n\t\t\t`\"fmt\"`,\n\t\t\t`\"iter\"`,\n\t\t\t`\"math\"`,\n\t\t\t`\"sort\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/json\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/proto\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/pcommon\"`,\n\t\t},\n\t\ttestImports: []string{\n\t\t\t`\"testing\"`,\n\t\t\t``,\n\t\t\t`\"github.com/stretchr/testify/assert\"`,\n\t\t\t`gootlpcommon \"go.opentelemetry.io/proto/slim/otlp/common/v1\"`,\n\t\t\t``,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/internal/json\"`,\n\t\t\t`\"go.opentelemetry.io/collector/pdata/pcommon\"`,\n\t\t},\n\t},\n\tstructs: []baseStruct{\n\t\tentityRefSlice,\n\t\tentityRef,\n\t},\n}\n\nvar entityRefSlice = &messageSlice{\n\tstructName:      \"EntityRefSlice\",\n\tpackageName:     \"entity\",\n\telementNullable: true,\n\telement:         entityRef,\n}\n\nvar entityRef = &messageStruct{\n\tstructName:    \"EntityRef\",\n\tpackageName:   \"entity\",\n\tprotoName:     \"EntityRef\",\n\tupstreamProto: \"gootlpcommon.EntityRef\",\n\tfields: []Field{\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"SchemaUrl\",\n\t\t\tprotoID:   1,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t\t&PrimitiveField{\n\t\t\tfieldName: \"Type\",\n\t\t\tprotoID:   2,\n\t\t\tprotoType: proto.TypeString,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"IdKeys\",\n\t\t\tprotoID:     3,\n\t\t\tprotoType:   proto.TypeString,\n\t\t\treturnSlice: stringSlice,\n\t\t},\n\t\t&SliceField{\n\t\t\tfieldName:   \"DescriptionKeys\",\n\t\t\tprotoID:     4,\n\t\t\tprotoType:   proto.TypeString,\n\t\t\treturnSlice: stringSlice,\n\t\t},\n\t},\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/copy.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\nimport (\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst copyOther = `{{ if .repeated -}}\n\tdest.{{ .fieldName }} = append(dest.{{ .fieldName }}[:0], src.{{ .fieldName }}...)\n{{ else if ne .oneOfGroup \"\" -}}\n\tvar ov *{{ .oneOfMessageName }}\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\tov = &{{ .oneOfMessageName }}{}\n\t} else {\n\t\tov = ProtoPool{{ .oneOfMessageName }}.Get().(*{{ .oneOfMessageName }})\n\t}\n\tov.{{ .fieldName }} = t.{{ .fieldName }}\n\tdest.{{ .oneOfGroup }} = ov\n{{ else if .nullable -}}\n\tif src.Has{{ .fieldName }}() {\n\t\tdest.Set{{ .fieldName }}(src.{{ .fieldName }})\n\t} else {\n\t\tdest.Remove{{ .fieldName }}()\n\t}\n{{ else -}}\n\tdest.{{ .fieldName }} = src.{{ .fieldName }}\n{{- end }}`\n\nconst copyMessage = `{{ if .repeated -}}\n\tdest.{{ .fieldName }} = Copy{{ .messageName }}{{ if .nullable }}Ptr{{ end }}Slice(dest.{{ .fieldName }}, src.{{ .fieldName }})\n{{- else if ne .oneOfGroup \"\" -}}\n\tvar ov *{{ .oneOfMessageName }}\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\tov = &{{ .oneOfMessageName }}{}\n\t} else {\n\t\tov = ProtoPool{{ .oneOfMessageName }}.Get().(*{{ .oneOfMessageName }})\n\t}\n\tov.{{ .fieldName }} = New{{ .messageName }}()\n\tCopy{{ .messageName }}(ov.{{ .fieldName }}, t.{{ .fieldName }})\n\tdest.{{ .oneOfGroup }} = ov\t\n{{- else if .nullable -}}\n\tdest.{{ .fieldName }} = Copy{{ .messageName }}(dest.{{ .fieldName }}, src.{{ .fieldName }})\n{{- else -}}\n\tCopy{{ .messageName }}(&dest.{{ .fieldName }}, &src.{{ .fieldName }})\n{{- end }}\n`\n\nfunc (pf *Field) GenCopy() string {\n\ttf := pf.getTemplateFields()\n\tif pf.Type == TypeMessage {\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"copyMessage\", []byte(copyMessage)), tf)\n\t}\n\treturn tmplutil.Execute(tmplutil.Parse(\"copyOther\", []byte(copyOther)), tf)\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/delete.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\nimport (\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst deleteOther = `{{ if ne .oneOfGroup \"\" -}}\n\tif metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\tov.{{ .fieldName }} = {{ .defaultValue }}\n\t\tProtoPool{{ .oneOfMessageName }}.Put(ov)\n\t}\n{{- end -}}`\n\nconst deleteMessage = `{{ if .repeated -}}\n\tfor i := range orig.{{ .fieldName }} {\n\t{{ if .nullable -}}\n\t\tDelete{{ .messageName }}(orig.{{ .fieldName }}[i], true)\n\t{{ else -}}\n\t\tDelete{{ .messageName }}(&orig.{{ .fieldName }}[i], false)\n\t{{- end -}}\n\t}\n{{- else if ne .oneOfGroup \"\" -}}\n\tDelete{{ .messageName }}(ov.{{ .fieldName }}, true)\n\tov.{{ .fieldName }} = nil\n\tProtoPool{{ .oneOfMessageName }}.Put(ov)\n{{- else if .nullable -}}\n\tDelete{{ .messageName }}(orig.{{ .fieldName }}, true)\n{{- else -}}\n\tDelete{{ .messageName }}(&orig.{{ .fieldName }}, false)\n{{- end -}}\n`\n\nfunc (pf *Field) GenDelete() string {\n\ttf := pf.getTemplateFields()\n\tif pf.Type == TypeMessage {\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"deleteMessage\", []byte(deleteMessage)), tf)\n\t}\n\tif pf.OneOfGroup != \"\" {\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"deleteOther\", []byte(deleteOther)), tf)\n\t}\n\treturn \"\"\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/enum.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\nimport (\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst enumMessageTemplate = `\n// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nconst (\n\t{{- range .Fields }}\n\t{{ $.Name }}_{{ .Name }} = {{ $.Name }}({{ .Value }})\n\t{{- end }}\n)\n\n{{ .Description }}\ntype {{ .Name }} int32\n\nvar {{ .Name }}_name = map[int32]string {\n\t{{- range .Fields }}\n\t{{ .Value }}: \"{{ .Name }}\",\n\t{{- end }}\n}\n\nvar {{ .Name }}_value = map[string]int32 {\n\t{{- range .Fields }}\n\t\"{{ .Name }}\": {{ .Value }},\n\t{{- end }}\n}\n\n`\n\ntype Enum struct {\n\tName        string\n\tDescription string\n\tFields      []*EnumField\n}\n\ntype EnumField struct {\n\tName  string\n\tValue int\n}\n\nfunc (ms *Enum) GenerateEnum() []byte {\n\treturn []byte(tmplutil.Execute(tmplutil.Parse(\"enumMessageTemplate\", []byte(enumMessageTemplate)), ms))\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/field.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n)\n\n// FieldInterface temporary interface until we generate the proto fields with pdatagen.\n// TODO: Remove when no more wrappers needed.\ntype FieldInterface interface {\n\tGenTestFailingUnmarshalProtoValues() string\n\n\tGenTestEncodingValues() string\n\n\tGenPool() string\n\n\tGenDelete() string\n\n\tGenCopy() string\n\n\tGenMarshalJSON() string\n\n\tGenUnmarshalJSON() string\n\n\tGenSizeProto() string\n\n\tGenMarshalProto() string\n\n\tGenUnmarshalProto() string\n\n\tGenMessageField() string\n\n\tGenOneOfMessages() string\n\n\tGenTest() string\n\n\tGoType() string\n\n\tDefaultValue() string\n\n\tTestValue() string\n\n\tGetName() string\n}\n\ntype Field struct {\n\tType              Type\n\tName              string\n\tOneOfGroup        string\n\tOneOfMessageName  string\n\tMessageName       string\n\tParentMessageName string\n\tID                uint32\n\tRepeated          bool\n\tNullable          bool\n}\n\nfunc (pf *Field) GetName() string { return pf.Name }\n\nfunc (pf *Field) wireType() WireType {\n\tswitch pf.Type {\n\tcase TypeInt32, TypeInt64, TypeUint32, TypeUint64, TypeSInt32, TypeSInt64, TypeBool, TypeEnum:\n\t\t// In proto3, repeated scalar types are packed; hence they use Length-Delimited (Wire Type 2).\n\t\tif pf.Repeated {\n\t\t\treturn WireTypeLen\n\t\t}\n\t\treturn WireTypeVarint\n\tcase TypeFixed32, TypeSFixed32, TypeFloat:\n\t\t// In proto3, repeated scalar types are packed; hence they use Length-Delimited (Wire Type 2).\n\t\tif pf.Repeated {\n\t\t\treturn WireTypeLen\n\t\t}\n\t\treturn WireTypeI32\n\tcase TypeFixed64, TypeSFixed64, TypeDouble:\n\t\t// In proto3, repeated scalar types are packed; hence they use Length-Delimited (Wire Type 2).\n\t\tif pf.Repeated {\n\t\t\treturn WireTypeLen\n\t\t}\n\t\treturn WireTypeI64\n\tcase TypeBytes, TypeMessage, TypeString:\n\t\treturn WireTypeLen\n\tdefault:\n\t\tpanic(\"unsupported field type\")\n\t}\n}\n\nfunc (pf *Field) DefaultValue() string {\n\tswitch pf.Type {\n\tcase TypeInt32, TypeInt64, TypeUint32, TypeUint64, TypeSInt32, TypeSInt64, TypeEnum, TypeFixed32, TypeSFixed32, TypeFloat, TypeFixed64, TypeSFixed64, TypeDouble:\n\t\treturn pf.GoType() + `(0)`\n\tcase TypeBool:\n\t\treturn `false`\n\tcase TypeBytes:\n\t\treturn `nil`\n\tcase TypeString:\n\t\treturn `\"\"`\n\tcase TypeMessage:\n\t\tif pf.Nullable {\n\t\t\treturn `&` + pf.MessageName + `{}`\n\t\t}\n\t\treturn pf.MessageName + `{}`\n\tdefault:\n\t\tpanic(\"unsupported field type\")\n\t}\n}\n\nfunc (pf *Field) GenTest() string {\n\tif pf.Repeated {\n\t\treturn \"orig.\" + pf.GetName() + \" = \" + pf.TestValue()\n\t}\n\n\tif pf.Type != TypeMessage && pf.Nullable {\n\t\treturn \"orig.Set\" + pf.GetName() + \"(\" + pf.TestValue() + \")\"\n\t}\n\treturn \"orig.\" + pf.GetName() + \" = \" + pf.TestValue()\n}\n\nfunc (pf *Field) TestValue() string {\n\tif pf.Repeated {\n\t\treturn pf.MemberGoType() + \"{\" + pf.DefaultValue() + \", \" + pf.rawTestValue() + \"}\"\n\t}\n\treturn pf.rawTestValue()\n}\n\nfunc (pf *Field) rawTestValue() string {\n\tswitch pf.Type {\n\tcase TypeInt32, TypeInt64, TypeUint32, TypeUint64, TypeSInt32, TypeSInt64, TypeEnum, TypeFixed32, TypeSFixed32, TypeFixed64, TypeSFixed64:\n\t\treturn pf.GoType() + \"(13)\"\n\tcase TypeFloat, TypeDouble:\n\t\treturn pf.GoType() + \"(3.1415926)\"\n\tcase TypeBool:\n\t\treturn `true`\n\tcase TypeBytes:\n\t\treturn `[]byte{1, 2, 3}`\n\tcase TypeString:\n\t\treturn `\"test_` + strings.ToLower(pf.Name) + `\"`\n\tcase TypeMessage:\n\t\tif pf.Nullable {\n\t\t\treturn `GenTest` + pf.MessageName + `()`\n\t\t}\n\t\treturn `*GenTest` + pf.MessageName + `()`\n\tdefault:\n\t\tpanic(\"unsupported field type\")\n\t}\n}\n\nfunc (pf *Field) GoType() string {\n\tswitch pf.Type {\n\tcase TypeDouble:\n\t\treturn \"float64\"\n\tcase TypeFloat:\n\t\treturn \"float32\"\n\tcase TypeInt32, TypeSInt32, TypeSFixed32:\n\t\treturn \"int32\"\n\tcase TypeInt64, TypeSInt64, TypeSFixed64:\n\t\treturn \"int64\"\n\tcase TypeUint32, TypeFixed32:\n\t\treturn \"uint32\"\n\tcase TypeUint64, TypeFixed64:\n\t\treturn \"uint64\"\n\tcase TypeBool:\n\t\treturn \"bool\"\n\tcase TypeString:\n\t\treturn \"string\"\n\tcase TypeBytes:\n\t\treturn \"[]byte\"\n\tcase TypeMessage, TypeEnum:\n\t\treturn pf.MessageName\n\tdefault:\n\t\tpanic(\"unsupported field type\")\n\t}\n}\n\nfunc (pf *Field) MemberGoType() string {\n\tptrGoType := func() string {\n\t\tif pf.Nullable {\n\t\t\treturn \"*\" + pf.GoType()\n\t\t}\n\t\treturn pf.GoType()\n\t}\n\tif pf.Repeated {\n\t\treturn \"[]\" + ptrGoType()\n\t}\n\tif pf.Type == TypeMessage {\n\t\treturn ptrGoType()\n\t}\n\treturn pf.GoType()\n}\n\nfunc (pf *Field) GenMessageField() string {\n\treturn pf.Name + \" \" + pf.MemberGoType()\n}\n\nfunc (pf *Field) getTemplateFields() map[string]any {\n\tbitSize := 0\n\tswitch pf.Type {\n\tcase TypeFixed64, TypeSFixed64, TypeInt64, TypeUint64, TypeSInt64, TypeDouble:\n\t\tbitSize = 64\n\tcase TypeFixed32, TypeSFixed32, TypeInt32, TypeUint32, TypeSInt32, TypeFloat, TypeEnum:\n\t\tbitSize = 32\n\t}\n\n\tprotoTag := genProtoTag(pf.ID, pf.wireType())\n\treturn map[string]any{\n\t\t\"protoTagSize\":      len(protoTag),\n\t\t\"protoTag\":          protoTag,\n\t\t\"protoFieldID\":      pf.ID,\n\t\t\"jsonTag\":           genJSONTag(pf.Name),\n\t\t\"fieldName\":         pf.Name,\n\t\t\"messageName\":       pf.MessageName,\n\t\t\"parentMessageName\": pf.ParentMessageName,\n\t\t\"oneOfGroup\":        pf.OneOfGroup,\n\t\t\"oneOfMessageName\":  pf.OneOfMessageName,\n\t\t\"repeated\":          pf.Repeated,\n\t\t\"nullable\":          pf.Nullable,\n\t\t\"bitSize\":           bitSize,\n\t\t\"goType\":            pf.GoType(),\n\t\t\"defaultValue\":      pf.DefaultValue(),\n\t\t\"testValue\":         pf.TestValue(),\n\t}\n}\n\nfunc genJSONTag(fieldName string) string {\n\t// Extract last word because for Enums we use the full name.\n\treturn lowerFirst(ExtractNameFromFull(fieldName))\n}\n\n// genProtoTag encodes the field key, and returns it in the reverse order.\nfunc genProtoTag(fieldNumber uint32, wt WireType) []string {\n\tx := fieldNumber<<3 | uint32(wt)\n\ti := 0\n\tkeybuf := make([]byte, 0)\n\tfor i = 0; x > 127; i++ {\n\t\tkeybuf = append(keybuf, 0x80|uint8(x&0x7F))\n\t\tx >>= 7\n\t}\n\tkeybuf = append(keybuf, uint8(x))\n\tret := make([]string, 0, len(keybuf))\n\tfor i = len(keybuf) - 1; i >= 0; i-- {\n\t\tret = append(ret, fmt.Sprintf(\"%#v\", keybuf[i]))\n\t}\n\treturn ret\n}\n\nfunc ExtractNameFromFull(fullName string) string {\n\t// Extract last word because for Enums we use the full name.\n\tlastSpaceIndex := strings.LastIndex(fullName, \".\")\n\tif lastSpaceIndex != -1 {\n\t\treturn fullName[lastSpaceIndex+1:]\n\t}\n\treturn fullName\n}\n\nfunc lowerFirst(s string) string {\n\treturn strings.ToLower(s[0:1]) + s[1:]\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/json_marshal.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\nimport (\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst marshalJSONPrimitive = `{{ if .repeated -}}\n\tif len(orig.{{ .fieldName }}) > 0 {\n\t\tdest.WriteObjectField(\"{{ .jsonTag }}\")\n\t\tdest.WriteArrayStart()\n\t\tdest.Write{{ upperFirst .goType }}(orig.{{ .fieldName }}[0])\n\t\tfor i := 1; i < len(orig.{{ .fieldName }}); i++ {\n\t\t\tdest.WriteMore()\n\t\t\tdest.Write{{ upperFirst .goType }}(orig.{{ .fieldName }}[i])\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n{{ else if ne .oneOfGroup \"\" -}}\n\t\tdest.WriteObjectField(\"{{ .jsonTag }}\")\n\t\tdest.Write{{ upperFirst .goType }}(orig.{{ .fieldName }})\n{{- else }}\n{{- if not .nullable -}}\n\tif orig.{{ .fieldName }} != {{ .defaultValue }} {\n{{- else -}}\n\tif orig.Has{{ .fieldName }} () {\n{{ end -}}\n\t\tdest.WriteObjectField(\"{{ .jsonTag }}\")\n\t\tdest.Write{{ upperFirst .goType }}(orig.{{ .fieldName }})\n\t}\n{{- end }}`\n\nconst marshalJSONEnum = `{{ if .repeated -}}\n\tif len(orig.{{ .fieldName }}) > 0 {\n\t\tdest.WriteObjectField(\"{{ .jsonTag }}\")\n\t\tdest.WriteArrayStart()\n\t\tdest.WriteInt32(int32(orig.{{ .fieldName }}[0]))\n\t\tfor i := 1; i < len(orig.{{ .fieldName }}); i++ {\n\t\t\tdest.WriteMore()\n\t\t\tdest.WriteInt32(int32(orig.{{ .fieldName }}[i]))\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n{{- else }}\n\tif int32(orig.{{ .fieldName }}) != 0 {\n\t\tdest.WriteObjectField(\"{{ .jsonTag }}\")\n\t\tdest.WriteInt32(int32(orig.{{ .fieldName }}))\n\t}\n{{- end }}`\n\nconst marshalJSONMessage = `{{ if .repeated -}}\n\tif len(orig.{{ .fieldName }}) > 0 {\n\t\tdest.WriteObjectField(\"{{ .jsonTag }}\")\n\t\tdest.WriteArrayStart()\n\t\torig.{{ .fieldName }}[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.{{ .fieldName }}); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.{{ .fieldName }}[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n{{- else }}\n{{- if .nullable -}}\n\tif orig.{{ .fieldName }} != nil {\n{{ end -}}\n\tdest.WriteObjectField(\"{{ .jsonTag }}\")\n\torig.{{ .fieldName }}.MarshalJSON(dest)\n{{- if .nullable -}}\n\t}\n{{- end }}{{- end }}`\n\nconst marshalJSONBytes = `{{ if .repeated -}}\n\tif len(orig.{{ .fieldName }}) > 0 {\n\t\tdest.WriteObjectField(\"{{ .jsonTag }}\")\n\t\tdest.WriteArrayStart()\n\t\tdest.WriteBytes(orig.{{ .fieldName }}[0])\n\t\tfor i := 1; i < len(orig.{{ .fieldName }}); i++ {\n\t\t\tdest.WriteMore()\n\t\t\tdest.WriteBytes(orig.{{ .fieldName }}[i])\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n{{- else }}{{ if not .nullable }}\n\tif len(orig.{{ .fieldName }}) > 0 {\n{{- end }}\n\t\tdest.WriteObjectField(\"{{ .jsonTag }}\")\n\t\tdest.WriteBytes(orig.{{ .fieldName }})\n{{- if not .nullable -}}\n\t}\n{{- end }}{{- end }}`\n\nfunc (pf *Field) GenMarshalJSON() string {\n\ttf := pf.getTemplateFields()\n\tswitch pf.Type {\n\tcase TypeBytes:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"marshalJSONBytes\", []byte(marshalJSONBytes)), tf)\n\tcase TypeMessage:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"marshalJSONMessage\", []byte(marshalJSONMessage)), tf)\n\tcase TypeEnum:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"marshalJSONEnum\", []byte(marshalJSONEnum)), tf)\n\tcase TypeDouble, TypeFloat,\n\t\tTypeFixed64, TypeSFixed64, TypeFixed32, TypeSFixed32,\n\t\tTypeInt32, TypeInt64, TypeUint32, TypeUint64,\n\t\tTypeSInt32, TypeSInt64,\n\t\tTypeBool, TypeString:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"marshalJSONPrimitive\", []byte(marshalJSONPrimitive)), tf)\n\t}\n\tpanic(fmt.Sprintf(\"unhandled case %T\", pf.Type))\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/json_unmarshal.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\nimport (\n\t\"fmt\"\n\t\"strings\"\n\n\t\"github.com/ettle/strcase\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst unmarshalJSONPrimitive = `\tcase {{ .allJSONTags }}:\n{{ if .repeated -}}\n\tfor iter.ReadArray() {\n\t\torig.{{ .fieldName }} = append(orig.{{ .fieldName }}, iter.Read{{ upperFirst .goType }}())\n\t}\n{{ else if ne .oneOfGroup \"\" -}}\n\t{\n\t\tvar ov *{{ .oneOfMessageName }}\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &{{ .oneOfMessageName }}{}\n\t\t} else {\n\t\t\tov = ProtoPool{{ .oneOfMessageName }}.Get().(*{{ .oneOfMessageName }})\n\t\t}\n\t\tov.{{ .fieldName }} = iter.Read{{ upperFirst .goType }}()\n\t\torig.{{ .oneOfGroup }} = ov\n\t}\n{{ else if .nullable -}}\n\torig.Set{{ .fieldName }}(iter.Read{{ upperFirst .goType }}())\n{{ else -}}\n\torig.{{ .fieldName }} = iter.Read{{ upperFirst .goType }}()\n{{- end }}`\n\nconst unmarshalJSONEnum = `\tcase {{ .allJSONTags }}:\n{{ if .repeated -}}\n\tfor iter.ReadArray() {\n\t\torig.{{ .fieldName }} = append(orig.{{ .fieldName }}, {{ .messageName }}(iter.ReadEnumValue({{ .messageName }}_value)))\n\t}\n{{ else -}}\n\torig.{{ .fieldName }} = {{ .messageName }}(iter.ReadEnumValue({{ .messageName }}_value))\n{{- end }}`\n\nconst unmarshalJSONMessage = `\tcase {{ .allJSONTags }}:\n{{ if .repeated -}}\n\tfor iter.ReadArray() {\n\t\torig.{{ .fieldName }} = append(orig.{{ .fieldName }}, {{ if .nullable }}New{{ .messageName }}(){{ else }}{{ .defaultValue }}{{ end }})\n\t\torig.{{ .fieldName }}[len(orig.{{ .fieldName }}) - 1].UnmarshalJSON(iter)\n\t}\n{{ else if ne .oneOfGroup \"\" -}}\n\t{\n\t\tvar ov *{{ .oneOfMessageName }}\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &{{ .oneOfMessageName }}{}\n\t\t} else {\n\t\t\tov = ProtoPool{{ .oneOfMessageName }}.Get().(*{{ .oneOfMessageName }})\n\t\t}\n\t\tov.{{ .fieldName }} = New{{ .messageName }}()\n\t\tov.{{ .fieldName }}.UnmarshalJSON(iter)\n\t\torig.{{ .oneOfGroup }} = ov\n\t}\n{{ else -}}\n\t{{ if .nullable }}orig.{{ .fieldName }} = New{{ .messageName }}(){{ end }}\n\torig.{{ .fieldName }}.UnmarshalJSON(iter)\n{{- end }}`\n\nconst unmarshalJSONBytes = `\tcase {{ .allJSONTags }}:\n{{ if .repeated -}}\n\tfor iter.ReadArray() {\n\t\torig.{{ .fieldName }} = append(orig.{{ .fieldName }}, iter.ReadBytes())\n\t}\n{{ else if ne .oneOfGroup \"\" -}}\n\t{\n\t\tvar ov *{{ .oneOfMessageName }}\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &{{ .oneOfMessageName }}{}\n\t\t} else {\n\t\t\tov = ProtoPool{{ .oneOfMessageName }}.Get().(*{{ .oneOfMessageName }})\n\t\t}\n\t\tov.{{ .fieldName }} = iter.ReadBytes()\n\t\torig.{{ .oneOfGroup }} = ov\n\t}\n{{ else -}}\n\torig.{{ .fieldName }} = iter.ReadBytes()\n{{- end }}`\n\nfunc (pf *Field) GenUnmarshalJSON() string {\n\ttf := pf.getTemplateFields()\n\ttf[\"allJSONTags\"] = allJSONTags(pf.Name)\n\tswitch pf.Type {\n\tcase TypeBytes:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"unmarshalJSONBytes\", []byte(unmarshalJSONBytes)), tf)\n\tcase TypeMessage:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"unmarshalJSONMessage\", []byte(unmarshalJSONMessage)), tf)\n\tcase TypeEnum:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"unmarshalJSONEnum\", []byte(unmarshalJSONEnum)), tf)\n\tcase TypeDouble, TypeFloat,\n\t\tTypeFixed64, TypeSFixed64, TypeFixed32, TypeSFixed32,\n\t\tTypeInt32, TypeInt64, TypeUint32, TypeUint64,\n\t\tTypeSInt32, TypeSInt64,\n\t\tTypeBool, TypeString:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"unmarshalJSONPrimitive\", []byte(unmarshalJSONPrimitive)), tf)\n\t}\n\tpanic(fmt.Sprintf(\"unhandled case %T\", pf.Type))\n}\n\nfunc allJSONTags(str string) string {\n\tsnake := strcase.ToSnake(str)\n\tif !strings.EqualFold(str, snake) {\n\t\treturn `\"` + lowerFirst(str) + `\", \"` + snake + `\"`\n\t}\n\treturn `\"` + lowerFirst(str) + `\"`\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/message.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\nimport (\n\t_ \"embed\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nvar (\n\t//go:embed templates/message.go.tmpl\n\tmessageTemplateBytes []byte\n\tmessageTemplate      = tmplutil.Parse(\"message_internal_test.go\", messageTemplateBytes)\n\n\t//go:embed templates/message_test.go.tmpl\n\tmessageTestTemplateBytes []byte\n\tmessageTestTemplate      = tmplutil.Parse(\"message_internal_test.go\", messageTestTemplateBytes)\n)\n\ntype Message struct {\n\tName            string\n\tDescription     string\n\tOriginFullName  string\n\tUpstreamMessage string\n\tFields          []FieldInterface\n\tmetadata        *Metadata\n}\n\nfunc (ms *Message) GenerateMessage(imports, testImports []string) []byte {\n\tms.metadata = newMetadata(ms)\n\treturn []byte(tmplutil.Execute(messageTemplate, ms.templateFields(imports, testImports)))\n}\n\nfunc (ms *Message) GenerateMessageTests(imports, testImports []string) []byte {\n\treturn []byte(tmplutil.Execute(messageTestTemplate, ms.templateFields(imports, testImports)))\n}\n\nfunc (ms *Message) GenerateMetadata() string {\n\treturn string(ms.metadata.Generate())\n}\n\nfunc (ms *Message) templateFields(imports, testImports []string) map[string]any {\n\treturn map[string]any{\n\t\t\"fields\":          ms.Fields,\n\t\t\"messageName\":     ms.Name,\n\t\t\"upstreamMessage\": ms.UpstreamMessage,\n\t\t\"description\":     ms.Description,\n\t\t\"imports\":         imports,\n\t\t\"testImports\":     testImports,\n\t\t// 0 size means no metadata is needed\n\t\t\"metadataSize\":     ms.metadataSize(),\n\t\t\"GenerateMetadata\": ms.GenerateMetadata,\n\t}\n}\n\nfunc (ms *Message) metadataSize() int {\n\tif ms.metadata == nil {\n\t\treturn 0\n\t}\n\n\tif len(ms.metadata.OptionalFields) == 0 {\n\t\treturn 0\n\t}\n\n\treturn ms.metadata.OptionalFields[len(ms.metadata.OptionalFields)-1].Value/64 + 1\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/metadata.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\nimport (\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst metadataMessageTemplate = `\n{{- range .OptionalFields }}\nconst fieldBlock{{ $.Name }}{{ .Name }} = uint64({{ .Value }} >> 6)\nconst fieldBit{{ $.Name }}{{ .Name }} = uint64(1 << {{ .Value }} & 0x3F)\n\nfunc (m *{{ $.Name }}) Set{{ .Name }}(value {{ .GoType }}) {\n\tm.{{ .Name }} = value\n\tm.metadata[fieldBlock{{ $.Name }}{{ .Name }}] |= fieldBit{{ $.Name }}{{ .Name }}\n}\n\nfunc (m *{{ $.Name }}) Remove{{ .Name }}() {\n\tm.{{ .Name }} = {{ .DefaultValue }}\n\tm.metadata[fieldBlock{{ $.Name }}{{ .Name }}] &^= fieldBit{{ $.Name }}{{ .Name }}\n}\n\nfunc (m *{{ $.Name }}) Has{{ .Name }}() bool {\n\treturn m.metadata[fieldBlock{{ $.Name }}{{ .Name }}] & fieldBit{{ $.Name }}{{ .Name }} != 0\n}\n{{- end }}\n\n`\n\ntype Metadata struct {\n\tName           string\n\tOptionalFields []*MetadataOptionalField\n}\n\ntype MetadataOptionalField struct {\n\t*Field\n\tValue int\n}\n\nfunc newMetadata(ms *Message) *Metadata {\n\tmeta := &Metadata{\n\t\tName: ms.Name,\n\t}\n\tvalue := 0\n\tfor _, fieldI := range ms.Fields {\n\t\tfield, ok := fieldI.(*Field)\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\t\tif field.Repeated {\n\t\t\tcontinue\n\t\t}\n\t\tswitch field.Type {\n\t\tcase TypeDouble, TypeFloat, TypeInt32, TypeInt64, TypeUint32, TypeUint64, TypeSInt32, TypeSInt64, TypeFixed32, TypeFixed64, TypeSFixed32, TypeSFixed64, TypeBool:\n\t\t\tif !field.Nullable {\n\t\t\t\tcontinue\n\t\t\t}\n\t\tdefault:\n\t\t\tcontinue\n\t\t}\n\t\tmeta.OptionalFields = append(meta.OptionalFields, &MetadataOptionalField{\n\t\t\tField: field,\n\t\t\tValue: value,\n\t\t})\n\t\tvalue++\n\t}\n\tif len(meta.OptionalFields) == 0 {\n\t\treturn nil\n\t}\n\treturn meta\n}\n\nfunc (meta *Metadata) Generate() []byte {\n\treturn []byte(tmplutil.Execute(tmplutil.Parse(\"metadataMessageTemplate\", []byte(metadataMessageTemplate)), meta))\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/oneof_message.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\nimport (\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst oneOfMessageOrigOtherTemplate = `\ntype {{ .oneOfMessageName }} struct {\n\t{{ .fieldName }} {{ .goType }}\n}\n\nfunc (m *{{ .parentMessageName }}) Get{{ .fieldName }}() {{ .goType }} {\n\tif v, ok := m.Get{{ .oneOfGroup }}().(*{{ .oneOfMessageName }}); ok {\n\t\treturn v.{{ .fieldName }}\n\t}\n\treturn {{ .defaultValue }}\n}\n`\n\nconst oneOfMessageOrigMessageTemplate = `\ntype {{ .oneOfMessageName }} struct {\n\t{{ .fieldName }} *{{ .goType }}\n}\n\nfunc (m *{{ .parentMessageName }}) Get{{ .fieldName }}() *{{ .goType }} {\n\tif v, ok := m.Get{{ .oneOfGroup }}().(*{{ .oneOfMessageName }}); ok {\n\t\treturn v.{{ .fieldName }}\n\t}\n\treturn nil\n}\n`\n\nfunc (pf *Field) GenOneOfMessages() string {\n\ttf := pf.getTemplateFields()\n\tif pf.OneOfGroup != \"\" {\n\t\tif pf.Type == TypeMessage {\n\t\t\treturn tmplutil.Execute(tmplutil.Parse(\"oneOfMessageOrigMessageTemplate\", []byte(oneOfMessageOrigMessageTemplate)), tf)\n\t\t}\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"oneOfMessageOrigOtherTemplate\", []byte(oneOfMessageOrigOtherTemplate)), tf)\n\t}\n\treturn \"\"\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/pools.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\nimport (\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst poolVarOrigTemplate = `\n\tProtoPool{{ .oneOfMessageName }} = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &{{ .oneOfMessageName }}{}\n\t\t},\n\t}\n`\n\nfunc (pf *Field) GenPool() string {\n\ttf := pf.getTemplateFields()\n\tif pf.OneOfGroup != \"\" {\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"poolVarOrigTemplate\", []byte(poolVarOrigTemplate)), tf)\n\t}\n\treturn \"\"\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/proto.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\ntype Type int32\n\nconst (\n\tTypeDouble Type = iota\n\tTypeFloat\n\n\tTypeInt32\n\tTypeInt64\n\tTypeUint32\n\tTypeUint64\n\n\tTypeSInt32\n\tTypeSInt64\n\n\tTypeFixed32\n\tTypeFixed64\n\tTypeSFixed32\n\tTypeSFixed64\n\n\tTypeBool\n\tTypeEnum\n\n\tTypeString\n\tTypeBytes\n\n\tTypeMessage\n)\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/proto_marshal.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\nimport (\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst marshalProtoFloat = `{{ if .repeated -}}\n\tl = len(orig.{{ .fieldName }})\n\tif l > 0 {\n\t\tfor i := l - 1; i >= 0; i-- {\n\t\t\tpos -= {{ div .bitSize 8 }}\n\t\t\tbinary.LittleEndian.PutUint{{ .bitSize }}(buf[pos:], math.Float{{ .bitSize }}bits(orig.{{ .fieldName }}[i]))\n\t\t}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l*{{ div .bitSize 8 }}))\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n\t}\n{{- else if ne .oneOfGroup \"\" -}}\n\t\tpos -= {{ div .bitSize 8 }}\n\t\tbinary.LittleEndian.PutUint{{ .bitSize }}(buf[pos:], math.Float{{ .bitSize }}bits(orig.{{ .fieldName }}))\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n{{- else }}\n\t{{- if not .nullable -}}\n\tif orig.{{ .fieldName }} != {{ .defaultValue }} {\n\t{{- else -}}\n\tif orig.Has{{ .fieldName }}() {\n\t{{- end }}\n\t\tpos -= {{ div .bitSize 8 }}\n\t\tbinary.LittleEndian.PutUint{{ .bitSize }}(buf[pos:], math.Float{{ .bitSize }}bits(orig.{{ .fieldName }}))\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n\t}\n{{- end }}`\n\nconst marshalProtoFixed = `{{ if .repeated -}}\n\tl = len(orig.{{ .fieldName }})\n\tif l > 0 {\n\t\tfor i := l - 1; i >= 0; i-- {\n\t\t\tpos -= {{ div .bitSize 8 }}\n\t\t\tbinary.LittleEndian.PutUint{{ .bitSize }}(buf[pos:], uint{{ .bitSize }}(orig.{{ .fieldName }}[i]))\n\t\t}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l*{{ div .bitSize 8 }}))\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n\t}\n{{- else if ne .oneOfGroup \"\" -}}\n\t\tpos -= {{ div .bitSize 8 }}\n\t\tbinary.LittleEndian.PutUint{{ .bitSize }}(buf[pos:], uint{{ .bitSize }}(orig.{{ .fieldName }}))\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n{{- else }}\n\t{{- if not .nullable -}}\n\tif orig.{{ .fieldName }} != {{ .defaultValue }} {\n\t{{- else -}}\n\tif orig.Has{{ .fieldName }}() {\n\t{{- end }}\n\t\tpos -= {{ div .bitSize 8 }}\n\t\tbinary.LittleEndian.PutUint{{ .bitSize }}(buf[pos:], uint{{ .bitSize }}(orig.{{ .fieldName }}))\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n\t}\n{{- end }}`\n\nconst marshalProtoBool = `{{ if .repeated -}}\n\tl = len(orig.{{ .fieldName }})\n\tif l > 0 {\n\t\tfor i := l - 1; i >= 0; i-- {\n\t\t\tpos--\n\t\t\tif orig.{{ .fieldName }}[i] {\n\t\t\t\tbuf[pos] = 1\n\t\t\t} else {\n\t\t\t\tbuf[pos] = 0\n\t\t\t}\n\t\t}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n\t}\n{{- else if ne .oneOfGroup \"\" -}}\n\t\tpos--\n\t\tif orig.{{ .fieldName }} {\n\t\t\tbuf[pos] = 1\n\t\t} else {\n\t\t\tbuf[pos] = 0\n\t\t}\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n{{- else }}\n\t{{- if not .nullable -}}\n\tif orig.{{ .fieldName }} != {{ .defaultValue }} {\n\t{{- else -}}\n\tif orig.Has{{ .fieldName }}() {\n\t{{- end }}\n\t\tpos--\n\t\tif orig.{{ .fieldName }} {\n\t\t\tbuf[pos] = 1\n\t\t} else {\n\t\t\tbuf[pos] = 0\n\t\t}\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n\t}\n{{- end }}`\n\nconst marshalProtoVarint = `{{ if .repeated -}}\n\tl = len(orig.{{ .fieldName }})\n\tif l > 0 {\n\t\tendPos := pos\n\t\tfor i := l - 1; i >= 0; i-- {\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.{{ .fieldName }}[i]))\n\t\t}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(endPos-pos))\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n\t}\n{{- else if ne .oneOfGroup \"\" -}}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.{{ .fieldName }}))\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n{{- else }}\n\t{{- if not .nullable -}}\n\tif orig.{{ .fieldName }} != {{ .defaultValue }} {\n\t{{- else -}}\n\tif orig.Has{{ .fieldName }}() {\n\t{{- end }}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.{{ .fieldName }}))\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n\t}\n{{- end }}`\n\nconst marshalProtoBytesString = `{{ if .repeated -}}\n\tfor i := len(orig.{{ .fieldName }}) - 1; i >= 0; i-- {\n\t\tl = len(orig.{{ .fieldName }}[i])\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.{{ .fieldName }}[i])\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n\t}\n{{- else -}}\n\tl = len(orig.{{ .fieldName }})\n{{ if not .nullable -}}\n\tif l > 0 {\n{{ end -}}\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.{{ .fieldName }})\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n{{- if not .nullable -}}\n\t}\n{{- end }}{{- end }}`\n\nconst marshalProtoMessage = `{{ if .repeated -}}\n\tfor i := len(orig.{{ .fieldName }}) - 1; i >= 0; i-- {\n\t\tl = orig.{{ .fieldName }}[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n\t}\n{{- else if .nullable -}}\n\tif orig.{{ .fieldName }} != nil {\n\t\tl = orig.{{ .fieldName }}.MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n\t}\n{{- else -}}\n\tl = orig.{{ .fieldName }}.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t{{ range .protoTag -}}\n\tpos--\n\tbuf[pos] = {{ . }}\n\t{{ end -}}\n{{- end }}`\n\nconst marshalProtoSignedVarint = `{{ if .repeated -}}\n\tl = len(orig.{{ .fieldName }})\n\tif l > 0 {\n\t\tendPos := pos\n\t\tfor i := l - 1; i >= 0; i-- {\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64((uint{{ .bitSize }}(orig.{{ .fieldName }}[i])<<1)^uint{{ .bitSize }}(orig.{{ .fieldName }}[i]>>{{ sub .bitSize 1}})))\n\t\t}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(endPos-pos))\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n\t}\n{{- else if ne .oneOfGroup \"\" -}}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64((uint{{ .bitSize }}(orig.{{ .fieldName }})<<1)^uint{{ .bitSize }}(orig.{{ .fieldName }}>>{{ sub .bitSize 1}})))\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n{{- else }}\n\t{{- if not .nullable -}}\n\tif orig.{{ .fieldName }} != {{ .defaultValue }} {\n\t{{- else -}}\n\tif orig.Has{{ .fieldName }}() {\n\t{{- end }}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64((uint{{ .bitSize }}(orig.{{ .fieldName }})<<1)^uint{{ .bitSize }}(orig.{{ .fieldName }}>>{{ sub .bitSize 1}})))\n\t\t{{ range .protoTag -}}\n\t\tpos--\n\t\tbuf[pos] = {{ . }}\n\t\t{{ end -}}\n\t}\n{{- end }}`\n\nfunc (pf *Field) GenMarshalProto() string {\n\ttf := pf.getTemplateFields()\n\tswitch pf.Type {\n\tcase TypeDouble, TypeFloat:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"marshalProtoFloat\", []byte(marshalProtoFloat)), tf)\n\tcase TypeFixed64, TypeSFixed64, TypeFixed32, TypeSFixed32:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"marshalProtoFixed\", []byte(marshalProtoFixed)), tf)\n\tcase TypeInt32, TypeInt64, TypeUint32, TypeUint64, TypeEnum:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"marshalProtoVarint\", []byte(marshalProtoVarint)), tf)\n\tcase TypeBool:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"marshalProtoBool\", []byte(marshalProtoBool)), tf)\n\tcase TypeBytes, TypeString:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"marshalProtoBytesString\", []byte(marshalProtoBytesString)), tf)\n\tcase TypeMessage:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"marshalProtoMessage\", []byte(marshalProtoMessage)), tf)\n\tcase TypeSInt32, TypeSInt64:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"marshalProtoSignedVarint\", []byte(marshalProtoSignedVarint)), tf)\n\t}\n\tpanic(fmt.Sprintf(\"unhandled case %T\", pf.Type))\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/proto_size.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\nimport (\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst sizeProtoI8 = `{{ if .repeated -}}\n\tl = len(orig.{{ .fieldName }})\n\tif l > 0 {\n\t\tl *= 8\n\t\tn+= {{ .protoTagSize }} + proto.Sov(uint64(l)) + l\n\t}\n{{- else if ne .oneOfGroup \"\" }}\n\t\tn+= {{ add .protoTagSize 8 }}\n{{- else }}\n\t{{- if not .nullable -}}\n\tif orig.{{ .fieldName }} != {{ .defaultValue }} {\n\t{{- else -}}\n\tif orig.Has{{ .fieldName }}() {\n\t{{- end }}\n\t\tn+= {{ add .protoTagSize 8 }}\n\t}\n{{- end }}`\n\nconst sizeProtoI4 = `{{ if .repeated -}}\n\tl = len(orig.{{ .fieldName }})\n\tif l > 0 {\n\t\tl *= 4\n\t\tn+= + {{ .protoTagSize }} + proto.Sov(uint64(l)) + l\n\t}\n{{- else if ne .oneOfGroup \"\" }}\n\t\tn+= {{ add .protoTagSize 4 }}\n{{- else }}\n\t{{- if not .nullable -}}\n\tif orig.{{ .fieldName }} != {{ .defaultValue }} {\n\t{{- else -}}\n\tif orig.Has{{ .fieldName }}() {\n\t{{- end }}\n\t\tn+= {{ add .protoTagSize 4 }}\n\t}\n{{- end }}`\n\nconst sizeProtoBool = `{{ if .repeated -}}\n\tl = len(orig.{{ .fieldName }})\n\tif l > 0 {\n\t\tn+= + {{ .protoTagSize }} + proto.Sov(uint64(l)) + l\n\t}\n{{- else if ne .oneOfGroup \"\" }}\n\t\tn+= {{ add .protoTagSize 1 }}\n{{- else -}}\n\t{{- if not .nullable -}}\n\tif orig.{{ .fieldName }} != {{ .defaultValue }} {\n\t{{- else -}}\n\tif orig.Has{{ .fieldName }}() {\n\t{{- end }}\n\t\tn+= {{ add .protoTagSize 1 }}\n\t}\n{{- end }}`\n\nconst sizeProtoVarint = `{{ if .repeated }}\n\tif len(orig.{{ .fieldName }}) > 0 {\n\t\tl = 0\n\t\tfor _, e := range orig.{{ .fieldName }} {\n\t\t\tl += proto.Sov(uint64(e))\n\t\t}\n\t\tn+= {{ .protoTagSize }} + proto.Sov(uint64(l)) + l\n\t}\n{{- else if ne .oneOfGroup \"\" }}\n\t\tn+= {{ .protoTagSize }} + proto.Sov(uint64(orig.{{ .fieldName }}))\n{{- else }}\n\t{{- if not .nullable -}}\n\tif orig.{{ .fieldName }} != {{ .defaultValue }} {\n\t{{- else -}}\n\tif orig.Has{{ .fieldName }}() {\n\t{{- end }}\n\t\tn+= {{ .protoTagSize }} + proto.Sov(uint64(orig.{{ .fieldName }}))\n\t}\n{{- end }}`\n\nconst sizeProtoBytesString = `{{ if .repeated -}}\n\tfor _, s := range orig.{{ .fieldName }} {\n\t\tl = len(s)\n\t\tn+= {{ .protoTagSize }} + proto.Sov(uint64(l)) + l\n\t}\n{{- else if ne .oneOfGroup \"\" -}}\n\t\tl = len(orig.{{ .fieldName }})\n\t\tn+= {{ .protoTagSize }} + proto.Sov(uint64(l)) + l\n{{- else }}\n\tl = len(orig.{{ .fieldName }})\n\tif l > 0 {\n\t\tn+= {{ .protoTagSize }} + proto.Sov(uint64(l)) + l\n\t}\n{{- end }}`\n\nconst sizeProtoMessage = `{{ if .repeated -}}\n\tfor i := range orig.{{ .fieldName }} {\n\t\tl = orig.{{ .fieldName }}[i].SizeProto()\n\t\tn+= {{ .protoTagSize }} + proto.Sov(uint64(l)) + l\n\t}\n{{- else if .nullable -}}\n\tif orig.{{ .fieldName }} != nil {\n\t\tl = orig.{{ .fieldName }}.SizeProto()\n\t\tn+= {{ .protoTagSize }} + proto.Sov(uint64(l)) + l\n\t}\n{{- else -}}\n\tl = orig.{{ .fieldName }}.SizeProto()\n\tn+= {{ .protoTagSize }} + proto.Sov(uint64(l)) + l\n{{- end }}`\n\nconst sizeProtoSignedVarint = `{{ if .repeated -}}\n\tif len(orig.{{ .fieldName }}) > 0 {\n\t\tl = 0\n\t\tfor _, e := range orig.{{ .fieldName }} {\n\t\t\tl += proto.Soz(uint64(e))\n\t\t}\n\t\tn+= {{ .protoTagSize }} + proto.Sov(uint64(l)) + l\n\t}\n{{- else if ne .oneOfGroup \"\" -}}\n\tn+= {{ .protoTagSize }} + proto.Soz(uint64(orig.{{ .fieldName }}))\n{{- else -}}\n\t{{- if not .nullable -}}\n\tif orig.{{ .fieldName }} != {{ .defaultValue }} {\n\t{{- else -}}\n\tif orig.Has{{ .fieldName }}() {\n\t{{- end }}\n\t\tn+= {{ .protoTagSize }} + proto.Soz(uint64(orig.{{ .fieldName }}))\n\t}\n{{- end }}`\n\nfunc (pf *Field) GenSizeProto() string {\n\ttf := pf.getTemplateFields()\n\tswitch pf.Type {\n\tcase TypeFixed64, TypeSFixed64, TypeDouble:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"sizeProtoI8\", []byte(sizeProtoI8)), tf)\n\tcase TypeFixed32, TypeSFixed32, TypeFloat:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"sizeProtoI4\", []byte(sizeProtoI4)), tf)\n\tcase TypeInt32, TypeInt64, TypeUint32, TypeUint64, TypeEnum:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"sizeProtoVarint\", []byte(sizeProtoVarint)), tf)\n\tcase TypeBool:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"sizeProtoBool\", []byte(sizeProtoBool)), tf)\n\tcase TypeBytes, TypeString:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"sizeProtoBytesString\", []byte(sizeProtoBytesString)), tf)\n\tcase TypeMessage:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"sizeProtoMessage\", []byte(sizeProtoMessage)), tf)\n\tcase TypeSInt32, TypeSInt64:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"sizeProtoSignedVarint\", []byte(sizeProtoSignedVarint)), tf)\n\t}\n\tpanic(fmt.Sprintf(\"unhandled case %T\", pf.Type))\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/proto_unmarshal.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\nimport (\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst unmarshalProtoFloat = `{{ if .repeated -}}\n\tcase {{ .protoFieldID }}:\n\t\tswitch wireType {\n\t\tcase proto.WireTypeLen:\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tsize := length / {{ div .bitSize 8 }}\n\t\t\torig.{{ .fieldName }} = make([]{{ .goType }}, size)\n\t\t\tvar num uint{{ .bitSize }}\n\t\t\tfor i := 0; i < size; i++ {\n\t\t\t\tnum, startPos, err = proto.ConsumeI{{ .bitSize }}(buf[:pos], startPos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\torig.{{ .fieldName }}[i] = math.Float{{ .bitSize }}frombits(num)\n\t\t\t}\n\t\t\tif startPos != pos {\n\t\t\t\treturn fmt.Errorf(\"proto: invalid field len = %d for field {{ .fieldName }}\", pos - startPos)\n\t\t\t}\n\t\tcase proto.WireTypeI{{ .bitSize }}:\n\t\t\tvar num uint{{ .bitSize }}\n\t\t\tnum, pos, err = proto.ConsumeI{{ .bitSize }}(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.{{ .fieldName }} = append(orig.{{ .fieldName }}, math.Float{{ .bitSize }}frombits(num))\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field {{ .fieldName }}\", wireType)\n\t\t}\n{{- else }}\n\tcase {{ .protoFieldID }}:\n\t\tif wireType != proto.WireTypeI{{ .bitSize }} {\n\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field {{ .fieldName }}\", wireType)\n\t\t}\n\t\tvar num uint{{ .bitSize }}\n\t\tnum, pos, err = proto.ConsumeI{{ .bitSize }}(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n{{ if ne .oneOfGroup \"\" -}}\n\t\tvar ov *{{ .oneOfMessageName }}\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &{{ .oneOfMessageName }}{}\n\t\t} else {\n\t\t\tov = ProtoPool{{ .oneOfMessageName }}.Get().(*{{ .oneOfMessageName }})\n\t\t}\n\t\tov.{{ .fieldName }} = math.Float{{ .bitSize }}frombits(num)\n\t\torig.{{ .oneOfGroup }} = ov\n{{- else if .nullable -}}\n\t\torig.Set{{ .fieldName }}(math.Float{{ .bitSize }}frombits(num))\n{{- else -}}\n\t\torig.{{ .fieldName }} = math.Float{{ .bitSize }}frombits(num)\n{{- end }}{{- end }}`\n\nconst unmarshalProtoFixed = `{{ if .repeated -}}\n\tcase {{ .protoFieldID }}:\n\t\tswitch wireType {\n\t\tcase proto.WireTypeLen:\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tsize := length / {{ div .bitSize 8 }}\n\t\t\torig.{{ .fieldName }} = make([]{{ .goType }}, size)\n\t\t\tvar num uint{{ .bitSize }}\n\t\t\tfor i := 0; i < size; i++ {\n\t\t\t\tnum, startPos, err = proto.ConsumeI{{ .bitSize }}(buf[:pos], startPos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\torig.{{ .fieldName }}[i] = {{ .goType }}(num)\n\t\t\t}\n\t\t\tif startPos != pos {\n\t\t\t\treturn fmt.Errorf(\"proto: invalid field len = %d for field {{ .fieldName }}\", pos - startPos)\n\t\t\t}\n\t\tcase proto.WireTypeI{{ .bitSize }}:\n\t\t\tvar num uint{{ .bitSize }}\n\t\t\tnum, pos, err = proto.ConsumeI{{ .bitSize }}(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.{{ .fieldName }} = append(orig.{{ .fieldName }}, {{ .goType }}(num))\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field {{ .fieldName }}\", wireType)\n\t\t}\n{{- else }}\n\tcase {{ .protoFieldID }}:\n\t\tif wireType != proto.WireTypeI{{ .bitSize }} {\n\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field {{ .fieldName }}\", wireType)\n\t\t}\n\t\tvar num uint{{ .bitSize }}\n\t\tnum, pos, err = proto.ConsumeI{{ .bitSize }}(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n{{ if ne .oneOfGroup \"\" -}}\n\t\tvar ov *{{ .oneOfMessageName }}\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &{{ .oneOfMessageName }}{}\n\t\t} else {\n\t\t\tov = ProtoPool{{ .oneOfMessageName }}.Get().(*{{ .oneOfMessageName }})\n\t\t}\n\t\tov.{{ .fieldName }} = {{ .goType }}(num)\n\t\torig.{{ .oneOfGroup }} = ov\n{{- else }}\n\t\torig.{{ .fieldName }} = {{ .goType }}(num)\n{{- end }}{{- end }}`\n\nconst unmarshalProtoBool = `{{ if .repeated -}}\n\tcase {{ .protoFieldID }}:\n\t\tswitch wireType {\n\t\tcase proto.WireTypeLen:\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\t// Optimistically assume that bools are encoded as 1 byte even in variant form.\n\t\t\torig.{{ .fieldName }} = make([]bool, 0, length)\n\t\t\tvar num uint64\n\t\t\tfor startPos < pos {\n\t\t\t\tnum, startPos, err = proto.ConsumeVarint(buf[:pos], startPos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\torig.{{ .fieldName }} = append(orig.{{ .fieldName }}, num != 0)\n\t\t\t}\n\t\t\tif startPos != pos {\n\t\t\t\treturn fmt.Errorf(\"proto: invalid field len = %d for field {{ .fieldName }}\", pos - startPos)\n\t\t\t}\n\t\tcase proto.WireTypeVarint:\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.{{ .fieldName }} = append(orig.{{ .fieldName }}, num != 0)\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field {{ .fieldName }}\", wireType)\n\t\t}\n{{- else }}\n\tcase {{ .protoFieldID }}:\n\t\tif wireType != proto.WireTypeVarint {\n\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field {{ .fieldName }}\", wireType)\n\t\t}\n\t\tvar num uint64\n\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n{{ if ne .oneOfGroup \"\" -}}\n\t\tvar ov *{{ .oneOfMessageName }}\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &{{ .oneOfMessageName }}{}\n\t\t} else {\n\t\t\tov = ProtoPool{{ .oneOfMessageName }}.Get().(*{{ .oneOfMessageName }})\n\t\t}\n\t\tov.{{ .fieldName }} = num != 0\n\t\torig.{{ .oneOfGroup }} = ov\n{{- else if .nullable -}}\n\t\torig.Set{{ .fieldName }}(num != 0)\n{{- else -}}\n\t\torig.{{ .fieldName }} = num != 0\n{{- end }}{{- end }}`\n\nconst unmarshalProtoVarint = `{{ if .repeated -}}\n\tcase {{ .protoFieldID }}:\n\t\tswitch wireType {\n\t\tcase proto.WireTypeLen:\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tvar num uint64\n\t\t\tfor startPos < pos {\n\t\t\t\tnum, startPos, err = proto.ConsumeVarint(buf[:pos], startPos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\torig.{{ .fieldName }} = append(orig.{{ .fieldName }}, {{ .goType }}(num))\n\t\t\t}\n\t\t\tif startPos != pos {\n\t\t\t\treturn fmt.Errorf(\"proto: invalid field len = %d for field {{ .fieldName }}\", pos - startPos)\n\t\t\t}\n\t\tcase proto.WireTypeVarint:\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.{{ .fieldName }} = append(orig.{{ .fieldName }}, {{ .goType }}(num))\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field {{ .fieldName }}\", wireType)\n\t\t}\n{{- else }}\n\tcase {{ .protoFieldID }}:\n\t\tif wireType != proto.WireTypeVarint {\n\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field {{ .fieldName }}\", wireType)\n\t\t}\n\t\tvar num uint64\n\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n{{ if ne .oneOfGroup \"\" -}}\n\t\tvar ov *{{ .oneOfMessageName }}\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &{{ .oneOfMessageName }}{}\n\t\t} else {\n\t\t\tov = ProtoPool{{ .oneOfMessageName }}.Get().(*{{ .oneOfMessageName }})\n\t\t}\n\t\tov.{{ .fieldName }} = {{ .goType }}(num)\n\t\torig.{{ .oneOfGroup }} = ov\n{{- else if .nullable -}}\n\t\torig.Set{{ .fieldName }}({{ .goType }}(num))\n{{- else -}}\n\t\torig.{{ .fieldName }} = {{ .goType }}(num)\n{{- end }}{{- end }}`\n\nconst unmarshalProtoString = `\n\tcase {{ .protoFieldID }}:\n\t\tif wireType != proto.WireTypeLen {\n\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field {{ .fieldName }}\", wireType)\n\t\t}\n\t\tvar length int\n\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tstartPos := pos - length\n{{ if ne .oneOfGroup \"\" -}}\n\t\tvar ov *{{ .oneOfMessageName }}\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &{{ .oneOfMessageName }}{}\n\t\t} else {\n\t\t\tov = ProtoPool{{ .oneOfMessageName }}.Get().(*{{ .oneOfMessageName }})\n\t\t}\n\t\tov.{{ .fieldName }} = string(buf[startPos:pos])\n\t\torig.{{ .oneOfGroup }} = ov\n{{- else if .repeated -}}\n\t\torig.{{ .fieldName }} = append(orig.{{ .fieldName }}, string(buf[startPos:pos]))\n{{- else -}}\n\t\torig.{{ .fieldName }} = string(buf[startPos:pos])\n{{- end }}`\n\nconst unmarshalProtoBytes = `\t\n\tcase {{ .protoFieldID }}:\n\t\tif wireType != proto.WireTypeLen {\n\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field {{ .fieldName }}\", wireType)\n\t\t}\n\t\tvar length int\n\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tstartPos := pos - length\n{{ if ne .oneOfGroup \"\" -}}\n\t\tvar ov *{{ .oneOfMessageName }}\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &{{ .oneOfMessageName }}{}\n\t\t} else {\n\t\t\tov = ProtoPool{{ .oneOfMessageName }}.Get().(*{{ .oneOfMessageName }})\n\t\t}\n\t\tif length != 0 {\n\t\t\tov.{{ .fieldName }} = make([]byte, length)\n\t\t\tcopy(ov.{{ .fieldName }}, buf[startPos:pos])\n\t\t}\n\t\torig.{{ .oneOfGroup }} = ov\n{{- else if .repeated -}}\n\t\tif length != 0 {\n\t\t\torig.{{ .fieldName }} = append(orig.{{ .fieldName }}, make([]byte, length))\n\t\t\tcopy(orig.{{ .fieldName }}[len(orig.{{ .fieldName }}) - 1], buf[startPos:pos])\n\t\t} else {\n\t\t\torig.{{ .fieldName }} = append(orig.{{ .fieldName }}, nil)\n\t\t}\n{{- else -}}\n\t\tif length != 0 {\n\t\t\torig.{{ .fieldName }} = make([]byte, length)\n\t\t\tcopy(orig.{{ .fieldName }}, buf[startPos:pos])\n\t\t}\n{{- end }}`\n\nconst unmarshalProtoMessage = `\n\tcase {{ .protoFieldID }}:\n\t\tif wireType != proto.WireTypeLen {\n\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field {{ .fieldName }}\", wireType)\n\t\t}\n\t\tvar length int\n\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tstartPos := pos - length\n{{ if ne .oneOfGroup \"\" -}}\n\t\tvar ov *{{ .oneOfMessageName }}\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &{{ .oneOfMessageName }}{}\n\t\t} else {\n\t\t\tov = ProtoPool{{ .oneOfMessageName }}.Get().(*{{ .oneOfMessageName }})\n\t\t}\n\t\tov.{{ .fieldName }} = New{{ .messageName }}()\n\t\terr = ov.{{ .fieldName }}.UnmarshalProto(buf[startPos:pos])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\torig.{{ .oneOfGroup }} = ov\n{{- else if .repeated -}}\n\t\torig.{{ .fieldName }} = append(orig.{{ .fieldName }}, {{ if .nullable }}New{{ .messageName }}(){{ else }}{{ .defaultValue }}{{ end }})\n\t\terr = orig.{{ .fieldName }}[len(orig.{{ .fieldName }})-1].UnmarshalProto(buf[startPos:pos])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n{{- else }}\n\t\t{{ if .nullable }}orig.{{ .fieldName }} = New{{ .messageName }}(){{ end }}\n\t\terr = orig.{{ .fieldName }}.UnmarshalProto(buf[startPos:pos]) \n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n{{- end }}`\n\nconst unmarshalProtoSignedVarint = `{{ if .repeated -}}\n\tcase {{ .protoFieldID }}:\n\t\tswitch wireType {\n\t\tcase proto.WireTypeLen:\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\t// Optimistically assume that bools are encoded as 1 byte even in variant form.\n\t\t\torig.{{ .fieldName }} = make([]bool, 0, pos - startPos)\n\t\t\tvar num uint64\n\t\t\tfor startPos < pos {\n\t\t\t\tnum, startPos, err = proto.ConsumeVarint(buf[:pos], startPos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\torig.{{ .fieldName }} = append(orig.{{ .fieldName }}, int{{ .bitSize }}(uint{{ .bitSize }}(num >> 1) ^ uint{{ .bitSize }}(int{{ .bitSize }}((num&1)<<{{ sub .bitSize 1 }})>>{{ sub .bitSize 1 }})))\n\t\t\t}\n\t\t\tif startPos != pos {\n\t\t\t\treturn fmt.Errorf(\"proto: invalid field len = %d for field {{ .fieldName }}\", pos - startPos)\n\t\t\t}\n\t\tcase proto.WireTypeVarint:\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.{{ .fieldName }} = append(orig.{{ .fieldName }}, int{{ .bitSize }}(uint{{ .bitSize }}(num >> 1) ^ uint{{ .bitSize }}(int{{ .bitSize }}((num&1)<<{{ sub .bitSize 1 }})>>{{ sub .bitSize 1 }})))\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field {{ .fieldName }}\", wireType)\n\t\t}\n\t\t\n{{- else }}\n\tcase {{ .protoFieldID }}:\n\t\tif wireType != proto.WireTypeVarint {\n\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field {{ .fieldName }}\", wireType)\n\t\t}\n\t\tvar num uint64\n\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n{{ if ne .oneOfGroup \"\" -}}\n\t\tvar ov *{{ .oneOfMessageName }}\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &{{ .oneOfMessageName }}{}\n\t\t} else {\n\t\t\tov = ProtoPool{{ .oneOfMessageName }}.Get().(*{{ .oneOfMessageName }})\n\t\t}\n\t\tov.{{ .fieldName }} = int{{ .bitSize }}(uint{{ .bitSize }}(num >> 1) ^ uint{{ .bitSize }}(int{{ .bitSize }}((num&1)<<{{ sub .bitSize 1 }})>>{{ sub .bitSize 1 }}))\n\t\torig.{{ .oneOfGroup }} = ov\n{{- else if .nullable -}}\n\t\torig.Set{{ .fieldName }}(int{{ .bitSize }}(uint{{ .bitSize }}(num >> 1) ^ uint{{ .bitSize }}(int{{ .bitSize }}((num&1)<<{{ sub .bitSize 1 }})>>{{ sub .bitSize 1 }})))\n{{- else -}}\n\t\torig.{{ .fieldName }} = int{{ .bitSize }}(uint{{ .bitSize }}(num >> 1) ^ uint{{ .bitSize }}(int{{ .bitSize }}((num&1)<<{{ sub .bitSize 1 }})>>{{ sub .bitSize 1 }}))\n{{- end }}{{- end }}`\n\nfunc (pf *Field) GenUnmarshalProto() string {\n\ttf := pf.getTemplateFields()\n\tswitch pf.Type {\n\tcase TypeDouble, TypeFloat:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"unmarshalProtoFloat\", []byte(unmarshalProtoFloat)), tf)\n\tcase TypeFixed64, TypeSFixed64, TypeFixed32, TypeSFixed32:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"unmarshalProtoFixed\", []byte(unmarshalProtoFixed)), tf)\n\tcase TypeInt32, TypeInt64, TypeUint32, TypeUint64, TypeEnum:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"unmarshalProtoVarint\", []byte(unmarshalProtoVarint)), tf)\n\tcase TypeBool:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"unmarshalProtoBool\", []byte(unmarshalProtoBool)), tf)\n\tcase TypeString:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"unmarshalProtoString\", []byte(unmarshalProtoString)), tf)\n\tcase TypeBytes:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"unmarshalProtoBytes\", []byte(unmarshalProtoBytes)), tf)\n\tcase TypeMessage:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"unmarshalProtoMessage\", []byte(unmarshalProtoMessage)), tf)\n\tcase TypeSInt32, TypeSInt64:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"unmarshalProtoSignedVarint\", []byte(unmarshalProtoSignedVarint)), tf)\n\t}\n\tpanic(fmt.Sprintf(\"unhandled case %T\", pf.Type))\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/templates/message.go.tmpl",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t{{ range $index, $element := .imports -}}\n\t{{ $element }}\n\t{{ end }}\n)\n\n{{- range .fields }}\n{{ .GenOneOfMessages }}\n{{- end }}\n\n{{ .description }}\ntype {{ .messageName }} struct {\n{{- range .fields }}\n    {{ .GenMessageField }}\n{{- end }}\n{{ if gt .metadataSize 0 -}}\n    metadata [{{ .metadataSize }}]uint64\n{{ end -}}\n}\n\nvar (\n\tprotoPool{{ .messageName }} = sync.Pool{\n\t    New: func() any {\n\t\t    return &{{ .messageName }}{}\n\t    },\n    }\n    {{- range .fields }}{{ .GenPool }}{{- end }}\n)\n\n\nfunc New{{ .messageName }}() *{{ .messageName }} {\n    if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n        return &{{ .messageName }}{}\n    }\n    return protoPool{{ .messageName }}.Get().(*{{ .messageName }})\n}\n\nfunc Delete{{ .messageName }}(orig *{{ .messageName }}, nullable bool) {\n    if orig == nil {\n        return\n    }\n\n    if !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n        orig.Reset()\n        return\n    }\n\n    {{- range .fields }}\n        {{ .GenDelete }}\n    {{- end }}\n    orig.Reset()\n    if nullable {\n        protoPool{{ .messageName }}.Put(orig)\n    }\n}\n\nfunc Copy{{ .messageName }}(dest, src *{{ .messageName }}) *{{ .messageName }}{\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n    }\n\n    if src == nil {\n        return nil;\n    }\n\n    if dest == nil {\n        dest = New{{ .messageName }}();\n    }\n\n    {{- range .fields }}\n\t{{ .GenCopy }}\n\t{{- end }}\n\n\treturn dest\n}\n\nfunc Copy{{ .messageName }}Slice(dest, src []{{ .messageName }}) []{{ .messageName }} {\n    var newDest []{{ .messageName }}\n    if cap(dest) < len(src) {\n        newDest = make([]{{ .messageName }}, len(src))\n    } else {\n        newDest = dest[:len(src)]\n        // Cleanup the rest of the elements so GC can free the memory.\n        // This can happen when len(src) < len(dest) < cap(dest).\n        for i := len(src); i < len(dest); i++ {\n            Delete{{ .messageName }}(&dest[i], false)\n        }\n    }\n    for i := range src {\n        Copy{{ .messageName }}(&newDest[i], &src[i])\n    }\n    return newDest\n}\n\nfunc Copy{{ .messageName }}PtrSlice(dest, src []*{{ .messageName }}) []*{{ .messageName }} {\n    var newDest []*{{ .messageName }}\n    if cap(dest) < len(src) {\n        newDest = make([]*{{ .messageName }}, len(src))\n        // Copy old pointers to re-use.\n        copy(newDest, dest)\n        // Add new pointers for missing elements from len(dest) to len(srt).\n        for i := len(dest); i < len(src); i++ {\n            newDest[i] = New{{ .messageName }}()\n        }\n\t} else {\n        newDest = dest[:len(src)]\n        // Cleanup the rest of the elements so GC can free the memory.\n        // This can happen when len(src) < len(dest) < cap(dest).\n        for i := len(src); i < len(dest); i++ {\n            Delete{{ .messageName }}(dest[i], true)\n            dest[i] = nil\n        }\n        // Add new pointers for missing elements.\n        // This can happen when len(dest) < len(src) < cap(dest).\n        for i := len(dest); i < len(src); i++ {\n            newDest[i] = New{{ .messageName }}()\n        }\n    }\n    for i := range src {\n        Copy{{ .messageName }}(newDest[i], src[i])\n    }\n    return newDest\n}\n\n\nfunc (orig *{{ .messageName }}) Reset() {\n\t*orig = {{ .messageName }}{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *{{ .messageName }}) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\t{{ range .fields -}}\n\t{{ .GenMarshalJSON }}\n\t{{ end -}}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *{{ .messageName }}) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\t{{ range .fields -}}\n\t\t{{ .GenUnmarshalJSON }}\n\t\t{{ end -}}\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *{{ .messageName }}) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\t{{ range .fields -}}\n\t{{ .GenSizeProto }}\n\t{{ end -}}\n\treturn n\n}\n\nfunc (orig *{{ .messageName }}) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\t{{ range .fields -}}\n\t{{ .GenMarshalProto }}\n\t{{ end -}}\n\treturn len(buf) - pos\n}\n\nfunc (orig *{{ .messageName }}) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\t\t\t{{ range .fields -}}\n\t\t\t{{ .GenUnmarshalProto }}\n\t\t\t{{ end -}}\n\t\t\tdefault:\n\t\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n{{ if gt .metadataSize 0 -}}\n{{ call .GenerateMetadata }}\n{{ end -}}\n\nfunc GenTest{{ .messageName }}() *{{ .messageName }} {\n    orig := New{{ .messageName }}()\n    {{- range .fields }}\n    {{ .GenTest }}\n    {{- end }}\n    return orig\n}\n\nfunc GenTest{{ .messageName }}PtrSlice() []*{{ .messageName }} {\n    orig := make([]*{{ .messageName }}, 5)\n    orig[0] = New{{ .messageName }}()\n    orig[1] = GenTest{{ .messageName }}()\n    orig[2] = New{{ .messageName }}()\n    orig[3] = GenTest{{ .messageName }}()\n    orig[4] = New{{ .messageName }}()\n    return orig\n}\n\nfunc GenTest{{ .messageName }}Slice() []{{ .messageName }} {\n    orig := make([]{{ .messageName }}, 5)\n    orig[1] = *GenTest{{ .messageName }}()\n    orig[3] = *GenTest{{ .messageName }}()\n    return orig\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/templates/message_test.go.tmpl",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t{{ range $index, $element := .testImports -}}\n\t{{ $element }}\n\t{{ end }}\n)\n\nfunc TestCopy{{ .messageName }}(t *testing.T) {\n    for name, src := range genTestEncodingValues{{ .messageName }}() {\n        for _, pooling := range []bool{true, false} {\n            t.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n                prevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n                require.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n                defer func() {\n                    require.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n                }()\n\n                dest := New{{ .messageName }}()\n                Copy{{ .messageName }}(dest, src)\n                assert.Equal(t, src, dest)\n                Copy{{ .messageName }}(dest, dest)\n                assert.Equal(t, src, dest)\n            })\n        }\n    }\n}\n\nfunc TestCopy{{ .messageName }}Slice(t *testing.T) {\n    src := []{{ .messageName }}{}\n    dest := []{{ .messageName }}{}\n    // Test CopyTo empty\n    dest = Copy{{ .messageName }}Slice(dest, src)\n    assert.Equal(t, []{{ .messageName }}{}, dest)\n\n    // Test CopyTo larger slice\n    src = GenTest{{ .messageName }}Slice()\n    dest = Copy{{ .messageName }}Slice(dest, src)\n    assert.Equal(t, GenTest{{ .messageName }}Slice(), dest)\n\n    // Test CopyTo same size slice\n    dest = Copy{{ .messageName }}Slice(dest, src)\n    assert.Equal(t, GenTest{{ .messageName }}Slice(), dest)\n\n    // Test CopyTo smaller size slice\n    dest = Copy{{ .messageName }}Slice(dest, []{{ .messageName }}{})\n    assert.Len(t, dest, 0)\n\n    // Test CopyTo larger slice with enough capacity\n    dest = Copy{{ .messageName }}Slice(dest, src)\n    assert.Equal(t, GenTest{{ .messageName }}Slice(), dest)\n}\n\nfunc TestCopy{{ .messageName }}PtrSlice(t *testing.T) {\n    src := []*{{ .messageName }}{}\n    dest := []*{{ .messageName }}{}\n    // Test CopyTo empty\n    dest = Copy{{ .messageName }}PtrSlice(dest, src)\n    assert.Equal(t, []*{{ .messageName }}{}, dest)\n\n    // Test CopyTo larger slice\n    src = GenTest{{ .messageName }}PtrSlice()\n    dest = Copy{{ .messageName }}PtrSlice(dest, src)\n    assert.Equal(t, GenTest{{ .messageName }}PtrSlice(), dest)\n\n    // Test CopyTo same size slice\n    dest = Copy{{ .messageName }}PtrSlice(dest, src)\n    assert.Equal(t, GenTest{{ .messageName }}PtrSlice(), dest)\n\n    // Test CopyTo smaller size slice\n    dest = Copy{{ .messageName }}PtrSlice(dest, []*{{ .messageName }}{})\n    assert.Len(t, dest, 0)\n\n    // Test CopyTo larger slice with enough capacity\n    dest = Copy{{ .messageName }}PtrSlice(dest, src)\n    assert.Equal(t, GenTest{{ .messageName }}PtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSON{{ .messageName }}Unknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := New{{ .messageName }}()\n    dest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, New{{ .messageName }}(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSON{{ .messageName }}(t *testing.T) {\n\tfor name, src := range genTestEncodingValues{{ .messageName }}() {\n        for _, pooling := range []bool{true, false} {\n            t.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n                prevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n                require.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n                defer func() {\n                    require.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n                }()\n\n                stream := json.BorrowStream(nil)\n                defer json.ReturnStream(stream)\n                src.MarshalJSON(stream)\n                require.NoError(t, stream.Error())\n\n                iter := json.BorrowIterator(stream.Buffer())\n                defer json.ReturnIterator(iter)\n                dest := New{{ .messageName }}()\n                dest.UnmarshalJSON(iter)\n                require.NoError(t, iter.Error())\n\n                assert.Equal(t, src, dest)\n                Delete{{ .messageName }}(dest, true)\n            })\n        }\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProto{{ .messageName }}Failing(t *testing.T) {\n    for name, buf := range genTestFailingUnmarshalProtoValues{{ .messageName }}() {\n        t.Run(name, func(t *testing.T) {\n            dest := New{{ .messageName }}()\n            require.Error(t, dest.UnmarshalProto(buf))\n        })\n    }\n}\n\nfunc TestMarshalAndUnmarshalProto{{ .messageName }}Unknown(t *testing.T) {\n\tdest := New{{ .messageName }}()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, New{{ .messageName }}(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProto{{ .messageName }}(t *testing.T) {\n\tfor name, src := range genTestEncodingValues{{ .messageName }}(){\n        for _, pooling := range []bool{true, false} {\n            t.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n                prevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n                require.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n                defer func() {\n                    require.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n                }()\n\n                buf := make([]byte, src.SizeProto())\n                gotSize := src.MarshalProto(buf)\n                assert.Equal(t, len(buf), gotSize)\n\n                dest := New{{ .messageName }}()\n                require.NoError(t, dest.UnmarshalProto(buf))\n\n                assert.Equal(t, src, dest)\n                Delete{{ .messageName }}(dest, true)\n            })\n        }\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobuf{{ .messageName }}(t *testing.T) {\n\tfor name, src := range genTestEncodingValues{{ .messageName }}(){\n\t\tt.Run(name, func(t *testing.T) {\n            buf := make([]byte, src.SizeProto())\n            gotSize := src.MarshalProto(buf)\n            assert.Equal(t, len(buf), gotSize)\n\n            goDest := &{{ .upstreamMessage }}{}\n            require.NoError(t, proto.Unmarshal(buf, goDest))\n\n            goBuf, err := proto.Marshal(goDest)\n            require.NoError(t, err)\n\n            dest := New{{ .messageName }}()\n            require.NoError(t, dest.UnmarshalProto(goBuf))\n            assert.Equal(t, src, dest)\n        })\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValues{{ .messageName }}() map[string][]byte {\n    return map[string][]byte{\n\t\t\"invalid_field\": { 0x02 },\n        {{- range .fields }}{{ .GenTestFailingUnmarshalProtoValues }}{{- end }}\n    }\n}\n\nfunc genTestEncodingValues{{ .messageName }}() map[string]*{{ .messageName }} {\n\treturn map[string]*{{ .messageName }}{\n\t\t\"empty\": New{{ .messageName }}(),\n\t\t{{- range .fields }}{{ .GenTestEncodingValues }}{{- end }}\n\t}\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/test_encoding_values.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\nimport (\n\t\"slices\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n)\n\nconst encodingTestValuesScalar = `{{ if ne .oneOfGroup \"\" -}}\n\"{{ .fieldName }}/default\": { {{ .oneOfGroup }}: &{{ .oneOfMessageName }}{{ \"{\" }}{{ .fieldName }}: {{ .defaultValue }}} },\n\"{{ .fieldName }}/test\": { {{ .oneOfGroup }}: &{{ .oneOfMessageName }}{{ \"{\" }}{{ .fieldName }}: {{ .testValue }}} },\n{{- else if .nullable }}\n\"{{ .fieldName }}/test\": func () *{{ .parentMessageName }} { \n\tms := New{{ .parentMessageName }}() \n\tms.Set{{ .fieldName }}({{ .testValue }})\n\treturn ms\n}(),\n{{- else }}\n\"{{ .fieldName }}/test\": { {{ .fieldName }}: {{ .testValue }} },\n{{- end }}`\n\nconst encodingTestValuesMessage = `{{ if ne .oneOfGroup \"\" -}}\n\"{{ .fieldName }}/default\": { {{ .oneOfGroup }}: &{{ .oneOfMessageName }}{{ \"{\" }}{{ .fieldName }}: {{ .defaultValue }}} },\n\"{{ .fieldName }}/test\": { {{ .oneOfGroup }}: &{{ .oneOfMessageName }}{{ \"{\" }}{{ .fieldName }}: {{ .testValue }}} },\n{{- else }}\n\"{{ .fieldName }}/test\": { {{ .fieldName }}: {{ .testValue }} },\n{{- end }}`\n\nfunc (pf *Field) GenTestEncodingValues() string {\n\ttf := pf.getTemplateFields()\n\tswitch pf.Type {\n\tcase TypeMessage:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"encodingTestValuesMessage\", []byte(encodingTestValuesMessage)), tf)\n\tcase\n\t\tTypeDouble, TypeFloat,\n\t\tTypeFixed64, TypeSFixed64, TypeFixed32, TypeSFixed32,\n\t\tTypeInt32, TypeInt64, TypeUint32, TypeUint64,\n\t\tTypeSInt32, TypeSInt64,\n\t\tTypeBool, TypeString, TypeBytes, TypeEnum:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"encodingTestValuesScalar\", []byte(encodingTestValuesScalar)), tf)\n\t}\n\treturn \"\"\n}\n\nconst failingUnmarshalProtoValuesScalar = `\n\t\"{{ .fieldName }}/wrong_wire_type\": []byte{ {{ .wrongWireTypeArray }} },\n\t\"{{ .fieldName }}/missing_value\": []byte{ {{ .missingValueArray }} },`\n\nfunc (pf *Field) GenTestFailingUnmarshalProtoValues() string {\n\ttf := pf.getTemplateFields()\n\ttf[\"wrongWireTypeArray\"] = protoTagAsByteArray(genProtoTag(pf.ID, WireTypeEndGroup))\n\ttf[\"missingValueArray\"] = protoTagAsByteArray(tf[\"protoTag\"].([]string))\n\tswitch pf.Type {\n\tcase TypeMessage,\n\t\tTypeDouble, TypeFloat,\n\t\tTypeFixed64, TypeSFixed64, TypeFixed32, TypeSFixed32,\n\t\tTypeInt32, TypeInt64, TypeUint32, TypeUint64,\n\t\tTypeSInt32, TypeSInt64,\n\t\tTypeBool, TypeString, TypeBytes, TypeEnum:\n\t\treturn tmplutil.Execute(tmplutil.Parse(\"failingUnmarshalProtoValuesScalar\", []byte(failingUnmarshalProtoValuesScalar)), tf)\n\t}\n\treturn \"\"\n}\n\nfunc protoTagAsByteArray(protoTag []string) string {\n\tslices.Reverse(protoTag)\n\treturn strings.Join(protoTag, \", \")\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/proto/wire_type.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/proto\"\n\n// WireType represents the proto wire type.\ntype WireType uint32\n\nconst (\n\tWireTypeVarint     WireType = 0\n\tWireTypeI64        WireType = 1\n\tWireTypeLen        WireType = 2\n\tWireTypeStartGroup WireType = 3\n\tWireTypeEndGroup   WireType = 4\n\tWireTypeI32        WireType = 5\n)\n"
  },
  {
    "path": "internal/cmd/pdatagen/internal/tmplutil/template.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage tmplutil // import \"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/tmplutil\"\n\nimport (\n\t\"strings\"\n\t\"text/template\"\n\n\t\"github.com/ettle/strcase\"\n)\n\nfunc Parse(name string, bytes []byte) *template.Template {\n\treturn template.Must(newTemplate(name).Parse(string(bytes)))\n}\n\nfunc Execute(tmpl *template.Template, data any) string {\n\tvar sb strings.Builder\n\tif err := tmpl.Execute(&sb, data); err != nil {\n\t\tpanic(err)\n\t}\n\treturn sb.String()\n}\n\nfunc newTemplate(name string) *template.Template {\n\treturn template.New(name).Funcs(template.FuncMap{\n\t\t\"upperFirst\": upperFirst,\n\t\t\"lowerFirst\": lowerFirst,\n\t\t\"add\":        add,\n\t\t\"sub\":        sub,\n\t\t\"div\":        div,\n\t\t\"needSnake\":  needSnake,\n\t\t\"toSnake\":    strcase.ToSnake,\n\t})\n}\n\nfunc upperFirst(s string) string {\n\treturn strings.ToUpper(s[0:1]) + s[1:]\n}\n\nfunc lowerFirst(s string) string {\n\treturn strings.ToLower(s[0:1]) + s[1:]\n}\n\nfunc add(a, b int) int {\n\treturn a + b\n}\n\nfunc sub(a, b int) int {\n\treturn a - b\n}\n\nfunc div(a, b int) int {\n\treturn a / b\n}\n\nfunc needSnake(str string) bool {\n\treturn strings.ToLower(str) != strcase.ToSnake(str)\n}\n"
  },
  {
    "path": "internal/cmd/pdatagen/main.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"go.opentelemetry.io/collector/internal/cmd/pdatagen/internal/pdata\"\n)\n\n// checkErr prints the given error and exits when e is non-nil.\nfunc checkErr(e error) {\n\tif e != nil {\n\t\tfmt.Println(e)\n\t\tos.Exit(1)\n\t}\n}\n\nfunc main() {\n\tvar workdir string\n\tflag.StringVar(&workdir, \"C\", \".\", \"set work directory\")\n\tflag.Parse()\n\n\tcheckErr(os.Chdir(workdir))\n\tcheckErr(pdata.DeleteGeneratedFiles(filepath.Join(\"pdata\", \"internal\")))\n\tfor _, fp := range pdata.AllPackages {\n\t\tcheckErr(pdata.DeleteGeneratedFiles(filepath.Join(\"pdata\", fp.Path())))\n\t\tcheckErr(fp.GenerateFiles())\n\t\tcheckErr(fp.GenerateTestFiles())\n\t\tcheckErr(fp.GenerateInternalFiles())\n\t\tcheckErr(fp.GenerateProtoMessageFiles())\n\t\tcheckErr(fp.GenerateProtoMessageTestsFiles())\n\t\tcheckErr(fp.GenerateProtoEnumFiles())\n\t}\n}\n"
  },
  {
    "path": "internal/componentalias/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "internal/componentalias/alias.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componentalias // import \"go.opentelemetry.io/collector/internal/componentalias\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\ntype TypeAliasHolder interface {\n\tDeprecatedAlias() component.Type\n\tSetDeprecatedAlias(component.Type)\n}\n\nfunc NewTypeAliasHolder() TypeAliasHolder {\n\tta := typeAlias(component.Type{})\n\treturn &ta\n}\n\ntype typeAlias component.Type\n\n// DeprecatedAlias returns the deprecated type typeAlias for this component, if any.\n// Returns an empty component.Type if no typeAlias is configured.\nfunc (ta *typeAlias) DeprecatedAlias() component.Type {\n\treturn component.Type(*ta)\n}\n\n// SetDeprecatedAlias sets the deprecated type typeAlias.\nfunc (ta *typeAlias) SetDeprecatedAlias(newAlias component.Type) {\n\t*ta = typeAlias(newAlias)\n}\n\n// ValidateComponentType returns an error if the provided factory does not match the provided component ID.\n// It checks both the current type and any deprecated alias type.\nfunc ValidateComponentType(f component.Factory, id component.ID) error {\n\tif id.Type() == f.Type() {\n\t\treturn nil\n\t}\n\terrMsg := fmt.Sprintf(\"component type mismatch: component ID %q does not have type %q\", id, f.Type())\n\tif aliasHolder, ok := f.(TypeAliasHolder); ok && aliasHolder.DeprecatedAlias().String() != \"\" {\n\t\tif id.Type() == aliasHolder.DeprecatedAlias() {\n\t\t\treturn nil\n\t\t}\n\t\terrMsg += fmt.Sprintf(\" or deprecated alias type %q\", aliasHolder.DeprecatedAlias())\n\t}\n\treturn errors.New(errMsg)\n}\n"
  },
  {
    "path": "internal/componentalias/alias_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componentalias\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc TestNewTypeAliasHolder(t *testing.T) {\n\tholder := NewTypeAliasHolder()\n\trequire.NotNil(t, holder)\n\n\talias := holder.DeprecatedAlias()\n\tassert.Equal(t, component.Type{}, alias)\n\tassert.Empty(t, alias.String())\n\n\ttestType := component.MustNewType(\"test_alias\")\n\tholder.SetDeprecatedAlias(testType)\n\tretrievedAlias := holder.DeprecatedAlias()\n\tassert.Equal(t, testType, retrievedAlias)\n\tassert.Equal(t, \"test_alias\", retrievedAlias.String())\n}\n\ntype mockFactory struct {\n\tfactoryType component.Type\n\tTypeAliasHolder\n}\n\nfunc (f *mockFactory) Type() component.Type {\n\treturn f.factoryType\n}\n\nfunc (f *mockFactory) CreateDefaultConfig() component.Config {\n\treturn nil\n}\n\nfunc TestValidateComponentType_ExactMatch(t *testing.T) {\n\ttestType := component.MustNewType(\"test\")\n\tfactory := &mockFactory{\n\t\tfactoryType:     testType,\n\t\tTypeAliasHolder: NewTypeAliasHolder(),\n\t}\n\n\ttestID := component.MustNewID(testType.String())\n\terr := ValidateComponentType(factory, testID)\n\trequire.NoError(t, err)\n}\n\nfunc TestValidateComponentType_AliasMatch(t *testing.T) {\n\tfactoryType := component.MustNewType(\"new_name\")\n\taliasType := component.MustNewType(\"old_name\")\n\n\tfactory := &mockFactory{\n\t\tfactoryType:     factoryType,\n\t\tTypeAliasHolder: NewTypeAliasHolder(),\n\t}\n\tfactory.SetDeprecatedAlias(aliasType)\n\n\t// Test with alias type\n\taliasID := component.MustNewID(aliasType.String())\n\terr := ValidateComponentType(factory, aliasID)\n\trequire.NoError(t, err)\n\n\t// Test with factory type still works\n\tfactoryID := component.MustNewID(factoryType.String())\n\terr = ValidateComponentType(factory, factoryID)\n\trequire.NoError(t, err)\n}\n\nfunc TestValidateComponentType_NoMatch(t *testing.T) {\n\tfactoryType := component.MustNewType(\"factory_type\")\n\twrongType := component.MustNewType(\"wrong_type\")\n\n\tfactory := &mockFactory{\n\t\tfactoryType:     factoryType,\n\t\tTypeAliasHolder: NewTypeAliasHolder(),\n\t}\n\n\twrongID := component.MustNewID(wrongType.String())\n\terr := ValidateComponentType(factory, wrongID)\n\trequire.Error(t, err)\n\tassert.Contains(t, err.Error(), \"component type mismatch\")\n\tassert.Contains(t, err.Error(), wrongType.String())\n\tassert.Contains(t, err.Error(), factoryType.String())\n}\n\nfunc TestValidateComponentType_NoMatchWithAlias(t *testing.T) {\n\tfactoryType := component.MustNewType(\"factory_type\")\n\taliasType := component.MustNewType(\"alias_type\")\n\twrongType := component.MustNewType(\"wrong_type\")\n\n\tfactory := &mockFactory{\n\t\tfactoryType:     factoryType,\n\t\tTypeAliasHolder: NewTypeAliasHolder(),\n\t}\n\tfactory.SetDeprecatedAlias(aliasType)\n\n\twrongID := component.MustNewID(wrongType.String())\n\terr := ValidateComponentType(factory, wrongID)\n\trequire.Error(t, err)\n\tassert.Contains(t, err.Error(), \"component type mismatch\")\n\tassert.Contains(t, err.Error(), wrongType.String())\n\tassert.Contains(t, err.Error(), factoryType.String())\n\tassert.Contains(t, err.Error(), \"deprecated alias type\")\n\tassert.Contains(t, err.Error(), aliasType.String())\n}\n\nfunc TestValidateComponentType_EmptyAlias(t *testing.T) {\n\tfactoryType := component.MustNewType(\"factory_type\")\n\twrongType := component.MustNewType(\"wrong_type\")\n\n\tfactory := &mockFactory{\n\t\tfactoryType:     factoryType,\n\t\tTypeAliasHolder: NewTypeAliasHolder(),\n\t}\n\t// Don't set any alias (empty by default)\n\n\twrongID := component.MustNewID(wrongType.String())\n\terr := ValidateComponentType(factory, wrongID)\n\trequire.Error(t, err)\n\tassert.Contains(t, err.Error(), \"component type mismatch\")\n\tassert.NotContains(t, err.Error(), \"deprecated alias type\")\n}\n\ntype mockFactoryWithoutAlias struct {\n\tfactoryType component.Type\n}\n\nfunc (f *mockFactoryWithoutAlias) Type() component.Type {\n\treturn f.factoryType\n}\n\nfunc (f *mockFactoryWithoutAlias) CreateDefaultConfig() component.Config {\n\treturn nil\n}\n\nfunc TestValidateComponentType_FactoryWithoutAliasSupport(t *testing.T) {\n\tfactoryType := component.MustNewType(\"factory_type\")\n\tfactory := &mockFactoryWithoutAlias{factoryType: factoryType}\n\n\tfactoryID := component.MustNewID(factoryType.String())\n\terr := ValidateComponentType(factory, factoryID)\n\trequire.NoError(t, err)\n\n\twrongType := component.MustNewType(\"wrong_type\")\n\twrongID := component.MustNewID(wrongType.String())\n\terr = ValidateComponentType(factory, wrongID)\n\trequire.Error(t, err)\n\tassert.Contains(t, err.Error(), \"component type mismatch\")\n\tassert.NotContains(t, err.Error(), \"deprecated alias type\")\n}\n"
  },
  {
    "path": "internal/componentalias/go.mod",
    "content": "module go.opentelemetry.io/collector/internal/componentalias\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../testutil\n"
  },
  {
    "path": "internal/componentalias/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "internal/e2e/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "internal/e2e/configauth_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2e\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/config/configauth\"\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\nfunc TestConfmapMarshalConfigAuth(t *testing.T) {\n\tconf := confmap.New()\n\trequire.NoError(t, conf.Marshal(configauth.Config{}))\n\tassert.Equal(t, map[string]any{}, conf.ToStringMap())\n}\n"
  },
  {
    "path": "internal/e2e/configgrpc_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2e\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/config/configgrpc\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\nfunc TestConfmapMarshalConfigGRPC(t *testing.T) {\n\tkeepaliveClientConfig := map[string]any{\n\t\t\"time\":    time.Second * 10,\n\t\t\"timeout\": time.Second * 10,\n\t}\n\tkeepaliveServerConfig := map[string]any{\n\t\t\"server_parameters\":  map[string]any{},\n\t\t\"enforcement_policy\": map[string]any{},\n\t}\n\n\tconf := confmap.New()\n\trequire.NoError(t, conf.Marshal(configgrpc.NewDefaultClientConfig()))\n\tassert.Equal(t, map[string]any{\n\t\t\"keepalive\":     keepaliveClientConfig,\n\t\t\"balancer_name\": \"round_robin\",\n\t}, conf.ToStringMap())\n\n\tconf = confmap.New()\n\trequire.NoError(t, conf.Marshal(configgrpc.NewDefaultKeepaliveClientConfig()))\n\tassert.Equal(t, keepaliveClientConfig, conf.ToStringMap())\n\n\tconf = confmap.New()\n\trequire.NoError(t, conf.Marshal(configgrpc.NewDefaultKeepaliveEnforcementPolicy()))\n\tassert.Equal(t, map[string]any{}, conf.ToStringMap())\n\n\tconf = confmap.New()\n\trequire.NoError(t, conf.Marshal(configgrpc.NewDefaultKeepaliveServerConfig()))\n\tassert.Equal(t, keepaliveServerConfig, conf.ToStringMap())\n\n\tconf = confmap.New()\n\trequire.NoError(t, conf.Marshal(configgrpc.NewDefaultKeepaliveServerParameters()))\n\tassert.Equal(t, map[string]any{}, conf.ToStringMap())\n\n\tconf = confmap.New()\n\trequire.NoError(t, conf.Marshal(configgrpc.NewDefaultServerConfig()))\n\tassert.Equal(t, map[string]any{\n\t\t\"keepalive\": keepaliveServerConfig,\n\t\t\"transport\": confignet.TransportType(\"tcp\"),\n\t}, conf.ToStringMap())\n}\n"
  },
  {
    "path": "internal/e2e/confighttp_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2e\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\nfunc TestConfmapMarshalConfigHTTP(t *testing.T) {\n\tconf := confmap.New()\n\trequire.NoError(t, conf.Marshal(confighttp.NewDefaultClientConfig()))\n\tassert.Equal(t, map[string]any{\n\t\t\"idle_conn_timeout\":   90 * time.Second,\n\t\t\"max_idle_conns\":      100,\n\t\t\"force_attempt_http2\": true,\n\t}, conf.ToStringMap())\n\n\tconf = confmap.New()\n\trequire.NoError(t, conf.Marshal(confighttp.NewDefaultCORSConfig()))\n\tassert.Equal(t, map[string]any{}, conf.ToStringMap())\n\n\tconf = confmap.New()\n\trequire.NoError(t, conf.Marshal(confighttp.NewDefaultServerConfig()))\n\tassert.Equal(t, map[string]any{\n\t\t\"cors\":                nil,\n\t\t\"idle_timeout\":        60 * time.Second,\n\t\t\"keep_alives_enabled\": true,\n\t\t\"read_header_timeout\": 60 * time.Second,\n\t\t\"tls\":                 nil,\n\t\t\"transport\":           confignet.TransportTypeTCP,\n\t\t\"write_timeout\":       30 * time.Second,\n\t}, conf.ToStringMap())\n\n\tconf = confmap.New()\n\trequire.NoError(t, conf.Marshal(confighttp.AuthConfig{}))\n\tassert.Equal(t, map[string]any{}, conf.ToStringMap())\n}\n"
  },
  {
    "path": "internal/e2e/confignet_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2e\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/config/confignet\"\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\nfunc TestConfmapMarshalConfigNet(t *testing.T) {\n\tconf := confmap.New()\n\trequire.NoError(t, conf.Marshal(confignet.NewDefaultDialerConfig()))\n\tassert.Equal(t, map[string]any{}, conf.ToStringMap())\n\n\tconf = confmap.New()\n\trequire.NoError(t, conf.Marshal(confignet.NewDefaultAddrConfig()))\n\tassert.Equal(t, map[string]any{}, conf.ToStringMap())\n\n\tconf = confmap.New()\n\trequire.NoError(t, conf.Marshal(confignet.NewDefaultTCPAddrConfig()))\n\tassert.Equal(t, map[string]any{}, conf.ToStringMap())\n}\n"
  },
  {
    "path": "internal/e2e/configtls_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2e\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\nfunc TestConfmapMarshalConfigTLS(t *testing.T) {\n\tconf := confmap.New()\n\trequire.NoError(t, conf.Marshal(configtls.NewDefaultConfig()))\n\tassert.Equal(t, map[string]any{}, conf.ToStringMap())\n\n\tconf = confmap.New()\n\trequire.NoError(t, conf.Marshal(configtls.NewDefaultClientConfig()))\n\tassert.Equal(t, map[string]any{}, conf.ToStringMap())\n\n\tconf = confmap.New()\n\trequire.NoError(t, conf.Marshal(configtls.NewDefaultServerConfig()))\n\tassert.Equal(t, map[string]any{}, conf.ToStringMap())\n}\n"
  },
  {
    "path": "internal/e2e/consume_contract_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2e\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configgrpc\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configretry\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/exporter/otlpexporter\"\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver\"\n)\n\nfunc testExporterConfig(endpoint string) component.Config {\n\tretryConfig := configretry.NewDefaultBackOffConfig()\n\tretryConfig.InitialInterval = time.Millisecond // interval is short for the test purposes\n\treturn &otlpexporter.Config{\n\t\tQueueConfig: configoptional.None[exporterhelper.QueueBatchConfig](),\n\t\tRetryConfig: retryConfig,\n\t\tClientConfig: configgrpc.ClientConfig{\n\t\t\tEndpoint: endpoint,\n\t\t\tTLS: configtls.ClientConfig{\n\t\t\t\tInsecure: true,\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc testReceiverConfig(endpoint string) component.Config {\n\tcfg := otlpreceiver.NewFactory().CreateDefaultConfig()\n\tcfg.(*otlpreceiver.Config).GRPC.GetOrInsertDefault().NetAddr.Endpoint = endpoint\n\treturn cfg\n}\n\n// TestConsumeContract is an example of testing of the exporter for the contract between the\n// exporter and the receiver.\nfunc TestConsumeContractOtlpLogs(t *testing.T) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\texportertest.CheckConsumeContract(exportertest.CheckConsumeContractParams{\n\t\tT:                    t,\n\t\tNumberOfTestElements: 10,\n\t\tExporterFactory:      otlpexporter.NewFactory(),\n\t\tSignal:               pipeline.SignalLogs,\n\t\tExporterConfig:       testExporterConfig(addr),\n\t\tReceiverFactory:      otlpreceiver.NewFactory(),\n\t\tReceiverConfig:       testReceiverConfig(addr),\n\t})\n}\n\nfunc TestConsumeContractOtlpTraces(t *testing.T) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\texportertest.CheckConsumeContract(exportertest.CheckConsumeContractParams{\n\t\tT:                    t,\n\t\tNumberOfTestElements: 10,\n\t\tSignal:               pipeline.SignalTraces,\n\t\tExporterFactory:      otlpexporter.NewFactory(),\n\t\tExporterConfig:       testExporterConfig(addr),\n\t\tReceiverFactory:      otlpreceiver.NewFactory(),\n\t\tReceiverConfig:       testReceiverConfig(addr),\n\t})\n}\n\nfunc TestConsumeContractOtlpMetrics(t *testing.T) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\texportertest.CheckConsumeContract(exportertest.CheckConsumeContractParams{\n\t\tT:                    t,\n\t\tNumberOfTestElements: 10,\n\t\tExporterFactory:      otlpexporter.NewFactory(),\n\t\tSignal:               pipeline.SignalMetrics,\n\t\tExporterConfig:       testExporterConfig(addr),\n\t\tReceiverFactory:      otlpreceiver.NewFactory(),\n\t\tReceiverConfig:       testReceiverConfig(addr),\n\t})\n}\n"
  },
  {
    "path": "internal/e2e/error_propagation_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2e\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"io\"\n\t\"net\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/credentials/insecure\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configgrpc\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/exporter/otlpexporter\"\n\t\"go.opentelemetry.io/collector/exporter/otlphttpexporter\"\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/plog/plogotlp\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver\"\n)\n\nvar _ plogotlp.GRPCServer = &logsServer{}\n\ntype logsServer struct {\n\tplogotlp.UnimplementedGRPCServer\n\n\texportError error\n}\n\nfunc (r *logsServer) Export(_ context.Context, _ plogotlp.ExportRequest) (plogotlp.ExportResponse, error) {\n\treturn plogotlp.NewExportResponse(), r.exportError\n}\n\nfunc TestGRPCToGRPC(t *testing.T) {\n\t// gRPC supports 17 different status codes.\n\t// Source: https://github.com/grpc/grpc/blob/41788c90bc66caf29f28ef808d066db806389792/doc/statuscodes.md\n\tfor i := range uint32(16) {\n\t\ts := status.New(codes.Code(i), \"Testing error\")\n\t\tt.Run(\"Code \"+s.Code().String(), func(t *testing.T) {\n\t\t\te := createGRPCExporter(t, s)\n\t\t\tassertOnGRPCCode(t, e, s)\n\t\t})\n\t}\n}\n\nfunc TestHTTPToGRPC(t *testing.T) {\n\ttestCases := []struct {\n\t\tgrpc codes.Code\n\t\thttp int\n\t}{\n\t\t{codes.OK, http.StatusOK},\n\t\t{codes.Canceled, http.StatusServiceUnavailable},\n\t\t{codes.DeadlineExceeded, http.StatusServiceUnavailable},\n\t\t{codes.Aborted, http.StatusServiceUnavailable},\n\t\t{codes.OutOfRange, http.StatusServiceUnavailable},\n\t\t{codes.Unavailable, http.StatusServiceUnavailable},\n\t\t{codes.DataLoss, http.StatusServiceUnavailable},\n\t\t{codes.ResourceExhausted, http.StatusTooManyRequests},\n\t\t{codes.InvalidArgument, http.StatusBadRequest},\n\t\t{codes.Unauthenticated, http.StatusUnauthorized},\n\t\t{codes.PermissionDenied, http.StatusForbidden},\n\t\t{codes.Unimplemented, http.StatusNotFound},\n\t}\n\n\tfor _, tt := range testCases {\n\t\ts := status.New(tt.grpc, \"Testing error\")\n\t\tt.Run(\"Code \"+s.Code().String(), func(t *testing.T) {\n\t\t\te := createGRPCExporter(t, s)\n\t\t\tassertOnHTTPCode(t, e, tt.http)\n\t\t})\n\t}\n}\n\nfunc TestGRPCToHTTP(t *testing.T) {\n\ttestCases := []struct {\n\t\thttp int\n\t\tgrpc codes.Code\n\t}{\n\t\t{http.StatusOK, codes.OK},\n\t\t{http.StatusBadRequest, codes.InvalidArgument},\n\t\t{http.StatusUnauthorized, codes.Unauthenticated},\n\t\t{http.StatusForbidden, codes.PermissionDenied},\n\t\t{http.StatusNotFound, codes.Unimplemented},\n\t\t{http.StatusTooManyRequests, codes.ResourceExhausted},\n\t\t{http.StatusBadGateway, codes.Unavailable},\n\t\t{http.StatusServiceUnavailable, codes.Unavailable},\n\t\t{http.StatusGatewayTimeout, codes.Unavailable},\n\t}\n\n\tfor _, tt := range testCases {\n\t\ts := status.New(tt.grpc, \"Testing error\")\n\t\tt.Run(\"Code \"+s.Code().String(), func(t *testing.T) {\n\t\t\te := createHTTPExporter(t, tt.http)\n\t\t\tassertOnGRPCCode(t, e, s)\n\t\t})\n\t}\n}\n\nfunc TestHTTPToHTTP(t *testing.T) {\n\ttestCases := []struct {\n\t\tcode    int\n\t\tmapping int\n\t}{\n\t\t{code: http.StatusOK},\n\t\t{code: http.StatusServiceUnavailable},\n\t\t{code: http.StatusTooManyRequests},\n\t\t{code: http.StatusBadRequest},\n\t\t{code: http.StatusUnauthorized},\n\t\t{code: http.StatusForbidden},\n\t\t{code: http.StatusNotFound},\n\t\t{code: http.StatusInternalServerError},\n\t\t// Mappings won't be necessary once the OTLP/HTTP Exporter returns consumererror.Error types.\n\t\t{code: http.StatusBadGateway, mapping: http.StatusServiceUnavailable},\n\t\t{code: http.StatusGatewayTimeout, mapping: http.StatusServiceUnavailable},\n\t\t{code: http.StatusTeapot, mapping: http.StatusInternalServerError},\n\t\t{code: http.StatusConflict, mapping: http.StatusInternalServerError},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(\"Code \"+strconv.Itoa(tt.code), func(t *testing.T) {\n\t\t\te := createHTTPExporter(t, tt.code)\n\t\t\tcode := tt.code\n\t\t\tif tt.mapping != 0 {\n\t\t\t\tcode = tt.mapping\n\t\t\t}\n\t\t\tassertOnHTTPCode(t, e, code)\n\t\t})\n\t}\n}\n\nfunc createGRPCExporter(t *testing.T, s *status.Status) consumer.Logs {\n\tt.Helper()\n\n\tln, err := net.Listen(\"tcp\", \"localhost:\")\n\trequire.NoError(t, err, \"Failed to find an available address to run the gRPC server: %v\", err)\n\n\tsrv := grpc.NewServer()\n\trcv := &logsServer{\n\t\texportError: s.Err(),\n\t}\n\n\tplogotlp.RegisterGRPCServer(srv, rcv)\n\tgo func() {\n\t\tassert.NoError(t, srv.Serve(ln))\n\t}()\n\tt.Cleanup(func() {\n\t\tsrv.Stop()\n\t})\n\n\tf := otlpexporter.NewFactory()\n\tcfg := f.CreateDefaultConfig().(*otlpexporter.Config)\n\tcfg.QueueConfig = configoptional.None[exporterhelper.QueueBatchConfig]()\n\tcfg.RetryConfig.Enabled = false\n\tcfg.ClientConfig = configgrpc.ClientConfig{\n\t\tEndpoint: ln.Addr().String(),\n\t\tTLS: configtls.ClientConfig{\n\t\t\tInsecure: true,\n\t\t},\n\t}\n\te, err := f.CreateLogs(context.Background(), exportertest.NewNopSettings(component.MustNewType(\"otlp\")), cfg)\n\trequire.NoError(t, err)\n\terr = e.Start(context.Background(), componenttest.NewNopHost())\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, e.Shutdown(context.Background()))\n\t})\n\n\treturn e\n}\n\nfunc createHTTPExporter(t *testing.T, code int) consumer.Logs {\n\tt.Helper()\n\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/v1/logs\", func(writer http.ResponseWriter, _ *http.Request) {\n\t\twriter.WriteHeader(code)\n\t})\n\n\tsrv := httptest.NewServer(mux)\n\tt.Cleanup(func() {\n\t\tsrv.Close()\n\t})\n\n\tf := otlphttpexporter.NewFactory()\n\tcfg := f.CreateDefaultConfig().(*otlphttpexporter.Config)\n\tcfg.QueueConfig = configoptional.None[exporterhelper.QueueBatchConfig]()\n\tcfg.RetryConfig.Enabled = false\n\tcfg.Encoding = otlphttpexporter.EncodingProto\n\tcfg.LogsEndpoint = srv.URL + \"/v1/logs\"\n\te, err := f.CreateLogs(context.Background(), exportertest.NewNopSettings(component.MustNewType(\"otlp_http\")), cfg)\n\trequire.NoError(t, err)\n\terr = e.Start(context.Background(), componenttest.NewNopHost())\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, e.Shutdown(context.Background()))\n\t})\n\n\treturn e\n}\n\nfunc assertOnGRPCCode(t *testing.T, l consumer.Logs, s *status.Status) {\n\tt.Helper()\n\n\trf := otlpreceiver.NewFactory()\n\trcfg := rf.CreateDefaultConfig().(*otlpreceiver.Config)\n\trcfg.GRPC = configoptional.Some(\n\t\tconfiggrpc.ServerConfig{\n\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\tEndpoint:  testutil.GetAvailableLocalAddress(t),\n\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t},\n\t\t},\n\t)\n\tr, err := rf.CreateLogs(context.Background(), receiver.Settings{\n\t\tID:                component.MustNewID(\"otlp\"),\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t}, rcfg, l)\n\trequire.NoError(t, err)\n\terr = r.Start(context.Background(), componenttest.NewNopHost())\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, r.Shutdown(context.Background()))\n\t})\n\n\tconn, err := grpc.NewClient(rcfg.GRPC.Get().NetAddr.Endpoint, grpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, conn.Close())\n\t})\n\n\tld := testdata.GenerateLogs(2)\n\n\tacc := plogotlp.NewGRPCClient(conn)\n\treq := plogotlp.NewExportRequestFromLogs(ld)\n\tres, err := acc.Export(context.Background(), req)\n\n\tif s.Code() == codes.OK {\n\t\trequire.NoError(t, err)\n\t} else {\n\t\tgot := status.Convert(err).Code()\n\t\trequire.Equal(t, s.Code(), got, \"Expected code %s but got %s\", s.Code().String(), got.String())\n\t}\n\trequire.NotNil(t, res)\n}\n\nfunc assertOnHTTPCode(t *testing.T, l consumer.Logs, code int) {\n\tt.Helper()\n\n\tld := testdata.GenerateLogs(2)\n\tprotoMarshaler := &plog.ProtoMarshaler{}\n\tlogProto, err := protoMarshaler.MarshalLogs(ld)\n\trequire.NoError(t, err)\n\n\taddr := testutil.GetAvailableLocalAddress(t)\n\trf := otlpreceiver.NewFactory()\n\trcfg := rf.CreateDefaultConfig().(*otlpreceiver.Config)\n\trcfg.HTTP = configoptional.Some(\n\t\totlpreceiver.HTTPConfig{\n\t\t\tServerConfig: confighttp.ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  addr,\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t},\n\t\t\tLogsURLPath: \"/v1/logs\",\n\t\t},\n\t)\n\tr, err := rf.CreateLogs(context.Background(), receiver.Settings{\n\t\tID:                component.MustNewID(\"otlp\"),\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t}, rcfg, l)\n\trequire.NoError(t, err)\n\terr = r.Start(context.Background(), componenttest.NewNopHost())\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, r.Shutdown(context.Background()))\n\t})\n\n\tdoHTTPRequest(t, addr+\"/v1/logs\", logProto, code)\n}\n\nfunc doHTTPRequest(\n\tt *testing.T,\n\turl string,\n\tdata []byte,\n\texpectStatusCode int,\n) []byte {\n\treq := createHTTPRequest(t, url, data)\n\tresp, err := http.DefaultClient.Do(req)\n\trequire.NoError(t, err)\n\n\trespBytes, err := io.ReadAll(resp.Body)\n\trequire.NoError(t, err)\n\n\trequire.NoError(t, resp.Body.Close())\n\n\tif expectStatusCode == 0 {\n\t\trequire.Equal(t, http.StatusOK, resp.StatusCode)\n\t} else {\n\t\trequire.Equal(t, expectStatusCode, resp.StatusCode)\n\t}\n\n\treturn respBytes\n}\n\nfunc createHTTPRequest(\n\tt *testing.T,\n\turl string,\n\tdata []byte,\n) *http.Request {\n\tbuf := bytes.NewBuffer(data)\n\n\treq, err := http.NewRequest(http.MethodPost, \"http://\"+url, buf)\n\trequire.NoError(t, err)\n\treq.Header.Set(\"Content-Type\", \"application/x-protobuf\")\n\n\treturn req\n}\n"
  },
  {
    "path": "internal/e2e/exporter_failure_attributes_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2e\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"path/filepath\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\tdto \"github.com/prometheus/client_model/go\"\n\t\"github.com/prometheus/common/expfmt\"\n\t\"github.com/prometheus/common/model\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/provider/envprovider\"\n\t\"go.opentelemetry.io/collector/confmap/provider/fileprovider\"\n\t\"go.opentelemetry.io/collector/confmap/provider/yamlprovider\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/otlphttpexporter\"\n\t\"go.opentelemetry.io/collector/otelcol\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver\"\n\t\"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\"\n)\n\nfunc TestExporterFailureAttributesDetailed(t *testing.T) {\n\tt.Run(\"permanent error sets error.permanent\", func(t *testing.T) {\n\t\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tif r.URL.Path != \"/v1/metrics\" {\n\t\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\t\treturn\n\t\t\t}\n\t\t\thttp.Error(w, \"bad request\", http.StatusBadRequest)\n\t\t}))\n\t\tdefer server.Close()\n\n\t\totelPort, metricsPort := startFailureAttributeCollector(t, server.URL)\n\n\t\trequire.NoError(t, sendTestMetrics(otelPort))\n\n\t\trequire.Eventually(t, func() bool {\n\t\t\tmetric := scrapeFailureMetric(t, metricsPort, \"otlp_http/test\")\n\t\t\tif metric == nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfailurePermanent, ok := labelValue(metric, \"error_permanent\")\n\t\t\treturn ok && failurePermanent == \"true\"\n\t\t}, 5*time.Second, 200*time.Millisecond, \"expected permanent failure metric\")\n\t})\n\n\tt.Run(\"transient error that recovers has no failure metric\", func(t *testing.T) {\n\t\tvar attempts atomic.Int32\n\t\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tif r.URL.Path != \"/v1/metrics\" {\n\t\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tif attempts.Add(1) == 1 {\n\t\t\t\thttp.Error(w, \"try again\", http.StatusServiceUnavailable)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tw.WriteHeader(http.StatusOK)\n\t\t}))\n\t\tdefer server.Close()\n\n\t\totelPort, metricsPort := startFailureAttributeCollector(t, server.URL)\n\n\t\trequire.NoError(t, sendTestMetrics(otelPort))\n\t\tassertNoFailureMetric(t, metricsPort, \"otlp_http/test\")\n\t})\n\n\tt.Run(\"retryable error exhausts retries\", func(t *testing.T) {\n\t\tserver := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\tif r.URL.Path != \"/v1/metrics\" {\n\t\t\t\tw.WriteHeader(http.StatusNotFound)\n\t\t\t\treturn\n\t\t\t}\n\t\t\thttp.Error(w, \"temporarily unavailable\", http.StatusServiceUnavailable)\n\t\t}))\n\t\tdefer server.Close()\n\n\t\totelPort, metricsPort := startFailureAttributeCollector(t, server.URL)\n\n\t\trequire.NoError(t, sendTestMetrics(otelPort))\n\n\t\trequire.Eventually(t, func() bool {\n\t\t\tmetric := scrapeFailureMetric(t, metricsPort, \"otlp_http/test\")\n\t\t\tif metric == nil {\n\t\t\t\treturn false\n\t\t\t}\n\t\t\tfailurePermanent, ok := labelValue(metric, \"error_permanent\")\n\t\t\treturn ok && failurePermanent == \"false\"\n\t\t}, 5*time.Second, 200*time.Millisecond, \"expected retry exhaustion metric\")\n\t})\n}\n\nfunc startFailureAttributeCollector(t *testing.T, exporterEndpoint string) (string, string) {\n\tt.Helper()\n\totelPort := getFreePort(t)\n\tmetricsPort := getFreePort(t)\n\n\tt.Setenv(\"METRICS_PORT\", metricsPort)\n\tt.Setenv(\"OTEL_PORT\", otelPort)\n\tt.Setenv(\"EXPORTER_ENDPOINT\", exporterEndpoint)\n\n\tcollector, err := otelcol.NewCollector(otelcol.CollectorSettings{\n\t\tBuildInfo: component.NewDefaultBuildInfo(),\n\t\tFactories: func() (otelcol.Factories, error) {\n\t\t\treturn otelcol.Factories{\n\t\t\t\tReceivers: map[component.Type]receiver.Factory{otlpreceiver.NewFactory().Type(): otlpreceiver.NewFactory()},\n\t\t\t\tExporters: map[component.Type]exporter.Factory{\n\t\t\t\t\totlphttpexporter.NewFactory().Type(): otlphttpexporter.NewFactory(),\n\t\t\t\t},\n\t\t\t\tTelemetry: otelconftelemetry.NewFactory(),\n\t\t\t}, nil\n\t\t},\n\t\tConfigProviderSettings: otelcol.ConfigProviderSettings{\n\t\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\t\tURIs: []string{filepath.Join(\"testdata\", \"exporter_failure_attributes_test.yaml\")},\n\t\t\t\tProviderFactories: []confmap.ProviderFactory{\n\t\t\t\t\tfileprovider.NewFactory(),\n\t\t\t\t\tyamlprovider.NewFactory(),\n\t\t\t\t\tenvprovider.NewFactory(),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n\trequire.NoError(t, err)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tt.Cleanup(cancel)\n\n\tgo func() {\n\t\tif err := collector.Run(ctx); err != nil {\n\t\t\tt.Logf(\"Collector stopped with error: %v\", err)\n\t\t}\n\t}()\n\n\trequire.Eventually(t, func() bool {\n\t\tresp, err := http.Get(fmt.Sprintf(\"http://localhost:%s/metrics\", metricsPort))\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tresp.Body.Close()\n\t\treturn resp.StatusCode == http.StatusOK\n\t}, 5*time.Second, 100*time.Millisecond, \"collector failed to start\")\n\n\treturn otelPort, metricsPort\n}\n\nfunc scrapeFailureMetric(t *testing.T, metricsPort, exporterName string) *dto.Metric {\n\tt.Helper()\n\tresp, err := http.Get(fmt.Sprintf(\"http://localhost:%s/metrics\", metricsPort))\n\tif err != nil {\n\t\treturn nil\n\t}\n\tdefer resp.Body.Close()\n\tif resp.StatusCode != http.StatusOK {\n\t\treturn nil\n\t}\n\n\tparser := expfmt.NewTextParser(model.UTF8Validation)\n\tparsed, err := parser.TextToMetricFamilies(resp.Body)\n\tif err != nil {\n\t\treturn nil\n\t}\n\n\tmetricFamily, ok := parsed[\"otelcol_exporter_send_failed_metric_points\"]\n\tif !ok {\n\t\tmetricFamily, ok = parsed[\"otelcol_exporter_send_failed_metric_points_total\"]\n\t}\n\tif !ok {\n\t\treturn nil\n\t}\n\n\tfor _, metric := range metricFamily.Metric {\n\t\tif hasLabel(metric, \"exporter\", exporterName) {\n\t\t\treturn metric\n\t\t}\n\t}\n\n\treturn nil\n}\n\nfunc hasLabel(metric *dto.Metric, name, expected string) bool {\n\tfor _, label := range metric.Label {\n\t\tif label.GetName() == name && label.GetValue() == expected {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\nfunc labelValue(metric *dto.Metric, labelName string) (string, bool) {\n\tfor _, label := range metric.Label {\n\t\tif label.GetName() == labelName {\n\t\t\treturn label.GetValue(), true\n\t\t}\n\t}\n\treturn \"\", false\n}\n\nfunc assertNoFailureMetric(t *testing.T, metricsPort, exporterName string) {\n\tt.Helper()\n\tdeadline := time.Now().Add(2 * time.Second)\n\tfor time.Now().Before(deadline) {\n\t\tif metric := scrapeFailureMetric(t, metricsPort, exporterName); metric != nil {\n\t\t\tfailurePermanent, _ := labelValue(metric, \"error_permanent\")\n\t\t\tt.Fatalf(\"unexpected failure metric recorded, error_permanent=%s\", failurePermanent)\n\t\t}\n\t\ttime.Sleep(100 * time.Millisecond)\n\t}\n}\n"
  },
  {
    "path": "internal/e2e/go.mod",
    "content": "module go.opentelemetry.io/collector/internal/e2e\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/google/go-cmp v0.7.0\n\tgithub.com/google/uuid v1.6.0\n\tgithub.com/prometheus/client_model v0.6.2\n\tgithub.com/prometheus/common v0.67.5\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componentstatus v0.148.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/config/configauth v1.54.0\n\tgo.opentelemetry.io/collector/config/configgrpc v0.148.0\n\tgo.opentelemetry.io/collector/config/confighttp v0.148.0\n\tgo.opentelemetry.io/collector/config/confignet v1.54.0\n\tgo.opentelemetry.io/collector/config/configopaque v1.54.0\n\tgo.opentelemetry.io/collector/config/configoptional v1.54.0\n\tgo.opentelemetry.io/collector/config/configretry v1.54.0\n\tgo.opentelemetry.io/collector/config/configtelemetry v0.148.0\n\tgo.opentelemetry.io/collector/config/configtls v1.54.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/confmap/provider/envprovider v1.54.0\n\tgo.opentelemetry.io/collector/confmap/provider/fileprovider v1.54.0\n\tgo.opentelemetry.io/collector/confmap/provider/yamlprovider v1.54.0\n\tgo.opentelemetry.io/collector/connector v0.148.0\n\tgo.opentelemetry.io/collector/connector/connectortest v0.148.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/exporter v1.54.0\n\tgo.opentelemetry.io/collector/exporter/debugexporter v0.148.0\n\tgo.opentelemetry.io/collector/exporter/exporterhelper v0.148.0\n\tgo.opentelemetry.io/collector/exporter/exportertest v0.148.0\n\tgo.opentelemetry.io/collector/exporter/otlpexporter v0.148.0\n\tgo.opentelemetry.io/collector/exporter/otlphttpexporter v0.148.0\n\tgo.opentelemetry.io/collector/extension v1.54.0\n\tgo.opentelemetry.io/collector/internal/sharedcomponent v0.148.0\n\tgo.opentelemetry.io/collector/internal/testutil v0.148.0\n\tgo.opentelemetry.io/collector/otelcol v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/processor v1.54.0\n\tgo.opentelemetry.io/collector/processor/batchprocessor v0.148.0\n\tgo.opentelemetry.io/collector/receiver v1.54.0\n\tgo.opentelemetry.io/collector/receiver/otlpreceiver v0.148.0\n\tgo.opentelemetry.io/collector/receiver/receivertest v0.148.0\n\tgo.opentelemetry.io/collector/service v0.148.0\n\tgo.opentelemetry.io/proto/otlp v1.10.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/zap v1.27.1\n\tgoogle.golang.org/grpc v1.79.3\n\tgoogle.golang.org/protobuf v1.36.11\n)\n\nrequire (\n\tgithub.com/beorn7/perks v1.0.1 // indirect\n\tgithub.com/cenkalti/backoff/v5 v5.0.3 // indirect\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect\n\tgithub.com/ebitengine/purego v0.10.0 // indirect\n\tgithub.com/felixge/httpsnoop v1.0.4 // indirect\n\tgithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f // indirect\n\tgithub.com/fsnotify/fsnotify v1.9.0 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-ole/go-ole v1.2.6 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/golang/snappy v1.0.0 // indirect\n\tgithub.com/google/go-tpm v0.9.8 // indirect\n\tgithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/hashicorp/golang-lru/v2 v2.0.7 // indirect\n\tgithub.com/inconshreveable/mousetrap v1.1.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/klauspost/compress v1.18.4 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/mostynb/go-grpc-compression v1.2.3 // indirect\n\tgithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect\n\tgithub.com/pierrec/lz4/v4 v4.1.26 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect\n\tgithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect\n\tgithub.com/prometheus/client_golang v1.23.2 // indirect\n\tgithub.com/prometheus/otlptranslator v1.0.0 // indirect\n\tgithub.com/prometheus/procfs v0.20.1 // indirect\n\tgithub.com/rs/cors v1.11.1 // indirect\n\tgithub.com/shirou/gopsutil/v4 v4.26.2 // indirect\n\tgithub.com/spf13/cobra v1.10.2 // indirect\n\tgithub.com/spf13/pflag v1.0.10 // indirect\n\tgithub.com/tklauser/go-sysconf v0.3.16 // indirect\n\tgithub.com/tklauser/numcpus v0.11.0 // indirect\n\tgithub.com/yusufpapurcu/wmi v1.2.4 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/client v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configcompression v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configmiddleware v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/connector/xconnector v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumererror/xconsumererror v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/exporter/xexporter v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionauth v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensioncapabilities v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionmiddleware v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensiontest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension/xextension v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/internal/fanoutconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/internal/telemetry v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/xpdata v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/processor/processortest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/processor/xprocessor v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/receiverhelper v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/service/hostcapabilities v0.148.0 // indirect\n\tgo.opentelemetry.io/contrib/bridges/otelzap v0.17.0 // indirect\n\tgo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 // indirect\n\tgo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect\n\tgo.opentelemetry.io/contrib/otelconf v0.22.0 // indirect\n\tgo.opentelemetry.io/contrib/propagators/b3 v1.42.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/prometheus v0.64.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/log v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/log v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.yaml.in/yaml/v2 v2.4.3 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/crypto v0.48.0 // indirect\n\tgolang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sys v0.42.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgonum.org/v1/gonum v0.17.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector => ../..\n\nreplace go.opentelemetry.io/collector/config/configopaque => ../../config/configopaque\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../../config/configoptional\n\nreplace go.opentelemetry.io/collector/config/configgrpc => ../../config/configgrpc\n\nreplace go.opentelemetry.io/collector/config/confignet => ../../config/confignet\n\nreplace go.opentelemetry.io/collector/config/confighttp => ../../config/confighttp\n\nreplace go.opentelemetry.io/collector/config/configauth => ../../config/configauth\n\nreplace go.opentelemetry.io/collector/config/configretry => ../../config/configretry\n\nreplace go.opentelemetry.io/collector/config/configtls => ../../config/configtls\n\nreplace go.opentelemetry.io/collector/extension/extensionauth => ../../extension/extensionauth\n\nreplace go.opentelemetry.io/collector/exporter/otlpexporter => ../../exporter/otlpexporter\n\nreplace go.opentelemetry.io/collector/config/configcompression => ../../config/configcompression\n\nreplace go.opentelemetry.io/collector/exporter/otlphttpexporter => ../../exporter/otlphttpexporter\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/receiver/otlpreceiver => ../../receiver/otlpreceiver\n\nreplace go.opentelemetry.io/collector/receiver => ../../receiver\n\nreplace go.opentelemetry.io/collector/receiver/receiverhelper => ../../receiver/receiverhelper\n\nreplace go.opentelemetry.io/collector/extension => ../../extension\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/exporter => ../../exporter\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/config/configtelemetry => ../../config/configtelemetry\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/client => ../../client\n\nreplace go.opentelemetry.io/collector/component/componentstatus => ../../component/componentstatus\n\nreplace go.opentelemetry.io/collector/connector => ../../connector\n\nreplace go.opentelemetry.io/collector/connector/connectortest => ../../connector/connectortest\n\nreplace go.opentelemetry.io/collector/processor => ../../processor\n\nreplace go.opentelemetry.io/collector/extension/zpagesextension => ../../extension/zpagesextension\n\nreplace go.opentelemetry.io/collector/service => ../../service\n\nreplace go.opentelemetry.io/collector/service/telemetry/telemetrytest => ../../service/telemetry/telemetrytest\n\nreplace go.opentelemetry.io/collector/extension/extensioncapabilities => ../../extension/extensioncapabilities\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../../receiver/receivertest\n\nreplace go.opentelemetry.io/collector/processor/xprocessor => ../../processor/xprocessor\n\nreplace go.opentelemetry.io/collector/connector/xconnector => ../../connector/xconnector\n\nreplace go.opentelemetry.io/collector/exporter/xexporter => ../../exporter/xexporter\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/exporter/exportertest => ../../exporter/exportertest\n\nreplace go.opentelemetry.io/collector/processor/processortest => ../../processor/processortest\n\nreplace go.opentelemetry.io/collector/consumer/consumererror/xconsumererror => ../../consumer/consumererror/xconsumererror\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper => ../../exporter/exporterhelper/xexporterhelper\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/internal/fanoutconsumer => ../../internal/fanoutconsumer\n\nreplace go.opentelemetry.io/collector/internal/sharedcomponent => ../../internal/sharedcomponent\n\nreplace go.opentelemetry.io/collector/internal/telemetry => ../../internal/telemetry\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../../extension/extensiontest\n\nreplace go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest => ../../extension/extensionauth/extensionauthtest\n\nreplace go.opentelemetry.io/collector/extension/xextension => ../../extension/xextension\n\nreplace go.opentelemetry.io/collector/otelcol => ../../otelcol\n\nreplace go.opentelemetry.io/collector/confmap/provider/yamlprovider => ../../confmap/provider/yamlprovider\n\nreplace go.opentelemetry.io/collector/confmap/provider/fileprovider => ../../confmap/provider/fileprovider\n\nreplace go.opentelemetry.io/collector/service/hostcapabilities => ../../service/hostcapabilities\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest => ../../extension/extensionmiddleware/extensionmiddlewaretest\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ../../extension/extensionmiddleware\n\nreplace go.opentelemetry.io/collector/config/configmiddleware => ../../config/configmiddleware\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/exporter/debugexporter => ../../exporter/debugexporter\n\nreplace go.opentelemetry.io/collector/processor/batchprocessor => ../../processor/batchprocessor\n\nreplace go.opentelemetry.io/collector/confmap/provider/envprovider => ../../confmap/provider/envprovider\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper => ../../exporter/exporterhelper\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../componentalias\n"
  },
  {
    "path": "internal/e2e/go.sum",
    "content": "github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=\ngithub.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=\ngithub.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=\ngithub.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=\ngithub.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=\ngithub.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=\ngithub.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f h1:RJ+BDPLSHQO7cSjKBqjPJSbi1qfk9WcsjQDtZiw3dZw=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f/go.mod h1:VHbbch/X4roIY22jL1s3qRbZhCiRIgUAF/PdSUcx2io=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=\ngithub.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=\ngithub.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=\ngithub.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=\ngithub.com/google/go-tpm-tools v0.4.7 h1:J3ycC8umYxM9A4eF73EofRZu4BxY0jjQnUnkhIBbvws=\ngithub.com/google/go-tpm-tools v0.4.7/go.mod h1:gSyXTZHe3fgbzb6WEGd90QucmsnT1SRdlye82gH8QjQ=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=\ngithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=\ngithub.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=\ngithub.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=\ngithub.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=\ngithub.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=\ngithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3 h1:PwQumkgq4/acIiZhtifTV5OUqqiP82UAl0h87xj/l9k=\ngithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/mostynb/go-grpc-compression v1.2.3 h1:42/BKWMy0KEJGSdWvzqIyOZ95YcR9mLPqKctH7Uo//I=\ngithub.com/mostynb/go-grpc-compression v1.2.3/go.mod h1:AghIxF3P57umzqM9yz795+y1Vjs47Km/Y2FE6ouQ7Lg=\ngithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=\ngithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=\ngithub.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=\ngithub.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=\ngithub.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=\ngithub.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=\ngithub.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=\ngithub.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=\ngithub.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=\ngithub.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=\ngithub.com/prometheus/otlptranslator v1.0.0 h1:s0LJW/iN9dkIH+EnhiD3BlkkP5QVIUVEoIwkU+A6qos=\ngithub.com/prometheus/otlptranslator v1.0.0/go.mod h1:vRYWnXvI6aWGpsdY/mOT/cbeVRBlPWtBNDb7kGR3uKM=\ngithub.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc=\ngithub.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=\ngithub.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=\ngithub.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=\ngithub.com/shirou/gopsutil/v4 v4.26.2 h1:X8i6sicvUFih4BmYIGT1m2wwgw2VG9YgrDTi7cIRGUI=\ngithub.com/shirou/gopsutil/v4 v4.26.2/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=\ngithub.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=\ngithub.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=\ngithub.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=\ngithub.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngithub.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYICU0nA=\ngithub.com/tklauser/go-sysconf v0.3.16/go.mod h1:/qNL9xxDhc7tx3HSRsLWNnuzbVfh3e7gh/BmM179nYI=\ngithub.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9RXw=\ngithub.com/tklauser/numcpus v0.11.0/go.mod h1:z+LwcLq54uWZTX0u/bGobaV34u6V7KNlTZejzM6/3MQ=\ngithub.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=\ngithub.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/contrib/bridges/otelzap v0.17.0 h1:oCltVHJcblcth2z9B9dRTeZIZTe2Sf9Ad9h8bcc+s8M=\ngo.opentelemetry.io/contrib/bridges/otelzap v0.17.0/go.mod h1:G/VE1A/hRn6mEWdfC8rMvSdQVGM64KUPi4XilLkwcQw=\ngo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 h1:yI1/OhfEPy7J9eoa6Sj051C7n5dvpj0QX8g4sRchg04=\ngo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0/go.mod h1:NoUCKYWK+3ecatC4HjkRktREheMeEtrXoQxrqYFeHSc=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=\ngo.opentelemetry.io/contrib/otelconf v0.22.0 h1:+kpcfczGOFM85zDZyqQCzWefhovegfn24D0WwmQz0n4=\ngo.opentelemetry.io/contrib/otelconf v0.22.0/go.mod h1:ojdbOukO+JRDJQmJY2PRIZEg0UYVzcOuZR59hp7xffc=\ngo.opentelemetry.io/contrib/propagators/b3 v1.42.0 h1:B2Pew5ufEtgkjLF+tSkXjgYZXQr9m7aCm1wLKB0URbU=\ngo.opentelemetry.io/contrib/propagators/b3 v1.42.0/go.mod h1:iPgUcSEF5DORW6+yNbdw/YevUy+QqJ508ncjhrRSCjc=\ngo.opentelemetry.io/contrib/zpages v0.67.0 h1:cIUwWSVDovuLEbDIKreptjdxMuIhGiqwq0uL8YNaq1c=\ngo.opentelemetry.io/contrib/zpages v0.67.0/go.mod h1:vK8fsYHgPYg4Z/XDbFSEvItSGZDbjWTvjBOu8+AiDhc=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0 h1:deI9UQMoGFgrg5iLPgzueqFPHevDl+28YKfSpPTI6rY=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0/go.mod h1:PFx9NgpNUKXdf7J4Q3agRxMs3Y07QhTCVipKmLsMKnU=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0 h1:icqq3Z34UrEFk2u+HMhTtRsvo7Ues+eiJVjaJt62njs=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0/go.mod h1:W2m8P+d5Wn5kipj4/xmbt9uMqezEKfBjzVJadfABSBE=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0 h1:MdKucPl/HbzckWWEisiNqMPhRrAOQX8r4jTuGr636gk=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0/go.mod h1:RolT8tWtfHcjajEH5wFIZ4Dgh5jpPdFXYV9pTAk/qjc=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0 h1:H7O6RlGOMTizyl3R08Kn5pdM06bnH8oscSj7o11tmLA=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0/go.mod h1:mBFWu/WOVDkWWsR7Tx7h6EpQB8wsv7P0Yrh0Pb7othc=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 h1:THuZiwpQZuHPul65w4WcwEnkX2QIuMT+UFoOrygtoJw=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0/go.mod h1:J2pvYM5NGHofZ2/Ru6zw/TNWnEQp5crgyDeSrYpXkAw=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0 h1:zWWrB1U6nqhS/k6zYB74CjRpuiitRtLLi68VcgmOEto=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0/go.mod h1:2qXPNBX1OVRC0IwOnfo1ljoid+RD0QK3443EaqVlsOU=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 h1:uLXP+3mghfMf7XmV4PkGfFhFKuNWoCvvx5wP/wOXo0o=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0/go.mod h1:v0Tj04armyT59mnURNUJf7RCKcKzq+lgJs6QSjHjaTc=\ngo.opentelemetry.io/otel/exporters/prometheus v0.64.0 h1:g0LRDXMX/G1SEZtK8zl8Chm4K6GBwRkjPKE36LxiTYs=\ngo.opentelemetry.io/otel/exporters/prometheus v0.64.0/go.mod h1:UrgcjnarfdlBDP3GjDIJWe6HTprwSazNjwsI+Ru6hro=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0 h1:KJVjPD3rcPb98rIs3HznyJlrfx9ge5oJvxxlGR+P/7s=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0/go.mod h1:K3kRa2ckmHWQaTWQdPRHc7qGXASuVuoEQXzrvlA98Ws=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0 h1:lSZHgNHfbmQTPfuTmWVkEu8J8qXaQwuV30pjCcAUvP8=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0/go.mod h1:so9ounLcuoRDu033MW/E0AD4hhUjVqswrMF5FoZlBcw=\ngo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0 h1:s/1iRkCKDfhlh1JF26knRneorus8aOwVIDhvYx9WoDw=\ngo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0/go.mod h1:UI3wi0FXg1Pofb8ZBiBLhtMzgoTm1TYkMvn71fAqDzs=\ngo.opentelemetry.io/otel/log v0.18.0 h1:XgeQIIBjZZrliksMEbcwMZefoOSMI1hdjiLEiiB0bAg=\ngo.opentelemetry.io/otel/log v0.18.0/go.mod h1:KEV1kad0NofR3ycsiDH4Yjcoj0+8206I6Ox2QYFSNgI=\ngo.opentelemetry.io/otel/log/logtest v0.18.0 h1:2QeyoKJdIgK2LJhG1yn78o/zmpXx1EditeyRDREqVS8=\ngo.opentelemetry.io/otel/log/logtest v0.18.0/go.mod h1:v1vh3PYR9zIa5MK6HwkH2lMrLBg/Y9Of6Qc+krlesX0=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/log v0.18.0 h1:n8OyZr7t7otkeTnPTbDNom6rW16TBYGtvyy2Gk6buQw=\ngo.opentelemetry.io/otel/sdk/log v0.18.0/go.mod h1:C0+wxkTwKpOCZLrlJ3pewPiiQwpzycPI/u6W0Z9fuYk=\ngo.opentelemetry.io/otel/sdk/log/logtest v0.18.0 h1:l3mYuPsuBx6UKE47BVcPrZoZ0q/KER57vbj2qkgDLXA=\ngo.opentelemetry.io/otel/sdk/log/logtest v0.18.0/go.mod h1:7cHtiVJpZebB3wybTa4NG+FUo5NPe3PROz1FqB0+qdw=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=\ngo.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=\ngo.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=\ngolang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=\ngolang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa h1:Zt3DZoOFFYkKhDT3v7Lm9FDMEV06GpzjG2jrqW+QTE0=\ngolang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=\ngolang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=\ngonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=\ngoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 h1:tu/dtnW1o3wfaxCOjSLn5IRX4YDcJrtlpzYkhHhGaC4=\ngoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171/go.mod h1:M5krXqk4GhBKvB596udGL3UyjL4I1+cTbK0orROM9ng=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "internal/e2e/internal_telemetry_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2e\n\nimport (\n\t\"bytes\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"net/url\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"slices\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/provider/fileprovider\"\n\t\"go.opentelemetry.io/collector/confmap/provider/yamlprovider\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/otelcol\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver\"\n\t\"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\"\n)\n\n// TestInternalTelemetry_ServiceInstanceID verifies that the service.instance.id\n// attribute is generated by default (unless overridden), and is is consistent\n// across all internal telemetry providers.\nfunc TestInternalTelemetry_ServiceInstanceID(t *testing.T) {\n\ttype testcase struct {\n\t\textraYamlConfig        string\n\t\tcheckServiceInstanceID func(t *testing.T, serviceInstanceID string)\n\t}\n\n\tfor name, tt := range map[string]testcase{\n\t\t\"default\": {\n\t\t\tcheckServiceInstanceID: func(t *testing.T, serviceInstanceID string) {\n\t\t\t\t// By default, service.instance.id should be a generated UUIDv4\n\t\t\t\t_, err := uuid.Parse(serviceInstanceID)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t},\n\t\t},\n\t\t\"service.instance.id set in config\": {\n\t\t\textraYamlConfig: `\nservice:\n  telemetry:\n    resource:\n      service.instance.id: \"my-custom-instance-id\"`,\n\t\t\tcheckServiceInstanceID: func(t *testing.T, serviceInstanceID string) {\n\t\t\t\tassert.Equal(t, \"my-custom-instance-id\", serviceInstanceID)\n\t\t\t},\n\t\t},\n\t} {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\t// Set up HTTP server to capture traces from collector's internal telemetry\n\t\t\ttraceSink := new(consumertest.TracesSink)\n\t\t\ttraceServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {\n\t\t\t\tbody, err := io.ReadAll(r.Body)\n\t\t\t\tif err != nil {\n\t\t\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\totlpReq := ptraceotlp.NewExportRequest()\n\t\t\t\tif err := otlpReq.UnmarshalProto(body); err != nil {\n\t\t\t\t\thttp.Error(w, err.Error(), http.StatusBadRequest)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\t_ = traceSink.ConsumeTraces(r.Context(), otlpReq.Traces())\n\t\t\t}))\n\t\t\tdefer traceServer.Close()\n\n\t\t\tlogSink := registerTestLogSink(t)\n\n\t\t\t// Create temporary directory for the config file\n\t\t\ttempdir := t.TempDir()\n\t\t\tconfigFile := filepath.Join(tempdir, \"config.yaml\")\n\n\t\t\t// Create YAML config\n\t\t\totlphttpPort := getFreePort(t)\n\t\t\tmetricsPort := getFreePort(t)\n\t\t\trequire.NoError(t, os.WriteFile(configFile, []byte(fmt.Sprintf(`\nreceivers:\n  otlp:\n    protocols:\n      http:\n        endpoint: localhost:%s\n\nexporters:\n  nop:\n\nservice:\n  telemetry:\n    logs:\n      level: info\n      encoding: json\n      output_paths: [%q]\n    metrics:\n      level: normal\n      readers:\n        - pull:\n            exporter:\n              prometheus:\n                host: localhost\n                port: %s\n    traces:\n      level: normal\n      processors:\n        - simple:\n            exporter:\n              otlp:\n                protocol: http/protobuf\n                endpoint: %s\n  pipelines:\n    traces:\n      receivers: [otlp]\n      exporters: [nop]\n`, otlphttpPort, logSink.url, metricsPort, traceServer.URL)[1:]), 0o600))\n\n\t\t\t// Create collector\n\t\t\tconfigURIs := []string{configFile}\n\t\t\tif tt.extraYamlConfig != \"\" {\n\t\t\t\tconfigURIs = append(configURIs, \"yaml:\"+tt.extraYamlConfig)\n\t\t\t}\n\t\t\tcollector, err := otelcol.NewCollector(otelcol.CollectorSettings{\n\t\t\t\tBuildInfo: component.NewDefaultBuildInfo(),\n\t\t\t\tFactories: func() (otelcol.Factories, error) {\n\t\t\t\t\totlpreceiverFactory := otlpreceiver.NewFactory()\n\t\t\t\t\treturn otelcol.Factories{\n\t\t\t\t\t\tReceivers: map[component.Type]receiver.Factory{\n\t\t\t\t\t\t\totlpreceiverFactory.Type(): otlpreceiverFactory,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tExporters: map[component.Type]exporter.Factory{\n\t\t\t\t\t\t\tnopType: exportertest.NewNopFactory(),\n\t\t\t\t\t\t},\n\t\t\t\t\t\tTelemetry: otelconftelemetry.NewFactory(),\n\t\t\t\t\t}, nil\n\t\t\t\t},\n\t\t\t\tConfigProviderSettings: otelcol.ConfigProviderSettings{\n\t\t\t\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\t\t\t\tURIs: configURIs,\n\t\t\t\t\t\tProviderFactories: []confmap.ProviderFactory{\n\t\t\t\t\t\t\tfileprovider.NewFactory(),\n\t\t\t\t\t\t\tyamlprovider.NewFactory(),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t})\n\t\t\trequire.NoError(t, err)\n\n\t\t\t// Start collector\n\t\t\tgo func() {\n\t\t\t\tassert.NoError(t, collector.Run(t.Context()))\n\t\t\t}()\n\t\t\twaitMetricsReady(t, metricsPort)\n\n\t\t\t// Send some data through the pipeline to trigger internal telemetry\n\t\t\terr = sendTestTraces(otlphttpPort)\n\t\t\trequire.NoError(t, err)\n\n\t\t\t// Capture service.instance.id from the Prometheus endpoint\n\t\t\tvar metricInstanceID string\n\t\t\tparsed := readMetrics(t, metricsPort)\n\t\t\ttargetInfo := parsed[\"target_info\"]\n\t\t\trequire.NotNil(t, targetInfo, \"target_info metric not found\")\n\t\t\trequire.Len(t, targetInfo.Metric, 1)\n\t\t\tfor _, label := range targetInfo.Metric[0].Label {\n\t\t\t\tif label.GetName() == \"service_instance_id\" {\n\t\t\t\t\tmetricInstanceID = label.GetValue()\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t\ttt.checkServiceInstanceID(t, metricInstanceID)\n\n\t\t\t// Wait for traces, verify service.instance.id matches the one from metrics\n\t\t\trequire.EventuallyWithT(t, func(t *assert.CollectT) {\n\t\t\t\tallTraces := traceSink.AllTraces()\n\t\t\t\trequire.NotEmpty(t, allTraces)\n\n\t\t\t\t// Find service.instance.id in resource attributes\n\t\t\t\tfor _, td := range allTraces {\n\t\t\t\t\tfor i := 0; i < td.ResourceSpans().Len(); i++ {\n\t\t\t\t\t\trs := td.ResourceSpans().At(i)\n\t\t\t\t\t\tif attr, ok := rs.Resource().Attributes().Get(\"service.instance.id\"); ok {\n\t\t\t\t\t\t\ttraceInstanceID := attr.AsString()\n\t\t\t\t\t\t\trequire.Equal(t, metricInstanceID, traceInstanceID)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}, 10*time.Second, 500*time.Millisecond)\n\n\t\t\t// Check service.instance.id in logs matches the one from metrics\n\t\t\tvar logsCount int\n\t\t\tlogContent := logSink.Bytes()\n\t\t\tfor line := range bytes.Lines(bytes.TrimSpace(logContent)) {\n\t\t\t\tvar logEntry map[string]any\n\t\t\t\tif err := json.Unmarshal(line, &logEntry); err != nil {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\t// Check for resource field with service.instance.id\n\t\t\t\t// Resource attributes are nested under \"resource\" key as a dictionary\n\t\t\t\tresource, ok := logEntry[\"resource\"].(map[string]any)\n\t\t\t\trequire.True(t, ok, \"log entry should have resource field\")\n\t\t\t\tlogInstanceID, ok := resource[\"service.instance.id\"].(string)\n\t\t\t\trequire.True(t, ok, \"resource should have service.instance.id\")\n\t\t\t\trequire.Equal(t, metricInstanceID, logInstanceID)\n\t\t\t\tlogsCount++\n\t\t\t}\n\t\t\tassert.NotZero(t, logsCount)\n\t\t})\n\t}\n}\n\n// Test-specific zap sink to capture logs as close as possible to logs being written to file.\n// The reason we don't actually write to files is because Zap provides no way of closing file\n// sinks created by zap.Config.Build.\n\nvar (\n\ttestSinksMu sync.Mutex\n\ttestSinks   = make(map[string]*testSink)\n)\n\ntype testSink struct {\n\turl string\n\n\tmu  sync.RWMutex\n\tbuf bytes.Buffer\n}\n\nfunc (s *testSink) Write(p []byte) (n int, err error) {\n\ts.mu.Lock()\n\tdefer s.mu.Unlock()\n\treturn s.buf.Write(p)\n}\n\nfunc (s *testSink) Bytes() []byte {\n\ts.mu.RLock()\n\tdefer s.mu.RUnlock()\n\treturn slices.Clone(s.buf.Bytes())\n}\n\nfunc (*testSink) Sync() error {\n\treturn nil\n}\n\nfunc (*testSink) Close() error {\n\treturn nil\n}\n\nfunc registerTestLogSink(tb testing.TB) *testSink {\n\tsink := &testSink{}\n\tsink.url = fmt.Sprintf(\"test://%s.%p\", tb.Name(), sink)\n\n\ttestSinksMu.Lock()\n\tdefer testSinksMu.Unlock()\n\n\ttestSinks[sink.url] = sink\n\ttb.Cleanup(func() {\n\t\ttestSinksMu.Lock()\n\t\tdefer testSinksMu.Unlock()\n\t\tdelete(testSinks, sink.url)\n\t})\n\treturn sink\n}\n\nfunc init() {\n\tif err := zap.RegisterSink(\"test\", func(u *url.URL) (zap.Sink, error) {\n\t\ttestSinksMu.Lock()\n\t\tdefer testSinksMu.Unlock()\n\t\tsink, ok := testSinks[u.String()]\n\t\tif !ok {\n\t\t\treturn nil, fmt.Errorf(\"no test sink registered for URL %q\", u.String())\n\t\t}\n\t\treturn sink, nil\n\t}); err != nil {\n\t\tlog.Fatal(err)\n\t}\n}\n"
  },
  {
    "path": "internal/e2e/metric_stability_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2e\n\nimport (\n\t\"bufio\"\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"net\"\n\t\"net/http\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"testing\"\n\t\"time\"\n\n\tdto \"github.com/prometheus/client_model/go\"\n\t\"github.com/prometheus/common/expfmt\"\n\t\"github.com/prometheus/common/model\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/provider/envprovider\"\n\t\"go.opentelemetry.io/collector/confmap/provider/fileprovider\"\n\t\"go.opentelemetry.io/collector/confmap/provider/yamlprovider\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/debugexporter\"\n\t\"go.opentelemetry.io/collector/exporter/otlphttpexporter\"\n\t\"go.opentelemetry.io/collector/otelcol\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/batchprocessor\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver\"\n\t\"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\"\n)\n\nfunc assertMetrics(t *testing.T, metricsPort string, expectedMetrics map[string]bool) bool {\n\tparsed := readMetrics(t, metricsPort)\n\n\tfor metricName, metricFamily := range parsed {\n\t\tif _, ok := expectedMetrics[metricName]; ok {\n\t\t\texpectedMetrics[metricName] = true\n\t\t\tassert.GreaterOrEqual(t, len(metricFamily.Metric), 1,\n\t\t\t\t\"metric %s should have at least one data point\", metricName)\n\t\t}\n\t}\n\n\tfor metricName, found := range expectedMetrics {\n\t\tif !found {\n\t\t\tt.Logf(\"expected metric %s was not found\", metricName)\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\nfunc TestMetricStability(t *testing.T) {\n\ttests := []struct {\n\t\tname            string\n\t\tconfigFile      string\n\t\texpectedMetrics map[string]bool\n\t\totelPort        string\n\t\tmetricsPort     string\n\t}{\n\t\t{\n\t\t\tname:       \"No metric readers (default)\",\n\t\t\tconfigFile: \"metric_stability_test_no_readers.yaml\",\n\t\t\texpectedMetrics: map[string]bool{\n\t\t\t\t// Process metrics\n\t\t\t\t\"otelcol_process_uptime\":                         false,\n\t\t\t\t\"otelcol_process_cpu_seconds\":                    false,\n\t\t\t\t\"otelcol_process_memory_rss\":                     false,\n\t\t\t\t\"otelcol_process_runtime_heap_alloc_bytes\":       false,\n\t\t\t\t\"otelcol_process_runtime_total_alloc_bytes\":      false,\n\t\t\t\t\"otelcol_process_runtime_total_sys_memory_bytes\": false,\n\n\t\t\t\t// Batch processor metrics\n\t\t\t\t\"otelcol_processor_batch_batch_send_size\":       false,\n\t\t\t\t\"otelcol_processor_batch_batch_send_size_bytes\": false,\n\t\t\t\t\"otelcol_processor_batch_metadata_cardinality\":  false,\n\t\t\t\t\"otelcol_processor_batch_timeout_trigger_send\":  false,\n\n\t\t\t\t// HTTP server metrics\n\t\t\t\t\"http_server_request_body_size\":  false,\n\t\t\t\t\"http_server_request_duration\":   false,\n\t\t\t\t\"http_server_response_body_size\": false,\n\n\t\t\t\t// Exporter metrics\n\t\t\t\t\"otelcol_exporter_sent_metric_points\":        false,\n\t\t\t\t\"otelcol_exporter_send_failed_metric_points\": false,\n\t\t\t\t\"otelcol_exporter_sent_spans\":                false,\n\t\t\t\t\"otelcol_exporter_send_failed_spans\":         false,\n\t\t\t\t\"otelcol_exporter_sent_log_records\":          false,\n\t\t\t\t\"otelcol_exporter_send_failed_log_records\":   false,\n\n\t\t\t\t// Receiver metrics\n\t\t\t\t\"otelcol_receiver_accepted_metric_points\": false,\n\t\t\t\t\"otelcol_receiver_refused_metric_points\":  false,\n\t\t\t\t\"otelcol_receiver_accepted_spans\":         false,\n\t\t\t\t\"otelcol_receiver_refused_spans\":          false,\n\t\t\t\t\"otelcol_receiver_accepted_log_records\":   false,\n\t\t\t\t\"otelcol_receiver_refused_log_records\":    false,\n\n\t\t\t\t// Other metrics\n\t\t\t\t\"promhttp_metric_handler_errors_total\": false,\n\t\t\t\t\"target_info\":                          false,\n\t\t\t},\n\t\t\totelPort:    getFreePort(t),\n\t\t\tmetricsPort: \"8888\", // default metrics port\n\t\t},\n\t\t{\n\t\t\tname:       \"Metric readers\",\n\t\t\tconfigFile: \"metric_stability_test_readers.yaml\",\n\t\t\texpectedMetrics: map[string]bool{\n\t\t\t\t// Process metrics\n\t\t\t\t\"otelcol_process_uptime_seconds_total\":            false,\n\t\t\t\t\"otelcol_process_cpu_seconds_total\":               false,\n\t\t\t\t\"otelcol_process_memory_rss_bytes\":                false,\n\t\t\t\t\"otelcol_process_runtime_heap_alloc_bytes\":        false,\n\t\t\t\t\"otelcol_process_runtime_total_alloc_bytes_total\": false,\n\t\t\t\t\"otelcol_process_runtime_total_sys_memory_bytes\":  false,\n\n\t\t\t\t// Batch processor metrics\n\t\t\t\t\"otelcol_processor_batch_batch_send_size\":            false,\n\t\t\t\t\"otelcol_processor_batch_batch_send_size_bytes\":      false,\n\t\t\t\t\"otelcol_processor_batch_metadata_cardinality\":       false,\n\t\t\t\t\"otelcol_processor_batch_timeout_trigger_send_total\": false,\n\n\t\t\t\t// HTTP server metrics\n\t\t\t\t\"http_server_request_body_size_bytes\":  false,\n\t\t\t\t\"http_server_request_duration_seconds\": false,\n\t\t\t\t\"http_server_response_body_size_bytes\": false,\n\n\t\t\t\t// Exporter metrics - Metrics\n\t\t\t\t\"otelcol_exporter_sent_metric_points_total\":        false,\n\t\t\t\t\"otelcol_exporter_send_failed_metric_points_total\": false,\n\n\t\t\t\t// Exporter metrics - Traces\n\t\t\t\t\"otelcol_exporter_sent_spans_total\":        false,\n\t\t\t\t\"otelcol_exporter_send_failed_spans_total\": false,\n\n\t\t\t\t// Exporter metrics - Logs\n\t\t\t\t\"otelcol_exporter_sent_log_records_total\":        false,\n\t\t\t\t\"otelcol_exporter_send_failed_log_records_total\": false,\n\n\t\t\t\t// Receiver metrics\n\t\t\t\t\"otelcol_receiver_accepted_metric_points_total\": false,\n\t\t\t\t\"otelcol_receiver_refused_metric_points_total\":  false,\n\n\t\t\t\t// Receiver metrics - Traces\n\t\t\t\t\"otelcol_receiver_accepted_spans_total\": false,\n\t\t\t\t\"otelcol_receiver_refused_spans_total\":  false,\n\n\t\t\t\t// Receiver metrics - Logs\n\t\t\t\t\"otelcol_receiver_accepted_log_records_total\": false,\n\t\t\t\t\"otelcol_receiver_refused_log_records_total\":  false,\n\n\t\t\t\t// Other metrics\n\t\t\t\t\"promhttp_metric_handler_errors_total\": false,\n\t\t\t\t\"target_info\":                          false,\n\t\t\t},\n\t\t\totelPort:    getFreePort(t),\n\t\t\tmetricsPort: getFreePort(t),\n\t\t},\n\t}\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\ttestMetricStability(t, test.configFile, test.expectedMetrics, test.metricsPort, test.otelPort)\n\t\t})\n\t}\n}\n\nfunc testMetricStability(t *testing.T, configFile string, expectedMetrics map[string]bool, metricsPort, otelPort string) {\n\tt.Setenv(\"METRICS_PORT\", metricsPort)\n\tt.Setenv(\"OTEL_PORT\", otelPort)\n\n\tcollector, err := otelcol.NewCollector(otelcol.CollectorSettings{\n\t\tBuildInfo: component.NewDefaultBuildInfo(),\n\t\tFactories: func() (otelcol.Factories, error) {\n\t\t\treturn otelcol.Factories{\n\t\t\t\tReceivers:  map[component.Type]receiver.Factory{otlpreceiver.NewFactory().Type(): otlpreceiver.NewFactory()},\n\t\t\t\tProcessors: map[component.Type]processor.Factory{batchprocessor.NewFactory().Type(): batchprocessor.NewFactory()},\n\t\t\t\tExporters: map[component.Type]exporter.Factory{\n\t\t\t\t\tdebugexporter.NewFactory().Type(): debugexporter.NewFactory(),\n\t\t\t\t\t// otlphttpexporter is needed because the test config files use otlphttp/fail exporter\n\t\t\t\t\totlphttpexporter.NewFactory().Type(): otlphttpexporter.NewFactory(),\n\t\t\t\t},\n\t\t\t\tTelemetry: otelconftelemetry.NewFactory(),\n\t\t\t}, nil\n\t\t},\n\t\tConfigProviderSettings: otelcol.ConfigProviderSettings{\n\t\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\t\tURIs: []string{filepath.Join(\"testdata\", configFile)},\n\t\t\t\tProviderFactories: []confmap.ProviderFactory{\n\t\t\t\t\tfileprovider.NewFactory(),\n\t\t\t\t\tyamlprovider.NewFactory(),\n\t\t\t\t\tenvprovider.NewFactory(),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t})\n\trequire.NoError(t, err)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\tdefer cancel()\n\n\tgo func() {\n\t\terr := collector.Run(ctx)\n\t\tif err != nil {\n\t\t\tt.Logf(\"Collector stopped with error: %v\", err)\n\t\t}\n\t}()\n\twaitMetricsReady(t, metricsPort)\n\n\tfor range 5 {\n\t\tsendTestData(t, otelPort)\n\t}\n\n\trequire.Eventually(t, func() bool {\n\t\treturn assertMetrics(t, metricsPort, expectedMetrics)\n\t}, 10*time.Second, 200*time.Millisecond, \"failed to verify metrics\")\n}\n\nfunc sendTestData(t *testing.T, otelPort string) {\n\trequire.NoError(t, sendTestMetrics(otelPort))\n\trequire.NoError(t, sendTestTraces(otelPort))\n\trequire.NoError(t, sendTestLogs(otelPort))\n}\n\nfunc sendTestMetrics(otelPort string) error {\n\tmetrics := pmetric.NewMetrics()\n\trm := metrics.ResourceMetrics().AppendEmpty()\n\tsm := rm.ScopeMetrics().AppendEmpty()\n\tmetric := sm.Metrics().AppendEmpty()\n\tmetric.SetName(\"test_metric\")\n\tmetric.SetDescription(\"test metric\")\n\tmetric.SetUnit(\"1\")\n\tdp := metric.SetEmptyGauge().DataPoints().AppendEmpty()\n\tdp.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\tdp.SetDoubleValue(42.0)\n\n\tclient := &http.Client{}\n\n\tmetricsMarshaler := pmetric.ProtoMarshaler{}\n\tmetricsBytes, err := metricsMarshaler.MarshalMetrics(metrics)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal metrics: %w\", err)\n\t}\n\n\treq, err := http.NewRequest(http.MethodPost, fmt.Sprintf(\"http://localhost:%s/v1/metrics\", otelPort), bytes.NewReader(metricsBytes))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create metrics request: %w\", err)\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/x-protobuf\")\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to send metrics: %w\", err)\n\t}\n\tresp.Body.Close()\n\n\treturn nil\n}\n\nfunc sendTestTraces(otelPort string) error {\n\ttraces := ptrace.NewTraces()\n\trs := traces.ResourceSpans().AppendEmpty()\n\tss := rs.ScopeSpans().AppendEmpty()\n\tspan := ss.Spans().AppendEmpty()\n\tspan.SetName(\"test_span\")\n\tnow := time.Now()\n\tspan.SetStartTimestamp(pcommon.NewTimestampFromTime(now))\n\tspan.SetEndTimestamp(pcommon.NewTimestampFromTime(now))\n\tspan.SetTraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16})\n\tspan.SetSpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8})\n\n\tclient := &http.Client{}\n\n\ttracesMarshaler := ptrace.ProtoMarshaler{}\n\ttracesBytes, err := tracesMarshaler.MarshalTraces(traces)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal traces: %w\", err)\n\t}\n\n\treq, err := http.NewRequest(http.MethodPost, fmt.Sprintf(\"http://localhost:%s/v1/traces\", otelPort), bytes.NewReader(tracesBytes))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create traces request: %w\", err)\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/x-protobuf\")\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to send traces: %w\", err)\n\t}\n\tresp.Body.Close()\n\n\treturn nil\n}\n\nfunc sendTestLogs(otelPort string) error {\n\tlogs := plog.NewLogs()\n\trl := logs.ResourceLogs().AppendEmpty()\n\tsl := rl.ScopeLogs().AppendEmpty()\n\tlog := sl.LogRecords().AppendEmpty()\n\tlog.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\tlog.SetSeverityText(\"INFO\")\n\tlog.SetSeverityNumber(plog.SeverityNumberInfo)\n\tlog.Body().SetStr(\"test log message\")\n\n\tclient := &http.Client{}\n\n\tlogsMarshaler := plog.ProtoMarshaler{}\n\tlogsBytes, err := logsMarshaler.MarshalLogs(logs)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal logs: %w\", err)\n\t}\n\n\treq, err := http.NewRequest(http.MethodPost, fmt.Sprintf(\"http://localhost:%s/v1/logs\", otelPort), bytes.NewReader(logsBytes))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create logs request: %w\", err)\n\t}\n\treq.Header.Set(\"Content-Type\", \"application/x-protobuf\")\n\n\tresp, err := client.Do(req)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to send logs: %w\", err)\n\t}\n\tresp.Body.Close()\n\n\treturn nil\n}\n\nfunc getFreePort(t *testing.T) string {\n\tt.Helper()\n\tl, err := net.Listen(\"tcp\", \"127.0.0.1:0\")\n\tif err != nil {\n\t\tt.Fatalf(\"could not get free port: %v\", err)\n\t}\n\tdefer l.Close()\n\treturn strconv.Itoa(l.Addr().(*net.TCPAddr).Port)\n}\n\nfunc waitMetricsReady(t *testing.T, metricsPort string) {\n\trequire.EventuallyWithT(t, func(t *assert.CollectT) {\n\t\t_ = readMetrics(t, metricsPort)\n\t}, 10*time.Second, 100*time.Millisecond, \"collector failed to start\")\n}\n\nfunc readMetrics(t require.TestingT, metricsPort string) map[string]*dto.MetricFamily {\n\tresp, err := http.Get(fmt.Sprintf(\"http://localhost:%s/metrics\", metricsPort))\n\trequire.NoError(t, err)\n\tdefer resp.Body.Close()\n\trequire.Equal(t, http.StatusOK, resp.StatusCode)\n\n\treader := bufio.NewReader(resp.Body)\n\tparser := expfmt.NewTextParser(model.UTF8Validation)\n\tparsed, err := parser.TextToMetricFamilies(reader)\n\trequire.NoError(t, err)\n\treturn parsed\n}\n"
  },
  {
    "path": "internal/e2e/opaque_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2e\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\ntype TestStruct struct {\n\tOpaque configopaque.String `json:\"opaque\" yaml:\"opaque\"`\n\tPlain  string              `json:\"plain\" yaml:\"plain\"`\n}\n\nvar example = TestStruct{\n\tOpaque: \"opaque\",\n\tPlain:  \"plain\",\n}\n\nfunc TestConfMapMarshalConfigOpaque(t *testing.T) {\n\tconf := confmap.New()\n\trequire.NoError(t, conf.Marshal(example))\n\tassert.Equal(t, \"[REDACTED]\", conf.Get(\"opaque\"))\n\tassert.Equal(t, \"plain\", conf.Get(\"plain\"))\n}\n"
  },
  {
    "path": "internal/e2e/otlphttp_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2e\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"context\"\n\t\"encoding/hex\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/google/go-cmp/cmp\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcollectortrace \"go.opentelemetry.io/proto/otlp/collector/trace/v1\"\n\tgootlpcommon \"go.opentelemetry.io/proto/otlp/common/v1\"\n\tgootlpresource \"go.opentelemetry.io/proto/otlp/resource/v1\"\n\tgootlptrace \"go.opentelemetry.io/proto/otlp/trace/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\t\"google.golang.org/protobuf/testing/protocmp\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/exporter/otlphttpexporter\"\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\nfunc TestInvalidConfig(t *testing.T) {\n\tconfig := &otlphttpexporter.Config{\n\t\tClientConfig: confighttp.ClientConfig{\n\t\t\tEndpoint: \"\",\n\t\t},\n\t}\n\tf := otlphttpexporter.NewFactory()\n\tset := exportertest.NewNopSettings(f.Type())\n\t_, err := f.CreateTraces(context.Background(), set, config)\n\trequire.Error(t, err)\n\t_, err = f.CreateMetrics(context.Background(), set, config)\n\trequire.Error(t, err)\n\t_, err = f.CreateLogs(context.Background(), set, config)\n\trequire.Error(t, err)\n}\n\nfunc TestTraceNoBackend(t *testing.T) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\texp := startTraces(t, \"\", fmt.Sprintf(\"http://%s/v1/traces\", addr))\n\ttd := testdata.GenerateTraces(1)\n\tassert.Error(t, exp.ConsumeTraces(context.Background(), td))\n}\n\nfunc TestTraceInvalidURL(t *testing.T) {\n\texp := startTraces(t, \"http:/\\\\//this_is_an/*/invalid_url\", \"\")\n\ttd := testdata.GenerateTraces(1)\n\trequire.Error(t, exp.ConsumeTraces(context.Background(), td))\n\n\texp = startTraces(t, \"\", \"http:/\\\\//this_is_an/*/invalid_url\")\n\ttd = testdata.GenerateTraces(1)\n\tassert.Error(t, exp.ConsumeTraces(context.Background(), td))\n}\n\nfunc TestTraceError(t *testing.T) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\n\tstartTracesReceiver(t, addr, consumertest.NewErr(errors.New(\"my_error\")))\n\texp := startTraces(t, \"\", fmt.Sprintf(\"http://%s/v1/traces\", addr))\n\n\ttd := testdata.GenerateTraces(1)\n\tassert.Error(t, exp.ConsumeTraces(context.Background(), td))\n}\n\nfunc TestTraceRoundTrip(t *testing.T) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\n\ttests := []struct {\n\t\tname        string\n\t\tbaseURL     string\n\t\toverrideURL string\n\t}{\n\t\t{\n\t\t\tname:        \"wrongbase\",\n\t\t\tbaseURL:     \"http://wronghostname\",\n\t\t\toverrideURL: fmt.Sprintf(\"http://%s/v1/traces\", addr),\n\t\t},\n\t\t{\n\t\t\tname:        \"onlybase\",\n\t\t\tbaseURL:     \"http://\" + addr,\n\t\t\toverrideURL: \"\",\n\t\t},\n\t\t{\n\t\t\tname:        \"override\",\n\t\t\tbaseURL:     \"\",\n\t\t\toverrideURL: fmt.Sprintf(\"http://%s/v1/traces\", addr),\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsink := new(consumertest.TracesSink)\n\t\t\tstartTracesReceiver(t, addr, sink)\n\t\t\texp := startTraces(t, tt.baseURL, tt.overrideURL)\n\n\t\t\ttd := testdata.GenerateTraces(1)\n\t\t\trequire.NoError(t, exp.ConsumeTraces(context.Background(), td))\n\t\t\trequire.Eventually(t, func() bool {\n\t\t\t\treturn sink.SpanCount() > 0\n\t\t\t}, 1*time.Second, 10*time.Millisecond)\n\t\t\tallTraces := sink.AllTraces()\n\t\t\trequire.Len(t, allTraces, 1)\n\t\t\tassert.Equal(t, td, allTraces[0])\n\t\t})\n\t}\n}\n\nfunc TestMetricsError(t *testing.T) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\n\tstartMetricsReceiver(t, addr, consumertest.NewErr(errors.New(\"my_error\")))\n\texp := startMetrics(t, \"\", fmt.Sprintf(\"http://%s/v1/metrics\", addr))\n\n\tmd := testdata.GenerateMetrics(1)\n\tassert.Error(t, exp.ConsumeMetrics(context.Background(), md))\n}\n\nfunc TestMetricsRoundTrip(t *testing.T) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\n\ttests := []struct {\n\t\tname        string\n\t\tbaseURL     string\n\t\toverrideURL string\n\t}{\n\t\t{\n\t\t\tname:        \"wrongbase\",\n\t\t\tbaseURL:     \"http://wronghostname\",\n\t\t\toverrideURL: fmt.Sprintf(\"http://%s/v1/metrics\", addr),\n\t\t},\n\t\t{\n\t\t\tname:        \"onlybase\",\n\t\t\tbaseURL:     \"http://\" + addr,\n\t\t\toverrideURL: \"\",\n\t\t},\n\t\t{\n\t\t\tname:        \"override\",\n\t\t\tbaseURL:     \"\",\n\t\t\toverrideURL: fmt.Sprintf(\"http://%s/v1/metrics\", addr),\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsink := new(consumertest.MetricsSink)\n\t\t\tstartMetricsReceiver(t, addr, sink)\n\t\t\texp := startMetrics(t, tt.baseURL, tt.overrideURL)\n\n\t\t\tmd := testdata.GenerateMetrics(1)\n\t\t\trequire.NoError(t, exp.ConsumeMetrics(context.Background(), md))\n\t\t\trequire.Eventually(t, func() bool {\n\t\t\t\treturn sink.DataPointCount() > 0\n\t\t\t}, 1*time.Second, 10*time.Millisecond)\n\t\t\tallMetrics := sink.AllMetrics()\n\t\t\trequire.Len(t, allMetrics, 1)\n\t\t\tassert.Equal(t, md, allMetrics[0])\n\t\t})\n\t}\n}\n\nfunc TestLogsError(t *testing.T) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\n\tstartLogsReceiver(t, addr, consumertest.NewErr(errors.New(\"my_error\")))\n\texp := startLogs(t, \"\", fmt.Sprintf(\"http://%s/v1/logs\", addr))\n\n\tmd := testdata.GenerateLogs(1)\n\tassert.Error(t, exp.ConsumeLogs(context.Background(), md))\n}\n\nfunc TestLogsRoundTrip(t *testing.T) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\n\ttests := []struct {\n\t\tname        string\n\t\tbaseURL     string\n\t\toverrideURL string\n\t}{\n\t\t{\n\t\t\tname:        \"wrongbase\",\n\t\t\tbaseURL:     \"http://wronghostname\",\n\t\t\toverrideURL: fmt.Sprintf(\"http://%s/v1/logs\", addr),\n\t\t},\n\t\t{\n\t\t\tname:        \"onlybase\",\n\t\t\tbaseURL:     \"http://\" + addr,\n\t\t\toverrideURL: \"\",\n\t\t},\n\t\t{\n\t\t\tname:        \"override\",\n\t\t\tbaseURL:     \"\",\n\t\t\toverrideURL: fmt.Sprintf(\"http://%s/v1/logs\", addr),\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsink := new(consumertest.LogsSink)\n\t\t\tstartLogsReceiver(t, addr, sink)\n\t\t\texp := startLogs(t, tt.baseURL, tt.overrideURL)\n\n\t\t\tmd := testdata.GenerateLogs(1)\n\t\t\trequire.NoError(t, exp.ConsumeLogs(context.Background(), md))\n\t\t\trequire.Eventually(t, func() bool {\n\t\t\t\treturn sink.LogRecordCount() > 0\n\t\t\t}, 1*time.Second, 10*time.Millisecond)\n\t\t\tallLogs := sink.AllLogs()\n\t\t\trequire.Len(t, allLogs, 1)\n\t\t\tassert.Equal(t, md, allLogs[0])\n\t\t})\n\t}\n}\n\nfunc TestIssue_4221(t *testing.T) {\n\ttraceIDBytesSlice, err := hex.DecodeString(\"4303853f086f4f8c86cf198b6551df84\")\n\trequire.NoError(t, err)\n\tspanIDBytesSlice, err := hex.DecodeString(\"e5513c32795c41b9\")\n\trequire.NoError(t, err)\n\n\tsvr := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {\n\t\tdefer func() { assert.NoError(t, r.Body.Close()) }()\n\t\tcompressedData, err := io.ReadAll(r.Body)\n\t\tassert.NoError(t, err)\n\t\tgzipReader, err := gzip.NewReader(bytes.NewReader(compressedData))\n\t\tassert.NoError(t, err)\n\t\tdata, err := io.ReadAll(gzipReader)\n\t\tassert.NoError(t, err)\n\t\t// Verify same base64 encoded string is received.\n\t\treq := &gootlpcollectortrace.ExportTraceServiceRequest{}\n\t\tassert.NoError(t, proto.Unmarshal(data, req))\n\n\t\tassert.Empty(t, cmp.Diff(&gootlpcollectortrace.ExportTraceServiceRequest{\n\t\t\tResourceSpans: []*gootlptrace.ResourceSpans{\n\t\t\t\t{\n\t\t\t\t\tResource: &gootlpresource.Resource{\n\t\t\t\t\t\tAttributes: []*gootlpcommon.KeyValue{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tKey: \"service.name\",\n\t\t\t\t\t\t\t\tValue: &gootlpcommon.AnyValue{\n\t\t\t\t\t\t\t\t\tValue: &gootlpcommon.AnyValue_StringValue{\n\t\t\t\t\t\t\t\t\t\tStringValue: \"uop.stage-eu-1\",\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tKey: \"outsystems.module.version\",\n\t\t\t\t\t\t\t\tValue: &gootlpcommon.AnyValue{\n\t\t\t\t\t\t\t\t\tValue: &gootlpcommon.AnyValue_StringValue{\n\t\t\t\t\t\t\t\t\t\tStringValue: \"903386\",\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\tScopeSpans: []*gootlptrace.ScopeSpans{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tScope: &gootlpcommon.InstrumentationScope{\n\t\t\t\t\t\t\t\tName:    \"uop_canaries\",\n\t\t\t\t\t\t\t\tVersion: \"1\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tSpans: []*gootlptrace.Span{\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\tTraceId:           traceIDBytesSlice,\n\t\t\t\t\t\t\t\t\tSpanId:            spanIDBytesSlice,\n\t\t\t\t\t\t\t\t\tStartTimeUnixNano: 1634684637873000000,\n\t\t\t\t\t\t\t\t\tEndTimeUnixNano:   1634684637873000000,\n\t\t\t\t\t\t\t\t\tAttributes: []*gootlpcommon.KeyValue{\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tKey: \"span_index\",\n\t\t\t\t\t\t\t\t\t\t\tValue: &gootlpcommon.AnyValue{\n\t\t\t\t\t\t\t\t\t\t\t\tValue: &gootlpcommon.AnyValue_IntValue{\n\t\t\t\t\t\t\t\t\t\t\t\t\tIntValue: 3,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\tKey: \"code.function\",\n\t\t\t\t\t\t\t\t\t\t\tValue: &gootlpcommon.AnyValue{\n\t\t\t\t\t\t\t\t\t\t\t\tValue: &gootlpcommon.AnyValue_StringValue{\n\t\t\t\t\t\t\t\t\t\t\t\t\tStringValue: \"myFunction36\",\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\tStatus: &gootlptrace.Status{},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}, req, protocmp.Transform()))\n\n\t\tassert.NoError(t, err)\n\t\ttr := ptraceotlp.NewExportRequest()\n\t\tassert.NoError(t, tr.UnmarshalProto(data))\n\t\tspan := tr.Traces().ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0)\n\t\ttraceID := span.TraceID()\n\t\tassert.Equal(t, \"4303853f086f4f8c86cf198b6551df84\", hex.EncodeToString(traceID[:]))\n\t\tspanID := span.SpanID()\n\t\tassert.Equal(t, \"e5513c32795c41b9\", hex.EncodeToString(spanID[:]))\n\t}))\n\tdefer func() { svr.Close() }()\n\n\texp := startTraces(t, \"\", svr.URL)\n\n\tmd := ptrace.NewTraces()\n\trms := md.ResourceSpans().AppendEmpty()\n\trms.Resource().Attributes().PutStr(\"service.name\", \"uop.stage-eu-1\")\n\trms.Resource().Attributes().PutStr(\"outsystems.module.version\", \"903386\")\n\tils := rms.ScopeSpans().AppendEmpty()\n\tils.Scope().SetName(\"uop_canaries\")\n\tils.Scope().SetVersion(\"1\")\n\tspan := ils.Spans().AppendEmpty()\n\n\tvar traceIDBytes [16]byte\n\tcopy(traceIDBytes[:], traceIDBytesSlice)\n\tspan.SetTraceID(traceIDBytes)\n\ttraceID := span.TraceID()\n\tassert.Equal(t, \"4303853f086f4f8c86cf198b6551df84\", hex.EncodeToString(traceID[:]))\n\n\tvar spanIDBytes [8]byte\n\tcopy(spanIDBytes[:], spanIDBytesSlice)\n\tspan.SetSpanID(spanIDBytes)\n\tspanID := span.SpanID()\n\tassert.Equal(t, \"e5513c32795c41b9\", hex.EncodeToString(spanID[:]))\n\n\tspan.SetEndTimestamp(1634684637873000000)\n\tspan.Attributes().PutInt(\"span_index\", 3)\n\tspan.Attributes().PutStr(\"code.function\", \"myFunction36\")\n\tspan.SetStartTimestamp(1634684637873000000)\n\n\tassert.NoError(t, exp.ConsumeTraces(context.Background(), md))\n}\n\nfunc startTraces(t *testing.T, baseURL, overrideURL string) exporter.Traces {\n\tfactory := otlphttpexporter.NewFactory()\n\tcfg := createConfig(baseURL, factory.CreateDefaultConfig())\n\tcfg.TracesEndpoint = overrideURL\n\texp, err := factory.CreateTraces(context.Background(), exportertest.NewNopSettings(factory.Type()), cfg)\n\trequire.NoError(t, err)\n\tstartAndCleanup(t, exp)\n\treturn exp\n}\n\nfunc startMetrics(t *testing.T, baseURL, overrideURL string) exporter.Metrics {\n\tfactory := otlphttpexporter.NewFactory()\n\tcfg := createConfig(baseURL, factory.CreateDefaultConfig())\n\tcfg.MetricsEndpoint = overrideURL\n\texp, err := factory.CreateMetrics(context.Background(), exportertest.NewNopSettings(factory.Type()), cfg)\n\trequire.NoError(t, err)\n\tstartAndCleanup(t, exp)\n\treturn exp\n}\n\nfunc startLogs(t *testing.T, baseURL, overrideURL string) exporter.Logs {\n\tfactory := otlphttpexporter.NewFactory()\n\tcfg := createConfig(baseURL, factory.CreateDefaultConfig())\n\tcfg.LogsEndpoint = overrideURL\n\texp, err := factory.CreateLogs(context.Background(), exportertest.NewNopSettings(factory.Type()), cfg)\n\trequire.NoError(t, err)\n\tstartAndCleanup(t, exp)\n\treturn exp\n}\n\nfunc createConfig(baseURL string, defaultCfg component.Config) *otlphttpexporter.Config {\n\tcfg := defaultCfg.(*otlphttpexporter.Config)\n\tcfg.ClientConfig.Endpoint = baseURL\n\tcfg.QueueConfig = configoptional.None[exporterhelper.QueueBatchConfig]()\n\tcfg.RetryConfig.Enabled = false\n\treturn cfg\n}\n\nfunc startTracesReceiver(t *testing.T, addr string, next consumer.Traces) {\n\tfactory := otlpreceiver.NewFactory()\n\tcfg := createReceiverConfig(addr, factory.CreateDefaultConfig())\n\trecv, err := factory.CreateTraces(context.Background(), receivertest.NewNopSettings(factory.Type()), cfg, next)\n\trequire.NoError(t, err)\n\tstartAndCleanup(t, recv)\n}\n\nfunc startMetricsReceiver(t *testing.T, addr string, next consumer.Metrics) {\n\tfactory := otlpreceiver.NewFactory()\n\tcfg := createReceiverConfig(addr, factory.CreateDefaultConfig())\n\trecv, err := factory.CreateMetrics(context.Background(), receivertest.NewNopSettings(factory.Type()), cfg, next)\n\trequire.NoError(t, err)\n\tstartAndCleanup(t, recv)\n}\n\nfunc startLogsReceiver(t *testing.T, addr string, next consumer.Logs) {\n\tfactory := otlpreceiver.NewFactory()\n\tcfg := createReceiverConfig(addr, factory.CreateDefaultConfig())\n\trecv, err := factory.CreateLogs(context.Background(), receivertest.NewNopSettings(factory.Type()), cfg, next)\n\trequire.NoError(t, err)\n\tstartAndCleanup(t, recv)\n}\n\nfunc createReceiverConfig(addr string, defaultCfg component.Config) *otlpreceiver.Config {\n\tcfg := defaultCfg.(*otlpreceiver.Config)\n\tcfg.HTTP.GetOrInsertDefault().ServerConfig.NetAddr.Endpoint = addr\n\treturn cfg\n}\n\nfunc startAndCleanup(t *testing.T, cmp component.Component) {\n\trequire.NoError(t, cmp.Start(context.Background(), componenttest.NewNopHost()))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, cmp.Shutdown(context.Background()))\n\t})\n}\n"
  },
  {
    "path": "internal/e2e/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2e\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "internal/e2e/status_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage e2e\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap/zapcore\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componentstatus\"\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/connectortest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/internal/sharedcomponent\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/service\"\n\t\"go.opentelemetry.io/collector/service/extensions\"\n\t\"go.opentelemetry.io/collector/service/pipelines\"\n\t\"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\"\n)\n\nvar nopType = component.MustNewType(\"nop\")\n\nvar wg = sync.WaitGroup{}\n\nfunc Test_ComponentStatusReporting_SharedInstance(t *testing.T) {\n\teventsReceived := make(map[*componentstatus.InstanceID][]*componentstatus.Event)\n\texporterFactory := exportertest.NewNopFactory()\n\tconnectorFactory := connectortest.NewNopFactory()\n\t// Use a different ID than receivertest and exportertest to avoid ambiguous\n\t// configuration scenarios. Ambiguous IDs are detected in the 'otelcol' package,\n\t// but lower level packages such as 'service' assume that IDs are disambiguated.\n\tconnID := component.NewIDWithName(nopType, \"conn\")\n\n\tset := service.Settings{\n\t\tBuildInfo:     component.NewDefaultBuildInfo(),\n\t\tCollectorConf: confmap.New(),\n\t\tReceiversConfigs: map[component.ID]component.Config{\n\t\t\tcomponent.NewID(component.MustNewType(\"test\")): &receiverConfig{},\n\t\t},\n\t\tReceiversFactories: map[component.Type]receiver.Factory{\n\t\t\tcomponent.MustNewType(\"test\"): newReceiverFactory(),\n\t\t},\n\t\tExportersConfigs: map[component.ID]component.Config{\n\t\t\tcomponent.NewID(nopType): exporterFactory.CreateDefaultConfig(),\n\t\t},\n\t\tExportersFactories: map[component.Type]exporter.Factory{\n\t\t\tnopType: exporterFactory,\n\t\t},\n\t\tConnectorsConfigs: map[component.ID]component.Config{\n\t\t\tconnID: connectorFactory.CreateDefaultConfig(),\n\t\t},\n\t\tConnectorsFactories: map[component.Type]connector.Factory{\n\t\t\tnopType: connectorFactory,\n\t\t},\n\t\tExtensionsConfigs: map[component.ID]component.Config{\n\t\t\tcomponent.NewID(component.MustNewType(\"watcher\")): &extensionConfig{eventsReceived},\n\t\t},\n\t\tExtensionsFactories: map[component.Type]extension.Factory{\n\t\t\tcomponent.MustNewType(\"watcher\"): newExtensionFactory(),\n\t\t},\n\t\tTelemetryFactory: otelconftelemetry.NewFactory(),\n\t}\n\tset.BuildInfo = component.BuildInfo{Version: \"test version\", Command: \"otelcoltest\"}\n\n\tcfg := service.Config{\n\t\tTelemetry: &otelconftelemetry.Config{\n\t\t\tLogs: otelconftelemetry.LogsConfig{\n\t\t\t\tLevel:       zapcore.InfoLevel,\n\t\t\t\tDevelopment: false,\n\t\t\t\tEncoding:    \"console\",\n\t\t\t\tSampling: &otelconftelemetry.LogsSamplingConfig{\n\t\t\t\t\tEnabled:    true,\n\t\t\t\t\tTick:       10 * time.Second,\n\t\t\t\t\tInitial:    100,\n\t\t\t\t\tThereafter: 100,\n\t\t\t\t},\n\t\t\t\tOutputPaths:       []string{\"stderr\"},\n\t\t\t\tErrorOutputPaths:  []string{\"stderr\"},\n\t\t\t\tDisableCaller:     false,\n\t\t\t\tDisableStacktrace: false,\n\t\t\t\tInitialFields:     map[string]any(nil),\n\t\t\t},\n\t\t\tMetrics: otelconftelemetry.MetricsConfig{\n\t\t\t\tLevel: configtelemetry.LevelNone,\n\t\t\t},\n\t\t},\n\t\tPipelines: pipelines.Config{\n\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\tReceivers: []component.ID{component.NewID(component.MustNewType(\"test\"))},\n\t\t\t\tExporters: []component.ID{component.NewID(nopType)},\n\t\t\t},\n\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\tReceivers: []component.ID{component.NewID(component.MustNewType(\"test\"))},\n\t\t\t\tExporters: []component.ID{component.NewID(nopType)},\n\t\t\t},\n\t\t},\n\t\tExtensions: extensions.Config{component.NewID(component.MustNewType(\"watcher\"))},\n\t}\n\n\ts, err := service.New(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\n\twg.Add(1)\n\terr = s.Start(context.Background())\n\trequire.NoError(t, err)\n\twg.Wait()\n\terr = s.Shutdown(context.Background())\n\trequire.NoError(t, err)\n\n\trequire.Len(t, eventsReceived, 2)\n\n\tfor instanceID, events := range eventsReceived {\n\t\tpipelineIDs := \"\"\n\t\tinstanceID.AllPipelineIDs(func(id pipeline.ID) bool {\n\t\t\tpipelineIDs += id.String() + \",\"\n\t\t\treturn true\n\t\t})\n\n\t\tt.Logf(\"checking errors for %v - %v - %v\", pipelineIDs, instanceID.Kind().String(), instanceID.ComponentID().String())\n\n\t\tvar expectedEvents []*componentstatus.Event\n\t\t// The StatusOk is not guaranteed to be in the slice, set it according to the number of captured states\n\t\tassert.True(t, len(events) == 4 || len(events) == 5)\n\t\treceiverTestAttrs := pcommon.NewMap()\n\t\treceiverTestAttrs.PutStr(\"scraper\", \"test\")\n\t\tif len(events) == 4 {\n\t\t\texpectedEvents = []*componentstatus.Event{\n\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStarting),\n\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusRecoverableError, componentstatus.WithAttributes(receiverTestAttrs)),\n\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopping),\n\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopped),\n\t\t\t}\n\t\t} else {\n\t\t\texpectedEvents = []*componentstatus.Event{\n\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStarting),\n\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusRecoverableError, componentstatus.WithAttributes(receiverTestAttrs)),\n\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusOK),\n\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopping),\n\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopped),\n\t\t\t}\n\t\t}\n\n\t\tvar eventStr strings.Builder\n\t\tfor i, e := range events {\n\t\t\tfmt.Fprintf(&eventStr, \"%v,\", e.Status())\n\t\t\tassert.Equal(t, expectedEvents[i].Status(), e.Status())\n\t\t}\n\t\tt.Logf(\"events received: %v\", eventStr.String())\n\t}\n}\n\nfunc newReceiverFactory() receiver.Factory {\n\treturn receiver.NewFactory(\n\t\tcomponent.MustNewType(\"test\"),\n\t\tcreateDefaultReceiverConfig,\n\t\treceiver.WithTraces(createTraces, component.StabilityLevelStable),\n\t\treceiver.WithMetrics(createMetrics, component.StabilityLevelStable),\n\t)\n}\n\ntype testReceiver struct{}\n\nfunc (t *testReceiver) Start(_ context.Context, host component.Host) error {\n\tscraperAttrs := pcommon.NewMap()\n\tscraperAttrs.PutStr(\"scraper\", \"test\")\n\tcomponentstatus.ReportStatus(host, componentstatus.NewEvent(\n\t\tcomponentstatus.StatusRecoverableError,\n\t\tcomponentstatus.WithError(errors.New(\"test recoverable error\")),\n\t\tcomponentstatus.WithAttributes(scraperAttrs),\n\t))\n\n\tgo func() {\n\t\tcomponentstatus.ReportStatus(host, componentstatus.NewEvent(componentstatus.StatusOK))\n\t\twg.Done()\n\t}()\n\treturn nil\n}\n\nfunc (t *testReceiver) Shutdown(_ context.Context) error {\n\treturn nil\n}\n\ntype receiverConfig struct{}\n\nfunc createDefaultReceiverConfig() component.Config {\n\treturn &receiverConfig{}\n}\n\nfunc createTraces(\n\t_ context.Context,\n\t_ receiver.Settings,\n\tcfg component.Config,\n\t_ consumer.Traces,\n) (receiver.Traces, error) {\n\toCfg := cfg.(*receiverConfig)\n\tr, err := receivers.LoadOrStore(\n\t\toCfg,\n\t\tfunc() (*testReceiver, error) {\n\t\t\treturn &testReceiver{}, nil\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r, nil\n}\n\nfunc createMetrics(\n\t_ context.Context,\n\t_ receiver.Settings,\n\tcfg component.Config,\n\t_ consumer.Metrics,\n) (receiver.Metrics, error) {\n\toCfg := cfg.(*receiverConfig)\n\tr, err := receivers.LoadOrStore(\n\t\toCfg,\n\t\tfunc() (*testReceiver, error) {\n\t\t\treturn &testReceiver{}, nil\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r, nil\n}\n\nvar receivers = sharedcomponent.NewMap[*receiverConfig, *testReceiver]()\n\nfunc newExtensionFactory() extension.Factory {\n\treturn extension.NewFactory(\n\t\tcomponent.MustNewType(\"watcher\"),\n\t\tcreateDefaultExtensionConfig,\n\t\tcreate,\n\t\tcomponent.StabilityLevelStable,\n\t)\n}\n\nfunc create(_ context.Context, _ extension.Settings, cfg component.Config) (extension.Extension, error) {\n\toCfg := cfg.(*extensionConfig)\n\treturn &testExtension{\n\t\teventsReceived: oCfg.eventsReceived,\n\t}, nil\n}\n\ntype testExtension struct {\n\teventsReceived map[*componentstatus.InstanceID][]*componentstatus.Event\n}\n\ntype extensionConfig struct {\n\teventsReceived map[*componentstatus.InstanceID][]*componentstatus.Event\n}\n\nfunc createDefaultExtensionConfig() component.Config {\n\treturn &extensionConfig{}\n}\n\n// Start implements the component.Component interface.\nfunc (t *testExtension) Start(_ context.Context, _ component.Host) error {\n\treturn nil\n}\n\n// Shutdown implements the component.Component interface.\nfunc (t *testExtension) Shutdown(_ context.Context) error {\n\treturn nil\n}\n\n// ComponentStatusChanged implements the extension.StatusWatcher interface.\nfunc (t *testExtension) ComponentStatusChanged(\n\tsource *componentstatus.InstanceID,\n\tevent *componentstatus.Event,\n) {\n\tif source.ComponentID() == component.NewID(component.MustNewType(\"test\")) {\n\t\tt.eventsReceived[source] = append(t.eventsReceived[source], event)\n\t}\n}\n\n// NotifyConfig implements the extensioncapabilities.ConfigWatcher interface.\nfunc (t *testExtension) NotifyConfig(_ context.Context, _ *confmap.Conf) error {\n\treturn nil\n}\n\n// Ready implements the extensioncapabilities.PipelineWatcher interface.\nfunc (t *testExtension) Ready() error {\n\treturn nil\n}\n\n// NotReady implements the extensioncapabilities.PipelineWatcher interface.\nfunc (t *testExtension) NotReady() error {\n\treturn nil\n}\n"
  },
  {
    "path": "internal/e2e/testdata/exporter_failure_attributes_test.yaml",
    "content": "receivers:\n  otlp:\n    protocols:\n      http:\n        endpoint: localhost:${env:OTEL_PORT}\n\nexporters:\n  otlp_http/test:\n    endpoint: ${env:EXPORTER_ENDPOINT}\n    timeout: 100ms\n    retry_on_failure:\n      enabled: true\n      initial_interval: 10ms\n      max_interval: 50ms\n      max_elapsed_time: 200ms\n    sending_queue:\n      enabled: false\n\nservice:\n  telemetry:\n    logs:\n      level: info\n    metrics:\n      level: detailed\n      readers:\n        - pull:\n            exporter:\n              prometheus:\n                host: localhost\n                port: ${env:METRICS_PORT}\n\n  pipelines:\n    metrics:\n      receivers: [otlp]\n      exporters: [otlp_http/test]\n"
  },
  {
    "path": "internal/e2e/testdata/metric_stability_test_no_readers.yaml",
    "content": "receivers:\n  otlp:\n    protocols:\n      http:\n        endpoint: localhost:${env:OTEL_PORT}\n\nprocessors:\n  batch:\n    timeout: 100ms\n    send_batch_size: 100\n\nexporters:\n  debug:\n    verbosity: detailed\n  otlp_http/fail:\n    endpoint: http://127.0.0.1:65535\n    timeout: 100ms\n    retry_on_failure:\n      enabled: false\n    sending_queue:\n      enabled: false\n\nservice:\n  telemetry:\n    logs:\n      level: info\n    metrics:\n      level: detailed\n\n  pipelines:\n    traces:\n      receivers: [otlp]\n      processors: [batch]\n      exporters: [debug]\n    traces/fail:\n      receivers: [otlp]\n      exporters: [otlp_http/fail]\n    metrics:\n      receivers: [otlp]\n      processors: [batch]\n      exporters: [debug]\n    metrics/fail:\n      receivers: [otlp]\n      exporters: [otlp_http/fail]\n    logs:\n      receivers: [otlp]\n      processors: [batch]\n      exporters: [debug]\n    logs/fail:\n      receivers: [otlp]\n      exporters: [otlp_http/fail]\n"
  },
  {
    "path": "internal/e2e/testdata/metric_stability_test_readers.yaml",
    "content": "receivers:\n  otlp:\n    protocols:\n      http:\n        endpoint: localhost:${env:OTEL_PORT}\n\nprocessors:\n  batch:\n    timeout: 100ms\n    send_batch_size: 100\n\nexporters:\n  debug:\n    verbosity: detailed\n  otlp_http/fail:\n    endpoint: http://127.0.0.1:65535\n    timeout: 100ms\n    retry_on_failure:\n      enabled: false\n    sending_queue:\n      enabled: false\n\nservice:\n  telemetry:\n    logs:\n      level: info\n    metrics:\n      level: detailed\n      readers:\n        - pull:\n            exporter:\n              prometheus:\n                host: localhost\n                port: ${env:METRICS_PORT}\n\n  pipelines:\n    traces:\n      receivers: [otlp]\n      processors: [batch]\n      exporters: [debug]\n    traces/fail:\n      receivers: [otlp]\n      exporters: [otlp_http/fail]\n    metrics:\n      receivers: [otlp]\n      processors: [batch]\n      exporters: [debug]\n    metrics/fail:\n      receivers: [otlp]\n      exporters: [otlp_http/fail]\n    logs:\n      receivers: [otlp]\n      processors: [batch]\n      exporters: [debug]\n    logs/fail:\n      receivers: [otlp]\n      exporters: [otlp_http/fail]\n"
  },
  {
    "path": "internal/fanoutconsumer/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "internal/fanoutconsumer/go.mod",
    "content": "module go.opentelemetry.io/collector/internal/fanoutconsumer\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/multierr v1.11.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../testutil\n"
  },
  {
    "path": "internal/fanoutconsumer/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/otel v1.40.0 h1:oA5YeOcpRTXq6NN7frwmwFR0Cn3RhTVZvXsP4duvCms=\ngo.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlV14J0g=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "internal/fanoutconsumer/logs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package fanoutconsumer contains implementations of Traces/Metrics/Logs consumers\n// that fan out the data to multiple other consumers.\npackage fanoutconsumer // import \"go.opentelemetry.io/collector/internal/fanoutconsumer\"\n\nimport (\n\t\"context\"\n\n\t\"go.uber.org/multierr\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\n// NewLogs wraps multiple log consumers in a single one.\n// It fans out the incoming data to all the consumers, and does smart routing:\n//   - Clones only to the consumer that needs to mutate the data.\n//   - If all consumers needs to mutate the data one will get the original mutable data.\nfunc NewLogs(lcs []consumer.Logs) consumer.Logs {\n\t// Don't wrap if there is only one non-mutating consumer.\n\tif len(lcs) == 1 && !lcs[0].Capabilities().MutatesData {\n\t\treturn lcs[0]\n\t}\n\n\tlc := &logsConsumer{}\n\tfor i := range lcs {\n\t\tif lcs[i].Capabilities().MutatesData {\n\t\t\tlc.mutable = append(lc.mutable, lcs[i])\n\t\t} else {\n\t\t\tlc.readonly = append(lc.readonly, lcs[i])\n\t\t}\n\t}\n\treturn lc\n}\n\ntype logsConsumer struct {\n\tmutable  []consumer.Logs\n\treadonly []consumer.Logs\n}\n\nfunc (lsc *logsConsumer) Capabilities() consumer.Capabilities {\n\t// If all consumers are mutating, then the original data will be passed to one of them.\n\treturn consumer.Capabilities{MutatesData: len(lsc.mutable) > 0 && len(lsc.readonly) == 0}\n}\n\n// ConsumeLogs exports the plog.Logs to all consumers wrapped by the current one.\nfunc (lsc *logsConsumer) ConsumeLogs(ctx context.Context, ld plog.Logs) error {\n\tvar errs error\n\n\tif len(lsc.mutable) > 0 {\n\t\t// Clone the data before sending to all mutating consumers except the last one.\n\t\tfor i := 0; i < len(lsc.mutable)-1; i++ {\n\t\t\terrs = multierr.Append(errs, lsc.mutable[i].ConsumeLogs(ctx, cloneLogs(ld)))\n\t\t}\n\t\t// Send data as is to the last mutating consumer only if there are no other non-mutating consumers and the\n\t\t// data is mutable. Never share the same data between a mutating and a non-mutating consumer since the\n\t\t// non-mutating consumer may process data async and the mutating consumer may change the data before that.\n\t\tlastConsumer := lsc.mutable[len(lsc.mutable)-1]\n\t\tif len(lsc.readonly) == 0 && !ld.IsReadOnly() {\n\t\t\terrs = multierr.Append(errs, lastConsumer.ConsumeLogs(ctx, ld))\n\t\t} else {\n\t\t\terrs = multierr.Append(errs, lastConsumer.ConsumeLogs(ctx, cloneLogs(ld)))\n\t\t}\n\t}\n\n\t// Mark the data as read-only if it will be sent to more than one read-only consumer.\n\tif len(lsc.readonly) > 1 && !ld.IsReadOnly() {\n\t\tld.MarkReadOnly()\n\t}\n\tfor _, lc := range lsc.readonly {\n\t\terrs = multierr.Append(errs, lc.ConsumeLogs(ctx, ld))\n\t}\n\n\treturn errs\n}\n\nfunc cloneLogs(ld plog.Logs) plog.Logs {\n\tclonedLogs := plog.NewLogs()\n\tld.CopyTo(clonedLogs)\n\treturn clonedLogs\n}\n"
  },
  {
    "path": "internal/fanoutconsumer/logs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage fanoutconsumer\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestLogsNotMultiplexing(t *testing.T) {\n\tnop := consumertest.NewNop()\n\tlfc := NewLogs([]consumer.Logs{nop})\n\tassert.Same(t, nop, lfc)\n}\n\nfunc TestLogsNotMultiplexingMutating(t *testing.T) {\n\tp := &mutatingLogsSink{LogsSink: new(consumertest.LogsSink)}\n\tlfc := NewLogs([]consumer.Logs{p})\n\tassert.True(t, lfc.Capabilities().MutatesData)\n}\n\nfunc TestLogsMultiplexingNonMutating(t *testing.T) {\n\tp1 := new(consumertest.LogsSink)\n\tp2 := new(consumertest.LogsSink)\n\tp3 := new(consumertest.LogsSink)\n\n\tlfc := NewLogs([]consumer.Logs{p1, p2, p3})\n\tassert.False(t, lfc.Capabilities().MutatesData)\n\tld := testdata.GenerateLogs(1)\n\n\tfor range 2 {\n\t\terr := lfc.ConsumeLogs(context.Background(), ld)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tassert.Equal(t, ld, p1.AllLogs()[0])\n\tassert.Equal(t, ld, p1.AllLogs()[1])\n\tassert.Equal(t, ld, p1.AllLogs()[0])\n\tassert.Equal(t, ld, p1.AllLogs()[1])\n\n\tassert.Equal(t, ld, p2.AllLogs()[0])\n\tassert.Equal(t, ld, p2.AllLogs()[1])\n\tassert.Equal(t, ld, p2.AllLogs()[0])\n\tassert.Equal(t, ld, p2.AllLogs()[1])\n\n\tassert.Equal(t, ld, p3.AllLogs()[0])\n\tassert.Equal(t, ld, p3.AllLogs()[1])\n\tassert.Equal(t, ld, p3.AllLogs()[0])\n\tassert.Equal(t, ld, p3.AllLogs()[1])\n\n\t// The data should be marked as read only.\n\tassert.True(t, ld.IsReadOnly())\n}\n\nfunc TestLogsMultiplexingMutating(t *testing.T) {\n\tp1 := &mutatingLogsSink{LogsSink: new(consumertest.LogsSink)}\n\tp2 := &mutatingLogsSink{LogsSink: new(consumertest.LogsSink)}\n\tp3 := &mutatingLogsSink{LogsSink: new(consumertest.LogsSink)}\n\n\tlfc := NewLogs([]consumer.Logs{p1, p2, p3})\n\tassert.True(t, lfc.Capabilities().MutatesData)\n\tld := testdata.GenerateLogs(1)\n\n\tfor range 2 {\n\t\terr := lfc.ConsumeLogs(context.Background(), ld)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tassert.NotSame(t, &ld, &p1.AllLogs()[0])\n\tassert.NotSame(t, &ld, &p1.AllLogs()[1])\n\tassert.Equal(t, ld, p1.AllLogs()[0])\n\tassert.Equal(t, ld, p1.AllLogs()[1])\n\n\tassert.NotSame(t, &ld, &p2.AllLogs()[0])\n\tassert.NotSame(t, &ld, &p2.AllLogs()[1])\n\tassert.Equal(t, ld, p2.AllLogs()[0])\n\tassert.Equal(t, ld, p2.AllLogs()[1])\n\n\t// For this consumer, will receive the initial data.\n\tassert.Equal(t, ld, p3.AllLogs()[0])\n\tassert.Equal(t, ld, p3.AllLogs()[1])\n\tassert.Equal(t, ld, p3.AllLogs()[0])\n\tassert.Equal(t, ld, p3.AllLogs()[1])\n\n\t// The data should not be marked as read only.\n\tassert.False(t, ld.IsReadOnly())\n}\n\nfunc TestReadOnlyLogsMultiplexingMutating(t *testing.T) {\n\tp1 := &mutatingLogsSink{LogsSink: new(consumertest.LogsSink)}\n\tp2 := &mutatingLogsSink{LogsSink: new(consumertest.LogsSink)}\n\tp3 := &mutatingLogsSink{LogsSink: new(consumertest.LogsSink)}\n\n\tlfc := NewLogs([]consumer.Logs{p1, p2, p3})\n\tassert.True(t, lfc.Capabilities().MutatesData)\n\tldOrig := testdata.GenerateLogs(1)\n\tld := testdata.GenerateLogs(1)\n\tld.MarkReadOnly()\n\n\tfor range 2 {\n\t\terr := lfc.ConsumeLogs(context.Background(), ld)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\t// All consumers should receive the cloned data.\n\n\tassert.NotEqual(t, ld, p1.AllLogs()[0])\n\tassert.NotEqual(t, ld, p1.AllLogs()[1])\n\tassert.Equal(t, ldOrig, p1.AllLogs()[0])\n\tassert.Equal(t, ldOrig, p1.AllLogs()[1])\n\n\tassert.NotEqual(t, ld, p2.AllLogs()[0])\n\tassert.NotEqual(t, ld, p2.AllLogs()[1])\n\tassert.Equal(t, ldOrig, p2.AllLogs()[0])\n\tassert.Equal(t, ldOrig, p2.AllLogs()[1])\n\n\tassert.NotEqual(t, ld, p3.AllLogs()[0])\n\tassert.NotEqual(t, ld, p3.AllLogs()[1])\n\tassert.Equal(t, ldOrig, p3.AllLogs()[0])\n\tassert.Equal(t, ldOrig, p3.AllLogs()[1])\n}\n\nfunc TestLogsMultiplexingMixLastMutating(t *testing.T) {\n\tp1 := &mutatingLogsSink{LogsSink: new(consumertest.LogsSink)}\n\tp2 := new(consumertest.LogsSink)\n\tp3 := &mutatingLogsSink{LogsSink: new(consumertest.LogsSink)}\n\n\tlfc := NewLogs([]consumer.Logs{p1, p2, p3})\n\tassert.False(t, lfc.Capabilities().MutatesData)\n\tld := testdata.GenerateLogs(1)\n\n\tfor range 2 {\n\t\terr := lfc.ConsumeLogs(context.Background(), ld)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tassert.NotSame(t, &ld, &p1.AllLogs()[0])\n\tassert.NotSame(t, &ld, &p1.AllLogs()[1])\n\tassert.Equal(t, ld, p1.AllLogs()[0])\n\tassert.Equal(t, ld, p1.AllLogs()[1])\n\n\t// For this consumer, will receive the initial data.\n\tassert.Equal(t, ld, p2.AllLogs()[0])\n\tassert.Equal(t, ld, p2.AllLogs()[1])\n\tassert.Equal(t, ld, p2.AllLogs()[0])\n\tassert.Equal(t, ld, p2.AllLogs()[1])\n\n\t// For this consumer, will clone the initial data.\n\tassert.NotSame(t, &ld, &p3.AllLogs()[0])\n\tassert.NotSame(t, &ld, &p3.AllLogs()[1])\n\tassert.Equal(t, ld, p3.AllLogs()[0])\n\tassert.Equal(t, ld, p3.AllLogs()[1])\n\n\t// The data should not be marked as read only.\n\tassert.False(t, ld.IsReadOnly())\n}\n\nfunc TestLogsMultiplexingMixLastNonMutating(t *testing.T) {\n\tp1 := &mutatingLogsSink{LogsSink: new(consumertest.LogsSink)}\n\tp2 := &mutatingLogsSink{LogsSink: new(consumertest.LogsSink)}\n\tp3 := new(consumertest.LogsSink)\n\n\tlfc := NewLogs([]consumer.Logs{p1, p2, p3})\n\tassert.False(t, lfc.Capabilities().MutatesData)\n\tld := testdata.GenerateLogs(1)\n\n\tfor range 2 {\n\t\terr := lfc.ConsumeLogs(context.Background(), ld)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tassert.NotSame(t, &ld, &p1.AllLogs()[0])\n\tassert.NotSame(t, &ld, &p1.AllLogs()[1])\n\tassert.Equal(t, ld, p1.AllLogs()[0])\n\tassert.Equal(t, ld, p1.AllLogs()[1])\n\n\tassert.NotSame(t, &ld, &p2.AllLogs()[0])\n\tassert.NotSame(t, &ld, &p2.AllLogs()[1])\n\tassert.Equal(t, ld, p2.AllLogs()[0])\n\tassert.Equal(t, ld, p2.AllLogs()[1])\n\n\t// For this consumer, will receive the initial data.\n\tassert.Equal(t, ld, p3.AllLogs()[0])\n\tassert.Equal(t, ld, p3.AllLogs()[1])\n\tassert.Equal(t, ld, p3.AllLogs()[0])\n\tassert.Equal(t, ld, p3.AllLogs()[1])\n\n\t// The data should not be marked as read only.\n\tassert.False(t, ld.IsReadOnly())\n}\n\nfunc TestLogsWhenErrors(t *testing.T) {\n\tp1 := mutatingErr{Consumer: consumertest.NewErr(errors.New(\"my error\"))}\n\tp2 := consumertest.NewErr(errors.New(\"my error\"))\n\tp3 := new(consumertest.LogsSink)\n\n\tlfc := NewLogs([]consumer.Logs{p1, p2, p3})\n\tld := testdata.GenerateLogs(1)\n\n\tfor range 2 {\n\t\trequire.Error(t, lfc.ConsumeLogs(context.Background(), ld))\n\t}\n\n\tassert.Equal(t, ld, p3.AllLogs()[0])\n\tassert.Equal(t, ld, p3.AllLogs()[1])\n\tassert.Equal(t, ld, p3.AllLogs()[0])\n\tassert.Equal(t, ld, p3.AllLogs()[1])\n}\n\ntype mutatingLogsSink struct {\n\t*consumertest.LogsSink\n}\n\nfunc (mts *mutatingLogsSink) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: true}\n}\n\ntype mutatingErr struct {\n\tconsumertest.Consumer\n}\n\nfunc (mts mutatingErr) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: true}\n}\n"
  },
  {
    "path": "internal/fanoutconsumer/metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage fanoutconsumer // import \"go.opentelemetry.io/collector/internal/fanoutconsumer\"\n\nimport (\n\t\"context\"\n\n\t\"go.uber.org/multierr\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\n// NewMetrics wraps multiple metrics consumers in a single one.\n// It fans out the incoming data to all the consumers, and does smart routing:\n//   - Clones only to the consumer that needs to mutate the data.\n//   - If all consumers needs to mutate the data one will get the original mutable data.\nfunc NewMetrics(mcs []consumer.Metrics) consumer.Metrics {\n\t// Don't wrap if there is only one non-mutating consumer.\n\tif len(mcs) == 1 && !mcs[0].Capabilities().MutatesData {\n\t\treturn mcs[0]\n\t}\n\n\tmc := &metricsConsumer{}\n\tfor i := range mcs {\n\t\tif mcs[i].Capabilities().MutatesData {\n\t\t\tmc.mutable = append(mc.mutable, mcs[i])\n\t\t} else {\n\t\t\tmc.readonly = append(mc.readonly, mcs[i])\n\t\t}\n\t}\n\treturn mc\n}\n\ntype metricsConsumer struct {\n\tmutable  []consumer.Metrics\n\treadonly []consumer.Metrics\n}\n\nfunc (msc *metricsConsumer) Capabilities() consumer.Capabilities {\n\t// If all consumers are mutating, then the original data will be passed to one of them.\n\treturn consumer.Capabilities{MutatesData: len(msc.mutable) > 0 && len(msc.readonly) == 0}\n}\n\n// ConsumeMetrics exports the pmetric.Metrics to all consumers wrapped by the current one.\nfunc (msc *metricsConsumer) ConsumeMetrics(ctx context.Context, md pmetric.Metrics) error {\n\tvar errs error\n\n\tif len(msc.mutable) > 0 {\n\t\t// Clone the data before sending to all mutating consumers except the last one.\n\t\tfor i := 0; i < len(msc.mutable)-1; i++ {\n\t\t\terrs = multierr.Append(errs, msc.mutable[i].ConsumeMetrics(ctx, cloneMetrics(md)))\n\t\t}\n\t\t// Send data as is to the last mutating consumer only if there are no other non-mutating consumers and the\n\t\t// data is mutable. Never share the same data between a mutating and a non-mutating consumer since the\n\t\t// non-mutating consumer may process data async and the mutating consumer may change the data before that.\n\t\tlastConsumer := msc.mutable[len(msc.mutable)-1]\n\t\tif len(msc.readonly) == 0 && !md.IsReadOnly() {\n\t\t\terrs = multierr.Append(errs, lastConsumer.ConsumeMetrics(ctx, md))\n\t\t} else {\n\t\t\terrs = multierr.Append(errs, lastConsumer.ConsumeMetrics(ctx, cloneMetrics(md)))\n\t\t}\n\t}\n\n\t// Mark the data as read-only if it will be sent to more than one read-only consumer.\n\tif len(msc.readonly) > 1 && !md.IsReadOnly() {\n\t\tmd.MarkReadOnly()\n\t}\n\tfor _, mc := range msc.readonly {\n\t\terrs = multierr.Append(errs, mc.ConsumeMetrics(ctx, md))\n\t}\n\n\treturn errs\n}\n\nfunc cloneMetrics(md pmetric.Metrics) pmetric.Metrics {\n\tclonedMetrics := pmetric.NewMetrics()\n\tmd.CopyTo(clonedMetrics)\n\treturn clonedMetrics\n}\n"
  },
  {
    "path": "internal/fanoutconsumer/metrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage fanoutconsumer\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestMetricsNotMultiplexing(t *testing.T) {\n\tnop := consumertest.NewNop()\n\tmfc := NewMetrics([]consumer.Metrics{nop})\n\tassert.Same(t, nop, mfc)\n}\n\nfunc TestMetricssNotMultiplexingMutating(t *testing.T) {\n\tp := &mutatingMetricsSink{MetricsSink: new(consumertest.MetricsSink)}\n\tlfc := NewMetrics([]consumer.Metrics{p})\n\tassert.True(t, lfc.Capabilities().MutatesData)\n}\n\nfunc TestMetricsMultiplexingNonMutating(t *testing.T) {\n\tp1 := new(consumertest.MetricsSink)\n\tp2 := new(consumertest.MetricsSink)\n\tp3 := new(consumertest.MetricsSink)\n\n\tmfc := NewMetrics([]consumer.Metrics{p1, p2, p3})\n\tassert.False(t, mfc.Capabilities().MutatesData)\n\tmd := testdata.GenerateMetrics(1)\n\n\tfor range 2 {\n\t\terr := mfc.ConsumeMetrics(context.Background(), md)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tassert.Equal(t, md, p1.AllMetrics()[0])\n\tassert.Equal(t, md, p1.AllMetrics()[1])\n\tassert.Equal(t, md, p1.AllMetrics()[0])\n\tassert.Equal(t, md, p1.AllMetrics()[1])\n\n\tassert.Equal(t, md, p2.AllMetrics()[0])\n\tassert.Equal(t, md, p2.AllMetrics()[1])\n\tassert.Equal(t, md, p2.AllMetrics()[0])\n\tassert.Equal(t, md, p2.AllMetrics()[1])\n\n\tassert.Equal(t, md, p3.AllMetrics()[0])\n\tassert.Equal(t, md, p3.AllMetrics()[1])\n\tassert.Equal(t, md, p3.AllMetrics()[0])\n\tassert.Equal(t, md, p3.AllMetrics()[1])\n\n\t// The data should be marked as read only.\n\tassert.True(t, md.IsReadOnly())\n}\n\nfunc TestMetricsMultiplexingMutating(t *testing.T) {\n\tp1 := &mutatingMetricsSink{MetricsSink: new(consumertest.MetricsSink)}\n\tp2 := &mutatingMetricsSink{MetricsSink: new(consumertest.MetricsSink)}\n\tp3 := &mutatingMetricsSink{MetricsSink: new(consumertest.MetricsSink)}\n\n\tmfc := NewMetrics([]consumer.Metrics{p1, p2, p3})\n\tassert.True(t, mfc.Capabilities().MutatesData)\n\tmd := testdata.GenerateMetrics(1)\n\n\tfor range 2 {\n\t\terr := mfc.ConsumeMetrics(context.Background(), md)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tassert.NotSame(t, &md, &p1.AllMetrics()[0])\n\tassert.NotSame(t, &md, &p1.AllMetrics()[1])\n\tassert.Equal(t, md, p1.AllMetrics()[0])\n\tassert.Equal(t, md, p1.AllMetrics()[1])\n\n\tassert.NotSame(t, &md, &p2.AllMetrics()[0])\n\tassert.NotSame(t, &md, &p2.AllMetrics()[1])\n\tassert.Equal(t, md, p2.AllMetrics()[0])\n\tassert.Equal(t, md, p2.AllMetrics()[1])\n\n\t// For this consumer, will receive the initial data.\n\tassert.Equal(t, md, p3.AllMetrics()[0])\n\tassert.Equal(t, md, p3.AllMetrics()[1])\n\tassert.Equal(t, md, p3.AllMetrics()[0])\n\tassert.Equal(t, md, p3.AllMetrics()[1])\n\n\t// The data should not be marked as read only.\n\tassert.False(t, md.IsReadOnly())\n}\n\nfunc TestReadOnlyMetricsMultiplexingMixFirstMutating(t *testing.T) {\n\tp1 := &mutatingMetricsSink{MetricsSink: new(consumertest.MetricsSink)}\n\tp2 := &mutatingMetricsSink{MetricsSink: new(consumertest.MetricsSink)}\n\tp3 := &mutatingMetricsSink{MetricsSink: new(consumertest.MetricsSink)}\n\n\tmfc := NewMetrics([]consumer.Metrics{p1, p2, p3})\n\tassert.True(t, mfc.Capabilities().MutatesData)\n\tmdOrig := testdata.GenerateMetrics(1)\n\tmd := testdata.GenerateMetrics(1)\n\tmd.MarkReadOnly()\n\n\tfor range 2 {\n\t\terr := mfc.ConsumeMetrics(context.Background(), md)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\t// All consumers should receive the cloned data.\n\n\tassert.NotEqual(t, md, p1.AllMetrics()[0])\n\tassert.NotEqual(t, md, p1.AllMetrics()[1])\n\tassert.Equal(t, mdOrig, p1.AllMetrics()[0])\n\tassert.Equal(t, mdOrig, p1.AllMetrics()[1])\n\n\tassert.NotEqual(t, md, p2.AllMetrics()[0])\n\tassert.NotEqual(t, md, p2.AllMetrics()[1])\n\tassert.Equal(t, mdOrig, p2.AllMetrics()[0])\n\tassert.Equal(t, mdOrig, p2.AllMetrics()[1])\n\n\tassert.NotEqual(t, md, p3.AllMetrics()[0])\n\tassert.NotEqual(t, md, p3.AllMetrics()[1])\n\tassert.Equal(t, mdOrig, p3.AllMetrics()[0])\n\tassert.Equal(t, mdOrig, p3.AllMetrics()[1])\n}\n\nfunc TestMetricsMultiplexingMixLastMutating(t *testing.T) {\n\tp1 := &mutatingMetricsSink{MetricsSink: new(consumertest.MetricsSink)}\n\tp2 := new(consumertest.MetricsSink)\n\tp3 := &mutatingMetricsSink{MetricsSink: new(consumertest.MetricsSink)}\n\n\tmfc := NewMetrics([]consumer.Metrics{p1, p2, p3})\n\tassert.False(t, mfc.Capabilities().MutatesData)\n\tmd := testdata.GenerateMetrics(1)\n\n\tfor range 2 {\n\t\terr := mfc.ConsumeMetrics(context.Background(), md)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tassert.NotSame(t, &md, &p1.AllMetrics()[0])\n\tassert.NotSame(t, &md, &p1.AllMetrics()[1])\n\tassert.Equal(t, md, p1.AllMetrics()[0])\n\tassert.Equal(t, md, p1.AllMetrics()[1])\n\n\t// For this consumer, will receive the initial data.\n\tassert.Equal(t, md, p2.AllMetrics()[0])\n\tassert.Equal(t, md, p2.AllMetrics()[1])\n\tassert.Equal(t, md, p2.AllMetrics()[0])\n\tassert.Equal(t, md, p2.AllMetrics()[1])\n\n\t// For this consumer, will clone the initial data.\n\tassert.NotSame(t, &md, &p3.AllMetrics()[0])\n\tassert.NotSame(t, &md, &p3.AllMetrics()[1])\n\tassert.Equal(t, md, p3.AllMetrics()[0])\n\tassert.Equal(t, md, p3.AllMetrics()[1])\n\n\t// The data should not be marked as read only.\n\tassert.False(t, md.IsReadOnly())\n}\n\nfunc TestMetricsMultiplexingMixLastNonMutating(t *testing.T) {\n\tp1 := &mutatingMetricsSink{MetricsSink: new(consumertest.MetricsSink)}\n\tp2 := &mutatingMetricsSink{MetricsSink: new(consumertest.MetricsSink)}\n\tp3 := new(consumertest.MetricsSink)\n\n\tmfc := NewMetrics([]consumer.Metrics{p1, p2, p3})\n\tassert.False(t, mfc.Capabilities().MutatesData)\n\tmd := testdata.GenerateMetrics(1)\n\n\tfor range 2 {\n\t\terr := mfc.ConsumeMetrics(context.Background(), md)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tassert.NotSame(t, &md, &p1.AllMetrics()[0])\n\tassert.NotSame(t, &md, &p1.AllMetrics()[1])\n\tassert.Equal(t, md, p1.AllMetrics()[0])\n\tassert.Equal(t, md, p1.AllMetrics()[1])\n\n\tassert.NotSame(t, &md, &p2.AllMetrics()[0])\n\tassert.NotSame(t, &md, &p2.AllMetrics()[1])\n\tassert.Equal(t, md, p2.AllMetrics()[0])\n\tassert.Equal(t, md, p2.AllMetrics()[1])\n\n\t// For this consumer, will receive the initial data.\n\tassert.Equal(t, md, p3.AllMetrics()[0])\n\tassert.Equal(t, md, p3.AllMetrics()[1])\n\tassert.Equal(t, md, p3.AllMetrics()[0])\n\tassert.Equal(t, md, p3.AllMetrics()[1])\n\n\t// The data should not be marked as read only.\n\tassert.False(t, md.IsReadOnly())\n}\n\nfunc TestMetricsWhenErrors(t *testing.T) {\n\tp1 := mutatingErr{Consumer: consumertest.NewErr(errors.New(\"my error\"))}\n\tp2 := consumertest.NewErr(errors.New(\"my error\"))\n\tp3 := new(consumertest.MetricsSink)\n\n\tmfc := NewMetrics([]consumer.Metrics{p1, p2, p3})\n\tmd := testdata.GenerateMetrics(1)\n\n\tfor range 2 {\n\t\trequire.Error(t, mfc.ConsumeMetrics(context.Background(), md))\n\t}\n\n\tassert.Equal(t, md, p3.AllMetrics()[0])\n\tassert.Equal(t, md, p3.AllMetrics()[1])\n\tassert.Equal(t, md, p3.AllMetrics()[0])\n\tassert.Equal(t, md, p3.AllMetrics()[1])\n}\n\ntype mutatingMetricsSink struct {\n\t*consumertest.MetricsSink\n}\n\nfunc (mts *mutatingMetricsSink) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: true}\n}\n"
  },
  {
    "path": "internal/fanoutconsumer/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage fanoutconsumer\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "internal/fanoutconsumer/profiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage fanoutconsumer // import \"go.opentelemetry.io/collector/internal/fanoutconsumer\"\n\nimport (\n\t\"context\"\n\n\t\"go.uber.org/multierr\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n)\n\n// NewProfiles wraps multiple profile consumers in a single one.\n// It fans out the incoming data to all the consumers, and does smart routing:\n//   - Clones only to the consumer that needs to mutate the data.\n//   - If all consumers needs to mutate the data one will get the original mutable data.\nfunc NewProfiles(tcs []xconsumer.Profiles) xconsumer.Profiles {\n\t// Don't wrap if there is only one non-mutating consumer.\n\tif len(tcs) == 1 && !tcs[0].Capabilities().MutatesData {\n\t\treturn tcs[0]\n\t}\n\n\ttc := &profilesConsumer{}\n\tfor i := range tcs {\n\t\tif tcs[i].Capabilities().MutatesData {\n\t\t\ttc.mutable = append(tc.mutable, tcs[i])\n\t\t} else {\n\t\t\ttc.readonly = append(tc.readonly, tcs[i])\n\t\t}\n\t}\n\treturn tc\n}\n\ntype profilesConsumer struct {\n\tmutable  []xconsumer.Profiles\n\treadonly []xconsumer.Profiles\n}\n\nfunc (tsc *profilesConsumer) Capabilities() consumer.Capabilities {\n\t// If all consumers are mutating, then the original data will be passed to one of them.\n\treturn consumer.Capabilities{MutatesData: len(tsc.mutable) > 0 && len(tsc.readonly) == 0}\n}\n\n// ConsumeProfiles exports the pprofile.Profiles to all consumers wrapped by the current one.\nfunc (tsc *profilesConsumer) ConsumeProfiles(ctx context.Context, td pprofile.Profiles) error {\n\tvar errs error\n\n\tif len(tsc.mutable) > 0 {\n\t\t// Clone the data before sending to all mutating consumers except the last one.\n\t\tfor i := 0; i < len(tsc.mutable)-1; i++ {\n\t\t\terrs = multierr.Append(errs, tsc.mutable[i].ConsumeProfiles(ctx, cloneProfiles(td)))\n\t\t}\n\t\t// Send data as is to the last mutating consumer only if there are no other non-mutating consumers and the\n\t\t// data is mutable. Never share the same data between a mutating and a non-mutating consumer since the\n\t\t// non-mutating consumer may process data async and the mutating consumer may change the data before that.\n\t\tlastConsumer := tsc.mutable[len(tsc.mutable)-1]\n\t\tif len(tsc.readonly) == 0 && !td.IsReadOnly() {\n\t\t\terrs = multierr.Append(errs, lastConsumer.ConsumeProfiles(ctx, td))\n\t\t} else {\n\t\t\terrs = multierr.Append(errs, lastConsumer.ConsumeProfiles(ctx, cloneProfiles(td)))\n\t\t}\n\t}\n\n\t// Mark the data as read-only if it will be sent to more than one read-only consumer.\n\tif len(tsc.readonly) > 1 && !td.IsReadOnly() {\n\t\ttd.MarkReadOnly()\n\t}\n\tfor _, tc := range tsc.readonly {\n\t\terrs = multierr.Append(errs, tc.ConsumeProfiles(ctx, td))\n\t}\n\n\treturn errs\n}\n\nfunc cloneProfiles(td pprofile.Profiles) pprofile.Profiles {\n\tclonedProfiles := pprofile.NewProfiles()\n\ttd.CopyTo(clonedProfiles)\n\treturn clonedProfiles\n}\n"
  },
  {
    "path": "internal/fanoutconsumer/profiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage fanoutconsumer\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestProfilesNotMultiplexing(t *testing.T) {\n\tnop := consumertest.NewNop()\n\ttfc := NewProfiles([]xconsumer.Profiles{nop})\n\tassert.Same(t, nop, tfc)\n}\n\nfunc TestProfilesNotMultiplexingMutating(t *testing.T) {\n\tp := &mutatingProfilesSink{ProfilesSink: new(consumertest.ProfilesSink)}\n\tlfc := NewProfiles([]xconsumer.Profiles{p})\n\tassert.True(t, lfc.Capabilities().MutatesData)\n}\n\nfunc TestProfilesMultiplexingNonMutating(t *testing.T) {\n\tp1 := new(consumertest.ProfilesSink)\n\tp2 := new(consumertest.ProfilesSink)\n\tp3 := new(consumertest.ProfilesSink)\n\n\ttfc := NewProfiles([]xconsumer.Profiles{p1, p2, p3})\n\tassert.False(t, tfc.Capabilities().MutatesData)\n\ttd := testdata.GenerateProfiles(1)\n\n\tfor range 2 {\n\t\terr := tfc.ConsumeProfiles(context.Background(), td)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tassert.Equal(t, td, p1.AllProfiles()[0])\n\tassert.Equal(t, td, p1.AllProfiles()[1])\n\tassert.Equal(t, td, p1.AllProfiles()[0])\n\tassert.Equal(t, td, p1.AllProfiles()[1])\n\n\tassert.Equal(t, td, p2.AllProfiles()[0])\n\tassert.Equal(t, td, p2.AllProfiles()[1])\n\tassert.Equal(t, td, p2.AllProfiles()[0])\n\tassert.Equal(t, td, p2.AllProfiles()[1])\n\n\tassert.Equal(t, td, p3.AllProfiles()[0])\n\tassert.Equal(t, td, p3.AllProfiles()[1])\n\tassert.Equal(t, td, p3.AllProfiles()[0])\n\tassert.Equal(t, td, p3.AllProfiles()[1])\n\n\t// The data should be marked as read only.\n\tassert.True(t, td.IsReadOnly())\n}\n\nfunc TestProfilesMultiplexingMutating(t *testing.T) {\n\tp1 := &mutatingProfilesSink{ProfilesSink: new(consumertest.ProfilesSink)}\n\tp2 := &mutatingProfilesSink{ProfilesSink: new(consumertest.ProfilesSink)}\n\tp3 := &mutatingProfilesSink{ProfilesSink: new(consumertest.ProfilesSink)}\n\n\ttfc := NewProfiles([]xconsumer.Profiles{p1, p2, p3})\n\tassert.True(t, tfc.Capabilities().MutatesData)\n\ttd := testdata.GenerateProfiles(1)\n\n\tfor range 2 {\n\t\terr := tfc.ConsumeProfiles(context.Background(), td)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tassert.NotSame(t, &td, &p1.AllProfiles()[0])\n\tassert.NotSame(t, &td, &p1.AllProfiles()[1])\n\tassert.Equal(t, td, p1.AllProfiles()[0])\n\tassert.Equal(t, td, p1.AllProfiles()[1])\n\n\tassert.NotSame(t, &td, &p2.AllProfiles()[0])\n\tassert.NotSame(t, &td, &p2.AllProfiles()[1])\n\tassert.Equal(t, td, p2.AllProfiles()[0])\n\tassert.Equal(t, td, p2.AllProfiles()[1])\n\n\t// For this consumer, will receive the initial data.\n\tassert.Equal(t, td, p3.AllProfiles()[0])\n\tassert.Equal(t, td, p3.AllProfiles()[1])\n\tassert.Equal(t, td, p3.AllProfiles()[0])\n\tassert.Equal(t, td, p3.AllProfiles()[1])\n\n\t// The data should not be marked as read only.\n\tassert.False(t, td.IsReadOnly())\n}\n\nfunc TestReadOnlyProfilesMultiplexingMutating(t *testing.T) {\n\tp1 := &mutatingProfilesSink{ProfilesSink: new(consumertest.ProfilesSink)}\n\tp2 := &mutatingProfilesSink{ProfilesSink: new(consumertest.ProfilesSink)}\n\tp3 := &mutatingProfilesSink{ProfilesSink: new(consumertest.ProfilesSink)}\n\n\ttfc := NewProfiles([]xconsumer.Profiles{p1, p2, p3})\n\tassert.True(t, tfc.Capabilities().MutatesData)\n\n\ttdOrig := testdata.GenerateProfiles(1)\n\ttd := testdata.GenerateProfiles(1)\n\ttd.MarkReadOnly()\n\n\tfor range 2 {\n\t\terr := tfc.ConsumeProfiles(context.Background(), td)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\t// All consumers should receive the cloned data.\n\n\tassert.NotEqual(t, td, p1.AllProfiles()[0])\n\tassert.NotEqual(t, td, p1.AllProfiles()[1])\n\tassert.Equal(t, tdOrig, p1.AllProfiles()[0])\n\tassert.Equal(t, tdOrig, p1.AllProfiles()[1])\n\n\tassert.NotEqual(t, td, p2.AllProfiles()[0])\n\tassert.NotEqual(t, td, p2.AllProfiles()[1])\n\tassert.Equal(t, tdOrig, p2.AllProfiles()[0])\n\tassert.Equal(t, tdOrig, p2.AllProfiles()[1])\n\n\tassert.NotEqual(t, td, p3.AllProfiles()[0])\n\tassert.NotEqual(t, td, p3.AllProfiles()[1])\n\tassert.Equal(t, tdOrig, p3.AllProfiles()[0])\n\tassert.Equal(t, tdOrig, p3.AllProfiles()[1])\n}\n\nfunc TestProfilesMultiplexingMixLastMutating(t *testing.T) {\n\tp1 := &mutatingProfilesSink{ProfilesSink: new(consumertest.ProfilesSink)}\n\tp2 := new(consumertest.ProfilesSink)\n\tp3 := &mutatingProfilesSink{ProfilesSink: new(consumertest.ProfilesSink)}\n\n\ttfc := NewProfiles([]xconsumer.Profiles{p1, p2, p3})\n\tassert.False(t, tfc.Capabilities().MutatesData)\n\ttd := testdata.GenerateProfiles(1)\n\n\tfor range 2 {\n\t\terr := tfc.ConsumeProfiles(context.Background(), td)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tassert.NotSame(t, &td, &p1.AllProfiles()[0])\n\tassert.NotSame(t, &td, &p1.AllProfiles()[1])\n\tassert.Equal(t, td, p1.AllProfiles()[0])\n\tassert.Equal(t, td, p1.AllProfiles()[1])\n\n\t// For this consumer, will receive the initial data.\n\tassert.Equal(t, td, p2.AllProfiles()[0])\n\tassert.Equal(t, td, p2.AllProfiles()[1])\n\tassert.Equal(t, td, p2.AllProfiles()[0])\n\tassert.Equal(t, td, p2.AllProfiles()[1])\n\n\t// For this consumer, will clone the initial data.\n\tassert.NotSame(t, &td, &p3.AllProfiles()[0])\n\tassert.NotSame(t, &td, &p3.AllProfiles()[1])\n\tassert.Equal(t, td, p3.AllProfiles()[0])\n\tassert.Equal(t, td, p3.AllProfiles()[1])\n\n\t// The data should not be marked as read only.\n\tassert.False(t, td.IsReadOnly())\n}\n\nfunc TestProfilesMultiplexingMixLastNonMutating(t *testing.T) {\n\tp1 := &mutatingProfilesSink{ProfilesSink: new(consumertest.ProfilesSink)}\n\tp2 := &mutatingProfilesSink{ProfilesSink: new(consumertest.ProfilesSink)}\n\tp3 := new(consumertest.ProfilesSink)\n\n\ttfc := NewProfiles([]xconsumer.Profiles{p1, p2, p3})\n\tassert.False(t, tfc.Capabilities().MutatesData)\n\ttd := testdata.GenerateProfiles(1)\n\n\tfor range 2 {\n\t\terr := tfc.ConsumeProfiles(context.Background(), td)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tassert.NotSame(t, &td, &p1.AllProfiles()[0])\n\tassert.NotSame(t, &td, &p1.AllProfiles()[1])\n\tassert.Equal(t, td, p1.AllProfiles()[0])\n\tassert.Equal(t, td, p1.AllProfiles()[1])\n\n\tassert.NotSame(t, &td, &p2.AllProfiles()[0])\n\tassert.NotSame(t, &td, &p2.AllProfiles()[1])\n\tassert.Equal(t, td, p2.AllProfiles()[0])\n\tassert.Equal(t, td, p2.AllProfiles()[1])\n\n\t// For this consumer, will receive the initial data.\n\tassert.Equal(t, td, p3.AllProfiles()[0])\n\tassert.Equal(t, td, p3.AllProfiles()[1])\n\tassert.Equal(t, td, p3.AllProfiles()[0])\n\tassert.Equal(t, td, p3.AllProfiles()[1])\n\n\t// The data should not be marked as read only.\n\tassert.False(t, td.IsReadOnly())\n}\n\nfunc TestProfilesWhenErrors(t *testing.T) {\n\tp1 := mutatingErr{Consumer: consumertest.NewErr(errors.New(\"my error\"))}\n\tp2 := consumertest.NewErr(errors.New(\"my error\"))\n\tp3 := new(consumertest.ProfilesSink)\n\n\ttfc := NewProfiles([]xconsumer.Profiles{p1, p2, p3})\n\ttd := testdata.GenerateProfiles(1)\n\n\tfor range 2 {\n\t\trequire.Error(t, tfc.ConsumeProfiles(context.Background(), td))\n\t}\n\n\tassert.Equal(t, td, p3.AllProfiles()[0])\n\tassert.Equal(t, td, p3.AllProfiles()[1])\n\tassert.Equal(t, td, p3.AllProfiles()[0])\n\tassert.Equal(t, td, p3.AllProfiles()[1])\n}\n\ntype mutatingProfilesSink struct {\n\t*consumertest.ProfilesSink\n}\n\nfunc (mts *mutatingProfilesSink) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: true}\n}\n"
  },
  {
    "path": "internal/fanoutconsumer/traces.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage fanoutconsumer // import \"go.opentelemetry.io/collector/internal/fanoutconsumer\"\n\nimport (\n\t\"context\"\n\n\t\"go.uber.org/multierr\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\n// NewTraces wraps multiple trace consumers in a single one.\n// It fans out the incoming data to all the consumers, and does smart routing:\n//   - Clones only to the consumer that needs to mutate the data.\n//   - If all consumers needs to mutate the data one will get the original mutable data.\nfunc NewTraces(tcs []consumer.Traces) consumer.Traces {\n\t// Don't wrap if there is only one non-mutating consumer.\n\tif len(tcs) == 1 && !tcs[0].Capabilities().MutatesData {\n\t\treturn tcs[0]\n\t}\n\n\ttc := &tracesConsumer{}\n\tfor i := range tcs {\n\t\tif tcs[i].Capabilities().MutatesData {\n\t\t\ttc.mutable = append(tc.mutable, tcs[i])\n\t\t} else {\n\t\t\ttc.readonly = append(tc.readonly, tcs[i])\n\t\t}\n\t}\n\treturn tc\n}\n\ntype tracesConsumer struct {\n\tmutable  []consumer.Traces\n\treadonly []consumer.Traces\n}\n\nfunc (tsc *tracesConsumer) Capabilities() consumer.Capabilities {\n\t// If all consumers are mutating, then the original data will be passed to one of them.\n\treturn consumer.Capabilities{MutatesData: len(tsc.mutable) > 0 && len(tsc.readonly) == 0}\n}\n\n// ConsumeTraces exports the ptrace.Traces to all consumers wrapped by the current one.\nfunc (tsc *tracesConsumer) ConsumeTraces(ctx context.Context, td ptrace.Traces) error {\n\tvar errs error\n\n\tif len(tsc.mutable) > 0 {\n\t\t// Clone the data before sending to all mutating consumers except the last one.\n\t\tfor i := 0; i < len(tsc.mutable)-1; i++ {\n\t\t\terrs = multierr.Append(errs, tsc.mutable[i].ConsumeTraces(ctx, cloneTraces(td)))\n\t\t}\n\t\t// Send data as is to the last mutating consumer only if there are no other non-mutating consumers and the\n\t\t// data is mutable. Never share the same data between a mutating and a non-mutating consumer since the\n\t\t// non-mutating consumer may process data async and the mutating consumer may change the data before that.\n\t\tlastConsumer := tsc.mutable[len(tsc.mutable)-1]\n\t\tif len(tsc.readonly) == 0 && !td.IsReadOnly() {\n\t\t\terrs = multierr.Append(errs, lastConsumer.ConsumeTraces(ctx, td))\n\t\t} else {\n\t\t\terrs = multierr.Append(errs, lastConsumer.ConsumeTraces(ctx, cloneTraces(td)))\n\t\t}\n\t}\n\n\t// Mark the data as read-only if it will be sent to more than one read-only consumer.\n\tif len(tsc.readonly) > 1 && !td.IsReadOnly() {\n\t\ttd.MarkReadOnly()\n\t}\n\tfor _, tc := range tsc.readonly {\n\t\terrs = multierr.Append(errs, tc.ConsumeTraces(ctx, td))\n\t}\n\n\treturn errs\n}\n\nfunc cloneTraces(td ptrace.Traces) ptrace.Traces {\n\tclonedTraces := ptrace.NewTraces()\n\ttd.CopyTo(clonedTraces)\n\treturn clonedTraces\n}\n"
  },
  {
    "path": "internal/fanoutconsumer/traces_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage fanoutconsumer\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestTracesNotMultiplexing(t *testing.T) {\n\tnop := consumertest.NewNop()\n\ttfc := NewTraces([]consumer.Traces{nop})\n\tassert.Same(t, nop, tfc)\n}\n\nfunc TestTracesNotMultiplexingMutating(t *testing.T) {\n\tp := &mutatingTracesSink{TracesSink: new(consumertest.TracesSink)}\n\tlfc := NewTraces([]consumer.Traces{p})\n\tassert.True(t, lfc.Capabilities().MutatesData)\n}\n\nfunc TestTracesMultiplexingNonMutating(t *testing.T) {\n\tp1 := new(consumertest.TracesSink)\n\tp2 := new(consumertest.TracesSink)\n\tp3 := new(consumertest.TracesSink)\n\n\ttfc := NewTraces([]consumer.Traces{p1, p2, p3})\n\tassert.False(t, tfc.Capabilities().MutatesData)\n\ttd := testdata.GenerateTraces(1)\n\n\tfor range 2 {\n\t\terr := tfc.ConsumeTraces(context.Background(), td)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tassert.Equal(t, td, p1.AllTraces()[0])\n\tassert.Equal(t, td, p1.AllTraces()[1])\n\tassert.Equal(t, td, p1.AllTraces()[0])\n\tassert.Equal(t, td, p1.AllTraces()[1])\n\n\tassert.Equal(t, td, p2.AllTraces()[0])\n\tassert.Equal(t, td, p2.AllTraces()[1])\n\tassert.Equal(t, td, p2.AllTraces()[0])\n\tassert.Equal(t, td, p2.AllTraces()[1])\n\n\tassert.Equal(t, td, p3.AllTraces()[0])\n\tassert.Equal(t, td, p3.AllTraces()[1])\n\tassert.Equal(t, td, p3.AllTraces()[0])\n\tassert.Equal(t, td, p3.AllTraces()[1])\n\n\t// The data should be marked as read only.\n\tassert.True(t, td.IsReadOnly())\n}\n\nfunc TestTracesMultiplexingMutating(t *testing.T) {\n\tp1 := &mutatingTracesSink{TracesSink: new(consumertest.TracesSink)}\n\tp2 := &mutatingTracesSink{TracesSink: new(consumertest.TracesSink)}\n\tp3 := &mutatingTracesSink{TracesSink: new(consumertest.TracesSink)}\n\n\ttfc := NewTraces([]consumer.Traces{p1, p2, p3})\n\tassert.True(t, tfc.Capabilities().MutatesData)\n\ttd := testdata.GenerateTraces(1)\n\n\tfor range 2 {\n\t\terr := tfc.ConsumeTraces(context.Background(), td)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tassert.NotSame(t, &td, &p1.AllTraces()[0])\n\tassert.NotSame(t, &td, &p1.AllTraces()[1])\n\tassert.Equal(t, td, p1.AllTraces()[0])\n\tassert.Equal(t, td, p1.AllTraces()[1])\n\n\tassert.NotSame(t, &td, &p2.AllTraces()[0])\n\tassert.NotSame(t, &td, &p2.AllTraces()[1])\n\tassert.Equal(t, td, p2.AllTraces()[0])\n\tassert.Equal(t, td, p2.AllTraces()[1])\n\n\t// For this consumer, will receive the initial data.\n\tassert.Equal(t, td, p3.AllTraces()[0])\n\tassert.Equal(t, td, p3.AllTraces()[1])\n\tassert.Equal(t, td, p3.AllTraces()[0])\n\tassert.Equal(t, td, p3.AllTraces()[1])\n\n\t// The data should not be marked as read only.\n\tassert.False(t, td.IsReadOnly())\n}\n\nfunc TestReadOnlyTracesMultiplexingMutating(t *testing.T) {\n\tp1 := &mutatingTracesSink{TracesSink: new(consumertest.TracesSink)}\n\tp2 := &mutatingTracesSink{TracesSink: new(consumertest.TracesSink)}\n\tp3 := &mutatingTracesSink{TracesSink: new(consumertest.TracesSink)}\n\n\ttfc := NewTraces([]consumer.Traces{p1, p2, p3})\n\tassert.True(t, tfc.Capabilities().MutatesData)\n\n\ttdOrig := testdata.GenerateTraces(1)\n\ttd := testdata.GenerateTraces(1)\n\ttd.MarkReadOnly()\n\n\tfor range 2 {\n\t\terr := tfc.ConsumeTraces(context.Background(), td)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\t// All consumers should receive the cloned data.\n\n\tassert.NotEqual(t, td, p1.AllTraces()[0])\n\tassert.NotEqual(t, td, p1.AllTraces()[1])\n\tassert.Equal(t, tdOrig, p1.AllTraces()[0])\n\tassert.Equal(t, tdOrig, p1.AllTraces()[1])\n\n\tassert.NotEqual(t, td, p2.AllTraces()[0])\n\tassert.NotEqual(t, td, p2.AllTraces()[1])\n\tassert.Equal(t, tdOrig, p2.AllTraces()[0])\n\tassert.Equal(t, tdOrig, p2.AllTraces()[1])\n\n\tassert.NotEqual(t, td, p3.AllTraces()[0])\n\tassert.NotEqual(t, td, p3.AllTraces()[1])\n\tassert.Equal(t, tdOrig, p3.AllTraces()[0])\n\tassert.Equal(t, tdOrig, p3.AllTraces()[1])\n}\n\nfunc TestTracesMultiplexingMixLastMutating(t *testing.T) {\n\tp1 := &mutatingTracesSink{TracesSink: new(consumertest.TracesSink)}\n\tp2 := new(consumertest.TracesSink)\n\tp3 := &mutatingTracesSink{TracesSink: new(consumertest.TracesSink)}\n\n\ttfc := NewTraces([]consumer.Traces{p1, p2, p3})\n\tassert.False(t, tfc.Capabilities().MutatesData)\n\ttd := testdata.GenerateTraces(1)\n\n\tfor range 2 {\n\t\terr := tfc.ConsumeTraces(context.Background(), td)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tassert.NotSame(t, &td, &p1.AllTraces()[0])\n\tassert.NotSame(t, &td, &p1.AllTraces()[1])\n\tassert.Equal(t, td, p1.AllTraces()[0])\n\tassert.Equal(t, td, p1.AllTraces()[1])\n\n\t// For this consumer, will receive the initial data.\n\tassert.Equal(t, td, p2.AllTraces()[0])\n\tassert.Equal(t, td, p2.AllTraces()[1])\n\tassert.Equal(t, td, p2.AllTraces()[0])\n\tassert.Equal(t, td, p2.AllTraces()[1])\n\n\t// For this consumer, will clone the initial data.\n\tassert.NotSame(t, &td, &p3.AllTraces()[0])\n\tassert.NotSame(t, &td, &p3.AllTraces()[1])\n\tassert.Equal(t, td, p3.AllTraces()[0])\n\tassert.Equal(t, td, p3.AllTraces()[1])\n\n\t// The data should not be marked as read only.\n\tassert.False(t, td.IsReadOnly())\n}\n\nfunc TestTracesMultiplexingMixLastNonMutating(t *testing.T) {\n\tp1 := &mutatingTracesSink{TracesSink: new(consumertest.TracesSink)}\n\tp2 := &mutatingTracesSink{TracesSink: new(consumertest.TracesSink)}\n\tp3 := new(consumertest.TracesSink)\n\n\ttfc := NewTraces([]consumer.Traces{p1, p2, p3})\n\tassert.False(t, tfc.Capabilities().MutatesData)\n\ttd := testdata.GenerateTraces(1)\n\n\tfor range 2 {\n\t\terr := tfc.ConsumeTraces(context.Background(), td)\n\t\tif err != nil {\n\t\t\tt.Errorf(\"Wanted nil got error\")\n\t\t\treturn\n\t\t}\n\t}\n\n\tassert.NotSame(t, &td, &p1.AllTraces()[0])\n\tassert.NotSame(t, &td, &p1.AllTraces()[1])\n\tassert.Equal(t, td, p1.AllTraces()[0])\n\tassert.Equal(t, td, p1.AllTraces()[1])\n\n\tassert.NotSame(t, &td, &p2.AllTraces()[0])\n\tassert.NotSame(t, &td, &p2.AllTraces()[1])\n\tassert.Equal(t, td, p2.AllTraces()[0])\n\tassert.Equal(t, td, p2.AllTraces()[1])\n\n\t// For this consumer, will receive the initial data.\n\tassert.Equal(t, td, p3.AllTraces()[0])\n\tassert.Equal(t, td, p3.AllTraces()[1])\n\tassert.Equal(t, td, p3.AllTraces()[0])\n\tassert.Equal(t, td, p3.AllTraces()[1])\n\n\t// The data should not be marked as read only.\n\tassert.False(t, td.IsReadOnly())\n}\n\nfunc TestTracesWhenErrors(t *testing.T) {\n\tp1 := mutatingErr{Consumer: consumertest.NewErr(errors.New(\"my error\"))}\n\tp2 := consumertest.NewErr(errors.New(\"my error\"))\n\tp3 := new(consumertest.TracesSink)\n\n\ttfc := NewTraces([]consumer.Traces{p1, p2, p3})\n\ttd := testdata.GenerateTraces(1)\n\n\tfor range 2 {\n\t\trequire.Error(t, tfc.ConsumeTraces(context.Background(), td))\n\t}\n\n\tassert.Equal(t, td, p3.AllTraces()[0])\n\tassert.Equal(t, td, p3.AllTraces()[1])\n\tassert.Equal(t, td, p3.AllTraces()[0])\n\tassert.Equal(t, td, p3.AllTraces()[1])\n}\n\ntype mutatingTracesSink struct {\n\t*consumertest.TracesSink\n}\n\nfunc (mts *mutatingTracesSink) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: true}\n}\n"
  },
  {
    "path": "internal/memorylimiter/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/cgroup.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Keep the original Uber license.\n\n// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n//go:build linux\n\npackage cgroups // import \"go.opentelemetry.io/collector/internal/memorylimiter/cgroups\"\n\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strconv\"\n)\n\n// CGroup represents the data structure for a Linux control group.\ntype CGroup struct {\n\tpath string\n}\n\n// NewCGroup returns a new *CGroup from a given path.\nfunc NewCGroup(path string) *CGroup {\n\treturn &CGroup{path: path}\n}\n\n// Path returns the path of the CGroup*.\nfunc (cg *CGroup) Path() string {\n\treturn cg.path\n}\n\n// ParamPath returns the path of the given cgroup param under itself.\nfunc (cg *CGroup) ParamPath(param string) string {\n\treturn filepath.Join(cg.path, param)\n}\n\n// readFirstLine reads the first line from a cgroup param file.\nfunc (cg *CGroup) readFirstLine(param string) (string, error) {\n\tparamFile, err := os.Open(cg.ParamPath(param))\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tdefer paramFile.Close()\n\n\tscanner := bufio.NewScanner(paramFile)\n\tif scanner.Scan() {\n\t\treturn scanner.Text(), nil\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn \"\", err\n\t}\n\treturn \"\", io.ErrUnexpectedEOF\n}\n\n// readInt parses the first line from a cgroup param file as int.\nfunc (cg *CGroup) readInt(param string) (int64, error) {\n\ttext, err := cg.readFirstLine(param)\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\treturn strconv.ParseInt(text, 10, 64)\n}\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/cgroup_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Keep the original Uber license.\n\n// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n//go:build linux\n\npackage cgroups\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestCGroupParamPath(t *testing.T) {\n\tcgroup := NewCGroup(\"/sys/fs/cgroup/cpu\")\n\tassert.Equal(t, \"/sys/fs/cgroup/cpu\", cgroup.Path())\n\tassert.Equal(t, \"/sys/fs/cgroup/cpu/cpu.cfs_quota_us\", cgroup.ParamPath(\"cpu.cfs_quota_us\"))\n}\n\nfunc TestCGroupReadFirstLine(t *testing.T) {\n\ttestTable := []struct {\n\t\tname            string\n\t\tparamName       string\n\t\texpectedContent string\n\t\tshouldHaveError bool\n\t}{\n\t\t{\n\t\t\tname:            \"cpu\",\n\t\t\tparamName:       \"cpu.cfs_period_us\",\n\t\t\texpectedContent: \"100000\",\n\t\t\tshouldHaveError: false,\n\t\t},\n\t\t{\n\t\t\tname:            \"absent\",\n\t\t\tparamName:       \"cpu.stat\",\n\t\t\texpectedContent: \"\",\n\t\t\tshouldHaveError: true,\n\t\t},\n\t\t{\n\t\t\tname:            \"empty\",\n\t\t\tparamName:       \"cpu.cfs_quota_us\",\n\t\t\texpectedContent: \"\",\n\t\t\tshouldHaveError: true,\n\t\t},\n\t}\n\n\tfor _, tt := range testTable {\n\t\tcgroupPath := filepath.Join(testDataCGroupsPath, tt.name)\n\t\tcgroup := NewCGroup(cgroupPath)\n\n\t\tcontent, err := cgroup.readFirstLine(tt.paramName)\n\t\tassert.Equal(t, tt.expectedContent, content, tt.name)\n\n\t\tif tt.shouldHaveError {\n\t\t\tassert.Error(t, err, tt.name)\n\t\t} else {\n\t\t\tassert.NoError(t, err, tt.name)\n\t\t}\n\t}\n}\n\nfunc TestCGroupReadInt(t *testing.T) {\n\ttestTable := []struct {\n\t\tname            string\n\t\tparamName       string\n\t\texpectedValue   int64\n\t\tshouldHaveError bool\n\t}{\n\t\t{\n\t\t\tname:            \"cpu\",\n\t\t\tparamName:       \"cpu.cfs_period_us\",\n\t\t\texpectedValue:   100000,\n\t\t\tshouldHaveError: false,\n\t\t},\n\t\t{\n\t\t\tname:            \"empty\",\n\t\t\tparamName:       \"cpu.cfs_quota_us\",\n\t\t\texpectedValue:   0,\n\t\t\tshouldHaveError: true,\n\t\t},\n\t\t{\n\t\t\tname:            \"invalid\",\n\t\t\tparamName:       \"cpu.cfs_quota_us\",\n\t\t\texpectedValue:   0,\n\t\t\tshouldHaveError: true,\n\t\t},\n\t\t{\n\t\t\tname:            \"absent\",\n\t\t\tparamName:       \"cpu.cfs_quota_us\",\n\t\t\texpectedValue:   0,\n\t\t\tshouldHaveError: true,\n\t\t},\n\t}\n\n\tfor _, tt := range testTable {\n\t\tcgroupPath := filepath.Join(testDataCGroupsPath, tt.name)\n\t\tcgroup := NewCGroup(cgroupPath)\n\n\t\tvalue, err := cgroup.readInt(tt.paramName)\n\t\tassert.Equal(t, tt.expectedValue, value, \"%s/%s\", tt.name, tt.paramName)\n\n\t\tif tt.shouldHaveError {\n\t\t\tassert.Error(t, err, tt.name)\n\t\t} else {\n\t\t\tassert.NoError(t, err, tt.name)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/cgroups.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Keep the original Uber license.\n\n// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n//go:build linux\n\npackage cgroups // import \"go.opentelemetry.io/collector/internal/memorylimiter/cgroups\"\nimport (\n\t\"bufio\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\t// _cgroupFSType is the Linux CGroup file system type used in\n\t// `/proc/$PID/mountinfo`.\n\t_cgroupFSType = \"cgroup\"\n\t// _cgroupSubsysCPU is the CPU CGroup subsystem.\n\t_cgroupSubsysCPU = \"cpu\"\n\t// _cgroupSubsysCPUAcct is the CPU accounting CGroup subsystem.\n\t_cgroupSubsysCPUAcct = \"cpuacct\"\n\t// _cgroupSubsysCPUSet is the CPUSet CGroup subsystem.\n\t_cgroupSubsysCPUSet = \"cpuset\"\n\t// _cgroupSubsysMemory is the Memory CGroup subsystem.\n\t_cgroupSubsysMemory = \"memory\"\n\n\t_cgroupMemoryLimitBytes = \"memory.limit_in_bytes\"\n\n\t// _cgroupv2MemoryMax is the file name for the CGroup-V2 Memory max\n\t// parameter.\n\t_cgroupv2MemoryMax = \"memory.max\"\n\t// _cgroupFSType is the Linux CGroup-V2 file system type used in\n\t// `/proc/$PID/mountinfo`.\n\t_cgroupv2FSType = \"cgroup2\"\n)\n\nconst (\n\t_procPathCGroup     = \"/proc/self/cgroup\"\n\t_procPathMountInfo  = \"/proc/self/mountinfo\"\n\t_cgroupv2MountPoint = \"/sys/fs/cgroup\"\n)\n\n// CGroups is a map that associates each CGroup with its subsystem name.\ntype CGroups map[string]*CGroup\n\n// NewCGroups returns a new *CGroups from given `mountinfo` and `cgroup` files\n// under for some process under `/proc` file system (see also proc(5) for more\n// information).\nfunc NewCGroups(procPathMountInfo, procPathCGroup string) (CGroups, error) {\n\tcgroupSubsystems, err := parseCGroupSubsystems(procPathCGroup)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcgroups := make(CGroups)\n\tnewMountPoint := func(mp *MountPoint) error {\n\t\tif mp.FSType != _cgroupFSType {\n\t\t\treturn nil\n\t\t}\n\n\t\tfor _, opt := range mp.SuperOptions {\n\t\t\tsubsys, exists := cgroupSubsystems[opt]\n\t\t\tif !exists {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tcgroupPath, err := mp.Translate(subsys.Name)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tif strings.HasPrefix(cgroupPath, \"/sys\") {\n\t\t\t\tcgroups[opt] = NewCGroup(cgroupPath)\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t}\n\n\tif err := parseMountInfo(procPathMountInfo, newMountPoint); err != nil {\n\t\treturn nil, err\n\t}\n\treturn cgroups, nil\n}\n\n// NewCGroupsForCurrentProcess returns a new *CGroups instance for the current\n// process.\nfunc NewCGroupsForCurrentProcess() (CGroups, error) {\n\treturn NewCGroups(_procPathMountInfo, _procPathCGroup)\n}\n\n// MemoryQuota returns the total memory limit of the process\n// It is a result of `memory.limit_in_bytes`. If the value of\n// `memory.limit_in_bytes` was not set (-1) or (9223372036854771712), the method returns `(-1, false, nil)`.\nfunc (cg CGroups) MemoryQuota() (int64, bool, error) {\n\tmemCGroup, exists := cg[_cgroupSubsysMemory]\n\tif !exists {\n\t\treturn -1, false, nil\n\t}\n\n\tmemLimitBytes, err := memCGroup.readInt(_cgroupMemoryLimitBytes)\n\tif defined := memLimitBytes > 0; err != nil || !defined {\n\t\treturn -1, defined, err\n\t}\n\treturn memLimitBytes, true, nil\n}\n\n// IsCGroupV2 returns true if the system supports and uses cgroup2.\n// It gets the required information for deciding from mountinfo file.\nfunc IsCGroupV2() (bool, error) {\n\treturn isCGroupV2(_procPathMountInfo)\n}\n\nfunc isCGroupV2(procPathMountInfo string) (bool, error) {\n\tisV2 := false\n\tnewMountPoint := func(mp *MountPoint) error {\n\t\tif mp.FSType == _cgroupv2FSType && mp.MountPoint == _cgroupv2MountPoint {\n\t\t\tisV2 = true\n\t\t}\n\t\treturn nil\n\t}\n\tif err := parseMountInfo(procPathMountInfo, newMountPoint); err != nil {\n\t\treturn false, err\n\t}\n\treturn isV2, nil\n}\n\n// MemoryQuotaV2 returns the total memory limit of the process\n// It is a result of cgroupv2 `memory.max`. If the value of\n// `memory.max` was not set (max), the method returns `(-1, false, nil)`.\nfunc MemoryQuotaV2() (int64, bool, error) {\n\treturn memoryQuotaV2(_cgroupv2MountPoint, _cgroupv2MemoryMax)\n}\n\nfunc memoryQuotaV2(cgroupv2MountPoint, cgroupv2MemoryMax string) (int64, bool, error) {\n\tmemoryMaxParams, err := os.Open(filepath.Clean(filepath.Join(cgroupv2MountPoint, cgroupv2MemoryMax)))\n\tif err != nil {\n\t\tif os.IsNotExist(err) {\n\t\t\treturn -1, false, nil\n\t\t}\n\t\treturn -1, false, err\n\t}\n\tscanner := bufio.NewScanner(memoryMaxParams)\n\tif scanner.Scan() {\n\t\tvalue := strings.TrimSpace(scanner.Text())\n\t\tif value == \"max\" {\n\t\t\treturn -1, false, nil\n\t\t}\n\t\tmaxVal, err := strconv.ParseInt(value, 10, 64)\n\t\tif err != nil {\n\t\t\treturn -1, false, err\n\t\t}\n\t\treturn maxVal, true, nil\n\t}\n\tif err := scanner.Err(); err != nil {\n\t\treturn -1, false, err\n\t}\n\treturn -1, false, io.ErrUnexpectedEOF\n}\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/cgroups_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Keep the original Uber license.\n\n// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n//go:build linux\n\npackage cgroups\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestNewCGroups(t *testing.T) {\n\tcgroupsProcCGroupPath := filepath.Join(testDataProcPath, \"cgroups\", \"cgroup\")\n\tcgroupsProcMountInfoPath := filepath.Join(testDataProcPath, \"cgroups\", \"mountinfo\")\n\n\ttestTable := []struct {\n\t\tsubsys string\n\t\tpath   string\n\t}{\n\t\t{_cgroupSubsysCPU, \"/sys/fs/cgroup/cpu,cpuacct\"},\n\t\t{_cgroupSubsysCPUAcct, \"/sys/fs/cgroup/cpu,cpuacct\"},\n\t\t{_cgroupSubsysCPUSet, \"/sys/fs/cgroup/cpuset\"},\n\t\t{_cgroupSubsysMemory, \"/sys/fs/cgroup/memory/large\"},\n\t}\n\n\tcgroups, err := NewCGroups(cgroupsProcMountInfoPath, cgroupsProcCGroupPath)\n\tassert.Len(t, cgroups, len(testTable))\n\trequire.NoError(t, err)\n\n\tfor _, tt := range testTable {\n\t\tcgroup, exists := cgroups[tt.subsys]\n\t\tassert.True(t, exists, \"%q expected to present in `cgroups`\", tt.subsys)\n\t\tassert.Equal(t, tt.path, cgroup.path, \"%q expected for `cgroups[%q].path`, got %q\", tt.path, tt.subsys, cgroup.path)\n\t}\n}\n\nfunc TestNewCGroupsWithErrors(t *testing.T) {\n\ttestTable := []struct {\n\t\tmountInfoPath string\n\t\tcgroupPath    string\n\t}{\n\t\t{\"non-existing-file\", \"/dev/null\"},\n\t\t{\"/dev/null\", \"non-existing-file\"},\n\t\t{\n\t\t\t\"/dev/null\",\n\t\t\tfilepath.Join(testDataProcPath, \"invalid-cgroup\", \"cgroup\"),\n\t\t},\n\t\t{\n\t\t\tfilepath.Join(testDataProcPath, \"invalid-mountinfo\", \"mountinfo\"),\n\t\t\t\"/dev/null\",\n\t\t},\n\t\t{\n\t\t\tfilepath.Join(testDataProcPath, \"untranslatable\", \"mountinfo\"),\n\t\t\tfilepath.Join(testDataProcPath, \"untranslatable\", \"cgroup\"),\n\t\t},\n\t}\n\n\tfor _, tt := range testTable {\n\t\tcgroups, err := NewCGroups(tt.mountInfoPath, tt.cgroupPath)\n\t\tassert.Nil(t, cgroups)\n\t\tassert.Error(t, err)\n\t}\n}\n\nfunc TestCGroupsMemoryQuota(t *testing.T) {\n\ttestTable := []struct {\n\t\tname            string\n\t\texpectedQuota   int64\n\t\texpectedDefined bool\n\t\tshouldHaveError bool\n\t}{\n\t\t{\n\t\t\tname:            \"undefined\",\n\t\t\texpectedQuota:   int64(-1.0),\n\t\t\texpectedDefined: false,\n\t\t\tshouldHaveError: true,\n\t\t},\n\t\t{\n\t\t\tname:            \"memory\",\n\t\t\texpectedQuota:   int64(8796093018112),\n\t\t\texpectedDefined: true,\n\t\t\tshouldHaveError: false,\n\t\t},\n\t}\n\n\tcgroups := make(CGroups)\n\n\tquota, defined, err := cgroups.MemoryQuota()\n\tassert.Equal(t, int64(-1), quota, \"nonexistent\")\n\tassert.False(t, defined, \"nonexistent\")\n\trequire.NoError(t, err, \"nonexistent\")\n\n\tfor _, tt := range testTable {\n\t\tcgroupPath := filepath.Join(testDataCGroupsPath, tt.name)\n\t\tcgroups[_cgroupSubsysMemory] = NewCGroup(cgroupPath)\n\n\t\tquota, defined, err := cgroups.MemoryQuota()\n\t\tassert.Equal(t, tt.expectedQuota, quota, tt.name)\n\t\tassert.Equal(t, tt.expectedDefined, defined, tt.name)\n\n\t\tif tt.shouldHaveError {\n\t\t\tassert.Error(t, err, tt.name)\n\t\t} else {\n\t\t\tassert.NoError(t, err, tt.name)\n\t\t}\n\t}\n}\n\nfunc TestCGroupsIsCGroupV2(t *testing.T) {\n\ttestTable := []struct {\n\t\tname            string\n\t\texpectedIsV2    bool\n\t\tshouldHaveError bool\n\t}{\n\t\t{\n\t\t\tname:            \"cgroupv1\",\n\t\t\texpectedIsV2:    false,\n\t\t\tshouldHaveError: false,\n\t\t},\n\t\t{\n\t\t\tname:            \"cgroupv1v2\",\n\t\t\texpectedIsV2:    false,\n\t\t\tshouldHaveError: false,\n\t\t},\n\t\t{\n\t\t\tname:            \"cgroupv2\",\n\t\t\texpectedIsV2:    true,\n\t\t\tshouldHaveError: false,\n\t\t},\n\t\t{\n\t\t\tname:            \"nonexistent\",\n\t\t\texpectedIsV2:    false,\n\t\t\tshouldHaveError: true,\n\t\t},\n\t}\n\n\tfor _, tt := range testTable {\n\t\tmountInfoPath := filepath.Join(testDataProcPath, \"v2\", tt.name, \"mountinfo\")\n\t\tisV2, err := isCGroupV2(mountInfoPath)\n\n\t\tassert.Equal(t, tt.expectedIsV2, isV2, tt.name)\n\n\t\tif tt.shouldHaveError {\n\t\t\tassert.Error(t, err, tt.name)\n\t\t} else {\n\t\t\tassert.NoError(t, err, tt.name)\n\t\t}\n\t}\n}\n\nfunc TestCGroupsMemoryQuotaV2(t *testing.T) {\n\ttestTable := []struct {\n\t\tname            string\n\t\texpectedQuota   int64\n\t\texpectedDefined bool\n\t\tshouldHaveError bool\n\t}{\n\t\t{\n\t\t\tname:            \"memory\",\n\t\t\texpectedQuota:   int64(250000000),\n\t\t\texpectedDefined: true,\n\t\t\tshouldHaveError: false,\n\t\t},\n\t\t{\n\t\t\tname:            \"undefined\",\n\t\t\texpectedQuota:   int64(-1),\n\t\t\texpectedDefined: false,\n\t\t\tshouldHaveError: false,\n\t\t},\n\t\t{\n\t\t\tname:            \"invalid\",\n\t\t\texpectedQuota:   int64(-1),\n\t\t\texpectedDefined: false,\n\t\t\tshouldHaveError: true,\n\t\t},\n\t\t{\n\t\t\tname:            \"empty\",\n\t\t\texpectedQuota:   int64(-1),\n\t\t\texpectedDefined: false,\n\t\t\tshouldHaveError: true,\n\t\t},\n\t}\n\n\tquota, defined, err := memoryQuotaV2(\"nonexistent\", \"nonexistent\")\n\tassert.Equal(t, int64(-1), quota, \"nonexistent\")\n\tassert.False(t, defined, \"nonexistent\")\n\trequire.NoError(t, err, \"nonexistent\")\n\n\tcgroupBasePath := filepath.Join(testDataCGroupsPath, \"v2\")\n\tfor _, tt := range testTable {\n\t\tcgroupPath := filepath.Join(cgroupBasePath, tt.name)\n\t\tquota, defined, err := memoryQuotaV2(cgroupPath, \"memory.max\")\n\t\tassert.Equal(t, tt.expectedQuota, quota, tt.name)\n\t\tassert.Equal(t, tt.expectedDefined, defined, tt.name)\n\n\t\tif tt.shouldHaveError {\n\t\t\tassert.Error(t, err, tt.name)\n\t\t} else {\n\t\t\tassert.NoError(t, err, tt.name)\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Keep the original Uber license.\n\n// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n// Package cgroups provides utilities to access Linux control group (CGroups)\n// parameters (total memory, for example) for a given process.\n// The original implementation is taken from https://github.com/uber-go/automaxprocs\npackage cgroups // import \"go.opentelemetry.io/collector/internal/memorylimiter/cgroups\"\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/errors.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Keep the original Uber license.\n\n// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n//go:build linux\n\npackage cgroups // import \"go.opentelemetry.io/collector/internal/memorylimiter/cgroups\"\n\nimport \"fmt\"\n\ntype cgroupSubsysFormatInvalidError struct {\n\tline string\n}\n\ntype mountPointFormatInvalidError struct {\n\tline string\n}\n\ntype pathNotExposedFromMountPointError struct {\n\tmountPoint string\n\troot       string\n\tpath       string\n}\n\nfunc (err cgroupSubsysFormatInvalidError) Error() string {\n\treturn fmt.Sprintf(\"invalid format for CGroupSubsys: %q\", err.line)\n}\n\nfunc (err mountPointFormatInvalidError) Error() string {\n\treturn fmt.Sprintf(\"invalid format for MountPoint: %q\", err.line)\n}\n\nfunc (err pathNotExposedFromMountPointError) Error() string {\n\treturn fmt.Sprintf(\"path %q is not a descendant of mount point root %q and cannot be exposed from %q\", err.path, err.root, err.mountPoint)\n}\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/mountpoint.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Keep the original Uber license.\n\n// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n//go:build linux\n\npackage cgroups // import \"go.opentelemetry.io/collector/internal/memorylimiter/cgroups\"\n\nimport (\n\t\"bufio\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\t_mountInfoSep               = \" \"\n\t_mountInfoOptsSep           = \",\"\n\t_mountInfoOptionalFieldsSep = \"-\"\n)\n\nconst (\n\t_miFieldIDMountID = iota\n\t_miFieldIDParentID\n\t_miFieldIDDeviceID\n\t_miFieldIDRoot\n\t_miFieldIDMountPoint\n\t_miFieldIDOptions\n\t_miFieldIDOptionalFields\n\n\t_miFieldCountFirstHalf\n)\n\nconst (\n\t_miFieldOffsetFSType = iota\n\t_miFieldOffsetMountSource\n\t_miFieldOffsetSuperOptions\n\n\t_miFieldCountSecondHalf\n)\n\nconst _miFieldCountMin = _miFieldCountFirstHalf + _miFieldCountSecondHalf\n\n// MountPoint is the data structure for the mount points in\n// `/proc/$PID/mountinfo`. See also proc(5) for more information.\ntype MountPoint struct {\n\tMountID        int\n\tParentID       int\n\tDeviceID       string\n\tRoot           string\n\tMountPoint     string\n\tOptions        []string\n\tOptionalFields []string\n\tFSType         string\n\tMountSource    string\n\tSuperOptions   []string\n}\n\n// NewMountPointFromLine parses a line read from `/proc/$PID/mountinfo` and\n// returns a new *MountPoint.\nfunc NewMountPointFromLine(line string) (*MountPoint, error) {\n\tfields := strings.Split(line, _mountInfoSep)\n\n\tif len(fields) < _miFieldCountMin {\n\t\treturn nil, mountPointFormatInvalidError{line}\n\t}\n\n\tmountID, err := strconv.Atoi(fields[_miFieldIDMountID])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tparentID, err := strconv.Atoi(fields[_miFieldIDParentID])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfor i, field := range fields[_miFieldIDOptionalFields:] {\n\t\tif field != _mountInfoOptionalFieldsSep {\n\t\t\tcontinue\n\t\t}\n\t\tfsTypeStart := _miFieldIDOptionalFields + i + 1\n\n\t\tif len(fields) != fsTypeStart+_miFieldCountSecondHalf {\n\t\t\treturn nil, mountPointFormatInvalidError{line}\n\t\t}\n\n\t\tmiFieldIDFSType := _miFieldOffsetFSType + fsTypeStart\n\t\tmiFieldIDMountSource := _miFieldOffsetMountSource + fsTypeStart\n\t\tmiFieldIDSuperOptions := _miFieldOffsetSuperOptions + fsTypeStart\n\n\t\treturn &MountPoint{\n\t\t\tMountID:        mountID,\n\t\t\tParentID:       parentID,\n\t\t\tDeviceID:       fields[_miFieldIDDeviceID],\n\t\t\tRoot:           fields[_miFieldIDRoot],\n\t\t\tMountPoint:     fields[_miFieldIDMountPoint],\n\t\t\tOptions:        strings.Split(fields[_miFieldIDOptions], _mountInfoOptsSep),\n\t\t\tOptionalFields: fields[_miFieldIDOptionalFields:(fsTypeStart - 1)],\n\t\t\tFSType:         fields[miFieldIDFSType],\n\t\t\tMountSource:    fields[miFieldIDMountSource],\n\t\t\tSuperOptions:   strings.Split(fields[miFieldIDSuperOptions], _mountInfoOptsSep),\n\t\t}, nil\n\t}\n\n\treturn nil, mountPointFormatInvalidError{line}\n}\n\n// Translate converts an absolute path inside the *MountPoint's file system to\n// the host file system path in the mount namespace the *MountPoint belongs to.\nfunc (mp *MountPoint) Translate(absPath string) (string, error) {\n\trelPath, err := filepath.Rel(mp.Root, absPath)\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\tif relPath == \"..\" || strings.HasPrefix(relPath, \"../\") {\n\t\treturn \"\", pathNotExposedFromMountPointError{\n\t\t\tmountPoint: mp.MountPoint,\n\t\t\troot:       mp.Root,\n\t\t\tpath:       absPath,\n\t\t}\n\t}\n\n\treturn filepath.Join(mp.MountPoint, relPath), nil\n}\n\n// parseMountInfo parses procPathMountInfo (usually at `/proc/$PID/mountinfo`)\n// and yields parsed *MountPoint into newMountPoint.\nfunc parseMountInfo(procPathMountInfo string, newMountPoint func(*MountPoint) error) error {\n\tmountInfoFile, err := os.Open(filepath.Clean(procPathMountInfo))\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefer mountInfoFile.Close()\n\n\tscanner := bufio.NewScanner(mountInfoFile)\n\n\tfor scanner.Scan() {\n\t\tmountPoint, err := NewMountPointFromLine(scanner.Text())\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := newMountPoint(mountPoint); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn scanner.Err()\n}\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/mountpoint_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Keep the original Uber license.\n\n// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n//go:build linux\n\npackage cgroups\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestNewMountPointFromLine(t *testing.T) {\n\ttestTable := []struct {\n\t\tname     string\n\t\tline     string\n\t\texpected *MountPoint\n\t}{\n\t\t{\n\t\t\tname: \"root\",\n\t\t\tline: \"1 0 252:0 / / rw,noatime - ext4 /dev/dm-0 rw,errors=remount-ro,data=ordered\",\n\t\t\texpected: &MountPoint{\n\t\t\t\tMountID:        1,\n\t\t\t\tParentID:       0,\n\t\t\t\tDeviceID:       \"252:0\",\n\t\t\t\tRoot:           \"/\",\n\t\t\t\tMountPoint:     \"/\",\n\t\t\t\tOptions:        []string{\"rw\", \"noatime\"},\n\t\t\t\tOptionalFields: []string{},\n\t\t\t\tFSType:         \"ext4\",\n\t\t\t\tMountSource:    \"/dev/dm-0\",\n\t\t\t\tSuperOptions:   []string{\"rw\", \"errors=remount-ro\", \"data=ordered\"},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"cgroup\",\n\t\t\tline: \"31 23 0:24 /docker /sys/fs/cgroup/cpu rw,nosuid,nodev,noexec,relatime shared:1 - cgroup cgroup rw,cpu\",\n\t\t\texpected: &MountPoint{\n\t\t\t\tMountID:        31,\n\t\t\t\tParentID:       23,\n\t\t\t\tDeviceID:       \"0:24\",\n\t\t\t\tRoot:           \"/docker\",\n\t\t\t\tMountPoint:     \"/sys/fs/cgroup/cpu\",\n\t\t\t\tOptions:        []string{\"rw\", \"nosuid\", \"nodev\", \"noexec\", \"relatime\"},\n\t\t\t\tOptionalFields: []string{\"shared:1\"},\n\t\t\t\tFSType:         \"cgroup\",\n\t\t\t\tMountSource:    \"cgroup\",\n\t\t\t\tSuperOptions:   []string{\"rw\", \"cpu\"},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range testTable {\n\t\tmountPoint, err := NewMountPointFromLine(tt.line)\n\t\tassert.Equal(t, tt.expected, mountPoint, tt.name)\n\t\tassert.NoError(t, err, tt.name)\n\t}\n}\n\nfunc TestNewMountPointFromLineErr(t *testing.T) {\n\tlinesWithInvalidIDs := []string{\n\t\t\"invalidMountID 0 252:0 / / rw,noatime - ext4 /dev/dm-0 rw,errors=remount-ro,data=ordered\",\n\t\t\"1 invalidParentID 252:0 / / rw,noatime - ext4 /dev/dm-0 rw,errors=remount-ro,data=ordered\",\n\t\t\"invalidMountID invalidParentID 252:0 / / rw,noatime - ext4 /dev/dm-0 rw,errors=remount-ro,data=ordered\",\n\t}\n\n\tfor i, line := range linesWithInvalidIDs {\n\t\tmountPoint, err := NewMountPointFromLine(line)\n\t\tassert.Nil(t, mountPoint, \"[%d] %q\", i, line)\n\t\trequire.Error(t, err, line)\n\t}\n\n\tlinesWithInvalidFields := []string{\n\t\t\"1 0 252:0 / / rw,noatime ext4 /dev/dm-0 rw,errors=remount-ro,data=ordered\",\n\t\t\"1 0 252:0 / / rw,noatime shared:1 - ext4 /dev/dm-0\",\n\t\t\"1 0 252:0 / / rw,noatime shared:1 ext4 - /dev/dm-0 rw,errors=remount-ro,data=ordered\",\n\t\t\"1 0 252:0 / / rw,noatime shared:1 ext4 /dev/dm-0 rw,errors=remount-ro,data=ordered\",\n\t\t\"random line\",\n\t}\n\n\tfor i, line := range linesWithInvalidFields {\n\t\tmountPoint, err := NewMountPointFromLine(line)\n\t\terrExpected := mountPointFormatInvalidError{line}\n\n\t\tassert.Nil(t, mountPoint, \"[%d] %q\", i, line)\n\t\tassert.Equal(t, errExpected, err, \"[%d] %q\", i, line)\n\t}\n}\n\nfunc TestMountPointTranslate(t *testing.T) {\n\tline := \"31 23 0:24 /docker/0123456789abcdef /sys/fs/cgroup/cpu rw,nosuid,nodev,noexec,relatime shared:1 - cgroup cgroup rw,cpu\"\n\tcgroupMountPoint, err := NewMountPointFromLine(line)\n\n\tassert.NotNil(t, cgroupMountPoint)\n\trequire.NoError(t, err)\n\n\ttestTable := []struct {\n\t\tname            string\n\t\tpathToTranslate string\n\t\tpathTranslated  string\n\t}{\n\t\t{\n\t\t\tname:            \"root\",\n\t\t\tpathToTranslate: \"/docker/0123456789abcdef\",\n\t\t\tpathTranslated:  \"/sys/fs/cgroup/cpu\",\n\t\t},\n\t\t{\n\t\t\tname:            \"root-with-extra-slash\",\n\t\t\tpathToTranslate: \"/docker/0123456789abcdef/\",\n\t\t\tpathTranslated:  \"/sys/fs/cgroup/cpu\",\n\t\t},\n\t\t{\n\t\t\tname:            \"descendant-from-root\",\n\t\t\tpathToTranslate: \"/docker/0123456789abcdef/large/cpu.cfs_quota_us\",\n\t\t\tpathTranslated:  \"/sys/fs/cgroup/cpu/large/cpu.cfs_quota_us\",\n\t\t},\n\t}\n\n\tfor _, tt := range testTable {\n\t\tpath, err := cgroupMountPoint.Translate(tt.pathToTranslate)\n\t\tassert.Equal(t, tt.pathTranslated, path, tt.name)\n\t\tassert.NoError(t, err, tt.name)\n\t}\n}\n\nfunc TestMountPointTranslateError(t *testing.T) {\n\tline := \"31 23 0:24 /docker/0123456789abcdef /sys/fs/cgroup/cpu rw,nosuid,nodev,noexec,relatime shared:1 - cgroup cgroup rw,cpu\"\n\tcgroupMountPoint, err := NewMountPointFromLine(line)\n\n\tassert.NotNil(t, cgroupMountPoint)\n\trequire.NoError(t, err)\n\n\tinaccessiblePaths := []string{\n\t\t\"/\",\n\t\t\"/docker\",\n\t\t\"/docker/0123456789abcdef-let-me-hack-this-path\",\n\t\t\"/docker/0123456789abcde/abc/../../def\",\n\t\t\"/system.slice/docker.service\",\n\t}\n\n\tfor i, path := range inaccessiblePaths {\n\t\ttranslated, err := cgroupMountPoint.Translate(path)\n\t\terrExpected := pathNotExposedFromMountPointError{\n\t\t\tmountPoint: cgroupMountPoint.MountPoint,\n\t\t\troot:       cgroupMountPoint.Root,\n\t\t\tpath:       path,\n\t\t}\n\n\t\tassert.Empty(t, translated, \"inaccessiblePaths[%d] == %q\", i, path)\n\t\tassert.Equal(t, errExpected, err, \"inaccessiblePaths[%d] == %q\", i, path)\n\t}\n\n\trelPaths := []string{\n\t\t\"docker\",\n\t\t\"docker/0123456789abcde/large\",\n\t\t\"system.slice/docker.service\",\n\t}\n\n\tfor i, path := range relPaths {\n\t\ttranslated, err := cgroupMountPoint.Translate(path)\n\n\t\tassert.Empty(t, translated, \"relPaths[%d] == %q\", i, path)\n\t\tassert.Error(t, err, path)\n\t}\n}\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage cgroups\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/subsys.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Keep the original Uber license.\n\n// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n//go:build linux\n\npackage cgroups // import \"go.opentelemetry.io/collector/internal/memorylimiter/cgroups\"\n\nimport (\n\t\"bufio\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strconv\"\n\t\"strings\"\n)\n\nconst (\n\t_cgroupSep       = \":\"\n\t_cgroupSubsysSep = \",\"\n)\n\nconst (\n\t_csFieldIDID = iota\n\t_csFieldIDSubsystems\n\t_csFieldIDName\n\t_csFieldCount\n)\n\n// CGroupSubsys represents the data structure for entities in\n// `/proc/$PID/cgroup`. See also proc(5) for more information.\ntype CGroupSubsys struct {\n\tID         int\n\tSubsystems []string\n\tName       string\n}\n\n// NewCGroupSubsysFromLine returns a new *CGroupSubsys by parsing a string in\n// the format of `/proc/$PID/cgroup`\nfunc NewCGroupSubsysFromLine(line string) (*CGroupSubsys, error) {\n\tfields := strings.SplitN(line, _cgroupSep, _csFieldCount)\n\n\tif len(fields) != _csFieldCount {\n\t\treturn nil, cgroupSubsysFormatInvalidError{line}\n\t}\n\n\tid, err := strconv.Atoi(fields[_csFieldIDID])\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcgroup := &CGroupSubsys{\n\t\tID:         id,\n\t\tSubsystems: strings.Split(fields[_csFieldIDSubsystems], _cgroupSubsysSep),\n\t\tName:       fields[_csFieldIDName],\n\t}\n\n\treturn cgroup, nil\n}\n\n// parseCGroupSubsystems parses procPathCGroup (usually at `/proc/$PID/cgroup`)\n// and returns a new map[string]*CGroupSubsys.\nfunc parseCGroupSubsystems(procPathCGroup string) (map[string]*CGroupSubsys, error) {\n\tcgroupFile, err := os.Open(filepath.Clean(procPathCGroup))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tdefer cgroupFile.Close()\n\n\tscanner := bufio.NewScanner(cgroupFile)\n\tsubsystems := make(map[string]*CGroupSubsys)\n\n\tfor scanner.Scan() {\n\t\tcgroup, err := NewCGroupSubsysFromLine(scanner.Text())\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tfor _, subsys := range cgroup.Subsystems {\n\t\t\tsubsystems[subsys] = cgroup\n\t\t}\n\t}\n\n\tif err := scanner.Err(); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn subsystems, nil\n}\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/subsys_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Keep the original Uber license.\n\n// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n//go:build linux\n\npackage cgroups\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestNewCGroupSubsysFromLine(t *testing.T) {\n\ttestTable := []struct {\n\t\tname           string\n\t\tline           string\n\t\texpectedSubsys *CGroupSubsys\n\t}{\n\t\t{\n\t\t\tname: \"single-subsys\",\n\t\t\tline: \"1:cpu:/\",\n\t\t\texpectedSubsys: &CGroupSubsys{\n\t\t\t\tID:         1,\n\t\t\t\tSubsystems: []string{\"cpu\"},\n\t\t\t\tName:       \"/\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"multi-subsys\",\n\t\t\tline: \"8:cpu,cpuacct,cpuset:/docker/1234567890abcdef\",\n\t\t\texpectedSubsys: &CGroupSubsys{\n\t\t\t\tID:         8,\n\t\t\t\tSubsystems: []string{\"cpu\", \"cpuacct\", \"cpuset\"},\n\t\t\t\tName:       \"/docker/1234567890abcdef\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"sophisticated-path\",\n\t\t\tline: \"4:pids:/example.slice:extra-path-designator\",\n\t\t\texpectedSubsys: &CGroupSubsys{\n\t\t\t\tID:         4,\n\t\t\t\tSubsystems: []string{\"pids\"},\n\t\t\t\tName:       \"/example.slice:extra-path-designator\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range testTable {\n\t\tsubsys, err := NewCGroupSubsysFromLine(tt.line)\n\t\tassert.Equal(t, tt.expectedSubsys, subsys, tt.name)\n\t\tassert.NoError(t, err, tt.name)\n\t}\n}\n\nfunc TestNewCGroupSubsysFromLineErr(t *testing.T) {\n\tlines := []string{\n\t\t\"1:cpu\",\n\t\t\"not-a-number:cpu:/\",\n\t}\n\t_, parseError := strconv.Atoi(\"not-a-number\")\n\n\ttestTable := []struct {\n\t\tname          string\n\t\tline          string\n\t\texpectedError error\n\t}{\n\t\t{\n\t\t\tname:          \"fewer-fields\",\n\t\t\tline:          lines[0],\n\t\t\texpectedError: cgroupSubsysFormatInvalidError{lines[0]},\n\t\t},\n\t\t{\n\t\t\tname:          \"illegal-id\",\n\t\t\tline:          lines[1],\n\t\t\texpectedError: parseError,\n\t\t},\n\t}\n\n\tfor _, tt := range testTable {\n\t\tsubsys, err := NewCGroupSubsysFromLine(tt.line)\n\t\tassert.Nil(t, subsys, tt.name)\n\t\tassert.Equal(t, tt.expectedError, err, tt.name)\n\t}\n}\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/cgroups/cpu/cpu.cfs_period_us",
    "content": "100000\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/cgroups/cpu/cpu.cfs_quota_us",
    "content": "600000\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/cgroups/empty/cpu.cfs_quota_us",
    "content": ""
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/cgroups/invalid/cpu.cfs_quota_us",
    "content": "non-an-integer\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/cgroups/memory/memory.limit_in_bytes",
    "content": "8796093018112\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/cgroups/undefined/cpu.cfs_period_us",
    "content": "100000\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/cgroups/undefined/cpu.cfs_quota_us",
    "content": "-1\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/cgroups/undefined-period/cpu.cfs_quota_us",
    "content": "800000\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/cgroups/v2/empty/memory.max",
    "content": ""
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/cgroups/v2/invalid/memory.max",
    "content": "ngn\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/cgroups/v2/memory/memory.max",
    "content": "250000000\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/cgroups/v2/undefined/memory.max",
    "content": "max\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/proc/cgroups/cgroup",
    "content": "3:memory:/docker/large\n2:cpu,cpuacct:/docker\n1:cpuset:/\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/proc/cgroups/mountinfo",
    "content": "1 0 8:1 / / rw,noatime shared:1 - ext4 /dev/sda1 rw,errors=remount-ro,data=reordered\n2 1 0:1 / /dev rw,relatime shared:2 - devtmpfs udev rw,size=10240k,nr_inodes=16487629,mode=755\n3 1 0:2 / /proc rw,nosuid,nodev,noexec,relatime shared:3 - proc proc rw\n4 1 0:3 / /sys rw,nosuid,nodev,noexec,relatime shared:4 - sysfs sysfs rw\n5 4 0:4 / /sys/fs/cgroup ro,nosuid,nodev,noexec shared:5 - tmpfs tmpfs ro,mode=755\n6 5 0:5 / /sys/fs/cgroup/cpuset rw,nosuid,nodev,noexec,relatime shared:6 - cgroup cgroup rw,cpuset\n7 5 0:6 /docker /sys/fs/cgroup/cpu,cpuacct rw,nosuid,nodev,noexec,relatime shared:7 - cgroup cgroup rw,cpu,cpuacct\n8 5 0:7 /docker /sys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime shared:8 - cgroup cgroup rw,memory\n9 1 0:8 / /var/lib/docker/overlay2/9054a95f2cf7296867089e1bd37931742a17eb3308a795d51adb2654ee2276df/merged/sys/fs/cgroup ro,nosuid,nodev,noexec,relatime - tmpfs tmpfs rw,mode=755\n10 9 0:9 /docker /var/lib/docker/overlay2/9054a95f2cf7296867089e1bd37931742a17eb3308a795d51adb2654ee2276df/merged/sys/fs/cgroup/memory ro,nosuid,nodev,noexec,relatime master:17 - cgroup cgroup rw,memory\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/proc/invalid-cgroup/cgroup",
    "content": "1:cpu:/cpu\ninvalid-line:\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/proc/invalid-mountinfo/mountinfo",
    "content": "1 0 8:1 / / rw,noatime shared:1 - ext4 /dev/sda1\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/proc/untranslatable/cgroup",
    "content": "1:cpu:/docker\n2:cpuacct:/docker\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/proc/untranslatable/mountinfo",
    "content": "31 23 0:24 / /sys/fs/cgroup/cpu rw,nosuid,nodev,noexec,relatime shared:1 - cgroup cgroup rw,cpu\n32 23 0:25 /docker/0123456789abcdef /sys/fs/cgroup/cpuacct rw,nosuid,nodev,noexec,relatime shared:2 - cgroup cgroup rw,cpuacct\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/proc/v2/cgroupv1/mountinfo",
    "content": "1 0 8:1 / / rw,noatime shared:1 - ext4 /dev/sda1 rw,errors=remount-ro,data=reordered\n2 1 0:1 / /dev rw,relatime shared:2 - devtmpfs udev rw,size=10240k,nr_inodes=16487629,mode=755\n3 1 0:2 / /proc rw,nosuid,nodev,noexec,relatime shared:3 - proc proc rw\n4 1 0:3 / /sys rw,nosuid,nodev,noexec,relatime shared:4 - sysfs sysfs rw\n5 4 0:4 / /sys/fs/cgroup ro,nosuid,nodev,noexec shared:5 - tmpfs tmpfs ro,mode=755\n6 5 0:5 / /sys/fs/cgroup/cpuset rw,nosuid,nodev,noexec,relatime shared:6 - cgroup cgroup rw,cpuset\n7 5 0:6 /docker /sys/fs/cgroup/cpu,cpuacct rw,nosuid,nodev,noexec,relatime shared:7 - cgroup cgroup rw,cpu,cpuacct\n8 5 0:7 /docker /sys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime shared:8 - cgroup cgroup rw,memory\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/proc/v2/cgroupv1v2/mountinfo",
    "content": "33 24 0:28 / /sys/fs/cgroup ro,nosuid,nodev,noexec shared:9 - tmpfs tmpfs ro,mode=755,inode64\n34 33 0:29 / /sys/fs/cgroup/unified rw,nosuid,nodev,noexec,relatime shared:10 - cgroup2 cgroup2 rw,nsdelegate\n35 33 0:30 / /sys/fs/cgroup/systemd rw,nosuid,nodev,noexec,relatime shared:11 - cgroup cgroup rw,xattr,name=systemd\n39 33 0:34 / /sys/fs/cgroup/misc rw,nosuid,nodev,noexec,relatime shared:16 - cgroup cgroup rw,misc\n40 33 0:35 / /sys/fs/cgroup/net_cls,net_prio rw,nosuid,nodev,noexec,relatime shared:17 - cgroup cgroup rw,net_cls,net_prio\n41 33 0:36 / /sys/fs/cgroup/rdma rw,nosuid,nodev,noexec,relatime shared:18 - cgroup cgroup rw,rdma\n42 33 0:37 / /sys/fs/cgroup/memory rw,nosuid,nodev,noexec,relatime shared:19 - cgroup cgroup rw,memory\n43 33 0:38 / /sys/fs/cgroup/blkio rw,nosuid,nodev,noexec,relatime shared:20 - cgroup cgroup rw,blkio\n44 33 0:39 / /sys/fs/cgroup/cpu,cpuacct rw,nosuid,nodev,noexec,relatime shared:21 - cgroup cgroup rw,cpu,cpuacct\n45 33 0:40 / /sys/fs/cgroup/pids rw,nosuid,nodev,noexec,relatime shared:22 - cgroup cgroup rw,pids\n46 33 0:41 / /sys/fs/cgroup/hugetlb rw,nosuid,nodev,noexec,relatime shared:23 - cgroup cgroup rw,hugetlb\n47 33 0:42 / /sys/fs/cgroup/freezer rw,nosuid,nodev,noexec,relatime shared:24 - cgroup cgroup rw,freezer\n48 33 0:43 / /sys/fs/cgroup/perf_event rw,nosuid,nodev,noexec,relatime shared:25 - cgroup cgroup rw,perf_event\n49 33 0:44 / /sys/fs/cgroup/devices rw,nosuid,nodev,noexec,relatime shared:26 - cgroup cgroup rw,devices\n50 33 0:45 / /sys/fs/cgroup/cpuset rw,nosuid,nodev,noexec,relatime shared:27 - cgroup cgroup rw,cpuset\n"
  },
  {
    "path": "internal/memorylimiter/cgroups/testdata/proc/v2/cgroupv2/mountinfo",
    "content": "34 33 0:29 / /sys/fs/cgroup rw,nosuid,nodev,noexec,relatime shared:10 - cgroup2 cgroup rw,nsdelegate"
  },
  {
    "path": "internal/memorylimiter/cgroups/util_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Keep the original Uber license.\n\n// Copyright (c) 2017 Uber Technologies, Inc.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in\n// all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n// THE SOFTWARE.\n\n//go:build linux\n\npackage cgroups\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n)\n\nvar (\n\tpwd                 = mustGetWd()\n\ttestDataPath        = filepath.Join(pwd, \"testdata\")\n\ttestDataCGroupsPath = filepath.Join(testDataPath, \"cgroups\")\n\ttestDataProcPath    = filepath.Join(testDataPath, \"proc\")\n)\n\nfunc mustGetWd() string {\n\tpwd, err := os.Getwd()\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\treturn pwd\n}\n"
  },
  {
    "path": "internal/memorylimiter/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage memorylimiter // import \"go.opentelemetry.io/collector/internal/memorylimiter\"\n\nimport (\n\t\"errors\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\terrCheckIntervalOutOfRange        = errors.New(\"'check_interval' must be greater than zero\")\n\terrInconsistentGCMinInterval      = errors.New(\"'min_gc_interval_when_soft_limited' should be larger than 'min_gc_interval_when_hard_limited'\")\n\terrLimitOutOfRange                = errors.New(\"'limit_mib' or 'limit_percentage' must be greater than zero\")\n\terrSpikeLimitOutOfRange           = errors.New(\"'spike_limit_mib' must be smaller than 'limit_mib'\")\n\terrSpikeLimitPercentageOutOfRange = errors.New(\"'spike_limit_percentage' must be smaller than 'limit_percentage'\")\n\terrLimitPercentageOutOfRange      = errors.New(\n\t\t\"'limit_percentage' and 'spike_limit_percentage' must be greater than zero and less than or equal to hundred\")\n)\n\n// Config defines configuration for memory memoryLimiter processor.\ntype Config struct {\n\t// CheckInterval is the time between measurements of memory usage for the\n\t// purposes of avoiding going over the limits. Defaults to zero, so no\n\t// checks will be performed.\n\tCheckInterval time.Duration `mapstructure:\"check_interval\"`\n\n\t// MinGCIntervalWhenSoftLimited minimum interval between forced GC when in soft (=limit_mib - spike_limit_mib) limited mode.\n\t// Zero value means no minimum interval.\n\t// GCs is a CPU-heavy operation and executing it too frequently may affect the recovery capabilities of the collector.\n\tMinGCIntervalWhenSoftLimited time.Duration `mapstructure:\"min_gc_interval_when_soft_limited\"`\n\n\t// MinGCIntervalWhenHardLimited minimum interval between forced GC when in hard (=limit_mib) limited mode.\n\t// Zero value means no minimum interval.\n\t// GCs is a CPU-heavy operation and executing it too frequently may affect the recovery capabilities of the collector.\n\tMinGCIntervalWhenHardLimited time.Duration `mapstructure:\"min_gc_interval_when_hard_limited\"`\n\n\t// MemoryLimitMiB is the maximum amount of memory, in MiB, targeted to be\n\t// allocated by the process.\n\tMemoryLimitMiB uint32 `mapstructure:\"limit_mib\"`\n\n\t// MemorySpikeLimitMiB is the maximum, in MiB, spike expected between the\n\t// measurements of memory usage.\n\tMemorySpikeLimitMiB uint32 `mapstructure:\"spike_limit_mib\"`\n\n\t// MemoryLimitPercentage is the maximum amount of memory, in %, targeted to be\n\t// allocated by the process. The fixed memory settings MemoryLimitMiB has a higher precedence.\n\tMemoryLimitPercentage uint32 `mapstructure:\"limit_percentage\"`\n\n\t// MemorySpikePercentage is the maximum, in percents against the total memory,\n\t// spike expected between the measurements of memory usage.\n\tMemorySpikePercentage uint32 `mapstructure:\"spike_limit_percentage\"`\n}\n\nvar _ component.Config = (*Config)(nil)\n\nfunc NewDefaultConfig() *Config {\n\treturn &Config{\n\t\tMinGCIntervalWhenSoftLimited: 10 * time.Second,\n\t}\n}\n\n// Validate checks if the processor configuration is valid\nfunc (cfg *Config) Validate() error {\n\tif cfg.CheckInterval <= 0 {\n\t\treturn errCheckIntervalOutOfRange\n\t}\n\tif cfg.MinGCIntervalWhenSoftLimited < cfg.MinGCIntervalWhenHardLimited {\n\t\treturn errInconsistentGCMinInterval\n\t}\n\tif cfg.MemoryLimitMiB == 0 && cfg.MemoryLimitPercentage == 0 {\n\t\treturn errLimitOutOfRange\n\t}\n\tif cfg.MemoryLimitPercentage > 100 || cfg.MemorySpikePercentage > 100 {\n\t\treturn errLimitPercentageOutOfRange\n\t}\n\tif cfg.MemoryLimitMiB > 0 && cfg.MemoryLimitMiB <= cfg.MemorySpikeLimitMiB {\n\t\treturn errSpikeLimitOutOfRange\n\t}\n\tif cfg.MemoryLimitPercentage > 0 && cfg.MemoryLimitPercentage <= cfg.MemorySpikePercentage {\n\t\treturn errSpikeLimitPercentageOutOfRange\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "internal/memorylimiter/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage memorylimiter\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n)\n\nfunc TestUnmarshalConfig(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tcfg := &Config{}\n\tassert.NoError(t, cm.Unmarshal(&cfg))\n\tassert.Equal(t,\n\t\t&Config{\n\t\t\tCheckInterval:       5 * time.Second,\n\t\t\tMemoryLimitMiB:      4000,\n\t\t\tMemorySpikeLimitMiB: 500,\n\t\t}, cfg)\n}\n\nfunc TestConfigValidate(t *testing.T) {\n\ttests := []struct {\n\t\tname string\n\t\tcfg  *Config\n\t\terr  error\n\t}{\n\t\t{\n\t\t\tname: \"valid\",\n\t\t\tcfg: &Config{\n\t\t\t\tMemoryLimitMiB:      5722,\n\t\t\t\tMemorySpikeLimitMiB: 1907,\n\t\t\t\tCheckInterval:       100 * time.Millisecond,\n\t\t\t},\n\t\t\terr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"zero check interval\",\n\t\t\tcfg: &Config{\n\t\t\t\tCheckInterval: 0,\n\t\t\t},\n\t\t\terr: errCheckIntervalOutOfRange,\n\t\t},\n\t\t{\n\t\t\tname: \"unset memory limit\",\n\t\t\tcfg: &Config{\n\t\t\t\tCheckInterval:         1 * time.Second,\n\t\t\t\tMemoryLimitMiB:        0,\n\t\t\t\tMemoryLimitPercentage: 0,\n\t\t\t},\n\t\t\terr: errLimitOutOfRange,\n\t\t},\n\t\t{\n\t\t\tname: \"invalid memory spike limit\",\n\t\t\tcfg: &Config{\n\t\t\t\tCheckInterval:       1 * time.Second,\n\t\t\t\tMemoryLimitMiB:      10,\n\t\t\t\tMemorySpikeLimitMiB: 10,\n\t\t\t},\n\t\t\terr: errSpikeLimitOutOfRange,\n\t\t},\n\t\t{\n\t\t\tname: \"invalid memory percentage limit\",\n\t\t\tcfg: &Config{\n\t\t\t\tCheckInterval:         1 * time.Second,\n\t\t\t\tMemoryLimitPercentage: 101,\n\t\t\t},\n\t\t\terr: errLimitPercentageOutOfRange,\n\t\t},\n\t\t{\n\t\t\tname: \"invalid memory spike percentage limit\",\n\t\t\tcfg: &Config{\n\t\t\t\tCheckInterval:         1 * time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 60,\n\t\t\t},\n\t\t\terr: errSpikeLimitPercentageOutOfRange,\n\t\t},\n\t\t{\n\t\t\tname: \"invalid gc intervals\",\n\t\t\tcfg: &Config{\n\t\t\t\tCheckInterval:                100 * time.Millisecond,\n\t\t\t\tMinGCIntervalWhenSoftLimited: 50 * time.Millisecond,\n\t\t\t\tMinGCIntervalWhenHardLimited: 100 * time.Millisecond,\n\t\t\t\tMemoryLimitMiB:               5722,\n\t\t\t\tMemorySpikeLimitMiB:          1907,\n\t\t\t},\n\t\t\terr: errInconsistentGCMinInterval,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := tt.cfg.Validate()\n\t\t\tassert.Equal(t, tt.err, err)\n\t\t})\n\t}\n}\n\nfunc TestUnmarshalInvalidConfig(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"negative_unsigned_limits_config.yaml\"))\n\trequire.NoError(t, err)\n\tcfg := &Config{}\n\terr = cm.Unmarshal(&cfg)\n\trequire.ErrorContains(t, err, \"'limit_mib' cannot parse value as 'uint32': -2000 overflows uint\")\n\trequire.ErrorContains(t, err, \"'spike_limit_mib' cannot parse value as 'uint32': -2300 overflows uint\")\n}\n"
  },
  {
    "path": "internal/memorylimiter/go.mod",
    "content": "module go.opentelemetry.io/collector/internal/memorylimiter\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/shirou/gopsutil/v4 v4.26.2\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/zap v1.27.1\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/ebitengine/purego v0.10.0 // indirect\n\tgithub.com/go-ole/go-ole v1.2.6 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect\n\tgithub.com/tklauser/go-sysconf v0.3.16 // indirect\n\tgithub.com/tklauser/numcpus v0.11.0 // indirect\n\tgithub.com/yusufpapurcu/wmi v1.2.4 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../testutil\n"
  },
  {
    "path": "internal/memorylimiter/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=\ngithub.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=\ngithub.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3 h1:PwQumkgq4/acIiZhtifTV5OUqqiP82UAl0h87xj/l9k=\ngithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/shirou/gopsutil/v4 v4.26.2 h1:X8i6sicvUFih4BmYIGT1m2wwgw2VG9YgrDTi7cIRGUI=\ngithub.com/shirou/gopsutil/v4 v4.26.2/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngithub.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYICU0nA=\ngithub.com/tklauser/go-sysconf v0.3.16/go.mod h1:/qNL9xxDhc7tx3HSRsLWNnuzbVfh3e7gh/BmM179nYI=\ngithub.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9RXw=\ngithub.com/tklauser/numcpus v0.11.0/go.mod h1:z+LwcLq54uWZTX0u/bGobaV34u6V7KNlTZejzM6/3MQ=\ngithub.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=\ngithub.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "internal/memorylimiter/iruntime/mem_info.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage iruntime // import \"go.opentelemetry.io/collector/internal/memorylimiter/iruntime\"\n\nimport (\n\t\"github.com/shirou/gopsutil/v4/mem\"\n)\n\n// readMemInfo returns the total memory\n// supports in linux, darwin and windows\nfunc readMemInfo() (uint64, error) {\n\tvmStat, err := mem.VirtualMemory()\n\treturn vmStat.Total, err\n}\n"
  },
  {
    "path": "internal/memorylimiter/iruntime/mem_info_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage iruntime\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestReadMemInfo(t *testing.T) {\n\tvmStat, err := readMemInfo()\n\trequire.NoError(t, err)\n\tassert.Positive(t, vmStat)\n}\n"
  },
  {
    "path": "internal/memorylimiter/iruntime/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage iruntime\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "internal/memorylimiter/iruntime/total_memory_linux.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build linux\n\npackage iruntime // import \"go.opentelemetry.io/collector/internal/memorylimiter/iruntime\"\n\nimport \"go.opentelemetry.io/collector/internal/memorylimiter/cgroups\"\n\n// unlimitedMemorySize defines the bytes size when memory limit is not set\n// for the container and process with cgroups\nconst unlimitedMemorySize = 9223372036854771712\n\n// TotalMemory returns total available memory.\n// This implementation is meant for linux and uses cgroups to determine available memory.\nfunc TotalMemory() (uint64, error) {\n\tvar memoryQuota int64\n\tvar defined bool\n\tvar err error\n\n\tisV2, err := cgroups.IsCGroupV2()\n\tif err != nil {\n\t\treturn 0, err\n\t}\n\n\tif isV2 {\n\t\tmemoryQuota, defined, err = cgroups.MemoryQuotaV2()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t} else {\n\t\tcgv1, err := cgroups.NewCGroupsForCurrentProcess()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tmemoryQuota, defined, err = cgv1.MemoryQuota()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\n\t// If memory is not defined or is set to unlimitedMemorySize (v1 unset),\n\t// we fallback to /proc/meminfo.\n\tif memoryQuota == unlimitedMemorySize || !defined {\n\t\ttotalMem, err := readMemInfo()\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\treturn totalMem, nil\n\t}\n\n\treturn uint64(memoryQuota), nil\n}\n"
  },
  {
    "path": "internal/memorylimiter/iruntime/total_memory_linux_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build linux\n\npackage iruntime\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestTotalMemory(t *testing.T) {\n\ttotalMemory, err := TotalMemory()\n\trequire.NoError(t, err)\n\tassert.Positive(t, totalMemory)\n}\n"
  },
  {
    "path": "internal/memorylimiter/iruntime/total_memory_other.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build !linux\n\npackage iruntime // import \"go.opentelemetry.io/collector/internal/memorylimiter/iruntime\"\n\n// TotalMemory returns total available memory for non-linux platforms.\nfunc TotalMemory() (uint64, error) {\n\treturn readMemInfo()\n}\n"
  },
  {
    "path": "internal/memorylimiter/iruntime/total_memory_other_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build !linux\n\npackage iruntime\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestTotalMemory(t *testing.T) {\n\ttotalMemory, err := TotalMemory()\n\trequire.NoError(t, err)\n\tassert.Positive(t, totalMemory)\n}\n"
  },
  {
    "path": "internal/memorylimiter/memorylimiter.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage memorylimiter // import \"go.opentelemetry.io/collector/internal/memorylimiter\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"time\"\n\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/internal/memorylimiter/iruntime\"\n)\n\nconst (\n\tmibBytes = 1024 * 1024\n)\n\nvar (\n\t// ErrDataRefused will be returned to callers of ConsumeTraceData to indicate\n\t// that data is being refused due to high memory usage.\n\tErrDataRefused = errors.New(\"data refused due to high memory usage\")\n\n\t// GetMemoryFn and ReadMemStatsFn make it overridable by tests\n\tGetMemoryFn    = iruntime.TotalMemory\n\tReadMemStatsFn = runtime.ReadMemStats\n)\n\n// MemoryLimiter is used to prevent out of memory situations on the collector.\ntype MemoryLimiter struct {\n\tusageChecker memUsageChecker\n\n\tmemCheckWait time.Duration\n\n\t// mustRefuse is used to indicate when data should be refused.\n\tmustRefuse *atomic.Bool\n\n\tticker *time.Ticker\n\n\tminGCIntervalWhenSoftLimited time.Duration\n\tminGCIntervalWhenHardLimited time.Duration\n\tlastGCDone                   time.Time\n\n\t// The functions to read the mem values and run GC are set as a reference to help with\n\t// testing different values.\n\treadMemStatsFn func(m *runtime.MemStats)\n\trunGCFn        func()\n\n\t// Fields used for logging.\n\tlogger *zap.Logger\n\n\trefCounterLock sync.Mutex\n\trefCounter     int\n\twaitGroup      sync.WaitGroup\n\tclosed         chan struct{}\n}\n\n// NewMemoryLimiter returns a new memory limiter component\nfunc NewMemoryLimiter(cfg *Config, logger *zap.Logger) (*MemoryLimiter, error) {\n\tusageChecker, err := getMemUsageChecker(cfg, logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tlogger.Info(\"Memory limiter configured\",\n\t\tzap.Uint64(\"limit_mib\", usageChecker.memAllocLimit/mibBytes),\n\t\tzap.Uint64(\"spike_limit_mib\", usageChecker.memSpikeLimit/mibBytes),\n\t\tzap.Duration(\"check_interval\", cfg.CheckInterval))\n\n\treturn &MemoryLimiter{\n\t\tusageChecker:                 *usageChecker,\n\t\tmemCheckWait:                 cfg.CheckInterval,\n\t\tticker:                       time.NewTicker(cfg.CheckInterval),\n\t\tminGCIntervalWhenSoftLimited: cfg.MinGCIntervalWhenSoftLimited,\n\t\tminGCIntervalWhenHardLimited: cfg.MinGCIntervalWhenHardLimited,\n\t\tlastGCDone:                   time.Now(),\n\t\treadMemStatsFn:               ReadMemStatsFn,\n\t\trunGCFn:                      runtime.GC,\n\t\tlogger:                       logger,\n\t\tmustRefuse:                   &atomic.Bool{},\n\t}, nil\n}\n\nfunc (ml *MemoryLimiter) Start(_ context.Context, _ component.Host) error {\n\tml.refCounterLock.Lock()\n\tdefer ml.refCounterLock.Unlock()\n\n\tml.refCounter++\n\tif ml.refCounter == 1 {\n\t\tml.closed = make(chan struct{})\n\t\tml.waitGroup.Go(func() {\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase <-ml.ticker.C:\n\t\t\t\tcase <-ml.closed:\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\t\tml.CheckMemLimits()\n\t\t\t}\n\t\t})\n\t}\n\treturn nil\n}\n\n// Shutdown resets MemoryLimiter monitoring ticker and stop monitoring\nfunc (ml *MemoryLimiter) Shutdown(context.Context) error {\n\tml.refCounterLock.Lock()\n\tdefer ml.refCounterLock.Unlock()\n\n\tswitch ml.refCounter {\n\tcase 0:\n\t\treturn nil\n\tcase 1:\n\t\tml.ticker.Stop()\n\t\tclose(ml.closed)\n\t\tml.waitGroup.Wait()\n\t}\n\tml.refCounter--\n\treturn nil\n}\n\n// MustRefuse returns true if memory has reached its configured limits\nfunc (ml *MemoryLimiter) MustRefuse() bool {\n\treturn ml.mustRefuse.Load()\n}\n\nfunc getMemUsageChecker(cfg *Config, logger *zap.Logger) (*memUsageChecker, error) {\n\tmemAllocLimit := uint64(cfg.MemoryLimitMiB) * mibBytes\n\tmemSpikeLimit := uint64(cfg.MemorySpikeLimitMiB) * mibBytes\n\tif cfg.MemoryLimitMiB != 0 {\n\t\treturn newFixedMemUsageChecker(memAllocLimit, memSpikeLimit), nil\n\t}\n\ttotalMemory, err := GetMemoryFn()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get total memory, use fixed memory settings (limit_mib): %w\", err)\n\t}\n\tlogger.Info(\"Using percentage memory limiter\",\n\t\tzap.Uint64(\"total_memory_mib\", totalMemory/mibBytes),\n\t\tzap.Uint32(\"limit_percentage\", cfg.MemoryLimitPercentage),\n\t\tzap.Uint32(\"spike_limit_percentage\", cfg.MemorySpikePercentage))\n\treturn newPercentageMemUsageChecker(totalMemory, uint64(cfg.MemoryLimitPercentage),\n\t\tuint64(cfg.MemorySpikePercentage)), nil\n}\n\nfunc (ml *MemoryLimiter) readMemStats() *runtime.MemStats {\n\tms := &runtime.MemStats{}\n\tml.readMemStatsFn(ms)\n\treturn ms\n}\n\nfunc memstatToZapField(ms *runtime.MemStats) zap.Field {\n\treturn zap.Uint64(\"cur_mem_mib\", ms.Alloc/mibBytes)\n}\n\nfunc (ml *MemoryLimiter) doGCandReadMemStats() *runtime.MemStats {\n\tml.runGCFn()\n\tml.lastGCDone = time.Now()\n\tms := ml.readMemStats()\n\tml.logger.Info(\"Memory usage after GC.\", memstatToZapField(ms))\n\treturn ms\n}\n\n// CheckMemLimits inspects current memory usage against threshold and toggles mustRefuse when threshold is exceeded\nfunc (ml *MemoryLimiter) CheckMemLimits() {\n\tms := ml.readMemStats()\n\n\tml.logger.Debug(\"Currently used memory.\", memstatToZapField(ms))\n\n\t// Check if we are below the soft limit.\n\taboveSoftLimit := ml.usageChecker.aboveSoftLimit(ms)\n\tif !aboveSoftLimit {\n\t\tif ml.mustRefuse.Load() {\n\t\t\t// Was previously refusing but enough memory is available now, no need to limit.\n\t\t\tml.logger.Info(\"Memory usage back within limits. Resuming normal operation.\", memstatToZapField(ms))\n\t\t}\n\t\tml.mustRefuse.Store(aboveSoftLimit)\n\t\treturn\n\t}\n\n\tif ml.usageChecker.aboveHardLimit(ms) {\n\t\t// We are above hard limit, do a GC if it wasn't done recently and see if\n\t\t// it brings memory usage below the soft limit.\n\t\tif time.Since(ml.lastGCDone) > ml.minGCIntervalWhenHardLimited {\n\t\t\tml.logger.Warn(\"Memory usage is above hard limit. Forcing a GC.\", memstatToZapField(ms))\n\t\t\tms = ml.doGCandReadMemStats()\n\t\t\t// Check the limit again to see if GC helped.\n\t\t\taboveSoftLimit = ml.usageChecker.aboveSoftLimit(ms)\n\t\t}\n\t} else {\n\t\t// We are above soft limit, do a GC if it wasn't done recently and see if\n\t\t// it brings memory usage below the soft limit.\n\t\tif time.Since(ml.lastGCDone) > ml.minGCIntervalWhenSoftLimited {\n\t\t\tml.logger.Info(\"Memory usage is above soft limit. Forcing a GC.\", memstatToZapField(ms))\n\t\t\tms = ml.doGCandReadMemStats()\n\t\t\t// Check the limit again to see if GC helped.\n\t\t\taboveSoftLimit = ml.usageChecker.aboveSoftLimit(ms)\n\t\t}\n\t}\n\n\tif !ml.mustRefuse.Load() && aboveSoftLimit {\n\t\tml.logger.Warn(\"Memory usage is above soft limit. Refusing data.\", memstatToZapField(ms))\n\t}\n\n\tml.mustRefuse.Store(aboveSoftLimit)\n}\n\ntype memUsageChecker struct {\n\tmemAllocLimit uint64\n\tmemSpikeLimit uint64\n}\n\nfunc (d memUsageChecker) aboveSoftLimit(ms *runtime.MemStats) bool {\n\treturn ms.Alloc >= d.memAllocLimit-d.memSpikeLimit\n}\n\nfunc (d memUsageChecker) aboveHardLimit(ms *runtime.MemStats) bool {\n\treturn ms.Alloc >= d.memAllocLimit\n}\n\nfunc newFixedMemUsageChecker(memAllocLimit, memSpikeLimit uint64) *memUsageChecker {\n\tif memSpikeLimit == 0 {\n\t\t// If spike limit is unspecified use 20% of mem limit.\n\t\tmemSpikeLimit = memAllocLimit / 5\n\t}\n\treturn &memUsageChecker{\n\t\tmemAllocLimit: memAllocLimit,\n\t\tmemSpikeLimit: memSpikeLimit,\n\t}\n}\n\nfunc newPercentageMemUsageChecker(totalMemory, percentageLimit, percentageSpike uint64) *memUsageChecker {\n\treturn newFixedMemUsageChecker(percentageLimit*totalMemory/100, percentageSpike*totalMemory/100)\n}\n"
  },
  {
    "path": "internal/memorylimiter/memorylimiter_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage memorylimiter\n\nimport (\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/internal/memorylimiter/iruntime\"\n)\n\n// TestMemoryPressureResponse manipulates results from querying memory and\n// check expected side effects.\nfunc TestMemoryPressureResponse(t *testing.T) {\n\tvar currentMemAlloc uint64\n\tcfg := &Config{\n\t\tCheckInterval:       1 * time.Minute,\n\t\tMemoryLimitMiB:      1024,\n\t\tMemorySpikeLimitMiB: 0,\n\t}\n\tml, err := NewMemoryLimiter(cfg, zap.NewNop())\n\trequire.NoError(t, err)\n\tml.readMemStatsFn = func(ms *runtime.MemStats) {\n\t\tms.Alloc = currentMemAlloc * mibBytes\n\t}\n\n\t// Below memAllocLimit.\n\tcurrentMemAlloc = 800\n\tml.CheckMemLimits()\n\tassert.False(t, ml.MustRefuse())\n\n\t// Above memAllocLimit.\n\tcurrentMemAlloc = 1800\n\tml.CheckMemLimits()\n\tassert.True(t, ml.MustRefuse())\n\n\t// Check spike limit\n\tml.usageChecker.memSpikeLimit = 512 * mibBytes\n\n\t// Below memSpikeLimit.\n\tcurrentMemAlloc = 500\n\tml.CheckMemLimits()\n\tassert.False(t, ml.MustRefuse())\n\n\t// Above memSpikeLimit.\n\tcurrentMemAlloc = 550\n\tml.CheckMemLimits()\n\tassert.True(t, ml.MustRefuse())\n}\n\nfunc TestGetDecision(t *testing.T) {\n\tt.Run(\"fixed_limit\", func(t *testing.T) {\n\t\td, err := getMemUsageChecker(&Config{MemoryLimitMiB: 100, MemorySpikeLimitMiB: 20}, zap.NewNop())\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, &memUsageChecker{\n\t\t\tmemAllocLimit: 100 * mibBytes,\n\t\t\tmemSpikeLimit: 20 * mibBytes,\n\t\t}, d)\n\t})\n\n\tt.Cleanup(func() {\n\t\tGetMemoryFn = iruntime.TotalMemory\n\t})\n\tGetMemoryFn = func() (uint64, error) {\n\t\treturn 100 * mibBytes, nil\n\t}\n\tt.Run(\"percentage_limit\", func(t *testing.T) {\n\t\td, err := getMemUsageChecker(&Config{MemoryLimitPercentage: 50, MemorySpikePercentage: 10}, zap.NewNop())\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, &memUsageChecker{\n\t\t\tmemAllocLimit: 50 * mibBytes,\n\t\t\tmemSpikeLimit: 10 * mibBytes,\n\t\t}, d)\n\t})\n}\n\nfunc TestRefuseDecision(t *testing.T) {\n\tdecision1000Limit30Spike30 := newPercentageMemUsageChecker(1000, 60, 30)\n\tdecision1000Limit60Spike50 := newPercentageMemUsageChecker(1000, 60, 50)\n\tdecision1000Limit40Spike20 := newPercentageMemUsageChecker(1000, 40, 20)\n\n\ttests := []struct {\n\t\tname         string\n\t\tusageChecker memUsageChecker\n\t\tms           *runtime.MemStats\n\t\tshouldRefuse bool\n\t}{\n\t\t{\n\t\t\tname:         \"should refuse over limit\",\n\t\t\tusageChecker: *decision1000Limit30Spike30,\n\t\t\tms:           &runtime.MemStats{Alloc: 600},\n\t\t\tshouldRefuse: true,\n\t\t},\n\t\t{\n\t\t\tname:         \"should not refuse\",\n\t\t\tusageChecker: *decision1000Limit30Spike30,\n\t\t\tms:           &runtime.MemStats{Alloc: 100},\n\t\t\tshouldRefuse: false,\n\t\t},\n\t\t{\n\t\t\tname: \"should not refuse spike, fixed usageChecker\",\n\t\t\tusageChecker: memUsageChecker{\n\t\t\t\tmemAllocLimit: 600,\n\t\t\t\tmemSpikeLimit: 500,\n\t\t\t},\n\t\t\tms:           &runtime.MemStats{Alloc: 300},\n\t\t\tshouldRefuse: true,\n\t\t},\n\t\t{\n\t\t\tname:         \"should refuse, spike, percentage usageChecker\",\n\t\t\tusageChecker: *decision1000Limit60Spike50,\n\t\t\tms:           &runtime.MemStats{Alloc: 300},\n\t\t\tshouldRefuse: true,\n\t\t},\n\t\t{\n\t\t\tname:         \"should refuse, spike, percentage usageChecker\",\n\t\t\tusageChecker: *decision1000Limit40Spike20,\n\t\t\tms:           &runtime.MemStats{Alloc: 250},\n\t\t\tshouldRefuse: true,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tshouldRefuse := test.usageChecker.aboveSoftLimit(test.ms)\n\t\t\tassert.Equal(t, test.shouldRefuse, shouldRefuse)\n\t\t})\n\t}\n}\n\nfunc TestCallGCWhenSoftLimit(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tmlCfg       *Config\n\t\tmemAllocMiB [2]uint64\n\t\tnumGCs      int\n\t}{\n\t\t{\n\t\t\tname: \"GC when first soft limit and not immediately\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:                1 * time.Minute,\n\t\t\t\tMinGCIntervalWhenSoftLimited: 10 * time.Second,\n\t\t\t\tMemoryLimitMiB:               50,\n\t\t\t\tMemorySpikeLimitMiB:          10,\n\t\t\t},\n\t\t\tmemAllocMiB: [2]uint64{45, 45},\n\t\t\tnumGCs:      1,\n\t\t},\n\t\t{\n\t\t\tname: \"GC always when soft limit min interval is 0\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:                1 * time.Minute,\n\t\t\t\tMinGCIntervalWhenSoftLimited: 0,\n\t\t\t\tMemoryLimitMiB:               50,\n\t\t\t\tMemorySpikeLimitMiB:          10,\n\t\t\t},\n\t\t\tmemAllocMiB: [2]uint64{45, 45},\n\t\t\tnumGCs:      2,\n\t\t},\n\t\t{\n\t\t\tname: \"GC when first hard limit and not immediately\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:                1 * time.Minute,\n\t\t\t\tMinGCIntervalWhenHardLimited: 10 * time.Second,\n\t\t\t\tMemoryLimitMiB:               50,\n\t\t\t\tMemorySpikeLimitMiB:          10,\n\t\t\t},\n\t\t\tmemAllocMiB: [2]uint64{55, 55},\n\t\t\tnumGCs:      1,\n\t\t},\n\t\t{\n\t\t\tname: \"GC always when hard limit min interval is 0\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:                1 * time.Minute,\n\t\t\t\tMinGCIntervalWhenHardLimited: 0,\n\t\t\t\tMemoryLimitMiB:               50,\n\t\t\t\tMemorySpikeLimitMiB:          10,\n\t\t\t},\n\t\t\tmemAllocMiB: [2]uint64{55, 55},\n\t\t\tnumGCs:      2,\n\t\t},\n\t\t{\n\t\t\tname: \"GC based on soft then based on hard limit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:                1 * time.Minute,\n\t\t\t\tMinGCIntervalWhenSoftLimited: 10 * time.Second,\n\t\t\t\tMinGCIntervalWhenHardLimited: 0,\n\t\t\t\tMemoryLimitMiB:               50,\n\t\t\t\tMemorySpikeLimitMiB:          10,\n\t\t\t},\n\t\t\tmemAllocMiB: [2]uint64{45, 55},\n\t\t\tnumGCs:      2,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tml, err := NewMemoryLimiter(tt.mlCfg, zap.NewNop())\n\t\t\trequire.NoError(t, err)\n\t\t\tmemAllocMiB := uint64(0)\n\t\t\tml.readMemStatsFn = func(ms *runtime.MemStats) {\n\t\t\t\tms.Alloc = memAllocMiB * mibBytes\n\t\t\t}\n\t\t\t// Mark last GC in the past so that even first call can trigger GC\n\t\t\t// Not updating the initialization code, since at the beginning of the collector no need to GC.\n\t\t\tml.lastGCDone = ml.lastGCDone.Add(-time.Minute)\n\t\t\tnumGCs := 0\n\t\t\tml.runGCFn = func() {\n\t\t\t\tnumGCs++\n\t\t\t}\n\n\t\t\tmemAllocMiB = tt.memAllocMiB[0]\n\t\t\tml.CheckMemLimits()\n\t\t\tassert.True(t, ml.MustRefuse())\n\n\t\t\t// On windows, time has larger precision, and checking here again may return same time as \"lastGCDone\"\n\t\t\t// which will not trigger a new GC for 0 duration, update last GC with -1 millis.\n\t\t\tml.lastGCDone = ml.lastGCDone.Add(-1 * time.Millisecond)\n\t\t\tmemAllocMiB = tt.memAllocMiB[1]\n\t\t\tml.CheckMemLimits()\n\t\t\tassert.True(t, ml.MustRefuse())\n\n\t\t\tassert.Equal(t, tt.numGCs, numGCs)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "internal/memorylimiter/testdata/config.yaml",
    "content": "# check_interval is the time between measurements of memory usage for the\n# purposes of avoiding going over the limits. Defaults to zero, so no\n# checks will be performed. Values below 1 second are not recommended since\n# it can result in unnecessary CPU consumption.\ncheck_interval: 5s\n\n# Maximum amount of memory, in MiB, targeted to be allocated by the process heap.\n# Note that typically the total memory usage of process will be about 50MiB higher\n# than this value.\nlimit_mib: 4000\n\n# The maximum, in MiB, spike expected between the measurements of memory usage.\nspike_limit_mib: 500\n"
  },
  {
    "path": "internal/memorylimiter/testdata/negative_unsigned_limits_config.yaml",
    "content": "# check_interval is the time between measurements of memory usage for the\n# purposes of avoiding going over the limits. Defaults to zero, so no\n# checks will be performed. Values below 1 second are not recommended since\n# it can result in unnecessary CPU consumption.\ncheck_interval: 5s\n\n# Maximum amount of memory, in MiB, targeted to be allocated by the process heap.\n# Note that typically the total memory usage of process will be about 50MiB higher\n# than this value.\nlimit_mib: -2000\n\n# The maximum, in MiB, spike expected between the measurements of memory usage.\nspike_limit_mib: -2300\n"
  },
  {
    "path": "internal/sharedcomponent/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "internal/sharedcomponent/go.mod",
    "content": "module go.opentelemetry.io/collector/internal/sharedcomponent\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componentstatus v0.148.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component/componentstatus => ../../component/componentstatus\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../testutil\n"
  },
  {
    "path": "internal/sharedcomponent/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "internal/sharedcomponent/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage sharedcomponent\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "internal/sharedcomponent/sharedcomponent.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package sharedcomponent exposes functionality for components\n// to register against a shared key, such as a configuration object, in order to be reused across signal types.\n// This is particularly useful when the component relies on a shared resource such as os.File or http.Server.\npackage sharedcomponent // import \"go.opentelemetry.io/collector/internal/sharedcomponent\"\n\nimport (\n\t\"container/ring\"\n\t\"context\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componentstatus\"\n)\n\nfunc NewMap[K comparable, V component.Component]() *Map[K, V] {\n\treturn &Map[K, V]{\n\t\tcomponents: map[K]*Component[V]{},\n\t}\n}\n\n// Map keeps reference of all created instances for a given shared key such as a component configuration.\ntype Map[K comparable, V component.Component] struct {\n\tlock       sync.Mutex\n\tcomponents map[K]*Component[V]\n}\n\n// LoadOrStore returns the already created instance if exists, otherwise creates a new instance\n// and adds it to the map of references.\nfunc (m *Map[K, V]) LoadOrStore(key K, create func() (V, error)) (*Component[V], error) {\n\tm.lock.Lock()\n\tdefer m.lock.Unlock()\n\tif c, ok := m.components[key]; ok {\n\t\treturn c, nil\n\t}\n\tcomp, err := create()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tnewComp := &Component[V]{\n\t\tcomponent: comp,\n\t\tremoveFunc: func() {\n\t\t\tm.lock.Lock()\n\t\t\tdefer m.lock.Unlock()\n\t\t\tdelete(m.components, key)\n\t\t},\n\t}\n\tm.components[key] = newComp\n\treturn newComp, nil\n}\n\n// Component ensures that the wrapped component is started and stopped only once.\n// When stopped it is removed from the Map.\ntype Component[V component.Component] struct {\n\tcomponent V\n\n\tstartOnce  sync.Once\n\tstopOnce   sync.Once\n\tremoveFunc func()\n\n\thostWrapper *hostWrapper\n}\n\n// Unwrap returns the original component.\nfunc (c *Component[V]) Unwrap() V {\n\treturn c.component\n}\n\n// Start starts the underlying component if it never started before.\nfunc (c *Component[V]) Start(ctx context.Context, host component.Host) error {\n\tif c.hostWrapper == nil {\n\t\tvar err error\n\t\tc.startOnce.Do(func() {\n\t\t\tc.hostWrapper = &hostWrapper{\n\t\t\t\thost:           host,\n\t\t\t\tsources:        make([]componentstatus.Reporter, 0),\n\t\t\t\tpreviousEvents: ring.New(5),\n\t\t\t}\n\t\t\tstatusReporter, isStatusReporter := host.(componentstatus.Reporter)\n\t\t\tif isStatusReporter {\n\t\t\t\tc.hostWrapper.addSource(statusReporter)\n\t\t\t}\n\n\t\t\t// It's important that status for a shared component is reported through its\n\t\t\t// telemetry settings to keep status in sync and avoid race conditions. This logic duplicates\n\t\t\t// and takes priority over the automated status reporting that happens in graph, making the\n\t\t\t// status reporting in graph a no-op.\n\t\t\tc.hostWrapper.Report(componentstatus.NewEvent(componentstatus.StatusStarting))\n\t\t\tif err = c.component.Start(ctx, c.hostWrapper); err != nil {\n\t\t\t\tc.hostWrapper.Report(componentstatus.NewPermanentErrorEvent(err))\n\t\t\t}\n\t\t})\n\t\treturn err\n\t}\n\tstatusReporter, isStatusReporter := host.(componentstatus.Reporter)\n\tif isStatusReporter {\n\t\tc.hostWrapper.addSource(statusReporter)\n\t}\n\treturn nil\n}\n\nvar (\n\t_ component.Host           = (*hostWrapper)(nil)\n\t_ componentstatus.Reporter = (*hostWrapper)(nil)\n)\n\ntype hostWrapper struct {\n\thost           component.Host\n\tsources        []componentstatus.Reporter\n\tpreviousEvents *ring.Ring\n\tlock           sync.Mutex\n}\n\nfunc (h *hostWrapper) GetExtensions() map[component.ID]component.Component {\n\treturn h.host.GetExtensions()\n}\n\nfunc (h *hostWrapper) Report(e *componentstatus.Event) {\n\t// Only remember an event if it will be emitted and it has not been sent already.\n\th.lock.Lock()\n\tdefer h.lock.Unlock()\n\tif len(h.sources) > 0 {\n\t\th.previousEvents.Value = e\n\t\th.previousEvents = h.previousEvents.Next()\n\t}\n\tfor _, s := range h.sources {\n\t\ts.Report(e)\n\t}\n}\n\nfunc (h *hostWrapper) addSource(s componentstatus.Reporter) {\n\th.lock.Lock()\n\tdefer h.lock.Unlock()\n\th.previousEvents.Do(func(a any) {\n\t\tif e, ok := a.(*componentstatus.Event); ok {\n\t\t\ts.Report(e)\n\t\t}\n\t})\n\th.sources = append(h.sources, s)\n}\n\n// Shutdown shuts down the underlying component.\nfunc (c *Component[V]) Shutdown(ctx context.Context) error {\n\tvar err error\n\tc.stopOnce.Do(func() {\n\t\t// It's important that status for a shared component is reported through its\n\t\t// telemetry settings to keep status in sync and avoid race conditions. This logic duplicates\n\t\t// and takes priority over the automated status reporting that happens in graph, making the\n\t\t// status reporting in graph a no-op.\n\t\tif c.hostWrapper != nil {\n\t\t\tc.hostWrapper.Report(componentstatus.NewEvent(componentstatus.StatusStopping))\n\t\t}\n\t\terr = c.component.Shutdown(ctx)\n\t\tif c.hostWrapper != nil {\n\t\t\tif err != nil {\n\t\t\t\tc.hostWrapper.Report(componentstatus.NewPermanentErrorEvent(err))\n\t\t\t} else {\n\t\t\t\tc.hostWrapper.Report(componentstatus.NewEvent(componentstatus.StatusStopped))\n\t\t\t}\n\t\t}\n\t\tc.removeFunc()\n\t})\n\treturn err\n}\n"
  },
  {
    "path": "internal/sharedcomponent/sharedcomponent_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage sharedcomponent\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componentstatus\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\nvar id = component.MustNewID(\"test\")\n\ntype baseComponent struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n}\n\nfunc TestNewMap(t *testing.T) {\n\tcomps := NewMap[component.ID, *baseComponent]()\n\tassert.Empty(t, comps.components)\n}\n\nfunc TestNewSharedComponentsCreateError(t *testing.T) {\n\tcomps := NewMap[component.ID, *baseComponent]()\n\tassert.Empty(t, comps.components)\n\tmyErr := errors.New(\"my error\")\n\t_, err := comps.LoadOrStore(\n\t\tid,\n\t\tfunc() (*baseComponent, error) { return nil, myErr },\n\t)\n\trequire.ErrorIs(t, err, myErr)\n\tassert.Empty(t, comps.components)\n}\n\nfunc TestSharedComponentsLoadOrStore(t *testing.T) {\n\tnop := &baseComponent{}\n\n\tcomps := NewMap[component.ID, *baseComponent]()\n\tgot, err := comps.LoadOrStore(\n\t\tid,\n\t\tfunc() (*baseComponent, error) { return nop, nil },\n\t)\n\trequire.NoError(t, err)\n\tassert.Len(t, comps.components, 1)\n\tassert.Same(t, nop, got.Unwrap())\n\tgotSecond, err := comps.LoadOrStore(\n\t\tid,\n\t\tfunc() (*baseComponent, error) { panic(\"should not be called\") },\n\t)\n\n\trequire.NoError(t, err)\n\tassert.Same(t, got, gotSecond)\n\n\t// Shutdown nop will remove\n\trequire.NoError(t, got.Shutdown(context.Background()))\n\tassert.Empty(t, comps.components)\n\tgotThird, err := comps.LoadOrStore(\n\t\tid,\n\t\tfunc() (*baseComponent, error) { return nop, nil },\n\t)\n\trequire.NoError(t, err)\n\tassert.NotSame(t, got, gotThird)\n}\n\nfunc TestSharedComponent(t *testing.T) {\n\twantErr := errors.New(\"my error\")\n\tcalledStart := 0\n\tcalledStop := 0\n\tcomp := &baseComponent{\n\t\tStartFunc: func(context.Context, component.Host) error {\n\t\t\tcalledStart++\n\t\t\treturn wantErr\n\t\t},\n\t\tShutdownFunc: func(context.Context) error {\n\t\t\tcalledStop++\n\t\t\treturn wantErr\n\t\t},\n\t}\n\n\tcomps := NewMap[component.ID, *baseComponent]()\n\tgot, err := comps.LoadOrStore(\n\t\tid,\n\t\tfunc() (*baseComponent, error) { return comp, nil },\n\t)\n\trequire.NoError(t, err)\n\tassert.Equal(t, wantErr, got.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.Equal(t, 1, calledStart)\n\t// Second time is not called anymore.\n\trequire.NoError(t, got.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.Equal(t, 1, calledStart)\n\t// first time, shutdown is called.\n\tassert.Equal(t, wantErr, got.Shutdown(context.Background()))\n\tassert.Equal(t, 1, calledStop)\n\t// Second time is not called anymore.\n\trequire.NoError(t, got.Shutdown(context.Background()))\n\tassert.Equal(t, 1, calledStop)\n}\n\nfunc TestReportStatusOnStartShutdown(t *testing.T) {\n\tfor _, tc := range []struct {\n\t\tname                         string\n\t\tstartErr                     error\n\t\tshutdownErr                  error\n\t\texpectedStatuses             []componentstatus.Status\n\t\texpectedNumReporterInstances int\n\t}{\n\t\t{\n\t\t\tname:        \"successful start/stop\",\n\t\t\tstartErr:    nil,\n\t\t\tshutdownErr: nil,\n\t\t\texpectedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusStopping,\n\t\t\t\tcomponentstatus.StatusStopped,\n\t\t\t},\n\t\t\texpectedNumReporterInstances: 3,\n\t\t},\n\t\t{\n\t\t\tname:        \"start error\",\n\t\t\tstartErr:    assert.AnError,\n\t\t\tshutdownErr: nil,\n\t\t\texpectedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusPermanentError,\n\t\t\t},\n\t\t\texpectedNumReporterInstances: 1,\n\t\t},\n\t\t{\n\t\t\tname:        \"shutdown error\",\n\t\t\tshutdownErr: assert.AnError,\n\t\t\texpectedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusStopping,\n\t\t\t\tcomponentstatus.StatusPermanentError,\n\t\t\t},\n\t\t\texpectedNumReporterInstances: 3,\n\t\t},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\treportedStatuses := make(map[*componentstatus.InstanceID][]componentstatus.Status)\n\t\t\tnewStatusFunc := func(id *componentstatus.InstanceID, ev *componentstatus.Event) {\n\t\t\t\treportedStatuses[id] = append(reportedStatuses[id], ev.Status())\n\t\t\t}\n\t\t\tbase := &baseComponent{}\n\t\t\tif tc.startErr != nil {\n\t\t\t\tbase.StartFunc = func(context.Context, component.Host) error {\n\t\t\t\t\treturn tc.startErr\n\t\t\t\t}\n\t\t\t}\n\t\t\tif tc.shutdownErr != nil {\n\t\t\t\tbase.ShutdownFunc = func(context.Context) error {\n\t\t\t\t\treturn tc.shutdownErr\n\t\t\t\t}\n\t\t\t}\n\t\t\tcomps := NewMap[component.ID, *baseComponent]()\n\t\t\tvar comp *Component[*baseComponent]\n\t\t\tvar err error\n\t\t\tfor range 3 {\n\t\t\t\tcomp, err = comps.LoadOrStore(\n\t\t\t\t\tid,\n\t\t\t\t\tfunc() (*baseComponent, error) { return base, nil },\n\t\t\t\t)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\n\t\t\tbaseHost := componenttest.NewNopHost()\n\t\t\tfor range 3 {\n\t\t\t\terr = comp.Start(context.Background(), &testHost{Host: baseHost, InstanceID: &componentstatus.InstanceID{}, newStatusFunc: newStatusFunc})\n\t\t\t\tif err != nil {\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\n\t\t\trequire.Equal(t, tc.startErr, err)\n\n\t\t\tif tc.startErr == nil {\n\t\t\t\tcomp.hostWrapper.Report(componentstatus.NewEvent(componentstatus.StatusOK))\n\n\t\t\t\terr = comp.Shutdown(context.Background())\n\t\t\t\trequire.Equal(t, tc.shutdownErr, err)\n\t\t\t}\n\n\t\t\trequire.Len(t, reportedStatuses, tc.expectedNumReporterInstances)\n\n\t\t\tfor _, actualStatuses := range reportedStatuses {\n\t\t\t\trequire.Equal(t, tc.expectedStatuses, actualStatuses)\n\t\t\t}\n\t\t})\n\t}\n}\n\nvar (\n\t_ component.Host           = (*testHost)(nil)\n\t_ componentstatus.Reporter = (*testHost)(nil)\n)\n\ntype testHost struct {\n\tcomponent.Host\n\t*componentstatus.InstanceID\n\tnewStatusFunc func(id *componentstatus.InstanceID, ev *componentstatus.Event)\n}\n\nfunc (h *testHost) Report(e *componentstatus.Event) {\n\th.newStatusFunc(h.InstanceID, e)\n}\n"
  },
  {
    "path": "internal/statusutil/helper.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage statusutil // import \"go.opentelemetry.io/collector/internal/statusutil\"\n\nimport (\n\t\"net/http\"\n\n\t\"google.golang.org/genproto/googleapis/rpc/errdetails\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n)\n\n// NewStatusFromMsgAndHTTPCode returns a gRPC status based on an error message string and a http status code.\n// This function is shared between the http receiver and http exporter for error propagation.\nfunc NewStatusFromMsgAndHTTPCode(errMsg string, statusCode int) *status.Status {\n\tvar c codes.Code\n\t// Mapping based on https://github.com/grpc/grpc/blob/master/doc/http-grpc-status-mapping.md\n\t// 429 mapping to ResourceExhausted and 400 mapping to StatusBadRequest are exceptions.\n\tswitch statusCode {\n\tcase http.StatusBadRequest:\n\t\tc = codes.InvalidArgument\n\tcase http.StatusUnauthorized:\n\t\tc = codes.Unauthenticated\n\tcase http.StatusForbidden:\n\t\tc = codes.PermissionDenied\n\tcase http.StatusNotFound:\n\t\tc = codes.Unimplemented\n\tcase http.StatusTooManyRequests:\n\t\tc = codes.ResourceExhausted\n\tcase http.StatusBadGateway, http.StatusServiceUnavailable, http.StatusGatewayTimeout:\n\t\tc = codes.Unavailable\n\tdefault:\n\t\tc = codes.Unknown\n\t}\n\treturn status.New(c, errMsg)\n}\n\nfunc GetRetryInfo(status *status.Status) *errdetails.RetryInfo {\n\tfor _, detail := range status.Details() {\n\t\tif t, ok := detail.(*errdetails.RetryInfo); ok {\n\t\t\treturn t\n\t\t}\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "internal/statusutil/helper_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage statusutil\n\nimport (\n\t\"net/http\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/genproto/googleapis/rpc/errdetails\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\t\"google.golang.org/protobuf/proto\"\n\t\"google.golang.org/protobuf/types/known/durationpb\"\n)\n\nfunc Test_ErrorMsgAndHTTPCodeToStatus(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\terrMsg     string\n\t\tstatusCode int\n\t\texpected   *status.Status\n\t}{\n\t\t{\n\t\t\tname:       \"Bad Request\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusBadRequest,\n\t\t\texpected:   status.New(codes.InvalidArgument, \"test\"),\n\t\t},\n\t\t{\n\t\t\tname:       \"Unauthorized\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusUnauthorized,\n\t\t\texpected:   status.New(codes.Unauthenticated, \"test\"),\n\t\t},\n\t\t{\n\t\t\tname:       \"Forbidden\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusForbidden,\n\t\t\texpected:   status.New(codes.PermissionDenied, \"test\"),\n\t\t},\n\t\t{\n\t\t\tname:       \"Not Found\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusNotFound,\n\t\t\texpected:   status.New(codes.Unimplemented, \"test\"),\n\t\t},\n\t\t{\n\t\t\tname:       \"Too Many Requests\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusTooManyRequests,\n\t\t\texpected:   status.New(codes.ResourceExhausted, \"test\"),\n\t\t},\n\t\t{\n\t\t\tname:       \"Bad Gateway\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusBadGateway,\n\t\t\texpected:   status.New(codes.Unavailable, \"test\"),\n\t\t},\n\t\t{\n\t\t\tname:       \"Service Unavailable\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusServiceUnavailable,\n\t\t\texpected:   status.New(codes.Unavailable, \"test\"),\n\t\t},\n\t\t{\n\t\t\tname:       \"Gateway Timeout\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusGatewayTimeout,\n\t\t\texpected:   status.New(codes.Unavailable, \"test\"),\n\t\t},\n\t\t{\n\t\t\tname:       \"Unsupported Media Type\",\n\t\t\terrMsg:     \"test\",\n\t\t\tstatusCode: http.StatusUnsupportedMediaType,\n\t\t\texpected:   status.New(codes.Unknown, \"test\"),\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := NewStatusFromMsgAndHTTPCode(tt.errMsg, tt.statusCode)\n\t\t\tassert.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n\nfunc TestGetRetryInfo(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    *status.Status\n\t\texpected *errdetails.RetryInfo\n\t}{\n\t\t{\n\t\t\tname:     \"NoDetails\",\n\t\t\tinput:    status.New(codes.InvalidArgument, \"test\"),\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"WithRetryInfoDetails\",\n\t\t\tinput: func() *status.Status {\n\t\t\t\tst := status.New(codes.ResourceExhausted, \"test\")\n\t\t\t\tdt, err := st.WithDetails(&errdetails.RetryInfo{RetryDelay: durationpb.New(1 * time.Second)})\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\treturn dt\n\t\t\t}(),\n\t\t\texpected: &errdetails.RetryInfo{RetryDelay: durationpb.New(1 * time.Second)},\n\t\t},\n\t\t{\n\t\t\tname: \"WithOtherDetails\",\n\t\t\tinput: func() *status.Status {\n\t\t\t\tst := status.New(codes.ResourceExhausted, \"test\")\n\t\t\t\tdt, err := st.WithDetails(&errdetails.ErrorInfo{Reason: \"my reason\"})\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\treturn dt\n\t\t\t}(),\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"WithMultipleDetails\",\n\t\t\tinput: func() *status.Status {\n\t\t\t\tst := status.New(codes.ResourceExhausted, \"test\")\n\t\t\t\tdt, err := st.WithDetails(\n\t\t\t\t\t&errdetails.ErrorInfo{Reason: \"my reason\"},\n\t\t\t\t\t&errdetails.RetryInfo{RetryDelay: durationpb.New(1 * time.Second)})\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\treturn dt\n\t\t\t}(),\n\t\t\texpected: &errdetails.RetryInfo{RetryDelay: durationpb.New(1 * time.Second)},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := GetRetryInfo(tt.input)\n\t\t\tassert.True(t, proto.Equal(tt.expected, result))\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "internal/telemetry/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "internal/telemetry/attribute.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage telemetry // import \"go.opentelemetry.io/collector/internal/telemetry\"\n\nimport (\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.uber.org/zap\"\n)\n\nconst (\n\tComponentKindKey = \"otelcol.component.kind\"\n\tComponentIDKey   = \"otelcol.component.id\"\n\tPipelineIDKey    = \"otelcol.pipeline.id\"\n\tSignalKey        = \"otelcol.signal\"\n\tSignalOutputKey  = \"otelcol.signal.output\"\n)\n\n// ToZapFields converts an OTel Go attribute set to a slice of zap fields.\nfunc ToZapFields(attrs []attribute.KeyValue) []zap.Field {\n\tzapFields := make([]zap.Field, 0, len(attrs))\n\tfor _, attr := range attrs {\n\t\tvar zapField zap.Field\n\t\tkey := string(attr.Key)\n\t\tswitch attr.Value.Type() {\n\t\tcase attribute.BOOL:\n\t\t\tzapField = zap.Bool(key, attr.Value.AsBool())\n\t\tcase attribute.INT64:\n\t\t\tzapField = zap.Int64(key, attr.Value.AsInt64())\n\t\tcase attribute.FLOAT64:\n\t\t\tzapField = zap.Float64(key, attr.Value.AsFloat64())\n\t\tcase attribute.STRING:\n\t\t\tzapField = zap.String(key, attr.Value.AsString())\n\t\tcase attribute.BOOLSLICE:\n\t\t\tzapField = zap.Bools(key, attr.Value.AsBoolSlice())\n\t\tcase attribute.INT64SLICE:\n\t\t\tzapField = zap.Int64s(key, attr.Value.AsInt64Slice())\n\t\tcase attribute.FLOAT64SLICE:\n\t\t\tzapField = zap.Float64s(key, attr.Value.AsFloat64Slice())\n\t\tcase attribute.STRINGSLICE:\n\t\t\tzapField = zap.Strings(key, attr.Value.AsStringSlice())\n\t\tdefault:\n\t\t\tzapField = zap.Any(key, attr.Value.AsInterface())\n\t\t}\n\t\tzapFields = append(zapFields, zapField)\n\t}\n\treturn zapFields\n}\n"
  },
  {
    "path": "internal/telemetry/attribute_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage telemetry // import \"go.opentelemetry.io/collector/internal/telemetry\"\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.uber.org/zap\"\n)\n\nfunc TestToZapFields(t *testing.T) {\n\ttests := []struct {\n\t\tattrs    attribute.Set\n\t\texpected []zap.Field\n\t}{\n\t\t{\n\t\t\tattrs: attribute.NewSet(\n\t\t\t\tattribute.String(\"string_key\", \"string_value\"),\n\t\t\t),\n\t\t\texpected: []zap.Field{\n\t\t\t\tzap.String(\"string_key\", \"string_value\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tattrs: attribute.NewSet(\n\t\t\t\tattribute.Bool(\"bool_key\", true),\n\t\t\t),\n\t\t\texpected: []zap.Field{\n\t\t\t\tzap.Bool(\"bool_key\", true),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tattrs: attribute.NewSet(\n\t\t\t\tattribute.Int64(\"int64_key\", 42),\n\t\t\t),\n\t\t\texpected: []zap.Field{\n\t\t\t\tzap.Int64(\"int64_key\", 42),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tattrs: attribute.NewSet(\n\t\t\t\tattribute.Float64(\"float64_key\", 3.14),\n\t\t\t),\n\t\t\texpected: []zap.Field{\n\t\t\t\tzap.Float64(\"float64_key\", 3.14),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tattrs: attribute.NewSet(\n\t\t\t\tattribute.BoolSlice(\"bool_slice_key\", []bool{true, false, true}),\n\t\t\t),\n\t\t\texpected: []zap.Field{\n\t\t\t\tzap.Bools(\"bool_slice_key\", []bool{true, false, true}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tattrs: attribute.NewSet(\n\t\t\t\tattribute.Int64Slice(\"int64_slice_key\", []int64{1, 2, 3}),\n\t\t\t),\n\t\t\texpected: []zap.Field{\n\t\t\t\tzap.Int64s(\"int64_slice_key\", []int64{1, 2, 3}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tattrs: attribute.NewSet(\n\t\t\t\tattribute.Float64Slice(\"float64_slice_key\", []float64{1.1, 2.2, 3.3}),\n\t\t\t),\n\t\t\texpected: []zap.Field{\n\t\t\t\tzap.Float64s(\"float64_slice_key\", []float64{1.1, 2.2, 3.3}),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tattrs: attribute.NewSet(\n\t\t\t\tattribute.StringSlice(\"string_slice_key\", []string{\"a\", \"b\", \"c\"}),\n\t\t\t),\n\t\t\texpected: []zap.Field{\n\t\t\t\tzap.Strings(\"string_slice_key\", []string{\"a\", \"b\", \"c\"}),\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tname := \"<empty>\"\n\t\tif tt.attrs.Len() > 0 {\n\t\t\tattr, ok := tt.attrs.Get(0)\n\t\t\tif ok {\n\t\t\t\tname = string(attr.Key)\n\t\t\t}\n\t\t}\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tresult := ToZapFields(tt.attrs.ToSlice())\n\t\t\trequire.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "internal/telemetry/go.mod",
    "content": "module go.opentelemetry.io/collector/internal/telemetry\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/otel v1.42.0\n\tgo.opentelemetry.io/otel/metric v1.42.0\n\tgo.opentelemetry.io/otel/trace v1.42.0\n\tgo.uber.org/zap v1.27.1\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../testutil\n"
  },
  {
    "path": "internal/telemetry/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "internal/telemetry/telemetry.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage telemetry // import \"go.opentelemetry.io/collector/internal/telemetry\"\n\nimport (\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/trace\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\ntype injectorCore interface {\n\tDropInjectedAttributes(droppedAttrs ...string) zapcore.Core\n}\n\ntype injectorTracerProvider interface {\n\tDropInjectedAttributes(droppedAttrs ...string) trace.TracerProvider\n}\n\ntype injectorMeterProvider interface {\n\tDropInjectedAttributes(droppedAttrs ...string) metric.MeterProvider\n}\n\nfunc DropInjectedAttributes(ts component.TelemetrySettings, attrs ...string) component.TelemetrySettings {\n\tts.Logger = ts.Logger.WithOptions(zap.WrapCore(func(c zapcore.Core) zapcore.Core {\n\t\tif ic, ok := c.(injectorCore); ok {\n\t\t\treturn ic.DropInjectedAttributes(attrs...)\n\t\t}\n\t\treturn c\n\t}))\n\tif itp, ok := ts.TracerProvider.(injectorTracerProvider); ok {\n\t\tts.TracerProvider = itp.DropInjectedAttributes(attrs...)\n\t}\n\tif imp, ok := ts.MeterProvider.(injectorMeterProvider); ok {\n\t\tts.MeterProvider = imp.DropInjectedAttributes(attrs...)\n\t}\n\treturn ts\n}\n"
  },
  {
    "path": "internal/telemetry/telemetrytest/mock.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage telemetrytest // import \"go.opentelemetry.io/collector/internal/telemetry/telemetrytest\"\n\nimport (\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n)\n\ntype mockInjectorCore struct {\n\tzapcore.Core\n\tdropped *[]string\n}\n\nfunc (mic mockInjectorCore) DropInjectedAttributes(droppedAttrs ...string) zapcore.Core {\n\t*mic.dropped = append(*mic.dropped, droppedAttrs...)\n\treturn mic\n}\n\nfunc MockInjectorLogger(logger *zap.Logger, dropped *[]string) *zap.Logger {\n\treturn logger.WithOptions(zap.WrapCore(func(c zapcore.Core) zapcore.Core {\n\t\treturn mockInjectorCore{\n\t\t\tCore:    c,\n\t\t\tdropped: dropped,\n\t\t}\n\t}))\n}\n"
  },
  {
    "path": "internal/testutil/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "internal/testutil/README.md",
    "content": "## Test Utilities\n\nThe `go.opentelemetry.io/collector/internal/testutil` module provides utility functions, etc. for use by tests in other \nOpenTelemetry Collector modules."
  },
  {
    "path": "internal/testutil/benchmarks.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testutil // import \"go.opentelemetry.io/collector/internal/testutil\"\n\nimport (\n\t\"os\"\n\t\"testing\"\n)\n\n// SkipMemoryBench will skip memory benchmarks on CI, as we currently only\n// monitor duration.\nfunc SkipMemoryBench(b *testing.B) {\n\tif os.Getenv(\"MEMBENCH\") == \"\" {\n\t\tb.Skip(\"Skipping since the 'MEMBENCH' environment variable was not set\")\n\t}\n}\n\n// SkipGCHeavyBench will skip GC-heavy benchmarks on CI.\n// These benchmarks tend to be flaky with the current settings since garbage\n// collection pauses can take ~50ms which is significant with the current benchmark times.\nfunc SkipGCHeavyBench(b *testing.B) {\n\tif os.Getenv(\"GCHEAVYBENCH\") == \"\" {\n\t\tb.Skip(\"Skipping since the 'GCHEAVYBENCH' environment variable was not set. See https://github.com/open-telemetry/opentelemetry-collector/issues/14257.\")\n\t}\n}\n"
  },
  {
    "path": "internal/testutil/fips.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testutil // import \"go.opentelemetry.io/collector/internal/testutil\"\n\nimport (\n\t\"os\"\n\t\"strings\"\n\t\"testing\"\n)\n\n// SkipIfFIPSOnly will mark the passed test as skipped if GODEBUG=fips140=only is detected.\n// If GODEBUG=fips140=on, go may call non-compliant algorithms and the test does not need to be skipped.\nfunc SkipIfFIPSOnly(t *testing.T, msg string) {\n\t// NOTE: This only checks env var; at the time of writing fips140 can only be set via env\n\t// other GODEBUG settings can be set via embedded comments or in go.mod, we may need to account for this in the future.\n\ts := os.Getenv(\"GODEBUG\")\n\tif strings.Contains(s, \"fips140=only\") {\n\t\tt.Skip(\"GODEBUG=fips140=only detected, skipping test:\", msg)\n\t}\n}\n"
  },
  {
    "path": "internal/testutil/go.mod",
    "content": "module go.opentelemetry.io/collector/internal/testutil\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/kr/text v0.2.0 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n"
  },
  {
    "path": "internal/testutil/go.sum",
    "content": "github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=\ngithub.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=\ngopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "internal/testutil/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testutil\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "internal/testutil/testutil.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testutil // import \"go.opentelemetry.io/collector/internal/testutil\"\n\nimport (\n\t\"net\"\n\t\"os/exec\"\n\t\"runtime\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\ntype portpair struct {\n\tfirst string\n\tlast  string\n}\n\n// GetAvailableLocalAddress finds an available local port and returns an endpoint\n// describing it. The port is available for opening when this function returns\n// provided that there is no race by some other code to grab the same port\n// immediately.\nfunc GetAvailableLocalAddress(tb testing.TB) string {\n\treturn findAvailable(tb, \"tcp4\")\n}\n\n// GetAvailableLocalIPv6Address is IPv6 version of GetAvailableLocalAddress.\nfunc GetAvailableLocalIPv6Address(tb testing.TB) string {\n\treturn findAvailable(tb, \"tcp6\")\n}\n\nfunc findAvailable(tb testing.TB, network string) string {\n\t// Retry has been added for windows as net.Listen can return a port that is not actually available. Details can be\n\t// found in https://github.com/docker/for-win/issues/3171 but to summarize Hyper-V will reserve ranges of ports\n\t// which do not show up under the \"netstat -ano\" but can only be found by\n\t// \"netsh interface ipv4 show excludedportrange protocol=tcp\".  We'll use []exclusions to hold those ranges and\n\t// retry if the port returned by GetAvailableLocalAddress falls in one of those them.\n\tvar exclusions []portpair\n\tportFound := false\n\tif runtime.GOOS == \"windows\" {\n\t\texclusions = getExclusionsList(tb, network)\n\t}\n\n\tvar endpoint string\n\tfor !portFound {\n\t\tendpoint = findAvailableAddress(tb, network)\n\t\t_, port, err := net.SplitHostPort(endpoint)\n\t\trequire.NoError(tb, err)\n\t\tportFound = true\n\t\tif runtime.GOOS == \"windows\" {\n\t\t\tfor _, pair := range exclusions {\n\t\t\t\tif port >= pair.first && port <= pair.last {\n\t\t\t\t\tportFound = false\n\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn endpoint\n}\n\nfunc findAvailableAddress(tb testing.TB, network string) string {\n\tvar host string\n\tswitch network {\n\tcase \"tcp\", \"tcp4\":\n\t\thost = \"localhost\"\n\tcase \"tcp6\":\n\t\thost = \"[::1]\"\n\t}\n\trequire.NotEmpty(tb, host, \"network must be either of tcp, tcp4 or tcp6\")\n\n\tln, err := net.Listen(\"tcp\", host+\":0\")\n\trequire.NoError(tb, err, \"Failed to get a free local port\")\n\t// There is a possible race if something else takes this same port before\n\t// the test uses it, however, that is unlikely in practice.\n\tdefer func() {\n\t\tassert.NoError(tb, ln.Close())\n\t}()\n\treturn ln.Addr().String()\n}\n\n// Get excluded ports on Windows from the command: netsh interface ipv4 show excludedportrange protocol=tcp\nfunc getExclusionsList(tb testing.TB, network string) []portpair {\n\tvar cmdTCP *exec.Cmd\n\tswitch network {\n\tcase \"tcp\", \"tcp4\":\n\t\tcmdTCP = exec.Command(\"netsh\", \"interface\", \"ipv4\", \"show\", \"excludedportrange\", \"protocol=tcp\")\n\tcase \"tcp6\":\n\t\tcmdTCP = exec.Command(\"netsh\", \"interface\", \"ipv6\", \"show\", \"excludedportrange\", \"protocol=tcp\")\n\t}\n\trequire.NotZero(tb, cmdTCP, \"network must be either of tcp, tcp4 or tcp6\")\n\n\toutputTCP, errTCP := cmdTCP.CombinedOutput()\n\trequire.NoError(tb, errTCP)\n\texclusions := createExclusionsList(tb, string(outputTCP))\n\n\tcmdUDP := exec.Command(\"netsh\", \"interface\", \"ipv4\", \"show\", \"excludedportrange\", \"protocol=udp\")\n\toutputUDP, errUDP := cmdUDP.CombinedOutput()\n\trequire.NoError(tb, errUDP)\n\texclusions = append(exclusions, createExclusionsList(tb, string(outputUDP))...)\n\n\treturn exclusions\n}\n\nfunc createExclusionsList(tb testing.TB, exclusionsText string) []portpair {\n\tvar exclusions []portpair\n\n\tparts := strings.Split(exclusionsText, \"--------\")\n\trequire.Len(tb, parts, 3)\n\tportsText := strings.Split(parts[2], \"*\")\n\trequire.Greater(tb, len(portsText), 1) // original text may have a suffix like \" - Administered port exclusions.\"\n\tlines := strings.SplitSeq(portsText[0], \"\\n\")\n\tfor line := range lines {\n\t\tif strings.TrimSpace(line) != \"\" {\n\t\t\tentries := strings.Fields(strings.TrimSpace(line))\n\t\t\trequire.Len(tb, entries, 2)\n\t\t\tpair := portpair{entries[0], entries[1]}\n\t\t\texclusions = append(exclusions, pair)\n\t\t}\n\t}\n\treturn exclusions\n}\n"
  },
  {
    "path": "internal/testutil/testutil_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testutil\n\nimport (\n\t\"net\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestGetAvailableLocalAddress(t *testing.T) {\n\tendpoint := GetAvailableLocalAddress(t)\n\n\t// Endpoint should be free.\n\tln0, err := net.Listen(\"tcp\", endpoint)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, ln0)\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, ln0.Close())\n\t})\n\n\t// Ensure that the endpoint wasn't something like \":0\" by checking that a\n\t// second listener will fail.\n\tln1, err := net.Listen(\"tcp\", endpoint)\n\trequire.Error(t, err)\n\trequire.Nil(t, ln1)\n}\n\nfunc TestGetAvailableLocalIpv6Address(t *testing.T) {\n\tendpoint := GetAvailableLocalIPv6Address(t)\n\n\t// Endpoint should be free.\n\tln0, err := net.Listen(\"tcp\", endpoint)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, ln0)\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, ln0.Close())\n\t})\n\n\t// Ensure that the endpoint wasn't something like \":0\" by checking that a\n\t// second listener will fail.\n\tln1, err := net.Listen(\"tcp\", endpoint)\n\trequire.Error(t, err)\n\trequire.Nil(t, ln1)\n}\n\nfunc TestCreateExclusionsList(t *testing.T) {\n\t// Test two examples of typical output from \"netsh interface ipv4 show excludedportrange protocol=tcp\"\n\temptyExclusionsText := `\n\nProtocol tcp Port Exclusion Ranges\n\nStart Port    End Port\n----------    --------\n\n* - Administered port exclusions.`\n\n\texclusionsText := `\n\nStart Port    End Port\n----------    --------\n     49697       49796\n     49797       49896\n\n* - Administered port exclusions.\n`\n\texclusions := createExclusionsList(t, exclusionsText)\n\trequire.Len(t, exclusions, 2)\n\n\temptyExclusions := createExclusionsList(t, emptyExclusionsText)\n\trequire.Empty(t, emptyExclusions)\n}\n"
  },
  {
    "path": "internal/tools/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "internal/tools/go.mod",
    "content": "module go.opentelemetry.io/collector/internal/tools\n\ngo 1.25.0\n\ntool (\n\tgithub.com/a8m/envsubst/cmd/envsubst\n\tgithub.com/client9/misspell/cmd/misspell\n\tgithub.com/dkorunic/betteralign/cmd/betteralign\n\tgithub.com/golangci/golangci-lint/v2/cmd/golangci-lint\n\tgithub.com/google/addlicense\n\tgithub.com/jcchavezs/porto/cmd/porto\n\tgithub.com/pavius/impi/cmd/impi\n\tgithub.com/rhysd/actionlint/cmd/actionlint\n\tgo.opentelemetry.io/build-tools/checkapi\n\tgo.opentelemetry.io/build-tools/checkfile\n\tgo.opentelemetry.io/build-tools/chloggen\n\tgo.opentelemetry.io/build-tools/crosslink\n\tgo.opentelemetry.io/build-tools/githubgen\n\tgo.opentelemetry.io/build-tools/multimod\n\tgolang.org/x/exp/cmd/apidiff\n\tgolang.org/x/tools/cmd/goimports\n\tgolang.org/x/tools/go/analysis/passes/modernize/cmd/modernize\n\tgolang.org/x/vuln/cmd/govulncheck\n\tgotest.tools/gotestsum\n\tmvdan.cc/gofumpt\n)\n\nrequire (\n\t4d63.com/gocheckcompilerdirectives v1.3.0 // indirect\n\t4d63.com/gochecknoglobals v0.2.2 // indirect\n\tcodeberg.org/chavacava/garif v0.2.0 // indirect\n\tdario.cat/mergo v1.0.2 // indirect\n\tdev.gaijin.team/go/exhaustruct/v4 v4.0.0 // indirect\n\tdev.gaijin.team/go/golib v0.6.0 // indirect\n\tgithub.com/4meepo/tagalign v1.4.3 // indirect\n\tgithub.com/Abirdcfly/dupword v0.1.7 // indirect\n\tgithub.com/AdminBenni/iota-mixing v1.0.0 // indirect\n\tgithub.com/AlwxSin/noinlineerr v1.0.5 // indirect\n\tgithub.com/Antonboom/errname v1.1.1 // indirect\n\tgithub.com/Antonboom/nilnil v1.1.1 // indirect\n\tgithub.com/Antonboom/testifylint v1.6.4 // indirect\n\tgithub.com/BurntSushi/toml v1.5.0 // indirect\n\tgithub.com/Djarvur/go-err113 v0.1.1 // indirect\n\tgithub.com/KimMachineGun/automemlimit v0.7.5 // indirect\n\tgithub.com/Masterminds/semver/v3 v3.4.0 // indirect\n\tgithub.com/Microsoft/go-winio v0.6.2 // indirect\n\tgithub.com/MirrexOne/unqueryvet v1.2.1 // indirect\n\tgithub.com/OpenPeeDeeP/depguard/v2 v2.2.1 // indirect\n\tgithub.com/ProtonMail/go-crypto v1.3.0 // indirect\n\tgithub.com/a8m/envsubst v1.4.3 // indirect\n\tgithub.com/alecthomas/chroma/v2 v2.20.0 // indirect\n\tgithub.com/alecthomas/go-check-sumtype v0.3.1 // indirect\n\tgithub.com/alexkohler/nakedret/v2 v2.0.6 // indirect\n\tgithub.com/alexkohler/prealloc v1.0.0 // indirect\n\tgithub.com/alfatraining/structtag v1.0.0 // indirect\n\tgithub.com/alingse/asasalint v0.0.11 // indirect\n\tgithub.com/alingse/nilnesserr v0.2.0 // indirect\n\tgithub.com/ashanbrown/forbidigo/v2 v2.3.0 // indirect\n\tgithub.com/ashanbrown/makezero/v2 v2.1.0 // indirect\n\tgithub.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect\n\tgithub.com/beorn7/perks v1.0.1 // indirect\n\tgithub.com/bitfield/gotestdox v0.2.2 // indirect\n\tgithub.com/bkielbasa/cyclop v1.2.3 // indirect\n\tgithub.com/blizzy78/varnamelen v0.8.0 // indirect\n\tgithub.com/bmatcuk/doublestar/v4 v4.10.0 // indirect\n\tgithub.com/bombsimon/wsl/v4 v4.7.0 // indirect\n\tgithub.com/bombsimon/wsl/v5 v5.3.0 // indirect\n\tgithub.com/breml/bidichk v0.3.3 // indirect\n\tgithub.com/breml/errchkjson v0.4.1 // indirect\n\tgithub.com/butuzov/ireturn v0.4.0 // indirect\n\tgithub.com/butuzov/mirror v1.3.0 // indirect\n\tgithub.com/catenacyber/perfsprint v0.10.1 // indirect\n\tgithub.com/ccojocar/zxcvbn-go v1.0.4 // indirect\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/charithe/durationcheck v0.0.11 // indirect\n\tgithub.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc // indirect\n\tgithub.com/charmbracelet/lipgloss v1.1.0 // indirect\n\tgithub.com/charmbracelet/x/ansi v0.8.0 // indirect\n\tgithub.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd // indirect\n\tgithub.com/charmbracelet/x/term v0.2.2 // indirect\n\tgithub.com/ckaznocha/intrange v0.3.1 // indirect\n\tgithub.com/client9/misspell v0.3.4 // indirect\n\tgithub.com/clipperhouse/uax29/v2 v2.2.0 // indirect\n\tgithub.com/cloudflare/circl v1.6.3 // indirect\n\tgithub.com/curioswitch/go-reassign v0.3.0 // indirect\n\tgithub.com/cyphar/filepath-securejoin v0.5.0 // indirect\n\tgithub.com/daixiang0/gci v0.13.7 // indirect\n\tgithub.com/dave/dst v0.27.3 // indirect\n\tgithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect\n\tgithub.com/denis-tingaikin/go-header v0.5.0 // indirect\n\tgithub.com/dkorunic/betteralign v0.8.2 // indirect\n\tgithub.com/dlclark/regexp2 v1.11.5 // indirect\n\tgithub.com/dnephin/pflag v1.0.7 // indirect\n\tgithub.com/emirpasic/gods v1.18.1 // indirect\n\tgithub.com/ettle/strcase v0.2.0 // indirect\n\tgithub.com/fatih/color v1.18.0 // indirect\n\tgithub.com/fatih/structtag v1.2.0 // indirect\n\tgithub.com/firefart/nonamedreturns v1.0.6 // indirect\n\tgithub.com/fsnotify/fsnotify v1.9.0 // indirect\n\tgithub.com/fzipp/gocyclo v0.6.0 // indirect\n\tgithub.com/ghostiam/protogetter v0.3.18 // indirect\n\tgithub.com/go-critic/go-critic v0.14.2 // indirect\n\tgithub.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 // indirect\n\tgithub.com/go-git/go-billy/v5 v5.6.2 // indirect\n\tgithub.com/go-git/go-git/v5 v5.16.5 // indirect\n\tgithub.com/go-json-experiment/json v0.0.0-20250813233538-9b1f9ea2e11b // indirect\n\tgithub.com/go-toolsmith/astcast v1.1.0 // indirect\n\tgithub.com/go-toolsmith/astcopy v1.1.0 // indirect\n\tgithub.com/go-toolsmith/astequal v1.2.0 // indirect\n\tgithub.com/go-toolsmith/astfmt v1.1.0 // indirect\n\tgithub.com/go-toolsmith/astp v1.1.0 // indirect\n\tgithub.com/go-toolsmith/strparse v1.1.0 // indirect\n\tgithub.com/go-toolsmith/typep v1.1.0 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.4.0 // indirect\n\tgithub.com/go-xmlfmt/xmlfmt v1.1.3 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/goccy/go-json v0.10.5 // indirect\n\tgithub.com/goccy/go-yaml v1.18.0 // indirect\n\tgithub.com/godoc-lint/godoc-lint v0.10.1 // indirect\n\tgithub.com/gofrs/flock v0.13.0 // indirect\n\tgithub.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect\n\tgithub.com/golangci/asciicheck v0.5.0 // indirect\n\tgithub.com/golangci/dupl v0.0.0-20250308024227-f665c8d69b32 // indirect\n\tgithub.com/golangci/go-printf-func-name v0.1.1 // indirect\n\tgithub.com/golangci/gofmt v0.0.0-20250106114630-d62b90e6713d // indirect\n\tgithub.com/golangci/golangci-lint/v2 v2.6.2 // indirect\n\tgithub.com/golangci/golines v0.0.0-20250217134842-442fd0091d95 // indirect\n\tgithub.com/golangci/misspell v0.7.0 // indirect\n\tgithub.com/golangci/plugin-module-register v0.1.2 // indirect\n\tgithub.com/golangci/revgrep v0.8.0 // indirect\n\tgithub.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e // indirect\n\tgithub.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e // indirect\n\tgithub.com/google/addlicense v1.2.0 // indirect\n\tgithub.com/google/go-cmp v0.7.0 // indirect\n\tgithub.com/google/go-github/v76 v76.0.0 // indirect\n\tgithub.com/google/go-querystring v1.1.0 // indirect\n\tgithub.com/google/renameio/v2 v2.0.1 // indirect\n\tgithub.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect\n\tgithub.com/gordonklaus/ineffassign v0.2.0 // indirect\n\tgithub.com/gostaticanalysis/analysisutil v0.7.1 // indirect\n\tgithub.com/gostaticanalysis/comment v1.5.0 // indirect\n\tgithub.com/gostaticanalysis/forcetypeassert v0.2.0 // indirect\n\tgithub.com/gostaticanalysis/nilerr v0.1.2 // indirect\n\tgithub.com/hashicorp/go-cleanhttp v0.5.2 // indirect\n\tgithub.com/hashicorp/go-immutable-radix/v2 v2.1.0 // indirect\n\tgithub.com/hashicorp/go-retryablehttp v0.7.8 // indirect\n\tgithub.com/hashicorp/go-version v1.7.0 // indirect\n\tgithub.com/hashicorp/golang-lru/v2 v2.0.7 // indirect\n\tgithub.com/hexops/gotextdiff v1.0.3 // indirect\n\tgithub.com/inconshreveable/mousetrap v1.1.0 // indirect\n\tgithub.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 // indirect\n\tgithub.com/jcchavezs/porto v0.7.0 // indirect\n\tgithub.com/jgautheron/goconst v1.8.2 // indirect\n\tgithub.com/jingyugao/rowserrcheck v1.1.1 // indirect\n\tgithub.com/jjti/go-spancheck v0.6.5 // indirect\n\tgithub.com/julz/importas v0.2.0 // indirect\n\tgithub.com/kaptinlin/go-i18n v0.1.6 // indirect\n\tgithub.com/kaptinlin/jsonschema v0.4.12 // indirect\n\tgithub.com/kaptinlin/messageformat-go v0.4.0 // indirect\n\tgithub.com/karamaru-alpha/copyloopvar v1.2.2 // indirect\n\tgithub.com/kevinburke/ssh_config v1.4.0 // indirect\n\tgithub.com/kisielk/errcheck v1.9.0 // indirect\n\tgithub.com/kisielk/gotool v1.0.0 // indirect\n\tgithub.com/kkHAIKE/contextcheck v1.1.6 // indirect\n\tgithub.com/klauspost/cpuid/v2 v2.3.0 // indirect\n\tgithub.com/kulti/thelper v0.7.1 // indirect\n\tgithub.com/kunwardeep/paralleltest v1.0.15 // indirect\n\tgithub.com/lasiar/canonicalheader v1.1.2 // indirect\n\tgithub.com/ldez/exptostd v0.4.5 // indirect\n\tgithub.com/ldez/gomoddirectives v0.7.1 // indirect\n\tgithub.com/ldez/grignotin v0.10.1 // indirect\n\tgithub.com/ldez/tagliatelle v0.7.2 // indirect\n\tgithub.com/ldez/usetesting v0.5.0 // indirect\n\tgithub.com/leonklingele/grouper v1.1.2 // indirect\n\tgithub.com/lucasb-eyer/go-colorful v1.2.0 // indirect\n\tgithub.com/macabu/inamedparam v0.2.0 // indirect\n\tgithub.com/manuelarte/embeddedstructfieldcheck v0.4.0 // indirect\n\tgithub.com/manuelarte/funcorder v0.5.0 // indirect\n\tgithub.com/maratori/testableexamples v1.0.1 // indirect\n\tgithub.com/maratori/testpackage v1.1.2 // indirect\n\tgithub.com/matoous/godox v1.1.0 // indirect\n\tgithub.com/mattn/go-colorable v0.1.14 // indirect\n\tgithub.com/mattn/go-isatty v0.0.20 // indirect\n\tgithub.com/mattn/go-runewidth v0.0.19 // indirect\n\tgithub.com/mattn/go-shellwords v1.0.12 // indirect\n\tgithub.com/mgechev/revive v1.12.0 // indirect\n\tgithub.com/mitchellh/go-homedir v1.1.0 // indirect\n\tgithub.com/moricho/tparallel v0.3.2 // indirect\n\tgithub.com/muesli/termenv v0.16.0 // indirect\n\tgithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect\n\tgithub.com/nakabonne/nestif v0.3.1 // indirect\n\tgithub.com/nishanths/exhaustive v0.12.0 // indirect\n\tgithub.com/nishanths/predeclared v0.2.2 // indirect\n\tgithub.com/nunnatsa/ginkgolinter v0.21.2 // indirect\n\tgithub.com/pavius/impi v0.0.3 // indirect\n\tgithub.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 // indirect\n\tgithub.com/pelletier/go-toml/v2 v2.2.4 // indirect\n\tgithub.com/pjbgf/sha1cd v0.5.0 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect\n\tgithub.com/polyfloyd/go-errorlint v1.8.0 // indirect\n\tgithub.com/prometheus/client_golang v1.23.2 // indirect\n\tgithub.com/prometheus/client_model v0.6.2 // indirect\n\tgithub.com/prometheus/common v0.66.1 // indirect\n\tgithub.com/prometheus/procfs v0.16.1 // indirect\n\tgithub.com/quasilyte/go-ruleguard v0.4.5 // indirect\n\tgithub.com/quasilyte/go-ruleguard/dsl v0.3.23 // indirect\n\tgithub.com/quasilyte/gogrep v0.5.0 // indirect\n\tgithub.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727 // indirect\n\tgithub.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 // indirect\n\tgithub.com/raeperd/recvcheck v0.2.0 // indirect\n\tgithub.com/rhysd/actionlint v1.7.11 // indirect\n\tgithub.com/rivo/uniseg v0.4.7 // indirect\n\tgithub.com/robfig/cron/v3 v3.0.1 // indirect\n\tgithub.com/rogpeppe/go-internal v1.14.1 // indirect\n\tgithub.com/ryancurrah/gomodguard v1.4.1 // indirect\n\tgithub.com/ryanrolds/sqlclosecheck v0.5.1 // indirect\n\tgithub.com/sagikazarmark/locafero v0.12.0 // indirect\n\tgithub.com/sanposhiho/wastedassign/v2 v2.1.0 // indirect\n\tgithub.com/santhosh-tekuri/jsonschema/v6 v6.0.2 // indirect\n\tgithub.com/sashamelentyev/interfacebloat v1.1.0 // indirect\n\tgithub.com/sashamelentyev/usestdlibvars v1.29.0 // indirect\n\tgithub.com/securego/gosec/v2 v2.22.10 // indirect\n\tgithub.com/sergi/go-diff v1.4.0 // indirect\n\tgithub.com/sirkon/dst v0.26.4 // indirect\n\tgithub.com/sirupsen/logrus v1.9.3 // indirect\n\tgithub.com/sivchari/containedctx v1.0.3 // indirect\n\tgithub.com/skeema/knownhosts v1.3.2 // indirect\n\tgithub.com/sonatard/noctx v0.4.0 // indirect\n\tgithub.com/sourcegraph/go-diff v0.7.0 // indirect\n\tgithub.com/spf13/afero v1.15.0 // indirect\n\tgithub.com/spf13/cast v1.10.0 // indirect\n\tgithub.com/spf13/cobra v1.10.2 // indirect\n\tgithub.com/spf13/pflag v1.0.10 // indirect\n\tgithub.com/spf13/viper v1.21.0 // indirect\n\tgithub.com/ssgreg/nlreturn/v2 v2.2.1 // indirect\n\tgithub.com/stbenjam/no-sprintf-host-port v0.2.0 // indirect\n\tgithub.com/stretchr/objx v0.5.3 // indirect\n\tgithub.com/stretchr/testify v1.11.1 // indirect\n\tgithub.com/subosito/gotenv v1.6.0 // indirect\n\tgithub.com/tetafro/godot v1.5.4 // indirect\n\tgithub.com/timakin/bodyclose v0.0.0-20241222091800-1db5c5ca4d67 // indirect\n\tgithub.com/timonwong/loggercheck v0.11.0 // indirect\n\tgithub.com/tomarrell/wrapcheck/v2 v2.11.0 // indirect\n\tgithub.com/tommy-muehle/go-mnd/v2 v2.5.1 // indirect\n\tgithub.com/ultraware/funlen v0.2.0 // indirect\n\tgithub.com/ultraware/whitespace v0.2.0 // indirect\n\tgithub.com/uudashr/gocognit v1.2.0 // indirect\n\tgithub.com/uudashr/iface v1.4.1 // indirect\n\tgithub.com/xanzy/ssh-agent v0.3.3 // indirect\n\tgithub.com/xen0n/gosmopolitan v1.3.0 // indirect\n\tgithub.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect\n\tgithub.com/yagipy/maintidx v1.0.0 // indirect\n\tgithub.com/yeya24/promlinter v0.3.0 // indirect\n\tgithub.com/ykadowak/zerologlint v0.1.5 // indirect\n\tgitlab.com/bosi/decorder v0.4.2 // indirect\n\tgo-simpler.org/musttag v0.14.0 // indirect\n\tgo-simpler.org/sloglint v0.11.1 // indirect\n\tgo.augendre.info/arangolint v0.3.1 // indirect\n\tgo.augendre.info/fatcontext v0.9.0 // indirect\n\tgo.opentelemetry.io/build-tools v0.29.0 // indirect\n\tgo.opentelemetry.io/build-tools/checkapi v0.29.0 // indirect\n\tgo.opentelemetry.io/build-tools/checkfile v0.29.0 // indirect\n\tgo.opentelemetry.io/build-tools/chloggen v0.29.0 // indirect\n\tgo.opentelemetry.io/build-tools/crosslink v0.29.0 // indirect\n\tgo.opentelemetry.io/build-tools/githubgen v0.29.0 // indirect\n\tgo.opentelemetry.io/build-tools/multimod v0.29.0 // indirect\n\tgo.uber.org/automaxprocs v1.6.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v2 v2.4.3 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgo.yaml.in/yaml/v4 v4.0.0-rc.3 // indirect\n\tgolang.org/x/crypto v0.48.0 // indirect\n\tgolang.org/x/exp v0.0.0-20240909161429-701f63a606c0 // indirect\n\tgolang.org/x/exp/typeparams v0.0.0-20251023183803-a4bb9ffd2546 // indirect\n\tgolang.org/x/mod v0.33.0 // indirect\n\tgolang.org/x/net v0.50.0 // indirect\n\tgolang.org/x/sync v0.19.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgolang.org/x/telemetry v0.0.0-20260209163413-e7419c687ee4 // indirect\n\tgolang.org/x/term v0.40.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgolang.org/x/tools v0.42.0 // indirect\n\tgolang.org/x/vuln v1.1.4 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/warnings.v0 v0.1.2 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n\tgotest.tools/gotestsum v1.13.0 // indirect\n\thonnef.co/go/tools v0.7.0-0.dev.0.20250523013057-bbc2f4dd71ea // indirect\n\tmvdan.cc/gofumpt v0.9.2 // indirect\n\tmvdan.cc/unparam v0.0.0-20251027182757-5beb8c8f8f15 // indirect\n)\n\nretract (\n\tv0.57.1 // Release failed, use v0.57.2\n\tv0.57.0 // Release failed, use v0.57.2\n)\n"
  },
  {
    "path": "internal/tools/go.sum",
    "content": "4d63.com/gocheckcompilerdirectives v1.3.0 h1:Ew5y5CtcAAQeTVKUVFrE7EwHMrTO6BggtEj8BZSjZ3A=\n4d63.com/gocheckcompilerdirectives v1.3.0/go.mod h1:ofsJ4zx2QAuIP/NO/NAh1ig6R1Fb18/GI7RVMwz7kAY=\n4d63.com/gochecknoglobals v0.2.2 h1:H1vdnwnMaZdQW/N+NrkT1SZMTBmcwHe9Vq8lJcYYTtU=\n4d63.com/gochecknoglobals v0.2.2/go.mod h1:lLxwTQjL5eIesRbvnzIP3jZtG140FnTdz+AlMa+ogt0=\ncodeberg.org/chavacava/garif v0.2.0 h1:F0tVjhYbuOCnvNcU3YSpO6b3Waw6Bimy4K0mM8y6MfY=\ncodeberg.org/chavacava/garif v0.2.0/go.mod h1:P2BPbVbT4QcvLZrORc2T29szK3xEOlnl0GiPTJmEqBQ=\ndario.cat/mergo v1.0.2 h1:85+piFYR1tMbRrLcDwR18y4UKJ3aH1Tbzi24VRW1TK8=\ndario.cat/mergo v1.0.2/go.mod h1:E/hbnu0NxMFBjpMIE34DRGLWqDy0g5FuKDhCb31ngxA=\ndev.gaijin.team/go/exhaustruct/v4 v4.0.0 h1:873r7aNneqoBB3IaFIzhvt2RFYTuHgmMjoKfwODoI1Y=\ndev.gaijin.team/go/exhaustruct/v4 v4.0.0/go.mod h1:aZ/k2o4Y05aMJtiux15x8iXaumE88YdiB0Ai4fXOzPI=\ndev.gaijin.team/go/golib v0.6.0 h1:v6nnznFTs4bppib/NyU1PQxobwDHwCXXl15P7DV5Zgo=\ndev.gaijin.team/go/golib v0.6.0/go.mod h1:uY1mShx8Z/aNHWDyAkZTkX+uCi5PdX7KsG1eDQa2AVE=\ngithub.com/4meepo/tagalign v1.4.3 h1:Bnu7jGWwbfpAie2vyl63Zup5KuRv21olsPIha53BJr8=\ngithub.com/4meepo/tagalign v1.4.3/go.mod h1:00WwRjiuSbrRJnSVeGWPLp2epS5Q/l4UEy0apLLS37c=\ngithub.com/Abirdcfly/dupword v0.1.7 h1:2j8sInznrje4I0CMisSL6ipEBkeJUJAmK1/lfoNGWrQ=\ngithub.com/Abirdcfly/dupword v0.1.7/go.mod h1:K0DkBeOebJ4VyOICFdppB23Q0YMOgVafM0zYW0n9lF4=\ngithub.com/AdminBenni/iota-mixing v1.0.0 h1:Os6lpjG2dp/AE5fYBPAA1zfa2qMdCAWwPMCgpwKq7wo=\ngithub.com/AdminBenni/iota-mixing v1.0.0/go.mod h1:i4+tpAaB+qMVIV9OK3m4/DAynOd5bQFaOu+2AhtBCNY=\ngithub.com/AlwxSin/noinlineerr v1.0.5 h1:RUjt63wk1AYWTXtVXbSqemlbVTb23JOSRiNsshj7TbY=\ngithub.com/AlwxSin/noinlineerr v1.0.5/go.mod h1:+QgkkoYrMH7RHvcdxdlI7vYYEdgeoFOVjU9sUhw/rQc=\ngithub.com/Antonboom/errname v1.1.1 h1:bllB7mlIbTVzO9jmSWVWLjxTEbGBVQ1Ff/ClQgtPw9Q=\ngithub.com/Antonboom/errname v1.1.1/go.mod h1:gjhe24xoxXp0ScLtHzjiXp0Exi1RFLKJb0bVBtWKCWQ=\ngithub.com/Antonboom/nilnil v1.1.1 h1:9Mdr6BYd8WHCDngQnNVV0b554xyisFioEKi30sksufQ=\ngithub.com/Antonboom/nilnil v1.1.1/go.mod h1:yCyAmSw3doopbOWhJlVci+HuyNRuHJKIv6V2oYQa8II=\ngithub.com/Antonboom/testifylint v1.6.4 h1:gs9fUEy+egzxkEbq9P4cpcMB6/G0DYdMeiFS87UiqmQ=\ngithub.com/Antonboom/testifylint v1.6.4/go.mod h1:YO33FROXX2OoUfwjz8g+gUxQXio5i9qpVy7nXGbxDD4=\ngithub.com/BurntSushi/toml v1.5.0 h1:W5quZX/G/csjUnuI8SUYlsHs9M38FC7znL0lIO+DvMg=\ngithub.com/BurntSushi/toml v1.5.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho=\ngithub.com/Djarvur/go-err113 v0.1.1 h1:eHfopDqXRwAi+YmCUas75ZE0+hoBHJ2GQNLYRSxao4g=\ngithub.com/Djarvur/go-err113 v0.1.1/go.mod h1:IaWJdYFLg76t2ihfflPZnM1LIQszWOsFDh2hhhAVF6k=\ngithub.com/KimMachineGun/automemlimit v0.7.5 h1:RkbaC0MwhjL1ZuBKunGDjE/ggwAX43DwZrJqVwyveTk=\ngithub.com/KimMachineGun/automemlimit v0.7.5/go.mod h1:QZxpHaGOQoYvFhv/r4u3U0JTC2ZcOwbSr11UZF46UBM=\ngithub.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0=\ngithub.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM=\ngithub.com/Microsoft/go-winio v0.5.2/go.mod h1:WpS1mjBmmwHBEWmogvA2mj8546UReBk4v8QkMxJ6pZY=\ngithub.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=\ngithub.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=\ngithub.com/MirrexOne/unqueryvet v1.2.1 h1:M+zdXMq84g+E1YOLa7g7ExN3dWfZQrdDSTCM7gC+m/A=\ngithub.com/MirrexOne/unqueryvet v1.2.1/go.mod h1:IWwCwMQlSWjAIteW0t+28Q5vouyktfujzYznSIWiuOg=\ngithub.com/OpenPeeDeeP/depguard/v2 v2.2.1 h1:vckeWVESWp6Qog7UZSARNqfu/cZqvki8zsuj3piCMx4=\ngithub.com/OpenPeeDeeP/depguard/v2 v2.2.1/go.mod h1:q4DKzC4UcVaAvcfd41CZh0PWpGgzrVxUYBlgKNGquUo=\ngithub.com/ProtonMail/go-crypto v1.3.0 h1:ILq8+Sf5If5DCpHQp4PbZdS1J7HDFRXz/+xKBiRGFrw=\ngithub.com/ProtonMail/go-crypto v1.3.0/go.mod h1:9whxjD8Rbs29b4XWbB8irEcE8KHMqaR2e7GWU1R+/PE=\ngithub.com/a8m/envsubst v1.4.3 h1:kDF7paGK8QACWYaQo6KtyYBozY2jhQrTuNNuUxQkhJY=\ngithub.com/a8m/envsubst v1.4.3/go.mod h1:4jjHWQlZoaXPoLQUb7H2qT4iLkZDdmEQiOUogdUmqVU=\ngithub.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0=\ngithub.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=\ngithub.com/alecthomas/chroma/v2 v2.20.0 h1:sfIHpxPyR07/Oylvmcai3X/exDlE8+FA820NTz+9sGw=\ngithub.com/alecthomas/chroma/v2 v2.20.0/go.mod h1:e7tViK0xh/Nf4BYHl00ycY6rV7b8iXBksI9E359yNmA=\ngithub.com/alecthomas/go-check-sumtype v0.3.1 h1:u9aUvbGINJxLVXiFvHUlPEaD7VDULsrxJb4Aq31NLkU=\ngithub.com/alecthomas/go-check-sumtype v0.3.1/go.mod h1:A8TSiN3UPRw3laIgWEUOHHLPa6/r9MtoigdlP5h3K/E=\ngithub.com/alecthomas/repr v0.5.1 h1:E3G4t2QbHTSNpPKBgMTln5KLkZHLOcU7r37J4pXBuIg=\ngithub.com/alecthomas/repr v0.5.1/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=\ngithub.com/alexkohler/nakedret/v2 v2.0.6 h1:ME3Qef1/KIKr3kWX3nti3hhgNxw6aqN5pZmQiFSsuzQ=\ngithub.com/alexkohler/nakedret/v2 v2.0.6/go.mod h1:l3RKju/IzOMQHmsEvXwkqMDzHHvurNQfAgE1eVmT40Q=\ngithub.com/alexkohler/prealloc v1.0.0 h1:Hbq0/3fJPQhNkN0dR95AVrr6R7tou91y0uHG5pOcUuw=\ngithub.com/alexkohler/prealloc v1.0.0/go.mod h1:VetnK3dIgFBBKmg0YnD9F9x6Icjd+9cvfHR56wJVlKE=\ngithub.com/alfatraining/structtag v1.0.0 h1:2qmcUqNcCoyVJ0up879K614L9PazjBSFruTB0GOFjCc=\ngithub.com/alfatraining/structtag v1.0.0/go.mod h1:p3Xi5SwzTi+Ryj64DqjLWz7XurHxbGsq6y3ubePJPus=\ngithub.com/alingse/asasalint v0.0.11 h1:SFwnQXJ49Kx/1GghOFz1XGqHYKp21Kq1nHad/0WQRnw=\ngithub.com/alingse/asasalint v0.0.11/go.mod h1:nCaoMhw7a9kSJObvQyVzNTPBDbNpdocqrSP7t/cW5+I=\ngithub.com/alingse/nilnesserr v0.2.0 h1:raLem5KG7EFVb4UIDAXgrv3N2JIaffeKNtcEXkEWd/w=\ngithub.com/alingse/nilnesserr v0.2.0/go.mod h1:1xJPrXonEtX7wyTq8Dytns5P2hNzoWymVUIaKm4HNFg=\ngithub.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be h1:9AeTilPcZAjCFIImctFaOjnTIavg87rW78vTPkQqLI8=\ngithub.com/anmitsu/go-shlex v0.0.0-20200514113438-38f4b401e2be/go.mod h1:ySMOLuWl6zY27l47sB3qLNK6tF2fkHG55UZxx8oIVo4=\ngithub.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio=\ngithub.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs=\ngithub.com/ashanbrown/forbidigo/v2 v2.3.0 h1:OZZDOchCgsX5gvToVtEBoV2UWbFfI6RKQTir2UZzSxo=\ngithub.com/ashanbrown/forbidigo/v2 v2.3.0/go.mod h1:5p6VmsG5/1xx3E785W9fouMxIOkvY2rRV9nMdWadd6c=\ngithub.com/ashanbrown/makezero/v2 v2.1.0 h1:snuKYMbqosNokUKm+R6/+vOPs8yVAi46La7Ck6QYSaE=\ngithub.com/ashanbrown/makezero/v2 v2.1.0/go.mod h1:aEGT/9q3S8DHeE57C88z2a6xydvgx8J5hgXIGWgo0MY=\ngithub.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k=\ngithub.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8=\ngithub.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=\ngithub.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=\ngithub.com/bitfield/gotestdox v0.2.2 h1:x6RcPAbBbErKLnapz1QeAlf3ospg8efBsedU93CDsnE=\ngithub.com/bitfield/gotestdox v0.2.2/go.mod h1:D+gwtS0urjBrzguAkTM2wodsTQYFHdpx8eqRJ3N+9pY=\ngithub.com/bkielbasa/cyclop v1.2.3 h1:faIVMIGDIANuGPWH031CZJTi2ymOQBULs9H21HSMa5w=\ngithub.com/bkielbasa/cyclop v1.2.3/go.mod h1:kHTwA9Q0uZqOADdupvcFJQtp/ksSnytRMe8ztxG8Fuo=\ngithub.com/blizzy78/varnamelen v0.8.0 h1:oqSblyuQvFsW1hbBHh1zfwrKe3kcSj0rnXkKzsQ089M=\ngithub.com/blizzy78/varnamelen v0.8.0/go.mod h1:V9TzQZ4fLJ1DSrjVDfl89H7aMnTvKkApdHeyESmyR7k=\ngithub.com/bmatcuk/doublestar/v4 v4.0.2/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc=\ngithub.com/bmatcuk/doublestar/v4 v4.10.0 h1:zU9WiOla1YA122oLM6i4EXvGW62DvKZVxIe6TYWexEs=\ngithub.com/bmatcuk/doublestar/v4 v4.10.0/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc=\ngithub.com/bombsimon/wsl/v4 v4.7.0 h1:1Ilm9JBPRczjyUs6hvOPKvd7VL1Q++PL8M0SXBDf+jQ=\ngithub.com/bombsimon/wsl/v4 v4.7.0/go.mod h1:uV/+6BkffuzSAVYD+yGyld1AChO7/EuLrCF/8xTiapg=\ngithub.com/bombsimon/wsl/v5 v5.3.0 h1:nZWREJFL6U3vgW/B1lfDOigl+tEF6qgs6dGGbFeR0UM=\ngithub.com/bombsimon/wsl/v5 v5.3.0/go.mod h1:Gp8lD04z27wm3FANIUPZycXp+8huVsn0oxc+n4qfV9I=\ngithub.com/breml/bidichk v0.3.3 h1:WSM67ztRusf1sMoqH6/c4OBCUlRVTKq+CbSeo0R17sE=\ngithub.com/breml/bidichk v0.3.3/go.mod h1:ISbsut8OnjB367j5NseXEGGgO/th206dVa427kR8YTE=\ngithub.com/breml/errchkjson v0.4.1 h1:keFSS8D7A2T0haP9kzZTi7o26r7kE3vymjZNeNDRDwg=\ngithub.com/breml/errchkjson v0.4.1/go.mod h1:a23OvR6Qvcl7DG/Z4o0el6BRAjKnaReoPQFciAl9U3s=\ngithub.com/butuzov/ireturn v0.4.0 h1:+s76bF/PfeKEdbG8b54aCocxXmi0wvYdOVsWxVO7n8E=\ngithub.com/butuzov/ireturn v0.4.0/go.mod h1:ghI0FrCmap8pDWZwfPisFD1vEc56VKH4NpQUxDHta70=\ngithub.com/butuzov/mirror v1.3.0 h1:HdWCXzmwlQHdVhwvsfBb2Au0r3HyINry3bDWLYXiKoc=\ngithub.com/butuzov/mirror v1.3.0/go.mod h1:AEij0Z8YMALaq4yQj9CPPVYOyJQyiexpQEQgihajRfI=\ngithub.com/catenacyber/perfsprint v0.10.1 h1:u7Riei30bk46XsG8nknMhKLXG9BcXz3+3tl/WpKm0PQ=\ngithub.com/catenacyber/perfsprint v0.10.1/go.mod h1:DJTGsi/Zufpuus6XPGJyKOTMELe347o6akPvWG9Zcsc=\ngithub.com/ccojocar/zxcvbn-go v1.0.4 h1:FWnCIRMXPj43ukfX000kvBZvV6raSxakYr1nzyNrUcc=\ngithub.com/ccojocar/zxcvbn-go v1.0.4/go.mod h1:3GxGX+rHmueTUMvm5ium7irpyjmm7ikxYFOSJB21Das=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/charithe/durationcheck v0.0.11 h1:g1/EX1eIiKS57NTWsYtHDZ/APfeXKhye1DidBcABctk=\ngithub.com/charithe/durationcheck v0.0.11/go.mod h1:x5iZaixRNl8ctbM+3B2RrPG5t856TxRyVQEnbIEM2X4=\ngithub.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc h1:4pZI35227imm7yK2bGPcfpFEmuY1gc2YSTShr4iJBfs=\ngithub.com/charmbracelet/colorprofile v0.2.3-0.20250311203215-f60798e515dc/go.mod h1:X4/0JoqgTIPSFcRA/P6INZzIuyqdFY5rm8tb41s9okk=\ngithub.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=\ngithub.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=\ngithub.com/charmbracelet/x/ansi v0.8.0 h1:9GTq3xq9caJW8ZrBTe0LIe2fvfLR/bYXKTx2llXn7xE=\ngithub.com/charmbracelet/x/ansi v0.8.0/go.mod h1:wdYl/ONOLHLIVmQaxbIYEC/cRKOQyjTkowiI4blgS9Q=\ngithub.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd h1:vy0GVL4jeHEwG5YOXDmi86oYw2yuYUGqz6a8sLwg0X8=\ngithub.com/charmbracelet/x/cellbuf v0.0.13-0.20250311204145-2c3ea96c31dd/go.mod h1:xe0nKWGd3eJgtqZRaN9RjMtK7xUYchjzPr7q6kcvCCs=\ngithub.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=\ngithub.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=\ngithub.com/ckaznocha/intrange v0.3.1 h1:j1onQyXvHUsPWujDH6WIjhyH26gkRt/txNlV7LspvJs=\ngithub.com/ckaznocha/intrange v0.3.1/go.mod h1:QVepyz1AkUoFQkpEqksSYpNpUo3c5W7nWh/s6SHIJJk=\ngithub.com/client9/misspell v0.3.4 h1:ta993UF76GwbvJcIo3Y68y/M3WxlpEHPWIGDkJYwzJI=\ngithub.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=\ngithub.com/clipperhouse/uax29/v2 v2.2.0 h1:ChwIKnQN3kcZteTXMgb1wztSgaU+ZemkgWdohwgs8tY=\ngithub.com/clipperhouse/uax29/v2 v2.2.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJSwu5BF98AuoVM=\ngithub.com/cloudflare/circl v1.6.3 h1:9GPOhQGF9MCYUeXyMYlqTR6a5gTrgR/fBLXvUgtVcg8=\ngithub.com/cloudflare/circl v1.6.3/go.mod h1:2eXP6Qfat4O/Yhh8BznvKnJ+uzEoTQ6jVKJRn81BiS4=\ngithub.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=\ngithub.com/curioswitch/go-reassign v0.3.0 h1:dh3kpQHuADL3cobV/sSGETA8DOv457dwl+fbBAhrQPs=\ngithub.com/curioswitch/go-reassign v0.3.0/go.mod h1:nApPCCTtqLJN/s8HfItCcKV0jIPwluBOvZP+dsJGA88=\ngithub.com/cyphar/filepath-securejoin v0.5.0 h1:hIAhkRBMQ8nIeuVwcAoymp7MY4oherZdAxD+m0u9zaw=\ngithub.com/cyphar/filepath-securejoin v0.5.0/go.mod h1:Sdj7gXlvMcPZsbhwhQ33GguGLDGQL7h7bg04C/+u9jI=\ngithub.com/daixiang0/gci v0.13.7 h1:+0bG5eK9vlI08J+J/NWGbWPTNiXPG4WhNLJOkSxWITQ=\ngithub.com/daixiang0/gci v0.13.7/go.mod h1:812WVN6JLFY9S6Tv76twqmNqevN0pa3SX3nih0brVzQ=\ngithub.com/dave/dst v0.27.3 h1:P1HPoMza3cMEquVf9kKy8yXsFirry4zEnWOdYPOoIzY=\ngithub.com/dave/dst v0.27.3/go.mod h1:jHh6EOibnHgcUW3WjKHisiooEkYwqpHLBSX1iOBhEyc=\ngithub.com/dave/jennifer v1.7.1 h1:B4jJJDHelWcDhlRQxWeo0Npa/pYKBLrirAQoTN45txo=\ngithub.com/dave/jennifer v1.7.1/go.mod h1:nXbxhEmQfOZhWml3D1cDK5M1FLnMSozpbFN/m3RmGZc=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/denis-tingaikin/go-header v0.5.0 h1:SRdnP5ZKvcO9KKRP1KJrhFR3RrlGuD+42t4429eC9k8=\ngithub.com/denis-tingaikin/go-header v0.5.0/go.mod h1:mMenU5bWrok6Wl2UsZjy+1okegmwQ3UgWl4V1D8gjlY=\ngithub.com/dkorunic/betteralign v0.8.2 h1:f3sJ/vtuuPOFd2/U3TeGfv8p+VhEyoBLuA05q6mAosU=\ngithub.com/dkorunic/betteralign v0.8.2/go.mod h1:TAkhmNuJ3OKPAN7YgGTauiccHIc9ETjBmtE24fpLxOk=\ngithub.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=\ngithub.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=\ngithub.com/dnephin/pflag v1.0.7 h1:oxONGlWxhmUct0YzKTgrpQv9AUA1wtPBn7zuSjJqptk=\ngithub.com/dnephin/pflag v1.0.7/go.mod h1:uxE91IoWURlOiTUIA8Mq5ZZkAv3dPUfZNaT80Zm7OQE=\ngithub.com/elazarl/goproxy v1.7.2 h1:Y2o6urb7Eule09PjlhQRGNsqRfPmYI3KKQLFpCAV3+o=\ngithub.com/elazarl/goproxy v1.7.2/go.mod h1:82vkLNir0ALaW14Rc399OTTjyNREgmdL2cVoIbS6XaE=\ngithub.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc=\ngithub.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ=\ngithub.com/ettle/strcase v0.2.0 h1:fGNiVF21fHXpX1niBgk0aROov1LagYsOwV/xqKDKR/Q=\ngithub.com/ettle/strcase v0.2.0/go.mod h1:DajmHElDSaX76ITe3/VHVyMin4LWSJN5Z909Wp+ED1A=\ngithub.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM=\ngithub.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU=\ngithub.com/fatih/structtag v1.2.0 h1:/OdNE99OxoI/PqaW/SuSK9uxxT3f/tcSZgon/ssNSx4=\ngithub.com/fatih/structtag v1.2.0/go.mod h1:mBJUNpUnHmRKrKlQQlmCrh5PuhftFbNv8Ys4/aAZl94=\ngithub.com/firefart/nonamedreturns v1.0.6 h1:vmiBcKV/3EqKY3ZiPxCINmpS431OcE1S47AQUwhrg8E=\ngithub.com/firefart/nonamedreturns v1.0.6/go.mod h1:R8NisJnSIpvPWheCq0mNRXJok6D8h7fagJTF8EMEwCo=\ngithub.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=\ngithub.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/fzipp/gocyclo v0.6.0 h1:lsblElZG7d3ALtGMx9fmxeTKZaLLpU8mET09yN4BBLo=\ngithub.com/fzipp/gocyclo v0.6.0/go.mod h1:rXPyn8fnlpa0R2csP/31uerbiVBugk5whMdlyaLkLoA=\ngithub.com/ghostiam/protogetter v0.3.18 h1:yEpghRGtP9PjKvVXtEzGpYfQj1Wl/ZehAfU6fr62Lfo=\ngithub.com/ghostiam/protogetter v0.3.18/go.mod h1:FjIu5Yfs6FT391m+Fjp3fbAYJ6rkL/J6ySpZBfnODuI=\ngithub.com/gliderlabs/ssh v0.3.8 h1:a4YXD1V7xMF9g5nTkdfnja3Sxy1PVDCj1Zg4Wb8vY6c=\ngithub.com/gliderlabs/ssh v0.3.8/go.mod h1:xYoytBv1sV0aL3CavoDuJIQNURXkkfPA/wxQ1pL1fAU=\ngithub.com/go-critic/go-critic v0.14.2 h1:PMvP5f+LdR8p6B29npvChUXbD1vrNlKDf60NJtgMBOo=\ngithub.com/go-critic/go-critic v0.14.2/go.mod h1:xwntfW6SYAd7h1OqDzmN6hBX/JxsEKl5up/Y2bsxgVQ=\ngithub.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376 h1:+zs/tPmkDkHx3U66DAb0lQFJrpS6731Oaa12ikc+DiI=\ngithub.com/go-git/gcfg v1.5.1-0.20230307220236-3a3c6141e376/go.mod h1:an3vInlBmSxCcxctByoQdvwPiA7DTK7jaaFDBTtu0ic=\ngithub.com/go-git/go-billy/v5 v5.6.2 h1:6Q86EsPXMa7c3YZ3aLAQsMA0VlWmy43r6FHqa/UNbRM=\ngithub.com/go-git/go-billy/v5 v5.6.2/go.mod h1:rcFC2rAsp/erv7CMz9GczHcuD0D32fWzH+MJAU+jaUU=\ngithub.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399 h1:eMje31YglSBqCdIqdhKBW8lokaMrL3uTkpGYlE2OOT4=\ngithub.com/go-git/go-git-fixtures/v4 v4.3.2-0.20231010084843-55a94097c399/go.mod h1:1OCfN199q1Jm3HZlxleg+Dw/mwps2Wbk9frAWm+4FII=\ngithub.com/go-git/go-git/v5 v5.16.5 h1:mdkuqblwr57kVfXri5TTH+nMFLNUxIj9Z7F5ykFbw5s=\ngithub.com/go-git/go-git/v5 v5.16.5/go.mod h1:QOMLpNf1qxuSY4StA/ArOdfFR2TrKEjJiye2kel2m+M=\ngithub.com/go-json-experiment/json v0.0.0-20250813233538-9b1f9ea2e11b h1:6Q4zRHXS/YLOl9Ng1b1OOOBWMidAQZR3Gel0UKPC/KU=\ngithub.com/go-json-experiment/json v0.0.0-20250813233538-9b1f9ea2e11b/go.mod h1:TiCD2a1pcmjd7YnhGH0f/zKNcCD06B029pHhzV23c2M=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-quicktest/qt v1.101.0 h1:O1K29Txy5P2OK0dGo59b7b0LR6wKfIhttaAhHUyn7eI=\ngithub.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow=\ngithub.com/go-task/slim-sprig/v3 v3.0.0 h1:sUs3vkvUymDpBKi3qH1YSqBQk9+9D/8M2mN1vB6EwHI=\ngithub.com/go-task/slim-sprig/v3 v3.0.0/go.mod h1:W848ghGpv3Qj3dhTPRyJypKRiqCdHZiAzKg9hl15HA8=\ngithub.com/go-toolsmith/astcast v1.1.0 h1:+JN9xZV1A+Re+95pgnMgDboWNVnIMMQXwfBwLRPgSC8=\ngithub.com/go-toolsmith/astcast v1.1.0/go.mod h1:qdcuFWeGGS2xX5bLM/c3U9lewg7+Zu4mr+xPwZIB4ZU=\ngithub.com/go-toolsmith/astcopy v1.1.0 h1:YGwBN0WM+ekI/6SS6+52zLDEf8Yvp3n2seZITCUBt5s=\ngithub.com/go-toolsmith/astcopy v1.1.0/go.mod h1:hXM6gan18VA1T/daUEHCFcYiW8Ai1tIwIzHY6srfEAw=\ngithub.com/go-toolsmith/astequal v1.0.3/go.mod h1:9Ai4UglvtR+4up+bAD4+hCj7iTo4m/OXVTSLnCyTAx4=\ngithub.com/go-toolsmith/astequal v1.1.0/go.mod h1:sedf7VIdCL22LD8qIvv7Nn9MuWJruQA/ysswh64lffQ=\ngithub.com/go-toolsmith/astequal v1.2.0 h1:3Fs3CYZ1k9Vo4FzFhwwewC3CHISHDnVUPC4x0bI2+Cw=\ngithub.com/go-toolsmith/astequal v1.2.0/go.mod h1:c8NZ3+kSFtFY/8lPso4v8LuJjdJiUFVnSuU3s0qrrDY=\ngithub.com/go-toolsmith/astfmt v1.1.0 h1:iJVPDPp6/7AaeLJEruMsBUlOYCmvg0MoCfJprsOmcco=\ngithub.com/go-toolsmith/astfmt v1.1.0/go.mod h1:OrcLlRwu0CuiIBp/8b5PYF9ktGVZUjlNMV634mhwuQ4=\ngithub.com/go-toolsmith/astp v1.1.0 h1:dXPuCl6u2llURjdPLLDxJeZInAeZ0/eZwFJmqZMnpQA=\ngithub.com/go-toolsmith/astp v1.1.0/go.mod h1:0T1xFGz9hicKs8Z5MfAqSUitoUYS30pDMsRVIDHs8CA=\ngithub.com/go-toolsmith/pkgload v1.2.2 h1:0CtmHq/02QhxcF7E9N5LIFcYFsMR5rdovfqTtRKkgIk=\ngithub.com/go-toolsmith/pkgload v1.2.2/go.mod h1:R2hxLNRKuAsiXCo2i5J6ZQPhnPMOVtU+f0arbFPWCus=\ngithub.com/go-toolsmith/strparse v1.0.0/go.mod h1:YI2nUKP9YGZnL/L1/DLFBfixrcjslWct4wyljWhSRy8=\ngithub.com/go-toolsmith/strparse v1.1.0 h1:GAioeZUK9TGxnLS+qfdqNbA4z0SSm5zVNtCQiyP2Bvw=\ngithub.com/go-toolsmith/strparse v1.1.0/go.mod h1:7ksGy58fsaQkGQlY8WVoBFNyEPMGuJin1rfoPS4lBSQ=\ngithub.com/go-toolsmith/typep v1.1.0 h1:fIRYDyF+JywLfqzyhdiHzRop/GQDxxNhLGQ6gFUNHus=\ngithub.com/go-toolsmith/typep v1.1.0/go.mod h1:fVIw+7zjdsMxDA3ITWnH1yOiw1rnTQKCsF/sk2H/qig=\ngithub.com/go-viper/mapstructure/v2 v2.4.0 h1:EBsztssimR/CONLSZZ04E8qAkxNYq4Qp9LvH92wZUgs=\ngithub.com/go-viper/mapstructure/v2 v2.4.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/go-xmlfmt/xmlfmt v1.1.3 h1:t8Ey3Uy7jDSEisW2K3somuMKIpzktkWptA0iFCnRUWY=\ngithub.com/go-xmlfmt/xmlfmt v1.1.3/go.mod h1:aUCEOzzezBEjDBbFBoSiya/gduyIiWYRP6CnSFIV8AM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/goccy/go-json v0.10.5 h1:Fq85nIqj+gXn/S5ahsiTlK3TmC85qgirsdTP/+DeaC4=\ngithub.com/goccy/go-json v0.10.5/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M=\ngithub.com/goccy/go-yaml v1.18.0 h1:8W7wMFS12Pcas7KU+VVkaiCng+kG8QiFeFwzFb+rwuw=\ngithub.com/goccy/go-yaml v1.18.0/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA=\ngithub.com/godoc-lint/godoc-lint v0.10.1 h1:ZPUVzlDtJfA+P688JfPJPkI/SuzcBr/753yGIk5bOPA=\ngithub.com/godoc-lint/godoc-lint v0.10.1/go.mod h1:KleLcHu/CGSvkjUH2RvZyoK1MBC7pDQg4NxMYLcBBsw=\ngithub.com/gofrs/flock v0.13.0 h1:95JolYOvGMqeH31+FC7D2+uULf6mG61mEZ/A8dRYMzw=\ngithub.com/gofrs/flock v0.13.0/go.mod h1:jxeyy9R1auM5S6JYDBhDt+E2TCo7DkratH4Pgi8P+Z0=\ngithub.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ=\ngithub.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8/go.mod h1:wcDNUvekVysuuOpQKo3191zZyTpiI6se1N1ULghS0sw=\ngithub.com/golangci/asciicheck v0.5.0 h1:jczN/BorERZwK8oiFBOGvlGPknhvq0bjnysTj4nUfo0=\ngithub.com/golangci/asciicheck v0.5.0/go.mod h1:5RMNAInbNFw2krqN6ibBxN/zfRFa9S6tA1nPdM0l8qQ=\ngithub.com/golangci/dupl v0.0.0-20250308024227-f665c8d69b32 h1:WUvBfQL6EW/40l6OmeSBYQJNSif4O11+bmWEz+C7FYw=\ngithub.com/golangci/dupl v0.0.0-20250308024227-f665c8d69b32/go.mod h1:NUw9Zr2Sy7+HxzdjIULge71wI6yEg1lWQr7Evcu8K0E=\ngithub.com/golangci/go-printf-func-name v0.1.1 h1:hIYTFJqAGp1iwoIfsNTpoq1xZAarogrvjO9AfiW3B4U=\ngithub.com/golangci/go-printf-func-name v0.1.1/go.mod h1:Es64MpWEZbh0UBtTAICOZiB+miW53w/K9Or/4QogJss=\ngithub.com/golangci/gofmt v0.0.0-20250106114630-d62b90e6713d h1:viFft9sS/dxoYY0aiOTsLKO2aZQAPT4nlQCsimGcSGE=\ngithub.com/golangci/gofmt v0.0.0-20250106114630-d62b90e6713d/go.mod h1:ivJ9QDg0XucIkmwhzCDsqcnxxlDStoTl89jDMIoNxKY=\ngithub.com/golangci/golangci-lint/v2 v2.6.2 h1:jkMSVv36JmyTENcEertckvimvjPcD5qxNM7W7qhECvI=\ngithub.com/golangci/golangci-lint/v2 v2.6.2/go.mod h1:fSIMDiBt9kzdpnvvV7GO6iWzyv5uaeZ+iPor+2uRczE=\ngithub.com/golangci/golines v0.0.0-20250217134842-442fd0091d95 h1:AkK+w9FZBXlU/xUmBtSJN1+tAI4FIvy5WtnUnY8e4p8=\ngithub.com/golangci/golines v0.0.0-20250217134842-442fd0091d95/go.mod h1:k9mmcyWKSTMcPPvQUCfRWWQ9VHJ1U9Dc0R7kaXAgtnQ=\ngithub.com/golangci/misspell v0.7.0 h1:4GOHr/T1lTW0hhR4tgaaV1WS/lJ+ncvYCoFKmqJsj0c=\ngithub.com/golangci/misspell v0.7.0/go.mod h1:WZyyI2P3hxPY2UVHs3cS8YcllAeyfquQcKfdeE9AFVg=\ngithub.com/golangci/plugin-module-register v0.1.2 h1:e5WM6PO6NIAEcij3B053CohVp3HIYbzSuP53UAYgOpg=\ngithub.com/golangci/plugin-module-register v0.1.2/go.mod h1:1+QGTsKBvAIvPvoY/os+G5eoqxWn70HYDm2uvUyGuVw=\ngithub.com/golangci/revgrep v0.8.0 h1:EZBctwbVd0aMeRnNUsFogoyayvKHyxlV3CdUA46FX2s=\ngithub.com/golangci/revgrep v0.8.0/go.mod h1:U4R/s9dlXZsg8uJmaR1GrloUr14D7qDl8gi2iPXJH8k=\ngithub.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e h1:ai0EfmVYE2bRA5htgAG9r7s3tHsfjIhN98WshBTJ9jM=\ngithub.com/golangci/swaggoswag v0.0.0-20250504205917-77f2aca3143e/go.mod h1:Vrn4B5oR9qRwM+f54koyeH3yzphlecwERs0el27Fr/s=\ngithub.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e h1:gD6P7NEo7Eqtt0ssnqSJNNndxe69DOQ24A5h7+i3KpM=\ngithub.com/golangci/unconvert v0.0.0-20250410112200-a129a6e6413e/go.mod h1:h+wZwLjUTJnm/P2rwlbJdRPZXOzaT36/FwnPnY2inzc=\ngithub.com/google/addlicense v1.2.0 h1:W+DP4A639JGkcwBGMDvjSurZHvaq2FN0pP7se9czsKA=\ngithub.com/google/addlicense v1.2.0/go.mod h1:Sm/DHu7Jk+T5miFHHehdIjbi4M5+dJDRS3Cq0rncIxA=\ngithub.com/google/go-cmdtest v0.4.1-0.20220921163831-55ab3332a786 h1:rcv+Ippz6RAtvaGgKxc+8FQIpxHgsF+HBzPyYL2cyVU=\ngithub.com/google/go-cmdtest v0.4.1-0.20220921163831-55ab3332a786/go.mod h1:apVn/GCasLZUVpAJ6oWAuyP7Ne7CEsQbTnc0plM3m+o=\ngithub.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=\ngithub.com/google/go-cmp v0.5.4/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=\ngithub.com/google/go-cmp v0.5.8/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/go-github/v76 v76.0.0 h1:MCa9VQn+VG5GG7Y7BAkBvSRUN3o+QpaEOuZwFPJmdFA=\ngithub.com/google/go-github/v76 v76.0.0/go.mod h1:38+d/8pYDO4fBLYfBhXF5EKO0wA3UkXBjfmQapFsNCQ=\ngithub.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8=\ngithub.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU=\ngithub.com/google/pprof v0.0.0-20250820193118-f64d9cf942d6 h1:EEHtgt9IwisQ2AZ4pIsMjahcegHh6rmhqxzIRQIyepY=\ngithub.com/google/pprof v0.0.0-20250820193118-f64d9cf942d6/go.mod h1:I6V7YzU0XDpsHqbsyrghnFZLO1gwK6NPTNvmetQIk9U=\ngithub.com/google/renameio v0.1.0 h1:GOZbcHa3HfsPKPlmyPyN2KEohoMXOhdMbHrvbpl2QaA=\ngithub.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=\ngithub.com/google/renameio/v2 v2.0.1 h1:HyOM6qd9gF9sf15AvhbptGHUnaLTpEI9akAFFU3VyW0=\ngithub.com/google/renameio/v2 v2.0.1/go.mod h1:BtmJXm5YlszgC+TD4HOEEUFgkJP3nLxehU6hfe7jRt4=\ngithub.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4=\ngithub.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ=\ngithub.com/gordonklaus/ineffassign v0.2.0 h1:Uths4KnmwxNJNzq87fwQQDDnbNb7De00VOk9Nu0TySs=\ngithub.com/gordonklaus/ineffassign v0.2.0/go.mod h1:TIpymnagPSexySzs7F9FnO1XFTy8IT3a59vmZp5Y9Lw=\ngithub.com/gostaticanalysis/analysisutil v0.7.1 h1:ZMCjoue3DtDWQ5WyU16YbjbQEQ3VuzwxALrpYd+HeKk=\ngithub.com/gostaticanalysis/analysisutil v0.7.1/go.mod h1:v21E3hY37WKMGSnbsw2S/ojApNWb6C1//mXO48CXbVc=\ngithub.com/gostaticanalysis/comment v1.4.2/go.mod h1:KLUTGDv6HOCotCH8h2erHKmpci2ZoR8VPu34YA2uzdM=\ngithub.com/gostaticanalysis/comment v1.5.0 h1:X82FLl+TswsUMpMh17srGRuKaaXprTaytmEpgnKIDu8=\ngithub.com/gostaticanalysis/comment v1.5.0/go.mod h1:V6eb3gpCv9GNVqb6amXzEUX3jXLVK/AdA+IrAMSqvEc=\ngithub.com/gostaticanalysis/forcetypeassert v0.2.0 h1:uSnWrrUEYDr86OCxWa4/Tp2jeYDlogZiZHzGkWFefTk=\ngithub.com/gostaticanalysis/forcetypeassert v0.2.0/go.mod h1:M5iPavzE9pPqWyeiVXSFghQjljW1+l/Uke3PXHS6ILY=\ngithub.com/gostaticanalysis/nilerr v0.1.2 h1:S6nk8a9N8g062nsx63kUkF6AzbHGw7zzyHMcpu52xQU=\ngithub.com/gostaticanalysis/nilerr v0.1.2/go.mod h1:A19UHhoY3y8ahoL7YKz6sdjDtduwTSI4CsymaC2htPA=\ngithub.com/gostaticanalysis/testutil v0.3.1-0.20210208050101-bfb5c8eec0e4/go.mod h1:D+FIZ+7OahH3ePw/izIEeH5I06eKs1IKI4Xr64/Am3M=\ngithub.com/gostaticanalysis/testutil v0.5.0 h1:Dq4wT1DdTwTGCQQv3rl3IvD5Ld0E6HiY+3Zh0sUGqw8=\ngithub.com/gostaticanalysis/testutil v0.5.0/go.mod h1:OLQSbuM6zw2EvCcXTz1lVq5unyoNft372msDY0nY5Hs=\ngithub.com/hashicorp/go-cleanhttp v0.5.2 h1:035FKYIWjmULyFRBKPs8TBQoi0x6d9G4xc9neXJWAZQ=\ngithub.com/hashicorp/go-cleanhttp v0.5.2/go.mod h1:kO/YDlP8L1346E6Sodw+PrpBSV4/SoxCXGY6BqNFT48=\ngithub.com/hashicorp/go-hclog v1.6.3 h1:Qr2kF+eVWjTiYmU7Y31tYlP1h0q/X3Nl3tPGdaB11/k=\ngithub.com/hashicorp/go-hclog v1.6.3/go.mod h1:W4Qnvbt70Wk/zYJryRzDRU/4r0kIg0PVHBcfoyhpF5M=\ngithub.com/hashicorp/go-immutable-radix/v2 v2.1.0 h1:CUW5RYIcysz+D3B+l1mDeXrQ7fUvGGCwJfdASSzbrfo=\ngithub.com/hashicorp/go-immutable-radix/v2 v2.1.0/go.mod h1:hgdqLXA4f6NIjRVisM1TJ9aOJVNRqKZj+xDGF6m7PBw=\ngithub.com/hashicorp/go-retryablehttp v0.7.8 h1:ylXZWnqa7Lhqpk0L1P1LzDtGcCR0rPVUrx/c8Unxc48=\ngithub.com/hashicorp/go-retryablehttp v0.7.8/go.mod h1:rjiScheydd+CxvumBsIrFKlx3iS0jrZ7LvzFGFmuKbw=\ngithub.com/hashicorp/go-uuid v1.0.3 h1:2gKiV6YVmrJ1i2CKKa9obLvRieoRGviZFL26PcT/Co8=\ngithub.com/hashicorp/go-uuid v1.0.3/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=\ngithub.com/hashicorp/go-version v1.2.1/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/hashicorp/go-version v1.7.0 h1:5tqGy27NaOTB8yJKUZELlFAS/LTKJkrmONwQKeRZfjY=\ngithub.com/hashicorp/go-version v1.7.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=\ngithub.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=\ngithub.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg=\ngithub.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=\ngithub.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=\ngithub.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99 h1:BQSFePA1RWJOlocH6Fxy8MmwDt+yVQYULKfN0RoTN8A=\ngithub.com/jbenet/go-context v0.0.0-20150711004518-d14ea06fba99/go.mod h1:1lJo3i6rXxKeerYnT8Nvf0QmHCRC1n8sfWVwXF2Frvo=\ngithub.com/jcchavezs/porto v0.7.0 h1:VncK84yxV7QZD4GdvoslzjnieSuruztGxLCmFi/Eu28=\ngithub.com/jcchavezs/porto v0.7.0/go.mod h1:tQ1cJ85cNzzZg/58VuZWOLbmrjcH1wPxkWgeBjvOq5o=\ngithub.com/jgautheron/goconst v1.8.2 h1:y0XF7X8CikZ93fSNT6WBTb/NElBu9IjaY7CCYQrCMX4=\ngithub.com/jgautheron/goconst v1.8.2/go.mod h1:A0oxgBCHy55NQn6sYpO7UdnA9p+h7cPtoOZUmvNIako=\ngithub.com/jingyugao/rowserrcheck v1.1.1 h1:zibz55j/MJtLsjP1OF4bSdgXxwL1b+Vn7Tjzq7gFzUs=\ngithub.com/jingyugao/rowserrcheck v1.1.1/go.mod h1:4yvlZSDb3IyDTUZJUmpZfm2Hwok+Dtp+nu2qOq+er9c=\ngithub.com/jjti/go-spancheck v0.6.5 h1:lmi7pKxa37oKYIMScialXUK6hP3iY5F1gu+mLBPgYB8=\ngithub.com/jjti/go-spancheck v0.6.5/go.mod h1:aEogkeatBrbYsyW6y5TgDfihCulDYciL1B7rG2vSsrU=\ngithub.com/julz/importas v0.2.0 h1:y+MJN/UdL63QbFJHws9BVC5RpA2iq0kpjrFajTGivjQ=\ngithub.com/julz/importas v0.2.0/go.mod h1:pThlt589EnCYtMnmhmRYY/qn9lCf/frPOK+WMx3xiJY=\ngithub.com/kaptinlin/go-i18n v0.1.6 h1:XQT3qvE/xgNrAps/zXBHAKWhPlWSrFS9t1jCZ4PVnOs=\ngithub.com/kaptinlin/go-i18n v0.1.6/go.mod h1:MoHPYUYQug2jyLygIWeT9F3VDUZEP480cKotmtQjUCc=\ngithub.com/kaptinlin/jsonschema v0.4.12 h1:10cy+j2b69jyOX+F+u9suLK2dw0k63UqzUNctpxiV3A=\ngithub.com/kaptinlin/jsonschema v0.4.12/go.mod h1:zG+WOWvAxUaPUnh83QrV/a/fsfloI6L6d/YM4mtZCHw=\ngithub.com/kaptinlin/messageformat-go v0.4.0 h1:L5wPgwQZkV1Rvs19htUT2RGx8N1GCq3uQG5nB6VHRcM=\ngithub.com/kaptinlin/messageformat-go v0.4.0/go.mod h1:LrLCV49C5ms/BZlOpFPihou+cPvhOQSvVJHj2wOe6w8=\ngithub.com/karamaru-alpha/copyloopvar v1.2.2 h1:yfNQvP9YaGQR7VaWLYcfZUlRP2eo2vhExWKxD/fP6q0=\ngithub.com/karamaru-alpha/copyloopvar v1.2.2/go.mod h1:oY4rGZqZ879JkJMtX3RRkcXRkmUvH0x35ykgaKgsgJY=\ngithub.com/kevinburke/ssh_config v1.4.0 h1:6xxtP5bZ2E4NF5tuQulISpTO2z8XbtH8cg1PWkxoFkQ=\ngithub.com/kevinburke/ssh_config v1.4.0/go.mod h1:q2RIzfka+BXARoNexmF9gkxEX7DmvbW9P4hIVx2Kg4M=\ngithub.com/kisielk/errcheck v1.9.0 h1:9xt1zI9EBfcYBvdU1nVrzMzzUPUtPKs9bVSIM3TAb3M=\ngithub.com/kisielk/errcheck v1.9.0/go.mod h1:kQxWMMVZgIkDq7U8xtG/n2juOjbLgZtedi0D+/VL/i8=\ngithub.com/kisielk/gotool v1.0.0 h1:AV2c/EiW3KqPNT9ZKl07ehoAGi4C5/01Cfbblndcapg=\ngithub.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=\ngithub.com/kkHAIKE/contextcheck v1.1.6 h1:7HIyRcnyzxL9Lz06NGhiKvenXq7Zw6Q0UQu/ttjfJCE=\ngithub.com/kkHAIKE/contextcheck v1.1.6/go.mod h1:3dDbMRNBFaq8HFXWC1JyvDSPm43CmE6IuHam8Wr0rkg=\ngithub.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=\ngithub.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=\ngithub.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=\ngithub.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/kulti/thelper v0.7.1 h1:fI8QITAoFVLx+y+vSyuLBP+rcVIB8jKooNSCT2EiI98=\ngithub.com/kulti/thelper v0.7.1/go.mod h1:NsMjfQEy6sd+9Kfw8kCP61W1I0nerGSYSFnGaxQkcbs=\ngithub.com/kunwardeep/paralleltest v1.0.15 h1:ZMk4Qt306tHIgKISHWFJAO1IDQJLc6uDyJMLyncOb6w=\ngithub.com/kunwardeep/paralleltest v1.0.15/go.mod h1:di4moFqtfz3ToSKxhNjhOZL+696QtJGCFe132CbBLGk=\ngithub.com/lasiar/canonicalheader v1.1.2 h1:vZ5uqwvDbyJCnMhmFYimgMZnJMjwljN5VGY0VKbMXb4=\ngithub.com/lasiar/canonicalheader v1.1.2/go.mod h1:qJCeLFS0G/QlLQ506T+Fk/fWMa2VmBUiEI2cuMK4djI=\ngithub.com/ldez/exptostd v0.4.5 h1:kv2ZGUVI6VwRfp/+bcQ6Nbx0ghFWcGIKInkG/oFn1aQ=\ngithub.com/ldez/exptostd v0.4.5/go.mod h1:QRjHRMXJrCTIm9WxVNH6VW7oN7KrGSht69bIRwvdFsM=\ngithub.com/ldez/gomoddirectives v0.7.1 h1:FaULkvUIG36hj6chpwa+FdCNGZBsD7/fO+p7CCsM6pE=\ngithub.com/ldez/gomoddirectives v0.7.1/go.mod h1:auDNtakWJR1rC+YX7ar+HmveqXATBAyEK1KYpsIRW/8=\ngithub.com/ldez/grignotin v0.10.1 h1:keYi9rYsgbvqAZGI1liek5c+jv9UUjbvdj3Tbn5fn4o=\ngithub.com/ldez/grignotin v0.10.1/go.mod h1:UlDbXFCARrXbWGNGP3S5vsysNXAPhnSuBufpTEbwOas=\ngithub.com/ldez/tagliatelle v0.7.2 h1:KuOlL70/fu9paxuxbeqlicJnCspCRjH0x8FW+NfgYUk=\ngithub.com/ldez/tagliatelle v0.7.2/go.mod h1:PtGgm163ZplJfZMZ2sf5nhUT170rSuPgBimoyYtdaSI=\ngithub.com/ldez/usetesting v0.5.0 h1:3/QtzZObBKLy1F4F8jLuKJiKBjjVFi1IavpoWbmqLwc=\ngithub.com/ldez/usetesting v0.5.0/go.mod h1:Spnb4Qppf8JTuRgblLrEWb7IE6rDmUpGvxY3iRrzvDQ=\ngithub.com/leonklingele/grouper v1.1.2 h1:o1ARBDLOmmasUaNDesWqWCIFH3u7hoFlM84YrjT3mIY=\ngithub.com/leonklingele/grouper v1.1.2/go.mod h1:6D0M/HVkhs2yRKRFZUoGjeDy7EZTfFBE9gl4kjmIGkA=\ngithub.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY=\ngithub.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=\ngithub.com/macabu/inamedparam v0.2.0 h1:VyPYpOc10nkhI2qeNUdh3Zket4fcZjEWe35poddBCpE=\ngithub.com/macabu/inamedparam v0.2.0/go.mod h1:+Pee9/YfGe5LJ62pYXqB89lJ+0k5bsR8Wgz/C0Zlq3U=\ngithub.com/manuelarte/embeddedstructfieldcheck v0.4.0 h1:3mAIyaGRtjK6EO9E73JlXLtiy7ha80b2ZVGyacxgfww=\ngithub.com/manuelarte/embeddedstructfieldcheck v0.4.0/go.mod h1:z8dFSyXqp+fC6NLDSljRJeNQJJDWnY7RoWFzV3PC6UM=\ngithub.com/manuelarte/funcorder v0.5.0 h1:llMuHXXbg7tD0i/LNw8vGnkDTHFpTnWqKPI85Rknc+8=\ngithub.com/manuelarte/funcorder v0.5.0/go.mod h1:Yt3CiUQthSBMBxjShjdXMexmzpP8YGvGLjrxJNkO2hA=\ngithub.com/maratori/testableexamples v1.0.1 h1:HfOQXs+XgfeRBJ+Wz0XfH+FHnoY9TVqL6Fcevpzy4q8=\ngithub.com/maratori/testableexamples v1.0.1/go.mod h1:XE2F/nQs7B9N08JgyRmdGjYVGqxWwClLPCGSQhXQSrQ=\ngithub.com/maratori/testpackage v1.1.2 h1:ffDSh+AgqluCLMXhM19f/cpvQAKygKAJXFl9aUjmbqs=\ngithub.com/maratori/testpackage v1.1.2/go.mod h1:8F24GdVDFW5Ew43Et02jamrVMNXLUNaOynhDssITGfc=\ngithub.com/matoous/godox v1.1.0 h1:W5mqwbyWrwZv6OQ5Z1a/DHGMOvXYCBP3+Ht7KMoJhq4=\ngithub.com/matoous/godox v1.1.0/go.mod h1:jgE/3fUXiTurkdHOLT5WEkThTSuE7yxHv5iWPa80afs=\ngithub.com/matryer/is v1.4.0 h1:sosSmIWwkYITGrxZ25ULNDeKiMNzFSr4V/eqBQP0PeE=\ngithub.com/matryer/is v1.4.0/go.mod h1:8I/i5uYgLzgsgEloJE1U6xx5HkBQpAZvepWuujKwMRU=\ngithub.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE=\ngithub.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8=\ngithub.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=\ngithub.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=\ngithub.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=\ngithub.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=\ngithub.com/mattn/go-shellwords v1.0.12 h1:M2zGm7EW6UQJvDeQxo4T51eKPurbeFbe8WtebGE2xrk=\ngithub.com/mattn/go-shellwords v1.0.12/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y=\ngithub.com/mgechev/revive v1.12.0 h1:Q+/kkbbwerrVYPv9d9efaPGmAO/NsxwW/nE6ahpQaCU=\ngithub.com/mgechev/revive v1.12.0/go.mod h1:VXsY2LsTigk8XU9BpZauVLjVrhICMOV3k1lpB3CXrp8=\ngithub.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=\ngithub.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=\ngithub.com/moricho/tparallel v0.3.2 h1:odr8aZVFA3NZrNybggMkYO3rgPRcqjeQUlBBFVxKHTI=\ngithub.com/moricho/tparallel v0.3.2/go.mod h1:OQ+K3b4Ln3l2TZveGCywybl68glfLEwFGqvnjok8b+U=\ngithub.com/muesli/termenv v0.16.0 h1:S5AlUN9dENB57rsbnkPyfdGuWIlkmzJjbFf0Tf5FWUc=\ngithub.com/muesli/termenv v0.16.0/go.mod h1:ZRfOIKPFDYQoDFF4Olj7/QJbW60Ol/kL1pU3VfY/Cnk=\ngithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=\ngithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=\ngithub.com/nakabonne/nestif v0.3.1 h1:wm28nZjhQY5HyYPx+weN3Q65k6ilSBxDb8v5S81B81U=\ngithub.com/nakabonne/nestif v0.3.1/go.mod h1:9EtoZochLn5iUprVDmDjqGKPofoUEBL8U4Ngq6aY7OE=\ngithub.com/nishanths/exhaustive v0.12.0 h1:vIY9sALmw6T/yxiASewa4TQcFsVYZQQRUQJhKRf3Swg=\ngithub.com/nishanths/exhaustive v0.12.0/go.mod h1:mEZ95wPIZW+x8kC4TgC+9YCUgiST7ecevsVDTgc2obs=\ngithub.com/nishanths/predeclared v0.2.2 h1:V2EPdZPliZymNAn79T8RkNApBjMmVKh5XRpLm/w98Vk=\ngithub.com/nishanths/predeclared v0.2.2/go.mod h1:RROzoN6TnGQupbC+lqggsOlcgysk3LMK/HI84Mp280c=\ngithub.com/nunnatsa/ginkgolinter v0.21.2 h1:khzWfm2/Br8ZemX8QM1pl72LwM+rMeW6VUbQ4rzh0Po=\ngithub.com/nunnatsa/ginkgolinter v0.21.2/go.mod h1:GItSI5fw7mCGLPmkvGYrr1kEetZe7B593jcyOpyabsY=\ngithub.com/onsi/ginkgo/v2 v2.26.0 h1:1J4Wut1IlYZNEAWIV3ALrT9NfiaGW2cDCJQSFQMs/gE=\ngithub.com/onsi/ginkgo/v2 v2.26.0/go.mod h1:qhEywmzWTBUY88kfO0BRvX4py7scov9yR+Az2oavUzw=\ngithub.com/onsi/gomega v1.38.2 h1:eZCjf2xjZAqe+LeWvKb5weQ+NcPwX84kqJ0cZNxok2A=\ngithub.com/onsi/gomega v1.38.2/go.mod h1:W2MJcYxRGV63b418Ai34Ud0hEdTVXq9NW9+Sx6uXf3k=\ngithub.com/otiai10/copy v1.2.0/go.mod h1:rrF5dJ5F0t/EWSYODDu4j9/vEeYHMkc8jt0zJChqQWw=\ngithub.com/otiai10/copy v1.14.1 h1:5/7E6qsUMBaH5AnQ0sSLzzTg1oTECmcCmT6lvF45Na8=\ngithub.com/otiai10/copy v1.14.1/go.mod h1:oQwrEDDOci3IM8dJF0d8+jnbfPDllW6vUjNc3DoZm9I=\ngithub.com/otiai10/curr v0.0.0-20150429015615-9b4961190c95/go.mod h1:9qAhocn7zKJG+0mI8eUu6xqkFDYS2kb2saOteoSB3cE=\ngithub.com/otiai10/curr v1.0.0/go.mod h1:LskTG5wDwr8Rs+nNQ+1LlxRjAtTZZjtJW4rMXl6j4vs=\ngithub.com/otiai10/mint v1.3.0/go.mod h1:F5AjcsTsWUqX+Na9fpHb52P8pcRX2CI6A3ctIT91xUo=\ngithub.com/otiai10/mint v1.3.1/go.mod h1:/yxELlJQ0ufhjUwhshSj+wFjZ78CnZ48/1wtmBH1OTc=\ngithub.com/otiai10/mint v1.6.3 h1:87qsV/aw1F5as1eH1zS/yqHY85ANKVMgkDrf9rcxbQs=\ngithub.com/otiai10/mint v1.6.3/go.mod h1:MJm72SBthJjz8qhefc4z1PYEieWmy8Bku7CjcAqyUSM=\ngithub.com/pavius/impi v0.0.3 h1:DND6MzU+BLABhOZXbELR3FU8b+zDgcq4dOCNLhiTYuI=\ngithub.com/pavius/impi v0.0.3/go.mod h1:x/hU0bfdWIhuOT1SKwiJg++yvkk6EuOtJk8WtDZqgr8=\ngithub.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58 h1:onHthvaw9LFnH4t2DcNVpwGmV9E1BkGknEliJkfwQj0=\ngithub.com/pbnjay/memory v0.0.0-20210728143218-7b4eea64cf58/go.mod h1:DXv8WO4yhMYhSNPKjeNKa5WY9YCIEBRbNzFFPJbWO6Y=\ngithub.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=\ngithub.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=\ngithub.com/pjbgf/sha1cd v0.5.0 h1:a+UkboSi1znleCDUNT3M5YxjOnN1fz2FhN48FlwCxs0=\ngithub.com/pjbgf/sha1cd v0.5.0/go.mod h1:lhpGlyHLpQZoxMv8HcgXvZEhcGs0PG/vsZnEJ7H0iCM=\ngithub.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=\ngithub.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/polyfloyd/go-errorlint v1.8.0 h1:DL4RestQqRLr8U4LygLw8g2DX6RN1eBJOpa2mzsrl1Q=\ngithub.com/polyfloyd/go-errorlint v1.8.0/go.mod h1:G2W0Q5roxbLCt0ZQbdoxQxXktTjwNyDbEaj3n7jvl4s=\ngithub.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4g=\ngithub.com/prashantv/gostub v1.1.0/go.mod h1:A5zLQHz7ieHGG7is6LLXLz7I8+3LZzsrV0P1IAHhP5U=\ngithub.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=\ngithub.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=\ngithub.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=\ngithub.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=\ngithub.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=\ngithub.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=\ngithub.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=\ngithub.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=\ngithub.com/quasilyte/go-ruleguard v0.4.5 h1:AGY0tiOT5hJX9BTdx/xBdoCubQUAE2grkqY2lSwvZcA=\ngithub.com/quasilyte/go-ruleguard v0.4.5/go.mod h1:Vl05zJ538vcEEwu16V/Hdu7IYZWyKSwIy4c88Ro1kRE=\ngithub.com/quasilyte/go-ruleguard/dsl v0.3.23 h1:lxjt5B6ZCiBeeNO8/oQsegE6fLeCzuMRoVWSkXC4uvY=\ngithub.com/quasilyte/go-ruleguard/dsl v0.3.23/go.mod h1:KeCP03KrjuSO0H1kTuZQCWlQPulDV6YMIXmpQss17rU=\ngithub.com/quasilyte/gogrep v0.5.0 h1:eTKODPXbI8ffJMN+W2aE0+oL0z/nh8/5eNdiO34SOAo=\ngithub.com/quasilyte/gogrep v0.5.0/go.mod h1:Cm9lpz9NZjEoL1tgZ2OgeUKPIxL1meE7eo60Z6Sk+Ng=\ngithub.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727 h1:TCg2WBOl980XxGFEZSS6KlBGIV0diGdySzxATTWoqaU=\ngithub.com/quasilyte/regex/syntax v0.0.0-20210819130434-b3f0c404a727/go.mod h1:rlzQ04UMyJXu/aOvhd8qT+hvDrFpiwqp8MRXDY9szc0=\ngithub.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567 h1:M8mH9eK4OUR4lu7Gd+PU1fV2/qnDNfzT635KRSObncs=\ngithub.com/quasilyte/stdinfo v0.0.0-20220114132959-f7386bf02567/go.mod h1:DWNGW8A4Y+GyBgPuaQJuWiy0XYftx4Xm/y5Jqk9I6VQ=\ngithub.com/raeperd/recvcheck v0.2.0 h1:GnU+NsbiCqdC2XX5+vMZzP+jAJC5fht7rcVTAhX74UI=\ngithub.com/raeperd/recvcheck v0.2.0/go.mod h1:n04eYkwIR0JbgD73wT8wL4JjPC3wm0nFtzBnWNocnYU=\ngithub.com/rhysd/actionlint v1.7.11 h1:m+aSuCpCIClS8X02xMG4Z8s87fCHPsAtYkAoWGQZgEE=\ngithub.com/rhysd/actionlint v1.7.11/go.mod h1:8n50YougV9+50niD7oxgDTZ1KbN/ZnKiQ2xpLFeVhsI=\ngithub.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=\ngithub.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=\ngithub.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs=\ngithub.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=\ngithub.com/ryancurrah/gomodguard v1.4.1 h1:eWC8eUMNZ/wM/PWuZBv7JxxqT5fiIKSIyTvjb7Elr+g=\ngithub.com/ryancurrah/gomodguard v1.4.1/go.mod h1:qnMJwV1hX9m+YJseXEBhd2s90+1Xn6x9dLz11ualI1I=\ngithub.com/ryanrolds/sqlclosecheck v0.5.1 h1:dibWW826u0P8jNLsLN+En7+RqWWTYrjCB9fJfSfdyCU=\ngithub.com/ryanrolds/sqlclosecheck v0.5.1/go.mod h1:2g3dUjoS6AL4huFdv6wn55WpLIDjY7ZgUR4J8HOO/XQ=\ngithub.com/sagikazarmark/locafero v0.12.0 h1:/NQhBAkUb4+fH1jivKHWusDYFjMOOKU88eegjfxfHb4=\ngithub.com/sagikazarmark/locafero v0.12.0/go.mod h1:sZh36u/YSZ918v0Io+U9ogLYQJ9tLLBmM4eneO6WwsI=\ngithub.com/sanposhiho/wastedassign/v2 v2.1.0 h1:crurBF7fJKIORrV85u9UUpePDYGWnwvv3+A96WvwXT0=\ngithub.com/sanposhiho/wastedassign/v2 v2.1.0/go.mod h1:+oSmSC+9bQ+VUAxA66nBb0Z7N8CK7mscKTDYC6aIek4=\ngithub.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ=\ngithub.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=\ngithub.com/sashamelentyev/interfacebloat v1.1.0 h1:xdRdJp0irL086OyW1H/RTZTr1h/tMEOsumirXcOJqAw=\ngithub.com/sashamelentyev/interfacebloat v1.1.0/go.mod h1:+Y9yU5YdTkrNvoX0xHc84dxiN1iBi9+G8zZIhPVoNjQ=\ngithub.com/sashamelentyev/usestdlibvars v1.29.0 h1:8J0MoRrw4/NAXtjQqTHrbW9NN+3iMf7Knkq057v4XOQ=\ngithub.com/sashamelentyev/usestdlibvars v1.29.0/go.mod h1:8PpnjHMk5VdeWlVb4wCdrB8PNbLqZ3wBZTZWkrpZZL8=\ngithub.com/securego/gosec/v2 v2.22.10 h1:ntbBqdWXnu46DUOXn+R2SvPo3PiJCDugTCgTW2g4tQg=\ngithub.com/securego/gosec/v2 v2.22.10/go.mod h1:9UNjK3tLpv/w2b0+7r82byV43wCJDNtEDQMeS+H/g2w=\ngithub.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw=\ngithub.com/sergi/go-diff v1.4.0/go.mod h1:A0bzQcvG0E7Rwjx0REVgAGH58e96+X0MeOfepqsbeW4=\ngithub.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk=\ngithub.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ=\ngithub.com/sirkon/dst v0.26.4 h1:ETxfjyp5JKE8OCpdybyyhzTyQqq/MwbIIcs7kxcUAcA=\ngithub.com/sirkon/dst v0.26.4/go.mod h1:e6HRc56jU5F2XT6GB8Cyci1Jb5cjX6gLqrm5+T/P7Zo=\ngithub.com/sirupsen/logrus v1.7.0/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0=\ngithub.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=\ngithub.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=\ngithub.com/sivchari/containedctx v1.0.3 h1:x+etemjbsh2fB5ewm5FeLNi5bUjK0V8n0RB+Wwfd0XE=\ngithub.com/sivchari/containedctx v1.0.3/go.mod h1:c1RDvCbnJLtH4lLcYD/GqwiBSSf4F5Qk0xld2rBqzJ4=\ngithub.com/skeema/knownhosts v1.3.2 h1:EDL9mgf4NzwMXCTfaxSD/o/a5fxDw/xL9nkU28JjdBg=\ngithub.com/skeema/knownhosts v1.3.2/go.mod h1:bEg3iQAuw+jyiw+484wwFJoKSLwcfd7fqRy+N0QTiow=\ngithub.com/sonatard/noctx v0.4.0 h1:7MC/5Gg4SQ4lhLYR6mvOP6mQVSxCrdyiExo7atBs27o=\ngithub.com/sonatard/noctx v0.4.0/go.mod h1:64XdbzFb18XL4LporKXp8poqZtPKbCrqQ402CV+kJas=\ngithub.com/sourcegraph/go-diff v0.7.0 h1:9uLlrd5T46OXs5qpp8L/MTltk0zikUGi0sNNyCpA8G0=\ngithub.com/sourcegraph/go-diff v0.7.0/go.mod h1:iBszgVvyxdc8SFZ7gm69go2KDdt3ag071iBaWPF6cjs=\ngithub.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=\ngithub.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=\ngithub.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=\ngithub.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=\ngithub.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=\ngithub.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=\ngithub.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=\ngithub.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=\ngithub.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=\ngithub.com/ssgreg/nlreturn/v2 v2.2.1 h1:X4XDI7jstt3ySqGU86YGAURbxw3oTDPK9sPEi6YEwQ0=\ngithub.com/ssgreg/nlreturn/v2 v2.2.1/go.mod h1:E/iiPB78hV7Szg2YfRgyIrk1AD6JVMTRkkxBiELzh2I=\ngithub.com/stbenjam/no-sprintf-host-port v0.2.0 h1:i8pxvGrt1+4G0czLr/WnmyH7zbZ8Bg8etvARQ1rpyl4=\ngithub.com/stbenjam/no-sprintf-host-port v0.2.0/go.mod h1:eL0bQ9PasS0hsyTyfTjjG+E80QIyPnBVQbYZyv20Jfk=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=\ngithub.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=\ngithub.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=\ngithub.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngithub.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=\ngithub.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=\ngithub.com/tenntenn/modver v1.0.1 h1:2klLppGhDgzJrScMpkj9Ujy3rXPUspSjAcev9tSEBgA=\ngithub.com/tenntenn/modver v1.0.1/go.mod h1:bePIyQPb7UeioSRkw3Q0XeMhYZSMx9B8ePqg6SAMGH0=\ngithub.com/tenntenn/text/transform v0.0.0-20200319021203-7eef512accb3 h1:f+jULpRQGxTSkNYKJ51yaw6ChIqO+Je8UqsTKN/cDag=\ngithub.com/tenntenn/text/transform v0.0.0-20200319021203-7eef512accb3/go.mod h1:ON8b8w4BN/kE1EOhwT0o+d62W65a6aPw1nouo9LMgyY=\ngithub.com/tetafro/godot v1.5.4 h1:u1ww+gqpRLiIA16yF2PV1CV1n/X3zhyezbNXC3E14Sg=\ngithub.com/tetafro/godot v1.5.4/go.mod h1:eOkMrVQurDui411nBY2FA05EYH01r14LuWY/NrVDVcU=\ngithub.com/timakin/bodyclose v0.0.0-20241222091800-1db5c5ca4d67 h1:9LPGD+jzxMlnk5r6+hJnar67cgpDIz/iyD+rfl5r2Vk=\ngithub.com/timakin/bodyclose v0.0.0-20241222091800-1db5c5ca4d67/go.mod h1:mkjARE7Yr8qU23YcGMSALbIxTQ9r9QBVahQOBRfU460=\ngithub.com/timonwong/loggercheck v0.11.0 h1:jdaMpYBl+Uq9mWPXv1r8jc5fC3gyXx4/WGwTnnNKn4M=\ngithub.com/timonwong/loggercheck v0.11.0/go.mod h1:HEAWU8djynujaAVX7QI65Myb8qgfcZ1uKbdpg3ZzKl8=\ngithub.com/tomarrell/wrapcheck/v2 v2.11.0 h1:BJSt36snX9+4WTIXeJ7nvHBQBcm1h2SjQMSlmQ6aFSU=\ngithub.com/tomarrell/wrapcheck/v2 v2.11.0/go.mod h1:wFL9pDWDAbXhhPZZt+nG8Fu+h29TtnZ2MW6Lx4BRXIU=\ngithub.com/tommy-muehle/go-mnd/v2 v2.5.1 h1:NowYhSdyE/1zwK9QCLeRb6USWdoif80Ie+v+yU8u1Zw=\ngithub.com/tommy-muehle/go-mnd/v2 v2.5.1/go.mod h1:WsUAkMJMYww6l/ufffCD3m+P7LEvr8TnZn9lwVDlgzw=\ngithub.com/ultraware/funlen v0.2.0 h1:gCHmCn+d2/1SemTdYMiKLAHFYxTYz7z9VIDRaTGyLkI=\ngithub.com/ultraware/funlen v0.2.0/go.mod h1:ZE0q4TsJ8T1SQcjmkhN/w+MceuatI6pBFSxxyteHIJA=\ngithub.com/ultraware/whitespace v0.2.0 h1:TYowo2m9Nfj1baEQBjuHzvMRbp19i+RCcRYrSWoFa+g=\ngithub.com/ultraware/whitespace v0.2.0/go.mod h1:XcP1RLD81eV4BW8UhQlpaR+SDc2givTvyI8a586WjW8=\ngithub.com/uudashr/gocognit v1.2.0 h1:3BU9aMr1xbhPlvJLSydKwdLN3tEUUrzPSSM8S4hDYRA=\ngithub.com/uudashr/gocognit v1.2.0/go.mod h1:k/DdKPI6XBZO1q7HgoV2juESI2/Ofj9AcHPZhBBdrTU=\ngithub.com/uudashr/iface v1.4.1 h1:J16Xl1wyNX9ofhpHmQ9h9gk5rnv2A6lX/2+APLTo0zU=\ngithub.com/uudashr/iface v1.4.1/go.mod h1:pbeBPlbuU2qkNDn0mmfrxP2X+wjPMIQAy+r1MBXSXtg=\ngithub.com/xanzy/ssh-agent v0.3.3 h1:+/15pJfg/RsTxqYcX6fHqOXZwwMP+2VyYWJeWM2qQFM=\ngithub.com/xanzy/ssh-agent v0.3.3/go.mod h1:6dzNDKs0J9rVPHPhaGCukekBHKqfl+L3KghI1Bc68Uw=\ngithub.com/xen0n/gosmopolitan v1.3.0 h1:zAZI1zefvo7gcpbCOrPSHJZJYA9ZgLfJqtKzZ5pHqQM=\ngithub.com/xen0n/gosmopolitan v1.3.0/go.mod h1:rckfr5T6o4lBtM1ga7mLGKZmLxswUoH1zxHgNXOsEt4=\ngithub.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=\ngithub.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=\ngithub.com/yagipy/maintidx v1.0.0 h1:h5NvIsCz+nRDapQ0exNv4aJ0yXSI0420omVANTv3GJM=\ngithub.com/yagipy/maintidx v1.0.0/go.mod h1:0qNf/I/CCZXSMhsRsrEPDZ+DkekpKLXAJfsTACwgXLk=\ngithub.com/yeya24/promlinter v0.3.0 h1:JVDbMp08lVCP7Y6NP3qHroGAO6z2yGKQtS5JsjqtoFs=\ngithub.com/yeya24/promlinter v0.3.0/go.mod h1:cDfJQQYv9uYciW60QT0eeHlFodotkYZlL+YcPQN+mW4=\ngithub.com/ykadowak/zerologlint v0.1.5 h1:Gy/fMz1dFQN9JZTPjv1hxEk+sRWm05row04Yoolgdiw=\ngithub.com/ykadowak/zerologlint v0.1.5/go.mod h1:KaUskqF3e/v59oPmdq1U1DnKcuHokl2/K1U4pmIELKg=\ngithub.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=\ngithub.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=\ngithub.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=\ngithub.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=\ngithub.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=\ngithub.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=\ngitlab.com/bosi/decorder v0.4.2 h1:qbQaV3zgwnBZ4zPMhGLW4KZe7A7NwxEhJx39R3shffo=\ngitlab.com/bosi/decorder v0.4.2/go.mod h1:muuhHoaJkA9QLcYHq4Mj8FJUwDZ+EirSHRiaTcTf6T8=\ngo-simpler.org/assert v0.9.0 h1:PfpmcSvL7yAnWyChSjOz6Sp6m9j5lyK8Ok9pEL31YkQ=\ngo-simpler.org/assert v0.9.0/go.mod h1:74Eqh5eI6vCK6Y5l3PI8ZYFXG4Sa+tkr70OIPJAUr28=\ngo-simpler.org/musttag v0.14.0 h1:XGySZATqQYSEV3/YTy+iX+aofbZZllJaqwFWs+RTtSo=\ngo-simpler.org/musttag v0.14.0/go.mod h1:uP8EymctQjJ4Z1kUnjX0u2l60WfUdQxCwSNKzE1JEOE=\ngo-simpler.org/sloglint v0.11.1 h1:xRbPepLT/MHPTCA6TS/wNfZrDzkGvCCqUv4Bdwc3H7s=\ngo-simpler.org/sloglint v0.11.1/go.mod h1:2PowwiCOK8mjiF+0KGifVOT8ZsCNiFzvfyJeJOIt8MQ=\ngo.augendre.info/arangolint v0.3.1 h1:n2E6p8f+zfXSFLa2e2WqFPp4bfvcuRdd50y6cT65pSo=\ngo.augendre.info/arangolint v0.3.1/go.mod h1:6ZKzEzIZuBQwoSvlKT+qpUfIbBfFCE5gbAoTg0/117g=\ngo.augendre.info/fatcontext v0.9.0 h1:Gt5jGD4Zcj8CDMVzjOJITlSb9cEch54hjRRlN3qDojE=\ngo.augendre.info/fatcontext v0.9.0/go.mod h1:L94brOAT1OOUNue6ph/2HnwxoNlds9aXDF2FcUntbNw=\ngo.opentelemetry.io/build-tools v0.29.0 h1:dG1zmHKYTMsP0zGT34+32/U+YR+lcJ8kka7Lc4RAoT4=\ngo.opentelemetry.io/build-tools v0.29.0/go.mod h1:jTzBit47RqVApCwStu9qw2TfGqR2Fhu5jinLHqfhghQ=\ngo.opentelemetry.io/build-tools/checkapi v0.29.0 h1:witlcpwRObFHyNBr0XM1P21C//jIUW25gxnO0V5sls0=\ngo.opentelemetry.io/build-tools/checkapi v0.29.0/go.mod h1:BUlDXzIK1uVJC4mcYBzeNTiRk1HbKA8kf3N44zlhx9g=\ngo.opentelemetry.io/build-tools/checkfile v0.29.0 h1:9ue2+J4x7NL9Nugahec6A9JsV4CUd0GhDiFxN3VUufE=\ngo.opentelemetry.io/build-tools/checkfile v0.29.0/go.mod h1:vtBRUpSPWJdfdGV3/vodhcD3wiMp8fhQ03HOwmczeJQ=\ngo.opentelemetry.io/build-tools/chloggen v0.29.0 h1:0HnDE47uJNlst1XtCukHB7sQYtUlJjmvdhWVdJn+GBU=\ngo.opentelemetry.io/build-tools/chloggen v0.29.0/go.mod h1:eby4AVJQF5uanGCnErZdhDYBSW/EJ0iqejBFNJMN4DQ=\ngo.opentelemetry.io/build-tools/crosslink v0.29.0 h1:sz8if4EgUejLvfulrfLF7i2yzSUEyiY4s++aWJGVMZc=\ngo.opentelemetry.io/build-tools/crosslink v0.29.0/go.mod h1:jWE8JLNnuAQhnISpzGsWumC4JREBHOPaxufdSeBbSWs=\ngo.opentelemetry.io/build-tools/githubgen v0.29.0 h1:ETjvcslIftce8aARBGtCCdxIs4Le2tSUlXD5cbzhYGE=\ngo.opentelemetry.io/build-tools/githubgen v0.29.0/go.mod h1:aTnMaP7dTUOZzFxAyS1OXmc27QHpSN9NK+3rD9irWqI=\ngo.opentelemetry.io/build-tools/multimod v0.29.0 h1:hVXibTuNuJumtn3cpzqPOX2xmcO+KogKZcB0yygHux0=\ngo.opentelemetry.io/build-tools/multimod v0.29.0/go.mod h1:tx762Z6RQe5Twkd04q1zzpmGQGtSljbKRy/P61EnJpo=\ngo.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs=\ngo.uber.org/automaxprocs v1.6.0/go.mod h1:ifeIMSnPZuznNm6jmdzmU3/bfk01Fe2fotchwEFJ8r8=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=\ngo.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngo.yaml.in/yaml/v4 v4.0.0-rc.3 h1:3h1fjsh1CTAPjW7q/EMe+C8shx5d8ctzZTrLcs/j8Go=\ngo.yaml.in/yaml/v4 v4.0.0-rc.3/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=\ngolang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=\ngolang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=\ngolang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=\ngolang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=\ngolang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=\ngolang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliYc=\ngolang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4=\ngolang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=\ngolang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=\ngolang.org/x/exp v0.0.0-20240909161429-701f63a606c0 h1:e66Fs6Z+fZTbFBAxKfP3PALWBtpfqks2bwGcexMxgtk=\ngolang.org/x/exp v0.0.0-20240909161429-701f63a606c0/go.mod h1:2TbTHSBQa924w8M6Xs1QcRcFwyucIwBGpK1p2f1YFFY=\ngolang.org/x/exp/typeparams v0.0.0-20220428152302-39d4317da171/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=\ngolang.org/x/exp/typeparams v0.0.0-20230203172020-98cc5a0785f9/go.mod h1:AbB0pIl9nAr9wVwH+Z2ZpaocVmF5I4GyWCDIsVjR0bk=\ngolang.org/x/exp/typeparams v0.0.0-20251023183803-a4bb9ffd2546 h1:HDjDiATsGqvuqvkDvgJjD1IgPrVekcSXVVE21JwvzGE=\ngolang.org/x/exp/typeparams v0.0.0-20251023183803-a4bb9ffd2546/go.mod h1:4Mzdyp/6jzw9auFDJ3OMF5qksa7UvPnzKqTVGcb04ms=\ngolang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=\ngolang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=\ngolang.org/x/mod v0.4.1/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=\ngolang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=\ngolang.org/x/mod v0.6.0-dev.0.20220106191415-9b9b3d81d5e3/go.mod h1:3p9vT2HGsQu2K1YbXdKPJLVgG5VJdoTa1poYQBtP1AY=\ngolang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=\ngolang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=\ngolang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=\ngolang.org/x/mod v0.13.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=\ngolang.org/x/mod v0.33.0 h1:tHFzIWbBifEmbwtGz65eaWyGiGZatSrT9prnU8DbVL8=\ngolang.org/x/mod v0.33.0/go.mod h1:swjeQEj+6r7fODbD2cqrnje9PnziFuw4bmLbBZFrQ5w=\ngolang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=\ngolang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=\ngolang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=\ngolang.org/x/net v0.0.0-20200625001655-4c5254603344/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=\ngolang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=\ngolang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=\ngolang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=\ngolang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=\ngolang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=\ngolang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=\ngolang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=\ngolang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg=\ngolang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=\ngolang.org/x/net v0.16.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE=\ngolang.org/x/net v0.50.0 h1:ucWh9eiCGyDR3vtzso0WMQinm2Dnt8cFMuQa9K33J60=\ngolang.org/x/net v0.50.0/go.mod h1:UgoSli3F/pBgdJBHCTc+tp3gmrU4XswgGRgtnwWTfyM=\ngolang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=\ngolang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=\ngolang.org/x/sync v0.4.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=\ngolang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=\ngolang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=\ngolang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=\ngolang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20211105183446-c75c47738b0c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.13.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/telemetry v0.0.0-20260209163413-e7419c687ee4 h1:bTLqdHv7xrGlFbvf5/TXNxy/iUwwdkjhqQTJDjW7aj0=\ngolang.org/x/telemetry v0.0.0-20260209163413-e7419c687ee4/go.mod h1:g5NllXBEermZrmR51cJDQxmJUHUOfRAaNyWBM+R+548=\ngolang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=\ngolang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=\ngolang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=\ngolang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo=\ngolang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=\ngolang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U=\ngolang.org/x/term v0.40.0 h1:36e4zGLqU4yhjlmxEaagx2KuYbJq3EwY8K943ZsHcvg=\ngolang.org/x/term v0.40.0/go.mod h1:w2P8uVp06p2iyKKuvXIm7N/y0UCRt3UfJTfZ7oOpglM=\ngolang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=\ngolang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=\ngolang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=\ngolang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=\ngolang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=\ngolang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=\ngolang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=\ngolang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngolang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=\ngolang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=\ngolang.org/x/tools v0.0.0-20200329025819-fd4102a86c65/go.mod h1:Sl4aGygMT6LrqrWclx+PTx3U+LnKx/seiNR+3G19Ar8=\ngolang.org/x/tools v0.0.0-20200724022722-7017fd6b1305/go.mod h1:njjCfa9FT2d7l9Bc6FUM5FLjQPp3cFF28FI3qnDFljA=\ngolang.org/x/tools v0.1.1-0.20210205202024-ef80cdb6ec6d/go.mod h1:9bzcO0MWcOuT0tm1iBGzDVPshzfwoVvREIui8C+MHqU=\ngolang.org/x/tools v0.1.1-0.20210302220138-2ac05c832e1a/go.mod h1:9bzcO0MWcOuT0tm1iBGzDVPshzfwoVvREIui8C+MHqU=\ngolang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=\ngolang.org/x/tools v0.1.10/go.mod h1:Uh6Zz+xoGYZom868N8YTex3t7RhtHDBrE8Gzo9bV56E=\ngolang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=\ngolang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=\ngolang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=\ngolang.org/x/tools v0.14.0/go.mod h1:uYBEerGOWcJyEORxN+Ek8+TT266gXkNlHdJBwexUsBg=\ngolang.org/x/tools v0.42.0 h1:uNgphsn75Tdz5Ji2q36v/nsFSfR/9BRFvqhGBaJGd5k=\ngolang.org/x/tools v0.42.0/go.mod h1:Ma6lCIwGZvHK6XtgbswSoWroEkhugApmsXyrUmBhfr0=\ngolang.org/x/tools/go/expect v0.1.1-deprecated h1:jpBZDwmgPhXsKZC6WhL20P4b/wmnpsEAGHaNy0n/rJM=\ngolang.org/x/tools/go/expect v0.1.1-deprecated/go.mod h1:eihoPOH+FgIqa3FpoTwguz/bVUSGBlGQU67vpBeOrBY=\ngolang.org/x/tools/go/packages/packagestest v0.1.1-deprecated h1:1h2MnaIAIXISqTFKdENegdpAgUXz6NrPEsbIeWaBRvM=\ngolang.org/x/tools/go/packages/packagestest v0.1.1-deprecated/go.mod h1:RVAQXBGNv1ib0J382/DPCRS/BPnsGebyM1Gj5VSDpG8=\ngolang.org/x/vuln v1.1.4 h1:Ju8QsuyhX3Hk8ma3CesTbO8vfJD9EvUBgHvkxHBzj0I=\ngolang.org/x/vuln v1.1.4/go.mod h1:F+45wmU18ym/ca5PLTPLsSzr2KppzswxPP603ldA67s=\ngolang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=\ngolang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=\ngolang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=\ngolang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/warnings.v0 v0.1.2 h1:wFXVbFY8DY5/xOe1ECiWdKCzZlxgshcYVNkBHstARME=\ngopkg.in/warnings.v0 v0.1.2/go.mod h1:jksf8JmL6Qr/oQM2OXTHunEvvTAsrWBLb6OOjuVWRNI=\ngopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=\ngopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=\ngopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\ngotest.tools/gotestsum v1.13.0 h1:+Lh454O9mu9AMG1APV4o0y7oDYKyik/3kBOiCqiEpRo=\ngotest.tools/gotestsum v1.13.0/go.mod h1:7f0NS5hFb0dWr4NtcsAsF0y1kzjEFfAil0HiBQJE03Q=\ngotest.tools/v3 v3.5.2 h1:7koQfIKdy+I8UTetycgUqXWSDwpgv193Ka+qRsmBY8Q=\ngotest.tools/v3 v3.5.2/go.mod h1:LtdLGcnqToBH83WByAAi/wiwSFCArdFIUV/xxN4pcjA=\nhonnef.co/go/tools v0.7.0-0.dev.0.20250523013057-bbc2f4dd71ea h1:fj8r9irJSpolAGUdZBxJIRY3lLc4jH2Dt4lwnWyWwpw=\nhonnef.co/go/tools v0.7.0-0.dev.0.20250523013057-bbc2f4dd71ea/go.mod h1:EPDDhEZqVHhWuPI5zPAsjU0U7v9xNIWjoOVyZ5ZcniQ=\nmvdan.cc/gofumpt v0.9.2 h1:zsEMWL8SVKGHNztrx6uZrXdp7AX8r421Vvp23sz7ik4=\nmvdan.cc/gofumpt v0.9.2/go.mod h1:iB7Hn+ai8lPvofHd9ZFGVg2GOr8sBUw1QUWjNbmIL/s=\nmvdan.cc/unparam v0.0.0-20251027182757-5beb8c8f8f15 h1:ssMzja7PDPJV8FStj7hq9IKiuiKhgz9ErWw+m68e7DI=\nmvdan.cc/unparam v0.0.0-20251027182757-5beb8c8f8f15/go.mod h1:4M5MMXl2kW6fivUT6yRGpLLPNfuGtU2Z0cPvFquGDYU=\n"
  },
  {
    "path": "otelcol/Makefile",
    "content": "include ../Makefile.Common\n"
  },
  {
    "path": "otelcol/buffered_core.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// This logger implements zapcore.Core and is based on zaptest/observer.\n\npackage otelcol // import \"go.opentelemetry.io/collector/otelcol\"\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\n\t\"go.uber.org/zap/zapcore\"\n)\n\ntype loggedEntry struct {\n\tzapcore.Entry\n\tContext []zapcore.Field\n}\n\nfunc newBufferedCore(enab zapcore.LevelEnabler) *bufferedCore {\n\treturn &bufferedCore{LevelEnabler: enab}\n}\n\nvar _ zapcore.Core = (*bufferedCore)(nil)\n\ntype bufferedCore struct {\n\tzapcore.LevelEnabler\n\tmu        sync.Mutex\n\tlogs      []loggedEntry\n\tcontext   []zapcore.Field\n\tlogsTaken bool\n}\n\nfunc (bc *bufferedCore) Level() zapcore.Level {\n\treturn zapcore.LevelOf(bc.LevelEnabler)\n}\n\nfunc (bc *bufferedCore) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {\n\tif bc.Enabled(ent.Level) {\n\t\treturn ce.AddCore(ent, bc)\n\t}\n\treturn ce\n}\n\nfunc (bc *bufferedCore) With(fields []zapcore.Field) zapcore.Core {\n\treturn &bufferedCore{\n\t\tLevelEnabler: bc.LevelEnabler,\n\t\tlogs:         bc.logs,\n\t\tlogsTaken:    bc.logsTaken,\n\t\tcontext:      append(bc.context, fields...),\n\t}\n}\n\nfunc (bc *bufferedCore) Write(ent zapcore.Entry, fields []zapcore.Field) error {\n\tbc.mu.Lock()\n\tdefer bc.mu.Unlock()\n\tif bc.logsTaken {\n\t\treturn errors.New(\"the buffered logs have already been taken so writing is no longer supported\")\n\t}\n\tall := make([]zapcore.Field, 0, len(fields)+len(bc.context))\n\tall = append(all, bc.context...)\n\tall = append(all, fields...)\n\tbc.logs = append(bc.logs, loggedEntry{ent, all})\n\treturn nil\n}\n\nfunc (bc *bufferedCore) Sync() error {\n\treturn nil\n}\n\nfunc (bc *bufferedCore) TakeLogs() []loggedEntry {\n\tbc.mu.Lock()\n\tdefer bc.mu.Unlock()\n\tif bc.logsTaken {\n\t\treturn nil\n\t}\n\tlogs := bc.logs\n\tbc.logs = nil\n\tbc.logsTaken = true\n\treturn logs\n}\n"
  },
  {
    "path": "otelcol/buffered_core_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap/zapcore\"\n)\n\nfunc Test_bufferedCore_Level(t *testing.T) {\n\tbc := newBufferedCore(zapcore.InfoLevel)\n\tassert.Equal(t, zapcore.InfoLevel, bc.Level())\n}\n\nfunc Test_bufferedCore_Check(t *testing.T) {\n\tt.Run(\"check passed\", func(t *testing.T) {\n\t\tbc := newBufferedCore(zapcore.InfoLevel)\n\t\te := zapcore.Entry{\n\t\t\tLevel: zapcore.InfoLevel,\n\t\t}\n\t\texpected := &zapcore.CheckedEntry{}\n\t\texpected = expected.AddCore(e, bc)\n\t\tce := bc.Check(e, nil)\n\t\tassert.Equal(t, expected, ce)\n\t})\n\n\tt.Run(\"check did not pass\", func(t *testing.T) {\n\t\tbc := newBufferedCore(zapcore.InfoLevel)\n\t\te := zapcore.Entry{\n\t\t\tLevel: zapcore.DebugLevel,\n\t\t}\n\t\tce := bc.Check(e, nil)\n\t\tassert.Nil(t, ce)\n\t})\n}\n\nfunc Test_bufferedCore_With(t *testing.T) {\n\tbc := newBufferedCore(zapcore.InfoLevel)\n\tbc.logsTaken = true\n\tbc.context = []zapcore.Field{\n\t\t{Key: \"original\", String: \"context\"},\n\t}\n\tinputs := []zapcore.Field{\n\t\t{Key: \"test\", String: \"passed\"},\n\t}\n\texpected := []zapcore.Field{\n\t\t{Key: \"original\", String: \"context\"},\n\t\t{Key: \"test\", String: \"passed\"},\n\t}\n\tnewBC := bc.With(inputs)\n\tassert.Equal(t, expected, newBC.(*bufferedCore).context)\n\tassert.True(t, newBC.(*bufferedCore).logsTaken)\n}\n\nfunc Test_bufferedCore_Write(t *testing.T) {\n\tbc := newBufferedCore(zapcore.InfoLevel)\n\te := zapcore.Entry{\n\t\tLevel:   zapcore.DebugLevel,\n\t\tMessage: \"test\",\n\t}\n\tfields := []zapcore.Field{\n\t\t{Key: \"field1\", String: \"value1\"},\n\t}\n\terr := bc.Write(e, fields)\n\trequire.NoError(t, err)\n\n\texpected := loggedEntry{\n\t\te,\n\t\tfields,\n\t}\n\trequire.Len(t, bc.logs, 1)\n\trequire.Equal(t, expected, bc.logs[0])\n}\n\nfunc Test_bufferedCore_Sync(t *testing.T) {\n\tbc := newBufferedCore(zapcore.InfoLevel)\n\tassert.NoError(t, bc.Sync())\n}\n\nfunc Test_bufferedCore_TakeLogs(t *testing.T) {\n\tbc := newBufferedCore(zapcore.InfoLevel)\n\te := zapcore.Entry{\n\t\tLevel:   zapcore.DebugLevel,\n\t\tMessage: \"test\",\n\t}\n\tfields := []zapcore.Field{\n\t\t{Key: \"field1\", String: \"value1\"},\n\t}\n\terr := bc.Write(e, fields)\n\trequire.NoError(t, err)\n\n\texpected := []loggedEntry{\n\t\t{\n\t\t\te,\n\t\t\tfields,\n\t\t},\n\t}\n\tassert.Equal(t, expected, bc.TakeLogs())\n\tassert.Nil(t, bc.logs)\n\n\trequire.Error(t, bc.Write(e, fields))\n\tassert.Nil(t, bc.TakeLogs())\n}\n"
  },
  {
    "path": "otelcol/collector.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package otelcol handles the command-line, configuration, and runs the OpenTelemetry Collector.\n// It contains the main [Collector] struct and its constructor [NewCollector].\n// [Collector.Run] starts the Collector and then blocks until it shuts down.\npackage otelcol // import \"go.opentelemetry.io/collector/otelcol\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/signal\"\n\t\"sync\"\n\t\"sync/atomic\"\n\n\t\"go.uber.org/multierr\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n\t\"go.opentelemetry.io/collector/otelcol/internal/grpclog\"\n\t\"go.opentelemetry.io/collector/service\"\n)\n\n// State defines Collector's state.\ntype State int\n\nconst (\n\tStateStarting State = iota\n\tStateRunning\n\tStateClosing\n\tStateClosed\n)\n\nfunc (s State) String() string {\n\tswitch s {\n\tcase StateStarting:\n\t\treturn \"Starting\"\n\tcase StateRunning:\n\t\treturn \"Running\"\n\tcase StateClosing:\n\t\treturn \"Closing\"\n\tcase StateClosed:\n\t\treturn \"Closed\"\n\t}\n\treturn \"UNKNOWN\"\n}\n\n// CollectorSettings holds configuration for creating a new Collector.\ntype CollectorSettings struct {\n\t// Factories returns component factories for the collector.\n\t//\n\t// TODO(13263) This is a dangerous \"bare\" function value, should define an interface\n\t// following style guidelines.\n\tFactories func() (Factories, error)\n\n\t// BuildInfo provides collector start information.\n\tBuildInfo component.BuildInfo\n\n\t// DisableGracefulShutdown disables the automatic graceful shutdown\n\t// of the collector on SIGINT or SIGTERM.\n\t// Users who want to handle signals themselves can disable this behavior\n\t// and manually handle the signals to shutdown the collector.\n\tDisableGracefulShutdown bool\n\n\t// ConfigProviderSettings allows configuring the way the Collector retrieves its configuration\n\t// The Collector will reload based on configuration changes from the ConfigProvider if any\n\t// confmap.Providers watch for configuration changes.\n\tConfigProviderSettings ConfigProviderSettings\n\n\t// ProviderModules maps provider schemes to their respective go modules.\n\tProviderModules map[string]string\n\n\t// ConverterModules maps converter names to their respective go modules.\n\tConverterModules []string\n\n\t// LoggingOptions provides a way to change behavior of zap logging.\n\tLoggingOptions []zap.Option\n\n\t// SkipSettingGRPCLogger avoids setting the grpc logger\n\tSkipSettingGRPCLogger bool\n}\n\n// (Internal note) Collector Lifecycle:\n// - New constructs a new Collector.\n// - Run starts the collector.\n// - Run calls setupConfigurationComponents to handle configuration.\n//   If configuration parser fails, collector's config can be reloaded.\n//   Collector can be shutdown if parser gets a shutdown error.\n// - Run runs runAndWaitForShutdownEvent and waits for a shutdown event.\n//   SIGINT and SIGTERM, errors, and (*Collector).Shutdown can trigger the shutdown events.\n// - Upon shutdown, pipelines are notified, then pipelines and extensions are shut down.\n// - Users can call (*Collector).Shutdown anytime to shut down the collector.\n\n// Collector represents a server providing the OpenTelemetry Collector service.\ntype Collector struct {\n\tset            CollectorSettings\n\tbuildZapLogger func(zap.Config, ...zap.Option) (*zap.Logger, error)\n\n\tconfigProvider *ConfigProvider\n\n\tserviceConfig *service.Config\n\tservice       *service.Service\n\tstate         *atomic.Int64\n\n\t// shutdownChan is used to terminate the collector.\n\tshutdownChan chan struct{}\n\tshutdownOnce sync.Once\n\n\t// signalsChannel is used to receive termination signals from the OS.\n\tsignalsChannel chan os.Signal\n\t// asyncErrorChannel is used to signal a fatal error from any component.\n\tasyncErrorChannel          chan error\n\tbc                         *bufferedCore\n\tupdateConfigProviderLogger func(core zapcore.Core)\n}\n\n// NewCollector creates and returns a new instance of Collector.\nfunc NewCollector(set CollectorSettings) (*Collector, error) {\n\tbc := newBufferedCore(zapcore.DebugLevel)\n\tcc := newCollectorCore(bc)\n\toptions := append([]zap.Option{zap.WithCaller(true)}, set.LoggingOptions...)\n\tlogger := zap.New(cc, options...)\n\tset.ConfigProviderSettings.ResolverSettings.ProviderSettings = confmap.ProviderSettings{Logger: logger}\n\tset.ConfigProviderSettings.ResolverSettings.ConverterSettings = confmap.ConverterSettings{Logger: logger}\n\n\tconfigProvider, err := NewConfigProvider(set.ConfigProviderSettings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tstate := new(atomic.Int64)\n\tstate.Store(int64(StateStarting))\n\treturn &Collector{\n\t\tset:            set,\n\t\tbuildZapLogger: zap.Config.Build,\n\t\tstate:          state,\n\t\tshutdownChan:   make(chan struct{}),\n\t\t// Per signal.Notify documentation, a size of the channel equaled with\n\t\t// the number of signals getting notified on is recommended.\n\t\tsignalsChannel:             make(chan os.Signal, 3),\n\t\tasyncErrorChannel:          make(chan error),\n\t\tconfigProvider:             configProvider,\n\t\tbc:                         bc,\n\t\tupdateConfigProviderLogger: cc.SetCore,\n\t}, nil\n}\n\n// GetState returns current state of the collector server.\nfunc (col *Collector) GetState() State {\n\treturn State(col.state.Load())\n}\n\n// Shutdown shuts down the collector server.\nfunc (col *Collector) Shutdown() {\n\tcol.shutdownOnce.Do(func() {\n\t\tclose(col.shutdownChan)\n\t})\n}\n\nfunc buildModuleInfo(m map[component.Type]string) map[component.Type]service.ModuleInfo {\n\tmoduleInfo := make(map[component.Type]service.ModuleInfo)\n\tfor k, v := range m {\n\t\tmoduleInfo[k] = service.ModuleInfo{BuilderRef: v}\n\t}\n\treturn moduleInfo\n}\n\n// setupConfigurationComponents loads the config, creates the graph, and starts the components. If all the steps succeeds it\n// sets the col.service with the service currently running.\nfunc (col *Collector) setupConfigurationComponents(ctx context.Context) error {\n\tcol.setCollectorState(StateStarting)\n\n\tfactories, err := col.set.Factories()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to initialize factories: %w\", err)\n\t}\n\n\tcfg, err := col.configProvider.Get(ctx, factories)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get config: %w\", err)\n\t}\n\n\tif err = xconfmap.Validate(cfg); err != nil {\n\t\treturn fmt.Errorf(\"invalid configuration: %w\", err)\n\t}\n\n\tcol.serviceConfig = &cfg.Service\n\n\tconf := confmap.New()\n\n\tif err = conf.Marshal(cfg); err != nil {\n\t\treturn fmt.Errorf(\"could not marshal configuration: %w\", err)\n\t}\n\n\t// Wrap the buildZapLogger to append LoggingOptions from collector settings,\n\t// since service.Settings.LoggingOptions is deprecated.\n\tbuildZapLogger := col.buildZapLogger\n\tif len(col.set.LoggingOptions) > 0 {\n\t\torigBuildZapLogger := buildZapLogger\n\t\tbuildZapLogger = func(zapCfg zap.Config, opts ...zap.Option) (*zap.Logger, error) {\n\t\t\topts = append(opts, col.set.LoggingOptions...)\n\t\t\treturn origBuildZapLogger(zapCfg, opts...)\n\t\t}\n\t}\n\n\tcol.service, err = service.New(ctx, service.Settings{\n\t\tBuildInfo:     col.set.BuildInfo,\n\t\tCollectorConf: conf,\n\n\t\tReceiversConfigs:    cfg.Receivers,\n\t\tReceiversFactories:  factories.Receivers,\n\t\tProcessorsConfigs:   cfg.Processors,\n\t\tProcessorsFactories: factories.Processors,\n\t\tExportersConfigs:    cfg.Exporters,\n\t\tExportersFactories:  factories.Exporters,\n\t\tConnectorsConfigs:   cfg.Connectors,\n\t\tConnectorsFactories: factories.Connectors,\n\t\tExtensionsConfigs:   cfg.Extensions,\n\t\tExtensionsFactories: factories.Extensions,\n\n\t\tModuleInfos: service.ModuleInfos{\n\t\t\tReceiver:  buildModuleInfo(factories.ReceiverModules),\n\t\t\tProcessor: buildModuleInfo(factories.ProcessorModules),\n\t\t\tExporter:  buildModuleInfo(factories.ExporterModules),\n\t\t\tExtension: buildModuleInfo(factories.ExtensionModules),\n\t\t\tConnector: buildModuleInfo(factories.ConnectorModules),\n\t\t},\n\t\tAsyncErrorChannel: col.asyncErrorChannel,\n\t\tBuildZapLogger:    buildZapLogger,\n\t\tTelemetryFactory:  factories.Telemetry,\n\t}, cfg.Service)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif col.updateConfigProviderLogger != nil {\n\t\tcol.updateConfigProviderLogger(col.service.Logger().Core())\n\t}\n\tif col.bc != nil {\n\t\tx := col.bc.TakeLogs()\n\t\tfor _, log := range x {\n\t\t\tce := col.service.Logger().Core().Check(log.Entry, nil)\n\t\t\tif ce != nil {\n\t\t\t\tce.Write(log.Context...)\n\t\t\t}\n\t\t}\n\t}\n\n\tif !col.set.SkipSettingGRPCLogger {\n\t\tgrpclog.SetLogger(col.service.Logger())\n\t}\n\n\tif err = col.service.Start(ctx); err != nil {\n\t\treturn multierr.Combine(err, col.service.Shutdown(ctx))\n\t}\n\tcol.setCollectorState(StateRunning)\n\n\treturn nil\n}\n\nfunc (col *Collector) reloadConfiguration(ctx context.Context) error {\n\tcol.service.Logger().Warn(\"Config updated, restart service\")\n\tcol.setCollectorState(StateClosing)\n\n\tif err := col.service.Shutdown(ctx); err != nil {\n\t\treturn fmt.Errorf(\"failed to shutdown the retiring config: %w\", err)\n\t}\n\n\tif err := col.setupConfigurationComponents(ctx); err != nil {\n\t\treturn fmt.Errorf(\"failed to setup configuration components: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc (col *Collector) DryRun(ctx context.Context) error {\n\tfactories, err := col.set.Factories()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to initialize factories: %w\", err)\n\t}\n\n\tcfg, err := col.configProvider.Get(ctx, factories)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to get config: %w\", err)\n\t}\n\n\tif err := xconfmap.Validate(cfg); err != nil {\n\t\treturn err\n\t}\n\n\treturn service.Validate(ctx, service.Settings{\n\t\tBuildInfo:           col.set.BuildInfo,\n\t\tReceiversConfigs:    cfg.Receivers,\n\t\tReceiversFactories:  factories.Receivers,\n\t\tProcessorsConfigs:   cfg.Processors,\n\t\tProcessorsFactories: factories.Processors,\n\t\tExportersConfigs:    cfg.Exporters,\n\t\tExportersFactories:  factories.Exporters,\n\t\tConnectorsConfigs:   cfg.Connectors,\n\t\tConnectorsFactories: factories.Connectors,\n\t\tTelemetryFactory:    factories.Telemetry,\n\t}, service.Config{\n\t\tPipelines: cfg.Service.Pipelines,\n\t})\n}\n\nfunc newFallbackLogger(options []zap.Option) (*zap.Logger, error) {\n\tec := zap.NewProductionEncoderConfig()\n\tec.EncodeTime = zapcore.ISO8601TimeEncoder\n\tzapCfg := &zap.Config{\n\t\tLevel:            zap.NewAtomicLevelAt(zapcore.DebugLevel),\n\t\tEncoding:         \"console\",\n\t\tEncoderConfig:    ec,\n\t\tOutputPaths:      []string{\"stderr\"},\n\t\tErrorOutputPaths: []string{\"stderr\"},\n\t}\n\treturn zapCfg.Build(options...)\n}\n\n// Run starts the collector according to the given configuration, and waits for it to complete.\n// Consecutive calls to Run are not allowed, Run shouldn't be called once a collector is shut down.\n// Sets up the control logic for config reloading and shutdown.\nfunc (col *Collector) Run(ctx context.Context) error {\n\t// setupConfigurationComponents is the \"main\" function responsible for startup\n\tif err := col.setupConfigurationComponents(ctx); err != nil {\n\t\tcol.setCollectorState(StateClosed)\n\t\tlogger, loggerErr := newFallbackLogger(col.set.LoggingOptions)\n\t\tif loggerErr != nil {\n\t\t\treturn errors.Join(err, fmt.Errorf(\"unable to create fallback logger: %w\", loggerErr))\n\t\t}\n\n\t\tif col.bc != nil {\n\t\t\tx := col.bc.TakeLogs()\n\t\t\tfor _, log := range x {\n\t\t\t\tce := logger.Core().Check(log.Entry, nil)\n\t\t\t\tif ce != nil {\n\t\t\t\t\tce.Write(log.Context...)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn err\n\t}\n\n\t// Always notify with SIGHUP for configuration reloading.\n\tsignal.Notify(col.signalsChannel, SIGHUP)\n\tdefer signal.Stop(col.signalsChannel)\n\n\t// Only notify with SIGTERM and SIGINT if graceful shutdown is enabled.\n\tif !col.set.DisableGracefulShutdown {\n\t\tsignal.Notify(col.signalsChannel, os.Interrupt, SIGTERM)\n\t}\n\n\t// Control loop: selects between channels for various interrupts - when this loop is broken, the collector exits.\n\t// If a configuration reload fails, we return without waiting for graceful shutdown.\nLOOP:\n\tfor {\n\t\tselect {\n\t\tcase err := <-col.configProvider.Watch():\n\t\t\tif err != nil {\n\t\t\t\tcol.service.Logger().Error(\"Config watch failed\", zap.Error(err))\n\t\t\t\tbreak LOOP\n\t\t\t}\n\t\t\tif err := col.reloadConfiguration(ctx); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase err := <-col.asyncErrorChannel:\n\t\t\tcol.service.Logger().Error(\"Asynchronous error received, terminating process\", zap.Error(err))\n\t\t\tbreak LOOP\n\t\tcase s := <-col.signalsChannel:\n\t\t\tcol.service.Logger().Info(\"Received signal from OS\", zap.String(\"signal\", s.String()))\n\t\t\tif s != SIGHUP {\n\t\t\t\tbreak LOOP\n\t\t\t}\n\t\t\tif err := col.reloadConfiguration(ctx); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase <-col.shutdownChan:\n\t\t\tcol.service.Logger().Info(\"Received shutdown request\")\n\t\t\tbreak LOOP\n\t\tcase <-ctx.Done():\n\t\t\tcol.service.Logger().Info(\"Context done, terminating process\", zap.Error(ctx.Err()))\n\t\t\t// Call shutdown with background context as the passed in context has been canceled\n\t\t\treturn col.shutdown(context.Background()) //nolint:contextcheck\n\t\t}\n\t}\n\treturn col.shutdown(ctx)\n}\n\nfunc (col *Collector) shutdown(ctx context.Context) error {\n\tcol.setCollectorState(StateClosing)\n\n\t// Accumulate errors and proceed with shutting down remaining components.\n\tvar errs error\n\n\tif err := col.configProvider.Shutdown(ctx); err != nil {\n\t\terrs = multierr.Append(errs, fmt.Errorf(\"failed to shutdown config provider: %w\", err))\n\t}\n\n\t// shutdown service\n\tif err := col.service.Shutdown(ctx); err != nil {\n\t\terrs = multierr.Append(errs, fmt.Errorf(\"failed to shutdown service after error: %w\", err))\n\t}\n\n\tcol.setCollectorState(StateClosed)\n\n\treturn errs\n}\n\n// setCollectorState provides current state of the collector\nfunc (col *Collector) setCollectorState(state State) {\n\tcol.state.Store(int64(state))\n}\n"
  },
  {
    "path": "otelcol/collector_core.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol // import \"go.opentelemetry.io/collector/otelcol\"\n\nimport (\n\t\"sync/atomic\"\n\n\t\"go.uber.org/zap/zapcore\"\n)\n\nvar _ zapcore.Core = (*collectorCore)(nil)\n\ntype collectorCore struct {\n\tdelegate atomic.Pointer[zapcore.Core]\n}\n\nfunc newCollectorCore(core zapcore.Core) *collectorCore {\n\tcc := &collectorCore{}\n\tcc.SetCore(core)\n\treturn cc\n}\n\nfunc (c *collectorCore) Enabled(l zapcore.Level) bool {\n\treturn c.loadDelegate().Enabled(l)\n}\n\nfunc (c *collectorCore) With(f []zapcore.Field) zapcore.Core {\n\treturn newCollectorCore(c.loadDelegate().With(f))\n}\n\nfunc (c *collectorCore) Check(e zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {\n\tcore := c.loadDelegate()\n\tif core.Enabled(e.Level) {\n\t\treturn ce.AddCore(e, core)\n\t}\n\treturn ce\n}\n\nfunc (c *collectorCore) Write(e zapcore.Entry, f []zapcore.Field) error {\n\treturn c.loadDelegate().Write(e, f)\n}\n\nfunc (c *collectorCore) Sync() error {\n\treturn c.loadDelegate().Sync()\n}\n\nfunc (c *collectorCore) SetCore(core zapcore.Core) {\n\tc.delegate.Store(&core)\n}\n\n// loadDelegate returns the delegate.\nfunc (c *collectorCore) loadDelegate() zapcore.Core {\n\treturn *c.delegate.Load()\n}\n"
  },
  {
    "path": "otelcol/collector_core_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap/zapcore\"\n)\n\nfunc Test_collectorCore_Enabled(t *testing.T) {\n\tcc := newCollectorCore(newBufferedCore(zapcore.InfoLevel))\n\tassert.True(t, cc.Enabled(zapcore.ErrorLevel))\n\tassert.False(t, cc.Enabled(zapcore.DebugLevel))\n}\n\nfunc Test_collectorCore_Check(t *testing.T) {\n\tt.Run(\"check passed\", func(t *testing.T) {\n\t\tbc := newBufferedCore(zapcore.InfoLevel)\n\t\tcc := newCollectorCore(bc)\n\t\te := zapcore.Entry{\n\t\t\tLevel: zapcore.InfoLevel,\n\t\t}\n\t\texpected := &zapcore.CheckedEntry{}\n\t\texpected = expected.AddCore(e, bc)\n\t\tassert.Equal(t, expected, cc.Check(e, nil))\n\t})\n\n\tt.Run(\"check did not pass\", func(t *testing.T) {\n\t\tcc := newCollectorCore(newBufferedCore(zapcore.InfoLevel))\n\t\te := zapcore.Entry{\n\t\t\tLevel: zapcore.DebugLevel,\n\t\t}\n\t\tassert.Nil(t, cc.Check(e, nil))\n\t})\n}\n\nfunc Test_collectorCore_With(t *testing.T) {\n\tcc := newCollectorCore(newBufferedCore(zapcore.InfoLevel))\n\tcc.loadDelegate().(*bufferedCore).context = []zapcore.Field{\n\t\t{Key: \"original\", String: \"context\"},\n\t}\n\tinputs := []zapcore.Field{\n\t\t{Key: \"test\", String: \"passed\"},\n\t}\n\texpected := []zapcore.Field{\n\t\t{Key: \"original\", String: \"context\"},\n\t\t{Key: \"test\", String: \"passed\"},\n\t}\n\tnewCC := cc.With(inputs)\n\tassert.Equal(t, expected, newCC.(*collectorCore).loadDelegate().(*bufferedCore).context)\n}\n\nfunc Test_collectorCore_Write(t *testing.T) {\n\tcc := newCollectorCore(newBufferedCore(zapcore.InfoLevel))\n\te := zapcore.Entry{\n\t\tLevel:   zapcore.DebugLevel,\n\t\tMessage: \"test\",\n\t}\n\tfields := []zapcore.Field{\n\t\t{Key: \"field1\", String: \"value1\"},\n\t}\n\terr := cc.Write(e, fields)\n\trequire.NoError(t, err)\n\n\texpected := loggedEntry{\n\t\te,\n\t\tfields,\n\t}\n\trequire.Len(t, cc.loadDelegate().(*bufferedCore).logs, 1)\n\trequire.Equal(t, expected, cc.loadDelegate().(*bufferedCore).logs[0])\n}\n\nfunc Test_collectorCore_Sync(t *testing.T) {\n\tcc := newCollectorCore(newBufferedCore(zapcore.InfoLevel))\n\tassert.NoError(t, cc.Sync())\n}\n\nfunc Test_collectorCore_SetCore(t *testing.T) {\n\tcc := newCollectorCore(newBufferedCore(zapcore.InfoLevel))\n\tnewCore := newBufferedCore(zapcore.DebugLevel)\n\tcc.SetCore(newCore)\n\tassert.Equal(t, zapcore.DebugLevel, cc.loadDelegate().(*bufferedCore).LevelEnabler)\n}\n"
  },
  {
    "path": "otelcol/collector_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package collector handles the command-line, configuration, and runs the OC collector.\npackage otelcol\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\t\"go.yaml.in/yaml/v3\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componentstatus\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n\t\"go.opentelemetry.io/collector/service/telemetry/telemetrytest\"\n)\n\nfunc TestStateString(t *testing.T) {\n\tassert.Equal(t, \"Starting\", StateStarting.String())\n\tassert.Equal(t, \"Running\", StateRunning.String())\n\tassert.Equal(t, \"Closing\", StateClosing.String())\n\tassert.Equal(t, \"Closed\", StateClosed.String())\n\tassert.Equal(t, \"UNKNOWN\", State(13).String())\n}\n\nfunc TestCollectorStartAsGoRoutine(t *testing.T) {\n\tset := CollectorSettings{\n\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\tFactories:              nopFactories,\n\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-nop.yaml\")}),\n\t}\n\tcol, err := NewCollector(set)\n\trequire.NoError(t, err)\n\n\twg := startCollector(context.Background(), t, col)\n\n\tassert.Eventually(t, func() bool {\n\t\treturn StateRunning == col.GetState()\n\t}, 2*time.Second, 200*time.Millisecond)\n\n\tcol.Shutdown()\n\tcol.Shutdown()\n\twg.Wait()\n\tassert.Equal(t, StateClosed, col.GetState())\n}\n\nfunc TestCollectorCancelContext(t *testing.T) {\n\tset := CollectorSettings{\n\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\tFactories:              nopFactories,\n\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-nop.yaml\")}),\n\t}\n\tcol, err := NewCollector(set)\n\trequire.NoError(t, err)\n\n\tctx, cancel := context.WithCancel(context.Background())\n\twg := startCollector(ctx, t, col)\n\n\tassert.Eventually(t, func() bool {\n\t\treturn StateRunning == col.GetState()\n\t}, 2*time.Second, 200*time.Millisecond)\n\n\tcancel()\n\twg.Wait()\n\tassert.Equal(t, StateClosed, col.GetState())\n}\n\nfunc TestCollectorStateAfterConfigChange(t *testing.T) {\n\tvar watcher confmap.WatcherFunc\n\tfileProvider := newFakeProvider(\"file\", func(_ context.Context, uri string, w confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\t\twatcher = w\n\t\tconf := newConfFromFile(t, uri[5:])\n\t\treturn confmap.NewRetrieved(conf)\n\t})\n\n\tshutdownRequests := make(chan chan struct{})\n\tshutdown := func(ctx context.Context) error {\n\t\tunblock := make(chan struct{})\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\tcase shutdownRequests <- unblock:\n\t\t\tselect {\n\t\t\tcase <-unblock:\n\t\t\tcase <-ctx.Done():\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t}\n\tfactories, err := nopFactories()\n\trequire.NoError(t, err)\n\tfactories.Telemetry = telemetry.NewFactory(\n\t\tfunc() component.Config { return fakeTelemetryConfig{} },\n\t\ttelemetrytest.WithLogger(zap.NewNop(), shutdown),\n\t)\n\n\tset := ConfigProviderSettings{\n\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\tURIs: []string{filepath.Join(\"testdata\", \"otelcol-nop.yaml\")},\n\t\t\tProviderFactories: []confmap.ProviderFactory{\n\t\t\t\tfileProvider,\n\t\t\t},\n\t\t},\n\t}\n\tcol, err := NewCollector(CollectorSettings{\n\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\tFactories:              func() (Factories, error) { return factories, nil },\n\t\tConfigProviderSettings: set,\n\t})\n\trequire.NoError(t, err)\n\n\twg := startCollector(context.Background(), t, col)\n\tassert.Eventually(t, func() bool {\n\t\treturn StateRunning == col.GetState()\n\t}, 10*time.Second, 10*time.Millisecond)\n\n\t// On config change, the collector will internally close\n\t// and recreate the service. The metrics reader will try to\n\t// push to the OTLP endpoint. We block the request to check\n\t// the state of the collector during the config change event.\n\twatcher(&confmap.ChangeEvent{})\n\tunblock := <-shutdownRequests\n\tassert.Equal(t, StateClosing, col.GetState())\n\tclose(unblock)\n\tassert.Eventually(t, func() bool {\n\t\treturn StateRunning == col.GetState()\n\t}, 10*time.Second, 10*time.Millisecond)\n\n\t// Do it again, but this time call Shutdown during the\n\t// config change to make sure the internal service shutdown\n\t// does not influence collector shutdown.\n\twatcher(&confmap.ChangeEvent{})\n\tunblock = <-shutdownRequests\n\tassert.Equal(t, StateClosing, col.GetState())\n\tcol.Shutdown()\n\tclose(unblock)\n\n\t// After the config reload, the final shutdown should occur.\n\tclose(<-shutdownRequests)\n\twg.Wait()\n\tassert.Equal(t, StateClosed, col.GetState())\n}\n\nfunc TestCollectorReportError(t *testing.T) {\n\tcol, err := NewCollector(CollectorSettings{\n\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\tFactories:              nopFactories,\n\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-nop.yaml\")}),\n\t})\n\trequire.NoError(t, err)\n\n\twg := startCollector(context.Background(), t, col)\n\n\tassert.Eventually(t, func() bool {\n\t\treturn StateRunning == col.GetState()\n\t}, 2*time.Second, 200*time.Millisecond)\n\n\tcol.asyncErrorChannel <- errors.New(\"err2\")\n\n\twg.Wait()\n\tassert.Equal(t, StateClosed, col.GetState())\n}\n\n// NewStatusWatcherExtensionFactory returns a component.ExtensionFactory to construct a status watcher extension.\nfunc NewStatusWatcherExtensionFactory(\n\tonStatusChanged func(source *componentstatus.InstanceID, event *componentstatus.Event),\n) extension.Factory {\n\treturn extension.NewFactory(\n\t\tcomponent.MustNewType(\"statuswatcher\"),\n\t\tfunc() component.Config {\n\t\t\treturn &struct{}{}\n\t\t},\n\t\tfunc(context.Context, extension.Settings, component.Config) (extension.Extension, error) {\n\t\t\treturn &statusWatcherExtension{onStatusChanged: onStatusChanged}, nil\n\t\t},\n\t\tcomponent.StabilityLevelStable)\n}\n\n// statusWatcherExtension receives status events reported via component status reporting for testing\n// purposes.\ntype statusWatcherExtension struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tonStatusChanged func(source *componentstatus.InstanceID, event *componentstatus.Event)\n}\n\nfunc (e statusWatcherExtension) ComponentStatusChanged(source *componentstatus.InstanceID, event *componentstatus.Event) {\n\te.onStatusChanged(source, event)\n}\n\nfunc TestComponentStatusWatcher(t *testing.T) {\n\tfactories, err := nopFactories()\n\trequire.NoError(t, err)\n\n\t// Use a processor factory that creates \"unhealthy\" processor: one that\n\t// always reports StatusRecoverableError after successful Start.\n\tunhealthyProcessorFactory := processortest.NewUnhealthyProcessorFactory()\n\tfactories.Processors[unhealthyProcessorFactory.Type()] = unhealthyProcessorFactory\n\n\t// Keep track of all status changes in a map.\n\tchangedComponents := map[*componentstatus.InstanceID][]componentstatus.Status{}\n\tvar mux sync.Mutex\n\tonStatusChanged := func(source *componentstatus.InstanceID, event *componentstatus.Event) {\n\t\tif source.ComponentID().Type() != unhealthyProcessorFactory.Type() {\n\t\t\treturn\n\t\t}\n\t\tmux.Lock()\n\t\tdefer mux.Unlock()\n\t\tchangedComponents[source] = append(changedComponents[source], event.Status())\n\t}\n\n\t// Add a \"statuswatcher\" extension that will receive notifications when processor\n\t// status changes.\n\tfactory := NewStatusWatcherExtensionFactory(onStatusChanged)\n\tfactories.Extensions[factory.Type()] = factory\n\n\t// Create a collector\n\tcol, err := NewCollector(CollectorSettings{\n\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\tFactories:              func() (Factories, error) { return factories, nil },\n\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-statuswatcher.yaml\")}),\n\t})\n\trequire.NoError(t, err)\n\n\t// Start the newly created collector.\n\twg := startCollector(context.Background(), t, col)\n\n\t// An unhealthy processor asynchronously reports a recoverable error. Depending on the Go\n\t// Scheduler the statuses reported at startup will be one of the two valid sequences below.\n\tstartupStatuses1 := []componentstatus.Status{\n\t\tcomponentstatus.StatusStarting,\n\t\tcomponentstatus.StatusOK,\n\t\tcomponentstatus.StatusRecoverableError,\n\t}\n\tstartupStatuses2 := []componentstatus.Status{\n\t\tcomponentstatus.StatusStarting,\n\t\tcomponentstatus.StatusRecoverableError,\n\t}\n\t// the modulus of the actual statuses will match the modulus of the startup statuses\n\tstartupStatuses := func(actualStatuses []componentstatus.Status) []componentstatus.Status {\n\t\tif len(actualStatuses)%2 == 1 {\n\t\t\treturn startupStatuses1\n\t\t}\n\t\treturn startupStatuses2\n\t}\n\n\t// The \"unhealthy\" processors will now begin to asynchronously report StatusRecoverableError.\n\t// We expect to see these reports.\n\tassert.Eventually(t, func() bool {\n\t\tmux.Lock()\n\t\tdefer mux.Unlock()\n\n\t\tfor k, v := range changedComponents {\n\t\t\t// All processors must report a status change with the same ID\n\t\t\tassert.Equal(t, component.NewID(unhealthyProcessorFactory.Type()), k.ComponentID())\n\t\t\t// And all must have a valid startup sequence\n\t\t\tassert.Equal(t, startupStatuses(v), v)\n\t\t}\n\t\t// We have 3 processors with exactly the same ID in otelcol-statuswatcher.yaml\n\t\t// We must have exactly 3 items in our map. This ensures that the \"source\" argument\n\t\t// passed to status change func is unique per instance of source component despite\n\t\t// components having the same IDs (having same ID for different component instances\n\t\t// is a normal situation for processors).\n\t\treturn len(changedComponents) == 3\n\t}, 2*time.Second, time.Millisecond*100)\n\n\tcol.Shutdown()\n\twg.Wait()\n\n\t// Check for additional statuses after Shutdown.\n\tfor _, v := range changedComponents {\n\t\texpectedStatuses := append([]componentstatus.Status{}, startupStatuses(v)...)\n\t\texpectedStatuses = append(expectedStatuses, componentstatus.StatusStopping, componentstatus.StatusStopped)\n\t\tassert.Equal(t, expectedStatuses, v)\n\t}\n\n\tassert.Equal(t, StateClosed, col.GetState())\n}\n\nfunc TestCollectorSendSignal(t *testing.T) {\n\tcol, err := NewCollector(CollectorSettings{\n\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\tFactories:              nopFactories,\n\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-nop.yaml\")}),\n\t})\n\trequire.NoError(t, err)\n\n\twg := startCollector(context.Background(), t, col)\n\n\tassert.Eventually(t, func() bool {\n\t\treturn StateRunning == col.GetState()\n\t}, 2*time.Second, 200*time.Millisecond)\n\n\tcol.signalsChannel <- SIGHUP\n\n\tassert.Eventually(t, func() bool {\n\t\treturn StateRunning == col.GetState()\n\t}, 2*time.Second, 200*time.Millisecond)\n\n\tcol.signalsChannel <- SIGTERM\n\n\twg.Wait()\n\tassert.Equal(t, StateClosed, col.GetState())\n}\n\nfunc TestCollectorFailedShutdown(t *testing.T) {\n\tt.Skip(\"This test was using telemetry shutdown failure, switch to use a component that errors on shutdown.\")\n\n\tcol, err := NewCollector(CollectorSettings{\n\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\tFactories:              nopFactories,\n\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-nop.yaml\")}),\n\t})\n\trequire.NoError(t, err)\n\n\twg := sync.WaitGroup{}\n\twg.Go(func() {\n\t\tassert.EqualError(t, col.Run(context.Background()), \"failed to shutdown collector telemetry: err1\")\n\t})\n\n\tassert.Eventually(t, func() bool {\n\t\treturn StateRunning == col.GetState()\n\t}, 2*time.Second, 200*time.Millisecond)\n\n\tcol.Shutdown()\n\n\twg.Wait()\n\tassert.Equal(t, StateClosed, col.GetState())\n}\n\nfunc TestCollectorStartInvalidConfig(t *testing.T) {\n\tcol, err := NewCollector(CollectorSettings{\n\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\tFactories:              nopFactories,\n\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-invalid.yaml\")}),\n\t})\n\trequire.NoError(t, err)\n\tassert.EqualError(t, col.Run(context.Background()), \"invalid configuration: service::pipelines::traces: references processor \\\"invalid\\\" which is not configured\")\n}\n\nfunc TestNewCollectorInvalidConfigProviderSettings(t *testing.T) {\n\t_, err := NewCollector(CollectorSettings{\n\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\tFactories:              nopFactories,\n\t\tConfigProviderSettings: ConfigProviderSettings{},\n\t})\n\trequire.Error(t, err)\n}\n\nfunc TestNewCollectorUseConfig(t *testing.T) {\n\tset := newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-nop.yaml\")})\n\n\tcol, err := NewCollector(CollectorSettings{\n\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\tFactories:              nopFactories,\n\t\tConfigProviderSettings: set,\n\t})\n\trequire.NoError(t, err)\n\trequire.NotNil(t, col.configProvider)\n}\n\nfunc TestNewCollectorValidatesResolverSettings(t *testing.T) {\n\tset := ConfigProviderSettings{\n\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\tURIs: []string{filepath.Join(\"testdata\", \"otelcol-nop.yaml\")},\n\t\t},\n\t}\n\n\t_, err := NewCollector(CollectorSettings{\n\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\tFactories:              nopFactories,\n\t\tConfigProviderSettings: set,\n\t})\n\trequire.Error(t, err)\n}\n\nfunc TestCollectorRun(t *testing.T) {\n\ttests := map[string]struct {\n\t\tfactories  func() (Factories, error)\n\t\tconfigFile string\n\t}{\n\t\t\"nop\": {\n\t\t\tfactories:  nopFactories,\n\t\t\tconfigFile: \"otelcol-nop.yaml\",\n\t\t},\n\t}\n\n\tfor name, test := range tests {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tset := CollectorSettings{\n\t\t\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\t\t\tFactories:              test.factories,\n\t\t\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", test.configFile)}),\n\t\t\t}\n\t\t\tcol, err := NewCollector(set)\n\t\t\trequire.NoError(t, err)\n\n\t\t\twg := startCollector(context.Background(), t, col)\n\n\t\t\tcol.Shutdown()\n\t\t\twg.Wait()\n\t\t\tassert.Equal(t, StateClosed, col.GetState())\n\t\t})\n\t}\n}\n\nfunc TestCollectorRun_AfterShutdown(t *testing.T) {\n\tset := CollectorSettings{\n\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\tFactories:              nopFactories,\n\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-nop.yaml\")}),\n\t}\n\tcol, err := NewCollector(set)\n\trequire.NoError(t, err)\n\n\t// Calling shutdown before collector is running should cause it to return quickly\n\trequire.NotPanics(t, func() { col.Shutdown() })\n\n\twg := startCollector(context.Background(), t, col)\n\n\tcol.Shutdown()\n\twg.Wait()\n\tassert.Equal(t, StateClosed, col.GetState())\n}\n\nfunc TestCollectorRun_Errors(t *testing.T) {\n\ttests := map[string]struct {\n\t\tsettings    CollectorSettings\n\t\texpectedErr string\n\t}{\n\t\t\"factories_error\": {\n\t\t\tsettings: CollectorSettings{\n\t\t\t\tFactories: func() (Factories, error) {\n\t\t\t\t\treturn Factories{}, errors.New(\"no factories for you\")\n\t\t\t\t},\n\t\t\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-nop.yaml\")}),\n\t\t\t},\n\t\t\texpectedErr: \"failed to initialize factories: no factories for you\",\n\t\t},\n\t\t\"invalid_processor\": {\n\t\t\tsettings: CollectorSettings{\n\t\t\t\tFactories:              nopFactories,\n\t\t\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-invalid.yaml\")}),\n\t\t\t},\n\t\t\texpectedErr: `invalid configuration: service::pipelines::traces: references processor \"invalid\" which is not configured`,\n\t\t},\n\t\t\"invalid_telemetry_config\": {\n\t\t\tsettings: CollectorSettings{\n\t\t\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\t\t\tFactories:              nopFactories,\n\t\t\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-invalid-telemetry.yaml\")}),\n\t\t\t},\n\t\t\texpectedErr: \"failed to get config: cannot unmarshal the configuration: decoding failed due to the following error(s):\\n\\n'service.telemetry' has invalid keys: unknown\",\n\t\t},\n\t\t\"missing_telemetry_factory\": {\n\t\t\tsettings: CollectorSettings{\n\t\t\t\tBuildInfo: component.NewDefaultBuildInfo(),\n\t\t\t\tFactories: func() (Factories, error) {\n\t\t\t\t\tfactories, _ := nopFactories()\n\t\t\t\t\tfactories.Telemetry = nil\n\t\t\t\t\treturn factories, nil\n\t\t\t\t},\n\t\t\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-otelconftelemetry.yaml\")}),\n\t\t\t},\n\t\t\texpectedErr: \"failed to get config: cannot unmarshal the configuration: otelcol.Factories.Telemetry must not be nil. For example, you can use otelconftelemetry.NewFactory to build a telemetry factory\",\n\t\t},\n\t}\n\n\tfor name, test := range tests {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tcol, err := NewCollector(test.settings)\n\t\t\trequire.NoError(t, err)\n\n\t\t\t// Expect run to error\n\t\t\terr = col.Run(context.Background())\n\t\t\trequire.EqualError(t, err, test.expectedErr)\n\n\t\t\t// Expect state to be closed\n\t\t\tassert.Equal(t, StateClosed, col.GetState())\n\t\t})\n\t}\n}\n\nfunc TestCollectorDryRun(t *testing.T) {\n\ttests := map[string]struct {\n\t\tsettings    CollectorSettings\n\t\texpectedErr string\n\t}{\n\t\t\"factories_error\": {\n\t\t\tsettings: CollectorSettings{\n\t\t\t\tFactories: func() (Factories, error) {\n\t\t\t\t\treturn Factories{}, errors.New(\"no factories for you\")\n\t\t\t\t},\n\t\t\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-nop.yaml\")}),\n\t\t\t},\n\t\t\texpectedErr: \"failed to initialize factories: no factories for you\",\n\t\t},\n\t\t\"invalid_processor\": {\n\t\t\tsettings: CollectorSettings{\n\t\t\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\t\t\tFactories:              nopFactories,\n\t\t\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-invalid.yaml\")}),\n\t\t\t},\n\t\t\texpectedErr: `service::pipelines::traces: references processor \"invalid\" which is not configured`,\n\t\t},\n\t\t\"invalid_connector_use_unused_exp\": {\n\t\t\tsettings: CollectorSettings{\n\t\t\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\t\t\tFactories:              nopFactories,\n\t\t\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-invalid-connector-unused-exp.yaml\")}),\n\t\t\t},\n\t\t\texpectedErr: `failed to build pipelines: connector \"nop/connector1\" used as receiver in [logs/in2] pipeline but not used in any supported exporter pipeline`,\n\t\t},\n\t\t\"invalid_connector_use_unused_rec\": {\n\t\t\tsettings: CollectorSettings{\n\t\t\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\t\t\tFactories:              nopFactories,\n\t\t\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-invalid-connector-unused-rec.yaml\")}),\n\t\t\t},\n\t\t\texpectedErr: `failed to build pipelines: connector \"nop/connector1\" used as exporter in [logs/in2] pipeline but not used in any supported receiver pipeline`,\n\t\t},\n\t\t\"cyclic_connector\": {\n\t\t\tsettings: CollectorSettings{\n\t\t\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\t\t\tFactories:              nopFactories,\n\t\t\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-cyclic-connector.yaml\")}),\n\t\t\t},\n\t\t\texpectedErr: `failed to build pipelines: cycle detected: connector \"nop/forward\" (traces to traces) -> connector \"nop/forward\" (traces to traces)`,\n\t\t},\n\t\t\"invalid_telemetry_config\": {\n\t\t\tsettings: CollectorSettings{\n\t\t\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\t\t\tFactories:              nopFactories,\n\t\t\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-invalid-telemetry.yaml\")}),\n\t\t\t},\n\t\t\texpectedErr: \"failed to get config: cannot unmarshal the configuration: decoding failed due to the following error(s):\\n\\n'service.telemetry' has invalid keys: unknown\",\n\t\t},\n\t\t\"missing_telemetry_factory\": {\n\t\t\tsettings: CollectorSettings{\n\t\t\t\tBuildInfo: component.NewDefaultBuildInfo(),\n\t\t\t\tFactories: func() (Factories, error) {\n\t\t\t\t\tfactories, _ := nopFactories()\n\t\t\t\t\tfactories.Telemetry = nil\n\t\t\t\t\treturn factories, nil\n\t\t\t\t},\n\t\t\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-otelconftelemetry.yaml\")}),\n\t\t\t},\n\t\t\texpectedErr: \"failed to get config: cannot unmarshal the configuration: otelcol.Factories.Telemetry must not be nil. For example, you can use otelconftelemetry.NewFactory to build a telemetry factory\",\n\t\t},\n\t}\n\n\tfor name, test := range tests {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tcol, err := NewCollector(test.settings)\n\t\t\trequire.NoError(t, err)\n\n\t\t\terr = col.DryRun(context.Background())\n\t\t\tif test.expectedErr == \"\" {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.EqualError(t, err, test.expectedErr)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc startCollector(ctx context.Context, t *testing.T, col *Collector) *sync.WaitGroup {\n\twg := &sync.WaitGroup{}\n\twg.Go(func() {\n\t\tassert.NoError(t, col.Run(ctx))\n\t})\n\treturn wg\n}\n\ntype failureProvider struct{}\n\nfunc newFailureProvider(_ confmap.ProviderSettings) confmap.Provider {\n\treturn &failureProvider{}\n}\n\nfunc (fmp *failureProvider) Retrieve(context.Context, string, confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\treturn nil, errors.New(\"a failure occurred during configuration retrieval\")\n}\n\nfunc (*failureProvider) Scheme() string {\n\treturn \"file\"\n}\n\nfunc (*failureProvider) Shutdown(context.Context) error {\n\treturn nil\n}\n\ntype fakeProvider struct {\n\tscheme string\n\tret    func(ctx context.Context, uri string, watcher confmap.WatcherFunc) (*confmap.Retrieved, error)\n\tlogger *zap.Logger\n}\n\nfunc (f *fakeProvider) Retrieve(ctx context.Context, uri string, watcher confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\treturn f.ret(ctx, uri, watcher)\n}\n\nfunc (f *fakeProvider) Scheme() string {\n\treturn f.scheme\n}\n\nfunc (f *fakeProvider) Shutdown(context.Context) error {\n\treturn nil\n}\n\nfunc newFakeProvider(scheme string, ret func(ctx context.Context, uri string, watcher confmap.WatcherFunc) (*confmap.Retrieved, error)) confmap.ProviderFactory {\n\treturn confmap.NewProviderFactory(func(ps confmap.ProviderSettings) confmap.Provider {\n\t\treturn &fakeProvider{\n\t\t\tscheme: scheme,\n\t\t\tret:    ret,\n\t\t\tlogger: ps.Logger,\n\t\t}\n\t})\n}\n\nfunc newEnvProvider() confmap.ProviderFactory {\n\treturn newFakeProvider(\"env\", func(_ context.Context, uri string, _ confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\t\t// When using `env` as the default scheme for tests, the uri will not include `env:`.\n\t\t// Instead of duplicating the switch cases, the scheme is added instead.\n\t\tif uri[0:4] != \"env:\" {\n\t\t\turi = \"env:\" + uri\n\t\t}\n\t\tswitch uri {\n\t\tcase \"env:COMPLEX_VALUE\":\n\t\t\treturn confmap.NewRetrieved([]any{\"localhost:3042\"})\n\t\tcase \"env:HOST\":\n\t\t\treturn confmap.NewRetrieved(\"localhost\")\n\t\tcase \"env:OS\":\n\t\t\treturn confmap.NewRetrieved(\"ubuntu\")\n\t\tcase \"env:PR\":\n\t\t\treturn confmap.NewRetrieved(\"amd\")\n\t\tcase \"env:PORT\":\n\t\t\treturn confmap.NewRetrieved(3044)\n\t\tcase \"env:INT\":\n\t\t\treturn confmap.NewRetrieved(1)\n\t\tcase \"env:INT32\":\n\t\t\treturn confmap.NewRetrieved(32)\n\t\tcase \"env:INT64\":\n\t\t\treturn confmap.NewRetrieved(64)\n\t\tcase \"env:FLOAT32\":\n\t\t\treturn confmap.NewRetrieved(float32(3.25))\n\t\tcase \"env:FLOAT64\":\n\t\t\treturn confmap.NewRetrieved(float64(6.4))\n\t\tcase \"env:BOOL\":\n\t\t\treturn confmap.NewRetrieved(true)\n\t\t}\n\t\treturn nil, errors.New(\"impossible\")\n\t})\n}\n\nfunc newDefaultConfigProviderSettings(tb testing.TB, uris []string) ConfigProviderSettings {\n\tfileProvider := newFakeProvider(\"file\", func(_ context.Context, uri string, _ confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\t\treturn confmap.NewRetrieved(newConfFromFile(tb, uri[5:]))\n\t})\n\treturn ConfigProviderSettings{\n\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\tURIs: uris,\n\t\t\tProviderFactories: []confmap.ProviderFactory{\n\t\t\t\tfileProvider,\n\t\t\t\tnewEnvProvider(),\n\t\t\t},\n\t\t},\n\t}\n}\n\n// newConfFromFile creates a new Conf by reading the given file.\nfunc newConfFromFile(tb testing.TB, fileName string) map[string]any {\n\tcontent, err := os.ReadFile(filepath.Clean(fileName))\n\trequire.NoErrorf(tb, err, \"unable to read the file %v\", fileName)\n\n\tvar data map[string]any\n\trequire.NoError(tb, yaml.Unmarshal(content, &data), \"unable to parse yaml\")\n\n\treturn confmap.NewFromStringMap(data).ToStringMap()\n}\n\nfunc TestProviderAndConverterModules(t *testing.T) {\n\tset := CollectorSettings{\n\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\tFactories:              nopFactories,\n\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-nop.yaml\")}),\n\t\tProviderModules: map[string]string{\n\t\t\t\"nop\": \"go.opentelemetry.io/collector/confmap/provider/testprovider v1.2.3\",\n\t\t},\n\t\tConverterModules: []string{\n\t\t\t\"go.opentelemetry.io/collector/converter/testconverter v1.2.3\",\n\t\t},\n\t}\n\tcol, err := NewCollector(set)\n\trequire.NoError(t, err)\n\twg := startCollector(context.Background(), t, col)\n\trequire.NoError(t, err)\n\tproviderModules := map[string]string{\n\t\t\"nop\": \"go.opentelemetry.io/collector/confmap/provider/testprovider v1.2.3\",\n\t}\n\tconverterModules := []string{\n\t\t\"go.opentelemetry.io/collector/converter/testconverter v1.2.3\",\n\t}\n\tassert.Equal(t, providerModules, col.set.ProviderModules)\n\tassert.Equal(t, converterModules, col.set.ConverterModules)\n\tcol.Shutdown()\n\twg.Wait()\n}\n\nfunc TestCollectorLoggingOptions(t *testing.T) {\n\t// Use zap observer to verify that LoggingOptions are applied\n\tobserverCore, observedLogs := observer.New(zapcore.InfoLevel)\n\n\tfactories, err := nopFactories()\n\trequire.NoError(t, err)\n\n\t// Create a custom telemetry factory that uses BuildZapLogger\n\t// This ensures BuildZapLogger (which includes LoggingOptions) is used\n\tfactories.Telemetry = telemetry.NewFactory(\n\t\tfunc() component.Config { return fakeTelemetryConfig{} },\n\t\ttelemetry.WithCreateLogger(\n\t\t\tfunc(_ context.Context, set telemetry.LoggerSettings, _ component.Config) (\n\t\t\t\t*zap.Logger, component.ShutdownFunc, error,\n\t\t\t) {\n\t\t\t\trequire.Empty(t, set.ZapOptions) // injected through BuidlZapLogger\n\t\t\t\tlogger, buildErr := set.BuildZapLogger(zap.NewDevelopmentConfig())\n\t\t\t\treturn logger, nil, buildErr\n\t\t\t},\n\t\t),\n\t)\n\n\tset := CollectorSettings{\n\t\tBuildInfo: component.NewDefaultBuildInfo(),\n\t\tFactories: func() (Factories, error) { return factories, nil },\n\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t,\n\t\t\t[]string{filepath.Join(\"testdata\", \"otelcol-nop.yaml\")},\n\t\t),\n\t\tLoggingOptions: []zap.Option{\n\t\t\tzap.WrapCore(func(zapcore.Core) zapcore.Core {\n\t\t\t\treturn observerCore\n\t\t\t}),\n\t\t},\n\t}\n\n\tcol, err := NewCollector(set)\n\trequire.NoError(t, err)\n\n\t// Start and stop the collector.\n\twg := startCollector(context.Background(), t, col)\n\tassert.Eventually(t, func() bool {\n\t\treturn StateRunning == col.GetState() && col.service != nil\n\t}, 2*time.Second, 200*time.Millisecond)\n\tcol.Shutdown()\n\twg.Wait()\n\n\t// Check that logs have been redirected to our observer core,\n\t// which proves that LoggingOptions were applied.\n\tentries := observedLogs.All()\n\trequire.NotEmpty(t, entries, \"Logger should have logged messages\")\n}\n"
  },
  {
    "path": "otelcol/collector_windows.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build windows\n\npackage otelcol // import \"go.opentelemetry.io/collector/otelcol\"\n\nimport (\n\t\"context\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"slices\"\n\t\"time\"\n\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\t\"golang.org/x/sys/windows/svc\"\n\t\"golang.org/x/sys/windows/svc/eventlog\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\ntype windowsService struct {\n\tsettings CollectorSettings\n\tcol      *Collector\n\tflags    *flag.FlagSet\n}\n\n// NewSvcHandler constructs a new svc.Handler using the given CollectorSettings.\nfunc NewSvcHandler(set CollectorSettings) svc.Handler {\n\treturn &windowsService{settings: set, flags: flags(featuregate.GlobalRegistry())}\n}\n\n// Execute implements https://godoc.org/golang.org/x/sys/windows/svc#Handler\nfunc (s *windowsService) Execute(args []string, requests <-chan svc.ChangeRequest, changes chan<- svc.Status) (ssec bool, errno uint32) {\n\t// The first argument supplied to service.Execute is the service name. If this is\n\t// not provided for some reason, raise a relevant error to the system event log\n\tif len(args) == 0 {\n\t\treturn false, 1213 // 1213: ERROR_INVALID_SERVICENAME\n\t}\n\n\telog, err := openEventLog(args[0])\n\tif err != nil {\n\t\treturn false, 1501 // 1501: ERROR_EVENTLOG_CANT_START\n\t}\n\n\tcolErrorChannel := make(chan error, 1)\n\n\tchanges <- svc.Status{State: svc.StartPending}\n\tif err = s.start(elog, colErrorChannel); err != nil {\n\t\t_ = elog.Error(3, fmt.Sprintf(\"failed to start service: %v\", err))\n\t\treturn false, 1064 // 1064: ERROR_EXCEPTION_IN_SERVICE\n\t}\n\tchanges <- svc.Status{State: svc.Running, Accepts: svc.AcceptStop | svc.AcceptShutdown}\n\n\tfor req := range requests {\n\t\tswitch req.Cmd {\n\t\tcase svc.Interrogate:\n\t\t\tchanges <- req.CurrentStatus\n\n\t\tcase svc.Stop, svc.Shutdown:\n\t\t\tchanges <- svc.Status{State: svc.StopPending}\n\t\t\tif err = s.stop(colErrorChannel); err != nil {\n\t\t\t\t_ = elog.Error(3, fmt.Sprintf(\"errors occurred while shutting down the service: %v\", err))\n\t\t\t}\n\t\t\tchanges <- svc.Status{State: svc.Stopped}\n\t\t\treturn false, 0\n\n\t\tdefault:\n\t\t\t_ = elog.Error(3, fmt.Sprintf(\"unexpected service control request #%d\", req.Cmd))\n\t\t\treturn false, 1052 // 1052: ERROR_INVALID_SERVICE_CONTROL\n\t\t}\n\t}\n\n\treturn false, 0\n}\n\nfunc (s *windowsService) start(elog *eventlog.Log, colErrorChannel chan error) error {\n\t// Parse all the flags manually.\n\tif err := s.flags.Parse(os.Args[1:]); err != nil {\n\t\treturn err\n\t}\n\n\tvar err error\n\terr = updateSettingsUsingFlags(&s.settings, s.flags)\n\tif err != nil {\n\t\treturn err\n\t}\n\ts.col, err = NewCollector(s.settings)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Override the Zap logger to write to the Windows Event Log\n\t// if no file output is specified.\n\ts.col.buildZapLogger = func(cfg zap.Config, opts ...zap.Option) (*zap.Logger, error) {\n\t\tfor _, output := range cfg.OutputPaths {\n\t\t\tif output != \"stdout\" && output != \"stderr\" {\n\t\t\t\t// A file has been specified in the configuration,\n\t\t\t\t// so do not use the Windows Event Log.\n\t\t\t\treturn cfg.Build(opts...)\n\t\t\t}\n\t\t}\n\t\topts = slices.Insert(opts, 0, zap.WrapCore(withWindowsCore(elog)))\n\t\treturn cfg.Build(opts...)\n\t}\n\n\t// col.Run blocks until receiving a SIGTERM signal, so needs to be started\n\t// asynchronously, but it will exit early if an error occurs on startup\n\tgo func() {\n\t\tcolErrorChannel <- s.col.Run(context.Background())\n\t}()\n\n\t// wait until the collector server is in the Running state\n\tgo func() {\n\t\tfor {\n\t\t\tstate := s.col.GetState()\n\t\t\tif state == StateRunning {\n\t\t\t\tcolErrorChannel <- nil\n\t\t\t\tbreak\n\t\t\t}\n\t\t\ttime.Sleep(time.Millisecond * 200)\n\t\t}\n\t}()\n\n\t// wait until the collector server is in the Running state, or an error was returned\n\treturn <-colErrorChannel\n}\n\nfunc (s *windowsService) stop(colErrorChannel chan error) error {\n\ts.col.Shutdown()\n\t// return the response of col.Start\n\treturn <-colErrorChannel\n}\n\nfunc openEventLog(serviceName string) (*eventlog.Log, error) {\n\telog, err := eventlog.Open(serviceName)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"service failed to open event log: %w\", err)\n\t}\n\n\treturn elog, nil\n}\n\nvar _ zapcore.Core = (*windowsEventLogCore)(nil)\n\ntype windowsEventLogCore struct {\n\tcore    zapcore.Core\n\telog    *eventlog.Log\n\tencoder zapcore.Encoder\n}\n\nfunc (w windowsEventLogCore) Enabled(level zapcore.Level) bool {\n\treturn w.core.Enabled(level)\n}\n\nfunc (w windowsEventLogCore) With(fields []zapcore.Field) zapcore.Core {\n\tenc := w.encoder.Clone()\n\tfor _, field := range fields {\n\t\tfield.AddTo(enc)\n\t}\n\treturn windowsEventLogCore{\n\t\tcore:    w.core,\n\t\telog:    w.elog,\n\t\tencoder: enc,\n\t}\n}\n\nfunc (w windowsEventLogCore) Check(ent zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {\n\tif w.Enabled(ent.Level) {\n\t\treturn ce.AddCore(ent, w)\n\t}\n\treturn ce\n}\n\nfunc (w windowsEventLogCore) Write(ent zapcore.Entry, fields []zapcore.Field) error {\n\tbuf, err := w.encoder.EncodeEntry(ent, fields)\n\tif err != nil {\n\t\t_ = w.elog.Warning(2, fmt.Sprintf(\"failed encoding log entry %v\\r\\n\", err))\n\t\treturn err\n\t}\n\tmsg := buf.String()\n\tbuf.Free()\n\n\tswitch ent.Level {\n\tcase zapcore.FatalLevel, zapcore.PanicLevel, zapcore.DPanicLevel:\n\t\t// golang.org/x/sys/windows/svc/eventlog does not support Critical level event logs\n\t\treturn w.elog.Error(3, msg)\n\tcase zapcore.ErrorLevel:\n\t\treturn w.elog.Error(3, msg)\n\tcase zapcore.WarnLevel:\n\t\treturn w.elog.Warning(2, msg)\n\tcase zapcore.InfoLevel:\n\t\treturn w.elog.Info(1, msg)\n\t}\n\t// We would not be here if debug were disabled so log as info to not drop.\n\treturn w.elog.Info(1, msg)\n}\n\nfunc (w windowsEventLogCore) Sync() error {\n\treturn w.core.Sync()\n}\n\nfunc withWindowsCore(elog *eventlog.Log) func(zapcore.Core) zapcore.Core {\n\treturn func(core zapcore.Core) zapcore.Core {\n\t\t// Use the Windows Event Log\n\t\tencoderConfig := zap.NewProductionEncoderConfig()\n\t\tencoderConfig.LineEnding = \"\\r\\n\"\n\t\tencoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder\n\t\treturn windowsEventLogCore{core, elog, zapcore.NewConsoleEncoder(encoderConfig)}\n\t}\n}\n"
  },
  {
    "path": "otelcol/collector_windows_service_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build windows && win32service\n\npackage otelcol\n\nimport (\n\t\"encoding/xml\"\n\t\"fmt\"\n\t\"os\"\n\t\"os/exec\"\n\t\"path/filepath\"\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"golang.org/x/sys/windows/svc\"\n\t\"golang.org/x/sys/windows/svc/mgr\"\n)\n\nconst (\n\tcollectorServiceName = \"otelcorecol\"\n)\n\n// Test the collector as a Windows service.\n// The test assumes that the service and respective event source are already created.\n//\n// To test locally:\n// * Build the binary:\n//   - make otelcorecol\n//\n// * Install the Windows service\n//   - New-Service -Name \"otelcorecol\" -StartupType \"Manual\" -BinaryPathName \"${PWD}\\bin\\otelcorecol_windows_$(go env GOARCH) --config ${PWD}\\examples\\local\\otel-config.yaml\"\n//\n// * Create event log source\n//   - eventcreate.exe /t information /id 1 /l application /d \"Creating event provider for 'otelcorecol'\" /so otelcorecol\n//\n// The test also must be executed with administrative privileges.\nfunc TestCollectorAsService(t *testing.T) {\n\tcollector_executable, err := filepath.Abs(filepath.Join(\"..\", \"bin\", fmt.Sprintf(\"otelcorecol_windows_%s\", runtime.GOARCH)))\n\trequire.NoError(t, err)\n\t_, err = os.Stat(collector_executable)\n\trequire.NoError(t, err)\n\n\tscm, err := mgr.Connect()\n\trequire.NoError(t, err)\n\tdefer scm.Disconnect()\n\n\tservice, err := scm.OpenService(collectorServiceName)\n\trequire.NoError(t, err)\n\tdefer service.Close()\n\n\ttests := []struct {\n\t\tname               string\n\t\tconfigFile         string\n\t\texpectStartFailure bool\n\t\tcustomSetup        func(*testing.T)\n\t\tcustomValidation   func(*testing.T)\n\t}{\n\t\t{\n\t\t\tname:       \"Default\",\n\t\t\tconfigFile: filepath.Join(\"..\", \"examples\", \"local\", \"otel-config.yaml\"),\n\t\t},\n\t\t{\n\t\t\tname:               \"ConfigFileNotFound\",\n\t\t\tconfigFile:         filepath.Join(\".\", \"non\", \"existent\", \"otel-config.yaml\"),\n\t\t\texpectStartFailure: true,\n\t\t},\n\t\t{\n\t\t\tname:       \"LogToFile\",\n\t\t\tconfigFile: filepath.Join(\".\", \"testdata\", \"otelcol-log-to-file.yaml\"),\n\t\t\tcustomSetup: func(t *testing.T) {\n\t\t\t\t// Create the folder and clean the log file if it exists\n\t\t\t\tprogramDataPath := os.Getenv(\"ProgramData\")\n\t\t\t\tlogsPath := filepath.Join(programDataPath, \"OpenTelemetry\", \"Collector\", \"Logs\")\n\t\t\t\terr := os.MkdirAll(logsPath, os.ModePerm)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\tlogFilePath := filepath.Join(logsPath, \"otelcol.log\")\n\t\t\t\terr = os.Remove(logFilePath)\n\t\t\t\tif err != nil && !os.IsNotExist(err) {\n\t\t\t\t\trequire.NoError(t, err)\n\t\t\t\t}\n\t\t\t},\n\t\t\tcustomValidation: func(t *testing.T) {\n\t\t\t\t// Check that the log file was created\n\t\t\t\tprogramDataPath := os.Getenv(\"ProgramData\")\n\t\t\t\tlogsPath := filepath.Join(programDataPath, \"OpenTelemetry\", \"Collector\", \"Logs\")\n\t\t\t\tlogFilePath := filepath.Join(logsPath, \"otelcol.log\")\n\t\t\t\tfileinfo, err := os.Stat(logFilePath)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.NotEmpty(t, fileinfo.Size())\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tserviceConfig, err := service.Config()\n\t\t\trequire.NoError(t, err)\n\n\t\t\t// Setup the command line to launch the collector as a service\n\t\t\tfullConfigPath, err := filepath.Abs(tt.configFile)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tserviceConfig.BinaryPathName = fmt.Sprintf(\"\\\"%s\\\" --config \\\"%s\\\"\", collector_executable, fullConfigPath)\n\t\t\terr = service.UpdateConfig(serviceConfig)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tif tt.customSetup != nil {\n\t\t\t\ttt.customSetup(t)\n\t\t\t}\n\n\t\t\tstartTime := time.Now()\n\n\t\t\terr = service.Start()\n\t\t\trequire.NoError(t, err)\n\n\t\t\texpectedState := svc.Running\n\t\t\tif tt.expectStartFailure {\n\t\t\t\texpectedState = svc.Stopped\n\t\t\t} else {\n\t\t\t\tdefer func() {\n\t\t\t\t\t_, err = service.Control(svc.Stop)\n\t\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\t\trequire.Eventually(t, func() bool {\n\t\t\t\t\t\tstatus, _ := service.Query()\n\t\t\t\t\t\treturn status.State == svc.Stopped\n\t\t\t\t\t}, 10*time.Second, 500*time.Millisecond)\n\t\t\t\t}()\n\t\t\t}\n\n\t\t\t// Wait for the service to reach the expected state\n\t\t\trequire.Eventually(t, func() bool {\n\t\t\t\tstatus, _ := service.Query()\n\t\t\t\treturn status.State == expectedState\n\t\t\t}, 10*time.Second, 500*time.Millisecond)\n\n\t\t\tif tt.customValidation != nil {\n\t\t\t\ttt.customValidation(t)\n\t\t\t} else {\n\t\t\t\t// Read the events from the otelcorecol source and check that they were emitted after the service\n\t\t\t\t// command started. This is a simple validation that the messages are being logged on the\n\t\t\t\t// Windows event log.\n\t\t\t\tcmd := exec.Command(\"wevtutil.exe\", \"qe\", \"Application\", \"/c:1\", \"/rd:true\", \"/f:RenderedXml\", \"/q:*[System[Provider[@Name='otelcorecol']]]\")\n\t\t\t\tout, err := cmd.CombinedOutput()\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\tvar e Event\n\t\t\t\trequire.NoError(t, xml.Unmarshal([]byte(out), &e))\n\n\t\t\t\teventTime, err := time.Parse(\"2006-01-02T15:04:05.9999999Z07:00\", e.System.TimeCreated.SystemTime)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\trequire.True(t, eventTime.After(startTime.In(time.UTC)))\n\t\t\t}\n\t\t})\n\t}\n}\n\n// Helper types to read the XML events from the event log using wevtutil\ntype Event struct {\n\tXMLName xml.Name `xml:\"Event\"`\n\tSystem  System   `xml:\"System\"`\n\tData    string   `xml:\"EventData>Data\"`\n}\n\ntype System struct {\n\tProvider      Provider    `xml:\"Provider\"`\n\tEventID       int         `xml:\"EventID\"`\n\tVersion       int         `xml:\"Version\"`\n\tLevel         int         `xml:\"Level\"`\n\tTask          int         `xml:\"Task\"`\n\tOpcode        int         `xml:\"Opcode\"`\n\tKeywords      string      `xml:\"Keywords\"`\n\tTimeCreated   TimeCreated `xml:\"TimeCreated\"`\n\tEventRecordID int         `xml:\"EventRecordID\"`\n\tExecution     Execution   `xml:\"Execution\"`\n\tChannel       string      `xml:\"Channel\"`\n\tComputer      string      `xml:\"Computer\"`\n}\n\ntype Provider struct {\n\tName string `xml:\"Name,attr\"`\n}\n\ntype TimeCreated struct {\n\tSystemTime string `xml:\"SystemTime,attr\"`\n}\n\ntype Execution struct {\n\tProcessID string `xml:\"ProcessID,attr\"`\n\tThreadID  string `xml:\"ThreadID,attr\"`\n}\n"
  },
  {
    "path": "otelcol/collector_windows_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build windows\n\npackage otelcol\n\nimport (\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"golang.org/x/sys/windows/svc\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc TestNewSvcHandler(t *testing.T) {\n\toldArgs := os.Args\n\tdefer func() { os.Args = oldArgs }()\n\tfilePath := filepath.Join(\"testdata\", \"otelcol-nop.yaml\")\n\tos.Args = []string{\"otelcol\", \"--config\", filePath}\n\n\ts := NewSvcHandler(CollectorSettings{BuildInfo: component.NewDefaultBuildInfo(), Factories: nopFactories, ConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filePath})})\n\n\tcolDone := make(chan struct{})\n\trequests := make(chan svc.ChangeRequest)\n\tchanges := make(chan svc.Status)\n\tgo func() {\n\t\tdefer close(colDone)\n\t\tssec, errno := s.Execute([]string{\"svc name\"}, requests, changes)\n\t\tassert.Equal(t, uint32(0), errno)\n\t\tassert.False(t, ssec)\n\t}()\n\n\tassert.Equal(t, svc.StartPending, (<-changes).State)\n\tassert.Equal(t, svc.Running, (<-changes).State)\n\trequests <- svc.ChangeRequest{Cmd: svc.Interrogate, CurrentStatus: svc.Status{State: svc.Running}}\n\tassert.Equal(t, svc.Running, (<-changes).State)\n\trequests <- svc.ChangeRequest{Cmd: svc.Stop}\n\tassert.Equal(t, svc.StopPending, (<-changes).State)\n\tassert.Equal(t, svc.Stopped, (<-changes).State)\n\t<-colDone\n}\n"
  },
  {
    "path": "otelcol/command.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol // import \"go.opentelemetry.io/collector/otelcol\"\n\n//go:generate mdatagen metadata.yaml\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"os\"\n\t\"text/tabwriter\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\n// NewCommand constructs a new cobra.Command using the given CollectorSettings.\n// Any URIs specified in CollectorSettings.ConfigProviderSettings.ResolverSettings.URIs\n// are considered defaults and will be overwritten by config flags passed as\n// command-line arguments to the executable.\n// At least one Provider must be set.\nfunc NewCommand(set CollectorSettings) *cobra.Command {\n\tflagSet := flags(featuregate.GlobalRegistry())\n\trootCmd := &cobra.Command{\n\t\tUse:          set.BuildInfo.Command,\n\t\tVersion:      set.BuildInfo.Version,\n\t\tSilenceUsage: true,\n\t\tRunE: func(cmd *cobra.Command, _ []string) error {\n\t\t\terr := updateSettingsUsingFlags(&set, flagSet)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\tcol, err := NewCollector(set)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn col.Run(cmd.Context())\n\t\t},\n\t}\n\trootCmd.AddCommand(newFeatureGateCommand())\n\trootCmd.AddCommand(newComponentsCommand(set))\n\trootCmd.AddCommand(newValidateSubCommand(set, flagSet))\n\trootCmd.AddCommand(newConfigPrintSubCommand(set, flagSet))\n\trootCmd.Flags().AddGoFlagSet(flagSet)\n\treturn rootCmd\n}\n\n// Puts command line flags from flags into the CollectorSettings, to be used during config resolution.\nfunc updateSettingsUsingFlags(set *CollectorSettings, flags *flag.FlagSet) error {\n\tresolverSet := &set.ConfigProviderSettings.ResolverSettings\n\tconfigFlags := getConfigFlag(flags)\n\n\tif len(configFlags) > 0 {\n\t\tresolverSet.URIs = configFlags\n\t}\n\tif len(resolverSet.URIs) == 0 {\n\t\treturn errors.New(\"at least one config flag must be provided\")\n\t}\n\n\tif set.ConfigProviderSettings.ResolverSettings.DefaultScheme == \"\" {\n\t\tset.ConfigProviderSettings.ResolverSettings.DefaultScheme = \"env\"\n\t}\n\n\tif len(resolverSet.ProviderFactories) == 0 {\n\t\treturn errors.New(\"at least one Provider must be supplied\")\n\t}\n\n\treturn nil\n}\n\nfunc newFeatureGateCommand() *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse:   \"featuregate [feature-id]\",\n\t\tShort: \"Display feature gates information\",\n\t\tLong:  \"Display information about available feature gates and their status\",\n\t\tArgs:  cobra.MaximumNArgs(1),\n\t\tRunE: func(_ *cobra.Command, args []string) error {\n\t\t\tif len(args) > 0 {\n\t\t\t\tfound := false\n\t\t\t\tfeaturegate.GlobalRegistry().VisitAll(func(g *featuregate.Gate) {\n\t\t\t\t\tif g.ID() == args[0] {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tfmt.Printf(\"Feature: %s\\n\", g.ID())\n\t\t\t\t\t\tfmt.Printf(\"Enabled: %v\\n\", g.IsEnabled())\n\t\t\t\t\t\tfmt.Printf(\"Stage: %s\\n\", g.Stage())\n\t\t\t\t\t\tfmt.Printf(\"Description: %s\\n\", g.Description())\n\t\t\t\t\t\tfmt.Printf(\"From Version: %s\\n\", g.FromVersion())\n\t\t\t\t\t\tif g.ToVersion() != \"\" {\n\t\t\t\t\t\t\tfmt.Printf(\"To Version: %s\\n\", g.ToVersion())\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tif !found {\n\t\t\t\t\treturn fmt.Errorf(\"feature %q not found\", args[0])\n\t\t\t\t}\n\t\t\t\treturn nil\n\t\t\t}\n\n\t\t\tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)\n\t\t\tfmt.Fprintf(w, \"ID\\tEnabled\\tStage\\tDescription\\n\")\n\t\t\tfeaturegate.GlobalRegistry().VisitAll(func(g *featuregate.Gate) {\n\t\t\t\tfmt.Fprintf(w, \"%s\\t%v\\t%s\\t%s\\n\",\n\t\t\t\t\tg.ID(),\n\t\t\t\t\tg.IsEnabled(),\n\t\t\t\t\tg.Stage(),\n\t\t\t\t\tg.Description())\n\t\t\t})\n\t\t\treturn w.Flush()\n\t\t},\n\t}\n}\n"
  },
  {
    "path": "otelcol/command_components.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol // import \"go.opentelemetry.io/collector/otelcol\"\n\nimport (\n\t\"fmt\"\n\t\"sort\"\n\n\t\"github.com/spf13/cobra\"\n\t\"go.yaml.in/yaml/v3\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/receiver\"\n)\n\ntype componentWithStability struct {\n\tName      component.Type\n\tModule    string\n\tStability map[string]string\n}\n\ntype componentWithoutStability struct {\n\tScheme string `yaml:\",omitempty\"`\n\tModule string\n}\n\ntype componentsOutput struct {\n\tBuildInfo  component.BuildInfo\n\tReceivers  []componentWithStability\n\tProcessors []componentWithStability\n\tExporters  []componentWithStability\n\tConnectors []componentWithStability\n\tExtensions []componentWithStability\n\tProviders  []componentWithoutStability\n\tConverters []componentWithoutStability `yaml:\",omitempty\"`\n}\n\n// newComponentsCommand constructs a new components command using the given CollectorSettings.\nfunc newComponentsCommand(set CollectorSettings) *cobra.Command {\n\treturn &cobra.Command{\n\t\tUse:   \"components\",\n\t\tShort: \"Outputs available components in this collector distribution\",\n\t\tLong:  \"Outputs available components in this collector distribution including their stability levels. The output format is not stable and can change between releases.\",\n\t\tArgs:  cobra.ExactArgs(0),\n\t\tRunE: func(cmd *cobra.Command, _ []string) error {\n\t\t\tfactories, err := set.Factories()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to initialize factories: %w\", err)\n\t\t\t}\n\n\t\t\tcomponents := componentsOutput{}\n\t\t\tfor _, con := range sortFactoriesByType[connector.Factory](factories.Connectors) {\n\t\t\t\tcomponents.Connectors = append(components.Connectors, componentWithStability{\n\t\t\t\t\tName:   con.Type(),\n\t\t\t\t\tModule: factories.ConnectorModules[con.Type()],\n\t\t\t\t\tStability: map[string]string{\n\t\t\t\t\t\t\"logs-to-logs\":    con.LogsToLogsStability().String(),\n\t\t\t\t\t\t\"logs-to-metrics\": con.LogsToMetricsStability().String(),\n\t\t\t\t\t\t\"logs-to-traces\":  con.LogsToTracesStability().String(),\n\n\t\t\t\t\t\t\"metrics-to-logs\":    con.MetricsToLogsStability().String(),\n\t\t\t\t\t\t\"metrics-to-metrics\": con.MetricsToMetricsStability().String(),\n\t\t\t\t\t\t\"metrics-to-traces\":  con.MetricsToTracesStability().String(),\n\n\t\t\t\t\t\t\"traces-to-logs\":    con.TracesToLogsStability().String(),\n\t\t\t\t\t\t\"traces-to-metrics\": con.TracesToMetricsStability().String(),\n\t\t\t\t\t\t\"traces-to-traces\":  con.TracesToTracesStability().String(),\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t\tfor _, ext := range sortFactoriesByType[extension.Factory](factories.Extensions) {\n\t\t\t\tcomponents.Extensions = append(components.Extensions, componentWithStability{\n\t\t\t\t\tName:   ext.Type(),\n\t\t\t\t\tModule: factories.ExtensionModules[ext.Type()],\n\t\t\t\t\tStability: map[string]string{\n\t\t\t\t\t\t\"extension\": ext.Stability().String(),\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t\tfor _, prs := range sortFactoriesByType[processor.Factory](factories.Processors) {\n\t\t\t\tcomponents.Processors = append(components.Processors, componentWithStability{\n\t\t\t\t\tName:   prs.Type(),\n\t\t\t\t\tModule: factories.ProcessorModules[prs.Type()],\n\t\t\t\t\tStability: map[string]string{\n\t\t\t\t\t\t\"logs\":    prs.LogsStability().String(),\n\t\t\t\t\t\t\"metrics\": prs.MetricsStability().String(),\n\t\t\t\t\t\t\"traces\":  prs.TracesStability().String(),\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t\tfor _, rcv := range sortFactoriesByType[receiver.Factory](factories.Receivers) {\n\t\t\t\tcomponents.Receivers = append(components.Receivers, componentWithStability{\n\t\t\t\t\tName:   rcv.Type(),\n\t\t\t\t\tModule: factories.ReceiverModules[rcv.Type()],\n\t\t\t\t\tStability: map[string]string{\n\t\t\t\t\t\t\"logs\":    rcv.LogsStability().String(),\n\t\t\t\t\t\t\"metrics\": rcv.MetricsStability().String(),\n\t\t\t\t\t\t\"traces\":  rcv.TracesStability().String(),\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t\tfor _, exp := range sortFactoriesByType[exporter.Factory](factories.Exporters) {\n\t\t\t\tcomponents.Exporters = append(components.Exporters, componentWithStability{\n\t\t\t\t\tName:   exp.Type(),\n\t\t\t\t\tModule: factories.ExporterModules[exp.Type()],\n\t\t\t\t\tStability: map[string]string{\n\t\t\t\t\t\t\"logs\":    exp.LogsStability().String(),\n\t\t\t\t\t\t\"metrics\": exp.MetricsStability().String(),\n\t\t\t\t\t\t\"traces\":  exp.TracesStability().String(),\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\t\t\tcomponents.BuildInfo = set.BuildInfo\n\n\t\t\tcomponents.Providers = append(components.Providers, sortProvidersByScheme(\n\t\t\t\tset.ProviderModules,\n\t\t\t\tset.ConfigProviderSettings.ResolverSettings.ProviderFactories,\n\t\t\t\tset.ConfigProviderSettings.ResolverSettings.ProviderSettings,\n\t\t\t)...)\n\t\t\tcomponents.Converters = append(components.Converters, sortConverterModules(set.ConverterModules)...)\n\n\t\t\tyamlData, err := yaml.Marshal(components)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tfmt.Fprint(cmd.OutOrStdout(), string(yamlData))\n\t\t\treturn nil\n\t\t},\n\t}\n}\n\nfunc sortFactoriesByType[T component.Factory](factories map[component.Type]T) []T {\n\t// Gather component types (factories map keys)\n\tcomponentTypes := make([]component.Type, 0, len(factories))\n\tfor componentType := range factories {\n\t\tcomponentTypes = append(componentTypes, componentType)\n\t}\n\n\t// Sort component types as strings\n\tsort.Slice(componentTypes, func(i, j int) bool {\n\t\treturn componentTypes[i].String() < componentTypes[j].String()\n\t})\n\n\t// Build and return list of factories, sorted by component types\n\tsortedFactories := make([]T, 0, len(factories))\n\tfor _, componentType := range componentTypes {\n\t\tif !isComponentAlias(factories[componentType]) {\n\t\t\tsortedFactories = append(sortedFactories, factories[componentType])\n\t\t}\n\t}\n\n\treturn sortedFactories\n}\n\nfunc sortProvidersByScheme(providerModules map[string]string, provFactories []confmap.ProviderFactory, set confmap.ProviderSettings) []componentWithoutStability {\n\tschemes := make([]string, 0, len(provFactories))\n\tfor _, f := range provFactories {\n\t\tprovF := f.Create(set)\n\t\tscheme := provF.Scheme()\n\t\tif !isComponentAlias(f) {\n\t\t\tschemes = append(schemes, scheme)\n\t\t}\n\t}\n\n\tsort.Strings(schemes)\n\n\tproviderComponents := make([]componentWithoutStability, 0, len(providerModules))\n\tfor _, scheme := range schemes {\n\t\tproviderComponents = append(providerComponents, componentWithoutStability{\n\t\t\tScheme: scheme,\n\t\t\tModule: providerModules[scheme],\n\t\t})\n\t}\n\treturn providerComponents\n}\n\nfunc sortConverterModules(modules []string) []componentWithoutStability {\n\tsortedModulesCopy := make([]string, len(modules))\n\tcopy(sortedModulesCopy, modules)\n\tsort.Strings(sortedModulesCopy)\n\n\tsortedModules := make([]componentWithoutStability, 0, len(modules))\n\tfor _, mod := range sortedModulesCopy {\n\t\tsortedModules = append(sortedModules, componentWithoutStability{\n\t\t\tModule: mod,\n\t\t})\n\t}\n\treturn sortedModules\n}\n\nfunc isComponentAlias(component any) bool {\n\tif al, ok := component.(componentalias.TypeAliasHolder); ok {\n\t\treturn al.DeprecatedAlias().String() != \"\"\n\t}\n\treturn false\n}\n"
  },
  {
    "path": "otelcol/command_components_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/xconnector\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/xprocessor\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n)\n\nfunc TestNewBuildSubCommand(t *testing.T) {\n\tset := CollectorSettings{\n\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\tFactories:              nopFactories,\n\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-nop.yaml\")}),\n\t\t// ensure default providers are referenced by scheme to a module\n\t\tProviderModules: map[string]string{\n\t\t\t\"file\": \"go.opentelemetry.io/collector/confmap/provider/testprovider v1.2.3\",\n\t\t\t\"env\":  \"go.opentelemetry.io/collector/confmap/provider/testprovider v1.2.3\",\n\t\t},\n\t\tConverterModules: []string{\n\t\t\t\"go.opentelemetry.io/collector/converter/testconverter v1.2.3\",\n\t\t},\n\t}\n\tcmd := NewCommand(set)\n\tcmd.SetArgs([]string{\"components\"})\n\n\texpectedOutput, err := os.ReadFile(filepath.Join(\"testdata\", \"components-output.yaml\"))\n\trequire.NoError(t, err)\n\n\tb := bytes.NewBufferString(\"\")\n\tcmd.SetOut(b)\n\terr = cmd.Execute()\n\trequire.NoError(t, err)\n\n\t// Trim new line at the end of the two strings to make a better comparison as string() adds an extra new\n\t// line that makes the test fail.\n\tassert.Equal(t, strings.TrimSpace(string(expectedOutput)), strings.TrimSpace(b.String()))\n}\n\nfunc TestComponentsStableOutput(t *testing.T) {\n\tset := CollectorSettings{\n\t\tBuildInfo:              component.NewDefaultBuildInfo(),\n\t\tFactories:              newNamedNopFactories([]string{\"bar\", \"foo\", \"baz\"}),\n\t\tConfigProviderSettings: newDefaultConfigProviderSettings(t, []string{filepath.Join(\"testdata\", \"otelcol-nop.yaml\")}),\n\t\t// assumes default config provider contains `file`` and `env` schemes`.\n\t\tProviderModules: map[string]string{\n\t\t\t\"file\": \"go.opentelemetry.io/collector/confmap/provider/testprovider v1.2.3\",\n\t\t\t\"env\":  \"go.opentelemetry.io/collector/confmap/provider/testprovider v1.2.3\",\n\t\t},\n\t\tConverterModules: []string{\n\t\t\t\"go.opentelemetry.io/collector/converter/baz v1.2.3\",\n\t\t\t\"go.opentelemetry.io/collector/converter/foo v1.2.3\",\n\t\t\t\"go.opentelemetry.io/collector/converter/bar v1.2.3\",\n\t\t},\n\t}\n\tcmd := NewCommand(set)\n\tcmd.SetArgs([]string{\"components\"})\n\n\texpectedOutput, err := os.ReadFile(filepath.Join(\"testdata\", \"components-output-sorted.yaml\"))\n\trequire.NoError(t, err)\n\n\t// ensure output is reasonably consistent\n\tfor range 5 {\n\t\tb := bytes.NewBufferString(\"\")\n\t\tcmd.SetOut(b)\n\t\terr = cmd.Execute()\n\t\trequire.NoError(t, err)\n\t\t// Trim new line at the end of the two strings to make a better comparison as string() adds an extra new\n\t\t// line that makes the test fail.\n\t\tassert.Equal(t, strings.TrimSpace(string(expectedOutput)), strings.TrimSpace(b.String()))\n\t}\n}\n\nfunc newNamedNopFactories(\n\tplaceholderTypes []string,\n) func() (Factories, error) {\n\treturn func() (Factories, error) {\n\t\tvar factories Factories\n\t\tvar err error\n\n\t\tif factories.Connectors, err = MakeFactoryMap(newListNamedConnectorNopFactory(\n\t\t\tplaceholderTypes,\n\t\t)...); err != nil {\n\t\t\treturn Factories{}, err\n\t\t}\n\t\tfactories.ConnectorModules = make(map[component.Type]string, len(factories.Connectors))\n\t\tfor _, con := range factories.Connectors {\n\t\t\tfactories.ConnectorModules[con.Type()] = \"go.opentelemetry.io/collector/connector/connectortest v1.2.3\"\n\t\t}\n\n\t\tif factories.Extensions, err = MakeFactoryMap(newListNamedExtensionNopFactory(\n\t\t\tplaceholderTypes,\n\t\t)...); err != nil {\n\t\t\treturn Factories{}, err\n\t\t}\n\t\tfactories.ExtensionModules = make(map[component.Type]string, len(factories.Extensions))\n\t\tfor _, ext := range factories.Extensions {\n\t\t\tfactories.ExtensionModules[ext.Type()] = \"go.opentelemetry.io/collector/extension/extensiontest v1.2.3\"\n\t\t}\n\n\t\tif factories.Receivers, err = MakeFactoryMap(newListNamedReceiverNopFactory(\n\t\t\tplaceholderTypes,\n\t\t)...); err != nil {\n\t\t\treturn Factories{}, err\n\t\t}\n\t\tfactories.ReceiverModules = make(map[component.Type]string, len(factories.Receivers))\n\t\tfor _, rec := range factories.Receivers {\n\t\t\tfactories.ReceiverModules[rec.Type()] = \"go.opentelemetry.io/collector/receiver/receivertest v1.2.3\"\n\t\t}\n\n\t\tif factories.Exporters, err = MakeFactoryMap(newListNamedExporterNopFactory(\n\t\t\tplaceholderTypes,\n\t\t)...); err != nil {\n\t\t\treturn Factories{}, err\n\t\t}\n\t\tfactories.ExporterModules = make(map[component.Type]string, len(factories.Exporters))\n\t\tfor _, exp := range factories.Exporters {\n\t\t\tfactories.ExporterModules[exp.Type()] = \"go.opentelemetry.io/collector/exporter/exportertest v1.2.3\"\n\t\t}\n\n\t\tif factories.Processors, err = MakeFactoryMap(newListNamedProcessorNopFactory(\n\t\t\tplaceholderTypes,\n\t\t)...); err != nil {\n\t\t\treturn Factories{}, err\n\t\t}\n\t\tfactories.ProcessorModules = make(map[component.Type]string, len(factories.Processors))\n\t\tfor _, proc := range factories.Processors {\n\t\t\tfactories.ProcessorModules[proc.Type()] = \"go.opentelemetry.io/collector/processor/processortest v1.2.3\"\n\t\t}\n\n\t\treturn factories, nil\n\t}\n}\n\ntype nopComponent struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n}\n\nfunc newNamedConnecterNopFactory(typeName string) connector.Factory {\n\treturn xconnector.NewFactory(\n\t\tcomponent.MustNewType(typeName),\n\t\tfunc() component.Config { return struct{}{} },\n\t)\n}\n\nfunc newListNamedConnectorNopFactory(typeNames []string) []connector.Factory {\n\tfacts := make([]connector.Factory, 0, len(typeNames))\n\tfor _, typ := range typeNames {\n\t\tfacts = append(facts, newNamedConnecterNopFactory(typ))\n\t}\n\treturn facts\n}\n\nfunc newNamedExtensionNopFactory(typeName string) extension.Factory {\n\treturn extension.NewFactory(\n\t\tcomponent.MustNewType(typeName),\n\t\tfunc() component.Config { return struct{}{} },\n\t\tfunc(context.Context, extension.Settings, component.Config) (extension.Extension, error) {\n\t\t\treturn nopComponent{}, nil\n\t\t},\n\t\tcomponent.StabilityLevelStable,\n\t)\n}\n\nfunc newListNamedExtensionNopFactory(typeNames []string) []extension.Factory {\n\tfacts := make([]extension.Factory, 0, len(typeNames))\n\tfor _, typ := range typeNames {\n\t\tfacts = append(facts, newNamedExtensionNopFactory(typ))\n\t}\n\treturn facts\n}\n\nfunc newNamedReceiverNopFactory(typeName string) receiver.Factory {\n\treturn xreceiver.NewFactory(\n\t\tcomponent.MustNewType(typeName),\n\t\tfunc() component.Config { return struct{}{} },\n\t)\n}\n\nfunc newListNamedReceiverNopFactory(typeNames []string) []receiver.Factory {\n\tfacts := make([]receiver.Factory, 0, len(typeNames))\n\tfor _, typ := range typeNames {\n\t\tfacts = append(facts, newNamedReceiverNopFactory(typ))\n\t}\n\treturn facts\n}\n\nfunc newNamedProcessorNopFactory(typeName string) processor.Factory {\n\treturn xprocessor.NewFactory(\n\t\tcomponent.MustNewType(typeName),\n\t\tfunc() component.Config { return struct{}{} },\n\t)\n}\n\nfunc newListNamedProcessorNopFactory(typeNames []string) []processor.Factory {\n\tfacts := make([]processor.Factory, 0, len(typeNames))\n\tfor _, typ := range typeNames {\n\t\tfacts = append(facts, newNamedProcessorNopFactory(typ))\n\t}\n\treturn facts\n}\n\nfunc newNamedExportersNopFactory(typeName string) exporter.Factory {\n\treturn xexporter.NewFactory(\n\t\tcomponent.MustNewType(typeName),\n\t\tfunc() component.Config { return struct{}{} },\n\t)\n}\n\nfunc newListNamedExporterNopFactory(typeNames []string) []exporter.Factory {\n\tfacts := make([]exporter.Factory, 0, len(typeNames))\n\tfor _, typ := range typeNames {\n\t\tfacts = append(facts, newNamedExportersNopFactory(typ))\n\t}\n\treturn facts\n}\n\ntype mockFactory struct {\n\tcomponentalias.TypeAliasHolder\n\tname string\n}\n\nfunc (mockFactory) CreateDefaultConfig() component.Config {\n\treturn nil\n}\n\nfunc (m mockFactory) Type() component.Type {\n\treturn component.MustNewType(m.name)\n}\n\nfunc newMockFactory(name string) mockFactory {\n\treturn mockFactory{\n\t\tTypeAliasHolder: componentalias.NewTypeAliasHolder(),\n\t\tname:            name,\n\t}\n}\n\nfunc TestSortFactoriesByType(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname      string\n\t\tfactories map[component.Type]mockFactory\n\t\twant      []mockFactory\n\t}{\n\t\t{\n\t\t\tname:      \"with an empty map\",\n\t\t\tfactories: map[component.Type]mockFactory{},\n\t\t\twant:      []mockFactory{},\n\t\t},\n\t\t{\n\t\t\tname: \"with a single factory\",\n\t\t\tfactories: map[component.Type]mockFactory{\n\t\t\t\tcomponent.MustNewType(\"receiver\"): newMockFactory(\"receiver_factory\"),\n\t\t\t},\n\t\t\twant: []mockFactory{\n\t\t\t\tnewMockFactory(\"receiver_factory\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with multiple factories\",\n\t\t\tfactories: map[component.Type]mockFactory{\n\t\t\t\tcomponent.MustNewType(\"processor\"): newMockFactory(\"processor_factory\"),\n\t\t\t\tcomponent.MustNewType(\"exporter\"):  newMockFactory(\"exporter_factory\"),\n\t\t\t\tcomponent.MustNewType(\"receiver\"):  newMockFactory(\"receiver_factory\"),\n\t\t\t},\n\t\t\twant: []mockFactory{\n\t\t\t\tnewMockFactory(\"exporter_factory\"),\n\t\t\t\tnewMockFactory(\"processor_factory\"),\n\t\t\t\tnewMockFactory(\"receiver_factory\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with aliases factories\",\n\t\t\tfactories: func() map[component.Type]mockFactory {\n\t\t\t\talias := newMockFactory(\"alias_processor_factory\")\n\t\t\t\talias.SetDeprecatedAlias(alias.Type())\n\n\t\t\t\treturn map[component.Type]mockFactory{\n\t\t\t\t\tcomponent.MustNewType(\"processor\"):       newMockFactory(\"processor_factory\"),\n\t\t\t\t\tcomponent.MustNewType(\"alias_processor\"): alias,\n\t\t\t\t}\n\t\t\t}(),\n\t\t\twant: []mockFactory{\n\t\t\t\tnewMockFactory(\"processor_factory\"),\n\t\t\t},\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tgot := sortFactoriesByType(tt.factories)\n\t\t\tassert.Equal(t, tt.want, got)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "otelcol/command_print.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol // import \"go.opentelemetry.io/collector/otelcol\"\n\nimport (\n\t\"encoding/json\"\n\t\"errors\"\n\t\"flag\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n\n\t\"github.com/spf13/cobra\"\n\t\"go.yaml.in/yaml/v3\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n\t\"go.opentelemetry.io/collector/otelcol/internal/metadata\"\n)\n\n// newConfigPrintSubCommand constructs a new print-config command using the given CollectorSettings.\nfunc newConfigPrintSubCommand(set CollectorSettings, flagSet *flag.FlagSet) *cobra.Command {\n\tvar outputFormat string\n\tvar mode string\n\tvar validate bool\n\n\tcmd := &cobra.Command{\n\t\tUse:     \"print-config\",\n\t\tAliases: []string{\"print-initial-config\"},\n\t\tShort:   \"Prints the Collector's configuration in the specified mode\",\n\t\tLong: `Prints the Collector's configuration with different levels of processing:\n\n- redacted: Shows the resolved configuration with sensitive data redacted (default)\n- unredacted: Shows the resolved configuration with all sensitive data visible\n\nThe output prints in YAML by default. To print JSON use --format=json,\nhowever this is considered unstable.\n\nValidation is enabled by default, as a safety measure.\n\nAll modes are experimental, requiring the otelcol.printInitialConfig feature gate.`,\n\t\tArgs: cobra.ExactArgs(0),\n\t\tRunE: func(cmd *cobra.Command, _ []string) error {\n\t\t\tpc := printContext{\n\t\t\t\tcmd:          cmd,\n\t\t\t\tstdout:       cmd.OutOrStdout(),\n\t\t\t\tset:          set,\n\t\t\t\toutputFormat: outputFormat,\n\t\t\t\tvalidate:     validate,\n\t\t\t}\n\t\t\treturn pc.configPrintSubCommand(flagSet, mode)\n\t\t},\n\t}\n\n\tformatHelp := \"Output format: yaml (default), json (unstable))\"\n\tcmd.Flags().StringVar(&outputFormat, \"format\", \"yaml\", formatHelp)\n\n\tmodeHelp := \"Operating mode: redacted (default), unredacted\"\n\tcmd.Flags().StringVar(&mode, \"mode\", \"redacted\", modeHelp)\n\n\tvalidateHelp := \"Validation mode: true (default), false\"\n\tcmd.Flags().BoolVar(&validate, \"validate\", true, validateHelp)\n\n\tcmd.Flags().AddGoFlagSet(flagSet)\n\treturn cmd\n}\n\ntype printContext struct {\n\tcmd          *cobra.Command\n\tstdout       io.Writer\n\tset          CollectorSettings\n\toutputFormat string\n\tvalidate     bool\n}\n\nfunc (pctx *printContext) configPrintSubCommand(flagSet *flag.FlagSet, mode string) error {\n\tif !metadata.OtelcolPrintInitialConfigFeatureGate.IsEnabled() {\n\t\treturn errors.New(\"print-config is currently experimental, use the otelcol.printInitialConfig feature gate to enable this command\")\n\t}\n\terr := updateSettingsUsingFlags(&pctx.set, flagSet)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tswitch strings.ToLower(mode) {\n\tcase \"redacted\":\n\t\treturn pctx.printRedactedConfig()\n\tcase \"unredacted\":\n\t\treturn pctx.printUnredactedConfig()\n\tdefault:\n\t\treturn fmt.Errorf(\"invalid mode %q: modes are: redacted, unredacted\", mode)\n\t}\n}\n\n// printConfigData formats and prints configuration data in yaml or json format.\nfunc (pctx *printContext) printConfigData(data map[string]any) error {\n\tformat := pctx.outputFormat\n\tif format == \"\" {\n\t\tformat = \"yaml\"\n\t}\n\n\tswitch {\n\tcase strings.EqualFold(format, \"yaml\"):\n\t\tb, err := yaml.Marshal(data)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfmt.Fprintf(pctx.stdout, \"%s\\n\", b)\n\t\treturn nil\n\n\tcase strings.EqualFold(format, \"json\"):\n\t\tencoder := json.NewEncoder(pctx.stdout)\n\t\tencoder.SetIndent(\"\", \"  \")\n\t\treturn encoder.Encode(data)\n\t}\n\n\treturn fmt.Errorf(\"unrecognized print format: %s\", format)\n}\n\nfunc (pctx *printContext) getPrintableConfig() (any, error) {\n\tvar factories Factories\n\tif pctx.set.Factories != nil {\n\t\tvar err error\n\t\tfactories, err = pctx.set.Factories()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to get factories: %w\", err)\n\t\t}\n\t}\n\n\tconfigProvider, err := NewConfigProvider(pctx.set.ConfigProviderSettings)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create config provider: %w\", err)\n\t}\n\n\tcfg, err := configProvider.Get(pctx.cmd.Context(), factories)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to get config: %w\", err)\n\t}\n\treturn cfg, nil\n}\n\n// printUnredactedConfig prints resolved configuration before interpreting\n// with the intended types for each component, thus it shows the full\n// configuration without considering configuopaque. Use with caution.\nfunc (pctx *printContext) printUnredactedConfig() error {\n\tif pctx.validate {\n\t\t// Validation serves prevent revealing invalid data.\n\t\tcfg, err := pctx.getPrintableConfig()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err = xconfmap.Validate(cfg); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid configuration: %w\", err)\n\t\t}\n\n\t\t// Note: we discard the validated configuration.\n\t}\n\tresolver, err := confmap.NewResolver(pctx.set.ConfigProviderSettings.ResolverSettings)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create new resolver: %w\", err)\n\t}\n\tconf, err := resolver.Resolve(pctx.cmd.Context())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error while resolving config: %w\", err)\n\t}\n\treturn pctx.printConfigData(conf.ToStringMap())\n}\n\n// printRedactedConfig prints resolved configuration with its assigned\n// types, but without validation. Notably, configopaque strings are printed\n// as \"[redacted]\". This is the default.\nfunc (pctx *printContext) printRedactedConfig() error {\n\tcfg, err := pctx.getPrintableConfig()\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tif pctx.validate {\n\t\tif err = xconfmap.Validate(cfg); err != nil {\n\t\t\treturn fmt.Errorf(\"invalid configuration: %w\", err)\n\t\t}\n\t}\n\n\tconfMap := confmap.New()\n\tif err := confMap.Marshal(cfg); err != nil {\n\t\treturn fmt.Errorf(\"failed to marshal config: %w\", err)\n\t}\n\treturn pctx.printConfigData(confMap.ToStringMap())\n}\n"
  },
  {
    "path": "otelcol/command_print_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol // import \"go.opentelemetry.io/collector/otelcol\"\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"path/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configopaque\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/provider/fileprovider\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/otelcol/internal/metadata\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n)\n\ntype printExporterConfig struct {\n\tTimeout time.Duration `mapstructure:\"timeout\"`\n}\n\ntype printReceiverConfig struct {\n\tOpaque configopaque.String `mapstructure:\"opaque\"`\n\tOther  string              `mapstructure:\"other,omitempty\"`\n}\n\nfunc (c *printExporterConfig) Validate() error {\n\tif c.Timeout < 0 {\n\t\treturn errors.New(\"timeout cannot be negative\")\n\t}\n\treturn nil\n}\n\nfunc TestPrintCommand(t *testing.T) {\n\tconst nonexistentConfig = \"file:nope.yaml\"\n\n\tvalidConfig := fmt.Sprint(\"file:\", filepath.Join(\"testdata\", \"print.yaml\"))\n\tinvalidConfig1 := fmt.Sprint(\"file:\", filepath.Join(\"testdata\", \"print_invalid.yaml\"))\n\tinvalidConfig2 := fmt.Sprint(\"file:\", filepath.Join(\"testdata\", \"print_negative.yaml\"))\n\tdefaultConfig := fmt.Sprint(\"file:\", filepath.Join(\"testdata\", \"print_default.yaml\"))\n\n\ttests := []struct {\n\t\tname            string\n\t\tofmt            string\n\t\tpath            string\n\t\terrString       string\n\t\toutString       map[string]string\n\t\tdisableFF       bool // disable the feature flag\n\t\tvalidate        bool // add validation (even redacted)\n\t\terrOnlyRedacted bool // error applies only in redacted mode\n\t}{\n\t\t{\n\t\t\tname:      \"file not found\",\n\t\t\tpath:      nonexistentConfig,\n\t\t\terrString: \"cannot retrieve the configuration: unable to read the file\",\n\t\t},\n\t\t{\n\t\t\tname: \"valid yaml\",\n\t\t\tpath: validConfig,\n\t\t},\n\t\t{\n\t\t\tname:            \"invalid syntax without validate\",\n\t\t\tpath:            invalidConfig1,\n\t\t\terrString:       \"'timeout' time: invalid duration\",\n\t\t\terrOnlyRedacted: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"validation fail\",\n\t\t\tpath:      invalidConfig2,\n\t\t\tvalidate:  true,\n\t\t\terrString: \"timeout cannot be negative\",\n\t\t},\n\t\t{\n\t\t\tname:      \"no feature flag\",\n\t\t\tpath:      validConfig,\n\t\t\tdisableFF: true,\n\t\t\terrString: \"use the otelcol.printInitialConfig feature gate\",\n\t\t},\n\t\t{\n\t\t\tname: \"field is set yaml\",\n\t\t\tpath: validConfig,\n\t\t\toutString: map[string]string{\n\t\t\t\t\"redacted\":   `timeout: 5s`,\n\t\t\t\t\"unredacted\": `timeout: 5s`,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"default field value\",\n\t\t\tpath: defaultConfig,\n\t\t\toutString: map[string]string{\n\t\t\t\t\"redacted\": `timeout: 1s`,\n\n\t\t\t\t// Since the structure is empty before\n\t\t\t\t// interpretation, no default is expanded.\n\t\t\t\t\"unredacted\": `e: null`,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"field is set json\",\n\t\t\tofmt: \"json\",\n\t\t\tpath: validConfig,\n\t\t\toutString: map[string]string{\n\t\t\t\t// Note: JSON does not format as a time.Duration\n\t\t\t\t\"redacted\": `\"timeout\": 5000000000`,\n\n\t\t\t\t// Note: the original input is \"5s\"\n\t\t\t\t\"unredacted\": `\"timeout\": \"5s\"`,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"opaque field\",\n\t\t\tpath: validConfig,\n\t\t\toutString: map[string]string{\n\t\t\t\t\"redacted\":   `opaque: '[REDACTED]'`,\n\t\t\t\t\"unredacted\": `opaque: OOO`,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"opaque default\",\n\t\t\tpath: defaultConfig,\n\t\t\toutString: map[string]string{\n\t\t\t\t\"redacted\": `opaque: '[REDACTED]'`,\n\n\t\t\t\t// Note: the default opaque value does not print,\n\t\t\t\t// the other value is set in defaultConfig so that\n\t\t\t\t// the whole component config is not defaulted.\n\t\t\t\t\"unredacted\": `other: lala`,\n\t\t\t},\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\ttestModes := []string{\"redacted\", \"unredacted\", \"unrecognized\"}\n\t\tfor _, mode := range testModes {\n\t\t\tt.Run(fmt.Sprint(test.name, \"_\", mode), func(t *testing.T) {\n\t\t\t\t// Save current feature flag state and restore after test\n\t\t\t\tfg := featuregate.GlobalRegistry()\n\n\t\t\t\tfg.VisitAll(func(g *featuregate.Gate) {\n\t\t\t\t\tif g.ID() == metadata.OtelcolPrintInitialConfigFeatureGate.ID() {\n\t\t\t\t\t\tdefer func() {\n\t\t\t\t\t\t\t_ = fg.Set(metadata.OtelcolPrintInitialConfigFeatureGate.ID(), g.IsEnabled())\n\t\t\t\t\t\t}()\n\t\t\t\t\t}\n\t\t\t\t})\n\t\t\t\tif test.disableFF {\n\t\t\t\t\trequire.NoError(t, fg.Set(metadata.OtelcolPrintInitialConfigFeatureGate.ID(), false))\n\t\t\t\t} else {\n\t\t\t\t\trequire.NoError(t, fg.Set(metadata.OtelcolPrintInitialConfigFeatureGate.ID(), true))\n\t\t\t\t}\n\n\t\t\t\ttestR := component.MustNewType(\"r\")\n\t\t\t\ttestE := component.MustNewType(\"e\")\n\t\t\t\ttestReceiver := xreceiver.NewFactory(\n\t\t\t\t\ttestR,\n\t\t\t\t\tfunc() component.Config {\n\t\t\t\t\t\treturn printReceiverConfig{\n\t\t\t\t\t\t\tOpaque: \"1234\",\n\t\t\t\t\t\t\tOther:  \"\",\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\txreceiver.WithLogs(func(context.Context, receiver.Settings, component.Config, consumer.Logs) (receiver.Logs, error) {\n\t\t\t\t\t\treturn nil, nil\n\t\t\t\t\t}, component.StabilityLevelStable),\n\t\t\t\t)\n\t\t\t\ttestExporter := xexporter.NewFactory(\n\t\t\t\t\ttestE,\n\t\t\t\t\tfunc() component.Config {\n\t\t\t\t\t\treturn printExporterConfig{\n\t\t\t\t\t\t\tTimeout: time.Second,\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\txexporter.WithLogs(func(context.Context, exporter.Settings, component.Config) (exporter.Logs, error) {\n\t\t\t\t\t\treturn nil, nil\n\t\t\t\t\t}, component.StabilityLevelStable),\n\t\t\t\t)\n\t\t\t\tvar stdout bytes.Buffer\n\n\t\t\t\tset := confmap.ResolverSettings{}\n\t\t\t\tset.ProviderFactories = []confmap.ProviderFactory{\n\t\t\t\t\tfileprovider.NewFactory(),\n\t\t\t\t}\n\t\t\t\tset.DefaultScheme = \"file\"\n\t\t\t\tset.URIs = []string{test.path}\n\n\t\t\t\tcmd := newConfigPrintSubCommand(CollectorSettings{\n\t\t\t\t\tFactories: func() (Factories, error) {\n\t\t\t\t\t\treturn Factories{\n\t\t\t\t\t\t\tReceivers: map[component.Type]receiver.Factory{\n\t\t\t\t\t\t\t\ttestR: testReceiver,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tExporters: map[component.Type]exporter.Factory{\n\t\t\t\t\t\t\t\ttestE: testExporter,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\tTelemetry: telemetry.NewFactory(func() component.Config {\n\t\t\t\t\t\t\t\treturn fakeTelemetryConfig{}\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t}, nil\n\t\t\t\t\t},\n\t\t\t\t\tConfigProviderSettings: ConfigProviderSettings{\n\t\t\t\t\t\tResolverSettings: set,\n\t\t\t\t\t},\n\t\t\t\t}, flags(featuregate.GlobalRegistry()))\n\t\t\t\tcmd.SetOut(&stdout)\n\t\t\t\targs := []string{\n\t\t\t\t\t\"--mode\", mode,\n\t\t\t\t\t\"--format\", test.ofmt,\n\t\t\t\t}\n\t\t\t\tif test.validate {\n\t\t\t\t\targs = append(args, \"--validate=true\")\n\t\t\t\t} else {\n\t\t\t\t\targs = append(args, \"--validate=false\")\n\t\t\t\t}\n\t\t\t\tcmd.SetArgs(args)\n\t\t\t\terr := cmd.Execute()\n\n\t\t\t\texpectErr := test.errString != \"\"\n\t\t\t\texpectErrMsg := test.errString\n\n\t\t\t\tswitch mode {\n\t\t\t\tcase \"redacted\":\n\t\t\t\tcase \"unredacted\":\n\t\t\t\t\tif test.errOnlyRedacted {\n\t\t\t\t\t\texpectErr = false\n\t\t\t\t\t\texpectErrMsg = \"\"\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\texpectErr = true\n\t\t\t\t\tif test.disableFF {\n\t\t\t\t\t\texpectErrMsg = \"feature gate\"\n\t\t\t\t\t} else {\n\t\t\t\t\t\texpectErrMsg = \"unrecognized\"\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif expectErr {\n\t\t\t\t\trequire.Error(t, err)\n\t\t\t\t\trequire.ErrorContains(t, err, expectErrMsg)\n\t\t\t\t} else {\n\t\t\t\t\trequire.NoError(t, err)\n\t\t\t\t}\n\t\t\t\tif test.outString[mode] != \"\" {\n\t\t\t\t\trequire.Contains(t, stdout.String(), test.outString[mode])\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "otelcol/command_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\nfunc TestNewCommandVersion(t *testing.T) {\n\tcmd := NewCommand(CollectorSettings{BuildInfo: component.BuildInfo{Version: \"test_version\"}})\n\tassert.Equal(t, \"test_version\", cmd.Version)\n}\n\nfunc TestNewCommandNoConfigURI(t *testing.T) {\n\tcmd := NewCommand(CollectorSettings{Factories: nopFactories})\n\trequire.Error(t, cmd.Execute())\n}\n\n// This test emulates usage of Collector in Jaeger all-in-one, which\n// allows running the binary with no explicit configuration.\nfunc TestNewCommandProgrammaticallyPassedConfig(t *testing.T) {\n\tcmd := NewCommand(CollectorSettings{Factories: nopFactories, ConfigProviderSettings: ConfigProviderSettings{\n\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\tProviderFactories: []confmap.ProviderFactory{confmap.NewProviderFactory(newFailureProvider)},\n\t\t\tDefaultScheme:     \"file\",\n\t\t},\n\t}})\n\totelRunE := cmd.RunE\n\tcmd.RunE = func(c *cobra.Command, args []string) error {\n\t\tconfigFlag := c.Flag(\"config\")\n\t\tcfg := `\nservice:\n  extensions: [invalid_component_name]\nreceivers:\n  invalid_component_name:\n`\n\t\trequire.NoError(t, configFlag.Value.Set(\"yaml:\"+cfg))\n\t\treturn otelRunE(cmd, args)\n\t}\n\t// verify that cmd.Execute was run with the implicitly provided config.\n\trequire.ErrorContains(t, cmd.Execute(), \"invalid_component_name\")\n}\n\nfunc TestAddFlagToSettings(t *testing.T) {\n\tfilePath := filepath.Join(\"testdata\", \"otelcol-invalid.yaml\")\n\tfileProvider := newFakeProvider(\"file\", func(_ context.Context, _ string, _ confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\t\treturn confmap.NewRetrieved(newConfFromFile(t, filePath))\n\t})\n\tset := CollectorSettings{\n\t\tConfigProviderSettings: ConfigProviderSettings{\n\t\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\t\tURIs:              []string{filePath},\n\t\t\t\tProviderFactories: []confmap.ProviderFactory{fileProvider},\n\t\t\t},\n\t\t},\n\t}\n\tflgs := flags(featuregate.NewRegistry())\n\terr := flgs.Parse([]string{\"--config=otelcol-nop.yaml\"})\n\trequire.NoError(t, err)\n\n\terr = updateSettingsUsingFlags(&set, flgs)\n\trequire.NoError(t, err)\n\trequire.Len(t, set.ConfigProviderSettings.ResolverSettings.URIs, 1)\n}\n\nfunc TestInvalidCollectorSettings(t *testing.T) {\n\tset := CollectorSettings{\n\t\tConfigProviderSettings: ConfigProviderSettings{\n\t\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\t\tURIs: []string{\"--config=otelcol-nop.yaml\"},\n\t\t\t},\n\t\t},\n\t}\n\n\tcmd := NewCommand(set)\n\trequire.Error(t, cmd.Execute())\n}\n\nfunc TestNewCommandInvalidComponent(t *testing.T) {\n\tfilePath := filepath.Join(\"testdata\", \"otelcol-invalid.yaml\")\n\tfileProvider := newFakeProvider(\"file\", func(_ context.Context, _ string, _ confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\t\treturn confmap.NewRetrieved(newConfFromFile(t, filePath))\n\t})\n\tset := ConfigProviderSettings{\n\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\tURIs:              []string{filePath},\n\t\t\tProviderFactories: []confmap.ProviderFactory{fileProvider},\n\t\t},\n\t}\n\n\tcmd := NewCommand(CollectorSettings{Factories: nopFactories, ConfigProviderSettings: set})\n\trequire.Error(t, cmd.Execute())\n}\n\nfunc TestNoProvidersReturnsError(t *testing.T) {\n\tset := CollectorSettings{\n\t\tConfigProviderSettings: ConfigProviderSettings{\n\t\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\t\tURIs: []string{filepath.Join(\"testdata\", \"otelcol-invalid.yaml\")},\n\t\t\t},\n\t\t},\n\t}\n\tflgs := flags(featuregate.NewRegistry())\n\terr := flgs.Parse([]string{\"--config=otelcol-nop.yaml\"})\n\trequire.NoError(t, err)\n\n\terr = updateSettingsUsingFlags(&set, flgs)\n\trequire.ErrorContains(t, err, \"at least one Provider must be supplied\")\n}\n\nfunc Test_UseUnifiedEnvVarExpansionRules(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    string\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"default scheme set\",\n\t\t\tinput:    \"file\",\n\t\t\texpected: \"file\",\n\t\t},\n\t\t{\n\t\t\tname:     \"default scheme not set\",\n\t\t\tinput:    \"\",\n\t\t\texpected: \"env\",\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tfileProvider := newFakeProvider(\"file\", func(_ context.Context, _ string, _ confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\t\t\t\treturn &confmap.Retrieved{}, nil\n\t\t\t})\n\t\t\tset := CollectorSettings{\n\t\t\t\tConfigProviderSettings: ConfigProviderSettings{\n\t\t\t\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\t\t\t\tProviderFactories: []confmap.ProviderFactory{fileProvider},\n\t\t\t\t\t\tDefaultScheme:     tt.input,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}\n\t\t\tflgs := flags(featuregate.NewRegistry())\n\t\t\terr := flgs.Parse([]string{\"--config=otelcol-nop.yaml\"})\n\t\t\trequire.NoError(t, err)\n\n\t\t\terr = updateSettingsUsingFlags(&set, flgs)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Equal(t, tt.expected, set.ConfigProviderSettings.ResolverSettings.DefaultScheme)\n\t\t})\n\t}\n}\n\nfunc TestNewFeatureGateCommand(t *testing.T) {\n\tt.Run(\"list all featuregates\", func(t *testing.T) {\n\t\tcmd := newFeatureGateCommand()\n\t\trequire.NotNil(t, cmd)\n\n\t\t// Capture stdout\n\t\toldStdout := os.Stdout\n\t\tr, w, _ := os.Pipe()\n\t\tos.Stdout = w\n\n\t\terr := cmd.RunE(cmd, []string{})\n\t\trequire.NoError(t, err)\n\n\t\tw.Close()\n\t\tout, _ := io.ReadAll(r)\n\t\tos.Stdout = oldStdout\n\n\t\toutput := string(out)\n\t\tassert.Contains(t, output, \"ID\")\n\t\tassert.Contains(t, output, \"Enabled\")\n\t\tassert.Contains(t, output, \"Stage\")\n\t\tassert.Contains(t, output, \"Description\")\n\t})\n\tt.Run(\"specific featuregate details\", func(t *testing.T) {\n\t\tcmd := newFeatureGateCommand()\n\n\t\t// Register a test feature gate in the global registry\n\t\tfeaturegate.GlobalRegistry().MustRegister(\"test.feature\", featuregate.StageBeta,\n\t\t\tfeaturegate.WithRegisterDescription(\"Test feature description\"))\n\n\t\t// Capture stdout\n\t\toldStdout := os.Stdout\n\t\tr, w, _ := os.Pipe()\n\t\tos.Stdout = w\n\n\t\terr := cmd.RunE(cmd, []string{\"test.feature\"})\n\t\trequire.NoError(t, err)\n\n\t\tw.Close()\n\t\tout, _ := io.ReadAll(r)\n\t\tos.Stdout = oldStdout\n\n\t\toutput := string(out)\n\t\tassert.Contains(t, output, \"Feature: test.feature\")\n\t\tassert.Contains(t, output, \"Description: Test feature description\")\n\t\tassert.Contains(t, output, \"Stage: Beta\")\n\t})\n\n\tt.Run(\"non-existent featuregate\", func(t *testing.T) {\n\t\tcmd := newFeatureGateCommand()\n\t\terr := cmd.RunE(cmd, []string{\"non.existent.feature\"})\n\t\trequire.Error(t, err)\n\t\tassert.Contains(t, err.Error(), \"feature \\\"non.existent.feature\\\" not found\")\n\t})\n\n\tt.Run(\"rejects multiple arguments\", func(t *testing.T) {\n\t\tcmd := newFeatureGateCommand()\n\t\tcmd.SetArgs([]string{\"gate1\", \"gate2\"})\n\t\terr := cmd.Execute()\n\t\trequire.Error(t, err)\n\t})\n}\n"
  },
  {
    "path": "otelcol/command_validate.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol // import \"go.opentelemetry.io/collector/otelcol\"\n\nimport (\n\t\"flag\"\n\n\t\"github.com/spf13/cobra\"\n)\n\n// newValidateSubCommand constructs a new validate sub command using the given CollectorSettings.\nfunc newValidateSubCommand(set CollectorSettings, flagSet *flag.FlagSet) *cobra.Command {\n\tvalidateCmd := &cobra.Command{\n\t\tUse:   \"validate\",\n\t\tShort: \"Validates the config without running the collector\",\n\t\tArgs:  cobra.ExactArgs(0),\n\t\tRunE: func(cmd *cobra.Command, _ []string) error {\n\t\t\tif err := updateSettingsUsingFlags(&set, flagSet); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tcol, err := NewCollector(set)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\treturn col.DryRun(cmd.Context())\n\t\t},\n\t}\n\tvalidateCmd.Flags().AddGoFlagSet(flagSet)\n\treturn validateCmd\n}\n"
  },
  {
    "path": "otelcol/command_validate_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol\n\nimport (\n\t\"context\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\nfunc TestValidateSubCommandNoConfig(t *testing.T) {\n\tcmd := newValidateSubCommand(CollectorSettings{Factories: nopFactories}, flags(featuregate.GlobalRegistry()))\n\terr := cmd.Execute()\n\trequire.ErrorContains(t, err, \"at least one config flag must be provided\")\n}\n\nfunc TestValidateSubCommandInvalidComponents(t *testing.T) {\n\tfilePath := filepath.Join(\"testdata\", \"otelcol-invalid-components.yaml\")\n\tfileProvider := newFakeProvider(\"file\", func(_ context.Context, _ string, _ confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\t\treturn confmap.NewRetrieved(newConfFromFile(t, filePath))\n\t})\n\tcmd := newValidateSubCommand(CollectorSettings{Factories: nopFactories, ConfigProviderSettings: ConfigProviderSettings{\n\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\tURIs:              []string{filePath},\n\t\t\tProviderFactories: []confmap.ProviderFactory{fileProvider},\n\t\t\tDefaultScheme:     \"file\",\n\t\t},\n\t}}, flags(featuregate.GlobalRegistry()))\n\terr := cmd.Execute()\n\trequire.ErrorContains(t, err, \"unknown type: \\\"nosuchprocessor\\\"\")\n}\n"
  },
  {
    "path": "otelcol/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol // import \"go.opentelemetry.io/collector/otelcol\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/service\"\n\t\"go.opentelemetry.io/collector/service/pipelines\"\n)\n\nvar (\n\terrMissingExporters       = errors.New(\"no exporter configuration specified in config\")\n\terrMissingReceivers       = errors.New(\"no receiver configuration specified in config\")\n\terrEmptyConfigurationFile = errors.New(\"empty configuration file\")\n)\n\n// Config defines the configuration for the various elements of collector or agent.\ntype Config struct {\n\t// Receivers is a map of ComponentID to Receivers.\n\tReceivers map[component.ID]component.Config `mapstructure:\"receivers\"`\n\n\t// Exporters is a map of ComponentID to Exporters.\n\tExporters map[component.ID]component.Config `mapstructure:\"exporters\"`\n\n\t// Processors is a map of ComponentID to Processors.\n\tProcessors map[component.ID]component.Config `mapstructure:\"processors\"`\n\n\t// Connectors is a map of ComponentID to connectors.\n\tConnectors map[component.ID]component.Config `mapstructure:\"connectors\"`\n\n\t// Extensions is a map of ComponentID to extensions.\n\tExtensions map[component.ID]component.Config `mapstructure:\"extensions\"`\n\n\tService service.Config `mapstructure:\"service\"`\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// Validate returns an error if the config is invalid.\n//\n// This function performs basic validation of configuration. There may be more subtle\n// invalid cases that we currently don't check for but which we may want to add in\n// the future (e.g. disallowing receiving and exporting on the same endpoint).\nfunc (cfg *Config) Validate() error {\n\t// There must be at least one property set in the configuration\tfile.\n\tif len(cfg.Receivers) == 0 && len(cfg.Exporters) == 0 && len(cfg.Processors) == 0 && len(cfg.Connectors) == 0 && len(cfg.Extensions) == 0 {\n\t\treturn errEmptyConfigurationFile\n\t}\n\n\t// Currently, there is no default receiver enabled.\n\t// The configuration must specify at least one receiver to be valid.\n\tif !pipelines.AllowNoPipelines.IsEnabled() && len(cfg.Receivers) == 0 {\n\t\treturn errMissingReceivers\n\t}\n\n\t// Currently, there is no default exporter enabled.\n\t// The configuration must specify at least one exporter to be valid.\n\tif !pipelines.AllowNoPipelines.IsEnabled() && len(cfg.Exporters) == 0 {\n\t\treturn errMissingExporters\n\t}\n\n\t// Validate the connector configuration.\n\tfor connID := range cfg.Connectors {\n\t\tif _, ok := cfg.Exporters[connID]; ok {\n\t\t\treturn fmt.Errorf(\"connectors::%s: ambiguous ID: Found both %q exporter and %q connector. \"+\n\t\t\t\t\"Change one of the components' IDs to eliminate ambiguity (e.g. rename %q connector to %q)\",\n\t\t\t\tconnID, connID, connID, connID, connID.String()+\"/connector\")\n\t\t}\n\t\tif _, ok := cfg.Receivers[connID]; ok {\n\t\t\treturn fmt.Errorf(\"connectors::%s: ambiguous ID: Found both %q receiver and %q connector. \"+\n\t\t\t\t\"Change one of the components' IDs to eliminate ambiguity (e.g. rename %q connector to %q)\",\n\t\t\t\tconnID, connID, connID, connID, connID.String()+\"/connector\")\n\t\t}\n\t}\n\n\t// Check that all enabled extensions in the service are configured.\n\tfor _, ref := range cfg.Service.Extensions {\n\t\t// Check that the name referenced in the Service extensions exists in the top-level extensions.\n\t\tif cfg.Extensions[ref] == nil {\n\t\t\treturn fmt.Errorf(\"service::extensions: references extension %q which is not configured\", ref)\n\t\t}\n\t}\n\n\t// Check that all pipelines reference only configured components.\n\tfor pipelineID, pipeline := range cfg.Service.Pipelines {\n\t\t// Validate pipeline receiver name references.\n\t\tfor _, ref := range pipeline.Receivers {\n\t\t\t// Check that the name referenced in the pipeline's receivers exists in the top-level receivers.\n\t\t\tif _, ok := cfg.Receivers[ref]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tif _, ok := cfg.Connectors[ref]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"service::pipelines::%s: references receiver %q which is not configured\", pipelineID.String(), ref)\n\t\t}\n\n\t\t// Validate pipeline processor name references.\n\t\tfor _, ref := range pipeline.Processors {\n\t\t\t// Check that the name referenced in the pipeline's processors exists in the top-level processors.\n\t\t\tif cfg.Processors[ref] == nil {\n\t\t\t\treturn fmt.Errorf(\"service::pipelines::%s: references processor %q which is not configured\", pipelineID.String(), ref)\n\t\t\t}\n\t\t}\n\n\t\t// Validate pipeline exporter name references.\n\t\tfor _, ref := range pipeline.Exporters {\n\t\t\t// Check that the name referenced in the pipeline's Exporters exists in the top-level Exporters.\n\t\t\tif _, ok := cfg.Exporters[ref]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tif _, ok := cfg.Connectors[ref]; ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"service::pipelines::%s: references exporter %q which is not configured\", pipelineID.String(), ref)\n\t\t}\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "otelcol/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/service\"\n\t\"go.opentelemetry.io/collector/service/pipelines\"\n)\n\nvar (\n\terrInvalidRecvConfig = errors.New(\"invalid receiver config\")\n\terrInvalidExpConfig  = errors.New(\"invalid exporter config\")\n\terrInvalidProcConfig = errors.New(\"invalid processor config\")\n\terrInvalidConnConfig = errors.New(\"invalid connector config\")\n\terrInvalidExtConfig  = errors.New(\"invalid extension config\")\n)\n\ntype errConfig struct {\n\tvalidateErr error\n}\n\nfunc (c *errConfig) Validate() error {\n\treturn c.validateErr\n}\n\nfunc TestConfigValidate(t *testing.T) {\n\ttestCases := []struct {\n\t\tname     string // test case name (also file name containing config yaml)\n\t\tcfgFn    func() *Config\n\t\texpected error\n\t}{\n\t\t{\n\t\t\tname:     \"valid\",\n\t\t\tcfgFn:    generateConfig,\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"valid-telemetry-config\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tcfg.Service.Telemetry = fakeTelemetryConfig{}\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"empty configuration file\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tcfg.Receivers = nil\n\t\t\t\tcfg.Connectors = nil\n\t\t\t\tcfg.Processors = nil\n\t\t\t\tcfg.Exporters = nil\n\t\t\t\tcfg.Extensions = nil\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errEmptyConfigurationFile,\n\t\t},\n\t\t{\n\t\t\tname: \"missing-exporters\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tcfg.Exporters = nil\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errMissingExporters,\n\t\t},\n\t\t{\n\t\t\tname: \"missing-receivers\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tcfg.Receivers = nil\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errMissingReceivers,\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-telemetry-config\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tcfg.Service.Telemetry = fakeTelemetryConfig{Invalid: true}\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errors.New(\"service::telemetry: invalid config\"),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-extension-reference\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tcfg.Service.Extensions = append(cfg.Service.Extensions, component.MustNewIDWithName(\"nop\", \"2\"))\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errors.New(`service::extensions: references extension \"nop/2\" which is not configured`),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-receiver-reference\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tpipe := cfg.Service.Pipelines[pipeline.NewID(pipeline.SignalTraces)]\n\t\t\t\tpipe.Receivers = append(pipe.Receivers, component.MustNewIDWithName(\"nop\", \"2\"))\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errors.New(`service::pipelines::traces: references receiver \"nop/2\" which is not configured`),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-processor-reference\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tpipe := cfg.Service.Pipelines[pipeline.NewID(pipeline.SignalTraces)]\n\t\t\t\tpipe.Processors = append(pipe.Processors, component.MustNewIDWithName(\"nop\", \"2\"))\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errors.New(`service::pipelines::traces: references processor \"nop/2\" which is not configured`),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-exporter-reference\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tpipe := cfg.Service.Pipelines[pipeline.NewID(pipeline.SignalTraces)]\n\t\t\t\tpipe.Exporters = append(pipe.Exporters, component.MustNewIDWithName(\"nop\", \"2\"))\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errors.New(`service::pipelines::traces: references exporter \"nop/2\" which is not configured`),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-receiver-config\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tcfg.Receivers[component.MustNewID(\"nop\")] = &errConfig{\n\t\t\t\t\tvalidateErr: errInvalidRecvConfig,\n\t\t\t\t}\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: fmt.Errorf(`receivers::nop: %w`, errInvalidRecvConfig),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-exporter-config\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tcfg.Exporters[component.MustNewID(\"nop\")] = &errConfig{\n\t\t\t\t\tvalidateErr: errInvalidExpConfig,\n\t\t\t\t}\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: fmt.Errorf(`exporters::nop: %w`, errInvalidExpConfig),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-processor-config\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tcfg.Processors[component.MustNewID(\"nop\")] = &errConfig{\n\t\t\t\t\tvalidateErr: errInvalidProcConfig,\n\t\t\t\t}\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: fmt.Errorf(`processors::nop: %w`, errInvalidProcConfig),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-extension-config\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tcfg.Extensions[component.MustNewID(\"nop\")] = &errConfig{\n\t\t\t\t\tvalidateErr: errInvalidExtConfig,\n\t\t\t\t}\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: fmt.Errorf(`extensions::nop: %w`, errInvalidExtConfig),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-connector-config\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tcfg.Connectors[component.MustNewIDWithName(\"nop\", \"conn\")] = &errConfig{\n\t\t\t\t\tvalidateErr: errInvalidConnConfig,\n\t\t\t\t}\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: fmt.Errorf(`connectors::nop/conn: %w`, errInvalidConnConfig),\n\t\t},\n\t\t{\n\t\t\tname: \"ambiguous-connector-name-as-receiver\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tcfg.Receivers[component.MustNewID(\"nop2\")] = &errConfig{}\n\t\t\t\tcfg.Connectors[component.MustNewID(\"nop2\")] = &errConfig{}\n\t\t\t\tpipe := cfg.Service.Pipelines[pipeline.NewID(pipeline.SignalTraces)]\n\t\t\t\tpipe.Receivers = append(pipe.Receivers, component.MustNewIDWithName(\"nop\", \"2\"))\n\t\t\t\tpipe.Exporters = append(pipe.Exporters, component.MustNewIDWithName(\"nop\", \"2\"))\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errors.New(`connectors::nop2: ambiguous ID: Found both \"nop2\" receiver and \"nop2\" connector. Change one of the components' IDs to eliminate ambiguity (e.g. rename \"nop2\" connector to \"nop2/connector\")`),\n\t\t},\n\t\t{\n\t\t\tname: \"ambiguous-connector-name-as-exporter\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tcfg.Exporters[component.MustNewID(\"nop2\")] = &errConfig{}\n\t\t\t\tcfg.Connectors[component.MustNewID(\"nop2\")] = &errConfig{}\n\t\t\t\tpipe := cfg.Service.Pipelines[pipeline.NewID(pipeline.SignalTraces)]\n\t\t\t\tpipe.Receivers = append(pipe.Receivers, component.MustNewIDWithName(\"nop\", \"2\"))\n\t\t\t\tpipe.Exporters = append(pipe.Exporters, component.MustNewIDWithName(\"nop\", \"2\"))\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errors.New(`connectors::nop2: ambiguous ID: Found both \"nop2\" exporter and \"nop2\" connector. Change one of the components' IDs to eliminate ambiguity (e.g. rename \"nop2\" connector to \"nop2/connector\")`),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-connector-reference-as-receiver\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tpipe := cfg.Service.Pipelines[pipeline.NewID(pipeline.SignalTraces)]\n\t\t\t\tpipe.Receivers = append(pipe.Receivers, component.MustNewIDWithName(\"nop\", \"conn2\"))\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errors.New(`service::pipelines::traces: references receiver \"nop/conn2\" which is not configured`),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-connector-reference-as-receiver\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tpipe := cfg.Service.Pipelines[pipeline.NewID(pipeline.SignalTraces)]\n\t\t\t\tpipe.Exporters = append(pipe.Exporters, component.MustNewIDWithName(\"nop\", \"conn2\"))\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errors.New(`service::pipelines::traces: references exporter \"nop/conn2\" which is not configured`),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-service-config\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tcfg.Service.Pipelines = nil\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: fmt.Errorf(`service::pipelines: %w`, errors.New(`service must have at least one pipeline`)),\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := tt.cfgFn()\n\t\t\terr := xconfmap.Validate(cfg)\n\t\t\tif tt.expected != nil {\n\t\t\t\trequire.EqualError(t, err, tt.expected.Error())\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestNoPipelinesFeatureGate(t *testing.T) {\n\tcfg := generateConfig()\n\tcfg.Receivers = nil\n\tcfg.Exporters = nil\n\tcfg.Service.Pipelines = pipelines.Config{}\n\n\trequire.Error(t, xconfmap.Validate(cfg))\n\n\tgate := pipelines.AllowNoPipelines\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(gate.ID(), true))\n\tdefer func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(gate.ID(), false))\n\t}()\n\n\trequire.NoError(t, xconfmap.Validate(cfg))\n}\n\nfunc generateConfig() *Config {\n\treturn &Config{\n\t\tReceivers: map[component.ID]component.Config{\n\t\t\tcomponent.MustNewID(\"nop\"): &errConfig{},\n\t\t},\n\t\tExporters: map[component.ID]component.Config{\n\t\t\tcomponent.MustNewID(\"nop\"): &errConfig{},\n\t\t},\n\t\tProcessors: map[component.ID]component.Config{\n\t\t\tcomponent.MustNewID(\"nop\"): &errConfig{},\n\t\t},\n\t\tConnectors: map[component.ID]component.Config{\n\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn\"): &errConfig{},\n\t\t},\n\t\tExtensions: map[component.ID]component.Config{\n\t\t\tcomponent.MustNewID(\"nop\"): &errConfig{},\n\t\t},\n\t\tService: service.Config{\n\t\t\tTelemetry:  fakeTelemetryConfig{},\n\t\t\tExtensions: []component.ID{component.MustNewID(\"nop\")},\n\t\t\tPipelines: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\ntype fakeTelemetryConfig struct {\n\tInvalid bool `mapstructure:\"invalid\"`\n}\n\nfunc (cfg fakeTelemetryConfig) Validate() error {\n\tif cfg.Invalid {\n\t\treturn errors.New(\"invalid config\")\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "otelcol/configprovider.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol // import \"go.opentelemetry.io/collector/otelcol\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\n// ConfigProvider provides the service configuration.\n//\n// The typical usage is the following:\n//\n//\tcfgProvider.Get(...)\n//\tcfgProvider.Watch() // wait for an event.\n//\tcfgProvider.Get(...)\n//\tcfgProvider.Watch() // wait for an event.\n//\t// repeat Get/Watch cycle until it is time to shut down the Collector process.\n//\tcfgProvider.Shutdown()\ntype ConfigProvider struct {\n\tmapResolver *confmap.Resolver\n}\n\n// ConfigProviderSettings are the settings to configure the behavior of the ConfigProvider.\ntype ConfigProviderSettings struct {\n\t// ResolverSettings are the settings to configure the behavior of the confmap.Resolver.\n\tResolverSettings confmap.ResolverSettings\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// NewConfigProvider returns a new ConfigProvider that provides the service configuration:\n// * Initially it resolves the \"configuration map\":\n//   - Retrieve the confmap.Conf by merging all retrieved maps from the given `locations` in order.\n//   - Then applies all the confmap.Converter in the given order.\n//\n// * Then unmarshalls the confmap.Conf into the service Config.\nfunc NewConfigProvider(set ConfigProviderSettings) (*ConfigProvider, error) {\n\tmr, err := confmap.NewResolver(set.ResolverSettings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &ConfigProvider{\n\t\tmapResolver: mr,\n\t}, nil\n}\n\n// Get returns the service configuration, or error otherwise.\n//\n// Should never be called concurrently with itself, Watch or Shutdown.\nfunc (cm *ConfigProvider) Get(ctx context.Context, factories Factories) (*Config, error) {\n\tconf, err := cm.mapResolver.Resolve(ctx)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot resolve the configuration: %w\", err)\n\t}\n\n\tvar cfg *configSettings\n\tif cfg, err = unmarshal(conf, factories); err != nil {\n\t\treturn nil, fmt.Errorf(\"cannot unmarshal the configuration: %w\", err)\n\t}\n\n\treturn &Config{\n\t\tReceivers:  cfg.Receivers.Configs(),\n\t\tProcessors: cfg.Processors.Configs(),\n\t\tExporters:  cfg.Exporters.Configs(),\n\t\tConnectors: cfg.Connectors.Configs(),\n\t\tExtensions: cfg.Extensions.Configs(),\n\t\tService:    cfg.Service,\n\t}, nil\n}\n\n// Watch blocks until any configuration change was detected or an unrecoverable error\n// happened during monitoring the configuration changes.\n//\n// Error is nil if the configuration is changed and needs to be re-fetched. Any non-nil\n// error indicates that there was a problem with watching the config changes.\n//\n// Should never be called concurrently with itself or Get.\nfunc (cm *ConfigProvider) Watch() <-chan error {\n\treturn cm.mapResolver.Watch()\n}\n\n// Shutdown signals that the provider is no longer in use and the that should close\n// and release any resources that it may have created.\n//\n// This function must terminate the Watch channel.\n//\n// Should never be called concurrently with itself or Get.\nfunc (cm *ConfigProvider) Shutdown(ctx context.Context) error {\n\treturn cm.mapResolver.Shutdown(ctx)\n}\n"
  },
  {
    "path": "otelcol/configprovider_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol\n\nimport (\n\t\"context\"\n\t\"os\"\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.yaml.in/yaml/v3\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/connector/connectortest\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/extension/extensiontest\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n\t\"go.opentelemetry.io/collector/service\"\n\t\"go.opentelemetry.io/collector/service/pipelines\"\n)\n\nfunc TestConfigProvider(t *testing.T) {\n\tnopComponentID := component.MustNewID(\"nop\")\n\tnopConComponentID := component.MustNewIDWithName(\"nop\", \"con\")\n\n\ttests := map[string]struct {\n\t\tfilename       string\n\t\tfactories      func() (Factories, error)\n\t\texpectedConfig *Config\n\t}{\n\t\t\"nop\": {\n\t\t\tfilename:  \"otelcol-nop.yaml\",\n\t\t\tfactories: nopFactories,\n\t\t\texpectedConfig: &Config{\n\t\t\t\tConnectors: map[component.ID]component.Config{\n\t\t\t\t\tnopConComponentID: connectortest.NewNopFactory().CreateDefaultConfig(),\n\t\t\t\t},\n\t\t\t\tExporters: map[component.ID]component.Config{\n\t\t\t\t\tnopComponentID: exportertest.NewNopFactory().CreateDefaultConfig(),\n\t\t\t\t},\n\t\t\t\tExtensions: map[component.ID]component.Config{\n\t\t\t\t\tnopComponentID: extensiontest.NewNopFactory().CreateDefaultConfig(),\n\t\t\t\t},\n\t\t\t\tProcessors: map[component.ID]component.Config{\n\t\t\t\t\tnopComponentID: processortest.NewNopFactory().CreateDefaultConfig(),\n\t\t\t\t},\n\t\t\t\tReceivers: map[component.ID]component.Config{\n\t\t\t\t\tnopComponentID: receivertest.NewNopFactory().CreateDefaultConfig(),\n\t\t\t\t},\n\t\t\t\tService: service.Config{\n\t\t\t\t\tTelemetry:  fakeTelemetryConfig{},\n\t\t\t\t\tExtensions: []component.ID{nopComponentID},\n\t\t\t\t\tPipelines: map[pipeline.ID]*pipelines.PipelineConfig{\n\t\t\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\t\t\tReceivers:  []component.ID{nopComponentID},\n\t\t\t\t\t\t\tProcessors: []component.ID{nopComponentID},\n\t\t\t\t\t\t\tExporters:  []component.ID{nopComponentID, nopConComponentID},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\t\t\tReceivers:  []component.ID{nopComponentID},\n\t\t\t\t\t\t\tProcessors: []component.ID{nopComponentID},\n\t\t\t\t\t\t\tExporters:  []component.ID{nopComponentID},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\t\t\tReceivers:  []component.ID{nopComponentID, nopConComponentID},\n\t\t\t\t\t\t\tProcessors: []component.ID{nopComponentID},\n\t\t\t\t\t\t\tExporters:  []component.ID{nopComponentID},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor name, test := range tests {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tyamlBytes, err := os.ReadFile(filepath.Join(\"testdata\", test.filename))\n\t\t\trequire.NoError(t, err)\n\n\t\t\tyamlProvider := newFakeProvider(\"yaml\", func(context.Context, string, confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\t\t\t\tvar rawConf any\n\t\t\t\tif yamlErr := yaml.Unmarshal(yamlBytes, &rawConf); yamlErr != nil {\n\t\t\t\t\treturn nil, yamlErr\n\t\t\t\t}\n\t\t\t\treturn confmap.NewRetrieved(rawConf)\n\t\t\t})\n\n\t\t\tset := ConfigProviderSettings{\n\t\t\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\t\t\tURIs:              []string{\"yaml:\" + string(yamlBytes)},\n\t\t\t\t\tProviderFactories: []confmap.ProviderFactory{yamlProvider},\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tcp, err := NewConfigProvider(set)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tfactories, err := test.factories()\n\t\t\trequire.NoError(t, err)\n\n\t\t\tcfg, err := cp.Get(context.Background(), factories)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tassert.Equal(t, test.expectedConfig, cfg)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "otelcol/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# otelcol\n\n## Feature Gates\n\nThis component has the following feature gates:\n\n| Feature Gate | Stage | Description | From Version | To Version | Reference |\n| ------------ | ----- | ----------- | ------------ | ---------- | --------- |\n| `otelcol.printInitialConfig` | beta | if set to true, enable the print-config command | v0.120.0 | N/A | [Link](https://github.com/open-telemetry/opentelemetry-collector/pull/11775) |\n\nFor more information about feature gates, see the [Feature Gates](https://github.com/open-telemetry/opentelemetry-collector/blob/main/featuregate/README.md) documentation.\n"
  },
  {
    "path": "otelcol/factories.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol // import \"go.opentelemetry.io/collector/otelcol\"\n\nimport (\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n)\n\n// Factories struct holds in a single type all component factories that\n// can be handled by the Config.\ntype Factories struct {\n\t// Receivers maps receiver type names in the config to the respective factory.\n\tReceivers map[component.Type]receiver.Factory\n\n\t// Processors maps processor type names in the config to the respective factory.\n\tProcessors map[component.Type]processor.Factory\n\n\t// Exporters maps exporter type names in the config to the respective factory.\n\tExporters map[component.Type]exporter.Factory\n\n\t// Extensions maps extension type names in the config to the respective factory.\n\tExtensions map[component.Type]extension.Factory\n\n\t// Connectors maps connector type names in the config to the respective factory.\n\tConnectors map[component.Type]connector.Factory\n\n\t// Telemetry is the factory to create the telemetry providers for the service.\n\tTelemetry telemetry.Factory\n\n\t// ReceiverModules maps receiver types to their respective go modules.\n\tReceiverModules map[component.Type]string\n\n\t// ProcessorModules maps processor types to their respective go modules.\n\tProcessorModules map[component.Type]string\n\n\t// ExporterModules maps exporter types to their respective go modules.\n\tExporterModules map[component.Type]string\n\n\t// ExtensionModules maps extension types to their respective go modules.\n\tExtensionModules map[component.Type]string\n\n\t// ConnectorModules maps connector types to their respective go modules.\n\tConnectorModules map[component.Type]string\n}\n\n// MakeFactoryMap takes a list of factories and returns a map with Factory type as keys.\n// It returns a non-nil error when there are factories with duplicate type.\n// If a factory has a deprecated alias, the map will also contain an entry for the alias.\nfunc MakeFactoryMap[T component.Factory](factories ...T) (map[component.Type]T, error) {\n\tfMap := make(map[component.Type]T, len(factories))\n\tfor _, f := range factories {\n\t\tif _, ok := fMap[f.Type()]; ok {\n\t\t\treturn fMap, fmt.Errorf(\"duplicate component factory %q\", f.Type())\n\t\t}\n\t\tfMap[f.Type()] = f\n\n\t\t// If factory has a deprecated alias, add it to the map as well\n\t\tif aliasHolder, ok := any(f).(componentalias.TypeAliasHolder); ok {\n\t\t\talias := aliasHolder.DeprecatedAlias()\n\t\t\tif alias.String() != \"\" {\n\t\t\t\tif _, exists := fMap[alias]; exists {\n\t\t\t\t\treturn fMap, fmt.Errorf(\"duplicate component factory %q (alias of %q)\", alias, f.Type())\n\t\t\t\t}\n\t\t\t\tfMap[alias] = f\n\t\t\t}\n\t\t}\n\t}\n\treturn fMap, nil\n}\n"
  },
  {
    "path": "otelcol/factories_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/connectortest\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensiontest\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n)\n\nfunc nopFactories() (Factories, error) {\n\tvar factories Factories\n\tvar err error\n\n\tif factories.Connectors, err = MakeFactoryMap(connectortest.NewNopFactory()); err != nil {\n\t\treturn Factories{}, err\n\t}\n\tfactories.ConnectorModules = make(map[component.Type]string, len(factories.Connectors))\n\tfor _, con := range factories.Connectors {\n\t\tfactories.ConnectorModules[con.Type()] = \"go.opentelemetry.io/collector/connector/connectortest v1.2.3\"\n\t}\n\n\tif factories.Extensions, err = MakeFactoryMap(extensiontest.NewNopFactory()); err != nil {\n\t\treturn Factories{}, err\n\t}\n\tfactories.ExtensionModules = make(map[component.Type]string, len(factories.Extensions))\n\tfor _, ext := range factories.Extensions {\n\t\tfactories.ExtensionModules[ext.Type()] = \"go.opentelemetry.io/collector/extension/extensiontest v1.2.3\"\n\t}\n\n\tif factories.Receivers, err = MakeFactoryMap(receivertest.NewNopFactory()); err != nil {\n\t\treturn Factories{}, err\n\t}\n\tfactories.ReceiverModules = make(map[component.Type]string, len(factories.Receivers))\n\tfor _, rec := range factories.Receivers {\n\t\tfactories.ReceiverModules[rec.Type()] = \"go.opentelemetry.io/collector/receiver/receivertest v1.2.3\"\n\t}\n\n\tif factories.Exporters, err = MakeFactoryMap(exportertest.NewNopFactory()); err != nil {\n\t\treturn Factories{}, err\n\t}\n\tfactories.ExporterModules = make(map[component.Type]string, len(factories.Exporters))\n\tfor _, exp := range factories.Exporters {\n\t\tfactories.ExporterModules[exp.Type()] = \"go.opentelemetry.io/collector/exporter/exportertest v1.2.3\"\n\t}\n\n\tif factories.Processors, err = MakeFactoryMap(processortest.NewNopFactory()); err != nil {\n\t\treturn Factories{}, err\n\t}\n\tfactories.ProcessorModules = make(map[component.Type]string, len(factories.Processors))\n\tfor _, proc := range factories.Processors {\n\t\tfactories.ProcessorModules[proc.Type()] = \"go.opentelemetry.io/collector/processor/processortest v1.2.3\"\n\t}\n\n\tfactories.Telemetry = telemetry.NewFactory(func() component.Config {\n\t\treturn fakeTelemetryConfig{}\n\t})\n\n\treturn factories, err\n}\n\nfunc TestMakeFactoryMap(t *testing.T) {\n\ttype testCase struct {\n\t\tname string\n\t\tin   []component.Factory\n\t\tout  map[component.Type]component.Factory\n\t}\n\n\tfRec := receiver.NewFactory(component.MustNewType(\"rec\"), nil)\n\tfRec2 := receiver.NewFactory(component.MustNewType(\"rec\"), nil)\n\tfRec3 := xreceiver.NewFactory(component.MustNewType(\"new_rec\"), nil, xreceiver.WithDeprecatedTypeAlias(component.MustNewType(\"rec\")))\n\tfPro := processor.NewFactory(component.MustNewType(\"pro\"), nil)\n\tfCon := connector.NewFactory(component.MustNewType(\"con\"), nil)\n\tfExp := exporter.NewFactory(component.MustNewType(\"exp\"), nil)\n\tfExt := extension.NewFactory(component.MustNewType(\"ext\"), nil, nil, component.StabilityLevelUndefined)\n\ttestCases := []testCase{\n\t\t{\n\t\t\tname: \"different names\",\n\t\t\tin:   []component.Factory{fRec, fPro, fCon, fExp, fExt},\n\t\t\tout: map[component.Type]component.Factory{\n\t\t\t\tfRec.Type(): fRec,\n\t\t\t\tfPro.Type(): fPro,\n\t\t\t\tfCon.Type(): fCon,\n\t\t\t\tfExp.Type(): fExp,\n\t\t\t\tfExt.Type(): fExt,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"same name\",\n\t\t\tin:   []component.Factory{fRec, fPro, fCon, fExp, fExt, fRec2},\n\t\t},\n\t\t{\n\t\t\tname: \"with deprecated alias\",\n\t\t\tin:   []component.Factory{fRec3},\n\t\t\tout: map[component.Type]component.Factory{\n\t\t\t\tfRec3.Type():                 fRec3,\n\t\t\t\tcomponent.MustNewType(\"rec\"): fRec3,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"conflicting alias name\",\n\t\t\tin:   []component.Factory{fRec, fRec3},\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tout, err := MakeFactoryMap(tt.in...)\n\t\t\tif tt.out == nil {\n\t\t\t\tassert.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tt.out, out)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "otelcol/flags.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol // import \"go.opentelemetry.io/collector/otelcol\"\n\nimport (\n\t\"errors\"\n\t\"flag\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\nconst (\n\tconfigFlag = \"config\"\n)\n\ntype configFlagValue struct {\n\tvalues []string\n\tsets   []string\n}\n\nfunc (s *configFlagValue) Set(val string) error {\n\ts.values = append(s.values, val)\n\treturn nil\n}\n\nfunc (s *configFlagValue) String() string {\n\treturn \"[\" + strings.Join(s.values, \", \") + \"]\"\n}\n\nfunc flags(reg *featuregate.Registry) *flag.FlagSet {\n\tflagSet := new(flag.FlagSet)\n\n\tcfgs := new(configFlagValue)\n\tflagSet.Var(cfgs, configFlag, \"Locations to the config file(s), note that only a\"+\n\t\t\" single location can be set per flag entry e.g. `--config=file:/path/to/first --config=file:path/to/second`.\")\n\n\tflagSet.Func(\"set\",\n\t\t\"Set arbitrary component config property. The component has to be defined in the config file and the flag\"+\n\t\t\t\" has a higher precedence. Array config properties are overridden and maps are joined. Example --set=processors.batch.timeout=2s\",\n\t\tfunc(s string) error {\n\t\t\tbefore, after, ok := strings.Cut(s, \"=\")\n\t\t\tif !ok {\n\t\t\t\t// No need for more context, see TestSetFlag/invalid_set.\n\t\t\t\treturn errors.New(\"missing equal sign\")\n\t\t\t}\n\t\t\tcfgs.sets = append(cfgs.sets, \"yaml:\"+strings.TrimSpace(strings.ReplaceAll(before, \".\", \"::\"))+\": \"+strings.TrimSpace(after))\n\t\t\treturn nil\n\t\t})\n\n\treg.RegisterFlags(flagSet)\n\treturn flagSet\n}\n\nfunc getConfigFlag(flagSet *flag.FlagSet) []string {\n\tcfv := flagSet.Lookup(configFlag).Value.(*configFlagValue)\n\treturn append(cfv.values, cfv.sets...)\n}\n"
  },
  {
    "path": "otelcol/flags_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\nfunc TestSetFlag(t *testing.T) {\n\ttests := []struct {\n\t\tname            string\n\t\targs            []string\n\t\texpectedConfigs []string\n\t\texpectedErr     string\n\t}{\n\t\t{\n\t\t\tname:            \"simple set\",\n\t\t\targs:            []string{\"--set=key=value\"},\n\t\t\texpectedConfigs: []string{\"yaml:key: value\"},\n\t\t},\n\t\t{\n\t\t\tname:            \"complex nested key\",\n\t\t\targs:            []string{\"--set=outer.inner=value\"},\n\t\t\texpectedConfigs: []string{\"yaml:outer::inner: value\"},\n\t\t},\n\t\t{\n\t\t\tname:            \"set array\",\n\t\t\targs:            []string{\"--set=key=[a, b, c]\"},\n\t\t\texpectedConfigs: []string{\"yaml:key: [a, b, c]\"},\n\t\t},\n\t\t{\n\t\t\tname:            \"set map\",\n\t\t\targs:            []string{\"--set=key={a: c}\"},\n\t\t\texpectedConfigs: []string{\"yaml:key: {a: c}\"},\n\t\t},\n\t\t{\n\t\t\tname:            \"set and config\",\n\t\t\targs:            []string{\"--set=key=value\", \"--config=file:testdata/otelcol-nop.yaml\"},\n\t\t\texpectedConfigs: []string{\"file:testdata/otelcol-nop.yaml\", \"yaml:key: value\"},\n\t\t},\n\t\t{\n\t\t\tname:            \"config and set\",\n\t\t\targs:            []string{\"--config=file:testdata/otelcol-nop.yaml\", \"--set=key=value\"},\n\t\t\texpectedConfigs: []string{\"file:testdata/otelcol-nop.yaml\", \"yaml:key: value\"},\n\t\t},\n\t\t{\n\t\t\tname:        \"invalid set\",\n\t\t\targs:        []string{\"--set=key:name\"},\n\t\t\texpectedErr: `invalid value \"key:name\" for flag -set: missing equal sign`,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tflgs := flags(featuregate.NewRegistry())\n\t\t\terr := flgs.Parse(tt.args)\n\t\t\tif tt.expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, tt.expectedErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, tt.expectedConfigs, getConfigFlag(flgs))\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "otelcol/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage otelcol\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "otelcol/go.mod",
    "content": "module go.opentelemetry.io/collector/otelcol\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/spf13/cobra v1.10.2\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componentstatus v0.148.0\n\tgo.opentelemetry.io/collector/config/configopaque v1.54.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/confmap/provider/fileprovider v1.54.0\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0\n\tgo.opentelemetry.io/collector/connector v0.148.0\n\tgo.opentelemetry.io/collector/connector/connectortest v0.148.0\n\tgo.opentelemetry.io/collector/connector/xconnector v0.148.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/exporter v1.54.0\n\tgo.opentelemetry.io/collector/exporter/exportertest v0.148.0\n\tgo.opentelemetry.io/collector/exporter/xexporter v0.148.0\n\tgo.opentelemetry.io/collector/extension v1.54.0\n\tgo.opentelemetry.io/collector/extension/extensiontest v0.148.0\n\tgo.opentelemetry.io/collector/featuregate v1.54.0\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/processor v1.54.0\n\tgo.opentelemetry.io/collector/processor/processortest v0.148.0\n\tgo.opentelemetry.io/collector/processor/xprocessor v0.148.0\n\tgo.opentelemetry.io/collector/receiver v1.54.0\n\tgo.opentelemetry.io/collector/receiver/receivertest v0.148.0\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0\n\tgo.opentelemetry.io/collector/service v0.148.0\n\tgo.opentelemetry.io/collector/service/telemetry/telemetrytest v0.148.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/multierr v1.11.0\n\tgo.uber.org/zap v1.27.1\n\tgo.yaml.in/yaml/v3 v3.0.4\n\tgolang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa\n\tgolang.org/x/sys v0.42.0\n\tgoogle.golang.org/grpc v1.79.3\n)\n\nrequire (\n\tgithub.com/beorn7/perks v1.0.1 // indirect\n\tgithub.com/cenkalti/backoff/v5 v5.0.3 // indirect\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect\n\tgithub.com/ebitengine/purego v0.10.0 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-ole/go-ole v1.2.6 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/inconshreveable/mousetrap v1.1.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect\n\tgithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect\n\tgithub.com/prometheus/client_golang v1.23.2 // indirect\n\tgithub.com/prometheus/client_model v0.6.2 // indirect\n\tgithub.com/prometheus/common v0.67.5 // indirect\n\tgithub.com/prometheus/otlptranslator v1.0.0 // indirect\n\tgithub.com/prometheus/procfs v0.20.1 // indirect\n\tgithub.com/shirou/gopsutil/v4 v4.26.2 // indirect\n\tgithub.com/spf13/pflag v1.0.10 // indirect\n\tgithub.com/tklauser/go-sysconf v0.3.16 // indirect\n\tgithub.com/tklauser/numcpus v0.11.0 // indirect\n\tgithub.com/yusufpapurcu/wmi v1.2.4 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/config/configtelemetry v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensioncapabilities v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/internal/fanoutconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/internal/telemetry v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/xpdata v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/service/hostcapabilities v0.148.0 // indirect\n\tgo.opentelemetry.io/contrib/otelconf v0.22.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/prometheus v0.64.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/log v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/log v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.opentelemetry.io/proto/otlp v1.10.0 // indirect\n\tgo.yaml.in/yaml/v2 v2.4.3 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgonum.org/v1/gonum v0.17.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/service => ../service\n\nreplace go.opentelemetry.io/collector/service/telemetry/telemetrytest => ../service/telemetry/telemetrytest\n\nreplace go.opentelemetry.io/collector/service/hostcapabilities => ../service/hostcapabilities\n\nreplace go.opentelemetry.io/collector/connector => ../connector\n\nreplace go.opentelemetry.io/collector/connector/connectortest => ../connector/connectortest\n\nreplace go.opentelemetry.io/collector/component => ../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../component/componenttest\n\nreplace go.opentelemetry.io/collector/pdata => ../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/extension/zpagesextension => ../extension/zpagesextension\n\nreplace go.opentelemetry.io/collector/extension => ../extension\n\nreplace go.opentelemetry.io/collector/exporter => ../exporter\n\nreplace go.opentelemetry.io/collector/confmap => ../confmap\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/config/configtelemetry => ../config/configtelemetry\n\nreplace go.opentelemetry.io/collector/processor => ../processor\n\nreplace go.opentelemetry.io/collector/consumer => ../consumer\n\nreplace go.opentelemetry.io/collector/receiver => ../receiver\n\nreplace go.opentelemetry.io/collector/featuregate => ../featuregate\n\nreplace go.opentelemetry.io/collector/config/configretry => ../config/configretry\n\nreplace go.opentelemetry.io/collector/config/confighttp => ../config/confighttp\n\nreplace go.opentelemetry.io/collector/config/configauth => ../config/configauth\n\nreplace go.opentelemetry.io/collector/extension/extensionauth => ../extension/extensionauth\n\nreplace go.opentelemetry.io/collector/config/configcompression => ../config/configcompression\n\nreplace go.opentelemetry.io/collector/config/configtls => ../config/configtls\n\nreplace go.opentelemetry.io/collector/config/configopaque => ../config/configopaque\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/client => ../client\n\nreplace go.opentelemetry.io/collector/component/componentstatus => ../component/componentstatus\n\nreplace go.opentelemetry.io/collector/extension/extensioncapabilities => ../extension/extensioncapabilities\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../receiver/receivertest\n\nreplace go.opentelemetry.io/collector/processor/xprocessor => ../processor/xprocessor\n\nreplace go.opentelemetry.io/collector/connector/xconnector => ../connector/xconnector\n\nreplace go.opentelemetry.io/collector/exporter/xexporter => ../exporter/xexporter\n\nreplace go.opentelemetry.io/collector/pipeline => ../pipeline\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/exporter/exportertest => ../exporter/exportertest\n\nreplace go.opentelemetry.io/collector/processor/processortest => ../processor/processortest\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/internal/fanoutconsumer => ../internal/fanoutconsumer\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../extension/extensiontest\n\nreplace go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest => ../extension/extensionauth/extensionauthtest\n\nreplace go.opentelemetry.io/collector/extension/xextension => ../extension/xextension\n\nreplace go.opentelemetry.io/collector/confmap/provider/fileprovider => ../confmap/provider/fileprovider\n\nreplace go.opentelemetry.io/collector/internal/telemetry => ../internal/telemetry\n\nreplace go.opentelemetry.io/collector/config/configmiddleware => ../config/configmiddleware\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ../extension/extensionmiddleware\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest => ../extension/extensionmiddleware/extensionmiddlewaretest\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../config/configoptional\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper => ../exporter/exporterhelper\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../internal/componentalias\n\nreplace go.opentelemetry.io/collector/config/confignet => ../config/confignet\n"
  },
  {
    "path": "otelcol/go.sum",
    "content": "github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=\ngithub.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=\ngithub.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=\ngithub.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=\ngithub.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=\ngithub.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=\ngithub.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f h1:RJ+BDPLSHQO7cSjKBqjPJSbi1qfk9WcsjQDtZiw3dZw=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f/go.mod h1:VHbbch/X4roIY22jL1s3qRbZhCiRIgUAF/PdSUcx2io=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=\ngithub.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=\ngithub.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=\ngithub.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=\ngithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=\ngithub.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=\ngithub.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=\ngithub.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=\ngithub.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=\ngithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3 h1:PwQumkgq4/acIiZhtifTV5OUqqiP82UAl0h87xj/l9k=\ngithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=\ngithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=\ngithub.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=\ngithub.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=\ngithub.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=\ngithub.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=\ngithub.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=\ngithub.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=\ngithub.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=\ngithub.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=\ngithub.com/prometheus/otlptranslator v1.0.0 h1:s0LJW/iN9dkIH+EnhiD3BlkkP5QVIUVEoIwkU+A6qos=\ngithub.com/prometheus/otlptranslator v1.0.0/go.mod h1:vRYWnXvI6aWGpsdY/mOT/cbeVRBlPWtBNDb7kGR3uKM=\ngithub.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc=\ngithub.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=\ngithub.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=\ngithub.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=\ngithub.com/shirou/gopsutil/v4 v4.26.2 h1:X8i6sicvUFih4BmYIGT1m2wwgw2VG9YgrDTi7cIRGUI=\ngithub.com/shirou/gopsutil/v4 v4.26.2/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=\ngithub.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=\ngithub.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=\ngithub.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=\ngithub.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngithub.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYICU0nA=\ngithub.com/tklauser/go-sysconf v0.3.16/go.mod h1:/qNL9xxDhc7tx3HSRsLWNnuzbVfh3e7gh/BmM179nYI=\ngithub.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9RXw=\ngithub.com/tklauser/numcpus v0.11.0/go.mod h1:z+LwcLq54uWZTX0u/bGobaV34u6V7KNlTZejzM6/3MQ=\ngithub.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=\ngithub.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=\ngo.opentelemetry.io/contrib/otelconf v0.22.0 h1:+kpcfczGOFM85zDZyqQCzWefhovegfn24D0WwmQz0n4=\ngo.opentelemetry.io/contrib/otelconf v0.22.0/go.mod h1:ojdbOukO+JRDJQmJY2PRIZEg0UYVzcOuZR59hp7xffc=\ngo.opentelemetry.io/contrib/zpages v0.67.0 h1:cIUwWSVDovuLEbDIKreptjdxMuIhGiqwq0uL8YNaq1c=\ngo.opentelemetry.io/contrib/zpages v0.67.0/go.mod h1:vK8fsYHgPYg4Z/XDbFSEvItSGZDbjWTvjBOu8+AiDhc=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0 h1:deI9UQMoGFgrg5iLPgzueqFPHevDl+28YKfSpPTI6rY=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0/go.mod h1:PFx9NgpNUKXdf7J4Q3agRxMs3Y07QhTCVipKmLsMKnU=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0 h1:icqq3Z34UrEFk2u+HMhTtRsvo7Ues+eiJVjaJt62njs=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0/go.mod h1:W2m8P+d5Wn5kipj4/xmbt9uMqezEKfBjzVJadfABSBE=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0 h1:MdKucPl/HbzckWWEisiNqMPhRrAOQX8r4jTuGr636gk=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0/go.mod h1:RolT8tWtfHcjajEH5wFIZ4Dgh5jpPdFXYV9pTAk/qjc=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0 h1:H7O6RlGOMTizyl3R08Kn5pdM06bnH8oscSj7o11tmLA=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0/go.mod h1:mBFWu/WOVDkWWsR7Tx7h6EpQB8wsv7P0Yrh0Pb7othc=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 h1:THuZiwpQZuHPul65w4WcwEnkX2QIuMT+UFoOrygtoJw=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0/go.mod h1:J2pvYM5NGHofZ2/Ru6zw/TNWnEQp5crgyDeSrYpXkAw=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0 h1:zWWrB1U6nqhS/k6zYB74CjRpuiitRtLLi68VcgmOEto=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0/go.mod h1:2qXPNBX1OVRC0IwOnfo1ljoid+RD0QK3443EaqVlsOU=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 h1:uLXP+3mghfMf7XmV4PkGfFhFKuNWoCvvx5wP/wOXo0o=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0/go.mod h1:v0Tj04armyT59mnURNUJf7RCKcKzq+lgJs6QSjHjaTc=\ngo.opentelemetry.io/otel/exporters/prometheus v0.64.0 h1:g0LRDXMX/G1SEZtK8zl8Chm4K6GBwRkjPKE36LxiTYs=\ngo.opentelemetry.io/otel/exporters/prometheus v0.64.0/go.mod h1:UrgcjnarfdlBDP3GjDIJWe6HTprwSazNjwsI+Ru6hro=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0 h1:KJVjPD3rcPb98rIs3HznyJlrfx9ge5oJvxxlGR+P/7s=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0/go.mod h1:K3kRa2ckmHWQaTWQdPRHc7qGXASuVuoEQXzrvlA98Ws=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0 h1:lSZHgNHfbmQTPfuTmWVkEu8J8qXaQwuV30pjCcAUvP8=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0/go.mod h1:so9ounLcuoRDu033MW/E0AD4hhUjVqswrMF5FoZlBcw=\ngo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0 h1:s/1iRkCKDfhlh1JF26knRneorus8aOwVIDhvYx9WoDw=\ngo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0/go.mod h1:UI3wi0FXg1Pofb8ZBiBLhtMzgoTm1TYkMvn71fAqDzs=\ngo.opentelemetry.io/otel/log v0.18.0 h1:XgeQIIBjZZrliksMEbcwMZefoOSMI1hdjiLEiiB0bAg=\ngo.opentelemetry.io/otel/log v0.18.0/go.mod h1:KEV1kad0NofR3ycsiDH4Yjcoj0+8206I6Ox2QYFSNgI=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/log v0.18.0 h1:n8OyZr7t7otkeTnPTbDNom6rW16TBYGtvyy2Gk6buQw=\ngo.opentelemetry.io/otel/sdk/log v0.18.0/go.mod h1:C0+wxkTwKpOCZLrlJ3pewPiiQwpzycPI/u6W0Z9fuYk=\ngo.opentelemetry.io/otel/sdk/log/logtest v0.18.0 h1:l3mYuPsuBx6UKE47BVcPrZoZ0q/KER57vbj2qkgDLXA=\ngo.opentelemetry.io/otel/sdk/log/logtest v0.18.0/go.mod h1:7cHtiVJpZebB3wybTa4NG+FUo5NPe3PROz1FqB0+qdw=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=\ngo.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=\ngo.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=\ngolang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=\ngolang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa h1:Zt3DZoOFFYkKhDT3v7Lm9FDMEV06GpzjG2jrqW+QTE0=\ngolang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=\ngolang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=\ngonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=\ngoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 h1:tu/dtnW1o3wfaxCOjSLn5IRX4YDcJrtlpzYkhHhGaC4=\ngoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171/go.mod h1:M5krXqk4GhBKvB596udGL3UyjL4I1+cTbK0orROM9ng=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "otelcol/internal/configunmarshaler/configs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configunmarshaler // import \"go.opentelemetry.io/collector/otelcol/internal/configunmarshaler\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"golang.org/x/exp/maps\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\ntype Configs[F component.Factory] struct {\n\tcfgs map[component.ID]component.Config\n\n\tfactories map[component.Type]F\n}\n\nfunc NewConfigs[F component.Factory](factories map[component.Type]F) *Configs[F] {\n\treturn &Configs[F]{factories: factories}\n}\n\nfunc (c *Configs[F]) Unmarshal(conf *confmap.Conf) error {\n\trawCfgs := make(map[component.ID]map[string]any)\n\tif err := conf.Unmarshal(&rawCfgs); err != nil {\n\t\treturn err\n\t}\n\n\t// Prepare resulting map.\n\tc.cfgs = make(map[component.ID]component.Config)\n\t// Iterate over raw configs and create a config for each.\n\tfor id := range rawCfgs {\n\t\t// Find factory based on component kind and type that we read from config source.\n\t\tfactory, ok := c.factories[id.Type()]\n\t\tif !ok {\n\t\t\treturn errorUnknownType(id, maps.Keys(c.factories))\n\t\t}\n\n\t\t// Get the configuration from the confmap.Conf to preserve internal representation.\n\t\tsub, err := conf.Sub(id.String())\n\t\tif err != nil {\n\t\t\treturn errorUnmarshalError(id, err)\n\t\t}\n\n\t\t// Create the default config for this component.\n\t\tcfg := factory.CreateDefaultConfig()\n\n\t\t// Now that the default config struct is created we can Unmarshal into it,\n\t\t// and it will apply user-defined config on top of the default.\n\t\tif err := sub.Unmarshal(&cfg); err != nil {\n\t\t\treturn errorUnmarshalError(id, err)\n\t\t}\n\n\t\tc.cfgs[id] = cfg\n\t}\n\n\treturn nil\n}\n\nfunc (c *Configs[F]) Configs() map[component.ID]component.Config {\n\treturn c.cfgs\n}\n\nfunc errorUnknownType(id component.ID, factories []component.Type) error {\n\tif id.Type().String() == \"logging\" {\n\t\treturn errors.New(\"the logging exporter has been deprecated, use the debug exporter instead\")\n\t}\n\treturn fmt.Errorf(\"unknown type: %q for id: %q (valid values: %v)\", id.Type(), id, factories)\n}\n\nfunc errorUnmarshalError(id component.ID, err error) error {\n\treturn fmt.Errorf(\"error reading configuration for %q: %w\", id, err)\n}\n"
  },
  {
    "path": "otelcol/internal/configunmarshaler/configs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configunmarshaler\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/connector/connectortest\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/extension/extensiontest\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\nvar nopType = component.MustNewType(\"nop\")\n\nvar testKinds = []struct {\n\tkind      string\n\tfactories map[component.Type]component.Factory\n}{\n\t{\n\t\tkind: \"receiver\",\n\t\tfactories: map[component.Type]component.Factory{\n\t\t\tnopType: receivertest.NewNopFactory(),\n\t\t},\n\t},\n\t{\n\t\tkind: \"processor\",\n\t\tfactories: map[component.Type]component.Factory{\n\t\t\tnopType: processortest.NewNopFactory(),\n\t\t},\n\t},\n\t{\n\t\tkind: \"exporter\",\n\t\tfactories: map[component.Type]component.Factory{\n\t\t\tnopType: exportertest.NewNopFactory(),\n\t\t},\n\t},\n\t{\n\t\tkind: \"connector\",\n\t\tfactories: map[component.Type]component.Factory{\n\t\t\tnopType: connectortest.NewNopFactory(),\n\t\t},\n\t},\n\t{\n\t\tkind: \"extension\",\n\t\tfactories: map[component.Type]component.Factory{\n\t\t\tnopType: extensiontest.NewNopFactory(),\n\t\t},\n\t},\n}\n\nfunc TestUnmarshal(t *testing.T) {\n\tfor _, tk := range testKinds {\n\t\tt.Run(tk.kind, func(t *testing.T) {\n\t\t\tcfgs := NewConfigs(tk.factories)\n\t\t\tconf := confmap.NewFromStringMap(map[string]any{\n\t\t\t\t\"nop\":              nil,\n\t\t\t\t\"nop/my\" + tk.kind: nil,\n\t\t\t})\n\t\t\trequire.NoError(t, cfgs.Unmarshal(conf))\n\n\t\t\tassert.Equal(t, map[component.ID]component.Config{\n\t\t\t\tcomponent.NewID(nopType):                       tk.factories[nopType].CreateDefaultConfig(),\n\t\t\t\tcomponent.NewIDWithName(nopType, \"my\"+tk.kind): tk.factories[nopType].CreateDefaultConfig(),\n\t\t\t}, cfgs.Configs())\n\t\t})\n\t}\n}\n\nfunc TestUnmarshalError(t *testing.T) {\n\tfor _, tk := range testKinds {\n\t\tt.Run(tk.kind, func(t *testing.T) {\n\t\t\ttestCases := []struct {\n\t\t\t\tname string\n\t\t\t\tconf *confmap.Conf\n\t\t\t\t// string that the error must contain\n\t\t\t\texpectedError string\n\t\t\t}{\n\t\t\t\t{\n\t\t\t\t\tname: \"invalid-type\",\n\t\t\t\t\tconf: confmap.NewFromStringMap(map[string]any{\n\t\t\t\t\t\t\"nop\":     nil,\n\t\t\t\t\t\t\"/custom\": nil,\n\t\t\t\t\t}),\n\t\t\t\t\texpectedError: \"the part before / should not be empty\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"invalid-name-after-slash\",\n\t\t\t\t\tconf: confmap.NewFromStringMap(map[string]any{\n\t\t\t\t\t\t\"nop\":  nil,\n\t\t\t\t\t\t\"nop/\": nil,\n\t\t\t\t\t}),\n\t\t\t\t\texpectedError: \"the part after / should not be empty\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"unknown-type\",\n\t\t\t\t\tconf: confmap.NewFromStringMap(map[string]any{\n\t\t\t\t\t\t\"nosuch\" + tk.kind: nil,\n\t\t\t\t\t}),\n\t\t\t\t\texpectedError: \"unknown type: \\\"nosuch\" + tk.kind + \"\\\" for id: \\\"nosuch\" + tk.kind + \"\\\" (valid values: [nop])\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"duplicate\",\n\t\t\t\t\tconf: confmap.NewFromStringMap(map[string]any{\n\t\t\t\t\t\t\"nop /my\" + tk.kind + \" \": nil,\n\t\t\t\t\t\t\" nop/ my\" + tk.kind:      nil,\n\t\t\t\t\t}),\n\t\t\t\t\texpectedError: \"duplicate name\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"invalid-section\",\n\t\t\t\t\tconf: confmap.NewFromStringMap(map[string]any{\n\t\t\t\t\t\t\"nop\": map[string]any{\n\t\t\t\t\t\t\t\"unknown_section\": tk.kind,\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t\texpectedError: \"error reading configuration for \\\"nop\\\"\",\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\tname: \"invalid-sub-config\",\n\t\t\t\t\tconf: confmap.NewFromStringMap(map[string]any{\n\t\t\t\t\t\t\"nop\": \"tests\",\n\t\t\t\t\t}),\n\t\t\t\t\texpectedError: \"'[nop]' expected type 'map[string]interface {}', got unconvertible type 'string'\",\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tfor _, tt := range testCases {\n\t\t\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t\t\tcfgs := NewConfigs(tk.factories)\n\t\t\t\t\terr := cfgs.Unmarshal(tt.conf)\n\t\t\t\t\tassert.ErrorContains(t, err, tt.expectedError)\n\t\t\t\t})\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestUnmarshal_LoggingExporter(t *testing.T) {\n\tconf := confmap.NewFromStringMap(map[string]any{\n\t\t\"logging\": nil,\n\t})\n\tfactories := map[component.Type]component.Factory{\n\t\tnopType: exportertest.NewNopFactory(),\n\t}\n\tcfgs := NewConfigs(factories)\n\terr := cfgs.Unmarshal(conf)\n\tassert.ErrorContains(t, err, \"the logging exporter has been deprecated, use the debug exporter instead\")\n}\n"
  },
  {
    "path": "otelcol/internal/configunmarshaler/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage configunmarshaler\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "otelcol/internal/grpclog/logger.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage grpclog // import \"go.opentelemetry.io/collector/otelcol/internal/grpclog\"\n\nimport (\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\t\"go.uber.org/zap/zapgrpc\"\n\t\"google.golang.org/grpc/grpclog\"\n)\n\n// SetLogger constructs a zapgrpc.Logger instance, and installs it as grpc logger, cloned from baseLogger with\n// exact configuration. The minimum level of gRPC logs is set to WARN should the loglevel of the collector is set to\n// INFO to avoid copious logging from grpc framework.\nfunc SetLogger(baseLogger *zap.Logger) *zapgrpc.Logger {\n\tlogger := zapgrpc.NewLogger(baseLogger.WithOptions(zap.WrapCore(func(core zapcore.Core) zapcore.Core {\n\t\tvar c zapcore.Core\n\t\tvar err error\n\t\tloglevel := baseLogger.Level()\n\t\tif loglevel == zapcore.InfoLevel {\n\t\t\tloglevel = zapcore.WarnLevel\n\t\t}\n\t\t// NewIncreaseLevelCore errors only if the new log level is less than the initial core level.\n\t\tc, err = zapcore.NewIncreaseLevelCore(core, loglevel)\n\t\t// In case of an error changing the level, move on, this happens when using the NopCore\n\t\tif err != nil {\n\t\t\tc = core\n\t\t}\n\t\treturn c.With([]zapcore.Field{zap.Bool(\"grpc_log\", true)})\n\t}), zap.AddCallerSkip(5)))\n\n\tgrpclog.SetLoggerV2(logger)\n\treturn logger\n}\n"
  },
  {
    "path": "otelcol/internal/grpclog/logger_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage grpclog\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\t\"google.golang.org/grpc/grpclog\"\n)\n\nfunc TestGRPCLogger(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\tcfg        zap.Config\n\t\tinfoLogged bool\n\t\twarnLogged bool\n\t}{\n\t\t{\n\t\t\t\"collector_info_level_grpc_log_warn\",\n\t\t\tzap.Config{\n\t\t\t\tLevel:    zap.NewAtomicLevelAt(zapcore.InfoLevel),\n\t\t\t\tEncoding: \"console\",\n\t\t\t},\n\t\t\tfalse,\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"collector_debug_level_grpc_log_debug\",\n\t\t\tzap.Config{\n\t\t\t\tLevel:    zap.NewAtomicLevelAt(zapcore.DebugLevel),\n\t\t\t\tEncoding: \"console\",\n\t\t\t},\n\t\t\ttrue,\n\t\t\ttrue,\n\t\t},\n\t\t{\n\t\t\t\"collector_warn_level_grpc_log_warn\",\n\t\t\tzap.Config{\n\t\t\t\tDevelopment: false, // this must set the grpc loggerV2 to loggerV2\n\t\t\t\tLevel:       zap.NewAtomicLevelAt(zapcore.WarnLevel),\n\t\t\t\tEncoding:    \"console\",\n\t\t\t},\n\t\t\tfalse,\n\t\t\ttrue,\n\t\t},\n\t}\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tobsInfo, obsWarn := false, false\n\t\t\tcallerInfo := \"\"\n\t\t\thook := zap.Hooks(func(entry zapcore.Entry) error {\n\t\t\t\tswitch entry.Level {\n\t\t\t\tcase zapcore.InfoLevel:\n\t\t\t\t\tobsInfo = true\n\t\t\t\tcase zapcore.WarnLevel:\n\t\t\t\t\tobsWarn = true\n\t\t\t\t}\n\t\t\t\tcallerInfo = entry.Caller.String()\n\t\t\t\treturn nil\n\t\t\t})\n\n\t\t\t// create new collector zap logger\n\t\t\tlogger, err := test.cfg.Build(hook)\n\t\t\trequire.NoError(t, err)\n\n\t\t\t// create GRPCLogger\n\t\t\tglogger := SetLogger(logger)\n\t\t\tassert.NotNil(t, glogger)\n\t\t\t// grpc does not usually call the logger directly, but through various wrappers that add extra depth\n\t\t\tcomponent := &mockComponent{logger: grpclog.Component(\"channelz\")}\n\t\t\tcomponent.Info(test.name)\n\t\t\tcomponent.Warning(test.name)\n\t\t\tassert.Equal(t, obsInfo, test.infoLogged)\n\t\t\tassert.Equal(t, obsWarn, test.warnLogged)\n\t\t\t// match the file name and line number of Warning() call above\n\t\t\tassert.Contains(t, callerInfo, \"internal/grpclog/logger_test.go:77\")\n\t\t})\n\t}\n}\n\ntype mockComponent struct {\n\tlogger grpclog.DepthLoggerV2\n}\n\nfunc (c *mockComponent) Info(args ...any) {\n\tc.logger.Info(args...)\n}\n\nfunc (c *mockComponent) Warning(args ...any) {\n\tc.logger.Warning(args...)\n}\n"
  },
  {
    "path": "otelcol/internal/grpclog/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage grpclog\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "otelcol/internal/metadata/generated_feature_gates.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\nvar OtelcolPrintInitialConfigFeatureGate = featuregate.GlobalRegistry().MustRegister(\n\t\"otelcol.printInitialConfig\",\n\tfeaturegate.StageBeta,\n\tfeaturegate.WithRegisterDescription(\"if set to true, enable the print-config command\"),\n\tfeaturegate.WithRegisterReferenceURL(\"https://github.com/open-telemetry/opentelemetry-collector/pull/11775\"),\n\tfeaturegate.WithRegisterFromVersion(\"v0.120.0\"),\n)\n"
  },
  {
    "path": "otelcol/metadata.yaml",
    "content": "type: otelcol\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  distributions: [core, contrib]\n  stability:\n    beta: [metrics, traces, logs]\n    alpha: [profiles]\n\nfeature_gates:\n  - id: otelcol.printInitialConfig\n    description: 'if set to true, enable the print-config command'\n    stage: beta\n    from_version: 'v0.120.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/pull/11775'\n"
  },
  {
    "path": "otelcol/otelcoltest/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "otelcol/otelcoltest/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcoltest // import \"go.opentelemetry.io/collector/otelcol/otelcoltest\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/provider/envprovider\"\n\t\"go.opentelemetry.io/collector/confmap/provider/fileprovider\"\n\t\"go.opentelemetry.io/collector/confmap/provider/httpprovider\"\n\t\"go.opentelemetry.io/collector/confmap/provider/yamlprovider\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n\t\"go.opentelemetry.io/collector/otelcol\"\n)\n\n// LoadConfig loads a config.Config from file, and does NOT validate the configuration.\n//\n// If factories.Telemetry is nil, a no-op telemetry factory will be used. This\n// factory does not support any telemetry configuration.\nfunc LoadConfig(fileName string, factories otelcol.Factories) (*otelcol.Config, error) {\n\tif factories.Telemetry == nil {\n\t\tfactories.Telemetry = nopTelemetryFactory()\n\t}\n\tprovider, err := otelcol.NewConfigProvider(otelcol.ConfigProviderSettings{\n\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\tURIs: []string{fileName},\n\t\t\tProviderFactories: []confmap.ProviderFactory{\n\t\t\t\tfileprovider.NewFactory(),\n\t\t\t\tenvprovider.NewFactory(),\n\t\t\t\tyamlprovider.NewFactory(),\n\t\t\t\thttpprovider.NewFactory(),\n\t\t\t},\n\t\t\tDefaultScheme: \"env\",\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn provider.Get(context.Background(), factories)\n}\n\n// LoadConfigAndValidate loads a config from the file, and validates the configuration.\nfunc LoadConfigAndValidate(fileName string, factories otelcol.Factories) (*otelcol.Config, error) {\n\tcfg, err := LoadConfig(fileName, factories)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn cfg, xconfmap.Validate(cfg)\n}\n"
  },
  {
    "path": "otelcol/otelcoltest/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcoltest\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/service/pipelines\"\n)\n\nfunc TestLoadConfig(t *testing.T) {\n\tfactories, err := NopFactories()\n\trequire.NoError(t, err)\n\n\tcfg, err := LoadConfig(filepath.Join(\"testdata\", \"config.yaml\"), factories)\n\trequire.NoError(t, err)\n\n\t// Verify extensions.\n\trequire.Len(t, cfg.Extensions, 2)\n\tassert.Contains(t, cfg.Extensions, component.MustNewID(\"nop\"))\n\tassert.Contains(t, cfg.Extensions, component.MustNewIDWithName(\"nop\", \"myextension\"))\n\n\t// Verify receivers\n\trequire.Len(t, cfg.Receivers, 2)\n\tassert.Contains(t, cfg.Receivers, component.MustNewID(\"nop\"))\n\tassert.Contains(t, cfg.Receivers, component.MustNewIDWithName(\"nop\", \"myreceiver\"))\n\n\t// Verify exporters\n\tassert.Len(t, cfg.Exporters, 2)\n\tassert.Contains(t, cfg.Exporters, component.MustNewID(\"nop\"))\n\tassert.Contains(t, cfg.Exporters, component.MustNewIDWithName(\"nop\", \"myexporter\"))\n\n\t// Verify procs\n\tassert.Len(t, cfg.Processors, 2)\n\tassert.Contains(t, cfg.Processors, component.MustNewID(\"nop\"))\n\tassert.Contains(t, cfg.Processors, component.MustNewIDWithName(\"nop\", \"myprocessor\"))\n\n\t// Verify connectors\n\tassert.Len(t, cfg.Connectors, 1)\n\tassert.Contains(t, cfg.Connectors, component.MustNewIDWithName(\"nop\", \"myconnector\"))\n\n\t// Verify service.\n\trequire.Len(t, cfg.Service.Extensions, 1)\n\tassert.Contains(t, cfg.Service.Extensions, component.MustNewID(\"nop\"))\n\trequire.Len(t, cfg.Service.Pipelines, 1)\n\tassert.Equal(t,\n\t\t&pipelines.PipelineConfig{\n\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t},\n\t\tcfg.Service.Pipelines[pipeline.NewID(pipeline.SignalTraces)],\n\t\t\"Did not load pipeline config correctly\")\n\n\t// Verify telemetry\n\tassert.Equal(t, struct{}{}, cfg.Service.Telemetry)\n}\n\nfunc TestLoadConfig_DefaultNopTelemetry(t *testing.T) {\n\tfactories, err := NopFactories()\n\trequire.NoError(t, err)\n\tfactories.Telemetry = nil\n\n\tcfg, err := LoadConfig(filepath.Join(\"testdata\", \"config.yaml\"), factories)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, struct{}{}, cfg.Service.Telemetry)\n}\n\nfunc TestLoadConfigAndValidate(t *testing.T) {\n\tfactories, err := NopFactories()\n\trequire.NoError(t, err)\n\n\tcfgValidate, errValidate := LoadConfigAndValidate(filepath.Join(\"testdata\", \"config.yaml\"), factories)\n\trequire.NoError(t, errValidate)\n\n\tcfg, errLoad := LoadConfig(filepath.Join(\"testdata\", \"config.yaml\"), factories)\n\trequire.NoError(t, errLoad)\n\n\tassert.Equal(t, cfg, cfgValidate)\n}\n\nfunc TestLoadConfigEnv(t *testing.T) {\n\tfactories, err := NopFactories()\n\trequire.NoError(t, err)\n\n\tfor _, tt := range []struct {\n\t\tfile string\n\t}{\n\t\t{file: filepath.Join(\"testdata\", \"config_env.yaml\")},\n\t\t{file: filepath.Join(\"testdata\", \"config_default_scheme.yaml\")},\n\t} {\n\t\tt.Run(tt.file, func(t *testing.T) {\n\t\t\tt.Setenv(\"RECEIVERS\", \"[nop]\")\n\t\t\tcfg, err := LoadConfigAndValidate(tt.file, factories)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tassert.Equal(t, []component.ID{component.MustNewID(\"nop\")}, cfg.Service.Pipelines[pipeline.NewID(pipeline.SignalTraces)].Receivers)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "otelcol/otelcoltest/go.mod",
    "content": "module go.opentelemetry.io/collector/otelcol/otelcoltest\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/confmap/provider/envprovider v1.54.0\n\tgo.opentelemetry.io/collector/confmap/provider/fileprovider v1.54.0\n\tgo.opentelemetry.io/collector/confmap/provider/httpprovider v1.54.0\n\tgo.opentelemetry.io/collector/confmap/provider/yamlprovider v1.54.0\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0\n\tgo.opentelemetry.io/collector/connector/connectortest v0.148.0\n\tgo.opentelemetry.io/collector/exporter/exportertest v0.148.0\n\tgo.opentelemetry.io/collector/extension/extensiontest v0.148.0\n\tgo.opentelemetry.io/collector/otelcol v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/processor/processortest v0.148.0\n\tgo.opentelemetry.io/collector/receiver/receivertest v0.148.0\n\tgo.opentelemetry.io/collector/service v0.148.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/beorn7/perks v1.0.1 // indirect\n\tgithub.com/cenkalti/backoff/v5 v5.0.3 // indirect\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect\n\tgithub.com/ebitengine/purego v0.10.0 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-ole/go-ole v1.2.6 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/inconshreveable/mousetrap v1.1.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect\n\tgithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect\n\tgithub.com/prometheus/client_golang v1.23.2 // indirect\n\tgithub.com/prometheus/client_model v0.6.2 // indirect\n\tgithub.com/prometheus/common v0.67.5 // indirect\n\tgithub.com/prometheus/otlptranslator v1.0.0 // indirect\n\tgithub.com/prometheus/procfs v0.20.1 // indirect\n\tgithub.com/shirou/gopsutil/v4 v4.26.2 // indirect\n\tgithub.com/spf13/cobra v1.10.2 // indirect\n\tgithub.com/spf13/pflag v1.0.10 // indirect\n\tgithub.com/tklauser/go-sysconf v0.3.16 // indirect\n\tgithub.com/tklauser/numcpus v0.11.0 // indirect\n\tgithub.com/yusufpapurcu/wmi v1.2.4 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/component/componentstatus v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/config/configtelemetry v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/connector v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/connector/xconnector v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/exporter v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/exporter/xexporter v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/extension v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensioncapabilities v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/internal/fanoutconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/internal/telemetry v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/xpdata v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/processor v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/processor/xprocessor v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/service/hostcapabilities v0.148.0 // indirect\n\tgo.opentelemetry.io/contrib/otelconf v0.22.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/prometheus v0.64.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/log v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/log v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.opentelemetry.io/proto/otlp v1.10.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v2 v2.4.3 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sys v0.42.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgonum.org/v1/gonum v0.17.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/receiver => ../../receiver\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/confmap/provider/httpprovider => ../../confmap/provider/httpprovider\n\nreplace go.opentelemetry.io/collector/confmap/provider/yamlprovider => ../../confmap/provider/yamlprovider\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/config/configtelemetry => ../../config/configtelemetry\n\nreplace go.opentelemetry.io/collector/processor => ../../processor\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/connector => ../../connector\n\nreplace go.opentelemetry.io/collector/connector/connectortest => ../../connector/connectortest\n\nreplace go.opentelemetry.io/collector/config/configretry => ../../config/configretry\n\nreplace go.opentelemetry.io/collector/confmap/provider/fileprovider => ../../confmap/provider/fileprovider\n\nreplace go.opentelemetry.io/collector/confmap/provider/envprovider => ../../confmap/provider/envprovider\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/extension => ../../extension\n\nreplace go.opentelemetry.io/collector/exporter => ../../exporter\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/component/componentstatus => ../../component/componentstatus\n\nreplace go.opentelemetry.io/collector/extension/extensioncapabilities => ../../extension/extensioncapabilities\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../../receiver/receivertest\n\nreplace go.opentelemetry.io/collector/processor/xprocessor => ../../processor/xprocessor\n\nreplace go.opentelemetry.io/collector/connector/xconnector => ../../connector/xconnector\n\nreplace go.opentelemetry.io/collector/exporter/xexporter => ../../exporter/xexporter\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/exporter/exportertest => ../../exporter/exportertest\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/config/configopaque => ../../config/configopaque\n\nreplace go.opentelemetry.io/collector/config/configauth => ../../config/configauth\n\nreplace go.opentelemetry.io/collector/config/configtls => ../../config/configtls\n\nreplace go.opentelemetry.io/collector/config/configcompression => ../../config/configcompression\n\nreplace go.opentelemetry.io/collector/config/confighttp => ../../config/confighttp\n\nreplace go.opentelemetry.io/collector/client => ../../client\n\nreplace go.opentelemetry.io/collector/extension/extensionauth => ../../extension/extensionauth\n\nreplace go.opentelemetry.io/collector/otelcol => ../\n\nreplace go.opentelemetry.io/collector/extension/zpagesextension => ../../extension/zpagesextension\n\nreplace go.opentelemetry.io/collector/service => ../../service\n\nreplace go.opentelemetry.io/collector/service/telemetry/telemetrytest => ../../service/telemetry/telemetrytest\n\nreplace go.opentelemetry.io/collector/service/hostcapabilities => ../../service/hostcapabilities\n\nreplace go.opentelemetry.io/collector/internal/fanoutconsumer => ../../internal/fanoutconsumer\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../../extension/extensiontest\n\nreplace go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest => ../../extension/extensionauth/extensionauthtest\n\nreplace go.opentelemetry.io/collector/extension/xextension => ../../extension/xextension\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/processor/processortest => ../../processor/processortest\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/internal/telemetry => ../../internal/telemetry\n\nreplace go.opentelemetry.io/collector/config/configmiddleware => ../../config/configmiddleware\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest => ../../extension/extensionmiddleware/extensionmiddlewaretest\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ../../extension/extensionmiddleware\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper => ../../exporter/exporterhelper\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../../config/configoptional\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n\nreplace go.opentelemetry.io/collector/config/confignet => ../../config/confignet\n"
  },
  {
    "path": "otelcol/otelcoltest/go.sum",
    "content": "github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=\ngithub.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=\ngithub.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=\ngithub.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=\ngithub.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=\ngithub.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=\ngithub.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f h1:RJ+BDPLSHQO7cSjKBqjPJSbi1qfk9WcsjQDtZiw3dZw=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f/go.mod h1:VHbbch/X4roIY22jL1s3qRbZhCiRIgUAF/PdSUcx2io=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=\ngithub.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=\ngithub.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=\ngithub.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=\ngithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=\ngithub.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=\ngithub.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=\ngithub.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=\ngithub.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=\ngithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3 h1:PwQumkgq4/acIiZhtifTV5OUqqiP82UAl0h87xj/l9k=\ngithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=\ngithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=\ngithub.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=\ngithub.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=\ngithub.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=\ngithub.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=\ngithub.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=\ngithub.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=\ngithub.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=\ngithub.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=\ngithub.com/prometheus/otlptranslator v1.0.0 h1:s0LJW/iN9dkIH+EnhiD3BlkkP5QVIUVEoIwkU+A6qos=\ngithub.com/prometheus/otlptranslator v1.0.0/go.mod h1:vRYWnXvI6aWGpsdY/mOT/cbeVRBlPWtBNDb7kGR3uKM=\ngithub.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc=\ngithub.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=\ngithub.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=\ngithub.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=\ngithub.com/shirou/gopsutil/v4 v4.26.2 h1:X8i6sicvUFih4BmYIGT1m2wwgw2VG9YgrDTi7cIRGUI=\ngithub.com/shirou/gopsutil/v4 v4.26.2/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=\ngithub.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=\ngithub.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=\ngithub.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=\ngithub.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngithub.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYICU0nA=\ngithub.com/tklauser/go-sysconf v0.3.16/go.mod h1:/qNL9xxDhc7tx3HSRsLWNnuzbVfh3e7gh/BmM179nYI=\ngithub.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9RXw=\ngithub.com/tklauser/numcpus v0.11.0/go.mod h1:z+LwcLq54uWZTX0u/bGobaV34u6V7KNlTZejzM6/3MQ=\ngithub.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=\ngithub.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=\ngo.opentelemetry.io/contrib/otelconf v0.22.0 h1:+kpcfczGOFM85zDZyqQCzWefhovegfn24D0WwmQz0n4=\ngo.opentelemetry.io/contrib/otelconf v0.22.0/go.mod h1:ojdbOukO+JRDJQmJY2PRIZEg0UYVzcOuZR59hp7xffc=\ngo.opentelemetry.io/contrib/zpages v0.67.0 h1:cIUwWSVDovuLEbDIKreptjdxMuIhGiqwq0uL8YNaq1c=\ngo.opentelemetry.io/contrib/zpages v0.67.0/go.mod h1:vK8fsYHgPYg4Z/XDbFSEvItSGZDbjWTvjBOu8+AiDhc=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0 h1:deI9UQMoGFgrg5iLPgzueqFPHevDl+28YKfSpPTI6rY=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0/go.mod h1:PFx9NgpNUKXdf7J4Q3agRxMs3Y07QhTCVipKmLsMKnU=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0 h1:icqq3Z34UrEFk2u+HMhTtRsvo7Ues+eiJVjaJt62njs=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0/go.mod h1:W2m8P+d5Wn5kipj4/xmbt9uMqezEKfBjzVJadfABSBE=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0 h1:MdKucPl/HbzckWWEisiNqMPhRrAOQX8r4jTuGr636gk=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0/go.mod h1:RolT8tWtfHcjajEH5wFIZ4Dgh5jpPdFXYV9pTAk/qjc=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0 h1:H7O6RlGOMTizyl3R08Kn5pdM06bnH8oscSj7o11tmLA=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0/go.mod h1:mBFWu/WOVDkWWsR7Tx7h6EpQB8wsv7P0Yrh0Pb7othc=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 h1:THuZiwpQZuHPul65w4WcwEnkX2QIuMT+UFoOrygtoJw=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0/go.mod h1:J2pvYM5NGHofZ2/Ru6zw/TNWnEQp5crgyDeSrYpXkAw=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0 h1:zWWrB1U6nqhS/k6zYB74CjRpuiitRtLLi68VcgmOEto=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0/go.mod h1:2qXPNBX1OVRC0IwOnfo1ljoid+RD0QK3443EaqVlsOU=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 h1:uLXP+3mghfMf7XmV4PkGfFhFKuNWoCvvx5wP/wOXo0o=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0/go.mod h1:v0Tj04armyT59mnURNUJf7RCKcKzq+lgJs6QSjHjaTc=\ngo.opentelemetry.io/otel/exporters/prometheus v0.64.0 h1:g0LRDXMX/G1SEZtK8zl8Chm4K6GBwRkjPKE36LxiTYs=\ngo.opentelemetry.io/otel/exporters/prometheus v0.64.0/go.mod h1:UrgcjnarfdlBDP3GjDIJWe6HTprwSazNjwsI+Ru6hro=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0 h1:KJVjPD3rcPb98rIs3HznyJlrfx9ge5oJvxxlGR+P/7s=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0/go.mod h1:K3kRa2ckmHWQaTWQdPRHc7qGXASuVuoEQXzrvlA98Ws=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0 h1:lSZHgNHfbmQTPfuTmWVkEu8J8qXaQwuV30pjCcAUvP8=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0/go.mod h1:so9ounLcuoRDu033MW/E0AD4hhUjVqswrMF5FoZlBcw=\ngo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0 h1:s/1iRkCKDfhlh1JF26knRneorus8aOwVIDhvYx9WoDw=\ngo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0/go.mod h1:UI3wi0FXg1Pofb8ZBiBLhtMzgoTm1TYkMvn71fAqDzs=\ngo.opentelemetry.io/otel/log v0.18.0 h1:XgeQIIBjZZrliksMEbcwMZefoOSMI1hdjiLEiiB0bAg=\ngo.opentelemetry.io/otel/log v0.18.0/go.mod h1:KEV1kad0NofR3ycsiDH4Yjcoj0+8206I6Ox2QYFSNgI=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/log v0.18.0 h1:n8OyZr7t7otkeTnPTbDNom6rW16TBYGtvyy2Gk6buQw=\ngo.opentelemetry.io/otel/sdk/log v0.18.0/go.mod h1:C0+wxkTwKpOCZLrlJ3pewPiiQwpzycPI/u6W0Z9fuYk=\ngo.opentelemetry.io/otel/sdk/log/logtest v0.18.0 h1:l3mYuPsuBx6UKE47BVcPrZoZ0q/KER57vbj2qkgDLXA=\ngo.opentelemetry.io/otel/sdk/log/logtest v0.18.0/go.mod h1:7cHtiVJpZebB3wybTa4NG+FUo5NPe3PROz1FqB0+qdw=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=\ngo.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=\ngo.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=\ngolang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=\ngolang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa h1:Zt3DZoOFFYkKhDT3v7Lm9FDMEV06GpzjG2jrqW+QTE0=\ngolang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=\ngolang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=\ngonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=\ngoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 h1:tu/dtnW1o3wfaxCOjSLn5IRX4YDcJrtlpzYkhHhGaC4=\ngoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171/go.mod h1:M5krXqk4GhBKvB596udGL3UyjL4I1+cTbK0orROM9ng=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "otelcol/otelcoltest/metadata.yaml",
    "content": "type: otelcol/otelcoltest\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "otelcol/otelcoltest/nop_factories.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcoltest // import \"go.opentelemetry.io/collector/otelcol/otelcoltest\"\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector/connectortest\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/extension/extensiontest\"\n\t\"go.opentelemetry.io/collector/otelcol\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n)\n\n// NopFactories returns a otelcol.Factories with all nop factories.\nfunc NopFactories() (otelcol.Factories, error) {\n\tvar factories otelcol.Factories\n\n\t// MakeFactoryMap can never return an error with a single Factory\n\tfactories.Extensions, _ = otelcol.MakeFactoryMap(extensiontest.NewNopFactory())\n\tfactories.Receivers, _ = otelcol.MakeFactoryMap(receivertest.NewNopFactory())\n\tfactories.Exporters, _ = otelcol.MakeFactoryMap(exportertest.NewNopFactory())\n\tfactories.Processors, _ = otelcol.MakeFactoryMap(processortest.NewNopFactory())\n\tfactories.Connectors, _ = otelcol.MakeFactoryMap(connectortest.NewNopFactory())\n\tfactories.Telemetry = nopTelemetryFactory()\n\n\treturn factories, nil\n}\n\nfunc nopTelemetryFactory() telemetry.Factory {\n\treturn telemetry.NewFactory(\n\t\tfunc() component.Config { return struct{}{} },\n\t)\n}\n"
  },
  {
    "path": "otelcol/otelcoltest/nop_factories_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcoltest\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar nopType = component.MustNewType(\"nop\")\n\nfunc TestNopFactories(t *testing.T) {\n\tnopFactories, err := NopFactories()\n\trequire.NoError(t, err)\n\n\trequire.Len(t, nopFactories.Receivers, 1)\n\tnopReceiverFactory, ok := nopFactories.Receivers[nopType]\n\trequire.True(t, ok)\n\trequire.Equal(t, nopType, nopReceiverFactory.Type())\n\n\trequire.Len(t, nopFactories.Processors, 1)\n\tnopProcessorFactory, ok := nopFactories.Processors[nopType]\n\trequire.True(t, ok)\n\trequire.Equal(t, nopType, nopProcessorFactory.Type())\n\n\trequire.Len(t, nopFactories.Exporters, 1)\n\tnopExporterFactory, ok := nopFactories.Exporters[nopType]\n\trequire.True(t, ok)\n\trequire.Equal(t, nopType, nopExporterFactory.Type())\n\n\trequire.Len(t, nopFactories.Extensions, 1)\n\tnopExtensionFactory, ok := nopFactories.Extensions[nopType]\n\trequire.True(t, ok)\n\trequire.Equal(t, nopType, nopExtensionFactory.Type())\n\n\trequire.Len(t, nopFactories.Connectors, 1)\n\tnopConnectorFactory, ok := nopFactories.Connectors[nopType]\n\trequire.True(t, ok)\n\trequire.Equal(t, nopType, nopConnectorFactory.Type())\n}\n"
  },
  {
    "path": "otelcol/otelcoltest/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcoltest\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "otelcol/otelcoltest/testdata/config.yaml",
    "content": "receivers:\n    nop:\n    nop/myreceiver:\n\nprocessors:\n    nop:\n    nop/myprocessor:\n\nexporters:\n    nop:\n    nop/myexporter:\n\nconnectors:\n    nop/myconnector:\n\nextensions:\n    nop:\n    nop/myextension:\n\nservice:\n    extensions: [nop]\n    pipelines:\n        traces:\n            receivers: [nop]\n            processors: [nop]\n            exporters: [nop]\n"
  },
  {
    "path": "otelcol/otelcoltest/testdata/config_default_scheme.yaml",
    "content": "receivers:\n    nop:\n\nexporters:\n    nop:\n\nservice:\n    pipelines:\n        traces:\n            receivers: ${RECEIVERS}\n            exporters: [nop]\n"
  },
  {
    "path": "otelcol/otelcoltest/testdata/config_env.yaml",
    "content": "receivers:\n    nop:\n\nexporters:\n    nop:\n\nservice:\n    pipelines:\n        traces:\n            receivers: ${env:RECEIVERS}\n            exporters: [nop]\n"
  },
  {
    "path": "otelcol/signals_others.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build !(js && wasm)\n\npackage otelcol // import \"go.opentelemetry.io/collector/otelcol\"\n\nimport (\n\t\"syscall\"\n)\n\nconst (\n\tSIGHUP  = syscall.SIGHUP\n\tSIGTERM = syscall.SIGTERM\n)\n"
  },
  {
    "path": "otelcol/signals_wasm.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build js && wasm\n\npackage otelcol // import \"go.opentelemetry.io/collector/otelcol\"\n\nimport (\n\t\"syscall\"\n)\n\nconst (\n\tSIGHUP  = syscall.Signal(-1)\n\tSIGTERM = syscall.Signal(-1)\n)\n"
  },
  {
    "path": "otelcol/testdata/components-output-sorted.yaml",
    "content": "buildinfo:\n    command: otelcol\n    description: OpenTelemetry Collector\n    version: latest\nreceivers:\n    - name: bar\n      module: go.opentelemetry.io/collector/receiver/receivertest v1.2.3\n      stability:\n        logs: Undefined\n        metrics: Undefined\n        traces: Undefined\n    - name: baz\n      module: go.opentelemetry.io/collector/receiver/receivertest v1.2.3\n      stability:\n        logs: Undefined\n        metrics: Undefined\n        traces: Undefined\n    - name: foo\n      module: go.opentelemetry.io/collector/receiver/receivertest v1.2.3\n      stability:\n        logs: Undefined\n        metrics: Undefined\n        traces: Undefined\nprocessors:\n    - name: bar\n      module: go.opentelemetry.io/collector/processor/processortest v1.2.3\n      stability:\n        logs: Undefined\n        metrics: Undefined\n        traces: Undefined\n    - name: baz\n      module: go.opentelemetry.io/collector/processor/processortest v1.2.3\n      stability:\n        logs: Undefined\n        metrics: Undefined\n        traces: Undefined\n    - name: foo\n      module: go.opentelemetry.io/collector/processor/processortest v1.2.3\n      stability:\n        logs: Undefined\n        metrics: Undefined\n        traces: Undefined\nexporters:\n    - name: bar\n      module: go.opentelemetry.io/collector/exporter/exportertest v1.2.3\n      stability:\n        logs: Undefined\n        metrics: Undefined\n        traces: Undefined\n    - name: baz\n      module: go.opentelemetry.io/collector/exporter/exportertest v1.2.3\n      stability:\n        logs: Undefined\n        metrics: Undefined\n        traces: Undefined\n    - name: foo\n      module: go.opentelemetry.io/collector/exporter/exportertest v1.2.3\n      stability:\n        logs: Undefined\n        metrics: Undefined\n        traces: Undefined\nconnectors:\n    - name: bar\n      module: go.opentelemetry.io/collector/connector/connectortest v1.2.3\n      stability:\n        logs-to-logs: Undefined\n        logs-to-metrics: Undefined\n        logs-to-traces: Undefined\n        metrics-to-logs: Undefined\n        metrics-to-metrics: Undefined\n        metrics-to-traces: Undefined\n        traces-to-logs: Undefined\n        traces-to-metrics: Undefined\n        traces-to-traces: Undefined\n    - name: baz\n      module: go.opentelemetry.io/collector/connector/connectortest v1.2.3\n      stability:\n        logs-to-logs: Undefined\n        logs-to-metrics: Undefined\n        logs-to-traces: Undefined\n        metrics-to-logs: Undefined\n        metrics-to-metrics: Undefined\n        metrics-to-traces: Undefined\n        traces-to-logs: Undefined\n        traces-to-metrics: Undefined\n        traces-to-traces: Undefined\n    - name: foo\n      module: go.opentelemetry.io/collector/connector/connectortest v1.2.3\n      stability:\n        logs-to-logs: Undefined\n        logs-to-metrics: Undefined\n        logs-to-traces: Undefined\n        metrics-to-logs: Undefined\n        metrics-to-metrics: Undefined\n        metrics-to-traces: Undefined\n        traces-to-logs: Undefined\n        traces-to-metrics: Undefined\n        traces-to-traces: Undefined\nextensions:\n    - name: bar\n      module: go.opentelemetry.io/collector/extension/extensiontest v1.2.3\n      stability:\n        extension: Stable\n    - name: baz\n      module: go.opentelemetry.io/collector/extension/extensiontest v1.2.3\n      stability:\n        extension: Stable\n    - name: foo\n      module: go.opentelemetry.io/collector/extension/extensiontest v1.2.3\n      stability:\n        extension: Stable\nproviders:\n    - scheme: env\n      module: go.opentelemetry.io/collector/confmap/provider/testprovider v1.2.3\n    - scheme: file\n      module: go.opentelemetry.io/collector/confmap/provider/testprovider v1.2.3\nconverters:\n    - module: go.opentelemetry.io/collector/converter/bar v1.2.3\n    - module: go.opentelemetry.io/collector/converter/baz v1.2.3\n    - module: go.opentelemetry.io/collector/converter/foo v1.2.3\n"
  },
  {
    "path": "otelcol/testdata/components-output.yaml",
    "content": "buildinfo:\n    command: otelcol\n    description: OpenTelemetry Collector\n    version: latest\nreceivers:\n    - name: nop\n      module: go.opentelemetry.io/collector/receiver/receivertest v1.2.3\n      stability:\n        logs: Stable\n        metrics: Stable\n        traces: Stable\nprocessors:\n    - name: nop\n      module: go.opentelemetry.io/collector/processor/processortest v1.2.3\n      stability:\n        logs: Stable\n        metrics: Stable\n        traces: Stable\nexporters:\n    - name: nop\n      module: go.opentelemetry.io/collector/exporter/exportertest v1.2.3\n      stability:\n        logs: Stable\n        metrics: Stable\n        traces: Stable\nconnectors:\n    - name: nop\n      module: go.opentelemetry.io/collector/connector/connectortest v1.2.3\n      stability:\n        logs-to-logs: Development\n        logs-to-metrics: Development\n        logs-to-traces: Development\n        metrics-to-logs: Development\n        metrics-to-metrics: Development\n        metrics-to-traces: Development\n        traces-to-logs: Development\n        traces-to-metrics: Development\n        traces-to-traces: Development\nextensions:\n    - name: nop\n      module: go.opentelemetry.io/collector/extension/extensiontest v1.2.3\n      stability:\n        extension: Stable\nproviders:\n    - scheme: env\n      module: go.opentelemetry.io/collector/confmap/provider/testprovider v1.2.3\n    - scheme: file\n      module: go.opentelemetry.io/collector/confmap/provider/testprovider v1.2.3\nconverters:\n    - module: go.opentelemetry.io/collector/converter/testconverter v1.2.3\n"
  },
  {
    "path": "otelcol/testdata/configs/1-config-first.yaml",
    "content": "receivers:\n    bar:\n        key: val\nexporters:\n    bar:\n        key: val\n"
  },
  {
    "path": "otelcol/testdata/configs/1-config-output.yaml",
    "content": "exporters:\n    bar:\n        key: val\n    foo:\n        key: val\nreceivers:\n    bar:\n        key: val\n    foo:\n        key: val\n"
  },
  {
    "path": "otelcol/testdata/configs/1-config-second.yaml",
    "content": "receivers:\n    foo:\n        key: val\nexporters:\n    foo:\n        key: val\n"
  },
  {
    "path": "otelcol/testdata/configs/2-config-output.yaml",
    "content": "exporters:\n    bar:\n        key: val\n    foo:\n        key: val\nreceivers:\n    bar:\n        key: val\n    foo:\n        key: val\nservice:\n    pipelines:\n        logs:\n            exporters:\n                - foo\n                - bar\n            receivers:\n                - foo\n                - bar\n"
  },
  {
    "path": "otelcol/testdata/otelcol-cyclic-connector.yaml",
    "content": "receivers:\n  nop:\n\nexporters:\n  nop:\n\nconnectors:\n  nop/forward:\n\nservice:\n  pipelines:\n    traces/in:\n      receivers: [nop/forward]\n      processors: [ ]\n      exporters: [nop/forward]\n    traces/out:\n      receivers: [nop/forward]\n      processors: [ ]\n      exporters: [nop/forward]"
  },
  {
    "path": "otelcol/testdata/otelcol-invalid-components.yaml",
    "content": "receivers:\n  nop:\nexporters:\n  nop:\nprocessors:\n  nosuchprocessor:\nservice:\n  pipelines:\n    traces:\n      receivers: [nop]\n      exporters: [nop]\n      processors: [nop]\n"
  },
  {
    "path": "otelcol/testdata/otelcol-invalid-connector-unused-exp.yaml",
    "content": "receivers:\n  nop:\n\nexporters:\n  nop:\n\nconnectors:\n  nop/connector1:\n\nservice:\n  pipelines:\n    logs/in1:\n      receivers: [nop]\n      processors: [ ]\n      exporters: [nop]\n    logs/in2:\n      receivers: [nop/connector1]\n      processors: [ ]\n      exporters: [nop]\n    logs/out:\n      receivers: [nop]\n      processors: [ ]\n      exporters: [nop]\n"
  },
  {
    "path": "otelcol/testdata/otelcol-invalid-connector-unused-rec.yaml",
    "content": "receivers:\n  nop:\n\nexporters:\n  nop:\n\nconnectors:\n  nop/connector1:\n\nservice:\n  pipelines:\n    logs/in1:\n      receivers: [nop]\n      processors: [ ]\n      exporters: [nop]\n    logs/in2:\n      receivers: [nop]\n      processors: [ ]\n      exporters: [nop/connector1]\n    logs/out:\n      receivers: [nop]\n      processors: [ ]\n      exporters: [nop]\n"
  },
  {
    "path": "otelcol/testdata/otelcol-invalid-receiver-type.yaml",
    "content": "receivers:\n  nop_logs:\n\nprocessors:\n  nop:\n\nexporters:\n  nop:\n\nservice:\n  pipelines:\n    traces:\n      receivers: [nop_logs]\n      processors: [nop]\n      exporters: [nop]\n"
  },
  {
    "path": "otelcol/testdata/otelcol-invalid-telemetry.yaml",
    "content": "receivers:\n  nop:\n\nexporters:\n  nop:\n\nservice:\n  telemetry:\n    unknown: key\n  pipelines:\n    metrics:\n      receivers: [nop]\n      exporters: [nop]\n"
  },
  {
    "path": "otelcol/testdata/otelcol-invalid.yaml",
    "content": "receivers:\n  nop:\n\nprocessors:\n  nop:\n\nexporters:\n  nop:\n\nservice:\n  pipelines:\n    traces:\n      receivers: [nop]\n      processors: [invalid]\n      exporters: [nop]\n"
  },
  {
    "path": "otelcol/testdata/otelcol-log-to-file.yaml",
    "content": "extensions:\n  zpages:\n\nreceivers:\n  otlp:\n    protocols:\n      grpc:\n      http:\n\nexporters:\n  debug:\n    verbosity: detailed\n\nservice:\n  telemetry:\n    logs:\n      level: info\n      output_paths:\n        # The folder need to be created prior to starting the collector\n        - ${ProgramData}\\OpenTelemetry\\Collector\\Logs\\otelcol.log\n\n  pipelines:\n    traces:\n      receivers: [otlp]\n      exporters: [debug]\n    metrics:\n      receivers: [otlp]\n      exporters: [debug]\n\n  extensions: [zpages]\n"
  },
  {
    "path": "otelcol/testdata/otelcol-nop.yaml",
    "content": "receivers:\n  nop:\n\nprocessors:\n  nop:\n\nexporters:\n  nop:\n\nextensions:\n  nop:\n\nconnectors:\n  nop/con:\n\nservice:\n  extensions: [nop]\n  pipelines:\n    traces:\n      receivers: [nop]\n      processors: [nop]\n      exporters: [nop, nop/con]\n    metrics:\n      receivers: [nop]\n      processors: [nop]\n      exporters: [nop]\n    logs:\n      receivers: [nop, nop/con]\n      processors: [nop]\n      exporters: [nop]\n"
  },
  {
    "path": "otelcol/testdata/otelcol-otelconftelemetry.yaml",
    "content": "receivers:\n  nop:\nexporters:\n  nop:\n\nservice:\n  telemetry:\n    # Set configuration understood by otelconftelemetry\n    metrics:\n      level: none\n  pipelines:\n    metrics:\n      receivers: [nop]\n      exporters: [nop]\n"
  },
  {
    "path": "otelcol/testdata/otelcol-statuswatcher.yaml",
    "content": "receivers:\n  nop:\n\nprocessors:\n  nop:\n  unhealthy:\n\nexporters:\n  nop:\n\nextensions:\n  statuswatcher:\n\nservice:\n  extensions: [statuswatcher]\n  pipelines:\n    traces:\n      receivers: [nop]\n      processors: [nop,unhealthy]\n      exporters: [nop]\n    metrics:\n      receivers: [nop]\n      processors: [nop,unhealthy]\n      exporters: [nop]\n    logs:\n      receivers: [nop]\n      processors: [nop,unhealthy]\n      exporters: [nop]\n"
  },
  {
    "path": "otelcol/testdata/otelcol-valid-connector-use.yaml",
    "content": "receivers:\n  nop:\n\nexporters:\n  nop:\n\nconnectors:\n  nop/connector1:\n\nservice:\n  pipelines:\n    logs/in1:\n      receivers: [nop]\n      processors: [ ]\n      exporters: [nop]\n    logs/in2:\n      receivers: [nop]\n      processors: [ ]\n      exporters: [nop/connector1]\n    logs/out:\n      receivers: [nop/connector1]\n      processors: [ ]\n      exporters: [nop]"
  },
  {
    "path": "otelcol/testdata/print.yaml",
    "content": "receivers:\n  r:\n    opaque: \"OOO\"\nexporters:\n  e:\n    timeout: 5s\nservice:\n  pipelines:\n    logs:\n      receivers: [r]\n      exporters: [e]\n"
  },
  {
    "path": "otelcol/testdata/print_default.yaml",
    "content": "receivers:\n  r:\n    other: lala\nexporters:\n  e:\nservice:\n  pipelines:\n    logs:\n      receivers: [r]\n      exporters: [e]\n"
  },
  {
    "path": "otelcol/testdata/print_invalid.yaml",
    "content": "receivers:\n  r:\nexporters:\n  e:\n    timeout: invalid\nservice:\n  pipelines:\n    logs:\n      receivers: [r]\n      exporters: [e]\n"
  },
  {
    "path": "otelcol/testdata/print_negative.yaml",
    "content": "receivers:\n  r:\nexporters:\n  e:\n    timeout: -1\nservice:\n  pipelines:\n    logs:\n      receivers: [r]\n      exporters: [e]\n"
  },
  {
    "path": "otelcol/unmarshal_dry_run_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/receiver\"\n)\n\nvar _ component.Config = (*Config)(nil)\n\ntype ValidateTestConfig struct {\n\tNumber int    `mapstructure:\"number\"`\n\tString string `mapstructure:\"string\"`\n}\n\nvar genericType component.Type = component.MustNewType(\"generic\")\n\nfunc NewFactories(_ *testing.T) func() (Factories, error) {\n\treturn func() (Factories, error) {\n\t\tfactories, err := nopFactories()\n\t\tif err != nil {\n\t\t\treturn Factories{}, err\n\t\t}\n\t\tfactories.Receivers[genericType] = receiver.NewFactory(\n\t\t\tgenericType,\n\t\t\tfunc() component.Config {\n\t\t\t\treturn &ValidateTestConfig{\n\t\t\t\t\tNumber: 1,\n\t\t\t\t\tString: \"default\",\n\t\t\t\t}\n\t\t\t})\n\n\t\treturn factories, nil\n\t}\n}\n\nvar sampleYAMLConfig = `\nreceivers:\n  generic:\n    number: ${mock:number}\n    string: ${mock:number}\n\nexporters:\n  nop:\n\nservice:\n  pipelines:\n    traces:\n      receivers: [generic]\n      exporters: [nop]\n`\n\nfunc TestDryRunWithExpandedValues(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\tyamlConfig string\n\t\tmockMap    map[string]string\n\t\texpectErr  bool\n\t}{\n\t\t{\n\t\t\tname:       \"string that looks like an integer\",\n\t\t\tyamlConfig: sampleYAMLConfig,\n\t\t\tmockMap: map[string]string{\n\t\t\t\t\"number\": \"123\",\n\t\t\t},\n\t\t\texpectErr: true,\n\t\t},\n\t\t{\n\t\t\tname:       \"string that looks like a bool\",\n\t\t\tyamlConfig: sampleYAMLConfig,\n\t\t\tmockMap: map[string]string{\n\t\t\t\t\"number\": \"true\",\n\t\t\t},\n\t\t\texpectErr: true,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcollector, err := NewCollector(CollectorSettings{\n\t\t\t\tFactories: NewFactories(t),\n\t\t\t\tConfigProviderSettings: ConfigProviderSettings{\n\t\t\t\t\tResolverSettings: confmap.ResolverSettings{\n\t\t\t\t\t\tURIs:          []string{\"file:file\"},\n\t\t\t\t\t\tDefaultScheme: \"mock\",\n\t\t\t\t\t\tProviderFactories: []confmap.ProviderFactory{\n\t\t\t\t\t\t\tnewFakeProvider(\"mock\", func(_ context.Context, uri string, _ confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\t\t\t\t\t\t\t\treturn confmap.NewRetrievedFromYAML([]byte(tt.mockMap[uri[len(\"mock:\"):]]))\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\tnewFakeProvider(\"file\", func(_ context.Context, _ string, _ confmap.WatcherFunc) (*confmap.Retrieved, error) {\n\t\t\t\t\t\t\t\treturn confmap.NewRetrievedFromYAML([]byte(tt.yamlConfig))\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tSkipSettingGRPCLogger: true,\n\t\t\t})\n\t\t\trequire.NoError(t, err)\n\n\t\t\terr = collector.DryRun(context.Background())\n\t\t\tif tt.expectErr {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "otelcol/unmarshaler.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol // import \"go.opentelemetry.io/collector/otelcol\"\n\nimport (\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/otelcol/internal/configunmarshaler\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/service\"\n)\n\nvar errNilTelemetryFactory = errors.New(\"otelcol.Factories.Telemetry must not be nil. For example, you can use otelconftelemetry.NewFactory to build a telemetry factory\")\n\ntype configSettings struct {\n\tReceivers  *configunmarshaler.Configs[receiver.Factory]  `mapstructure:\"receivers\"`\n\tProcessors *configunmarshaler.Configs[processor.Factory] `mapstructure:\"processors\"`\n\tExporters  *configunmarshaler.Configs[exporter.Factory]  `mapstructure:\"exporters\"`\n\tConnectors *configunmarshaler.Configs[connector.Factory] `mapstructure:\"connectors\"`\n\tExtensions *configunmarshaler.Configs[extension.Factory] `mapstructure:\"extensions\"`\n\tService    service.Config                                `mapstructure:\"service\"`\n}\n\n// unmarshal the configSettings from a confmap.Conf.\n// After the config is unmarshalled, `Validate()` must be called to validate.\nfunc unmarshal(v *confmap.Conf, factories Factories) (*configSettings, error) {\n\tif factories.Telemetry == nil {\n\t\treturn nil, errNilTelemetryFactory\n\t}\n\n\t// Unmarshal top level sections and validate.\n\tcfg := &configSettings{\n\t\tReceivers:  configunmarshaler.NewConfigs(factories.Receivers),\n\t\tProcessors: configunmarshaler.NewConfigs(factories.Processors),\n\t\tExporters:  configunmarshaler.NewConfigs(factories.Exporters),\n\t\tConnectors: configunmarshaler.NewConfigs(factories.Connectors),\n\t\tExtensions: configunmarshaler.NewConfigs(factories.Extensions),\n\t\t// TODO: Add a component.ServiceFactory to allow this to be defined by the Service.\n\t\tService: service.Config{\n\t\t\tTelemetry: factories.Telemetry.CreateDefaultConfig(),\n\t\t},\n\t}\n\terr := v.Unmarshal(&cfg)\n\treturn cfg, err\n}\n"
  },
  {
    "path": "otelcol/unmarshaler_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelcol\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/service\"\n\t\"go.opentelemetry.io/collector/service/pipelines\"\n)\n\nfunc TestUnmarshalEmpty(t *testing.T) {\n\tfactories, err := nopFactories()\n\trequire.NoError(t, err)\n\n\t_, err = unmarshal(confmap.New(), factories)\n\tassert.NoError(t, err)\n}\n\nfunc TestUnmarshalEmptyAllSections(t *testing.T) {\n\tfactories, err := nopFactories()\n\trequire.NoError(t, err)\n\n\tconf := confmap.NewFromStringMap(map[string]any{\n\t\t\"receivers\":  nil,\n\t\t\"processors\": nil,\n\t\t\"exporters\":  nil,\n\t\t\"connectors\": nil,\n\t\t\"extensions\": nil,\n\t\t\"service\":    nil,\n\t})\n\tcfg, err := unmarshal(conf, factories)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, fakeTelemetryConfig{}, cfg.Service.Telemetry)\n}\n\nfunc TestUnmarshalUnknownTopLevel(t *testing.T) {\n\tfactories, err := nopFactories()\n\trequire.NoError(t, err)\n\n\tconf := confmap.NewFromStringMap(map[string]any{\n\t\t\"unknown_section\": nil,\n\t})\n\t_, err = unmarshal(conf, factories)\n\tassert.ErrorContains(t, err, \"has invalid keys: unknown_section\")\n}\n\nfunc TestPipelineConfigUnmarshalError(t *testing.T) {\n\ttestCases := []struct {\n\t\t// test case name (also file name containing config yaml)\n\t\tname string\n\t\tconf *confmap.Conf\n\t\t// string that the error must contain\n\t\texpectError string\n\t}{\n\t\t{\n\t\t\tname: \"duplicate-pipeline\",\n\t\t\tconf: confmap.NewFromStringMap(map[string]any{\n\t\t\t\t\"traces/ pipe\": nil,\n\t\t\t\t\"traces /pipe\": nil,\n\t\t\t}),\n\t\t\texpectError: \"duplicate name\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-pipeline-name-after-slash\",\n\t\t\tconf: confmap.NewFromStringMap(map[string]any{\n\t\t\t\t\"metrics/\": nil,\n\t\t\t}),\n\t\t\texpectError: \"in \\\"metrics/\\\" id: the part after / should not be empty\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-pipeline-section\",\n\t\t\tconf: confmap.NewFromStringMap(map[string]any{\n\t\t\t\t\"traces\": map[string]any{\n\t\t\t\t\t\"unknown_section\": nil,\n\t\t\t\t},\n\t\t\t}),\n\t\t\texpectError: \"'[traces]' has invalid keys: unknown_section\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-pipeline-sub-config\",\n\t\t\tconf: confmap.NewFromStringMap(map[string]any{\n\t\t\t\t\"traces\": \"string\",\n\t\t\t}),\n\t\t\texpectError: \"'[traces]' expected a map or struct, got \\\"string\\\"\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-pipeline-type\",\n\t\t\tconf: confmap.NewFromStringMap(map[string]any{\n\t\t\t\t\"/metrics\": nil,\n\t\t\t}),\n\t\t\texpectError: \"in \\\"/metrics\\\" id: the part before / should not be empty\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-sequence-value\",\n\t\t\tconf: confmap.NewFromStringMap(map[string]any{\n\t\t\t\t\"traces\": map[string]any{\n\t\t\t\t\t\"receivers\": map[string]any{\n\t\t\t\t\t\t\"nop\": map[string]any{\n\t\t\t\t\t\t\t\"some\": \"config\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t\texpectError: \"'[traces].receivers' source data must be an array or slice, got map\",\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tpips := new(pipelines.Config)\n\t\t\terr := tt.conf.Unmarshal(&pips)\n\t\t\tassert.ErrorContains(t, err, tt.expectError)\n\t\t})\n\t}\n}\n\nfunc TestServiceUnmarshalError(t *testing.T) {\n\ttestCases := []struct {\n\t\t// test case name (also file name containing config yaml)\n\t\tname string\n\t\tconf *confmap.Conf\n\t\t// string that the error must contain\n\t\texpectError string\n\t}{\n\t\t{\n\t\t\tname: \"invalid-telemetry-unknown-key\",\n\t\t\tconf: confmap.NewFromStringMap(map[string]any{\n\t\t\t\t\"telemetry\": map[string]any{\n\t\t\t\t\t\"unknown\": \"key\",\n\t\t\t\t},\n\t\t\t}),\n\t\t\texpectError: \"decoding failed due to the following error(s):\\n\\n'telemetry' has invalid keys: unknown\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-service-extensions-section\",\n\t\t\tconf: confmap.NewFromStringMap(map[string]any{\n\t\t\t\t\"extensions\": []any{\n\t\t\t\t\tmap[string]any{\n\t\t\t\t\t\t\"nop\": map[string]any{\n\t\t\t\t\t\t\t\"some\": \"config\",\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t\texpectError: \"'extensions[0]' has invalid keys: nop\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-service-section\",\n\t\t\tconf: confmap.NewFromStringMap(map[string]any{\n\t\t\t\t\"unknown_section\": \"string\",\n\t\t\t}),\n\t\t\texpectError: \"has invalid keys: unknown_section\",\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-pipelines-config\",\n\t\t\tconf: confmap.NewFromStringMap(map[string]any{\n\t\t\t\t\"pipelines\": \"string\",\n\t\t\t}),\n\t\t\texpectError: \"'pipelines' expected type 'pipelines.Config', got unconvertible type 'string'\",\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\terr := tt.conf.Unmarshal(&service.Config{\n\t\t\t\tTelemetry: fakeTelemetryConfig{},\n\t\t\t})\n\t\t\trequire.ErrorContains(t, err, tt.expectError)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "pdata/Makefile",
    "content": "include ../Makefile.Common\n"
  },
  {
    "path": "pdata/README.md",
    "content": "# Pipeline data (pdata)\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [stable]: traces, metrics, logs   |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Apkg%2Fpdata%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Apkg%2Fpdata) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Apkg%2Fpdata%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Apkg%2Fpdata) |\n| [Code Owners](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/CONTRIBUTING.md#becoming-a-code-owner)    | [@bogdandrutu](https://www.github.com/bogdandrutu), [@dmitryax](https://www.github.com/dmitryax) |\n\n[stable]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stable\n<!-- end autogenerated section -->\n\nPipeline data (pdata) implements data structures that represent telemetry data in-memory. All data received \nis converted into this format, travels through the pipeline in this format, and is converted from this format by \nexporters when sending.\n\nCurrent implementation primarily uses OTLP protobuf structs as the underlying data structures for many of the \ndeclared structs. We keep a pointer to OTLP protobuf in the \"orig\" member field. This allows efficient translation \nto/from OTLP wire protocol. The underlying data structure is kept private so that we are free to make changes to it \nin the future.\n\nThe pdata API is designed to avoid mutable data sharing and bugs that stem from that. Each pdata instance cannot \ncontain a reference to an object that is used in another pdata instance.\n\n## API naming convention\n\n### Package names\n\nNames of pdata packages don't follow names of the protobuf packages. The pdata has a package per telemetry type \nstarting with `p`, e.g. `ptrace`, and `pcommon` package which includes pdata API for protobuf definitions from \n`common` and `resource` protobuf packages.\n\n### Protobuf message representation in pdata\n\nPipeline data structs SHOULD be based on the names of the underlying OTLP protobuf messages. Data types for \nprotobuf messages defined as part of another message SHOULD include the owner's name as a prefix. The following \nexamples are two pdata structs based on protobuf messages defined at the package level and as part of another \nmessage: \n\n- `pmetric.NumberDataPoint` based on a `NumberDataPoint` protobuf message defined in \n  [metrics.proto](https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/metrics/v1/metrics.proto)\n  package.\n- `pmetric.ExponentialHistogramDataPointBuckets` based on a `Buckets` protobuf message defined in \n  `ExponentialHistogramDataPoint` message of\n  [metrics.proto](https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/metrics/v1/metrics.proto)\n  package. \n\nExceptions to the naming rules are possible, but not encouraged. Another name can be chosen for brevity or if the \nstruct provides a different interface to manipulate the underlying data. The following exceptions are currently \naccepted:\n\n- `plog.Logs` based on `LogsData` protobuf message.\n- `pmetric.Metrics` based on `MetricsData` protobuf message.\n- `ptrace.Traces` based on `TracesData` protobuf message.\n- `pcommon.Slice` based on `ArrayValue` protobuf message.\n- `pcommon.Map` based on `KeyValueList` protobuf message.\n- `pcommon.Value` based on `AnyValue` protobuf message.\n\nEach pdata struct MUST have an initialization function starting with `New` prefix. Usage of zero-initialized values is \nprohibited and can cause a panic. Each pdata struct MUST provide the following methods:\n\n- `MoveTo(<type>)`: moves all the data from one struct instance to another. The destination instance is overwritten and the \n  source instance is re-initialized as a new empty instance.\n- `CopyTo(<type>)`: deep copies all the data from one struct instance to another. The destination instance is \n  overwritten and the source instance is not modified.\n\nEach pdata struct based on a protobuf message SHOULD have getter methods for every protobuf field. Exceptions to\nthis rule are allowed if exposing a field is not desirable in pdata. For example, a deprecated protobuf field MAY\nnot be exposed in pdata. Also, pdata MAY provide a different interface to manipulate protobuf fields without\nexposing them explicitly as is done with `pcommon.Map`.\n\n### Protobuf fields representation in pdata\n\n#### Singular fields\n\nName of a pdata getter methods representing singular protobuf fields SHOULD match the name the protobuf field but \nwritten in CamelCase aligned with Go naming conventions. If a protobuf field is of scalar or enum type, the \ncorresponding pdata struct MUST provide a setter method with `Set` prefix.\n\nSome fields of scalar type in a protobuf message MAY be represented by another pdata type providing an additional \ninterface, for example `pcommon.Timestamp` is another type that wraps `uint64` value and provides an additional\ninterface to work with timestamps. pdata fields returning `pcommon.Timestamp` don't follow the recommended naming\nschema, `Timestamp` word is used instead of `TimeUnixNano` to represent protobuf fields that contain\n`time_unix_nano`, for example `StartTimestamp` pdata field is used for `start_time_unix_nano` protobuf fields.\n\n#### Optional fields\n\nEach optional field in a protobuf message exposed in pdata MUST have the following additional methods: \n- A method starting with `Has` to determine if the field is set. For example, \n  `func (ms HistogramDataPoint) HasMin() bool`.\n- A method starting with `Remove` prefix to remove a value associated with the optional field. For example,\n  `func (ms HistogramDataPoint) RemoveMin()`.\n\n#### OneOf fields\n\nA pdata struct representing a protobuf message with an exposed oneof field MUST provide getter and setter methods for \neach option of the oneof field. Name of each setter and getter SHOULD be called the same as the protobuf oneof field \noptions. The following exception is adopted in pdata for numeric oneof protobuf fields for brevity:\n\n```protobuf\noneof value {\n  double as_double = 4;\n  sfixed64 as_int = 6;\n}\n```\n\nis represented in pdata in a shorter form of the following methods:\n\n```golang\nDoubleValue() float64\nSetDoubleValue(float64)\nIntValue() int64\nSetIntValue(v int64)\n```\n\nIf a oneof field option is another protobuf message, the setter name MUST include `Empty` in its name. Such setter \nMUST set the oneof field to an empty initialized struct and return it. The following conditions define whether the \nname of the oneof field must be included in the setter and getter method names:\n\n1. If a oneof field represents the whole protobuf message, name of the oneof field itself MAY be omitted in setter \n   and getter methods. For example:\n\n```go\nfunc (ms Metric) Sum() Sum\nfunc (ms Metric) SetEmptySum() Sum\n```\n\n2. If a oneof field is relevant only to a particular field of the message, the pdata getter and setter methods MUST \n   include name of the oneof field along with name of the option. For example:\n\n```go\nfunc (ms NumberDataPoint) IntValue() int64\nfunc (ms NumberDataPoint) SetIntValue(v int64)\n```\n\nAdditionally, the pdata struct MUST provide a type getter for every exposed oneof protobuf field. Name of the getter \nMUST be `Type` for oneof fields representing the whole protobuf message (1), or `<oneof field>Type` for oneof fields \nrelevant only to a particular field. The function MUST return an `int32` enum type called `<struct name>Type` for (1) \nand `<struct name><oneof field>Type` for (2). For example:\n\n- `func (ms Metric) Type() MetricType` (1)\n- `func (ms NumberDataPoint) ValueType() NumberDataPointValueType` (2)\n\nThe enum constants MUST be called the same as the type with a suffix named after the oneof option, e.g.: \n\n- `MetricTypeSum` (1)\n- `NumberDataPointValueTypeString` (2)\n\nAn unset oneof protobuf value MUST be represented by a pdata constant with `Empty` suffix, e.g.:\n\n- `MetricTypeEmpty` (1)\n- `NumberDataPointValueTypeEmpty` (2)\n\nThe pdata enum type SHOULD have `String()` method returning a string value of the corresponding oneof field option. \n\n#### Repeated protobuf fields\n\nEach repeated protobuf message field exposed in pdata MUST be represented as another pdata struct that SHOULD be \ncalled the same as the underlying protobuf field with `Slice` suffix. An exception example is `pdata.Map` that \nprovides a different interface to manipulate the underlying protobuf data.\n\n#### Repeated scalar fields\n\nEach repeated scalar protobuf field exposed in pdata MUST be represented as another pdata type wrapping a native go \nslice. Name of the type SHOULD include name of the primitive data type ending with `Slice` suffix, e.g. `UInt64Slice`.\n\n#### Enum fields\n\nEach protobuf enum field exposed in pdata MUST have a type declared with underlying `int64` type. Name of the type \nSHOULD follow the same rules as for struct type names representing protobuf messages:\n\n- If a protobuf enum is defined on the package level, pdata type SHOULD have the same name.\n- If a protobuf enum is defined as part of another message, pdata type SHOULD include the protobuf message name as a \n  prefix.\n\nConstants defined for the pdata int64 type MUST have the same names and numeric values defined in protobuf. Names \nof the constants must be translated from ALL_CAPS_SNAKE_CASE to CamelCase.\n\nThe pdata enum type SHOULD have `String()` method returning a string value for each constant.\n\nExample of a protobuf enum definition in pdata:\n\n```golang\ntype AggregationTemporality int32\nconst (\n\tAggregationTemporalityUnspecified = AggregationTemporality(otlpmetrics.AggregationTemporality_AGGREGATION_TEMPORALITY_UNSPECIFIED)\n\tAggregationTemporalityDelta = AggregationTemporality(otlpmetrics.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA)\n\tAggregationTemporalityCumulative = AggregationTemporality(otlpmetrics.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE)\n)\n```\n\n### Flags\n\nFlags fields are typically defined in protobuf as `uint32` fields representing 32 distinct boolean flags. The \nexposed protobuf flags fields MUST be defined as new types with `uint32` underlying type and called according to \nthe same rules as struct names representing protobuf messages and other enum types. Each pdata flags type MUST have \nan empty variable of the fields type with `Default` prefix. Each flag MUST have a getter method returning a \nparticular flag and a setter method with `With` prefix returning a new instance of the pdata flags type. Any instance \nof the pdata type is immutable since it's just a wrapper over `uint32`.\n\nThe following pdata type is used for log record flags field:\n\n```golang\ntype LogRecordFlags uint32\nvar DefaultLogRecordFlags = LogRecordFlags(0)\nfunc (ms LogRecordFlags) IsSampled() bool\nfunc (ms LogRecordFlags) WithIsSampled(b bool) LogRecordFlags \n```\n\n### Examples\n\nThe following protobuf message: \n\n```protobuf\nmessage NumberDataPoint {\n  reserved 1;\n  repeated opentelemetry.proto.common.v1.KeyValue attributes = 7;\n  fixed64 start_time_unix_nano = 2;\n  fixed64 time_unix_nano = 3;\n  oneof value {\n    double as_double = 4;\n    sfixed64 as_int = 6;\n  }\n  repeated Exemplar exemplars = 5;\n  uint32 flags = 8;\n}\n```\n\nis represented by the following pdata API\n\n```go\ntype NumberDataPoint\nfunc NewNumberDataPoint() NumberDataPoint \nfunc (ms NumberDataPoint) MoveTo(dest NumberDataPoint)\nfunc (ms NumberDataPoint) CopyTo(dest NumberDataPoint)\nfunc (ms NumberDataPoint) Attributes() pcommon.Map\nfunc (ms NumberDataPoint) StartTimestamp() pcommon.Timestamp\nfunc (ms NumberDataPoint) SetStartTimestamp(v pcommon.Timestamp)\nfunc (ms NumberDataPoint) Timestamp() pcommon.Timestamp\nfunc (ms NumberDataPoint) SetTimestamp(v pcommon.Timestamp)\nfunc (ms NumberDataPoint) ValueType() NumberDataPointValueType\nfunc (ms NumberDataPoint) DoubleValue() float64\nfunc (ms NumberDataPoint) SetDoubleValue(v float64)\nfunc (ms NumberDataPoint) IntValue() int64\nfunc (ms NumberDataPoint) SetIntValue(v int64)\nfunc (ms NumberDataPoint) Exemplars() ExemplarSlice \nfunc (ms NumberDataPoint) Flags() DataPointFlags\nfunc (ms NumberDataPoint) SetFlags(v DataPointFlags)\n```\n"
  },
  {
    "path": "pdata/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\n// Package pdata provides the data model definitions for all supported pipeline data.\npackage pdata // import \"go.opentelemetry.io/collector/pdata\"\n"
  },
  {
    "path": "pdata/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# pdata\n\n## Feature Gates\n\nThis component has the following feature gates:\n\n| Feature Gate | Stage | Description | From Version | To Version | Reference |\n| ------------ | ----- | ----------- | ------------ | ---------- | --------- |\n| `pdata.useCustomProtoEncoding` | stable | When enabled, enable custom proto encoding. This is a required step to enable featuregate pdata.useProtoPooling. | v0.133.0 | v0.137.0 | [Link](https://github.com/open-telemetry/opentelemetry-collector/issues/13631) |\n| `pdata.useProtoPooling` | alpha | When enabled, enable using local memory pools for underlying data that the pdata messages are pushed to. | v0.133.0 | N/A | [Link](https://github.com/open-telemetry/opentelemetry-collector/issues/13631) |\n\nFor more information about feature gates, see the [Feature Gates](https://github.com/open-telemetry/opentelemetry-collector/blob/main/featuregate/README.md) documentation.\n"
  },
  {
    "path": "pdata/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage pdata\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "pdata/go.mod",
    "content": "module go.opentelemetry.io/collector/pdata\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/json-iterator/go v1.1.12\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/featuregate v1.54.0\n\tgo.opentelemetry.io/collector/internal/testutil v0.148.0\n\tgo.opentelemetry.io/proto/slim/otlp v1.10.0\n\tgo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0\n\tgo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/multierr v1.11.0\n\tgoogle.golang.org/grpc v1.79.3\n\tgoogle.golang.org/protobuf v1.36.11\n)\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nretract (\n\tv1.0.0-rc10 // RC version scheme discovered to be alphabetical, use v1.0.0-rcv0011 instead\n\tv0.57.1 // Release failed, use v0.57.2\n\tv0.57.0 // Release failed, use v0.57.2\n)\n\nreplace go.opentelemetry.io/collector/featuregate => ../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../internal/testutil\n"
  },
  {
    "path": "pdata/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.39.0 h1:8yPrr/S0ND9QEfTfdP9V+SiwT4E0G7Y5MO7p85nis48=\ngo.opentelemetry.io/otel v1.39.0/go.mod h1:kLlFTywNWrFyEdH0oj2xK0bFYZtHRYUdv1NklR/tgc8=\ngo.opentelemetry.io/otel/metric v1.39.0 h1:d1UzonvEZriVfpNKEVmHXbdf909uGTOQjA0HF0Ls5Q0=\ngo.opentelemetry.io/otel/metric v1.39.0/go.mod h1:jrZSWL33sD7bBxg1xjrqyDjnuzTUB0x1nBERXd7Ftcs=\ngo.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18=\ngo.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE=\ngo.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8=\ngo.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew=\ngo.opentelemetry.io/otel/trace v1.39.0 h1:2d2vfpEDmCJ5zVYz7ijaJdOF59xLomrvj7bjt6/qCJI=\ngo.opentelemetry.io/otel/trace v1.39.0/go.mod h1:88w4/PnZSazkGzz/w84VHpQafiU4EtqqlVdxWy+rNOA=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=\ngonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "pdata/internal/.gitignore",
    "content": ".patched-otlp-proto\nopentelemetry-proto\n"
  },
  {
    "path": "pdata/internal/bytesid.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/pdata/internal\"\n\nimport (\n\t\"encoding/hex\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n)\n\n// unmarshalJSON inflates trace id from hex string, possibly enclosed in quotes.\n// Called by Protobuf JSON deserialization.\nfunc unmarshalJSON(dst []byte, iter *json.Iterator) {\n\tsrc := iter.ReadStringAsSlice()\n\tif len(src) == 0 {\n\t\treturn\n\t}\n\n\tif len(dst) != hex.DecodedLen(len(src)) {\n\t\titer.ReportError(\"ID.UnmarshalJSONIter\", \"length mismatch\")\n\t\treturn\n\t}\n\n\t_, err := hex.Decode(dst, src)\n\tif err != nil {\n\t\titer.ReportError(\"ID.UnmarshalJSONIter\", err.Error())\n\t\treturn\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/bytesid_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n)\n\nfunc TestUnmarshalJSON(t *testing.T) {\n\titer := json.BorrowIterator(nil)\n\tdefer json.ReturnIterator(iter)\n\n\tid := [16]byte{}\n\tunmarshalJSON(id[:], iter.ResetBytes([]byte(`\"\"`)))\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, [16]byte{}, id)\n\n\tidBytes := [16]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}\n\tunmarshalJSON(id[:], iter.ResetBytes([]byte(`\"12345678123456781234567812345678\"`)))\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, idBytes, id)\n\n\tunmarshalJSON(id[:], iter.ResetBytes([]byte(`\"nothex\"`)))\n\trequire.Error(t, iter.Error())\n\n\tunmarshalJSON(id[:], iter.ResetBytes([]byte(`\"1\"`)))\n\trequire.Error(t, iter.Error())\n\n\tunmarshalJSON(id[:], iter.ResetBytes([]byte(`\"123\"`)))\n\trequire.Error(t, iter.Error())\n\n\tunmarshalJSON(id[:], iter.ResetBytes([]byte(`\"`)))\n\trequire.Error(t, iter.Error())\n}\n"
  },
  {
    "path": "pdata/internal/config.schema.yaml",
    "content": "$defs:\n  aggregation_temporality:\n    description: AggregationTemporality defines how a metric aggregator reports aggregated values. It describes how those values relate to the time interval over which they are aggregated.\n    type: integer\n    x-customType: int32\n  profile_id:\n    description: ProfileID is a custom data type that is used for all profile_id fields in OTLP Protobuf messages.\n    type: array\n    items:\n      type: string\n      x-customType: byte\n  severity_number:\n    description: SeverityNumber represent possible values for LogRecord.SeverityNumber\n    type: integer\n    x-customType: int32\n  span_id:\n    description: SpanID is a custom data type that is used for all span_id fields in OTLP Protobuf messages.\n    type: array\n    items:\n      type: string\n      x-customType: byte\n  span_kind:\n    description: SpanKind is the type of span. Can be used to specify additional relationships between spans in addition to a parent/child relationship.\n    type: integer\n    x-customType: int32\n  status_code:\n    description: StatusCode is the status of the span, for the semantics of codes see https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#set-status\n    type: integer\n    x-customType: int32\n  trace_id:\n    description: TraceID is a custom data type that is used for all trace_id fields in OTLP Protobuf messages.\n    type: array\n    items:\n      type: string\n      x-customType: byte\n"
  },
  {
    "path": "pdata/internal/generated_enum_aggregationtemporality.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nconst (\n\tAggregationTemporality_AGGREGATION_TEMPORALITY_UNSPECIFIED = AggregationTemporality(0)\n\tAggregationTemporality_AGGREGATION_TEMPORALITY_DELTA       = AggregationTemporality(1)\n\tAggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE  = AggregationTemporality(2)\n)\n\n// AggregationTemporality defines how a metric aggregator reports aggregated values.\n// It describes how those values relate to the time interval over which they are aggregated.\ntype AggregationTemporality int32\n\nvar AggregationTemporality_name = map[int32]string{\n\t0: \"AGGREGATION_TEMPORALITY_UNSPECIFIED\",\n\t1: \"AGGREGATION_TEMPORALITY_DELTA\",\n\t2: \"AGGREGATION_TEMPORALITY_CUMULATIVE\",\n}\n\nvar AggregationTemporality_value = map[string]int32{\n\t\"AGGREGATION_TEMPORALITY_UNSPECIFIED\": 0,\n\t\"AGGREGATION_TEMPORALITY_DELTA\":       1,\n\t\"AGGREGATION_TEMPORALITY_CUMULATIVE\":  2,\n}\n"
  },
  {
    "path": "pdata/internal/generated_enum_severitynumber.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nconst (\n\tSeverityNumber_SEVERITY_NUMBER_UNSPECIFIED = SeverityNumber(0)\n\tSeverityNumber_SEVERITY_NUMBER_TRACE       = SeverityNumber(1)\n\tSeverityNumber_SEVERITY_NUMBER_TRACE2      = SeverityNumber(2)\n\tSeverityNumber_SEVERITY_NUMBER_TRACE3      = SeverityNumber(3)\n\tSeverityNumber_SEVERITY_NUMBER_TRACE4      = SeverityNumber(4)\n\tSeverityNumber_SEVERITY_NUMBER_DEBUG       = SeverityNumber(5)\n\tSeverityNumber_SEVERITY_NUMBER_DEBUG2      = SeverityNumber(6)\n\tSeverityNumber_SEVERITY_NUMBER_DEBUG3      = SeverityNumber(7)\n\tSeverityNumber_SEVERITY_NUMBER_DEBUG4      = SeverityNumber(8)\n\tSeverityNumber_SEVERITY_NUMBER_INFO        = SeverityNumber(9)\n\tSeverityNumber_SEVERITY_NUMBER_INFO2       = SeverityNumber(10)\n\tSeverityNumber_SEVERITY_NUMBER_INFO3       = SeverityNumber(11)\n\tSeverityNumber_SEVERITY_NUMBER_INFO4       = SeverityNumber(12)\n\tSeverityNumber_SEVERITY_NUMBER_WARN        = SeverityNumber(13)\n\tSeverityNumber_SEVERITY_NUMBER_WARN2       = SeverityNumber(14)\n\tSeverityNumber_SEVERITY_NUMBER_WARN3       = SeverityNumber(15)\n\tSeverityNumber_SEVERITY_NUMBER_WARN4       = SeverityNumber(16)\n\tSeverityNumber_SEVERITY_NUMBER_ERROR       = SeverityNumber(17)\n\tSeverityNumber_SEVERITY_NUMBER_ERROR2      = SeverityNumber(18)\n\tSeverityNumber_SEVERITY_NUMBER_ERROR3      = SeverityNumber(19)\n\tSeverityNumber_SEVERITY_NUMBER_ERROR4      = SeverityNumber(20)\n\tSeverityNumber_SEVERITY_NUMBER_FATAL       = SeverityNumber(21)\n\tSeverityNumber_SEVERITY_NUMBER_FATAL2      = SeverityNumber(22)\n\tSeverityNumber_SEVERITY_NUMBER_FATAL3      = SeverityNumber(23)\n\tSeverityNumber_SEVERITY_NUMBER_FATAL4      = SeverityNumber(24)\n)\n\n// SeverityNumber represent possible values for LogRecord.SeverityNumber\ntype SeverityNumber int32\n\nvar SeverityNumber_name = map[int32]string{\n\t0:  \"SEVERITY_NUMBER_UNSPECIFIED\",\n\t1:  \"SEVERITY_NUMBER_TRACE \",\n\t2:  \"SEVERITY_NUMBER_TRACE2\",\n\t3:  \"SEVERITY_NUMBER_TRACE3\",\n\t4:  \"SEVERITY_NUMBER_TRACE4\",\n\t5:  \"SEVERITY_NUMBER_DEBUG\",\n\t6:  \"SEVERITY_NUMBER_DEBUG2\",\n\t7:  \"SEVERITY_NUMBER_DEBUG3\",\n\t8:  \"SEVERITY_NUMBER_DEBUG4\",\n\t9:  \"SEVERITY_NUMBER_INFO\",\n\t10: \"SEVERITY_NUMBER_INFO2\",\n\t11: \"SEVERITY_NUMBER_INFO3\",\n\t12: \"SEVERITY_NUMBER_INFO4\",\n\t13: \"SEVERITY_NUMBER_WARN\",\n\t14: \"SEVERITY_NUMBER_WARN2\",\n\t15: \"SEVERITY_NUMBER_WARN3\",\n\t16: \"SEVERITY_NUMBER_WARN4\",\n\t17: \"SEVERITY_NUMBER_ERROR\",\n\t18: \"SEVERITY_NUMBER_ERROR2\",\n\t19: \"SEVERITY_NUMBER_ERROR3\",\n\t20: \"SEVERITY_NUMBER_ERROR4\",\n\t21: \"SEVERITY_NUMBER_FATAL\",\n\t22: \"SEVERITY_NUMBER_FATAL2\",\n\t23: \"SEVERITY_NUMBER_FATAL3\",\n\t24: \"SEVERITY_NUMBER_FATAL4\",\n}\n\nvar SeverityNumber_value = map[string]int32{\n\t\"SEVERITY_NUMBER_UNSPECIFIED\": 0,\n\t\"SEVERITY_NUMBER_TRACE \":      1,\n\t\"SEVERITY_NUMBER_TRACE2\":      2,\n\t\"SEVERITY_NUMBER_TRACE3\":      3,\n\t\"SEVERITY_NUMBER_TRACE4\":      4,\n\t\"SEVERITY_NUMBER_DEBUG\":       5,\n\t\"SEVERITY_NUMBER_DEBUG2\":      6,\n\t\"SEVERITY_NUMBER_DEBUG3\":      7,\n\t\"SEVERITY_NUMBER_DEBUG4\":      8,\n\t\"SEVERITY_NUMBER_INFO\":        9,\n\t\"SEVERITY_NUMBER_INFO2\":       10,\n\t\"SEVERITY_NUMBER_INFO3\":       11,\n\t\"SEVERITY_NUMBER_INFO4\":       12,\n\t\"SEVERITY_NUMBER_WARN\":        13,\n\t\"SEVERITY_NUMBER_WARN2\":       14,\n\t\"SEVERITY_NUMBER_WARN3\":       15,\n\t\"SEVERITY_NUMBER_WARN4\":       16,\n\t\"SEVERITY_NUMBER_ERROR\":       17,\n\t\"SEVERITY_NUMBER_ERROR2\":      18,\n\t\"SEVERITY_NUMBER_ERROR3\":      19,\n\t\"SEVERITY_NUMBER_ERROR4\":      20,\n\t\"SEVERITY_NUMBER_FATAL\":       21,\n\t\"SEVERITY_NUMBER_FATAL2\":      22,\n\t\"SEVERITY_NUMBER_FATAL3\":      23,\n\t\"SEVERITY_NUMBER_FATAL4\":      24,\n}\n"
  },
  {
    "path": "pdata/internal/generated_enum_spankind.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nconst (\n\tSpanKind_SPAN_KIND_UNSPECIFIED = SpanKind(0)\n\tSpanKind_SPAN_KIND_INTERNAL    = SpanKind(1)\n\tSpanKind_SPAN_KIND_SERVER      = SpanKind(2)\n\tSpanKind_SPAN_KIND_CLIENT      = SpanKind(3)\n\tSpanKind_SPAN_KIND_PRODUCER    = SpanKind(4)\n\tSpanKind_SPAN_KIND_CONSUMER    = SpanKind(5)\n)\n\n// SpanKind is the type of span.\n// Can be used to specify additional relationships between spans in addition to a parent/child relationship.\ntype SpanKind int32\n\nvar SpanKind_name = map[int32]string{\n\t0: \"SPAN_KIND_UNSPECIFIED\",\n\t1: \"SPAN_KIND_INTERNAL\",\n\t2: \"SPAN_KIND_SERVER\",\n\t3: \"SPAN_KIND_CLIENT\",\n\t4: \"SPAN_KIND_PRODUCER\",\n\t5: \"SPAN_KIND_CONSUMER\",\n}\n\nvar SpanKind_value = map[string]int32{\n\t\"SPAN_KIND_UNSPECIFIED\": 0,\n\t\"SPAN_KIND_INTERNAL\":    1,\n\t\"SPAN_KIND_SERVER\":      2,\n\t\"SPAN_KIND_CLIENT\":      3,\n\t\"SPAN_KIND_PRODUCER\":    4,\n\t\"SPAN_KIND_CONSUMER\":    5,\n}\n"
  },
  {
    "path": "pdata/internal/generated_enum_statuscode.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nconst (\n\tStatusCode_STATUS_CODE_UNSET = StatusCode(0)\n\tStatusCode_STATUS_CODE_OK    = StatusCode(1)\n\tStatusCode_STATUS_CODE_ERROR = StatusCode(2)\n)\n\n// StatusCode is the status of the span, for the semantics of codes see\n// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#set-status\ntype StatusCode int32\n\nvar StatusCode_name = map[int32]string{\n\t0: \"STATUS_CODE_UNSET\",\n\t1: \"STATUS_CODE_OK\",\n\t2: \"STATUS_CODE_ERROR\",\n}\n\nvar StatusCode_value = map[string]int32{\n\t\"STATUS_CODE_UNSET\": 0,\n\t\"STATUS_CODE_OK\":    1,\n\t\"STATUS_CODE_ERROR\": 2,\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_anyvalue.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"math\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\nfunc (m *AnyValue) GetValue() any {\n\tif m != nil {\n\t\treturn m.Value\n\t}\n\treturn nil\n}\n\ntype AnyValue_StringValue struct {\n\tStringValue string\n}\n\nfunc (m *AnyValue) GetStringValue() string {\n\tif v, ok := m.GetValue().(*AnyValue_StringValue); ok {\n\t\treturn v.StringValue\n\t}\n\treturn \"\"\n}\n\ntype AnyValue_BoolValue struct {\n\tBoolValue bool\n}\n\nfunc (m *AnyValue) GetBoolValue() bool {\n\tif v, ok := m.GetValue().(*AnyValue_BoolValue); ok {\n\t\treturn v.BoolValue\n\t}\n\treturn false\n}\n\ntype AnyValue_IntValue struct {\n\tIntValue int64\n}\n\nfunc (m *AnyValue) GetIntValue() int64 {\n\tif v, ok := m.GetValue().(*AnyValue_IntValue); ok {\n\t\treturn v.IntValue\n\t}\n\treturn int64(0)\n}\n\ntype AnyValue_DoubleValue struct {\n\tDoubleValue float64\n}\n\nfunc (m *AnyValue) GetDoubleValue() float64 {\n\tif v, ok := m.GetValue().(*AnyValue_DoubleValue); ok {\n\t\treturn v.DoubleValue\n\t}\n\treturn float64(0)\n}\n\ntype AnyValue_ArrayValue struct {\n\tArrayValue *ArrayValue\n}\n\nfunc (m *AnyValue) GetArrayValue() *ArrayValue {\n\tif v, ok := m.GetValue().(*AnyValue_ArrayValue); ok {\n\t\treturn v.ArrayValue\n\t}\n\treturn nil\n}\n\ntype AnyValue_KvlistValue struct {\n\tKvlistValue *KeyValueList\n}\n\nfunc (m *AnyValue) GetKvlistValue() *KeyValueList {\n\tif v, ok := m.GetValue().(*AnyValue_KvlistValue); ok {\n\t\treturn v.KvlistValue\n\t}\n\treturn nil\n}\n\ntype AnyValue_BytesValue struct {\n\tBytesValue []byte\n}\n\nfunc (m *AnyValue) GetBytesValue() []byte {\n\tif v, ok := m.GetValue().(*AnyValue_BytesValue); ok {\n\t\treturn v.BytesValue\n\t}\n\treturn nil\n}\n\ntype AnyValue_StringValueStrindex struct {\n\tStringValueStrindex int32\n}\n\nfunc (m *AnyValue) GetStringValueStrindex() int32 {\n\tif v, ok := m.GetValue().(*AnyValue_StringValueStrindex); ok {\n\t\treturn v.StringValueStrindex\n\t}\n\treturn int32(0)\n}\n\ntype AnyValue struct {\n\tValue any\n}\n\nvar (\n\tprotoPoolAnyValue = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &AnyValue{}\n\t\t},\n\t}\n\n\tProtoPoolAnyValue_StringValue = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &AnyValue_StringValue{}\n\t\t},\n\t}\n\n\tProtoPoolAnyValue_BoolValue = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &AnyValue_BoolValue{}\n\t\t},\n\t}\n\n\tProtoPoolAnyValue_IntValue = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &AnyValue_IntValue{}\n\t\t},\n\t}\n\n\tProtoPoolAnyValue_DoubleValue = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &AnyValue_DoubleValue{}\n\t\t},\n\t}\n\n\tProtoPoolAnyValue_ArrayValue = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &AnyValue_ArrayValue{}\n\t\t},\n\t}\n\n\tProtoPoolAnyValue_KvlistValue = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &AnyValue_KvlistValue{}\n\t\t},\n\t}\n\n\tProtoPoolAnyValue_BytesValue = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &AnyValue_BytesValue{}\n\t\t},\n\t}\n\n\tProtoPoolAnyValue_StringValueStrindex = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &AnyValue_StringValueStrindex{}\n\t\t},\n\t}\n)\n\nfunc NewAnyValue() *AnyValue {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &AnyValue{}\n\t}\n\treturn protoPoolAnyValue.Get().(*AnyValue)\n}\n\nfunc DeleteAnyValue(orig *AnyValue, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tswitch ov := orig.Value.(type) {\n\tcase *AnyValue_StringValue:\n\t\tif metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov.StringValue = \"\"\n\t\t\tProtoPoolAnyValue_StringValue.Put(ov)\n\t\t}\n\tcase *AnyValue_BoolValue:\n\t\tif metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov.BoolValue = false\n\t\t\tProtoPoolAnyValue_BoolValue.Put(ov)\n\t\t}\n\tcase *AnyValue_IntValue:\n\t\tif metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov.IntValue = int64(0)\n\t\t\tProtoPoolAnyValue_IntValue.Put(ov)\n\t\t}\n\tcase *AnyValue_DoubleValue:\n\t\tif metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov.DoubleValue = float64(0)\n\t\t\tProtoPoolAnyValue_DoubleValue.Put(ov)\n\t\t}\n\tcase *AnyValue_ArrayValue:\n\t\tDeleteArrayValue(ov.ArrayValue, true)\n\t\tov.ArrayValue = nil\n\t\tProtoPoolAnyValue_ArrayValue.Put(ov)\n\tcase *AnyValue_KvlistValue:\n\t\tDeleteKeyValueList(ov.KvlistValue, true)\n\t\tov.KvlistValue = nil\n\t\tProtoPoolAnyValue_KvlistValue.Put(ov)\n\tcase *AnyValue_BytesValue:\n\t\tif metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov.BytesValue = nil\n\t\t\tProtoPoolAnyValue_BytesValue.Put(ov)\n\t\t}\n\tcase *AnyValue_StringValueStrindex:\n\t\tif metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov.StringValueStrindex = int32(0)\n\t\t\tProtoPoolAnyValue_StringValueStrindex.Put(ov)\n\t\t}\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolAnyValue.Put(orig)\n\t}\n}\n\nfunc CopyAnyValue(dest, src *AnyValue) *AnyValue {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewAnyValue()\n\t}\n\tswitch t := src.Value.(type) {\n\tcase *AnyValue_StringValue:\n\t\tvar ov *AnyValue_StringValue\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &AnyValue_StringValue{}\n\t\t} else {\n\t\t\tov = ProtoPoolAnyValue_StringValue.Get().(*AnyValue_StringValue)\n\t\t}\n\t\tov.StringValue = t.StringValue\n\t\tdest.Value = ov\n\n\tcase *AnyValue_BoolValue:\n\t\tvar ov *AnyValue_BoolValue\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &AnyValue_BoolValue{}\n\t\t} else {\n\t\t\tov = ProtoPoolAnyValue_BoolValue.Get().(*AnyValue_BoolValue)\n\t\t}\n\t\tov.BoolValue = t.BoolValue\n\t\tdest.Value = ov\n\n\tcase *AnyValue_IntValue:\n\t\tvar ov *AnyValue_IntValue\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &AnyValue_IntValue{}\n\t\t} else {\n\t\t\tov = ProtoPoolAnyValue_IntValue.Get().(*AnyValue_IntValue)\n\t\t}\n\t\tov.IntValue = t.IntValue\n\t\tdest.Value = ov\n\n\tcase *AnyValue_DoubleValue:\n\t\tvar ov *AnyValue_DoubleValue\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &AnyValue_DoubleValue{}\n\t\t} else {\n\t\t\tov = ProtoPoolAnyValue_DoubleValue.Get().(*AnyValue_DoubleValue)\n\t\t}\n\t\tov.DoubleValue = t.DoubleValue\n\t\tdest.Value = ov\n\n\tcase *AnyValue_ArrayValue:\n\t\tvar ov *AnyValue_ArrayValue\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &AnyValue_ArrayValue{}\n\t\t} else {\n\t\t\tov = ProtoPoolAnyValue_ArrayValue.Get().(*AnyValue_ArrayValue)\n\t\t}\n\t\tov.ArrayValue = NewArrayValue()\n\t\tCopyArrayValue(ov.ArrayValue, t.ArrayValue)\n\t\tdest.Value = ov\n\n\tcase *AnyValue_KvlistValue:\n\t\tvar ov *AnyValue_KvlistValue\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &AnyValue_KvlistValue{}\n\t\t} else {\n\t\t\tov = ProtoPoolAnyValue_KvlistValue.Get().(*AnyValue_KvlistValue)\n\t\t}\n\t\tov.KvlistValue = NewKeyValueList()\n\t\tCopyKeyValueList(ov.KvlistValue, t.KvlistValue)\n\t\tdest.Value = ov\n\n\tcase *AnyValue_BytesValue:\n\t\tvar ov *AnyValue_BytesValue\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &AnyValue_BytesValue{}\n\t\t} else {\n\t\t\tov = ProtoPoolAnyValue_BytesValue.Get().(*AnyValue_BytesValue)\n\t\t}\n\t\tov.BytesValue = t.BytesValue\n\t\tdest.Value = ov\n\n\tcase *AnyValue_StringValueStrindex:\n\t\tvar ov *AnyValue_StringValueStrindex\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &AnyValue_StringValueStrindex{}\n\t\t} else {\n\t\t\tov = ProtoPoolAnyValue_StringValueStrindex.Get().(*AnyValue_StringValueStrindex)\n\t\t}\n\t\tov.StringValueStrindex = t.StringValueStrindex\n\t\tdest.Value = ov\n\n\tdefault:\n\t\tdest.Value = nil\n\t}\n\n\treturn dest\n}\n\nfunc CopyAnyValueSlice(dest, src []AnyValue) []AnyValue {\n\tvar newDest []AnyValue\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]AnyValue, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteAnyValue(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyAnyValue(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyAnyValuePtrSlice(dest, src []*AnyValue) []*AnyValue {\n\tvar newDest []*AnyValue\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*AnyValue, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewAnyValue()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteAnyValue(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewAnyValue()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyAnyValue(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *AnyValue) Reset() {\n\t*orig = AnyValue{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *AnyValue) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tswitch orig := orig.Value.(type) {\n\tcase *AnyValue_StringValue:\n\t\tdest.WriteObjectField(\"stringValue\")\n\t\tdest.WriteString(orig.StringValue)\n\tcase *AnyValue_BoolValue:\n\t\tdest.WriteObjectField(\"boolValue\")\n\t\tdest.WriteBool(orig.BoolValue)\n\tcase *AnyValue_IntValue:\n\t\tdest.WriteObjectField(\"intValue\")\n\t\tdest.WriteInt64(orig.IntValue)\n\tcase *AnyValue_DoubleValue:\n\t\tdest.WriteObjectField(\"doubleValue\")\n\t\tdest.WriteFloat64(orig.DoubleValue)\n\tcase *AnyValue_ArrayValue:\n\t\tif orig.ArrayValue != nil {\n\t\t\tdest.WriteObjectField(\"arrayValue\")\n\t\t\torig.ArrayValue.MarshalJSON(dest)\n\t\t}\n\tcase *AnyValue_KvlistValue:\n\t\tif orig.KvlistValue != nil {\n\t\t\tdest.WriteObjectField(\"kvlistValue\")\n\t\t\torig.KvlistValue.MarshalJSON(dest)\n\t\t}\n\tcase *AnyValue_BytesValue:\n\n\t\tdest.WriteObjectField(\"bytesValue\")\n\t\tdest.WriteBytes(orig.BytesValue)\n\tcase *AnyValue_StringValueStrindex:\n\t\tdest.WriteObjectField(\"stringValueStrindex\")\n\t\tdest.WriteInt32(orig.StringValueStrindex)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *AnyValue) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\n\t\tcase \"stringValue\", \"string_value\":\n\t\t\t{\n\t\t\t\tvar ov *AnyValue_StringValue\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &AnyValue_StringValue{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolAnyValue_StringValue.Get().(*AnyValue_StringValue)\n\t\t\t\t}\n\t\t\t\tov.StringValue = iter.ReadString()\n\t\t\t\torig.Value = ov\n\t\t\t}\n\t\tcase \"boolValue\", \"bool_value\":\n\t\t\t{\n\t\t\t\tvar ov *AnyValue_BoolValue\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &AnyValue_BoolValue{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolAnyValue_BoolValue.Get().(*AnyValue_BoolValue)\n\t\t\t\t}\n\t\t\t\tov.BoolValue = iter.ReadBool()\n\t\t\t\torig.Value = ov\n\t\t\t}\n\t\tcase \"intValue\", \"int_value\":\n\t\t\t{\n\t\t\t\tvar ov *AnyValue_IntValue\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &AnyValue_IntValue{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolAnyValue_IntValue.Get().(*AnyValue_IntValue)\n\t\t\t\t}\n\t\t\t\tov.IntValue = iter.ReadInt64()\n\t\t\t\torig.Value = ov\n\t\t\t}\n\t\tcase \"doubleValue\", \"double_value\":\n\t\t\t{\n\t\t\t\tvar ov *AnyValue_DoubleValue\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &AnyValue_DoubleValue{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolAnyValue_DoubleValue.Get().(*AnyValue_DoubleValue)\n\t\t\t\t}\n\t\t\t\tov.DoubleValue = iter.ReadFloat64()\n\t\t\t\torig.Value = ov\n\t\t\t}\n\t\tcase \"arrayValue\", \"array_value\":\n\t\t\t{\n\t\t\t\tvar ov *AnyValue_ArrayValue\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &AnyValue_ArrayValue{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolAnyValue_ArrayValue.Get().(*AnyValue_ArrayValue)\n\t\t\t\t}\n\t\t\t\tov.ArrayValue = NewArrayValue()\n\t\t\t\tov.ArrayValue.UnmarshalJSON(iter)\n\t\t\t\torig.Value = ov\n\t\t\t}\n\t\tcase \"kvlistValue\", \"kvlist_value\":\n\t\t\t{\n\t\t\t\tvar ov *AnyValue_KvlistValue\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &AnyValue_KvlistValue{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolAnyValue_KvlistValue.Get().(*AnyValue_KvlistValue)\n\t\t\t\t}\n\t\t\t\tov.KvlistValue = NewKeyValueList()\n\t\t\t\tov.KvlistValue.UnmarshalJSON(iter)\n\t\t\t\torig.Value = ov\n\t\t\t}\n\t\tcase \"bytesValue\", \"bytes_value\":\n\t\t\t{\n\t\t\t\tvar ov *AnyValue_BytesValue\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &AnyValue_BytesValue{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolAnyValue_BytesValue.Get().(*AnyValue_BytesValue)\n\t\t\t\t}\n\t\t\t\tov.BytesValue = iter.ReadBytes()\n\t\t\t\torig.Value = ov\n\t\t\t}\n\t\tcase \"stringValueStrindex\", \"string_value_strindex\":\n\t\t\t{\n\t\t\t\tvar ov *AnyValue_StringValueStrindex\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &AnyValue_StringValueStrindex{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolAnyValue_StringValueStrindex.Get().(*AnyValue_StringValueStrindex)\n\t\t\t\t}\n\t\t\t\tov.StringValueStrindex = iter.ReadInt32()\n\t\t\t\torig.Value = ov\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *AnyValue) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tswitch orig := orig.Value.(type) {\n\tcase nil:\n\t\t_ = orig\n\t\tbreak\n\tcase *AnyValue_StringValue:\n\t\tl = len(orig.StringValue)\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\tcase *AnyValue_BoolValue:\n\n\t\tn += 2\n\tcase *AnyValue_IntValue:\n\n\t\tn += 1 + proto.Sov(uint64(orig.IntValue))\n\tcase *AnyValue_DoubleValue:\n\n\t\tn += 9\n\tcase *AnyValue_ArrayValue:\n\t\tif orig.ArrayValue != nil {\n\t\t\tl = orig.ArrayValue.SizeProto()\n\t\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t\t}\n\tcase *AnyValue_KvlistValue:\n\t\tif orig.KvlistValue != nil {\n\t\t\tl = orig.KvlistValue.SizeProto()\n\t\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t\t}\n\tcase *AnyValue_BytesValue:\n\t\tl = len(orig.BytesValue)\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\tcase *AnyValue_StringValueStrindex:\n\n\t\tn += 1 + proto.Sov(uint64(orig.StringValueStrindex))\n\t}\n\treturn n\n}\n\nfunc (orig *AnyValue) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tswitch orig := orig.Value.(type) {\n\tcase *AnyValue_StringValue:\n\t\tl = len(orig.StringValue)\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.StringValue)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\n\tcase *AnyValue_BoolValue:\n\t\tpos--\n\t\tif orig.BoolValue {\n\t\t\tbuf[pos] = 1\n\t\t} else {\n\t\t\tbuf[pos] = 0\n\t\t}\n\t\tpos--\n\t\tbuf[pos] = 0x10\n\n\tcase *AnyValue_IntValue:\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.IntValue))\n\t\tpos--\n\t\tbuf[pos] = 0x18\n\n\tcase *AnyValue_DoubleValue:\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.DoubleValue))\n\t\tpos--\n\t\tbuf[pos] = 0x21\n\n\tcase *AnyValue_ArrayValue:\n\t\tif orig.ArrayValue != nil {\n\t\t\tl = orig.ArrayValue.MarshalProto(buf[:pos])\n\t\t\tpos -= l\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\t\tpos--\n\t\t\tbuf[pos] = 0x2a\n\t\t}\n\tcase *AnyValue_KvlistValue:\n\t\tif orig.KvlistValue != nil {\n\t\t\tl = orig.KvlistValue.MarshalProto(buf[:pos])\n\t\t\tpos -= l\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\t\tpos--\n\t\t\tbuf[pos] = 0x32\n\t\t}\n\tcase *AnyValue_BytesValue:\n\t\tl = len(orig.BytesValue)\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.BytesValue)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x3a\n\n\tcase *AnyValue_StringValueStrindex:\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.StringValueStrindex))\n\t\tpos--\n\t\tbuf[pos] = 0x40\n\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *AnyValue) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field StringValue\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tvar ov *AnyValue_StringValue\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &AnyValue_StringValue{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolAnyValue_StringValue.Get().(*AnyValue_StringValue)\n\t\t\t}\n\t\t\tov.StringValue = string(buf[startPos:pos])\n\t\t\torig.Value = ov\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field BoolValue\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvar ov *AnyValue_BoolValue\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &AnyValue_BoolValue{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolAnyValue_BoolValue.Get().(*AnyValue_BoolValue)\n\t\t\t}\n\t\t\tov.BoolValue = num != 0\n\t\t\torig.Value = ov\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field IntValue\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvar ov *AnyValue_IntValue\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &AnyValue_IntValue{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolAnyValue_IntValue.Get().(*AnyValue_IntValue)\n\t\t\t}\n\t\t\tov.IntValue = int64(num)\n\t\t\torig.Value = ov\n\n\t\tcase 4:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DoubleValue\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvar ov *AnyValue_DoubleValue\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &AnyValue_DoubleValue{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolAnyValue_DoubleValue.Get().(*AnyValue_DoubleValue)\n\t\t\t}\n\t\t\tov.DoubleValue = math.Float64frombits(num)\n\t\t\torig.Value = ov\n\n\t\tcase 5:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ArrayValue\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tvar ov *AnyValue_ArrayValue\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &AnyValue_ArrayValue{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolAnyValue_ArrayValue.Get().(*AnyValue_ArrayValue)\n\t\t\t}\n\t\t\tov.ArrayValue = NewArrayValue()\n\t\t\terr = ov.ArrayValue.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Value = ov\n\n\t\tcase 6:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field KvlistValue\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tvar ov *AnyValue_KvlistValue\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &AnyValue_KvlistValue{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolAnyValue_KvlistValue.Get().(*AnyValue_KvlistValue)\n\t\t\t}\n\t\t\tov.KvlistValue = NewKeyValueList()\n\t\t\terr = ov.KvlistValue.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Value = ov\n\n\t\tcase 7:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field BytesValue\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tvar ov *AnyValue_BytesValue\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &AnyValue_BytesValue{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolAnyValue_BytesValue.Get().(*AnyValue_BytesValue)\n\t\t\t}\n\t\t\tif length != 0 {\n\t\t\t\tov.BytesValue = make([]byte, length)\n\t\t\t\tcopy(ov.BytesValue, buf[startPos:pos])\n\t\t\t}\n\t\t\torig.Value = ov\n\n\t\tcase 8:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field StringValueStrindex\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvar ov *AnyValue_StringValueStrindex\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &AnyValue_StringValueStrindex{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolAnyValue_StringValueStrindex.Get().(*AnyValue_StringValueStrindex)\n\t\t\t}\n\t\t\tov.StringValueStrindex = int32(num)\n\t\t\torig.Value = ov\n\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestAnyValue() *AnyValue {\n\torig := NewAnyValue()\n\torig.Value = &AnyValue_StringValue{StringValue: \"test_stringvalue\"}\n\treturn orig\n}\n\nfunc GenTestAnyValuePtrSlice() []*AnyValue {\n\torig := make([]*AnyValue, 5)\n\torig[0] = NewAnyValue()\n\torig[1] = GenTestAnyValue()\n\torig[2] = NewAnyValue()\n\torig[3] = GenTestAnyValue()\n\torig[4] = NewAnyValue()\n\treturn orig\n}\n\nfunc GenTestAnyValueSlice() []AnyValue {\n\torig := make([]AnyValue, 5)\n\torig[1] = *GenTestAnyValue()\n\torig[3] = *GenTestAnyValue()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_anyvalue_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcommon \"go.opentelemetry.io/proto/slim/otlp/common/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyAnyValue(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesAnyValue() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewAnyValue()\n\t\t\t\tCopyAnyValue(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyAnyValue(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyAnyValueSlice(t *testing.T) {\n\tsrc := []AnyValue{}\n\tdest := []AnyValue{}\n\t// Test CopyTo empty\n\tdest = CopyAnyValueSlice(dest, src)\n\tassert.Equal(t, []AnyValue{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestAnyValueSlice()\n\tdest = CopyAnyValueSlice(dest, src)\n\tassert.Equal(t, GenTestAnyValueSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyAnyValueSlice(dest, src)\n\tassert.Equal(t, GenTestAnyValueSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyAnyValueSlice(dest, []AnyValue{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyAnyValueSlice(dest, src)\n\tassert.Equal(t, GenTestAnyValueSlice(), dest)\n}\n\nfunc TestCopyAnyValuePtrSlice(t *testing.T) {\n\tsrc := []*AnyValue{}\n\tdest := []*AnyValue{}\n\t// Test CopyTo empty\n\tdest = CopyAnyValuePtrSlice(dest, src)\n\tassert.Equal(t, []*AnyValue{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestAnyValuePtrSlice()\n\tdest = CopyAnyValuePtrSlice(dest, src)\n\tassert.Equal(t, GenTestAnyValuePtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyAnyValuePtrSlice(dest, src)\n\tassert.Equal(t, GenTestAnyValuePtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyAnyValuePtrSlice(dest, []*AnyValue{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyAnyValuePtrSlice(dest, src)\n\tassert.Equal(t, GenTestAnyValuePtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONAnyValueUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewAnyValue()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewAnyValue(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONAnyValue(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesAnyValue() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewAnyValue()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteAnyValue(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoAnyValueFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesAnyValue() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewAnyValue()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoAnyValueUnknown(t *testing.T) {\n\tdest := NewAnyValue()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewAnyValue(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoAnyValue(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesAnyValue() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewAnyValue()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteAnyValue(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufAnyValue(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesAnyValue() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcommon.AnyValue{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewAnyValue()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesAnyValue() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\": {0x02},\n\n\t\t\"StringValue/wrong_wire_type\":         {0xc},\n\t\t\"StringValue/missing_value\":           {0xa},\n\t\t\"BoolValue/wrong_wire_type\":           {0x14},\n\t\t\"BoolValue/missing_value\":             {0x10},\n\t\t\"IntValue/wrong_wire_type\":            {0x1c},\n\t\t\"IntValue/missing_value\":              {0x18},\n\t\t\"DoubleValue/wrong_wire_type\":         {0x24},\n\t\t\"DoubleValue/missing_value\":           {0x21},\n\t\t\"ArrayValue/wrong_wire_type\":          {0x2c},\n\t\t\"ArrayValue/missing_value\":            {0x2a},\n\t\t\"KvlistValue/wrong_wire_type\":         {0x34},\n\t\t\"KvlistValue/missing_value\":           {0x32},\n\t\t\"BytesValue/wrong_wire_type\":          {0x3c},\n\t\t\"BytesValue/missing_value\":            {0x3a},\n\t\t\"StringValueStrindex/wrong_wire_type\": {0x44},\n\t\t\"StringValueStrindex/missing_value\":   {0x40},\n\t}\n}\n\nfunc genTestEncodingValuesAnyValue() map[string]*AnyValue {\n\treturn map[string]*AnyValue{\n\t\t\"empty\":               NewAnyValue(),\n\t\t\"StringValue/default\": {Value: &AnyValue_StringValue{StringValue: \"\"}},\n\t\t\"StringValue/test\":    {Value: &AnyValue_StringValue{StringValue: \"test_stringvalue\"}}, \"BoolValue/default\": {Value: &AnyValue_BoolValue{BoolValue: false}},\n\t\t\"BoolValue/test\": {Value: &AnyValue_BoolValue{BoolValue: true}}, \"IntValue/default\": {Value: &AnyValue_IntValue{IntValue: int64(0)}},\n\t\t\"IntValue/test\": {Value: &AnyValue_IntValue{IntValue: int64(13)}}, \"DoubleValue/default\": {Value: &AnyValue_DoubleValue{DoubleValue: float64(0)}},\n\t\t\"DoubleValue/test\": {Value: &AnyValue_DoubleValue{DoubleValue: float64(3.1415926)}}, \"ArrayValue/default\": {Value: &AnyValue_ArrayValue{ArrayValue: &ArrayValue{}}},\n\t\t\"ArrayValue/test\": {Value: &AnyValue_ArrayValue{ArrayValue: GenTestArrayValue()}}, \"KvlistValue/default\": {Value: &AnyValue_KvlistValue{KvlistValue: &KeyValueList{}}},\n\t\t\"KvlistValue/test\": {Value: &AnyValue_KvlistValue{KvlistValue: GenTestKeyValueList()}}, \"BytesValue/default\": {Value: &AnyValue_BytesValue{BytesValue: nil}},\n\t\t\"BytesValue/test\": {Value: &AnyValue_BytesValue{BytesValue: []byte{1, 2, 3}}}, \"StringValueStrindex/default\": {Value: &AnyValue_StringValueStrindex{StringValueStrindex: int32(0)}},\n\t\t\"StringValueStrindex/test\": {Value: &AnyValue_StringValueStrindex{StringValueStrindex: int32(13)}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_arrayvalue.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ArrayValue is a list of AnyValue messages. We need ArrayValue as a message since oneof in AnyValue does not allow repeated fields.\ntype ArrayValue struct {\n\tValues []AnyValue\n}\n\nvar (\n\tprotoPoolArrayValue = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ArrayValue{}\n\t\t},\n\t}\n)\n\nfunc NewArrayValue() *ArrayValue {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ArrayValue{}\n\t}\n\treturn protoPoolArrayValue.Get().(*ArrayValue)\n}\n\nfunc DeleteArrayValue(orig *ArrayValue, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.Values {\n\t\tDeleteAnyValue(&orig.Values[i], false)\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolArrayValue.Put(orig)\n\t}\n}\n\nfunc CopyArrayValue(dest, src *ArrayValue) *ArrayValue {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewArrayValue()\n\t}\n\tdest.Values = CopyAnyValueSlice(dest.Values, src.Values)\n\n\treturn dest\n}\n\nfunc CopyArrayValueSlice(dest, src []ArrayValue) []ArrayValue {\n\tvar newDest []ArrayValue\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ArrayValue, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteArrayValue(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyArrayValue(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyArrayValuePtrSlice(dest, src []*ArrayValue) []*ArrayValue {\n\tvar newDest []*ArrayValue\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ArrayValue, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewArrayValue()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteArrayValue(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewArrayValue()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyArrayValue(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ArrayValue) Reset() {\n\t*orig = ArrayValue{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ArrayValue) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.Values) > 0 {\n\t\tdest.WriteObjectField(\"values\")\n\t\tdest.WriteArrayStart()\n\t\torig.Values[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Values); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Values[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ArrayValue) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"values\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Values = append(orig.Values, AnyValue{})\n\t\t\t\torig.Values[len(orig.Values)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ArrayValue) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.Values {\n\t\tl = orig.Values[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ArrayValue) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.Values) - 1; i >= 0; i-- {\n\t\tl = orig.Values[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ArrayValue) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Values\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Values = append(orig.Values, AnyValue{})\n\t\t\terr = orig.Values[len(orig.Values)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestArrayValue() *ArrayValue {\n\torig := NewArrayValue()\n\torig.Values = []AnyValue{{}, *GenTestAnyValue()}\n\treturn orig\n}\n\nfunc GenTestArrayValuePtrSlice() []*ArrayValue {\n\torig := make([]*ArrayValue, 5)\n\torig[0] = NewArrayValue()\n\torig[1] = GenTestArrayValue()\n\torig[2] = NewArrayValue()\n\torig[3] = GenTestArrayValue()\n\torig[4] = NewArrayValue()\n\treturn orig\n}\n\nfunc GenTestArrayValueSlice() []ArrayValue {\n\torig := make([]ArrayValue, 5)\n\torig[1] = *GenTestArrayValue()\n\torig[3] = *GenTestArrayValue()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_arrayvalue_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcommon \"go.opentelemetry.io/proto/slim/otlp/common/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyArrayValue(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesArrayValue() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewArrayValue()\n\t\t\t\tCopyArrayValue(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyArrayValue(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyArrayValueSlice(t *testing.T) {\n\tsrc := []ArrayValue{}\n\tdest := []ArrayValue{}\n\t// Test CopyTo empty\n\tdest = CopyArrayValueSlice(dest, src)\n\tassert.Equal(t, []ArrayValue{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestArrayValueSlice()\n\tdest = CopyArrayValueSlice(dest, src)\n\tassert.Equal(t, GenTestArrayValueSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyArrayValueSlice(dest, src)\n\tassert.Equal(t, GenTestArrayValueSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyArrayValueSlice(dest, []ArrayValue{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyArrayValueSlice(dest, src)\n\tassert.Equal(t, GenTestArrayValueSlice(), dest)\n}\n\nfunc TestCopyArrayValuePtrSlice(t *testing.T) {\n\tsrc := []*ArrayValue{}\n\tdest := []*ArrayValue{}\n\t// Test CopyTo empty\n\tdest = CopyArrayValuePtrSlice(dest, src)\n\tassert.Equal(t, []*ArrayValue{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestArrayValuePtrSlice()\n\tdest = CopyArrayValuePtrSlice(dest, src)\n\tassert.Equal(t, GenTestArrayValuePtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyArrayValuePtrSlice(dest, src)\n\tassert.Equal(t, GenTestArrayValuePtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyArrayValuePtrSlice(dest, []*ArrayValue{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyArrayValuePtrSlice(dest, src)\n\tassert.Equal(t, GenTestArrayValuePtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONArrayValueUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewArrayValue()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewArrayValue(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONArrayValue(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesArrayValue() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewArrayValue()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteArrayValue(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoArrayValueFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesArrayValue() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewArrayValue()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoArrayValueUnknown(t *testing.T) {\n\tdest := NewArrayValue()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewArrayValue(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoArrayValue(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesArrayValue() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewArrayValue()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteArrayValue(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufArrayValue(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesArrayValue() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcommon.ArrayValue{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewArrayValue()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesArrayValue() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":          {0x02},\n\t\t\"Values/wrong_wire_type\": {0xc},\n\t\t\"Values/missing_value\":   {0xa},\n\t}\n}\n\nfunc genTestEncodingValuesArrayValue() map[string]*ArrayValue {\n\treturn map[string]*ArrayValue{\n\t\t\"empty\":       NewArrayValue(),\n\t\t\"Values/test\": {Values: []AnyValue{{}, *GenTestAnyValue()}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_entityref.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\ntype EntityRef struct {\n\tSchemaUrl       string\n\tType            string\n\tIdKeys          []string\n\tDescriptionKeys []string\n}\n\nvar (\n\tprotoPoolEntityRef = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &EntityRef{}\n\t\t},\n\t}\n)\n\nfunc NewEntityRef() *EntityRef {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &EntityRef{}\n\t}\n\treturn protoPoolEntityRef.Get().(*EntityRef)\n}\n\nfunc DeleteEntityRef(orig *EntityRef, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolEntityRef.Put(orig)\n\t}\n}\n\nfunc CopyEntityRef(dest, src *EntityRef) *EntityRef {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewEntityRef()\n\t}\n\tdest.SchemaUrl = src.SchemaUrl\n\tdest.Type = src.Type\n\tdest.IdKeys = append(dest.IdKeys[:0], src.IdKeys...)\n\n\tdest.DescriptionKeys = append(dest.DescriptionKeys[:0], src.DescriptionKeys...)\n\n\treturn dest\n}\n\nfunc CopyEntityRefSlice(dest, src []EntityRef) []EntityRef {\n\tvar newDest []EntityRef\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]EntityRef, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteEntityRef(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyEntityRef(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyEntityRefPtrSlice(dest, src []*EntityRef) []*EntityRef {\n\tvar newDest []*EntityRef\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*EntityRef, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewEntityRef()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteEntityRef(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewEntityRef()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyEntityRef(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *EntityRef) Reset() {\n\t*orig = EntityRef{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *EntityRef) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.SchemaUrl != \"\" {\n\t\tdest.WriteObjectField(\"schemaUrl\")\n\t\tdest.WriteString(orig.SchemaUrl)\n\t}\n\tif orig.Type != \"\" {\n\t\tdest.WriteObjectField(\"type\")\n\t\tdest.WriteString(orig.Type)\n\t}\n\tif len(orig.IdKeys) > 0 {\n\t\tdest.WriteObjectField(\"idKeys\")\n\t\tdest.WriteArrayStart()\n\t\tdest.WriteString(orig.IdKeys[0])\n\t\tfor i := 1; i < len(orig.IdKeys); i++ {\n\t\t\tdest.WriteMore()\n\t\t\tdest.WriteString(orig.IdKeys[i])\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\n\tif len(orig.DescriptionKeys) > 0 {\n\t\tdest.WriteObjectField(\"descriptionKeys\")\n\t\tdest.WriteArrayStart()\n\t\tdest.WriteString(orig.DescriptionKeys[0])\n\t\tfor i := 1; i < len(orig.DescriptionKeys); i++ {\n\t\t\tdest.WriteMore()\n\t\t\tdest.WriteString(orig.DescriptionKeys[i])\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *EntityRef) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"schemaUrl\", \"schema_url\":\n\t\t\torig.SchemaUrl = iter.ReadString()\n\t\tcase \"type\":\n\t\t\torig.Type = iter.ReadString()\n\t\tcase \"idKeys\", \"id_keys\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.IdKeys = append(orig.IdKeys, iter.ReadString())\n\t\t\t}\n\n\t\tcase \"descriptionKeys\", \"description_keys\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.DescriptionKeys = append(orig.DescriptionKeys, iter.ReadString())\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *EntityRef) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\n\tl = len(orig.Type)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tfor _, s := range orig.IdKeys {\n\t\tl = len(s)\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tfor _, s := range orig.DescriptionKeys {\n\t\tl = len(s)\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *EntityRef) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.SchemaUrl)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\tl = len(orig.Type)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.Type)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tfor i := len(orig.IdKeys) - 1; i >= 0; i-- {\n\t\tl = len(orig.IdKeys[i])\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.IdKeys[i])\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\tfor i := len(orig.DescriptionKeys) - 1; i >= 0; i-- {\n\t\tl = len(orig.DescriptionKeys[i])\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.DescriptionKeys[i])\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x22\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *EntityRef) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SchemaUrl\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.SchemaUrl = string(buf[startPos:pos])\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Type\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Type = string(buf[startPos:pos])\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field IdKeys\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.IdKeys = append(orig.IdKeys, string(buf[startPos:pos]))\n\n\t\tcase 4:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DescriptionKeys\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.DescriptionKeys = append(orig.DescriptionKeys, string(buf[startPos:pos]))\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestEntityRef() *EntityRef {\n\torig := NewEntityRef()\n\torig.SchemaUrl = \"test_schemaurl\"\n\torig.Type = \"test_type\"\n\torig.IdKeys = []string{\"\", \"test_idkeys\"}\n\torig.DescriptionKeys = []string{\"\", \"test_descriptionkeys\"}\n\treturn orig\n}\n\nfunc GenTestEntityRefPtrSlice() []*EntityRef {\n\torig := make([]*EntityRef, 5)\n\torig[0] = NewEntityRef()\n\torig[1] = GenTestEntityRef()\n\torig[2] = NewEntityRef()\n\torig[3] = GenTestEntityRef()\n\torig[4] = NewEntityRef()\n\treturn orig\n}\n\nfunc GenTestEntityRefSlice() []EntityRef {\n\torig := make([]EntityRef, 5)\n\torig[1] = *GenTestEntityRef()\n\torig[3] = *GenTestEntityRef()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_entityref_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcommon \"go.opentelemetry.io/proto/slim/otlp/common/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyEntityRef(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesEntityRef() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewEntityRef()\n\t\t\t\tCopyEntityRef(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyEntityRef(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyEntityRefSlice(t *testing.T) {\n\tsrc := []EntityRef{}\n\tdest := []EntityRef{}\n\t// Test CopyTo empty\n\tdest = CopyEntityRefSlice(dest, src)\n\tassert.Equal(t, []EntityRef{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestEntityRefSlice()\n\tdest = CopyEntityRefSlice(dest, src)\n\tassert.Equal(t, GenTestEntityRefSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyEntityRefSlice(dest, src)\n\tassert.Equal(t, GenTestEntityRefSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyEntityRefSlice(dest, []EntityRef{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyEntityRefSlice(dest, src)\n\tassert.Equal(t, GenTestEntityRefSlice(), dest)\n}\n\nfunc TestCopyEntityRefPtrSlice(t *testing.T) {\n\tsrc := []*EntityRef{}\n\tdest := []*EntityRef{}\n\t// Test CopyTo empty\n\tdest = CopyEntityRefPtrSlice(dest, src)\n\tassert.Equal(t, []*EntityRef{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestEntityRefPtrSlice()\n\tdest = CopyEntityRefPtrSlice(dest, src)\n\tassert.Equal(t, GenTestEntityRefPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyEntityRefPtrSlice(dest, src)\n\tassert.Equal(t, GenTestEntityRefPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyEntityRefPtrSlice(dest, []*EntityRef{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyEntityRefPtrSlice(dest, src)\n\tassert.Equal(t, GenTestEntityRefPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONEntityRefUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewEntityRef()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewEntityRef(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONEntityRef(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesEntityRef() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewEntityRef()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteEntityRef(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoEntityRefFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesEntityRef() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewEntityRef()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoEntityRefUnknown(t *testing.T) {\n\tdest := NewEntityRef()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewEntityRef(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoEntityRef(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesEntityRef() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewEntityRef()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteEntityRef(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufEntityRef(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesEntityRef() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcommon.EntityRef{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewEntityRef()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesEntityRef() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                   {0x02},\n\t\t\"SchemaUrl/wrong_wire_type\":       {0xc},\n\t\t\"SchemaUrl/missing_value\":         {0xa},\n\t\t\"Type/wrong_wire_type\":            {0x14},\n\t\t\"Type/missing_value\":              {0x12},\n\t\t\"IdKeys/wrong_wire_type\":          {0x1c},\n\t\t\"IdKeys/missing_value\":            {0x1a},\n\t\t\"DescriptionKeys/wrong_wire_type\": {0x24},\n\t\t\"DescriptionKeys/missing_value\":   {0x22},\n\t}\n}\n\nfunc genTestEncodingValuesEntityRef() map[string]*EntityRef {\n\treturn map[string]*EntityRef{\n\t\t\"empty\":                NewEntityRef(),\n\t\t\"SchemaUrl/test\":       {SchemaUrl: \"test_schemaurl\"},\n\t\t\"Type/test\":            {Type: \"test_type\"},\n\t\t\"IdKeys/test\":          {IdKeys: []string{\"\", \"test_idkeys\"}},\n\t\t\"DescriptionKeys/test\": {DescriptionKeys: []string{\"\", \"test_descriptionkeys\"}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exemplar.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"math\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\nfunc (m *Exemplar) GetValue() any {\n\tif m != nil {\n\t\treturn m.Value\n\t}\n\treturn nil\n}\n\ntype Exemplar_AsDouble struct {\n\tAsDouble float64\n}\n\nfunc (m *Exemplar) GetAsDouble() float64 {\n\tif v, ok := m.GetValue().(*Exemplar_AsDouble); ok {\n\t\treturn v.AsDouble\n\t}\n\treturn float64(0)\n}\n\ntype Exemplar_AsInt struct {\n\tAsInt int64\n}\n\nfunc (m *Exemplar) GetAsInt() int64 {\n\tif v, ok := m.GetValue().(*Exemplar_AsInt); ok {\n\t\treturn v.AsInt\n\t}\n\treturn int64(0)\n}\n\n// Exemplar is a sample input double measurement.\n//\n// Exemplars also hold information about the environment when the measurement was recorded,\n// for example the span and trace ID of the active span when the exemplar was recorded.\ntype Exemplar struct {\n\tValue              any\n\tFilteredAttributes []KeyValue\n\tTimeUnixNano       uint64\n\tTraceId            TraceID\n\tSpanId             SpanID\n}\n\nvar (\n\tprotoPoolExemplar = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Exemplar{}\n\t\t},\n\t}\n\n\tProtoPoolExemplar_AsDouble = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Exemplar_AsDouble{}\n\t\t},\n\t}\n\n\tProtoPoolExemplar_AsInt = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Exemplar_AsInt{}\n\t\t},\n\t}\n)\n\nfunc NewExemplar() *Exemplar {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &Exemplar{}\n\t}\n\treturn protoPoolExemplar.Get().(*Exemplar)\n}\n\nfunc DeleteExemplar(orig *Exemplar, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.FilteredAttributes {\n\t\tDeleteKeyValue(&orig.FilteredAttributes[i], false)\n\t}\n\n\tswitch ov := orig.Value.(type) {\n\tcase *Exemplar_AsDouble:\n\t\tif metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov.AsDouble = float64(0)\n\t\t\tProtoPoolExemplar_AsDouble.Put(ov)\n\t\t}\n\tcase *Exemplar_AsInt:\n\t\tif metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov.AsInt = int64(0)\n\t\t\tProtoPoolExemplar_AsInt.Put(ov)\n\t\t}\n\t}\n\tDeleteTraceID(&orig.TraceId, false)\n\tDeleteSpanID(&orig.SpanId, false)\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolExemplar.Put(orig)\n\t}\n}\n\nfunc CopyExemplar(dest, src *Exemplar) *Exemplar {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewExemplar()\n\t}\n\tdest.FilteredAttributes = CopyKeyValueSlice(dest.FilteredAttributes, src.FilteredAttributes)\n\n\tdest.TimeUnixNano = src.TimeUnixNano\n\tswitch t := src.Value.(type) {\n\tcase *Exemplar_AsDouble:\n\t\tvar ov *Exemplar_AsDouble\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &Exemplar_AsDouble{}\n\t\t} else {\n\t\t\tov = ProtoPoolExemplar_AsDouble.Get().(*Exemplar_AsDouble)\n\t\t}\n\t\tov.AsDouble = t.AsDouble\n\t\tdest.Value = ov\n\n\tcase *Exemplar_AsInt:\n\t\tvar ov *Exemplar_AsInt\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &Exemplar_AsInt{}\n\t\t} else {\n\t\t\tov = ProtoPoolExemplar_AsInt.Get().(*Exemplar_AsInt)\n\t\t}\n\t\tov.AsInt = t.AsInt\n\t\tdest.Value = ov\n\n\tdefault:\n\t\tdest.Value = nil\n\t}\n\tCopyTraceID(&dest.TraceId, &src.TraceId)\n\n\tCopySpanID(&dest.SpanId, &src.SpanId)\n\n\treturn dest\n}\n\nfunc CopyExemplarSlice(dest, src []Exemplar) []Exemplar {\n\tvar newDest []Exemplar\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]Exemplar, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExemplar(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExemplar(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyExemplarPtrSlice(dest, src []*Exemplar) []*Exemplar {\n\tvar newDest []*Exemplar\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*Exemplar, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExemplar()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExemplar(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExemplar()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExemplar(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *Exemplar) Reset() {\n\t*orig = Exemplar{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *Exemplar) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.FilteredAttributes) > 0 {\n\t\tdest.WriteObjectField(\"filteredAttributes\")\n\t\tdest.WriteArrayStart()\n\t\torig.FilteredAttributes[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.FilteredAttributes); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.FilteredAttributes[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tdest.WriteObjectField(\"timeUnixNano\")\n\t\tdest.WriteUint64(orig.TimeUnixNano)\n\t}\n\tswitch orig := orig.Value.(type) {\n\tcase *Exemplar_AsDouble:\n\t\tdest.WriteObjectField(\"asDouble\")\n\t\tdest.WriteFloat64(orig.AsDouble)\n\tcase *Exemplar_AsInt:\n\t\tdest.WriteObjectField(\"asInt\")\n\t\tdest.WriteInt64(orig.AsInt)\n\t}\n\tif !orig.TraceId.IsEmpty() {\n\t\tdest.WriteObjectField(\"traceId\")\n\t\torig.TraceId.MarshalJSON(dest)\n\t}\n\tif !orig.SpanId.IsEmpty() {\n\t\tdest.WriteObjectField(\"spanId\")\n\t\torig.SpanId.MarshalJSON(dest)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *Exemplar) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"filteredAttributes\", \"filtered_attributes\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.FilteredAttributes = append(orig.FilteredAttributes, KeyValue{})\n\t\t\t\torig.FilteredAttributes[len(orig.FilteredAttributes)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"timeUnixNano\", \"time_unix_nano\":\n\t\t\torig.TimeUnixNano = iter.ReadUint64()\n\n\t\tcase \"asDouble\", \"as_double\":\n\t\t\t{\n\t\t\t\tvar ov *Exemplar_AsDouble\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &Exemplar_AsDouble{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolExemplar_AsDouble.Get().(*Exemplar_AsDouble)\n\t\t\t\t}\n\t\t\t\tov.AsDouble = iter.ReadFloat64()\n\t\t\t\torig.Value = ov\n\t\t\t}\n\t\tcase \"asInt\", \"as_int\":\n\t\t\t{\n\t\t\t\tvar ov *Exemplar_AsInt\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &Exemplar_AsInt{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolExemplar_AsInt.Get().(*Exemplar_AsInt)\n\t\t\t\t}\n\t\t\t\tov.AsInt = iter.ReadInt64()\n\t\t\t\torig.Value = ov\n\t\t\t}\n\n\t\tcase \"traceId\", \"trace_id\":\n\n\t\t\torig.TraceId.UnmarshalJSON(iter)\n\t\tcase \"spanId\", \"span_id\":\n\n\t\t\torig.SpanId.UnmarshalJSON(iter)\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *Exemplar) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.FilteredAttributes {\n\t\tl = orig.FilteredAttributes[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tn += 9\n\t}\n\tswitch orig := orig.Value.(type) {\n\tcase nil:\n\t\t_ = orig\n\t\tbreak\n\tcase *Exemplar_AsDouble:\n\n\t\tn += 9\n\tcase *Exemplar_AsInt:\n\n\t\tn += 9\n\t}\n\tl = orig.TraceId.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tl = orig.SpanId.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\treturn n\n}\n\nfunc (orig *Exemplar) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.FilteredAttributes) - 1; i >= 0; i-- {\n\t\tl = orig.FilteredAttributes[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x3a\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimeUnixNano))\n\t\tpos--\n\t\tbuf[pos] = 0x11\n\t}\n\tswitch orig := orig.Value.(type) {\n\tcase *Exemplar_AsDouble:\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.AsDouble))\n\t\tpos--\n\t\tbuf[pos] = 0x19\n\n\tcase *Exemplar_AsInt:\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.AsInt))\n\t\tpos--\n\t\tbuf[pos] = 0x31\n\n\t}\n\tl = orig.TraceId.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x2a\n\n\tl = orig.SpanId.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x22\n\n\treturn len(buf) - pos\n}\n\nfunc (orig *Exemplar) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 7:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field FilteredAttributes\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.FilteredAttributes = append(orig.FilteredAttributes, KeyValue{})\n\t\t\terr = orig.FilteredAttributes[len(orig.FilteredAttributes)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TimeUnixNano\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.TimeUnixNano = uint64(num)\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field AsDouble\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvar ov *Exemplar_AsDouble\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &Exemplar_AsDouble{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolExemplar_AsDouble.Get().(*Exemplar_AsDouble)\n\t\t\t}\n\t\t\tov.AsDouble = math.Float64frombits(num)\n\t\t\torig.Value = ov\n\n\t\tcase 6:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field AsInt\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvar ov *Exemplar_AsInt\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &Exemplar_AsInt{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolExemplar_AsInt.Get().(*Exemplar_AsInt)\n\t\t\t}\n\t\t\tov.AsInt = int64(num)\n\t\t\torig.Value = ov\n\n\t\tcase 5:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TraceId\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.TraceId.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 4:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SpanId\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.SpanId.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestExemplar() *Exemplar {\n\torig := NewExemplar()\n\torig.FilteredAttributes = []KeyValue{{}, *GenTestKeyValue()}\n\torig.TimeUnixNano = uint64(13)\n\torig.Value = &Exemplar_AsDouble{AsDouble: float64(3.1415926)}\n\torig.TraceId = *GenTestTraceID()\n\torig.SpanId = *GenTestSpanID()\n\treturn orig\n}\n\nfunc GenTestExemplarPtrSlice() []*Exemplar {\n\torig := make([]*Exemplar, 5)\n\torig[0] = NewExemplar()\n\torig[1] = GenTestExemplar()\n\torig[2] = NewExemplar()\n\torig[3] = GenTestExemplar()\n\torig[4] = NewExemplar()\n\treturn orig\n}\n\nfunc GenTestExemplarSlice() []Exemplar {\n\torig := make([]Exemplar, 5)\n\torig[1] = *GenTestExemplar()\n\torig[3] = *GenTestExemplar()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exemplar_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyExemplar(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExemplar() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewExemplar()\n\t\t\t\tCopyExemplar(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyExemplar(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyExemplarSlice(t *testing.T) {\n\tsrc := []Exemplar{}\n\tdest := []Exemplar{}\n\t// Test CopyTo empty\n\tdest = CopyExemplarSlice(dest, src)\n\tassert.Equal(t, []Exemplar{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExemplarSlice()\n\tdest = CopyExemplarSlice(dest, src)\n\tassert.Equal(t, GenTestExemplarSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExemplarSlice(dest, src)\n\tassert.Equal(t, GenTestExemplarSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExemplarSlice(dest, []Exemplar{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExemplarSlice(dest, src)\n\tassert.Equal(t, GenTestExemplarSlice(), dest)\n}\n\nfunc TestCopyExemplarPtrSlice(t *testing.T) {\n\tsrc := []*Exemplar{}\n\tdest := []*Exemplar{}\n\t// Test CopyTo empty\n\tdest = CopyExemplarPtrSlice(dest, src)\n\tassert.Equal(t, []*Exemplar{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExemplarPtrSlice()\n\tdest = CopyExemplarPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExemplarPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExemplarPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExemplarPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExemplarPtrSlice(dest, []*Exemplar{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExemplarPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExemplarPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExemplarUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewExemplar()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewExemplar(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExemplar(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExemplar() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewExemplar()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExemplar(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExemplarFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesExemplar() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewExemplar()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExemplarUnknown(t *testing.T) {\n\tdest := NewExemplar()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewExemplar(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoExemplar(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExemplar() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewExemplar()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExemplar(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufExemplar(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExemplar() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpmetrics.Exemplar{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewExemplar()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesExemplar() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                      {0x02},\n\t\t\"FilteredAttributes/wrong_wire_type\": {0x3c},\n\t\t\"FilteredAttributes/missing_value\":   {0x3a},\n\t\t\"TimeUnixNano/wrong_wire_type\":       {0x14},\n\t\t\"TimeUnixNano/missing_value\":         {0x11},\n\n\t\t\"AsDouble/wrong_wire_type\": {0x1c},\n\t\t\"AsDouble/missing_value\":   {0x19},\n\t\t\"AsInt/wrong_wire_type\":    {0x34},\n\t\t\"AsInt/missing_value\":      {0x31},\n\t\t\"TraceId/wrong_wire_type\":  {0x2c},\n\t\t\"TraceId/missing_value\":    {0x2a},\n\t\t\"SpanId/wrong_wire_type\":   {0x24},\n\t\t\"SpanId/missing_value\":     {0x22},\n\t}\n}\n\nfunc genTestEncodingValuesExemplar() map[string]*Exemplar {\n\treturn map[string]*Exemplar{\n\t\t\"empty\":                   NewExemplar(),\n\t\t\"FilteredAttributes/test\": {FilteredAttributes: []KeyValue{{}, *GenTestKeyValue()}},\n\t\t\"TimeUnixNano/test\":       {TimeUnixNano: uint64(13)},\n\t\t\"AsDouble/default\":        {Value: &Exemplar_AsDouble{AsDouble: float64(0)}},\n\t\t\"AsDouble/test\":           {Value: &Exemplar_AsDouble{AsDouble: float64(3.1415926)}}, \"AsInt/default\": {Value: &Exemplar_AsInt{AsInt: int64(0)}},\n\t\t\"AsInt/test\":   {Value: &Exemplar_AsInt{AsInt: int64(13)}},\n\t\t\"TraceId/test\": {TraceId: *GenTestTraceID()},\n\t\t\"SpanId/test\":  {SpanId: *GenTestSpanID()},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exponentialhistogram.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ExponentialHistogram represents the type of a metric that is calculated by aggregating\n// as a ExponentialHistogram of all reported double measurements over a time interval.\ntype ExponentialHistogram struct {\n\tDataPoints             []*ExponentialHistogramDataPoint\n\tAggregationTemporality AggregationTemporality\n}\n\nvar (\n\tprotoPoolExponentialHistogram = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ExponentialHistogram{}\n\t\t},\n\t}\n)\n\nfunc NewExponentialHistogram() *ExponentialHistogram {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ExponentialHistogram{}\n\t}\n\treturn protoPoolExponentialHistogram.Get().(*ExponentialHistogram)\n}\n\nfunc DeleteExponentialHistogram(orig *ExponentialHistogram, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.DataPoints {\n\t\tDeleteExponentialHistogramDataPoint(orig.DataPoints[i], true)\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolExponentialHistogram.Put(orig)\n\t}\n}\n\nfunc CopyExponentialHistogram(dest, src *ExponentialHistogram) *ExponentialHistogram {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewExponentialHistogram()\n\t}\n\tdest.DataPoints = CopyExponentialHistogramDataPointPtrSlice(dest.DataPoints, src.DataPoints)\n\n\tdest.AggregationTemporality = src.AggregationTemporality\n\n\treturn dest\n}\n\nfunc CopyExponentialHistogramSlice(dest, src []ExponentialHistogram) []ExponentialHistogram {\n\tvar newDest []ExponentialHistogram\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ExponentialHistogram, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExponentialHistogram(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExponentialHistogram(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyExponentialHistogramPtrSlice(dest, src []*ExponentialHistogram) []*ExponentialHistogram {\n\tvar newDest []*ExponentialHistogram\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ExponentialHistogram, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExponentialHistogram()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExponentialHistogram(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExponentialHistogram()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExponentialHistogram(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ExponentialHistogram) Reset() {\n\t*orig = ExponentialHistogram{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ExponentialHistogram) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.DataPoints) > 0 {\n\t\tdest.WriteObjectField(\"dataPoints\")\n\t\tdest.WriteArrayStart()\n\t\torig.DataPoints[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.DataPoints); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.DataPoints[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\n\tif int32(orig.AggregationTemporality) != 0 {\n\t\tdest.WriteObjectField(\"aggregationTemporality\")\n\t\tdest.WriteInt32(int32(orig.AggregationTemporality))\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ExponentialHistogram) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"dataPoints\", \"data_points\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.DataPoints = append(orig.DataPoints, NewExponentialHistogramDataPoint())\n\t\t\t\torig.DataPoints[len(orig.DataPoints)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"aggregationTemporality\", \"aggregation_temporality\":\n\t\t\torig.AggregationTemporality = AggregationTemporality(iter.ReadEnumValue(AggregationTemporality_value))\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ExponentialHistogram) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.DataPoints {\n\t\tl = orig.DataPoints[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.AggregationTemporality != AggregationTemporality(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.AggregationTemporality))\n\t}\n\treturn n\n}\n\nfunc (orig *ExponentialHistogram) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.DataPoints) - 1; i >= 0; i-- {\n\t\tl = orig.DataPoints[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\tif orig.AggregationTemporality != AggregationTemporality(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.AggregationTemporality))\n\t\tpos--\n\t\tbuf[pos] = 0x10\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ExponentialHistogram) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DataPoints\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.DataPoints = append(orig.DataPoints, NewExponentialHistogramDataPoint())\n\t\t\terr = orig.DataPoints[len(orig.DataPoints)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field AggregationTemporality\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.AggregationTemporality = AggregationTemporality(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestExponentialHistogram() *ExponentialHistogram {\n\torig := NewExponentialHistogram()\n\torig.DataPoints = []*ExponentialHistogramDataPoint{{}, GenTestExponentialHistogramDataPoint()}\n\torig.AggregationTemporality = AggregationTemporality(13)\n\treturn orig\n}\n\nfunc GenTestExponentialHistogramPtrSlice() []*ExponentialHistogram {\n\torig := make([]*ExponentialHistogram, 5)\n\torig[0] = NewExponentialHistogram()\n\torig[1] = GenTestExponentialHistogram()\n\torig[2] = NewExponentialHistogram()\n\torig[3] = GenTestExponentialHistogram()\n\torig[4] = NewExponentialHistogram()\n\treturn orig\n}\n\nfunc GenTestExponentialHistogramSlice() []ExponentialHistogram {\n\torig := make([]ExponentialHistogram, 5)\n\torig[1] = *GenTestExponentialHistogram()\n\torig[3] = *GenTestExponentialHistogram()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exponentialhistogram_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyExponentialHistogram(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExponentialHistogram() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewExponentialHistogram()\n\t\t\t\tCopyExponentialHistogram(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyExponentialHistogram(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyExponentialHistogramSlice(t *testing.T) {\n\tsrc := []ExponentialHistogram{}\n\tdest := []ExponentialHistogram{}\n\t// Test CopyTo empty\n\tdest = CopyExponentialHistogramSlice(dest, src)\n\tassert.Equal(t, []ExponentialHistogram{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExponentialHistogramSlice()\n\tdest = CopyExponentialHistogramSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExponentialHistogramSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExponentialHistogramSlice(dest, []ExponentialHistogram{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExponentialHistogramSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramSlice(), dest)\n}\n\nfunc TestCopyExponentialHistogramPtrSlice(t *testing.T) {\n\tsrc := []*ExponentialHistogram{}\n\tdest := []*ExponentialHistogram{}\n\t// Test CopyTo empty\n\tdest = CopyExponentialHistogramPtrSlice(dest, src)\n\tassert.Equal(t, []*ExponentialHistogram{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExponentialHistogramPtrSlice()\n\tdest = CopyExponentialHistogramPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExponentialHistogramPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExponentialHistogramPtrSlice(dest, []*ExponentialHistogram{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExponentialHistogramPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExponentialHistogramUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewExponentialHistogram()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewExponentialHistogram(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExponentialHistogram(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExponentialHistogram() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewExponentialHistogram()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExponentialHistogram(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExponentialHistogramFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesExponentialHistogram() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewExponentialHistogram()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExponentialHistogramUnknown(t *testing.T) {\n\tdest := NewExponentialHistogram()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewExponentialHistogram(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoExponentialHistogram(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExponentialHistogram() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewExponentialHistogram()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExponentialHistogram(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufExponentialHistogram(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExponentialHistogram() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpmetrics.ExponentialHistogram{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewExponentialHistogram()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesExponentialHistogram() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                          {0x02},\n\t\t\"DataPoints/wrong_wire_type\":             {0xc},\n\t\t\"DataPoints/missing_value\":               {0xa},\n\t\t\"AggregationTemporality/wrong_wire_type\": {0x14},\n\t\t\"AggregationTemporality/missing_value\":   {0x10},\n\t}\n}\n\nfunc genTestEncodingValuesExponentialHistogram() map[string]*ExponentialHistogram {\n\treturn map[string]*ExponentialHistogram{\n\t\t\"empty\":                       NewExponentialHistogram(),\n\t\t\"DataPoints/test\":             {DataPoints: []*ExponentialHistogramDataPoint{{}, GenTestExponentialHistogramDataPoint()}},\n\t\t\"AggregationTemporality/test\": {AggregationTemporality: AggregationTemporality(13)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exponentialhistogramdatapoint.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"math\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ExponentialHistogramDataPoint is a single data point in a timeseries that describes the\n// time-varying values of a ExponentialHistogram of double values. A ExponentialHistogram contains\n// summary statistics for a population of values, it may optionally contain the\n// distribution of those values across a set of buckets.\ntype ExponentialHistogramDataPoint struct {\n\tPositive          ExponentialHistogramDataPointBuckets\n\tNegative          ExponentialHistogramDataPointBuckets\n\tAttributes        []KeyValue\n\tExemplars         []Exemplar\n\tStartTimeUnixNano uint64\n\tTimeUnixNano      uint64\n\tCount             uint64\n\tSum               float64\n\tZeroCount         uint64\n\tMin               float64\n\tMax               float64\n\tZeroThreshold     float64\n\tmetadata          [1]uint64\n\tScale             int32\n\tFlags             uint32\n}\n\nvar (\n\tprotoPoolExponentialHistogramDataPoint = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ExponentialHistogramDataPoint{}\n\t\t},\n\t}\n)\n\nfunc NewExponentialHistogramDataPoint() *ExponentialHistogramDataPoint {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ExponentialHistogramDataPoint{}\n\t}\n\treturn protoPoolExponentialHistogramDataPoint.Get().(*ExponentialHistogramDataPoint)\n}\n\nfunc DeleteExponentialHistogramDataPoint(orig *ExponentialHistogramDataPoint, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.Attributes {\n\t\tDeleteKeyValue(&orig.Attributes[i], false)\n\t}\n\n\tDeleteExponentialHistogramDataPointBuckets(&orig.Positive, false)\n\tDeleteExponentialHistogramDataPointBuckets(&orig.Negative, false)\n\n\tfor i := range orig.Exemplars {\n\t\tDeleteExemplar(&orig.Exemplars[i], false)\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolExponentialHistogramDataPoint.Put(orig)\n\t}\n}\n\nfunc CopyExponentialHistogramDataPoint(dest, src *ExponentialHistogramDataPoint) *ExponentialHistogramDataPoint {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewExponentialHistogramDataPoint()\n\t}\n\tdest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)\n\n\tdest.StartTimeUnixNano = src.StartTimeUnixNano\n\tdest.TimeUnixNano = src.TimeUnixNano\n\tdest.Count = src.Count\n\tif src.HasSum() {\n\t\tdest.SetSum(src.Sum)\n\t} else {\n\t\tdest.RemoveSum()\n\t}\n\n\tdest.Scale = src.Scale\n\tdest.ZeroCount = src.ZeroCount\n\tCopyExponentialHistogramDataPointBuckets(&dest.Positive, &src.Positive)\n\n\tCopyExponentialHistogramDataPointBuckets(&dest.Negative, &src.Negative)\n\n\tdest.Flags = src.Flags\n\tdest.Exemplars = CopyExemplarSlice(dest.Exemplars, src.Exemplars)\n\n\tif src.HasMin() {\n\t\tdest.SetMin(src.Min)\n\t} else {\n\t\tdest.RemoveMin()\n\t}\n\n\tif src.HasMax() {\n\t\tdest.SetMax(src.Max)\n\t} else {\n\t\tdest.RemoveMax()\n\t}\n\n\tdest.ZeroThreshold = src.ZeroThreshold\n\n\treturn dest\n}\n\nfunc CopyExponentialHistogramDataPointSlice(dest, src []ExponentialHistogramDataPoint) []ExponentialHistogramDataPoint {\n\tvar newDest []ExponentialHistogramDataPoint\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ExponentialHistogramDataPoint, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExponentialHistogramDataPoint(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExponentialHistogramDataPoint(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyExponentialHistogramDataPointPtrSlice(dest, src []*ExponentialHistogramDataPoint) []*ExponentialHistogramDataPoint {\n\tvar newDest []*ExponentialHistogramDataPoint\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ExponentialHistogramDataPoint, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExponentialHistogramDataPoint()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExponentialHistogramDataPoint(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExponentialHistogramDataPoint()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExponentialHistogramDataPoint(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ExponentialHistogramDataPoint) Reset() {\n\t*orig = ExponentialHistogramDataPoint{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ExponentialHistogramDataPoint) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.Attributes) > 0 {\n\t\tdest.WriteObjectField(\"attributes\")\n\t\tdest.WriteArrayStart()\n\t\torig.Attributes[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Attributes); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Attributes[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.StartTimeUnixNano != uint64(0) {\n\t\tdest.WriteObjectField(\"startTimeUnixNano\")\n\t\tdest.WriteUint64(orig.StartTimeUnixNano)\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tdest.WriteObjectField(\"timeUnixNano\")\n\t\tdest.WriteUint64(orig.TimeUnixNano)\n\t}\n\tif orig.Count != uint64(0) {\n\t\tdest.WriteObjectField(\"count\")\n\t\tdest.WriteUint64(orig.Count)\n\t}\n\tif orig.HasSum() {\n\t\tdest.WriteObjectField(\"sum\")\n\t\tdest.WriteFloat64(orig.Sum)\n\t}\n\tif orig.Scale != int32(0) {\n\t\tdest.WriteObjectField(\"scale\")\n\t\tdest.WriteInt32(orig.Scale)\n\t}\n\tif orig.ZeroCount != uint64(0) {\n\t\tdest.WriteObjectField(\"zeroCount\")\n\t\tdest.WriteUint64(orig.ZeroCount)\n\t}\n\tdest.WriteObjectField(\"positive\")\n\torig.Positive.MarshalJSON(dest)\n\tdest.WriteObjectField(\"negative\")\n\torig.Negative.MarshalJSON(dest)\n\tif orig.Flags != uint32(0) {\n\t\tdest.WriteObjectField(\"flags\")\n\t\tdest.WriteUint32(orig.Flags)\n\t}\n\tif len(orig.Exemplars) > 0 {\n\t\tdest.WriteObjectField(\"exemplars\")\n\t\tdest.WriteArrayStart()\n\t\torig.Exemplars[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Exemplars); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Exemplars[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.HasMin() {\n\t\tdest.WriteObjectField(\"min\")\n\t\tdest.WriteFloat64(orig.Min)\n\t}\n\tif orig.HasMax() {\n\t\tdest.WriteObjectField(\"max\")\n\t\tdest.WriteFloat64(orig.Max)\n\t}\n\tif orig.ZeroThreshold != float64(0) {\n\t\tdest.WriteObjectField(\"zeroThreshold\")\n\t\tdest.WriteFloat64(orig.ZeroThreshold)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ExponentialHistogramDataPoint) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"attributes\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\t\torig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"startTimeUnixNano\", \"start_time_unix_nano\":\n\t\t\torig.StartTimeUnixNano = iter.ReadUint64()\n\t\tcase \"timeUnixNano\", \"time_unix_nano\":\n\t\t\torig.TimeUnixNano = iter.ReadUint64()\n\t\tcase \"count\":\n\t\t\torig.Count = iter.ReadUint64()\n\t\tcase \"sum\":\n\t\t\torig.SetSum(iter.ReadFloat64())\n\n\t\tcase \"scale\":\n\t\t\torig.Scale = iter.ReadInt32()\n\t\tcase \"zeroCount\", \"zero_count\":\n\t\t\torig.ZeroCount = iter.ReadUint64()\n\t\tcase \"positive\":\n\n\t\t\torig.Positive.UnmarshalJSON(iter)\n\t\tcase \"negative\":\n\n\t\t\torig.Negative.UnmarshalJSON(iter)\n\t\tcase \"flags\":\n\t\t\torig.Flags = iter.ReadUint32()\n\t\tcase \"exemplars\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Exemplars = append(orig.Exemplars, Exemplar{})\n\t\t\t\torig.Exemplars[len(orig.Exemplars)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"min\":\n\t\t\torig.SetMin(iter.ReadFloat64())\n\n\t\tcase \"max\":\n\t\t\torig.SetMax(iter.ReadFloat64())\n\n\t\tcase \"zeroThreshold\", \"zero_threshold\":\n\t\t\torig.ZeroThreshold = iter.ReadFloat64()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ExponentialHistogramDataPoint) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.Attributes {\n\t\tl = orig.Attributes[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.StartTimeUnixNano != uint64(0) {\n\t\tn += 9\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tn += 9\n\t}\n\tif orig.Count != uint64(0) {\n\t\tn += 9\n\t}\n\tif orig.HasSum() {\n\t\tn += 9\n\t}\n\tif orig.Scale != int32(0) {\n\t\tn += 1 + proto.Soz(uint64(orig.Scale))\n\t}\n\tif orig.ZeroCount != uint64(0) {\n\t\tn += 9\n\t}\n\tl = orig.Positive.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tl = orig.Negative.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tif orig.Flags != uint32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.Flags))\n\t}\n\tfor i := range orig.Exemplars {\n\t\tl = orig.Exemplars[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.HasMin() {\n\t\tn += 9\n\t}\n\tif orig.HasMax() {\n\t\tn += 9\n\t}\n\tif orig.ZeroThreshold != float64(0) {\n\t\tn += 9\n\t}\n\treturn n\n}\n\nfunc (orig *ExponentialHistogramDataPoint) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.Attributes) - 1; i >= 0; i-- {\n\t\tl = orig.Attributes[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\tif orig.StartTimeUnixNano != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.StartTimeUnixNano))\n\t\tpos--\n\t\tbuf[pos] = 0x11\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimeUnixNano))\n\t\tpos--\n\t\tbuf[pos] = 0x19\n\t}\n\tif orig.Count != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.Count))\n\t\tpos--\n\t\tbuf[pos] = 0x21\n\t}\n\tif orig.HasSum() {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Sum))\n\t\tpos--\n\t\tbuf[pos] = 0x29\n\t}\n\tif orig.Scale != int32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64((uint32(orig.Scale)<<1)^uint32(orig.Scale>>31)))\n\t\tpos--\n\t\tbuf[pos] = 0x30\n\t}\n\tif orig.ZeroCount != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.ZeroCount))\n\t\tpos--\n\t\tbuf[pos] = 0x39\n\t}\n\tl = orig.Positive.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x42\n\n\tl = orig.Negative.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x4a\n\n\tif orig.Flags != uint32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.Flags))\n\t\tpos--\n\t\tbuf[pos] = 0x50\n\t}\n\tfor i := len(orig.Exemplars) - 1; i >= 0; i-- {\n\t\tl = orig.Exemplars[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x5a\n\t}\n\tif orig.HasMin() {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Min))\n\t\tpos--\n\t\tbuf[pos] = 0x61\n\t}\n\tif orig.HasMax() {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Max))\n\t\tpos--\n\t\tbuf[pos] = 0x69\n\t}\n\tif orig.ZeroThreshold != float64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.ZeroThreshold))\n\t\tpos--\n\t\tbuf[pos] = 0x71\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ExponentialHistogramDataPoint) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Attributes\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\terr = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field StartTimeUnixNano\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.StartTimeUnixNano = uint64(num)\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TimeUnixNano\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.TimeUnixNano = uint64(num)\n\n\t\tcase 4:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Count\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.Count = uint64(num)\n\n\t\tcase 5:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Sum\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.SetSum(math.Float64frombits(num))\n\n\t\tcase 6:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Scale\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Scale = int32(uint32(num>>1) ^ uint32(int32((num&1)<<31)>>31))\n\n\t\tcase 7:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ZeroCount\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.ZeroCount = uint64(num)\n\n\t\tcase 8:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Positive\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.Positive.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 9:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Negative\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.Negative.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 10:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Flags\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Flags = uint32(num)\n\n\t\tcase 11:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Exemplars\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Exemplars = append(orig.Exemplars, Exemplar{})\n\t\t\terr = orig.Exemplars[len(orig.Exemplars)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 12:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Min\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.SetMin(math.Float64frombits(num))\n\n\t\tcase 13:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Max\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.SetMax(math.Float64frombits(num))\n\n\t\tcase 14:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ZeroThreshold\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.ZeroThreshold = math.Float64frombits(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nconst fieldBlockExponentialHistogramDataPointSum = uint64(0 >> 6)\nconst fieldBitExponentialHistogramDataPointSum = uint64(1 << 0 & 0x3F)\n\nfunc (m *ExponentialHistogramDataPoint) SetSum(value float64) {\n\tm.Sum = value\n\tm.metadata[fieldBlockExponentialHistogramDataPointSum] |= fieldBitExponentialHistogramDataPointSum\n}\n\nfunc (m *ExponentialHistogramDataPoint) RemoveSum() {\n\tm.Sum = float64(0)\n\tm.metadata[fieldBlockExponentialHistogramDataPointSum] &^= fieldBitExponentialHistogramDataPointSum\n}\n\nfunc (m *ExponentialHistogramDataPoint) HasSum() bool {\n\treturn m.metadata[fieldBlockExponentialHistogramDataPointSum]&fieldBitExponentialHistogramDataPointSum != 0\n}\n\nconst fieldBlockExponentialHistogramDataPointMin = uint64(1 >> 6)\nconst fieldBitExponentialHistogramDataPointMin = uint64(1 << 1 & 0x3F)\n\nfunc (m *ExponentialHistogramDataPoint) SetMin(value float64) {\n\tm.Min = value\n\tm.metadata[fieldBlockExponentialHistogramDataPointMin] |= fieldBitExponentialHistogramDataPointMin\n}\n\nfunc (m *ExponentialHistogramDataPoint) RemoveMin() {\n\tm.Min = float64(0)\n\tm.metadata[fieldBlockExponentialHistogramDataPointMin] &^= fieldBitExponentialHistogramDataPointMin\n}\n\nfunc (m *ExponentialHistogramDataPoint) HasMin() bool {\n\treturn m.metadata[fieldBlockExponentialHistogramDataPointMin]&fieldBitExponentialHistogramDataPointMin != 0\n}\n\nconst fieldBlockExponentialHistogramDataPointMax = uint64(2 >> 6)\nconst fieldBitExponentialHistogramDataPointMax = uint64(1 << 2 & 0x3F)\n\nfunc (m *ExponentialHistogramDataPoint) SetMax(value float64) {\n\tm.Max = value\n\tm.metadata[fieldBlockExponentialHistogramDataPointMax] |= fieldBitExponentialHistogramDataPointMax\n}\n\nfunc (m *ExponentialHistogramDataPoint) RemoveMax() {\n\tm.Max = float64(0)\n\tm.metadata[fieldBlockExponentialHistogramDataPointMax] &^= fieldBitExponentialHistogramDataPointMax\n}\n\nfunc (m *ExponentialHistogramDataPoint) HasMax() bool {\n\treturn m.metadata[fieldBlockExponentialHistogramDataPointMax]&fieldBitExponentialHistogramDataPointMax != 0\n}\n\nfunc GenTestExponentialHistogramDataPoint() *ExponentialHistogramDataPoint {\n\torig := NewExponentialHistogramDataPoint()\n\torig.Attributes = []KeyValue{{}, *GenTestKeyValue()}\n\torig.StartTimeUnixNano = uint64(13)\n\torig.TimeUnixNano = uint64(13)\n\torig.Count = uint64(13)\n\torig.SetSum(float64(3.1415926))\n\torig.Scale = int32(13)\n\torig.ZeroCount = uint64(13)\n\torig.Positive = *GenTestExponentialHistogramDataPointBuckets()\n\torig.Negative = *GenTestExponentialHistogramDataPointBuckets()\n\torig.Flags = uint32(13)\n\torig.Exemplars = []Exemplar{{}, *GenTestExemplar()}\n\torig.SetMin(float64(3.1415926))\n\torig.SetMax(float64(3.1415926))\n\torig.ZeroThreshold = float64(3.1415926)\n\treturn orig\n}\n\nfunc GenTestExponentialHistogramDataPointPtrSlice() []*ExponentialHistogramDataPoint {\n\torig := make([]*ExponentialHistogramDataPoint, 5)\n\torig[0] = NewExponentialHistogramDataPoint()\n\torig[1] = GenTestExponentialHistogramDataPoint()\n\torig[2] = NewExponentialHistogramDataPoint()\n\torig[3] = GenTestExponentialHistogramDataPoint()\n\torig[4] = NewExponentialHistogramDataPoint()\n\treturn orig\n}\n\nfunc GenTestExponentialHistogramDataPointSlice() []ExponentialHistogramDataPoint {\n\torig := make([]ExponentialHistogramDataPoint, 5)\n\torig[1] = *GenTestExponentialHistogramDataPoint()\n\torig[3] = *GenTestExponentialHistogramDataPoint()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exponentialhistogramdatapoint_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyExponentialHistogramDataPoint(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExponentialHistogramDataPoint() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewExponentialHistogramDataPoint()\n\t\t\t\tCopyExponentialHistogramDataPoint(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyExponentialHistogramDataPoint(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyExponentialHistogramDataPointSlice(t *testing.T) {\n\tsrc := []ExponentialHistogramDataPoint{}\n\tdest := []ExponentialHistogramDataPoint{}\n\t// Test CopyTo empty\n\tdest = CopyExponentialHistogramDataPointSlice(dest, src)\n\tassert.Equal(t, []ExponentialHistogramDataPoint{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExponentialHistogramDataPointSlice()\n\tdest = CopyExponentialHistogramDataPointSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramDataPointSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExponentialHistogramDataPointSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramDataPointSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExponentialHistogramDataPointSlice(dest, []ExponentialHistogramDataPoint{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExponentialHistogramDataPointSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramDataPointSlice(), dest)\n}\n\nfunc TestCopyExponentialHistogramDataPointPtrSlice(t *testing.T) {\n\tsrc := []*ExponentialHistogramDataPoint{}\n\tdest := []*ExponentialHistogramDataPoint{}\n\t// Test CopyTo empty\n\tdest = CopyExponentialHistogramDataPointPtrSlice(dest, src)\n\tassert.Equal(t, []*ExponentialHistogramDataPoint{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExponentialHistogramDataPointPtrSlice()\n\tdest = CopyExponentialHistogramDataPointPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramDataPointPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExponentialHistogramDataPointPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramDataPointPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExponentialHistogramDataPointPtrSlice(dest, []*ExponentialHistogramDataPoint{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExponentialHistogramDataPointPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramDataPointPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExponentialHistogramDataPointUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewExponentialHistogramDataPoint()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewExponentialHistogramDataPoint(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExponentialHistogramDataPoint(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExponentialHistogramDataPoint() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewExponentialHistogramDataPoint()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExponentialHistogramDataPoint(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExponentialHistogramDataPointFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesExponentialHistogramDataPoint() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewExponentialHistogramDataPoint()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExponentialHistogramDataPointUnknown(t *testing.T) {\n\tdest := NewExponentialHistogramDataPoint()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewExponentialHistogramDataPoint(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoExponentialHistogramDataPoint(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExponentialHistogramDataPoint() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewExponentialHistogramDataPoint()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExponentialHistogramDataPoint(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufExponentialHistogramDataPoint(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExponentialHistogramDataPoint() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpmetrics.ExponentialHistogramDataPoint{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewExponentialHistogramDataPoint()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesExponentialHistogramDataPoint() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                     {0x02},\n\t\t\"Attributes/wrong_wire_type\":        {0xc},\n\t\t\"Attributes/missing_value\":          {0xa},\n\t\t\"StartTimeUnixNano/wrong_wire_type\": {0x14},\n\t\t\"StartTimeUnixNano/missing_value\":   {0x11},\n\t\t\"TimeUnixNano/wrong_wire_type\":      {0x1c},\n\t\t\"TimeUnixNano/missing_value\":        {0x19},\n\t\t\"Count/wrong_wire_type\":             {0x24},\n\t\t\"Count/missing_value\":               {0x21},\n\t\t\"Sum/wrong_wire_type\":               {0x2c},\n\t\t\"Sum/missing_value\":                 {0x29},\n\t\t\"Scale/wrong_wire_type\":             {0x34},\n\t\t\"Scale/missing_value\":               {0x30},\n\t\t\"ZeroCount/wrong_wire_type\":         {0x3c},\n\t\t\"ZeroCount/missing_value\":           {0x39},\n\t\t\"Positive/wrong_wire_type\":          {0x44},\n\t\t\"Positive/missing_value\":            {0x42},\n\t\t\"Negative/wrong_wire_type\":          {0x4c},\n\t\t\"Negative/missing_value\":            {0x4a},\n\t\t\"Flags/wrong_wire_type\":             {0x54},\n\t\t\"Flags/missing_value\":               {0x50},\n\t\t\"Exemplars/wrong_wire_type\":         {0x5c},\n\t\t\"Exemplars/missing_value\":           {0x5a},\n\t\t\"Min/wrong_wire_type\":               {0x64},\n\t\t\"Min/missing_value\":                 {0x61},\n\t\t\"Max/wrong_wire_type\":               {0x6c},\n\t\t\"Max/missing_value\":                 {0x69},\n\t\t\"ZeroThreshold/wrong_wire_type\":     {0x74},\n\t\t\"ZeroThreshold/missing_value\":       {0x71},\n\t}\n}\n\nfunc genTestEncodingValuesExponentialHistogramDataPoint() map[string]*ExponentialHistogramDataPoint {\n\treturn map[string]*ExponentialHistogramDataPoint{\n\t\t\"empty\":                  NewExponentialHistogramDataPoint(),\n\t\t\"Attributes/test\":        {Attributes: []KeyValue{{}, *GenTestKeyValue()}},\n\t\t\"StartTimeUnixNano/test\": {StartTimeUnixNano: uint64(13)},\n\t\t\"TimeUnixNano/test\":      {TimeUnixNano: uint64(13)},\n\t\t\"Count/test\":             {Count: uint64(13)},\n\t\t\"Sum/test\": func() *ExponentialHistogramDataPoint {\n\t\t\tms := NewExponentialHistogramDataPoint()\n\t\t\tms.SetSum(float64(3.1415926))\n\t\t\treturn ms\n\t\t}(),\n\t\t\"Scale/test\":     {Scale: int32(13)},\n\t\t\"ZeroCount/test\": {ZeroCount: uint64(13)},\n\t\t\"Positive/test\":  {Positive: *GenTestExponentialHistogramDataPointBuckets()},\n\t\t\"Negative/test\":  {Negative: *GenTestExponentialHistogramDataPointBuckets()},\n\t\t\"Flags/test\":     {Flags: uint32(13)},\n\t\t\"Exemplars/test\": {Exemplars: []Exemplar{{}, *GenTestExemplar()}},\n\t\t\"Min/test\": func() *ExponentialHistogramDataPoint {\n\t\t\tms := NewExponentialHistogramDataPoint()\n\t\t\tms.SetMin(float64(3.1415926))\n\t\t\treturn ms\n\t\t}(),\n\t\t\"Max/test\": func() *ExponentialHistogramDataPoint {\n\t\t\tms := NewExponentialHistogramDataPoint()\n\t\t\tms.SetMax(float64(3.1415926))\n\t\t\treturn ms\n\t\t}(),\n\t\t\"ZeroThreshold/test\": {ZeroThreshold: float64(3.1415926)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exponentialhistogramdatapointbuckets.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ExponentialHistogramDataPointBuckets are a set of bucket counts, encoded in a contiguous array of counts.\ntype ExponentialHistogramDataPointBuckets struct {\n\tBucketCounts []uint64\n\tOffset       int32\n}\n\nvar (\n\tprotoPoolExponentialHistogramDataPointBuckets = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ExponentialHistogramDataPointBuckets{}\n\t\t},\n\t}\n)\n\nfunc NewExponentialHistogramDataPointBuckets() *ExponentialHistogramDataPointBuckets {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ExponentialHistogramDataPointBuckets{}\n\t}\n\treturn protoPoolExponentialHistogramDataPointBuckets.Get().(*ExponentialHistogramDataPointBuckets)\n}\n\nfunc DeleteExponentialHistogramDataPointBuckets(orig *ExponentialHistogramDataPointBuckets, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolExponentialHistogramDataPointBuckets.Put(orig)\n\t}\n}\n\nfunc CopyExponentialHistogramDataPointBuckets(dest, src *ExponentialHistogramDataPointBuckets) *ExponentialHistogramDataPointBuckets {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewExponentialHistogramDataPointBuckets()\n\t}\n\tdest.Offset = src.Offset\n\tdest.BucketCounts = append(dest.BucketCounts[:0], src.BucketCounts...)\n\n\treturn dest\n}\n\nfunc CopyExponentialHistogramDataPointBucketsSlice(dest, src []ExponentialHistogramDataPointBuckets) []ExponentialHistogramDataPointBuckets {\n\tvar newDest []ExponentialHistogramDataPointBuckets\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ExponentialHistogramDataPointBuckets, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExponentialHistogramDataPointBuckets(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExponentialHistogramDataPointBuckets(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyExponentialHistogramDataPointBucketsPtrSlice(dest, src []*ExponentialHistogramDataPointBuckets) []*ExponentialHistogramDataPointBuckets {\n\tvar newDest []*ExponentialHistogramDataPointBuckets\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ExponentialHistogramDataPointBuckets, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExponentialHistogramDataPointBuckets()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExponentialHistogramDataPointBuckets(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExponentialHistogramDataPointBuckets()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExponentialHistogramDataPointBuckets(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ExponentialHistogramDataPointBuckets) Reset() {\n\t*orig = ExponentialHistogramDataPointBuckets{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ExponentialHistogramDataPointBuckets) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.Offset != int32(0) {\n\t\tdest.WriteObjectField(\"offset\")\n\t\tdest.WriteInt32(orig.Offset)\n\t}\n\tif len(orig.BucketCounts) > 0 {\n\t\tdest.WriteObjectField(\"bucketCounts\")\n\t\tdest.WriteArrayStart()\n\t\tdest.WriteUint64(orig.BucketCounts[0])\n\t\tfor i := 1; i < len(orig.BucketCounts); i++ {\n\t\t\tdest.WriteMore()\n\t\t\tdest.WriteUint64(orig.BucketCounts[i])\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ExponentialHistogramDataPointBuckets) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"offset\":\n\t\t\torig.Offset = iter.ReadInt32()\n\t\tcase \"bucketCounts\", \"bucket_counts\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.BucketCounts = append(orig.BucketCounts, iter.ReadUint64())\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ExponentialHistogramDataPointBuckets) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.Offset != int32(0) {\n\t\tn += 1 + proto.Soz(uint64(orig.Offset))\n\t}\n\n\tif len(orig.BucketCounts) > 0 {\n\t\tl = 0\n\t\tfor _, e := range orig.BucketCounts {\n\t\t\tl += proto.Sov(uint64(e))\n\t\t}\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ExponentialHistogramDataPointBuckets) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.Offset != int32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64((uint32(orig.Offset)<<1)^uint32(orig.Offset>>31)))\n\t\tpos--\n\t\tbuf[pos] = 0x8\n\t}\n\tl = len(orig.BucketCounts)\n\tif l > 0 {\n\t\tendPos := pos\n\t\tfor i := l - 1; i >= 0; i-- {\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.BucketCounts[i]))\n\t\t}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(endPos-pos))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ExponentialHistogramDataPointBuckets) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Offset\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Offset = int32(uint32(num>>1) ^ uint32(int32((num&1)<<31)>>31))\n\t\tcase 2:\n\t\t\tswitch wireType {\n\t\t\tcase proto.WireTypeLen:\n\t\t\t\tvar length int\n\t\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tstartPos := pos - length\n\t\t\t\tvar num uint64\n\t\t\t\tfor startPos < pos {\n\t\t\t\t\tnum, startPos, err = proto.ConsumeVarint(buf[:pos], startPos)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\torig.BucketCounts = append(orig.BucketCounts, uint64(num))\n\t\t\t\t}\n\t\t\t\tif startPos != pos {\n\t\t\t\t\treturn fmt.Errorf(\"proto: invalid field len = %d for field BucketCounts\", pos-startPos)\n\t\t\t\t}\n\t\t\tcase proto.WireTypeVarint:\n\t\t\t\tvar num uint64\n\t\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\torig.BucketCounts = append(orig.BucketCounts, uint64(num))\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field BucketCounts\", wireType)\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestExponentialHistogramDataPointBuckets() *ExponentialHistogramDataPointBuckets {\n\torig := NewExponentialHistogramDataPointBuckets()\n\torig.Offset = int32(13)\n\torig.BucketCounts = []uint64{uint64(0), uint64(13)}\n\treturn orig\n}\n\nfunc GenTestExponentialHistogramDataPointBucketsPtrSlice() []*ExponentialHistogramDataPointBuckets {\n\torig := make([]*ExponentialHistogramDataPointBuckets, 5)\n\torig[0] = NewExponentialHistogramDataPointBuckets()\n\torig[1] = GenTestExponentialHistogramDataPointBuckets()\n\torig[2] = NewExponentialHistogramDataPointBuckets()\n\torig[3] = GenTestExponentialHistogramDataPointBuckets()\n\torig[4] = NewExponentialHistogramDataPointBuckets()\n\treturn orig\n}\n\nfunc GenTestExponentialHistogramDataPointBucketsSlice() []ExponentialHistogramDataPointBuckets {\n\torig := make([]ExponentialHistogramDataPointBuckets, 5)\n\torig[1] = *GenTestExponentialHistogramDataPointBuckets()\n\torig[3] = *GenTestExponentialHistogramDataPointBuckets()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exponentialhistogramdatapointbuckets_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyExponentialHistogramDataPointBuckets(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExponentialHistogramDataPointBuckets() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewExponentialHistogramDataPointBuckets()\n\t\t\t\tCopyExponentialHistogramDataPointBuckets(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyExponentialHistogramDataPointBuckets(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyExponentialHistogramDataPointBucketsSlice(t *testing.T) {\n\tsrc := []ExponentialHistogramDataPointBuckets{}\n\tdest := []ExponentialHistogramDataPointBuckets{}\n\t// Test CopyTo empty\n\tdest = CopyExponentialHistogramDataPointBucketsSlice(dest, src)\n\tassert.Equal(t, []ExponentialHistogramDataPointBuckets{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExponentialHistogramDataPointBucketsSlice()\n\tdest = CopyExponentialHistogramDataPointBucketsSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramDataPointBucketsSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExponentialHistogramDataPointBucketsSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramDataPointBucketsSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExponentialHistogramDataPointBucketsSlice(dest, []ExponentialHistogramDataPointBuckets{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExponentialHistogramDataPointBucketsSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramDataPointBucketsSlice(), dest)\n}\n\nfunc TestCopyExponentialHistogramDataPointBucketsPtrSlice(t *testing.T) {\n\tsrc := []*ExponentialHistogramDataPointBuckets{}\n\tdest := []*ExponentialHistogramDataPointBuckets{}\n\t// Test CopyTo empty\n\tdest = CopyExponentialHistogramDataPointBucketsPtrSlice(dest, src)\n\tassert.Equal(t, []*ExponentialHistogramDataPointBuckets{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExponentialHistogramDataPointBucketsPtrSlice()\n\tdest = CopyExponentialHistogramDataPointBucketsPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramDataPointBucketsPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExponentialHistogramDataPointBucketsPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramDataPointBucketsPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExponentialHistogramDataPointBucketsPtrSlice(dest, []*ExponentialHistogramDataPointBuckets{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExponentialHistogramDataPointBucketsPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExponentialHistogramDataPointBucketsPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExponentialHistogramDataPointBucketsUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewExponentialHistogramDataPointBuckets()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewExponentialHistogramDataPointBuckets(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExponentialHistogramDataPointBuckets(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExponentialHistogramDataPointBuckets() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewExponentialHistogramDataPointBuckets()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExponentialHistogramDataPointBuckets(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExponentialHistogramDataPointBucketsFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesExponentialHistogramDataPointBuckets() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewExponentialHistogramDataPointBuckets()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExponentialHistogramDataPointBucketsUnknown(t *testing.T) {\n\tdest := NewExponentialHistogramDataPointBuckets()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewExponentialHistogramDataPointBuckets(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoExponentialHistogramDataPointBuckets(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExponentialHistogramDataPointBuckets() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewExponentialHistogramDataPointBuckets()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExponentialHistogramDataPointBuckets(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufExponentialHistogramDataPointBuckets(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExponentialHistogramDataPointBuckets() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpmetrics.ExponentialHistogramDataPoint_Buckets{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewExponentialHistogramDataPointBuckets()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesExponentialHistogramDataPointBuckets() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                {0x02},\n\t\t\"Offset/wrong_wire_type\":       {0xc},\n\t\t\"Offset/missing_value\":         {0x8},\n\t\t\"BucketCounts/wrong_wire_type\": {0x14},\n\t\t\"BucketCounts/missing_value\":   {0x12},\n\t}\n}\n\nfunc genTestEncodingValuesExponentialHistogramDataPointBuckets() map[string]*ExponentialHistogramDataPointBuckets {\n\treturn map[string]*ExponentialHistogramDataPointBuckets{\n\t\t\"empty\":             NewExponentialHistogramDataPointBuckets(),\n\t\t\"Offset/test\":       {Offset: int32(13)},\n\t\t\"BucketCounts/test\": {BucketCounts: []uint64{uint64(0), uint64(13)}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportlogspartialsuccess.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ExportPartialSuccess represents the details of a partially successful export request.\ntype ExportLogsPartialSuccess struct {\n\tErrorMessage       string\n\tRejectedLogRecords int64\n}\n\nvar (\n\tprotoPoolExportLogsPartialSuccess = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ExportLogsPartialSuccess{}\n\t\t},\n\t}\n)\n\nfunc NewExportLogsPartialSuccess() *ExportLogsPartialSuccess {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ExportLogsPartialSuccess{}\n\t}\n\treturn protoPoolExportLogsPartialSuccess.Get().(*ExportLogsPartialSuccess)\n}\n\nfunc DeleteExportLogsPartialSuccess(orig *ExportLogsPartialSuccess, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolExportLogsPartialSuccess.Put(orig)\n\t}\n}\n\nfunc CopyExportLogsPartialSuccess(dest, src *ExportLogsPartialSuccess) *ExportLogsPartialSuccess {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewExportLogsPartialSuccess()\n\t}\n\tdest.RejectedLogRecords = src.RejectedLogRecords\n\tdest.ErrorMessage = src.ErrorMessage\n\n\treturn dest\n}\n\nfunc CopyExportLogsPartialSuccessSlice(dest, src []ExportLogsPartialSuccess) []ExportLogsPartialSuccess {\n\tvar newDest []ExportLogsPartialSuccess\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ExportLogsPartialSuccess, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportLogsPartialSuccess(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportLogsPartialSuccess(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyExportLogsPartialSuccessPtrSlice(dest, src []*ExportLogsPartialSuccess) []*ExportLogsPartialSuccess {\n\tvar newDest []*ExportLogsPartialSuccess\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ExportLogsPartialSuccess, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportLogsPartialSuccess()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportLogsPartialSuccess(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportLogsPartialSuccess()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportLogsPartialSuccess(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ExportLogsPartialSuccess) Reset() {\n\t*orig = ExportLogsPartialSuccess{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ExportLogsPartialSuccess) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.RejectedLogRecords != int64(0) {\n\t\tdest.WriteObjectField(\"rejectedLogRecords\")\n\t\tdest.WriteInt64(orig.RejectedLogRecords)\n\t}\n\tif orig.ErrorMessage != \"\" {\n\t\tdest.WriteObjectField(\"errorMessage\")\n\t\tdest.WriteString(orig.ErrorMessage)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ExportLogsPartialSuccess) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"rejectedLogRecords\", \"rejected_log_records\":\n\t\t\torig.RejectedLogRecords = iter.ReadInt64()\n\t\tcase \"errorMessage\", \"error_message\":\n\t\t\torig.ErrorMessage = iter.ReadString()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ExportLogsPartialSuccess) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.RejectedLogRecords != int64(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.RejectedLogRecords))\n\t}\n\n\tl = len(orig.ErrorMessage)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ExportLogsPartialSuccess) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.RejectedLogRecords != int64(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.RejectedLogRecords))\n\t\tpos--\n\t\tbuf[pos] = 0x8\n\t}\n\tl = len(orig.ErrorMessage)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.ErrorMessage)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ExportLogsPartialSuccess) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field RejectedLogRecords\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.RejectedLogRecords = int64(num)\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ErrorMessage\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.ErrorMessage = string(buf[startPos:pos])\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestExportLogsPartialSuccess() *ExportLogsPartialSuccess {\n\torig := NewExportLogsPartialSuccess()\n\torig.RejectedLogRecords = int64(13)\n\torig.ErrorMessage = \"test_errormessage\"\n\treturn orig\n}\n\nfunc GenTestExportLogsPartialSuccessPtrSlice() []*ExportLogsPartialSuccess {\n\torig := make([]*ExportLogsPartialSuccess, 5)\n\torig[0] = NewExportLogsPartialSuccess()\n\torig[1] = GenTestExportLogsPartialSuccess()\n\torig[2] = NewExportLogsPartialSuccess()\n\torig[3] = GenTestExportLogsPartialSuccess()\n\torig[4] = NewExportLogsPartialSuccess()\n\treturn orig\n}\n\nfunc GenTestExportLogsPartialSuccessSlice() []ExportLogsPartialSuccess {\n\torig := make([]ExportLogsPartialSuccess, 5)\n\torig[1] = *GenTestExportLogsPartialSuccess()\n\torig[3] = *GenTestExportLogsPartialSuccess()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportlogspartialsuccess_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcollectorlogs \"go.opentelemetry.io/proto/slim/otlp/collector/logs/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyExportLogsPartialSuccess(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportLogsPartialSuccess() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewExportLogsPartialSuccess()\n\t\t\t\tCopyExportLogsPartialSuccess(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyExportLogsPartialSuccess(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyExportLogsPartialSuccessSlice(t *testing.T) {\n\tsrc := []ExportLogsPartialSuccess{}\n\tdest := []ExportLogsPartialSuccess{}\n\t// Test CopyTo empty\n\tdest = CopyExportLogsPartialSuccessSlice(dest, src)\n\tassert.Equal(t, []ExportLogsPartialSuccess{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportLogsPartialSuccessSlice()\n\tdest = CopyExportLogsPartialSuccessSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsPartialSuccessSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportLogsPartialSuccessSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsPartialSuccessSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportLogsPartialSuccessSlice(dest, []ExportLogsPartialSuccess{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportLogsPartialSuccessSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsPartialSuccessSlice(), dest)\n}\n\nfunc TestCopyExportLogsPartialSuccessPtrSlice(t *testing.T) {\n\tsrc := []*ExportLogsPartialSuccess{}\n\tdest := []*ExportLogsPartialSuccess{}\n\t// Test CopyTo empty\n\tdest = CopyExportLogsPartialSuccessPtrSlice(dest, src)\n\tassert.Equal(t, []*ExportLogsPartialSuccess{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportLogsPartialSuccessPtrSlice()\n\tdest = CopyExportLogsPartialSuccessPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsPartialSuccessPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportLogsPartialSuccessPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsPartialSuccessPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportLogsPartialSuccessPtrSlice(dest, []*ExportLogsPartialSuccess{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportLogsPartialSuccessPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsPartialSuccessPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportLogsPartialSuccessUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewExportLogsPartialSuccess()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewExportLogsPartialSuccess(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportLogsPartialSuccess(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportLogsPartialSuccess() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewExportLogsPartialSuccess()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportLogsPartialSuccess(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportLogsPartialSuccessFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesExportLogsPartialSuccess() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewExportLogsPartialSuccess()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportLogsPartialSuccessUnknown(t *testing.T) {\n\tdest := NewExportLogsPartialSuccess()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewExportLogsPartialSuccess(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoExportLogsPartialSuccess(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportLogsPartialSuccess() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewExportLogsPartialSuccess()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportLogsPartialSuccess(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufExportLogsPartialSuccess(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportLogsPartialSuccess() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcollectorlogs.ExportLogsPartialSuccess{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewExportLogsPartialSuccess()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesExportLogsPartialSuccess() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                      {0x02},\n\t\t\"RejectedLogRecords/wrong_wire_type\": {0xc},\n\t\t\"RejectedLogRecords/missing_value\":   {0x8},\n\t\t\"ErrorMessage/wrong_wire_type\":       {0x14},\n\t\t\"ErrorMessage/missing_value\":         {0x12},\n\t}\n}\n\nfunc genTestEncodingValuesExportLogsPartialSuccess() map[string]*ExportLogsPartialSuccess {\n\treturn map[string]*ExportLogsPartialSuccess{\n\t\t\"empty\":                   NewExportLogsPartialSuccess(),\n\t\t\"RejectedLogRecords/test\": {RejectedLogRecords: int64(13)},\n\t\t\"ErrorMessage/test\":       {ErrorMessage: \"test_errormessage\"},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportlogsservicerequest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Logs is the top-level struct that is propagated through the logs pipeline.\n// Use NewLogs to create new instance, zero-initialized instance is not valid for use.\ntype ExportLogsServiceRequest struct {\n\tResourceLogs []*ResourceLogs\n}\n\nvar (\n\tprotoPoolExportLogsServiceRequest = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ExportLogsServiceRequest{}\n\t\t},\n\t}\n)\n\nfunc NewExportLogsServiceRequest() *ExportLogsServiceRequest {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ExportLogsServiceRequest{}\n\t}\n\treturn protoPoolExportLogsServiceRequest.Get().(*ExportLogsServiceRequest)\n}\n\nfunc DeleteExportLogsServiceRequest(orig *ExportLogsServiceRequest, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.ResourceLogs {\n\t\tDeleteResourceLogs(orig.ResourceLogs[i], true)\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolExportLogsServiceRequest.Put(orig)\n\t}\n}\n\nfunc CopyExportLogsServiceRequest(dest, src *ExportLogsServiceRequest) *ExportLogsServiceRequest {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewExportLogsServiceRequest()\n\t}\n\tdest.ResourceLogs = CopyResourceLogsPtrSlice(dest.ResourceLogs, src.ResourceLogs)\n\n\treturn dest\n}\n\nfunc CopyExportLogsServiceRequestSlice(dest, src []ExportLogsServiceRequest) []ExportLogsServiceRequest {\n\tvar newDest []ExportLogsServiceRequest\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ExportLogsServiceRequest, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportLogsServiceRequest(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportLogsServiceRequest(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyExportLogsServiceRequestPtrSlice(dest, src []*ExportLogsServiceRequest) []*ExportLogsServiceRequest {\n\tvar newDest []*ExportLogsServiceRequest\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ExportLogsServiceRequest, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportLogsServiceRequest()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportLogsServiceRequest(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportLogsServiceRequest()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportLogsServiceRequest(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ExportLogsServiceRequest) Reset() {\n\t*orig = ExportLogsServiceRequest{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ExportLogsServiceRequest) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.ResourceLogs) > 0 {\n\t\tdest.WriteObjectField(\"resourceLogs\")\n\t\tdest.WriteArrayStart()\n\t\torig.ResourceLogs[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.ResourceLogs); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.ResourceLogs[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ExportLogsServiceRequest) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"resourceLogs\", \"resource_logs\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.ResourceLogs = append(orig.ResourceLogs, NewResourceLogs())\n\t\t\t\torig.ResourceLogs[len(orig.ResourceLogs)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ExportLogsServiceRequest) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.ResourceLogs {\n\t\tl = orig.ResourceLogs[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ExportLogsServiceRequest) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.ResourceLogs) - 1; i >= 0; i-- {\n\t\tl = orig.ResourceLogs[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ExportLogsServiceRequest) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ResourceLogs\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.ResourceLogs = append(orig.ResourceLogs, NewResourceLogs())\n\t\t\terr = orig.ResourceLogs[len(orig.ResourceLogs)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestExportLogsServiceRequest() *ExportLogsServiceRequest {\n\torig := NewExportLogsServiceRequest()\n\torig.ResourceLogs = []*ResourceLogs{{}, GenTestResourceLogs()}\n\treturn orig\n}\n\nfunc GenTestExportLogsServiceRequestPtrSlice() []*ExportLogsServiceRequest {\n\torig := make([]*ExportLogsServiceRequest, 5)\n\torig[0] = NewExportLogsServiceRequest()\n\torig[1] = GenTestExportLogsServiceRequest()\n\torig[2] = NewExportLogsServiceRequest()\n\torig[3] = GenTestExportLogsServiceRequest()\n\torig[4] = NewExportLogsServiceRequest()\n\treturn orig\n}\n\nfunc GenTestExportLogsServiceRequestSlice() []ExportLogsServiceRequest {\n\torig := make([]ExportLogsServiceRequest, 5)\n\torig[1] = *GenTestExportLogsServiceRequest()\n\torig[3] = *GenTestExportLogsServiceRequest()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportlogsservicerequest_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcollectorlogs \"go.opentelemetry.io/proto/slim/otlp/collector/logs/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyExportLogsServiceRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportLogsServiceRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewExportLogsServiceRequest()\n\t\t\t\tCopyExportLogsServiceRequest(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyExportLogsServiceRequest(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyExportLogsServiceRequestSlice(t *testing.T) {\n\tsrc := []ExportLogsServiceRequest{}\n\tdest := []ExportLogsServiceRequest{}\n\t// Test CopyTo empty\n\tdest = CopyExportLogsServiceRequestSlice(dest, src)\n\tassert.Equal(t, []ExportLogsServiceRequest{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportLogsServiceRequestSlice()\n\tdest = CopyExportLogsServiceRequestSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsServiceRequestSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportLogsServiceRequestSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsServiceRequestSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportLogsServiceRequestSlice(dest, []ExportLogsServiceRequest{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportLogsServiceRequestSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsServiceRequestSlice(), dest)\n}\n\nfunc TestCopyExportLogsServiceRequestPtrSlice(t *testing.T) {\n\tsrc := []*ExportLogsServiceRequest{}\n\tdest := []*ExportLogsServiceRequest{}\n\t// Test CopyTo empty\n\tdest = CopyExportLogsServiceRequestPtrSlice(dest, src)\n\tassert.Equal(t, []*ExportLogsServiceRequest{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportLogsServiceRequestPtrSlice()\n\tdest = CopyExportLogsServiceRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsServiceRequestPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportLogsServiceRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsServiceRequestPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportLogsServiceRequestPtrSlice(dest, []*ExportLogsServiceRequest{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportLogsServiceRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsServiceRequestPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportLogsServiceRequestUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewExportLogsServiceRequest()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewExportLogsServiceRequest(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportLogsServiceRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportLogsServiceRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewExportLogsServiceRequest()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportLogsServiceRequest(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportLogsServiceRequestFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesExportLogsServiceRequest() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewExportLogsServiceRequest()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportLogsServiceRequestUnknown(t *testing.T) {\n\tdest := NewExportLogsServiceRequest()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewExportLogsServiceRequest(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoExportLogsServiceRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportLogsServiceRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewExportLogsServiceRequest()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportLogsServiceRequest(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufExportLogsServiceRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportLogsServiceRequest() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcollectorlogs.ExportLogsServiceRequest{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewExportLogsServiceRequest()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesExportLogsServiceRequest() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                {0x02},\n\t\t\"ResourceLogs/wrong_wire_type\": {0xc},\n\t\t\"ResourceLogs/missing_value\":   {0xa},\n\t}\n}\n\nfunc genTestEncodingValuesExportLogsServiceRequest() map[string]*ExportLogsServiceRequest {\n\treturn map[string]*ExportLogsServiceRequest{\n\t\t\"empty\":             NewExportLogsServiceRequest(),\n\t\t\"ResourceLogs/test\": {ResourceLogs: []*ResourceLogs{{}, GenTestResourceLogs()}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportlogsserviceresponse.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ExportResponse represents the response for gRPC/HTTP client/server.\ntype ExportLogsServiceResponse struct {\n\tPartialSuccess ExportLogsPartialSuccess\n}\n\nvar (\n\tprotoPoolExportLogsServiceResponse = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ExportLogsServiceResponse{}\n\t\t},\n\t}\n)\n\nfunc NewExportLogsServiceResponse() *ExportLogsServiceResponse {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ExportLogsServiceResponse{}\n\t}\n\treturn protoPoolExportLogsServiceResponse.Get().(*ExportLogsServiceResponse)\n}\n\nfunc DeleteExportLogsServiceResponse(orig *ExportLogsServiceResponse, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteExportLogsPartialSuccess(&orig.PartialSuccess, false)\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolExportLogsServiceResponse.Put(orig)\n\t}\n}\n\nfunc CopyExportLogsServiceResponse(dest, src *ExportLogsServiceResponse) *ExportLogsServiceResponse {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewExportLogsServiceResponse()\n\t}\n\tCopyExportLogsPartialSuccess(&dest.PartialSuccess, &src.PartialSuccess)\n\n\treturn dest\n}\n\nfunc CopyExportLogsServiceResponseSlice(dest, src []ExportLogsServiceResponse) []ExportLogsServiceResponse {\n\tvar newDest []ExportLogsServiceResponse\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ExportLogsServiceResponse, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportLogsServiceResponse(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportLogsServiceResponse(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyExportLogsServiceResponsePtrSlice(dest, src []*ExportLogsServiceResponse) []*ExportLogsServiceResponse {\n\tvar newDest []*ExportLogsServiceResponse\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ExportLogsServiceResponse, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportLogsServiceResponse()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportLogsServiceResponse(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportLogsServiceResponse()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportLogsServiceResponse(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ExportLogsServiceResponse) Reset() {\n\t*orig = ExportLogsServiceResponse{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ExportLogsServiceResponse) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tdest.WriteObjectField(\"partialSuccess\")\n\torig.PartialSuccess.MarshalJSON(dest)\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ExportLogsServiceResponse) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"partialSuccess\", \"partial_success\":\n\n\t\t\torig.PartialSuccess.UnmarshalJSON(iter)\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ExportLogsServiceResponse) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tl = orig.PartialSuccess.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\treturn n\n}\n\nfunc (orig *ExportLogsServiceResponse) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = orig.PartialSuccess.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0xa\n\n\treturn len(buf) - pos\n}\n\nfunc (orig *ExportLogsServiceResponse) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field PartialSuccess\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.PartialSuccess.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestExportLogsServiceResponse() *ExportLogsServiceResponse {\n\torig := NewExportLogsServiceResponse()\n\torig.PartialSuccess = *GenTestExportLogsPartialSuccess()\n\treturn orig\n}\n\nfunc GenTestExportLogsServiceResponsePtrSlice() []*ExportLogsServiceResponse {\n\torig := make([]*ExportLogsServiceResponse, 5)\n\torig[0] = NewExportLogsServiceResponse()\n\torig[1] = GenTestExportLogsServiceResponse()\n\torig[2] = NewExportLogsServiceResponse()\n\torig[3] = GenTestExportLogsServiceResponse()\n\torig[4] = NewExportLogsServiceResponse()\n\treturn orig\n}\n\nfunc GenTestExportLogsServiceResponseSlice() []ExportLogsServiceResponse {\n\torig := make([]ExportLogsServiceResponse, 5)\n\torig[1] = *GenTestExportLogsServiceResponse()\n\torig[3] = *GenTestExportLogsServiceResponse()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportlogsserviceresponse_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcollectorlogs \"go.opentelemetry.io/proto/slim/otlp/collector/logs/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyExportLogsServiceResponse(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportLogsServiceResponse() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewExportLogsServiceResponse()\n\t\t\t\tCopyExportLogsServiceResponse(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyExportLogsServiceResponse(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyExportLogsServiceResponseSlice(t *testing.T) {\n\tsrc := []ExportLogsServiceResponse{}\n\tdest := []ExportLogsServiceResponse{}\n\t// Test CopyTo empty\n\tdest = CopyExportLogsServiceResponseSlice(dest, src)\n\tassert.Equal(t, []ExportLogsServiceResponse{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportLogsServiceResponseSlice()\n\tdest = CopyExportLogsServiceResponseSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsServiceResponseSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportLogsServiceResponseSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsServiceResponseSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportLogsServiceResponseSlice(dest, []ExportLogsServiceResponse{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportLogsServiceResponseSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsServiceResponseSlice(), dest)\n}\n\nfunc TestCopyExportLogsServiceResponsePtrSlice(t *testing.T) {\n\tsrc := []*ExportLogsServiceResponse{}\n\tdest := []*ExportLogsServiceResponse{}\n\t// Test CopyTo empty\n\tdest = CopyExportLogsServiceResponsePtrSlice(dest, src)\n\tassert.Equal(t, []*ExportLogsServiceResponse{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportLogsServiceResponsePtrSlice()\n\tdest = CopyExportLogsServiceResponsePtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsServiceResponsePtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportLogsServiceResponsePtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsServiceResponsePtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportLogsServiceResponsePtrSlice(dest, []*ExportLogsServiceResponse{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportLogsServiceResponsePtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportLogsServiceResponsePtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportLogsServiceResponseUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewExportLogsServiceResponse()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewExportLogsServiceResponse(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportLogsServiceResponse(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportLogsServiceResponse() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewExportLogsServiceResponse()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportLogsServiceResponse(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportLogsServiceResponseFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesExportLogsServiceResponse() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewExportLogsServiceResponse()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportLogsServiceResponseUnknown(t *testing.T) {\n\tdest := NewExportLogsServiceResponse()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewExportLogsServiceResponse(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoExportLogsServiceResponse(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportLogsServiceResponse() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewExportLogsServiceResponse()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportLogsServiceResponse(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufExportLogsServiceResponse(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportLogsServiceResponse() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcollectorlogs.ExportLogsServiceResponse{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewExportLogsServiceResponse()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesExportLogsServiceResponse() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                  {0x02},\n\t\t\"PartialSuccess/wrong_wire_type\": {0xc},\n\t\t\"PartialSuccess/missing_value\":   {0xa},\n\t}\n}\n\nfunc genTestEncodingValuesExportLogsServiceResponse() map[string]*ExportLogsServiceResponse {\n\treturn map[string]*ExportLogsServiceResponse{\n\t\t\"empty\":               NewExportLogsServiceResponse(),\n\t\t\"PartialSuccess/test\": {PartialSuccess: *GenTestExportLogsPartialSuccess()},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportmetricspartialsuccess.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ExportPartialSuccess represents the details of a partially successful export request.\ntype ExportMetricsPartialSuccess struct {\n\tErrorMessage       string\n\tRejectedDataPoints int64\n}\n\nvar (\n\tprotoPoolExportMetricsPartialSuccess = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ExportMetricsPartialSuccess{}\n\t\t},\n\t}\n)\n\nfunc NewExportMetricsPartialSuccess() *ExportMetricsPartialSuccess {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ExportMetricsPartialSuccess{}\n\t}\n\treturn protoPoolExportMetricsPartialSuccess.Get().(*ExportMetricsPartialSuccess)\n}\n\nfunc DeleteExportMetricsPartialSuccess(orig *ExportMetricsPartialSuccess, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolExportMetricsPartialSuccess.Put(orig)\n\t}\n}\n\nfunc CopyExportMetricsPartialSuccess(dest, src *ExportMetricsPartialSuccess) *ExportMetricsPartialSuccess {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewExportMetricsPartialSuccess()\n\t}\n\tdest.RejectedDataPoints = src.RejectedDataPoints\n\tdest.ErrorMessage = src.ErrorMessage\n\n\treturn dest\n}\n\nfunc CopyExportMetricsPartialSuccessSlice(dest, src []ExportMetricsPartialSuccess) []ExportMetricsPartialSuccess {\n\tvar newDest []ExportMetricsPartialSuccess\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ExportMetricsPartialSuccess, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportMetricsPartialSuccess(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportMetricsPartialSuccess(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyExportMetricsPartialSuccessPtrSlice(dest, src []*ExportMetricsPartialSuccess) []*ExportMetricsPartialSuccess {\n\tvar newDest []*ExportMetricsPartialSuccess\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ExportMetricsPartialSuccess, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportMetricsPartialSuccess()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportMetricsPartialSuccess(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportMetricsPartialSuccess()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportMetricsPartialSuccess(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ExportMetricsPartialSuccess) Reset() {\n\t*orig = ExportMetricsPartialSuccess{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ExportMetricsPartialSuccess) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.RejectedDataPoints != int64(0) {\n\t\tdest.WriteObjectField(\"rejectedDataPoints\")\n\t\tdest.WriteInt64(orig.RejectedDataPoints)\n\t}\n\tif orig.ErrorMessage != \"\" {\n\t\tdest.WriteObjectField(\"errorMessage\")\n\t\tdest.WriteString(orig.ErrorMessage)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ExportMetricsPartialSuccess) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"rejectedDataPoints\", \"rejected_data_points\":\n\t\t\torig.RejectedDataPoints = iter.ReadInt64()\n\t\tcase \"errorMessage\", \"error_message\":\n\t\t\torig.ErrorMessage = iter.ReadString()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ExportMetricsPartialSuccess) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.RejectedDataPoints != int64(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.RejectedDataPoints))\n\t}\n\n\tl = len(orig.ErrorMessage)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ExportMetricsPartialSuccess) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.RejectedDataPoints != int64(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.RejectedDataPoints))\n\t\tpos--\n\t\tbuf[pos] = 0x8\n\t}\n\tl = len(orig.ErrorMessage)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.ErrorMessage)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ExportMetricsPartialSuccess) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field RejectedDataPoints\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.RejectedDataPoints = int64(num)\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ErrorMessage\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.ErrorMessage = string(buf[startPos:pos])\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestExportMetricsPartialSuccess() *ExportMetricsPartialSuccess {\n\torig := NewExportMetricsPartialSuccess()\n\torig.RejectedDataPoints = int64(13)\n\torig.ErrorMessage = \"test_errormessage\"\n\treturn orig\n}\n\nfunc GenTestExportMetricsPartialSuccessPtrSlice() []*ExportMetricsPartialSuccess {\n\torig := make([]*ExportMetricsPartialSuccess, 5)\n\torig[0] = NewExportMetricsPartialSuccess()\n\torig[1] = GenTestExportMetricsPartialSuccess()\n\torig[2] = NewExportMetricsPartialSuccess()\n\torig[3] = GenTestExportMetricsPartialSuccess()\n\torig[4] = NewExportMetricsPartialSuccess()\n\treturn orig\n}\n\nfunc GenTestExportMetricsPartialSuccessSlice() []ExportMetricsPartialSuccess {\n\torig := make([]ExportMetricsPartialSuccess, 5)\n\torig[1] = *GenTestExportMetricsPartialSuccess()\n\torig[3] = *GenTestExportMetricsPartialSuccess()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportmetricspartialsuccess_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcollectormetrics \"go.opentelemetry.io/proto/slim/otlp/collector/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyExportMetricsPartialSuccess(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportMetricsPartialSuccess() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewExportMetricsPartialSuccess()\n\t\t\t\tCopyExportMetricsPartialSuccess(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyExportMetricsPartialSuccess(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyExportMetricsPartialSuccessSlice(t *testing.T) {\n\tsrc := []ExportMetricsPartialSuccess{}\n\tdest := []ExportMetricsPartialSuccess{}\n\t// Test CopyTo empty\n\tdest = CopyExportMetricsPartialSuccessSlice(dest, src)\n\tassert.Equal(t, []ExportMetricsPartialSuccess{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportMetricsPartialSuccessSlice()\n\tdest = CopyExportMetricsPartialSuccessSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsPartialSuccessSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportMetricsPartialSuccessSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsPartialSuccessSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportMetricsPartialSuccessSlice(dest, []ExportMetricsPartialSuccess{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportMetricsPartialSuccessSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsPartialSuccessSlice(), dest)\n}\n\nfunc TestCopyExportMetricsPartialSuccessPtrSlice(t *testing.T) {\n\tsrc := []*ExportMetricsPartialSuccess{}\n\tdest := []*ExportMetricsPartialSuccess{}\n\t// Test CopyTo empty\n\tdest = CopyExportMetricsPartialSuccessPtrSlice(dest, src)\n\tassert.Equal(t, []*ExportMetricsPartialSuccess{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportMetricsPartialSuccessPtrSlice()\n\tdest = CopyExportMetricsPartialSuccessPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsPartialSuccessPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportMetricsPartialSuccessPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsPartialSuccessPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportMetricsPartialSuccessPtrSlice(dest, []*ExportMetricsPartialSuccess{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportMetricsPartialSuccessPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsPartialSuccessPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportMetricsPartialSuccessUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewExportMetricsPartialSuccess()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewExportMetricsPartialSuccess(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportMetricsPartialSuccess(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportMetricsPartialSuccess() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewExportMetricsPartialSuccess()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportMetricsPartialSuccess(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportMetricsPartialSuccessFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesExportMetricsPartialSuccess() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewExportMetricsPartialSuccess()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportMetricsPartialSuccessUnknown(t *testing.T) {\n\tdest := NewExportMetricsPartialSuccess()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewExportMetricsPartialSuccess(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoExportMetricsPartialSuccess(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportMetricsPartialSuccess() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewExportMetricsPartialSuccess()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportMetricsPartialSuccess(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufExportMetricsPartialSuccess(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportMetricsPartialSuccess() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcollectormetrics.ExportMetricsPartialSuccess{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewExportMetricsPartialSuccess()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesExportMetricsPartialSuccess() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                      {0x02},\n\t\t\"RejectedDataPoints/wrong_wire_type\": {0xc},\n\t\t\"RejectedDataPoints/missing_value\":   {0x8},\n\t\t\"ErrorMessage/wrong_wire_type\":       {0x14},\n\t\t\"ErrorMessage/missing_value\":         {0x12},\n\t}\n}\n\nfunc genTestEncodingValuesExportMetricsPartialSuccess() map[string]*ExportMetricsPartialSuccess {\n\treturn map[string]*ExportMetricsPartialSuccess{\n\t\t\"empty\":                   NewExportMetricsPartialSuccess(),\n\t\t\"RejectedDataPoints/test\": {RejectedDataPoints: int64(13)},\n\t\t\"ErrorMessage/test\":       {ErrorMessage: \"test_errormessage\"},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportmetricsservicerequest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Metrics is the top-level struct that is propagated through the metrics pipeline.\n// Use NewMetrics to create new instance, zero-initialized instance is not valid for use.\ntype ExportMetricsServiceRequest struct {\n\tResourceMetrics []*ResourceMetrics\n}\n\nvar (\n\tprotoPoolExportMetricsServiceRequest = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ExportMetricsServiceRequest{}\n\t\t},\n\t}\n)\n\nfunc NewExportMetricsServiceRequest() *ExportMetricsServiceRequest {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ExportMetricsServiceRequest{}\n\t}\n\treturn protoPoolExportMetricsServiceRequest.Get().(*ExportMetricsServiceRequest)\n}\n\nfunc DeleteExportMetricsServiceRequest(orig *ExportMetricsServiceRequest, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.ResourceMetrics {\n\t\tDeleteResourceMetrics(orig.ResourceMetrics[i], true)\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolExportMetricsServiceRequest.Put(orig)\n\t}\n}\n\nfunc CopyExportMetricsServiceRequest(dest, src *ExportMetricsServiceRequest) *ExportMetricsServiceRequest {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewExportMetricsServiceRequest()\n\t}\n\tdest.ResourceMetrics = CopyResourceMetricsPtrSlice(dest.ResourceMetrics, src.ResourceMetrics)\n\n\treturn dest\n}\n\nfunc CopyExportMetricsServiceRequestSlice(dest, src []ExportMetricsServiceRequest) []ExportMetricsServiceRequest {\n\tvar newDest []ExportMetricsServiceRequest\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ExportMetricsServiceRequest, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportMetricsServiceRequest(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportMetricsServiceRequest(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyExportMetricsServiceRequestPtrSlice(dest, src []*ExportMetricsServiceRequest) []*ExportMetricsServiceRequest {\n\tvar newDest []*ExportMetricsServiceRequest\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ExportMetricsServiceRequest, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportMetricsServiceRequest()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportMetricsServiceRequest(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportMetricsServiceRequest()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportMetricsServiceRequest(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ExportMetricsServiceRequest) Reset() {\n\t*orig = ExportMetricsServiceRequest{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ExportMetricsServiceRequest) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.ResourceMetrics) > 0 {\n\t\tdest.WriteObjectField(\"resourceMetrics\")\n\t\tdest.WriteArrayStart()\n\t\torig.ResourceMetrics[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.ResourceMetrics); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.ResourceMetrics[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ExportMetricsServiceRequest) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"resourceMetrics\", \"resource_metrics\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.ResourceMetrics = append(orig.ResourceMetrics, NewResourceMetrics())\n\t\t\t\torig.ResourceMetrics[len(orig.ResourceMetrics)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ExportMetricsServiceRequest) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.ResourceMetrics {\n\t\tl = orig.ResourceMetrics[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ExportMetricsServiceRequest) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.ResourceMetrics) - 1; i >= 0; i-- {\n\t\tl = orig.ResourceMetrics[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ExportMetricsServiceRequest) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ResourceMetrics\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.ResourceMetrics = append(orig.ResourceMetrics, NewResourceMetrics())\n\t\t\terr = orig.ResourceMetrics[len(orig.ResourceMetrics)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestExportMetricsServiceRequest() *ExportMetricsServiceRequest {\n\torig := NewExportMetricsServiceRequest()\n\torig.ResourceMetrics = []*ResourceMetrics{{}, GenTestResourceMetrics()}\n\treturn orig\n}\n\nfunc GenTestExportMetricsServiceRequestPtrSlice() []*ExportMetricsServiceRequest {\n\torig := make([]*ExportMetricsServiceRequest, 5)\n\torig[0] = NewExportMetricsServiceRequest()\n\torig[1] = GenTestExportMetricsServiceRequest()\n\torig[2] = NewExportMetricsServiceRequest()\n\torig[3] = GenTestExportMetricsServiceRequest()\n\torig[4] = NewExportMetricsServiceRequest()\n\treturn orig\n}\n\nfunc GenTestExportMetricsServiceRequestSlice() []ExportMetricsServiceRequest {\n\torig := make([]ExportMetricsServiceRequest, 5)\n\torig[1] = *GenTestExportMetricsServiceRequest()\n\torig[3] = *GenTestExportMetricsServiceRequest()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportmetricsservicerequest_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcollectormetrics \"go.opentelemetry.io/proto/slim/otlp/collector/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyExportMetricsServiceRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportMetricsServiceRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewExportMetricsServiceRequest()\n\t\t\t\tCopyExportMetricsServiceRequest(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyExportMetricsServiceRequest(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyExportMetricsServiceRequestSlice(t *testing.T) {\n\tsrc := []ExportMetricsServiceRequest{}\n\tdest := []ExportMetricsServiceRequest{}\n\t// Test CopyTo empty\n\tdest = CopyExportMetricsServiceRequestSlice(dest, src)\n\tassert.Equal(t, []ExportMetricsServiceRequest{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportMetricsServiceRequestSlice()\n\tdest = CopyExportMetricsServiceRequestSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsServiceRequestSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportMetricsServiceRequestSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsServiceRequestSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportMetricsServiceRequestSlice(dest, []ExportMetricsServiceRequest{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportMetricsServiceRequestSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsServiceRequestSlice(), dest)\n}\n\nfunc TestCopyExportMetricsServiceRequestPtrSlice(t *testing.T) {\n\tsrc := []*ExportMetricsServiceRequest{}\n\tdest := []*ExportMetricsServiceRequest{}\n\t// Test CopyTo empty\n\tdest = CopyExportMetricsServiceRequestPtrSlice(dest, src)\n\tassert.Equal(t, []*ExportMetricsServiceRequest{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportMetricsServiceRequestPtrSlice()\n\tdest = CopyExportMetricsServiceRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsServiceRequestPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportMetricsServiceRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsServiceRequestPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportMetricsServiceRequestPtrSlice(dest, []*ExportMetricsServiceRequest{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportMetricsServiceRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsServiceRequestPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportMetricsServiceRequestUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewExportMetricsServiceRequest()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewExportMetricsServiceRequest(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportMetricsServiceRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportMetricsServiceRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewExportMetricsServiceRequest()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportMetricsServiceRequest(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportMetricsServiceRequestFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesExportMetricsServiceRequest() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewExportMetricsServiceRequest()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportMetricsServiceRequestUnknown(t *testing.T) {\n\tdest := NewExportMetricsServiceRequest()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewExportMetricsServiceRequest(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoExportMetricsServiceRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportMetricsServiceRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewExportMetricsServiceRequest()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportMetricsServiceRequest(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufExportMetricsServiceRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportMetricsServiceRequest() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcollectormetrics.ExportMetricsServiceRequest{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewExportMetricsServiceRequest()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesExportMetricsServiceRequest() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                   {0x02},\n\t\t\"ResourceMetrics/wrong_wire_type\": {0xc},\n\t\t\"ResourceMetrics/missing_value\":   {0xa},\n\t}\n}\n\nfunc genTestEncodingValuesExportMetricsServiceRequest() map[string]*ExportMetricsServiceRequest {\n\treturn map[string]*ExportMetricsServiceRequest{\n\t\t\"empty\":                NewExportMetricsServiceRequest(),\n\t\t\"ResourceMetrics/test\": {ResourceMetrics: []*ResourceMetrics{{}, GenTestResourceMetrics()}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportmetricsserviceresponse.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ExportResponse represents the response for gRPC/HTTP client/server.\ntype ExportMetricsServiceResponse struct {\n\tPartialSuccess ExportMetricsPartialSuccess\n}\n\nvar (\n\tprotoPoolExportMetricsServiceResponse = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ExportMetricsServiceResponse{}\n\t\t},\n\t}\n)\n\nfunc NewExportMetricsServiceResponse() *ExportMetricsServiceResponse {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ExportMetricsServiceResponse{}\n\t}\n\treturn protoPoolExportMetricsServiceResponse.Get().(*ExportMetricsServiceResponse)\n}\n\nfunc DeleteExportMetricsServiceResponse(orig *ExportMetricsServiceResponse, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteExportMetricsPartialSuccess(&orig.PartialSuccess, false)\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolExportMetricsServiceResponse.Put(orig)\n\t}\n}\n\nfunc CopyExportMetricsServiceResponse(dest, src *ExportMetricsServiceResponse) *ExportMetricsServiceResponse {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewExportMetricsServiceResponse()\n\t}\n\tCopyExportMetricsPartialSuccess(&dest.PartialSuccess, &src.PartialSuccess)\n\n\treturn dest\n}\n\nfunc CopyExportMetricsServiceResponseSlice(dest, src []ExportMetricsServiceResponse) []ExportMetricsServiceResponse {\n\tvar newDest []ExportMetricsServiceResponse\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ExportMetricsServiceResponse, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportMetricsServiceResponse(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportMetricsServiceResponse(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyExportMetricsServiceResponsePtrSlice(dest, src []*ExportMetricsServiceResponse) []*ExportMetricsServiceResponse {\n\tvar newDest []*ExportMetricsServiceResponse\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ExportMetricsServiceResponse, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportMetricsServiceResponse()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportMetricsServiceResponse(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportMetricsServiceResponse()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportMetricsServiceResponse(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ExportMetricsServiceResponse) Reset() {\n\t*orig = ExportMetricsServiceResponse{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ExportMetricsServiceResponse) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tdest.WriteObjectField(\"partialSuccess\")\n\torig.PartialSuccess.MarshalJSON(dest)\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ExportMetricsServiceResponse) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"partialSuccess\", \"partial_success\":\n\n\t\t\torig.PartialSuccess.UnmarshalJSON(iter)\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ExportMetricsServiceResponse) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tl = orig.PartialSuccess.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\treturn n\n}\n\nfunc (orig *ExportMetricsServiceResponse) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = orig.PartialSuccess.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0xa\n\n\treturn len(buf) - pos\n}\n\nfunc (orig *ExportMetricsServiceResponse) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field PartialSuccess\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.PartialSuccess.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestExportMetricsServiceResponse() *ExportMetricsServiceResponse {\n\torig := NewExportMetricsServiceResponse()\n\torig.PartialSuccess = *GenTestExportMetricsPartialSuccess()\n\treturn orig\n}\n\nfunc GenTestExportMetricsServiceResponsePtrSlice() []*ExportMetricsServiceResponse {\n\torig := make([]*ExportMetricsServiceResponse, 5)\n\torig[0] = NewExportMetricsServiceResponse()\n\torig[1] = GenTestExportMetricsServiceResponse()\n\torig[2] = NewExportMetricsServiceResponse()\n\torig[3] = GenTestExportMetricsServiceResponse()\n\torig[4] = NewExportMetricsServiceResponse()\n\treturn orig\n}\n\nfunc GenTestExportMetricsServiceResponseSlice() []ExportMetricsServiceResponse {\n\torig := make([]ExportMetricsServiceResponse, 5)\n\torig[1] = *GenTestExportMetricsServiceResponse()\n\torig[3] = *GenTestExportMetricsServiceResponse()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportmetricsserviceresponse_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcollectormetrics \"go.opentelemetry.io/proto/slim/otlp/collector/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyExportMetricsServiceResponse(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportMetricsServiceResponse() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewExportMetricsServiceResponse()\n\t\t\t\tCopyExportMetricsServiceResponse(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyExportMetricsServiceResponse(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyExportMetricsServiceResponseSlice(t *testing.T) {\n\tsrc := []ExportMetricsServiceResponse{}\n\tdest := []ExportMetricsServiceResponse{}\n\t// Test CopyTo empty\n\tdest = CopyExportMetricsServiceResponseSlice(dest, src)\n\tassert.Equal(t, []ExportMetricsServiceResponse{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportMetricsServiceResponseSlice()\n\tdest = CopyExportMetricsServiceResponseSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsServiceResponseSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportMetricsServiceResponseSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsServiceResponseSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportMetricsServiceResponseSlice(dest, []ExportMetricsServiceResponse{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportMetricsServiceResponseSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsServiceResponseSlice(), dest)\n}\n\nfunc TestCopyExportMetricsServiceResponsePtrSlice(t *testing.T) {\n\tsrc := []*ExportMetricsServiceResponse{}\n\tdest := []*ExportMetricsServiceResponse{}\n\t// Test CopyTo empty\n\tdest = CopyExportMetricsServiceResponsePtrSlice(dest, src)\n\tassert.Equal(t, []*ExportMetricsServiceResponse{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportMetricsServiceResponsePtrSlice()\n\tdest = CopyExportMetricsServiceResponsePtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsServiceResponsePtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportMetricsServiceResponsePtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsServiceResponsePtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportMetricsServiceResponsePtrSlice(dest, []*ExportMetricsServiceResponse{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportMetricsServiceResponsePtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportMetricsServiceResponsePtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportMetricsServiceResponseUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewExportMetricsServiceResponse()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewExportMetricsServiceResponse(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportMetricsServiceResponse(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportMetricsServiceResponse() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewExportMetricsServiceResponse()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportMetricsServiceResponse(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportMetricsServiceResponseFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesExportMetricsServiceResponse() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewExportMetricsServiceResponse()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportMetricsServiceResponseUnknown(t *testing.T) {\n\tdest := NewExportMetricsServiceResponse()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewExportMetricsServiceResponse(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoExportMetricsServiceResponse(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportMetricsServiceResponse() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewExportMetricsServiceResponse()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportMetricsServiceResponse(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufExportMetricsServiceResponse(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportMetricsServiceResponse() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcollectormetrics.ExportMetricsServiceResponse{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewExportMetricsServiceResponse()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesExportMetricsServiceResponse() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                  {0x02},\n\t\t\"PartialSuccess/wrong_wire_type\": {0xc},\n\t\t\"PartialSuccess/missing_value\":   {0xa},\n\t}\n}\n\nfunc genTestEncodingValuesExportMetricsServiceResponse() map[string]*ExportMetricsServiceResponse {\n\treturn map[string]*ExportMetricsServiceResponse{\n\t\t\"empty\":               NewExportMetricsServiceResponse(),\n\t\t\"PartialSuccess/test\": {PartialSuccess: *GenTestExportMetricsPartialSuccess()},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportprofilespartialsuccess.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ExportPartialSuccess represents the details of a partially successful export request.\ntype ExportProfilesPartialSuccess struct {\n\tErrorMessage     string\n\tRejectedProfiles int64\n}\n\nvar (\n\tprotoPoolExportProfilesPartialSuccess = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ExportProfilesPartialSuccess{}\n\t\t},\n\t}\n)\n\nfunc NewExportProfilesPartialSuccess() *ExportProfilesPartialSuccess {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ExportProfilesPartialSuccess{}\n\t}\n\treturn protoPoolExportProfilesPartialSuccess.Get().(*ExportProfilesPartialSuccess)\n}\n\nfunc DeleteExportProfilesPartialSuccess(orig *ExportProfilesPartialSuccess, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolExportProfilesPartialSuccess.Put(orig)\n\t}\n}\n\nfunc CopyExportProfilesPartialSuccess(dest, src *ExportProfilesPartialSuccess) *ExportProfilesPartialSuccess {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewExportProfilesPartialSuccess()\n\t}\n\tdest.RejectedProfiles = src.RejectedProfiles\n\tdest.ErrorMessage = src.ErrorMessage\n\n\treturn dest\n}\n\nfunc CopyExportProfilesPartialSuccessSlice(dest, src []ExportProfilesPartialSuccess) []ExportProfilesPartialSuccess {\n\tvar newDest []ExportProfilesPartialSuccess\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ExportProfilesPartialSuccess, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportProfilesPartialSuccess(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportProfilesPartialSuccess(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyExportProfilesPartialSuccessPtrSlice(dest, src []*ExportProfilesPartialSuccess) []*ExportProfilesPartialSuccess {\n\tvar newDest []*ExportProfilesPartialSuccess\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ExportProfilesPartialSuccess, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportProfilesPartialSuccess()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportProfilesPartialSuccess(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportProfilesPartialSuccess()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportProfilesPartialSuccess(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ExportProfilesPartialSuccess) Reset() {\n\t*orig = ExportProfilesPartialSuccess{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ExportProfilesPartialSuccess) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.RejectedProfiles != int64(0) {\n\t\tdest.WriteObjectField(\"rejectedProfiles\")\n\t\tdest.WriteInt64(orig.RejectedProfiles)\n\t}\n\tif orig.ErrorMessage != \"\" {\n\t\tdest.WriteObjectField(\"errorMessage\")\n\t\tdest.WriteString(orig.ErrorMessage)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ExportProfilesPartialSuccess) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"rejectedProfiles\", \"rejected_profiles\":\n\t\t\torig.RejectedProfiles = iter.ReadInt64()\n\t\tcase \"errorMessage\", \"error_message\":\n\t\t\torig.ErrorMessage = iter.ReadString()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ExportProfilesPartialSuccess) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.RejectedProfiles != int64(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.RejectedProfiles))\n\t}\n\n\tl = len(orig.ErrorMessage)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ExportProfilesPartialSuccess) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.RejectedProfiles != int64(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.RejectedProfiles))\n\t\tpos--\n\t\tbuf[pos] = 0x8\n\t}\n\tl = len(orig.ErrorMessage)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.ErrorMessage)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ExportProfilesPartialSuccess) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field RejectedProfiles\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.RejectedProfiles = int64(num)\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ErrorMessage\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.ErrorMessage = string(buf[startPos:pos])\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestExportProfilesPartialSuccess() *ExportProfilesPartialSuccess {\n\torig := NewExportProfilesPartialSuccess()\n\torig.RejectedProfiles = int64(13)\n\torig.ErrorMessage = \"test_errormessage\"\n\treturn orig\n}\n\nfunc GenTestExportProfilesPartialSuccessPtrSlice() []*ExportProfilesPartialSuccess {\n\torig := make([]*ExportProfilesPartialSuccess, 5)\n\torig[0] = NewExportProfilesPartialSuccess()\n\torig[1] = GenTestExportProfilesPartialSuccess()\n\torig[2] = NewExportProfilesPartialSuccess()\n\torig[3] = GenTestExportProfilesPartialSuccess()\n\torig[4] = NewExportProfilesPartialSuccess()\n\treturn orig\n}\n\nfunc GenTestExportProfilesPartialSuccessSlice() []ExportProfilesPartialSuccess {\n\torig := make([]ExportProfilesPartialSuccess, 5)\n\torig[1] = *GenTestExportProfilesPartialSuccess()\n\torig[3] = *GenTestExportProfilesPartialSuccess()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportprofilespartialsuccess_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcollectorprofiles \"go.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyExportProfilesPartialSuccess(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportProfilesPartialSuccess() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewExportProfilesPartialSuccess()\n\t\t\t\tCopyExportProfilesPartialSuccess(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyExportProfilesPartialSuccess(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyExportProfilesPartialSuccessSlice(t *testing.T) {\n\tsrc := []ExportProfilesPartialSuccess{}\n\tdest := []ExportProfilesPartialSuccess{}\n\t// Test CopyTo empty\n\tdest = CopyExportProfilesPartialSuccessSlice(dest, src)\n\tassert.Equal(t, []ExportProfilesPartialSuccess{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportProfilesPartialSuccessSlice()\n\tdest = CopyExportProfilesPartialSuccessSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesPartialSuccessSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportProfilesPartialSuccessSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesPartialSuccessSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportProfilesPartialSuccessSlice(dest, []ExportProfilesPartialSuccess{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportProfilesPartialSuccessSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesPartialSuccessSlice(), dest)\n}\n\nfunc TestCopyExportProfilesPartialSuccessPtrSlice(t *testing.T) {\n\tsrc := []*ExportProfilesPartialSuccess{}\n\tdest := []*ExportProfilesPartialSuccess{}\n\t// Test CopyTo empty\n\tdest = CopyExportProfilesPartialSuccessPtrSlice(dest, src)\n\tassert.Equal(t, []*ExportProfilesPartialSuccess{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportProfilesPartialSuccessPtrSlice()\n\tdest = CopyExportProfilesPartialSuccessPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesPartialSuccessPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportProfilesPartialSuccessPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesPartialSuccessPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportProfilesPartialSuccessPtrSlice(dest, []*ExportProfilesPartialSuccess{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportProfilesPartialSuccessPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesPartialSuccessPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportProfilesPartialSuccessUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewExportProfilesPartialSuccess()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewExportProfilesPartialSuccess(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportProfilesPartialSuccess(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportProfilesPartialSuccess() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewExportProfilesPartialSuccess()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportProfilesPartialSuccess(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportProfilesPartialSuccessFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesExportProfilesPartialSuccess() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewExportProfilesPartialSuccess()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportProfilesPartialSuccessUnknown(t *testing.T) {\n\tdest := NewExportProfilesPartialSuccess()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewExportProfilesPartialSuccess(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoExportProfilesPartialSuccess(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportProfilesPartialSuccess() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewExportProfilesPartialSuccess()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportProfilesPartialSuccess(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufExportProfilesPartialSuccess(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportProfilesPartialSuccess() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcollectorprofiles.ExportProfilesPartialSuccess{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewExportProfilesPartialSuccess()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesExportProfilesPartialSuccess() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                    {0x02},\n\t\t\"RejectedProfiles/wrong_wire_type\": {0xc},\n\t\t\"RejectedProfiles/missing_value\":   {0x8},\n\t\t\"ErrorMessage/wrong_wire_type\":     {0x14},\n\t\t\"ErrorMessage/missing_value\":       {0x12},\n\t}\n}\n\nfunc genTestEncodingValuesExportProfilesPartialSuccess() map[string]*ExportProfilesPartialSuccess {\n\treturn map[string]*ExportProfilesPartialSuccess{\n\t\t\"empty\":                 NewExportProfilesPartialSuccess(),\n\t\t\"RejectedProfiles/test\": {RejectedProfiles: int64(13)},\n\t\t\"ErrorMessage/test\":     {ErrorMessage: \"test_errormessage\"},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportprofilesservicerequest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Profiles is the top-level struct that is propagated through the profiles pipeline.\n// Use NewProfiles to create new instance, zero-initialized instance is not valid for use.\ntype ExportProfilesServiceRequest struct {\n\tResourceProfiles []*ResourceProfiles\n\tDictionary       ProfilesDictionary\n}\n\nvar (\n\tprotoPoolExportProfilesServiceRequest = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ExportProfilesServiceRequest{}\n\t\t},\n\t}\n)\n\nfunc NewExportProfilesServiceRequest() *ExportProfilesServiceRequest {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ExportProfilesServiceRequest{}\n\t}\n\treturn protoPoolExportProfilesServiceRequest.Get().(*ExportProfilesServiceRequest)\n}\n\nfunc DeleteExportProfilesServiceRequest(orig *ExportProfilesServiceRequest, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.ResourceProfiles {\n\t\tDeleteResourceProfiles(orig.ResourceProfiles[i], true)\n\t}\n\tDeleteProfilesDictionary(&orig.Dictionary, false)\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolExportProfilesServiceRequest.Put(orig)\n\t}\n}\n\nfunc CopyExportProfilesServiceRequest(dest, src *ExportProfilesServiceRequest) *ExportProfilesServiceRequest {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewExportProfilesServiceRequest()\n\t}\n\tdest.ResourceProfiles = CopyResourceProfilesPtrSlice(dest.ResourceProfiles, src.ResourceProfiles)\n\n\tCopyProfilesDictionary(&dest.Dictionary, &src.Dictionary)\n\n\treturn dest\n}\n\nfunc CopyExportProfilesServiceRequestSlice(dest, src []ExportProfilesServiceRequest) []ExportProfilesServiceRequest {\n\tvar newDest []ExportProfilesServiceRequest\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ExportProfilesServiceRequest, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportProfilesServiceRequest(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportProfilesServiceRequest(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyExportProfilesServiceRequestPtrSlice(dest, src []*ExportProfilesServiceRequest) []*ExportProfilesServiceRequest {\n\tvar newDest []*ExportProfilesServiceRequest\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ExportProfilesServiceRequest, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportProfilesServiceRequest()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportProfilesServiceRequest(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportProfilesServiceRequest()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportProfilesServiceRequest(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ExportProfilesServiceRequest) Reset() {\n\t*orig = ExportProfilesServiceRequest{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ExportProfilesServiceRequest) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.ResourceProfiles) > 0 {\n\t\tdest.WriteObjectField(\"resourceProfiles\")\n\t\tdest.WriteArrayStart()\n\t\torig.ResourceProfiles[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.ResourceProfiles); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.ResourceProfiles[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectField(\"dictionary\")\n\torig.Dictionary.MarshalJSON(dest)\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ExportProfilesServiceRequest) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"resourceProfiles\", \"resource_profiles\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.ResourceProfiles = append(orig.ResourceProfiles, NewResourceProfiles())\n\t\t\t\torig.ResourceProfiles[len(orig.ResourceProfiles)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"dictionary\":\n\n\t\t\torig.Dictionary.UnmarshalJSON(iter)\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ExportProfilesServiceRequest) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.ResourceProfiles {\n\t\tl = orig.ResourceProfiles[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tl = orig.Dictionary.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\treturn n\n}\n\nfunc (orig *ExportProfilesServiceRequest) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.ResourceProfiles) - 1; i >= 0; i-- {\n\t\tl = orig.ResourceProfiles[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\tl = orig.Dictionary.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x12\n\n\treturn len(buf) - pos\n}\n\nfunc (orig *ExportProfilesServiceRequest) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ResourceProfiles\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.ResourceProfiles = append(orig.ResourceProfiles, NewResourceProfiles())\n\t\t\terr = orig.ResourceProfiles[len(orig.ResourceProfiles)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Dictionary\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.Dictionary.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestExportProfilesServiceRequest() *ExportProfilesServiceRequest {\n\torig := NewExportProfilesServiceRequest()\n\torig.ResourceProfiles = []*ResourceProfiles{{}, GenTestResourceProfiles()}\n\torig.Dictionary = *GenTestProfilesDictionary()\n\treturn orig\n}\n\nfunc GenTestExportProfilesServiceRequestPtrSlice() []*ExportProfilesServiceRequest {\n\torig := make([]*ExportProfilesServiceRequest, 5)\n\torig[0] = NewExportProfilesServiceRequest()\n\torig[1] = GenTestExportProfilesServiceRequest()\n\torig[2] = NewExportProfilesServiceRequest()\n\torig[3] = GenTestExportProfilesServiceRequest()\n\torig[4] = NewExportProfilesServiceRequest()\n\treturn orig\n}\n\nfunc GenTestExportProfilesServiceRequestSlice() []ExportProfilesServiceRequest {\n\torig := make([]ExportProfilesServiceRequest, 5)\n\torig[1] = *GenTestExportProfilesServiceRequest()\n\torig[3] = *GenTestExportProfilesServiceRequest()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportprofilesservicerequest_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcollectorprofiles \"go.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyExportProfilesServiceRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportProfilesServiceRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewExportProfilesServiceRequest()\n\t\t\t\tCopyExportProfilesServiceRequest(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyExportProfilesServiceRequest(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyExportProfilesServiceRequestSlice(t *testing.T) {\n\tsrc := []ExportProfilesServiceRequest{}\n\tdest := []ExportProfilesServiceRequest{}\n\t// Test CopyTo empty\n\tdest = CopyExportProfilesServiceRequestSlice(dest, src)\n\tassert.Equal(t, []ExportProfilesServiceRequest{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportProfilesServiceRequestSlice()\n\tdest = CopyExportProfilesServiceRequestSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesServiceRequestSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportProfilesServiceRequestSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesServiceRequestSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportProfilesServiceRequestSlice(dest, []ExportProfilesServiceRequest{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportProfilesServiceRequestSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesServiceRequestSlice(), dest)\n}\n\nfunc TestCopyExportProfilesServiceRequestPtrSlice(t *testing.T) {\n\tsrc := []*ExportProfilesServiceRequest{}\n\tdest := []*ExportProfilesServiceRequest{}\n\t// Test CopyTo empty\n\tdest = CopyExportProfilesServiceRequestPtrSlice(dest, src)\n\tassert.Equal(t, []*ExportProfilesServiceRequest{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportProfilesServiceRequestPtrSlice()\n\tdest = CopyExportProfilesServiceRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesServiceRequestPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportProfilesServiceRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesServiceRequestPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportProfilesServiceRequestPtrSlice(dest, []*ExportProfilesServiceRequest{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportProfilesServiceRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesServiceRequestPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportProfilesServiceRequestUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewExportProfilesServiceRequest()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewExportProfilesServiceRequest(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportProfilesServiceRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportProfilesServiceRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewExportProfilesServiceRequest()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportProfilesServiceRequest(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportProfilesServiceRequestFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesExportProfilesServiceRequest() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewExportProfilesServiceRequest()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportProfilesServiceRequestUnknown(t *testing.T) {\n\tdest := NewExportProfilesServiceRequest()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewExportProfilesServiceRequest(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoExportProfilesServiceRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportProfilesServiceRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewExportProfilesServiceRequest()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportProfilesServiceRequest(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufExportProfilesServiceRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportProfilesServiceRequest() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcollectorprofiles.ExportProfilesServiceRequest{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewExportProfilesServiceRequest()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesExportProfilesServiceRequest() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                    {0x02},\n\t\t\"ResourceProfiles/wrong_wire_type\": {0xc},\n\t\t\"ResourceProfiles/missing_value\":   {0xa},\n\t\t\"Dictionary/wrong_wire_type\":       {0x14},\n\t\t\"Dictionary/missing_value\":         {0x12},\n\t}\n}\n\nfunc genTestEncodingValuesExportProfilesServiceRequest() map[string]*ExportProfilesServiceRequest {\n\treturn map[string]*ExportProfilesServiceRequest{\n\t\t\"empty\":                 NewExportProfilesServiceRequest(),\n\t\t\"ResourceProfiles/test\": {ResourceProfiles: []*ResourceProfiles{{}, GenTestResourceProfiles()}},\n\t\t\"Dictionary/test\":       {Dictionary: *GenTestProfilesDictionary()},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportprofilesserviceresponse.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ExportResponse represents the response for gRPC/HTTP client/server.\ntype ExportProfilesServiceResponse struct {\n\tPartialSuccess ExportProfilesPartialSuccess\n}\n\nvar (\n\tprotoPoolExportProfilesServiceResponse = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ExportProfilesServiceResponse{}\n\t\t},\n\t}\n)\n\nfunc NewExportProfilesServiceResponse() *ExportProfilesServiceResponse {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ExportProfilesServiceResponse{}\n\t}\n\treturn protoPoolExportProfilesServiceResponse.Get().(*ExportProfilesServiceResponse)\n}\n\nfunc DeleteExportProfilesServiceResponse(orig *ExportProfilesServiceResponse, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteExportProfilesPartialSuccess(&orig.PartialSuccess, false)\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolExportProfilesServiceResponse.Put(orig)\n\t}\n}\n\nfunc CopyExportProfilesServiceResponse(dest, src *ExportProfilesServiceResponse) *ExportProfilesServiceResponse {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewExportProfilesServiceResponse()\n\t}\n\tCopyExportProfilesPartialSuccess(&dest.PartialSuccess, &src.PartialSuccess)\n\n\treturn dest\n}\n\nfunc CopyExportProfilesServiceResponseSlice(dest, src []ExportProfilesServiceResponse) []ExportProfilesServiceResponse {\n\tvar newDest []ExportProfilesServiceResponse\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ExportProfilesServiceResponse, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportProfilesServiceResponse(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportProfilesServiceResponse(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyExportProfilesServiceResponsePtrSlice(dest, src []*ExportProfilesServiceResponse) []*ExportProfilesServiceResponse {\n\tvar newDest []*ExportProfilesServiceResponse\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ExportProfilesServiceResponse, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportProfilesServiceResponse()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportProfilesServiceResponse(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportProfilesServiceResponse()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportProfilesServiceResponse(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ExportProfilesServiceResponse) Reset() {\n\t*orig = ExportProfilesServiceResponse{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ExportProfilesServiceResponse) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tdest.WriteObjectField(\"partialSuccess\")\n\torig.PartialSuccess.MarshalJSON(dest)\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ExportProfilesServiceResponse) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"partialSuccess\", \"partial_success\":\n\n\t\t\torig.PartialSuccess.UnmarshalJSON(iter)\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ExportProfilesServiceResponse) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tl = orig.PartialSuccess.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\treturn n\n}\n\nfunc (orig *ExportProfilesServiceResponse) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = orig.PartialSuccess.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0xa\n\n\treturn len(buf) - pos\n}\n\nfunc (orig *ExportProfilesServiceResponse) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field PartialSuccess\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.PartialSuccess.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestExportProfilesServiceResponse() *ExportProfilesServiceResponse {\n\torig := NewExportProfilesServiceResponse()\n\torig.PartialSuccess = *GenTestExportProfilesPartialSuccess()\n\treturn orig\n}\n\nfunc GenTestExportProfilesServiceResponsePtrSlice() []*ExportProfilesServiceResponse {\n\torig := make([]*ExportProfilesServiceResponse, 5)\n\torig[0] = NewExportProfilesServiceResponse()\n\torig[1] = GenTestExportProfilesServiceResponse()\n\torig[2] = NewExportProfilesServiceResponse()\n\torig[3] = GenTestExportProfilesServiceResponse()\n\torig[4] = NewExportProfilesServiceResponse()\n\treturn orig\n}\n\nfunc GenTestExportProfilesServiceResponseSlice() []ExportProfilesServiceResponse {\n\torig := make([]ExportProfilesServiceResponse, 5)\n\torig[1] = *GenTestExportProfilesServiceResponse()\n\torig[3] = *GenTestExportProfilesServiceResponse()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exportprofilesserviceresponse_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcollectorprofiles \"go.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyExportProfilesServiceResponse(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportProfilesServiceResponse() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewExportProfilesServiceResponse()\n\t\t\t\tCopyExportProfilesServiceResponse(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyExportProfilesServiceResponse(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyExportProfilesServiceResponseSlice(t *testing.T) {\n\tsrc := []ExportProfilesServiceResponse{}\n\tdest := []ExportProfilesServiceResponse{}\n\t// Test CopyTo empty\n\tdest = CopyExportProfilesServiceResponseSlice(dest, src)\n\tassert.Equal(t, []ExportProfilesServiceResponse{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportProfilesServiceResponseSlice()\n\tdest = CopyExportProfilesServiceResponseSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesServiceResponseSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportProfilesServiceResponseSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesServiceResponseSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportProfilesServiceResponseSlice(dest, []ExportProfilesServiceResponse{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportProfilesServiceResponseSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesServiceResponseSlice(), dest)\n}\n\nfunc TestCopyExportProfilesServiceResponsePtrSlice(t *testing.T) {\n\tsrc := []*ExportProfilesServiceResponse{}\n\tdest := []*ExportProfilesServiceResponse{}\n\t// Test CopyTo empty\n\tdest = CopyExportProfilesServiceResponsePtrSlice(dest, src)\n\tassert.Equal(t, []*ExportProfilesServiceResponse{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportProfilesServiceResponsePtrSlice()\n\tdest = CopyExportProfilesServiceResponsePtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesServiceResponsePtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportProfilesServiceResponsePtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesServiceResponsePtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportProfilesServiceResponsePtrSlice(dest, []*ExportProfilesServiceResponse{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportProfilesServiceResponsePtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportProfilesServiceResponsePtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportProfilesServiceResponseUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewExportProfilesServiceResponse()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewExportProfilesServiceResponse(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportProfilesServiceResponse(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportProfilesServiceResponse() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewExportProfilesServiceResponse()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportProfilesServiceResponse(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportProfilesServiceResponseFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesExportProfilesServiceResponse() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewExportProfilesServiceResponse()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportProfilesServiceResponseUnknown(t *testing.T) {\n\tdest := NewExportProfilesServiceResponse()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewExportProfilesServiceResponse(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoExportProfilesServiceResponse(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportProfilesServiceResponse() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewExportProfilesServiceResponse()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportProfilesServiceResponse(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufExportProfilesServiceResponse(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportProfilesServiceResponse() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcollectorprofiles.ExportProfilesServiceResponse{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewExportProfilesServiceResponse()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesExportProfilesServiceResponse() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                  {0x02},\n\t\t\"PartialSuccess/wrong_wire_type\": {0xc},\n\t\t\"PartialSuccess/missing_value\":   {0xa},\n\t}\n}\n\nfunc genTestEncodingValuesExportProfilesServiceResponse() map[string]*ExportProfilesServiceResponse {\n\treturn map[string]*ExportProfilesServiceResponse{\n\t\t\"empty\":               NewExportProfilesServiceResponse(),\n\t\t\"PartialSuccess/test\": {PartialSuccess: *GenTestExportProfilesPartialSuccess()},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exporttracepartialsuccess.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ExportPartialSuccess represents the details of a partially successful export request.\ntype ExportTracePartialSuccess struct {\n\tErrorMessage  string\n\tRejectedSpans int64\n}\n\nvar (\n\tprotoPoolExportTracePartialSuccess = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ExportTracePartialSuccess{}\n\t\t},\n\t}\n)\n\nfunc NewExportTracePartialSuccess() *ExportTracePartialSuccess {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ExportTracePartialSuccess{}\n\t}\n\treturn protoPoolExportTracePartialSuccess.Get().(*ExportTracePartialSuccess)\n}\n\nfunc DeleteExportTracePartialSuccess(orig *ExportTracePartialSuccess, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolExportTracePartialSuccess.Put(orig)\n\t}\n}\n\nfunc CopyExportTracePartialSuccess(dest, src *ExportTracePartialSuccess) *ExportTracePartialSuccess {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewExportTracePartialSuccess()\n\t}\n\tdest.RejectedSpans = src.RejectedSpans\n\tdest.ErrorMessage = src.ErrorMessage\n\n\treturn dest\n}\n\nfunc CopyExportTracePartialSuccessSlice(dest, src []ExportTracePartialSuccess) []ExportTracePartialSuccess {\n\tvar newDest []ExportTracePartialSuccess\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ExportTracePartialSuccess, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportTracePartialSuccess(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportTracePartialSuccess(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyExportTracePartialSuccessPtrSlice(dest, src []*ExportTracePartialSuccess) []*ExportTracePartialSuccess {\n\tvar newDest []*ExportTracePartialSuccess\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ExportTracePartialSuccess, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportTracePartialSuccess()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportTracePartialSuccess(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportTracePartialSuccess()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportTracePartialSuccess(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ExportTracePartialSuccess) Reset() {\n\t*orig = ExportTracePartialSuccess{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ExportTracePartialSuccess) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.RejectedSpans != int64(0) {\n\t\tdest.WriteObjectField(\"rejectedSpans\")\n\t\tdest.WriteInt64(orig.RejectedSpans)\n\t}\n\tif orig.ErrorMessage != \"\" {\n\t\tdest.WriteObjectField(\"errorMessage\")\n\t\tdest.WriteString(orig.ErrorMessage)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ExportTracePartialSuccess) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"rejectedSpans\", \"rejected_spans\":\n\t\t\torig.RejectedSpans = iter.ReadInt64()\n\t\tcase \"errorMessage\", \"error_message\":\n\t\t\torig.ErrorMessage = iter.ReadString()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ExportTracePartialSuccess) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.RejectedSpans != int64(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.RejectedSpans))\n\t}\n\n\tl = len(orig.ErrorMessage)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ExportTracePartialSuccess) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.RejectedSpans != int64(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.RejectedSpans))\n\t\tpos--\n\t\tbuf[pos] = 0x8\n\t}\n\tl = len(orig.ErrorMessage)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.ErrorMessage)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ExportTracePartialSuccess) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field RejectedSpans\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.RejectedSpans = int64(num)\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ErrorMessage\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.ErrorMessage = string(buf[startPos:pos])\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestExportTracePartialSuccess() *ExportTracePartialSuccess {\n\torig := NewExportTracePartialSuccess()\n\torig.RejectedSpans = int64(13)\n\torig.ErrorMessage = \"test_errormessage\"\n\treturn orig\n}\n\nfunc GenTestExportTracePartialSuccessPtrSlice() []*ExportTracePartialSuccess {\n\torig := make([]*ExportTracePartialSuccess, 5)\n\torig[0] = NewExportTracePartialSuccess()\n\torig[1] = GenTestExportTracePartialSuccess()\n\torig[2] = NewExportTracePartialSuccess()\n\torig[3] = GenTestExportTracePartialSuccess()\n\torig[4] = NewExportTracePartialSuccess()\n\treturn orig\n}\n\nfunc GenTestExportTracePartialSuccessSlice() []ExportTracePartialSuccess {\n\torig := make([]ExportTracePartialSuccess, 5)\n\torig[1] = *GenTestExportTracePartialSuccess()\n\torig[3] = *GenTestExportTracePartialSuccess()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exporttracepartialsuccess_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcollectortrace \"go.opentelemetry.io/proto/slim/otlp/collector/trace/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyExportTracePartialSuccess(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportTracePartialSuccess() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewExportTracePartialSuccess()\n\t\t\t\tCopyExportTracePartialSuccess(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyExportTracePartialSuccess(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyExportTracePartialSuccessSlice(t *testing.T) {\n\tsrc := []ExportTracePartialSuccess{}\n\tdest := []ExportTracePartialSuccess{}\n\t// Test CopyTo empty\n\tdest = CopyExportTracePartialSuccessSlice(dest, src)\n\tassert.Equal(t, []ExportTracePartialSuccess{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportTracePartialSuccessSlice()\n\tdest = CopyExportTracePartialSuccessSlice(dest, src)\n\tassert.Equal(t, GenTestExportTracePartialSuccessSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportTracePartialSuccessSlice(dest, src)\n\tassert.Equal(t, GenTestExportTracePartialSuccessSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportTracePartialSuccessSlice(dest, []ExportTracePartialSuccess{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportTracePartialSuccessSlice(dest, src)\n\tassert.Equal(t, GenTestExportTracePartialSuccessSlice(), dest)\n}\n\nfunc TestCopyExportTracePartialSuccessPtrSlice(t *testing.T) {\n\tsrc := []*ExportTracePartialSuccess{}\n\tdest := []*ExportTracePartialSuccess{}\n\t// Test CopyTo empty\n\tdest = CopyExportTracePartialSuccessPtrSlice(dest, src)\n\tassert.Equal(t, []*ExportTracePartialSuccess{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportTracePartialSuccessPtrSlice()\n\tdest = CopyExportTracePartialSuccessPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportTracePartialSuccessPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportTracePartialSuccessPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportTracePartialSuccessPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportTracePartialSuccessPtrSlice(dest, []*ExportTracePartialSuccess{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportTracePartialSuccessPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportTracePartialSuccessPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportTracePartialSuccessUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewExportTracePartialSuccess()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewExportTracePartialSuccess(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportTracePartialSuccess(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportTracePartialSuccess() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewExportTracePartialSuccess()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportTracePartialSuccess(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportTracePartialSuccessFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesExportTracePartialSuccess() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewExportTracePartialSuccess()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportTracePartialSuccessUnknown(t *testing.T) {\n\tdest := NewExportTracePartialSuccess()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewExportTracePartialSuccess(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoExportTracePartialSuccess(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportTracePartialSuccess() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewExportTracePartialSuccess()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportTracePartialSuccess(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufExportTracePartialSuccess(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportTracePartialSuccess() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcollectortrace.ExportTracePartialSuccess{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewExportTracePartialSuccess()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesExportTracePartialSuccess() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                 {0x02},\n\t\t\"RejectedSpans/wrong_wire_type\": {0xc},\n\t\t\"RejectedSpans/missing_value\":   {0x8},\n\t\t\"ErrorMessage/wrong_wire_type\":  {0x14},\n\t\t\"ErrorMessage/missing_value\":    {0x12},\n\t}\n}\n\nfunc genTestEncodingValuesExportTracePartialSuccess() map[string]*ExportTracePartialSuccess {\n\treturn map[string]*ExportTracePartialSuccess{\n\t\t\"empty\":              NewExportTracePartialSuccess(),\n\t\t\"RejectedSpans/test\": {RejectedSpans: int64(13)},\n\t\t\"ErrorMessage/test\":  {ErrorMessage: \"test_errormessage\"},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exporttraceservicerequest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Traces is the top-level struct that is propagated through the traces pipeline.\n// Use NewTraces to create new instance, zero-initialized instance is not valid for use.\ntype ExportTraceServiceRequest struct {\n\tResourceSpans []*ResourceSpans\n}\n\nvar (\n\tprotoPoolExportTraceServiceRequest = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ExportTraceServiceRequest{}\n\t\t},\n\t}\n)\n\nfunc NewExportTraceServiceRequest() *ExportTraceServiceRequest {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ExportTraceServiceRequest{}\n\t}\n\treturn protoPoolExportTraceServiceRequest.Get().(*ExportTraceServiceRequest)\n}\n\nfunc DeleteExportTraceServiceRequest(orig *ExportTraceServiceRequest, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.ResourceSpans {\n\t\tDeleteResourceSpans(orig.ResourceSpans[i], true)\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolExportTraceServiceRequest.Put(orig)\n\t}\n}\n\nfunc CopyExportTraceServiceRequest(dest, src *ExportTraceServiceRequest) *ExportTraceServiceRequest {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewExportTraceServiceRequest()\n\t}\n\tdest.ResourceSpans = CopyResourceSpansPtrSlice(dest.ResourceSpans, src.ResourceSpans)\n\n\treturn dest\n}\n\nfunc CopyExportTraceServiceRequestSlice(dest, src []ExportTraceServiceRequest) []ExportTraceServiceRequest {\n\tvar newDest []ExportTraceServiceRequest\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ExportTraceServiceRequest, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportTraceServiceRequest(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportTraceServiceRequest(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyExportTraceServiceRequestPtrSlice(dest, src []*ExportTraceServiceRequest) []*ExportTraceServiceRequest {\n\tvar newDest []*ExportTraceServiceRequest\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ExportTraceServiceRequest, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportTraceServiceRequest()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportTraceServiceRequest(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportTraceServiceRequest()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportTraceServiceRequest(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ExportTraceServiceRequest) Reset() {\n\t*orig = ExportTraceServiceRequest{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ExportTraceServiceRequest) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.ResourceSpans) > 0 {\n\t\tdest.WriteObjectField(\"resourceSpans\")\n\t\tdest.WriteArrayStart()\n\t\torig.ResourceSpans[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.ResourceSpans); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.ResourceSpans[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ExportTraceServiceRequest) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"resourceSpans\", \"resource_spans\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.ResourceSpans = append(orig.ResourceSpans, NewResourceSpans())\n\t\t\t\torig.ResourceSpans[len(orig.ResourceSpans)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ExportTraceServiceRequest) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.ResourceSpans {\n\t\tl = orig.ResourceSpans[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ExportTraceServiceRequest) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.ResourceSpans) - 1; i >= 0; i-- {\n\t\tl = orig.ResourceSpans[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ExportTraceServiceRequest) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ResourceSpans\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.ResourceSpans = append(orig.ResourceSpans, NewResourceSpans())\n\t\t\terr = orig.ResourceSpans[len(orig.ResourceSpans)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestExportTraceServiceRequest() *ExportTraceServiceRequest {\n\torig := NewExportTraceServiceRequest()\n\torig.ResourceSpans = []*ResourceSpans{{}, GenTestResourceSpans()}\n\treturn orig\n}\n\nfunc GenTestExportTraceServiceRequestPtrSlice() []*ExportTraceServiceRequest {\n\torig := make([]*ExportTraceServiceRequest, 5)\n\torig[0] = NewExportTraceServiceRequest()\n\torig[1] = GenTestExportTraceServiceRequest()\n\torig[2] = NewExportTraceServiceRequest()\n\torig[3] = GenTestExportTraceServiceRequest()\n\torig[4] = NewExportTraceServiceRequest()\n\treturn orig\n}\n\nfunc GenTestExportTraceServiceRequestSlice() []ExportTraceServiceRequest {\n\torig := make([]ExportTraceServiceRequest, 5)\n\torig[1] = *GenTestExportTraceServiceRequest()\n\torig[3] = *GenTestExportTraceServiceRequest()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exporttraceservicerequest_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcollectortrace \"go.opentelemetry.io/proto/slim/otlp/collector/trace/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyExportTraceServiceRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportTraceServiceRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewExportTraceServiceRequest()\n\t\t\t\tCopyExportTraceServiceRequest(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyExportTraceServiceRequest(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyExportTraceServiceRequestSlice(t *testing.T) {\n\tsrc := []ExportTraceServiceRequest{}\n\tdest := []ExportTraceServiceRequest{}\n\t// Test CopyTo empty\n\tdest = CopyExportTraceServiceRequestSlice(dest, src)\n\tassert.Equal(t, []ExportTraceServiceRequest{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportTraceServiceRequestSlice()\n\tdest = CopyExportTraceServiceRequestSlice(dest, src)\n\tassert.Equal(t, GenTestExportTraceServiceRequestSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportTraceServiceRequestSlice(dest, src)\n\tassert.Equal(t, GenTestExportTraceServiceRequestSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportTraceServiceRequestSlice(dest, []ExportTraceServiceRequest{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportTraceServiceRequestSlice(dest, src)\n\tassert.Equal(t, GenTestExportTraceServiceRequestSlice(), dest)\n}\n\nfunc TestCopyExportTraceServiceRequestPtrSlice(t *testing.T) {\n\tsrc := []*ExportTraceServiceRequest{}\n\tdest := []*ExportTraceServiceRequest{}\n\t// Test CopyTo empty\n\tdest = CopyExportTraceServiceRequestPtrSlice(dest, src)\n\tassert.Equal(t, []*ExportTraceServiceRequest{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportTraceServiceRequestPtrSlice()\n\tdest = CopyExportTraceServiceRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportTraceServiceRequestPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportTraceServiceRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportTraceServiceRequestPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportTraceServiceRequestPtrSlice(dest, []*ExportTraceServiceRequest{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportTraceServiceRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportTraceServiceRequestPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportTraceServiceRequestUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewExportTraceServiceRequest()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewExportTraceServiceRequest(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportTraceServiceRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportTraceServiceRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewExportTraceServiceRequest()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportTraceServiceRequest(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportTraceServiceRequestFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesExportTraceServiceRequest() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewExportTraceServiceRequest()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportTraceServiceRequestUnknown(t *testing.T) {\n\tdest := NewExportTraceServiceRequest()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewExportTraceServiceRequest(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoExportTraceServiceRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportTraceServiceRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewExportTraceServiceRequest()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportTraceServiceRequest(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufExportTraceServiceRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportTraceServiceRequest() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcollectortrace.ExportTraceServiceRequest{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewExportTraceServiceRequest()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesExportTraceServiceRequest() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                 {0x02},\n\t\t\"ResourceSpans/wrong_wire_type\": {0xc},\n\t\t\"ResourceSpans/missing_value\":   {0xa},\n\t}\n}\n\nfunc genTestEncodingValuesExportTraceServiceRequest() map[string]*ExportTraceServiceRequest {\n\treturn map[string]*ExportTraceServiceRequest{\n\t\t\"empty\":              NewExportTraceServiceRequest(),\n\t\t\"ResourceSpans/test\": {ResourceSpans: []*ResourceSpans{{}, GenTestResourceSpans()}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exporttraceserviceresponse.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ExportResponse represents the response for gRPC/HTTP client/server.\ntype ExportTraceServiceResponse struct {\n\tPartialSuccess ExportTracePartialSuccess\n}\n\nvar (\n\tprotoPoolExportTraceServiceResponse = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ExportTraceServiceResponse{}\n\t\t},\n\t}\n)\n\nfunc NewExportTraceServiceResponse() *ExportTraceServiceResponse {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ExportTraceServiceResponse{}\n\t}\n\treturn protoPoolExportTraceServiceResponse.Get().(*ExportTraceServiceResponse)\n}\n\nfunc DeleteExportTraceServiceResponse(orig *ExportTraceServiceResponse, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteExportTracePartialSuccess(&orig.PartialSuccess, false)\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolExportTraceServiceResponse.Put(orig)\n\t}\n}\n\nfunc CopyExportTraceServiceResponse(dest, src *ExportTraceServiceResponse) *ExportTraceServiceResponse {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewExportTraceServiceResponse()\n\t}\n\tCopyExportTracePartialSuccess(&dest.PartialSuccess, &src.PartialSuccess)\n\n\treturn dest\n}\n\nfunc CopyExportTraceServiceResponseSlice(dest, src []ExportTraceServiceResponse) []ExportTraceServiceResponse {\n\tvar newDest []ExportTraceServiceResponse\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ExportTraceServiceResponse, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportTraceServiceResponse(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportTraceServiceResponse(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyExportTraceServiceResponsePtrSlice(dest, src []*ExportTraceServiceResponse) []*ExportTraceServiceResponse {\n\tvar newDest []*ExportTraceServiceResponse\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ExportTraceServiceResponse, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportTraceServiceResponse()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteExportTraceServiceResponse(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewExportTraceServiceResponse()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyExportTraceServiceResponse(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ExportTraceServiceResponse) Reset() {\n\t*orig = ExportTraceServiceResponse{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ExportTraceServiceResponse) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tdest.WriteObjectField(\"partialSuccess\")\n\torig.PartialSuccess.MarshalJSON(dest)\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ExportTraceServiceResponse) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"partialSuccess\", \"partial_success\":\n\n\t\t\torig.PartialSuccess.UnmarshalJSON(iter)\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ExportTraceServiceResponse) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tl = orig.PartialSuccess.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\treturn n\n}\n\nfunc (orig *ExportTraceServiceResponse) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = orig.PartialSuccess.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0xa\n\n\treturn len(buf) - pos\n}\n\nfunc (orig *ExportTraceServiceResponse) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field PartialSuccess\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.PartialSuccess.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestExportTraceServiceResponse() *ExportTraceServiceResponse {\n\torig := NewExportTraceServiceResponse()\n\torig.PartialSuccess = *GenTestExportTracePartialSuccess()\n\treturn orig\n}\n\nfunc GenTestExportTraceServiceResponsePtrSlice() []*ExportTraceServiceResponse {\n\torig := make([]*ExportTraceServiceResponse, 5)\n\torig[0] = NewExportTraceServiceResponse()\n\torig[1] = GenTestExportTraceServiceResponse()\n\torig[2] = NewExportTraceServiceResponse()\n\torig[3] = GenTestExportTraceServiceResponse()\n\torig[4] = NewExportTraceServiceResponse()\n\treturn orig\n}\n\nfunc GenTestExportTraceServiceResponseSlice() []ExportTraceServiceResponse {\n\torig := make([]ExportTraceServiceResponse, 5)\n\torig[1] = *GenTestExportTraceServiceResponse()\n\torig[3] = *GenTestExportTraceServiceResponse()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_exporttraceserviceresponse_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcollectortrace \"go.opentelemetry.io/proto/slim/otlp/collector/trace/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyExportTraceServiceResponse(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportTraceServiceResponse() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewExportTraceServiceResponse()\n\t\t\t\tCopyExportTraceServiceResponse(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyExportTraceServiceResponse(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyExportTraceServiceResponseSlice(t *testing.T) {\n\tsrc := []ExportTraceServiceResponse{}\n\tdest := []ExportTraceServiceResponse{}\n\t// Test CopyTo empty\n\tdest = CopyExportTraceServiceResponseSlice(dest, src)\n\tassert.Equal(t, []ExportTraceServiceResponse{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportTraceServiceResponseSlice()\n\tdest = CopyExportTraceServiceResponseSlice(dest, src)\n\tassert.Equal(t, GenTestExportTraceServiceResponseSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportTraceServiceResponseSlice(dest, src)\n\tassert.Equal(t, GenTestExportTraceServiceResponseSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportTraceServiceResponseSlice(dest, []ExportTraceServiceResponse{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportTraceServiceResponseSlice(dest, src)\n\tassert.Equal(t, GenTestExportTraceServiceResponseSlice(), dest)\n}\n\nfunc TestCopyExportTraceServiceResponsePtrSlice(t *testing.T) {\n\tsrc := []*ExportTraceServiceResponse{}\n\tdest := []*ExportTraceServiceResponse{}\n\t// Test CopyTo empty\n\tdest = CopyExportTraceServiceResponsePtrSlice(dest, src)\n\tassert.Equal(t, []*ExportTraceServiceResponse{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestExportTraceServiceResponsePtrSlice()\n\tdest = CopyExportTraceServiceResponsePtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportTraceServiceResponsePtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyExportTraceServiceResponsePtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportTraceServiceResponsePtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyExportTraceServiceResponsePtrSlice(dest, []*ExportTraceServiceResponse{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyExportTraceServiceResponsePtrSlice(dest, src)\n\tassert.Equal(t, GenTestExportTraceServiceResponsePtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportTraceServiceResponseUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewExportTraceServiceResponse()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewExportTraceServiceResponse(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONExportTraceServiceResponse(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportTraceServiceResponse() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewExportTraceServiceResponse()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportTraceServiceResponse(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportTraceServiceResponseFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesExportTraceServiceResponse() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewExportTraceServiceResponse()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoExportTraceServiceResponseUnknown(t *testing.T) {\n\tdest := NewExportTraceServiceResponse()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewExportTraceServiceResponse(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoExportTraceServiceResponse(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportTraceServiceResponse() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewExportTraceServiceResponse()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteExportTraceServiceResponse(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufExportTraceServiceResponse(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesExportTraceServiceResponse() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcollectortrace.ExportTraceServiceResponse{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewExportTraceServiceResponse()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesExportTraceServiceResponse() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                  {0x02},\n\t\t\"PartialSuccess/wrong_wire_type\": {0xc},\n\t\t\"PartialSuccess/missing_value\":   {0xa},\n\t}\n}\n\nfunc genTestEncodingValuesExportTraceServiceResponse() map[string]*ExportTraceServiceResponse {\n\treturn map[string]*ExportTraceServiceResponse{\n\t\t\"empty\":               NewExportTraceServiceResponse(),\n\t\t\"PartialSuccess/test\": {PartialSuccess: *GenTestExportTracePartialSuccess()},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_function.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Function describes a function, including its human-readable name, system name, source file, and starting line number in the source.\ntype Function struct {\n\tNameStrindex       int32\n\tSystemNameStrindex int32\n\tFilenameStrindex   int32\n\tStartLine          int64\n}\n\nvar (\n\tprotoPoolFunction = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Function{}\n\t\t},\n\t}\n)\n\nfunc NewFunction() *Function {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &Function{}\n\t}\n\treturn protoPoolFunction.Get().(*Function)\n}\n\nfunc DeleteFunction(orig *Function, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolFunction.Put(orig)\n\t}\n}\n\nfunc CopyFunction(dest, src *Function) *Function {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewFunction()\n\t}\n\tdest.NameStrindex = src.NameStrindex\n\tdest.SystemNameStrindex = src.SystemNameStrindex\n\tdest.FilenameStrindex = src.FilenameStrindex\n\tdest.StartLine = src.StartLine\n\n\treturn dest\n}\n\nfunc CopyFunctionSlice(dest, src []Function) []Function {\n\tvar newDest []Function\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]Function, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteFunction(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyFunction(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyFunctionPtrSlice(dest, src []*Function) []*Function {\n\tvar newDest []*Function\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*Function, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewFunction()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteFunction(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewFunction()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyFunction(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *Function) Reset() {\n\t*orig = Function{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *Function) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.NameStrindex != int32(0) {\n\t\tdest.WriteObjectField(\"nameStrindex\")\n\t\tdest.WriteInt32(orig.NameStrindex)\n\t}\n\tif orig.SystemNameStrindex != int32(0) {\n\t\tdest.WriteObjectField(\"systemNameStrindex\")\n\t\tdest.WriteInt32(orig.SystemNameStrindex)\n\t}\n\tif orig.FilenameStrindex != int32(0) {\n\t\tdest.WriteObjectField(\"filenameStrindex\")\n\t\tdest.WriteInt32(orig.FilenameStrindex)\n\t}\n\tif orig.StartLine != int64(0) {\n\t\tdest.WriteObjectField(\"startLine\")\n\t\tdest.WriteInt64(orig.StartLine)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *Function) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"nameStrindex\", \"name_strindex\":\n\t\t\torig.NameStrindex = iter.ReadInt32()\n\t\tcase \"systemNameStrindex\", \"system_name_strindex\":\n\t\t\torig.SystemNameStrindex = iter.ReadInt32()\n\t\tcase \"filenameStrindex\", \"filename_strindex\":\n\t\t\torig.FilenameStrindex = iter.ReadInt32()\n\t\tcase \"startLine\", \"start_line\":\n\t\t\torig.StartLine = iter.ReadInt64()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *Function) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.NameStrindex != int32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.NameStrindex))\n\t}\n\tif orig.SystemNameStrindex != int32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.SystemNameStrindex))\n\t}\n\tif orig.FilenameStrindex != int32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.FilenameStrindex))\n\t}\n\tif orig.StartLine != int64(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.StartLine))\n\t}\n\treturn n\n}\n\nfunc (orig *Function) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.NameStrindex != int32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.NameStrindex))\n\t\tpos--\n\t\tbuf[pos] = 0x8\n\t}\n\tif orig.SystemNameStrindex != int32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.SystemNameStrindex))\n\t\tpos--\n\t\tbuf[pos] = 0x10\n\t}\n\tif orig.FilenameStrindex != int32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.FilenameStrindex))\n\t\tpos--\n\t\tbuf[pos] = 0x18\n\t}\n\tif orig.StartLine != int64(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.StartLine))\n\t\tpos--\n\t\tbuf[pos] = 0x20\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *Function) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field NameStrindex\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.NameStrindex = int32(num)\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SystemNameStrindex\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.SystemNameStrindex = int32(num)\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field FilenameStrindex\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.FilenameStrindex = int32(num)\n\n\t\tcase 4:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field StartLine\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.StartLine = int64(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestFunction() *Function {\n\torig := NewFunction()\n\torig.NameStrindex = int32(13)\n\torig.SystemNameStrindex = int32(13)\n\torig.FilenameStrindex = int32(13)\n\torig.StartLine = int64(13)\n\treturn orig\n}\n\nfunc GenTestFunctionPtrSlice() []*Function {\n\torig := make([]*Function, 5)\n\torig[0] = NewFunction()\n\torig[1] = GenTestFunction()\n\torig[2] = NewFunction()\n\torig[3] = GenTestFunction()\n\torig[4] = NewFunction()\n\treturn orig\n}\n\nfunc GenTestFunctionSlice() []Function {\n\torig := make([]Function, 5)\n\torig[1] = *GenTestFunction()\n\torig[3] = *GenTestFunction()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_function_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpprofiles \"go.opentelemetry.io/proto/slim/otlp/profiles/v1development\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyFunction(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesFunction() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewFunction()\n\t\t\t\tCopyFunction(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyFunction(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyFunctionSlice(t *testing.T) {\n\tsrc := []Function{}\n\tdest := []Function{}\n\t// Test CopyTo empty\n\tdest = CopyFunctionSlice(dest, src)\n\tassert.Equal(t, []Function{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestFunctionSlice()\n\tdest = CopyFunctionSlice(dest, src)\n\tassert.Equal(t, GenTestFunctionSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyFunctionSlice(dest, src)\n\tassert.Equal(t, GenTestFunctionSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyFunctionSlice(dest, []Function{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyFunctionSlice(dest, src)\n\tassert.Equal(t, GenTestFunctionSlice(), dest)\n}\n\nfunc TestCopyFunctionPtrSlice(t *testing.T) {\n\tsrc := []*Function{}\n\tdest := []*Function{}\n\t// Test CopyTo empty\n\tdest = CopyFunctionPtrSlice(dest, src)\n\tassert.Equal(t, []*Function{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestFunctionPtrSlice()\n\tdest = CopyFunctionPtrSlice(dest, src)\n\tassert.Equal(t, GenTestFunctionPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyFunctionPtrSlice(dest, src)\n\tassert.Equal(t, GenTestFunctionPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyFunctionPtrSlice(dest, []*Function{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyFunctionPtrSlice(dest, src)\n\tassert.Equal(t, GenTestFunctionPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONFunctionUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewFunction()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewFunction(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONFunction(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesFunction() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewFunction()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteFunction(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoFunctionFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesFunction() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewFunction()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoFunctionUnknown(t *testing.T) {\n\tdest := NewFunction()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewFunction(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoFunction(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesFunction() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewFunction()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteFunction(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufFunction(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesFunction() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpprofiles.Function{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewFunction()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesFunction() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                      {0x02},\n\t\t\"NameStrindex/wrong_wire_type\":       {0xc},\n\t\t\"NameStrindex/missing_value\":         {0x8},\n\t\t\"SystemNameStrindex/wrong_wire_type\": {0x14},\n\t\t\"SystemNameStrindex/missing_value\":   {0x10},\n\t\t\"FilenameStrindex/wrong_wire_type\":   {0x1c},\n\t\t\"FilenameStrindex/missing_value\":     {0x18},\n\t\t\"StartLine/wrong_wire_type\":          {0x24},\n\t\t\"StartLine/missing_value\":            {0x20},\n\t}\n}\n\nfunc genTestEncodingValuesFunction() map[string]*Function {\n\treturn map[string]*Function{\n\t\t\"empty\":                   NewFunction(),\n\t\t\"NameStrindex/test\":       {NameStrindex: int32(13)},\n\t\t\"SystemNameStrindex/test\": {SystemNameStrindex: int32(13)},\n\t\t\"FilenameStrindex/test\":   {FilenameStrindex: int32(13)},\n\t\t\"StartLine/test\":          {StartLine: int64(13)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_gauge.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Gauge represents the type of a numeric metric that always exports the \"current value\" for every data point.\ntype Gauge struct {\n\tDataPoints []*NumberDataPoint\n}\n\nvar (\n\tprotoPoolGauge = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Gauge{}\n\t\t},\n\t}\n)\n\nfunc NewGauge() *Gauge {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &Gauge{}\n\t}\n\treturn protoPoolGauge.Get().(*Gauge)\n}\n\nfunc DeleteGauge(orig *Gauge, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.DataPoints {\n\t\tDeleteNumberDataPoint(orig.DataPoints[i], true)\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolGauge.Put(orig)\n\t}\n}\n\nfunc CopyGauge(dest, src *Gauge) *Gauge {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewGauge()\n\t}\n\tdest.DataPoints = CopyNumberDataPointPtrSlice(dest.DataPoints, src.DataPoints)\n\n\treturn dest\n}\n\nfunc CopyGaugeSlice(dest, src []Gauge) []Gauge {\n\tvar newDest []Gauge\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]Gauge, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteGauge(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyGauge(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyGaugePtrSlice(dest, src []*Gauge) []*Gauge {\n\tvar newDest []*Gauge\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*Gauge, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewGauge()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteGauge(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewGauge()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyGauge(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *Gauge) Reset() {\n\t*orig = Gauge{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *Gauge) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.DataPoints) > 0 {\n\t\tdest.WriteObjectField(\"dataPoints\")\n\t\tdest.WriteArrayStart()\n\t\torig.DataPoints[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.DataPoints); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.DataPoints[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *Gauge) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"dataPoints\", \"data_points\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.DataPoints = append(orig.DataPoints, NewNumberDataPoint())\n\t\t\t\torig.DataPoints[len(orig.DataPoints)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *Gauge) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.DataPoints {\n\t\tl = orig.DataPoints[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *Gauge) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.DataPoints) - 1; i >= 0; i-- {\n\t\tl = orig.DataPoints[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *Gauge) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DataPoints\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.DataPoints = append(orig.DataPoints, NewNumberDataPoint())\n\t\t\terr = orig.DataPoints[len(orig.DataPoints)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestGauge() *Gauge {\n\torig := NewGauge()\n\torig.DataPoints = []*NumberDataPoint{{}, GenTestNumberDataPoint()}\n\treturn orig\n}\n\nfunc GenTestGaugePtrSlice() []*Gauge {\n\torig := make([]*Gauge, 5)\n\torig[0] = NewGauge()\n\torig[1] = GenTestGauge()\n\torig[2] = NewGauge()\n\torig[3] = GenTestGauge()\n\torig[4] = NewGauge()\n\treturn orig\n}\n\nfunc GenTestGaugeSlice() []Gauge {\n\torig := make([]Gauge, 5)\n\torig[1] = *GenTestGauge()\n\torig[3] = *GenTestGauge()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_gauge_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyGauge(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesGauge() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewGauge()\n\t\t\t\tCopyGauge(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyGauge(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyGaugeSlice(t *testing.T) {\n\tsrc := []Gauge{}\n\tdest := []Gauge{}\n\t// Test CopyTo empty\n\tdest = CopyGaugeSlice(dest, src)\n\tassert.Equal(t, []Gauge{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestGaugeSlice()\n\tdest = CopyGaugeSlice(dest, src)\n\tassert.Equal(t, GenTestGaugeSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyGaugeSlice(dest, src)\n\tassert.Equal(t, GenTestGaugeSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyGaugeSlice(dest, []Gauge{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyGaugeSlice(dest, src)\n\tassert.Equal(t, GenTestGaugeSlice(), dest)\n}\n\nfunc TestCopyGaugePtrSlice(t *testing.T) {\n\tsrc := []*Gauge{}\n\tdest := []*Gauge{}\n\t// Test CopyTo empty\n\tdest = CopyGaugePtrSlice(dest, src)\n\tassert.Equal(t, []*Gauge{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestGaugePtrSlice()\n\tdest = CopyGaugePtrSlice(dest, src)\n\tassert.Equal(t, GenTestGaugePtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyGaugePtrSlice(dest, src)\n\tassert.Equal(t, GenTestGaugePtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyGaugePtrSlice(dest, []*Gauge{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyGaugePtrSlice(dest, src)\n\tassert.Equal(t, GenTestGaugePtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONGaugeUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewGauge()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewGauge(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONGauge(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesGauge() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewGauge()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteGauge(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoGaugeFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesGauge() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewGauge()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoGaugeUnknown(t *testing.T) {\n\tdest := NewGauge()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewGauge(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoGauge(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesGauge() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewGauge()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteGauge(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufGauge(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesGauge() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpmetrics.Gauge{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewGauge()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesGauge() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":              {0x02},\n\t\t\"DataPoints/wrong_wire_type\": {0xc},\n\t\t\"DataPoints/missing_value\":   {0xa},\n\t}\n}\n\nfunc genTestEncodingValuesGauge() map[string]*Gauge {\n\treturn map[string]*Gauge{\n\t\t\"empty\":           NewGauge(),\n\t\t\"DataPoints/test\": {DataPoints: []*NumberDataPoint{{}, GenTestNumberDataPoint()}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_histogram.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Histogram represents the type of a metric that is calculated by aggregating as a Histogram of all reported measurements over a time interval.\ntype Histogram struct {\n\tDataPoints             []*HistogramDataPoint\n\tAggregationTemporality AggregationTemporality\n}\n\nvar (\n\tprotoPoolHistogram = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Histogram{}\n\t\t},\n\t}\n)\n\nfunc NewHistogram() *Histogram {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &Histogram{}\n\t}\n\treturn protoPoolHistogram.Get().(*Histogram)\n}\n\nfunc DeleteHistogram(orig *Histogram, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.DataPoints {\n\t\tDeleteHistogramDataPoint(orig.DataPoints[i], true)\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolHistogram.Put(orig)\n\t}\n}\n\nfunc CopyHistogram(dest, src *Histogram) *Histogram {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewHistogram()\n\t}\n\tdest.DataPoints = CopyHistogramDataPointPtrSlice(dest.DataPoints, src.DataPoints)\n\n\tdest.AggregationTemporality = src.AggregationTemporality\n\n\treturn dest\n}\n\nfunc CopyHistogramSlice(dest, src []Histogram) []Histogram {\n\tvar newDest []Histogram\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]Histogram, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteHistogram(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyHistogram(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyHistogramPtrSlice(dest, src []*Histogram) []*Histogram {\n\tvar newDest []*Histogram\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*Histogram, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewHistogram()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteHistogram(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewHistogram()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyHistogram(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *Histogram) Reset() {\n\t*orig = Histogram{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *Histogram) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.DataPoints) > 0 {\n\t\tdest.WriteObjectField(\"dataPoints\")\n\t\tdest.WriteArrayStart()\n\t\torig.DataPoints[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.DataPoints); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.DataPoints[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\n\tif int32(orig.AggregationTemporality) != 0 {\n\t\tdest.WriteObjectField(\"aggregationTemporality\")\n\t\tdest.WriteInt32(int32(orig.AggregationTemporality))\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *Histogram) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"dataPoints\", \"data_points\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.DataPoints = append(orig.DataPoints, NewHistogramDataPoint())\n\t\t\t\torig.DataPoints[len(orig.DataPoints)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"aggregationTemporality\", \"aggregation_temporality\":\n\t\t\torig.AggregationTemporality = AggregationTemporality(iter.ReadEnumValue(AggregationTemporality_value))\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *Histogram) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.DataPoints {\n\t\tl = orig.DataPoints[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.AggregationTemporality != AggregationTemporality(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.AggregationTemporality))\n\t}\n\treturn n\n}\n\nfunc (orig *Histogram) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.DataPoints) - 1; i >= 0; i-- {\n\t\tl = orig.DataPoints[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\tif orig.AggregationTemporality != AggregationTemporality(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.AggregationTemporality))\n\t\tpos--\n\t\tbuf[pos] = 0x10\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *Histogram) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DataPoints\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.DataPoints = append(orig.DataPoints, NewHistogramDataPoint())\n\t\t\terr = orig.DataPoints[len(orig.DataPoints)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field AggregationTemporality\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.AggregationTemporality = AggregationTemporality(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestHistogram() *Histogram {\n\torig := NewHistogram()\n\torig.DataPoints = []*HistogramDataPoint{{}, GenTestHistogramDataPoint()}\n\torig.AggregationTemporality = AggregationTemporality(13)\n\treturn orig\n}\n\nfunc GenTestHistogramPtrSlice() []*Histogram {\n\torig := make([]*Histogram, 5)\n\torig[0] = NewHistogram()\n\torig[1] = GenTestHistogram()\n\torig[2] = NewHistogram()\n\torig[3] = GenTestHistogram()\n\torig[4] = NewHistogram()\n\treturn orig\n}\n\nfunc GenTestHistogramSlice() []Histogram {\n\torig := make([]Histogram, 5)\n\torig[1] = *GenTestHistogram()\n\torig[3] = *GenTestHistogram()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_histogram_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyHistogram(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesHistogram() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewHistogram()\n\t\t\t\tCopyHistogram(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyHistogram(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyHistogramSlice(t *testing.T) {\n\tsrc := []Histogram{}\n\tdest := []Histogram{}\n\t// Test CopyTo empty\n\tdest = CopyHistogramSlice(dest, src)\n\tassert.Equal(t, []Histogram{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestHistogramSlice()\n\tdest = CopyHistogramSlice(dest, src)\n\tassert.Equal(t, GenTestHistogramSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyHistogramSlice(dest, src)\n\tassert.Equal(t, GenTestHistogramSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyHistogramSlice(dest, []Histogram{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyHistogramSlice(dest, src)\n\tassert.Equal(t, GenTestHistogramSlice(), dest)\n}\n\nfunc TestCopyHistogramPtrSlice(t *testing.T) {\n\tsrc := []*Histogram{}\n\tdest := []*Histogram{}\n\t// Test CopyTo empty\n\tdest = CopyHistogramPtrSlice(dest, src)\n\tassert.Equal(t, []*Histogram{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestHistogramPtrSlice()\n\tdest = CopyHistogramPtrSlice(dest, src)\n\tassert.Equal(t, GenTestHistogramPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyHistogramPtrSlice(dest, src)\n\tassert.Equal(t, GenTestHistogramPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyHistogramPtrSlice(dest, []*Histogram{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyHistogramPtrSlice(dest, src)\n\tassert.Equal(t, GenTestHistogramPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONHistogramUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewHistogram()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewHistogram(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONHistogram(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesHistogram() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewHistogram()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteHistogram(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoHistogramFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesHistogram() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewHistogram()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoHistogramUnknown(t *testing.T) {\n\tdest := NewHistogram()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewHistogram(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoHistogram(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesHistogram() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewHistogram()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteHistogram(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufHistogram(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesHistogram() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpmetrics.Histogram{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewHistogram()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesHistogram() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                          {0x02},\n\t\t\"DataPoints/wrong_wire_type\":             {0xc},\n\t\t\"DataPoints/missing_value\":               {0xa},\n\t\t\"AggregationTemporality/wrong_wire_type\": {0x14},\n\t\t\"AggregationTemporality/missing_value\":   {0x10},\n\t}\n}\n\nfunc genTestEncodingValuesHistogram() map[string]*Histogram {\n\treturn map[string]*Histogram{\n\t\t\"empty\":                       NewHistogram(),\n\t\t\"DataPoints/test\":             {DataPoints: []*HistogramDataPoint{{}, GenTestHistogramDataPoint()}},\n\t\t\"AggregationTemporality/test\": {AggregationTemporality: AggregationTemporality(13)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_histogramdatapoint.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"math\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// HistogramDataPoint is a single data point in a timeseries that describes the time-varying values of a Histogram of values.\ntype HistogramDataPoint struct {\n\tAttributes        []KeyValue\n\tBucketCounts      []uint64\n\tExplicitBounds    []float64\n\tExemplars         []Exemplar\n\tStartTimeUnixNano uint64\n\tTimeUnixNano      uint64\n\tCount             uint64\n\tSum               float64\n\tMin               float64\n\tMax               float64\n\tmetadata          [1]uint64\n\tFlags             uint32\n}\n\nvar (\n\tprotoPoolHistogramDataPoint = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &HistogramDataPoint{}\n\t\t},\n\t}\n)\n\nfunc NewHistogramDataPoint() *HistogramDataPoint {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &HistogramDataPoint{}\n\t}\n\treturn protoPoolHistogramDataPoint.Get().(*HistogramDataPoint)\n}\n\nfunc DeleteHistogramDataPoint(orig *HistogramDataPoint, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.Attributes {\n\t\tDeleteKeyValue(&orig.Attributes[i], false)\n\t}\n\n\tfor i := range orig.Exemplars {\n\t\tDeleteExemplar(&orig.Exemplars[i], false)\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolHistogramDataPoint.Put(orig)\n\t}\n}\n\nfunc CopyHistogramDataPoint(dest, src *HistogramDataPoint) *HistogramDataPoint {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewHistogramDataPoint()\n\t}\n\tdest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)\n\n\tdest.StartTimeUnixNano = src.StartTimeUnixNano\n\tdest.TimeUnixNano = src.TimeUnixNano\n\tdest.Count = src.Count\n\tif src.HasSum() {\n\t\tdest.SetSum(src.Sum)\n\t} else {\n\t\tdest.RemoveSum()\n\t}\n\n\tdest.BucketCounts = append(dest.BucketCounts[:0], src.BucketCounts...)\n\n\tdest.ExplicitBounds = append(dest.ExplicitBounds[:0], src.ExplicitBounds...)\n\n\tdest.Exemplars = CopyExemplarSlice(dest.Exemplars, src.Exemplars)\n\n\tdest.Flags = src.Flags\n\tif src.HasMin() {\n\t\tdest.SetMin(src.Min)\n\t} else {\n\t\tdest.RemoveMin()\n\t}\n\n\tif src.HasMax() {\n\t\tdest.SetMax(src.Max)\n\t} else {\n\t\tdest.RemoveMax()\n\t}\n\n\treturn dest\n}\n\nfunc CopyHistogramDataPointSlice(dest, src []HistogramDataPoint) []HistogramDataPoint {\n\tvar newDest []HistogramDataPoint\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]HistogramDataPoint, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteHistogramDataPoint(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyHistogramDataPoint(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyHistogramDataPointPtrSlice(dest, src []*HistogramDataPoint) []*HistogramDataPoint {\n\tvar newDest []*HistogramDataPoint\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*HistogramDataPoint, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewHistogramDataPoint()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteHistogramDataPoint(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewHistogramDataPoint()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyHistogramDataPoint(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *HistogramDataPoint) Reset() {\n\t*orig = HistogramDataPoint{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *HistogramDataPoint) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.Attributes) > 0 {\n\t\tdest.WriteObjectField(\"attributes\")\n\t\tdest.WriteArrayStart()\n\t\torig.Attributes[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Attributes); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Attributes[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.StartTimeUnixNano != uint64(0) {\n\t\tdest.WriteObjectField(\"startTimeUnixNano\")\n\t\tdest.WriteUint64(orig.StartTimeUnixNano)\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tdest.WriteObjectField(\"timeUnixNano\")\n\t\tdest.WriteUint64(orig.TimeUnixNano)\n\t}\n\tif orig.Count != uint64(0) {\n\t\tdest.WriteObjectField(\"count\")\n\t\tdest.WriteUint64(orig.Count)\n\t}\n\tif orig.HasSum() {\n\t\tdest.WriteObjectField(\"sum\")\n\t\tdest.WriteFloat64(orig.Sum)\n\t}\n\tif len(orig.BucketCounts) > 0 {\n\t\tdest.WriteObjectField(\"bucketCounts\")\n\t\tdest.WriteArrayStart()\n\t\tdest.WriteUint64(orig.BucketCounts[0])\n\t\tfor i := 1; i < len(orig.BucketCounts); i++ {\n\t\t\tdest.WriteMore()\n\t\t\tdest.WriteUint64(orig.BucketCounts[i])\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\n\tif len(orig.ExplicitBounds) > 0 {\n\t\tdest.WriteObjectField(\"explicitBounds\")\n\t\tdest.WriteArrayStart()\n\t\tdest.WriteFloat64(orig.ExplicitBounds[0])\n\t\tfor i := 1; i < len(orig.ExplicitBounds); i++ {\n\t\t\tdest.WriteMore()\n\t\t\tdest.WriteFloat64(orig.ExplicitBounds[i])\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\n\tif len(orig.Exemplars) > 0 {\n\t\tdest.WriteObjectField(\"exemplars\")\n\t\tdest.WriteArrayStart()\n\t\torig.Exemplars[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Exemplars); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Exemplars[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.Flags != uint32(0) {\n\t\tdest.WriteObjectField(\"flags\")\n\t\tdest.WriteUint32(orig.Flags)\n\t}\n\tif orig.HasMin() {\n\t\tdest.WriteObjectField(\"min\")\n\t\tdest.WriteFloat64(orig.Min)\n\t}\n\tif orig.HasMax() {\n\t\tdest.WriteObjectField(\"max\")\n\t\tdest.WriteFloat64(orig.Max)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *HistogramDataPoint) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"attributes\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\t\torig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"startTimeUnixNano\", \"start_time_unix_nano\":\n\t\t\torig.StartTimeUnixNano = iter.ReadUint64()\n\t\tcase \"timeUnixNano\", \"time_unix_nano\":\n\t\t\torig.TimeUnixNano = iter.ReadUint64()\n\t\tcase \"count\":\n\t\t\torig.Count = iter.ReadUint64()\n\t\tcase \"sum\":\n\t\t\torig.SetSum(iter.ReadFloat64())\n\n\t\tcase \"bucketCounts\", \"bucket_counts\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.BucketCounts = append(orig.BucketCounts, iter.ReadUint64())\n\t\t\t}\n\n\t\tcase \"explicitBounds\", \"explicit_bounds\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.ExplicitBounds = append(orig.ExplicitBounds, iter.ReadFloat64())\n\t\t\t}\n\n\t\tcase \"exemplars\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Exemplars = append(orig.Exemplars, Exemplar{})\n\t\t\t\torig.Exemplars[len(orig.Exemplars)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"flags\":\n\t\t\torig.Flags = iter.ReadUint32()\n\t\tcase \"min\":\n\t\t\torig.SetMin(iter.ReadFloat64())\n\n\t\tcase \"max\":\n\t\t\torig.SetMax(iter.ReadFloat64())\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *HistogramDataPoint) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.Attributes {\n\t\tl = orig.Attributes[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.StartTimeUnixNano != uint64(0) {\n\t\tn += 9\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tn += 9\n\t}\n\tif orig.Count != uint64(0) {\n\t\tn += 9\n\t}\n\tif orig.HasSum() {\n\t\tn += 9\n\t}\n\tl = len(orig.BucketCounts)\n\tif l > 0 {\n\t\tl *= 8\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tl = len(orig.ExplicitBounds)\n\tif l > 0 {\n\t\tl *= 8\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tfor i := range orig.Exemplars {\n\t\tl = orig.Exemplars[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.Flags != uint32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.Flags))\n\t}\n\tif orig.HasMin() {\n\t\tn += 9\n\t}\n\tif orig.HasMax() {\n\t\tn += 9\n\t}\n\treturn n\n}\n\nfunc (orig *HistogramDataPoint) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.Attributes) - 1; i >= 0; i-- {\n\t\tl = orig.Attributes[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x4a\n\t}\n\tif orig.StartTimeUnixNano != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.StartTimeUnixNano))\n\t\tpos--\n\t\tbuf[pos] = 0x11\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimeUnixNano))\n\t\tpos--\n\t\tbuf[pos] = 0x19\n\t}\n\tif orig.Count != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.Count))\n\t\tpos--\n\t\tbuf[pos] = 0x21\n\t}\n\tif orig.HasSum() {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Sum))\n\t\tpos--\n\t\tbuf[pos] = 0x29\n\t}\n\tl = len(orig.BucketCounts)\n\tif l > 0 {\n\t\tfor i := l - 1; i >= 0; i-- {\n\t\t\tpos -= 8\n\t\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.BucketCounts[i]))\n\t\t}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l*8))\n\t\tpos--\n\t\tbuf[pos] = 0x32\n\t}\n\tl = len(orig.ExplicitBounds)\n\tif l > 0 {\n\t\tfor i := l - 1; i >= 0; i-- {\n\t\t\tpos -= 8\n\t\t\tbinary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.ExplicitBounds[i]))\n\t\t}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l*8))\n\t\tpos--\n\t\tbuf[pos] = 0x3a\n\t}\n\tfor i := len(orig.Exemplars) - 1; i >= 0; i-- {\n\t\tl = orig.Exemplars[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x42\n\t}\n\tif orig.Flags != uint32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.Flags))\n\t\tpos--\n\t\tbuf[pos] = 0x50\n\t}\n\tif orig.HasMin() {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Min))\n\t\tpos--\n\t\tbuf[pos] = 0x59\n\t}\n\tif orig.HasMax() {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Max))\n\t\tpos--\n\t\tbuf[pos] = 0x61\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *HistogramDataPoint) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 9:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Attributes\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\terr = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field StartTimeUnixNano\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.StartTimeUnixNano = uint64(num)\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TimeUnixNano\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.TimeUnixNano = uint64(num)\n\n\t\tcase 4:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Count\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.Count = uint64(num)\n\n\t\tcase 5:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Sum\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.SetSum(math.Float64frombits(num))\n\t\tcase 6:\n\t\t\tswitch wireType {\n\t\t\tcase proto.WireTypeLen:\n\t\t\t\tvar length int\n\t\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tstartPos := pos - length\n\t\t\t\tsize := length / 8\n\t\t\t\torig.BucketCounts = make([]uint64, size)\n\t\t\t\tvar num uint64\n\t\t\t\tfor i := 0; i < size; i++ {\n\t\t\t\t\tnum, startPos, err = proto.ConsumeI64(buf[:pos], startPos)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\torig.BucketCounts[i] = uint64(num)\n\t\t\t\t}\n\t\t\t\tif startPos != pos {\n\t\t\t\t\treturn fmt.Errorf(\"proto: invalid field len = %d for field BucketCounts\", pos-startPos)\n\t\t\t\t}\n\t\t\tcase proto.WireTypeI64:\n\t\t\t\tvar num uint64\n\t\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\torig.BucketCounts = append(orig.BucketCounts, uint64(num))\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field BucketCounts\", wireType)\n\t\t\t}\n\t\tcase 7:\n\t\t\tswitch wireType {\n\t\t\tcase proto.WireTypeLen:\n\t\t\t\tvar length int\n\t\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tstartPos := pos - length\n\t\t\t\tsize := length / 8\n\t\t\t\torig.ExplicitBounds = make([]float64, size)\n\t\t\t\tvar num uint64\n\t\t\t\tfor i := 0; i < size; i++ {\n\t\t\t\t\tnum, startPos, err = proto.ConsumeI64(buf[:pos], startPos)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\torig.ExplicitBounds[i] = math.Float64frombits(num)\n\t\t\t\t}\n\t\t\t\tif startPos != pos {\n\t\t\t\t\treturn fmt.Errorf(\"proto: invalid field len = %d for field ExplicitBounds\", pos-startPos)\n\t\t\t\t}\n\t\t\tcase proto.WireTypeI64:\n\t\t\t\tvar num uint64\n\t\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\torig.ExplicitBounds = append(orig.ExplicitBounds, math.Float64frombits(num))\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ExplicitBounds\", wireType)\n\t\t\t}\n\n\t\tcase 8:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Exemplars\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Exemplars = append(orig.Exemplars, Exemplar{})\n\t\t\terr = orig.Exemplars[len(orig.Exemplars)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 10:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Flags\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Flags = uint32(num)\n\n\t\tcase 11:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Min\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.SetMin(math.Float64frombits(num))\n\n\t\tcase 12:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Max\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.SetMax(math.Float64frombits(num))\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nconst fieldBlockHistogramDataPointSum = uint64(0 >> 6)\nconst fieldBitHistogramDataPointSum = uint64(1 << 0 & 0x3F)\n\nfunc (m *HistogramDataPoint) SetSum(value float64) {\n\tm.Sum = value\n\tm.metadata[fieldBlockHistogramDataPointSum] |= fieldBitHistogramDataPointSum\n}\n\nfunc (m *HistogramDataPoint) RemoveSum() {\n\tm.Sum = float64(0)\n\tm.metadata[fieldBlockHistogramDataPointSum] &^= fieldBitHistogramDataPointSum\n}\n\nfunc (m *HistogramDataPoint) HasSum() bool {\n\treturn m.metadata[fieldBlockHistogramDataPointSum]&fieldBitHistogramDataPointSum != 0\n}\n\nconst fieldBlockHistogramDataPointMin = uint64(1 >> 6)\nconst fieldBitHistogramDataPointMin = uint64(1 << 1 & 0x3F)\n\nfunc (m *HistogramDataPoint) SetMin(value float64) {\n\tm.Min = value\n\tm.metadata[fieldBlockHistogramDataPointMin] |= fieldBitHistogramDataPointMin\n}\n\nfunc (m *HistogramDataPoint) RemoveMin() {\n\tm.Min = float64(0)\n\tm.metadata[fieldBlockHistogramDataPointMin] &^= fieldBitHistogramDataPointMin\n}\n\nfunc (m *HistogramDataPoint) HasMin() bool {\n\treturn m.metadata[fieldBlockHistogramDataPointMin]&fieldBitHistogramDataPointMin != 0\n}\n\nconst fieldBlockHistogramDataPointMax = uint64(2 >> 6)\nconst fieldBitHistogramDataPointMax = uint64(1 << 2 & 0x3F)\n\nfunc (m *HistogramDataPoint) SetMax(value float64) {\n\tm.Max = value\n\tm.metadata[fieldBlockHistogramDataPointMax] |= fieldBitHistogramDataPointMax\n}\n\nfunc (m *HistogramDataPoint) RemoveMax() {\n\tm.Max = float64(0)\n\tm.metadata[fieldBlockHistogramDataPointMax] &^= fieldBitHistogramDataPointMax\n}\n\nfunc (m *HistogramDataPoint) HasMax() bool {\n\treturn m.metadata[fieldBlockHistogramDataPointMax]&fieldBitHistogramDataPointMax != 0\n}\n\nfunc GenTestHistogramDataPoint() *HistogramDataPoint {\n\torig := NewHistogramDataPoint()\n\torig.Attributes = []KeyValue{{}, *GenTestKeyValue()}\n\torig.StartTimeUnixNano = uint64(13)\n\torig.TimeUnixNano = uint64(13)\n\torig.Count = uint64(13)\n\torig.SetSum(float64(3.1415926))\n\torig.BucketCounts = []uint64{uint64(0), uint64(13)}\n\torig.ExplicitBounds = []float64{float64(0), float64(3.1415926)}\n\torig.Exemplars = []Exemplar{{}, *GenTestExemplar()}\n\torig.Flags = uint32(13)\n\torig.SetMin(float64(3.1415926))\n\torig.SetMax(float64(3.1415926))\n\treturn orig\n}\n\nfunc GenTestHistogramDataPointPtrSlice() []*HistogramDataPoint {\n\torig := make([]*HistogramDataPoint, 5)\n\torig[0] = NewHistogramDataPoint()\n\torig[1] = GenTestHistogramDataPoint()\n\torig[2] = NewHistogramDataPoint()\n\torig[3] = GenTestHistogramDataPoint()\n\torig[4] = NewHistogramDataPoint()\n\treturn orig\n}\n\nfunc GenTestHistogramDataPointSlice() []HistogramDataPoint {\n\torig := make([]HistogramDataPoint, 5)\n\torig[1] = *GenTestHistogramDataPoint()\n\torig[3] = *GenTestHistogramDataPoint()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_histogramdatapoint_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyHistogramDataPoint(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesHistogramDataPoint() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewHistogramDataPoint()\n\t\t\t\tCopyHistogramDataPoint(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyHistogramDataPoint(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyHistogramDataPointSlice(t *testing.T) {\n\tsrc := []HistogramDataPoint{}\n\tdest := []HistogramDataPoint{}\n\t// Test CopyTo empty\n\tdest = CopyHistogramDataPointSlice(dest, src)\n\tassert.Equal(t, []HistogramDataPoint{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestHistogramDataPointSlice()\n\tdest = CopyHistogramDataPointSlice(dest, src)\n\tassert.Equal(t, GenTestHistogramDataPointSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyHistogramDataPointSlice(dest, src)\n\tassert.Equal(t, GenTestHistogramDataPointSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyHistogramDataPointSlice(dest, []HistogramDataPoint{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyHistogramDataPointSlice(dest, src)\n\tassert.Equal(t, GenTestHistogramDataPointSlice(), dest)\n}\n\nfunc TestCopyHistogramDataPointPtrSlice(t *testing.T) {\n\tsrc := []*HistogramDataPoint{}\n\tdest := []*HistogramDataPoint{}\n\t// Test CopyTo empty\n\tdest = CopyHistogramDataPointPtrSlice(dest, src)\n\tassert.Equal(t, []*HistogramDataPoint{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestHistogramDataPointPtrSlice()\n\tdest = CopyHistogramDataPointPtrSlice(dest, src)\n\tassert.Equal(t, GenTestHistogramDataPointPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyHistogramDataPointPtrSlice(dest, src)\n\tassert.Equal(t, GenTestHistogramDataPointPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyHistogramDataPointPtrSlice(dest, []*HistogramDataPoint{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyHistogramDataPointPtrSlice(dest, src)\n\tassert.Equal(t, GenTestHistogramDataPointPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONHistogramDataPointUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewHistogramDataPoint()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewHistogramDataPoint(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONHistogramDataPoint(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesHistogramDataPoint() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewHistogramDataPoint()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteHistogramDataPoint(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoHistogramDataPointFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesHistogramDataPoint() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewHistogramDataPoint()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoHistogramDataPointUnknown(t *testing.T) {\n\tdest := NewHistogramDataPoint()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewHistogramDataPoint(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoHistogramDataPoint(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesHistogramDataPoint() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewHistogramDataPoint()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteHistogramDataPoint(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufHistogramDataPoint(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesHistogramDataPoint() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpmetrics.HistogramDataPoint{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewHistogramDataPoint()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesHistogramDataPoint() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                     {0x02},\n\t\t\"Attributes/wrong_wire_type\":        {0x4c},\n\t\t\"Attributes/missing_value\":          {0x4a},\n\t\t\"StartTimeUnixNano/wrong_wire_type\": {0x14},\n\t\t\"StartTimeUnixNano/missing_value\":   {0x11},\n\t\t\"TimeUnixNano/wrong_wire_type\":      {0x1c},\n\t\t\"TimeUnixNano/missing_value\":        {0x19},\n\t\t\"Count/wrong_wire_type\":             {0x24},\n\t\t\"Count/missing_value\":               {0x21},\n\t\t\"Sum/wrong_wire_type\":               {0x2c},\n\t\t\"Sum/missing_value\":                 {0x29},\n\t\t\"BucketCounts/wrong_wire_type\":      {0x34},\n\t\t\"BucketCounts/missing_value\":        {0x32},\n\t\t\"ExplicitBounds/wrong_wire_type\":    {0x3c},\n\t\t\"ExplicitBounds/missing_value\":      {0x3a},\n\t\t\"Exemplars/wrong_wire_type\":         {0x44},\n\t\t\"Exemplars/missing_value\":           {0x42},\n\t\t\"Flags/wrong_wire_type\":             {0x54},\n\t\t\"Flags/missing_value\":               {0x50},\n\t\t\"Min/wrong_wire_type\":               {0x5c},\n\t\t\"Min/missing_value\":                 {0x59},\n\t\t\"Max/wrong_wire_type\":               {0x64},\n\t\t\"Max/missing_value\":                 {0x61},\n\t}\n}\n\nfunc genTestEncodingValuesHistogramDataPoint() map[string]*HistogramDataPoint {\n\treturn map[string]*HistogramDataPoint{\n\t\t\"empty\":                  NewHistogramDataPoint(),\n\t\t\"Attributes/test\":        {Attributes: []KeyValue{{}, *GenTestKeyValue()}},\n\t\t\"StartTimeUnixNano/test\": {StartTimeUnixNano: uint64(13)},\n\t\t\"TimeUnixNano/test\":      {TimeUnixNano: uint64(13)},\n\t\t\"Count/test\":             {Count: uint64(13)},\n\t\t\"Sum/test\": func() *HistogramDataPoint {\n\t\t\tms := NewHistogramDataPoint()\n\t\t\tms.SetSum(float64(3.1415926))\n\t\t\treturn ms\n\t\t}(),\n\t\t\"BucketCounts/test\":   {BucketCounts: []uint64{uint64(0), uint64(13)}},\n\t\t\"ExplicitBounds/test\": {ExplicitBounds: []float64{float64(0), float64(3.1415926)}},\n\t\t\"Exemplars/test\":      {Exemplars: []Exemplar{{}, *GenTestExemplar()}},\n\t\t\"Flags/test\":          {Flags: uint32(13)},\n\t\t\"Min/test\": func() *HistogramDataPoint {\n\t\t\tms := NewHistogramDataPoint()\n\t\t\tms.SetMin(float64(3.1415926))\n\t\t\treturn ms\n\t\t}(),\n\t\t\"Max/test\": func() *HistogramDataPoint {\n\t\t\tms := NewHistogramDataPoint()\n\t\t\tms.SetMax(float64(3.1415926))\n\t\t\treturn ms\n\t\t}(),\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_instrumentationscope.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// InstrumentationScope is a message representing the instrumentation scope information.\ntype InstrumentationScope struct {\n\tName                   string\n\tVersion                string\n\tAttributes             []KeyValue\n\tDroppedAttributesCount uint32\n}\n\nvar (\n\tprotoPoolInstrumentationScope = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &InstrumentationScope{}\n\t\t},\n\t}\n)\n\nfunc NewInstrumentationScope() *InstrumentationScope {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &InstrumentationScope{}\n\t}\n\treturn protoPoolInstrumentationScope.Get().(*InstrumentationScope)\n}\n\nfunc DeleteInstrumentationScope(orig *InstrumentationScope, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\tfor i := range orig.Attributes {\n\t\tDeleteKeyValue(&orig.Attributes[i], false)\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolInstrumentationScope.Put(orig)\n\t}\n}\n\nfunc CopyInstrumentationScope(dest, src *InstrumentationScope) *InstrumentationScope {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewInstrumentationScope()\n\t}\n\tdest.Name = src.Name\n\tdest.Version = src.Version\n\tdest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)\n\n\tdest.DroppedAttributesCount = src.DroppedAttributesCount\n\n\treturn dest\n}\n\nfunc CopyInstrumentationScopeSlice(dest, src []InstrumentationScope) []InstrumentationScope {\n\tvar newDest []InstrumentationScope\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]InstrumentationScope, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteInstrumentationScope(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyInstrumentationScope(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyInstrumentationScopePtrSlice(dest, src []*InstrumentationScope) []*InstrumentationScope {\n\tvar newDest []*InstrumentationScope\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*InstrumentationScope, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewInstrumentationScope()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteInstrumentationScope(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewInstrumentationScope()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyInstrumentationScope(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *InstrumentationScope) Reset() {\n\t*orig = InstrumentationScope{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *InstrumentationScope) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.Name != \"\" {\n\t\tdest.WriteObjectField(\"name\")\n\t\tdest.WriteString(orig.Name)\n\t}\n\tif orig.Version != \"\" {\n\t\tdest.WriteObjectField(\"version\")\n\t\tdest.WriteString(orig.Version)\n\t}\n\tif len(orig.Attributes) > 0 {\n\t\tdest.WriteObjectField(\"attributes\")\n\t\tdest.WriteArrayStart()\n\t\torig.Attributes[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Attributes); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Attributes[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tdest.WriteObjectField(\"droppedAttributesCount\")\n\t\tdest.WriteUint32(orig.DroppedAttributesCount)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *InstrumentationScope) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"name\":\n\t\t\torig.Name = iter.ReadString()\n\t\tcase \"version\":\n\t\t\torig.Version = iter.ReadString()\n\t\tcase \"attributes\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\t\torig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"droppedAttributesCount\", \"dropped_attributes_count\":\n\t\t\torig.DroppedAttributesCount = iter.ReadUint32()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *InstrumentationScope) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\n\tl = len(orig.Name)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\n\tl = len(orig.Version)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tfor i := range orig.Attributes {\n\t\tl = orig.Attributes[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.DroppedAttributesCount))\n\t}\n\treturn n\n}\n\nfunc (orig *InstrumentationScope) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = len(orig.Name)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.Name)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\tl = len(orig.Version)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.Version)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tfor i := len(orig.Attributes) - 1; i >= 0; i-- {\n\t\tl = orig.Attributes[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedAttributesCount))\n\t\tpos--\n\t\tbuf[pos] = 0x20\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *InstrumentationScope) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Name\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Name = string(buf[startPos:pos])\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Version\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Version = string(buf[startPos:pos])\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Attributes\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\terr = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 4:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DroppedAttributesCount\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.DroppedAttributesCount = uint32(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestInstrumentationScope() *InstrumentationScope {\n\torig := NewInstrumentationScope()\n\torig.Name = \"test_name\"\n\torig.Version = \"test_version\"\n\torig.Attributes = []KeyValue{{}, *GenTestKeyValue()}\n\torig.DroppedAttributesCount = uint32(13)\n\treturn orig\n}\n\nfunc GenTestInstrumentationScopePtrSlice() []*InstrumentationScope {\n\torig := make([]*InstrumentationScope, 5)\n\torig[0] = NewInstrumentationScope()\n\torig[1] = GenTestInstrumentationScope()\n\torig[2] = NewInstrumentationScope()\n\torig[3] = GenTestInstrumentationScope()\n\torig[4] = NewInstrumentationScope()\n\treturn orig\n}\n\nfunc GenTestInstrumentationScopeSlice() []InstrumentationScope {\n\torig := make([]InstrumentationScope, 5)\n\torig[1] = *GenTestInstrumentationScope()\n\torig[3] = *GenTestInstrumentationScope()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_instrumentationscope_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcommon \"go.opentelemetry.io/proto/slim/otlp/common/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyInstrumentationScope(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesInstrumentationScope() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewInstrumentationScope()\n\t\t\t\tCopyInstrumentationScope(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyInstrumentationScope(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyInstrumentationScopeSlice(t *testing.T) {\n\tsrc := []InstrumentationScope{}\n\tdest := []InstrumentationScope{}\n\t// Test CopyTo empty\n\tdest = CopyInstrumentationScopeSlice(dest, src)\n\tassert.Equal(t, []InstrumentationScope{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestInstrumentationScopeSlice()\n\tdest = CopyInstrumentationScopeSlice(dest, src)\n\tassert.Equal(t, GenTestInstrumentationScopeSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyInstrumentationScopeSlice(dest, src)\n\tassert.Equal(t, GenTestInstrumentationScopeSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyInstrumentationScopeSlice(dest, []InstrumentationScope{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyInstrumentationScopeSlice(dest, src)\n\tassert.Equal(t, GenTestInstrumentationScopeSlice(), dest)\n}\n\nfunc TestCopyInstrumentationScopePtrSlice(t *testing.T) {\n\tsrc := []*InstrumentationScope{}\n\tdest := []*InstrumentationScope{}\n\t// Test CopyTo empty\n\tdest = CopyInstrumentationScopePtrSlice(dest, src)\n\tassert.Equal(t, []*InstrumentationScope{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestInstrumentationScopePtrSlice()\n\tdest = CopyInstrumentationScopePtrSlice(dest, src)\n\tassert.Equal(t, GenTestInstrumentationScopePtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyInstrumentationScopePtrSlice(dest, src)\n\tassert.Equal(t, GenTestInstrumentationScopePtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyInstrumentationScopePtrSlice(dest, []*InstrumentationScope{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyInstrumentationScopePtrSlice(dest, src)\n\tassert.Equal(t, GenTestInstrumentationScopePtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONInstrumentationScopeUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewInstrumentationScope()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewInstrumentationScope(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONInstrumentationScope(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesInstrumentationScope() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewInstrumentationScope()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteInstrumentationScope(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoInstrumentationScopeFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesInstrumentationScope() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewInstrumentationScope()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoInstrumentationScopeUnknown(t *testing.T) {\n\tdest := NewInstrumentationScope()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewInstrumentationScope(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoInstrumentationScope(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesInstrumentationScope() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewInstrumentationScope()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteInstrumentationScope(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufInstrumentationScope(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesInstrumentationScope() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcommon.InstrumentationScope{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewInstrumentationScope()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesInstrumentationScope() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                          {0x02},\n\t\t\"Name/wrong_wire_type\":                   {0xc},\n\t\t\"Name/missing_value\":                     {0xa},\n\t\t\"Version/wrong_wire_type\":                {0x14},\n\t\t\"Version/missing_value\":                  {0x12},\n\t\t\"Attributes/wrong_wire_type\":             {0x1c},\n\t\t\"Attributes/missing_value\":               {0x1a},\n\t\t\"DroppedAttributesCount/wrong_wire_type\": {0x24},\n\t\t\"DroppedAttributesCount/missing_value\":   {0x20},\n\t}\n}\n\nfunc genTestEncodingValuesInstrumentationScope() map[string]*InstrumentationScope {\n\treturn map[string]*InstrumentationScope{\n\t\t\"empty\":                       NewInstrumentationScope(),\n\t\t\"Name/test\":                   {Name: \"test_name\"},\n\t\t\"Version/test\":                {Version: \"test_version\"},\n\t\t\"Attributes/test\":             {Attributes: []KeyValue{{}, *GenTestKeyValue()}},\n\t\t\"DroppedAttributesCount/test\": {DroppedAttributesCount: uint32(13)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_ipaddr.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\ntype IPAddr struct {\n\tZone string\n\tIP   []byte\n}\n\nvar (\n\tprotoPoolIPAddr = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &IPAddr{}\n\t\t},\n\t}\n)\n\nfunc NewIPAddr() *IPAddr {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &IPAddr{}\n\t}\n\treturn protoPoolIPAddr.Get().(*IPAddr)\n}\n\nfunc DeleteIPAddr(orig *IPAddr, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolIPAddr.Put(orig)\n\t}\n}\n\nfunc CopyIPAddr(dest, src *IPAddr) *IPAddr {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewIPAddr()\n\t}\n\tdest.IP = src.IP\n\tdest.Zone = src.Zone\n\n\treturn dest\n}\n\nfunc CopyIPAddrSlice(dest, src []IPAddr) []IPAddr {\n\tvar newDest []IPAddr\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]IPAddr, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteIPAddr(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyIPAddr(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyIPAddrPtrSlice(dest, src []*IPAddr) []*IPAddr {\n\tvar newDest []*IPAddr\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*IPAddr, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewIPAddr()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteIPAddr(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewIPAddr()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyIPAddr(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *IPAddr) Reset() {\n\t*orig = IPAddr{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *IPAddr) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\n\tif len(orig.IP) > 0 {\n\t\tdest.WriteObjectField(\"iP\")\n\t\tdest.WriteBytes(orig.IP)\n\t}\n\tif orig.Zone != \"\" {\n\t\tdest.WriteObjectField(\"zone\")\n\t\tdest.WriteString(orig.Zone)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *IPAddr) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"iP\":\n\t\t\torig.IP = iter.ReadBytes()\n\t\tcase \"zone\":\n\t\t\torig.Zone = iter.ReadString()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *IPAddr) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\n\tl = len(orig.IP)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\n\tl = len(orig.Zone)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *IPAddr) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = len(orig.IP)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.IP)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\tl = len(orig.Zone)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.Zone)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *IPAddr) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field IP\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tif length != 0 {\n\t\t\t\torig.IP = make([]byte, length)\n\t\t\t\tcopy(orig.IP, buf[startPos:pos])\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Zone\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Zone = string(buf[startPos:pos])\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestIPAddr() *IPAddr {\n\torig := NewIPAddr()\n\torig.IP = []byte{1, 2, 3}\n\torig.Zone = \"test_zone\"\n\treturn orig\n}\n\nfunc GenTestIPAddrPtrSlice() []*IPAddr {\n\torig := make([]*IPAddr, 5)\n\torig[0] = NewIPAddr()\n\torig[1] = GenTestIPAddr()\n\torig[2] = NewIPAddr()\n\torig[3] = GenTestIPAddr()\n\torig[4] = NewIPAddr()\n\treturn orig\n}\n\nfunc GenTestIPAddrSlice() []IPAddr {\n\torig := make([]IPAddr, 5)\n\torig[1] = *GenTestIPAddr()\n\torig[3] = *GenTestIPAddr()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_ipaddr_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/protobuf/proto\"\n\t\"google.golang.org/protobuf/types/known/emptypb\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyIPAddr(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesIPAddr() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewIPAddr()\n\t\t\t\tCopyIPAddr(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyIPAddr(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyIPAddrSlice(t *testing.T) {\n\tsrc := []IPAddr{}\n\tdest := []IPAddr{}\n\t// Test CopyTo empty\n\tdest = CopyIPAddrSlice(dest, src)\n\tassert.Equal(t, []IPAddr{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestIPAddrSlice()\n\tdest = CopyIPAddrSlice(dest, src)\n\tassert.Equal(t, GenTestIPAddrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyIPAddrSlice(dest, src)\n\tassert.Equal(t, GenTestIPAddrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyIPAddrSlice(dest, []IPAddr{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyIPAddrSlice(dest, src)\n\tassert.Equal(t, GenTestIPAddrSlice(), dest)\n}\n\nfunc TestCopyIPAddrPtrSlice(t *testing.T) {\n\tsrc := []*IPAddr{}\n\tdest := []*IPAddr{}\n\t// Test CopyTo empty\n\tdest = CopyIPAddrPtrSlice(dest, src)\n\tassert.Equal(t, []*IPAddr{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestIPAddrPtrSlice()\n\tdest = CopyIPAddrPtrSlice(dest, src)\n\tassert.Equal(t, GenTestIPAddrPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyIPAddrPtrSlice(dest, src)\n\tassert.Equal(t, GenTestIPAddrPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyIPAddrPtrSlice(dest, []*IPAddr{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyIPAddrPtrSlice(dest, src)\n\tassert.Equal(t, GenTestIPAddrPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONIPAddrUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewIPAddr()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewIPAddr(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONIPAddr(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesIPAddr() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewIPAddr()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteIPAddr(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoIPAddrFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesIPAddr() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewIPAddr()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoIPAddrUnknown(t *testing.T) {\n\tdest := NewIPAddr()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewIPAddr(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoIPAddr(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesIPAddr() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewIPAddr()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteIPAddr(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufIPAddr(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesIPAddr() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &emptypb.Empty{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewIPAddr()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesIPAddr() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":        {0x02},\n\t\t\"IP/wrong_wire_type\":   {0xc},\n\t\t\"IP/missing_value\":     {0xa},\n\t\t\"Zone/wrong_wire_type\": {0x14},\n\t\t\"Zone/missing_value\":   {0x12},\n\t}\n}\n\nfunc genTestEncodingValuesIPAddr() map[string]*IPAddr {\n\treturn map[string]*IPAddr{\n\t\t\"empty\":     NewIPAddr(),\n\t\t\"IP/test\":   {IP: []byte{1, 2, 3}},\n\t\t\"Zone/test\": {Zone: \"test_zone\"},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_keyvalue.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\ntype KeyValue struct {\n\tValue       AnyValue\n\tKey         string\n\tKeyStrindex int32\n}\n\nvar (\n\tprotoPoolKeyValue = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &KeyValue{}\n\t\t},\n\t}\n)\n\nfunc NewKeyValue() *KeyValue {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &KeyValue{}\n\t}\n\treturn protoPoolKeyValue.Get().(*KeyValue)\n}\n\nfunc DeleteKeyValue(orig *KeyValue, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\tDeleteAnyValue(&orig.Value, false)\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolKeyValue.Put(orig)\n\t}\n}\n\nfunc CopyKeyValue(dest, src *KeyValue) *KeyValue {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewKeyValue()\n\t}\n\tdest.Key = src.Key\n\tCopyAnyValue(&dest.Value, &src.Value)\n\n\tdest.KeyStrindex = src.KeyStrindex\n\n\treturn dest\n}\n\nfunc CopyKeyValueSlice(dest, src []KeyValue) []KeyValue {\n\tvar newDest []KeyValue\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]KeyValue, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteKeyValue(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyKeyValue(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyKeyValuePtrSlice(dest, src []*KeyValue) []*KeyValue {\n\tvar newDest []*KeyValue\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*KeyValue, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewKeyValue()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteKeyValue(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewKeyValue()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyKeyValue(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *KeyValue) Reset() {\n\t*orig = KeyValue{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *KeyValue) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.Key != \"\" {\n\t\tdest.WriteObjectField(\"key\")\n\t\tdest.WriteString(orig.Key)\n\t}\n\tdest.WriteObjectField(\"value\")\n\torig.Value.MarshalJSON(dest)\n\tif orig.KeyStrindex != int32(0) {\n\t\tdest.WriteObjectField(\"keyStrindex\")\n\t\tdest.WriteInt32(orig.KeyStrindex)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *KeyValue) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"key\":\n\t\t\torig.Key = iter.ReadString()\n\t\tcase \"value\":\n\n\t\t\torig.Value.UnmarshalJSON(iter)\n\t\tcase \"keyStrindex\", \"key_strindex\":\n\t\t\torig.KeyStrindex = iter.ReadInt32()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *KeyValue) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\n\tl = len(orig.Key)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tl = orig.Value.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tif orig.KeyStrindex != int32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.KeyStrindex))\n\t}\n\treturn n\n}\n\nfunc (orig *KeyValue) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = len(orig.Key)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.Key)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\tl = orig.Value.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x12\n\n\tif orig.KeyStrindex != int32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.KeyStrindex))\n\t\tpos--\n\t\tbuf[pos] = 0x18\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *KeyValue) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Key\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Key = string(buf[startPos:pos])\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Value\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.Value.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field KeyStrindex\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.KeyStrindex = int32(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestKeyValue() *KeyValue {\n\torig := NewKeyValue()\n\torig.Key = \"test_key\"\n\torig.Value = *GenTestAnyValue()\n\torig.KeyStrindex = int32(13)\n\treturn orig\n}\n\nfunc GenTestKeyValuePtrSlice() []*KeyValue {\n\torig := make([]*KeyValue, 5)\n\torig[0] = NewKeyValue()\n\torig[1] = GenTestKeyValue()\n\torig[2] = NewKeyValue()\n\torig[3] = GenTestKeyValue()\n\torig[4] = NewKeyValue()\n\treturn orig\n}\n\nfunc GenTestKeyValueSlice() []KeyValue {\n\torig := make([]KeyValue, 5)\n\torig[1] = *GenTestKeyValue()\n\torig[3] = *GenTestKeyValue()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_keyvalue_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcommon \"go.opentelemetry.io/proto/slim/otlp/common/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyKeyValue(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesKeyValue() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewKeyValue()\n\t\t\t\tCopyKeyValue(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyKeyValue(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyKeyValueSlice(t *testing.T) {\n\tsrc := []KeyValue{}\n\tdest := []KeyValue{}\n\t// Test CopyTo empty\n\tdest = CopyKeyValueSlice(dest, src)\n\tassert.Equal(t, []KeyValue{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestKeyValueSlice()\n\tdest = CopyKeyValueSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValueSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyKeyValueSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValueSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyKeyValueSlice(dest, []KeyValue{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyKeyValueSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValueSlice(), dest)\n}\n\nfunc TestCopyKeyValuePtrSlice(t *testing.T) {\n\tsrc := []*KeyValue{}\n\tdest := []*KeyValue{}\n\t// Test CopyTo empty\n\tdest = CopyKeyValuePtrSlice(dest, src)\n\tassert.Equal(t, []*KeyValue{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestKeyValuePtrSlice()\n\tdest = CopyKeyValuePtrSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValuePtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyKeyValuePtrSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValuePtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyKeyValuePtrSlice(dest, []*KeyValue{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyKeyValuePtrSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValuePtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONKeyValueUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewKeyValue()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewKeyValue(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONKeyValue(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesKeyValue() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewKeyValue()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteKeyValue(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoKeyValueFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesKeyValue() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewKeyValue()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoKeyValueUnknown(t *testing.T) {\n\tdest := NewKeyValue()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewKeyValue(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoKeyValue(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesKeyValue() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewKeyValue()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteKeyValue(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufKeyValue(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesKeyValue() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcommon.KeyValue{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewKeyValue()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesKeyValue() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":               {0x02},\n\t\t\"Key/wrong_wire_type\":         {0xc},\n\t\t\"Key/missing_value\":           {0xa},\n\t\t\"Value/wrong_wire_type\":       {0x14},\n\t\t\"Value/missing_value\":         {0x12},\n\t\t\"KeyStrindex/wrong_wire_type\": {0x1c},\n\t\t\"KeyStrindex/missing_value\":   {0x18},\n\t}\n}\n\nfunc genTestEncodingValuesKeyValue() map[string]*KeyValue {\n\treturn map[string]*KeyValue{\n\t\t\"empty\":            NewKeyValue(),\n\t\t\"Key/test\":         {Key: \"test_key\"},\n\t\t\"Value/test\":       {Value: *GenTestAnyValue()},\n\t\t\"KeyStrindex/test\": {KeyStrindex: int32(13)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_keyvalueandunit.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// KeyValueAndUnit represents a custom 'dictionary native'\n// style of encoding attributes which is more convenient\n// for profiles than opentelemetry.proto.common.v1.KeyValue.\ntype KeyValueAndUnit struct {\n\tValue        AnyValue\n\tKeyStrindex  int32\n\tUnitStrindex int32\n}\n\nvar (\n\tprotoPoolKeyValueAndUnit = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &KeyValueAndUnit{}\n\t\t},\n\t}\n)\n\nfunc NewKeyValueAndUnit() *KeyValueAndUnit {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &KeyValueAndUnit{}\n\t}\n\treturn protoPoolKeyValueAndUnit.Get().(*KeyValueAndUnit)\n}\n\nfunc DeleteKeyValueAndUnit(orig *KeyValueAndUnit, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\tDeleteAnyValue(&orig.Value, false)\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolKeyValueAndUnit.Put(orig)\n\t}\n}\n\nfunc CopyKeyValueAndUnit(dest, src *KeyValueAndUnit) *KeyValueAndUnit {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewKeyValueAndUnit()\n\t}\n\tdest.KeyStrindex = src.KeyStrindex\n\tCopyAnyValue(&dest.Value, &src.Value)\n\n\tdest.UnitStrindex = src.UnitStrindex\n\n\treturn dest\n}\n\nfunc CopyKeyValueAndUnitSlice(dest, src []KeyValueAndUnit) []KeyValueAndUnit {\n\tvar newDest []KeyValueAndUnit\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]KeyValueAndUnit, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteKeyValueAndUnit(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyKeyValueAndUnit(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyKeyValueAndUnitPtrSlice(dest, src []*KeyValueAndUnit) []*KeyValueAndUnit {\n\tvar newDest []*KeyValueAndUnit\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*KeyValueAndUnit, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewKeyValueAndUnit()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteKeyValueAndUnit(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewKeyValueAndUnit()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyKeyValueAndUnit(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *KeyValueAndUnit) Reset() {\n\t*orig = KeyValueAndUnit{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *KeyValueAndUnit) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.KeyStrindex != int32(0) {\n\t\tdest.WriteObjectField(\"keyStrindex\")\n\t\tdest.WriteInt32(orig.KeyStrindex)\n\t}\n\tdest.WriteObjectField(\"value\")\n\torig.Value.MarshalJSON(dest)\n\tif orig.UnitStrindex != int32(0) {\n\t\tdest.WriteObjectField(\"unitStrindex\")\n\t\tdest.WriteInt32(orig.UnitStrindex)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *KeyValueAndUnit) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"keyStrindex\", \"key_strindex\":\n\t\t\torig.KeyStrindex = iter.ReadInt32()\n\t\tcase \"value\":\n\n\t\t\torig.Value.UnmarshalJSON(iter)\n\t\tcase \"unitStrindex\", \"unit_strindex\":\n\t\t\torig.UnitStrindex = iter.ReadInt32()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *KeyValueAndUnit) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.KeyStrindex != int32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.KeyStrindex))\n\t}\n\tl = orig.Value.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tif orig.UnitStrindex != int32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.UnitStrindex))\n\t}\n\treturn n\n}\n\nfunc (orig *KeyValueAndUnit) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.KeyStrindex != int32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.KeyStrindex))\n\t\tpos--\n\t\tbuf[pos] = 0x8\n\t}\n\tl = orig.Value.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x12\n\n\tif orig.UnitStrindex != int32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.UnitStrindex))\n\t\tpos--\n\t\tbuf[pos] = 0x18\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *KeyValueAndUnit) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field KeyStrindex\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.KeyStrindex = int32(num)\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Value\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.Value.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field UnitStrindex\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.UnitStrindex = int32(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestKeyValueAndUnit() *KeyValueAndUnit {\n\torig := NewKeyValueAndUnit()\n\torig.KeyStrindex = int32(13)\n\torig.Value = *GenTestAnyValue()\n\torig.UnitStrindex = int32(13)\n\treturn orig\n}\n\nfunc GenTestKeyValueAndUnitPtrSlice() []*KeyValueAndUnit {\n\torig := make([]*KeyValueAndUnit, 5)\n\torig[0] = NewKeyValueAndUnit()\n\torig[1] = GenTestKeyValueAndUnit()\n\torig[2] = NewKeyValueAndUnit()\n\torig[3] = GenTestKeyValueAndUnit()\n\torig[4] = NewKeyValueAndUnit()\n\treturn orig\n}\n\nfunc GenTestKeyValueAndUnitSlice() []KeyValueAndUnit {\n\torig := make([]KeyValueAndUnit, 5)\n\torig[1] = *GenTestKeyValueAndUnit()\n\torig[3] = *GenTestKeyValueAndUnit()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_keyvalueandunit_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpprofiles \"go.opentelemetry.io/proto/slim/otlp/profiles/v1development\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyKeyValueAndUnit(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesKeyValueAndUnit() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewKeyValueAndUnit()\n\t\t\t\tCopyKeyValueAndUnit(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyKeyValueAndUnit(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyKeyValueAndUnitSlice(t *testing.T) {\n\tsrc := []KeyValueAndUnit{}\n\tdest := []KeyValueAndUnit{}\n\t// Test CopyTo empty\n\tdest = CopyKeyValueAndUnitSlice(dest, src)\n\tassert.Equal(t, []KeyValueAndUnit{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestKeyValueAndUnitSlice()\n\tdest = CopyKeyValueAndUnitSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValueAndUnitSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyKeyValueAndUnitSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValueAndUnitSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyKeyValueAndUnitSlice(dest, []KeyValueAndUnit{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyKeyValueAndUnitSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValueAndUnitSlice(), dest)\n}\n\nfunc TestCopyKeyValueAndUnitPtrSlice(t *testing.T) {\n\tsrc := []*KeyValueAndUnit{}\n\tdest := []*KeyValueAndUnit{}\n\t// Test CopyTo empty\n\tdest = CopyKeyValueAndUnitPtrSlice(dest, src)\n\tassert.Equal(t, []*KeyValueAndUnit{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestKeyValueAndUnitPtrSlice()\n\tdest = CopyKeyValueAndUnitPtrSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValueAndUnitPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyKeyValueAndUnitPtrSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValueAndUnitPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyKeyValueAndUnitPtrSlice(dest, []*KeyValueAndUnit{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyKeyValueAndUnitPtrSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValueAndUnitPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONKeyValueAndUnitUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewKeyValueAndUnit()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewKeyValueAndUnit(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONKeyValueAndUnit(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesKeyValueAndUnit() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewKeyValueAndUnit()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteKeyValueAndUnit(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoKeyValueAndUnitFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesKeyValueAndUnit() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewKeyValueAndUnit()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoKeyValueAndUnitUnknown(t *testing.T) {\n\tdest := NewKeyValueAndUnit()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewKeyValueAndUnit(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoKeyValueAndUnit(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesKeyValueAndUnit() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewKeyValueAndUnit()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteKeyValueAndUnit(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufKeyValueAndUnit(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesKeyValueAndUnit() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpprofiles.KeyValueAndUnit{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewKeyValueAndUnit()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesKeyValueAndUnit() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                {0x02},\n\t\t\"KeyStrindex/wrong_wire_type\":  {0xc},\n\t\t\"KeyStrindex/missing_value\":    {0x8},\n\t\t\"Value/wrong_wire_type\":        {0x14},\n\t\t\"Value/missing_value\":          {0x12},\n\t\t\"UnitStrindex/wrong_wire_type\": {0x1c},\n\t\t\"UnitStrindex/missing_value\":   {0x18},\n\t}\n}\n\nfunc genTestEncodingValuesKeyValueAndUnit() map[string]*KeyValueAndUnit {\n\treturn map[string]*KeyValueAndUnit{\n\t\t\"empty\":             NewKeyValueAndUnit(),\n\t\t\"KeyStrindex/test\":  {KeyStrindex: int32(13)},\n\t\t\"Value/test\":        {Value: *GenTestAnyValue()},\n\t\t\"UnitStrindex/test\": {UnitStrindex: int32(13)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_keyvaluelist.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// KeyValueList is a list of KeyValue messages. We need KeyValueList as a message since oneof in AnyValue does not allow repeated fields.\ntype KeyValueList struct {\n\tValues []KeyValue\n}\n\nvar (\n\tprotoPoolKeyValueList = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &KeyValueList{}\n\t\t},\n\t}\n)\n\nfunc NewKeyValueList() *KeyValueList {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &KeyValueList{}\n\t}\n\treturn protoPoolKeyValueList.Get().(*KeyValueList)\n}\n\nfunc DeleteKeyValueList(orig *KeyValueList, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.Values {\n\t\tDeleteKeyValue(&orig.Values[i], false)\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolKeyValueList.Put(orig)\n\t}\n}\n\nfunc CopyKeyValueList(dest, src *KeyValueList) *KeyValueList {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewKeyValueList()\n\t}\n\tdest.Values = CopyKeyValueSlice(dest.Values, src.Values)\n\n\treturn dest\n}\n\nfunc CopyKeyValueListSlice(dest, src []KeyValueList) []KeyValueList {\n\tvar newDest []KeyValueList\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]KeyValueList, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteKeyValueList(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyKeyValueList(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyKeyValueListPtrSlice(dest, src []*KeyValueList) []*KeyValueList {\n\tvar newDest []*KeyValueList\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*KeyValueList, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewKeyValueList()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteKeyValueList(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewKeyValueList()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyKeyValueList(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *KeyValueList) Reset() {\n\t*orig = KeyValueList{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *KeyValueList) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.Values) > 0 {\n\t\tdest.WriteObjectField(\"values\")\n\t\tdest.WriteArrayStart()\n\t\torig.Values[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Values); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Values[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *KeyValueList) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"values\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Values = append(orig.Values, KeyValue{})\n\t\t\t\torig.Values[len(orig.Values)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *KeyValueList) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.Values {\n\t\tl = orig.Values[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *KeyValueList) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.Values) - 1; i >= 0; i-- {\n\t\tl = orig.Values[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *KeyValueList) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Values\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Values = append(orig.Values, KeyValue{})\n\t\t\terr = orig.Values[len(orig.Values)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestKeyValueList() *KeyValueList {\n\torig := NewKeyValueList()\n\torig.Values = []KeyValue{{}, *GenTestKeyValue()}\n\treturn orig\n}\n\nfunc GenTestKeyValueListPtrSlice() []*KeyValueList {\n\torig := make([]*KeyValueList, 5)\n\torig[0] = NewKeyValueList()\n\torig[1] = GenTestKeyValueList()\n\torig[2] = NewKeyValueList()\n\torig[3] = GenTestKeyValueList()\n\torig[4] = NewKeyValueList()\n\treturn orig\n}\n\nfunc GenTestKeyValueListSlice() []KeyValueList {\n\torig := make([]KeyValueList, 5)\n\torig[1] = *GenTestKeyValueList()\n\torig[3] = *GenTestKeyValueList()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_keyvaluelist_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcommon \"go.opentelemetry.io/proto/slim/otlp/common/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyKeyValueList(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesKeyValueList() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewKeyValueList()\n\t\t\t\tCopyKeyValueList(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyKeyValueList(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyKeyValueListSlice(t *testing.T) {\n\tsrc := []KeyValueList{}\n\tdest := []KeyValueList{}\n\t// Test CopyTo empty\n\tdest = CopyKeyValueListSlice(dest, src)\n\tassert.Equal(t, []KeyValueList{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestKeyValueListSlice()\n\tdest = CopyKeyValueListSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValueListSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyKeyValueListSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValueListSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyKeyValueListSlice(dest, []KeyValueList{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyKeyValueListSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValueListSlice(), dest)\n}\n\nfunc TestCopyKeyValueListPtrSlice(t *testing.T) {\n\tsrc := []*KeyValueList{}\n\tdest := []*KeyValueList{}\n\t// Test CopyTo empty\n\tdest = CopyKeyValueListPtrSlice(dest, src)\n\tassert.Equal(t, []*KeyValueList{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestKeyValueListPtrSlice()\n\tdest = CopyKeyValueListPtrSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValueListPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyKeyValueListPtrSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValueListPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyKeyValueListPtrSlice(dest, []*KeyValueList{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyKeyValueListPtrSlice(dest, src)\n\tassert.Equal(t, GenTestKeyValueListPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONKeyValueListUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewKeyValueList()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewKeyValueList(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONKeyValueList(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesKeyValueList() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewKeyValueList()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteKeyValueList(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoKeyValueListFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesKeyValueList() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewKeyValueList()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoKeyValueListUnknown(t *testing.T) {\n\tdest := NewKeyValueList()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewKeyValueList(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoKeyValueList(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesKeyValueList() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewKeyValueList()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteKeyValueList(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufKeyValueList(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesKeyValueList() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpcommon.KeyValueList{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewKeyValueList()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesKeyValueList() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":          {0x02},\n\t\t\"Values/wrong_wire_type\": {0xc},\n\t\t\"Values/missing_value\":   {0xa},\n\t}\n}\n\nfunc genTestEncodingValuesKeyValueList() map[string]*KeyValueList {\n\treturn map[string]*KeyValueList{\n\t\t\"empty\":       NewKeyValueList(),\n\t\t\"Values/test\": {Values: []KeyValue{{}, *GenTestKeyValue()}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_line.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Line details a specific line in a source code, linked to a function.\ntype Line struct {\n\tFunctionIndex int32\n\tLine          int64\n\tColumn        int64\n}\n\nvar (\n\tprotoPoolLine = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Line{}\n\t\t},\n\t}\n)\n\nfunc NewLine() *Line {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &Line{}\n\t}\n\treturn protoPoolLine.Get().(*Line)\n}\n\nfunc DeleteLine(orig *Line, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolLine.Put(orig)\n\t}\n}\n\nfunc CopyLine(dest, src *Line) *Line {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewLine()\n\t}\n\tdest.FunctionIndex = src.FunctionIndex\n\tdest.Line = src.Line\n\tdest.Column = src.Column\n\n\treturn dest\n}\n\nfunc CopyLineSlice(dest, src []Line) []Line {\n\tvar newDest []Line\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]Line, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteLine(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyLine(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyLinePtrSlice(dest, src []*Line) []*Line {\n\tvar newDest []*Line\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*Line, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewLine()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteLine(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewLine()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyLine(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *Line) Reset() {\n\t*orig = Line{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *Line) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.FunctionIndex != int32(0) {\n\t\tdest.WriteObjectField(\"functionIndex\")\n\t\tdest.WriteInt32(orig.FunctionIndex)\n\t}\n\tif orig.Line != int64(0) {\n\t\tdest.WriteObjectField(\"line\")\n\t\tdest.WriteInt64(orig.Line)\n\t}\n\tif orig.Column != int64(0) {\n\t\tdest.WriteObjectField(\"column\")\n\t\tdest.WriteInt64(orig.Column)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *Line) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"functionIndex\", \"function_index\":\n\t\t\torig.FunctionIndex = iter.ReadInt32()\n\t\tcase \"line\":\n\t\t\torig.Line = iter.ReadInt64()\n\t\tcase \"column\":\n\t\t\torig.Column = iter.ReadInt64()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *Line) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.FunctionIndex != int32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.FunctionIndex))\n\t}\n\tif orig.Line != int64(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.Line))\n\t}\n\tif orig.Column != int64(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.Column))\n\t}\n\treturn n\n}\n\nfunc (orig *Line) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.FunctionIndex != int32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.FunctionIndex))\n\t\tpos--\n\t\tbuf[pos] = 0x8\n\t}\n\tif orig.Line != int64(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.Line))\n\t\tpos--\n\t\tbuf[pos] = 0x10\n\t}\n\tif orig.Column != int64(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.Column))\n\t\tpos--\n\t\tbuf[pos] = 0x18\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *Line) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field FunctionIndex\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.FunctionIndex = int32(num)\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Line\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Line = int64(num)\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Column\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Column = int64(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestLine() *Line {\n\torig := NewLine()\n\torig.FunctionIndex = int32(13)\n\torig.Line = int64(13)\n\torig.Column = int64(13)\n\treturn orig\n}\n\nfunc GenTestLinePtrSlice() []*Line {\n\torig := make([]*Line, 5)\n\torig[0] = NewLine()\n\torig[1] = GenTestLine()\n\torig[2] = NewLine()\n\torig[3] = GenTestLine()\n\torig[4] = NewLine()\n\treturn orig\n}\n\nfunc GenTestLineSlice() []Line {\n\torig := make([]Line, 5)\n\torig[1] = *GenTestLine()\n\torig[3] = *GenTestLine()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_line_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpprofiles \"go.opentelemetry.io/proto/slim/otlp/profiles/v1development\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyLine(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLine() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewLine()\n\t\t\t\tCopyLine(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyLine(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyLineSlice(t *testing.T) {\n\tsrc := []Line{}\n\tdest := []Line{}\n\t// Test CopyTo empty\n\tdest = CopyLineSlice(dest, src)\n\tassert.Equal(t, []Line{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestLineSlice()\n\tdest = CopyLineSlice(dest, src)\n\tassert.Equal(t, GenTestLineSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyLineSlice(dest, src)\n\tassert.Equal(t, GenTestLineSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyLineSlice(dest, []Line{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyLineSlice(dest, src)\n\tassert.Equal(t, GenTestLineSlice(), dest)\n}\n\nfunc TestCopyLinePtrSlice(t *testing.T) {\n\tsrc := []*Line{}\n\tdest := []*Line{}\n\t// Test CopyTo empty\n\tdest = CopyLinePtrSlice(dest, src)\n\tassert.Equal(t, []*Line{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestLinePtrSlice()\n\tdest = CopyLinePtrSlice(dest, src)\n\tassert.Equal(t, GenTestLinePtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyLinePtrSlice(dest, src)\n\tassert.Equal(t, GenTestLinePtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyLinePtrSlice(dest, []*Line{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyLinePtrSlice(dest, src)\n\tassert.Equal(t, GenTestLinePtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONLineUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewLine()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewLine(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONLine(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLine() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewLine()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteLine(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoLineFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesLine() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewLine()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoLineUnknown(t *testing.T) {\n\tdest := NewLine()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewLine(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoLine(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLine() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewLine()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteLine(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufLine(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLine() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpprofiles.Line{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewLine()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesLine() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                 {0x02},\n\t\t\"FunctionIndex/wrong_wire_type\": {0xc},\n\t\t\"FunctionIndex/missing_value\":   {0x8},\n\t\t\"Line/wrong_wire_type\":          {0x14},\n\t\t\"Line/missing_value\":            {0x10},\n\t\t\"Column/wrong_wire_type\":        {0x1c},\n\t\t\"Column/missing_value\":          {0x18},\n\t}\n}\n\nfunc genTestEncodingValuesLine() map[string]*Line {\n\treturn map[string]*Line{\n\t\t\"empty\":              NewLine(),\n\t\t\"FunctionIndex/test\": {FunctionIndex: int32(13)},\n\t\t\"Line/test\":          {Line: int64(13)},\n\t\t\"Column/test\":        {Column: int64(13)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_link.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Link represents a pointer from a profile Sample to a trace Span.\ntype Link struct {\n\tTraceId TraceID\n\tSpanId  SpanID\n}\n\nvar (\n\tprotoPoolLink = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Link{}\n\t\t},\n\t}\n)\n\nfunc NewLink() *Link {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &Link{}\n\t}\n\treturn protoPoolLink.Get().(*Link)\n}\n\nfunc DeleteLink(orig *Link, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteTraceID(&orig.TraceId, false)\n\tDeleteSpanID(&orig.SpanId, false)\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolLink.Put(orig)\n\t}\n}\n\nfunc CopyLink(dest, src *Link) *Link {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewLink()\n\t}\n\tCopyTraceID(&dest.TraceId, &src.TraceId)\n\n\tCopySpanID(&dest.SpanId, &src.SpanId)\n\n\treturn dest\n}\n\nfunc CopyLinkSlice(dest, src []Link) []Link {\n\tvar newDest []Link\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]Link, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteLink(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyLink(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyLinkPtrSlice(dest, src []*Link) []*Link {\n\tvar newDest []*Link\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*Link, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewLink()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteLink(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewLink()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyLink(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *Link) Reset() {\n\t*orig = Link{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *Link) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif !orig.TraceId.IsEmpty() {\n\t\tdest.WriteObjectField(\"traceId\")\n\t\torig.TraceId.MarshalJSON(dest)\n\t}\n\tif !orig.SpanId.IsEmpty() {\n\t\tdest.WriteObjectField(\"spanId\")\n\t\torig.SpanId.MarshalJSON(dest)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *Link) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"traceId\", \"trace_id\":\n\n\t\t\torig.TraceId.UnmarshalJSON(iter)\n\t\tcase \"spanId\", \"span_id\":\n\n\t\t\torig.SpanId.UnmarshalJSON(iter)\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *Link) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tl = orig.TraceId.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tl = orig.SpanId.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\treturn n\n}\n\nfunc (orig *Link) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = orig.TraceId.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0xa\n\n\tl = orig.SpanId.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x12\n\n\treturn len(buf) - pos\n}\n\nfunc (orig *Link) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TraceId\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.TraceId.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SpanId\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.SpanId.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestLink() *Link {\n\torig := NewLink()\n\torig.TraceId = *GenTestTraceID()\n\torig.SpanId = *GenTestSpanID()\n\treturn orig\n}\n\nfunc GenTestLinkPtrSlice() []*Link {\n\torig := make([]*Link, 5)\n\torig[0] = NewLink()\n\torig[1] = GenTestLink()\n\torig[2] = NewLink()\n\torig[3] = GenTestLink()\n\torig[4] = NewLink()\n\treturn orig\n}\n\nfunc GenTestLinkSlice() []Link {\n\torig := make([]Link, 5)\n\torig[1] = *GenTestLink()\n\torig[3] = *GenTestLink()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_link_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpprofiles \"go.opentelemetry.io/proto/slim/otlp/profiles/v1development\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyLink(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLink() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewLink()\n\t\t\t\tCopyLink(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyLink(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyLinkSlice(t *testing.T) {\n\tsrc := []Link{}\n\tdest := []Link{}\n\t// Test CopyTo empty\n\tdest = CopyLinkSlice(dest, src)\n\tassert.Equal(t, []Link{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestLinkSlice()\n\tdest = CopyLinkSlice(dest, src)\n\tassert.Equal(t, GenTestLinkSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyLinkSlice(dest, src)\n\tassert.Equal(t, GenTestLinkSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyLinkSlice(dest, []Link{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyLinkSlice(dest, src)\n\tassert.Equal(t, GenTestLinkSlice(), dest)\n}\n\nfunc TestCopyLinkPtrSlice(t *testing.T) {\n\tsrc := []*Link{}\n\tdest := []*Link{}\n\t// Test CopyTo empty\n\tdest = CopyLinkPtrSlice(dest, src)\n\tassert.Equal(t, []*Link{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestLinkPtrSlice()\n\tdest = CopyLinkPtrSlice(dest, src)\n\tassert.Equal(t, GenTestLinkPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyLinkPtrSlice(dest, src)\n\tassert.Equal(t, GenTestLinkPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyLinkPtrSlice(dest, []*Link{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyLinkPtrSlice(dest, src)\n\tassert.Equal(t, GenTestLinkPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONLinkUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewLink()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewLink(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONLink(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLink() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewLink()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteLink(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoLinkFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesLink() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewLink()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoLinkUnknown(t *testing.T) {\n\tdest := NewLink()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewLink(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoLink(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLink() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewLink()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteLink(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufLink(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLink() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpprofiles.Link{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewLink()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesLink() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":           {0x02},\n\t\t\"TraceId/wrong_wire_type\": {0xc},\n\t\t\"TraceId/missing_value\":   {0xa},\n\t\t\"SpanId/wrong_wire_type\":  {0x14},\n\t\t\"SpanId/missing_value\":    {0x12},\n\t}\n}\n\nfunc genTestEncodingValuesLink() map[string]*Link {\n\treturn map[string]*Link{\n\t\t\"empty\":        NewLink(),\n\t\t\"TraceId/test\": {TraceId: *GenTestTraceID()},\n\t\t\"SpanId/test\":  {SpanId: *GenTestSpanID()},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_location.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Location describes function and line table debug information.\ntype Location struct {\n\tLines            []*Line\n\tAttributeIndices []int32\n\tAddress          uint64\n\tMappingIndex     int32\n}\n\nvar (\n\tprotoPoolLocation = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Location{}\n\t\t},\n\t}\n)\n\nfunc NewLocation() *Location {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &Location{}\n\t}\n\treturn protoPoolLocation.Get().(*Location)\n}\n\nfunc DeleteLocation(orig *Location, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\tfor i := range orig.Lines {\n\t\tDeleteLine(orig.Lines[i], true)\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolLocation.Put(orig)\n\t}\n}\n\nfunc CopyLocation(dest, src *Location) *Location {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewLocation()\n\t}\n\tdest.MappingIndex = src.MappingIndex\n\tdest.Address = src.Address\n\tdest.Lines = CopyLinePtrSlice(dest.Lines, src.Lines)\n\n\tdest.AttributeIndices = append(dest.AttributeIndices[:0], src.AttributeIndices...)\n\n\treturn dest\n}\n\nfunc CopyLocationSlice(dest, src []Location) []Location {\n\tvar newDest []Location\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]Location, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteLocation(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyLocation(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyLocationPtrSlice(dest, src []*Location) []*Location {\n\tvar newDest []*Location\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*Location, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewLocation()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteLocation(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewLocation()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyLocation(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *Location) Reset() {\n\t*orig = Location{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *Location) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.MappingIndex != int32(0) {\n\t\tdest.WriteObjectField(\"mappingIndex\")\n\t\tdest.WriteInt32(orig.MappingIndex)\n\t}\n\tif orig.Address != uint64(0) {\n\t\tdest.WriteObjectField(\"address\")\n\t\tdest.WriteUint64(orig.Address)\n\t}\n\tif len(orig.Lines) > 0 {\n\t\tdest.WriteObjectField(\"lines\")\n\t\tdest.WriteArrayStart()\n\t\torig.Lines[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Lines); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Lines[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif len(orig.AttributeIndices) > 0 {\n\t\tdest.WriteObjectField(\"attributeIndices\")\n\t\tdest.WriteArrayStart()\n\t\tdest.WriteInt32(orig.AttributeIndices[0])\n\t\tfor i := 1; i < len(orig.AttributeIndices); i++ {\n\t\t\tdest.WriteMore()\n\t\t\tdest.WriteInt32(orig.AttributeIndices[i])\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *Location) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"mappingIndex\", \"mapping_index\":\n\t\t\torig.MappingIndex = iter.ReadInt32()\n\t\tcase \"address\":\n\t\t\torig.Address = iter.ReadUint64()\n\t\tcase \"lines\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Lines = append(orig.Lines, NewLine())\n\t\t\t\torig.Lines[len(orig.Lines)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"attributeIndices\", \"attribute_indices\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.AttributeIndices = append(orig.AttributeIndices, iter.ReadInt32())\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *Location) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.MappingIndex != int32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.MappingIndex))\n\t}\n\tif orig.Address != uint64(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.Address))\n\t}\n\tfor i := range orig.Lines {\n\t\tl = orig.Lines[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\n\tif len(orig.AttributeIndices) > 0 {\n\t\tl = 0\n\t\tfor _, e := range orig.AttributeIndices {\n\t\t\tl += proto.Sov(uint64(e))\n\t\t}\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *Location) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.MappingIndex != int32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.MappingIndex))\n\t\tpos--\n\t\tbuf[pos] = 0x8\n\t}\n\tif orig.Address != uint64(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.Address))\n\t\tpos--\n\t\tbuf[pos] = 0x10\n\t}\n\tfor i := len(orig.Lines) - 1; i >= 0; i-- {\n\t\tl = orig.Lines[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\tl = len(orig.AttributeIndices)\n\tif l > 0 {\n\t\tendPos := pos\n\t\tfor i := l - 1; i >= 0; i-- {\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.AttributeIndices[i]))\n\t\t}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(endPos-pos))\n\t\tpos--\n\t\tbuf[pos] = 0x22\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *Location) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field MappingIndex\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.MappingIndex = int32(num)\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Address\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Address = uint64(num)\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Lines\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Lines = append(orig.Lines, NewLine())\n\t\t\terr = orig.Lines[len(orig.Lines)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tcase 4:\n\t\t\tswitch wireType {\n\t\t\tcase proto.WireTypeLen:\n\t\t\t\tvar length int\n\t\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tstartPos := pos - length\n\t\t\t\tvar num uint64\n\t\t\t\tfor startPos < pos {\n\t\t\t\t\tnum, startPos, err = proto.ConsumeVarint(buf[:pos], startPos)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\torig.AttributeIndices = append(orig.AttributeIndices, int32(num))\n\t\t\t\t}\n\t\t\t\tif startPos != pos {\n\t\t\t\t\treturn fmt.Errorf(\"proto: invalid field len = %d for field AttributeIndices\", pos-startPos)\n\t\t\t\t}\n\t\t\tcase proto.WireTypeVarint:\n\t\t\t\tvar num uint64\n\t\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\torig.AttributeIndices = append(orig.AttributeIndices, int32(num))\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field AttributeIndices\", wireType)\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestLocation() *Location {\n\torig := NewLocation()\n\torig.MappingIndex = int32(13)\n\torig.Address = uint64(13)\n\torig.Lines = []*Line{{}, GenTestLine()}\n\torig.AttributeIndices = []int32{int32(0), int32(13)}\n\treturn orig\n}\n\nfunc GenTestLocationPtrSlice() []*Location {\n\torig := make([]*Location, 5)\n\torig[0] = NewLocation()\n\torig[1] = GenTestLocation()\n\torig[2] = NewLocation()\n\torig[3] = GenTestLocation()\n\torig[4] = NewLocation()\n\treturn orig\n}\n\nfunc GenTestLocationSlice() []Location {\n\torig := make([]Location, 5)\n\torig[1] = *GenTestLocation()\n\torig[3] = *GenTestLocation()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_location_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpprofiles \"go.opentelemetry.io/proto/slim/otlp/profiles/v1development\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyLocation(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLocation() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewLocation()\n\t\t\t\tCopyLocation(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyLocation(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyLocationSlice(t *testing.T) {\n\tsrc := []Location{}\n\tdest := []Location{}\n\t// Test CopyTo empty\n\tdest = CopyLocationSlice(dest, src)\n\tassert.Equal(t, []Location{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestLocationSlice()\n\tdest = CopyLocationSlice(dest, src)\n\tassert.Equal(t, GenTestLocationSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyLocationSlice(dest, src)\n\tassert.Equal(t, GenTestLocationSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyLocationSlice(dest, []Location{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyLocationSlice(dest, src)\n\tassert.Equal(t, GenTestLocationSlice(), dest)\n}\n\nfunc TestCopyLocationPtrSlice(t *testing.T) {\n\tsrc := []*Location{}\n\tdest := []*Location{}\n\t// Test CopyTo empty\n\tdest = CopyLocationPtrSlice(dest, src)\n\tassert.Equal(t, []*Location{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestLocationPtrSlice()\n\tdest = CopyLocationPtrSlice(dest, src)\n\tassert.Equal(t, GenTestLocationPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyLocationPtrSlice(dest, src)\n\tassert.Equal(t, GenTestLocationPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyLocationPtrSlice(dest, []*Location{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyLocationPtrSlice(dest, src)\n\tassert.Equal(t, GenTestLocationPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONLocationUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewLocation()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewLocation(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONLocation(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLocation() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewLocation()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteLocation(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoLocationFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesLocation() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewLocation()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoLocationUnknown(t *testing.T) {\n\tdest := NewLocation()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewLocation(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoLocation(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLocation() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewLocation()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteLocation(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufLocation(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLocation() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpprofiles.Location{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewLocation()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesLocation() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                    {0x02},\n\t\t\"MappingIndex/wrong_wire_type\":     {0xc},\n\t\t\"MappingIndex/missing_value\":       {0x8},\n\t\t\"Address/wrong_wire_type\":          {0x14},\n\t\t\"Address/missing_value\":            {0x10},\n\t\t\"Lines/wrong_wire_type\":            {0x1c},\n\t\t\"Lines/missing_value\":              {0x1a},\n\t\t\"AttributeIndices/wrong_wire_type\": {0x24},\n\t\t\"AttributeIndices/missing_value\":   {0x22},\n\t}\n}\n\nfunc genTestEncodingValuesLocation() map[string]*Location {\n\treturn map[string]*Location{\n\t\t\"empty\":                 NewLocation(),\n\t\t\"MappingIndex/test\":     {MappingIndex: int32(13)},\n\t\t\"Address/test\":          {Address: uint64(13)},\n\t\t\"Lines/test\":            {Lines: []*Line{{}, GenTestLine()}},\n\t\t\"AttributeIndices/test\": {AttributeIndices: []int32{int32(0), int32(13)}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_logrecord.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// LogRecord are experimental implementation of OpenTelemetry Log Data Model.\n\ntype LogRecord struct {\n\tBody                   AnyValue\n\tSeverityText           string\n\tEventName              string\n\tAttributes             []KeyValue\n\tTimeUnixNano           uint64\n\tObservedTimeUnixNano   uint64\n\tSeverityNumber         SeverityNumber\n\tDroppedAttributesCount uint32\n\tFlags                  uint32\n\tTraceId                TraceID\n\tSpanId                 SpanID\n}\n\nvar (\n\tprotoPoolLogRecord = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &LogRecord{}\n\t\t},\n\t}\n)\n\nfunc NewLogRecord() *LogRecord {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &LogRecord{}\n\t}\n\treturn protoPoolLogRecord.Get().(*LogRecord)\n}\n\nfunc DeleteLogRecord(orig *LogRecord, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\tDeleteAnyValue(&orig.Body, false)\n\tfor i := range orig.Attributes {\n\t\tDeleteKeyValue(&orig.Attributes[i], false)\n\t}\n\n\tDeleteTraceID(&orig.TraceId, false)\n\tDeleteSpanID(&orig.SpanId, false)\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolLogRecord.Put(orig)\n\t}\n}\n\nfunc CopyLogRecord(dest, src *LogRecord) *LogRecord {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewLogRecord()\n\t}\n\tdest.TimeUnixNano = src.TimeUnixNano\n\tdest.ObservedTimeUnixNano = src.ObservedTimeUnixNano\n\tdest.SeverityNumber = src.SeverityNumber\n\tdest.SeverityText = src.SeverityText\n\tCopyAnyValue(&dest.Body, &src.Body)\n\n\tdest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)\n\n\tdest.DroppedAttributesCount = src.DroppedAttributesCount\n\tdest.Flags = src.Flags\n\tCopyTraceID(&dest.TraceId, &src.TraceId)\n\n\tCopySpanID(&dest.SpanId, &src.SpanId)\n\n\tdest.EventName = src.EventName\n\n\treturn dest\n}\n\nfunc CopyLogRecordSlice(dest, src []LogRecord) []LogRecord {\n\tvar newDest []LogRecord\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]LogRecord, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteLogRecord(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyLogRecord(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyLogRecordPtrSlice(dest, src []*LogRecord) []*LogRecord {\n\tvar newDest []*LogRecord\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*LogRecord, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewLogRecord()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteLogRecord(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewLogRecord()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyLogRecord(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *LogRecord) Reset() {\n\t*orig = LogRecord{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *LogRecord) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tdest.WriteObjectField(\"timeUnixNano\")\n\t\tdest.WriteUint64(orig.TimeUnixNano)\n\t}\n\tif orig.ObservedTimeUnixNano != uint64(0) {\n\t\tdest.WriteObjectField(\"observedTimeUnixNano\")\n\t\tdest.WriteUint64(orig.ObservedTimeUnixNano)\n\t}\n\n\tif int32(orig.SeverityNumber) != 0 {\n\t\tdest.WriteObjectField(\"severityNumber\")\n\t\tdest.WriteInt32(int32(orig.SeverityNumber))\n\t}\n\tif orig.SeverityText != \"\" {\n\t\tdest.WriteObjectField(\"severityText\")\n\t\tdest.WriteString(orig.SeverityText)\n\t}\n\tdest.WriteObjectField(\"body\")\n\torig.Body.MarshalJSON(dest)\n\tif len(orig.Attributes) > 0 {\n\t\tdest.WriteObjectField(\"attributes\")\n\t\tdest.WriteArrayStart()\n\t\torig.Attributes[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Attributes); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Attributes[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tdest.WriteObjectField(\"droppedAttributesCount\")\n\t\tdest.WriteUint32(orig.DroppedAttributesCount)\n\t}\n\tif orig.Flags != uint32(0) {\n\t\tdest.WriteObjectField(\"flags\")\n\t\tdest.WriteUint32(orig.Flags)\n\t}\n\tif !orig.TraceId.IsEmpty() {\n\t\tdest.WriteObjectField(\"traceId\")\n\t\torig.TraceId.MarshalJSON(dest)\n\t}\n\tif !orig.SpanId.IsEmpty() {\n\t\tdest.WriteObjectField(\"spanId\")\n\t\torig.SpanId.MarshalJSON(dest)\n\t}\n\tif orig.EventName != \"\" {\n\t\tdest.WriteObjectField(\"eventName\")\n\t\tdest.WriteString(orig.EventName)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *LogRecord) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"timeUnixNano\", \"time_unix_nano\":\n\t\t\torig.TimeUnixNano = iter.ReadUint64()\n\t\tcase \"observedTimeUnixNano\", \"observed_time_unix_nano\":\n\t\t\torig.ObservedTimeUnixNano = iter.ReadUint64()\n\t\tcase \"severityNumber\", \"severity_number\":\n\t\t\torig.SeverityNumber = SeverityNumber(iter.ReadEnumValue(SeverityNumber_value))\n\t\tcase \"severityText\", \"severity_text\":\n\t\t\torig.SeverityText = iter.ReadString()\n\t\tcase \"body\":\n\n\t\t\torig.Body.UnmarshalJSON(iter)\n\t\tcase \"attributes\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\t\torig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"droppedAttributesCount\", \"dropped_attributes_count\":\n\t\t\torig.DroppedAttributesCount = iter.ReadUint32()\n\t\tcase \"flags\":\n\t\t\torig.Flags = iter.ReadUint32()\n\t\tcase \"traceId\", \"trace_id\":\n\n\t\t\torig.TraceId.UnmarshalJSON(iter)\n\t\tcase \"spanId\", \"span_id\":\n\n\t\t\torig.SpanId.UnmarshalJSON(iter)\n\t\tcase \"eventName\", \"event_name\":\n\t\t\torig.EventName = iter.ReadString()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *LogRecord) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tn += 9\n\t}\n\tif orig.ObservedTimeUnixNano != uint64(0) {\n\t\tn += 9\n\t}\n\tif orig.SeverityNumber != SeverityNumber(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.SeverityNumber))\n\t}\n\n\tl = len(orig.SeverityText)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tl = orig.Body.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tfor i := range orig.Attributes {\n\t\tl = orig.Attributes[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.DroppedAttributesCount))\n\t}\n\tif orig.Flags != uint32(0) {\n\t\tn += 5\n\t}\n\tl = orig.TraceId.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tl = orig.SpanId.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\n\tl = len(orig.EventName)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *LogRecord) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimeUnixNano))\n\t\tpos--\n\t\tbuf[pos] = 0x9\n\t}\n\tif orig.ObservedTimeUnixNano != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.ObservedTimeUnixNano))\n\t\tpos--\n\t\tbuf[pos] = 0x59\n\t}\n\tif orig.SeverityNumber != SeverityNumber(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.SeverityNumber))\n\t\tpos--\n\t\tbuf[pos] = 0x10\n\t}\n\tl = len(orig.SeverityText)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.SeverityText)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\tl = orig.Body.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x2a\n\n\tfor i := len(orig.Attributes) - 1; i >= 0; i-- {\n\t\tl = orig.Attributes[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x32\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedAttributesCount))\n\t\tpos--\n\t\tbuf[pos] = 0x38\n\t}\n\tif orig.Flags != uint32(0) {\n\t\tpos -= 4\n\t\tbinary.LittleEndian.PutUint32(buf[pos:], uint32(orig.Flags))\n\t\tpos--\n\t\tbuf[pos] = 0x45\n\t}\n\tl = orig.TraceId.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x4a\n\n\tl = orig.SpanId.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x52\n\n\tl = len(orig.EventName)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.EventName)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x62\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *LogRecord) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TimeUnixNano\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.TimeUnixNano = uint64(num)\n\n\t\tcase 11:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ObservedTimeUnixNano\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.ObservedTimeUnixNano = uint64(num)\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SeverityNumber\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.SeverityNumber = SeverityNumber(num)\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SeverityText\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.SeverityText = string(buf[startPos:pos])\n\n\t\tcase 5:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Body\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.Body.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 6:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Attributes\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\terr = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 7:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DroppedAttributesCount\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.DroppedAttributesCount = uint32(num)\n\n\t\tcase 8:\n\t\t\tif wireType != proto.WireTypeI32 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Flags\", wireType)\n\t\t\t}\n\t\t\tvar num uint32\n\t\t\tnum, pos, err = proto.ConsumeI32(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.Flags = uint32(num)\n\n\t\tcase 9:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TraceId\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.TraceId.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 10:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SpanId\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.SpanId.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 12:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field EventName\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.EventName = string(buf[startPos:pos])\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestLogRecord() *LogRecord {\n\torig := NewLogRecord()\n\torig.TimeUnixNano = uint64(13)\n\torig.ObservedTimeUnixNano = uint64(13)\n\torig.SeverityNumber = SeverityNumber(13)\n\torig.SeverityText = \"test_severitytext\"\n\torig.Body = *GenTestAnyValue()\n\torig.Attributes = []KeyValue{{}, *GenTestKeyValue()}\n\torig.DroppedAttributesCount = uint32(13)\n\torig.Flags = uint32(13)\n\torig.TraceId = *GenTestTraceID()\n\torig.SpanId = *GenTestSpanID()\n\torig.EventName = \"test_eventname\"\n\treturn orig\n}\n\nfunc GenTestLogRecordPtrSlice() []*LogRecord {\n\torig := make([]*LogRecord, 5)\n\torig[0] = NewLogRecord()\n\torig[1] = GenTestLogRecord()\n\torig[2] = NewLogRecord()\n\torig[3] = GenTestLogRecord()\n\torig[4] = NewLogRecord()\n\treturn orig\n}\n\nfunc GenTestLogRecordSlice() []LogRecord {\n\torig := make([]LogRecord, 5)\n\torig[1] = *GenTestLogRecord()\n\torig[3] = *GenTestLogRecord()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_logrecord_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlplogs \"go.opentelemetry.io/proto/slim/otlp/logs/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyLogRecord(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLogRecord() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewLogRecord()\n\t\t\t\tCopyLogRecord(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyLogRecord(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyLogRecordSlice(t *testing.T) {\n\tsrc := []LogRecord{}\n\tdest := []LogRecord{}\n\t// Test CopyTo empty\n\tdest = CopyLogRecordSlice(dest, src)\n\tassert.Equal(t, []LogRecord{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestLogRecordSlice()\n\tdest = CopyLogRecordSlice(dest, src)\n\tassert.Equal(t, GenTestLogRecordSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyLogRecordSlice(dest, src)\n\tassert.Equal(t, GenTestLogRecordSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyLogRecordSlice(dest, []LogRecord{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyLogRecordSlice(dest, src)\n\tassert.Equal(t, GenTestLogRecordSlice(), dest)\n}\n\nfunc TestCopyLogRecordPtrSlice(t *testing.T) {\n\tsrc := []*LogRecord{}\n\tdest := []*LogRecord{}\n\t// Test CopyTo empty\n\tdest = CopyLogRecordPtrSlice(dest, src)\n\tassert.Equal(t, []*LogRecord{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestLogRecordPtrSlice()\n\tdest = CopyLogRecordPtrSlice(dest, src)\n\tassert.Equal(t, GenTestLogRecordPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyLogRecordPtrSlice(dest, src)\n\tassert.Equal(t, GenTestLogRecordPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyLogRecordPtrSlice(dest, []*LogRecord{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyLogRecordPtrSlice(dest, src)\n\tassert.Equal(t, GenTestLogRecordPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONLogRecordUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewLogRecord()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewLogRecord(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONLogRecord(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLogRecord() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewLogRecord()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteLogRecord(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoLogRecordFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesLogRecord() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewLogRecord()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoLogRecordUnknown(t *testing.T) {\n\tdest := NewLogRecord()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewLogRecord(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoLogRecord(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLogRecord() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewLogRecord()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteLogRecord(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufLogRecord(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLogRecord() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlplogs.LogRecord{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewLogRecord()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesLogRecord() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                          {0x02},\n\t\t\"TimeUnixNano/wrong_wire_type\":           {0xc},\n\t\t\"TimeUnixNano/missing_value\":             {0x9},\n\t\t\"ObservedTimeUnixNano/wrong_wire_type\":   {0x5c},\n\t\t\"ObservedTimeUnixNano/missing_value\":     {0x59},\n\t\t\"SeverityNumber/wrong_wire_type\":         {0x14},\n\t\t\"SeverityNumber/missing_value\":           {0x10},\n\t\t\"SeverityText/wrong_wire_type\":           {0x1c},\n\t\t\"SeverityText/missing_value\":             {0x1a},\n\t\t\"Body/wrong_wire_type\":                   {0x2c},\n\t\t\"Body/missing_value\":                     {0x2a},\n\t\t\"Attributes/wrong_wire_type\":             {0x34},\n\t\t\"Attributes/missing_value\":               {0x32},\n\t\t\"DroppedAttributesCount/wrong_wire_type\": {0x3c},\n\t\t\"DroppedAttributesCount/missing_value\":   {0x38},\n\t\t\"Flags/wrong_wire_type\":                  {0x44},\n\t\t\"Flags/missing_value\":                    {0x45},\n\t\t\"TraceId/wrong_wire_type\":                {0x4c},\n\t\t\"TraceId/missing_value\":                  {0x4a},\n\t\t\"SpanId/wrong_wire_type\":                 {0x54},\n\t\t\"SpanId/missing_value\":                   {0x52},\n\t\t\"EventName/wrong_wire_type\":              {0x64},\n\t\t\"EventName/missing_value\":                {0x62},\n\t}\n}\n\nfunc genTestEncodingValuesLogRecord() map[string]*LogRecord {\n\treturn map[string]*LogRecord{\n\t\t\"empty\":                       NewLogRecord(),\n\t\t\"TimeUnixNano/test\":           {TimeUnixNano: uint64(13)},\n\t\t\"ObservedTimeUnixNano/test\":   {ObservedTimeUnixNano: uint64(13)},\n\t\t\"SeverityNumber/test\":         {SeverityNumber: SeverityNumber(13)},\n\t\t\"SeverityText/test\":           {SeverityText: \"test_severitytext\"},\n\t\t\"Body/test\":                   {Body: *GenTestAnyValue()},\n\t\t\"Attributes/test\":             {Attributes: []KeyValue{{}, *GenTestKeyValue()}},\n\t\t\"DroppedAttributesCount/test\": {DroppedAttributesCount: uint32(13)},\n\t\t\"Flags/test\":                  {Flags: uint32(13)},\n\t\t\"TraceId/test\":                {TraceId: *GenTestTraceID()},\n\t\t\"SpanId/test\":                 {SpanId: *GenTestSpanID()},\n\t\t\"EventName/test\":              {EventName: \"test_eventname\"},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_logsdata.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// LogsData represents the logs data that can be stored in a persistent storage,\n// OR can be embedded by other protocols that transfer OTLP logs data but do not\n// implement the OTLP protocol.\ntype LogsData struct {\n\tResourceLogs []*ResourceLogs\n}\n\nvar (\n\tprotoPoolLogsData = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &LogsData{}\n\t\t},\n\t}\n)\n\nfunc NewLogsData() *LogsData {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &LogsData{}\n\t}\n\treturn protoPoolLogsData.Get().(*LogsData)\n}\n\nfunc DeleteLogsData(orig *LogsData, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.ResourceLogs {\n\t\tDeleteResourceLogs(orig.ResourceLogs[i], true)\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolLogsData.Put(orig)\n\t}\n}\n\nfunc CopyLogsData(dest, src *LogsData) *LogsData {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewLogsData()\n\t}\n\tdest.ResourceLogs = CopyResourceLogsPtrSlice(dest.ResourceLogs, src.ResourceLogs)\n\n\treturn dest\n}\n\nfunc CopyLogsDataSlice(dest, src []LogsData) []LogsData {\n\tvar newDest []LogsData\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]LogsData, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteLogsData(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyLogsData(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyLogsDataPtrSlice(dest, src []*LogsData) []*LogsData {\n\tvar newDest []*LogsData\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*LogsData, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewLogsData()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteLogsData(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewLogsData()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyLogsData(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *LogsData) Reset() {\n\t*orig = LogsData{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *LogsData) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.ResourceLogs) > 0 {\n\t\tdest.WriteObjectField(\"resourceLogs\")\n\t\tdest.WriteArrayStart()\n\t\torig.ResourceLogs[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.ResourceLogs); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.ResourceLogs[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *LogsData) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"resourceLogs\", \"resource_logs\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.ResourceLogs = append(orig.ResourceLogs, NewResourceLogs())\n\t\t\t\torig.ResourceLogs[len(orig.ResourceLogs)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *LogsData) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.ResourceLogs {\n\t\tl = orig.ResourceLogs[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *LogsData) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.ResourceLogs) - 1; i >= 0; i-- {\n\t\tl = orig.ResourceLogs[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *LogsData) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ResourceLogs\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.ResourceLogs = append(orig.ResourceLogs, NewResourceLogs())\n\t\t\terr = orig.ResourceLogs[len(orig.ResourceLogs)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestLogsData() *LogsData {\n\torig := NewLogsData()\n\torig.ResourceLogs = []*ResourceLogs{{}, GenTestResourceLogs()}\n\treturn orig\n}\n\nfunc GenTestLogsDataPtrSlice() []*LogsData {\n\torig := make([]*LogsData, 5)\n\torig[0] = NewLogsData()\n\torig[1] = GenTestLogsData()\n\torig[2] = NewLogsData()\n\torig[3] = GenTestLogsData()\n\torig[4] = NewLogsData()\n\treturn orig\n}\n\nfunc GenTestLogsDataSlice() []LogsData {\n\torig := make([]LogsData, 5)\n\torig[1] = *GenTestLogsData()\n\torig[3] = *GenTestLogsData()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_logsdata_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlplogs \"go.opentelemetry.io/proto/slim/otlp/logs/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyLogsData(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLogsData() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewLogsData()\n\t\t\t\tCopyLogsData(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyLogsData(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyLogsDataSlice(t *testing.T) {\n\tsrc := []LogsData{}\n\tdest := []LogsData{}\n\t// Test CopyTo empty\n\tdest = CopyLogsDataSlice(dest, src)\n\tassert.Equal(t, []LogsData{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestLogsDataSlice()\n\tdest = CopyLogsDataSlice(dest, src)\n\tassert.Equal(t, GenTestLogsDataSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyLogsDataSlice(dest, src)\n\tassert.Equal(t, GenTestLogsDataSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyLogsDataSlice(dest, []LogsData{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyLogsDataSlice(dest, src)\n\tassert.Equal(t, GenTestLogsDataSlice(), dest)\n}\n\nfunc TestCopyLogsDataPtrSlice(t *testing.T) {\n\tsrc := []*LogsData{}\n\tdest := []*LogsData{}\n\t// Test CopyTo empty\n\tdest = CopyLogsDataPtrSlice(dest, src)\n\tassert.Equal(t, []*LogsData{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestLogsDataPtrSlice()\n\tdest = CopyLogsDataPtrSlice(dest, src)\n\tassert.Equal(t, GenTestLogsDataPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyLogsDataPtrSlice(dest, src)\n\tassert.Equal(t, GenTestLogsDataPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyLogsDataPtrSlice(dest, []*LogsData{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyLogsDataPtrSlice(dest, src)\n\tassert.Equal(t, GenTestLogsDataPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONLogsDataUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewLogsData()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewLogsData(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONLogsData(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLogsData() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewLogsData()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteLogsData(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoLogsDataFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesLogsData() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewLogsData()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoLogsDataUnknown(t *testing.T) {\n\tdest := NewLogsData()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewLogsData(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoLogsData(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLogsData() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewLogsData()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteLogsData(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufLogsData(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLogsData() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlplogs.LogsData{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewLogsData()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesLogsData() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                {0x02},\n\t\t\"ResourceLogs/wrong_wire_type\": {0xc},\n\t\t\"ResourceLogs/missing_value\":   {0xa},\n\t}\n}\n\nfunc genTestEncodingValuesLogsData() map[string]*LogsData {\n\treturn map[string]*LogsData{\n\t\t\"empty\":             NewLogsData(),\n\t\t\"ResourceLogs/test\": {ResourceLogs: []*ResourceLogs{{}, GenTestResourceLogs()}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_logsrequest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\ntype LogsRequest struct {\n\tRequestContext *RequestContext\n\tLogsData       LogsData\n\tFormatVersion  uint32\n}\n\nvar (\n\tprotoPoolLogsRequest = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &LogsRequest{}\n\t\t},\n\t}\n)\n\nfunc NewLogsRequest() *LogsRequest {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &LogsRequest{}\n\t}\n\treturn protoPoolLogsRequest.Get().(*LogsRequest)\n}\n\nfunc DeleteLogsRequest(orig *LogsRequest, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteRequestContext(orig.RequestContext, true)\n\tDeleteLogsData(&orig.LogsData, false)\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolLogsRequest.Put(orig)\n\t}\n}\n\nfunc CopyLogsRequest(dest, src *LogsRequest) *LogsRequest {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewLogsRequest()\n\t}\n\tdest.RequestContext = CopyRequestContext(dest.RequestContext, src.RequestContext)\n\n\tCopyLogsData(&dest.LogsData, &src.LogsData)\n\n\tdest.FormatVersion = src.FormatVersion\n\n\treturn dest\n}\n\nfunc CopyLogsRequestSlice(dest, src []LogsRequest) []LogsRequest {\n\tvar newDest []LogsRequest\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]LogsRequest, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteLogsRequest(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyLogsRequest(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyLogsRequestPtrSlice(dest, src []*LogsRequest) []*LogsRequest {\n\tvar newDest []*LogsRequest\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*LogsRequest, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewLogsRequest()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteLogsRequest(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewLogsRequest()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyLogsRequest(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *LogsRequest) Reset() {\n\t*orig = LogsRequest{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *LogsRequest) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.RequestContext != nil {\n\t\tdest.WriteObjectField(\"requestContext\")\n\t\torig.RequestContext.MarshalJSON(dest)\n\t}\n\tdest.WriteObjectField(\"logsData\")\n\torig.LogsData.MarshalJSON(dest)\n\tif orig.FormatVersion != uint32(0) {\n\t\tdest.WriteObjectField(\"formatVersion\")\n\t\tdest.WriteUint32(orig.FormatVersion)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *LogsRequest) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"requestContext\", \"request_context\":\n\t\t\torig.RequestContext = NewRequestContext()\n\t\t\torig.RequestContext.UnmarshalJSON(iter)\n\t\tcase \"logsData\", \"logs_data\":\n\n\t\t\torig.LogsData.UnmarshalJSON(iter)\n\t\tcase \"formatVersion\", \"format_version\":\n\t\t\torig.FormatVersion = iter.ReadUint32()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *LogsRequest) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.RequestContext != nil {\n\t\tl = orig.RequestContext.SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tl = orig.LogsData.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tif orig.FormatVersion != uint32(0) {\n\t\tn += 5\n\t}\n\treturn n\n}\n\nfunc (orig *LogsRequest) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.RequestContext != nil {\n\t\tl = orig.RequestContext.MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tl = orig.LogsData.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x1a\n\n\tif orig.FormatVersion != uint32(0) {\n\t\tpos -= 4\n\t\tbinary.LittleEndian.PutUint32(buf[pos:], uint32(orig.FormatVersion))\n\t\tpos--\n\t\tbuf[pos] = 0xd\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *LogsRequest) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field RequestContext\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\torig.RequestContext = NewRequestContext()\n\t\t\terr = orig.RequestContext.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field LogsData\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.LogsData.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeI32 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field FormatVersion\", wireType)\n\t\t\t}\n\t\t\tvar num uint32\n\t\t\tnum, pos, err = proto.ConsumeI32(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.FormatVersion = uint32(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestLogsRequest() *LogsRequest {\n\torig := NewLogsRequest()\n\torig.RequestContext = GenTestRequestContext()\n\torig.LogsData = *GenTestLogsData()\n\torig.FormatVersion = uint32(13)\n\treturn orig\n}\n\nfunc GenTestLogsRequestPtrSlice() []*LogsRequest {\n\torig := make([]*LogsRequest, 5)\n\torig[0] = NewLogsRequest()\n\torig[1] = GenTestLogsRequest()\n\torig[2] = NewLogsRequest()\n\torig[3] = GenTestLogsRequest()\n\torig[4] = NewLogsRequest()\n\treturn orig\n}\n\nfunc GenTestLogsRequestSlice() []LogsRequest {\n\torig := make([]LogsRequest, 5)\n\torig[1] = *GenTestLogsRequest()\n\torig[3] = *GenTestLogsRequest()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_logsrequest_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/protobuf/proto\"\n\t\"google.golang.org/protobuf/types/known/emptypb\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyLogsRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLogsRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewLogsRequest()\n\t\t\t\tCopyLogsRequest(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyLogsRequest(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyLogsRequestSlice(t *testing.T) {\n\tsrc := []LogsRequest{}\n\tdest := []LogsRequest{}\n\t// Test CopyTo empty\n\tdest = CopyLogsRequestSlice(dest, src)\n\tassert.Equal(t, []LogsRequest{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestLogsRequestSlice()\n\tdest = CopyLogsRequestSlice(dest, src)\n\tassert.Equal(t, GenTestLogsRequestSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyLogsRequestSlice(dest, src)\n\tassert.Equal(t, GenTestLogsRequestSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyLogsRequestSlice(dest, []LogsRequest{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyLogsRequestSlice(dest, src)\n\tassert.Equal(t, GenTestLogsRequestSlice(), dest)\n}\n\nfunc TestCopyLogsRequestPtrSlice(t *testing.T) {\n\tsrc := []*LogsRequest{}\n\tdest := []*LogsRequest{}\n\t// Test CopyTo empty\n\tdest = CopyLogsRequestPtrSlice(dest, src)\n\tassert.Equal(t, []*LogsRequest{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestLogsRequestPtrSlice()\n\tdest = CopyLogsRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestLogsRequestPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyLogsRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestLogsRequestPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyLogsRequestPtrSlice(dest, []*LogsRequest{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyLogsRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestLogsRequestPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONLogsRequestUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewLogsRequest()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewLogsRequest(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONLogsRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLogsRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewLogsRequest()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteLogsRequest(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoLogsRequestFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesLogsRequest() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewLogsRequest()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoLogsRequestUnknown(t *testing.T) {\n\tdest := NewLogsRequest()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewLogsRequest(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoLogsRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLogsRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewLogsRequest()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteLogsRequest(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufLogsRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesLogsRequest() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &emptypb.Empty{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewLogsRequest()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesLogsRequest() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                  {0x02},\n\t\t\"RequestContext/wrong_wire_type\": {0x14},\n\t\t\"RequestContext/missing_value\":   {0x12},\n\t\t\"LogsData/wrong_wire_type\":       {0x1c},\n\t\t\"LogsData/missing_value\":         {0x1a},\n\t\t\"FormatVersion/wrong_wire_type\":  {0xc},\n\t\t\"FormatVersion/missing_value\":    {0xd},\n\t}\n}\n\nfunc genTestEncodingValuesLogsRequest() map[string]*LogsRequest {\n\treturn map[string]*LogsRequest{\n\t\t\"empty\":               NewLogsRequest(),\n\t\t\"RequestContext/test\": {RequestContext: GenTestRequestContext()},\n\t\t\"LogsData/test\":       {LogsData: *GenTestLogsData()},\n\t\t\"FormatVersion/test\":  {FormatVersion: uint32(13)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_mapping.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Mapping describes the mapping of a binary in memory, including its address range, file offset, and metadata like build ID\ntype Mapping struct {\n\tAttributeIndices []int32\n\tMemoryStart      uint64\n\tMemoryLimit      uint64\n\tFileOffset       uint64\n\tFilenameStrindex int32\n}\n\nvar (\n\tprotoPoolMapping = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Mapping{}\n\t\t},\n\t}\n)\n\nfunc NewMapping() *Mapping {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &Mapping{}\n\t}\n\treturn protoPoolMapping.Get().(*Mapping)\n}\n\nfunc DeleteMapping(orig *Mapping, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolMapping.Put(orig)\n\t}\n}\n\nfunc CopyMapping(dest, src *Mapping) *Mapping {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewMapping()\n\t}\n\tdest.MemoryStart = src.MemoryStart\n\tdest.MemoryLimit = src.MemoryLimit\n\tdest.FileOffset = src.FileOffset\n\tdest.FilenameStrindex = src.FilenameStrindex\n\tdest.AttributeIndices = append(dest.AttributeIndices[:0], src.AttributeIndices...)\n\n\treturn dest\n}\n\nfunc CopyMappingSlice(dest, src []Mapping) []Mapping {\n\tvar newDest []Mapping\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]Mapping, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteMapping(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyMapping(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyMappingPtrSlice(dest, src []*Mapping) []*Mapping {\n\tvar newDest []*Mapping\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*Mapping, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewMapping()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteMapping(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewMapping()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyMapping(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *Mapping) Reset() {\n\t*orig = Mapping{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *Mapping) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.MemoryStart != uint64(0) {\n\t\tdest.WriteObjectField(\"memoryStart\")\n\t\tdest.WriteUint64(orig.MemoryStart)\n\t}\n\tif orig.MemoryLimit != uint64(0) {\n\t\tdest.WriteObjectField(\"memoryLimit\")\n\t\tdest.WriteUint64(orig.MemoryLimit)\n\t}\n\tif orig.FileOffset != uint64(0) {\n\t\tdest.WriteObjectField(\"fileOffset\")\n\t\tdest.WriteUint64(orig.FileOffset)\n\t}\n\tif orig.FilenameStrindex != int32(0) {\n\t\tdest.WriteObjectField(\"filenameStrindex\")\n\t\tdest.WriteInt32(orig.FilenameStrindex)\n\t}\n\tif len(orig.AttributeIndices) > 0 {\n\t\tdest.WriteObjectField(\"attributeIndices\")\n\t\tdest.WriteArrayStart()\n\t\tdest.WriteInt32(orig.AttributeIndices[0])\n\t\tfor i := 1; i < len(orig.AttributeIndices); i++ {\n\t\t\tdest.WriteMore()\n\t\t\tdest.WriteInt32(orig.AttributeIndices[i])\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *Mapping) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"memoryStart\", \"memory_start\":\n\t\t\torig.MemoryStart = iter.ReadUint64()\n\t\tcase \"memoryLimit\", \"memory_limit\":\n\t\t\torig.MemoryLimit = iter.ReadUint64()\n\t\tcase \"fileOffset\", \"file_offset\":\n\t\t\torig.FileOffset = iter.ReadUint64()\n\t\tcase \"filenameStrindex\", \"filename_strindex\":\n\t\t\torig.FilenameStrindex = iter.ReadInt32()\n\t\tcase \"attributeIndices\", \"attribute_indices\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.AttributeIndices = append(orig.AttributeIndices, iter.ReadInt32())\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *Mapping) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.MemoryStart != uint64(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.MemoryStart))\n\t}\n\tif orig.MemoryLimit != uint64(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.MemoryLimit))\n\t}\n\tif orig.FileOffset != uint64(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.FileOffset))\n\t}\n\tif orig.FilenameStrindex != int32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.FilenameStrindex))\n\t}\n\n\tif len(orig.AttributeIndices) > 0 {\n\t\tl = 0\n\t\tfor _, e := range orig.AttributeIndices {\n\t\t\tl += proto.Sov(uint64(e))\n\t\t}\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *Mapping) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.MemoryStart != uint64(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.MemoryStart))\n\t\tpos--\n\t\tbuf[pos] = 0x8\n\t}\n\tif orig.MemoryLimit != uint64(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.MemoryLimit))\n\t\tpos--\n\t\tbuf[pos] = 0x10\n\t}\n\tif orig.FileOffset != uint64(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.FileOffset))\n\t\tpos--\n\t\tbuf[pos] = 0x18\n\t}\n\tif orig.FilenameStrindex != int32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.FilenameStrindex))\n\t\tpos--\n\t\tbuf[pos] = 0x20\n\t}\n\tl = len(orig.AttributeIndices)\n\tif l > 0 {\n\t\tendPos := pos\n\t\tfor i := l - 1; i >= 0; i-- {\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.AttributeIndices[i]))\n\t\t}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(endPos-pos))\n\t\tpos--\n\t\tbuf[pos] = 0x2a\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *Mapping) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field MemoryStart\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.MemoryStart = uint64(num)\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field MemoryLimit\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.MemoryLimit = uint64(num)\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field FileOffset\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.FileOffset = uint64(num)\n\n\t\tcase 4:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field FilenameStrindex\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.FilenameStrindex = int32(num)\n\t\tcase 5:\n\t\t\tswitch wireType {\n\t\t\tcase proto.WireTypeLen:\n\t\t\t\tvar length int\n\t\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tstartPos := pos - length\n\t\t\t\tvar num uint64\n\t\t\t\tfor startPos < pos {\n\t\t\t\t\tnum, startPos, err = proto.ConsumeVarint(buf[:pos], startPos)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\torig.AttributeIndices = append(orig.AttributeIndices, int32(num))\n\t\t\t\t}\n\t\t\t\tif startPos != pos {\n\t\t\t\t\treturn fmt.Errorf(\"proto: invalid field len = %d for field AttributeIndices\", pos-startPos)\n\t\t\t\t}\n\t\t\tcase proto.WireTypeVarint:\n\t\t\t\tvar num uint64\n\t\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\torig.AttributeIndices = append(orig.AttributeIndices, int32(num))\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field AttributeIndices\", wireType)\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestMapping() *Mapping {\n\torig := NewMapping()\n\torig.MemoryStart = uint64(13)\n\torig.MemoryLimit = uint64(13)\n\torig.FileOffset = uint64(13)\n\torig.FilenameStrindex = int32(13)\n\torig.AttributeIndices = []int32{int32(0), int32(13)}\n\treturn orig\n}\n\nfunc GenTestMappingPtrSlice() []*Mapping {\n\torig := make([]*Mapping, 5)\n\torig[0] = NewMapping()\n\torig[1] = GenTestMapping()\n\torig[2] = NewMapping()\n\torig[3] = GenTestMapping()\n\torig[4] = NewMapping()\n\treturn orig\n}\n\nfunc GenTestMappingSlice() []Mapping {\n\torig := make([]Mapping, 5)\n\torig[1] = *GenTestMapping()\n\torig[3] = *GenTestMapping()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_mapping_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpprofiles \"go.opentelemetry.io/proto/slim/otlp/profiles/v1development\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyMapping(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesMapping() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewMapping()\n\t\t\t\tCopyMapping(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyMapping(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyMappingSlice(t *testing.T) {\n\tsrc := []Mapping{}\n\tdest := []Mapping{}\n\t// Test CopyTo empty\n\tdest = CopyMappingSlice(dest, src)\n\tassert.Equal(t, []Mapping{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestMappingSlice()\n\tdest = CopyMappingSlice(dest, src)\n\tassert.Equal(t, GenTestMappingSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyMappingSlice(dest, src)\n\tassert.Equal(t, GenTestMappingSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyMappingSlice(dest, []Mapping{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyMappingSlice(dest, src)\n\tassert.Equal(t, GenTestMappingSlice(), dest)\n}\n\nfunc TestCopyMappingPtrSlice(t *testing.T) {\n\tsrc := []*Mapping{}\n\tdest := []*Mapping{}\n\t// Test CopyTo empty\n\tdest = CopyMappingPtrSlice(dest, src)\n\tassert.Equal(t, []*Mapping{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestMappingPtrSlice()\n\tdest = CopyMappingPtrSlice(dest, src)\n\tassert.Equal(t, GenTestMappingPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyMappingPtrSlice(dest, src)\n\tassert.Equal(t, GenTestMappingPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyMappingPtrSlice(dest, []*Mapping{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyMappingPtrSlice(dest, src)\n\tassert.Equal(t, GenTestMappingPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONMappingUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewMapping()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewMapping(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONMapping(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesMapping() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewMapping()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteMapping(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoMappingFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesMapping() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewMapping()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoMappingUnknown(t *testing.T) {\n\tdest := NewMapping()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewMapping(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoMapping(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesMapping() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewMapping()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteMapping(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufMapping(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesMapping() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpprofiles.Mapping{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewMapping()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesMapping() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                    {0x02},\n\t\t\"MemoryStart/wrong_wire_type\":      {0xc},\n\t\t\"MemoryStart/missing_value\":        {0x8},\n\t\t\"MemoryLimit/wrong_wire_type\":      {0x14},\n\t\t\"MemoryLimit/missing_value\":        {0x10},\n\t\t\"FileOffset/wrong_wire_type\":       {0x1c},\n\t\t\"FileOffset/missing_value\":         {0x18},\n\t\t\"FilenameStrindex/wrong_wire_type\": {0x24},\n\t\t\"FilenameStrindex/missing_value\":   {0x20},\n\t\t\"AttributeIndices/wrong_wire_type\": {0x2c},\n\t\t\"AttributeIndices/missing_value\":   {0x2a},\n\t}\n}\n\nfunc genTestEncodingValuesMapping() map[string]*Mapping {\n\treturn map[string]*Mapping{\n\t\t\"empty\":                 NewMapping(),\n\t\t\"MemoryStart/test\":      {MemoryStart: uint64(13)},\n\t\t\"MemoryLimit/test\":      {MemoryLimit: uint64(13)},\n\t\t\"FileOffset/test\":       {FileOffset: uint64(13)},\n\t\t\"FilenameStrindex/test\": {FilenameStrindex: int32(13)},\n\t\t\"AttributeIndices/test\": {AttributeIndices: []int32{int32(0), int32(13)}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_metric.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\nfunc (m *Metric) GetData() any {\n\tif m != nil {\n\t\treturn m.Data\n\t}\n\treturn nil\n}\n\ntype Metric_Gauge struct {\n\tGauge *Gauge\n}\n\nfunc (m *Metric) GetGauge() *Gauge {\n\tif v, ok := m.GetData().(*Metric_Gauge); ok {\n\t\treturn v.Gauge\n\t}\n\treturn nil\n}\n\ntype Metric_Sum struct {\n\tSum *Sum\n}\n\nfunc (m *Metric) GetSum() *Sum {\n\tif v, ok := m.GetData().(*Metric_Sum); ok {\n\t\treturn v.Sum\n\t}\n\treturn nil\n}\n\ntype Metric_Histogram struct {\n\tHistogram *Histogram\n}\n\nfunc (m *Metric) GetHistogram() *Histogram {\n\tif v, ok := m.GetData().(*Metric_Histogram); ok {\n\t\treturn v.Histogram\n\t}\n\treturn nil\n}\n\ntype Metric_ExponentialHistogram struct {\n\tExponentialHistogram *ExponentialHistogram\n}\n\nfunc (m *Metric) GetExponentialHistogram() *ExponentialHistogram {\n\tif v, ok := m.GetData().(*Metric_ExponentialHistogram); ok {\n\t\treturn v.ExponentialHistogram\n\t}\n\treturn nil\n}\n\ntype Metric_Summary struct {\n\tSummary *Summary\n}\n\nfunc (m *Metric) GetSummary() *Summary {\n\tif v, ok := m.GetData().(*Metric_Summary); ok {\n\t\treturn v.Summary\n\t}\n\treturn nil\n}\n\n// Metric represents one metric as a collection of datapoints.\n// See Metric definition in OTLP: https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/metrics/v1/metrics.proto\ntype Metric struct {\n\tName        string\n\tDescription string\n\tUnit        string\n\tData        any\n\tMetadata    []KeyValue\n}\n\nvar (\n\tprotoPoolMetric = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Metric{}\n\t\t},\n\t}\n\n\tProtoPoolMetric_Gauge = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Metric_Gauge{}\n\t\t},\n\t}\n\n\tProtoPoolMetric_Sum = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Metric_Sum{}\n\t\t},\n\t}\n\n\tProtoPoolMetric_Histogram = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Metric_Histogram{}\n\t\t},\n\t}\n\n\tProtoPoolMetric_ExponentialHistogram = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Metric_ExponentialHistogram{}\n\t\t},\n\t}\n\n\tProtoPoolMetric_Summary = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Metric_Summary{}\n\t\t},\n\t}\n)\n\nfunc NewMetric() *Metric {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &Metric{}\n\t}\n\treturn protoPoolMetric.Get().(*Metric)\n}\n\nfunc DeleteMetric(orig *Metric, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\tswitch ov := orig.Data.(type) {\n\tcase *Metric_Gauge:\n\t\tDeleteGauge(ov.Gauge, true)\n\t\tov.Gauge = nil\n\t\tProtoPoolMetric_Gauge.Put(ov)\n\tcase *Metric_Sum:\n\t\tDeleteSum(ov.Sum, true)\n\t\tov.Sum = nil\n\t\tProtoPoolMetric_Sum.Put(ov)\n\tcase *Metric_Histogram:\n\t\tDeleteHistogram(ov.Histogram, true)\n\t\tov.Histogram = nil\n\t\tProtoPoolMetric_Histogram.Put(ov)\n\tcase *Metric_ExponentialHistogram:\n\t\tDeleteExponentialHistogram(ov.ExponentialHistogram, true)\n\t\tov.ExponentialHistogram = nil\n\t\tProtoPoolMetric_ExponentialHistogram.Put(ov)\n\tcase *Metric_Summary:\n\t\tDeleteSummary(ov.Summary, true)\n\t\tov.Summary = nil\n\t\tProtoPoolMetric_Summary.Put(ov)\n\t}\n\tfor i := range orig.Metadata {\n\t\tDeleteKeyValue(&orig.Metadata[i], false)\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolMetric.Put(orig)\n\t}\n}\n\nfunc CopyMetric(dest, src *Metric) *Metric {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewMetric()\n\t}\n\tdest.Name = src.Name\n\tdest.Description = src.Description\n\tdest.Unit = src.Unit\n\tswitch t := src.Data.(type) {\n\tcase *Metric_Gauge:\n\t\tvar ov *Metric_Gauge\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &Metric_Gauge{}\n\t\t} else {\n\t\t\tov = ProtoPoolMetric_Gauge.Get().(*Metric_Gauge)\n\t\t}\n\t\tov.Gauge = NewGauge()\n\t\tCopyGauge(ov.Gauge, t.Gauge)\n\t\tdest.Data = ov\n\n\tcase *Metric_Sum:\n\t\tvar ov *Metric_Sum\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &Metric_Sum{}\n\t\t} else {\n\t\t\tov = ProtoPoolMetric_Sum.Get().(*Metric_Sum)\n\t\t}\n\t\tov.Sum = NewSum()\n\t\tCopySum(ov.Sum, t.Sum)\n\t\tdest.Data = ov\n\n\tcase *Metric_Histogram:\n\t\tvar ov *Metric_Histogram\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &Metric_Histogram{}\n\t\t} else {\n\t\t\tov = ProtoPoolMetric_Histogram.Get().(*Metric_Histogram)\n\t\t}\n\t\tov.Histogram = NewHistogram()\n\t\tCopyHistogram(ov.Histogram, t.Histogram)\n\t\tdest.Data = ov\n\n\tcase *Metric_ExponentialHistogram:\n\t\tvar ov *Metric_ExponentialHistogram\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &Metric_ExponentialHistogram{}\n\t\t} else {\n\t\t\tov = ProtoPoolMetric_ExponentialHistogram.Get().(*Metric_ExponentialHistogram)\n\t\t}\n\t\tov.ExponentialHistogram = NewExponentialHistogram()\n\t\tCopyExponentialHistogram(ov.ExponentialHistogram, t.ExponentialHistogram)\n\t\tdest.Data = ov\n\n\tcase *Metric_Summary:\n\t\tvar ov *Metric_Summary\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &Metric_Summary{}\n\t\t} else {\n\t\t\tov = ProtoPoolMetric_Summary.Get().(*Metric_Summary)\n\t\t}\n\t\tov.Summary = NewSummary()\n\t\tCopySummary(ov.Summary, t.Summary)\n\t\tdest.Data = ov\n\n\tdefault:\n\t\tdest.Data = nil\n\t}\n\tdest.Metadata = CopyKeyValueSlice(dest.Metadata, src.Metadata)\n\n\treturn dest\n}\n\nfunc CopyMetricSlice(dest, src []Metric) []Metric {\n\tvar newDest []Metric\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]Metric, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteMetric(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyMetric(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyMetricPtrSlice(dest, src []*Metric) []*Metric {\n\tvar newDest []*Metric\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*Metric, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewMetric()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteMetric(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewMetric()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyMetric(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *Metric) Reset() {\n\t*orig = Metric{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *Metric) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.Name != \"\" {\n\t\tdest.WriteObjectField(\"name\")\n\t\tdest.WriteString(orig.Name)\n\t}\n\tif orig.Description != \"\" {\n\t\tdest.WriteObjectField(\"description\")\n\t\tdest.WriteString(orig.Description)\n\t}\n\tif orig.Unit != \"\" {\n\t\tdest.WriteObjectField(\"unit\")\n\t\tdest.WriteString(orig.Unit)\n\t}\n\tswitch orig := orig.Data.(type) {\n\tcase *Metric_Gauge:\n\t\tif orig.Gauge != nil {\n\t\t\tdest.WriteObjectField(\"gauge\")\n\t\t\torig.Gauge.MarshalJSON(dest)\n\t\t}\n\tcase *Metric_Sum:\n\t\tif orig.Sum != nil {\n\t\t\tdest.WriteObjectField(\"sum\")\n\t\t\torig.Sum.MarshalJSON(dest)\n\t\t}\n\tcase *Metric_Histogram:\n\t\tif orig.Histogram != nil {\n\t\t\tdest.WriteObjectField(\"histogram\")\n\t\t\torig.Histogram.MarshalJSON(dest)\n\t\t}\n\tcase *Metric_ExponentialHistogram:\n\t\tif orig.ExponentialHistogram != nil {\n\t\t\tdest.WriteObjectField(\"exponentialHistogram\")\n\t\t\torig.ExponentialHistogram.MarshalJSON(dest)\n\t\t}\n\tcase *Metric_Summary:\n\t\tif orig.Summary != nil {\n\t\t\tdest.WriteObjectField(\"summary\")\n\t\t\torig.Summary.MarshalJSON(dest)\n\t\t}\n\t}\n\tif len(orig.Metadata) > 0 {\n\t\tdest.WriteObjectField(\"metadata\")\n\t\tdest.WriteArrayStart()\n\t\torig.Metadata[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Metadata); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Metadata[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *Metric) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"name\":\n\t\t\torig.Name = iter.ReadString()\n\t\tcase \"description\":\n\t\t\torig.Description = iter.ReadString()\n\t\tcase \"unit\":\n\t\t\torig.Unit = iter.ReadString()\n\n\t\tcase \"gauge\":\n\t\t\t{\n\t\t\t\tvar ov *Metric_Gauge\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &Metric_Gauge{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolMetric_Gauge.Get().(*Metric_Gauge)\n\t\t\t\t}\n\t\t\t\tov.Gauge = NewGauge()\n\t\t\t\tov.Gauge.UnmarshalJSON(iter)\n\t\t\t\torig.Data = ov\n\t\t\t}\n\t\tcase \"sum\":\n\t\t\t{\n\t\t\t\tvar ov *Metric_Sum\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &Metric_Sum{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolMetric_Sum.Get().(*Metric_Sum)\n\t\t\t\t}\n\t\t\t\tov.Sum = NewSum()\n\t\t\t\tov.Sum.UnmarshalJSON(iter)\n\t\t\t\torig.Data = ov\n\t\t\t}\n\t\tcase \"histogram\":\n\t\t\t{\n\t\t\t\tvar ov *Metric_Histogram\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &Metric_Histogram{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolMetric_Histogram.Get().(*Metric_Histogram)\n\t\t\t\t}\n\t\t\t\tov.Histogram = NewHistogram()\n\t\t\t\tov.Histogram.UnmarshalJSON(iter)\n\t\t\t\torig.Data = ov\n\t\t\t}\n\t\tcase \"exponentialHistogram\", \"exponential_histogram\":\n\t\t\t{\n\t\t\t\tvar ov *Metric_ExponentialHistogram\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &Metric_ExponentialHistogram{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolMetric_ExponentialHistogram.Get().(*Metric_ExponentialHistogram)\n\t\t\t\t}\n\t\t\t\tov.ExponentialHistogram = NewExponentialHistogram()\n\t\t\t\tov.ExponentialHistogram.UnmarshalJSON(iter)\n\t\t\t\torig.Data = ov\n\t\t\t}\n\t\tcase \"summary\":\n\t\t\t{\n\t\t\t\tvar ov *Metric_Summary\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &Metric_Summary{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolMetric_Summary.Get().(*Metric_Summary)\n\t\t\t\t}\n\t\t\t\tov.Summary = NewSummary()\n\t\t\t\tov.Summary.UnmarshalJSON(iter)\n\t\t\t\torig.Data = ov\n\t\t\t}\n\n\t\tcase \"metadata\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Metadata = append(orig.Metadata, KeyValue{})\n\t\t\t\torig.Metadata[len(orig.Metadata)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *Metric) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\n\tl = len(orig.Name)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\n\tl = len(orig.Description)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\n\tl = len(orig.Unit)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tswitch orig := orig.Data.(type) {\n\tcase nil:\n\t\t_ = orig\n\t\tbreak\n\tcase *Metric_Gauge:\n\t\tif orig.Gauge != nil {\n\t\t\tl = orig.Gauge.SizeProto()\n\t\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t\t}\n\tcase *Metric_Sum:\n\t\tif orig.Sum != nil {\n\t\t\tl = orig.Sum.SizeProto()\n\t\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t\t}\n\tcase *Metric_Histogram:\n\t\tif orig.Histogram != nil {\n\t\t\tl = orig.Histogram.SizeProto()\n\t\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t\t}\n\tcase *Metric_ExponentialHistogram:\n\t\tif orig.ExponentialHistogram != nil {\n\t\t\tl = orig.ExponentialHistogram.SizeProto()\n\t\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t\t}\n\tcase *Metric_Summary:\n\t\tif orig.Summary != nil {\n\t\t\tl = orig.Summary.SizeProto()\n\t\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t\t}\n\t}\n\tfor i := range orig.Metadata {\n\t\tl = orig.Metadata[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *Metric) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = len(orig.Name)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.Name)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\tl = len(orig.Description)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.Description)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tl = len(orig.Unit)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.Unit)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\tswitch orig := orig.Data.(type) {\n\tcase *Metric_Gauge:\n\t\tif orig.Gauge != nil {\n\t\t\tl = orig.Gauge.MarshalProto(buf[:pos])\n\t\t\tpos -= l\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\t\tpos--\n\t\t\tbuf[pos] = 0x2a\n\t\t}\n\tcase *Metric_Sum:\n\t\tif orig.Sum != nil {\n\t\t\tl = orig.Sum.MarshalProto(buf[:pos])\n\t\t\tpos -= l\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\t\tpos--\n\t\t\tbuf[pos] = 0x3a\n\t\t}\n\tcase *Metric_Histogram:\n\t\tif orig.Histogram != nil {\n\t\t\tl = orig.Histogram.MarshalProto(buf[:pos])\n\t\t\tpos -= l\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\t\tpos--\n\t\t\tbuf[pos] = 0x4a\n\t\t}\n\tcase *Metric_ExponentialHistogram:\n\t\tif orig.ExponentialHistogram != nil {\n\t\t\tl = orig.ExponentialHistogram.MarshalProto(buf[:pos])\n\t\t\tpos -= l\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\t\tpos--\n\t\t\tbuf[pos] = 0x52\n\t\t}\n\tcase *Metric_Summary:\n\t\tif orig.Summary != nil {\n\t\t\tl = orig.Summary.MarshalProto(buf[:pos])\n\t\t\tpos -= l\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\t\tpos--\n\t\t\tbuf[pos] = 0x5a\n\t\t}\n\t}\n\tfor i := len(orig.Metadata) - 1; i >= 0; i-- {\n\t\tl = orig.Metadata[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x62\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *Metric) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Name\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Name = string(buf[startPos:pos])\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Description\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Description = string(buf[startPos:pos])\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Unit\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Unit = string(buf[startPos:pos])\n\n\t\tcase 5:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Gauge\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tvar ov *Metric_Gauge\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &Metric_Gauge{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolMetric_Gauge.Get().(*Metric_Gauge)\n\t\t\t}\n\t\t\tov.Gauge = NewGauge()\n\t\t\terr = ov.Gauge.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Data = ov\n\n\t\tcase 7:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Sum\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tvar ov *Metric_Sum\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &Metric_Sum{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolMetric_Sum.Get().(*Metric_Sum)\n\t\t\t}\n\t\t\tov.Sum = NewSum()\n\t\t\terr = ov.Sum.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Data = ov\n\n\t\tcase 9:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Histogram\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tvar ov *Metric_Histogram\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &Metric_Histogram{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolMetric_Histogram.Get().(*Metric_Histogram)\n\t\t\t}\n\t\t\tov.Histogram = NewHistogram()\n\t\t\terr = ov.Histogram.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Data = ov\n\n\t\tcase 10:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ExponentialHistogram\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tvar ov *Metric_ExponentialHistogram\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &Metric_ExponentialHistogram{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolMetric_ExponentialHistogram.Get().(*Metric_ExponentialHistogram)\n\t\t\t}\n\t\t\tov.ExponentialHistogram = NewExponentialHistogram()\n\t\t\terr = ov.ExponentialHistogram.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Data = ov\n\n\t\tcase 11:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Summary\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tvar ov *Metric_Summary\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &Metric_Summary{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolMetric_Summary.Get().(*Metric_Summary)\n\t\t\t}\n\t\t\tov.Summary = NewSummary()\n\t\t\terr = ov.Summary.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Data = ov\n\n\t\tcase 12:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Metadata\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Metadata = append(orig.Metadata, KeyValue{})\n\t\t\terr = orig.Metadata[len(orig.Metadata)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestMetric() *Metric {\n\torig := NewMetric()\n\torig.Name = \"test_name\"\n\torig.Description = \"test_description\"\n\torig.Unit = \"test_unit\"\n\torig.Data = &Metric_Gauge{Gauge: GenTestGauge()}\n\torig.Metadata = []KeyValue{{}, *GenTestKeyValue()}\n\treturn orig\n}\n\nfunc GenTestMetricPtrSlice() []*Metric {\n\torig := make([]*Metric, 5)\n\torig[0] = NewMetric()\n\torig[1] = GenTestMetric()\n\torig[2] = NewMetric()\n\torig[3] = GenTestMetric()\n\torig[4] = NewMetric()\n\treturn orig\n}\n\nfunc GenTestMetricSlice() []Metric {\n\torig := make([]Metric, 5)\n\torig[1] = *GenTestMetric()\n\torig[3] = *GenTestMetric()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_metric_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyMetric(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesMetric() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewMetric()\n\t\t\t\tCopyMetric(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyMetric(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyMetricSlice(t *testing.T) {\n\tsrc := []Metric{}\n\tdest := []Metric{}\n\t// Test CopyTo empty\n\tdest = CopyMetricSlice(dest, src)\n\tassert.Equal(t, []Metric{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestMetricSlice()\n\tdest = CopyMetricSlice(dest, src)\n\tassert.Equal(t, GenTestMetricSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyMetricSlice(dest, src)\n\tassert.Equal(t, GenTestMetricSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyMetricSlice(dest, []Metric{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyMetricSlice(dest, src)\n\tassert.Equal(t, GenTestMetricSlice(), dest)\n}\n\nfunc TestCopyMetricPtrSlice(t *testing.T) {\n\tsrc := []*Metric{}\n\tdest := []*Metric{}\n\t// Test CopyTo empty\n\tdest = CopyMetricPtrSlice(dest, src)\n\tassert.Equal(t, []*Metric{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestMetricPtrSlice()\n\tdest = CopyMetricPtrSlice(dest, src)\n\tassert.Equal(t, GenTestMetricPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyMetricPtrSlice(dest, src)\n\tassert.Equal(t, GenTestMetricPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyMetricPtrSlice(dest, []*Metric{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyMetricPtrSlice(dest, src)\n\tassert.Equal(t, GenTestMetricPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONMetricUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewMetric()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewMetric(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONMetric(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesMetric() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewMetric()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteMetric(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoMetricFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesMetric() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewMetric()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoMetricUnknown(t *testing.T) {\n\tdest := NewMetric()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewMetric(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoMetric(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesMetric() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewMetric()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteMetric(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufMetric(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesMetric() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpmetrics.Metric{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewMetric()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesMetric() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":               {0x02},\n\t\t\"Name/wrong_wire_type\":        {0xc},\n\t\t\"Name/missing_value\":          {0xa},\n\t\t\"Description/wrong_wire_type\": {0x14},\n\t\t\"Description/missing_value\":   {0x12},\n\t\t\"Unit/wrong_wire_type\":        {0x1c},\n\t\t\"Unit/missing_value\":          {0x1a},\n\n\t\t\"Gauge/wrong_wire_type\":                {0x2c},\n\t\t\"Gauge/missing_value\":                  {0x2a},\n\t\t\"Sum/wrong_wire_type\":                  {0x3c},\n\t\t\"Sum/missing_value\":                    {0x3a},\n\t\t\"Histogram/wrong_wire_type\":            {0x4c},\n\t\t\"Histogram/missing_value\":              {0x4a},\n\t\t\"ExponentialHistogram/wrong_wire_type\": {0x54},\n\t\t\"ExponentialHistogram/missing_value\":   {0x52},\n\t\t\"Summary/wrong_wire_type\":              {0x5c},\n\t\t\"Summary/missing_value\":                {0x5a},\n\t\t\"Metadata/wrong_wire_type\":             {0x64},\n\t\t\"Metadata/missing_value\":               {0x62},\n\t}\n}\n\nfunc genTestEncodingValuesMetric() map[string]*Metric {\n\treturn map[string]*Metric{\n\t\t\"empty\":            NewMetric(),\n\t\t\"Name/test\":        {Name: \"test_name\"},\n\t\t\"Description/test\": {Description: \"test_description\"},\n\t\t\"Unit/test\":        {Unit: \"test_unit\"},\n\t\t\"Gauge/default\":    {Data: &Metric_Gauge{Gauge: &Gauge{}}},\n\t\t\"Gauge/test\":       {Data: &Metric_Gauge{Gauge: GenTestGauge()}}, \"Sum/default\": {Data: &Metric_Sum{Sum: &Sum{}}},\n\t\t\"Sum/test\": {Data: &Metric_Sum{Sum: GenTestSum()}}, \"Histogram/default\": {Data: &Metric_Histogram{Histogram: &Histogram{}}},\n\t\t\"Histogram/test\": {Data: &Metric_Histogram{Histogram: GenTestHistogram()}}, \"ExponentialHistogram/default\": {Data: &Metric_ExponentialHistogram{ExponentialHistogram: &ExponentialHistogram{}}},\n\t\t\"ExponentialHistogram/test\": {Data: &Metric_ExponentialHistogram{ExponentialHistogram: GenTestExponentialHistogram()}}, \"Summary/default\": {Data: &Metric_Summary{Summary: &Summary{}}},\n\t\t\"Summary/test\":  {Data: &Metric_Summary{Summary: GenTestSummary()}},\n\t\t\"Metadata/test\": {Metadata: []KeyValue{{}, *GenTestKeyValue()}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_metricsdata.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// MetricsData represents the metrics data that can be stored in a persistent storage,\n// OR can be embedded by other protocols that transfer OTLP metrics data but do not\n// implement the OTLP protocol..\ntype MetricsData struct {\n\tResourceMetrics []*ResourceMetrics\n}\n\nvar (\n\tprotoPoolMetricsData = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &MetricsData{}\n\t\t},\n\t}\n)\n\nfunc NewMetricsData() *MetricsData {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &MetricsData{}\n\t}\n\treturn protoPoolMetricsData.Get().(*MetricsData)\n}\n\nfunc DeleteMetricsData(orig *MetricsData, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.ResourceMetrics {\n\t\tDeleteResourceMetrics(orig.ResourceMetrics[i], true)\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolMetricsData.Put(orig)\n\t}\n}\n\nfunc CopyMetricsData(dest, src *MetricsData) *MetricsData {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewMetricsData()\n\t}\n\tdest.ResourceMetrics = CopyResourceMetricsPtrSlice(dest.ResourceMetrics, src.ResourceMetrics)\n\n\treturn dest\n}\n\nfunc CopyMetricsDataSlice(dest, src []MetricsData) []MetricsData {\n\tvar newDest []MetricsData\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]MetricsData, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteMetricsData(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyMetricsData(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyMetricsDataPtrSlice(dest, src []*MetricsData) []*MetricsData {\n\tvar newDest []*MetricsData\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*MetricsData, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewMetricsData()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteMetricsData(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewMetricsData()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyMetricsData(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *MetricsData) Reset() {\n\t*orig = MetricsData{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *MetricsData) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.ResourceMetrics) > 0 {\n\t\tdest.WriteObjectField(\"resourceMetrics\")\n\t\tdest.WriteArrayStart()\n\t\torig.ResourceMetrics[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.ResourceMetrics); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.ResourceMetrics[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *MetricsData) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"resourceMetrics\", \"resource_metrics\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.ResourceMetrics = append(orig.ResourceMetrics, NewResourceMetrics())\n\t\t\t\torig.ResourceMetrics[len(orig.ResourceMetrics)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *MetricsData) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.ResourceMetrics {\n\t\tl = orig.ResourceMetrics[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *MetricsData) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.ResourceMetrics) - 1; i >= 0; i-- {\n\t\tl = orig.ResourceMetrics[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *MetricsData) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ResourceMetrics\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.ResourceMetrics = append(orig.ResourceMetrics, NewResourceMetrics())\n\t\t\terr = orig.ResourceMetrics[len(orig.ResourceMetrics)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestMetricsData() *MetricsData {\n\torig := NewMetricsData()\n\torig.ResourceMetrics = []*ResourceMetrics{{}, GenTestResourceMetrics()}\n\treturn orig\n}\n\nfunc GenTestMetricsDataPtrSlice() []*MetricsData {\n\torig := make([]*MetricsData, 5)\n\torig[0] = NewMetricsData()\n\torig[1] = GenTestMetricsData()\n\torig[2] = NewMetricsData()\n\torig[3] = GenTestMetricsData()\n\torig[4] = NewMetricsData()\n\treturn orig\n}\n\nfunc GenTestMetricsDataSlice() []MetricsData {\n\torig := make([]MetricsData, 5)\n\torig[1] = *GenTestMetricsData()\n\torig[3] = *GenTestMetricsData()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_metricsdata_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyMetricsData(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesMetricsData() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewMetricsData()\n\t\t\t\tCopyMetricsData(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyMetricsData(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyMetricsDataSlice(t *testing.T) {\n\tsrc := []MetricsData{}\n\tdest := []MetricsData{}\n\t// Test CopyTo empty\n\tdest = CopyMetricsDataSlice(dest, src)\n\tassert.Equal(t, []MetricsData{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestMetricsDataSlice()\n\tdest = CopyMetricsDataSlice(dest, src)\n\tassert.Equal(t, GenTestMetricsDataSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyMetricsDataSlice(dest, src)\n\tassert.Equal(t, GenTestMetricsDataSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyMetricsDataSlice(dest, []MetricsData{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyMetricsDataSlice(dest, src)\n\tassert.Equal(t, GenTestMetricsDataSlice(), dest)\n}\n\nfunc TestCopyMetricsDataPtrSlice(t *testing.T) {\n\tsrc := []*MetricsData{}\n\tdest := []*MetricsData{}\n\t// Test CopyTo empty\n\tdest = CopyMetricsDataPtrSlice(dest, src)\n\tassert.Equal(t, []*MetricsData{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestMetricsDataPtrSlice()\n\tdest = CopyMetricsDataPtrSlice(dest, src)\n\tassert.Equal(t, GenTestMetricsDataPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyMetricsDataPtrSlice(dest, src)\n\tassert.Equal(t, GenTestMetricsDataPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyMetricsDataPtrSlice(dest, []*MetricsData{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyMetricsDataPtrSlice(dest, src)\n\tassert.Equal(t, GenTestMetricsDataPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONMetricsDataUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewMetricsData()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewMetricsData(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONMetricsData(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesMetricsData() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewMetricsData()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteMetricsData(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoMetricsDataFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesMetricsData() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewMetricsData()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoMetricsDataUnknown(t *testing.T) {\n\tdest := NewMetricsData()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewMetricsData(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoMetricsData(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesMetricsData() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewMetricsData()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteMetricsData(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufMetricsData(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesMetricsData() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpmetrics.MetricsData{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewMetricsData()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesMetricsData() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                   {0x02},\n\t\t\"ResourceMetrics/wrong_wire_type\": {0xc},\n\t\t\"ResourceMetrics/missing_value\":   {0xa},\n\t}\n}\n\nfunc genTestEncodingValuesMetricsData() map[string]*MetricsData {\n\treturn map[string]*MetricsData{\n\t\t\"empty\":                NewMetricsData(),\n\t\t\"ResourceMetrics/test\": {ResourceMetrics: []*ResourceMetrics{{}, GenTestResourceMetrics()}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_metricsrequest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\ntype MetricsRequest struct {\n\tRequestContext *RequestContext\n\tMetricsData    MetricsData\n\tFormatVersion  uint32\n}\n\nvar (\n\tprotoPoolMetricsRequest = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &MetricsRequest{}\n\t\t},\n\t}\n)\n\nfunc NewMetricsRequest() *MetricsRequest {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &MetricsRequest{}\n\t}\n\treturn protoPoolMetricsRequest.Get().(*MetricsRequest)\n}\n\nfunc DeleteMetricsRequest(orig *MetricsRequest, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteRequestContext(orig.RequestContext, true)\n\tDeleteMetricsData(&orig.MetricsData, false)\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolMetricsRequest.Put(orig)\n\t}\n}\n\nfunc CopyMetricsRequest(dest, src *MetricsRequest) *MetricsRequest {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewMetricsRequest()\n\t}\n\tdest.RequestContext = CopyRequestContext(dest.RequestContext, src.RequestContext)\n\n\tCopyMetricsData(&dest.MetricsData, &src.MetricsData)\n\n\tdest.FormatVersion = src.FormatVersion\n\n\treturn dest\n}\n\nfunc CopyMetricsRequestSlice(dest, src []MetricsRequest) []MetricsRequest {\n\tvar newDest []MetricsRequest\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]MetricsRequest, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteMetricsRequest(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyMetricsRequest(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyMetricsRequestPtrSlice(dest, src []*MetricsRequest) []*MetricsRequest {\n\tvar newDest []*MetricsRequest\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*MetricsRequest, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewMetricsRequest()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteMetricsRequest(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewMetricsRequest()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyMetricsRequest(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *MetricsRequest) Reset() {\n\t*orig = MetricsRequest{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *MetricsRequest) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.RequestContext != nil {\n\t\tdest.WriteObjectField(\"requestContext\")\n\t\torig.RequestContext.MarshalJSON(dest)\n\t}\n\tdest.WriteObjectField(\"metricsData\")\n\torig.MetricsData.MarshalJSON(dest)\n\tif orig.FormatVersion != uint32(0) {\n\t\tdest.WriteObjectField(\"formatVersion\")\n\t\tdest.WriteUint32(orig.FormatVersion)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *MetricsRequest) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"requestContext\", \"request_context\":\n\t\t\torig.RequestContext = NewRequestContext()\n\t\t\torig.RequestContext.UnmarshalJSON(iter)\n\t\tcase \"metricsData\", \"metrics_data\":\n\n\t\t\torig.MetricsData.UnmarshalJSON(iter)\n\t\tcase \"formatVersion\", \"format_version\":\n\t\t\torig.FormatVersion = iter.ReadUint32()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *MetricsRequest) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.RequestContext != nil {\n\t\tl = orig.RequestContext.SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tl = orig.MetricsData.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tif orig.FormatVersion != uint32(0) {\n\t\tn += 5\n\t}\n\treturn n\n}\n\nfunc (orig *MetricsRequest) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.RequestContext != nil {\n\t\tl = orig.RequestContext.MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tl = orig.MetricsData.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x1a\n\n\tif orig.FormatVersion != uint32(0) {\n\t\tpos -= 4\n\t\tbinary.LittleEndian.PutUint32(buf[pos:], uint32(orig.FormatVersion))\n\t\tpos--\n\t\tbuf[pos] = 0xd\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *MetricsRequest) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field RequestContext\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\torig.RequestContext = NewRequestContext()\n\t\t\terr = orig.RequestContext.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field MetricsData\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.MetricsData.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeI32 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field FormatVersion\", wireType)\n\t\t\t}\n\t\t\tvar num uint32\n\t\t\tnum, pos, err = proto.ConsumeI32(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.FormatVersion = uint32(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestMetricsRequest() *MetricsRequest {\n\torig := NewMetricsRequest()\n\torig.RequestContext = GenTestRequestContext()\n\torig.MetricsData = *GenTestMetricsData()\n\torig.FormatVersion = uint32(13)\n\treturn orig\n}\n\nfunc GenTestMetricsRequestPtrSlice() []*MetricsRequest {\n\torig := make([]*MetricsRequest, 5)\n\torig[0] = NewMetricsRequest()\n\torig[1] = GenTestMetricsRequest()\n\torig[2] = NewMetricsRequest()\n\torig[3] = GenTestMetricsRequest()\n\torig[4] = NewMetricsRequest()\n\treturn orig\n}\n\nfunc GenTestMetricsRequestSlice() []MetricsRequest {\n\torig := make([]MetricsRequest, 5)\n\torig[1] = *GenTestMetricsRequest()\n\torig[3] = *GenTestMetricsRequest()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_metricsrequest_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/protobuf/proto\"\n\t\"google.golang.org/protobuf/types/known/emptypb\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyMetricsRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesMetricsRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewMetricsRequest()\n\t\t\t\tCopyMetricsRequest(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyMetricsRequest(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyMetricsRequestSlice(t *testing.T) {\n\tsrc := []MetricsRequest{}\n\tdest := []MetricsRequest{}\n\t// Test CopyTo empty\n\tdest = CopyMetricsRequestSlice(dest, src)\n\tassert.Equal(t, []MetricsRequest{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestMetricsRequestSlice()\n\tdest = CopyMetricsRequestSlice(dest, src)\n\tassert.Equal(t, GenTestMetricsRequestSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyMetricsRequestSlice(dest, src)\n\tassert.Equal(t, GenTestMetricsRequestSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyMetricsRequestSlice(dest, []MetricsRequest{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyMetricsRequestSlice(dest, src)\n\tassert.Equal(t, GenTestMetricsRequestSlice(), dest)\n}\n\nfunc TestCopyMetricsRequestPtrSlice(t *testing.T) {\n\tsrc := []*MetricsRequest{}\n\tdest := []*MetricsRequest{}\n\t// Test CopyTo empty\n\tdest = CopyMetricsRequestPtrSlice(dest, src)\n\tassert.Equal(t, []*MetricsRequest{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestMetricsRequestPtrSlice()\n\tdest = CopyMetricsRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestMetricsRequestPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyMetricsRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestMetricsRequestPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyMetricsRequestPtrSlice(dest, []*MetricsRequest{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyMetricsRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestMetricsRequestPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONMetricsRequestUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewMetricsRequest()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewMetricsRequest(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONMetricsRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesMetricsRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewMetricsRequest()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteMetricsRequest(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoMetricsRequestFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesMetricsRequest() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewMetricsRequest()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoMetricsRequestUnknown(t *testing.T) {\n\tdest := NewMetricsRequest()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewMetricsRequest(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoMetricsRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesMetricsRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewMetricsRequest()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteMetricsRequest(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufMetricsRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesMetricsRequest() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &emptypb.Empty{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewMetricsRequest()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesMetricsRequest() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                  {0x02},\n\t\t\"RequestContext/wrong_wire_type\": {0x14},\n\t\t\"RequestContext/missing_value\":   {0x12},\n\t\t\"MetricsData/wrong_wire_type\":    {0x1c},\n\t\t\"MetricsData/missing_value\":      {0x1a},\n\t\t\"FormatVersion/wrong_wire_type\":  {0xc},\n\t\t\"FormatVersion/missing_value\":    {0xd},\n\t}\n}\n\nfunc genTestEncodingValuesMetricsRequest() map[string]*MetricsRequest {\n\treturn map[string]*MetricsRequest{\n\t\t\"empty\":               NewMetricsRequest(),\n\t\t\"RequestContext/test\": {RequestContext: GenTestRequestContext()},\n\t\t\"MetricsData/test\":    {MetricsData: *GenTestMetricsData()},\n\t\t\"FormatVersion/test\":  {FormatVersion: uint32(13)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_numberdatapoint.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"math\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\nfunc (m *NumberDataPoint) GetValue() any {\n\tif m != nil {\n\t\treturn m.Value\n\t}\n\treturn nil\n}\n\ntype NumberDataPoint_AsDouble struct {\n\tAsDouble float64\n}\n\nfunc (m *NumberDataPoint) GetAsDouble() float64 {\n\tif v, ok := m.GetValue().(*NumberDataPoint_AsDouble); ok {\n\t\treturn v.AsDouble\n\t}\n\treturn float64(0)\n}\n\ntype NumberDataPoint_AsInt struct {\n\tAsInt int64\n}\n\nfunc (m *NumberDataPoint) GetAsInt() int64 {\n\tif v, ok := m.GetValue().(*NumberDataPoint_AsInt); ok {\n\t\treturn v.AsInt\n\t}\n\treturn int64(0)\n}\n\n// NumberDataPoint is a single data point in a timeseries that describes the time-varying value of a number metric.\ntype NumberDataPoint struct {\n\tValue             any\n\tAttributes        []KeyValue\n\tExemplars         []Exemplar\n\tStartTimeUnixNano uint64\n\tTimeUnixNano      uint64\n\tFlags             uint32\n}\n\nvar (\n\tprotoPoolNumberDataPoint = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &NumberDataPoint{}\n\t\t},\n\t}\n\n\tProtoPoolNumberDataPoint_AsDouble = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &NumberDataPoint_AsDouble{}\n\t\t},\n\t}\n\n\tProtoPoolNumberDataPoint_AsInt = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &NumberDataPoint_AsInt{}\n\t\t},\n\t}\n)\n\nfunc NewNumberDataPoint() *NumberDataPoint {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &NumberDataPoint{}\n\t}\n\treturn protoPoolNumberDataPoint.Get().(*NumberDataPoint)\n}\n\nfunc DeleteNumberDataPoint(orig *NumberDataPoint, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.Attributes {\n\t\tDeleteKeyValue(&orig.Attributes[i], false)\n\t}\n\n\tswitch ov := orig.Value.(type) {\n\tcase *NumberDataPoint_AsDouble:\n\t\tif metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov.AsDouble = float64(0)\n\t\t\tProtoPoolNumberDataPoint_AsDouble.Put(ov)\n\t\t}\n\tcase *NumberDataPoint_AsInt:\n\t\tif metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov.AsInt = int64(0)\n\t\t\tProtoPoolNumberDataPoint_AsInt.Put(ov)\n\t\t}\n\t}\n\tfor i := range orig.Exemplars {\n\t\tDeleteExemplar(&orig.Exemplars[i], false)\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolNumberDataPoint.Put(orig)\n\t}\n}\n\nfunc CopyNumberDataPoint(dest, src *NumberDataPoint) *NumberDataPoint {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewNumberDataPoint()\n\t}\n\tdest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)\n\n\tdest.StartTimeUnixNano = src.StartTimeUnixNano\n\tdest.TimeUnixNano = src.TimeUnixNano\n\tswitch t := src.Value.(type) {\n\tcase *NumberDataPoint_AsDouble:\n\t\tvar ov *NumberDataPoint_AsDouble\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &NumberDataPoint_AsDouble{}\n\t\t} else {\n\t\t\tov = ProtoPoolNumberDataPoint_AsDouble.Get().(*NumberDataPoint_AsDouble)\n\t\t}\n\t\tov.AsDouble = t.AsDouble\n\t\tdest.Value = ov\n\n\tcase *NumberDataPoint_AsInt:\n\t\tvar ov *NumberDataPoint_AsInt\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &NumberDataPoint_AsInt{}\n\t\t} else {\n\t\t\tov = ProtoPoolNumberDataPoint_AsInt.Get().(*NumberDataPoint_AsInt)\n\t\t}\n\t\tov.AsInt = t.AsInt\n\t\tdest.Value = ov\n\n\tdefault:\n\t\tdest.Value = nil\n\t}\n\tdest.Exemplars = CopyExemplarSlice(dest.Exemplars, src.Exemplars)\n\n\tdest.Flags = src.Flags\n\n\treturn dest\n}\n\nfunc CopyNumberDataPointSlice(dest, src []NumberDataPoint) []NumberDataPoint {\n\tvar newDest []NumberDataPoint\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]NumberDataPoint, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteNumberDataPoint(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyNumberDataPoint(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyNumberDataPointPtrSlice(dest, src []*NumberDataPoint) []*NumberDataPoint {\n\tvar newDest []*NumberDataPoint\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*NumberDataPoint, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewNumberDataPoint()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteNumberDataPoint(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewNumberDataPoint()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyNumberDataPoint(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *NumberDataPoint) Reset() {\n\t*orig = NumberDataPoint{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *NumberDataPoint) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.Attributes) > 0 {\n\t\tdest.WriteObjectField(\"attributes\")\n\t\tdest.WriteArrayStart()\n\t\torig.Attributes[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Attributes); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Attributes[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.StartTimeUnixNano != uint64(0) {\n\t\tdest.WriteObjectField(\"startTimeUnixNano\")\n\t\tdest.WriteUint64(orig.StartTimeUnixNano)\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tdest.WriteObjectField(\"timeUnixNano\")\n\t\tdest.WriteUint64(orig.TimeUnixNano)\n\t}\n\tswitch orig := orig.Value.(type) {\n\tcase *NumberDataPoint_AsDouble:\n\t\tdest.WriteObjectField(\"asDouble\")\n\t\tdest.WriteFloat64(orig.AsDouble)\n\tcase *NumberDataPoint_AsInt:\n\t\tdest.WriteObjectField(\"asInt\")\n\t\tdest.WriteInt64(orig.AsInt)\n\t}\n\tif len(orig.Exemplars) > 0 {\n\t\tdest.WriteObjectField(\"exemplars\")\n\t\tdest.WriteArrayStart()\n\t\torig.Exemplars[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Exemplars); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Exemplars[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.Flags != uint32(0) {\n\t\tdest.WriteObjectField(\"flags\")\n\t\tdest.WriteUint32(orig.Flags)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *NumberDataPoint) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"attributes\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\t\torig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"startTimeUnixNano\", \"start_time_unix_nano\":\n\t\t\torig.StartTimeUnixNano = iter.ReadUint64()\n\t\tcase \"timeUnixNano\", \"time_unix_nano\":\n\t\t\torig.TimeUnixNano = iter.ReadUint64()\n\n\t\tcase \"asDouble\", \"as_double\":\n\t\t\t{\n\t\t\t\tvar ov *NumberDataPoint_AsDouble\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &NumberDataPoint_AsDouble{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolNumberDataPoint_AsDouble.Get().(*NumberDataPoint_AsDouble)\n\t\t\t\t}\n\t\t\t\tov.AsDouble = iter.ReadFloat64()\n\t\t\t\torig.Value = ov\n\t\t\t}\n\t\tcase \"asInt\", \"as_int\":\n\t\t\t{\n\t\t\t\tvar ov *NumberDataPoint_AsInt\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &NumberDataPoint_AsInt{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolNumberDataPoint_AsInt.Get().(*NumberDataPoint_AsInt)\n\t\t\t\t}\n\t\t\t\tov.AsInt = iter.ReadInt64()\n\t\t\t\torig.Value = ov\n\t\t\t}\n\n\t\tcase \"exemplars\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Exemplars = append(orig.Exemplars, Exemplar{})\n\t\t\t\torig.Exemplars[len(orig.Exemplars)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"flags\":\n\t\t\torig.Flags = iter.ReadUint32()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *NumberDataPoint) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.Attributes {\n\t\tl = orig.Attributes[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.StartTimeUnixNano != uint64(0) {\n\t\tn += 9\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tn += 9\n\t}\n\tswitch orig := orig.Value.(type) {\n\tcase nil:\n\t\t_ = orig\n\t\tbreak\n\tcase *NumberDataPoint_AsDouble:\n\n\t\tn += 9\n\tcase *NumberDataPoint_AsInt:\n\n\t\tn += 9\n\t}\n\tfor i := range orig.Exemplars {\n\t\tl = orig.Exemplars[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.Flags != uint32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.Flags))\n\t}\n\treturn n\n}\n\nfunc (orig *NumberDataPoint) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.Attributes) - 1; i >= 0; i-- {\n\t\tl = orig.Attributes[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x3a\n\t}\n\tif orig.StartTimeUnixNano != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.StartTimeUnixNano))\n\t\tpos--\n\t\tbuf[pos] = 0x11\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimeUnixNano))\n\t\tpos--\n\t\tbuf[pos] = 0x19\n\t}\n\tswitch orig := orig.Value.(type) {\n\tcase *NumberDataPoint_AsDouble:\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.AsDouble))\n\t\tpos--\n\t\tbuf[pos] = 0x21\n\n\tcase *NumberDataPoint_AsInt:\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.AsInt))\n\t\tpos--\n\t\tbuf[pos] = 0x31\n\n\t}\n\tfor i := len(orig.Exemplars) - 1; i >= 0; i-- {\n\t\tl = orig.Exemplars[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x2a\n\t}\n\tif orig.Flags != uint32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.Flags))\n\t\tpos--\n\t\tbuf[pos] = 0x40\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *NumberDataPoint) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 7:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Attributes\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\terr = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field StartTimeUnixNano\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.StartTimeUnixNano = uint64(num)\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TimeUnixNano\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.TimeUnixNano = uint64(num)\n\n\t\tcase 4:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field AsDouble\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvar ov *NumberDataPoint_AsDouble\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &NumberDataPoint_AsDouble{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolNumberDataPoint_AsDouble.Get().(*NumberDataPoint_AsDouble)\n\t\t\t}\n\t\t\tov.AsDouble = math.Float64frombits(num)\n\t\t\torig.Value = ov\n\n\t\tcase 6:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field AsInt\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tvar ov *NumberDataPoint_AsInt\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &NumberDataPoint_AsInt{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolNumberDataPoint_AsInt.Get().(*NumberDataPoint_AsInt)\n\t\t\t}\n\t\t\tov.AsInt = int64(num)\n\t\t\torig.Value = ov\n\n\t\tcase 5:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Exemplars\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Exemplars = append(orig.Exemplars, Exemplar{})\n\t\t\terr = orig.Exemplars[len(orig.Exemplars)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 8:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Flags\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Flags = uint32(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestNumberDataPoint() *NumberDataPoint {\n\torig := NewNumberDataPoint()\n\torig.Attributes = []KeyValue{{}, *GenTestKeyValue()}\n\torig.StartTimeUnixNano = uint64(13)\n\torig.TimeUnixNano = uint64(13)\n\torig.Value = &NumberDataPoint_AsDouble{AsDouble: float64(3.1415926)}\n\torig.Exemplars = []Exemplar{{}, *GenTestExemplar()}\n\torig.Flags = uint32(13)\n\treturn orig\n}\n\nfunc GenTestNumberDataPointPtrSlice() []*NumberDataPoint {\n\torig := make([]*NumberDataPoint, 5)\n\torig[0] = NewNumberDataPoint()\n\torig[1] = GenTestNumberDataPoint()\n\torig[2] = NewNumberDataPoint()\n\torig[3] = GenTestNumberDataPoint()\n\torig[4] = NewNumberDataPoint()\n\treturn orig\n}\n\nfunc GenTestNumberDataPointSlice() []NumberDataPoint {\n\torig := make([]NumberDataPoint, 5)\n\torig[1] = *GenTestNumberDataPoint()\n\torig[3] = *GenTestNumberDataPoint()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_numberdatapoint_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyNumberDataPoint(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesNumberDataPoint() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewNumberDataPoint()\n\t\t\t\tCopyNumberDataPoint(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyNumberDataPoint(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyNumberDataPointSlice(t *testing.T) {\n\tsrc := []NumberDataPoint{}\n\tdest := []NumberDataPoint{}\n\t// Test CopyTo empty\n\tdest = CopyNumberDataPointSlice(dest, src)\n\tassert.Equal(t, []NumberDataPoint{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestNumberDataPointSlice()\n\tdest = CopyNumberDataPointSlice(dest, src)\n\tassert.Equal(t, GenTestNumberDataPointSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyNumberDataPointSlice(dest, src)\n\tassert.Equal(t, GenTestNumberDataPointSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyNumberDataPointSlice(dest, []NumberDataPoint{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyNumberDataPointSlice(dest, src)\n\tassert.Equal(t, GenTestNumberDataPointSlice(), dest)\n}\n\nfunc TestCopyNumberDataPointPtrSlice(t *testing.T) {\n\tsrc := []*NumberDataPoint{}\n\tdest := []*NumberDataPoint{}\n\t// Test CopyTo empty\n\tdest = CopyNumberDataPointPtrSlice(dest, src)\n\tassert.Equal(t, []*NumberDataPoint{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestNumberDataPointPtrSlice()\n\tdest = CopyNumberDataPointPtrSlice(dest, src)\n\tassert.Equal(t, GenTestNumberDataPointPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyNumberDataPointPtrSlice(dest, src)\n\tassert.Equal(t, GenTestNumberDataPointPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyNumberDataPointPtrSlice(dest, []*NumberDataPoint{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyNumberDataPointPtrSlice(dest, src)\n\tassert.Equal(t, GenTestNumberDataPointPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONNumberDataPointUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewNumberDataPoint()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewNumberDataPoint(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONNumberDataPoint(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesNumberDataPoint() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewNumberDataPoint()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteNumberDataPoint(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoNumberDataPointFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesNumberDataPoint() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewNumberDataPoint()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoNumberDataPointUnknown(t *testing.T) {\n\tdest := NewNumberDataPoint()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewNumberDataPoint(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoNumberDataPoint(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesNumberDataPoint() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewNumberDataPoint()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteNumberDataPoint(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufNumberDataPoint(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesNumberDataPoint() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpmetrics.NumberDataPoint{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewNumberDataPoint()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesNumberDataPoint() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                     {0x02},\n\t\t\"Attributes/wrong_wire_type\":        {0x3c},\n\t\t\"Attributes/missing_value\":          {0x3a},\n\t\t\"StartTimeUnixNano/wrong_wire_type\": {0x14},\n\t\t\"StartTimeUnixNano/missing_value\":   {0x11},\n\t\t\"TimeUnixNano/wrong_wire_type\":      {0x1c},\n\t\t\"TimeUnixNano/missing_value\":        {0x19},\n\n\t\t\"AsDouble/wrong_wire_type\":  {0x24},\n\t\t\"AsDouble/missing_value\":    {0x21},\n\t\t\"AsInt/wrong_wire_type\":     {0x34},\n\t\t\"AsInt/missing_value\":       {0x31},\n\t\t\"Exemplars/wrong_wire_type\": {0x2c},\n\t\t\"Exemplars/missing_value\":   {0x2a},\n\t\t\"Flags/wrong_wire_type\":     {0x44},\n\t\t\"Flags/missing_value\":       {0x40},\n\t}\n}\n\nfunc genTestEncodingValuesNumberDataPoint() map[string]*NumberDataPoint {\n\treturn map[string]*NumberDataPoint{\n\t\t\"empty\":                  NewNumberDataPoint(),\n\t\t\"Attributes/test\":        {Attributes: []KeyValue{{}, *GenTestKeyValue()}},\n\t\t\"StartTimeUnixNano/test\": {StartTimeUnixNano: uint64(13)},\n\t\t\"TimeUnixNano/test\":      {TimeUnixNano: uint64(13)},\n\t\t\"AsDouble/default\":       {Value: &NumberDataPoint_AsDouble{AsDouble: float64(0)}},\n\t\t\"AsDouble/test\":          {Value: &NumberDataPoint_AsDouble{AsDouble: float64(3.1415926)}}, \"AsInt/default\": {Value: &NumberDataPoint_AsInt{AsInt: int64(0)}},\n\t\t\"AsInt/test\":     {Value: &NumberDataPoint_AsInt{AsInt: int64(13)}},\n\t\t\"Exemplars/test\": {Exemplars: []Exemplar{{}, *GenTestExemplar()}},\n\t\t\"Flags/test\":     {Flags: uint32(13)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_profile.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Profile are an implementation of the pprofextended data model.\n\ntype Profile struct {\n\tOriginalPayloadFormat  string\n\tSamples                []*Sample\n\tOriginalPayload        []byte\n\tAttributeIndices       []int32\n\tTimeUnixNano           uint64\n\tDurationNano           uint64\n\tPeriod                 int64\n\tSampleType             ValueType\n\tPeriodType             ValueType\n\tDroppedAttributesCount uint32\n\tProfileId              ProfileID\n}\n\nvar (\n\tprotoPoolProfile = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Profile{}\n\t\t},\n\t}\n)\n\nfunc NewProfile() *Profile {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &Profile{}\n\t}\n\treturn protoPoolProfile.Get().(*Profile)\n}\n\nfunc DeleteProfile(orig *Profile, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteValueType(&orig.SampleType, false)\n\tfor i := range orig.Samples {\n\t\tDeleteSample(orig.Samples[i], true)\n\t}\n\n\tDeleteValueType(&orig.PeriodType, false)\n\n\tDeleteProfileID(&orig.ProfileId, false)\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolProfile.Put(orig)\n\t}\n}\n\nfunc CopyProfile(dest, src *Profile) *Profile {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewProfile()\n\t}\n\tCopyValueType(&dest.SampleType, &src.SampleType)\n\n\tdest.Samples = CopySamplePtrSlice(dest.Samples, src.Samples)\n\n\tdest.TimeUnixNano = src.TimeUnixNano\n\tdest.DurationNano = src.DurationNano\n\tCopyValueType(&dest.PeriodType, &src.PeriodType)\n\n\tdest.Period = src.Period\n\tCopyProfileID(&dest.ProfileId, &src.ProfileId)\n\n\tdest.DroppedAttributesCount = src.DroppedAttributesCount\n\tdest.OriginalPayloadFormat = src.OriginalPayloadFormat\n\tdest.OriginalPayload = src.OriginalPayload\n\tdest.AttributeIndices = append(dest.AttributeIndices[:0], src.AttributeIndices...)\n\n\treturn dest\n}\n\nfunc CopyProfileSlice(dest, src []Profile) []Profile {\n\tvar newDest []Profile\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]Profile, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteProfile(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyProfile(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyProfilePtrSlice(dest, src []*Profile) []*Profile {\n\tvar newDest []*Profile\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*Profile, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewProfile()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteProfile(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewProfile()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyProfile(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *Profile) Reset() {\n\t*orig = Profile{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *Profile) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tdest.WriteObjectField(\"sampleType\")\n\torig.SampleType.MarshalJSON(dest)\n\tif len(orig.Samples) > 0 {\n\t\tdest.WriteObjectField(\"samples\")\n\t\tdest.WriteArrayStart()\n\t\torig.Samples[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Samples); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Samples[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tdest.WriteObjectField(\"timeUnixNano\")\n\t\tdest.WriteUint64(orig.TimeUnixNano)\n\t}\n\tif orig.DurationNano != uint64(0) {\n\t\tdest.WriteObjectField(\"durationNano\")\n\t\tdest.WriteUint64(orig.DurationNano)\n\t}\n\tdest.WriteObjectField(\"periodType\")\n\torig.PeriodType.MarshalJSON(dest)\n\tif orig.Period != int64(0) {\n\t\tdest.WriteObjectField(\"period\")\n\t\tdest.WriteInt64(orig.Period)\n\t}\n\tif !orig.ProfileId.IsEmpty() {\n\t\tdest.WriteObjectField(\"profileId\")\n\t\torig.ProfileId.MarshalJSON(dest)\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tdest.WriteObjectField(\"droppedAttributesCount\")\n\t\tdest.WriteUint32(orig.DroppedAttributesCount)\n\t}\n\tif orig.OriginalPayloadFormat != \"\" {\n\t\tdest.WriteObjectField(\"originalPayloadFormat\")\n\t\tdest.WriteString(orig.OriginalPayloadFormat)\n\t}\n\n\tif len(orig.OriginalPayload) > 0 {\n\t\tdest.WriteObjectField(\"originalPayload\")\n\t\tdest.WriteBytes(orig.OriginalPayload)\n\t}\n\tif len(orig.AttributeIndices) > 0 {\n\t\tdest.WriteObjectField(\"attributeIndices\")\n\t\tdest.WriteArrayStart()\n\t\tdest.WriteInt32(orig.AttributeIndices[0])\n\t\tfor i := 1; i < len(orig.AttributeIndices); i++ {\n\t\t\tdest.WriteMore()\n\t\t\tdest.WriteInt32(orig.AttributeIndices[i])\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *Profile) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"sampleType\", \"sample_type\":\n\n\t\t\torig.SampleType.UnmarshalJSON(iter)\n\t\tcase \"samples\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Samples = append(orig.Samples, NewSample())\n\t\t\t\torig.Samples[len(orig.Samples)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"timeUnixNano\", \"time_unix_nano\":\n\t\t\torig.TimeUnixNano = iter.ReadUint64()\n\t\tcase \"durationNano\", \"duration_nano\":\n\t\t\torig.DurationNano = iter.ReadUint64()\n\t\tcase \"periodType\", \"period_type\":\n\n\t\t\torig.PeriodType.UnmarshalJSON(iter)\n\t\tcase \"period\":\n\t\t\torig.Period = iter.ReadInt64()\n\t\tcase \"profileId\", \"profile_id\":\n\n\t\t\torig.ProfileId.UnmarshalJSON(iter)\n\t\tcase \"droppedAttributesCount\", \"dropped_attributes_count\":\n\t\t\torig.DroppedAttributesCount = iter.ReadUint32()\n\t\tcase \"originalPayloadFormat\", \"original_payload_format\":\n\t\t\torig.OriginalPayloadFormat = iter.ReadString()\n\t\tcase \"originalPayload\", \"original_payload\":\n\t\t\torig.OriginalPayload = iter.ReadBytes()\n\t\tcase \"attributeIndices\", \"attribute_indices\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.AttributeIndices = append(orig.AttributeIndices, iter.ReadInt32())\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *Profile) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tl = orig.SampleType.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tfor i := range orig.Samples {\n\t\tl = orig.Samples[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tn += 9\n\t}\n\tif orig.DurationNano != uint64(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.DurationNano))\n\t}\n\tl = orig.PeriodType.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tif orig.Period != int64(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.Period))\n\t}\n\tl = orig.ProfileId.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.DroppedAttributesCount))\n\t}\n\n\tl = len(orig.OriginalPayloadFormat)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\n\tl = len(orig.OriginalPayload)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\n\tif len(orig.AttributeIndices) > 0 {\n\t\tl = 0\n\t\tfor _, e := range orig.AttributeIndices {\n\t\t\tl += proto.Sov(uint64(e))\n\t\t}\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *Profile) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = orig.SampleType.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0xa\n\n\tfor i := len(orig.Samples) - 1; i >= 0; i-- {\n\t\tl = orig.Samples[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimeUnixNano))\n\t\tpos--\n\t\tbuf[pos] = 0x19\n\t}\n\tif orig.DurationNano != uint64(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.DurationNano))\n\t\tpos--\n\t\tbuf[pos] = 0x20\n\t}\n\tl = orig.PeriodType.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x2a\n\n\tif orig.Period != int64(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.Period))\n\t\tpos--\n\t\tbuf[pos] = 0x30\n\t}\n\tl = orig.ProfileId.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x3a\n\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedAttributesCount))\n\t\tpos--\n\t\tbuf[pos] = 0x40\n\t}\n\tl = len(orig.OriginalPayloadFormat)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.OriginalPayloadFormat)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x4a\n\t}\n\tl = len(orig.OriginalPayload)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.OriginalPayload)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x52\n\t}\n\tl = len(orig.AttributeIndices)\n\tif l > 0 {\n\t\tendPos := pos\n\t\tfor i := l - 1; i >= 0; i-- {\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.AttributeIndices[i]))\n\t\t}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(endPos-pos))\n\t\tpos--\n\t\tbuf[pos] = 0x5a\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *Profile) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SampleType\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.SampleType.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Samples\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Samples = append(orig.Samples, NewSample())\n\t\t\terr = orig.Samples[len(orig.Samples)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TimeUnixNano\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.TimeUnixNano = uint64(num)\n\n\t\tcase 4:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DurationNano\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.DurationNano = uint64(num)\n\n\t\tcase 5:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field PeriodType\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.PeriodType.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 6:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Period\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Period = int64(num)\n\n\t\tcase 7:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ProfileId\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.ProfileId.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 8:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DroppedAttributesCount\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.DroppedAttributesCount = uint32(num)\n\n\t\tcase 9:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field OriginalPayloadFormat\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.OriginalPayloadFormat = string(buf[startPos:pos])\n\n\t\tcase 10:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field OriginalPayload\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tif length != 0 {\n\t\t\t\torig.OriginalPayload = make([]byte, length)\n\t\t\t\tcopy(orig.OriginalPayload, buf[startPos:pos])\n\t\t\t}\n\t\tcase 11:\n\t\t\tswitch wireType {\n\t\t\tcase proto.WireTypeLen:\n\t\t\t\tvar length int\n\t\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tstartPos := pos - length\n\t\t\t\tvar num uint64\n\t\t\t\tfor startPos < pos {\n\t\t\t\t\tnum, startPos, err = proto.ConsumeVarint(buf[:pos], startPos)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\torig.AttributeIndices = append(orig.AttributeIndices, int32(num))\n\t\t\t\t}\n\t\t\t\tif startPos != pos {\n\t\t\t\t\treturn fmt.Errorf(\"proto: invalid field len = %d for field AttributeIndices\", pos-startPos)\n\t\t\t\t}\n\t\t\tcase proto.WireTypeVarint:\n\t\t\t\tvar num uint64\n\t\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\torig.AttributeIndices = append(orig.AttributeIndices, int32(num))\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field AttributeIndices\", wireType)\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestProfile() *Profile {\n\torig := NewProfile()\n\torig.SampleType = *GenTestValueType()\n\torig.Samples = []*Sample{{}, GenTestSample()}\n\torig.TimeUnixNano = uint64(13)\n\torig.DurationNano = uint64(13)\n\torig.PeriodType = *GenTestValueType()\n\torig.Period = int64(13)\n\torig.ProfileId = *GenTestProfileID()\n\torig.DroppedAttributesCount = uint32(13)\n\torig.OriginalPayloadFormat = \"test_originalpayloadformat\"\n\torig.OriginalPayload = []byte{1, 2, 3}\n\torig.AttributeIndices = []int32{int32(0), int32(13)}\n\treturn orig\n}\n\nfunc GenTestProfilePtrSlice() []*Profile {\n\torig := make([]*Profile, 5)\n\torig[0] = NewProfile()\n\torig[1] = GenTestProfile()\n\torig[2] = NewProfile()\n\torig[3] = GenTestProfile()\n\torig[4] = NewProfile()\n\treturn orig\n}\n\nfunc GenTestProfileSlice() []Profile {\n\torig := make([]Profile, 5)\n\torig[1] = *GenTestProfile()\n\torig[3] = *GenTestProfile()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_profile_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpprofiles \"go.opentelemetry.io/proto/slim/otlp/profiles/v1development\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyProfile(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesProfile() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewProfile()\n\t\t\t\tCopyProfile(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyProfile(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyProfileSlice(t *testing.T) {\n\tsrc := []Profile{}\n\tdest := []Profile{}\n\t// Test CopyTo empty\n\tdest = CopyProfileSlice(dest, src)\n\tassert.Equal(t, []Profile{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestProfileSlice()\n\tdest = CopyProfileSlice(dest, src)\n\tassert.Equal(t, GenTestProfileSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyProfileSlice(dest, src)\n\tassert.Equal(t, GenTestProfileSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyProfileSlice(dest, []Profile{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyProfileSlice(dest, src)\n\tassert.Equal(t, GenTestProfileSlice(), dest)\n}\n\nfunc TestCopyProfilePtrSlice(t *testing.T) {\n\tsrc := []*Profile{}\n\tdest := []*Profile{}\n\t// Test CopyTo empty\n\tdest = CopyProfilePtrSlice(dest, src)\n\tassert.Equal(t, []*Profile{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestProfilePtrSlice()\n\tdest = CopyProfilePtrSlice(dest, src)\n\tassert.Equal(t, GenTestProfilePtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyProfilePtrSlice(dest, src)\n\tassert.Equal(t, GenTestProfilePtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyProfilePtrSlice(dest, []*Profile{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyProfilePtrSlice(dest, src)\n\tassert.Equal(t, GenTestProfilePtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONProfileUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewProfile()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewProfile(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONProfile(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesProfile() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewProfile()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteProfile(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoProfileFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesProfile() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewProfile()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoProfileUnknown(t *testing.T) {\n\tdest := NewProfile()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewProfile(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoProfile(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesProfile() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewProfile()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteProfile(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufProfile(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesProfile() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpprofiles.Profile{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewProfile()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesProfile() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                          {0x02},\n\t\t\"SampleType/wrong_wire_type\":             {0xc},\n\t\t\"SampleType/missing_value\":               {0xa},\n\t\t\"Samples/wrong_wire_type\":                {0x14},\n\t\t\"Samples/missing_value\":                  {0x12},\n\t\t\"TimeUnixNano/wrong_wire_type\":           {0x1c},\n\t\t\"TimeUnixNano/missing_value\":             {0x19},\n\t\t\"DurationNano/wrong_wire_type\":           {0x24},\n\t\t\"DurationNano/missing_value\":             {0x20},\n\t\t\"PeriodType/wrong_wire_type\":             {0x2c},\n\t\t\"PeriodType/missing_value\":               {0x2a},\n\t\t\"Period/wrong_wire_type\":                 {0x34},\n\t\t\"Period/missing_value\":                   {0x30},\n\t\t\"ProfileId/wrong_wire_type\":              {0x3c},\n\t\t\"ProfileId/missing_value\":                {0x3a},\n\t\t\"DroppedAttributesCount/wrong_wire_type\": {0x44},\n\t\t\"DroppedAttributesCount/missing_value\":   {0x40},\n\t\t\"OriginalPayloadFormat/wrong_wire_type\":  {0x4c},\n\t\t\"OriginalPayloadFormat/missing_value\":    {0x4a},\n\t\t\"OriginalPayload/wrong_wire_type\":        {0x54},\n\t\t\"OriginalPayload/missing_value\":          {0x52},\n\t\t\"AttributeIndices/wrong_wire_type\":       {0x5c},\n\t\t\"AttributeIndices/missing_value\":         {0x5a},\n\t}\n}\n\nfunc genTestEncodingValuesProfile() map[string]*Profile {\n\treturn map[string]*Profile{\n\t\t\"empty\":                       NewProfile(),\n\t\t\"SampleType/test\":             {SampleType: *GenTestValueType()},\n\t\t\"Samples/test\":                {Samples: []*Sample{{}, GenTestSample()}},\n\t\t\"TimeUnixNano/test\":           {TimeUnixNano: uint64(13)},\n\t\t\"DurationNano/test\":           {DurationNano: uint64(13)},\n\t\t\"PeriodType/test\":             {PeriodType: *GenTestValueType()},\n\t\t\"Period/test\":                 {Period: int64(13)},\n\t\t\"ProfileId/test\":              {ProfileId: *GenTestProfileID()},\n\t\t\"DroppedAttributesCount/test\": {DroppedAttributesCount: uint32(13)},\n\t\t\"OriginalPayloadFormat/test\":  {OriginalPayloadFormat: \"test_originalpayloadformat\"},\n\t\t\"OriginalPayload/test\":        {OriginalPayload: []byte{1, 2, 3}},\n\t\t\"AttributeIndices/test\":       {AttributeIndices: []int32{int32(0), int32(13)}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_profilesdata.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ProfilesData represents the profiles data that can be stored in persistent storage,\n// OR can be embedded by other protocols that transfer OTLP profiles data but do not\n// implement the OTLP protocol.\ntype ProfilesData struct {\n\tResourceProfiles []*ResourceProfiles\n\tDictionary       ProfilesDictionary\n}\n\nvar (\n\tprotoPoolProfilesData = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ProfilesData{}\n\t\t},\n\t}\n)\n\nfunc NewProfilesData() *ProfilesData {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ProfilesData{}\n\t}\n\treturn protoPoolProfilesData.Get().(*ProfilesData)\n}\n\nfunc DeleteProfilesData(orig *ProfilesData, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.ResourceProfiles {\n\t\tDeleteResourceProfiles(orig.ResourceProfiles[i], true)\n\t}\n\tDeleteProfilesDictionary(&orig.Dictionary, false)\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolProfilesData.Put(orig)\n\t}\n}\n\nfunc CopyProfilesData(dest, src *ProfilesData) *ProfilesData {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewProfilesData()\n\t}\n\tdest.ResourceProfiles = CopyResourceProfilesPtrSlice(dest.ResourceProfiles, src.ResourceProfiles)\n\n\tCopyProfilesDictionary(&dest.Dictionary, &src.Dictionary)\n\n\treturn dest\n}\n\nfunc CopyProfilesDataSlice(dest, src []ProfilesData) []ProfilesData {\n\tvar newDest []ProfilesData\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ProfilesData, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteProfilesData(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyProfilesData(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyProfilesDataPtrSlice(dest, src []*ProfilesData) []*ProfilesData {\n\tvar newDest []*ProfilesData\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ProfilesData, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewProfilesData()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteProfilesData(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewProfilesData()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyProfilesData(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ProfilesData) Reset() {\n\t*orig = ProfilesData{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ProfilesData) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.ResourceProfiles) > 0 {\n\t\tdest.WriteObjectField(\"resourceProfiles\")\n\t\tdest.WriteArrayStart()\n\t\torig.ResourceProfiles[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.ResourceProfiles); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.ResourceProfiles[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectField(\"dictionary\")\n\torig.Dictionary.MarshalJSON(dest)\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ProfilesData) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"resourceProfiles\", \"resource_profiles\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.ResourceProfiles = append(orig.ResourceProfiles, NewResourceProfiles())\n\t\t\t\torig.ResourceProfiles[len(orig.ResourceProfiles)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"dictionary\":\n\n\t\t\torig.Dictionary.UnmarshalJSON(iter)\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ProfilesData) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.ResourceProfiles {\n\t\tl = orig.ResourceProfiles[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tl = orig.Dictionary.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\treturn n\n}\n\nfunc (orig *ProfilesData) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.ResourceProfiles) - 1; i >= 0; i-- {\n\t\tl = orig.ResourceProfiles[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\tl = orig.Dictionary.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x12\n\n\treturn len(buf) - pos\n}\n\nfunc (orig *ProfilesData) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ResourceProfiles\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.ResourceProfiles = append(orig.ResourceProfiles, NewResourceProfiles())\n\t\t\terr = orig.ResourceProfiles[len(orig.ResourceProfiles)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Dictionary\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.Dictionary.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestProfilesData() *ProfilesData {\n\torig := NewProfilesData()\n\torig.ResourceProfiles = []*ResourceProfiles{{}, GenTestResourceProfiles()}\n\torig.Dictionary = *GenTestProfilesDictionary()\n\treturn orig\n}\n\nfunc GenTestProfilesDataPtrSlice() []*ProfilesData {\n\torig := make([]*ProfilesData, 5)\n\torig[0] = NewProfilesData()\n\torig[1] = GenTestProfilesData()\n\torig[2] = NewProfilesData()\n\torig[3] = GenTestProfilesData()\n\torig[4] = NewProfilesData()\n\treturn orig\n}\n\nfunc GenTestProfilesDataSlice() []ProfilesData {\n\torig := make([]ProfilesData, 5)\n\torig[1] = *GenTestProfilesData()\n\torig[3] = *GenTestProfilesData()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_profilesdata_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpprofiles \"go.opentelemetry.io/proto/slim/otlp/profiles/v1development\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyProfilesData(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesProfilesData() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewProfilesData()\n\t\t\t\tCopyProfilesData(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyProfilesData(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyProfilesDataSlice(t *testing.T) {\n\tsrc := []ProfilesData{}\n\tdest := []ProfilesData{}\n\t// Test CopyTo empty\n\tdest = CopyProfilesDataSlice(dest, src)\n\tassert.Equal(t, []ProfilesData{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestProfilesDataSlice()\n\tdest = CopyProfilesDataSlice(dest, src)\n\tassert.Equal(t, GenTestProfilesDataSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyProfilesDataSlice(dest, src)\n\tassert.Equal(t, GenTestProfilesDataSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyProfilesDataSlice(dest, []ProfilesData{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyProfilesDataSlice(dest, src)\n\tassert.Equal(t, GenTestProfilesDataSlice(), dest)\n}\n\nfunc TestCopyProfilesDataPtrSlice(t *testing.T) {\n\tsrc := []*ProfilesData{}\n\tdest := []*ProfilesData{}\n\t// Test CopyTo empty\n\tdest = CopyProfilesDataPtrSlice(dest, src)\n\tassert.Equal(t, []*ProfilesData{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestProfilesDataPtrSlice()\n\tdest = CopyProfilesDataPtrSlice(dest, src)\n\tassert.Equal(t, GenTestProfilesDataPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyProfilesDataPtrSlice(dest, src)\n\tassert.Equal(t, GenTestProfilesDataPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyProfilesDataPtrSlice(dest, []*ProfilesData{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyProfilesDataPtrSlice(dest, src)\n\tassert.Equal(t, GenTestProfilesDataPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONProfilesDataUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewProfilesData()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewProfilesData(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONProfilesData(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesProfilesData() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewProfilesData()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteProfilesData(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoProfilesDataFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesProfilesData() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewProfilesData()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoProfilesDataUnknown(t *testing.T) {\n\tdest := NewProfilesData()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewProfilesData(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoProfilesData(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesProfilesData() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewProfilesData()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteProfilesData(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufProfilesData(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesProfilesData() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpprofiles.ProfilesData{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewProfilesData()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesProfilesData() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                    {0x02},\n\t\t\"ResourceProfiles/wrong_wire_type\": {0xc},\n\t\t\"ResourceProfiles/missing_value\":   {0xa},\n\t\t\"Dictionary/wrong_wire_type\":       {0x14},\n\t\t\"Dictionary/missing_value\":         {0x12},\n\t}\n}\n\nfunc genTestEncodingValuesProfilesData() map[string]*ProfilesData {\n\treturn map[string]*ProfilesData{\n\t\t\"empty\":                 NewProfilesData(),\n\t\t\"ResourceProfiles/test\": {ResourceProfiles: []*ResourceProfiles{{}, GenTestResourceProfiles()}},\n\t\t\"Dictionary/test\":       {Dictionary: *GenTestProfilesDictionary()},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_profilesdictionary.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ProfilesDictionary is the reference table containing all data shared by profiles across the message being sent.\ntype ProfilesDictionary struct {\n\tMappingTable   []*Mapping\n\tLocationTable  []*Location\n\tFunctionTable  []*Function\n\tLinkTable      []*Link\n\tStringTable    []string\n\tAttributeTable []*KeyValueAndUnit\n\tStackTable     []*Stack\n}\n\nvar (\n\tprotoPoolProfilesDictionary = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ProfilesDictionary{}\n\t\t},\n\t}\n)\n\nfunc NewProfilesDictionary() *ProfilesDictionary {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ProfilesDictionary{}\n\t}\n\treturn protoPoolProfilesDictionary.Get().(*ProfilesDictionary)\n}\n\nfunc DeleteProfilesDictionary(orig *ProfilesDictionary, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.MappingTable {\n\t\tDeleteMapping(orig.MappingTable[i], true)\n\t}\n\tfor i := range orig.LocationTable {\n\t\tDeleteLocation(orig.LocationTable[i], true)\n\t}\n\tfor i := range orig.FunctionTable {\n\t\tDeleteFunction(orig.FunctionTable[i], true)\n\t}\n\tfor i := range orig.LinkTable {\n\t\tDeleteLink(orig.LinkTable[i], true)\n\t}\n\n\tfor i := range orig.AttributeTable {\n\t\tDeleteKeyValueAndUnit(orig.AttributeTable[i], true)\n\t}\n\tfor i := range orig.StackTable {\n\t\tDeleteStack(orig.StackTable[i], true)\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolProfilesDictionary.Put(orig)\n\t}\n}\n\nfunc CopyProfilesDictionary(dest, src *ProfilesDictionary) *ProfilesDictionary {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewProfilesDictionary()\n\t}\n\tdest.MappingTable = CopyMappingPtrSlice(dest.MappingTable, src.MappingTable)\n\n\tdest.LocationTable = CopyLocationPtrSlice(dest.LocationTable, src.LocationTable)\n\n\tdest.FunctionTable = CopyFunctionPtrSlice(dest.FunctionTable, src.FunctionTable)\n\n\tdest.LinkTable = CopyLinkPtrSlice(dest.LinkTable, src.LinkTable)\n\n\tdest.StringTable = append(dest.StringTable[:0], src.StringTable...)\n\n\tdest.AttributeTable = CopyKeyValueAndUnitPtrSlice(dest.AttributeTable, src.AttributeTable)\n\n\tdest.StackTable = CopyStackPtrSlice(dest.StackTable, src.StackTable)\n\n\treturn dest\n}\n\nfunc CopyProfilesDictionarySlice(dest, src []ProfilesDictionary) []ProfilesDictionary {\n\tvar newDest []ProfilesDictionary\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ProfilesDictionary, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteProfilesDictionary(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyProfilesDictionary(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyProfilesDictionaryPtrSlice(dest, src []*ProfilesDictionary) []*ProfilesDictionary {\n\tvar newDest []*ProfilesDictionary\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ProfilesDictionary, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewProfilesDictionary()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteProfilesDictionary(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewProfilesDictionary()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyProfilesDictionary(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ProfilesDictionary) Reset() {\n\t*orig = ProfilesDictionary{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ProfilesDictionary) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.MappingTable) > 0 {\n\t\tdest.WriteObjectField(\"mappingTable\")\n\t\tdest.WriteArrayStart()\n\t\torig.MappingTable[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.MappingTable); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.MappingTable[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif len(orig.LocationTable) > 0 {\n\t\tdest.WriteObjectField(\"locationTable\")\n\t\tdest.WriteArrayStart()\n\t\torig.LocationTable[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.LocationTable); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.LocationTable[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif len(orig.FunctionTable) > 0 {\n\t\tdest.WriteObjectField(\"functionTable\")\n\t\tdest.WriteArrayStart()\n\t\torig.FunctionTable[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.FunctionTable); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.FunctionTable[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif len(orig.LinkTable) > 0 {\n\t\tdest.WriteObjectField(\"linkTable\")\n\t\tdest.WriteArrayStart()\n\t\torig.LinkTable[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.LinkTable); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.LinkTable[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif len(orig.StringTable) > 0 {\n\t\tdest.WriteObjectField(\"stringTable\")\n\t\tdest.WriteArrayStart()\n\t\tdest.WriteString(orig.StringTable[0])\n\t\tfor i := 1; i < len(orig.StringTable); i++ {\n\t\t\tdest.WriteMore()\n\t\t\tdest.WriteString(orig.StringTable[i])\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\n\tif len(orig.AttributeTable) > 0 {\n\t\tdest.WriteObjectField(\"attributeTable\")\n\t\tdest.WriteArrayStart()\n\t\torig.AttributeTable[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.AttributeTable); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.AttributeTable[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif len(orig.StackTable) > 0 {\n\t\tdest.WriteObjectField(\"stackTable\")\n\t\tdest.WriteArrayStart()\n\t\torig.StackTable[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.StackTable); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.StackTable[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ProfilesDictionary) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"mappingTable\", \"mapping_table\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.MappingTable = append(orig.MappingTable, NewMapping())\n\t\t\t\torig.MappingTable[len(orig.MappingTable)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"locationTable\", \"location_table\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.LocationTable = append(orig.LocationTable, NewLocation())\n\t\t\t\torig.LocationTable[len(orig.LocationTable)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"functionTable\", \"function_table\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.FunctionTable = append(orig.FunctionTable, NewFunction())\n\t\t\t\torig.FunctionTable[len(orig.FunctionTable)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"linkTable\", \"link_table\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.LinkTable = append(orig.LinkTable, NewLink())\n\t\t\t\torig.LinkTable[len(orig.LinkTable)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"stringTable\", \"string_table\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.StringTable = append(orig.StringTable, iter.ReadString())\n\t\t\t}\n\n\t\tcase \"attributeTable\", \"attribute_table\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.AttributeTable = append(orig.AttributeTable, NewKeyValueAndUnit())\n\t\t\t\torig.AttributeTable[len(orig.AttributeTable)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"stackTable\", \"stack_table\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.StackTable = append(orig.StackTable, NewStack())\n\t\t\t\torig.StackTable[len(orig.StackTable)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ProfilesDictionary) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.MappingTable {\n\t\tl = orig.MappingTable[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tfor i := range orig.LocationTable {\n\t\tl = orig.LocationTable[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tfor i := range orig.FunctionTable {\n\t\tl = orig.FunctionTable[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tfor i := range orig.LinkTable {\n\t\tl = orig.LinkTable[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tfor _, s := range orig.StringTable {\n\t\tl = len(s)\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tfor i := range orig.AttributeTable {\n\t\tl = orig.AttributeTable[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tfor i := range orig.StackTable {\n\t\tl = orig.StackTable[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ProfilesDictionary) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.MappingTable) - 1; i >= 0; i-- {\n\t\tl = orig.MappingTable[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\tfor i := len(orig.LocationTable) - 1; i >= 0; i-- {\n\t\tl = orig.LocationTable[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tfor i := len(orig.FunctionTable) - 1; i >= 0; i-- {\n\t\tl = orig.FunctionTable[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\tfor i := len(orig.LinkTable) - 1; i >= 0; i-- {\n\t\tl = orig.LinkTable[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x22\n\t}\n\tfor i := len(orig.StringTable) - 1; i >= 0; i-- {\n\t\tl = len(orig.StringTable[i])\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.StringTable[i])\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x2a\n\t}\n\tfor i := len(orig.AttributeTable) - 1; i >= 0; i-- {\n\t\tl = orig.AttributeTable[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x32\n\t}\n\tfor i := len(orig.StackTable) - 1; i >= 0; i-- {\n\t\tl = orig.StackTable[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x3a\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ProfilesDictionary) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field MappingTable\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.MappingTable = append(orig.MappingTable, NewMapping())\n\t\t\terr = orig.MappingTable[len(orig.MappingTable)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field LocationTable\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.LocationTable = append(orig.LocationTable, NewLocation())\n\t\t\terr = orig.LocationTable[len(orig.LocationTable)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field FunctionTable\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.FunctionTable = append(orig.FunctionTable, NewFunction())\n\t\t\terr = orig.FunctionTable[len(orig.FunctionTable)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 4:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field LinkTable\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.LinkTable = append(orig.LinkTable, NewLink())\n\t\t\terr = orig.LinkTable[len(orig.LinkTable)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 5:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field StringTable\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.StringTable = append(orig.StringTable, string(buf[startPos:pos]))\n\n\t\tcase 6:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field AttributeTable\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.AttributeTable = append(orig.AttributeTable, NewKeyValueAndUnit())\n\t\t\terr = orig.AttributeTable[len(orig.AttributeTable)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 7:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field StackTable\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.StackTable = append(orig.StackTable, NewStack())\n\t\t\terr = orig.StackTable[len(orig.StackTable)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestProfilesDictionary() *ProfilesDictionary {\n\torig := NewProfilesDictionary()\n\torig.MappingTable = []*Mapping{{}, GenTestMapping()}\n\torig.LocationTable = []*Location{{}, GenTestLocation()}\n\torig.FunctionTable = []*Function{{}, GenTestFunction()}\n\torig.LinkTable = []*Link{{}, GenTestLink()}\n\torig.StringTable = []string{\"\", \"test_stringtable\"}\n\torig.AttributeTable = []*KeyValueAndUnit{{}, GenTestKeyValueAndUnit()}\n\torig.StackTable = []*Stack{{}, GenTestStack()}\n\treturn orig\n}\n\nfunc GenTestProfilesDictionaryPtrSlice() []*ProfilesDictionary {\n\torig := make([]*ProfilesDictionary, 5)\n\torig[0] = NewProfilesDictionary()\n\torig[1] = GenTestProfilesDictionary()\n\torig[2] = NewProfilesDictionary()\n\torig[3] = GenTestProfilesDictionary()\n\torig[4] = NewProfilesDictionary()\n\treturn orig\n}\n\nfunc GenTestProfilesDictionarySlice() []ProfilesDictionary {\n\torig := make([]ProfilesDictionary, 5)\n\torig[1] = *GenTestProfilesDictionary()\n\torig[3] = *GenTestProfilesDictionary()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_profilesdictionary_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpprofiles \"go.opentelemetry.io/proto/slim/otlp/profiles/v1development\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyProfilesDictionary(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesProfilesDictionary() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewProfilesDictionary()\n\t\t\t\tCopyProfilesDictionary(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyProfilesDictionary(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyProfilesDictionarySlice(t *testing.T) {\n\tsrc := []ProfilesDictionary{}\n\tdest := []ProfilesDictionary{}\n\t// Test CopyTo empty\n\tdest = CopyProfilesDictionarySlice(dest, src)\n\tassert.Equal(t, []ProfilesDictionary{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestProfilesDictionarySlice()\n\tdest = CopyProfilesDictionarySlice(dest, src)\n\tassert.Equal(t, GenTestProfilesDictionarySlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyProfilesDictionarySlice(dest, src)\n\tassert.Equal(t, GenTestProfilesDictionarySlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyProfilesDictionarySlice(dest, []ProfilesDictionary{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyProfilesDictionarySlice(dest, src)\n\tassert.Equal(t, GenTestProfilesDictionarySlice(), dest)\n}\n\nfunc TestCopyProfilesDictionaryPtrSlice(t *testing.T) {\n\tsrc := []*ProfilesDictionary{}\n\tdest := []*ProfilesDictionary{}\n\t// Test CopyTo empty\n\tdest = CopyProfilesDictionaryPtrSlice(dest, src)\n\tassert.Equal(t, []*ProfilesDictionary{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestProfilesDictionaryPtrSlice()\n\tdest = CopyProfilesDictionaryPtrSlice(dest, src)\n\tassert.Equal(t, GenTestProfilesDictionaryPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyProfilesDictionaryPtrSlice(dest, src)\n\tassert.Equal(t, GenTestProfilesDictionaryPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyProfilesDictionaryPtrSlice(dest, []*ProfilesDictionary{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyProfilesDictionaryPtrSlice(dest, src)\n\tassert.Equal(t, GenTestProfilesDictionaryPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONProfilesDictionaryUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewProfilesDictionary()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewProfilesDictionary(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONProfilesDictionary(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesProfilesDictionary() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewProfilesDictionary()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteProfilesDictionary(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoProfilesDictionaryFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesProfilesDictionary() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewProfilesDictionary()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoProfilesDictionaryUnknown(t *testing.T) {\n\tdest := NewProfilesDictionary()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewProfilesDictionary(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoProfilesDictionary(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesProfilesDictionary() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewProfilesDictionary()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteProfilesDictionary(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufProfilesDictionary(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesProfilesDictionary() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpprofiles.ProfilesDictionary{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewProfilesDictionary()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesProfilesDictionary() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                  {0x02},\n\t\t\"MappingTable/wrong_wire_type\":   {0xc},\n\t\t\"MappingTable/missing_value\":     {0xa},\n\t\t\"LocationTable/wrong_wire_type\":  {0x14},\n\t\t\"LocationTable/missing_value\":    {0x12},\n\t\t\"FunctionTable/wrong_wire_type\":  {0x1c},\n\t\t\"FunctionTable/missing_value\":    {0x1a},\n\t\t\"LinkTable/wrong_wire_type\":      {0x24},\n\t\t\"LinkTable/missing_value\":        {0x22},\n\t\t\"StringTable/wrong_wire_type\":    {0x2c},\n\t\t\"StringTable/missing_value\":      {0x2a},\n\t\t\"AttributeTable/wrong_wire_type\": {0x34},\n\t\t\"AttributeTable/missing_value\":   {0x32},\n\t\t\"StackTable/wrong_wire_type\":     {0x3c},\n\t\t\"StackTable/missing_value\":       {0x3a},\n\t}\n}\n\nfunc genTestEncodingValuesProfilesDictionary() map[string]*ProfilesDictionary {\n\treturn map[string]*ProfilesDictionary{\n\t\t\"empty\":               NewProfilesDictionary(),\n\t\t\"MappingTable/test\":   {MappingTable: []*Mapping{{}, GenTestMapping()}},\n\t\t\"LocationTable/test\":  {LocationTable: []*Location{{}, GenTestLocation()}},\n\t\t\"FunctionTable/test\":  {FunctionTable: []*Function{{}, GenTestFunction()}},\n\t\t\"LinkTable/test\":      {LinkTable: []*Link{{}, GenTestLink()}},\n\t\t\"StringTable/test\":    {StringTable: []string{\"\", \"test_stringtable\"}},\n\t\t\"AttributeTable/test\": {AttributeTable: []*KeyValueAndUnit{{}, GenTestKeyValueAndUnit()}},\n\t\t\"StackTable/test\":     {StackTable: []*Stack{{}, GenTestStack()}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_profilesrequest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\ntype ProfilesRequest struct {\n\tRequestContext *RequestContext\n\tProfilesData   ProfilesData\n\tFormatVersion  uint32\n}\n\nvar (\n\tprotoPoolProfilesRequest = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ProfilesRequest{}\n\t\t},\n\t}\n)\n\nfunc NewProfilesRequest() *ProfilesRequest {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ProfilesRequest{}\n\t}\n\treturn protoPoolProfilesRequest.Get().(*ProfilesRequest)\n}\n\nfunc DeleteProfilesRequest(orig *ProfilesRequest, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteRequestContext(orig.RequestContext, true)\n\tDeleteProfilesData(&orig.ProfilesData, false)\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolProfilesRequest.Put(orig)\n\t}\n}\n\nfunc CopyProfilesRequest(dest, src *ProfilesRequest) *ProfilesRequest {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewProfilesRequest()\n\t}\n\tdest.RequestContext = CopyRequestContext(dest.RequestContext, src.RequestContext)\n\n\tCopyProfilesData(&dest.ProfilesData, &src.ProfilesData)\n\n\tdest.FormatVersion = src.FormatVersion\n\n\treturn dest\n}\n\nfunc CopyProfilesRequestSlice(dest, src []ProfilesRequest) []ProfilesRequest {\n\tvar newDest []ProfilesRequest\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ProfilesRequest, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteProfilesRequest(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyProfilesRequest(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyProfilesRequestPtrSlice(dest, src []*ProfilesRequest) []*ProfilesRequest {\n\tvar newDest []*ProfilesRequest\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ProfilesRequest, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewProfilesRequest()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteProfilesRequest(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewProfilesRequest()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyProfilesRequest(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ProfilesRequest) Reset() {\n\t*orig = ProfilesRequest{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ProfilesRequest) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.RequestContext != nil {\n\t\tdest.WriteObjectField(\"requestContext\")\n\t\torig.RequestContext.MarshalJSON(dest)\n\t}\n\tdest.WriteObjectField(\"profilesData\")\n\torig.ProfilesData.MarshalJSON(dest)\n\tif orig.FormatVersion != uint32(0) {\n\t\tdest.WriteObjectField(\"formatVersion\")\n\t\tdest.WriteUint32(orig.FormatVersion)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ProfilesRequest) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"requestContext\", \"request_context\":\n\t\t\torig.RequestContext = NewRequestContext()\n\t\t\torig.RequestContext.UnmarshalJSON(iter)\n\t\tcase \"profilesData\", \"profiles_data\":\n\n\t\t\torig.ProfilesData.UnmarshalJSON(iter)\n\t\tcase \"formatVersion\", \"format_version\":\n\t\t\torig.FormatVersion = iter.ReadUint32()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ProfilesRequest) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.RequestContext != nil {\n\t\tl = orig.RequestContext.SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tl = orig.ProfilesData.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tif orig.FormatVersion != uint32(0) {\n\t\tn += 5\n\t}\n\treturn n\n}\n\nfunc (orig *ProfilesRequest) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.RequestContext != nil {\n\t\tl = orig.RequestContext.MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tl = orig.ProfilesData.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x1a\n\n\tif orig.FormatVersion != uint32(0) {\n\t\tpos -= 4\n\t\tbinary.LittleEndian.PutUint32(buf[pos:], uint32(orig.FormatVersion))\n\t\tpos--\n\t\tbuf[pos] = 0xd\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ProfilesRequest) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field RequestContext\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\torig.RequestContext = NewRequestContext()\n\t\t\terr = orig.RequestContext.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ProfilesData\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.ProfilesData.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeI32 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field FormatVersion\", wireType)\n\t\t\t}\n\t\t\tvar num uint32\n\t\t\tnum, pos, err = proto.ConsumeI32(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.FormatVersion = uint32(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestProfilesRequest() *ProfilesRequest {\n\torig := NewProfilesRequest()\n\torig.RequestContext = GenTestRequestContext()\n\torig.ProfilesData = *GenTestProfilesData()\n\torig.FormatVersion = uint32(13)\n\treturn orig\n}\n\nfunc GenTestProfilesRequestPtrSlice() []*ProfilesRequest {\n\torig := make([]*ProfilesRequest, 5)\n\torig[0] = NewProfilesRequest()\n\torig[1] = GenTestProfilesRequest()\n\torig[2] = NewProfilesRequest()\n\torig[3] = GenTestProfilesRequest()\n\torig[4] = NewProfilesRequest()\n\treturn orig\n}\n\nfunc GenTestProfilesRequestSlice() []ProfilesRequest {\n\torig := make([]ProfilesRequest, 5)\n\torig[1] = *GenTestProfilesRequest()\n\torig[3] = *GenTestProfilesRequest()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_profilesrequest_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/protobuf/proto\"\n\t\"google.golang.org/protobuf/types/known/emptypb\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyProfilesRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesProfilesRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewProfilesRequest()\n\t\t\t\tCopyProfilesRequest(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyProfilesRequest(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyProfilesRequestSlice(t *testing.T) {\n\tsrc := []ProfilesRequest{}\n\tdest := []ProfilesRequest{}\n\t// Test CopyTo empty\n\tdest = CopyProfilesRequestSlice(dest, src)\n\tassert.Equal(t, []ProfilesRequest{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestProfilesRequestSlice()\n\tdest = CopyProfilesRequestSlice(dest, src)\n\tassert.Equal(t, GenTestProfilesRequestSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyProfilesRequestSlice(dest, src)\n\tassert.Equal(t, GenTestProfilesRequestSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyProfilesRequestSlice(dest, []ProfilesRequest{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyProfilesRequestSlice(dest, src)\n\tassert.Equal(t, GenTestProfilesRequestSlice(), dest)\n}\n\nfunc TestCopyProfilesRequestPtrSlice(t *testing.T) {\n\tsrc := []*ProfilesRequest{}\n\tdest := []*ProfilesRequest{}\n\t// Test CopyTo empty\n\tdest = CopyProfilesRequestPtrSlice(dest, src)\n\tassert.Equal(t, []*ProfilesRequest{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestProfilesRequestPtrSlice()\n\tdest = CopyProfilesRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestProfilesRequestPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyProfilesRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestProfilesRequestPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyProfilesRequestPtrSlice(dest, []*ProfilesRequest{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyProfilesRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestProfilesRequestPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONProfilesRequestUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewProfilesRequest()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewProfilesRequest(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONProfilesRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesProfilesRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewProfilesRequest()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteProfilesRequest(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoProfilesRequestFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesProfilesRequest() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewProfilesRequest()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoProfilesRequestUnknown(t *testing.T) {\n\tdest := NewProfilesRequest()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewProfilesRequest(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoProfilesRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesProfilesRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewProfilesRequest()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteProfilesRequest(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufProfilesRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesProfilesRequest() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &emptypb.Empty{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewProfilesRequest()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesProfilesRequest() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                  {0x02},\n\t\t\"RequestContext/wrong_wire_type\": {0x14},\n\t\t\"RequestContext/missing_value\":   {0x12},\n\t\t\"ProfilesData/wrong_wire_type\":   {0x1c},\n\t\t\"ProfilesData/missing_value\":     {0x1a},\n\t\t\"FormatVersion/wrong_wire_type\":  {0xc},\n\t\t\"FormatVersion/missing_value\":    {0xd},\n\t}\n}\n\nfunc genTestEncodingValuesProfilesRequest() map[string]*ProfilesRequest {\n\treturn map[string]*ProfilesRequest{\n\t\t\"empty\":               NewProfilesRequest(),\n\t\t\"RequestContext/test\": {RequestContext: GenTestRequestContext()},\n\t\t\"ProfilesData/test\":   {ProfilesData: *GenTestProfilesData()},\n\t\t\"FormatVersion/test\":  {FormatVersion: uint32(13)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_requestcontext.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\nfunc (m *RequestContext) GetClientAddress() any {\n\tif m != nil {\n\t\treturn m.ClientAddress\n\t}\n\treturn nil\n}\n\ntype RequestContext_IP struct {\n\tIP *IPAddr\n}\n\nfunc (m *RequestContext) GetIP() *IPAddr {\n\tif v, ok := m.GetClientAddress().(*RequestContext_IP); ok {\n\t\treturn v.IP\n\t}\n\treturn nil\n}\n\ntype RequestContext_TCP struct {\n\tTCP *TCPAddr\n}\n\nfunc (m *RequestContext) GetTCP() *TCPAddr {\n\tif v, ok := m.GetClientAddress().(*RequestContext_TCP); ok {\n\t\treturn v.TCP\n\t}\n\treturn nil\n}\n\ntype RequestContext_UDP struct {\n\tUDP *UDPAddr\n}\n\nfunc (m *RequestContext) GetUDP() *UDPAddr {\n\tif v, ok := m.GetClientAddress().(*RequestContext_UDP); ok {\n\t\treturn v.UDP\n\t}\n\treturn nil\n}\n\ntype RequestContext_Unix struct {\n\tUnix *UnixAddr\n}\n\nfunc (m *RequestContext) GetUnix() *UnixAddr {\n\tif v, ok := m.GetClientAddress().(*RequestContext_Unix); ok {\n\t\treturn v.Unix\n\t}\n\treturn nil\n}\n\ntype RequestContext struct {\n\tClientAddress  any\n\tSpanContext    *SpanContext\n\tClientMetadata []KeyValue\n}\n\nvar (\n\tprotoPoolRequestContext = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &RequestContext{}\n\t\t},\n\t}\n\n\tProtoPoolRequestContext_IP = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &RequestContext_IP{}\n\t\t},\n\t}\n\n\tProtoPoolRequestContext_TCP = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &RequestContext_TCP{}\n\t\t},\n\t}\n\n\tProtoPoolRequestContext_UDP = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &RequestContext_UDP{}\n\t\t},\n\t}\n\n\tProtoPoolRequestContext_Unix = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &RequestContext_Unix{}\n\t\t},\n\t}\n)\n\nfunc NewRequestContext() *RequestContext {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &RequestContext{}\n\t}\n\treturn protoPoolRequestContext.Get().(*RequestContext)\n}\n\nfunc DeleteRequestContext(orig *RequestContext, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteSpanContext(orig.SpanContext, true)\n\tfor i := range orig.ClientMetadata {\n\t\tDeleteKeyValue(&orig.ClientMetadata[i], false)\n\t}\n\tswitch ov := orig.ClientAddress.(type) {\n\tcase *RequestContext_IP:\n\t\tDeleteIPAddr(ov.IP, true)\n\t\tov.IP = nil\n\t\tProtoPoolRequestContext_IP.Put(ov)\n\tcase *RequestContext_TCP:\n\t\tDeleteTCPAddr(ov.TCP, true)\n\t\tov.TCP = nil\n\t\tProtoPoolRequestContext_TCP.Put(ov)\n\tcase *RequestContext_UDP:\n\t\tDeleteUDPAddr(ov.UDP, true)\n\t\tov.UDP = nil\n\t\tProtoPoolRequestContext_UDP.Put(ov)\n\tcase *RequestContext_Unix:\n\t\tDeleteUnixAddr(ov.Unix, true)\n\t\tov.Unix = nil\n\t\tProtoPoolRequestContext_Unix.Put(ov)\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolRequestContext.Put(orig)\n\t}\n}\n\nfunc CopyRequestContext(dest, src *RequestContext) *RequestContext {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewRequestContext()\n\t}\n\tdest.SpanContext = CopySpanContext(dest.SpanContext, src.SpanContext)\n\n\tdest.ClientMetadata = CopyKeyValueSlice(dest.ClientMetadata, src.ClientMetadata)\n\n\tswitch t := src.ClientAddress.(type) {\n\tcase *RequestContext_IP:\n\t\tvar ov *RequestContext_IP\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &RequestContext_IP{}\n\t\t} else {\n\t\t\tov = ProtoPoolRequestContext_IP.Get().(*RequestContext_IP)\n\t\t}\n\t\tov.IP = NewIPAddr()\n\t\tCopyIPAddr(ov.IP, t.IP)\n\t\tdest.ClientAddress = ov\n\n\tcase *RequestContext_TCP:\n\t\tvar ov *RequestContext_TCP\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &RequestContext_TCP{}\n\t\t} else {\n\t\t\tov = ProtoPoolRequestContext_TCP.Get().(*RequestContext_TCP)\n\t\t}\n\t\tov.TCP = NewTCPAddr()\n\t\tCopyTCPAddr(ov.TCP, t.TCP)\n\t\tdest.ClientAddress = ov\n\n\tcase *RequestContext_UDP:\n\t\tvar ov *RequestContext_UDP\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &RequestContext_UDP{}\n\t\t} else {\n\t\t\tov = ProtoPoolRequestContext_UDP.Get().(*RequestContext_UDP)\n\t\t}\n\t\tov.UDP = NewUDPAddr()\n\t\tCopyUDPAddr(ov.UDP, t.UDP)\n\t\tdest.ClientAddress = ov\n\n\tcase *RequestContext_Unix:\n\t\tvar ov *RequestContext_Unix\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &RequestContext_Unix{}\n\t\t} else {\n\t\t\tov = ProtoPoolRequestContext_Unix.Get().(*RequestContext_Unix)\n\t\t}\n\t\tov.Unix = NewUnixAddr()\n\t\tCopyUnixAddr(ov.Unix, t.Unix)\n\t\tdest.ClientAddress = ov\n\n\tdefault:\n\t\tdest.ClientAddress = nil\n\t}\n\n\treturn dest\n}\n\nfunc CopyRequestContextSlice(dest, src []RequestContext) []RequestContext {\n\tvar newDest []RequestContext\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]RequestContext, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteRequestContext(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyRequestContext(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyRequestContextPtrSlice(dest, src []*RequestContext) []*RequestContext {\n\tvar newDest []*RequestContext\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*RequestContext, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewRequestContext()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteRequestContext(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewRequestContext()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyRequestContext(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *RequestContext) Reset() {\n\t*orig = RequestContext{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *RequestContext) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.SpanContext != nil {\n\t\tdest.WriteObjectField(\"spanContext\")\n\t\torig.SpanContext.MarshalJSON(dest)\n\t}\n\tif len(orig.ClientMetadata) > 0 {\n\t\tdest.WriteObjectField(\"clientMetadata\")\n\t\tdest.WriteArrayStart()\n\t\torig.ClientMetadata[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.ClientMetadata); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.ClientMetadata[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tswitch orig := orig.ClientAddress.(type) {\n\tcase *RequestContext_IP:\n\t\tif orig.IP != nil {\n\t\t\tdest.WriteObjectField(\"iP\")\n\t\t\torig.IP.MarshalJSON(dest)\n\t\t}\n\tcase *RequestContext_TCP:\n\t\tif orig.TCP != nil {\n\t\t\tdest.WriteObjectField(\"tCP\")\n\t\t\torig.TCP.MarshalJSON(dest)\n\t\t}\n\tcase *RequestContext_UDP:\n\t\tif orig.UDP != nil {\n\t\t\tdest.WriteObjectField(\"uDP\")\n\t\t\torig.UDP.MarshalJSON(dest)\n\t\t}\n\tcase *RequestContext_Unix:\n\t\tif orig.Unix != nil {\n\t\t\tdest.WriteObjectField(\"unix\")\n\t\t\torig.Unix.MarshalJSON(dest)\n\t\t}\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *RequestContext) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"spanContext\", \"span_context\":\n\t\t\torig.SpanContext = NewSpanContext()\n\t\t\torig.SpanContext.UnmarshalJSON(iter)\n\t\tcase \"clientMetadata\", \"client_metadata\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.ClientMetadata = append(orig.ClientMetadata, KeyValue{})\n\t\t\t\torig.ClientMetadata[len(orig.ClientMetadata)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"iP\":\n\t\t\t{\n\t\t\t\tvar ov *RequestContext_IP\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &RequestContext_IP{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolRequestContext_IP.Get().(*RequestContext_IP)\n\t\t\t\t}\n\t\t\t\tov.IP = NewIPAddr()\n\t\t\t\tov.IP.UnmarshalJSON(iter)\n\t\t\t\torig.ClientAddress = ov\n\t\t\t}\n\t\tcase \"tCP\":\n\t\t\t{\n\t\t\t\tvar ov *RequestContext_TCP\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &RequestContext_TCP{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolRequestContext_TCP.Get().(*RequestContext_TCP)\n\t\t\t\t}\n\t\t\t\tov.TCP = NewTCPAddr()\n\t\t\t\tov.TCP.UnmarshalJSON(iter)\n\t\t\t\torig.ClientAddress = ov\n\t\t\t}\n\t\tcase \"uDP\":\n\t\t\t{\n\t\t\t\tvar ov *RequestContext_UDP\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &RequestContext_UDP{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolRequestContext_UDP.Get().(*RequestContext_UDP)\n\t\t\t\t}\n\t\t\t\tov.UDP = NewUDPAddr()\n\t\t\t\tov.UDP.UnmarshalJSON(iter)\n\t\t\t\torig.ClientAddress = ov\n\t\t\t}\n\t\tcase \"unix\":\n\t\t\t{\n\t\t\t\tvar ov *RequestContext_Unix\n\t\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\t\tov = &RequestContext_Unix{}\n\t\t\t\t} else {\n\t\t\t\t\tov = ProtoPoolRequestContext_Unix.Get().(*RequestContext_Unix)\n\t\t\t\t}\n\t\t\t\tov.Unix = NewUnixAddr()\n\t\t\t\tov.Unix.UnmarshalJSON(iter)\n\t\t\t\torig.ClientAddress = ov\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *RequestContext) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.SpanContext != nil {\n\t\tl = orig.SpanContext.SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tfor i := range orig.ClientMetadata {\n\t\tl = orig.ClientMetadata[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tswitch orig := orig.ClientAddress.(type) {\n\tcase nil:\n\t\t_ = orig\n\t\tbreak\n\tcase *RequestContext_IP:\n\t\tif orig.IP != nil {\n\t\t\tl = orig.IP.SizeProto()\n\t\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t\t}\n\tcase *RequestContext_TCP:\n\t\tif orig.TCP != nil {\n\t\t\tl = orig.TCP.SizeProto()\n\t\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t\t}\n\tcase *RequestContext_UDP:\n\t\tif orig.UDP != nil {\n\t\t\tl = orig.UDP.SizeProto()\n\t\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t\t}\n\tcase *RequestContext_Unix:\n\t\tif orig.Unix != nil {\n\t\t\tl = orig.Unix.SizeProto()\n\t\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t\t}\n\t}\n\treturn n\n}\n\nfunc (orig *RequestContext) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.SpanContext != nil {\n\t\tl = orig.SpanContext.MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\tfor i := len(orig.ClientMetadata) - 1; i >= 0; i-- {\n\t\tl = orig.ClientMetadata[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tswitch orig := orig.ClientAddress.(type) {\n\tcase *RequestContext_IP:\n\t\tif orig.IP != nil {\n\t\t\tl = orig.IP.MarshalProto(buf[:pos])\n\t\t\tpos -= l\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\t\tpos--\n\t\t\tbuf[pos] = 0x1a\n\t\t}\n\tcase *RequestContext_TCP:\n\t\tif orig.TCP != nil {\n\t\t\tl = orig.TCP.MarshalProto(buf[:pos])\n\t\t\tpos -= l\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\t\tpos--\n\t\t\tbuf[pos] = 0x22\n\t\t}\n\tcase *RequestContext_UDP:\n\t\tif orig.UDP != nil {\n\t\t\tl = orig.UDP.MarshalProto(buf[:pos])\n\t\t\tpos -= l\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\t\tpos--\n\t\t\tbuf[pos] = 0x2a\n\t\t}\n\tcase *RequestContext_Unix:\n\t\tif orig.Unix != nil {\n\t\t\tl = orig.Unix.MarshalProto(buf[:pos])\n\t\t\tpos -= l\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\t\tpos--\n\t\t\tbuf[pos] = 0x32\n\t\t}\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *RequestContext) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SpanContext\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\torig.SpanContext = NewSpanContext()\n\t\t\terr = orig.SpanContext.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ClientMetadata\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.ClientMetadata = append(orig.ClientMetadata, KeyValue{})\n\t\t\terr = orig.ClientMetadata[len(orig.ClientMetadata)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field IP\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tvar ov *RequestContext_IP\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &RequestContext_IP{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolRequestContext_IP.Get().(*RequestContext_IP)\n\t\t\t}\n\t\t\tov.IP = NewIPAddr()\n\t\t\terr = ov.IP.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.ClientAddress = ov\n\n\t\tcase 4:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TCP\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tvar ov *RequestContext_TCP\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &RequestContext_TCP{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolRequestContext_TCP.Get().(*RequestContext_TCP)\n\t\t\t}\n\t\t\tov.TCP = NewTCPAddr()\n\t\t\terr = ov.TCP.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.ClientAddress = ov\n\n\t\tcase 5:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field UDP\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tvar ov *RequestContext_UDP\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &RequestContext_UDP{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolRequestContext_UDP.Get().(*RequestContext_UDP)\n\t\t\t}\n\t\t\tov.UDP = NewUDPAddr()\n\t\t\terr = ov.UDP.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.ClientAddress = ov\n\n\t\tcase 6:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Unix\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tvar ov *RequestContext_Unix\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &RequestContext_Unix{}\n\t\t\t} else {\n\t\t\t\tov = ProtoPoolRequestContext_Unix.Get().(*RequestContext_Unix)\n\t\t\t}\n\t\t\tov.Unix = NewUnixAddr()\n\t\t\terr = ov.Unix.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.ClientAddress = ov\n\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestRequestContext() *RequestContext {\n\torig := NewRequestContext()\n\torig.SpanContext = GenTestSpanContext()\n\torig.ClientMetadata = []KeyValue{{}, *GenTestKeyValue()}\n\torig.ClientAddress = &RequestContext_IP{IP: GenTestIPAddr()}\n\treturn orig\n}\n\nfunc GenTestRequestContextPtrSlice() []*RequestContext {\n\torig := make([]*RequestContext, 5)\n\torig[0] = NewRequestContext()\n\torig[1] = GenTestRequestContext()\n\torig[2] = NewRequestContext()\n\torig[3] = GenTestRequestContext()\n\torig[4] = NewRequestContext()\n\treturn orig\n}\n\nfunc GenTestRequestContextSlice() []RequestContext {\n\torig := make([]RequestContext, 5)\n\torig[1] = *GenTestRequestContext()\n\torig[3] = *GenTestRequestContext()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_requestcontext_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/protobuf/proto\"\n\t\"google.golang.org/protobuf/types/known/emptypb\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyRequestContext(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesRequestContext() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewRequestContext()\n\t\t\t\tCopyRequestContext(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyRequestContext(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyRequestContextSlice(t *testing.T) {\n\tsrc := []RequestContext{}\n\tdest := []RequestContext{}\n\t// Test CopyTo empty\n\tdest = CopyRequestContextSlice(dest, src)\n\tassert.Equal(t, []RequestContext{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestRequestContextSlice()\n\tdest = CopyRequestContextSlice(dest, src)\n\tassert.Equal(t, GenTestRequestContextSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyRequestContextSlice(dest, src)\n\tassert.Equal(t, GenTestRequestContextSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyRequestContextSlice(dest, []RequestContext{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyRequestContextSlice(dest, src)\n\tassert.Equal(t, GenTestRequestContextSlice(), dest)\n}\n\nfunc TestCopyRequestContextPtrSlice(t *testing.T) {\n\tsrc := []*RequestContext{}\n\tdest := []*RequestContext{}\n\t// Test CopyTo empty\n\tdest = CopyRequestContextPtrSlice(dest, src)\n\tassert.Equal(t, []*RequestContext{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestRequestContextPtrSlice()\n\tdest = CopyRequestContextPtrSlice(dest, src)\n\tassert.Equal(t, GenTestRequestContextPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyRequestContextPtrSlice(dest, src)\n\tassert.Equal(t, GenTestRequestContextPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyRequestContextPtrSlice(dest, []*RequestContext{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyRequestContextPtrSlice(dest, src)\n\tassert.Equal(t, GenTestRequestContextPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONRequestContextUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewRequestContext()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewRequestContext(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONRequestContext(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesRequestContext() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewRequestContext()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteRequestContext(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoRequestContextFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesRequestContext() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewRequestContext()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoRequestContextUnknown(t *testing.T) {\n\tdest := NewRequestContext()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewRequestContext(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoRequestContext(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesRequestContext() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewRequestContext()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteRequestContext(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufRequestContext(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesRequestContext() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &emptypb.Empty{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewRequestContext()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesRequestContext() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                  {0x02},\n\t\t\"SpanContext/wrong_wire_type\":    {0xc},\n\t\t\"SpanContext/missing_value\":      {0xa},\n\t\t\"ClientMetadata/wrong_wire_type\": {0x14},\n\t\t\"ClientMetadata/missing_value\":   {0x12},\n\n\t\t\"IP/wrong_wire_type\":   {0x1c},\n\t\t\"IP/missing_value\":     {0x1a},\n\t\t\"TCP/wrong_wire_type\":  {0x24},\n\t\t\"TCP/missing_value\":    {0x22},\n\t\t\"UDP/wrong_wire_type\":  {0x2c},\n\t\t\"UDP/missing_value\":    {0x2a},\n\t\t\"Unix/wrong_wire_type\": {0x34},\n\t\t\"Unix/missing_value\":   {0x32},\n\t}\n}\n\nfunc genTestEncodingValuesRequestContext() map[string]*RequestContext {\n\treturn map[string]*RequestContext{\n\t\t\"empty\":               NewRequestContext(),\n\t\t\"SpanContext/test\":    {SpanContext: GenTestSpanContext()},\n\t\t\"ClientMetadata/test\": {ClientMetadata: []KeyValue{{}, *GenTestKeyValue()}},\n\t\t\"IP/default\":          {ClientAddress: &RequestContext_IP{IP: &IPAddr{}}},\n\t\t\"IP/test\":             {ClientAddress: &RequestContext_IP{IP: GenTestIPAddr()}}, \"TCP/default\": {ClientAddress: &RequestContext_TCP{TCP: &TCPAddr{}}},\n\t\t\"TCP/test\": {ClientAddress: &RequestContext_TCP{TCP: GenTestTCPAddr()}}, \"UDP/default\": {ClientAddress: &RequestContext_UDP{UDP: &UDPAddr{}}},\n\t\t\"UDP/test\": {ClientAddress: &RequestContext_UDP{UDP: GenTestUDPAddr()}}, \"Unix/default\": {ClientAddress: &RequestContext_Unix{Unix: &UnixAddr{}}},\n\t\t\"Unix/test\": {ClientAddress: &RequestContext_Unix{Unix: GenTestUnixAddr()}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_resource.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Resource is a message representing the resource information.\ntype Resource struct {\n\tAttributes             []KeyValue\n\tEntityRefs             []*EntityRef\n\tDroppedAttributesCount uint32\n}\n\nvar (\n\tprotoPoolResource = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Resource{}\n\t\t},\n\t}\n)\n\nfunc NewResource() *Resource {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &Resource{}\n\t}\n\treturn protoPoolResource.Get().(*Resource)\n}\n\nfunc DeleteResource(orig *Resource, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.Attributes {\n\t\tDeleteKeyValue(&orig.Attributes[i], false)\n\t}\n\n\tfor i := range orig.EntityRefs {\n\t\tDeleteEntityRef(orig.EntityRefs[i], true)\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolResource.Put(orig)\n\t}\n}\n\nfunc CopyResource(dest, src *Resource) *Resource {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewResource()\n\t}\n\tdest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)\n\n\tdest.DroppedAttributesCount = src.DroppedAttributesCount\n\tdest.EntityRefs = CopyEntityRefPtrSlice(dest.EntityRefs, src.EntityRefs)\n\n\treturn dest\n}\n\nfunc CopyResourceSlice(dest, src []Resource) []Resource {\n\tvar newDest []Resource\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]Resource, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteResource(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyResource(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyResourcePtrSlice(dest, src []*Resource) []*Resource {\n\tvar newDest []*Resource\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*Resource, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewResource()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteResource(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewResource()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyResource(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *Resource) Reset() {\n\t*orig = Resource{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *Resource) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.Attributes) > 0 {\n\t\tdest.WriteObjectField(\"attributes\")\n\t\tdest.WriteArrayStart()\n\t\torig.Attributes[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Attributes); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Attributes[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tdest.WriteObjectField(\"droppedAttributesCount\")\n\t\tdest.WriteUint32(orig.DroppedAttributesCount)\n\t}\n\tif len(orig.EntityRefs) > 0 {\n\t\tdest.WriteObjectField(\"entityRefs\")\n\t\tdest.WriteArrayStart()\n\t\torig.EntityRefs[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.EntityRefs); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.EntityRefs[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *Resource) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"attributes\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\t\torig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"droppedAttributesCount\", \"dropped_attributes_count\":\n\t\t\torig.DroppedAttributesCount = iter.ReadUint32()\n\t\tcase \"entityRefs\", \"entity_refs\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.EntityRefs = append(orig.EntityRefs, NewEntityRef())\n\t\t\t\torig.EntityRefs[len(orig.EntityRefs)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *Resource) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.Attributes {\n\t\tl = orig.Attributes[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.DroppedAttributesCount))\n\t}\n\tfor i := range orig.EntityRefs {\n\t\tl = orig.EntityRefs[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *Resource) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.Attributes) - 1; i >= 0; i-- {\n\t\tl = orig.Attributes[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedAttributesCount))\n\t\tpos--\n\t\tbuf[pos] = 0x10\n\t}\n\tfor i := len(orig.EntityRefs) - 1; i >= 0; i-- {\n\t\tl = orig.EntityRefs[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *Resource) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Attributes\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\terr = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DroppedAttributesCount\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.DroppedAttributesCount = uint32(num)\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field EntityRefs\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.EntityRefs = append(orig.EntityRefs, NewEntityRef())\n\t\t\terr = orig.EntityRefs[len(orig.EntityRefs)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestResource() *Resource {\n\torig := NewResource()\n\torig.Attributes = []KeyValue{{}, *GenTestKeyValue()}\n\torig.DroppedAttributesCount = uint32(13)\n\torig.EntityRefs = []*EntityRef{{}, GenTestEntityRef()}\n\treturn orig\n}\n\nfunc GenTestResourcePtrSlice() []*Resource {\n\torig := make([]*Resource, 5)\n\torig[0] = NewResource()\n\torig[1] = GenTestResource()\n\torig[2] = NewResource()\n\torig[3] = GenTestResource()\n\torig[4] = NewResource()\n\treturn orig\n}\n\nfunc GenTestResourceSlice() []Resource {\n\torig := make([]Resource, 5)\n\torig[1] = *GenTestResource()\n\torig[3] = *GenTestResource()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_resource_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpresource \"go.opentelemetry.io/proto/slim/otlp/resource/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyResource(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResource() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewResource()\n\t\t\t\tCopyResource(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyResource(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyResourceSlice(t *testing.T) {\n\tsrc := []Resource{}\n\tdest := []Resource{}\n\t// Test CopyTo empty\n\tdest = CopyResourceSlice(dest, src)\n\tassert.Equal(t, []Resource{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestResourceSlice()\n\tdest = CopyResourceSlice(dest, src)\n\tassert.Equal(t, GenTestResourceSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyResourceSlice(dest, src)\n\tassert.Equal(t, GenTestResourceSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyResourceSlice(dest, []Resource{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyResourceSlice(dest, src)\n\tassert.Equal(t, GenTestResourceSlice(), dest)\n}\n\nfunc TestCopyResourcePtrSlice(t *testing.T) {\n\tsrc := []*Resource{}\n\tdest := []*Resource{}\n\t// Test CopyTo empty\n\tdest = CopyResourcePtrSlice(dest, src)\n\tassert.Equal(t, []*Resource{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestResourcePtrSlice()\n\tdest = CopyResourcePtrSlice(dest, src)\n\tassert.Equal(t, GenTestResourcePtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyResourcePtrSlice(dest, src)\n\tassert.Equal(t, GenTestResourcePtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyResourcePtrSlice(dest, []*Resource{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyResourcePtrSlice(dest, src)\n\tassert.Equal(t, GenTestResourcePtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONResourceUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewResource()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewResource(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONResource(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResource() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewResource()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteResource(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoResourceFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesResource() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewResource()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoResourceUnknown(t *testing.T) {\n\tdest := NewResource()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewResource(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoResource(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResource() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewResource()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteResource(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufResource(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResource() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpresource.Resource{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewResource()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesResource() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                          {0x02},\n\t\t\"Attributes/wrong_wire_type\":             {0xc},\n\t\t\"Attributes/missing_value\":               {0xa},\n\t\t\"DroppedAttributesCount/wrong_wire_type\": {0x14},\n\t\t\"DroppedAttributesCount/missing_value\":   {0x10},\n\t\t\"EntityRefs/wrong_wire_type\":             {0x1c},\n\t\t\"EntityRefs/missing_value\":               {0x1a},\n\t}\n}\n\nfunc genTestEncodingValuesResource() map[string]*Resource {\n\treturn map[string]*Resource{\n\t\t\"empty\":                       NewResource(),\n\t\t\"Attributes/test\":             {Attributes: []KeyValue{{}, *GenTestKeyValue()}},\n\t\t\"DroppedAttributesCount/test\": {DroppedAttributesCount: uint32(13)},\n\t\t\"EntityRefs/test\":             {EntityRefs: []*EntityRef{{}, GenTestEntityRef()}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_resourcelogs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ResourceLogs is a collection of logs from a Resource.\ntype ResourceLogs struct {\n\tResource            Resource\n\tScopeLogs           []*ScopeLogs\n\tSchemaUrl           string\n\tDeprecatedScopeLogs []*ScopeLogs\n}\n\nvar (\n\tprotoPoolResourceLogs = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ResourceLogs{}\n\t\t},\n\t}\n)\n\nfunc NewResourceLogs() *ResourceLogs {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ResourceLogs{}\n\t}\n\treturn protoPoolResourceLogs.Get().(*ResourceLogs)\n}\n\nfunc DeleteResourceLogs(orig *ResourceLogs, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteResource(&orig.Resource, false)\n\tfor i := range orig.ScopeLogs {\n\t\tDeleteScopeLogs(orig.ScopeLogs[i], true)\n\t}\n\n\tfor i := range orig.DeprecatedScopeLogs {\n\t\tDeleteScopeLogs(orig.DeprecatedScopeLogs[i], true)\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolResourceLogs.Put(orig)\n\t}\n}\n\nfunc CopyResourceLogs(dest, src *ResourceLogs) *ResourceLogs {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewResourceLogs()\n\t}\n\tCopyResource(&dest.Resource, &src.Resource)\n\n\tdest.ScopeLogs = CopyScopeLogsPtrSlice(dest.ScopeLogs, src.ScopeLogs)\n\n\tdest.SchemaUrl = src.SchemaUrl\n\tdest.DeprecatedScopeLogs = CopyScopeLogsPtrSlice(dest.DeprecatedScopeLogs, src.DeprecatedScopeLogs)\n\n\treturn dest\n}\n\nfunc CopyResourceLogsSlice(dest, src []ResourceLogs) []ResourceLogs {\n\tvar newDest []ResourceLogs\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ResourceLogs, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteResourceLogs(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyResourceLogs(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyResourceLogsPtrSlice(dest, src []*ResourceLogs) []*ResourceLogs {\n\tvar newDest []*ResourceLogs\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ResourceLogs, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewResourceLogs()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteResourceLogs(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewResourceLogs()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyResourceLogs(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ResourceLogs) Reset() {\n\t*orig = ResourceLogs{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ResourceLogs) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tdest.WriteObjectField(\"resource\")\n\torig.Resource.MarshalJSON(dest)\n\tif len(orig.ScopeLogs) > 0 {\n\t\tdest.WriteObjectField(\"scopeLogs\")\n\t\tdest.WriteArrayStart()\n\t\torig.ScopeLogs[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.ScopeLogs); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.ScopeLogs[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.SchemaUrl != \"\" {\n\t\tdest.WriteObjectField(\"schemaUrl\")\n\t\tdest.WriteString(orig.SchemaUrl)\n\t}\n\tif len(orig.DeprecatedScopeLogs) > 0 {\n\t\tdest.WriteObjectField(\"deprecatedScopeLogs\")\n\t\tdest.WriteArrayStart()\n\t\torig.DeprecatedScopeLogs[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.DeprecatedScopeLogs); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.DeprecatedScopeLogs[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ResourceLogs) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"resource\":\n\n\t\t\torig.Resource.UnmarshalJSON(iter)\n\t\tcase \"scopeLogs\", \"scope_logs\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.ScopeLogs = append(orig.ScopeLogs, NewScopeLogs())\n\t\t\t\torig.ScopeLogs[len(orig.ScopeLogs)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"schemaUrl\", \"schema_url\":\n\t\t\torig.SchemaUrl = iter.ReadString()\n\t\tcase \"deprecatedScopeLogs\", \"deprecated_scope_logs\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.DeprecatedScopeLogs = append(orig.DeprecatedScopeLogs, NewScopeLogs())\n\t\t\t\torig.DeprecatedScopeLogs[len(orig.DeprecatedScopeLogs)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ResourceLogs) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tl = orig.Resource.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tfor i := range orig.ScopeLogs {\n\t\tl = orig.ScopeLogs[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tfor i := range orig.DeprecatedScopeLogs {\n\t\tl = orig.DeprecatedScopeLogs[i].SizeProto()\n\t\tn += 2 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ResourceLogs) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = orig.Resource.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0xa\n\n\tfor i := len(orig.ScopeLogs) - 1; i >= 0; i-- {\n\t\tl = orig.ScopeLogs[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.SchemaUrl)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\tfor i := len(orig.DeprecatedScopeLogs) - 1; i >= 0; i-- {\n\t\tl = orig.DeprecatedScopeLogs[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x3e\n\t\tpos--\n\t\tbuf[pos] = 0xc2\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ResourceLogs) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Resource\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.Resource.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ScopeLogs\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.ScopeLogs = append(orig.ScopeLogs, NewScopeLogs())\n\t\t\terr = orig.ScopeLogs[len(orig.ScopeLogs)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SchemaUrl\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.SchemaUrl = string(buf[startPos:pos])\n\n\t\tcase 1000:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DeprecatedScopeLogs\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.DeprecatedScopeLogs = append(orig.DeprecatedScopeLogs, NewScopeLogs())\n\t\t\terr = orig.DeprecatedScopeLogs[len(orig.DeprecatedScopeLogs)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestResourceLogs() *ResourceLogs {\n\torig := NewResourceLogs()\n\torig.Resource = *GenTestResource()\n\torig.ScopeLogs = []*ScopeLogs{{}, GenTestScopeLogs()}\n\torig.SchemaUrl = \"test_schemaurl\"\n\torig.DeprecatedScopeLogs = []*ScopeLogs{{}, GenTestScopeLogs()}\n\treturn orig\n}\n\nfunc GenTestResourceLogsPtrSlice() []*ResourceLogs {\n\torig := make([]*ResourceLogs, 5)\n\torig[0] = NewResourceLogs()\n\torig[1] = GenTestResourceLogs()\n\torig[2] = NewResourceLogs()\n\torig[3] = GenTestResourceLogs()\n\torig[4] = NewResourceLogs()\n\treturn orig\n}\n\nfunc GenTestResourceLogsSlice() []ResourceLogs {\n\torig := make([]ResourceLogs, 5)\n\torig[1] = *GenTestResourceLogs()\n\torig[3] = *GenTestResourceLogs()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_resourcelogs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlplogs \"go.opentelemetry.io/proto/slim/otlp/logs/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyResourceLogs(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResourceLogs() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewResourceLogs()\n\t\t\t\tCopyResourceLogs(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyResourceLogs(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyResourceLogsSlice(t *testing.T) {\n\tsrc := []ResourceLogs{}\n\tdest := []ResourceLogs{}\n\t// Test CopyTo empty\n\tdest = CopyResourceLogsSlice(dest, src)\n\tassert.Equal(t, []ResourceLogs{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestResourceLogsSlice()\n\tdest = CopyResourceLogsSlice(dest, src)\n\tassert.Equal(t, GenTestResourceLogsSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyResourceLogsSlice(dest, src)\n\tassert.Equal(t, GenTestResourceLogsSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyResourceLogsSlice(dest, []ResourceLogs{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyResourceLogsSlice(dest, src)\n\tassert.Equal(t, GenTestResourceLogsSlice(), dest)\n}\n\nfunc TestCopyResourceLogsPtrSlice(t *testing.T) {\n\tsrc := []*ResourceLogs{}\n\tdest := []*ResourceLogs{}\n\t// Test CopyTo empty\n\tdest = CopyResourceLogsPtrSlice(dest, src)\n\tassert.Equal(t, []*ResourceLogs{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestResourceLogsPtrSlice()\n\tdest = CopyResourceLogsPtrSlice(dest, src)\n\tassert.Equal(t, GenTestResourceLogsPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyResourceLogsPtrSlice(dest, src)\n\tassert.Equal(t, GenTestResourceLogsPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyResourceLogsPtrSlice(dest, []*ResourceLogs{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyResourceLogsPtrSlice(dest, src)\n\tassert.Equal(t, GenTestResourceLogsPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONResourceLogsUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewResourceLogs()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewResourceLogs(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONResourceLogs(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResourceLogs() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewResourceLogs()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteResourceLogs(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoResourceLogsFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesResourceLogs() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewResourceLogs()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoResourceLogsUnknown(t *testing.T) {\n\tdest := NewResourceLogs()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewResourceLogs(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoResourceLogs(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResourceLogs() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewResourceLogs()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteResourceLogs(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufResourceLogs(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResourceLogs() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlplogs.ResourceLogs{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewResourceLogs()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesResourceLogs() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                       {0x02},\n\t\t\"Resource/wrong_wire_type\":            {0xc},\n\t\t\"Resource/missing_value\":              {0xa},\n\t\t\"ScopeLogs/wrong_wire_type\":           {0x14},\n\t\t\"ScopeLogs/missing_value\":             {0x12},\n\t\t\"SchemaUrl/wrong_wire_type\":           {0x1c},\n\t\t\"SchemaUrl/missing_value\":             {0x1a},\n\t\t\"DeprecatedScopeLogs/wrong_wire_type\": {0xc4, 0x3e},\n\t\t\"DeprecatedScopeLogs/missing_value\":   {0xc2, 0x3e},\n\t}\n}\n\nfunc genTestEncodingValuesResourceLogs() map[string]*ResourceLogs {\n\treturn map[string]*ResourceLogs{\n\t\t\"empty\":                    NewResourceLogs(),\n\t\t\"Resource/test\":            {Resource: *GenTestResource()},\n\t\t\"ScopeLogs/test\":           {ScopeLogs: []*ScopeLogs{{}, GenTestScopeLogs()}},\n\t\t\"SchemaUrl/test\":           {SchemaUrl: \"test_schemaurl\"},\n\t\t\"DeprecatedScopeLogs/test\": {DeprecatedScopeLogs: []*ScopeLogs{{}, GenTestScopeLogs()}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_resourcemetrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ResourceMetrics is a collection of metrics from a Resource.\ntype ResourceMetrics struct {\n\tResource               Resource\n\tScopeMetrics           []*ScopeMetrics\n\tSchemaUrl              string\n\tDeprecatedScopeMetrics []*ScopeMetrics\n}\n\nvar (\n\tprotoPoolResourceMetrics = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ResourceMetrics{}\n\t\t},\n\t}\n)\n\nfunc NewResourceMetrics() *ResourceMetrics {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ResourceMetrics{}\n\t}\n\treturn protoPoolResourceMetrics.Get().(*ResourceMetrics)\n}\n\nfunc DeleteResourceMetrics(orig *ResourceMetrics, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteResource(&orig.Resource, false)\n\tfor i := range orig.ScopeMetrics {\n\t\tDeleteScopeMetrics(orig.ScopeMetrics[i], true)\n\t}\n\n\tfor i := range orig.DeprecatedScopeMetrics {\n\t\tDeleteScopeMetrics(orig.DeprecatedScopeMetrics[i], true)\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolResourceMetrics.Put(orig)\n\t}\n}\n\nfunc CopyResourceMetrics(dest, src *ResourceMetrics) *ResourceMetrics {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewResourceMetrics()\n\t}\n\tCopyResource(&dest.Resource, &src.Resource)\n\n\tdest.ScopeMetrics = CopyScopeMetricsPtrSlice(dest.ScopeMetrics, src.ScopeMetrics)\n\n\tdest.SchemaUrl = src.SchemaUrl\n\tdest.DeprecatedScopeMetrics = CopyScopeMetricsPtrSlice(dest.DeprecatedScopeMetrics, src.DeprecatedScopeMetrics)\n\n\treturn dest\n}\n\nfunc CopyResourceMetricsSlice(dest, src []ResourceMetrics) []ResourceMetrics {\n\tvar newDest []ResourceMetrics\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ResourceMetrics, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteResourceMetrics(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyResourceMetrics(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyResourceMetricsPtrSlice(dest, src []*ResourceMetrics) []*ResourceMetrics {\n\tvar newDest []*ResourceMetrics\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ResourceMetrics, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewResourceMetrics()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteResourceMetrics(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewResourceMetrics()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyResourceMetrics(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ResourceMetrics) Reset() {\n\t*orig = ResourceMetrics{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ResourceMetrics) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tdest.WriteObjectField(\"resource\")\n\torig.Resource.MarshalJSON(dest)\n\tif len(orig.ScopeMetrics) > 0 {\n\t\tdest.WriteObjectField(\"scopeMetrics\")\n\t\tdest.WriteArrayStart()\n\t\torig.ScopeMetrics[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.ScopeMetrics); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.ScopeMetrics[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.SchemaUrl != \"\" {\n\t\tdest.WriteObjectField(\"schemaUrl\")\n\t\tdest.WriteString(orig.SchemaUrl)\n\t}\n\tif len(orig.DeprecatedScopeMetrics) > 0 {\n\t\tdest.WriteObjectField(\"deprecatedScopeMetrics\")\n\t\tdest.WriteArrayStart()\n\t\torig.DeprecatedScopeMetrics[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.DeprecatedScopeMetrics); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.DeprecatedScopeMetrics[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ResourceMetrics) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"resource\":\n\n\t\t\torig.Resource.UnmarshalJSON(iter)\n\t\tcase \"scopeMetrics\", \"scope_metrics\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.ScopeMetrics = append(orig.ScopeMetrics, NewScopeMetrics())\n\t\t\t\torig.ScopeMetrics[len(orig.ScopeMetrics)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"schemaUrl\", \"schema_url\":\n\t\t\torig.SchemaUrl = iter.ReadString()\n\t\tcase \"deprecatedScopeMetrics\", \"deprecated_scope_metrics\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.DeprecatedScopeMetrics = append(orig.DeprecatedScopeMetrics, NewScopeMetrics())\n\t\t\t\torig.DeprecatedScopeMetrics[len(orig.DeprecatedScopeMetrics)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ResourceMetrics) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tl = orig.Resource.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tfor i := range orig.ScopeMetrics {\n\t\tl = orig.ScopeMetrics[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tfor i := range orig.DeprecatedScopeMetrics {\n\t\tl = orig.DeprecatedScopeMetrics[i].SizeProto()\n\t\tn += 2 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ResourceMetrics) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = orig.Resource.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0xa\n\n\tfor i := len(orig.ScopeMetrics) - 1; i >= 0; i-- {\n\t\tl = orig.ScopeMetrics[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.SchemaUrl)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\tfor i := len(orig.DeprecatedScopeMetrics) - 1; i >= 0; i-- {\n\t\tl = orig.DeprecatedScopeMetrics[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x3e\n\t\tpos--\n\t\tbuf[pos] = 0xc2\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ResourceMetrics) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Resource\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.Resource.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ScopeMetrics\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.ScopeMetrics = append(orig.ScopeMetrics, NewScopeMetrics())\n\t\t\terr = orig.ScopeMetrics[len(orig.ScopeMetrics)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SchemaUrl\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.SchemaUrl = string(buf[startPos:pos])\n\n\t\tcase 1000:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DeprecatedScopeMetrics\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.DeprecatedScopeMetrics = append(orig.DeprecatedScopeMetrics, NewScopeMetrics())\n\t\t\terr = orig.DeprecatedScopeMetrics[len(orig.DeprecatedScopeMetrics)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestResourceMetrics() *ResourceMetrics {\n\torig := NewResourceMetrics()\n\torig.Resource = *GenTestResource()\n\torig.ScopeMetrics = []*ScopeMetrics{{}, GenTestScopeMetrics()}\n\torig.SchemaUrl = \"test_schemaurl\"\n\torig.DeprecatedScopeMetrics = []*ScopeMetrics{{}, GenTestScopeMetrics()}\n\treturn orig\n}\n\nfunc GenTestResourceMetricsPtrSlice() []*ResourceMetrics {\n\torig := make([]*ResourceMetrics, 5)\n\torig[0] = NewResourceMetrics()\n\torig[1] = GenTestResourceMetrics()\n\torig[2] = NewResourceMetrics()\n\torig[3] = GenTestResourceMetrics()\n\torig[4] = NewResourceMetrics()\n\treturn orig\n}\n\nfunc GenTestResourceMetricsSlice() []ResourceMetrics {\n\torig := make([]ResourceMetrics, 5)\n\torig[1] = *GenTestResourceMetrics()\n\torig[3] = *GenTestResourceMetrics()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_resourcemetrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyResourceMetrics(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResourceMetrics() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewResourceMetrics()\n\t\t\t\tCopyResourceMetrics(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyResourceMetrics(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyResourceMetricsSlice(t *testing.T) {\n\tsrc := []ResourceMetrics{}\n\tdest := []ResourceMetrics{}\n\t// Test CopyTo empty\n\tdest = CopyResourceMetricsSlice(dest, src)\n\tassert.Equal(t, []ResourceMetrics{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestResourceMetricsSlice()\n\tdest = CopyResourceMetricsSlice(dest, src)\n\tassert.Equal(t, GenTestResourceMetricsSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyResourceMetricsSlice(dest, src)\n\tassert.Equal(t, GenTestResourceMetricsSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyResourceMetricsSlice(dest, []ResourceMetrics{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyResourceMetricsSlice(dest, src)\n\tassert.Equal(t, GenTestResourceMetricsSlice(), dest)\n}\n\nfunc TestCopyResourceMetricsPtrSlice(t *testing.T) {\n\tsrc := []*ResourceMetrics{}\n\tdest := []*ResourceMetrics{}\n\t// Test CopyTo empty\n\tdest = CopyResourceMetricsPtrSlice(dest, src)\n\tassert.Equal(t, []*ResourceMetrics{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestResourceMetricsPtrSlice()\n\tdest = CopyResourceMetricsPtrSlice(dest, src)\n\tassert.Equal(t, GenTestResourceMetricsPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyResourceMetricsPtrSlice(dest, src)\n\tassert.Equal(t, GenTestResourceMetricsPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyResourceMetricsPtrSlice(dest, []*ResourceMetrics{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyResourceMetricsPtrSlice(dest, src)\n\tassert.Equal(t, GenTestResourceMetricsPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONResourceMetricsUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewResourceMetrics()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewResourceMetrics(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONResourceMetrics(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResourceMetrics() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewResourceMetrics()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteResourceMetrics(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoResourceMetricsFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesResourceMetrics() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewResourceMetrics()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoResourceMetricsUnknown(t *testing.T) {\n\tdest := NewResourceMetrics()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewResourceMetrics(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoResourceMetrics(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResourceMetrics() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewResourceMetrics()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteResourceMetrics(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufResourceMetrics(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResourceMetrics() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpmetrics.ResourceMetrics{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewResourceMetrics()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesResourceMetrics() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                          {0x02},\n\t\t\"Resource/wrong_wire_type\":               {0xc},\n\t\t\"Resource/missing_value\":                 {0xa},\n\t\t\"ScopeMetrics/wrong_wire_type\":           {0x14},\n\t\t\"ScopeMetrics/missing_value\":             {0x12},\n\t\t\"SchemaUrl/wrong_wire_type\":              {0x1c},\n\t\t\"SchemaUrl/missing_value\":                {0x1a},\n\t\t\"DeprecatedScopeMetrics/wrong_wire_type\": {0xc4, 0x3e},\n\t\t\"DeprecatedScopeMetrics/missing_value\":   {0xc2, 0x3e},\n\t}\n}\n\nfunc genTestEncodingValuesResourceMetrics() map[string]*ResourceMetrics {\n\treturn map[string]*ResourceMetrics{\n\t\t\"empty\":                       NewResourceMetrics(),\n\t\t\"Resource/test\":               {Resource: *GenTestResource()},\n\t\t\"ScopeMetrics/test\":           {ScopeMetrics: []*ScopeMetrics{{}, GenTestScopeMetrics()}},\n\t\t\"SchemaUrl/test\":              {SchemaUrl: \"test_schemaurl\"},\n\t\t\"DeprecatedScopeMetrics/test\": {DeprecatedScopeMetrics: []*ScopeMetrics{{}, GenTestScopeMetrics()}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_resourceprofiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ResourceProfiles is a collection of profiles from a Resource.\ntype ResourceProfiles struct {\n\tSchemaUrl     string\n\tResource      Resource\n\tScopeProfiles []*ScopeProfiles\n}\n\nvar (\n\tprotoPoolResourceProfiles = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ResourceProfiles{}\n\t\t},\n\t}\n)\n\nfunc NewResourceProfiles() *ResourceProfiles {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ResourceProfiles{}\n\t}\n\treturn protoPoolResourceProfiles.Get().(*ResourceProfiles)\n}\n\nfunc DeleteResourceProfiles(orig *ResourceProfiles, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteResource(&orig.Resource, false)\n\tfor i := range orig.ScopeProfiles {\n\t\tDeleteScopeProfiles(orig.ScopeProfiles[i], true)\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolResourceProfiles.Put(orig)\n\t}\n}\n\nfunc CopyResourceProfiles(dest, src *ResourceProfiles) *ResourceProfiles {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewResourceProfiles()\n\t}\n\tCopyResource(&dest.Resource, &src.Resource)\n\n\tdest.ScopeProfiles = CopyScopeProfilesPtrSlice(dest.ScopeProfiles, src.ScopeProfiles)\n\n\tdest.SchemaUrl = src.SchemaUrl\n\n\treturn dest\n}\n\nfunc CopyResourceProfilesSlice(dest, src []ResourceProfiles) []ResourceProfiles {\n\tvar newDest []ResourceProfiles\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ResourceProfiles, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteResourceProfiles(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyResourceProfiles(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyResourceProfilesPtrSlice(dest, src []*ResourceProfiles) []*ResourceProfiles {\n\tvar newDest []*ResourceProfiles\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ResourceProfiles, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewResourceProfiles()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteResourceProfiles(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewResourceProfiles()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyResourceProfiles(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ResourceProfiles) Reset() {\n\t*orig = ResourceProfiles{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ResourceProfiles) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tdest.WriteObjectField(\"resource\")\n\torig.Resource.MarshalJSON(dest)\n\tif len(orig.ScopeProfiles) > 0 {\n\t\tdest.WriteObjectField(\"scopeProfiles\")\n\t\tdest.WriteArrayStart()\n\t\torig.ScopeProfiles[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.ScopeProfiles); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.ScopeProfiles[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.SchemaUrl != \"\" {\n\t\tdest.WriteObjectField(\"schemaUrl\")\n\t\tdest.WriteString(orig.SchemaUrl)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ResourceProfiles) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"resource\":\n\n\t\t\torig.Resource.UnmarshalJSON(iter)\n\t\tcase \"scopeProfiles\", \"scope_profiles\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.ScopeProfiles = append(orig.ScopeProfiles, NewScopeProfiles())\n\t\t\t\torig.ScopeProfiles[len(orig.ScopeProfiles)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"schemaUrl\", \"schema_url\":\n\t\t\torig.SchemaUrl = iter.ReadString()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ResourceProfiles) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tl = orig.Resource.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tfor i := range orig.ScopeProfiles {\n\t\tl = orig.ScopeProfiles[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ResourceProfiles) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = orig.Resource.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0xa\n\n\tfor i := len(orig.ScopeProfiles) - 1; i >= 0; i-- {\n\t\tl = orig.ScopeProfiles[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.SchemaUrl)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ResourceProfiles) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Resource\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.Resource.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ScopeProfiles\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.ScopeProfiles = append(orig.ScopeProfiles, NewScopeProfiles())\n\t\t\terr = orig.ScopeProfiles[len(orig.ScopeProfiles)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SchemaUrl\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.SchemaUrl = string(buf[startPos:pos])\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestResourceProfiles() *ResourceProfiles {\n\torig := NewResourceProfiles()\n\torig.Resource = *GenTestResource()\n\torig.ScopeProfiles = []*ScopeProfiles{{}, GenTestScopeProfiles()}\n\torig.SchemaUrl = \"test_schemaurl\"\n\treturn orig\n}\n\nfunc GenTestResourceProfilesPtrSlice() []*ResourceProfiles {\n\torig := make([]*ResourceProfiles, 5)\n\torig[0] = NewResourceProfiles()\n\torig[1] = GenTestResourceProfiles()\n\torig[2] = NewResourceProfiles()\n\torig[3] = GenTestResourceProfiles()\n\torig[4] = NewResourceProfiles()\n\treturn orig\n}\n\nfunc GenTestResourceProfilesSlice() []ResourceProfiles {\n\torig := make([]ResourceProfiles, 5)\n\torig[1] = *GenTestResourceProfiles()\n\torig[3] = *GenTestResourceProfiles()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_resourceprofiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpprofiles \"go.opentelemetry.io/proto/slim/otlp/profiles/v1development\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyResourceProfiles(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResourceProfiles() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewResourceProfiles()\n\t\t\t\tCopyResourceProfiles(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyResourceProfiles(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyResourceProfilesSlice(t *testing.T) {\n\tsrc := []ResourceProfiles{}\n\tdest := []ResourceProfiles{}\n\t// Test CopyTo empty\n\tdest = CopyResourceProfilesSlice(dest, src)\n\tassert.Equal(t, []ResourceProfiles{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestResourceProfilesSlice()\n\tdest = CopyResourceProfilesSlice(dest, src)\n\tassert.Equal(t, GenTestResourceProfilesSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyResourceProfilesSlice(dest, src)\n\tassert.Equal(t, GenTestResourceProfilesSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyResourceProfilesSlice(dest, []ResourceProfiles{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyResourceProfilesSlice(dest, src)\n\tassert.Equal(t, GenTestResourceProfilesSlice(), dest)\n}\n\nfunc TestCopyResourceProfilesPtrSlice(t *testing.T) {\n\tsrc := []*ResourceProfiles{}\n\tdest := []*ResourceProfiles{}\n\t// Test CopyTo empty\n\tdest = CopyResourceProfilesPtrSlice(dest, src)\n\tassert.Equal(t, []*ResourceProfiles{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestResourceProfilesPtrSlice()\n\tdest = CopyResourceProfilesPtrSlice(dest, src)\n\tassert.Equal(t, GenTestResourceProfilesPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyResourceProfilesPtrSlice(dest, src)\n\tassert.Equal(t, GenTestResourceProfilesPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyResourceProfilesPtrSlice(dest, []*ResourceProfiles{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyResourceProfilesPtrSlice(dest, src)\n\tassert.Equal(t, GenTestResourceProfilesPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONResourceProfilesUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewResourceProfiles()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewResourceProfiles(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONResourceProfiles(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResourceProfiles() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewResourceProfiles()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteResourceProfiles(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoResourceProfilesFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesResourceProfiles() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewResourceProfiles()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoResourceProfilesUnknown(t *testing.T) {\n\tdest := NewResourceProfiles()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewResourceProfiles(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoResourceProfiles(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResourceProfiles() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewResourceProfiles()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteResourceProfiles(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufResourceProfiles(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResourceProfiles() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpprofiles.ResourceProfiles{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewResourceProfiles()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesResourceProfiles() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                 {0x02},\n\t\t\"Resource/wrong_wire_type\":      {0xc},\n\t\t\"Resource/missing_value\":        {0xa},\n\t\t\"ScopeProfiles/wrong_wire_type\": {0x14},\n\t\t\"ScopeProfiles/missing_value\":   {0x12},\n\t\t\"SchemaUrl/wrong_wire_type\":     {0x1c},\n\t\t\"SchemaUrl/missing_value\":       {0x1a},\n\t}\n}\n\nfunc genTestEncodingValuesResourceProfiles() map[string]*ResourceProfiles {\n\treturn map[string]*ResourceProfiles{\n\t\t\"empty\":              NewResourceProfiles(),\n\t\t\"Resource/test\":      {Resource: *GenTestResource()},\n\t\t\"ScopeProfiles/test\": {ScopeProfiles: []*ScopeProfiles{{}, GenTestScopeProfiles()}},\n\t\t\"SchemaUrl/test\":     {SchemaUrl: \"test_schemaurl\"},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_resourcespans.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ResourceSpans is a collection of spans from a Resource.\ntype ResourceSpans struct {\n\tResource             Resource\n\tScopeSpans           []*ScopeSpans\n\tSchemaUrl            string\n\tDeprecatedScopeSpans []*ScopeSpans\n}\n\nvar (\n\tprotoPoolResourceSpans = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ResourceSpans{}\n\t\t},\n\t}\n)\n\nfunc NewResourceSpans() *ResourceSpans {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ResourceSpans{}\n\t}\n\treturn protoPoolResourceSpans.Get().(*ResourceSpans)\n}\n\nfunc DeleteResourceSpans(orig *ResourceSpans, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteResource(&orig.Resource, false)\n\tfor i := range orig.ScopeSpans {\n\t\tDeleteScopeSpans(orig.ScopeSpans[i], true)\n\t}\n\n\tfor i := range orig.DeprecatedScopeSpans {\n\t\tDeleteScopeSpans(orig.DeprecatedScopeSpans[i], true)\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolResourceSpans.Put(orig)\n\t}\n}\n\nfunc CopyResourceSpans(dest, src *ResourceSpans) *ResourceSpans {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewResourceSpans()\n\t}\n\tCopyResource(&dest.Resource, &src.Resource)\n\n\tdest.ScopeSpans = CopyScopeSpansPtrSlice(dest.ScopeSpans, src.ScopeSpans)\n\n\tdest.SchemaUrl = src.SchemaUrl\n\tdest.DeprecatedScopeSpans = CopyScopeSpansPtrSlice(dest.DeprecatedScopeSpans, src.DeprecatedScopeSpans)\n\n\treturn dest\n}\n\nfunc CopyResourceSpansSlice(dest, src []ResourceSpans) []ResourceSpans {\n\tvar newDest []ResourceSpans\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ResourceSpans, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteResourceSpans(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyResourceSpans(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyResourceSpansPtrSlice(dest, src []*ResourceSpans) []*ResourceSpans {\n\tvar newDest []*ResourceSpans\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ResourceSpans, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewResourceSpans()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteResourceSpans(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewResourceSpans()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyResourceSpans(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ResourceSpans) Reset() {\n\t*orig = ResourceSpans{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ResourceSpans) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tdest.WriteObjectField(\"resource\")\n\torig.Resource.MarshalJSON(dest)\n\tif len(orig.ScopeSpans) > 0 {\n\t\tdest.WriteObjectField(\"scopeSpans\")\n\t\tdest.WriteArrayStart()\n\t\torig.ScopeSpans[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.ScopeSpans); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.ScopeSpans[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.SchemaUrl != \"\" {\n\t\tdest.WriteObjectField(\"schemaUrl\")\n\t\tdest.WriteString(orig.SchemaUrl)\n\t}\n\tif len(orig.DeprecatedScopeSpans) > 0 {\n\t\tdest.WriteObjectField(\"deprecatedScopeSpans\")\n\t\tdest.WriteArrayStart()\n\t\torig.DeprecatedScopeSpans[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.DeprecatedScopeSpans); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.DeprecatedScopeSpans[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ResourceSpans) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"resource\":\n\n\t\t\torig.Resource.UnmarshalJSON(iter)\n\t\tcase \"scopeSpans\", \"scope_spans\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.ScopeSpans = append(orig.ScopeSpans, NewScopeSpans())\n\t\t\t\torig.ScopeSpans[len(orig.ScopeSpans)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"schemaUrl\", \"schema_url\":\n\t\t\torig.SchemaUrl = iter.ReadString()\n\t\tcase \"deprecatedScopeSpans\", \"deprecated_scope_spans\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.DeprecatedScopeSpans = append(orig.DeprecatedScopeSpans, NewScopeSpans())\n\t\t\t\torig.DeprecatedScopeSpans[len(orig.DeprecatedScopeSpans)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ResourceSpans) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tl = orig.Resource.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tfor i := range orig.ScopeSpans {\n\t\tl = orig.ScopeSpans[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tfor i := range orig.DeprecatedScopeSpans {\n\t\tl = orig.DeprecatedScopeSpans[i].SizeProto()\n\t\tn += 2 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ResourceSpans) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = orig.Resource.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0xa\n\n\tfor i := len(orig.ScopeSpans) - 1; i >= 0; i-- {\n\t\tl = orig.ScopeSpans[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.SchemaUrl)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\tfor i := len(orig.DeprecatedScopeSpans) - 1; i >= 0; i-- {\n\t\tl = orig.DeprecatedScopeSpans[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x3e\n\t\tpos--\n\t\tbuf[pos] = 0xc2\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ResourceSpans) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Resource\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.Resource.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ScopeSpans\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.ScopeSpans = append(orig.ScopeSpans, NewScopeSpans())\n\t\t\terr = orig.ScopeSpans[len(orig.ScopeSpans)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SchemaUrl\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.SchemaUrl = string(buf[startPos:pos])\n\n\t\tcase 1000:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DeprecatedScopeSpans\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.DeprecatedScopeSpans = append(orig.DeprecatedScopeSpans, NewScopeSpans())\n\t\t\terr = orig.DeprecatedScopeSpans[len(orig.DeprecatedScopeSpans)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestResourceSpans() *ResourceSpans {\n\torig := NewResourceSpans()\n\torig.Resource = *GenTestResource()\n\torig.ScopeSpans = []*ScopeSpans{{}, GenTestScopeSpans()}\n\torig.SchemaUrl = \"test_schemaurl\"\n\torig.DeprecatedScopeSpans = []*ScopeSpans{{}, GenTestScopeSpans()}\n\treturn orig\n}\n\nfunc GenTestResourceSpansPtrSlice() []*ResourceSpans {\n\torig := make([]*ResourceSpans, 5)\n\torig[0] = NewResourceSpans()\n\torig[1] = GenTestResourceSpans()\n\torig[2] = NewResourceSpans()\n\torig[3] = GenTestResourceSpans()\n\torig[4] = NewResourceSpans()\n\treturn orig\n}\n\nfunc GenTestResourceSpansSlice() []ResourceSpans {\n\torig := make([]ResourceSpans, 5)\n\torig[1] = *GenTestResourceSpans()\n\torig[3] = *GenTestResourceSpans()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_resourcespans_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlptrace \"go.opentelemetry.io/proto/slim/otlp/trace/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyResourceSpans(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResourceSpans() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewResourceSpans()\n\t\t\t\tCopyResourceSpans(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyResourceSpans(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyResourceSpansSlice(t *testing.T) {\n\tsrc := []ResourceSpans{}\n\tdest := []ResourceSpans{}\n\t// Test CopyTo empty\n\tdest = CopyResourceSpansSlice(dest, src)\n\tassert.Equal(t, []ResourceSpans{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestResourceSpansSlice()\n\tdest = CopyResourceSpansSlice(dest, src)\n\tassert.Equal(t, GenTestResourceSpansSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyResourceSpansSlice(dest, src)\n\tassert.Equal(t, GenTestResourceSpansSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyResourceSpansSlice(dest, []ResourceSpans{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyResourceSpansSlice(dest, src)\n\tassert.Equal(t, GenTestResourceSpansSlice(), dest)\n}\n\nfunc TestCopyResourceSpansPtrSlice(t *testing.T) {\n\tsrc := []*ResourceSpans{}\n\tdest := []*ResourceSpans{}\n\t// Test CopyTo empty\n\tdest = CopyResourceSpansPtrSlice(dest, src)\n\tassert.Equal(t, []*ResourceSpans{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestResourceSpansPtrSlice()\n\tdest = CopyResourceSpansPtrSlice(dest, src)\n\tassert.Equal(t, GenTestResourceSpansPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyResourceSpansPtrSlice(dest, src)\n\tassert.Equal(t, GenTestResourceSpansPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyResourceSpansPtrSlice(dest, []*ResourceSpans{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyResourceSpansPtrSlice(dest, src)\n\tassert.Equal(t, GenTestResourceSpansPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONResourceSpansUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewResourceSpans()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewResourceSpans(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONResourceSpans(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResourceSpans() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewResourceSpans()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteResourceSpans(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoResourceSpansFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesResourceSpans() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewResourceSpans()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoResourceSpansUnknown(t *testing.T) {\n\tdest := NewResourceSpans()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewResourceSpans(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoResourceSpans(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResourceSpans() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewResourceSpans()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteResourceSpans(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufResourceSpans(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesResourceSpans() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlptrace.ResourceSpans{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewResourceSpans()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesResourceSpans() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                        {0x02},\n\t\t\"Resource/wrong_wire_type\":             {0xc},\n\t\t\"Resource/missing_value\":               {0xa},\n\t\t\"ScopeSpans/wrong_wire_type\":           {0x14},\n\t\t\"ScopeSpans/missing_value\":             {0x12},\n\t\t\"SchemaUrl/wrong_wire_type\":            {0x1c},\n\t\t\"SchemaUrl/missing_value\":              {0x1a},\n\t\t\"DeprecatedScopeSpans/wrong_wire_type\": {0xc4, 0x3e},\n\t\t\"DeprecatedScopeSpans/missing_value\":   {0xc2, 0x3e},\n\t}\n}\n\nfunc genTestEncodingValuesResourceSpans() map[string]*ResourceSpans {\n\treturn map[string]*ResourceSpans{\n\t\t\"empty\":                     NewResourceSpans(),\n\t\t\"Resource/test\":             {Resource: *GenTestResource()},\n\t\t\"ScopeSpans/test\":           {ScopeSpans: []*ScopeSpans{{}, GenTestScopeSpans()}},\n\t\t\"SchemaUrl/test\":            {SchemaUrl: \"test_schemaurl\"},\n\t\t\"DeprecatedScopeSpans/test\": {DeprecatedScopeSpans: []*ScopeSpans{{}, GenTestScopeSpans()}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_sample.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Sample represents each record value encountered within a profiled program.\ntype Sample struct {\n\tAttributeIndices   []int32\n\tValues             []int64\n\tTimestampsUnixNano []uint64\n\tStackIndex         int32\n\tLinkIndex          int32\n}\n\nvar (\n\tprotoPoolSample = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Sample{}\n\t\t},\n\t}\n)\n\nfunc NewSample() *Sample {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &Sample{}\n\t}\n\treturn protoPoolSample.Get().(*Sample)\n}\n\nfunc DeleteSample(orig *Sample, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolSample.Put(orig)\n\t}\n}\n\nfunc CopySample(dest, src *Sample) *Sample {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewSample()\n\t}\n\tdest.StackIndex = src.StackIndex\n\tdest.AttributeIndices = append(dest.AttributeIndices[:0], src.AttributeIndices...)\n\n\tdest.LinkIndex = src.LinkIndex\n\tdest.Values = append(dest.Values[:0], src.Values...)\n\n\tdest.TimestampsUnixNano = append(dest.TimestampsUnixNano[:0], src.TimestampsUnixNano...)\n\n\treturn dest\n}\n\nfunc CopySampleSlice(dest, src []Sample) []Sample {\n\tvar newDest []Sample\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]Sample, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSample(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySample(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopySamplePtrSlice(dest, src []*Sample) []*Sample {\n\tvar newDest []*Sample\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*Sample, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSample()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSample(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSample()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySample(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *Sample) Reset() {\n\t*orig = Sample{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *Sample) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.StackIndex != int32(0) {\n\t\tdest.WriteObjectField(\"stackIndex\")\n\t\tdest.WriteInt32(orig.StackIndex)\n\t}\n\tif len(orig.AttributeIndices) > 0 {\n\t\tdest.WriteObjectField(\"attributeIndices\")\n\t\tdest.WriteArrayStart()\n\t\tdest.WriteInt32(orig.AttributeIndices[0])\n\t\tfor i := 1; i < len(orig.AttributeIndices); i++ {\n\t\t\tdest.WriteMore()\n\t\t\tdest.WriteInt32(orig.AttributeIndices[i])\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\n\tif orig.LinkIndex != int32(0) {\n\t\tdest.WriteObjectField(\"linkIndex\")\n\t\tdest.WriteInt32(orig.LinkIndex)\n\t}\n\tif len(orig.Values) > 0 {\n\t\tdest.WriteObjectField(\"values\")\n\t\tdest.WriteArrayStart()\n\t\tdest.WriteInt64(orig.Values[0])\n\t\tfor i := 1; i < len(orig.Values); i++ {\n\t\t\tdest.WriteMore()\n\t\t\tdest.WriteInt64(orig.Values[i])\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\n\tif len(orig.TimestampsUnixNano) > 0 {\n\t\tdest.WriteObjectField(\"timestampsUnixNano\")\n\t\tdest.WriteArrayStart()\n\t\tdest.WriteUint64(orig.TimestampsUnixNano[0])\n\t\tfor i := 1; i < len(orig.TimestampsUnixNano); i++ {\n\t\t\tdest.WriteMore()\n\t\t\tdest.WriteUint64(orig.TimestampsUnixNano[i])\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *Sample) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"stackIndex\", \"stack_index\":\n\t\t\torig.StackIndex = iter.ReadInt32()\n\t\tcase \"attributeIndices\", \"attribute_indices\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.AttributeIndices = append(orig.AttributeIndices, iter.ReadInt32())\n\t\t\t}\n\n\t\tcase \"linkIndex\", \"link_index\":\n\t\t\torig.LinkIndex = iter.ReadInt32()\n\t\tcase \"values\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Values = append(orig.Values, iter.ReadInt64())\n\t\t\t}\n\n\t\tcase \"timestampsUnixNano\", \"timestamps_unix_nano\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.TimestampsUnixNano = append(orig.TimestampsUnixNano, iter.ReadUint64())\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *Sample) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.StackIndex != int32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.StackIndex))\n\t}\n\n\tif len(orig.AttributeIndices) > 0 {\n\t\tl = 0\n\t\tfor _, e := range orig.AttributeIndices {\n\t\t\tl += proto.Sov(uint64(e))\n\t\t}\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.LinkIndex != int32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.LinkIndex))\n\t}\n\n\tif len(orig.Values) > 0 {\n\t\tl = 0\n\t\tfor _, e := range orig.Values {\n\t\t\tl += proto.Sov(uint64(e))\n\t\t}\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tl = len(orig.TimestampsUnixNano)\n\tif l > 0 {\n\t\tl *= 8\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *Sample) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.StackIndex != int32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.StackIndex))\n\t\tpos--\n\t\tbuf[pos] = 0x8\n\t}\n\tl = len(orig.AttributeIndices)\n\tif l > 0 {\n\t\tendPos := pos\n\t\tfor i := l - 1; i >= 0; i-- {\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.AttributeIndices[i]))\n\t\t}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(endPos-pos))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tif orig.LinkIndex != int32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.LinkIndex))\n\t\tpos--\n\t\tbuf[pos] = 0x18\n\t}\n\tl = len(orig.Values)\n\tif l > 0 {\n\t\tendPos := pos\n\t\tfor i := l - 1; i >= 0; i-- {\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.Values[i]))\n\t\t}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(endPos-pos))\n\t\tpos--\n\t\tbuf[pos] = 0x22\n\t}\n\tl = len(orig.TimestampsUnixNano)\n\tif l > 0 {\n\t\tfor i := l - 1; i >= 0; i-- {\n\t\t\tpos -= 8\n\t\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimestampsUnixNano[i]))\n\t\t}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l*8))\n\t\tpos--\n\t\tbuf[pos] = 0x2a\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *Sample) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field StackIndex\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.StackIndex = int32(num)\n\t\tcase 2:\n\t\t\tswitch wireType {\n\t\t\tcase proto.WireTypeLen:\n\t\t\t\tvar length int\n\t\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tstartPos := pos - length\n\t\t\t\tvar num uint64\n\t\t\t\tfor startPos < pos {\n\t\t\t\t\tnum, startPos, err = proto.ConsumeVarint(buf[:pos], startPos)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\torig.AttributeIndices = append(orig.AttributeIndices, int32(num))\n\t\t\t\t}\n\t\t\t\tif startPos != pos {\n\t\t\t\t\treturn fmt.Errorf(\"proto: invalid field len = %d for field AttributeIndices\", pos-startPos)\n\t\t\t\t}\n\t\t\tcase proto.WireTypeVarint:\n\t\t\t\tvar num uint64\n\t\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\torig.AttributeIndices = append(orig.AttributeIndices, int32(num))\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field AttributeIndices\", wireType)\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field LinkIndex\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.LinkIndex = int32(num)\n\t\tcase 4:\n\t\t\tswitch wireType {\n\t\t\tcase proto.WireTypeLen:\n\t\t\t\tvar length int\n\t\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tstartPos := pos - length\n\t\t\t\tvar num uint64\n\t\t\t\tfor startPos < pos {\n\t\t\t\t\tnum, startPos, err = proto.ConsumeVarint(buf[:pos], startPos)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\torig.Values = append(orig.Values, int64(num))\n\t\t\t\t}\n\t\t\t\tif startPos != pos {\n\t\t\t\t\treturn fmt.Errorf(\"proto: invalid field len = %d for field Values\", pos-startPos)\n\t\t\t\t}\n\t\t\tcase proto.WireTypeVarint:\n\t\t\t\tvar num uint64\n\t\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\torig.Values = append(orig.Values, int64(num))\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Values\", wireType)\n\t\t\t}\n\t\tcase 5:\n\t\t\tswitch wireType {\n\t\t\tcase proto.WireTypeLen:\n\t\t\t\tvar length int\n\t\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tstartPos := pos - length\n\t\t\t\tsize := length / 8\n\t\t\t\torig.TimestampsUnixNano = make([]uint64, size)\n\t\t\t\tvar num uint64\n\t\t\t\tfor i := 0; i < size; i++ {\n\t\t\t\t\tnum, startPos, err = proto.ConsumeI64(buf[:pos], startPos)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\torig.TimestampsUnixNano[i] = uint64(num)\n\t\t\t\t}\n\t\t\t\tif startPos != pos {\n\t\t\t\t\treturn fmt.Errorf(\"proto: invalid field len = %d for field TimestampsUnixNano\", pos-startPos)\n\t\t\t\t}\n\t\t\tcase proto.WireTypeI64:\n\t\t\t\tvar num uint64\n\t\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\torig.TimestampsUnixNano = append(orig.TimestampsUnixNano, uint64(num))\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TimestampsUnixNano\", wireType)\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestSample() *Sample {\n\torig := NewSample()\n\torig.StackIndex = int32(13)\n\torig.AttributeIndices = []int32{int32(0), int32(13)}\n\torig.LinkIndex = int32(13)\n\torig.Values = []int64{int64(0), int64(13)}\n\torig.TimestampsUnixNano = []uint64{uint64(0), uint64(13)}\n\treturn orig\n}\n\nfunc GenTestSamplePtrSlice() []*Sample {\n\torig := make([]*Sample, 5)\n\torig[0] = NewSample()\n\torig[1] = GenTestSample()\n\torig[2] = NewSample()\n\torig[3] = GenTestSample()\n\torig[4] = NewSample()\n\treturn orig\n}\n\nfunc GenTestSampleSlice() []Sample {\n\torig := make([]Sample, 5)\n\torig[1] = *GenTestSample()\n\torig[3] = *GenTestSample()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_sample_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpprofiles \"go.opentelemetry.io/proto/slim/otlp/profiles/v1development\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopySample(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSample() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewSample()\n\t\t\t\tCopySample(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopySample(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopySampleSlice(t *testing.T) {\n\tsrc := []Sample{}\n\tdest := []Sample{}\n\t// Test CopyTo empty\n\tdest = CopySampleSlice(dest, src)\n\tassert.Equal(t, []Sample{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSampleSlice()\n\tdest = CopySampleSlice(dest, src)\n\tassert.Equal(t, GenTestSampleSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySampleSlice(dest, src)\n\tassert.Equal(t, GenTestSampleSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySampleSlice(dest, []Sample{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySampleSlice(dest, src)\n\tassert.Equal(t, GenTestSampleSlice(), dest)\n}\n\nfunc TestCopySamplePtrSlice(t *testing.T) {\n\tsrc := []*Sample{}\n\tdest := []*Sample{}\n\t// Test CopyTo empty\n\tdest = CopySamplePtrSlice(dest, src)\n\tassert.Equal(t, []*Sample{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSamplePtrSlice()\n\tdest = CopySamplePtrSlice(dest, src)\n\tassert.Equal(t, GenTestSamplePtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySamplePtrSlice(dest, src)\n\tassert.Equal(t, GenTestSamplePtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySamplePtrSlice(dest, []*Sample{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySamplePtrSlice(dest, src)\n\tassert.Equal(t, GenTestSamplePtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSampleUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewSample()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewSample(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSample(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSample() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewSample()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSample(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSampleFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesSample() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewSample()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSampleUnknown(t *testing.T) {\n\tdest := NewSample()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewSample(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoSample(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSample() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewSample()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSample(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufSample(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSample() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpprofiles.Sample{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewSample()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesSample() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                      {0x02},\n\t\t\"StackIndex/wrong_wire_type\":         {0xc},\n\t\t\"StackIndex/missing_value\":           {0x8},\n\t\t\"AttributeIndices/wrong_wire_type\":   {0x14},\n\t\t\"AttributeIndices/missing_value\":     {0x12},\n\t\t\"LinkIndex/wrong_wire_type\":          {0x1c},\n\t\t\"LinkIndex/missing_value\":            {0x18},\n\t\t\"Values/wrong_wire_type\":             {0x24},\n\t\t\"Values/missing_value\":               {0x22},\n\t\t\"TimestampsUnixNano/wrong_wire_type\": {0x2c},\n\t\t\"TimestampsUnixNano/missing_value\":   {0x2a},\n\t}\n}\n\nfunc genTestEncodingValuesSample() map[string]*Sample {\n\treturn map[string]*Sample{\n\t\t\"empty\":                   NewSample(),\n\t\t\"StackIndex/test\":         {StackIndex: int32(13)},\n\t\t\"AttributeIndices/test\":   {AttributeIndices: []int32{int32(0), int32(13)}},\n\t\t\"LinkIndex/test\":          {LinkIndex: int32(13)},\n\t\t\"Values/test\":             {Values: []int64{int64(0), int64(13)}},\n\t\t\"TimestampsUnixNano/test\": {TimestampsUnixNano: []uint64{uint64(0), uint64(13)}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_scopelogs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ScopeLogs is a collection of logs from a LibraryInstrumentation.\ntype ScopeLogs struct {\n\tSchemaUrl  string\n\tLogRecords []*LogRecord\n\tScope      InstrumentationScope\n}\n\nvar (\n\tprotoPoolScopeLogs = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ScopeLogs{}\n\t\t},\n\t}\n)\n\nfunc NewScopeLogs() *ScopeLogs {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ScopeLogs{}\n\t}\n\treturn protoPoolScopeLogs.Get().(*ScopeLogs)\n}\n\nfunc DeleteScopeLogs(orig *ScopeLogs, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteInstrumentationScope(&orig.Scope, false)\n\tfor i := range orig.LogRecords {\n\t\tDeleteLogRecord(orig.LogRecords[i], true)\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolScopeLogs.Put(orig)\n\t}\n}\n\nfunc CopyScopeLogs(dest, src *ScopeLogs) *ScopeLogs {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewScopeLogs()\n\t}\n\tCopyInstrumentationScope(&dest.Scope, &src.Scope)\n\n\tdest.LogRecords = CopyLogRecordPtrSlice(dest.LogRecords, src.LogRecords)\n\n\tdest.SchemaUrl = src.SchemaUrl\n\n\treturn dest\n}\n\nfunc CopyScopeLogsSlice(dest, src []ScopeLogs) []ScopeLogs {\n\tvar newDest []ScopeLogs\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ScopeLogs, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteScopeLogs(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyScopeLogs(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyScopeLogsPtrSlice(dest, src []*ScopeLogs) []*ScopeLogs {\n\tvar newDest []*ScopeLogs\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ScopeLogs, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewScopeLogs()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteScopeLogs(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewScopeLogs()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyScopeLogs(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ScopeLogs) Reset() {\n\t*orig = ScopeLogs{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ScopeLogs) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tdest.WriteObjectField(\"scope\")\n\torig.Scope.MarshalJSON(dest)\n\tif len(orig.LogRecords) > 0 {\n\t\tdest.WriteObjectField(\"logRecords\")\n\t\tdest.WriteArrayStart()\n\t\torig.LogRecords[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.LogRecords); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.LogRecords[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.SchemaUrl != \"\" {\n\t\tdest.WriteObjectField(\"schemaUrl\")\n\t\tdest.WriteString(orig.SchemaUrl)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ScopeLogs) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"scope\":\n\n\t\t\torig.Scope.UnmarshalJSON(iter)\n\t\tcase \"logRecords\", \"log_records\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.LogRecords = append(orig.LogRecords, NewLogRecord())\n\t\t\t\torig.LogRecords[len(orig.LogRecords)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"schemaUrl\", \"schema_url\":\n\t\t\torig.SchemaUrl = iter.ReadString()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ScopeLogs) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tl = orig.Scope.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tfor i := range orig.LogRecords {\n\t\tl = orig.LogRecords[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ScopeLogs) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = orig.Scope.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0xa\n\n\tfor i := len(orig.LogRecords) - 1; i >= 0; i-- {\n\t\tl = orig.LogRecords[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.SchemaUrl)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ScopeLogs) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Scope\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.Scope.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field LogRecords\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.LogRecords = append(orig.LogRecords, NewLogRecord())\n\t\t\terr = orig.LogRecords[len(orig.LogRecords)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SchemaUrl\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.SchemaUrl = string(buf[startPos:pos])\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestScopeLogs() *ScopeLogs {\n\torig := NewScopeLogs()\n\torig.Scope = *GenTestInstrumentationScope()\n\torig.LogRecords = []*LogRecord{{}, GenTestLogRecord()}\n\torig.SchemaUrl = \"test_schemaurl\"\n\treturn orig\n}\n\nfunc GenTestScopeLogsPtrSlice() []*ScopeLogs {\n\torig := make([]*ScopeLogs, 5)\n\torig[0] = NewScopeLogs()\n\torig[1] = GenTestScopeLogs()\n\torig[2] = NewScopeLogs()\n\torig[3] = GenTestScopeLogs()\n\torig[4] = NewScopeLogs()\n\treturn orig\n}\n\nfunc GenTestScopeLogsSlice() []ScopeLogs {\n\torig := make([]ScopeLogs, 5)\n\torig[1] = *GenTestScopeLogs()\n\torig[3] = *GenTestScopeLogs()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_scopelogs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlplogs \"go.opentelemetry.io/proto/slim/otlp/logs/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyScopeLogs(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesScopeLogs() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewScopeLogs()\n\t\t\t\tCopyScopeLogs(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyScopeLogs(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyScopeLogsSlice(t *testing.T) {\n\tsrc := []ScopeLogs{}\n\tdest := []ScopeLogs{}\n\t// Test CopyTo empty\n\tdest = CopyScopeLogsSlice(dest, src)\n\tassert.Equal(t, []ScopeLogs{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestScopeLogsSlice()\n\tdest = CopyScopeLogsSlice(dest, src)\n\tassert.Equal(t, GenTestScopeLogsSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyScopeLogsSlice(dest, src)\n\tassert.Equal(t, GenTestScopeLogsSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyScopeLogsSlice(dest, []ScopeLogs{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyScopeLogsSlice(dest, src)\n\tassert.Equal(t, GenTestScopeLogsSlice(), dest)\n}\n\nfunc TestCopyScopeLogsPtrSlice(t *testing.T) {\n\tsrc := []*ScopeLogs{}\n\tdest := []*ScopeLogs{}\n\t// Test CopyTo empty\n\tdest = CopyScopeLogsPtrSlice(dest, src)\n\tassert.Equal(t, []*ScopeLogs{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestScopeLogsPtrSlice()\n\tdest = CopyScopeLogsPtrSlice(dest, src)\n\tassert.Equal(t, GenTestScopeLogsPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyScopeLogsPtrSlice(dest, src)\n\tassert.Equal(t, GenTestScopeLogsPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyScopeLogsPtrSlice(dest, []*ScopeLogs{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyScopeLogsPtrSlice(dest, src)\n\tassert.Equal(t, GenTestScopeLogsPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONScopeLogsUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewScopeLogs()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewScopeLogs(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONScopeLogs(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesScopeLogs() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewScopeLogs()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteScopeLogs(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoScopeLogsFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesScopeLogs() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewScopeLogs()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoScopeLogsUnknown(t *testing.T) {\n\tdest := NewScopeLogs()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewScopeLogs(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoScopeLogs(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesScopeLogs() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewScopeLogs()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteScopeLogs(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufScopeLogs(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesScopeLogs() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlplogs.ScopeLogs{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewScopeLogs()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesScopeLogs() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":              {0x02},\n\t\t\"Scope/wrong_wire_type\":      {0xc},\n\t\t\"Scope/missing_value\":        {0xa},\n\t\t\"LogRecords/wrong_wire_type\": {0x14},\n\t\t\"LogRecords/missing_value\":   {0x12},\n\t\t\"SchemaUrl/wrong_wire_type\":  {0x1c},\n\t\t\"SchemaUrl/missing_value\":    {0x1a},\n\t}\n}\n\nfunc genTestEncodingValuesScopeLogs() map[string]*ScopeLogs {\n\treturn map[string]*ScopeLogs{\n\t\t\"empty\":           NewScopeLogs(),\n\t\t\"Scope/test\":      {Scope: *GenTestInstrumentationScope()},\n\t\t\"LogRecords/test\": {LogRecords: []*LogRecord{{}, GenTestLogRecord()}},\n\t\t\"SchemaUrl/test\":  {SchemaUrl: \"test_schemaurl\"},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_scopemetrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ScopeMetrics is a collection of metrics from a LibraryInstrumentation.\ntype ScopeMetrics struct {\n\tSchemaUrl string\n\tMetrics   []*Metric\n\tScope     InstrumentationScope\n}\n\nvar (\n\tprotoPoolScopeMetrics = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ScopeMetrics{}\n\t\t},\n\t}\n)\n\nfunc NewScopeMetrics() *ScopeMetrics {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ScopeMetrics{}\n\t}\n\treturn protoPoolScopeMetrics.Get().(*ScopeMetrics)\n}\n\nfunc DeleteScopeMetrics(orig *ScopeMetrics, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteInstrumentationScope(&orig.Scope, false)\n\tfor i := range orig.Metrics {\n\t\tDeleteMetric(orig.Metrics[i], true)\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolScopeMetrics.Put(orig)\n\t}\n}\n\nfunc CopyScopeMetrics(dest, src *ScopeMetrics) *ScopeMetrics {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewScopeMetrics()\n\t}\n\tCopyInstrumentationScope(&dest.Scope, &src.Scope)\n\n\tdest.Metrics = CopyMetricPtrSlice(dest.Metrics, src.Metrics)\n\n\tdest.SchemaUrl = src.SchemaUrl\n\n\treturn dest\n}\n\nfunc CopyScopeMetricsSlice(dest, src []ScopeMetrics) []ScopeMetrics {\n\tvar newDest []ScopeMetrics\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ScopeMetrics, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteScopeMetrics(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyScopeMetrics(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyScopeMetricsPtrSlice(dest, src []*ScopeMetrics) []*ScopeMetrics {\n\tvar newDest []*ScopeMetrics\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ScopeMetrics, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewScopeMetrics()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteScopeMetrics(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewScopeMetrics()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyScopeMetrics(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ScopeMetrics) Reset() {\n\t*orig = ScopeMetrics{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ScopeMetrics) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tdest.WriteObjectField(\"scope\")\n\torig.Scope.MarshalJSON(dest)\n\tif len(orig.Metrics) > 0 {\n\t\tdest.WriteObjectField(\"metrics\")\n\t\tdest.WriteArrayStart()\n\t\torig.Metrics[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Metrics); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Metrics[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.SchemaUrl != \"\" {\n\t\tdest.WriteObjectField(\"schemaUrl\")\n\t\tdest.WriteString(orig.SchemaUrl)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ScopeMetrics) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"scope\":\n\n\t\t\torig.Scope.UnmarshalJSON(iter)\n\t\tcase \"metrics\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Metrics = append(orig.Metrics, NewMetric())\n\t\t\t\torig.Metrics[len(orig.Metrics)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"schemaUrl\", \"schema_url\":\n\t\t\torig.SchemaUrl = iter.ReadString()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ScopeMetrics) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tl = orig.Scope.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tfor i := range orig.Metrics {\n\t\tl = orig.Metrics[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ScopeMetrics) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = orig.Scope.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0xa\n\n\tfor i := len(orig.Metrics) - 1; i >= 0; i-- {\n\t\tl = orig.Metrics[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.SchemaUrl)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ScopeMetrics) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Scope\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.Scope.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Metrics\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Metrics = append(orig.Metrics, NewMetric())\n\t\t\terr = orig.Metrics[len(orig.Metrics)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SchemaUrl\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.SchemaUrl = string(buf[startPos:pos])\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestScopeMetrics() *ScopeMetrics {\n\torig := NewScopeMetrics()\n\torig.Scope = *GenTestInstrumentationScope()\n\torig.Metrics = []*Metric{{}, GenTestMetric()}\n\torig.SchemaUrl = \"test_schemaurl\"\n\treturn orig\n}\n\nfunc GenTestScopeMetricsPtrSlice() []*ScopeMetrics {\n\torig := make([]*ScopeMetrics, 5)\n\torig[0] = NewScopeMetrics()\n\torig[1] = GenTestScopeMetrics()\n\torig[2] = NewScopeMetrics()\n\torig[3] = GenTestScopeMetrics()\n\torig[4] = NewScopeMetrics()\n\treturn orig\n}\n\nfunc GenTestScopeMetricsSlice() []ScopeMetrics {\n\torig := make([]ScopeMetrics, 5)\n\torig[1] = *GenTestScopeMetrics()\n\torig[3] = *GenTestScopeMetrics()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_scopemetrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyScopeMetrics(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesScopeMetrics() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewScopeMetrics()\n\t\t\t\tCopyScopeMetrics(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyScopeMetrics(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyScopeMetricsSlice(t *testing.T) {\n\tsrc := []ScopeMetrics{}\n\tdest := []ScopeMetrics{}\n\t// Test CopyTo empty\n\tdest = CopyScopeMetricsSlice(dest, src)\n\tassert.Equal(t, []ScopeMetrics{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestScopeMetricsSlice()\n\tdest = CopyScopeMetricsSlice(dest, src)\n\tassert.Equal(t, GenTestScopeMetricsSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyScopeMetricsSlice(dest, src)\n\tassert.Equal(t, GenTestScopeMetricsSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyScopeMetricsSlice(dest, []ScopeMetrics{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyScopeMetricsSlice(dest, src)\n\tassert.Equal(t, GenTestScopeMetricsSlice(), dest)\n}\n\nfunc TestCopyScopeMetricsPtrSlice(t *testing.T) {\n\tsrc := []*ScopeMetrics{}\n\tdest := []*ScopeMetrics{}\n\t// Test CopyTo empty\n\tdest = CopyScopeMetricsPtrSlice(dest, src)\n\tassert.Equal(t, []*ScopeMetrics{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestScopeMetricsPtrSlice()\n\tdest = CopyScopeMetricsPtrSlice(dest, src)\n\tassert.Equal(t, GenTestScopeMetricsPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyScopeMetricsPtrSlice(dest, src)\n\tassert.Equal(t, GenTestScopeMetricsPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyScopeMetricsPtrSlice(dest, []*ScopeMetrics{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyScopeMetricsPtrSlice(dest, src)\n\tassert.Equal(t, GenTestScopeMetricsPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONScopeMetricsUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewScopeMetrics()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewScopeMetrics(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONScopeMetrics(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesScopeMetrics() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewScopeMetrics()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteScopeMetrics(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoScopeMetricsFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesScopeMetrics() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewScopeMetrics()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoScopeMetricsUnknown(t *testing.T) {\n\tdest := NewScopeMetrics()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewScopeMetrics(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoScopeMetrics(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesScopeMetrics() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewScopeMetrics()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteScopeMetrics(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufScopeMetrics(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesScopeMetrics() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpmetrics.ScopeMetrics{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewScopeMetrics()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesScopeMetrics() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":             {0x02},\n\t\t\"Scope/wrong_wire_type\":     {0xc},\n\t\t\"Scope/missing_value\":       {0xa},\n\t\t\"Metrics/wrong_wire_type\":   {0x14},\n\t\t\"Metrics/missing_value\":     {0x12},\n\t\t\"SchemaUrl/wrong_wire_type\": {0x1c},\n\t\t\"SchemaUrl/missing_value\":   {0x1a},\n\t}\n}\n\nfunc genTestEncodingValuesScopeMetrics() map[string]*ScopeMetrics {\n\treturn map[string]*ScopeMetrics{\n\t\t\"empty\":          NewScopeMetrics(),\n\t\t\"Scope/test\":     {Scope: *GenTestInstrumentationScope()},\n\t\t\"Metrics/test\":   {Metrics: []*Metric{{}, GenTestMetric()}},\n\t\t\"SchemaUrl/test\": {SchemaUrl: \"test_schemaurl\"},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_scopeprofiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ScopeProfiles is a collection of profiles from a LibraryInstrumentation.\ntype ScopeProfiles struct {\n\tSchemaUrl string\n\tProfiles  []*Profile\n\tScope     InstrumentationScope\n}\n\nvar (\n\tprotoPoolScopeProfiles = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ScopeProfiles{}\n\t\t},\n\t}\n)\n\nfunc NewScopeProfiles() *ScopeProfiles {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ScopeProfiles{}\n\t}\n\treturn protoPoolScopeProfiles.Get().(*ScopeProfiles)\n}\n\nfunc DeleteScopeProfiles(orig *ScopeProfiles, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteInstrumentationScope(&orig.Scope, false)\n\tfor i := range orig.Profiles {\n\t\tDeleteProfile(orig.Profiles[i], true)\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolScopeProfiles.Put(orig)\n\t}\n}\n\nfunc CopyScopeProfiles(dest, src *ScopeProfiles) *ScopeProfiles {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewScopeProfiles()\n\t}\n\tCopyInstrumentationScope(&dest.Scope, &src.Scope)\n\n\tdest.Profiles = CopyProfilePtrSlice(dest.Profiles, src.Profiles)\n\n\tdest.SchemaUrl = src.SchemaUrl\n\n\treturn dest\n}\n\nfunc CopyScopeProfilesSlice(dest, src []ScopeProfiles) []ScopeProfiles {\n\tvar newDest []ScopeProfiles\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ScopeProfiles, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteScopeProfiles(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyScopeProfiles(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyScopeProfilesPtrSlice(dest, src []*ScopeProfiles) []*ScopeProfiles {\n\tvar newDest []*ScopeProfiles\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ScopeProfiles, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewScopeProfiles()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteScopeProfiles(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewScopeProfiles()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyScopeProfiles(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ScopeProfiles) Reset() {\n\t*orig = ScopeProfiles{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ScopeProfiles) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tdest.WriteObjectField(\"scope\")\n\torig.Scope.MarshalJSON(dest)\n\tif len(orig.Profiles) > 0 {\n\t\tdest.WriteObjectField(\"profiles\")\n\t\tdest.WriteArrayStart()\n\t\torig.Profiles[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Profiles); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Profiles[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.SchemaUrl != \"\" {\n\t\tdest.WriteObjectField(\"schemaUrl\")\n\t\tdest.WriteString(orig.SchemaUrl)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ScopeProfiles) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"scope\":\n\n\t\t\torig.Scope.UnmarshalJSON(iter)\n\t\tcase \"profiles\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Profiles = append(orig.Profiles, NewProfile())\n\t\t\t\torig.Profiles[len(orig.Profiles)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"schemaUrl\", \"schema_url\":\n\t\t\torig.SchemaUrl = iter.ReadString()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ScopeProfiles) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tl = orig.Scope.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tfor i := range orig.Profiles {\n\t\tl = orig.Profiles[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ScopeProfiles) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = orig.Scope.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0xa\n\n\tfor i := len(orig.Profiles) - 1; i >= 0; i-- {\n\t\tl = orig.Profiles[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.SchemaUrl)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ScopeProfiles) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Scope\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.Scope.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Profiles\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Profiles = append(orig.Profiles, NewProfile())\n\t\t\terr = orig.Profiles[len(orig.Profiles)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SchemaUrl\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.SchemaUrl = string(buf[startPos:pos])\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestScopeProfiles() *ScopeProfiles {\n\torig := NewScopeProfiles()\n\torig.Scope = *GenTestInstrumentationScope()\n\torig.Profiles = []*Profile{{}, GenTestProfile()}\n\torig.SchemaUrl = \"test_schemaurl\"\n\treturn orig\n}\n\nfunc GenTestScopeProfilesPtrSlice() []*ScopeProfiles {\n\torig := make([]*ScopeProfiles, 5)\n\torig[0] = NewScopeProfiles()\n\torig[1] = GenTestScopeProfiles()\n\torig[2] = NewScopeProfiles()\n\torig[3] = GenTestScopeProfiles()\n\torig[4] = NewScopeProfiles()\n\treturn orig\n}\n\nfunc GenTestScopeProfilesSlice() []ScopeProfiles {\n\torig := make([]ScopeProfiles, 5)\n\torig[1] = *GenTestScopeProfiles()\n\torig[3] = *GenTestScopeProfiles()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_scopeprofiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpprofiles \"go.opentelemetry.io/proto/slim/otlp/profiles/v1development\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyScopeProfiles(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesScopeProfiles() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewScopeProfiles()\n\t\t\t\tCopyScopeProfiles(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyScopeProfiles(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyScopeProfilesSlice(t *testing.T) {\n\tsrc := []ScopeProfiles{}\n\tdest := []ScopeProfiles{}\n\t// Test CopyTo empty\n\tdest = CopyScopeProfilesSlice(dest, src)\n\tassert.Equal(t, []ScopeProfiles{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestScopeProfilesSlice()\n\tdest = CopyScopeProfilesSlice(dest, src)\n\tassert.Equal(t, GenTestScopeProfilesSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyScopeProfilesSlice(dest, src)\n\tassert.Equal(t, GenTestScopeProfilesSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyScopeProfilesSlice(dest, []ScopeProfiles{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyScopeProfilesSlice(dest, src)\n\tassert.Equal(t, GenTestScopeProfilesSlice(), dest)\n}\n\nfunc TestCopyScopeProfilesPtrSlice(t *testing.T) {\n\tsrc := []*ScopeProfiles{}\n\tdest := []*ScopeProfiles{}\n\t// Test CopyTo empty\n\tdest = CopyScopeProfilesPtrSlice(dest, src)\n\tassert.Equal(t, []*ScopeProfiles{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestScopeProfilesPtrSlice()\n\tdest = CopyScopeProfilesPtrSlice(dest, src)\n\tassert.Equal(t, GenTestScopeProfilesPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyScopeProfilesPtrSlice(dest, src)\n\tassert.Equal(t, GenTestScopeProfilesPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyScopeProfilesPtrSlice(dest, []*ScopeProfiles{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyScopeProfilesPtrSlice(dest, src)\n\tassert.Equal(t, GenTestScopeProfilesPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONScopeProfilesUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewScopeProfiles()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewScopeProfiles(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONScopeProfiles(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesScopeProfiles() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewScopeProfiles()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteScopeProfiles(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoScopeProfilesFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesScopeProfiles() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewScopeProfiles()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoScopeProfilesUnknown(t *testing.T) {\n\tdest := NewScopeProfiles()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewScopeProfiles(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoScopeProfiles(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesScopeProfiles() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewScopeProfiles()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteScopeProfiles(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufScopeProfiles(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesScopeProfiles() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpprofiles.ScopeProfiles{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewScopeProfiles()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesScopeProfiles() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":             {0x02},\n\t\t\"Scope/wrong_wire_type\":     {0xc},\n\t\t\"Scope/missing_value\":       {0xa},\n\t\t\"Profiles/wrong_wire_type\":  {0x14},\n\t\t\"Profiles/missing_value\":    {0x12},\n\t\t\"SchemaUrl/wrong_wire_type\": {0x1c},\n\t\t\"SchemaUrl/missing_value\":   {0x1a},\n\t}\n}\n\nfunc genTestEncodingValuesScopeProfiles() map[string]*ScopeProfiles {\n\treturn map[string]*ScopeProfiles{\n\t\t\"empty\":          NewScopeProfiles(),\n\t\t\"Scope/test\":     {Scope: *GenTestInstrumentationScope()},\n\t\t\"Profiles/test\":  {Profiles: []*Profile{{}, GenTestProfile()}},\n\t\t\"SchemaUrl/test\": {SchemaUrl: \"test_schemaurl\"},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_scopespans.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ScopeSpans is a collection of spans from a LibraryInstrumentation.\ntype ScopeSpans struct {\n\tSchemaUrl string\n\tSpans     []*Span\n\tScope     InstrumentationScope\n}\n\nvar (\n\tprotoPoolScopeSpans = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ScopeSpans{}\n\t\t},\n\t}\n)\n\nfunc NewScopeSpans() *ScopeSpans {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ScopeSpans{}\n\t}\n\treturn protoPoolScopeSpans.Get().(*ScopeSpans)\n}\n\nfunc DeleteScopeSpans(orig *ScopeSpans, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteInstrumentationScope(&orig.Scope, false)\n\tfor i := range orig.Spans {\n\t\tDeleteSpan(orig.Spans[i], true)\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolScopeSpans.Put(orig)\n\t}\n}\n\nfunc CopyScopeSpans(dest, src *ScopeSpans) *ScopeSpans {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewScopeSpans()\n\t}\n\tCopyInstrumentationScope(&dest.Scope, &src.Scope)\n\n\tdest.Spans = CopySpanPtrSlice(dest.Spans, src.Spans)\n\n\tdest.SchemaUrl = src.SchemaUrl\n\n\treturn dest\n}\n\nfunc CopyScopeSpansSlice(dest, src []ScopeSpans) []ScopeSpans {\n\tvar newDest []ScopeSpans\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ScopeSpans, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteScopeSpans(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyScopeSpans(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyScopeSpansPtrSlice(dest, src []*ScopeSpans) []*ScopeSpans {\n\tvar newDest []*ScopeSpans\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ScopeSpans, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewScopeSpans()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteScopeSpans(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewScopeSpans()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyScopeSpans(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ScopeSpans) Reset() {\n\t*orig = ScopeSpans{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ScopeSpans) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tdest.WriteObjectField(\"scope\")\n\torig.Scope.MarshalJSON(dest)\n\tif len(orig.Spans) > 0 {\n\t\tdest.WriteObjectField(\"spans\")\n\t\tdest.WriteArrayStart()\n\t\torig.Spans[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Spans); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Spans[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.SchemaUrl != \"\" {\n\t\tdest.WriteObjectField(\"schemaUrl\")\n\t\tdest.WriteString(orig.SchemaUrl)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ScopeSpans) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"scope\":\n\n\t\t\torig.Scope.UnmarshalJSON(iter)\n\t\tcase \"spans\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Spans = append(orig.Spans, NewSpan())\n\t\t\t\torig.Spans[len(orig.Spans)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"schemaUrl\", \"schema_url\":\n\t\t\torig.SchemaUrl = iter.ReadString()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ScopeSpans) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tl = orig.Scope.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tfor i := range orig.Spans {\n\t\tl = orig.Spans[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *ScopeSpans) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = orig.Scope.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0xa\n\n\tfor i := len(orig.Spans) - 1; i >= 0; i-- {\n\t\tl = orig.Spans[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tl = len(orig.SchemaUrl)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.SchemaUrl)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ScopeSpans) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Scope\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.Scope.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Spans\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Spans = append(orig.Spans, NewSpan())\n\t\t\terr = orig.Spans[len(orig.Spans)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SchemaUrl\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.SchemaUrl = string(buf[startPos:pos])\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestScopeSpans() *ScopeSpans {\n\torig := NewScopeSpans()\n\torig.Scope = *GenTestInstrumentationScope()\n\torig.Spans = []*Span{{}, GenTestSpan()}\n\torig.SchemaUrl = \"test_schemaurl\"\n\treturn orig\n}\n\nfunc GenTestScopeSpansPtrSlice() []*ScopeSpans {\n\torig := make([]*ScopeSpans, 5)\n\torig[0] = NewScopeSpans()\n\torig[1] = GenTestScopeSpans()\n\torig[2] = NewScopeSpans()\n\torig[3] = GenTestScopeSpans()\n\torig[4] = NewScopeSpans()\n\treturn orig\n}\n\nfunc GenTestScopeSpansSlice() []ScopeSpans {\n\torig := make([]ScopeSpans, 5)\n\torig[1] = *GenTestScopeSpans()\n\torig[3] = *GenTestScopeSpans()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_scopespans_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlptrace \"go.opentelemetry.io/proto/slim/otlp/trace/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyScopeSpans(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesScopeSpans() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewScopeSpans()\n\t\t\t\tCopyScopeSpans(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyScopeSpans(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyScopeSpansSlice(t *testing.T) {\n\tsrc := []ScopeSpans{}\n\tdest := []ScopeSpans{}\n\t// Test CopyTo empty\n\tdest = CopyScopeSpansSlice(dest, src)\n\tassert.Equal(t, []ScopeSpans{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestScopeSpansSlice()\n\tdest = CopyScopeSpansSlice(dest, src)\n\tassert.Equal(t, GenTestScopeSpansSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyScopeSpansSlice(dest, src)\n\tassert.Equal(t, GenTestScopeSpansSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyScopeSpansSlice(dest, []ScopeSpans{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyScopeSpansSlice(dest, src)\n\tassert.Equal(t, GenTestScopeSpansSlice(), dest)\n}\n\nfunc TestCopyScopeSpansPtrSlice(t *testing.T) {\n\tsrc := []*ScopeSpans{}\n\tdest := []*ScopeSpans{}\n\t// Test CopyTo empty\n\tdest = CopyScopeSpansPtrSlice(dest, src)\n\tassert.Equal(t, []*ScopeSpans{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestScopeSpansPtrSlice()\n\tdest = CopyScopeSpansPtrSlice(dest, src)\n\tassert.Equal(t, GenTestScopeSpansPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyScopeSpansPtrSlice(dest, src)\n\tassert.Equal(t, GenTestScopeSpansPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyScopeSpansPtrSlice(dest, []*ScopeSpans{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyScopeSpansPtrSlice(dest, src)\n\tassert.Equal(t, GenTestScopeSpansPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONScopeSpansUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewScopeSpans()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewScopeSpans(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONScopeSpans(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesScopeSpans() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewScopeSpans()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteScopeSpans(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoScopeSpansFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesScopeSpans() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewScopeSpans()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoScopeSpansUnknown(t *testing.T) {\n\tdest := NewScopeSpans()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewScopeSpans(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoScopeSpans(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesScopeSpans() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewScopeSpans()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteScopeSpans(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufScopeSpans(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesScopeSpans() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlptrace.ScopeSpans{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewScopeSpans()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesScopeSpans() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":             {0x02},\n\t\t\"Scope/wrong_wire_type\":     {0xc},\n\t\t\"Scope/missing_value\":       {0xa},\n\t\t\"Spans/wrong_wire_type\":     {0x14},\n\t\t\"Spans/missing_value\":       {0x12},\n\t\t\"SchemaUrl/wrong_wire_type\": {0x1c},\n\t\t\"SchemaUrl/missing_value\":   {0x1a},\n\t}\n}\n\nfunc genTestEncodingValuesScopeSpans() map[string]*ScopeSpans {\n\treturn map[string]*ScopeSpans{\n\t\t\"empty\":          NewScopeSpans(),\n\t\t\"Scope/test\":     {Scope: *GenTestInstrumentationScope()},\n\t\t\"Spans/test\":     {Spans: []*Span{{}, GenTestSpan()}},\n\t\t\"SchemaUrl/test\": {SchemaUrl: \"test_schemaurl\"},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_span.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Span represents a single operation within a trace.\n// See Span definition in OTLP: https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/trace/v1/trace.proto\ntype Span struct {\n\tTraceState             string\n\tName                   string\n\tAttributes             []KeyValue\n\tEvents                 []*SpanEvent\n\tLinks                  []*SpanLink\n\tStatus                 Status\n\tStartTimeUnixNano      uint64\n\tEndTimeUnixNano        uint64\n\tFlags                  uint32\n\tKind                   SpanKind\n\tDroppedAttributesCount uint32\n\tDroppedEventsCount     uint32\n\tDroppedLinksCount      uint32\n\tTraceId                TraceID\n\tSpanId                 SpanID\n\tParentSpanId           SpanID\n}\n\nvar (\n\tprotoPoolSpan = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Span{}\n\t\t},\n\t}\n)\n\nfunc NewSpan() *Span {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &Span{}\n\t}\n\treturn protoPoolSpan.Get().(*Span)\n}\n\nfunc DeleteSpan(orig *Span, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteTraceID(&orig.TraceId, false)\n\tDeleteSpanID(&orig.SpanId, false)\n\n\tDeleteSpanID(&orig.ParentSpanId, false)\n\n\tfor i := range orig.Attributes {\n\t\tDeleteKeyValue(&orig.Attributes[i], false)\n\t}\n\n\tfor i := range orig.Events {\n\t\tDeleteSpanEvent(orig.Events[i], true)\n\t}\n\n\tfor i := range orig.Links {\n\t\tDeleteSpanLink(orig.Links[i], true)\n\t}\n\n\tDeleteStatus(&orig.Status, false)\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolSpan.Put(orig)\n\t}\n}\n\nfunc CopySpan(dest, src *Span) *Span {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewSpan()\n\t}\n\tCopyTraceID(&dest.TraceId, &src.TraceId)\n\n\tCopySpanID(&dest.SpanId, &src.SpanId)\n\n\tdest.TraceState = src.TraceState\n\tCopySpanID(&dest.ParentSpanId, &src.ParentSpanId)\n\n\tdest.Flags = src.Flags\n\tdest.Name = src.Name\n\tdest.Kind = src.Kind\n\tdest.StartTimeUnixNano = src.StartTimeUnixNano\n\tdest.EndTimeUnixNano = src.EndTimeUnixNano\n\tdest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)\n\n\tdest.DroppedAttributesCount = src.DroppedAttributesCount\n\tdest.Events = CopySpanEventPtrSlice(dest.Events, src.Events)\n\n\tdest.DroppedEventsCount = src.DroppedEventsCount\n\tdest.Links = CopySpanLinkPtrSlice(dest.Links, src.Links)\n\n\tdest.DroppedLinksCount = src.DroppedLinksCount\n\tCopyStatus(&dest.Status, &src.Status)\n\n\treturn dest\n}\n\nfunc CopySpanSlice(dest, src []Span) []Span {\n\tvar newDest []Span\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]Span, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSpan(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySpan(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopySpanPtrSlice(dest, src []*Span) []*Span {\n\tvar newDest []*Span\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*Span, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSpan()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSpan(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSpan()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySpan(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *Span) Reset() {\n\t*orig = Span{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *Span) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif !orig.TraceId.IsEmpty() {\n\t\tdest.WriteObjectField(\"traceId\")\n\t\torig.TraceId.MarshalJSON(dest)\n\t}\n\tif !orig.SpanId.IsEmpty() {\n\t\tdest.WriteObjectField(\"spanId\")\n\t\torig.SpanId.MarshalJSON(dest)\n\t}\n\tif orig.TraceState != \"\" {\n\t\tdest.WriteObjectField(\"traceState\")\n\t\tdest.WriteString(orig.TraceState)\n\t}\n\tif !orig.ParentSpanId.IsEmpty() {\n\t\tdest.WriteObjectField(\"parentSpanId\")\n\t\torig.ParentSpanId.MarshalJSON(dest)\n\t}\n\tif orig.Flags != uint32(0) {\n\t\tdest.WriteObjectField(\"flags\")\n\t\tdest.WriteUint32(orig.Flags)\n\t}\n\tif orig.Name != \"\" {\n\t\tdest.WriteObjectField(\"name\")\n\t\tdest.WriteString(orig.Name)\n\t}\n\n\tif int32(orig.Kind) != 0 {\n\t\tdest.WriteObjectField(\"kind\")\n\t\tdest.WriteInt32(int32(orig.Kind))\n\t}\n\tif orig.StartTimeUnixNano != uint64(0) {\n\t\tdest.WriteObjectField(\"startTimeUnixNano\")\n\t\tdest.WriteUint64(orig.StartTimeUnixNano)\n\t}\n\tif orig.EndTimeUnixNano != uint64(0) {\n\t\tdest.WriteObjectField(\"endTimeUnixNano\")\n\t\tdest.WriteUint64(orig.EndTimeUnixNano)\n\t}\n\tif len(orig.Attributes) > 0 {\n\t\tdest.WriteObjectField(\"attributes\")\n\t\tdest.WriteArrayStart()\n\t\torig.Attributes[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Attributes); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Attributes[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tdest.WriteObjectField(\"droppedAttributesCount\")\n\t\tdest.WriteUint32(orig.DroppedAttributesCount)\n\t}\n\tif len(orig.Events) > 0 {\n\t\tdest.WriteObjectField(\"events\")\n\t\tdest.WriteArrayStart()\n\t\torig.Events[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Events); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Events[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.DroppedEventsCount != uint32(0) {\n\t\tdest.WriteObjectField(\"droppedEventsCount\")\n\t\tdest.WriteUint32(orig.DroppedEventsCount)\n\t}\n\tif len(orig.Links) > 0 {\n\t\tdest.WriteObjectField(\"links\")\n\t\tdest.WriteArrayStart()\n\t\torig.Links[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Links); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Links[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.DroppedLinksCount != uint32(0) {\n\t\tdest.WriteObjectField(\"droppedLinksCount\")\n\t\tdest.WriteUint32(orig.DroppedLinksCount)\n\t}\n\tdest.WriteObjectField(\"status\")\n\torig.Status.MarshalJSON(dest)\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *Span) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"traceId\", \"trace_id\":\n\n\t\t\torig.TraceId.UnmarshalJSON(iter)\n\t\tcase \"spanId\", \"span_id\":\n\n\t\t\torig.SpanId.UnmarshalJSON(iter)\n\t\tcase \"traceState\", \"trace_state\":\n\t\t\torig.TraceState = iter.ReadString()\n\t\tcase \"parentSpanId\", \"parent_span_id\":\n\n\t\t\torig.ParentSpanId.UnmarshalJSON(iter)\n\t\tcase \"flags\":\n\t\t\torig.Flags = iter.ReadUint32()\n\t\tcase \"name\":\n\t\t\torig.Name = iter.ReadString()\n\t\tcase \"kind\":\n\t\t\torig.Kind = SpanKind(iter.ReadEnumValue(SpanKind_value))\n\t\tcase \"startTimeUnixNano\", \"start_time_unix_nano\":\n\t\t\torig.StartTimeUnixNano = iter.ReadUint64()\n\t\tcase \"endTimeUnixNano\", \"end_time_unix_nano\":\n\t\t\torig.EndTimeUnixNano = iter.ReadUint64()\n\t\tcase \"attributes\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\t\torig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"droppedAttributesCount\", \"dropped_attributes_count\":\n\t\t\torig.DroppedAttributesCount = iter.ReadUint32()\n\t\tcase \"events\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Events = append(orig.Events, NewSpanEvent())\n\t\t\t\torig.Events[len(orig.Events)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"droppedEventsCount\", \"dropped_events_count\":\n\t\t\torig.DroppedEventsCount = iter.ReadUint32()\n\t\tcase \"links\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Links = append(orig.Links, NewSpanLink())\n\t\t\t\torig.Links[len(orig.Links)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"droppedLinksCount\", \"dropped_links_count\":\n\t\t\torig.DroppedLinksCount = iter.ReadUint32()\n\t\tcase \"status\":\n\n\t\t\torig.Status.UnmarshalJSON(iter)\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *Span) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tl = orig.TraceId.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tl = orig.SpanId.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\n\tl = len(orig.TraceState)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tl = orig.ParentSpanId.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tif orig.Flags != uint32(0) {\n\t\tn += 6\n\t}\n\n\tl = len(orig.Name)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.Kind != SpanKind(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.Kind))\n\t}\n\tif orig.StartTimeUnixNano != uint64(0) {\n\t\tn += 9\n\t}\n\tif orig.EndTimeUnixNano != uint64(0) {\n\t\tn += 9\n\t}\n\tfor i := range orig.Attributes {\n\t\tl = orig.Attributes[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.DroppedAttributesCount))\n\t}\n\tfor i := range orig.Events {\n\t\tl = orig.Events[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.DroppedEventsCount != uint32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.DroppedEventsCount))\n\t}\n\tfor i := range orig.Links {\n\t\tl = orig.Links[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.DroppedLinksCount != uint32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.DroppedLinksCount))\n\t}\n\tl = orig.Status.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\treturn n\n}\n\nfunc (orig *Span) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = orig.TraceId.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0xa\n\n\tl = orig.SpanId.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x12\n\n\tl = len(orig.TraceState)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.TraceState)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\tl = orig.ParentSpanId.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x22\n\n\tif orig.Flags != uint32(0) {\n\t\tpos -= 4\n\t\tbinary.LittleEndian.PutUint32(buf[pos:], uint32(orig.Flags))\n\t\tpos--\n\t\tbuf[pos] = 0x1\n\t\tpos--\n\t\tbuf[pos] = 0x85\n\t}\n\tl = len(orig.Name)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.Name)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x2a\n\t}\n\tif orig.Kind != SpanKind(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.Kind))\n\t\tpos--\n\t\tbuf[pos] = 0x30\n\t}\n\tif orig.StartTimeUnixNano != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.StartTimeUnixNano))\n\t\tpos--\n\t\tbuf[pos] = 0x39\n\t}\n\tif orig.EndTimeUnixNano != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.EndTimeUnixNano))\n\t\tpos--\n\t\tbuf[pos] = 0x41\n\t}\n\tfor i := len(orig.Attributes) - 1; i >= 0; i-- {\n\t\tl = orig.Attributes[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x4a\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedAttributesCount))\n\t\tpos--\n\t\tbuf[pos] = 0x50\n\t}\n\tfor i := len(orig.Events) - 1; i >= 0; i-- {\n\t\tl = orig.Events[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x5a\n\t}\n\tif orig.DroppedEventsCount != uint32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedEventsCount))\n\t\tpos--\n\t\tbuf[pos] = 0x60\n\t}\n\tfor i := len(orig.Links) - 1; i >= 0; i-- {\n\t\tl = orig.Links[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x6a\n\t}\n\tif orig.DroppedLinksCount != uint32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedLinksCount))\n\t\tpos--\n\t\tbuf[pos] = 0x70\n\t}\n\tl = orig.Status.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x7a\n\n\treturn len(buf) - pos\n}\n\nfunc (orig *Span) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TraceId\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.TraceId.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SpanId\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.SpanId.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TraceState\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.TraceState = string(buf[startPos:pos])\n\n\t\tcase 4:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ParentSpanId\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.ParentSpanId.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 16:\n\t\t\tif wireType != proto.WireTypeI32 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Flags\", wireType)\n\t\t\t}\n\t\t\tvar num uint32\n\t\t\tnum, pos, err = proto.ConsumeI32(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.Flags = uint32(num)\n\n\t\tcase 5:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Name\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Name = string(buf[startPos:pos])\n\n\t\tcase 6:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Kind\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Kind = SpanKind(num)\n\n\t\tcase 7:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field StartTimeUnixNano\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.StartTimeUnixNano = uint64(num)\n\n\t\tcase 8:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field EndTimeUnixNano\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.EndTimeUnixNano = uint64(num)\n\n\t\tcase 9:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Attributes\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\terr = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 10:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DroppedAttributesCount\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.DroppedAttributesCount = uint32(num)\n\n\t\tcase 11:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Events\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Events = append(orig.Events, NewSpanEvent())\n\t\t\terr = orig.Events[len(orig.Events)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 12:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DroppedEventsCount\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.DroppedEventsCount = uint32(num)\n\n\t\tcase 13:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Links\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Links = append(orig.Links, NewSpanLink())\n\t\t\terr = orig.Links[len(orig.Links)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 14:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DroppedLinksCount\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.DroppedLinksCount = uint32(num)\n\n\t\tcase 15:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Status\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.Status.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestSpan() *Span {\n\torig := NewSpan()\n\torig.TraceId = *GenTestTraceID()\n\torig.SpanId = *GenTestSpanID()\n\torig.TraceState = \"test_tracestate\"\n\torig.ParentSpanId = *GenTestSpanID()\n\torig.Flags = uint32(13)\n\torig.Name = \"test_name\"\n\torig.Kind = SpanKind(13)\n\torig.StartTimeUnixNano = uint64(13)\n\torig.EndTimeUnixNano = uint64(13)\n\torig.Attributes = []KeyValue{{}, *GenTestKeyValue()}\n\torig.DroppedAttributesCount = uint32(13)\n\torig.Events = []*SpanEvent{{}, GenTestSpanEvent()}\n\torig.DroppedEventsCount = uint32(13)\n\torig.Links = []*SpanLink{{}, GenTestSpanLink()}\n\torig.DroppedLinksCount = uint32(13)\n\torig.Status = *GenTestStatus()\n\treturn orig\n}\n\nfunc GenTestSpanPtrSlice() []*Span {\n\torig := make([]*Span, 5)\n\torig[0] = NewSpan()\n\torig[1] = GenTestSpan()\n\torig[2] = NewSpan()\n\torig[3] = GenTestSpan()\n\torig[4] = NewSpan()\n\treturn orig\n}\n\nfunc GenTestSpanSlice() []Span {\n\torig := make([]Span, 5)\n\torig[1] = *GenTestSpan()\n\torig[3] = *GenTestSpan()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_span_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlptrace \"go.opentelemetry.io/proto/slim/otlp/trace/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopySpan(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSpan() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewSpan()\n\t\t\t\tCopySpan(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopySpan(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopySpanSlice(t *testing.T) {\n\tsrc := []Span{}\n\tdest := []Span{}\n\t// Test CopyTo empty\n\tdest = CopySpanSlice(dest, src)\n\tassert.Equal(t, []Span{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSpanSlice()\n\tdest = CopySpanSlice(dest, src)\n\tassert.Equal(t, GenTestSpanSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySpanSlice(dest, src)\n\tassert.Equal(t, GenTestSpanSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySpanSlice(dest, []Span{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySpanSlice(dest, src)\n\tassert.Equal(t, GenTestSpanSlice(), dest)\n}\n\nfunc TestCopySpanPtrSlice(t *testing.T) {\n\tsrc := []*Span{}\n\tdest := []*Span{}\n\t// Test CopyTo empty\n\tdest = CopySpanPtrSlice(dest, src)\n\tassert.Equal(t, []*Span{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSpanPtrSlice()\n\tdest = CopySpanPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSpanPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySpanPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSpanPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySpanPtrSlice(dest, []*Span{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySpanPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSpanPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSpanUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewSpan()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewSpan(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSpan(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSpan() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewSpan()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSpan(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSpanFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesSpan() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewSpan()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSpanUnknown(t *testing.T) {\n\tdest := NewSpan()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewSpan(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoSpan(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSpan() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewSpan()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSpan(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufSpan(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSpan() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlptrace.Span{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewSpan()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesSpan() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                          {0x02},\n\t\t\"TraceId/wrong_wire_type\":                {0xc},\n\t\t\"TraceId/missing_value\":                  {0xa},\n\t\t\"SpanId/wrong_wire_type\":                 {0x14},\n\t\t\"SpanId/missing_value\":                   {0x12},\n\t\t\"TraceState/wrong_wire_type\":             {0x1c},\n\t\t\"TraceState/missing_value\":               {0x1a},\n\t\t\"ParentSpanId/wrong_wire_type\":           {0x24},\n\t\t\"ParentSpanId/missing_value\":             {0x22},\n\t\t\"Flags/wrong_wire_type\":                  {0x84, 0x1},\n\t\t\"Flags/missing_value\":                    {0x85, 0x1},\n\t\t\"Name/wrong_wire_type\":                   {0x2c},\n\t\t\"Name/missing_value\":                     {0x2a},\n\t\t\"Kind/wrong_wire_type\":                   {0x34},\n\t\t\"Kind/missing_value\":                     {0x30},\n\t\t\"StartTimeUnixNano/wrong_wire_type\":      {0x3c},\n\t\t\"StartTimeUnixNano/missing_value\":        {0x39},\n\t\t\"EndTimeUnixNano/wrong_wire_type\":        {0x44},\n\t\t\"EndTimeUnixNano/missing_value\":          {0x41},\n\t\t\"Attributes/wrong_wire_type\":             {0x4c},\n\t\t\"Attributes/missing_value\":               {0x4a},\n\t\t\"DroppedAttributesCount/wrong_wire_type\": {0x54},\n\t\t\"DroppedAttributesCount/missing_value\":   {0x50},\n\t\t\"Events/wrong_wire_type\":                 {0x5c},\n\t\t\"Events/missing_value\":                   {0x5a},\n\t\t\"DroppedEventsCount/wrong_wire_type\":     {0x64},\n\t\t\"DroppedEventsCount/missing_value\":       {0x60},\n\t\t\"Links/wrong_wire_type\":                  {0x6c},\n\t\t\"Links/missing_value\":                    {0x6a},\n\t\t\"DroppedLinksCount/wrong_wire_type\":      {0x74},\n\t\t\"DroppedLinksCount/missing_value\":        {0x70},\n\t\t\"Status/wrong_wire_type\":                 {0x7c},\n\t\t\"Status/missing_value\":                   {0x7a},\n\t}\n}\n\nfunc genTestEncodingValuesSpan() map[string]*Span {\n\treturn map[string]*Span{\n\t\t\"empty\":                       NewSpan(),\n\t\t\"TraceId/test\":                {TraceId: *GenTestTraceID()},\n\t\t\"SpanId/test\":                 {SpanId: *GenTestSpanID()},\n\t\t\"TraceState/test\":             {TraceState: \"test_tracestate\"},\n\t\t\"ParentSpanId/test\":           {ParentSpanId: *GenTestSpanID()},\n\t\t\"Flags/test\":                  {Flags: uint32(13)},\n\t\t\"Name/test\":                   {Name: \"test_name\"},\n\t\t\"Kind/test\":                   {Kind: SpanKind(13)},\n\t\t\"StartTimeUnixNano/test\":      {StartTimeUnixNano: uint64(13)},\n\t\t\"EndTimeUnixNano/test\":        {EndTimeUnixNano: uint64(13)},\n\t\t\"Attributes/test\":             {Attributes: []KeyValue{{}, *GenTestKeyValue()}},\n\t\t\"DroppedAttributesCount/test\": {DroppedAttributesCount: uint32(13)},\n\t\t\"Events/test\":                 {Events: []*SpanEvent{{}, GenTestSpanEvent()}},\n\t\t\"DroppedEventsCount/test\":     {DroppedEventsCount: uint32(13)},\n\t\t\"Links/test\":                  {Links: []*SpanLink{{}, GenTestSpanLink()}},\n\t\t\"DroppedLinksCount/test\":      {DroppedLinksCount: uint32(13)},\n\t\t\"Status/test\":                 {Status: *GenTestStatus()},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_spancontext.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\ntype SpanContext struct {\n\tTraceState string\n\tTraceFlags uint32\n\tTraceID    TraceID\n\tSpanID     SpanID\n\tRemote     bool\n}\n\nvar (\n\tprotoPoolSpanContext = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &SpanContext{}\n\t\t},\n\t}\n)\n\nfunc NewSpanContext() *SpanContext {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &SpanContext{}\n\t}\n\treturn protoPoolSpanContext.Get().(*SpanContext)\n}\n\nfunc DeleteSpanContext(orig *SpanContext, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteTraceID(&orig.TraceID, false)\n\tDeleteSpanID(&orig.SpanID, false)\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolSpanContext.Put(orig)\n\t}\n}\n\nfunc CopySpanContext(dest, src *SpanContext) *SpanContext {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewSpanContext()\n\t}\n\tCopyTraceID(&dest.TraceID, &src.TraceID)\n\n\tCopySpanID(&dest.SpanID, &src.SpanID)\n\n\tdest.TraceFlags = src.TraceFlags\n\tdest.TraceState = src.TraceState\n\tdest.Remote = src.Remote\n\n\treturn dest\n}\n\nfunc CopySpanContextSlice(dest, src []SpanContext) []SpanContext {\n\tvar newDest []SpanContext\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]SpanContext, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSpanContext(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySpanContext(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopySpanContextPtrSlice(dest, src []*SpanContext) []*SpanContext {\n\tvar newDest []*SpanContext\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*SpanContext, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSpanContext()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSpanContext(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSpanContext()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySpanContext(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *SpanContext) Reset() {\n\t*orig = SpanContext{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *SpanContext) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif !orig.TraceID.IsEmpty() {\n\t\tdest.WriteObjectField(\"traceID\")\n\t\torig.TraceID.MarshalJSON(dest)\n\t}\n\tif !orig.SpanID.IsEmpty() {\n\t\tdest.WriteObjectField(\"spanID\")\n\t\torig.SpanID.MarshalJSON(dest)\n\t}\n\tif orig.TraceFlags != uint32(0) {\n\t\tdest.WriteObjectField(\"traceFlags\")\n\t\tdest.WriteUint32(orig.TraceFlags)\n\t}\n\tif orig.TraceState != \"\" {\n\t\tdest.WriteObjectField(\"traceState\")\n\t\tdest.WriteString(orig.TraceState)\n\t}\n\tif orig.Remote != false {\n\t\tdest.WriteObjectField(\"remote\")\n\t\tdest.WriteBool(orig.Remote)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *SpanContext) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"traceID\", \"trace_id\":\n\n\t\t\torig.TraceID.UnmarshalJSON(iter)\n\t\tcase \"spanID\", \"span_id\":\n\n\t\t\torig.SpanID.UnmarshalJSON(iter)\n\t\tcase \"traceFlags\", \"trace_flags\":\n\t\t\torig.TraceFlags = iter.ReadUint32()\n\t\tcase \"traceState\", \"trace_state\":\n\t\t\torig.TraceState = iter.ReadString()\n\t\tcase \"remote\":\n\t\t\torig.Remote = iter.ReadBool()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *SpanContext) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tl = orig.TraceID.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tl = orig.SpanID.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tif orig.TraceFlags != uint32(0) {\n\t\tn += 5\n\t}\n\n\tl = len(orig.TraceState)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.Remote != false {\n\t\tn += 2\n\t}\n\treturn n\n}\n\nfunc (orig *SpanContext) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = orig.TraceID.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0xa\n\n\tl = orig.SpanID.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x12\n\n\tif orig.TraceFlags != uint32(0) {\n\t\tpos -= 4\n\t\tbinary.LittleEndian.PutUint32(buf[pos:], uint32(orig.TraceFlags))\n\t\tpos--\n\t\tbuf[pos] = 0x1d\n\t}\n\tl = len(orig.TraceState)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.TraceState)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x22\n\t}\n\tif orig.Remote != false {\n\t\tpos--\n\t\tif orig.Remote {\n\t\t\tbuf[pos] = 1\n\t\t} else {\n\t\t\tbuf[pos] = 0\n\t\t}\n\t\tpos--\n\t\tbuf[pos] = 0x28\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *SpanContext) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TraceID\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.TraceID.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SpanID\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.SpanID.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeI32 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TraceFlags\", wireType)\n\t\t\t}\n\t\t\tvar num uint32\n\t\t\tnum, pos, err = proto.ConsumeI32(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.TraceFlags = uint32(num)\n\n\t\tcase 4:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TraceState\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.TraceState = string(buf[startPos:pos])\n\n\t\tcase 5:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Remote\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Remote = num != 0\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestSpanContext() *SpanContext {\n\torig := NewSpanContext()\n\torig.TraceID = *GenTestTraceID()\n\torig.SpanID = *GenTestSpanID()\n\torig.TraceFlags = uint32(13)\n\torig.TraceState = \"test_tracestate\"\n\torig.Remote = true\n\treturn orig\n}\n\nfunc GenTestSpanContextPtrSlice() []*SpanContext {\n\torig := make([]*SpanContext, 5)\n\torig[0] = NewSpanContext()\n\torig[1] = GenTestSpanContext()\n\torig[2] = NewSpanContext()\n\torig[3] = GenTestSpanContext()\n\torig[4] = NewSpanContext()\n\treturn orig\n}\n\nfunc GenTestSpanContextSlice() []SpanContext {\n\torig := make([]SpanContext, 5)\n\torig[1] = *GenTestSpanContext()\n\torig[3] = *GenTestSpanContext()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_spancontext_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/protobuf/proto\"\n\t\"google.golang.org/protobuf/types/known/emptypb\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopySpanContext(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSpanContext() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewSpanContext()\n\t\t\t\tCopySpanContext(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopySpanContext(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopySpanContextSlice(t *testing.T) {\n\tsrc := []SpanContext{}\n\tdest := []SpanContext{}\n\t// Test CopyTo empty\n\tdest = CopySpanContextSlice(dest, src)\n\tassert.Equal(t, []SpanContext{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSpanContextSlice()\n\tdest = CopySpanContextSlice(dest, src)\n\tassert.Equal(t, GenTestSpanContextSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySpanContextSlice(dest, src)\n\tassert.Equal(t, GenTestSpanContextSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySpanContextSlice(dest, []SpanContext{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySpanContextSlice(dest, src)\n\tassert.Equal(t, GenTestSpanContextSlice(), dest)\n}\n\nfunc TestCopySpanContextPtrSlice(t *testing.T) {\n\tsrc := []*SpanContext{}\n\tdest := []*SpanContext{}\n\t// Test CopyTo empty\n\tdest = CopySpanContextPtrSlice(dest, src)\n\tassert.Equal(t, []*SpanContext{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSpanContextPtrSlice()\n\tdest = CopySpanContextPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSpanContextPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySpanContextPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSpanContextPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySpanContextPtrSlice(dest, []*SpanContext{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySpanContextPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSpanContextPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSpanContextUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewSpanContext()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewSpanContext(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSpanContext(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSpanContext() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewSpanContext()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSpanContext(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSpanContextFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesSpanContext() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewSpanContext()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSpanContextUnknown(t *testing.T) {\n\tdest := NewSpanContext()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewSpanContext(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoSpanContext(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSpanContext() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewSpanContext()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSpanContext(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufSpanContext(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSpanContext() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &emptypb.Empty{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewSpanContext()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesSpanContext() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":              {0x02},\n\t\t\"TraceID/wrong_wire_type\":    {0xc},\n\t\t\"TraceID/missing_value\":      {0xa},\n\t\t\"SpanID/wrong_wire_type\":     {0x14},\n\t\t\"SpanID/missing_value\":       {0x12},\n\t\t\"TraceFlags/wrong_wire_type\": {0x1c},\n\t\t\"TraceFlags/missing_value\":   {0x1d},\n\t\t\"TraceState/wrong_wire_type\": {0x24},\n\t\t\"TraceState/missing_value\":   {0x22},\n\t\t\"Remote/wrong_wire_type\":     {0x2c},\n\t\t\"Remote/missing_value\":       {0x28},\n\t}\n}\n\nfunc genTestEncodingValuesSpanContext() map[string]*SpanContext {\n\treturn map[string]*SpanContext{\n\t\t\"empty\":           NewSpanContext(),\n\t\t\"TraceID/test\":    {TraceID: *GenTestTraceID()},\n\t\t\"SpanID/test\":     {SpanID: *GenTestSpanID()},\n\t\t\"TraceFlags/test\": {TraceFlags: uint32(13)},\n\t\t\"TraceState/test\": {TraceState: \"test_tracestate\"},\n\t\t\"Remote/test\":     {Remote: true},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_spanevent.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// SpanEvent is a time-stamped annotation of the span, consisting of user-supplied\n// text description and key-value pairs. See OTLP for event definition.\ntype SpanEvent struct {\n\tName                   string\n\tAttributes             []KeyValue\n\tTimeUnixNano           uint64\n\tDroppedAttributesCount uint32\n}\n\nvar (\n\tprotoPoolSpanEvent = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &SpanEvent{}\n\t\t},\n\t}\n)\n\nfunc NewSpanEvent() *SpanEvent {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &SpanEvent{}\n\t}\n\treturn protoPoolSpanEvent.Get().(*SpanEvent)\n}\n\nfunc DeleteSpanEvent(orig *SpanEvent, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\tfor i := range orig.Attributes {\n\t\tDeleteKeyValue(&orig.Attributes[i], false)\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolSpanEvent.Put(orig)\n\t}\n}\n\nfunc CopySpanEvent(dest, src *SpanEvent) *SpanEvent {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewSpanEvent()\n\t}\n\tdest.TimeUnixNano = src.TimeUnixNano\n\tdest.Name = src.Name\n\tdest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)\n\n\tdest.DroppedAttributesCount = src.DroppedAttributesCount\n\n\treturn dest\n}\n\nfunc CopySpanEventSlice(dest, src []SpanEvent) []SpanEvent {\n\tvar newDest []SpanEvent\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]SpanEvent, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSpanEvent(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySpanEvent(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopySpanEventPtrSlice(dest, src []*SpanEvent) []*SpanEvent {\n\tvar newDest []*SpanEvent\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*SpanEvent, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSpanEvent()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSpanEvent(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSpanEvent()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySpanEvent(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *SpanEvent) Reset() {\n\t*orig = SpanEvent{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *SpanEvent) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tdest.WriteObjectField(\"timeUnixNano\")\n\t\tdest.WriteUint64(orig.TimeUnixNano)\n\t}\n\tif orig.Name != \"\" {\n\t\tdest.WriteObjectField(\"name\")\n\t\tdest.WriteString(orig.Name)\n\t}\n\tif len(orig.Attributes) > 0 {\n\t\tdest.WriteObjectField(\"attributes\")\n\t\tdest.WriteArrayStart()\n\t\torig.Attributes[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Attributes); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Attributes[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tdest.WriteObjectField(\"droppedAttributesCount\")\n\t\tdest.WriteUint32(orig.DroppedAttributesCount)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *SpanEvent) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"timeUnixNano\", \"time_unix_nano\":\n\t\t\torig.TimeUnixNano = iter.ReadUint64()\n\t\tcase \"name\":\n\t\t\torig.Name = iter.ReadString()\n\t\tcase \"attributes\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\t\torig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"droppedAttributesCount\", \"dropped_attributes_count\":\n\t\t\torig.DroppedAttributesCount = iter.ReadUint32()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *SpanEvent) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tn += 9\n\t}\n\n\tl = len(orig.Name)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tfor i := range orig.Attributes {\n\t\tl = orig.Attributes[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.DroppedAttributesCount))\n\t}\n\treturn n\n}\n\nfunc (orig *SpanEvent) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimeUnixNano))\n\t\tpos--\n\t\tbuf[pos] = 0x9\n\t}\n\tl = len(orig.Name)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.Name)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tfor i := len(orig.Attributes) - 1; i >= 0; i-- {\n\t\tl = orig.Attributes[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedAttributesCount))\n\t\tpos--\n\t\tbuf[pos] = 0x20\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *SpanEvent) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TimeUnixNano\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.TimeUnixNano = uint64(num)\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Name\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Name = string(buf[startPos:pos])\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Attributes\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\terr = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 4:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DroppedAttributesCount\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.DroppedAttributesCount = uint32(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestSpanEvent() *SpanEvent {\n\torig := NewSpanEvent()\n\torig.TimeUnixNano = uint64(13)\n\torig.Name = \"test_name\"\n\torig.Attributes = []KeyValue{{}, *GenTestKeyValue()}\n\torig.DroppedAttributesCount = uint32(13)\n\treturn orig\n}\n\nfunc GenTestSpanEventPtrSlice() []*SpanEvent {\n\torig := make([]*SpanEvent, 5)\n\torig[0] = NewSpanEvent()\n\torig[1] = GenTestSpanEvent()\n\torig[2] = NewSpanEvent()\n\torig[3] = GenTestSpanEvent()\n\torig[4] = NewSpanEvent()\n\treturn orig\n}\n\nfunc GenTestSpanEventSlice() []SpanEvent {\n\torig := make([]SpanEvent, 5)\n\torig[1] = *GenTestSpanEvent()\n\torig[3] = *GenTestSpanEvent()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_spanevent_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlptrace \"go.opentelemetry.io/proto/slim/otlp/trace/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopySpanEvent(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSpanEvent() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewSpanEvent()\n\t\t\t\tCopySpanEvent(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopySpanEvent(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopySpanEventSlice(t *testing.T) {\n\tsrc := []SpanEvent{}\n\tdest := []SpanEvent{}\n\t// Test CopyTo empty\n\tdest = CopySpanEventSlice(dest, src)\n\tassert.Equal(t, []SpanEvent{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSpanEventSlice()\n\tdest = CopySpanEventSlice(dest, src)\n\tassert.Equal(t, GenTestSpanEventSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySpanEventSlice(dest, src)\n\tassert.Equal(t, GenTestSpanEventSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySpanEventSlice(dest, []SpanEvent{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySpanEventSlice(dest, src)\n\tassert.Equal(t, GenTestSpanEventSlice(), dest)\n}\n\nfunc TestCopySpanEventPtrSlice(t *testing.T) {\n\tsrc := []*SpanEvent{}\n\tdest := []*SpanEvent{}\n\t// Test CopyTo empty\n\tdest = CopySpanEventPtrSlice(dest, src)\n\tassert.Equal(t, []*SpanEvent{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSpanEventPtrSlice()\n\tdest = CopySpanEventPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSpanEventPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySpanEventPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSpanEventPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySpanEventPtrSlice(dest, []*SpanEvent{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySpanEventPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSpanEventPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSpanEventUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewSpanEvent()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewSpanEvent(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSpanEvent(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSpanEvent() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewSpanEvent()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSpanEvent(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSpanEventFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesSpanEvent() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewSpanEvent()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSpanEventUnknown(t *testing.T) {\n\tdest := NewSpanEvent()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewSpanEvent(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoSpanEvent(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSpanEvent() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewSpanEvent()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSpanEvent(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufSpanEvent(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSpanEvent() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlptrace.Span_Event{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewSpanEvent()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesSpanEvent() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                          {0x02},\n\t\t\"TimeUnixNano/wrong_wire_type\":           {0xc},\n\t\t\"TimeUnixNano/missing_value\":             {0x9},\n\t\t\"Name/wrong_wire_type\":                   {0x14},\n\t\t\"Name/missing_value\":                     {0x12},\n\t\t\"Attributes/wrong_wire_type\":             {0x1c},\n\t\t\"Attributes/missing_value\":               {0x1a},\n\t\t\"DroppedAttributesCount/wrong_wire_type\": {0x24},\n\t\t\"DroppedAttributesCount/missing_value\":   {0x20},\n\t}\n}\n\nfunc genTestEncodingValuesSpanEvent() map[string]*SpanEvent {\n\treturn map[string]*SpanEvent{\n\t\t\"empty\":                       NewSpanEvent(),\n\t\t\"TimeUnixNano/test\":           {TimeUnixNano: uint64(13)},\n\t\t\"Name/test\":                   {Name: \"test_name\"},\n\t\t\"Attributes/test\":             {Attributes: []KeyValue{{}, *GenTestKeyValue()}},\n\t\t\"DroppedAttributesCount/test\": {DroppedAttributesCount: uint32(13)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_spanlink.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// SpanLink is a pointer from the current span to another span in the same trace or in a\n// different trace.\n// See Link definition in OTLP: https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/trace/v1/trace.proto\ntype SpanLink struct {\n\tTraceState             string\n\tAttributes             []KeyValue\n\tDroppedAttributesCount uint32\n\tFlags                  uint32\n\tTraceId                TraceID\n\tSpanId                 SpanID\n}\n\nvar (\n\tprotoPoolSpanLink = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &SpanLink{}\n\t\t},\n\t}\n)\n\nfunc NewSpanLink() *SpanLink {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &SpanLink{}\n\t}\n\treturn protoPoolSpanLink.Get().(*SpanLink)\n}\n\nfunc DeleteSpanLink(orig *SpanLink, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteTraceID(&orig.TraceId, false)\n\tDeleteSpanID(&orig.SpanId, false)\n\n\tfor i := range orig.Attributes {\n\t\tDeleteKeyValue(&orig.Attributes[i], false)\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolSpanLink.Put(orig)\n\t}\n}\n\nfunc CopySpanLink(dest, src *SpanLink) *SpanLink {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewSpanLink()\n\t}\n\tCopyTraceID(&dest.TraceId, &src.TraceId)\n\n\tCopySpanID(&dest.SpanId, &src.SpanId)\n\n\tdest.TraceState = src.TraceState\n\tdest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)\n\n\tdest.DroppedAttributesCount = src.DroppedAttributesCount\n\tdest.Flags = src.Flags\n\n\treturn dest\n}\n\nfunc CopySpanLinkSlice(dest, src []SpanLink) []SpanLink {\n\tvar newDest []SpanLink\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]SpanLink, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSpanLink(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySpanLink(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopySpanLinkPtrSlice(dest, src []*SpanLink) []*SpanLink {\n\tvar newDest []*SpanLink\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*SpanLink, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSpanLink()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSpanLink(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSpanLink()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySpanLink(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *SpanLink) Reset() {\n\t*orig = SpanLink{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *SpanLink) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif !orig.TraceId.IsEmpty() {\n\t\tdest.WriteObjectField(\"traceId\")\n\t\torig.TraceId.MarshalJSON(dest)\n\t}\n\tif !orig.SpanId.IsEmpty() {\n\t\tdest.WriteObjectField(\"spanId\")\n\t\torig.SpanId.MarshalJSON(dest)\n\t}\n\tif orig.TraceState != \"\" {\n\t\tdest.WriteObjectField(\"traceState\")\n\t\tdest.WriteString(orig.TraceState)\n\t}\n\tif len(orig.Attributes) > 0 {\n\t\tdest.WriteObjectField(\"attributes\")\n\t\tdest.WriteArrayStart()\n\t\torig.Attributes[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Attributes); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Attributes[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tdest.WriteObjectField(\"droppedAttributesCount\")\n\t\tdest.WriteUint32(orig.DroppedAttributesCount)\n\t}\n\tif orig.Flags != uint32(0) {\n\t\tdest.WriteObjectField(\"flags\")\n\t\tdest.WriteUint32(orig.Flags)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *SpanLink) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"traceId\", \"trace_id\":\n\n\t\t\torig.TraceId.UnmarshalJSON(iter)\n\t\tcase \"spanId\", \"span_id\":\n\n\t\t\torig.SpanId.UnmarshalJSON(iter)\n\t\tcase \"traceState\", \"trace_state\":\n\t\t\torig.TraceState = iter.ReadString()\n\t\tcase \"attributes\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\t\torig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"droppedAttributesCount\", \"dropped_attributes_count\":\n\t\t\torig.DroppedAttributesCount = iter.ReadUint32()\n\t\tcase \"flags\":\n\t\t\torig.Flags = iter.ReadUint32()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *SpanLink) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tl = orig.TraceId.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tl = orig.SpanId.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\n\tl = len(orig.TraceState)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tfor i := range orig.Attributes {\n\t\tl = orig.Attributes[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.DroppedAttributesCount))\n\t}\n\tif orig.Flags != uint32(0) {\n\t\tn += 5\n\t}\n\treturn n\n}\n\nfunc (orig *SpanLink) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = orig.TraceId.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0xa\n\n\tl = orig.SpanId.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x12\n\n\tl = len(orig.TraceState)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.TraceState)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\tfor i := len(orig.Attributes) - 1; i >= 0; i-- {\n\t\tl = orig.Attributes[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x22\n\t}\n\tif orig.DroppedAttributesCount != uint32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.DroppedAttributesCount))\n\t\tpos--\n\t\tbuf[pos] = 0x28\n\t}\n\tif orig.Flags != uint32(0) {\n\t\tpos -= 4\n\t\tbinary.LittleEndian.PutUint32(buf[pos:], uint32(orig.Flags))\n\t\tpos--\n\t\tbuf[pos] = 0x35\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *SpanLink) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TraceId\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.TraceId.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field SpanId\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.SpanId.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TraceState\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.TraceState = string(buf[startPos:pos])\n\n\t\tcase 4:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Attributes\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\terr = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 5:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DroppedAttributesCount\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.DroppedAttributesCount = uint32(num)\n\n\t\tcase 6:\n\t\t\tif wireType != proto.WireTypeI32 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Flags\", wireType)\n\t\t\t}\n\t\t\tvar num uint32\n\t\t\tnum, pos, err = proto.ConsumeI32(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.Flags = uint32(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestSpanLink() *SpanLink {\n\torig := NewSpanLink()\n\torig.TraceId = *GenTestTraceID()\n\torig.SpanId = *GenTestSpanID()\n\torig.TraceState = \"test_tracestate\"\n\torig.Attributes = []KeyValue{{}, *GenTestKeyValue()}\n\torig.DroppedAttributesCount = uint32(13)\n\torig.Flags = uint32(13)\n\treturn orig\n}\n\nfunc GenTestSpanLinkPtrSlice() []*SpanLink {\n\torig := make([]*SpanLink, 5)\n\torig[0] = NewSpanLink()\n\torig[1] = GenTestSpanLink()\n\torig[2] = NewSpanLink()\n\torig[3] = GenTestSpanLink()\n\torig[4] = NewSpanLink()\n\treturn orig\n}\n\nfunc GenTestSpanLinkSlice() []SpanLink {\n\torig := make([]SpanLink, 5)\n\torig[1] = *GenTestSpanLink()\n\torig[3] = *GenTestSpanLink()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_spanlink_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlptrace \"go.opentelemetry.io/proto/slim/otlp/trace/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopySpanLink(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSpanLink() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewSpanLink()\n\t\t\t\tCopySpanLink(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopySpanLink(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopySpanLinkSlice(t *testing.T) {\n\tsrc := []SpanLink{}\n\tdest := []SpanLink{}\n\t// Test CopyTo empty\n\tdest = CopySpanLinkSlice(dest, src)\n\tassert.Equal(t, []SpanLink{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSpanLinkSlice()\n\tdest = CopySpanLinkSlice(dest, src)\n\tassert.Equal(t, GenTestSpanLinkSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySpanLinkSlice(dest, src)\n\tassert.Equal(t, GenTestSpanLinkSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySpanLinkSlice(dest, []SpanLink{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySpanLinkSlice(dest, src)\n\tassert.Equal(t, GenTestSpanLinkSlice(), dest)\n}\n\nfunc TestCopySpanLinkPtrSlice(t *testing.T) {\n\tsrc := []*SpanLink{}\n\tdest := []*SpanLink{}\n\t// Test CopyTo empty\n\tdest = CopySpanLinkPtrSlice(dest, src)\n\tassert.Equal(t, []*SpanLink{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSpanLinkPtrSlice()\n\tdest = CopySpanLinkPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSpanLinkPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySpanLinkPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSpanLinkPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySpanLinkPtrSlice(dest, []*SpanLink{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySpanLinkPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSpanLinkPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSpanLinkUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewSpanLink()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewSpanLink(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSpanLink(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSpanLink() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewSpanLink()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSpanLink(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSpanLinkFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesSpanLink() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewSpanLink()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSpanLinkUnknown(t *testing.T) {\n\tdest := NewSpanLink()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewSpanLink(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoSpanLink(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSpanLink() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewSpanLink()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSpanLink(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufSpanLink(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSpanLink() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlptrace.Span_Link{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewSpanLink()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesSpanLink() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                          {0x02},\n\t\t\"TraceId/wrong_wire_type\":                {0xc},\n\t\t\"TraceId/missing_value\":                  {0xa},\n\t\t\"SpanId/wrong_wire_type\":                 {0x14},\n\t\t\"SpanId/missing_value\":                   {0x12},\n\t\t\"TraceState/wrong_wire_type\":             {0x1c},\n\t\t\"TraceState/missing_value\":               {0x1a},\n\t\t\"Attributes/wrong_wire_type\":             {0x24},\n\t\t\"Attributes/missing_value\":               {0x22},\n\t\t\"DroppedAttributesCount/wrong_wire_type\": {0x2c},\n\t\t\"DroppedAttributesCount/missing_value\":   {0x28},\n\t\t\"Flags/wrong_wire_type\":                  {0x34},\n\t\t\"Flags/missing_value\":                    {0x35},\n\t}\n}\n\nfunc genTestEncodingValuesSpanLink() map[string]*SpanLink {\n\treturn map[string]*SpanLink{\n\t\t\"empty\":                       NewSpanLink(),\n\t\t\"TraceId/test\":                {TraceId: *GenTestTraceID()},\n\t\t\"SpanId/test\":                 {SpanId: *GenTestSpanID()},\n\t\t\"TraceState/test\":             {TraceState: \"test_tracestate\"},\n\t\t\"Attributes/test\":             {Attributes: []KeyValue{{}, *GenTestKeyValue()}},\n\t\t\"DroppedAttributesCount/test\": {DroppedAttributesCount: uint32(13)},\n\t\t\"Flags/test\":                  {Flags: uint32(13)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_stack.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Stack represents a stack trace as a list of locations.\n\ntype Stack struct {\n\tLocationIndices []int32\n}\n\nvar (\n\tprotoPoolStack = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Stack{}\n\t\t},\n\t}\n)\n\nfunc NewStack() *Stack {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &Stack{}\n\t}\n\treturn protoPoolStack.Get().(*Stack)\n}\n\nfunc DeleteStack(orig *Stack, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolStack.Put(orig)\n\t}\n}\n\nfunc CopyStack(dest, src *Stack) *Stack {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewStack()\n\t}\n\tdest.LocationIndices = append(dest.LocationIndices[:0], src.LocationIndices...)\n\n\treturn dest\n}\n\nfunc CopyStackSlice(dest, src []Stack) []Stack {\n\tvar newDest []Stack\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]Stack, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteStack(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyStack(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyStackPtrSlice(dest, src []*Stack) []*Stack {\n\tvar newDest []*Stack\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*Stack, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewStack()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteStack(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewStack()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyStack(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *Stack) Reset() {\n\t*orig = Stack{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *Stack) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.LocationIndices) > 0 {\n\t\tdest.WriteObjectField(\"locationIndices\")\n\t\tdest.WriteArrayStart()\n\t\tdest.WriteInt32(orig.LocationIndices[0])\n\t\tfor i := 1; i < len(orig.LocationIndices); i++ {\n\t\t\tdest.WriteMore()\n\t\t\tdest.WriteInt32(orig.LocationIndices[i])\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *Stack) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"locationIndices\", \"location_indices\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.LocationIndices = append(orig.LocationIndices, iter.ReadInt32())\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *Stack) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\n\tif len(orig.LocationIndices) > 0 {\n\t\tl = 0\n\t\tfor _, e := range orig.LocationIndices {\n\t\t\tl += proto.Sov(uint64(e))\n\t\t}\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *Stack) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = len(orig.LocationIndices)\n\tif l > 0 {\n\t\tendPos := pos\n\t\tfor i := l - 1; i >= 0; i-- {\n\t\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.LocationIndices[i]))\n\t\t}\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(endPos-pos))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *Stack) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\t\tcase 1:\n\t\t\tswitch wireType {\n\t\t\tcase proto.WireTypeLen:\n\t\t\t\tvar length int\n\t\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tstartPos := pos - length\n\t\t\t\tvar num uint64\n\t\t\t\tfor startPos < pos {\n\t\t\t\t\tnum, startPos, err = proto.ConsumeVarint(buf[:pos], startPos)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\treturn err\n\t\t\t\t\t}\n\t\t\t\t\torig.LocationIndices = append(orig.LocationIndices, int32(num))\n\t\t\t\t}\n\t\t\t\tif startPos != pos {\n\t\t\t\t\treturn fmt.Errorf(\"proto: invalid field len = %d for field LocationIndices\", pos-startPos)\n\t\t\t\t}\n\t\t\tcase proto.WireTypeVarint:\n\t\t\t\tvar num uint64\n\t\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\torig.LocationIndices = append(orig.LocationIndices, int32(num))\n\t\t\tdefault:\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field LocationIndices\", wireType)\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestStack() *Stack {\n\torig := NewStack()\n\torig.LocationIndices = []int32{int32(0), int32(13)}\n\treturn orig\n}\n\nfunc GenTestStackPtrSlice() []*Stack {\n\torig := make([]*Stack, 5)\n\torig[0] = NewStack()\n\torig[1] = GenTestStack()\n\torig[2] = NewStack()\n\torig[3] = GenTestStack()\n\torig[4] = NewStack()\n\treturn orig\n}\n\nfunc GenTestStackSlice() []Stack {\n\torig := make([]Stack, 5)\n\torig[1] = *GenTestStack()\n\torig[3] = *GenTestStack()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_stack_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpprofiles \"go.opentelemetry.io/proto/slim/otlp/profiles/v1development\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyStack(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesStack() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewStack()\n\t\t\t\tCopyStack(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyStack(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyStackSlice(t *testing.T) {\n\tsrc := []Stack{}\n\tdest := []Stack{}\n\t// Test CopyTo empty\n\tdest = CopyStackSlice(dest, src)\n\tassert.Equal(t, []Stack{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestStackSlice()\n\tdest = CopyStackSlice(dest, src)\n\tassert.Equal(t, GenTestStackSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyStackSlice(dest, src)\n\tassert.Equal(t, GenTestStackSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyStackSlice(dest, []Stack{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyStackSlice(dest, src)\n\tassert.Equal(t, GenTestStackSlice(), dest)\n}\n\nfunc TestCopyStackPtrSlice(t *testing.T) {\n\tsrc := []*Stack{}\n\tdest := []*Stack{}\n\t// Test CopyTo empty\n\tdest = CopyStackPtrSlice(dest, src)\n\tassert.Equal(t, []*Stack{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestStackPtrSlice()\n\tdest = CopyStackPtrSlice(dest, src)\n\tassert.Equal(t, GenTestStackPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyStackPtrSlice(dest, src)\n\tassert.Equal(t, GenTestStackPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyStackPtrSlice(dest, []*Stack{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyStackPtrSlice(dest, src)\n\tassert.Equal(t, GenTestStackPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONStackUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewStack()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewStack(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONStack(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesStack() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewStack()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteStack(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoStackFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesStack() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewStack()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoStackUnknown(t *testing.T) {\n\tdest := NewStack()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewStack(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoStack(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesStack() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewStack()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteStack(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufStack(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesStack() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpprofiles.Stack{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewStack()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesStack() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                   {0x02},\n\t\t\"LocationIndices/wrong_wire_type\": {0xc},\n\t\t\"LocationIndices/missing_value\":   {0xa},\n\t}\n}\n\nfunc genTestEncodingValuesStack() map[string]*Stack {\n\treturn map[string]*Stack{\n\t\t\"empty\":                NewStack(),\n\t\t\"LocationIndices/test\": {LocationIndices: []int32{int32(0), int32(13)}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_status.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Status is an optional final status for this span. Semantically, when Status was not\n// set, that means the span ended without errors and to assume Status.Ok (code = 0).\ntype Status struct {\n\tMessage string\n\tCode    StatusCode\n}\n\nvar (\n\tprotoPoolStatus = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Status{}\n\t\t},\n\t}\n)\n\nfunc NewStatus() *Status {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &Status{}\n\t}\n\treturn protoPoolStatus.Get().(*Status)\n}\n\nfunc DeleteStatus(orig *Status, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolStatus.Put(orig)\n\t}\n}\n\nfunc CopyStatus(dest, src *Status) *Status {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewStatus()\n\t}\n\tdest.Message = src.Message\n\tdest.Code = src.Code\n\n\treturn dest\n}\n\nfunc CopyStatusSlice(dest, src []Status) []Status {\n\tvar newDest []Status\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]Status, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteStatus(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyStatus(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyStatusPtrSlice(dest, src []*Status) []*Status {\n\tvar newDest []*Status\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*Status, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewStatus()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteStatus(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewStatus()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyStatus(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *Status) Reset() {\n\t*orig = Status{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *Status) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.Message != \"\" {\n\t\tdest.WriteObjectField(\"message\")\n\t\tdest.WriteString(orig.Message)\n\t}\n\n\tif int32(orig.Code) != 0 {\n\t\tdest.WriteObjectField(\"code\")\n\t\tdest.WriteInt32(int32(orig.Code))\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *Status) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"message\":\n\t\t\torig.Message = iter.ReadString()\n\t\tcase \"code\":\n\t\t\torig.Code = StatusCode(iter.ReadEnumValue(StatusCode_value))\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *Status) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\n\tl = len(orig.Message)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.Code != StatusCode(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.Code))\n\t}\n\treturn n\n}\n\nfunc (orig *Status) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = len(orig.Message)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.Message)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tif orig.Code != StatusCode(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.Code))\n\t\tpos--\n\t\tbuf[pos] = 0x18\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *Status) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Message\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Message = string(buf[startPos:pos])\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Code\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Code = StatusCode(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestStatus() *Status {\n\torig := NewStatus()\n\torig.Message = \"test_message\"\n\torig.Code = StatusCode(13)\n\treturn orig\n}\n\nfunc GenTestStatusPtrSlice() []*Status {\n\torig := make([]*Status, 5)\n\torig[0] = NewStatus()\n\torig[1] = GenTestStatus()\n\torig[2] = NewStatus()\n\torig[3] = GenTestStatus()\n\torig[4] = NewStatus()\n\treturn orig\n}\n\nfunc GenTestStatusSlice() []Status {\n\torig := make([]Status, 5)\n\torig[1] = *GenTestStatus()\n\torig[3] = *GenTestStatus()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_status_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlptrace \"go.opentelemetry.io/proto/slim/otlp/trace/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyStatus(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesStatus() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewStatus()\n\t\t\t\tCopyStatus(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyStatus(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyStatusSlice(t *testing.T) {\n\tsrc := []Status{}\n\tdest := []Status{}\n\t// Test CopyTo empty\n\tdest = CopyStatusSlice(dest, src)\n\tassert.Equal(t, []Status{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestStatusSlice()\n\tdest = CopyStatusSlice(dest, src)\n\tassert.Equal(t, GenTestStatusSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyStatusSlice(dest, src)\n\tassert.Equal(t, GenTestStatusSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyStatusSlice(dest, []Status{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyStatusSlice(dest, src)\n\tassert.Equal(t, GenTestStatusSlice(), dest)\n}\n\nfunc TestCopyStatusPtrSlice(t *testing.T) {\n\tsrc := []*Status{}\n\tdest := []*Status{}\n\t// Test CopyTo empty\n\tdest = CopyStatusPtrSlice(dest, src)\n\tassert.Equal(t, []*Status{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestStatusPtrSlice()\n\tdest = CopyStatusPtrSlice(dest, src)\n\tassert.Equal(t, GenTestStatusPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyStatusPtrSlice(dest, src)\n\tassert.Equal(t, GenTestStatusPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyStatusPtrSlice(dest, []*Status{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyStatusPtrSlice(dest, src)\n\tassert.Equal(t, GenTestStatusPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONStatusUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewStatus()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewStatus(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONStatus(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesStatus() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewStatus()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteStatus(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoStatusFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesStatus() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewStatus()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoStatusUnknown(t *testing.T) {\n\tdest := NewStatus()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewStatus(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoStatus(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesStatus() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewStatus()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteStatus(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufStatus(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesStatus() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlptrace.Status{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewStatus()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesStatus() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":           {0x02},\n\t\t\"Message/wrong_wire_type\": {0x14},\n\t\t\"Message/missing_value\":   {0x12},\n\t\t\"Code/wrong_wire_type\":    {0x1c},\n\t\t\"Code/missing_value\":      {0x18},\n\t}\n}\n\nfunc genTestEncodingValuesStatus() map[string]*Status {\n\treturn map[string]*Status{\n\t\t\"empty\":        NewStatus(),\n\t\t\"Message/test\": {Message: \"test_message\"},\n\t\t\"Code/test\":    {Code: StatusCode(13)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_sum.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Sum represents the type of a numeric metric that is calculated as a sum of all reported measurements over a time interval.\ntype Sum struct {\n\tDataPoints             []*NumberDataPoint\n\tAggregationTemporality AggregationTemporality\n\tIsMonotonic            bool\n}\n\nvar (\n\tprotoPoolSum = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Sum{}\n\t\t},\n\t}\n)\n\nfunc NewSum() *Sum {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &Sum{}\n\t}\n\treturn protoPoolSum.Get().(*Sum)\n}\n\nfunc DeleteSum(orig *Sum, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.DataPoints {\n\t\tDeleteNumberDataPoint(orig.DataPoints[i], true)\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolSum.Put(orig)\n\t}\n}\n\nfunc CopySum(dest, src *Sum) *Sum {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewSum()\n\t}\n\tdest.DataPoints = CopyNumberDataPointPtrSlice(dest.DataPoints, src.DataPoints)\n\n\tdest.AggregationTemporality = src.AggregationTemporality\n\tdest.IsMonotonic = src.IsMonotonic\n\n\treturn dest\n}\n\nfunc CopySumSlice(dest, src []Sum) []Sum {\n\tvar newDest []Sum\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]Sum, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSum(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySum(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopySumPtrSlice(dest, src []*Sum) []*Sum {\n\tvar newDest []*Sum\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*Sum, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSum()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSum(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSum()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySum(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *Sum) Reset() {\n\t*orig = Sum{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *Sum) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.DataPoints) > 0 {\n\t\tdest.WriteObjectField(\"dataPoints\")\n\t\tdest.WriteArrayStart()\n\t\torig.DataPoints[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.DataPoints); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.DataPoints[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\n\tif int32(orig.AggregationTemporality) != 0 {\n\t\tdest.WriteObjectField(\"aggregationTemporality\")\n\t\tdest.WriteInt32(int32(orig.AggregationTemporality))\n\t}\n\tif orig.IsMonotonic != false {\n\t\tdest.WriteObjectField(\"isMonotonic\")\n\t\tdest.WriteBool(orig.IsMonotonic)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *Sum) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"dataPoints\", \"data_points\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.DataPoints = append(orig.DataPoints, NewNumberDataPoint())\n\t\t\t\torig.DataPoints[len(orig.DataPoints)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"aggregationTemporality\", \"aggregation_temporality\":\n\t\t\torig.AggregationTemporality = AggregationTemporality(iter.ReadEnumValue(AggregationTemporality_value))\n\t\tcase \"isMonotonic\", \"is_monotonic\":\n\t\t\torig.IsMonotonic = iter.ReadBool()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *Sum) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.DataPoints {\n\t\tl = orig.DataPoints[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.AggregationTemporality != AggregationTemporality(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.AggregationTemporality))\n\t}\n\tif orig.IsMonotonic != false {\n\t\tn += 2\n\t}\n\treturn n\n}\n\nfunc (orig *Sum) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.DataPoints) - 1; i >= 0; i-- {\n\t\tl = orig.DataPoints[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\tif orig.AggregationTemporality != AggregationTemporality(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.AggregationTemporality))\n\t\tpos--\n\t\tbuf[pos] = 0x10\n\t}\n\tif orig.IsMonotonic != false {\n\t\tpos--\n\t\tif orig.IsMonotonic {\n\t\t\tbuf[pos] = 1\n\t\t} else {\n\t\t\tbuf[pos] = 0\n\t\t}\n\t\tpos--\n\t\tbuf[pos] = 0x18\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *Sum) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DataPoints\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.DataPoints = append(orig.DataPoints, NewNumberDataPoint())\n\t\t\terr = orig.DataPoints[len(orig.DataPoints)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field AggregationTemporality\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.AggregationTemporality = AggregationTemporality(num)\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field IsMonotonic\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.IsMonotonic = num != 0\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestSum() *Sum {\n\torig := NewSum()\n\torig.DataPoints = []*NumberDataPoint{{}, GenTestNumberDataPoint()}\n\torig.AggregationTemporality = AggregationTemporality(13)\n\torig.IsMonotonic = true\n\treturn orig\n}\n\nfunc GenTestSumPtrSlice() []*Sum {\n\torig := make([]*Sum, 5)\n\torig[0] = NewSum()\n\torig[1] = GenTestSum()\n\torig[2] = NewSum()\n\torig[3] = GenTestSum()\n\torig[4] = NewSum()\n\treturn orig\n}\n\nfunc GenTestSumSlice() []Sum {\n\torig := make([]Sum, 5)\n\torig[1] = *GenTestSum()\n\torig[3] = *GenTestSum()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_sum_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopySum(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSum() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewSum()\n\t\t\t\tCopySum(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopySum(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopySumSlice(t *testing.T) {\n\tsrc := []Sum{}\n\tdest := []Sum{}\n\t// Test CopyTo empty\n\tdest = CopySumSlice(dest, src)\n\tassert.Equal(t, []Sum{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSumSlice()\n\tdest = CopySumSlice(dest, src)\n\tassert.Equal(t, GenTestSumSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySumSlice(dest, src)\n\tassert.Equal(t, GenTestSumSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySumSlice(dest, []Sum{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySumSlice(dest, src)\n\tassert.Equal(t, GenTestSumSlice(), dest)\n}\n\nfunc TestCopySumPtrSlice(t *testing.T) {\n\tsrc := []*Sum{}\n\tdest := []*Sum{}\n\t// Test CopyTo empty\n\tdest = CopySumPtrSlice(dest, src)\n\tassert.Equal(t, []*Sum{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSumPtrSlice()\n\tdest = CopySumPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSumPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySumPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSumPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySumPtrSlice(dest, []*Sum{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySumPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSumPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSumUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewSum()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewSum(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSum(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSum() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewSum()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSum(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSumFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesSum() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewSum()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSumUnknown(t *testing.T) {\n\tdest := NewSum()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewSum(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoSum(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSum() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewSum()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSum(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufSum(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSum() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpmetrics.Sum{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewSum()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesSum() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                          {0x02},\n\t\t\"DataPoints/wrong_wire_type\":             {0xc},\n\t\t\"DataPoints/missing_value\":               {0xa},\n\t\t\"AggregationTemporality/wrong_wire_type\": {0x14},\n\t\t\"AggregationTemporality/missing_value\":   {0x10},\n\t\t\"IsMonotonic/wrong_wire_type\":            {0x1c},\n\t\t\"IsMonotonic/missing_value\":              {0x18},\n\t}\n}\n\nfunc genTestEncodingValuesSum() map[string]*Sum {\n\treturn map[string]*Sum{\n\t\t\"empty\":                       NewSum(),\n\t\t\"DataPoints/test\":             {DataPoints: []*NumberDataPoint{{}, GenTestNumberDataPoint()}},\n\t\t\"AggregationTemporality/test\": {AggregationTemporality: AggregationTemporality(13)},\n\t\t\"IsMonotonic/test\":            {IsMonotonic: true},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_summary.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// Summary represents the type of a metric that is calculated by aggregating as a Summary of all reported double measurements over a time interval.\ntype Summary struct {\n\tDataPoints []*SummaryDataPoint\n}\n\nvar (\n\tprotoPoolSummary = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &Summary{}\n\t\t},\n\t}\n)\n\nfunc NewSummary() *Summary {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &Summary{}\n\t}\n\treturn protoPoolSummary.Get().(*Summary)\n}\n\nfunc DeleteSummary(orig *Summary, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.DataPoints {\n\t\tDeleteSummaryDataPoint(orig.DataPoints[i], true)\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolSummary.Put(orig)\n\t}\n}\n\nfunc CopySummary(dest, src *Summary) *Summary {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewSummary()\n\t}\n\tdest.DataPoints = CopySummaryDataPointPtrSlice(dest.DataPoints, src.DataPoints)\n\n\treturn dest\n}\n\nfunc CopySummarySlice(dest, src []Summary) []Summary {\n\tvar newDest []Summary\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]Summary, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSummary(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySummary(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopySummaryPtrSlice(dest, src []*Summary) []*Summary {\n\tvar newDest []*Summary\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*Summary, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSummary()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSummary(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSummary()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySummary(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *Summary) Reset() {\n\t*orig = Summary{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *Summary) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.DataPoints) > 0 {\n\t\tdest.WriteObjectField(\"dataPoints\")\n\t\tdest.WriteArrayStart()\n\t\torig.DataPoints[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.DataPoints); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.DataPoints[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *Summary) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"dataPoints\", \"data_points\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.DataPoints = append(orig.DataPoints, NewSummaryDataPoint())\n\t\t\t\torig.DataPoints[len(orig.DataPoints)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *Summary) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.DataPoints {\n\t\tl = orig.DataPoints[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *Summary) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.DataPoints) - 1; i >= 0; i-- {\n\t\tl = orig.DataPoints[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *Summary) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field DataPoints\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.DataPoints = append(orig.DataPoints, NewSummaryDataPoint())\n\t\t\terr = orig.DataPoints[len(orig.DataPoints)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestSummary() *Summary {\n\torig := NewSummary()\n\torig.DataPoints = []*SummaryDataPoint{{}, GenTestSummaryDataPoint()}\n\treturn orig\n}\n\nfunc GenTestSummaryPtrSlice() []*Summary {\n\torig := make([]*Summary, 5)\n\torig[0] = NewSummary()\n\torig[1] = GenTestSummary()\n\torig[2] = NewSummary()\n\torig[3] = GenTestSummary()\n\torig[4] = NewSummary()\n\treturn orig\n}\n\nfunc GenTestSummarySlice() []Summary {\n\torig := make([]Summary, 5)\n\torig[1] = *GenTestSummary()\n\torig[3] = *GenTestSummary()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_summary_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopySummary(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSummary() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewSummary()\n\t\t\t\tCopySummary(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopySummary(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopySummarySlice(t *testing.T) {\n\tsrc := []Summary{}\n\tdest := []Summary{}\n\t// Test CopyTo empty\n\tdest = CopySummarySlice(dest, src)\n\tassert.Equal(t, []Summary{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSummarySlice()\n\tdest = CopySummarySlice(dest, src)\n\tassert.Equal(t, GenTestSummarySlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySummarySlice(dest, src)\n\tassert.Equal(t, GenTestSummarySlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySummarySlice(dest, []Summary{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySummarySlice(dest, src)\n\tassert.Equal(t, GenTestSummarySlice(), dest)\n}\n\nfunc TestCopySummaryPtrSlice(t *testing.T) {\n\tsrc := []*Summary{}\n\tdest := []*Summary{}\n\t// Test CopyTo empty\n\tdest = CopySummaryPtrSlice(dest, src)\n\tassert.Equal(t, []*Summary{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSummaryPtrSlice()\n\tdest = CopySummaryPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSummaryPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySummaryPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSummaryPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySummaryPtrSlice(dest, []*Summary{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySummaryPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSummaryPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSummaryUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewSummary()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewSummary(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSummary(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSummary() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewSummary()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSummary(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSummaryFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesSummary() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewSummary()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSummaryUnknown(t *testing.T) {\n\tdest := NewSummary()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewSummary(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoSummary(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSummary() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewSummary()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSummary(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufSummary(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSummary() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpmetrics.Summary{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewSummary()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesSummary() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":              {0x02},\n\t\t\"DataPoints/wrong_wire_type\": {0xc},\n\t\t\"DataPoints/missing_value\":   {0xa},\n\t}\n}\n\nfunc genTestEncodingValuesSummary() map[string]*Summary {\n\treturn map[string]*Summary{\n\t\t\"empty\":           NewSummary(),\n\t\t\"DataPoints/test\": {DataPoints: []*SummaryDataPoint{{}, GenTestSummaryDataPoint()}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_summarydatapoint.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"math\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// SummaryDataPoint is a single data point in a timeseries that describes the time-varying values of a Summary of double values.\ntype SummaryDataPoint struct {\n\tAttributes        []KeyValue\n\tQuantileValues    []*SummaryDataPointValueAtQuantile\n\tStartTimeUnixNano uint64\n\tTimeUnixNano      uint64\n\tCount             uint64\n\tSum               float64\n\tFlags             uint32\n}\n\nvar (\n\tprotoPoolSummaryDataPoint = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &SummaryDataPoint{}\n\t\t},\n\t}\n)\n\nfunc NewSummaryDataPoint() *SummaryDataPoint {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &SummaryDataPoint{}\n\t}\n\treturn protoPoolSummaryDataPoint.Get().(*SummaryDataPoint)\n}\n\nfunc DeleteSummaryDataPoint(orig *SummaryDataPoint, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.Attributes {\n\t\tDeleteKeyValue(&orig.Attributes[i], false)\n\t}\n\n\tfor i := range orig.QuantileValues {\n\t\tDeleteSummaryDataPointValueAtQuantile(orig.QuantileValues[i], true)\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolSummaryDataPoint.Put(orig)\n\t}\n}\n\nfunc CopySummaryDataPoint(dest, src *SummaryDataPoint) *SummaryDataPoint {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewSummaryDataPoint()\n\t}\n\tdest.Attributes = CopyKeyValueSlice(dest.Attributes, src.Attributes)\n\n\tdest.StartTimeUnixNano = src.StartTimeUnixNano\n\tdest.TimeUnixNano = src.TimeUnixNano\n\tdest.Count = src.Count\n\tdest.Sum = src.Sum\n\tdest.QuantileValues = CopySummaryDataPointValueAtQuantilePtrSlice(dest.QuantileValues, src.QuantileValues)\n\n\tdest.Flags = src.Flags\n\n\treturn dest\n}\n\nfunc CopySummaryDataPointSlice(dest, src []SummaryDataPoint) []SummaryDataPoint {\n\tvar newDest []SummaryDataPoint\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]SummaryDataPoint, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSummaryDataPoint(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySummaryDataPoint(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopySummaryDataPointPtrSlice(dest, src []*SummaryDataPoint) []*SummaryDataPoint {\n\tvar newDest []*SummaryDataPoint\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*SummaryDataPoint, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSummaryDataPoint()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSummaryDataPoint(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSummaryDataPoint()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySummaryDataPoint(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *SummaryDataPoint) Reset() {\n\t*orig = SummaryDataPoint{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *SummaryDataPoint) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.Attributes) > 0 {\n\t\tdest.WriteObjectField(\"attributes\")\n\t\tdest.WriteArrayStart()\n\t\torig.Attributes[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.Attributes); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.Attributes[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.StartTimeUnixNano != uint64(0) {\n\t\tdest.WriteObjectField(\"startTimeUnixNano\")\n\t\tdest.WriteUint64(orig.StartTimeUnixNano)\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tdest.WriteObjectField(\"timeUnixNano\")\n\t\tdest.WriteUint64(orig.TimeUnixNano)\n\t}\n\tif orig.Count != uint64(0) {\n\t\tdest.WriteObjectField(\"count\")\n\t\tdest.WriteUint64(orig.Count)\n\t}\n\tif orig.Sum != float64(0) {\n\t\tdest.WriteObjectField(\"sum\")\n\t\tdest.WriteFloat64(orig.Sum)\n\t}\n\tif len(orig.QuantileValues) > 0 {\n\t\tdest.WriteObjectField(\"quantileValues\")\n\t\tdest.WriteArrayStart()\n\t\torig.QuantileValues[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.QuantileValues); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.QuantileValues[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tif orig.Flags != uint32(0) {\n\t\tdest.WriteObjectField(\"flags\")\n\t\tdest.WriteUint32(orig.Flags)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *SummaryDataPoint) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"attributes\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\t\torig.Attributes[len(orig.Attributes)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"startTimeUnixNano\", \"start_time_unix_nano\":\n\t\t\torig.StartTimeUnixNano = iter.ReadUint64()\n\t\tcase \"timeUnixNano\", \"time_unix_nano\":\n\t\t\torig.TimeUnixNano = iter.ReadUint64()\n\t\tcase \"count\":\n\t\t\torig.Count = iter.ReadUint64()\n\t\tcase \"sum\":\n\t\t\torig.Sum = iter.ReadFloat64()\n\t\tcase \"quantileValues\", \"quantile_values\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.QuantileValues = append(orig.QuantileValues, NewSummaryDataPointValueAtQuantile())\n\t\t\t\torig.QuantileValues[len(orig.QuantileValues)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tcase \"flags\":\n\t\t\torig.Flags = iter.ReadUint32()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *SummaryDataPoint) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.Attributes {\n\t\tl = orig.Attributes[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.StartTimeUnixNano != uint64(0) {\n\t\tn += 9\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tn += 9\n\t}\n\tif orig.Count != uint64(0) {\n\t\tn += 9\n\t}\n\tif orig.Sum != float64(0) {\n\t\tn += 9\n\t}\n\tfor i := range orig.QuantileValues {\n\t\tl = orig.QuantileValues[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.Flags != uint32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.Flags))\n\t}\n\treturn n\n}\n\nfunc (orig *SummaryDataPoint) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.Attributes) - 1; i >= 0; i-- {\n\t\tl = orig.Attributes[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x3a\n\t}\n\tif orig.StartTimeUnixNano != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.StartTimeUnixNano))\n\t\tpos--\n\t\tbuf[pos] = 0x11\n\t}\n\tif orig.TimeUnixNano != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.TimeUnixNano))\n\t\tpos--\n\t\tbuf[pos] = 0x19\n\t}\n\tif orig.Count != uint64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], uint64(orig.Count))\n\t\tpos--\n\t\tbuf[pos] = 0x21\n\t}\n\tif orig.Sum != float64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Sum))\n\t\tpos--\n\t\tbuf[pos] = 0x29\n\t}\n\tfor i := len(orig.QuantileValues) - 1; i >= 0; i-- {\n\t\tl = orig.QuantileValues[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x32\n\t}\n\tif orig.Flags != uint32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.Flags))\n\t\tpos--\n\t\tbuf[pos] = 0x40\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *SummaryDataPoint) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 7:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Attributes\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Attributes = append(orig.Attributes, KeyValue{})\n\t\t\terr = orig.Attributes[len(orig.Attributes)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field StartTimeUnixNano\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.StartTimeUnixNano = uint64(num)\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TimeUnixNano\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.TimeUnixNano = uint64(num)\n\n\t\tcase 4:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Count\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.Count = uint64(num)\n\n\t\tcase 5:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Sum\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Sum = math.Float64frombits(num)\n\n\t\tcase 6:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field QuantileValues\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.QuantileValues = append(orig.QuantileValues, NewSummaryDataPointValueAtQuantile())\n\t\t\terr = orig.QuantileValues[len(orig.QuantileValues)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 8:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Flags\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Flags = uint32(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestSummaryDataPoint() *SummaryDataPoint {\n\torig := NewSummaryDataPoint()\n\torig.Attributes = []KeyValue{{}, *GenTestKeyValue()}\n\torig.StartTimeUnixNano = uint64(13)\n\torig.TimeUnixNano = uint64(13)\n\torig.Count = uint64(13)\n\torig.Sum = float64(3.1415926)\n\torig.QuantileValues = []*SummaryDataPointValueAtQuantile{{}, GenTestSummaryDataPointValueAtQuantile()}\n\torig.Flags = uint32(13)\n\treturn orig\n}\n\nfunc GenTestSummaryDataPointPtrSlice() []*SummaryDataPoint {\n\torig := make([]*SummaryDataPoint, 5)\n\torig[0] = NewSummaryDataPoint()\n\torig[1] = GenTestSummaryDataPoint()\n\torig[2] = NewSummaryDataPoint()\n\torig[3] = GenTestSummaryDataPoint()\n\torig[4] = NewSummaryDataPoint()\n\treturn orig\n}\n\nfunc GenTestSummaryDataPointSlice() []SummaryDataPoint {\n\torig := make([]SummaryDataPoint, 5)\n\torig[1] = *GenTestSummaryDataPoint()\n\torig[3] = *GenTestSummaryDataPoint()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_summarydatapoint_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopySummaryDataPoint(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSummaryDataPoint() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewSummaryDataPoint()\n\t\t\t\tCopySummaryDataPoint(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopySummaryDataPoint(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopySummaryDataPointSlice(t *testing.T) {\n\tsrc := []SummaryDataPoint{}\n\tdest := []SummaryDataPoint{}\n\t// Test CopyTo empty\n\tdest = CopySummaryDataPointSlice(dest, src)\n\tassert.Equal(t, []SummaryDataPoint{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSummaryDataPointSlice()\n\tdest = CopySummaryDataPointSlice(dest, src)\n\tassert.Equal(t, GenTestSummaryDataPointSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySummaryDataPointSlice(dest, src)\n\tassert.Equal(t, GenTestSummaryDataPointSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySummaryDataPointSlice(dest, []SummaryDataPoint{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySummaryDataPointSlice(dest, src)\n\tassert.Equal(t, GenTestSummaryDataPointSlice(), dest)\n}\n\nfunc TestCopySummaryDataPointPtrSlice(t *testing.T) {\n\tsrc := []*SummaryDataPoint{}\n\tdest := []*SummaryDataPoint{}\n\t// Test CopyTo empty\n\tdest = CopySummaryDataPointPtrSlice(dest, src)\n\tassert.Equal(t, []*SummaryDataPoint{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSummaryDataPointPtrSlice()\n\tdest = CopySummaryDataPointPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSummaryDataPointPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySummaryDataPointPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSummaryDataPointPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySummaryDataPointPtrSlice(dest, []*SummaryDataPoint{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySummaryDataPointPtrSlice(dest, src)\n\tassert.Equal(t, GenTestSummaryDataPointPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSummaryDataPointUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewSummaryDataPoint()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewSummaryDataPoint(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSummaryDataPoint(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSummaryDataPoint() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewSummaryDataPoint()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSummaryDataPoint(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSummaryDataPointFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesSummaryDataPoint() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewSummaryDataPoint()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSummaryDataPointUnknown(t *testing.T) {\n\tdest := NewSummaryDataPoint()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewSummaryDataPoint(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoSummaryDataPoint(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSummaryDataPoint() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewSummaryDataPoint()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSummaryDataPoint(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufSummaryDataPoint(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSummaryDataPoint() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpmetrics.SummaryDataPoint{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewSummaryDataPoint()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesSummaryDataPoint() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                     {0x02},\n\t\t\"Attributes/wrong_wire_type\":        {0x3c},\n\t\t\"Attributes/missing_value\":          {0x3a},\n\t\t\"StartTimeUnixNano/wrong_wire_type\": {0x14},\n\t\t\"StartTimeUnixNano/missing_value\":   {0x11},\n\t\t\"TimeUnixNano/wrong_wire_type\":      {0x1c},\n\t\t\"TimeUnixNano/missing_value\":        {0x19},\n\t\t\"Count/wrong_wire_type\":             {0x24},\n\t\t\"Count/missing_value\":               {0x21},\n\t\t\"Sum/wrong_wire_type\":               {0x2c},\n\t\t\"Sum/missing_value\":                 {0x29},\n\t\t\"QuantileValues/wrong_wire_type\":    {0x34},\n\t\t\"QuantileValues/missing_value\":      {0x32},\n\t\t\"Flags/wrong_wire_type\":             {0x44},\n\t\t\"Flags/missing_value\":               {0x40},\n\t}\n}\n\nfunc genTestEncodingValuesSummaryDataPoint() map[string]*SummaryDataPoint {\n\treturn map[string]*SummaryDataPoint{\n\t\t\"empty\":                  NewSummaryDataPoint(),\n\t\t\"Attributes/test\":        {Attributes: []KeyValue{{}, *GenTestKeyValue()}},\n\t\t\"StartTimeUnixNano/test\": {StartTimeUnixNano: uint64(13)},\n\t\t\"TimeUnixNano/test\":      {TimeUnixNano: uint64(13)},\n\t\t\"Count/test\":             {Count: uint64(13)},\n\t\t\"Sum/test\":               {Sum: float64(3.1415926)},\n\t\t\"QuantileValues/test\":    {QuantileValues: []*SummaryDataPointValueAtQuantile{{}, GenTestSummaryDataPointValueAtQuantile()}},\n\t\t\"Flags/test\":             {Flags: uint32(13)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_summarydatapointvalueatquantile.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"math\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// SummaryDataPointValueAtQuantile is a quantile value within a Summary data point.\ntype SummaryDataPointValueAtQuantile struct {\n\tQuantile float64\n\tValue    float64\n}\n\nvar (\n\tprotoPoolSummaryDataPointValueAtQuantile = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &SummaryDataPointValueAtQuantile{}\n\t\t},\n\t}\n)\n\nfunc NewSummaryDataPointValueAtQuantile() *SummaryDataPointValueAtQuantile {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &SummaryDataPointValueAtQuantile{}\n\t}\n\treturn protoPoolSummaryDataPointValueAtQuantile.Get().(*SummaryDataPointValueAtQuantile)\n}\n\nfunc DeleteSummaryDataPointValueAtQuantile(orig *SummaryDataPointValueAtQuantile, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolSummaryDataPointValueAtQuantile.Put(orig)\n\t}\n}\n\nfunc CopySummaryDataPointValueAtQuantile(dest, src *SummaryDataPointValueAtQuantile) *SummaryDataPointValueAtQuantile {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewSummaryDataPointValueAtQuantile()\n\t}\n\tdest.Quantile = src.Quantile\n\tdest.Value = src.Value\n\n\treturn dest\n}\n\nfunc CopySummaryDataPointValueAtQuantileSlice(dest, src []SummaryDataPointValueAtQuantile) []SummaryDataPointValueAtQuantile {\n\tvar newDest []SummaryDataPointValueAtQuantile\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]SummaryDataPointValueAtQuantile, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSummaryDataPointValueAtQuantile(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySummaryDataPointValueAtQuantile(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopySummaryDataPointValueAtQuantilePtrSlice(dest, src []*SummaryDataPointValueAtQuantile) []*SummaryDataPointValueAtQuantile {\n\tvar newDest []*SummaryDataPointValueAtQuantile\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*SummaryDataPointValueAtQuantile, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSummaryDataPointValueAtQuantile()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteSummaryDataPointValueAtQuantile(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewSummaryDataPointValueAtQuantile()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopySummaryDataPointValueAtQuantile(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *SummaryDataPointValueAtQuantile) Reset() {\n\t*orig = SummaryDataPointValueAtQuantile{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *SummaryDataPointValueAtQuantile) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.Quantile != float64(0) {\n\t\tdest.WriteObjectField(\"quantile\")\n\t\tdest.WriteFloat64(orig.Quantile)\n\t}\n\tif orig.Value != float64(0) {\n\t\tdest.WriteObjectField(\"value\")\n\t\tdest.WriteFloat64(orig.Value)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *SummaryDataPointValueAtQuantile) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"quantile\":\n\t\t\torig.Quantile = iter.ReadFloat64()\n\t\tcase \"value\":\n\t\t\torig.Value = iter.ReadFloat64()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *SummaryDataPointValueAtQuantile) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.Quantile != float64(0) {\n\t\tn += 9\n\t}\n\tif orig.Value != float64(0) {\n\t\tn += 9\n\t}\n\treturn n\n}\n\nfunc (orig *SummaryDataPointValueAtQuantile) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.Quantile != float64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Quantile))\n\t\tpos--\n\t\tbuf[pos] = 0x9\n\t}\n\tif orig.Value != float64(0) {\n\t\tpos -= 8\n\t\tbinary.LittleEndian.PutUint64(buf[pos:], math.Float64bits(orig.Value))\n\t\tpos--\n\t\tbuf[pos] = 0x11\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *SummaryDataPointValueAtQuantile) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Quantile\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Quantile = math.Float64frombits(num)\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeI64 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Value\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeI64(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Value = math.Float64frombits(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestSummaryDataPointValueAtQuantile() *SummaryDataPointValueAtQuantile {\n\torig := NewSummaryDataPointValueAtQuantile()\n\torig.Quantile = float64(3.1415926)\n\torig.Value = float64(3.1415926)\n\treturn orig\n}\n\nfunc GenTestSummaryDataPointValueAtQuantilePtrSlice() []*SummaryDataPointValueAtQuantile {\n\torig := make([]*SummaryDataPointValueAtQuantile, 5)\n\torig[0] = NewSummaryDataPointValueAtQuantile()\n\torig[1] = GenTestSummaryDataPointValueAtQuantile()\n\torig[2] = NewSummaryDataPointValueAtQuantile()\n\torig[3] = GenTestSummaryDataPointValueAtQuantile()\n\torig[4] = NewSummaryDataPointValueAtQuantile()\n\treturn orig\n}\n\nfunc GenTestSummaryDataPointValueAtQuantileSlice() []SummaryDataPointValueAtQuantile {\n\torig := make([]SummaryDataPointValueAtQuantile, 5)\n\torig[1] = *GenTestSummaryDataPointValueAtQuantile()\n\torig[3] = *GenTestSummaryDataPointValueAtQuantile()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_summarydatapointvalueatquantile_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopySummaryDataPointValueAtQuantile(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSummaryDataPointValueAtQuantile() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewSummaryDataPointValueAtQuantile()\n\t\t\t\tCopySummaryDataPointValueAtQuantile(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopySummaryDataPointValueAtQuantile(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopySummaryDataPointValueAtQuantileSlice(t *testing.T) {\n\tsrc := []SummaryDataPointValueAtQuantile{}\n\tdest := []SummaryDataPointValueAtQuantile{}\n\t// Test CopyTo empty\n\tdest = CopySummaryDataPointValueAtQuantileSlice(dest, src)\n\tassert.Equal(t, []SummaryDataPointValueAtQuantile{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSummaryDataPointValueAtQuantileSlice()\n\tdest = CopySummaryDataPointValueAtQuantileSlice(dest, src)\n\tassert.Equal(t, GenTestSummaryDataPointValueAtQuantileSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySummaryDataPointValueAtQuantileSlice(dest, src)\n\tassert.Equal(t, GenTestSummaryDataPointValueAtQuantileSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySummaryDataPointValueAtQuantileSlice(dest, []SummaryDataPointValueAtQuantile{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySummaryDataPointValueAtQuantileSlice(dest, src)\n\tassert.Equal(t, GenTestSummaryDataPointValueAtQuantileSlice(), dest)\n}\n\nfunc TestCopySummaryDataPointValueAtQuantilePtrSlice(t *testing.T) {\n\tsrc := []*SummaryDataPointValueAtQuantile{}\n\tdest := []*SummaryDataPointValueAtQuantile{}\n\t// Test CopyTo empty\n\tdest = CopySummaryDataPointValueAtQuantilePtrSlice(dest, src)\n\tassert.Equal(t, []*SummaryDataPointValueAtQuantile{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestSummaryDataPointValueAtQuantilePtrSlice()\n\tdest = CopySummaryDataPointValueAtQuantilePtrSlice(dest, src)\n\tassert.Equal(t, GenTestSummaryDataPointValueAtQuantilePtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopySummaryDataPointValueAtQuantilePtrSlice(dest, src)\n\tassert.Equal(t, GenTestSummaryDataPointValueAtQuantilePtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopySummaryDataPointValueAtQuantilePtrSlice(dest, []*SummaryDataPointValueAtQuantile{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopySummaryDataPointValueAtQuantilePtrSlice(dest, src)\n\tassert.Equal(t, GenTestSummaryDataPointValueAtQuantilePtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSummaryDataPointValueAtQuantileUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewSummaryDataPointValueAtQuantile()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewSummaryDataPointValueAtQuantile(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONSummaryDataPointValueAtQuantile(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSummaryDataPointValueAtQuantile() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewSummaryDataPointValueAtQuantile()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSummaryDataPointValueAtQuantile(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSummaryDataPointValueAtQuantileFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesSummaryDataPointValueAtQuantile() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewSummaryDataPointValueAtQuantile()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoSummaryDataPointValueAtQuantileUnknown(t *testing.T) {\n\tdest := NewSummaryDataPointValueAtQuantile()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewSummaryDataPointValueAtQuantile(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoSummaryDataPointValueAtQuantile(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSummaryDataPointValueAtQuantile() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewSummaryDataPointValueAtQuantile()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteSummaryDataPointValueAtQuantile(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufSummaryDataPointValueAtQuantile(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesSummaryDataPointValueAtQuantile() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpmetrics.SummaryDataPoint_ValueAtQuantile{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewSummaryDataPointValueAtQuantile()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesSummaryDataPointValueAtQuantile() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":            {0x02},\n\t\t\"Quantile/wrong_wire_type\": {0xc},\n\t\t\"Quantile/missing_value\":   {0x9},\n\t\t\"Value/wrong_wire_type\":    {0x14},\n\t\t\"Value/missing_value\":      {0x11},\n\t}\n}\n\nfunc genTestEncodingValuesSummaryDataPointValueAtQuantile() map[string]*SummaryDataPointValueAtQuantile {\n\treturn map[string]*SummaryDataPointValueAtQuantile{\n\t\t\"empty\":         NewSummaryDataPointValueAtQuantile(),\n\t\t\"Quantile/test\": {Quantile: float64(3.1415926)},\n\t\t\"Value/test\":    {Value: float64(3.1415926)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_tcpaddr.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\ntype TCPAddr struct {\n\tZone string\n\tIP   []byte\n\tPort int64\n}\n\nvar (\n\tprotoPoolTCPAddr = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &TCPAddr{}\n\t\t},\n\t}\n)\n\nfunc NewTCPAddr() *TCPAddr {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &TCPAddr{}\n\t}\n\treturn protoPoolTCPAddr.Get().(*TCPAddr)\n}\n\nfunc DeleteTCPAddr(orig *TCPAddr, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolTCPAddr.Put(orig)\n\t}\n}\n\nfunc CopyTCPAddr(dest, src *TCPAddr) *TCPAddr {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewTCPAddr()\n\t}\n\tdest.IP = src.IP\n\tdest.Port = src.Port\n\tdest.Zone = src.Zone\n\n\treturn dest\n}\n\nfunc CopyTCPAddrSlice(dest, src []TCPAddr) []TCPAddr {\n\tvar newDest []TCPAddr\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]TCPAddr, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteTCPAddr(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyTCPAddr(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyTCPAddrPtrSlice(dest, src []*TCPAddr) []*TCPAddr {\n\tvar newDest []*TCPAddr\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*TCPAddr, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewTCPAddr()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteTCPAddr(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewTCPAddr()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyTCPAddr(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *TCPAddr) Reset() {\n\t*orig = TCPAddr{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *TCPAddr) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\n\tif len(orig.IP) > 0 {\n\t\tdest.WriteObjectField(\"iP\")\n\t\tdest.WriteBytes(orig.IP)\n\t}\n\tif orig.Port != int64(0) {\n\t\tdest.WriteObjectField(\"port\")\n\t\tdest.WriteInt64(orig.Port)\n\t}\n\tif orig.Zone != \"\" {\n\t\tdest.WriteObjectField(\"zone\")\n\t\tdest.WriteString(orig.Zone)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *TCPAddr) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"iP\":\n\t\t\torig.IP = iter.ReadBytes()\n\t\tcase \"port\":\n\t\t\torig.Port = iter.ReadInt64()\n\t\tcase \"zone\":\n\t\t\torig.Zone = iter.ReadString()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *TCPAddr) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\n\tl = len(orig.IP)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.Port != int64(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.Port))\n\t}\n\n\tl = len(orig.Zone)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *TCPAddr) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = len(orig.IP)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.IP)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\tif orig.Port != int64(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.Port))\n\t\tpos--\n\t\tbuf[pos] = 0x10\n\t}\n\tl = len(orig.Zone)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.Zone)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *TCPAddr) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field IP\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tif length != 0 {\n\t\t\t\torig.IP = make([]byte, length)\n\t\t\t\tcopy(orig.IP, buf[startPos:pos])\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Port\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Port = int64(num)\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Zone\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Zone = string(buf[startPos:pos])\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestTCPAddr() *TCPAddr {\n\torig := NewTCPAddr()\n\torig.IP = []byte{1, 2, 3}\n\torig.Port = int64(13)\n\torig.Zone = \"test_zone\"\n\treturn orig\n}\n\nfunc GenTestTCPAddrPtrSlice() []*TCPAddr {\n\torig := make([]*TCPAddr, 5)\n\torig[0] = NewTCPAddr()\n\torig[1] = GenTestTCPAddr()\n\torig[2] = NewTCPAddr()\n\torig[3] = GenTestTCPAddr()\n\torig[4] = NewTCPAddr()\n\treturn orig\n}\n\nfunc GenTestTCPAddrSlice() []TCPAddr {\n\torig := make([]TCPAddr, 5)\n\torig[1] = *GenTestTCPAddr()\n\torig[3] = *GenTestTCPAddr()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_tcpaddr_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/protobuf/proto\"\n\t\"google.golang.org/protobuf/types/known/emptypb\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyTCPAddr(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesTCPAddr() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewTCPAddr()\n\t\t\t\tCopyTCPAddr(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyTCPAddr(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyTCPAddrSlice(t *testing.T) {\n\tsrc := []TCPAddr{}\n\tdest := []TCPAddr{}\n\t// Test CopyTo empty\n\tdest = CopyTCPAddrSlice(dest, src)\n\tassert.Equal(t, []TCPAddr{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestTCPAddrSlice()\n\tdest = CopyTCPAddrSlice(dest, src)\n\tassert.Equal(t, GenTestTCPAddrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyTCPAddrSlice(dest, src)\n\tassert.Equal(t, GenTestTCPAddrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyTCPAddrSlice(dest, []TCPAddr{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyTCPAddrSlice(dest, src)\n\tassert.Equal(t, GenTestTCPAddrSlice(), dest)\n}\n\nfunc TestCopyTCPAddrPtrSlice(t *testing.T) {\n\tsrc := []*TCPAddr{}\n\tdest := []*TCPAddr{}\n\t// Test CopyTo empty\n\tdest = CopyTCPAddrPtrSlice(dest, src)\n\tassert.Equal(t, []*TCPAddr{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestTCPAddrPtrSlice()\n\tdest = CopyTCPAddrPtrSlice(dest, src)\n\tassert.Equal(t, GenTestTCPAddrPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyTCPAddrPtrSlice(dest, src)\n\tassert.Equal(t, GenTestTCPAddrPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyTCPAddrPtrSlice(dest, []*TCPAddr{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyTCPAddrPtrSlice(dest, src)\n\tassert.Equal(t, GenTestTCPAddrPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONTCPAddrUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewTCPAddr()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewTCPAddr(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONTCPAddr(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesTCPAddr() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewTCPAddr()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteTCPAddr(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoTCPAddrFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesTCPAddr() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewTCPAddr()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoTCPAddrUnknown(t *testing.T) {\n\tdest := NewTCPAddr()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewTCPAddr(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoTCPAddr(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesTCPAddr() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewTCPAddr()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteTCPAddr(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufTCPAddr(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesTCPAddr() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &emptypb.Empty{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewTCPAddr()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesTCPAddr() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":        {0x02},\n\t\t\"IP/wrong_wire_type\":   {0xc},\n\t\t\"IP/missing_value\":     {0xa},\n\t\t\"Port/wrong_wire_type\": {0x14},\n\t\t\"Port/missing_value\":   {0x10},\n\t\t\"Zone/wrong_wire_type\": {0x1c},\n\t\t\"Zone/missing_value\":   {0x1a},\n\t}\n}\n\nfunc genTestEncodingValuesTCPAddr() map[string]*TCPAddr {\n\treturn map[string]*TCPAddr{\n\t\t\"empty\":     NewTCPAddr(),\n\t\t\"IP/test\":   {IP: []byte{1, 2, 3}},\n\t\t\"Port/test\": {Port: int64(13)},\n\t\t\"Zone/test\": {Zone: \"test_zone\"},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_tracesdata.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// TracesData represents the traces data that can be stored in a persistent storage,\n// OR can be embedded by other protocols that transfer OTLP traces data but do not\n// implement the OTLP protocol.\ntype TracesData struct {\n\tResourceSpans []*ResourceSpans\n}\n\nvar (\n\tprotoPoolTracesData = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &TracesData{}\n\t\t},\n\t}\n)\n\nfunc NewTracesData() *TracesData {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &TracesData{}\n\t}\n\treturn protoPoolTracesData.Get().(*TracesData)\n}\n\nfunc DeleteTracesData(orig *TracesData, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tfor i := range orig.ResourceSpans {\n\t\tDeleteResourceSpans(orig.ResourceSpans[i], true)\n\t}\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolTracesData.Put(orig)\n\t}\n}\n\nfunc CopyTracesData(dest, src *TracesData) *TracesData {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewTracesData()\n\t}\n\tdest.ResourceSpans = CopyResourceSpansPtrSlice(dest.ResourceSpans, src.ResourceSpans)\n\n\treturn dest\n}\n\nfunc CopyTracesDataSlice(dest, src []TracesData) []TracesData {\n\tvar newDest []TracesData\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]TracesData, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteTracesData(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyTracesData(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyTracesDataPtrSlice(dest, src []*TracesData) []*TracesData {\n\tvar newDest []*TracesData\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*TracesData, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewTracesData()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteTracesData(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewTracesData()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyTracesData(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *TracesData) Reset() {\n\t*orig = TracesData{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *TracesData) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif len(orig.ResourceSpans) > 0 {\n\t\tdest.WriteObjectField(\"resourceSpans\")\n\t\tdest.WriteArrayStart()\n\t\torig.ResourceSpans[0].MarshalJSON(dest)\n\t\tfor i := 1; i < len(orig.ResourceSpans); i++ {\n\t\t\tdest.WriteMore()\n\t\t\torig.ResourceSpans[i].MarshalJSON(dest)\n\t\t}\n\t\tdest.WriteArrayEnd()\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *TracesData) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"resourceSpans\", \"resource_spans\":\n\t\t\tfor iter.ReadArray() {\n\t\t\t\torig.ResourceSpans = append(orig.ResourceSpans, NewResourceSpans())\n\t\t\t\torig.ResourceSpans[len(orig.ResourceSpans)-1].UnmarshalJSON(iter)\n\t\t\t}\n\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *TracesData) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tfor i := range orig.ResourceSpans {\n\t\tl = orig.ResourceSpans[i].SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *TracesData) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tfor i := len(orig.ResourceSpans) - 1; i >= 0; i-- {\n\t\tl = orig.ResourceSpans[i].MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *TracesData) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field ResourceSpans\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.ResourceSpans = append(orig.ResourceSpans, NewResourceSpans())\n\t\t\terr = orig.ResourceSpans[len(orig.ResourceSpans)-1].UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestTracesData() *TracesData {\n\torig := NewTracesData()\n\torig.ResourceSpans = []*ResourceSpans{{}, GenTestResourceSpans()}\n\treturn orig\n}\n\nfunc GenTestTracesDataPtrSlice() []*TracesData {\n\torig := make([]*TracesData, 5)\n\torig[0] = NewTracesData()\n\torig[1] = GenTestTracesData()\n\torig[2] = NewTracesData()\n\torig[3] = GenTestTracesData()\n\torig[4] = NewTracesData()\n\treturn orig\n}\n\nfunc GenTestTracesDataSlice() []TracesData {\n\torig := make([]TracesData, 5)\n\torig[1] = *GenTestTracesData()\n\torig[3] = *GenTestTracesData()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_tracesdata_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlptrace \"go.opentelemetry.io/proto/slim/otlp/trace/v1\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyTracesData(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesTracesData() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewTracesData()\n\t\t\t\tCopyTracesData(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyTracesData(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyTracesDataSlice(t *testing.T) {\n\tsrc := []TracesData{}\n\tdest := []TracesData{}\n\t// Test CopyTo empty\n\tdest = CopyTracesDataSlice(dest, src)\n\tassert.Equal(t, []TracesData{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestTracesDataSlice()\n\tdest = CopyTracesDataSlice(dest, src)\n\tassert.Equal(t, GenTestTracesDataSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyTracesDataSlice(dest, src)\n\tassert.Equal(t, GenTestTracesDataSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyTracesDataSlice(dest, []TracesData{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyTracesDataSlice(dest, src)\n\tassert.Equal(t, GenTestTracesDataSlice(), dest)\n}\n\nfunc TestCopyTracesDataPtrSlice(t *testing.T) {\n\tsrc := []*TracesData{}\n\tdest := []*TracesData{}\n\t// Test CopyTo empty\n\tdest = CopyTracesDataPtrSlice(dest, src)\n\tassert.Equal(t, []*TracesData{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestTracesDataPtrSlice()\n\tdest = CopyTracesDataPtrSlice(dest, src)\n\tassert.Equal(t, GenTestTracesDataPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyTracesDataPtrSlice(dest, src)\n\tassert.Equal(t, GenTestTracesDataPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyTracesDataPtrSlice(dest, []*TracesData{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyTracesDataPtrSlice(dest, src)\n\tassert.Equal(t, GenTestTracesDataPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONTracesDataUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewTracesData()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewTracesData(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONTracesData(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesTracesData() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewTracesData()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteTracesData(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoTracesDataFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesTracesData() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewTracesData()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoTracesDataUnknown(t *testing.T) {\n\tdest := NewTracesData()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewTracesData(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoTracesData(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesTracesData() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewTracesData()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteTracesData(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufTracesData(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesTracesData() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlptrace.TracesData{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewTracesData()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesTracesData() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                 {0x02},\n\t\t\"ResourceSpans/wrong_wire_type\": {0xc},\n\t\t\"ResourceSpans/missing_value\":   {0xa},\n\t}\n}\n\nfunc genTestEncodingValuesTracesData() map[string]*TracesData {\n\treturn map[string]*TracesData{\n\t\t\"empty\":              NewTracesData(),\n\t\t\"ResourceSpans/test\": {ResourceSpans: []*ResourceSpans{{}, GenTestResourceSpans()}},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_tracesrequest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\ntype TracesRequest struct {\n\tRequestContext *RequestContext\n\tTracesData     TracesData\n\tFormatVersion  uint32\n}\n\nvar (\n\tprotoPoolTracesRequest = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &TracesRequest{}\n\t\t},\n\t}\n)\n\nfunc NewTracesRequest() *TracesRequest {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &TracesRequest{}\n\t}\n\treturn protoPoolTracesRequest.Get().(*TracesRequest)\n}\n\nfunc DeleteTracesRequest(orig *TracesRequest, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\tDeleteRequestContext(orig.RequestContext, true)\n\tDeleteTracesData(&orig.TracesData, false)\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolTracesRequest.Put(orig)\n\t}\n}\n\nfunc CopyTracesRequest(dest, src *TracesRequest) *TracesRequest {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewTracesRequest()\n\t}\n\tdest.RequestContext = CopyRequestContext(dest.RequestContext, src.RequestContext)\n\n\tCopyTracesData(&dest.TracesData, &src.TracesData)\n\n\tdest.FormatVersion = src.FormatVersion\n\n\treturn dest\n}\n\nfunc CopyTracesRequestSlice(dest, src []TracesRequest) []TracesRequest {\n\tvar newDest []TracesRequest\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]TracesRequest, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteTracesRequest(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyTracesRequest(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyTracesRequestPtrSlice(dest, src []*TracesRequest) []*TracesRequest {\n\tvar newDest []*TracesRequest\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*TracesRequest, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewTracesRequest()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteTracesRequest(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewTracesRequest()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyTracesRequest(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *TracesRequest) Reset() {\n\t*orig = TracesRequest{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *TracesRequest) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.RequestContext != nil {\n\t\tdest.WriteObjectField(\"requestContext\")\n\t\torig.RequestContext.MarshalJSON(dest)\n\t}\n\tdest.WriteObjectField(\"tracesData\")\n\torig.TracesData.MarshalJSON(dest)\n\tif orig.FormatVersion != uint32(0) {\n\t\tdest.WriteObjectField(\"formatVersion\")\n\t\tdest.WriteUint32(orig.FormatVersion)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *TracesRequest) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"requestContext\", \"request_context\":\n\t\t\torig.RequestContext = NewRequestContext()\n\t\t\torig.RequestContext.UnmarshalJSON(iter)\n\t\tcase \"tracesData\", \"traces_data\":\n\n\t\t\torig.TracesData.UnmarshalJSON(iter)\n\t\tcase \"formatVersion\", \"format_version\":\n\t\t\torig.FormatVersion = iter.ReadUint32()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *TracesRequest) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.RequestContext != nil {\n\t\tl = orig.RequestContext.SizeProto()\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tl = orig.TracesData.SizeProto()\n\tn += 1 + proto.Sov(uint64(l)) + l\n\tif orig.FormatVersion != uint32(0) {\n\t\tn += 5\n\t}\n\treturn n\n}\n\nfunc (orig *TracesRequest) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.RequestContext != nil {\n\t\tl = orig.RequestContext.MarshalProto(buf[:pos])\n\t\tpos -= l\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\tl = orig.TracesData.MarshalProto(buf[:pos])\n\tpos -= l\n\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\tpos--\n\tbuf[pos] = 0x1a\n\n\tif orig.FormatVersion != uint32(0) {\n\t\tpos -= 4\n\t\tbinary.LittleEndian.PutUint32(buf[pos:], uint32(orig.FormatVersion))\n\t\tpos--\n\t\tbuf[pos] = 0xd\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *TracesRequest) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field RequestContext\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\torig.RequestContext = NewRequestContext()\n\t\t\terr = orig.RequestContext.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TracesData\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\n\t\t\terr = orig.TracesData.UnmarshalProto(buf[startPos:pos])\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeI32 {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field FormatVersion\", wireType)\n\t\t\t}\n\t\t\tvar num uint32\n\t\t\tnum, pos, err = proto.ConsumeI32(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\n\t\t\torig.FormatVersion = uint32(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestTracesRequest() *TracesRequest {\n\torig := NewTracesRequest()\n\torig.RequestContext = GenTestRequestContext()\n\torig.TracesData = *GenTestTracesData()\n\torig.FormatVersion = uint32(13)\n\treturn orig\n}\n\nfunc GenTestTracesRequestPtrSlice() []*TracesRequest {\n\torig := make([]*TracesRequest, 5)\n\torig[0] = NewTracesRequest()\n\torig[1] = GenTestTracesRequest()\n\torig[2] = NewTracesRequest()\n\torig[3] = GenTestTracesRequest()\n\torig[4] = NewTracesRequest()\n\treturn orig\n}\n\nfunc GenTestTracesRequestSlice() []TracesRequest {\n\torig := make([]TracesRequest, 5)\n\torig[1] = *GenTestTracesRequest()\n\torig[3] = *GenTestTracesRequest()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_tracesrequest_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/protobuf/proto\"\n\t\"google.golang.org/protobuf/types/known/emptypb\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyTracesRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesTracesRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewTracesRequest()\n\t\t\t\tCopyTracesRequest(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyTracesRequest(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyTracesRequestSlice(t *testing.T) {\n\tsrc := []TracesRequest{}\n\tdest := []TracesRequest{}\n\t// Test CopyTo empty\n\tdest = CopyTracesRequestSlice(dest, src)\n\tassert.Equal(t, []TracesRequest{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestTracesRequestSlice()\n\tdest = CopyTracesRequestSlice(dest, src)\n\tassert.Equal(t, GenTestTracesRequestSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyTracesRequestSlice(dest, src)\n\tassert.Equal(t, GenTestTracesRequestSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyTracesRequestSlice(dest, []TracesRequest{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyTracesRequestSlice(dest, src)\n\tassert.Equal(t, GenTestTracesRequestSlice(), dest)\n}\n\nfunc TestCopyTracesRequestPtrSlice(t *testing.T) {\n\tsrc := []*TracesRequest{}\n\tdest := []*TracesRequest{}\n\t// Test CopyTo empty\n\tdest = CopyTracesRequestPtrSlice(dest, src)\n\tassert.Equal(t, []*TracesRequest{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestTracesRequestPtrSlice()\n\tdest = CopyTracesRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestTracesRequestPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyTracesRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestTracesRequestPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyTracesRequestPtrSlice(dest, []*TracesRequest{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyTracesRequestPtrSlice(dest, src)\n\tassert.Equal(t, GenTestTracesRequestPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONTracesRequestUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewTracesRequest()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewTracesRequest(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONTracesRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesTracesRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewTracesRequest()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteTracesRequest(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoTracesRequestFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesTracesRequest() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewTracesRequest()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoTracesRequestUnknown(t *testing.T) {\n\tdest := NewTracesRequest()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewTracesRequest(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoTracesRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesTracesRequest() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewTracesRequest()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteTracesRequest(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufTracesRequest(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesTracesRequest() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &emptypb.Empty{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewTracesRequest()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesTracesRequest() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                  {0x02},\n\t\t\"RequestContext/wrong_wire_type\": {0x14},\n\t\t\"RequestContext/missing_value\":   {0x12},\n\t\t\"TracesData/wrong_wire_type\":     {0x1c},\n\t\t\"TracesData/missing_value\":       {0x1a},\n\t\t\"FormatVersion/wrong_wire_type\":  {0xc},\n\t\t\"FormatVersion/missing_value\":    {0xd},\n\t}\n}\n\nfunc genTestEncodingValuesTracesRequest() map[string]*TracesRequest {\n\treturn map[string]*TracesRequest{\n\t\t\"empty\":               NewTracesRequest(),\n\t\t\"RequestContext/test\": {RequestContext: GenTestRequestContext()},\n\t\t\"TracesData/test\":     {TracesData: *GenTestTracesData()},\n\t\t\"FormatVersion/test\":  {FormatVersion: uint32(13)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_udpaddr.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\ntype UDPAddr struct {\n\tZone string\n\tIP   []byte\n\tPort int64\n}\n\nvar (\n\tprotoPoolUDPAddr = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &UDPAddr{}\n\t\t},\n\t}\n)\n\nfunc NewUDPAddr() *UDPAddr {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &UDPAddr{}\n\t}\n\treturn protoPoolUDPAddr.Get().(*UDPAddr)\n}\n\nfunc DeleteUDPAddr(orig *UDPAddr, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolUDPAddr.Put(orig)\n\t}\n}\n\nfunc CopyUDPAddr(dest, src *UDPAddr) *UDPAddr {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewUDPAddr()\n\t}\n\tdest.IP = src.IP\n\tdest.Port = src.Port\n\tdest.Zone = src.Zone\n\n\treturn dest\n}\n\nfunc CopyUDPAddrSlice(dest, src []UDPAddr) []UDPAddr {\n\tvar newDest []UDPAddr\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]UDPAddr, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteUDPAddr(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyUDPAddr(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyUDPAddrPtrSlice(dest, src []*UDPAddr) []*UDPAddr {\n\tvar newDest []*UDPAddr\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*UDPAddr, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewUDPAddr()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteUDPAddr(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewUDPAddr()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyUDPAddr(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *UDPAddr) Reset() {\n\t*orig = UDPAddr{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *UDPAddr) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\n\tif len(orig.IP) > 0 {\n\t\tdest.WriteObjectField(\"iP\")\n\t\tdest.WriteBytes(orig.IP)\n\t}\n\tif orig.Port != int64(0) {\n\t\tdest.WriteObjectField(\"port\")\n\t\tdest.WriteInt64(orig.Port)\n\t}\n\tif orig.Zone != \"\" {\n\t\tdest.WriteObjectField(\"zone\")\n\t\tdest.WriteString(orig.Zone)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *UDPAddr) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"iP\":\n\t\t\torig.IP = iter.ReadBytes()\n\t\tcase \"port\":\n\t\t\torig.Port = iter.ReadInt64()\n\t\tcase \"zone\":\n\t\t\torig.Zone = iter.ReadString()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *UDPAddr) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\n\tl = len(orig.IP)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\tif orig.Port != int64(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.Port))\n\t}\n\n\tl = len(orig.Zone)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *UDPAddr) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = len(orig.IP)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.IP)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\tif orig.Port != int64(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.Port))\n\t\tpos--\n\t\tbuf[pos] = 0x10\n\t}\n\tl = len(orig.Zone)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.Zone)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x1a\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *UDPAddr) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field IP\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\tif length != 0 {\n\t\t\t\torig.IP = make([]byte, length)\n\t\t\t\tcopy(orig.IP, buf[startPos:pos])\n\t\t\t}\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Port\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.Port = int64(num)\n\n\t\tcase 3:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Zone\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Zone = string(buf[startPos:pos])\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestUDPAddr() *UDPAddr {\n\torig := NewUDPAddr()\n\torig.IP = []byte{1, 2, 3}\n\torig.Port = int64(13)\n\torig.Zone = \"test_zone\"\n\treturn orig\n}\n\nfunc GenTestUDPAddrPtrSlice() []*UDPAddr {\n\torig := make([]*UDPAddr, 5)\n\torig[0] = NewUDPAddr()\n\torig[1] = GenTestUDPAddr()\n\torig[2] = NewUDPAddr()\n\torig[3] = GenTestUDPAddr()\n\torig[4] = NewUDPAddr()\n\treturn orig\n}\n\nfunc GenTestUDPAddrSlice() []UDPAddr {\n\torig := make([]UDPAddr, 5)\n\torig[1] = *GenTestUDPAddr()\n\torig[3] = *GenTestUDPAddr()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_udpaddr_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/protobuf/proto\"\n\t\"google.golang.org/protobuf/types/known/emptypb\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyUDPAddr(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesUDPAddr() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewUDPAddr()\n\t\t\t\tCopyUDPAddr(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyUDPAddr(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyUDPAddrSlice(t *testing.T) {\n\tsrc := []UDPAddr{}\n\tdest := []UDPAddr{}\n\t// Test CopyTo empty\n\tdest = CopyUDPAddrSlice(dest, src)\n\tassert.Equal(t, []UDPAddr{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestUDPAddrSlice()\n\tdest = CopyUDPAddrSlice(dest, src)\n\tassert.Equal(t, GenTestUDPAddrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyUDPAddrSlice(dest, src)\n\tassert.Equal(t, GenTestUDPAddrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyUDPAddrSlice(dest, []UDPAddr{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyUDPAddrSlice(dest, src)\n\tassert.Equal(t, GenTestUDPAddrSlice(), dest)\n}\n\nfunc TestCopyUDPAddrPtrSlice(t *testing.T) {\n\tsrc := []*UDPAddr{}\n\tdest := []*UDPAddr{}\n\t// Test CopyTo empty\n\tdest = CopyUDPAddrPtrSlice(dest, src)\n\tassert.Equal(t, []*UDPAddr{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestUDPAddrPtrSlice()\n\tdest = CopyUDPAddrPtrSlice(dest, src)\n\tassert.Equal(t, GenTestUDPAddrPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyUDPAddrPtrSlice(dest, src)\n\tassert.Equal(t, GenTestUDPAddrPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyUDPAddrPtrSlice(dest, []*UDPAddr{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyUDPAddrPtrSlice(dest, src)\n\tassert.Equal(t, GenTestUDPAddrPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONUDPAddrUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewUDPAddr()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewUDPAddr(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONUDPAddr(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesUDPAddr() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewUDPAddr()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteUDPAddr(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoUDPAddrFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesUDPAddr() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewUDPAddr()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoUDPAddrUnknown(t *testing.T) {\n\tdest := NewUDPAddr()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewUDPAddr(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoUDPAddr(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesUDPAddr() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewUDPAddr()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteUDPAddr(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufUDPAddr(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesUDPAddr() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &emptypb.Empty{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewUDPAddr()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesUDPAddr() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":        {0x02},\n\t\t\"IP/wrong_wire_type\":   {0xc},\n\t\t\"IP/missing_value\":     {0xa},\n\t\t\"Port/wrong_wire_type\": {0x14},\n\t\t\"Port/missing_value\":   {0x10},\n\t\t\"Zone/wrong_wire_type\": {0x1c},\n\t\t\"Zone/missing_value\":   {0x1a},\n\t}\n}\n\nfunc genTestEncodingValuesUDPAddr() map[string]*UDPAddr {\n\treturn map[string]*UDPAddr{\n\t\t\"empty\":     NewUDPAddr(),\n\t\t\"IP/test\":   {IP: []byte{1, 2, 3}},\n\t\t\"Port/test\": {Port: int64(13)},\n\t\t\"Zone/test\": {Zone: \"test_zone\"},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_unixaddr.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\ntype UnixAddr struct {\n\tName string\n\tNet  string\n}\n\nvar (\n\tprotoPoolUnixAddr = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &UnixAddr{}\n\t\t},\n\t}\n)\n\nfunc NewUnixAddr() *UnixAddr {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &UnixAddr{}\n\t}\n\treturn protoPoolUnixAddr.Get().(*UnixAddr)\n}\n\nfunc DeleteUnixAddr(orig *UnixAddr, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolUnixAddr.Put(orig)\n\t}\n}\n\nfunc CopyUnixAddr(dest, src *UnixAddr) *UnixAddr {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewUnixAddr()\n\t}\n\tdest.Name = src.Name\n\tdest.Net = src.Net\n\n\treturn dest\n}\n\nfunc CopyUnixAddrSlice(dest, src []UnixAddr) []UnixAddr {\n\tvar newDest []UnixAddr\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]UnixAddr, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteUnixAddr(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyUnixAddr(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyUnixAddrPtrSlice(dest, src []*UnixAddr) []*UnixAddr {\n\tvar newDest []*UnixAddr\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*UnixAddr, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewUnixAddr()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteUnixAddr(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewUnixAddr()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyUnixAddr(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *UnixAddr) Reset() {\n\t*orig = UnixAddr{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *UnixAddr) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.Name != \"\" {\n\t\tdest.WriteObjectField(\"name\")\n\t\tdest.WriteString(orig.Name)\n\t}\n\tif orig.Net != \"\" {\n\t\tdest.WriteObjectField(\"net\")\n\t\tdest.WriteString(orig.Net)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *UnixAddr) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"name\":\n\t\t\torig.Name = iter.ReadString()\n\t\tcase \"net\":\n\t\t\torig.Net = iter.ReadString()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *UnixAddr) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\n\tl = len(orig.Name)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\n\tl = len(orig.Net)\n\tif l > 0 {\n\t\tn += 1 + proto.Sov(uint64(l)) + l\n\t}\n\treturn n\n}\n\nfunc (orig *UnixAddr) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tl = len(orig.Name)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.Name)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0xa\n\t}\n\tl = len(orig.Net)\n\tif l > 0 {\n\t\tpos -= l\n\t\tcopy(buf[pos:], orig.Net)\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(l))\n\t\tpos--\n\t\tbuf[pos] = 0x12\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *UnixAddr) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Name\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Name = string(buf[startPos:pos])\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeLen {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field Net\", wireType)\n\t\t\t}\n\t\t\tvar length int\n\t\t\tlength, pos, err = proto.ConsumeLen(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\tstartPos := pos - length\n\t\t\torig.Net = string(buf[startPos:pos])\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestUnixAddr() *UnixAddr {\n\torig := NewUnixAddr()\n\torig.Name = \"test_name\"\n\torig.Net = \"test_net\"\n\treturn orig\n}\n\nfunc GenTestUnixAddrPtrSlice() []*UnixAddr {\n\torig := make([]*UnixAddr, 5)\n\torig[0] = NewUnixAddr()\n\torig[1] = GenTestUnixAddr()\n\torig[2] = NewUnixAddr()\n\torig[3] = GenTestUnixAddr()\n\torig[4] = NewUnixAddr()\n\treturn orig\n}\n\nfunc GenTestUnixAddrSlice() []UnixAddr {\n\torig := make([]UnixAddr, 5)\n\torig[1] = *GenTestUnixAddr()\n\torig[3] = *GenTestUnixAddr()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_unixaddr_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/protobuf/proto\"\n\t\"google.golang.org/protobuf/types/known/emptypb\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyUnixAddr(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesUnixAddr() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewUnixAddr()\n\t\t\t\tCopyUnixAddr(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyUnixAddr(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyUnixAddrSlice(t *testing.T) {\n\tsrc := []UnixAddr{}\n\tdest := []UnixAddr{}\n\t// Test CopyTo empty\n\tdest = CopyUnixAddrSlice(dest, src)\n\tassert.Equal(t, []UnixAddr{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestUnixAddrSlice()\n\tdest = CopyUnixAddrSlice(dest, src)\n\tassert.Equal(t, GenTestUnixAddrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyUnixAddrSlice(dest, src)\n\tassert.Equal(t, GenTestUnixAddrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyUnixAddrSlice(dest, []UnixAddr{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyUnixAddrSlice(dest, src)\n\tassert.Equal(t, GenTestUnixAddrSlice(), dest)\n}\n\nfunc TestCopyUnixAddrPtrSlice(t *testing.T) {\n\tsrc := []*UnixAddr{}\n\tdest := []*UnixAddr{}\n\t// Test CopyTo empty\n\tdest = CopyUnixAddrPtrSlice(dest, src)\n\tassert.Equal(t, []*UnixAddr{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestUnixAddrPtrSlice()\n\tdest = CopyUnixAddrPtrSlice(dest, src)\n\tassert.Equal(t, GenTestUnixAddrPtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyUnixAddrPtrSlice(dest, src)\n\tassert.Equal(t, GenTestUnixAddrPtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyUnixAddrPtrSlice(dest, []*UnixAddr{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyUnixAddrPtrSlice(dest, src)\n\tassert.Equal(t, GenTestUnixAddrPtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONUnixAddrUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewUnixAddr()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewUnixAddr(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONUnixAddr(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesUnixAddr() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewUnixAddr()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteUnixAddr(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoUnixAddrFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesUnixAddr() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewUnixAddr()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoUnixAddrUnknown(t *testing.T) {\n\tdest := NewUnixAddr()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewUnixAddr(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoUnixAddr(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesUnixAddr() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewUnixAddr()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteUnixAddr(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufUnixAddr(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesUnixAddr() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &emptypb.Empty{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewUnixAddr()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesUnixAddr() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":        {0x02},\n\t\t\"Name/wrong_wire_type\": {0xc},\n\t\t\"Name/missing_value\":   {0xa},\n\t\t\"Net/wrong_wire_type\":  {0x14},\n\t\t\"Net/missing_value\":    {0x12},\n\t}\n}\n\nfunc genTestEncodingValuesUnixAddr() map[string]*UnixAddr {\n\treturn map[string]*UnixAddr{\n\t\t\"empty\":     NewUnixAddr(),\n\t\t\"Name/test\": {Name: \"test_name\"},\n\t\t\"Net/test\":  {Net: \"test_net\"},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_valuetype.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// ValueType describes the type and units of a value.\ntype ValueType struct {\n\tTypeStrindex int32\n\tUnitStrindex int32\n}\n\nvar (\n\tprotoPoolValueType = sync.Pool{\n\t\tNew: func() any {\n\t\t\treturn &ValueType{}\n\t\t},\n\t}\n)\n\nfunc NewValueType() *ValueType {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &ValueType{}\n\t}\n\treturn protoPoolValueType.Get().(*ValueType)\n}\n\nfunc DeleteValueType(orig *ValueType, nullable bool) {\n\tif orig == nil {\n\t\treturn\n\t}\n\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\torig.Reset()\n\t\treturn\n\t}\n\n\torig.Reset()\n\tif nullable {\n\t\tprotoPoolValueType.Put(orig)\n\t}\n}\n\nfunc CopyValueType(dest, src *ValueType) *ValueType {\n\t// If copying to same object, just return.\n\tif src == dest {\n\t\treturn dest\n\t}\n\n\tif src == nil {\n\t\treturn nil\n\t}\n\n\tif dest == nil {\n\t\tdest = NewValueType()\n\t}\n\tdest.TypeStrindex = src.TypeStrindex\n\tdest.UnitStrindex = src.UnitStrindex\n\n\treturn dest\n}\n\nfunc CopyValueTypeSlice(dest, src []ValueType) []ValueType {\n\tvar newDest []ValueType\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]ValueType, len(src))\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteValueType(&dest[i], false)\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyValueType(&newDest[i], &src[i])\n\t}\n\treturn newDest\n}\n\nfunc CopyValueTypePtrSlice(dest, src []*ValueType) []*ValueType {\n\tvar newDest []*ValueType\n\tif cap(dest) < len(src) {\n\t\tnewDest = make([]*ValueType, len(src))\n\t\t// Copy old pointers to re-use.\n\t\tcopy(newDest, dest)\n\t\t// Add new pointers for missing elements from len(dest) to len(srt).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewValueType()\n\t\t}\n\t} else {\n\t\tnewDest = dest[:len(src)]\n\t\t// Cleanup the rest of the elements so GC can free the memory.\n\t\t// This can happen when len(src) < len(dest) < cap(dest).\n\t\tfor i := len(src); i < len(dest); i++ {\n\t\t\tDeleteValueType(dest[i], true)\n\t\t\tdest[i] = nil\n\t\t}\n\t\t// Add new pointers for missing elements.\n\t\t// This can happen when len(dest) < len(src) < cap(dest).\n\t\tfor i := len(dest); i < len(src); i++ {\n\t\t\tnewDest[i] = NewValueType()\n\t\t}\n\t}\n\tfor i := range src {\n\t\tCopyValueType(newDest[i], src[i])\n\t}\n\treturn newDest\n}\n\nfunc (orig *ValueType) Reset() {\n\t*orig = ValueType{}\n}\n\n// MarshalJSON marshals all properties from the current struct to the destination stream.\nfunc (orig *ValueType) MarshalJSON(dest *json.Stream) {\n\tdest.WriteObjectStart()\n\tif orig.TypeStrindex != int32(0) {\n\t\tdest.WriteObjectField(\"typeStrindex\")\n\t\tdest.WriteInt32(orig.TypeStrindex)\n\t}\n\tif orig.UnitStrindex != int32(0) {\n\t\tdest.WriteObjectField(\"unitStrindex\")\n\t\tdest.WriteInt32(orig.UnitStrindex)\n\t}\n\tdest.WriteObjectEnd()\n}\n\n// UnmarshalJSON unmarshals all properties from the current struct from the source iterator.\nfunc (orig *ValueType) UnmarshalJSON(iter *json.Iterator) {\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tswitch f {\n\t\tcase \"typeStrindex\", \"type_strindex\":\n\t\t\torig.TypeStrindex = iter.ReadInt32()\n\t\tcase \"unitStrindex\", \"unit_strindex\":\n\t\t\torig.UnitStrindex = iter.ReadInt32()\n\t\tdefault:\n\t\t\titer.Skip()\n\t\t}\n\t}\n}\n\nfunc (orig *ValueType) SizeProto() int {\n\tvar n int\n\tvar l int\n\t_ = l\n\tif orig.TypeStrindex != int32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.TypeStrindex))\n\t}\n\tif orig.UnitStrindex != int32(0) {\n\t\tn += 1 + proto.Sov(uint64(orig.UnitStrindex))\n\t}\n\treturn n\n}\n\nfunc (orig *ValueType) MarshalProto(buf []byte) int {\n\tpos := len(buf)\n\tvar l int\n\t_ = l\n\tif orig.TypeStrindex != int32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.TypeStrindex))\n\t\tpos--\n\t\tbuf[pos] = 0x8\n\t}\n\tif orig.UnitStrindex != int32(0) {\n\t\tpos = proto.EncodeVarint(buf, pos, uint64(orig.UnitStrindex))\n\t\tpos--\n\t\tbuf[pos] = 0x10\n\t}\n\treturn len(buf) - pos\n}\n\nfunc (orig *ValueType) UnmarshalProto(buf []byte) error {\n\tvar err error\n\tvar fieldNum int32\n\tvar wireType proto.WireType\n\n\tl := len(buf)\n\tpos := 0\n\tfor pos < l {\n\t\t// If in a group parsing, move to the next tag.\n\t\tfieldNum, wireType, pos, err = proto.ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tswitch fieldNum {\n\n\t\tcase 1:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field TypeStrindex\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.TypeStrindex = int32(num)\n\n\t\tcase 2:\n\t\t\tif wireType != proto.WireTypeVarint {\n\t\t\t\treturn fmt.Errorf(\"proto: wrong wireType = %d for field UnitStrindex\", wireType)\n\t\t\t}\n\t\t\tvar num uint64\n\t\t\tnum, pos, err = proto.ConsumeVarint(buf, pos)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t\torig.UnitStrindex = int32(num)\n\t\tdefault:\n\t\t\tpos, err = proto.ConsumeUnknown(buf, pos, wireType)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc GenTestValueType() *ValueType {\n\torig := NewValueType()\n\torig.TypeStrindex = int32(13)\n\torig.UnitStrindex = int32(13)\n\treturn orig\n}\n\nfunc GenTestValueTypePtrSlice() []*ValueType {\n\torig := make([]*ValueType, 5)\n\torig[0] = NewValueType()\n\torig[1] = GenTestValueType()\n\torig[2] = NewValueType()\n\torig[3] = GenTestValueType()\n\torig[4] = NewValueType()\n\treturn orig\n}\n\nfunc GenTestValueTypeSlice() []ValueType {\n\torig := make([]ValueType, 5)\n\torig[1] = *GenTestValueType()\n\torig[3] = *GenTestValueType()\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/generated_proto_valuetype_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpprofiles \"go.opentelemetry.io/proto/slim/otlp/profiles/v1development\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestCopyValueType(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesValueType() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tdest := NewValueType()\n\t\t\t\tCopyValueType(dest, src)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tCopyValueType(dest, dest)\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestCopyValueTypeSlice(t *testing.T) {\n\tsrc := []ValueType{}\n\tdest := []ValueType{}\n\t// Test CopyTo empty\n\tdest = CopyValueTypeSlice(dest, src)\n\tassert.Equal(t, []ValueType{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestValueTypeSlice()\n\tdest = CopyValueTypeSlice(dest, src)\n\tassert.Equal(t, GenTestValueTypeSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyValueTypeSlice(dest, src)\n\tassert.Equal(t, GenTestValueTypeSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyValueTypeSlice(dest, []ValueType{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyValueTypeSlice(dest, src)\n\tassert.Equal(t, GenTestValueTypeSlice(), dest)\n}\n\nfunc TestCopyValueTypePtrSlice(t *testing.T) {\n\tsrc := []*ValueType{}\n\tdest := []*ValueType{}\n\t// Test CopyTo empty\n\tdest = CopyValueTypePtrSlice(dest, src)\n\tassert.Equal(t, []*ValueType{}, dest)\n\n\t// Test CopyTo larger slice\n\tsrc = GenTestValueTypePtrSlice()\n\tdest = CopyValueTypePtrSlice(dest, src)\n\tassert.Equal(t, GenTestValueTypePtrSlice(), dest)\n\n\t// Test CopyTo same size slice\n\tdest = CopyValueTypePtrSlice(dest, src)\n\tassert.Equal(t, GenTestValueTypePtrSlice(), dest)\n\n\t// Test CopyTo smaller size slice\n\tdest = CopyValueTypePtrSlice(dest, []*ValueType{})\n\tassert.Len(t, dest, 0)\n\n\t// Test CopyTo larger slice with enough capacity\n\tdest = CopyValueTypePtrSlice(dest, src)\n\tassert.Equal(t, GenTestValueTypePtrSlice(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONValueTypeUnknown(t *testing.T) {\n\titer := json.BorrowIterator([]byte(`{\"unknown\": \"string\"}`))\n\tdefer json.ReturnIterator(iter)\n\tdest := NewValueType()\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\tassert.Equal(t, NewValueType(), dest)\n}\n\nfunc TestMarshalAndUnmarshalJSONValueType(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesValueType() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tstream := json.BorrowStream(nil)\n\t\t\t\tdefer json.ReturnStream(stream)\n\t\t\t\tsrc.MarshalJSON(stream)\n\t\t\t\trequire.NoError(t, stream.Error())\n\n\t\t\t\titer := json.BorrowIterator(stream.Buffer())\n\t\t\t\tdefer json.ReturnIterator(iter)\n\t\t\t\tdest := NewValueType()\n\t\t\t\tdest.UnmarshalJSON(iter)\n\t\t\t\trequire.NoError(t, iter.Error())\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteValueType(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoValueTypeFailing(t *testing.T) {\n\tfor name, buf := range genTestFailingUnmarshalProtoValuesValueType() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tdest := NewValueType()\n\t\t\trequire.Error(t, dest.UnmarshalProto(buf))\n\t\t})\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoValueTypeUnknown(t *testing.T) {\n\tdest := NewValueType()\n\t// message Test { required int64 field = 1313; } encoding { \"field\": \"1234\" }\n\trequire.NoError(t, dest.UnmarshalProto([]byte{0x88, 0x52, 0xD2, 0x09}))\n\tassert.Equal(t, NewValueType(), dest)\n}\n\nfunc TestMarshalAndUnmarshalProtoValueType(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesValueType() {\n\t\tfor _, pooling := range []bool{true, false} {\n\t\t\tt.Run(name+\"/Pooling=\"+strconv.FormatBool(pooling), func(t *testing.T) {\n\t\t\t\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), pooling))\n\t\t\t\tdefer func() {\n\t\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t\t\t\t}()\n\n\t\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\t\tdest := NewValueType()\n\t\t\t\trequire.NoError(t, dest.UnmarshalProto(buf))\n\n\t\t\t\tassert.Equal(t, src, dest)\n\t\t\t\tDeleteValueType(dest, true)\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestMarshalAndUnmarshalProtoViaProtobufValueType(t *testing.T) {\n\tfor name, src := range genTestEncodingValuesValueType() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tbuf := make([]byte, src.SizeProto())\n\t\t\tgotSize := src.MarshalProto(buf)\n\t\t\tassert.Equal(t, len(buf), gotSize)\n\n\t\t\tgoDest := &gootlpprofiles.ValueType{}\n\t\t\trequire.NoError(t, proto.Unmarshal(buf, goDest))\n\n\t\t\tgoBuf, err := proto.Marshal(goDest)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tdest := NewValueType()\n\t\t\trequire.NoError(t, dest.UnmarshalProto(goBuf))\n\t\t\tassert.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc genTestFailingUnmarshalProtoValuesValueType() map[string][]byte {\n\treturn map[string][]byte{\n\t\t\"invalid_field\":                {0x02},\n\t\t\"TypeStrindex/wrong_wire_type\": {0xc},\n\t\t\"TypeStrindex/missing_value\":   {0x8},\n\t\t\"UnitStrindex/wrong_wire_type\": {0x14},\n\t\t\"UnitStrindex/missing_value\":   {0x10},\n\t}\n}\n\nfunc genTestEncodingValuesValueType() map[string]*ValueType {\n\treturn map[string]*ValueType{\n\t\t\"empty\":             NewValueType(),\n\t\t\"TypeStrindex/test\": {TypeStrindex: int32(13)},\n\t\t\"UnitStrindex/test\": {UnitStrindex: int32(13)},\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/generated_wrapper_anyvalueslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\ntype SliceWrapper struct {\n\torig  *[]AnyValue\n\tstate *State\n}\n\nfunc GetSliceOrig(ms SliceWrapper) *[]AnyValue {\n\treturn ms.orig\n}\n\nfunc GetSliceState(ms SliceWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewSliceWrapper(orig *[]AnyValue, state *State) SliceWrapper {\n\treturn SliceWrapper{orig: orig, state: state}\n}\n\nfunc GenTestSliceWrapper() SliceWrapper {\n\torig := GenTestAnyValueSlice()\n\treturn NewSliceWrapper(&orig, NewState())\n}\n"
  },
  {
    "path": "pdata/internal/generated_wrapper_byteslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\ntype ByteSliceWrapper struct {\n\torig  *[]byte\n\tstate *State\n}\n\nfunc GetByteSliceOrig(ms ByteSliceWrapper) *[]byte {\n\treturn ms.orig\n}\n\nfunc GetByteSliceState(ms ByteSliceWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewByteSliceWrapper(orig *[]byte, state *State) ByteSliceWrapper {\n\treturn ByteSliceWrapper{orig: orig, state: state}\n}\n\nfunc GenTestByteSliceWrapper() ByteSliceWrapper {\n\torig := []byte{1, 2, 3}\n\treturn NewByteSliceWrapper(&orig, NewState())\n}\n\nfunc GenTestByteSlice() []byte {\n\treturn []byte{1, 2, 3}\n}\n"
  },
  {
    "path": "pdata/internal/generated_wrapper_entityref.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\ntype EntityRefWrapper struct {\n\torig  *EntityRef\n\tstate *State\n}\n\nfunc GetEntityRefOrig(ms EntityRefWrapper) *EntityRef {\n\treturn ms.orig\n}\n\nfunc GetEntityRefState(ms EntityRefWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewEntityRefWrapper(orig *EntityRef, state *State) EntityRefWrapper {\n\treturn EntityRefWrapper{orig: orig, state: state}\n}\n\nfunc GenTestEntityRefWrapper() EntityRefWrapper {\n\treturn NewEntityRefWrapper(GenTestEntityRef(), NewState())\n}\n"
  },
  {
    "path": "pdata/internal/generated_wrapper_entityrefslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\ntype EntityRefSliceWrapper struct {\n\torig  *[]*EntityRef\n\tstate *State\n}\n\nfunc GetEntityRefSliceOrig(ms EntityRefSliceWrapper) *[]*EntityRef {\n\treturn ms.orig\n}\n\nfunc GetEntityRefSliceState(ms EntityRefSliceWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewEntityRefSliceWrapper(orig *[]*EntityRef, state *State) EntityRefSliceWrapper {\n\treturn EntityRefSliceWrapper{orig: orig, state: state}\n}\n\nfunc GenTestEntityRefSliceWrapper() EntityRefSliceWrapper {\n\torig := GenTestEntityRefPtrSlice()\n\treturn NewEntityRefSliceWrapper(&orig, NewState())\n}\n"
  },
  {
    "path": "pdata/internal/generated_wrapper_exportlogsservicerequest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\ntype LogsWrapper struct {\n\torig  *ExportLogsServiceRequest\n\tstate *State\n}\n\nfunc GetLogsOrig(ms LogsWrapper) *ExportLogsServiceRequest {\n\treturn ms.orig\n}\n\nfunc GetLogsState(ms LogsWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewLogsWrapper(orig *ExportLogsServiceRequest, state *State) LogsWrapper {\n\treturn LogsWrapper{orig: orig, state: state}\n}\n\nfunc GenTestLogsWrapper() LogsWrapper {\n\treturn NewLogsWrapper(GenTestExportLogsServiceRequest(), NewState())\n}\n"
  },
  {
    "path": "pdata/internal/generated_wrapper_exportmetricsservicerequest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\ntype MetricsWrapper struct {\n\torig  *ExportMetricsServiceRequest\n\tstate *State\n}\n\nfunc GetMetricsOrig(ms MetricsWrapper) *ExportMetricsServiceRequest {\n\treturn ms.orig\n}\n\nfunc GetMetricsState(ms MetricsWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewMetricsWrapper(orig *ExportMetricsServiceRequest, state *State) MetricsWrapper {\n\treturn MetricsWrapper{orig: orig, state: state}\n}\n\nfunc GenTestMetricsWrapper() MetricsWrapper {\n\treturn NewMetricsWrapper(GenTestExportMetricsServiceRequest(), NewState())\n}\n"
  },
  {
    "path": "pdata/internal/generated_wrapper_exportprofilesservicerequest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\ntype ProfilesWrapper struct {\n\torig  *ExportProfilesServiceRequest\n\tstate *State\n}\n\nfunc GetProfilesOrig(ms ProfilesWrapper) *ExportProfilesServiceRequest {\n\treturn ms.orig\n}\n\nfunc GetProfilesState(ms ProfilesWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewProfilesWrapper(orig *ExportProfilesServiceRequest, state *State) ProfilesWrapper {\n\treturn ProfilesWrapper{orig: orig, state: state}\n}\n\nfunc GenTestProfilesWrapper() ProfilesWrapper {\n\treturn NewProfilesWrapper(GenTestExportProfilesServiceRequest(), NewState())\n}\n"
  },
  {
    "path": "pdata/internal/generated_wrapper_exporttraceservicerequest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\ntype TracesWrapper struct {\n\torig  *ExportTraceServiceRequest\n\tstate *State\n}\n\nfunc GetTracesOrig(ms TracesWrapper) *ExportTraceServiceRequest {\n\treturn ms.orig\n}\n\nfunc GetTracesState(ms TracesWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewTracesWrapper(orig *ExportTraceServiceRequest, state *State) TracesWrapper {\n\treturn TracesWrapper{orig: orig, state: state}\n}\n\nfunc GenTestTracesWrapper() TracesWrapper {\n\treturn NewTracesWrapper(GenTestExportTraceServiceRequest(), NewState())\n}\n"
  },
  {
    "path": "pdata/internal/generated_wrapper_float64slice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\ntype Float64SliceWrapper struct {\n\torig  *[]float64\n\tstate *State\n}\n\nfunc GetFloat64SliceOrig(ms Float64SliceWrapper) *[]float64 {\n\treturn ms.orig\n}\n\nfunc GetFloat64SliceState(ms Float64SliceWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewFloat64SliceWrapper(orig *[]float64, state *State) Float64SliceWrapper {\n\treturn Float64SliceWrapper{orig: orig, state: state}\n}\n\nfunc GenTestFloat64SliceWrapper() Float64SliceWrapper {\n\torig := []float64{1.1, 2.2, 3.3}\n\treturn NewFloat64SliceWrapper(&orig, NewState())\n}\n\nfunc GenTestFloat64Slice() []float64 {\n\treturn []float64{1.1, 2.2, 3.3}\n}\n"
  },
  {
    "path": "pdata/internal/generated_wrapper_instrumentationscope.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\ntype InstrumentationScopeWrapper struct {\n\torig  *InstrumentationScope\n\tstate *State\n}\n\nfunc GetInstrumentationScopeOrig(ms InstrumentationScopeWrapper) *InstrumentationScope {\n\treturn ms.orig\n}\n\nfunc GetInstrumentationScopeState(ms InstrumentationScopeWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewInstrumentationScopeWrapper(orig *InstrumentationScope, state *State) InstrumentationScopeWrapper {\n\treturn InstrumentationScopeWrapper{orig: orig, state: state}\n}\n\nfunc GenTestInstrumentationScopeWrapper() InstrumentationScopeWrapper {\n\treturn NewInstrumentationScopeWrapper(GenTestInstrumentationScope(), NewState())\n}\n"
  },
  {
    "path": "pdata/internal/generated_wrapper_int32slice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\ntype Int32SliceWrapper struct {\n\torig  *[]int32\n\tstate *State\n}\n\nfunc GetInt32SliceOrig(ms Int32SliceWrapper) *[]int32 {\n\treturn ms.orig\n}\n\nfunc GetInt32SliceState(ms Int32SliceWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewInt32SliceWrapper(orig *[]int32, state *State) Int32SliceWrapper {\n\treturn Int32SliceWrapper{orig: orig, state: state}\n}\n\nfunc GenTestInt32SliceWrapper() Int32SliceWrapper {\n\torig := []int32{1, 2, 3}\n\treturn NewInt32SliceWrapper(&orig, NewState())\n}\n\nfunc GenTestInt32Slice() []int32 {\n\treturn []int32{1, 2, 3}\n}\n"
  },
  {
    "path": "pdata/internal/generated_wrapper_int64slice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\ntype Int64SliceWrapper struct {\n\torig  *[]int64\n\tstate *State\n}\n\nfunc GetInt64SliceOrig(ms Int64SliceWrapper) *[]int64 {\n\treturn ms.orig\n}\n\nfunc GetInt64SliceState(ms Int64SliceWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewInt64SliceWrapper(orig *[]int64, state *State) Int64SliceWrapper {\n\treturn Int64SliceWrapper{orig: orig, state: state}\n}\n\nfunc GenTestInt64SliceWrapper() Int64SliceWrapper {\n\torig := []int64{1, 2, 3}\n\treturn NewInt64SliceWrapper(&orig, NewState())\n}\n\nfunc GenTestInt64Slice() []int64 {\n\treturn []int64{1, 2, 3}\n}\n"
  },
  {
    "path": "pdata/internal/generated_wrapper_profilesdata.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\ntype ProfilesDataWrapper struct {\n\torig  *ProfilesData\n\tstate *State\n}\n\nfunc GetProfilesDataOrig(ms ProfilesDataWrapper) *ProfilesData {\n\treturn ms.orig\n}\n\nfunc GetProfilesDataState(ms ProfilesDataWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewProfilesDataWrapper(orig *ProfilesData, state *State) ProfilesDataWrapper {\n\treturn ProfilesDataWrapper{orig: orig, state: state}\n}\n\nfunc GenTestProfilesDataWrapper() ProfilesDataWrapper {\n\treturn NewProfilesDataWrapper(GenTestProfilesData(), NewState())\n}\n"
  },
  {
    "path": "pdata/internal/generated_wrapper_resource.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\ntype ResourceWrapper struct {\n\torig  *Resource\n\tstate *State\n}\n\nfunc GetResourceOrig(ms ResourceWrapper) *Resource {\n\treturn ms.orig\n}\n\nfunc GetResourceState(ms ResourceWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewResourceWrapper(orig *Resource, state *State) ResourceWrapper {\n\treturn ResourceWrapper{orig: orig, state: state}\n}\n\nfunc GenTestResourceWrapper() ResourceWrapper {\n\treturn NewResourceWrapper(GenTestResource(), NewState())\n}\n"
  },
  {
    "path": "pdata/internal/generated_wrapper_stringslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\ntype StringSliceWrapper struct {\n\torig  *[]string\n\tstate *State\n}\n\nfunc GetStringSliceOrig(ms StringSliceWrapper) *[]string {\n\treturn ms.orig\n}\n\nfunc GetStringSliceState(ms StringSliceWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewStringSliceWrapper(orig *[]string, state *State) StringSliceWrapper {\n\treturn StringSliceWrapper{orig: orig, state: state}\n}\n\nfunc GenTestStringSliceWrapper() StringSliceWrapper {\n\torig := []string{\"a\", \"b\", \"c\"}\n\treturn NewStringSliceWrapper(&orig, NewState())\n}\n\nfunc GenTestStringSlice() []string {\n\treturn []string{\"a\", \"b\", \"c\"}\n}\n"
  },
  {
    "path": "pdata/internal/generated_wrapper_uint64slice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage internal\n\ntype UInt64SliceWrapper struct {\n\torig  *[]uint64\n\tstate *State\n}\n\nfunc GetUInt64SliceOrig(ms UInt64SliceWrapper) *[]uint64 {\n\treturn ms.orig\n}\n\nfunc GetUInt64SliceState(ms UInt64SliceWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewUInt64SliceWrapper(orig *[]uint64, state *State) UInt64SliceWrapper {\n\treturn UInt64SliceWrapper{orig: orig, state: state}\n}\n\nfunc GenTestUInt64SliceWrapper() UInt64SliceWrapper {\n\torig := []uint64{1, 2, 3}\n\treturn NewUInt64SliceWrapper(&orig, NewState())\n}\n\nfunc GenTestUint64Slice() []uint64 {\n\treturn []uint64{1, 2, 3}\n}\n"
  },
  {
    "path": "pdata/internal/json/iterator.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage json // import \"go.opentelemetry.io/collector/pdata/internal/json\"\nimport (\n\t\"encoding/base64\"\n\t\"strconv\"\n\n\tjsoniter \"github.com/json-iterator/go\"\n)\n\nfunc BorrowIterator(data []byte) *Iterator {\n\treturn &Iterator{\n\t\tdelegate: jsoniter.ConfigFastest.BorrowIterator(data),\n\t}\n}\n\nfunc ReturnIterator(s *Iterator) {\n\tjsoniter.ConfigFastest.ReturnIterator(s.delegate)\n}\n\ntype Iterator struct {\n\tdelegate *jsoniter.Iterator\n}\n\n// ReadInt32 unmarshalls JSON data into an int32. Accepts both numbers and strings decimal.\n// See https://developers.google.com/protocol-buffers/docs/proto3#json.\nfunc (iter *Iterator) ReadInt32() int32 {\n\tswitch iter.delegate.WhatIsNext() {\n\tcase jsoniter.NumberValue:\n\t\treturn iter.delegate.ReadInt32()\n\tcase jsoniter.StringValue:\n\t\tval, err := strconv.ParseInt(iter.ReadString(), 10, 32)\n\t\tif err != nil {\n\t\t\titer.ReportError(\"ReadInt32\", err.Error())\n\t\t\treturn 0\n\t\t}\n\t\treturn int32(val)\n\tdefault:\n\t\titer.ReportError(\"ReadInt32\", \"unsupported value type\")\n\t\treturn 0\n\t}\n}\n\n// ReadUint32 unmarshalls JSON data into an uint32. Accepts both numbers and strings decimal.\n// See https://developers.google.com/protocol-buffers/docs/proto3#json.\nfunc (iter *Iterator) ReadUint32() uint32 {\n\tswitch iter.delegate.WhatIsNext() {\n\tcase jsoniter.NumberValue:\n\t\treturn iter.delegate.ReadUint32()\n\tcase jsoniter.StringValue:\n\t\tval, err := strconv.ParseUint(iter.ReadString(), 10, 32)\n\t\tif err != nil {\n\t\t\titer.ReportError(\"ReadUint32\", err.Error())\n\t\t\treturn 0\n\t\t}\n\t\treturn uint32(val)\n\tdefault:\n\t\titer.ReportError(\"ReadUint32\", \"unsupported value type\")\n\t\treturn 0\n\t}\n}\n\n// ReadInt64 unmarshalls JSON data into an int64. Accepts both numbers and strings decimal.\n// See https://developers.google.com/protocol-buffers/docs/proto3#json.\nfunc (iter *Iterator) ReadInt64() int64 {\n\tswitch iter.delegate.WhatIsNext() {\n\tcase jsoniter.NumberValue:\n\t\treturn iter.delegate.ReadInt64()\n\tcase jsoniter.StringValue:\n\t\tval, err := strconv.ParseInt(iter.ReadString(), 10, 64)\n\t\tif err != nil {\n\t\t\titer.ReportError(\"ReadInt64\", err.Error())\n\t\t\treturn 0\n\t\t}\n\t\treturn val\n\tdefault:\n\t\titer.ReportError(\"ReadInt64\", \"unsupported value type\")\n\t\treturn 0\n\t}\n}\n\n// ReadUint64 unmarshalls JSON data into an uint64. Accepts both numbers and strings decimal.\n// See https://developers.google.com/protocol-buffers/docs/proto3#json.\nfunc (iter *Iterator) ReadUint64() uint64 {\n\tswitch iter.delegate.WhatIsNext() {\n\tcase jsoniter.NumberValue:\n\t\treturn iter.delegate.ReadUint64()\n\tcase jsoniter.StringValue:\n\t\tval, err := strconv.ParseUint(iter.ReadString(), 10, 64)\n\t\tif err != nil {\n\t\t\titer.ReportError(\"ReadUint64\", err.Error())\n\t\t\treturn 0\n\t\t}\n\t\treturn val\n\tdefault:\n\t\titer.ReportError(\"ReadUint64\", \"unsupported value type\")\n\t\treturn 0\n\t}\n}\n\nfunc (iter *Iterator) ReadFloat32() float32 {\n\tswitch iter.delegate.WhatIsNext() {\n\tcase jsoniter.NumberValue:\n\t\treturn iter.delegate.ReadFloat32()\n\tcase jsoniter.StringValue:\n\t\tval, err := strconv.ParseFloat(iter.ReadString(), 32)\n\t\tif err != nil {\n\t\t\titer.ReportError(\"ReadUint64\", err.Error())\n\t\t\treturn 0\n\t\t}\n\t\treturn float32(val)\n\tdefault:\n\t\titer.ReportError(\"ReadUint64\", \"unsupported value type\")\n\t\treturn 0\n\t}\n}\n\nfunc (iter *Iterator) ReadFloat64() float64 {\n\tswitch iter.delegate.WhatIsNext() {\n\tcase jsoniter.NumberValue:\n\t\treturn iter.delegate.ReadFloat64()\n\tcase jsoniter.StringValue:\n\t\tval, err := strconv.ParseFloat(iter.ReadString(), 64)\n\t\tif err != nil {\n\t\t\titer.ReportError(\"ReadUint64\", err.Error())\n\t\t\treturn 0\n\t\t}\n\t\treturn val\n\tdefault:\n\t\titer.ReportError(\"ReadUint64\", \"unsupported value type\")\n\t\treturn 0\n\t}\n}\n\n// ReadBool reads a json object as BoolValue\nfunc (iter *Iterator) ReadBool() bool {\n\treturn iter.delegate.ReadBool()\n}\n\n// ReadString read string from iterator\nfunc (iter *Iterator) ReadString() string {\n\treturn iter.delegate.ReadString()\n}\n\n// ReadBytes read base64 encoded bytes from iterator.\nfunc (iter *Iterator) ReadBytes() []byte {\n\tbuf := iter.ReadStringAsSlice()\n\tif len(buf) == 0 {\n\t\treturn nil\n\t}\n\torig := make([]byte, base64.StdEncoding.DecodedLen(len(buf)))\n\tn, err := base64.StdEncoding.Decode(orig, buf)\n\tif err != nil {\n\t\titer.ReportError(\"base64.Decode\", err.Error())\n\t}\n\treturn orig[:n]\n}\n\n// ReadStringAsSlice read string from iterator without copying into string form.\n// The []byte cannot be kept, as it will change after next iterator call.\nfunc (iter *Iterator) ReadStringAsSlice() []byte {\n\treturn iter.delegate.ReadStringAsSlice()\n}\n\n// ReportError record a error in iterator instance with current position.\nfunc (iter *Iterator) ReportError(operation, msg string) {\n\titer.delegate.ReportError(operation, msg)\n}\n\n// Error returns any recorded error if any otherwise it returns nil.\nfunc (iter *Iterator) Error() error {\n\treturn iter.delegate.Error\n}\n\n// Skip skips a json object and positions to relatively the next json object\nfunc (iter *Iterator) Skip() {\n\titer.delegate.Skip()\n}\n\n// ReadArray read array element, returns true if the array has more element to read.\nfunc (iter *Iterator) ReadArray() bool {\n\treturn iter.delegate.ReadArray()\n}\n\n// ReadObject read one field from object.\n// If object ended, returns empty string. Otherwise, returns the field name.\nfunc (iter *Iterator) ReadObject() string {\n\treturn iter.delegate.ReadObject()\n}\n\n// ReadEnumValue returns the enum integer value representation. Accepts both enum names and enum integer values.\n// See https://developers.google.com/protocol-buffers/docs/proto3#json.\nfunc (iter *Iterator) ReadEnumValue(valueMap map[string]int32) int32 {\n\tswitch iter.delegate.WhatIsNext() {\n\tcase jsoniter.NumberValue:\n\t\treturn iter.ReadInt32()\n\tcase jsoniter.StringValue:\n\t\tval, ok := valueMap[iter.ReadString()]\n\t\t// Same behavior with official protobuf JSON decoder,\n\t\t// see https://github.com/open-telemetry/opentelemetry-proto-go/pull/81\n\t\tif !ok {\n\t\t\titer.ReportError(\"ReadEnumValue\", \"unknown string value\")\n\t\t\treturn 0\n\t\t}\n\t\treturn val\n\tdefault:\n\t\titer.ReportError(\"ReadEnumValue\", \"unsupported value type\")\n\t\treturn 0\n\t}\n}\n\n// ResetBytes reuse iterator instance by specifying another byte array as input\nfunc (iter *Iterator) ResetBytes(input []byte) *Iterator {\n\titer.delegate.ResetBytes(input)\n\treturn iter\n}\n"
  },
  {
    "path": "pdata/internal/json/iterator_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage json\n\nimport (\n\t\"math\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestReadInt32(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tjsonStr string\n\t\twant    int32\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:    \"number\",\n\t\t\tjsonStr: `1 `,\n\t\t\twant:    1,\n\t\t},\n\t\t{\n\t\t\tname:    \"string\",\n\t\t\tjsonStr: `\"1\"`,\n\t\t\twant:    1,\n\t\t},\n\t\t{\n\t\t\tname:    \"negative number\",\n\t\t\tjsonStr: `-1 `,\n\t\t\twant:    -1,\n\t\t},\n\t\t{\n\t\t\tname:    \"negative string\",\n\t\t\tjsonStr: `\"-1\"`,\n\t\t\twant:    -1,\n\t\t},\n\t\t{\n\t\t\tname:    \"wrong string\",\n\t\t\tjsonStr: `\"3.f14\"`,\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"wrong type\",\n\t\t\tjsonStr: `true`,\n\t\t\twantErr: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\titer := BorrowIterator([]byte(tt.jsonStr))\n\t\t\tdefer ReturnIterator(iter)\n\t\t\tval := iter.ReadInt32()\n\t\t\tif tt.wantErr {\n\t\t\t\trequire.Error(t, iter.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, iter.Error())\n\t\t\tassert.Equal(t, tt.want, val)\n\t\t})\n\t}\n}\n\nfunc TestReadUint32(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tjsonStr string\n\t\twant    uint32\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:    \"number\",\n\t\t\tjsonStr: `1 `,\n\t\t\twant:    1,\n\t\t},\n\t\t{\n\t\t\tname:    \"string\",\n\t\t\tjsonStr: `\"1\"`,\n\t\t\twant:    1,\n\t\t},\n\t\t{\n\t\t\tname:    \"negative number\",\n\t\t\tjsonStr: `-1 `,\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"negative string\",\n\t\t\tjsonStr: `\"-1\"`,\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"wrong string\",\n\t\t\tjsonStr: `\"3.f14\"`,\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"wrong type\",\n\t\t\tjsonStr: `true`,\n\t\t\twantErr: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\titer := BorrowIterator([]byte(tt.jsonStr))\n\t\t\tdefer ReturnIterator(iter)\n\t\t\tval := iter.ReadUint32()\n\t\t\tif tt.wantErr {\n\t\t\t\trequire.Error(t, iter.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, iter.Error())\n\t\t\tassert.Equal(t, tt.want, val)\n\t\t})\n\t}\n}\n\nfunc TestReadInt64(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tjsonStr string\n\t\twant    int64\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:    \"number\",\n\t\t\tjsonStr: `1 `,\n\t\t\twant:    1,\n\t\t},\n\t\t{\n\t\t\tname:    \"string\",\n\t\t\tjsonStr: `\"1\"`,\n\t\t\twant:    1,\n\t\t},\n\t\t{\n\t\t\tname:    \"negative number\",\n\t\t\tjsonStr: `-1 `,\n\t\t\twant:    -1,\n\t\t},\n\t\t{\n\t\t\tname:    \"negative string\",\n\t\t\tjsonStr: `\"-1\"`,\n\t\t\twant:    -1,\n\t\t},\n\t\t{\n\t\t\tname:    \"wrong string\",\n\t\t\tjsonStr: `\"3.f14\"`,\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"wrong type\",\n\t\t\tjsonStr: `true`,\n\t\t\twantErr: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\titer := BorrowIterator([]byte(tt.jsonStr))\n\t\t\tdefer ReturnIterator(iter)\n\t\t\tval := iter.ReadInt64()\n\t\t\tif tt.wantErr {\n\t\t\t\trequire.Error(t, iter.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, iter.Error())\n\t\t\tassert.Equal(t, tt.want, val)\n\t\t})\n\t}\n}\n\nfunc TestReadUint64(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tjsonStr string\n\t\twant    uint64\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:    \"number\",\n\t\t\tjsonStr: `1 `,\n\t\t\twant:    1,\n\t\t},\n\t\t{\n\t\t\tname:    \"string\",\n\t\t\tjsonStr: `\"1\"`,\n\t\t\twant:    1,\n\t\t},\n\t\t{\n\t\t\tname:    \"negative number\",\n\t\t\tjsonStr: `-1 `,\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"negative string\",\n\t\t\tjsonStr: `\"-1\"`,\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"wrong string\",\n\t\t\tjsonStr: `\"3.f14\"`,\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"wrong type\",\n\t\t\tjsonStr: `true`,\n\t\t\twantErr: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\titer := BorrowIterator([]byte(tt.jsonStr))\n\t\t\tdefer ReturnIterator(iter)\n\t\t\tval := iter.ReadUint64()\n\t\t\tif tt.wantErr {\n\t\t\t\trequire.Error(t, iter.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, iter.Error())\n\t\t\tassert.Equal(t, tt.want, val)\n\t\t})\n\t}\n}\n\nfunc TestReadFloat32(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tjsonStr string\n\t\twant    float32\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:    \"number\",\n\t\t\tjsonStr: `3.14 `,\n\t\t\twant:    3.14,\n\t\t},\n\t\t{\n\t\t\tname:    \"string\",\n\t\t\tjsonStr: `\"3.14\"`,\n\t\t\twant:    3.14,\n\t\t},\n\t\t{\n\t\t\tname:    \"negative number\",\n\t\t\tjsonStr: `-3.14 `,\n\t\t\twant:    -3.14,\n\t\t},\n\t\t{\n\t\t\tname:    \"negative string\",\n\t\t\tjsonStr: `\"-3.14\"`,\n\t\t\twant:    -3.14,\n\t\t},\n\t\t{\n\t\t\tname:    \"wrong string\",\n\t\t\tjsonStr: `\"3.f14\"`,\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"wrong type\",\n\t\t\tjsonStr: `true`,\n\t\t\twantErr: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\titer := BorrowIterator([]byte(tt.jsonStr))\n\t\t\tdefer ReturnIterator(iter)\n\t\t\tval := iter.ReadFloat32()\n\t\t\tif tt.wantErr {\n\t\t\t\trequire.Error(t, iter.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, iter.Error())\n\t\t\tassert.InDelta(t, tt.want, val, 0.01)\n\t\t})\n\t}\n}\n\nfunc TestReadFloat32MaxValue(t *testing.T) {\n\titer := BorrowIterator([]byte(`{\"value\": 3.4028234663852886e+38}`))\n\tdefer ReturnIterator(iter)\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tassert.Equal(t, \"value\", f)\n\t\tassert.InDelta(t, math.MaxFloat32, iter.ReadFloat64(), 0.01)\n\t}\n\trequire.NoError(t, iter.Error())\n}\n\nfunc TestReadFloat64(t *testing.T) {\n\ttests := []struct {\n\t\tname    string\n\t\tjsonStr string\n\t\twant    float64\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:    \"number\",\n\t\t\tjsonStr: `3.14 `,\n\t\t\twant:    3.14,\n\t\t},\n\t\t{\n\t\t\tname:    \"string\",\n\t\t\tjsonStr: `\"3.14\"`,\n\t\t\twant:    3.14,\n\t\t},\n\t\t{\n\t\t\tname:    \"negative number\",\n\t\t\tjsonStr: `-3.14 `,\n\t\t\twant:    -3.14,\n\t\t},\n\t\t{\n\t\t\tname:    \"negative string\",\n\t\t\tjsonStr: `\"-3.14\"`,\n\t\t\twant:    -3.14,\n\t\t},\n\t\t{\n\t\t\tname:    \"wrong string\",\n\t\t\tjsonStr: `\"3.f14\"`,\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"wrong type\",\n\t\t\tjsonStr: `true`,\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"positive infinity\",\n\t\t\tjsonStr: `\"Infinity\"`,\n\t\t\twant:    math.Inf(1),\n\t\t},\n\t\t{\n\t\t\tname:    \"negative infinity\",\n\t\t\tjsonStr: `\"-Infinity\"`,\n\t\t\twant:    math.Inf(-1),\n\t\t},\n\t\t{\n\t\t\tname:    \"not-a-number\",\n\t\t\tjsonStr: `\"NaN\"`,\n\t\t\twant:    math.NaN(),\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\titer := BorrowIterator([]byte(tt.jsonStr))\n\t\t\tdefer ReturnIterator(iter)\n\t\t\tval := iter.ReadFloat64()\n\t\t\tif tt.wantErr {\n\t\t\t\trequire.Error(t, iter.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, iter.Error())\n\t\t\tassert.InDelta(t, tt.want, val, 0.01)\n\t\t})\n\t}\n}\n\nfunc TestReadFloat64MaxValue(t *testing.T) {\n\titer := BorrowIterator([]byte(`{\"value\": 1.7976931348623157e+308}`))\n\tdefer ReturnIterator(iter)\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tassert.Equal(t, \"value\", f)\n\t\tassert.InDelta(t, math.MaxFloat64, iter.ReadFloat64(), 0.01)\n\t}\n\trequire.NoError(t, iter.Error())\n}\n\nfunc TestReadEnumValue(t *testing.T) {\n\tvalueMap := map[string]int32{\n\t\t\"undefined\": 0,\n\t\t\"foo\":       1,\n\t\t\"bar\":       2,\n\t}\n\ttests := []struct {\n\t\tname    string\n\t\tjsonStr string\n\t\twant    int32\n\t\twantErr bool\n\t}{\n\t\t{\n\t\t\tname:    \"foo string\",\n\t\t\tjsonStr: \"\\\"foo\\\"\\n\",\n\t\t\twant:    1,\n\t\t},\n\t\t{\n\t\t\tname:    \"foo number\",\n\t\t\tjsonStr: \"1\\n\",\n\t\t\twant:    1,\n\t\t},\n\t\t{\n\t\t\tname:    \"unknown number\",\n\t\t\tjsonStr: \"5\\n\",\n\t\t\twant:    5,\n\t\t},\n\t\t{\n\t\t\tname:    \"bar string\",\n\t\t\tjsonStr: \"\\\"bar\\\"\\n\",\n\t\t\twant:    2,\n\t\t},\n\t\t{\n\t\t\tname:    \"bar number\",\n\t\t\tjsonStr: \"2\\n\",\n\t\t\twant:    2,\n\t\t},\n\t\t{\n\t\t\tname:    \"unknown string\",\n\t\t\tjsonStr: \"\\\"baz\\\"\\n\",\n\t\t\twantErr: true,\n\t\t},\n\t\t{\n\t\t\tname:    \"wrong type\",\n\t\t\tjsonStr: \"true\",\n\t\t\twantErr: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\titer := BorrowIterator([]byte(tt.jsonStr))\n\t\t\tdefer ReturnIterator(iter)\n\t\t\tval := iter.ReadEnumValue(valueMap)\n\t\t\tif tt.wantErr {\n\t\t\t\tassert.Error(t, iter.Error())\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, iter.Error())\n\t\t\tassert.Equal(t, tt.want, val)\n\t\t})\n\t}\n}\n\nfunc TestReadBytes(t *testing.T) {\n\titer := BorrowIterator([]byte(`{\"value\": \"dGVzdA==\"}`))\n\tdefer ReturnIterator(iter)\n\tfor f := iter.ReadObject(); f != \"\"; f = iter.ReadObject() {\n\t\tassert.Equal(t, \"value\", f)\n\t\tassert.Equal(t, \"test\", string(iter.ReadBytes()))\n\t}\n\trequire.NoError(t, iter.Error())\n}\n"
  },
  {
    "path": "pdata/internal/json/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage json\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "pdata/internal/json/stream.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage json // import \"go.opentelemetry.io/collector/pdata/internal/json\"\n\nimport (\n\t\"encoding/base64\"\n\t\"errors\"\n\t\"io\"\n\t\"math\"\n\t\"strconv\"\n\n\tjsoniter \"github.com/json-iterator/go\"\n)\n\nfunc BorrowStream(writer io.Writer) *Stream {\n\treturn &Stream{\n\t\tStream:    jsoniter.ConfigFastest.BorrowStream(writer),\n\t\twmTracker: make([]bool, 32),\n\t}\n}\n\nfunc ReturnStream(s *Stream) {\n\tjsoniter.ConfigFastest.ReturnStream(s.Stream)\n}\n\n// Stream avoids the need to explicitly call the `Stream.WriteMore` method while marshaling objects by\n// checking if a field was previously written inside the current object and automatically appending a \",\"\n// if so before writing the next field.\ntype Stream struct {\n\t*jsoniter.Stream\n\t// wmTracker acts like a stack which pushes a new value when an object is started and removes the\n\t// top when it is ended. The value added for every object tracks if there is any written field\n\t// already for that object, and if it is then automatically add a \",\" before any new field.\n\twmTracker []bool\n}\n\nfunc (ots *Stream) WriteObjectStart() {\n\tots.Stream.WriteObjectStart()\n\tots.wmTracker = append(ots.wmTracker, false)\n}\n\nfunc (ots *Stream) WriteObjectField(field string) {\n\tif ots.wmTracker[len(ots.wmTracker)-1] {\n\t\tots.WriteMore()\n\t}\n\n\tots.Stream.WriteObjectField(field)\n\tots.wmTracker[len(ots.wmTracker)-1] = true\n}\n\nfunc (ots *Stream) WriteObjectEnd() {\n\tots.Stream.WriteObjectEnd()\n\tots.wmTracker = ots.wmTracker[:len(ots.wmTracker)-1]\n}\n\n// WriteInt64 writes the values as a decimal string. This is per the protobuf encoding rules for int64, fixed64, uint64.\nfunc (ots *Stream) WriteInt64(val int64) {\n\tots.WriteString(strconv.FormatInt(val, 10))\n}\n\n// WriteUint64 writes the values as a decimal string. This is per the protobuf encoding rules for int64, fixed64, uint64.\nfunc (ots *Stream) WriteUint64(val uint64) {\n\tots.WriteString(strconv.FormatUint(val, 10))\n}\n\n// WriteBytes writes the values as a base64 encoded string. This is per the protobuf encoding rules for bytes.\nfunc (ots *Stream) WriteBytes(val []byte) {\n\tif len(val) == 0 {\n\t\tots.WriteString(\"\")\n\t\treturn\n\t}\n\n\tots.WriteString(base64.StdEncoding.EncodeToString(val))\n}\n\n// WriteFloat64 writes the JSON value that will be a number or one of the special string\n// values \"NaN\", \"Infinity\", and \"-Infinity\". Either numbers or strings are accepted.\n// Empty strings are invalid. Exponent notation is also accepted.\n// See https://protobuf.dev/programming-guides/json/.\nfunc (ots *Stream) WriteFloat64(val float64) {\n\tif math.IsNaN(val) {\n\t\tots.WriteString(\"NaN\")\n\t\treturn\n\t}\n\tif math.IsInf(val, 1) {\n\t\tots.WriteString(\"Infinity\")\n\t\treturn\n\t}\n\tif math.IsInf(val, -1) {\n\t\tots.WriteString(\"-Infinity\")\n\t\treturn\n\t}\n\n\tots.Stream.WriteFloat64(val)\n}\n\nfunc (ots *Stream) ReportError(err error) {\n\tots.Stream.Error = errors.Join(ots.Stream.Error, err)\n}\n\nfunc (ots *Stream) Error() error {\n\treturn ots.Stream.Error\n}\n"
  },
  {
    "path": "pdata/internal/json/stream_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage json\n\nimport (\n\t\"math\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestNestedObject(t *testing.T) {\n\ts := BorrowStream(nil)\n\tdefer ReturnStream(s)\n\n\ts.WriteObjectStart()\n\ts.WriteObjectField(\"field1\")\n\ts.WriteString(\"val1\")\n\ts.WriteObjectField(\"field2\")\n\ts.WriteObjectStart()\n\ts.WriteObjectField(\"field3\")\n\ts.WriteObjectStart()\n\ts.WriteObjectField(\"field4\")\n\ts.WriteString(\"val4\")\n\ts.WriteObjectField(\"field5\")\n\ts.WriteString(\"val5\")\n\ts.WriteObjectEnd()\n\ts.WriteObjectField(\"field6\")\n\ts.WriteString(\"val6\")\n\ts.WriteObjectField(\"field7\")\n\ts.WriteObjectStart()\n\ts.WriteObjectEnd()\n\ts.WriteObjectEnd()\n\ts.WriteObjectEnd()\n\n\texpected := `{\n\t\t\"field1\": \"val1\",\n\t\t\"field2\": {\n\t\t\t\"field3\": {\n\t\t\t\t\"field4\": \"val4\",\n\t\t\t\t\"field5\": \"val5\"\n\t\t\t},\n\t\t\t\"field6\": \"val6\",\n\t\t\t\"field7\": {}\n\t\t}\n\t}`\n\tassert.JSONEq(t, expected, string(s.Buffer()))\n}\n\nfunc TestMarshalFloat(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\tinputFloat float64\n\t\texpected   string\n\t}{\n\t\t{\n\t\t\tname:       \"positive infinity\",\n\t\t\tinputFloat: math.Inf(1),\n\t\t\texpected:   `\"Infinity\"`,\n\t\t},\n\t\t{\n\t\t\tname:       \"negative infinity\",\n\t\t\tinputFloat: math.Inf(-1),\n\t\t\texpected:   `\"-Infinity\"`,\n\t\t},\n\t\t{\n\t\t\tname:       \"not-a-number\",\n\t\t\tinputFloat: math.NaN(),\n\t\t\texpected:   `\"NaN\"`,\n\t\t},\n\t\t{\n\t\t\tname:       \"regular float\",\n\t\t\tinputFloat: math.MaxFloat64,\n\t\t\texpected:   \"1.7976931348623157e+308\",\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\ts := BorrowStream(nil)\n\t\t\tdefer ReturnStream(s)\n\t\t\ts.WriteFloat64(tt.inputFloat)\n\t\t\trequire.Equal(t, tt.expected, string(s.Buffer()))\n\t\t})\n\t}\n}\n\nfunc TestWriteBytes(t *testing.T) {\n\ts := BorrowStream(nil)\n\tdefer ReturnStream(s)\n\ts.WriteBytes([]byte(\"test\"))\n\trequire.Equal(t, `\"dGVzdA==\"`, string(s.Buffer()))\n}\n"
  },
  {
    "path": "pdata/internal/metadata/generated_feature_gates.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\nvar PdataUseCustomProtoEncodingFeatureGate = featuregate.GlobalRegistry().MustRegister(\n\t\"pdata.useCustomProtoEncoding\",\n\tfeaturegate.StageStable,\n\tfeaturegate.WithRegisterDescription(\"When enabled, enable custom proto encoding. This is a required step to enable featuregate pdata.useProtoPooling.\"),\n\tfeaturegate.WithRegisterReferenceURL(\"https://github.com/open-telemetry/opentelemetry-collector/issues/13631\"),\n\tfeaturegate.WithRegisterFromVersion(\"v0.133.0\"),\n\tfeaturegate.WithRegisterToVersion(\"v0.137.0\"),\n)\n\nvar PdataUseProtoPoolingFeatureGate = featuregate.GlobalRegistry().MustRegister(\n\t\"pdata.useProtoPooling\",\n\tfeaturegate.StageAlpha,\n\tfeaturegate.WithRegisterDescription(\"When enabled, enable using local memory pools for underlying data that the pdata messages are pushed to.\"),\n\tfeaturegate.WithRegisterReferenceURL(\"https://github.com/open-telemetry/opentelemetry-collector/issues/13631\"),\n\tfeaturegate.WithRegisterFromVersion(\"v0.133.0\"),\n)\n"
  },
  {
    "path": "pdata/internal/otelgrpc/encoding.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelgrpc // import \"go.opentelemetry.io/collector/pdata/internal/otelgrpc\"\n\nimport (\n\t\"google.golang.org/grpc/encoding\"\n\t\"google.golang.org/grpc/mem\"\n)\n\nvar (\n\tdefaultBufferPoolSizes = []int{\n\t\t256,\n\t\t4 << 10,   // 4KB (go page size)\n\t\t16 << 10,  // 16KB (max HTTP/2 frame size used by gRPC)\n\t\t32 << 10,  // 32KB (default buffer size for io.Copy)\n\t\t512 << 10, // 512KB\n\t\t1 << 20,   // 1MB\n\t\t4 << 20,   // 4MB\n\t\t16 << 20,  // 16MB\n\t}\n\totelBufferPool = mem.NewTieredBufferPool(defaultBufferPoolSizes...)\n)\n\n// DefaultBufferPool returns the current default buffer pool. It is a BufferPool\n// created with mem.NewTieredBufferPool that uses a set of default sizes optimized for\n// expected telemetry workflows.\nfunc DefaultBufferPool() mem.BufferPool {\n\treturn otelBufferPool\n}\n\n// Name is the name registered for the proto compressor.\nconst Name = \"proto\"\n\nfunc init() {\n\tencoding.RegisterCodecV2(&codecV2{delegate: encoding.GetCodecV2(Name)})\n}\n\n// codecV2 is a custom proto encoding that uses a different tier schema for the TieredBufferPool as well\n// as it call into the custom marshal/unmarshal logic that works with memory pooling.\n// If not an otlp payload fallback on the default grpc/proto encoding.\ntype codecV2 struct {\n\tdelegate encoding.CodecV2\n}\n\ntype otelEncoder interface {\n\tSizeProto() int\n\tMarshalProto([]byte) int\n\tUnmarshalProto([]byte) error\n}\n\nfunc (c *codecV2) Marshal(v any) (mem.BufferSlice, error) {\n\tif m, ok := v.(otelEncoder); ok {\n\t\tsize := m.SizeProto()\n\t\tbuf := otelBufferPool.Get(size)\n\t\tn := m.MarshalProto((*buf)[:size])\n\t\t*buf = (*buf)[:n]\n\t\treturn []mem.Buffer{mem.NewBuffer(buf, otelBufferPool)}, nil\n\t}\n\n\treturn c.delegate.Marshal(v)\n}\n\nfunc (c *codecV2) Unmarshal(data mem.BufferSlice, v any) (err error) {\n\tif m, ok := v.(otelEncoder); ok {\n\t\t// TODO: Upgrade custom Unmarshal logic to support reading from mem.BufferSlice.\n\t\tbuf := data.MaterializeToBuffer(otelBufferPool)\n\t\tdefer buf.Free()\n\t\treturn m.UnmarshalProto(buf.ReadOnlyData())\n\t}\n\n\treturn c.delegate.Unmarshal(data, v)\n}\n\nfunc (c *codecV2) Name() string {\n\treturn Name\n}\n"
  },
  {
    "path": "pdata/internal/otelgrpc/logs_service.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelgrpc // import \"go.opentelemetry.io/collector/pdata/internal/otelgrpc\"\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// LogsServiceClient is the client API for LogsService service.\n//\n// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.\ntype LogsServiceClient interface {\n\tExport(context.Context, *internal.ExportLogsServiceRequest, ...grpc.CallOption) (*internal.ExportLogsServiceResponse, error)\n}\n\ntype logsServiceClient struct {\n\tcc *grpc.ClientConn\n}\n\nfunc NewLogsServiceClient(cc *grpc.ClientConn) LogsServiceClient {\n\treturn &logsServiceClient{cc}\n}\n\nfunc (c *logsServiceClient) Export(ctx context.Context, in *internal.ExportLogsServiceRequest, opts ...grpc.CallOption) (*internal.ExportLogsServiceResponse, error) {\n\tout := new(internal.ExportLogsServiceResponse)\n\terr := c.cc.Invoke(ctx, \"/opentelemetry.proto.collector.logs.v1.LogsService/Export\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}\n\n// LogsServiceServer is the server API for LogsService service.\ntype LogsServiceServer interface {\n\tExport(context.Context, *internal.ExportLogsServiceRequest) (*internal.ExportLogsServiceResponse, error)\n}\n\n// UnimplementedLogsServiceServer can be embedded to have forward compatible implementations.\ntype UnimplementedLogsServiceServer struct{}\n\nfunc (*UnimplementedLogsServiceServer) Export(context.Context, *internal.ExportLogsServiceRequest) (*internal.ExportLogsServiceResponse, error) {\n\treturn nil, status.Errorf(codes.Unimplemented, \"method Export not implemented\")\n}\n\nfunc RegisterLogsServiceServer(s *grpc.Server, srv LogsServiceServer) {\n\ts.RegisterService(&logsServiceServiceDesc, srv)\n}\n\n// Context cannot be the first parameter of the function because gRPC definition.\n//\n//nolint:revive\nfunc logsServiceExportHandler(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {\n\tin := new(internal.ExportLogsServiceRequest)\n\tif err := dec(in); err != nil {\n\t\treturn nil, err\n\t}\n\tif interceptor == nil {\n\t\treturn srv.(LogsServiceServer).Export(ctx, in)\n\t}\n\tinfo := &grpc.UnaryServerInfo{\n\t\tServer:     srv,\n\t\tFullMethod: \"/opentelemetry.proto.collector.logs.v1.LogsService/Export\",\n\t}\n\thandler := func(ctx context.Context, req any) (any, error) {\n\t\treturn srv.(LogsServiceServer).Export(ctx, req.(*internal.ExportLogsServiceRequest))\n\t}\n\treturn interceptor(ctx, in, info, handler)\n}\n\nvar logsServiceServiceDesc = grpc.ServiceDesc{\n\tServiceName: \"opentelemetry.proto.collector.logs.v1.LogsService\",\n\tHandlerType: (*LogsServiceServer)(nil),\n\tMethods: []grpc.MethodDesc{\n\t\t{\n\t\t\tMethodName: \"Export\",\n\t\t\tHandler:    logsServiceExportHandler,\n\t\t},\n\t},\n\tStreams:  []grpc.StreamDesc{},\n\tMetadata: \"opentelemetry/proto/collector/logs/v1/logs_service.proto\",\n}\n"
  },
  {
    "path": "pdata/internal/otelgrpc/metrics_service.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelgrpc // import \"go.opentelemetry.io/collector/pdata/internal/otelgrpc\"\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// MetricsServiceClient is the client API for MetricsService service.\n//\n// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.\ntype MetricsServiceClient interface {\n\tExport(context.Context, *internal.ExportMetricsServiceRequest, ...grpc.CallOption) (*internal.ExportMetricsServiceResponse, error)\n}\n\ntype metricsServiceClient struct {\n\tcc *grpc.ClientConn\n}\n\nfunc NewMetricsServiceClient(cc *grpc.ClientConn) MetricsServiceClient {\n\treturn &metricsServiceClient{cc}\n}\n\nfunc (c *metricsServiceClient) Export(ctx context.Context, in *internal.ExportMetricsServiceRequest, opts ...grpc.CallOption) (*internal.ExportMetricsServiceResponse, error) {\n\tout := new(internal.ExportMetricsServiceResponse)\n\terr := c.cc.Invoke(ctx, \"/opentelemetry.proto.collector.metrics.v1.MetricsService/Export\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}\n\n// MetricsServiceServer is the server API for MetricsService service.\ntype MetricsServiceServer interface {\n\tExport(context.Context, *internal.ExportMetricsServiceRequest) (*internal.ExportMetricsServiceResponse, error)\n}\n\n// UnimplementedMetricsServiceServer can be embedded to have forward compatible implementations.\ntype UnimplementedMetricsServiceServer struct{}\n\nfunc (*UnimplementedMetricsServiceServer) Export(context.Context, *internal.ExportMetricsServiceRequest) (*internal.ExportMetricsServiceResponse, error) {\n\treturn nil, status.Errorf(codes.Unimplemented, \"method Export not implemented\")\n}\n\nfunc RegisterMetricsServiceServer(s *grpc.Server, srv MetricsServiceServer) {\n\ts.RegisterService(&metricsServiceServiceDesc, srv)\n}\n\n// Context cannot be the first parameter of the function because gRPC definition.\n//\n//nolint:revive\nfunc metricsServiceExportHandler(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {\n\tin := new(internal.ExportMetricsServiceRequest)\n\tif err := dec(in); err != nil {\n\t\treturn nil, err\n\t}\n\tif interceptor == nil {\n\t\treturn srv.(MetricsServiceServer).Export(ctx, in)\n\t}\n\tinfo := &grpc.UnaryServerInfo{\n\t\tServer:     srv,\n\t\tFullMethod: \"/opentelemetry.proto.collector.metrics.v1.MetricsService/Export\",\n\t}\n\thandler := func(ctx context.Context, req any) (any, error) {\n\t\treturn srv.(MetricsServiceServer).Export(ctx, req.(*internal.ExportMetricsServiceRequest))\n\t}\n\treturn interceptor(ctx, in, info, handler)\n}\n\nvar metricsServiceServiceDesc = grpc.ServiceDesc{\n\tServiceName: \"opentelemetry.proto.collector.metrics.v1.MetricsService\",\n\tHandlerType: (*MetricsServiceServer)(nil),\n\tMethods: []grpc.MethodDesc{\n\t\t{\n\t\t\tMethodName: \"Export\",\n\t\t\tHandler:    metricsServiceExportHandler,\n\t\t},\n\t},\n\tStreams:  []grpc.StreamDesc{},\n\tMetadata: \"opentelemetry/proto/collector/metrics/v1/metrics_service.proto\",\n}\n"
  },
  {
    "path": "pdata/internal/otelgrpc/profiles_service.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelgrpc // import \"go.opentelemetry.io/collector/pdata/internal/otelgrpc\"\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ProfilesServiceClient is the client API for ProfilesService service.\n//\n// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.\ntype ProfilesServiceClient interface {\n\tExport(context.Context, *internal.ExportProfilesServiceRequest, ...grpc.CallOption) (*internal.ExportProfilesServiceResponse, error)\n}\n\ntype profilesServiceClient struct {\n\tcc *grpc.ClientConn\n}\n\nfunc NewProfilesServiceClient(cc *grpc.ClientConn) ProfilesServiceClient {\n\treturn &profilesServiceClient{cc}\n}\n\nfunc (c *profilesServiceClient) Export(ctx context.Context, in *internal.ExportProfilesServiceRequest, opts ...grpc.CallOption) (*internal.ExportProfilesServiceResponse, error) {\n\tout := new(internal.ExportProfilesServiceResponse)\n\terr := c.cc.Invoke(ctx, \"/opentelemetry.proto.collector.profiles.v1development.ProfilesService/Export\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}\n\n// ProfilesServiceServer is the server API for ProfilesService service.\ntype ProfilesServiceServer interface {\n\tExport(context.Context, *internal.ExportProfilesServiceRequest) (*internal.ExportProfilesServiceResponse, error)\n}\n\n// UnimplementedProfilesServiceServer can be embedded to have forward compatible implementations.\ntype UnimplementedProfilesServiceServer struct{}\n\nfunc (*UnimplementedProfilesServiceServer) Export(context.Context, *internal.ExportProfilesServiceRequest) (*internal.ExportProfilesServiceResponse, error) {\n\treturn nil, status.Errorf(codes.Unimplemented, \"method Export not implemented\")\n}\n\nfunc RegisterProfilesServiceServer(s *grpc.Server, srv ProfilesServiceServer) {\n\ts.RegisterService(&profilesServiceServiceDesc, srv)\n}\n\n// Context cannot be the first parameter of the function because gRPC definition.\n//\n//nolint:revive\nfunc profilesServiceExportHandler(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {\n\tin := new(internal.ExportProfilesServiceRequest)\n\tif err := dec(in); err != nil {\n\t\treturn nil, err\n\t}\n\tif interceptor == nil {\n\t\treturn srv.(ProfilesServiceServer).Export(ctx, in)\n\t}\n\tinfo := &grpc.UnaryServerInfo{\n\t\tServer:     srv,\n\t\tFullMethod: \"/opentelemetry.proto.collector.profiles.v1development.ProfilesService/Export\",\n\t}\n\thandler := func(ctx context.Context, req any) (any, error) {\n\t\treturn srv.(ProfilesServiceServer).Export(ctx, req.(*internal.ExportProfilesServiceRequest))\n\t}\n\treturn interceptor(ctx, in, info, handler)\n}\n\nvar profilesServiceServiceDesc = grpc.ServiceDesc{\n\tServiceName: \"opentelemetry.proto.collector.profiles.v1development.ProfilesService\",\n\tHandlerType: (*ProfilesServiceServer)(nil),\n\tMethods: []grpc.MethodDesc{\n\t\t{\n\t\t\tMethodName: \"Export\",\n\t\t\tHandler:    profilesServiceExportHandler,\n\t\t},\n\t},\n\tStreams:  []grpc.StreamDesc{},\n\tMetadata: \"opentelemetry/proto/collector/profiles/v1development/profiles_service.proto\",\n}\n"
  },
  {
    "path": "pdata/internal/otelgrpc/trace_service.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelgrpc // import \"go.opentelemetry.io/collector/pdata/internal/otelgrpc\"\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// TraceServiceClient is the client API for TraceService service.\n//\n// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.\ntype TraceServiceClient interface {\n\tExport(context.Context, *internal.ExportTraceServiceRequest, ...grpc.CallOption) (*internal.ExportTraceServiceResponse, error)\n}\n\ntype traceServiceClient struct {\n\tcc *grpc.ClientConn\n}\n\nfunc NewTraceServiceClient(cc *grpc.ClientConn) TraceServiceClient {\n\treturn &traceServiceClient{cc}\n}\n\nfunc (c *traceServiceClient) Export(ctx context.Context, in *internal.ExportTraceServiceRequest, opts ...grpc.CallOption) (*internal.ExportTraceServiceResponse, error) {\n\tout := new(internal.ExportTraceServiceResponse)\n\terr := c.cc.Invoke(ctx, \"/opentelemetry.proto.collector.trace.v1.TraceService/Export\", in, out, opts...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn out, nil\n}\n\n// TraceServiceServer is the server API for TraceService service.\ntype TraceServiceServer interface {\n\tExport(context.Context, *internal.ExportTraceServiceRequest) (*internal.ExportTraceServiceResponse, error)\n}\n\n// UnimplementedTraceServiceServer can be embedded to have forward compatible implementations.\ntype UnimplementedTraceServiceServer struct{}\n\nfunc (*UnimplementedTraceServiceServer) Export(context.Context, *internal.ExportTraceServiceRequest) (*internal.ExportTraceServiceResponse, error) {\n\treturn nil, status.Errorf(codes.Unimplemented, \"method Export not implemented\")\n}\n\nfunc RegisterTraceServiceServer(s *grpc.Server, srv TraceServiceServer) {\n\ts.RegisterService(&traceServiceServiceDesc, srv)\n}\n\n// Context cannot be the first parameter of the function because gRPC definition.\n//\n//nolint:revive\nfunc traceServiceExportHandler(srv any, ctx context.Context, dec func(any) error, interceptor grpc.UnaryServerInterceptor) (any, error) {\n\tin := new(internal.ExportTraceServiceRequest)\n\tif err := dec(in); err != nil {\n\t\treturn nil, err\n\t}\n\tif interceptor == nil {\n\t\treturn srv.(TraceServiceServer).Export(ctx, in)\n\t}\n\tinfo := &grpc.UnaryServerInfo{\n\t\tServer:     srv,\n\t\tFullMethod: \"/opentelemetry.proto.collector.trace.v1.TraceService/Export\",\n\t}\n\thandler := func(ctx context.Context, req any) (any, error) {\n\t\treturn srv.(TraceServiceServer).Export(ctx, req.(*internal.ExportTraceServiceRequest))\n\t}\n\treturn interceptor(ctx, in, info, handler)\n}\n\nvar traceServiceServiceDesc = grpc.ServiceDesc{\n\tServiceName: \"opentelemetry.proto.collector.trace.v1.TraceService\",\n\tHandlerType: (*TraceServiceServer)(nil),\n\tMethods: []grpc.MethodDesc{\n\t\t{\n\t\t\tMethodName: \"Export\",\n\t\t\tHandler:    traceServiceExportHandler,\n\t\t},\n\t},\n\tStreams:  []grpc.StreamDesc{},\n\tMetadata: \"opentelemetry/proto/collector/trace/v1/trace_service.proto\",\n}\n"
  },
  {
    "path": "pdata/internal/otlp/logs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlp // import \"go.opentelemetry.io/collector/pdata/internal/otlp\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// MigrateLogs implements any translation needed due to deprecation in OTLP logs protocol.\n// Any plog.Unmarshaler implementation from OTLP (proto/json) MUST call this, and the gRPC Server implementation.\nfunc MigrateLogs(rls []*internal.ResourceLogs) {\n\tfor _, rl := range rls {\n\t\tif len(rl.ScopeLogs) == 0 {\n\t\t\trl.ScopeLogs = rl.DeprecatedScopeLogs\n\t\t}\n\t\trl.DeprecatedScopeLogs = nil\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/otlp/logs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlp\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestDeprecatedScopeLogs(t *testing.T) {\n\tsl := new(internal.ScopeLogs)\n\trls := []*internal.ResourceLogs{\n\t\t{\n\t\t\tScopeLogs:           []*internal.ScopeLogs{sl},\n\t\t\tDeprecatedScopeLogs: []*internal.ScopeLogs{sl},\n\t\t},\n\t\t{\n\t\t\tScopeLogs:           []*internal.ScopeLogs{},\n\t\t\tDeprecatedScopeLogs: []*internal.ScopeLogs{sl},\n\t\t},\n\t}\n\n\tMigrateLogs(rls)\n\tassert.Same(t, sl, rls[0].ScopeLogs[0])\n\tassert.Same(t, sl, rls[1].ScopeLogs[0])\n\tassert.Nil(t, rls[0].DeprecatedScopeLogs)\n\tassert.Nil(t, rls[0].DeprecatedScopeLogs)\n}\n"
  },
  {
    "path": "pdata/internal/otlp/metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlp // import \"go.opentelemetry.io/collector/pdata/internal/otlp\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// MigrateMetrics implements any translation needed due to deprecation in OTLP metrics protocol.\n// Any pmetric.Unmarshaler implementation from OTLP (proto/json) MUST call this, and the gRPC Server implementation.\nfunc MigrateMetrics(rms []*internal.ResourceMetrics) {\n\tfor _, rm := range rms {\n\t\tif len(rm.ScopeMetrics) == 0 {\n\t\t\trm.ScopeMetrics = rm.DeprecatedScopeMetrics\n\t\t}\n\t\trm.DeprecatedScopeMetrics = nil\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/otlp/metrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlp\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestDeprecatedScopeMetrics(t *testing.T) {\n\tsm := new(internal.ScopeMetrics)\n\trms := []*internal.ResourceMetrics{\n\t\t{\n\t\t\tScopeMetrics:           []*internal.ScopeMetrics{sm},\n\t\t\tDeprecatedScopeMetrics: []*internal.ScopeMetrics{sm},\n\t\t},\n\t\t{\n\t\t\tScopeMetrics:           []*internal.ScopeMetrics{},\n\t\t\tDeprecatedScopeMetrics: []*internal.ScopeMetrics{sm},\n\t\t},\n\t}\n\n\tMigrateMetrics(rms)\n\tassert.Same(t, sm, rms[0].ScopeMetrics[0])\n\tassert.Same(t, sm, rms[1].ScopeMetrics[0])\n\tassert.Nil(t, rms[0].DeprecatedScopeMetrics)\n\tassert.Nil(t, rms[0].DeprecatedScopeMetrics)\n}\n"
  },
  {
    "path": "pdata/internal/otlp/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlp\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "pdata/internal/otlp/profiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlp // import \"go.opentelemetry.io/collector/pdata/internal/otlp\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// MigrateProfiles implements any translation needed due to deprecation in OTLP profiles protocol.\n// Any pprofile.Unmarshaler implementation from OTLP (proto/json) MUST call this, and the gRPC Server implementation.\nfunc MigrateProfiles(_ []*internal.ResourceProfiles) {}\n"
  },
  {
    "path": "pdata/internal/otlp/profiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlp\n\nimport (\n\t\"testing\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestMigrateProfiles(_ *testing.T) {\n\trps := []*internal.ResourceProfiles{\n\t\t{},\n\t}\n\n\tMigrateProfiles(rps)\n}\n"
  },
  {
    "path": "pdata/internal/otlp/traces.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlp // import \"go.opentelemetry.io/collector/pdata/internal/otlp\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// MigrateTraces implements any translation needed due to deprecation in OTLP traces protocol.\n// Any ptrace.Unmarshaler implementation from OTLP (proto/json) MUST call this, and the gRPC Server implementation.\nfunc MigrateTraces(rss []*internal.ResourceSpans) {\n\tfor _, rs := range rss {\n\t\tif len(rs.ScopeSpans) == 0 {\n\t\t\trs.ScopeSpans = rs.DeprecatedScopeSpans\n\t\t}\n\t\trs.DeprecatedScopeSpans = nil\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/otlp/traces_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlp\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestDeprecatedScopeSpans(t *testing.T) {\n\tss := new(internal.ScopeSpans)\n\trss := []*internal.ResourceSpans{\n\t\t{\n\t\t\tScopeSpans:           []*internal.ScopeSpans{ss},\n\t\t\tDeprecatedScopeSpans: []*internal.ScopeSpans{ss},\n\t\t},\n\t\t{\n\t\t\tScopeSpans:           []*internal.ScopeSpans{},\n\t\t\tDeprecatedScopeSpans: []*internal.ScopeSpans{ss},\n\t\t},\n\t}\n\n\tMigrateTraces(rss)\n\tassert.Same(t, ss, rss[0].ScopeSpans[0])\n\tassert.Same(t, ss, rss[1].ScopeSpans[0])\n\tassert.Nil(t, rss[0].DeprecatedScopeSpans)\n\tassert.Nil(t, rss[0].DeprecatedScopeSpans)\n}\n"
  },
  {
    "path": "pdata/internal/profileid.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/pdata/internal\"\n\nimport (\n\t\"encoding/hex\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n)\n\nconst profileIDSize = 16\n\nvar errUnmarshalProfileID = errors.New(\"unmarshal: invalid ProfileID length\")\n\n// ProfileID is a custom data type that is used for all profile_id fields in OTLP\n// Protobuf messages.\ntype ProfileID [profileIDSize]byte\n\nfunc DeleteProfileID(*ProfileID, bool) {}\n\nfunc CopyProfileID(dest, src *ProfileID) {\n\t*dest = *src\n}\n\n// IsEmpty returns true if id contains at leas one non-zero byte.\nfunc (pid ProfileID) IsEmpty() bool {\n\treturn pid == [profileIDSize]byte{}\n}\n\n// SizeProto returns the size of the data to serialize in proto format.\nfunc (pid ProfileID) SizeProto() int {\n\tif pid.IsEmpty() {\n\t\treturn 0\n\t}\n\n\treturn profileIDSize\n}\n\n// MarshalProto converts profile ID into a binary representation. Called by Protobuf serialization.\nfunc (pid ProfileID) MarshalProto(buf []byte) int {\n\tif pid.IsEmpty() {\n\t\treturn 0\n\t}\n\n\treturn copy(buf[len(buf)-profileIDSize:], pid[:])\n}\n\n// UnmarshalProto inflates this profile ID from binary representation. Called by Protobuf serialization.\nfunc (pid *ProfileID) UnmarshalProto(buf []byte) error {\n\tif len(buf) == 0 {\n\t\t*pid = [profileIDSize]byte{}\n\t\treturn nil\n\t}\n\n\tif len(buf) != profileIDSize {\n\t\treturn errUnmarshalProfileID\n\t}\n\n\tcopy(pid[:], buf)\n\treturn nil\n}\n\n// MarshalJSON converts ProfileID into a hex string.\n//\n//nolint:govet\nfunc (pid ProfileID) MarshalJSON(dest *json.Stream) {\n\tdest.WriteString(hex.EncodeToString(pid[:]))\n}\n\n// UnmarshalJSON decodes ProfileID from hex string.\n//\n//nolint:govet\nfunc (pid *ProfileID) UnmarshalJSON(iter *json.Iterator) {\n\t*pid = [profileIDSize]byte{}\n\tunmarshalJSON(pid[:], iter)\n}\n\nfunc GenTestProfileID() *ProfileID {\n\tpid := ProfileID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1})\n\treturn &pid\n}\n"
  },
  {
    "path": "pdata/internal/profileid_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n)\n\nfunc TestProfileID(t *testing.T) {\n\ttid := ProfileID([profileIDSize]byte{})\n\tassert.EqualValues(t, [profileIDSize]byte{}, tid)\n\tassert.Equal(t, 0, tid.SizeProto())\n\n\tb := [profileIDSize]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}\n\ttid = b\n\tassert.EqualValues(t, b, tid)\n\tassert.Equal(t, profileIDSize, tid.SizeProto())\n}\n\nfunc TestProfileIDMarshal(t *testing.T) {\n\tbuf := make([]byte, profileIDSize)\n\n\ttid := ProfileID([profileIDSize]byte{})\n\tn := tid.MarshalProto(buf)\n\tassert.Equal(t, 0, n)\n\n\ttid = [profileIDSize]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}\n\tn = tid.MarshalProto(buf)\n\tassert.Equal(t, profileIDSize, n)\n\tassert.Equal(t, []byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}, buf[0:profileIDSize])\n}\n\nfunc TestProfileIDUnmarshal(t *testing.T) {\n\tbuf := [profileIDSize]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}\n\n\ttid := ProfileID{}\n\terr := tid.UnmarshalProto(buf[:])\n\trequire.NoError(t, err)\n\tassert.EqualValues(t, buf, tid)\n\n\terr = tid.UnmarshalProto(buf[0:0])\n\trequire.NoError(t, err)\n\tassert.EqualValues(t, [profileIDSize]byte{}, tid)\n\n\terr = tid.UnmarshalProto(nil)\n\trequire.NoError(t, err)\n\tassert.EqualValues(t, [profileIDSize]byte{}, tid)\n}\n\nfunc TestProfileIDMarshalAndUnmarshalJSON(t *testing.T) {\n\tstream := json.BorrowStream(nil)\n\tdefer json.ReturnStream(stream)\n\tsrc := ProfileID([profileIDSize]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78})\n\tsrc.MarshalJSON(stream)\n\trequire.NoError(t, stream.Error())\n\n\titer := json.BorrowIterator(stream.Buffer())\n\tdefer json.ReturnIterator(iter)\n\tdest := ProfileID{}\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\n\tassert.Equal(t, src, dest)\n}\n"
  },
  {
    "path": "pdata/internal/proto/marshal.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/pdata/internal/proto\"\n\n// EncodeVarint encodes the variant at the end of the buffer.\nfunc EncodeVarint(buf []byte, offset int, v uint64) int {\n\toffset -= Sov(v)\n\tbase := offset\n\tfor v >= 1<<7 {\n\t\tbuf[offset] = uint8(v&0x7f | 0x80)\n\t\tv >>= 7\n\t\toffset++\n\t}\n\tbuf[offset] = uint8(v)\n\treturn base\n}\n"
  },
  {
    "path": "pdata/internal/proto/size.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/pdata/internal/proto\"\n\nimport (\n\t\"math/bits\"\n)\n\nfunc Sov(x uint64) (n int) {\n\treturn (bits.Len64(x|1) + 6) / 7\n}\n\nfunc Soz(x uint64) (n int) {\n\treturn Sov((x << 1) ^ uint64((int64(x) >> 63)))\n}\n"
  },
  {
    "path": "pdata/internal/proto/unmarshal.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proto // import \"go.opentelemetry.io/collector/pdata/internal/proto\"\n\nimport (\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n)\n\n// WireType represents the proto wire type.\ntype WireType int8\n\nconst (\n\tWireTypeVarint     WireType = 0\n\tWireTypeI64        WireType = 1\n\tWireTypeLen        WireType = 2\n\tWireTypeStartGroup WireType = 3\n\tWireTypeEndGroup   WireType = 4\n\tWireTypeI32        WireType = 5\n)\n\nvar (\n\tErrInvalidLength        = errors.New(\"proto: negative length found during unmarshaling\")\n\tErrIntOverflow          = errors.New(\"proto: integer overflow\")\n\tErrUnexpectedEndOfGroup = errors.New(\"proto: unexpected end of group\")\n)\n\n// ConsumeUnknown parses buf starting at pos as a wireType field, reporting the new position.\nfunc ConsumeUnknown(buf []byte, pos int, wireType WireType) (int, error) {\n\tvar err error\n\tl := len(buf)\n\tdepth := 0\n\tfor pos < l {\n\t\tswitch wireType {\n\t\tcase WireTypeVarint:\n\t\t\t_, pos, err = ConsumeVarint(buf, pos)\n\t\t\treturn pos, err\n\t\tcase WireTypeI64:\n\t\t\t_, pos, err = ConsumeI64(buf, pos)\n\t\t\treturn pos, err\n\t\tcase WireTypeLen:\n\t\t\t_, pos, err = ConsumeLen(buf, pos)\n\t\t\treturn pos, err\n\t\tcase WireTypeStartGroup:\n\t\t\tdepth++\n\t\tcase WireTypeEndGroup:\n\t\t\tif depth == 0 {\n\t\t\t\treturn 0, ErrUnexpectedEndOfGroup\n\t\t\t}\n\t\t\tdepth--\n\t\tcase WireTypeI32:\n\t\t\t_, pos, err = ConsumeI32(buf, pos)\n\t\t\treturn pos, err\n\t\tdefault:\n\t\t\treturn 0, fmt.Errorf(\"proto: illegal wireType %d\", wireType)\n\t\t}\n\n\t\t// Only when parsing a group can be here, if done return otherwise parse more tags.\n\t\tif depth == 0 {\n\t\t\treturn pos, nil\n\t\t}\n\n\t\t// If in a group parsing, move to the next tag.\n\t\t_, wireType, pos, err = ConsumeTag(buf, pos)\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t}\n\treturn 0, io.ErrUnexpectedEOF\n}\n\n// ConsumeI64 parses buf starting at pos as a WireTypeI64 field, reporting the value and the new position.\nfunc ConsumeI64(buf []byte, pos int) (uint64, int, error) {\n\tpos += 8\n\tif pos < 0 || pos > len(buf) {\n\t\treturn 0, 0, io.ErrUnexpectedEOF\n\t}\n\treturn binary.LittleEndian.Uint64(buf[pos-8:]), pos, nil\n}\n\n// ConsumeLen parses buf starting at pos as a WireTypeLen field, reporting the len and the new position.\nfunc ConsumeLen(buf []byte, pos int) (int, int, error) {\n\tvar num uint64\n\tvar err error\n\tnum, pos, err = ConsumeVarint(buf, pos)\n\tif err != nil {\n\t\treturn 0, 0, err\n\t}\n\tlength := int(num)\n\tif length < 0 {\n\t\treturn 0, 0, ErrInvalidLength\n\t}\n\tpos += length\n\tif pos < 0 || pos > len(buf) {\n\t\treturn 0, 0, io.ErrUnexpectedEOF\n\t}\n\treturn length, pos, nil\n}\n\n// ConsumeI32 parses buf starting at pos as a WireTypeI32 field, reporting the value and the new position.\nfunc ConsumeI32(buf []byte, pos int) (uint32, int, error) {\n\tpos += 4\n\tif pos < 0 || pos > len(buf) {\n\t\treturn 0, 0, io.ErrUnexpectedEOF\n\t}\n\treturn binary.LittleEndian.Uint32(buf[pos-4:]), pos, nil\n}\n\n// ConsumeTag parses buf starting at pos as a varint-encoded tag, reporting the new position.\nfunc ConsumeTag(buf []byte, pos int) (int32, WireType, int, error) {\n\ttag, pos, err := ConsumeVarint(buf, pos)\n\tif err != nil {\n\t\treturn 0, 0, 0, err\n\t}\n\tfieldNum := int32(tag >> 3)\n\twireType := int8(tag & 0x7)\n\tif fieldNum <= 0 {\n\t\treturn 0, 0, 0, fmt.Errorf(\"proto: Link: illegal field=%d (tag=%d, pos=%d)\", fieldNum, tag, pos)\n\t}\n\treturn fieldNum, WireType(wireType), pos, nil\n}\n\n// ConsumeVarint parses buf starting at pos as a varint-encoded uint64, reporting the new position.\nfunc ConsumeVarint(buf []byte, pos int) (uint64, int, error) {\n\tl := len(buf)\n\tvar num uint64\n\tfor shift := uint(0); ; shift += 7 {\n\t\tif shift >= 64 {\n\t\t\treturn 0, 0, ErrIntOverflow\n\t\t}\n\t\tif pos >= l {\n\t\t\treturn 0, 0, io.ErrUnexpectedEOF\n\t\t}\n\t\tb := buf[pos]\n\t\tpos++\n\t\tnum |= uint64(b&0x7F) << shift\n\t\tif b < 0x80 {\n\t\t\tbreak\n\t\t}\n\t}\n\treturn num, pos, nil\n}\n"
  },
  {
    "path": "pdata/internal/spanid.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/pdata/internal\"\n\nimport (\n\t\"encoding/hex\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n)\n\nconst spanIDSize = 8\n\nvar errUnmarshalSpanID = errors.New(\"unmarshal: invalid SpanID length\")\n\n// SpanID is a custom data type that is used for all span_id fields in OTLP\n// Protobuf messages.\ntype SpanID [spanIDSize]byte\n\nfunc DeleteSpanID(*SpanID, bool) {}\n\nfunc CopySpanID(dest, src *SpanID) {\n\t*dest = *src\n}\n\n// IsEmpty returns true if id contains at least one non-zero byte.\nfunc (sid SpanID) IsEmpty() bool {\n\treturn sid == [spanIDSize]byte{}\n}\n\n// SizeProto returns the size of the data to serialize in proto format.\nfunc (sid SpanID) SizeProto() int {\n\tif sid.IsEmpty() {\n\t\treturn 0\n\t}\n\treturn spanIDSize\n}\n\n// MarshalProto converts span ID into a binary representation. Called by Protobuf serialization.\nfunc (sid SpanID) MarshalProto(buf []byte) int {\n\tif sid.IsEmpty() {\n\t\treturn 0\n\t}\n\n\treturn copy(buf[len(buf)-spanIDSize:], sid[:])\n}\n\n// UnmarshalProto inflates this span ID from binary representation. Called by Protobuf serialization.\nfunc (sid *SpanID) UnmarshalProto(data []byte) error {\n\tif len(data) == 0 {\n\t\t*sid = [spanIDSize]byte{}\n\t\treturn nil\n\t}\n\n\tif len(data) != spanIDSize {\n\t\treturn errUnmarshalSpanID\n\t}\n\n\tcopy(sid[:], data)\n\treturn nil\n}\n\n// MarshalJSON converts SpanID into a hex string.\n//\n//nolint:govet\nfunc (sid SpanID) MarshalJSON(dest *json.Stream) {\n\tdest.WriteString(hex.EncodeToString(sid[:]))\n}\n\n// UnmarshalJSON decodes SpanID from hex string.\n//\n//nolint:govet\nfunc (sid *SpanID) UnmarshalJSON(iter *json.Iterator) {\n\t*sid = [spanIDSize]byte{}\n\tunmarshalJSON(sid[:], iter)\n}\n\nfunc GenTestSpanID() *SpanID {\n\tsid := SpanID([8]byte{8, 7, 6, 5, 4, 3, 2, 1})\n\treturn &sid\n}\n"
  },
  {
    "path": "pdata/internal/spanid_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n)\n\nfunc TestSpanID(t *testing.T) {\n\tsid := SpanID([spanIDSize]byte{})\n\tassert.EqualValues(t, [spanIDSize]byte{}, sid)\n\tassert.Equal(t, 0, sid.SizeProto())\n\n\tb := [spanIDSize]byte{1, 2, 3, 4, 5, 6, 7, 8}\n\tsid = b\n\tassert.EqualValues(t, b, sid)\n\tassert.Equal(t, 8, sid.SizeProto())\n}\n\nfunc TestSpanIDMarshal(t *testing.T) {\n\tbuf := make([]byte, spanIDSize)\n\n\tsid := SpanID([spanIDSize]byte{})\n\tn := sid.MarshalProto(buf)\n\tassert.Equal(t, 0, n)\n\n\tsid = [spanIDSize]byte{1, 2, 3, 4, 5, 6, 7, 8}\n\tn = sid.MarshalProto(buf)\n\tassert.Equal(t, spanIDSize, n)\n\tassert.Equal(t, []byte{1, 2, 3, 4, 5, 6, 7, 8}, buf[0:spanIDSize])\n}\n\nfunc TestSpanIDUnmarshal(t *testing.T) {\n\tbuf := [spanIDSize]byte{0x12, 0x23, 0xAD, 0x12, 0x23, 0xAD, 0x12, 0x23}\n\n\tsid := SpanID{}\n\terr := sid.UnmarshalProto(buf[:])\n\trequire.NoError(t, err)\n\tassert.EqualValues(t, [spanIDSize]byte{0x12, 0x23, 0xAD, 0x12, 0x23, 0xAD, 0x12, 0x23}, sid)\n\n\terr = sid.UnmarshalProto(buf[0:0])\n\trequire.NoError(t, err)\n\tassert.EqualValues(t, [spanIDSize]byte{}, sid)\n\n\terr = sid.UnmarshalProto(nil)\n\trequire.NoError(t, err)\n\tassert.EqualValues(t, [spanIDSize]byte{}, sid)\n\n\terr = sid.UnmarshalProto(buf[0:3])\n\tassert.Error(t, err)\n}\n\nfunc TestSpanIDMarshalAndUnmarshalJSON(t *testing.T) {\n\tstream := json.BorrowStream(nil)\n\tdefer json.ReturnStream(stream)\n\tsrc := SpanID([spanIDSize]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78})\n\tsrc.MarshalJSON(stream)\n\trequire.NoError(t, stream.Error())\n\n\titer := json.BorrowIterator(stream.Buffer())\n\tdefer json.ReturnIterator(iter)\n\tdest := SpanID{}\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\n\tassert.Equal(t, src, dest)\n}\n"
  },
  {
    "path": "pdata/internal/state.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/pdata/internal\"\nimport (\n\t\"sync/atomic\"\n)\n\n// State defines an ownership state of pmetric.Metrics, plog.Logs, ptrace.Traces or pprofile.Profiles.\ntype State struct {\n\trefs  atomic.Int32\n\tstate uint32\n}\n\nconst (\n\tdefaultState          uint32 = 0\n\tstateReadOnlyBit             = uint32(1 << 0)\n\tstatePipelineOwnedBit        = uint32(1 << 1)\n)\n\nfunc NewState() *State {\n\tst := &State{\n\t\tstate: defaultState,\n\t}\n\tst.refs.Store(1)\n\treturn st\n}\n\nfunc (st *State) MarkReadOnly() {\n\tst.state |= stateReadOnlyBit\n}\n\nfunc (st *State) IsReadOnly() bool {\n\treturn st.state&stateReadOnlyBit != 0\n}\n\n// AssertMutable panics if the state is not StateMutable.\nfunc (st *State) AssertMutable() {\n\tif st.state&stateReadOnlyBit != 0 {\n\t\tpanic(\"invalid access to shared data\")\n\t}\n}\n\n// MarkPipelineOwned marks the data as owned by the pipeline, returns true if the data were\n// previously not owned by the pipeline, otherwise false.\nfunc (st *State) MarkPipelineOwned() bool {\n\tif st.state&statePipelineOwnedBit != 0 {\n\t\treturn false\n\t}\n\tst.state |= statePipelineOwnedBit\n\treturn true\n}\n\n// Ref add one to the count of active references.\nfunc (st *State) Ref() {\n\tst.refs.Add(1)\n}\n\n// Unref returns true if reference count got to 0 which means no more active references,\n// otherwise it returns false.\nfunc (st *State) Unref() bool {\n\trefs := st.refs.Add(-1)\n\tswitch {\n\tcase refs > 0:\n\t\treturn false\n\tcase refs == 0:\n\t\treturn true\n\tdefault:\n\t\tpanic(\"Cannot unref freed data\")\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/state_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc TestAssertMutable(t *testing.T) {\n\tassert.NotPanics(t, func() { NewState().AssertMutable() })\n\tassert.Panics(t, func() {\n\t\tstate := NewState()\n\t\tstate.MarkReadOnly()\n\t\tstate.AssertMutable()\n\t})\n}\n\nfunc BenchmarkAssertMutable(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\tb.ReportAllocs()\n\n\tmutable := NewState()\n\tfor b.Loop() {\n\t\tmutable.AssertMutable()\n\t}\n}\n"
  },
  {
    "path": "pdata/internal/traceid.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/pdata/internal\"\n\nimport (\n\t\"encoding/hex\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n)\n\nconst traceIDSize = 16\n\nvar errUnmarshalTraceID = errors.New(\"unmarshal: invalid TraceID length\")\n\n// TraceID is a custom data type that is used for all trace_id fields in OTLP\n// Protobuf messages.\ntype TraceID [traceIDSize]byte\n\nfunc DeleteTraceID(*TraceID, bool) {}\n\nfunc CopyTraceID(dest, src *TraceID) {\n\t*dest = *src\n}\n\n// IsEmpty returns true if id contains at leas one non-zero byte.\nfunc (tid TraceID) IsEmpty() bool {\n\treturn tid == [traceIDSize]byte{}\n}\n\n// SizeProto returns the size of the data to serialize in proto format.\nfunc (tid TraceID) SizeProto() int {\n\tif tid.IsEmpty() {\n\t\treturn 0\n\t}\n\n\treturn traceIDSize\n}\n\n// MarshalProto converts trace ID into a binary representation. Called by Protobuf serialization.\nfunc (tid TraceID) MarshalProto(buf []byte) int {\n\tif tid.IsEmpty() {\n\t\treturn 0\n\t}\n\n\treturn copy(buf[len(buf)-traceIDSize:], tid[:])\n}\n\n// UnmarshalProto inflates this trace ID from binary representation. Called by Protobuf serialization.\nfunc (tid *TraceID) UnmarshalProto(buf []byte) error {\n\tif len(buf) == 0 {\n\t\t*tid = [traceIDSize]byte{}\n\t\treturn nil\n\t}\n\n\tif len(buf) != traceIDSize {\n\t\treturn errUnmarshalTraceID\n\t}\n\n\tcopy(tid[:], buf)\n\treturn nil\n}\n\n// MarshalJSON converts TraceID into a hex string.\n//\n//nolint:govet\nfunc (tid TraceID) MarshalJSON(dest *json.Stream) {\n\tdest.WriteString(hex.EncodeToString(tid[:]))\n}\n\n// UnmarshalJSON decodes TraceID from hex string.\n//\n//nolint:govet\nfunc (tid *TraceID) UnmarshalJSON(iter *json.Iterator) {\n\t*tid = [profileIDSize]byte{}\n\tunmarshalJSON(tid[:], iter)\n}\n\nfunc GenTestTraceID() *TraceID {\n\ttid := TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1})\n\treturn &tid\n}\n"
  },
  {
    "path": "pdata/internal/traceid_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n)\n\nfunc TestTraceID(t *testing.T) {\n\ttid := TraceID([traceIDSize]byte{})\n\tassert.EqualValues(t, [traceIDSize]byte{}, tid)\n\tassert.Equal(t, 0, tid.SizeProto())\n\n\tb := [traceIDSize]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}\n\ttid = b\n\tassert.EqualValues(t, b, tid)\n\tassert.Equal(t, traceIDSize, tid.SizeProto())\n}\n\nfunc TestTraceIDMarshal(t *testing.T) {\n\tbuf := make([]byte, traceIDSize)\n\n\ttid := TraceID([traceIDSize]byte{})\n\tn := tid.MarshalProto(buf)\n\tassert.Equal(t, 0, n)\n\n\ttid = [traceIDSize]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}\n\tn = tid.MarshalProto(buf)\n\tassert.Equal(t, traceIDSize, n)\n\tassert.Equal(t, []byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}, buf[0:traceIDSize])\n}\n\nfunc TestTraceIDUnmarshal(t *testing.T) {\n\tbuf := [16]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}\n\n\ttid := TraceID{}\n\terr := tid.UnmarshalProto(buf[:])\n\trequire.NoError(t, err)\n\tassert.EqualValues(t, buf, tid)\n\n\terr = tid.UnmarshalProto(buf[0:0])\n\trequire.NoError(t, err)\n\tassert.EqualValues(t, [traceIDSize]byte{}, tid)\n\n\terr = tid.UnmarshalProto(nil)\n\trequire.NoError(t, err)\n\tassert.EqualValues(t, [traceIDSize]byte{}, tid)\n}\n\nfunc TestTraceIDMarshalAndUnmarshalJSON(t *testing.T) {\n\tstream := json.BorrowStream(nil)\n\tdefer json.ReturnStream(stream)\n\tsrc := TraceID([traceIDSize]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78})\n\tsrc.MarshalJSON(stream)\n\trequire.NoError(t, stream.Error())\n\n\titer := json.BorrowIterator(stream.Buffer())\n\tdefer json.ReturnIterator(iter)\n\tdest := TraceID{}\n\tdest.UnmarshalJSON(iter)\n\trequire.NoError(t, iter.Error())\n\n\tassert.Equal(t, src, dest)\n}\n"
  },
  {
    "path": "pdata/internal/unpacked_unmarshal_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"encoding/binary\"\n\t\"math\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/proto\"\n)\n\n// For each repeated field in the OTLP proto that should be packed, check that we can unmarshal\n// payloads where it is encoded as unpacked.\n// The Protobuf spec recommends this for backwards compatibility purposes.\n// We do not test profiles payloads since their proto definition is currently in development.\n\nfunc appendTag(buf []byte, fieldNo byte, wireType proto.WireType) []byte {\n\treturn append(buf, (fieldNo<<3)|byte(wireType))\n}\n\nfunc appendVarint(buf []byte, v uint64) []byte {\n\tn := proto.Sov(v)\n\tfor range n {\n\t\tbuf = append(buf, 0)\n\t}\n\t_ = proto.EncodeVarint(buf, len(buf), v)\n\treturn buf\n}\n\nfunc TestUnmarshalUnpackedHistogramDataPoint(t *testing.T) {\n\tvar pb []byte\n\tpb = appendTag(pb, 6, proto.WireTypeI64) // bucket_counts\n\tpb = binary.LittleEndian.AppendUint64(pb, 42)\n\tpb = appendTag(pb, 7, proto.WireTypeI64) // explicit_bounds\n\tpb = binary.LittleEndian.AppendUint64(pb, math.Float64bits(42.0))\n\n\tvar hdp HistogramDataPoint\n\terr := hdp.UnmarshalProto(pb)\n\trequire.NoError(t, err)\n\tassert.Equal(t, HistogramDataPoint{\n\t\tBucketCounts:   []uint64{42},\n\t\tExplicitBounds: []float64{42.0},\n\t}, hdp)\n}\n\nfunc TestUnmarshalUnpackedExponentialHistogramDataPoint_Buckets(t *testing.T) {\n\tvar pb []byte\n\tpb = appendTag(pb, 2, proto.WireTypeVarint) // bucket_counts\n\tpb = appendVarint(pb, 42)\n\n\tvar ehdpb ExponentialHistogramDataPointBuckets\n\terr := ehdpb.UnmarshalProto(pb)\n\trequire.NoError(t, err)\n\tassert.Equal(t, ExponentialHistogramDataPointBuckets{\n\t\tBucketCounts: []uint64{42},\n\t}, ehdpb)\n}\n"
  },
  {
    "path": "pdata/internal/wrapper_logs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/pdata/internal\"\n\n// LogsToProto internal helper to convert Logs to protobuf representation.\nfunc LogsToProto(l LogsWrapper) LogsData {\n\treturn LogsData{\n\t\tResourceLogs: l.orig.ResourceLogs,\n\t}\n}\n\n// LogsFromProto internal helper to convert protobuf representation to Logs.\n// This function set exclusive state assuming that it's called only once per Logs.\nfunc LogsFromProto(orig LogsData) LogsWrapper {\n\treturn NewLogsWrapper(&ExportLogsServiceRequest{\n\t\tResourceLogs: orig.ResourceLogs,\n\t}, NewState())\n}\n"
  },
  {
    "path": "pdata/internal/wrapper_map.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/pdata/internal\"\n\ntype MapWrapper struct {\n\torig  *[]KeyValue\n\tstate *State\n}\n\nfunc GetMapOrig(ms MapWrapper) *[]KeyValue {\n\treturn ms.orig\n}\n\nfunc GetMapState(ms MapWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewMapWrapper(orig *[]KeyValue, state *State) MapWrapper {\n\treturn MapWrapper{orig: orig, state: state}\n}\n\nfunc GenTestMapWrapper() MapWrapper {\n\torig := GenTestKeyValueSlice()\n\treturn NewMapWrapper(&orig, NewState())\n}\n"
  },
  {
    "path": "pdata/internal/wrapper_metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/pdata/internal\"\n\n// MetricsToProto internal helper to convert Metrics to protobuf representation.\nfunc MetricsToProto(l MetricsWrapper) MetricsData {\n\treturn MetricsData{\n\t\tResourceMetrics: l.orig.ResourceMetrics,\n\t}\n}\n\n// MetricsFromProto internal helper to convert protobuf representation to Metrics.\n// This function set exclusive state assuming that it's called only once per Metrics.\nfunc MetricsFromProto(orig MetricsData) MetricsWrapper {\n\treturn NewMetricsWrapper(&ExportMetricsServiceRequest{\n\t\tResourceMetrics: orig.ResourceMetrics,\n\t}, NewState())\n}\n"
  },
  {
    "path": "pdata/internal/wrapper_profiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/pdata/internal\"\n\n// ProfilesToProto internal helper to convert Profiles to protobuf representation.\nfunc ProfilesToProto(l ProfilesWrapper) ProfilesData {\n\treturn ProfilesData{\n\t\tResourceProfiles: l.orig.ResourceProfiles,\n\t\tDictionary:       l.orig.Dictionary,\n\t}\n}\n\n// ProfilesFromProto internal helper to convert protobuf representation to Profiles.\n// This function set exclusive state assuming that it's called only once per Profiles.\nfunc ProfilesFromProto(orig ProfilesData) ProfilesWrapper {\n\treturn NewProfilesWrapper(&ExportProfilesServiceRequest{\n\t\tResourceProfiles: orig.ResourceProfiles,\n\t\tDictionary:       orig.Dictionary,\n\t}, NewState())\n}\n"
  },
  {
    "path": "pdata/internal/wrapper_traces.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/pdata/internal\"\n\n// TracesToProto internal helper to convert Traces to protobuf representation.\nfunc TracesToProto(l TracesWrapper) TracesData {\n\treturn TracesData{\n\t\tResourceSpans: l.orig.ResourceSpans,\n\t}\n}\n\n// TracesFromProto internal helper to convert protobuf representation to Traces.\n// This function set exclusive state assuming that it's called only once per Traces.\nfunc TracesFromProto(orig TracesData) TracesWrapper {\n\treturn NewTracesWrapper(&ExportTraceServiceRequest{\n\t\tResourceSpans: orig.ResourceSpans,\n\t}, NewState())\n}\n"
  },
  {
    "path": "pdata/internal/wrapper_tracestate.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/pdata/internal\"\n\ntype TraceStateWrapper struct {\n\torig  *string\n\tstate *State\n}\n\nfunc GetTraceStateOrig(ms TraceStateWrapper) *string {\n\treturn ms.orig\n}\n\nfunc GetTraceStateState(ms TraceStateWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewTraceStateWrapper(orig *string, state *State) TraceStateWrapper {\n\treturn TraceStateWrapper{orig: orig, state: state}\n}\n\nfunc GenTestTraceStateWrapper() TraceStateWrapper {\n\treturn NewTraceStateWrapper(GenTestTraceState(), NewState())\n}\n\nfunc GenTestTraceState() *string {\n\torig := new(string)\n\t*orig = \"rojo=00f067aa0ba902b7\"\n\treturn orig\n}\n"
  },
  {
    "path": "pdata/internal/wrapper_value.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/pdata/internal\"\n\nimport \"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\ntype ValueWrapper struct {\n\torig  *AnyValue\n\tstate *State\n}\n\nfunc GetValueOrig(ms ValueWrapper) *AnyValue {\n\treturn ms.orig\n}\n\nfunc GetValueState(ms ValueWrapper) *State {\n\treturn ms.state\n}\n\nfunc NewValueWrapper(orig *AnyValue, state *State) ValueWrapper {\n\treturn ValueWrapper{orig: orig, state: state}\n}\n\nfunc GenTestValueWrapper() ValueWrapper {\n\torig := GenTestAnyValue()\n\treturn NewValueWrapper(orig, NewState())\n}\n\nfunc NewAnyValueStringValue() *AnyValue_StringValue {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &AnyValue_StringValue{}\n\t}\n\treturn ProtoPoolAnyValue_StringValue.Get().(*AnyValue_StringValue)\n}\n\nfunc NewAnyValueIntValue() *AnyValue_IntValue {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &AnyValue_IntValue{}\n\t}\n\treturn ProtoPoolAnyValue_IntValue.Get().(*AnyValue_IntValue)\n}\n\nfunc NewAnyValueBoolValue() *AnyValue_BoolValue {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &AnyValue_BoolValue{}\n\t}\n\treturn ProtoPoolAnyValue_BoolValue.Get().(*AnyValue_BoolValue)\n}\n\nfunc NewAnyValueDoubleValue() *AnyValue_DoubleValue {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &AnyValue_DoubleValue{}\n\t}\n\treturn ProtoPoolAnyValue_DoubleValue.Get().(*AnyValue_DoubleValue)\n}\n\nfunc NewAnyValueBytesValue() *AnyValue_BytesValue {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &AnyValue_BytesValue{}\n\t}\n\treturn ProtoPoolAnyValue_BytesValue.Get().(*AnyValue_BytesValue)\n}\n\nfunc NewAnyValueArrayValue() *AnyValue_ArrayValue {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &AnyValue_ArrayValue{}\n\t}\n\treturn ProtoPoolAnyValue_ArrayValue.Get().(*AnyValue_ArrayValue)\n}\n\nfunc NewAnyValueKvlistValue() *AnyValue_KvlistValue {\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\treturn &AnyValue_KvlistValue{}\n\t}\n\treturn ProtoPoolAnyValue_KvlistValue.Get().(*AnyValue_KvlistValue)\n}\n"
  },
  {
    "path": "pdata/internal/wrapper_value_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcommon \"go.opentelemetry.io/proto/slim/otlp/common/v1\"\n\tgoproto \"google.golang.org/protobuf/proto\"\n)\n\nfunc TestAnyValueBytes(t *testing.T) {\n\tav := &gootlpcommon.AnyValue{Value: &gootlpcommon.AnyValue_BytesValue{BytesValue: nil}}\n\tbuf, err := goproto.Marshal(av)\n\trequire.NoError(t, err)\n\n\tpav := &AnyValue{Value: &AnyValue_BytesValue{BytesValue: nil}}\n\tpbuf := make([]byte, pav.SizeProto())\n\tn := pav.MarshalProto(pbuf)\n\tpbuf = pbuf[:n]\n\trequire.Equal(t, buf, pbuf)\n}\n"
  },
  {
    "path": "pdata/metadata.yaml",
    "content": "type: pdata\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  codeowners:\n    active:\n      - bogdandrutu\n      - dmitryax\n  stability:\n    stable: [traces, metrics, logs]\n\nfeature_gates:\n  - id: pdata.useCustomProtoEncoding\n    description: 'When enabled, enable custom proto encoding. This is a required step to enable featuregate pdata.useProtoPooling.'\n    stage: stable\n    from_version: 'v0.133.0'\n    to_version: 'v0.137.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/issues/13631'\n  - id: pdata.useProtoPooling\n    description: 'When enabled, enable using local memory pools for underlying data that the pdata messages are pushed to.'\n    stage: alpha\n    from_version: 'v0.133.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/issues/13631'\n"
  },
  {
    "path": "pdata/pcommon/generated_byteslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"iter\"\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ByteSlice represents a []byte slice.\n// The instance of ByteSlice can be assigned to multiple objects since it's immutable.\n//\n// Must use NewByteSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ByteSlice internal.ByteSliceWrapper\n\nfunc (ms ByteSlice) getOrig() *[]byte {\n\treturn internal.GetByteSliceOrig(internal.ByteSliceWrapper(ms))\n}\n\nfunc (ms ByteSlice) getState() *internal.State {\n\treturn internal.GetByteSliceState(internal.ByteSliceWrapper(ms))\n}\n\n// NewByteSlice creates a new empty ByteSlice.\nfunc NewByteSlice() ByteSlice {\n\torig := []byte(nil)\n\treturn ByteSlice(internal.NewByteSliceWrapper(&orig, internal.NewState()))\n}\n\n// AsRaw returns a copy of the []byte slice.\nfunc (ms ByteSlice) AsRaw() []byte {\n\treturn copyByteSlice(nil, *ms.getOrig())\n}\n\n// FromRaw copies raw []byte into the slice ByteSlice.\nfunc (ms ByteSlice) FromRaw(val []byte) {\n\tms.getState().AssertMutable()\n\t*ms.getOrig() = copyByteSlice(*ms.getOrig(), val)\n}\n\n// Len returns length of the []byte slice value.\n// Equivalent of len(byteSlice).\nfunc (ms ByteSlice) Len() int {\n\treturn len(*ms.getOrig())\n}\n\n// At returns an item from particular index.\n// Equivalent of byteSlice[i].\nfunc (ms ByteSlice) At(i int) byte {\n\treturn (*ms.getOrig())[i]\n}\n\n// All returns an iterator over index-value pairs in the slice.\nfunc (ms ByteSlice) All() iter.Seq2[int, byte] {\n\treturn func(yield func(int, byte) bool) {\n\t\tfor i := 0; i < ms.Len(); i++ {\n\t\t\tif !yield(i, ms.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// SetAt sets byte item at particular index.\n// Equivalent of byteSlice[i] = val\nfunc (ms ByteSlice) SetAt(i int, val byte) {\n\tms.getState().AssertMutable()\n\t(*ms.getOrig())[i] = val\n}\n\n// EnsureCapacity ensures ByteSlice has at least the specified capacity.\n//  1. If the newCap <= cap, then is no change in capacity.\n//  2. If the newCap > cap, then the slice capacity will be expanded to the provided value which will be equivalent of:\n//     buf := make([]byte, len(byteSlice), newCap)\n//     copy(buf, byteSlice)\n//     byteSlice = buf\nfunc (ms ByteSlice) EnsureCapacity(newCap int) {\n\tms.getState().AssertMutable()\n\toldCap := cap(*ms.getOrig())\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]byte, len(*ms.getOrig()), newCap)\n\tcopy(newOrig, *ms.getOrig())\n\t*ms.getOrig() = newOrig\n}\n\n// Append appends extra elements to ByteSlice.\n// Equivalent of byteSlice = append(byteSlice, elms...)\nfunc (ms ByteSlice) Append(elms ...byte) {\n\tms.getState().AssertMutable()\n\t*ms.getOrig() = append(*ms.getOrig(), elms...)\n}\n\n// MoveTo moves all elements from the current slice overriding the destination and\n// resetting the current instance to its zero value.\nfunc (ms ByteSlice) MoveTo(dest ByteSlice) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = *ms.getOrig()\n\t*ms.getOrig() = nil\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (ms ByteSlice) MoveAndAppendTo(dest ByteSlice) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\tif *dest.getOrig() == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.getOrig() = *ms.getOrig()\n\t} else {\n\t\t*dest.getOrig() = append(*dest.getOrig(), *ms.getOrig()...)\n\t}\n\t*ms.getOrig() = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (ms ByteSlice) RemoveIf(f func(byte) bool) {\n\tms.getState().AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*ms.getOrig()); i++ {\n\t\tif f((*ms.getOrig())[i]) {\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*ms.getOrig())[newLen] = (*ms.getOrig())[i]\n\t\tvar zero byte\n\t\t(*ms.getOrig())[i] = zero\n\t\tnewLen++\n\t}\n\t*ms.getOrig() = (*ms.getOrig())[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (ms ByteSlice) CopyTo(dest ByteSlice) {\n\tdest.getState().AssertMutable()\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = copyByteSlice(*dest.getOrig(), *ms.getOrig())\n}\n\n// Equal checks equality with another ByteSlice\nfunc (ms ByteSlice) Equal(val ByteSlice) bool {\n\treturn slices.Equal(*ms.getOrig(), *val.getOrig())\n}\n\nfunc copyByteSlice(dst, src []byte) []byte {\n\treturn append(dst[:0], src...)\n}\n"
  },
  {
    "path": "pdata/pcommon/generated_byteslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestNewByteSlice(t *testing.T) {\n\tms := NewByteSlice()\n\tassert.Equal(t, 0, ms.Len())\n\tms.FromRaw([]byte{1, 2, 3})\n\tassert.Equal(t, 3, ms.Len())\n\tassert.Equal(t, []byte{1, 2, 3}, ms.AsRaw())\n\tms.SetAt(1, byte(5))\n\tassert.Equal(t, []byte{1, 5, 3}, ms.AsRaw())\n\tms.FromRaw([]byte{3})\n\tassert.Equal(t, 1, ms.Len())\n\tassert.Equal(t, byte(3), ms.At(0))\n\n\tcp := NewByteSlice()\n\tms.CopyTo(cp)\n\tms.SetAt(0, byte(2))\n\tassert.Equal(t, byte(2), ms.At(0))\n\tassert.Equal(t, byte(3), cp.At(0))\n\tms.CopyTo(cp)\n\tassert.Equal(t, byte(2), cp.At(0))\n\n\tmv := NewByteSlice()\n\tms.MoveTo(mv)\n\tassert.Equal(t, 0, ms.Len())\n\tassert.Equal(t, 1, mv.Len())\n\tassert.Equal(t, byte(2), mv.At(0))\n\tms.FromRaw([]byte{1, 2, 3})\n\tms.MoveTo(mv)\n\tassert.Equal(t, 3, mv.Len())\n\tassert.Equal(t, byte(1), mv.At(0))\n\tmv.MoveTo(mv)\n\tassert.Equal(t, 3, mv.Len())\n\tassert.Equal(t, byte(1), mv.At(0))\n}\n\nfunc TestByteSliceReadOnly(t *testing.T) {\n\traw := []byte{1, 2, 3}\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tms := ByteSlice(internal.NewByteSliceWrapper(&raw, sharedState))\n\n\tassert.Equal(t, 3, ms.Len())\n\tassert.Equal(t, byte(1), ms.At(0))\n\tassert.Panics(t, func() { ms.Append(1) })\n\tassert.Panics(t, func() { ms.EnsureCapacity(2) })\n\tassert.Equal(t, raw, ms.AsRaw())\n\tassert.Panics(t, func() { ms.FromRaw(raw) })\n\n\tms2 := NewByteSlice()\n\tms.CopyTo(ms2)\n\tassert.Equal(t, ms.AsRaw(), ms2.AsRaw())\n\tassert.Panics(t, func() { ms2.CopyTo(ms) })\n\n\tassert.Panics(t, func() { ms.MoveTo(ms2) })\n\tassert.Panics(t, func() { ms2.MoveTo(ms) })\n}\n\nfunc TestByteSliceAppend(t *testing.T) {\n\tms := NewByteSlice()\n\tms.FromRaw([]byte{1, 2, 3})\n\tms.Append(5, 5)\n\tassert.Equal(t, 5, ms.Len())\n\tassert.Equal(t, byte(5), ms.At(4))\n}\n\nfunc TestByteSliceEnsureCapacity(t *testing.T) {\n\tms := NewByteSlice()\n\tms.EnsureCapacity(4)\n\tassert.Equal(t, 4, cap(*ms.getOrig()))\n\tms.EnsureCapacity(2)\n\tassert.Equal(t, 4, cap(*ms.getOrig()))\n}\n\nfunc TestByteSliceAll(t *testing.T) {\n\tms := NewByteSlice()\n\tms.FromRaw([]byte{1, 2, 3})\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestByteSliceMoveAndAppendTo(t *testing.T) {\n\t// Test moving from an empty slice\n\tms := NewByteSlice()\n\tms2 := NewByteSlice()\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, NewByteSlice(), ms2)\n\tassert.Equal(t, ms.Len(), 0)\n\n\t// Test moving to empty slice\n\tms.FromRaw([]byte{1, 2, 3})\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, ms2.Len(), 3)\n\n\t// Test moving to a non empty slice\n\tms.FromRaw([]byte{1, 2, 3})\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, ms2.Len(), 6)\n}\n\nfunc TestByteSliceRemoveIf(t *testing.T) {\n\temptySlice := NewByteSlice()\n\temptySlice.RemoveIf(func(el byte) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\tms := NewByteSlice()\n\tms.FromRaw([]byte{1, 2, 3})\n\tpos := 0\n\tms.RemoveIf(func(el byte) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, pos/2, ms.Len())\n}\n\nfunc TestByteSliceRemoveIfAll(t *testing.T) {\n\tms := NewByteSlice()\n\tms.FromRaw([]byte{1, 2, 3})\n\tms.RemoveIf(func(el byte) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, ms.Len())\n}\n\nfunc TestByteSliceEqual(t *testing.T) {\n\tms := NewByteSlice()\n\tms2 := NewByteSlice()\n\tassert.True(t, ms.Equal(ms2))\n\n\tms.Append(1, 2, 3)\n\tassert.False(t, ms.Equal(ms2))\n\n\tms2.Append(1, 2, 3)\n\tassert.True(t, ms.Equal(ms2))\n}\n\nfunc BenchmarkByteSliceEqual(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\tms := NewByteSlice()\n\tms.Append(1, 2, 3)\n\tcmp := NewByteSlice()\n\tcmp.Append(1, 2, 3)\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\n\tfor n := 0; n < b.N; n++ {\n\t\t_ = ms.Equal(cmp)\n\t}\n}\n"
  },
  {
    "path": "pdata/pcommon/generated_float64slice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"iter\"\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// Float64Slice represents a []float64 slice.\n// The instance of Float64Slice can be assigned to multiple objects since it's immutable.\n//\n// Must use NewFloat64Slice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Float64Slice internal.Float64SliceWrapper\n\nfunc (ms Float64Slice) getOrig() *[]float64 {\n\treturn internal.GetFloat64SliceOrig(internal.Float64SliceWrapper(ms))\n}\n\nfunc (ms Float64Slice) getState() *internal.State {\n\treturn internal.GetFloat64SliceState(internal.Float64SliceWrapper(ms))\n}\n\n// NewFloat64Slice creates a new empty Float64Slice.\nfunc NewFloat64Slice() Float64Slice {\n\torig := []float64(nil)\n\treturn Float64Slice(internal.NewFloat64SliceWrapper(&orig, internal.NewState()))\n}\n\n// AsRaw returns a copy of the []float64 slice.\nfunc (ms Float64Slice) AsRaw() []float64 {\n\treturn copyFloat64Slice(nil, *ms.getOrig())\n}\n\n// FromRaw copies raw []float64 into the slice Float64Slice.\nfunc (ms Float64Slice) FromRaw(val []float64) {\n\tms.getState().AssertMutable()\n\t*ms.getOrig() = copyFloat64Slice(*ms.getOrig(), val)\n}\n\n// Len returns length of the []float64 slice value.\n// Equivalent of len(float64Slice).\nfunc (ms Float64Slice) Len() int {\n\treturn len(*ms.getOrig())\n}\n\n// At returns an item from particular index.\n// Equivalent of float64Slice[i].\nfunc (ms Float64Slice) At(i int) float64 {\n\treturn (*ms.getOrig())[i]\n}\n\n// All returns an iterator over index-value pairs in the slice.\nfunc (ms Float64Slice) All() iter.Seq2[int, float64] {\n\treturn func(yield func(int, float64) bool) {\n\t\tfor i := 0; i < ms.Len(); i++ {\n\t\t\tif !yield(i, ms.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// SetAt sets float64 item at particular index.\n// Equivalent of float64Slice[i] = val\nfunc (ms Float64Slice) SetAt(i int, val float64) {\n\tms.getState().AssertMutable()\n\t(*ms.getOrig())[i] = val\n}\n\n// EnsureCapacity ensures Float64Slice has at least the specified capacity.\n//  1. If the newCap <= cap, then is no change in capacity.\n//  2. If the newCap > cap, then the slice capacity will be expanded to the provided value which will be equivalent of:\n//     buf := make([]float64, len(float64Slice), newCap)\n//     copy(buf, float64Slice)\n//     float64Slice = buf\nfunc (ms Float64Slice) EnsureCapacity(newCap int) {\n\tms.getState().AssertMutable()\n\toldCap := cap(*ms.getOrig())\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]float64, len(*ms.getOrig()), newCap)\n\tcopy(newOrig, *ms.getOrig())\n\t*ms.getOrig() = newOrig\n}\n\n// Append appends extra elements to Float64Slice.\n// Equivalent of float64Slice = append(float64Slice, elms...)\nfunc (ms Float64Slice) Append(elms ...float64) {\n\tms.getState().AssertMutable()\n\t*ms.getOrig() = append(*ms.getOrig(), elms...)\n}\n\n// MoveTo moves all elements from the current slice overriding the destination and\n// resetting the current instance to its zero value.\nfunc (ms Float64Slice) MoveTo(dest Float64Slice) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = *ms.getOrig()\n\t*ms.getOrig() = nil\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (ms Float64Slice) MoveAndAppendTo(dest Float64Slice) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\tif *dest.getOrig() == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.getOrig() = *ms.getOrig()\n\t} else {\n\t\t*dest.getOrig() = append(*dest.getOrig(), *ms.getOrig()...)\n\t}\n\t*ms.getOrig() = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (ms Float64Slice) RemoveIf(f func(float64) bool) {\n\tms.getState().AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*ms.getOrig()); i++ {\n\t\tif f((*ms.getOrig())[i]) {\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*ms.getOrig())[newLen] = (*ms.getOrig())[i]\n\t\tvar zero float64\n\t\t(*ms.getOrig())[i] = zero\n\t\tnewLen++\n\t}\n\t*ms.getOrig() = (*ms.getOrig())[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (ms Float64Slice) CopyTo(dest Float64Slice) {\n\tdest.getState().AssertMutable()\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = copyFloat64Slice(*dest.getOrig(), *ms.getOrig())\n}\n\n// Equal checks equality with another Float64Slice\nfunc (ms Float64Slice) Equal(val Float64Slice) bool {\n\treturn slices.Equal(*ms.getOrig(), *val.getOrig())\n}\n\nfunc copyFloat64Slice(dst, src []float64) []float64 {\n\treturn append(dst[:0], src...)\n}\n"
  },
  {
    "path": "pdata/pcommon/generated_float64slice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestNewFloat64Slice(t *testing.T) {\n\tms := NewFloat64Slice()\n\tassert.Equal(t, 0, ms.Len())\n\tms.FromRaw([]float64{1.1, 2.2, 3.3})\n\tassert.Equal(t, 3, ms.Len())\n\tassert.Equal(t, []float64{1.1, 2.2, 3.3}, ms.AsRaw())\n\tms.SetAt(1, float64(5.5))\n\tassert.Equal(t, []float64{1.1, 5.5, 3.3}, ms.AsRaw())\n\tms.FromRaw([]float64{3.3})\n\tassert.Equal(t, 1, ms.Len())\n\tassert.InDelta(t, float64(3.3), ms.At(0), 0.01)\n\n\tcp := NewFloat64Slice()\n\tms.CopyTo(cp)\n\tms.SetAt(0, float64(2.2))\n\tassert.InDelta(t, float64(2.2), ms.At(0), 0.01)\n\tassert.InDelta(t, float64(3.3), cp.At(0), 0.01)\n\tms.CopyTo(cp)\n\tassert.InDelta(t, float64(2.2), cp.At(0), 0.01)\n\n\tmv := NewFloat64Slice()\n\tms.MoveTo(mv)\n\tassert.Equal(t, 0, ms.Len())\n\tassert.Equal(t, 1, mv.Len())\n\tassert.InDelta(t, float64(2.2), mv.At(0), 0.01)\n\tms.FromRaw([]float64{1.1, 2.2, 3.3})\n\tms.MoveTo(mv)\n\tassert.Equal(t, 3, mv.Len())\n\tassert.InDelta(t, float64(1.1), mv.At(0), 0.01)\n\tmv.MoveTo(mv)\n\tassert.Equal(t, 3, mv.Len())\n\tassert.InDelta(t, float64(1.1), mv.At(0), 0.01)\n}\n\nfunc TestFloat64SliceReadOnly(t *testing.T) {\n\traw := []float64{1.1, 2.2, 3.3}\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tms := Float64Slice(internal.NewFloat64SliceWrapper(&raw, sharedState))\n\n\tassert.Equal(t, 3, ms.Len())\n\tassert.InDelta(t, float64(1.1), ms.At(0), 0.01)\n\tassert.Panics(t, func() { ms.Append(1.1) })\n\tassert.Panics(t, func() { ms.EnsureCapacity(2) })\n\tassert.Equal(t, raw, ms.AsRaw())\n\tassert.Panics(t, func() { ms.FromRaw(raw) })\n\n\tms2 := NewFloat64Slice()\n\tms.CopyTo(ms2)\n\tassert.Equal(t, ms.AsRaw(), ms2.AsRaw())\n\tassert.Panics(t, func() { ms2.CopyTo(ms) })\n\n\tassert.Panics(t, func() { ms.MoveTo(ms2) })\n\tassert.Panics(t, func() { ms2.MoveTo(ms) })\n}\n\nfunc TestFloat64SliceAppend(t *testing.T) {\n\tms := NewFloat64Slice()\n\tms.FromRaw([]float64{1.1, 2.2, 3.3})\n\tms.Append(5.5, 5.5)\n\tassert.Equal(t, 5, ms.Len())\n\tassert.InDelta(t, float64(5.5), ms.At(4), 0.01)\n}\n\nfunc TestFloat64SliceEnsureCapacity(t *testing.T) {\n\tms := NewFloat64Slice()\n\tms.EnsureCapacity(4)\n\tassert.Equal(t, 4, cap(*ms.getOrig()))\n\tms.EnsureCapacity(2)\n\tassert.Equal(t, 4, cap(*ms.getOrig()))\n}\n\nfunc TestFloat64SliceAll(t *testing.T) {\n\tms := NewFloat64Slice()\n\tms.FromRaw([]float64{1.1, 2.2, 3.3})\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestFloat64SliceMoveAndAppendTo(t *testing.T) {\n\t// Test moving from an empty slice\n\tms := NewFloat64Slice()\n\tms2 := NewFloat64Slice()\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, NewFloat64Slice(), ms2)\n\tassert.Equal(t, ms.Len(), 0)\n\n\t// Test moving to empty slice\n\tms.FromRaw([]float64{1.1, 2.2, 3.3})\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, ms2.Len(), 3)\n\n\t// Test moving to a non empty slice\n\tms.FromRaw([]float64{1.1, 2.2, 3.3})\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, ms2.Len(), 6)\n}\n\nfunc TestFloat64SliceRemoveIf(t *testing.T) {\n\temptySlice := NewFloat64Slice()\n\temptySlice.RemoveIf(func(el float64) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\tms := NewFloat64Slice()\n\tms.FromRaw([]float64{1.1, 2.2, 3.3})\n\tpos := 0\n\tms.RemoveIf(func(el float64) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, pos/2, ms.Len())\n}\n\nfunc TestFloat64SliceRemoveIfAll(t *testing.T) {\n\tms := NewFloat64Slice()\n\tms.FromRaw([]float64{1.1, 2.2, 3.3})\n\tms.RemoveIf(func(el float64) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, ms.Len())\n}\n\nfunc TestFloat64SliceEqual(t *testing.T) {\n\tms := NewFloat64Slice()\n\tms2 := NewFloat64Slice()\n\tassert.True(t, ms.Equal(ms2))\n\n\tms.Append(1.1, 2.2, 3.3)\n\tassert.False(t, ms.Equal(ms2))\n\n\tms2.Append(1.1, 2.2, 3.3)\n\tassert.True(t, ms.Equal(ms2))\n}\n\nfunc BenchmarkFloat64SliceEqual(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\tms := NewFloat64Slice()\n\tms.Append(1.1, 2.2, 3.3)\n\tcmp := NewFloat64Slice()\n\tcmp.Append(1.1, 2.2, 3.3)\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\n\tfor n := 0; n < b.N; n++ {\n\t\t_ = ms.Equal(cmp)\n\t}\n}\n"
  },
  {
    "path": "pdata/pcommon/generated_instrumentationscope.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// InstrumentationScope is a message representing the instrumentation scope information.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewInstrumentationScope function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype InstrumentationScope internal.InstrumentationScopeWrapper\n\nfunc newInstrumentationScope(orig *internal.InstrumentationScope, state *internal.State) InstrumentationScope {\n\treturn InstrumentationScope(internal.NewInstrumentationScopeWrapper(orig, state))\n}\n\n// NewInstrumentationScope creates a new empty InstrumentationScope.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewInstrumentationScope() InstrumentationScope {\n\treturn newInstrumentationScope(internal.NewInstrumentationScope(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms InstrumentationScope) MoveTo(dest InstrumentationScope) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\tinternal.DeleteInstrumentationScope(dest.getOrig(), false)\n\t*dest.getOrig(), *ms.getOrig() = *ms.getOrig(), *dest.getOrig()\n}\n\n// Name returns the name associated with this InstrumentationScope.\nfunc (ms InstrumentationScope) Name() string {\n\treturn ms.getOrig().Name\n}\n\n// SetName replaces the name associated with this InstrumentationScope.\nfunc (ms InstrumentationScope) SetName(v string) {\n\tms.getState().AssertMutable()\n\tms.getOrig().Name = v\n}\n\n// Version returns the version associated with this InstrumentationScope.\nfunc (ms InstrumentationScope) Version() string {\n\treturn ms.getOrig().Version\n}\n\n// SetVersion replaces the version associated with this InstrumentationScope.\nfunc (ms InstrumentationScope) SetVersion(v string) {\n\tms.getState().AssertMutable()\n\tms.getOrig().Version = v\n}\n\n// Attributes returns the Attributes associated with this InstrumentationScope.\nfunc (ms InstrumentationScope) Attributes() Map {\n\treturn Map(internal.NewMapWrapper(&ms.getOrig().Attributes, ms.getState()))\n}\n\n// DroppedAttributesCount returns the droppedattributescount associated with this InstrumentationScope.\nfunc (ms InstrumentationScope) DroppedAttributesCount() uint32 {\n\treturn ms.getOrig().DroppedAttributesCount\n}\n\n// SetDroppedAttributesCount replaces the droppedattributescount associated with this InstrumentationScope.\nfunc (ms InstrumentationScope) SetDroppedAttributesCount(v uint32) {\n\tms.getState().AssertMutable()\n\tms.getOrig().DroppedAttributesCount = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms InstrumentationScope) CopyTo(dest InstrumentationScope) {\n\tdest.getState().AssertMutable()\n\tinternal.CopyInstrumentationScope(dest.getOrig(), ms.getOrig())\n}\n\nfunc (ms InstrumentationScope) getOrig() *internal.InstrumentationScope {\n\treturn internal.GetInstrumentationScopeOrig(internal.InstrumentationScopeWrapper(ms))\n}\n\nfunc (ms InstrumentationScope) getState() *internal.State {\n\treturn internal.GetInstrumentationScopeState(internal.InstrumentationScopeWrapper(ms))\n}\n"
  },
  {
    "path": "pdata/pcommon/generated_instrumentationscope_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestInstrumentationScope_MoveTo(t *testing.T) {\n\tms := generateTestInstrumentationScope()\n\tdest := NewInstrumentationScope()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewInstrumentationScope(), ms)\n\tassert.Equal(t, generateTestInstrumentationScope(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestInstrumentationScope(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newInstrumentationScope(internal.NewInstrumentationScope(), sharedState)) })\n\tassert.Panics(t, func() { newInstrumentationScope(internal.NewInstrumentationScope(), sharedState).MoveTo(dest) })\n}\n\nfunc TestInstrumentationScope_CopyTo(t *testing.T) {\n\tms := NewInstrumentationScope()\n\torig := NewInstrumentationScope()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestInstrumentationScope()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newInstrumentationScope(internal.NewInstrumentationScope(), sharedState)) })\n}\n\nfunc TestInstrumentationScope_Name(t *testing.T) {\n\tms := NewInstrumentationScope()\n\tassert.Empty(t, ms.Name())\n\tms.SetName(\"test_name\")\n\tassert.Equal(t, \"test_name\", ms.Name())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newInstrumentationScope(internal.NewInstrumentationScope(), sharedState).SetName(\"test_name\") })\n}\n\nfunc TestInstrumentationScope_Version(t *testing.T) {\n\tms := NewInstrumentationScope()\n\tassert.Empty(t, ms.Version())\n\tms.SetVersion(\"test_version\")\n\tassert.Equal(t, \"test_version\", ms.Version())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewInstrumentationScope(internal.NewInstrumentationScope(), sharedState).SetVersion(\"test_version\")\n\t})\n}\n\nfunc TestInstrumentationScope_Attributes(t *testing.T) {\n\tms := NewInstrumentationScope()\n\tassert.Equal(t, NewMap(), ms.Attributes())\n\tms.getOrig().Attributes = internal.GenTestKeyValueSlice()\n\tassert.Equal(t, Map(internal.GenTestMapWrapper()), ms.Attributes())\n}\n\nfunc TestInstrumentationScope_DroppedAttributesCount(t *testing.T) {\n\tms := NewInstrumentationScope()\n\tassert.Equal(t, uint32(0), ms.DroppedAttributesCount())\n\tms.SetDroppedAttributesCount(uint32(13))\n\tassert.Equal(t, uint32(13), ms.DroppedAttributesCount())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewInstrumentationScope(internal.NewInstrumentationScope(), sharedState).SetDroppedAttributesCount(uint32(13))\n\t})\n}\n\nfunc generateTestInstrumentationScope() InstrumentationScope {\n\treturn newInstrumentationScope(internal.GenTestInstrumentationScope(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pcommon/generated_int32slice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"iter\"\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// Int32Slice represents a []int32 slice.\n// The instance of Int32Slice can be assigned to multiple objects since it's immutable.\n//\n// Must use NewInt32Slice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Int32Slice internal.Int32SliceWrapper\n\nfunc (ms Int32Slice) getOrig() *[]int32 {\n\treturn internal.GetInt32SliceOrig(internal.Int32SliceWrapper(ms))\n}\n\nfunc (ms Int32Slice) getState() *internal.State {\n\treturn internal.GetInt32SliceState(internal.Int32SliceWrapper(ms))\n}\n\n// NewInt32Slice creates a new empty Int32Slice.\nfunc NewInt32Slice() Int32Slice {\n\torig := []int32(nil)\n\treturn Int32Slice(internal.NewInt32SliceWrapper(&orig, internal.NewState()))\n}\n\n// AsRaw returns a copy of the []int32 slice.\nfunc (ms Int32Slice) AsRaw() []int32 {\n\treturn copyInt32Slice(nil, *ms.getOrig())\n}\n\n// FromRaw copies raw []int32 into the slice Int32Slice.\nfunc (ms Int32Slice) FromRaw(val []int32) {\n\tms.getState().AssertMutable()\n\t*ms.getOrig() = copyInt32Slice(*ms.getOrig(), val)\n}\n\n// Len returns length of the []int32 slice value.\n// Equivalent of len(int32Slice).\nfunc (ms Int32Slice) Len() int {\n\treturn len(*ms.getOrig())\n}\n\n// At returns an item from particular index.\n// Equivalent of int32Slice[i].\nfunc (ms Int32Slice) At(i int) int32 {\n\treturn (*ms.getOrig())[i]\n}\n\n// All returns an iterator over index-value pairs in the slice.\nfunc (ms Int32Slice) All() iter.Seq2[int, int32] {\n\treturn func(yield func(int, int32) bool) {\n\t\tfor i := 0; i < ms.Len(); i++ {\n\t\t\tif !yield(i, ms.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// SetAt sets int32 item at particular index.\n// Equivalent of int32Slice[i] = val\nfunc (ms Int32Slice) SetAt(i int, val int32) {\n\tms.getState().AssertMutable()\n\t(*ms.getOrig())[i] = val\n}\n\n// EnsureCapacity ensures Int32Slice has at least the specified capacity.\n//  1. If the newCap <= cap, then is no change in capacity.\n//  2. If the newCap > cap, then the slice capacity will be expanded to the provided value which will be equivalent of:\n//     buf := make([]int32, len(int32Slice), newCap)\n//     copy(buf, int32Slice)\n//     int32Slice = buf\nfunc (ms Int32Slice) EnsureCapacity(newCap int) {\n\tms.getState().AssertMutable()\n\toldCap := cap(*ms.getOrig())\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]int32, len(*ms.getOrig()), newCap)\n\tcopy(newOrig, *ms.getOrig())\n\t*ms.getOrig() = newOrig\n}\n\n// Append appends extra elements to Int32Slice.\n// Equivalent of int32Slice = append(int32Slice, elms...)\nfunc (ms Int32Slice) Append(elms ...int32) {\n\tms.getState().AssertMutable()\n\t*ms.getOrig() = append(*ms.getOrig(), elms...)\n}\n\n// MoveTo moves all elements from the current slice overriding the destination and\n// resetting the current instance to its zero value.\nfunc (ms Int32Slice) MoveTo(dest Int32Slice) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = *ms.getOrig()\n\t*ms.getOrig() = nil\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (ms Int32Slice) MoveAndAppendTo(dest Int32Slice) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\tif *dest.getOrig() == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.getOrig() = *ms.getOrig()\n\t} else {\n\t\t*dest.getOrig() = append(*dest.getOrig(), *ms.getOrig()...)\n\t}\n\t*ms.getOrig() = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (ms Int32Slice) RemoveIf(f func(int32) bool) {\n\tms.getState().AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*ms.getOrig()); i++ {\n\t\tif f((*ms.getOrig())[i]) {\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*ms.getOrig())[newLen] = (*ms.getOrig())[i]\n\t\tvar zero int32\n\t\t(*ms.getOrig())[i] = zero\n\t\tnewLen++\n\t}\n\t*ms.getOrig() = (*ms.getOrig())[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (ms Int32Slice) CopyTo(dest Int32Slice) {\n\tdest.getState().AssertMutable()\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = copyInt32Slice(*dest.getOrig(), *ms.getOrig())\n}\n\n// Equal checks equality with another Int32Slice\nfunc (ms Int32Slice) Equal(val Int32Slice) bool {\n\treturn slices.Equal(*ms.getOrig(), *val.getOrig())\n}\n\nfunc copyInt32Slice(dst, src []int32) []int32 {\n\treturn append(dst[:0], src...)\n}\n"
  },
  {
    "path": "pdata/pcommon/generated_int32slice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestNewInt32Slice(t *testing.T) {\n\tms := NewInt32Slice()\n\tassert.Equal(t, 0, ms.Len())\n\tms.FromRaw([]int32{1, 2, 3})\n\tassert.Equal(t, 3, ms.Len())\n\tassert.Equal(t, []int32{1, 2, 3}, ms.AsRaw())\n\tms.SetAt(1, int32(5))\n\tassert.Equal(t, []int32{1, 5, 3}, ms.AsRaw())\n\tms.FromRaw([]int32{3})\n\tassert.Equal(t, 1, ms.Len())\n\tassert.Equal(t, int32(3), ms.At(0))\n\n\tcp := NewInt32Slice()\n\tms.CopyTo(cp)\n\tms.SetAt(0, int32(2))\n\tassert.Equal(t, int32(2), ms.At(0))\n\tassert.Equal(t, int32(3), cp.At(0))\n\tms.CopyTo(cp)\n\tassert.Equal(t, int32(2), cp.At(0))\n\n\tmv := NewInt32Slice()\n\tms.MoveTo(mv)\n\tassert.Equal(t, 0, ms.Len())\n\tassert.Equal(t, 1, mv.Len())\n\tassert.Equal(t, int32(2), mv.At(0))\n\tms.FromRaw([]int32{1, 2, 3})\n\tms.MoveTo(mv)\n\tassert.Equal(t, 3, mv.Len())\n\tassert.Equal(t, int32(1), mv.At(0))\n\tmv.MoveTo(mv)\n\tassert.Equal(t, 3, mv.Len())\n\tassert.Equal(t, int32(1), mv.At(0))\n}\n\nfunc TestInt32SliceReadOnly(t *testing.T) {\n\traw := []int32{1, 2, 3}\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tms := Int32Slice(internal.NewInt32SliceWrapper(&raw, sharedState))\n\n\tassert.Equal(t, 3, ms.Len())\n\tassert.Equal(t, int32(1), ms.At(0))\n\tassert.Panics(t, func() { ms.Append(1) })\n\tassert.Panics(t, func() { ms.EnsureCapacity(2) })\n\tassert.Equal(t, raw, ms.AsRaw())\n\tassert.Panics(t, func() { ms.FromRaw(raw) })\n\n\tms2 := NewInt32Slice()\n\tms.CopyTo(ms2)\n\tassert.Equal(t, ms.AsRaw(), ms2.AsRaw())\n\tassert.Panics(t, func() { ms2.CopyTo(ms) })\n\n\tassert.Panics(t, func() { ms.MoveTo(ms2) })\n\tassert.Panics(t, func() { ms2.MoveTo(ms) })\n}\n\nfunc TestInt32SliceAppend(t *testing.T) {\n\tms := NewInt32Slice()\n\tms.FromRaw([]int32{1, 2, 3})\n\tms.Append(5, 5)\n\tassert.Equal(t, 5, ms.Len())\n\tassert.Equal(t, int32(5), ms.At(4))\n}\n\nfunc TestInt32SliceEnsureCapacity(t *testing.T) {\n\tms := NewInt32Slice()\n\tms.EnsureCapacity(4)\n\tassert.Equal(t, 4, cap(*ms.getOrig()))\n\tms.EnsureCapacity(2)\n\tassert.Equal(t, 4, cap(*ms.getOrig()))\n}\n\nfunc TestInt32SliceAll(t *testing.T) {\n\tms := NewInt32Slice()\n\tms.FromRaw([]int32{1, 2, 3})\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestInt32SliceMoveAndAppendTo(t *testing.T) {\n\t// Test moving from an empty slice\n\tms := NewInt32Slice()\n\tms2 := NewInt32Slice()\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, NewInt32Slice(), ms2)\n\tassert.Equal(t, ms.Len(), 0)\n\n\t// Test moving to empty slice\n\tms.FromRaw([]int32{1, 2, 3})\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, ms2.Len(), 3)\n\n\t// Test moving to a non empty slice\n\tms.FromRaw([]int32{1, 2, 3})\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, ms2.Len(), 6)\n}\n\nfunc TestInt32SliceRemoveIf(t *testing.T) {\n\temptySlice := NewInt32Slice()\n\temptySlice.RemoveIf(func(el int32) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\tms := NewInt32Slice()\n\tms.FromRaw([]int32{1, 2, 3})\n\tpos := 0\n\tms.RemoveIf(func(el int32) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, pos/2, ms.Len())\n}\n\nfunc TestInt32SliceRemoveIfAll(t *testing.T) {\n\tms := NewInt32Slice()\n\tms.FromRaw([]int32{1, 2, 3})\n\tms.RemoveIf(func(el int32) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, ms.Len())\n}\n\nfunc TestInt32SliceEqual(t *testing.T) {\n\tms := NewInt32Slice()\n\tms2 := NewInt32Slice()\n\tassert.True(t, ms.Equal(ms2))\n\n\tms.Append(1, 2, 3)\n\tassert.False(t, ms.Equal(ms2))\n\n\tms2.Append(1, 2, 3)\n\tassert.True(t, ms.Equal(ms2))\n}\n\nfunc BenchmarkInt32SliceEqual(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\tms := NewInt32Slice()\n\tms.Append(1, 2, 3)\n\tcmp := NewInt32Slice()\n\tcmp.Append(1, 2, 3)\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\n\tfor n := 0; n < b.N; n++ {\n\t\t_ = ms.Equal(cmp)\n\t}\n}\n"
  },
  {
    "path": "pdata/pcommon/generated_int64slice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"iter\"\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// Int64Slice represents a []int64 slice.\n// The instance of Int64Slice can be assigned to multiple objects since it's immutable.\n//\n// Must use NewInt64Slice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Int64Slice internal.Int64SliceWrapper\n\nfunc (ms Int64Slice) getOrig() *[]int64 {\n\treturn internal.GetInt64SliceOrig(internal.Int64SliceWrapper(ms))\n}\n\nfunc (ms Int64Slice) getState() *internal.State {\n\treturn internal.GetInt64SliceState(internal.Int64SliceWrapper(ms))\n}\n\n// NewInt64Slice creates a new empty Int64Slice.\nfunc NewInt64Slice() Int64Slice {\n\torig := []int64(nil)\n\treturn Int64Slice(internal.NewInt64SliceWrapper(&orig, internal.NewState()))\n}\n\n// AsRaw returns a copy of the []int64 slice.\nfunc (ms Int64Slice) AsRaw() []int64 {\n\treturn copyInt64Slice(nil, *ms.getOrig())\n}\n\n// FromRaw copies raw []int64 into the slice Int64Slice.\nfunc (ms Int64Slice) FromRaw(val []int64) {\n\tms.getState().AssertMutable()\n\t*ms.getOrig() = copyInt64Slice(*ms.getOrig(), val)\n}\n\n// Len returns length of the []int64 slice value.\n// Equivalent of len(int64Slice).\nfunc (ms Int64Slice) Len() int {\n\treturn len(*ms.getOrig())\n}\n\n// At returns an item from particular index.\n// Equivalent of int64Slice[i].\nfunc (ms Int64Slice) At(i int) int64 {\n\treturn (*ms.getOrig())[i]\n}\n\n// All returns an iterator over index-value pairs in the slice.\nfunc (ms Int64Slice) All() iter.Seq2[int, int64] {\n\treturn func(yield func(int, int64) bool) {\n\t\tfor i := 0; i < ms.Len(); i++ {\n\t\t\tif !yield(i, ms.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// SetAt sets int64 item at particular index.\n// Equivalent of int64Slice[i] = val\nfunc (ms Int64Slice) SetAt(i int, val int64) {\n\tms.getState().AssertMutable()\n\t(*ms.getOrig())[i] = val\n}\n\n// EnsureCapacity ensures Int64Slice has at least the specified capacity.\n//  1. If the newCap <= cap, then is no change in capacity.\n//  2. If the newCap > cap, then the slice capacity will be expanded to the provided value which will be equivalent of:\n//     buf := make([]int64, len(int64Slice), newCap)\n//     copy(buf, int64Slice)\n//     int64Slice = buf\nfunc (ms Int64Slice) EnsureCapacity(newCap int) {\n\tms.getState().AssertMutable()\n\toldCap := cap(*ms.getOrig())\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]int64, len(*ms.getOrig()), newCap)\n\tcopy(newOrig, *ms.getOrig())\n\t*ms.getOrig() = newOrig\n}\n\n// Append appends extra elements to Int64Slice.\n// Equivalent of int64Slice = append(int64Slice, elms...)\nfunc (ms Int64Slice) Append(elms ...int64) {\n\tms.getState().AssertMutable()\n\t*ms.getOrig() = append(*ms.getOrig(), elms...)\n}\n\n// MoveTo moves all elements from the current slice overriding the destination and\n// resetting the current instance to its zero value.\nfunc (ms Int64Slice) MoveTo(dest Int64Slice) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = *ms.getOrig()\n\t*ms.getOrig() = nil\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (ms Int64Slice) MoveAndAppendTo(dest Int64Slice) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\tif *dest.getOrig() == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.getOrig() = *ms.getOrig()\n\t} else {\n\t\t*dest.getOrig() = append(*dest.getOrig(), *ms.getOrig()...)\n\t}\n\t*ms.getOrig() = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (ms Int64Slice) RemoveIf(f func(int64) bool) {\n\tms.getState().AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*ms.getOrig()); i++ {\n\t\tif f((*ms.getOrig())[i]) {\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*ms.getOrig())[newLen] = (*ms.getOrig())[i]\n\t\tvar zero int64\n\t\t(*ms.getOrig())[i] = zero\n\t\tnewLen++\n\t}\n\t*ms.getOrig() = (*ms.getOrig())[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (ms Int64Slice) CopyTo(dest Int64Slice) {\n\tdest.getState().AssertMutable()\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = copyInt64Slice(*dest.getOrig(), *ms.getOrig())\n}\n\n// Equal checks equality with another Int64Slice\nfunc (ms Int64Slice) Equal(val Int64Slice) bool {\n\treturn slices.Equal(*ms.getOrig(), *val.getOrig())\n}\n\nfunc copyInt64Slice(dst, src []int64) []int64 {\n\treturn append(dst[:0], src...)\n}\n"
  },
  {
    "path": "pdata/pcommon/generated_int64slice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestNewInt64Slice(t *testing.T) {\n\tms := NewInt64Slice()\n\tassert.Equal(t, 0, ms.Len())\n\tms.FromRaw([]int64{1, 2, 3})\n\tassert.Equal(t, 3, ms.Len())\n\tassert.Equal(t, []int64{1, 2, 3}, ms.AsRaw())\n\tms.SetAt(1, int64(5))\n\tassert.Equal(t, []int64{1, 5, 3}, ms.AsRaw())\n\tms.FromRaw([]int64{3})\n\tassert.Equal(t, 1, ms.Len())\n\tassert.Equal(t, int64(3), ms.At(0))\n\n\tcp := NewInt64Slice()\n\tms.CopyTo(cp)\n\tms.SetAt(0, int64(2))\n\tassert.Equal(t, int64(2), ms.At(0))\n\tassert.Equal(t, int64(3), cp.At(0))\n\tms.CopyTo(cp)\n\tassert.Equal(t, int64(2), cp.At(0))\n\n\tmv := NewInt64Slice()\n\tms.MoveTo(mv)\n\tassert.Equal(t, 0, ms.Len())\n\tassert.Equal(t, 1, mv.Len())\n\tassert.Equal(t, int64(2), mv.At(0))\n\tms.FromRaw([]int64{1, 2, 3})\n\tms.MoveTo(mv)\n\tassert.Equal(t, 3, mv.Len())\n\tassert.Equal(t, int64(1), mv.At(0))\n\tmv.MoveTo(mv)\n\tassert.Equal(t, 3, mv.Len())\n\tassert.Equal(t, int64(1), mv.At(0))\n}\n\nfunc TestInt64SliceReadOnly(t *testing.T) {\n\traw := []int64{1, 2, 3}\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tms := Int64Slice(internal.NewInt64SliceWrapper(&raw, sharedState))\n\n\tassert.Equal(t, 3, ms.Len())\n\tassert.Equal(t, int64(1), ms.At(0))\n\tassert.Panics(t, func() { ms.Append(1) })\n\tassert.Panics(t, func() { ms.EnsureCapacity(2) })\n\tassert.Equal(t, raw, ms.AsRaw())\n\tassert.Panics(t, func() { ms.FromRaw(raw) })\n\n\tms2 := NewInt64Slice()\n\tms.CopyTo(ms2)\n\tassert.Equal(t, ms.AsRaw(), ms2.AsRaw())\n\tassert.Panics(t, func() { ms2.CopyTo(ms) })\n\n\tassert.Panics(t, func() { ms.MoveTo(ms2) })\n\tassert.Panics(t, func() { ms2.MoveTo(ms) })\n}\n\nfunc TestInt64SliceAppend(t *testing.T) {\n\tms := NewInt64Slice()\n\tms.FromRaw([]int64{1, 2, 3})\n\tms.Append(5, 5)\n\tassert.Equal(t, 5, ms.Len())\n\tassert.Equal(t, int64(5), ms.At(4))\n}\n\nfunc TestInt64SliceEnsureCapacity(t *testing.T) {\n\tms := NewInt64Slice()\n\tms.EnsureCapacity(4)\n\tassert.Equal(t, 4, cap(*ms.getOrig()))\n\tms.EnsureCapacity(2)\n\tassert.Equal(t, 4, cap(*ms.getOrig()))\n}\n\nfunc TestInt64SliceAll(t *testing.T) {\n\tms := NewInt64Slice()\n\tms.FromRaw([]int64{1, 2, 3})\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestInt64SliceMoveAndAppendTo(t *testing.T) {\n\t// Test moving from an empty slice\n\tms := NewInt64Slice()\n\tms2 := NewInt64Slice()\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, NewInt64Slice(), ms2)\n\tassert.Equal(t, ms.Len(), 0)\n\n\t// Test moving to empty slice\n\tms.FromRaw([]int64{1, 2, 3})\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, ms2.Len(), 3)\n\n\t// Test moving to a non empty slice\n\tms.FromRaw([]int64{1, 2, 3})\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, ms2.Len(), 6)\n}\n\nfunc TestInt64SliceRemoveIf(t *testing.T) {\n\temptySlice := NewInt64Slice()\n\temptySlice.RemoveIf(func(el int64) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\tms := NewInt64Slice()\n\tms.FromRaw([]int64{1, 2, 3})\n\tpos := 0\n\tms.RemoveIf(func(el int64) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, pos/2, ms.Len())\n}\n\nfunc TestInt64SliceRemoveIfAll(t *testing.T) {\n\tms := NewInt64Slice()\n\tms.FromRaw([]int64{1, 2, 3})\n\tms.RemoveIf(func(el int64) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, ms.Len())\n}\n\nfunc TestInt64SliceEqual(t *testing.T) {\n\tms := NewInt64Slice()\n\tms2 := NewInt64Slice()\n\tassert.True(t, ms.Equal(ms2))\n\n\tms.Append(1, 2, 3)\n\tassert.False(t, ms.Equal(ms2))\n\n\tms2.Append(1, 2, 3)\n\tassert.True(t, ms.Equal(ms2))\n}\n\nfunc BenchmarkInt64SliceEqual(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\tms := NewInt64Slice()\n\tms.Append(1, 2, 3)\n\tcmp := NewInt64Slice()\n\tcmp.Append(1, 2, 3)\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\n\tfor n := 0; n < b.N; n++ {\n\t\t_ = ms.Equal(cmp)\n\t}\n}\n"
  },
  {
    "path": "pdata/pcommon/generated_resource.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// Resource is a message representing the resource information.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewResource function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Resource internal.ResourceWrapper\n\nfunc newResource(orig *internal.Resource, state *internal.State) Resource {\n\treturn Resource(internal.NewResourceWrapper(orig, state))\n}\n\n// NewResource creates a new empty Resource.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewResource() Resource {\n\treturn newResource(internal.NewResource(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Resource) MoveTo(dest Resource) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\tinternal.DeleteResource(dest.getOrig(), false)\n\t*dest.getOrig(), *ms.getOrig() = *ms.getOrig(), *dest.getOrig()\n}\n\n// Attributes returns the Attributes associated with this Resource.\nfunc (ms Resource) Attributes() Map {\n\treturn Map(internal.NewMapWrapper(&ms.getOrig().Attributes, ms.getState()))\n}\n\n// DroppedAttributesCount returns the droppedattributescount associated with this Resource.\nfunc (ms Resource) DroppedAttributesCount() uint32 {\n\treturn ms.getOrig().DroppedAttributesCount\n}\n\n// SetDroppedAttributesCount replaces the droppedattributescount associated with this Resource.\nfunc (ms Resource) SetDroppedAttributesCount(v uint32) {\n\tms.getState().AssertMutable()\n\tms.getOrig().DroppedAttributesCount = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Resource) CopyTo(dest Resource) {\n\tdest.getState().AssertMutable()\n\tinternal.CopyResource(dest.getOrig(), ms.getOrig())\n}\n\nfunc (ms Resource) getOrig() *internal.Resource {\n\treturn internal.GetResourceOrig(internal.ResourceWrapper(ms))\n}\n\nfunc (ms Resource) getState() *internal.State {\n\treturn internal.GetResourceState(internal.ResourceWrapper(ms))\n}\n"
  },
  {
    "path": "pdata/pcommon/generated_resource_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestResource_MoveTo(t *testing.T) {\n\tms := generateTestResource()\n\tdest := NewResource()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewResource(), ms)\n\tassert.Equal(t, generateTestResource(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestResource(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newResource(internal.NewResource(), sharedState)) })\n\tassert.Panics(t, func() { newResource(internal.NewResource(), sharedState).MoveTo(dest) })\n}\n\nfunc TestResource_CopyTo(t *testing.T) {\n\tms := NewResource()\n\torig := NewResource()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestResource()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newResource(internal.NewResource(), sharedState)) })\n}\n\nfunc TestResource_Attributes(t *testing.T) {\n\tms := NewResource()\n\tassert.Equal(t, NewMap(), ms.Attributes())\n\tms.getOrig().Attributes = internal.GenTestKeyValueSlice()\n\tassert.Equal(t, Map(internal.GenTestMapWrapper()), ms.Attributes())\n}\n\nfunc TestResource_DroppedAttributesCount(t *testing.T) {\n\tms := NewResource()\n\tassert.Equal(t, uint32(0), ms.DroppedAttributesCount())\n\tms.SetDroppedAttributesCount(uint32(13))\n\tassert.Equal(t, uint32(13), ms.DroppedAttributesCount())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newResource(internal.NewResource(), sharedState).SetDroppedAttributesCount(uint32(13)) })\n}\n\nfunc generateTestResource() Resource {\n\treturn newResource(internal.GenTestResource(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pcommon/generated_slice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"iter\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// Slice logically represents a slice of Value.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Slice internal.SliceWrapper\n\nfunc newSlice(orig *[]internal.AnyValue, state *internal.State) Slice {\n\treturn Slice(internal.NewSliceWrapper(orig, state))\n}\n\n// NewSlice creates a SliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewSlice() Slice {\n\torig := []internal.AnyValue(nil)\n\treturn newSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewSlice()\".\nfunc (es Slice) Len() int {\n\treturn len(*es.getOrig())\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es Slice) At(i int) Value {\n\treturn newValue(&(*es.getOrig())[i], es.getState())\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es Slice) All() iter.Seq2[int, Value] {\n\treturn func(yield func(int, Value) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new Slice can be initialized:\n//\n//\tes := NewSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es Slice) EnsureCapacity(newCap int) {\n\tes.getState().AssertMutable()\n\toldCap := cap(*es.getOrig())\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]internal.AnyValue, len(*es.getOrig()), newCap)\n\tcopy(newOrig, *es.getOrig())\n\t*es.getOrig() = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty Value.\n// It returns the newly added Value.\nfunc (es Slice) AppendEmpty() Value {\n\tes.getState().AssertMutable()\n\t*es.getOrig() = append(*es.getOrig(), internal.AnyValue{})\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es Slice) MoveAndAppendTo(dest Slice) {\n\tes.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\tif *dest.getOrig() == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.getOrig() = *es.getOrig()\n\t} else {\n\t\t*dest.getOrig() = append(*dest.getOrig(), *es.getOrig()...)\n\t}\n\t*es.getOrig() = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es Slice) RemoveIf(f func(Value) bool) {\n\tes.getState().AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.getOrig()); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteAnyValue(&(*es.getOrig())[i], false)\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.getOrig())[newLen] = (*es.getOrig())[i]\n\t\t(*es.getOrig())[i].Reset()\n\t\tnewLen++\n\t}\n\t*es.getOrig() = (*es.getOrig())[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es Slice) CopyTo(dest Slice) {\n\tdest.getState().AssertMutable()\n\tif es.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = internal.CopyAnyValueSlice(*dest.getOrig(), *es.getOrig())\n}\n\nfunc (ms Slice) getOrig() *[]internal.AnyValue {\n\treturn internal.GetSliceOrig(internal.SliceWrapper(ms))\n}\n\nfunc (ms Slice) getState() *internal.State {\n\treturn internal.GetSliceState(internal.SliceWrapper(ms))\n}\n"
  },
  {
    "path": "pdata/pcommon/generated_slice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestSlice(t *testing.T) {\n\tes := NewSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newSlice(&[]internal.AnyValue{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewValueEmpty()\n\ttestVal := Value(internal.GenTestValueWrapper())\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.getOrig())[i] = *internal.GenTestAnyValue()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newSlice(&[]internal.AnyValue{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestSlice_CopyTo(t *testing.T) {\n\tdest := NewSlice()\n\tsrc := generateTestSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestSlice(), dest)\n}\n\nfunc TestSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.getOrig()))\n\tassert.Equal(t, generateTestSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.getOrig()))\n\tassert.Equal(t, generateTestSlice(), es)\n}\n\nfunc TestSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestSlice()\n\tdest := NewSlice()\n\tsrc := generateTestSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewSlice()\n\temptySlice.RemoveIf(func(el Value) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el Value) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestSlice()\n\tgot.RemoveIf(func(el Value) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestSliceAll(t *testing.T) {\n\tms := generateTestSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc generateTestSlice() Slice {\n\tms := NewSlice()\n\t*ms.getOrig() = internal.GenTestAnyValueSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pcommon/generated_stringslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"iter\"\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// StringSlice represents a []string slice.\n// The instance of StringSlice can be assigned to multiple objects since it's immutable.\n//\n// Must use NewStringSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype StringSlice internal.StringSliceWrapper\n\nfunc (ms StringSlice) getOrig() *[]string {\n\treturn internal.GetStringSliceOrig(internal.StringSliceWrapper(ms))\n}\n\nfunc (ms StringSlice) getState() *internal.State {\n\treturn internal.GetStringSliceState(internal.StringSliceWrapper(ms))\n}\n\n// NewStringSlice creates a new empty StringSlice.\nfunc NewStringSlice() StringSlice {\n\torig := []string(nil)\n\treturn StringSlice(internal.NewStringSliceWrapper(&orig, internal.NewState()))\n}\n\n// AsRaw returns a copy of the []string slice.\nfunc (ms StringSlice) AsRaw() []string {\n\treturn copyStringSlice(nil, *ms.getOrig())\n}\n\n// FromRaw copies raw []string into the slice StringSlice.\nfunc (ms StringSlice) FromRaw(val []string) {\n\tms.getState().AssertMutable()\n\t*ms.getOrig() = copyStringSlice(*ms.getOrig(), val)\n}\n\n// Len returns length of the []string slice value.\n// Equivalent of len(stringSlice).\nfunc (ms StringSlice) Len() int {\n\treturn len(*ms.getOrig())\n}\n\n// At returns an item from particular index.\n// Equivalent of stringSlice[i].\nfunc (ms StringSlice) At(i int) string {\n\treturn (*ms.getOrig())[i]\n}\n\n// All returns an iterator over index-value pairs in the slice.\nfunc (ms StringSlice) All() iter.Seq2[int, string] {\n\treturn func(yield func(int, string) bool) {\n\t\tfor i := 0; i < ms.Len(); i++ {\n\t\t\tif !yield(i, ms.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// SetAt sets string item at particular index.\n// Equivalent of stringSlice[i] = val\nfunc (ms StringSlice) SetAt(i int, val string) {\n\tms.getState().AssertMutable()\n\t(*ms.getOrig())[i] = val\n}\n\n// EnsureCapacity ensures StringSlice has at least the specified capacity.\n//  1. If the newCap <= cap, then is no change in capacity.\n//  2. If the newCap > cap, then the slice capacity will be expanded to the provided value which will be equivalent of:\n//     buf := make([]string, len(stringSlice), newCap)\n//     copy(buf, stringSlice)\n//     stringSlice = buf\nfunc (ms StringSlice) EnsureCapacity(newCap int) {\n\tms.getState().AssertMutable()\n\toldCap := cap(*ms.getOrig())\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]string, len(*ms.getOrig()), newCap)\n\tcopy(newOrig, *ms.getOrig())\n\t*ms.getOrig() = newOrig\n}\n\n// Append appends extra elements to StringSlice.\n// Equivalent of stringSlice = append(stringSlice, elms...)\nfunc (ms StringSlice) Append(elms ...string) {\n\tms.getState().AssertMutable()\n\t*ms.getOrig() = append(*ms.getOrig(), elms...)\n}\n\n// MoveTo moves all elements from the current slice overriding the destination and\n// resetting the current instance to its zero value.\nfunc (ms StringSlice) MoveTo(dest StringSlice) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = *ms.getOrig()\n\t*ms.getOrig() = nil\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (ms StringSlice) MoveAndAppendTo(dest StringSlice) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\tif *dest.getOrig() == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.getOrig() = *ms.getOrig()\n\t} else {\n\t\t*dest.getOrig() = append(*dest.getOrig(), *ms.getOrig()...)\n\t}\n\t*ms.getOrig() = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (ms StringSlice) RemoveIf(f func(string) bool) {\n\tms.getState().AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*ms.getOrig()); i++ {\n\t\tif f((*ms.getOrig())[i]) {\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*ms.getOrig())[newLen] = (*ms.getOrig())[i]\n\t\tvar zero string\n\t\t(*ms.getOrig())[i] = zero\n\t\tnewLen++\n\t}\n\t*ms.getOrig() = (*ms.getOrig())[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (ms StringSlice) CopyTo(dest StringSlice) {\n\tdest.getState().AssertMutable()\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = copyStringSlice(*dest.getOrig(), *ms.getOrig())\n}\n\n// Equal checks equality with another StringSlice\nfunc (ms StringSlice) Equal(val StringSlice) bool {\n\treturn slices.Equal(*ms.getOrig(), *val.getOrig())\n}\n\nfunc copyStringSlice(dst, src []string) []string {\n\treturn append(dst[:0], src...)\n}\n"
  },
  {
    "path": "pdata/pcommon/generated_stringslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestNewStringSlice(t *testing.T) {\n\tms := NewStringSlice()\n\tassert.Equal(t, 0, ms.Len())\n\tms.FromRaw([]string{\"a\", \"b\", \"c\"})\n\tassert.Equal(t, 3, ms.Len())\n\tassert.Equal(t, []string{\"a\", \"b\", \"c\"}, ms.AsRaw())\n\tms.SetAt(1, string(\"d\"))\n\tassert.Equal(t, []string{\"a\", \"d\", \"c\"}, ms.AsRaw())\n\tms.FromRaw([]string{\"c\"})\n\tassert.Equal(t, 1, ms.Len())\n\tassert.Equal(t, string(\"c\"), ms.At(0))\n\n\tcp := NewStringSlice()\n\tms.CopyTo(cp)\n\tms.SetAt(0, string(\"b\"))\n\tassert.Equal(t, string(\"b\"), ms.At(0))\n\tassert.Equal(t, string(\"c\"), cp.At(0))\n\tms.CopyTo(cp)\n\tassert.Equal(t, string(\"b\"), cp.At(0))\n\n\tmv := NewStringSlice()\n\tms.MoveTo(mv)\n\tassert.Equal(t, 0, ms.Len())\n\tassert.Equal(t, 1, mv.Len())\n\tassert.Equal(t, string(\"b\"), mv.At(0))\n\tms.FromRaw([]string{\"a\", \"b\", \"c\"})\n\tms.MoveTo(mv)\n\tassert.Equal(t, 3, mv.Len())\n\tassert.Equal(t, string(\"a\"), mv.At(0))\n\tmv.MoveTo(mv)\n\tassert.Equal(t, 3, mv.Len())\n\tassert.Equal(t, string(\"a\"), mv.At(0))\n}\n\nfunc TestStringSliceReadOnly(t *testing.T) {\n\traw := []string{\"a\", \"b\", \"c\"}\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tms := StringSlice(internal.NewStringSliceWrapper(&raw, sharedState))\n\n\tassert.Equal(t, 3, ms.Len())\n\tassert.Equal(t, string(\"a\"), ms.At(0))\n\tassert.Panics(t, func() { ms.Append(\"a\") })\n\tassert.Panics(t, func() { ms.EnsureCapacity(2) })\n\tassert.Equal(t, raw, ms.AsRaw())\n\tassert.Panics(t, func() { ms.FromRaw(raw) })\n\n\tms2 := NewStringSlice()\n\tms.CopyTo(ms2)\n\tassert.Equal(t, ms.AsRaw(), ms2.AsRaw())\n\tassert.Panics(t, func() { ms2.CopyTo(ms) })\n\n\tassert.Panics(t, func() { ms.MoveTo(ms2) })\n\tassert.Panics(t, func() { ms2.MoveTo(ms) })\n}\n\nfunc TestStringSliceAppend(t *testing.T) {\n\tms := NewStringSlice()\n\tms.FromRaw([]string{\"a\", \"b\", \"c\"})\n\tms.Append(\"d\", \"d\")\n\tassert.Equal(t, 5, ms.Len())\n\tassert.Equal(t, string(\"d\"), ms.At(4))\n}\n\nfunc TestStringSliceEnsureCapacity(t *testing.T) {\n\tms := NewStringSlice()\n\tms.EnsureCapacity(4)\n\tassert.Equal(t, 4, cap(*ms.getOrig()))\n\tms.EnsureCapacity(2)\n\tassert.Equal(t, 4, cap(*ms.getOrig()))\n}\n\nfunc TestStringSliceAll(t *testing.T) {\n\tms := NewStringSlice()\n\tms.FromRaw([]string{\"a\", \"b\", \"c\"})\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestStringSliceMoveAndAppendTo(t *testing.T) {\n\t// Test moving from an empty slice\n\tms := NewStringSlice()\n\tms2 := NewStringSlice()\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, NewStringSlice(), ms2)\n\tassert.Equal(t, ms.Len(), 0)\n\n\t// Test moving to empty slice\n\tms.FromRaw([]string{\"a\", \"b\", \"c\"})\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, ms2.Len(), 3)\n\n\t// Test moving to a non empty slice\n\tms.FromRaw([]string{\"a\", \"b\", \"c\"})\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, ms2.Len(), 6)\n}\n\nfunc TestStringSliceRemoveIf(t *testing.T) {\n\temptySlice := NewStringSlice()\n\temptySlice.RemoveIf(func(el string) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\tms := NewStringSlice()\n\tms.FromRaw([]string{\"a\", \"b\", \"c\"})\n\tpos := 0\n\tms.RemoveIf(func(el string) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, pos/2, ms.Len())\n}\n\nfunc TestStringSliceRemoveIfAll(t *testing.T) {\n\tms := NewStringSlice()\n\tms.FromRaw([]string{\"a\", \"b\", \"c\"})\n\tms.RemoveIf(func(el string) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, ms.Len())\n}\n\nfunc TestStringSliceEqual(t *testing.T) {\n\tms := NewStringSlice()\n\tms2 := NewStringSlice()\n\tassert.True(t, ms.Equal(ms2))\n\n\tms.Append(\"a\", \"b\", \"c\")\n\tassert.False(t, ms.Equal(ms2))\n\n\tms2.Append(\"a\", \"b\", \"c\")\n\tassert.True(t, ms.Equal(ms2))\n}\n\nfunc BenchmarkStringSliceEqual(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\tms := NewStringSlice()\n\tms.Append(\"a\", \"b\", \"c\")\n\tcmp := NewStringSlice()\n\tcmp.Append(\"a\", \"b\", \"c\")\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\n\tfor n := 0; n < b.N; n++ {\n\t\t_ = ms.Equal(cmp)\n\t}\n}\n"
  },
  {
    "path": "pdata/pcommon/generated_uint64slice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"iter\"\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// UInt64Slice represents a []uint64 slice.\n// The instance of UInt64Slice can be assigned to multiple objects since it's immutable.\n//\n// Must use NewUInt64Slice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype UInt64Slice internal.UInt64SliceWrapper\n\nfunc (ms UInt64Slice) getOrig() *[]uint64 {\n\treturn internal.GetUInt64SliceOrig(internal.UInt64SliceWrapper(ms))\n}\n\nfunc (ms UInt64Slice) getState() *internal.State {\n\treturn internal.GetUInt64SliceState(internal.UInt64SliceWrapper(ms))\n}\n\n// NewUInt64Slice creates a new empty UInt64Slice.\nfunc NewUInt64Slice() UInt64Slice {\n\torig := []uint64(nil)\n\treturn UInt64Slice(internal.NewUInt64SliceWrapper(&orig, internal.NewState()))\n}\n\n// AsRaw returns a copy of the []uint64 slice.\nfunc (ms UInt64Slice) AsRaw() []uint64 {\n\treturn copyUint64Slice(nil, *ms.getOrig())\n}\n\n// FromRaw copies raw []uint64 into the slice UInt64Slice.\nfunc (ms UInt64Slice) FromRaw(val []uint64) {\n\tms.getState().AssertMutable()\n\t*ms.getOrig() = copyUint64Slice(*ms.getOrig(), val)\n}\n\n// Len returns length of the []uint64 slice value.\n// Equivalent of len(uInt64Slice).\nfunc (ms UInt64Slice) Len() int {\n\treturn len(*ms.getOrig())\n}\n\n// At returns an item from particular index.\n// Equivalent of uInt64Slice[i].\nfunc (ms UInt64Slice) At(i int) uint64 {\n\treturn (*ms.getOrig())[i]\n}\n\n// All returns an iterator over index-value pairs in the slice.\nfunc (ms UInt64Slice) All() iter.Seq2[int, uint64] {\n\treturn func(yield func(int, uint64) bool) {\n\t\tfor i := 0; i < ms.Len(); i++ {\n\t\t\tif !yield(i, ms.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// SetAt sets uint64 item at particular index.\n// Equivalent of uInt64Slice[i] = val\nfunc (ms UInt64Slice) SetAt(i int, val uint64) {\n\tms.getState().AssertMutable()\n\t(*ms.getOrig())[i] = val\n}\n\n// EnsureCapacity ensures UInt64Slice has at least the specified capacity.\n//  1. If the newCap <= cap, then is no change in capacity.\n//  2. If the newCap > cap, then the slice capacity will be expanded to the provided value which will be equivalent of:\n//     buf := make([]uint64, len(uInt64Slice), newCap)\n//     copy(buf, uInt64Slice)\n//     uInt64Slice = buf\nfunc (ms UInt64Slice) EnsureCapacity(newCap int) {\n\tms.getState().AssertMutable()\n\toldCap := cap(*ms.getOrig())\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]uint64, len(*ms.getOrig()), newCap)\n\tcopy(newOrig, *ms.getOrig())\n\t*ms.getOrig() = newOrig\n}\n\n// Append appends extra elements to UInt64Slice.\n// Equivalent of uInt64Slice = append(uInt64Slice, elms...)\nfunc (ms UInt64Slice) Append(elms ...uint64) {\n\tms.getState().AssertMutable()\n\t*ms.getOrig() = append(*ms.getOrig(), elms...)\n}\n\n// MoveTo moves all elements from the current slice overriding the destination and\n// resetting the current instance to its zero value.\nfunc (ms UInt64Slice) MoveTo(dest UInt64Slice) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = *ms.getOrig()\n\t*ms.getOrig() = nil\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (ms UInt64Slice) MoveAndAppendTo(dest UInt64Slice) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\tif *dest.getOrig() == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.getOrig() = *ms.getOrig()\n\t} else {\n\t\t*dest.getOrig() = append(*dest.getOrig(), *ms.getOrig()...)\n\t}\n\t*ms.getOrig() = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (ms UInt64Slice) RemoveIf(f func(uint64) bool) {\n\tms.getState().AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*ms.getOrig()); i++ {\n\t\tif f((*ms.getOrig())[i]) {\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*ms.getOrig())[newLen] = (*ms.getOrig())[i]\n\t\tvar zero uint64\n\t\t(*ms.getOrig())[i] = zero\n\t\tnewLen++\n\t}\n\t*ms.getOrig() = (*ms.getOrig())[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (ms UInt64Slice) CopyTo(dest UInt64Slice) {\n\tdest.getState().AssertMutable()\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = copyUint64Slice(*dest.getOrig(), *ms.getOrig())\n}\n\n// Equal checks equality with another UInt64Slice\nfunc (ms UInt64Slice) Equal(val UInt64Slice) bool {\n\treturn slices.Equal(*ms.getOrig(), *val.getOrig())\n}\n\nfunc copyUint64Slice(dst, src []uint64) []uint64 {\n\treturn append(dst[:0], src...)\n}\n"
  },
  {
    "path": "pdata/pcommon/generated_uint64slice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pcommon\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestNewUInt64Slice(t *testing.T) {\n\tms := NewUInt64Slice()\n\tassert.Equal(t, 0, ms.Len())\n\tms.FromRaw([]uint64{1, 2, 3})\n\tassert.Equal(t, 3, ms.Len())\n\tassert.Equal(t, []uint64{1, 2, 3}, ms.AsRaw())\n\tms.SetAt(1, uint64(5))\n\tassert.Equal(t, []uint64{1, 5, 3}, ms.AsRaw())\n\tms.FromRaw([]uint64{3})\n\tassert.Equal(t, 1, ms.Len())\n\tassert.Equal(t, uint64(3), ms.At(0))\n\n\tcp := NewUInt64Slice()\n\tms.CopyTo(cp)\n\tms.SetAt(0, uint64(2))\n\tassert.Equal(t, uint64(2), ms.At(0))\n\tassert.Equal(t, uint64(3), cp.At(0))\n\tms.CopyTo(cp)\n\tassert.Equal(t, uint64(2), cp.At(0))\n\n\tmv := NewUInt64Slice()\n\tms.MoveTo(mv)\n\tassert.Equal(t, 0, ms.Len())\n\tassert.Equal(t, 1, mv.Len())\n\tassert.Equal(t, uint64(2), mv.At(0))\n\tms.FromRaw([]uint64{1, 2, 3})\n\tms.MoveTo(mv)\n\tassert.Equal(t, 3, mv.Len())\n\tassert.Equal(t, uint64(1), mv.At(0))\n\tmv.MoveTo(mv)\n\tassert.Equal(t, 3, mv.Len())\n\tassert.Equal(t, uint64(1), mv.At(0))\n}\n\nfunc TestUInt64SliceReadOnly(t *testing.T) {\n\traw := []uint64{1, 2, 3}\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tms := UInt64Slice(internal.NewUInt64SliceWrapper(&raw, sharedState))\n\n\tassert.Equal(t, 3, ms.Len())\n\tassert.Equal(t, uint64(1), ms.At(0))\n\tassert.Panics(t, func() { ms.Append(1) })\n\tassert.Panics(t, func() { ms.EnsureCapacity(2) })\n\tassert.Equal(t, raw, ms.AsRaw())\n\tassert.Panics(t, func() { ms.FromRaw(raw) })\n\n\tms2 := NewUInt64Slice()\n\tms.CopyTo(ms2)\n\tassert.Equal(t, ms.AsRaw(), ms2.AsRaw())\n\tassert.Panics(t, func() { ms2.CopyTo(ms) })\n\n\tassert.Panics(t, func() { ms.MoveTo(ms2) })\n\tassert.Panics(t, func() { ms2.MoveTo(ms) })\n}\n\nfunc TestUInt64SliceAppend(t *testing.T) {\n\tms := NewUInt64Slice()\n\tms.FromRaw([]uint64{1, 2, 3})\n\tms.Append(5, 5)\n\tassert.Equal(t, 5, ms.Len())\n\tassert.Equal(t, uint64(5), ms.At(4))\n}\n\nfunc TestUInt64SliceEnsureCapacity(t *testing.T) {\n\tms := NewUInt64Slice()\n\tms.EnsureCapacity(4)\n\tassert.Equal(t, 4, cap(*ms.getOrig()))\n\tms.EnsureCapacity(2)\n\tassert.Equal(t, 4, cap(*ms.getOrig()))\n}\n\nfunc TestUInt64SliceAll(t *testing.T) {\n\tms := NewUInt64Slice()\n\tms.FromRaw([]uint64{1, 2, 3})\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestUInt64SliceMoveAndAppendTo(t *testing.T) {\n\t// Test moving from an empty slice\n\tms := NewUInt64Slice()\n\tms2 := NewUInt64Slice()\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, NewUInt64Slice(), ms2)\n\tassert.Equal(t, ms.Len(), 0)\n\n\t// Test moving to empty slice\n\tms.FromRaw([]uint64{1, 2, 3})\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, ms2.Len(), 3)\n\n\t// Test moving to a non empty slice\n\tms.FromRaw([]uint64{1, 2, 3})\n\tms.MoveAndAppendTo(ms2)\n\tassert.Equal(t, ms2.Len(), 6)\n}\n\nfunc TestUInt64SliceRemoveIf(t *testing.T) {\n\temptySlice := NewUInt64Slice()\n\temptySlice.RemoveIf(func(el uint64) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\tms := NewUInt64Slice()\n\tms.FromRaw([]uint64{1, 2, 3})\n\tpos := 0\n\tms.RemoveIf(func(el uint64) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, pos/2, ms.Len())\n}\n\nfunc TestUInt64SliceRemoveIfAll(t *testing.T) {\n\tms := NewUInt64Slice()\n\tms.FromRaw([]uint64{1, 2, 3})\n\tms.RemoveIf(func(el uint64) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, ms.Len())\n}\n\nfunc TestUInt64SliceEqual(t *testing.T) {\n\tms := NewUInt64Slice()\n\tms2 := NewUInt64Slice()\n\tassert.True(t, ms.Equal(ms2))\n\n\tms.Append(1, 2, 3)\n\tassert.False(t, ms.Equal(ms2))\n\n\tms2.Append(1, 2, 3)\n\tassert.True(t, ms.Equal(ms2))\n}\n\nfunc BenchmarkUInt64SliceEqual(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\tms := NewUInt64Slice()\n\tms.Append(1, 2, 3)\n\tcmp := NewUInt64Slice()\n\tcmp.Append(1, 2, 3)\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\n\tfor n := 0; n < b.N; n++ {\n\t\t_ = ms.Equal(cmp)\n\t}\n}\n"
  },
  {
    "path": "pdata/pcommon/map.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pcommon // import \"go.opentelemetry.io/collector/pdata/pcommon\"\n\nimport (\n\t\"iter\"\n\n\t\"go.uber.org/multierr\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// Map stores a map of string keys to elements of Value type.\n//\n// Must use NewMap function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Map internal.MapWrapper\n\n// NewMap creates a Map with 0 elements.\nfunc NewMap() Map {\n\torig := []internal.KeyValue(nil)\n\treturn Map(internal.NewMapWrapper(&orig, internal.NewState()))\n}\n\nfunc (m Map) getOrig() *[]internal.KeyValue {\n\treturn internal.GetMapOrig(internal.MapWrapper(m))\n}\n\nfunc (m Map) getState() *internal.State {\n\treturn internal.GetMapState(internal.MapWrapper(m))\n}\n\nfunc newMap(orig *[]internal.KeyValue, state *internal.State) Map {\n\treturn Map(internal.NewMapWrapper(orig, state))\n}\n\n// Clear erases any existing entries in this Map instance.\nfunc (m Map) Clear() {\n\tm.getState().AssertMutable()\n\t*m.getOrig() = nil\n}\n\n// EnsureCapacity increases the capacity of this Map instance, if necessary,\n// to ensure that it can hold at least the number of elements specified by the capacity argument.\nfunc (m Map) EnsureCapacity(capacity int) {\n\tm.getState().AssertMutable()\n\toldOrig := *m.getOrig()\n\tif capacity <= cap(oldOrig) {\n\t\treturn\n\t}\n\t*m.getOrig() = make([]internal.KeyValue, len(oldOrig), capacity)\n\tcopy(*m.getOrig(), oldOrig)\n}\n\n// Get returns the Value associated with the key and true. The returned\n// Value is not a copy, it is a reference to the value stored in this map.\n// It is allowed to modify the returned value using Value.Set* functions.\n// Such modification will be applied to the value stored in this map.\n// Accessing the returned value after modifying the underlying map\n// (removing or adding new values) is an undefined behavior.\n//\n// If the key does not exist, returns a zero-initialized KeyValue and false.\n// Calling any functions on the returned invalid instance may cause a panic.\nfunc (m Map) Get(key string) (Value, bool) {\n\tfor i := range *m.getOrig() {\n\t\takv := &(*m.getOrig())[i]\n\t\tif akv.Key == key {\n\t\t\treturn newValue(&akv.Value, m.getState()), true\n\t\t}\n\t}\n\treturn newValue(nil, m.getState()), false\n}\n\n// Remove removes the entry associated with the key and returns true if the key\n// was present in the map, otherwise returns false.\nfunc (m Map) Remove(key string) bool {\n\tm.getState().AssertMutable()\n\tfor i := range *m.getOrig() {\n\t\takv := &(*m.getOrig())[i]\n\t\tif akv.Key == key {\n\t\t\t*akv = (*m.getOrig())[len(*m.getOrig())-1]\n\t\t\t*m.getOrig() = (*m.getOrig())[:len(*m.getOrig())-1]\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// RemoveIf removes the entries for which the function in question returns true\nfunc (m Map) RemoveIf(f func(string, Value) bool) {\n\tm.getState().AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*m.getOrig()); i++ {\n\t\tif f((*m.getOrig())[i].Key, newValue(&(*m.getOrig())[i].Value, m.getState())) {\n\t\t\t(*m.getOrig())[i] = internal.KeyValue{}\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*m.getOrig())[newLen] = (*m.getOrig())[i]\n\t\t(*m.getOrig())[i] = internal.KeyValue{}\n\t\tnewLen++\n\t}\n\t*m.getOrig() = (*m.getOrig())[:newLen]\n}\n\n// PutEmpty inserts or updates an empty value to the map under given key\n// and return the updated/inserted value.\nfunc (m Map) PutEmpty(k string) Value {\n\tm.getState().AssertMutable()\n\tif av, existing := m.Get(k); existing {\n\t\tav.getOrig().Value = nil\n\t\treturn newValue(av.getOrig(), m.getState())\n\t}\n\t*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k})\n\treturn newValue(&(*m.getOrig())[len(*m.getOrig())-1].Value, m.getState())\n}\n\n// GetOrPutEmpty returns the Value associated with the key and true (loaded) if the key exists in the map,\n// otherwise inserts an empty value to the map under the given key and returns the inserted value\n// and false (loaded).\nfunc (m Map) GetOrPutEmpty(k string) (Value, bool) {\n\tm.getState().AssertMutable()\n\tif av, existing := m.Get(k); existing {\n\t\treturn av, true\n\t}\n\t*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k})\n\treturn newValue(&(*m.getOrig())[len(*m.getOrig())-1].Value, m.getState()), false\n}\n\n// PutStr performs the Insert or Update action. The Value is\n// inserted to the map that did not originally have the key. The key/value is\n// updated to the map where the key already existed.\nfunc (m Map) PutStr(k, v string) {\n\tm.getState().AssertMutable()\n\tif av, existing := m.Get(k); existing {\n\t\tav.SetStr(v)\n\t\treturn\n\t}\n\tov := internal.NewAnyValueStringValue()\n\tov.StringValue = v\n\t*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})\n}\n\n// PutInt performs the Insert or Update action. The int Value is\n// inserted to the map that did not originally have the key. The key/value is\n// updated to the map where the key already existed.\nfunc (m Map) PutInt(k string, v int64) {\n\tm.getState().AssertMutable()\n\tif av, existing := m.Get(k); existing {\n\t\tav.SetInt(v)\n\t\treturn\n\t}\n\tov := internal.NewAnyValueIntValue()\n\tov.IntValue = v\n\t*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})\n}\n\n// PutDouble performs the Insert or Update action. The double Value is\n// inserted to the map that did not originally have the key. The key/value is\n// updated to the map where the key already existed.\nfunc (m Map) PutDouble(k string, v float64) {\n\tm.getState().AssertMutable()\n\tif av, existing := m.Get(k); existing {\n\t\tav.SetDouble(v)\n\t\treturn\n\t}\n\tov := internal.NewAnyValueDoubleValue()\n\tov.DoubleValue = v\n\t*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})\n}\n\n// PutBool performs the Insert or Update action. The bool Value is\n// inserted to the map that did not originally have the key. The key/value is\n// updated to the map where the key already existed.\nfunc (m Map) PutBool(k string, v bool) {\n\tm.getState().AssertMutable()\n\tif av, existing := m.Get(k); existing {\n\t\tav.SetBool(v)\n\t\treturn\n\t}\n\tov := internal.NewAnyValueBoolValue()\n\tov.BoolValue = v\n\t*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})\n}\n\n// PutEmptyBytes inserts or updates an empty byte slice under given key and returns it.\nfunc (m Map) PutEmptyBytes(k string) ByteSlice {\n\tm.getState().AssertMutable()\n\tif av, existing := m.Get(k); existing {\n\t\treturn av.SetEmptyBytes()\n\t}\n\tov := internal.NewAnyValueBytesValue()\n\t*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})\n\treturn ByteSlice(internal.NewByteSliceWrapper(&ov.BytesValue, m.getState()))\n}\n\n// PutEmptyMap inserts or updates an empty map under given key and returns it.\nfunc (m Map) PutEmptyMap(k string) Map {\n\tm.getState().AssertMutable()\n\tif av, existing := m.Get(k); existing {\n\t\treturn av.SetEmptyMap()\n\t}\n\tov := internal.NewAnyValueKvlistValue()\n\tov.KvlistValue = internal.NewKeyValueList()\n\t*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})\n\treturn Map(internal.NewMapWrapper(&ov.KvlistValue.Values, m.getState()))\n}\n\n// PutEmptySlice inserts or updates an empty slice under given key and returns it.\nfunc (m Map) PutEmptySlice(k string) Slice {\n\tm.getState().AssertMutable()\n\tif av, existing := m.Get(k); existing {\n\t\treturn av.SetEmptySlice()\n\t}\n\tov := internal.NewAnyValueArrayValue()\n\tov.ArrayValue = internal.NewArrayValue()\n\t*m.getOrig() = append(*m.getOrig(), internal.KeyValue{Key: k, Value: internal.AnyValue{Value: ov}})\n\treturn Slice(internal.NewSliceWrapper(&ov.ArrayValue.Values, m.getState()))\n}\n\n// Len returns the length of this map.\n//\n// Because the Map is represented internally by a slice of pointers, and the data are comping from the wire,\n// it is possible that when iterating using \"Range\" to get access to fewer elements because nil elements are skipped.\nfunc (m Map) Len() int {\n\treturn len(*m.getOrig())\n}\n\n// Range calls f sequentially for each key and value present in the map. If f returns false, range stops the iteration.\n//\n// Example:\n//\n//\tsm.Range(func(k string, v Value) bool {\n//\t    ...\n//\t})\nfunc (m Map) Range(f func(k string, v Value) bool) {\n\tfor i := range *m.getOrig() {\n\t\tkv := &(*m.getOrig())[i]\n\t\tif !f(kv.Key, Value(internal.NewValueWrapper(&kv.Value, m.getState()))) {\n\t\t\tbreak\n\t\t}\n\t}\n}\n\n// All returns an iterator over key-value pairs in the Map.\n//\n//\tfor k, v := range es.All() {\n//\t    ... // Do something with key-value pair\n//\t}\nfunc (m Map) All() iter.Seq2[string, Value] {\n\treturn func(yield func(string, Value) bool) {\n\t\tfor i := range *m.getOrig() {\n\t\t\tkv := &(*m.getOrig())[i]\n\t\t\tif !yield(kv.Key, Value(internal.NewValueWrapper(&kv.Value, m.getState()))) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// MoveTo moves all key/values from the current map overriding the destination and\n// resetting the current instance to its zero value\nfunc (m Map) MoveTo(dest Map) {\n\tm.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif m.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = *m.getOrig()\n\t*m.getOrig() = nil\n}\n\n// CopyTo copies all elements from the current map overriding the destination.\nfunc (m Map) CopyTo(dest Map) {\n\tdest.getState().AssertMutable()\n\tif m.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = internal.CopyKeyValueSlice(*dest.getOrig(), *m.getOrig())\n}\n\n// AsRaw returns a standard go map representation of this Map.\nfunc (m Map) AsRaw() map[string]any {\n\trawMap := make(map[string]any, m.Len())\n\tm.Range(func(k string, v Value) bool {\n\t\trawMap[k] = v.AsRaw()\n\t\treturn true\n\t})\n\treturn rawMap\n}\n\n// FromRaw overrides this Map instance from a standard go map.\nfunc (m Map) FromRaw(rawMap map[string]any) error {\n\tm.getState().AssertMutable()\n\tif len(rawMap) == 0 {\n\t\t*m.getOrig() = nil\n\t\treturn nil\n\t}\n\n\tvar errs error\n\torigs := make([]internal.KeyValue, len(rawMap))\n\tix := 0\n\tfor k, iv := range rawMap {\n\t\torigs[ix].Key = k\n\t\terrs = multierr.Append(errs, newValue(&origs[ix].Value, m.getState()).FromRaw(iv))\n\t\tix++\n\t}\n\t*m.getOrig() = origs\n\treturn errs\n}\n\n// Equal checks equality with another Map\nfunc (m Map) Equal(val Map) bool {\n\tif m.Len() != val.Len() {\n\t\treturn false\n\t}\n\n\tfullEqual := true\n\n\tm.Range(func(k string, v Value) bool {\n\t\tvv, ok := val.Get(k)\n\t\tif !ok {\n\t\t\tfullEqual = false\n\t\t\treturn fullEqual\n\t\t}\n\n\t\tif !v.Equal(vv) {\n\t\t\tfullEqual = false\n\t\t}\n\t\treturn fullEqual\n\t})\n\treturn fullEqual\n}\n"
  },
  {
    "path": "pdata/pcommon/map_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pcommon\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestMap(t *testing.T) {\n\tassert.Equal(t, 0, NewMap().Len())\n\n\tval, exist := NewMap().Get(\"test_key\")\n\tassert.False(t, exist)\n\tassert.Equal(t, newValue(nil, internal.NewState()), val)\n\n\tputString := NewMap()\n\tputString.PutStr(\"k\", \"v\")\n\tassert.Equal(t, generateTestStringMap(t), putString)\n\n\tputInt := NewMap()\n\tputInt.PutInt(\"k\", 123)\n\tassert.Equal(t, generateTestIntMap(t), putInt)\n\n\tputDouble := NewMap()\n\tputDouble.PutDouble(\"k\", 12.3)\n\tassert.Equal(t, generateTestDoubleMap(t), putDouble)\n\n\tputBool := NewMap()\n\tputBool.PutBool(\"k\", true)\n\tassert.Equal(t, generateTestBoolMap(t), putBool)\n\n\tputBytes := NewMap()\n\tputBytes.PutEmptyBytes(\"k\").FromRaw([]byte{1, 2, 3, 4, 5})\n\tassert.Equal(t, generateTestBytesMap(t), putBytes)\n\n\tputMap := NewMap()\n\tputMap.PutEmptyMap(\"k\")\n\tassert.Equal(t, generateTestEmptyMap(t), putMap)\n\n\tputSlice := NewMap()\n\tputSlice.PutEmptySlice(\"k\")\n\tassert.Equal(t, generateTestEmptySlice(t), putSlice)\n\n\tremoveMap := NewMap()\n\tassert.False(t, removeMap.Remove(\"k\"))\n\tassert.Equal(t, NewMap(), removeMap)\n}\n\nfunc TestMapReadOnly(t *testing.T) {\n\tstate := internal.NewState()\n\tstate.MarkReadOnly()\n\tm := newMap(&[]internal.KeyValue{\n\t\t{Key: \"k1\", Value: internal.AnyValue{Value: &internal.AnyValue_StringValue{StringValue: \"v1\"}}},\n\t}, state)\n\n\tassert.Equal(t, 1, m.Len())\n\n\tv, ok := m.Get(\"k1\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"v1\", v.Str())\n\n\tm.Range(func(k string, v Value) bool {\n\t\tassert.Equal(t, \"k1\", k)\n\t\tassert.Equal(t, \"v1\", v.Str())\n\t\treturn true\n\t})\n\n\tassert.Panics(t, func() { m.PutStr(\"k2\", \"v2\") })\n\tassert.Panics(t, func() { m.PutInt(\"k2\", 123) })\n\tassert.Panics(t, func() { m.PutDouble(\"k2\", 1.23) })\n\tassert.Panics(t, func() { m.PutBool(\"k2\", true) })\n\tassert.Panics(t, func() { m.PutEmpty(\"foo\") })\n\tassert.Panics(t, func() { m.GetOrPutEmpty(\"foo\") })\n\tassert.Panics(t, func() { m.PutEmptyBytes(\"k2\") })\n\tassert.Panics(t, func() { m.PutEmptyMap(\"k2\") })\n\tassert.Panics(t, func() { m.PutEmptySlice(\"k2\") })\n\tassert.Panics(t, func() { m.Remove(\"k1\") })\n\tassert.Panics(t, func() { m.RemoveIf(func(string, Value) bool { return true }) })\n\tassert.Panics(t, func() { m.EnsureCapacity(2) })\n\n\tm2 := NewMap()\n\tm.CopyTo(m2)\n\tassert.Equal(t, m2.AsRaw(), m.AsRaw())\n\tassert.Panics(t, func() { NewMap().CopyTo(m) })\n\n\tassert.Equal(t, map[string]any{\"k1\": \"v1\"}, m.AsRaw())\n\tassert.Panics(t, func() { _ = m.FromRaw(map[string]any{\"k1\": \"v1\"}) })\n}\n\nfunc TestMapPutEmpty(t *testing.T) {\n\tm := NewMap()\n\tv := m.PutEmpty(\"k1\")\n\tassert.Equal(t, map[string]any{\n\t\t\"k1\": nil,\n\t}, m.AsRaw())\n\n\tv.SetBool(true)\n\tassert.Equal(t, map[string]any{\n\t\t\"k1\": true,\n\t}, m.AsRaw())\n\n\tv = m.PutEmpty(\"k1\")\n\tv.SetInt(1)\n\tv2, ok := m.Get(\"k1\")\n\tassert.True(t, ok)\n\tassert.Equal(t, int64(1), v2.Int())\n}\n\nfunc TestMapGetOrPutEmpty(t *testing.T) {\n\tm := NewMap()\n\tv := m.PutEmpty(\"k1\")\n\tv.SetStr(\"test\")\n\tassert.Equal(t, map[string]any{\n\t\t\"k1\": \"test\",\n\t}, m.AsRaw())\n\n\tv, found := m.GetOrPutEmpty(\"k1\")\n\tassert.True(t, found)\n\trequire.Equal(t, ValueTypeStr, v.Type())\n\tassert.Equal(t, \"test\", v.Str())\n\n\tv, found = m.GetOrPutEmpty(\"k2\")\n\tassert.False(t, found)\n\trequire.Equal(t, ValueTypeEmpty, v.Type())\n}\n\nfunc TestMapPutEmptyMap(t *testing.T) {\n\tm := NewMap()\n\tchildMap := m.PutEmptyMap(\"k1\")\n\tassert.Equal(t, map[string]any{\n\t\t\"k1\": map[string]any{},\n\t}, m.AsRaw())\n\tchildMap.PutEmptySlice(\"k2\").AppendEmpty().SetStr(\"val\")\n\tassert.Equal(t, map[string]any{\n\t\t\"k1\": map[string]any{\n\t\t\t\"k2\": []any{\"val\"},\n\t\t},\n\t}, m.AsRaw())\n\n\tchildMap.PutEmptyMap(\"k2\").PutInt(\"k3\", 1)\n\tassert.Equal(t, map[string]any{\n\t\t\"k1\": map[string]any{\n\t\t\t\"k2\": map[string]any{\"k3\": int64(1)},\n\t\t},\n\t}, m.AsRaw())\n}\n\nfunc TestMapPutEmptySlice(t *testing.T) {\n\tm := NewMap()\n\tchildSlice := m.PutEmptySlice(\"k\")\n\tassert.Equal(t, map[string]any{\n\t\t\"k\": []any{},\n\t}, m.AsRaw())\n\tchildSlice.AppendEmpty().SetDouble(1.1)\n\tassert.Equal(t, map[string]any{\n\t\t\"k\": []any{1.1},\n\t}, m.AsRaw())\n\n\tm.PutEmptySlice(\"k\")\n\tassert.Equal(t, map[string]any{\n\t\t\"k\": []any{},\n\t}, m.AsRaw())\n\tchildSliceVal, ok := m.Get(\"k\")\n\tassert.True(t, ok)\n\tchildSliceVal.Slice().AppendEmpty().SetEmptySlice().AppendEmpty().SetStr(\"val\")\n\tassert.Equal(t, map[string]any{\n\t\t\"k\": []any{[]any{\"val\"}},\n\t}, m.AsRaw())\n}\n\nfunc TestMapPutEmptyBytes(t *testing.T) {\n\tm := NewMap()\n\tb := m.PutEmptyBytes(\"k\")\n\tbv, ok := m.Get(\"k\")\n\tassert.True(t, ok)\n\tassert.Equal(t, []byte(nil), bv.Bytes().AsRaw())\n\tb.FromRaw([]byte{1, 2, 3})\n\tbv, ok = m.Get(\"k\")\n\tassert.True(t, ok)\n\tassert.Equal(t, []byte{1, 2, 3}, bv.Bytes().AsRaw())\n\n\tm.PutEmptyBytes(\"k\")\n\tbv, ok = m.Get(\"k\")\n\tassert.True(t, ok)\n\tassert.Equal(t, []byte(nil), bv.Bytes().AsRaw())\n\tbv.Bytes().FromRaw([]byte{3, 2, 1})\n\tbv, ok = m.Get(\"k\")\n\tassert.True(t, ok)\n\tassert.Equal(t, []byte{3, 2, 1}, bv.Bytes().AsRaw())\n}\n\nfunc TestMapWithEmpty(t *testing.T) {\n\torigWithNil := []internal.KeyValue{\n\t\t{},\n\t\t{\n\t\t\tKey:   \"test_key\",\n\t\t\tValue: internal.AnyValue{Value: &internal.AnyValue_StringValue{StringValue: \"test_value\"}},\n\t\t},\n\t\t{\n\t\t\tKey:   \"test_key2\",\n\t\t\tValue: internal.AnyValue{Value: nil},\n\t\t},\n\t}\n\tsm := newMap(&origWithNil, internal.NewState())\n\tval, exist := sm.Get(\"test_key\")\n\tassert.True(t, exist)\n\tassert.Equal(t, ValueTypeStr, val.Type())\n\tassert.Equal(t, \"test_value\", val.Str())\n\n\tval, exist = sm.Get(\"test_key2\")\n\tassert.True(t, exist)\n\tassert.Equal(t, ValueTypeEmpty, val.Type())\n\tassert.Empty(t, val.Str())\n\n\tsm.PutStr(\"other_key_string\", \"other_value\")\n\tval, exist = sm.Get(\"other_key_string\")\n\tassert.True(t, exist)\n\tassert.Equal(t, ValueTypeStr, val.Type())\n\tassert.Equal(t, \"other_value\", val.Str())\n\n\tsm.PutInt(\"other_key_int\", 123)\n\tval, exist = sm.Get(\"other_key_int\")\n\tassert.True(t, exist)\n\tassert.Equal(t, ValueTypeInt, val.Type())\n\tassert.EqualValues(t, 123, val.Int())\n\n\tsm.PutDouble(\"other_key_double\", 1.23)\n\tval, exist = sm.Get(\"other_key_double\")\n\tassert.True(t, exist)\n\tassert.Equal(t, ValueTypeDouble, val.Type())\n\tassert.InDelta(t, 1.23, val.Double(), 0.01)\n\n\tsm.PutBool(\"other_key_bool\", true)\n\tval, exist = sm.Get(\"other_key_bool\")\n\tassert.True(t, exist)\n\tassert.Equal(t, ValueTypeBool, val.Type())\n\tassert.True(t, val.Bool())\n\n\tsm.PutEmptyBytes(\"other_key_bytes\").FromRaw([]byte{7, 8, 9})\n\tval, exist = sm.Get(\"other_key_bytes\")\n\tassert.True(t, exist)\n\tassert.Equal(t, ValueTypeBytes, val.Type())\n\tassert.Equal(t, []byte{7, 8, 9}, val.Bytes().AsRaw())\n\n\tsm.PutStr(\"another_key_string\", \"another_value\")\n\tval, exist = sm.Get(\"another_key_string\")\n\tassert.True(t, exist)\n\tassert.Equal(t, ValueTypeStr, val.Type())\n\tassert.Equal(t, \"another_value\", val.Str())\n\n\tsm.PutInt(\"another_key_int\", 456)\n\tval, exist = sm.Get(\"another_key_int\")\n\tassert.True(t, exist)\n\tassert.Equal(t, ValueTypeInt, val.Type())\n\tassert.EqualValues(t, 456, val.Int())\n\n\tsm.PutDouble(\"another_key_double\", 4.56)\n\tval, exist = sm.Get(\"another_key_double\")\n\tassert.True(t, exist)\n\tassert.Equal(t, ValueTypeDouble, val.Type())\n\tassert.InDelta(t, 4.56, val.Double(), 0.01)\n\n\tsm.PutBool(\"another_key_bool\", false)\n\tval, exist = sm.Get(\"another_key_bool\")\n\tassert.True(t, exist)\n\tassert.Equal(t, ValueTypeBool, val.Type())\n\tassert.False(t, val.Bool())\n\n\tsm.PutEmptyBytes(\"another_key_bytes\").FromRaw([]byte{1})\n\tval, exist = sm.Get(\"another_key_bytes\")\n\tassert.True(t, exist)\n\tassert.Equal(t, ValueTypeBytes, val.Type())\n\tassert.Equal(t, []byte{1}, val.Bytes().AsRaw())\n\n\tassert.True(t, sm.Remove(\"other_key_string\"))\n\tassert.True(t, sm.Remove(\"other_key_int\"))\n\tassert.True(t, sm.Remove(\"other_key_double\"))\n\tassert.True(t, sm.Remove(\"other_key_bool\"))\n\tassert.True(t, sm.Remove(\"other_key_bytes\"))\n\tassert.True(t, sm.Remove(\"another_key_string\"))\n\tassert.True(t, sm.Remove(\"another_key_int\"))\n\tassert.True(t, sm.Remove(\"another_key_double\"))\n\tassert.True(t, sm.Remove(\"another_key_bool\"))\n\tassert.True(t, sm.Remove(\"another_key_bytes\"))\n\n\tassert.False(t, sm.Remove(\"other_key_string\"))\n\tassert.False(t, sm.Remove(\"another_key_string\"))\n\n\t// Test that the initial key is still there.\n\tval, exist = sm.Get(\"test_key\")\n\tassert.True(t, exist)\n\tassert.Equal(t, ValueTypeStr, val.Type())\n\tassert.Equal(t, \"test_value\", val.Str())\n\n\tval, exist = sm.Get(\"test_key2\")\n\tassert.True(t, exist)\n\tassert.Equal(t, ValueTypeEmpty, val.Type())\n\tassert.Empty(t, val.Str())\n\n\t_, exist = sm.Get(\"test_key3\")\n\tassert.False(t, exist)\n}\n\nfunc TestMapIterationNil(t *testing.T) {\n\tNewMap().Range(func(string, Value) bool {\n\t\t// Fail if any element is returned\n\t\tt.Fail()\n\t\treturn true\n\t})\n}\n\nfunc TestMap_Range(t *testing.T) {\n\trawMap := map[string]any{\n\t\t\"k_string\": \"123\",\n\t\t\"k_int\":    int64(123),\n\t\t\"k_double\": float64(1.23),\n\t\t\"k_bool\":   true,\n\t\t\"k_empty\":  nil,\n\t}\n\tam := NewMap()\n\trequire.NoError(t, am.FromRaw(rawMap))\n\tassert.Equal(t, 5, am.Len())\n\n\tcalls := 0\n\tam.Range(func(string, Value) bool {\n\t\tcalls++\n\t\treturn false\n\t})\n\tassert.Equal(t, 1, calls)\n\n\tam.Range(func(k string, v Value) bool {\n\t\tassert.Equal(t, rawMap[k], v.AsRaw())\n\t\tdelete(rawMap, k)\n\t\treturn true\n\t})\n\tassert.Empty(t, rawMap)\n}\n\nfunc TestMap_All(t *testing.T) {\n\trawMap := map[string]any{\n\t\t\"k_string\": \"123\",\n\t\t\"k_int\":    int64(123),\n\t\t\"k_double\": float64(1.23),\n\t\t\"k_bool\":   true,\n\t\t\"k_empty\":  nil,\n\t}\n\tam := NewMap()\n\trequire.NoError(t, am.FromRaw(rawMap))\n\tassert.Equal(t, 5, am.Len())\n\n\tcalls := 0\n\tfor range am.All() {\n\t\tcalls++\n\t}\n\tassert.Equal(t, am.Len(), calls)\n\n\tfor k, v := range am.All() {\n\t\tassert.Equal(t, rawMap[k], v.AsRaw())\n\t\tdelete(rawMap, k)\n\t}\n\tassert.Empty(t, rawMap)\n}\n\nfunc TestMap_FromRaw(t *testing.T) {\n\tam := NewMap()\n\trequire.NoError(t, am.FromRaw(map[string]any{}))\n\tassert.Equal(t, 0, am.Len())\n\tam.PutEmpty(\"k\")\n\tassert.Equal(t, 1, am.Len())\n\n\trequire.NoError(t, am.FromRaw(nil))\n\tassert.Equal(t, 0, am.Len())\n\tam.PutEmpty(\"k\")\n\tassert.Equal(t, 1, am.Len())\n\n\trequire.NoError(t, am.FromRaw(map[string]any{\n\t\t\"k_string\": \"123\",\n\t\t\"k_int\":    123,\n\t\t\"k_double\": 1.23,\n\t\t\"k_bool\":   true,\n\t\t\"k_null\":   nil,\n\t\t\"k_bytes\":  []byte{1, 2, 3},\n\t\t\"k_slice\":  []any{1, 2.1, \"val\"},\n\t\t\"k_map\": map[string]any{\n\t\t\t\"k_int\":    1,\n\t\t\t\"k_string\": \"val\",\n\t\t},\n\t}))\n\tassert.Equal(t, 8, am.Len())\n\tv, ok := am.Get(\"k_string\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"123\", v.Str())\n\tv, ok = am.Get(\"k_int\")\n\tassert.True(t, ok)\n\tassert.Equal(t, int64(123), v.Int())\n\tv, ok = am.Get(\"k_double\")\n\tassert.True(t, ok)\n\tassert.InDelta(t, 1.23, v.Double(), 0.01)\n\tv, ok = am.Get(\"k_null\")\n\tassert.True(t, ok)\n\tassert.Equal(t, ValueTypeEmpty, v.Type())\n\tv, ok = am.Get(\"k_bytes\")\n\tassert.True(t, ok)\n\tassert.Equal(t, []byte{1, 2, 3}, v.Bytes().AsRaw())\n\tv, ok = am.Get(\"k_slice\")\n\tassert.True(t, ok)\n\tassert.Equal(t, []any{int64(1), 2.1, \"val\"}, v.Slice().AsRaw())\n\tv, ok = am.Get(\"k_map\")\n\tassert.True(t, ok)\n\tassert.Equal(t, map[string]any{\n\t\t\"k_int\":    int64(1),\n\t\t\"k_string\": \"val\",\n\t}, v.Map().AsRaw())\n}\n\nfunc TestMap_MoveTo(t *testing.T) {\n\tdest := NewMap()\n\t// Test MoveTo to empty\n\tNewMap().MoveTo(dest)\n\tassert.Equal(t, 0, dest.Len())\n\n\t// Test MoveTo larger slice\n\tsrc := Map(internal.GenTestMapWrapper())\n\tsrc.MoveTo(dest)\n\tassert.Equal(t, Map(internal.GenTestMapWrapper()), dest)\n\tassert.Equal(t, 0, src.Len())\n\n\t// Test MoveTo from empty to non-empty\n\tNewMap().MoveTo(dest)\n\tassert.Equal(t, 0, dest.Len())\n\n\tdest.PutStr(\"k\", \"v\")\n\tdest.MoveTo(dest)\n\tassert.Equal(t, 1, dest.Len())\n\tassert.Equal(t, map[string]any{\"k\": \"v\"}, dest.AsRaw())\n}\n\nfunc TestMap_CopyTo(t *testing.T) {\n\tdest := NewMap()\n\t// Test CopyTo to empty\n\tNewMap().CopyTo(dest)\n\tassert.Equal(t, 0, dest.Len())\n\n\t// Test CopyTo larger slice\n\tMap(internal.GenTestMapWrapper()).CopyTo(dest)\n\tassert.Equal(t, Map(internal.GenTestMapWrapper()), dest)\n\n\t// Test CopyTo same size slice\n\tMap(internal.GenTestMapWrapper()).CopyTo(dest)\n\tassert.Equal(t, Map(internal.GenTestMapWrapper()), dest)\n\n\t// Test CopyTo with an empty Value in the destination\n\t(*dest.getOrig())[0].Value = internal.AnyValue{}\n\tMap(internal.GenTestMapWrapper()).CopyTo(dest)\n\tassert.Equal(t, Map(internal.GenTestMapWrapper()), dest)\n\n\t// Test CopyTo same size slice\n\tdest.CopyTo(dest)\n\tassert.Equal(t, Map(internal.GenTestMapWrapper()), dest)\n}\n\nfunc TestMap_CopyToAndEnsureCapacity(t *testing.T) {\n\tdest := NewMap()\n\tsrc := Map(internal.GenTestMapWrapper())\n\tdest.EnsureCapacity(src.Len())\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, Map(internal.GenTestMapWrapper()), dest)\n}\n\nfunc TestMap_EnsureCapacity_Zero(t *testing.T) {\n\tam := NewMap()\n\tam.EnsureCapacity(0)\n\tassert.Equal(t, 0, am.Len())\n\tassert.Equal(t, 0, cap(*am.getOrig()))\n}\n\nfunc TestMap_EnsureCapacity(t *testing.T) {\n\tam := NewMap()\n\tam.EnsureCapacity(5)\n\tassert.Equal(t, 0, am.Len())\n\tassert.Equal(t, 5, cap(*am.getOrig()))\n\tam.EnsureCapacity(3)\n\tassert.Equal(t, 0, am.Len())\n\tassert.Equal(t, 5, cap(*am.getOrig()))\n\tam.EnsureCapacity(8)\n\tassert.Equal(t, 0, am.Len())\n\tassert.Equal(t, 8, cap(*am.getOrig()))\n}\n\nfunc TestMap_EnsureCapacity_Existing(t *testing.T) {\n\tam := NewMap()\n\tam.PutStr(\"foo\", \"bar\")\n\n\tassert.Equal(t, 1, am.Len())\n\n\t// Add more capacity.\n\tam.EnsureCapacity(5)\n\n\t// Ensure previously existing element is still there.\n\tassert.Equal(t, 1, am.Len())\n\tv, ok := am.Get(\"foo\")\n\tassert.Equal(t, \"bar\", v.Str())\n\tassert.True(t, ok)\n\n\tassert.Equal(t, 5, cap(*am.getOrig()))\n\n\t// Add one more element.\n\tam.PutStr(\"abc\", \"xyz\")\n\n\t// Verify that both elements are there.\n\tassert.Equal(t, 2, am.Len())\n\n\tv, ok = am.Get(\"foo\")\n\tassert.Equal(t, \"bar\", v.Str())\n\tassert.True(t, ok)\n\n\tv, ok = am.Get(\"abc\")\n\tassert.Equal(t, \"xyz\", v.Str())\n\tassert.True(t, ok)\n}\n\nfunc TestMap_Clear(t *testing.T) {\n\tam := NewMap()\n\tassert.Nil(t, *am.getOrig())\n\tam.Clear()\n\tassert.Nil(t, *am.getOrig())\n\tam.EnsureCapacity(5)\n\tassert.NotNil(t, *am.getOrig())\n\tam.Clear()\n\tassert.Nil(t, *am.getOrig())\n}\n\nfunc TestMap_RemoveIf(t *testing.T) {\n\tam := NewMap()\n\tam.PutStr(\"k_string\", \"123\")\n\tam.PutInt(\"k_int\", int64(123))\n\tam.PutDouble(\"k_double\", float64(1.23))\n\tam.PutBool(\"k_bool\", true)\n\tam.PutEmpty(\"k_empty\")\n\n\tassert.Equal(t, 5, am.Len())\n\n\tam.RemoveIf(func(key string, val Value) bool {\n\t\treturn key == \"k_int\" || val.Type() == ValueTypeBool\n\t})\n\tassert.Equal(t, 3, am.Len())\n\t_, exists := am.Get(\"k_string\")\n\tassert.True(t, exists)\n\t_, exists = am.Get(\"k_int\")\n\tassert.False(t, exists)\n\t_, exists = am.Get(\"k_double\")\n\tassert.True(t, exists)\n\t_, exists = am.Get(\"k_bool\")\n\tassert.False(t, exists)\n\t_, exists = am.Get(\"k_empty\")\n\tassert.True(t, exists)\n}\n\nfunc TestMap_RemoveIfAll(t *testing.T) {\n\tam := Map(internal.GenTestMapWrapper())\n\tassert.Equal(t, 5, am.Len())\n\tam.RemoveIf(func(string, Value) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, am.Len())\n}\n\nfunc generateTestEmptyMap(t *testing.T) Map {\n\tm := NewMap()\n\tassert.NoError(t, m.FromRaw(map[string]any{\"k\": map[string]any(nil)}))\n\treturn m\n}\n\nfunc generateTestEmptySlice(t *testing.T) Map {\n\tm := NewMap()\n\tassert.NoError(t, m.FromRaw(map[string]any{\"k\": []any(nil)}))\n\treturn m\n}\n\nfunc generateTestStringMap(t *testing.T) Map {\n\tm := NewMap()\n\tassert.NoError(t, m.FromRaw(map[string]any{\"k\": \"v\"}))\n\treturn m\n}\n\nfunc generateTestIntMap(t *testing.T) Map {\n\tm := NewMap()\n\tassert.NoError(t, m.FromRaw(map[string]any{\"k\": 123}))\n\treturn m\n}\n\nfunc generateTestDoubleMap(t *testing.T) Map {\n\tm := NewMap()\n\tassert.NoError(t, m.FromRaw(map[string]any{\"k\": 12.3}))\n\treturn m\n}\n\nfunc generateTestBoolMap(t *testing.T) Map {\n\tm := NewMap()\n\tassert.NoError(t, m.FromRaw(map[string]any{\"k\": true}))\n\treturn m\n}\n\nfunc generateTestBytesMap(t *testing.T) Map {\n\tm := NewMap()\n\tassert.NoError(t, m.FromRaw(map[string]any{\"k\": []byte{1, 2, 3, 4, 5}}))\n\treturn m\n}\n\nfunc TestInvalidMap(t *testing.T) {\n\tv := Map{}\n\n\ttestFunc := func(string, Value) bool {\n\t\treturn true\n\t}\n\n\tassert.Panics(t, func() { v.Clear() })\n\tassert.Panics(t, func() { v.EnsureCapacity(1) })\n\tassert.Panics(t, func() { v.Get(\"foo\") })\n\tassert.Panics(t, func() { v.Remove(\"foo\") })\n\tassert.Panics(t, func() { v.RemoveIf(testFunc) })\n\tassert.Panics(t, func() { v.PutEmpty(\"foo\") })\n\tassert.Panics(t, func() { v.GetOrPutEmpty(\"foo\") })\n\tassert.Panics(t, func() { v.PutStr(\"foo\", \"bar\") })\n\tassert.Panics(t, func() { v.PutInt(\"foo\", 1) })\n\tassert.Panics(t, func() { v.PutDouble(\"foo\", 1.1) })\n\tassert.Panics(t, func() { v.PutBool(\"foo\", true) })\n\tassert.Panics(t, func() { v.PutEmptyBytes(\"foo\") })\n\tassert.Panics(t, func() { v.PutEmptyMap(\"foo\") })\n\tassert.Panics(t, func() { v.PutEmptySlice(\"foo\") })\n\tassert.Panics(t, func() { v.Len() })\n\tassert.Panics(t, func() { v.Range(testFunc) })\n\tassert.Panics(t, func() { v.CopyTo(NewMap()) })\n\tassert.Panics(t, func() { v.AsRaw() })\n\tassert.Panics(t, func() { _ = v.FromRaw(map[string]any{\"foo\": \"bar\"}) })\n}\n\nfunc TestMapEqual(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname       string\n\t\tval        Map\n\t\tcomparison Map\n\t\texpected   bool\n\t}{\n\t\t{\n\t\t\tname:       \"with two empty maps\",\n\t\t\tval:        NewMap(),\n\t\t\tcomparison: NewMap(),\n\t\t\texpected:   true,\n\t\t},\n\t\t{\n\t\t\tname: \"with two equal values\",\n\t\t\tval: func() Map {\n\t\t\t\tm := NewMap()\n\t\t\t\tm.PutStr(\"hello\", \"world\")\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\tcomparison: func() Map {\n\t\t\t\tm := NewMap()\n\t\t\t\tm.PutStr(\"hello\", \"world\")\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname: \"with multiple equal values\",\n\t\t\tval: func() Map {\n\t\t\t\tm := NewMap()\n\t\t\t\tm.PutStr(\"hello\", \"world\")\n\t\t\t\tm.PutStr(\"bonjour\", \"monde\")\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\tcomparison: func() Map {\n\t\t\t\tm := NewMap()\n\t\t\t\tm.PutStr(\"hello\", \"world\")\n\t\t\t\tm.PutStr(\"bonjour\", \"monde\")\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname: \"with two different values\",\n\t\t\tval: func() Map {\n\t\t\t\tm := NewMap()\n\t\t\t\tm.PutStr(\"hello\", \"world\")\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\tcomparison: func() Map {\n\t\t\t\tm := NewMap()\n\t\t\t\tm.PutStr(\"bonjour\", \"monde\")\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with the same key and different values\",\n\t\t\tval: func() Map {\n\t\t\t\tm := NewMap()\n\t\t\t\tm.PutStr(\"hello\", \"world\")\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\tcomparison: func() Map {\n\t\t\t\tm := NewMap()\n\t\t\t\tm.PutStr(\"hello\", \"monde\")\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with multiple different values\",\n\t\t\tval: func() Map {\n\t\t\t\tm := NewMap()\n\t\t\t\tm.PutStr(\"hello\", \"world\")\n\t\t\t\tm.PutStr(\"bonjour\", \"monde\")\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\tcomparison: func() Map {\n\t\t\t\tm := NewMap()\n\t\t\t\tm.PutStr(\"question\", \"unknown\")\n\t\t\t\tm.PutStr(\"answer\", \"42\")\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\texpected: false,\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tassert.Equal(t, tt.expected, tt.val.Equal(tt.comparison))\n\t\t})\n\t}\n}\n\nfunc BenchmarkMapEqual(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\tm := NewMap()\n\tm.PutStr(\"hello\", \"world\")\n\tcmp := NewMap()\n\tcmp.PutStr(\"hello\", \"world\")\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\t_ = m.Equal(cmp)\n\t}\n}\n"
  },
  {
    "path": "pdata/pcommon/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pcommon\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "pdata/pcommon/slice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pcommon // import \"go.opentelemetry.io/collector/pdata/pcommon\"\n\nimport (\n\t\"go.uber.org/multierr\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// AsRaw return []any copy of the Slice.\nfunc (es Slice) AsRaw() []any {\n\trawSlice := make([]any, 0, es.Len())\n\tfor i := 0; i < es.Len(); i++ {\n\t\trawSlice = append(rawSlice, es.At(i).AsRaw())\n\t}\n\treturn rawSlice\n}\n\n// FromRaw copies []any into the Slice.\nfunc (es Slice) FromRaw(rawSlice []any) error {\n\tes.getState().AssertMutable()\n\tif len(rawSlice) == 0 {\n\t\t*es.getOrig() = nil\n\t\treturn nil\n\t}\n\tvar errs error\n\torigs := make([]internal.AnyValue, len(rawSlice))\n\tfor ix, iv := range rawSlice {\n\t\terrs = multierr.Append(errs, newValue(&origs[ix], es.getState()).FromRaw(iv))\n\t}\n\t*es.getOrig() = origs\n\treturn errs\n}\n\n// Equal checks equality with another Slice\nfunc (es Slice) Equal(val Slice) bool {\n\tif es.Len() != val.Len() {\n\t\treturn false\n\t}\n\n\tfor i := 0; i < es.Len(); i++ {\n\t\tif !es.At(i).Equal(val.At(i)) {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n"
  },
  {
    "path": "pdata/pcommon/slice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pcommon\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc TestSlice_AsFromRaw(t *testing.T) {\n\tes := NewSlice()\n\tassert.Equal(t, 0, es.Len())\n\n\traw := []any{int64(1), float64(2.3), true, \"test\", []any{\"other\"}, map[string]any{\"key\": \"value\", \"int\": int64(2)}}\n\trequire.NoError(t, es.FromRaw(raw))\n\tassert.Equal(t, 6, es.Len())\n\tassert.Equal(t, raw, es.AsRaw())\n}\n\nfunc TestInvalidSlice(t *testing.T) {\n\tes := Slice{}\n\n\tassert.Panics(t, func() { es.Len() })\n\tassert.Panics(t, func() { es.At(0) })\n\tassert.Panics(t, func() { es.CopyTo(Slice{}) })\n\tassert.Panics(t, func() { es.EnsureCapacity(1) })\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(Slice{}) })\n\tassert.Panics(t, func() { es.RemoveIf(func(Value) bool { return false }) })\n\tassert.Panics(t, func() { es.AsRaw() })\n\tassert.Panics(t, func() { _ = es.FromRaw([]any{3}) })\n}\n\nfunc TestSliceEqual(t *testing.T) {\n\tes := NewSlice()\n\tes2 := NewSlice()\n\tassert.True(t, es.Equal(es2))\n\n\tv := es.AppendEmpty()\n\tv.SetStr(\"test\")\n\tassert.False(t, es.Equal(es2))\n\n\tv = es2.AppendEmpty()\n\tv.SetStr(\"test\")\n\tassert.True(t, es.Equal(es2))\n}\n\nfunc BenchmarkSliceEqual(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\n\tes := NewSlice()\n\tv := es.AppendEmpty()\n\tv.SetStr(\"test\")\n\tcmp := NewSlice()\n\tv = cmp.AppendEmpty()\n\tv.SetStr(\"test\")\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\t_ = es.Equal(cmp)\n\t}\n}\n"
  },
  {
    "path": "pdata/pcommon/spanid.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pcommon // import \"go.opentelemetry.io/collector/pdata/pcommon\"\nimport (\n\t\"encoding/hex\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nvar emptySpanID = SpanID([8]byte{})\n\n// SpanID is span identifier.\ntype SpanID [8]byte\n\n// NewSpanIDEmpty returns a new empty (all zero bytes) SpanID.\nfunc NewSpanIDEmpty() SpanID {\n\treturn emptySpanID\n}\n\n// String returns string representation of the SpanID.\n//\n// Important: Don't rely on this method to get a string identifier of SpanID,\n// Use hex.EncodeToString explicitly instead.\n// This method meant to implement Stringer interface for display purposes only.\nfunc (ms SpanID) String() string {\n\tif ms.IsEmpty() {\n\t\treturn \"\"\n\t}\n\treturn hex.EncodeToString(ms[:])\n}\n\n// IsEmpty returns true if id doesn't contain at least one non-zero byte.\nfunc (ms SpanID) IsEmpty() bool {\n\treturn internal.SpanID(ms).IsEmpty()\n}\n"
  },
  {
    "path": "pdata/pcommon/spanid_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pcommon\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestSpanID(t *testing.T) {\n\tsid := SpanID([8]byte{1, 2, 3, 4, 4, 3, 2, 1})\n\tassert.Equal(t, [8]byte{1, 2, 3, 4, 4, 3, 2, 1}, [8]byte(sid))\n\tassert.False(t, sid.IsEmpty())\n}\n\nfunc TestNewSpanIDEmpty(t *testing.T) {\n\tsid := NewSpanIDEmpty()\n\tassert.Equal(t, [8]byte{}, [8]byte(sid))\n\tassert.True(t, sid.IsEmpty())\n}\n\nfunc TestSpanIDString(t *testing.T) {\n\tsid := SpanID([8]byte{})\n\tassert.Empty(t, sid.String())\n\n\tsid = SpanID([8]byte{0x12, 0x23, 0xAD, 0x12, 0x23, 0xAD, 0x12, 0x23})\n\tassert.Equal(t, \"1223ad1223ad1223\", sid.String())\n}\n\nfunc TestSpanIDImmutable(t *testing.T) {\n\tinitialBytes := [8]byte{0x12, 0x23, 0xAD, 0x12, 0x23, 0xAD, 0x12, 0x23}\n\tsid := SpanID(initialBytes)\n\tassert.Equal(t, SpanID(initialBytes), sid)\n\n\t// Get the bytes and try to mutate.\n\tsid[4] = 0x89\n\n\t// Does not change the already created SpanID.\n\tassert.NotEqual(t, SpanID(initialBytes), sid)\n}\n"
  },
  {
    "path": "pdata/pcommon/timestamp.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pcommon // import \"go.opentelemetry.io/collector/pdata/pcommon\"\n\nimport (\n\t\"time\"\n)\n\n// Timestamp is a time specified as UNIX Epoch time in nanoseconds since\n// 1970-01-01 00:00:00 +0000 UTC.\ntype Timestamp uint64\n\n// NewTimestampFromTime constructs a new Timestamp from the provided time.Time.\nfunc NewTimestampFromTime(t time.Time) Timestamp {\n\treturn Timestamp(uint64(t.UnixNano()))\n}\n\n// AsTime converts this to a time.Time.\nfunc (ts Timestamp) AsTime() time.Time {\n\treturn time.Unix(0, int64(ts)).UTC()\n}\n\n// String returns the string representation of this in UTC.\nfunc (ts Timestamp) String() string {\n\treturn ts.AsTime().String()\n}\n"
  },
  {
    "path": "pdata/pcommon/timestamp_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pcommon\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestUnixNanosConverters(t *testing.T) {\n\tt1 := time.Date(2020, 3, 24, 1, 13, 23, 789, time.UTC)\n\ttun := Timestamp(t1.UnixNano())\n\n\tassert.EqualValues(t, uint64(1585012403000000789), tun)\n\tassert.Equal(t, tun, NewTimestampFromTime(t1))\n\tassert.Equal(t, t1, NewTimestampFromTime(t1).AsTime())\n\tassert.Equal(t, \"2020-03-24 01:13:23.000000789 +0000 UTC\", t1.String())\n}\n\nfunc TestZeroTimestamp(t *testing.T) {\n\tassert.Equal(t, time.Unix(0, 0).UTC(), Timestamp(0).AsTime())\n\tassert.Zero(t, NewTimestampFromTime(time.Unix(0, 0).UTC()))\n\tassert.Equal(t, \"1970-01-01 00:00:00 +0000 UTC\", Timestamp(0).String())\n}\n"
  },
  {
    "path": "pdata/pcommon/trace_state.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pcommon // import \"go.opentelemetry.io/collector/pdata/pcommon\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// TraceState represents the trace state from the w3c-trace-context.\n//\n// Must use NewTraceState function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype TraceState internal.TraceStateWrapper\n\nfunc NewTraceState() TraceState {\n\treturn TraceState(internal.NewTraceStateWrapper(new(string), internal.NewState()))\n}\n\nfunc (ms TraceState) getOrig() *string {\n\treturn internal.GetTraceStateOrig(internal.TraceStateWrapper(ms))\n}\n\nfunc (ms TraceState) getState() *internal.State {\n\treturn internal.GetTraceStateState(internal.TraceStateWrapper(ms))\n}\n\n// AsRaw returns the string representation of the tracestate in w3c-trace-context format: https://www.w3.org/TR/trace-context/#tracestate-header\nfunc (ms TraceState) AsRaw() string {\n\treturn *ms.getOrig()\n}\n\n// FromRaw copies the string representation in w3c-trace-context format of the tracestate into this TraceState.\nfunc (ms TraceState) FromRaw(v string) {\n\tms.getState().AssertMutable()\n\t*ms.getOrig() = v\n}\n\n// MoveTo moves the TraceState instance overriding the destination\n// and resetting the current instance to its zero value.\nfunc (ms TraceState) MoveTo(dest TraceState) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = *ms.getOrig()\n\t*ms.getOrig() = \"\"\n}\n\n// CopyTo copies the TraceState instance overriding the destination.\nfunc (ms TraceState) CopyTo(dest TraceState) {\n\tdest.getState().AssertMutable()\n\t*dest.getOrig() = *ms.getOrig()\n}\n"
  },
  {
    "path": "pdata/pcommon/trace_state_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pcommon\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestTraceState_MoveTo(t *testing.T) {\n\tms := TraceState(internal.GenTestTraceStateWrapper())\n\tdest := NewTraceState()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewTraceState(), ms)\n\tassert.Equal(t, TraceState(internal.GenTestTraceStateWrapper()), dest)\n\n\tdest.MoveTo(dest)\n\tassert.Equal(t, TraceState(internal.GenTestTraceStateWrapper()), dest)\n}\n\nfunc TestTraceState_CopyTo(t *testing.T) {\n\tms := NewTraceState()\n\torig := NewTraceState()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = TraceState(internal.GenTestTraceStateWrapper())\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n}\n\nfunc TestTraceState_FromRaw_AsRaw(t *testing.T) {\n\tms := NewTraceState()\n\tassert.Empty(t, ms.AsRaw())\n\tms.FromRaw(\"congo=t61rcWkgMzE\")\n\tassert.Equal(t, \"congo=t61rcWkgMzE\", ms.AsRaw())\n}\n\nfunc TestInvalidTraceState(t *testing.T) {\n\tv := TraceState{}\n\n\tassert.Panics(t, func() { v.AsRaw() })\n\tassert.Panics(t, func() { v.FromRaw(\"\") })\n\tassert.Panics(t, func() { v.MoveTo(TraceState{}) })\n\tassert.Panics(t, func() { v.CopyTo(TraceState{}) })\n}\n"
  },
  {
    "path": "pdata/pcommon/traceid.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pcommon // import \"go.opentelemetry.io/collector/pdata/pcommon\"\n\nimport (\n\t\"encoding/hex\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nvar emptyTraceID = TraceID([16]byte{})\n\n// TraceID is a trace identifier.\ntype TraceID [16]byte\n\n// NewTraceIDEmpty returns a new empty (all zero bytes) TraceID.\nfunc NewTraceIDEmpty() TraceID {\n\treturn emptyTraceID\n}\n\n// String returns string representation of the TraceID.\n//\n// Important: Don't rely on this method to get a string identifier of TraceID.\n// Use hex.EncodeToString explicitly instead.\n// This method meant to implement Stringer interface for display purposes only.\nfunc (ms TraceID) String() string {\n\tif ms.IsEmpty() {\n\t\treturn \"\"\n\t}\n\treturn hex.EncodeToString(ms[:])\n}\n\n// IsEmpty returns true if id doesn't contain at least one non-zero byte.\nfunc (ms TraceID) IsEmpty() bool {\n\treturn internal.TraceID(ms).IsEmpty()\n}\n"
  },
  {
    "path": "pdata/pcommon/traceid_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pcommon\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestTraceID(t *testing.T) {\n\ttid := TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1})\n\tassert.Equal(t, [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1}, [16]byte(tid))\n\tassert.False(t, tid.IsEmpty())\n}\n\nfunc TestNewTraceIDEmpty(t *testing.T) {\n\ttid := NewTraceIDEmpty()\n\tassert.Equal(t, [16]byte{}, [16]byte(tid))\n\tassert.True(t, tid.IsEmpty())\n}\n\nfunc TestTraceIDString(t *testing.T) {\n\ttid := TraceID([16]byte{})\n\tassert.Empty(t, tid.String())\n\n\ttid = [16]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}\n\tassert.Equal(t, \"12345678123456781234567812345678\", tid.String())\n}\n\nfunc TestTraceIDImmutable(t *testing.T) {\n\tinitialBytes := [16]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}\n\ttid := TraceID(initialBytes)\n\tassert.Equal(t, TraceID(initialBytes), tid)\n\n\t// Get the bytes and try to mutate.\n\ttid[4] = 0x23\n\n\t// Does not change the already created TraceID.\n\tassert.NotEqual(t, TraceID(initialBytes), tid)\n}\n"
  },
  {
    "path": "pdata/pcommon/value.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pcommon // import \"go.opentelemetry.io/collector/pdata/pcommon\"\n\nimport (\n\t\"encoding/base64\"\n\t\"encoding/json\"\n\t\"fmt\"\n\t\"math\"\n\t\"strconv\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ValueType specifies the type of Value.\ntype ValueType int32\n\nconst (\n\tValueTypeEmpty ValueType = iota\n\tValueTypeStr\n\tValueTypeInt\n\tValueTypeDouble\n\tValueTypeBool\n\tValueTypeMap\n\tValueTypeSlice\n\tValueTypeBytes\n)\n\n// String returns the string representation of the ValueType.\nfunc (avt ValueType) String() string {\n\tswitch avt {\n\tcase ValueTypeEmpty:\n\t\treturn \"Empty\"\n\tcase ValueTypeStr:\n\t\treturn \"Str\"\n\tcase ValueTypeBool:\n\t\treturn \"Bool\"\n\tcase ValueTypeInt:\n\t\treturn \"Int\"\n\tcase ValueTypeDouble:\n\t\treturn \"Double\"\n\tcase ValueTypeMap:\n\t\treturn \"Map\"\n\tcase ValueTypeSlice:\n\t\treturn \"Slice\"\n\tcase ValueTypeBytes:\n\t\treturn \"Bytes\"\n\t}\n\treturn \"\"\n}\n\n// Value is a mutable cell containing any value. Typically used as an element of Map or Slice.\n// Must use one of NewValue+ functions below to create new instances.\n//\n// Intended to be passed by value since internally it is just a pointer to actual\n// value representation. For the same reason passing by value and calling setters\n// will modify the original, e.g.:\n//\n//\tfunc f1(val Value) { val.SetInt(234) }\n//\tfunc f2() {\n//\t    v := NewValueStr(\"a string\")\n//\t    f1(v)\n//\t    _ := v.Type() // this will return ValueTypeInt\n//\t}\n//\n// Important: zero-initialized instance is not valid for use. All Value functions below must\n// be called only on instances that are created via NewValue+ functions.\ntype Value internal.ValueWrapper\n\n// NewValueEmpty creates a new Value with an empty value.\nfunc NewValueEmpty() Value {\n\treturn newValue(&internal.AnyValue{}, internal.NewState())\n}\n\n// NewValueStr creates a new Value with the given string value.\nfunc NewValueStr(v string) Value {\n\tov := internal.NewAnyValueStringValue()\n\tov.StringValue = v\n\torig := internal.NewAnyValue()\n\torig.Value = ov\n\treturn newValue(orig, internal.NewState())\n}\n\n// NewValueInt creates a new Value with the given int64 value.\nfunc NewValueInt(v int64) Value {\n\tov := internal.NewAnyValueIntValue()\n\tov.IntValue = v\n\torig := internal.NewAnyValue()\n\torig.Value = ov\n\treturn newValue(orig, internal.NewState())\n}\n\n// NewValueDouble creates a new Value with the given float64 value.\nfunc NewValueDouble(v float64) Value {\n\tov := internal.NewAnyValueDoubleValue()\n\tov.DoubleValue = v\n\torig := internal.NewAnyValue()\n\torig.Value = ov\n\treturn newValue(orig, internal.NewState())\n}\n\n// NewValueBool creates a new Value with the given bool value.\nfunc NewValueBool(v bool) Value {\n\tov := internal.NewAnyValueBoolValue()\n\tov.BoolValue = v\n\torig := internal.NewAnyValue()\n\torig.Value = ov\n\treturn newValue(orig, internal.NewState())\n}\n\n// NewValueMap creates a new Value of map type.\nfunc NewValueMap() Value {\n\tov := internal.NewAnyValueKvlistValue()\n\tov.KvlistValue = internal.NewKeyValueList()\n\torig := internal.NewAnyValue()\n\torig.Value = ov\n\treturn newValue(orig, internal.NewState())\n}\n\n// NewValueSlice creates a new Value of array type.\nfunc NewValueSlice() Value {\n\tov := internal.NewAnyValueArrayValue()\n\tov.ArrayValue = internal.NewArrayValue()\n\torig := internal.NewAnyValue()\n\torig.Value = ov\n\treturn newValue(orig, internal.NewState())\n}\n\n// NewValueBytes creates a new empty Value of byte type.\nfunc NewValueBytes() Value {\n\tov := internal.NewAnyValueBytesValue()\n\torig := internal.NewAnyValue()\n\torig.Value = ov\n\treturn newValue(orig, internal.NewState())\n}\n\nfunc newValue(orig *internal.AnyValue, state *internal.State) Value {\n\treturn Value(internal.NewValueWrapper(orig, state))\n}\n\nfunc (v Value) getOrig() *internal.AnyValue {\n\treturn internal.GetValueOrig(internal.ValueWrapper(v))\n}\n\nfunc (v Value) getState() *internal.State {\n\treturn internal.GetValueState(internal.ValueWrapper(v))\n}\n\n// FromRaw sets the value from the given raw value.\n// Calling this function on zero-initialized Value will cause a panic.\nfunc (v Value) FromRaw(iv any) error {\n\tswitch tv := iv.(type) {\n\tcase nil:\n\t\tv.getOrig().Value = nil\n\tcase string:\n\t\tv.SetStr(tv)\n\tcase int:\n\t\tv.SetInt(int64(tv))\n\tcase int8:\n\t\tv.SetInt(int64(tv))\n\tcase int16:\n\t\tv.SetInt(int64(tv))\n\tcase int32:\n\t\tv.SetInt(int64(tv))\n\tcase int64:\n\t\tv.SetInt(tv)\n\tcase uint:\n\t\tv.SetInt(int64(tv))\n\tcase uint8:\n\t\tv.SetInt(int64(tv))\n\tcase uint16:\n\t\tv.SetInt(int64(tv))\n\tcase uint32:\n\t\tv.SetInt(int64(tv))\n\tcase uint64:\n\t\tv.SetInt(int64(tv))\n\tcase float32:\n\t\tv.SetDouble(float64(tv))\n\tcase float64:\n\t\tv.SetDouble(tv)\n\tcase bool:\n\t\tv.SetBool(tv)\n\tcase []byte:\n\t\tv.SetEmptyBytes().FromRaw(tv)\n\tcase map[string]any:\n\t\treturn v.SetEmptyMap().FromRaw(tv)\n\tcase []any:\n\t\treturn v.SetEmptySlice().FromRaw(tv)\n\tdefault:\n\t\treturn fmt.Errorf(\"<Invalid value type %T>\", tv)\n\t}\n\treturn nil\n}\n\n// Type returns the type of the value for this Value.\n// Calling this function on zero-initialized Value will cause a panic.\nfunc (v Value) Type() ValueType {\n\tswitch v.getOrig().Value.(type) {\n\tcase *internal.AnyValue_StringValue:\n\t\treturn ValueTypeStr\n\tcase *internal.AnyValue_BoolValue:\n\t\treturn ValueTypeBool\n\tcase *internal.AnyValue_IntValue:\n\t\treturn ValueTypeInt\n\tcase *internal.AnyValue_DoubleValue:\n\t\treturn ValueTypeDouble\n\tcase *internal.AnyValue_KvlistValue:\n\t\treturn ValueTypeMap\n\tcase *internal.AnyValue_ArrayValue:\n\t\treturn ValueTypeSlice\n\tcase *internal.AnyValue_BytesValue:\n\t\treturn ValueTypeBytes\n\t}\n\treturn ValueTypeEmpty\n}\n\n// Str returns the string value associated with this Value.\n// The shorter name is used instead of String to avoid implementing fmt.Stringer interface.\n// If the Type() is not ValueTypeStr then returns empty string.\nfunc (v Value) Str() string {\n\treturn v.getOrig().GetStringValue()\n}\n\n// Int returns the int64 value associated with this Value.\n// If the Type() is not ValueTypeInt then returns int64(0).\nfunc (v Value) Int() int64 {\n\treturn v.getOrig().GetIntValue()\n}\n\n// Double returns the float64 value associated with this Value.\n// If the Type() is not ValueTypeDouble then returns float64(0).\nfunc (v Value) Double() float64 {\n\treturn v.getOrig().GetDoubleValue()\n}\n\n// Bool returns the bool value associated with this Value.\n// If the Type() is not ValueTypeBool then returns false.\nfunc (v Value) Bool() bool {\n\treturn v.getOrig().GetBoolValue()\n}\n\n// Map returns the map value associated with this Value.\n// If the function is called on zero-initialized Value or if the Type() is not ValueTypeMap\n// then it returns an invalid map. Note that using such map can cause panic.\nfunc (v Value) Map() Map {\n\tkvlist := v.getOrig().GetKvlistValue()\n\tif kvlist == nil {\n\t\treturn Map{}\n\t}\n\treturn newMap(&kvlist.Values, internal.GetValueState(internal.ValueWrapper(v)))\n}\n\n// Slice returns the slice value associated with this Value.\n// If the function is called on zero-initialized Value or if the Type() is not ValueTypeSlice\n// then returns an invalid slice. Note that using such slice can cause panic.\nfunc (v Value) Slice() Slice {\n\tarr := v.getOrig().GetArrayValue()\n\tif arr == nil {\n\t\treturn Slice{}\n\t}\n\treturn newSlice(&arr.Values, internal.GetValueState(internal.ValueWrapper(v)))\n}\n\n// Bytes returns the ByteSlice value associated with this Value.\n// If the function is called on zero-initialized Value or if the Type() is not ValueTypeBytes\n// then returns an invalid ByteSlice object. Note that using such slice can cause panic.\nfunc (v Value) Bytes() ByteSlice {\n\tbv, ok := v.getOrig().GetValue().(*internal.AnyValue_BytesValue)\n\tif !ok {\n\t\treturn ByteSlice{}\n\t}\n\treturn ByteSlice(internal.NewByteSliceWrapper(&bv.BytesValue, internal.GetValueState(internal.ValueWrapper(v))))\n}\n\n// SetStr replaces the string value associated with this Value,\n// it also changes the type to be ValueTypeStr.\n// The shorter name is used instead of SetString to avoid implementing\n// fmt.Stringer interface by the corresponding getter method.\n// Calling this function on zero-initialized Value will cause a panic.\nfunc (v Value) SetStr(sv string) {\n\tv.getState().AssertMutable()\n\t// Delete everything but the AnyValue object itself.\n\tinternal.DeleteAnyValue(v.getOrig(), false)\n\tov := internal.NewAnyValueStringValue()\n\tov.StringValue = sv\n\tv.getOrig().Value = ov\n}\n\n// SetInt replaces the int64 value associated with this Value,\n// it also changes the type to be ValueTypeInt.\n// Calling this function on zero-initialized Value will cause a panic.\nfunc (v Value) SetInt(iv int64) {\n\tv.getState().AssertMutable()\n\t// Delete everything but the AnyValue object itself.\n\tinternal.DeleteAnyValue(v.getOrig(), false)\n\tov := internal.NewAnyValueIntValue()\n\tov.IntValue = iv\n\tv.getOrig().Value = ov\n}\n\n// SetDouble replaces the float64 value associated with this Value,\n// it also changes the type to be ValueTypeDouble.\n// Calling this function on zero-initialized Value will cause a panic.\nfunc (v Value) SetDouble(dv float64) {\n\tv.getState().AssertMutable()\n\t// Delete everything but the AnyValue object itself.\n\tinternal.DeleteAnyValue(v.getOrig(), false)\n\tov := internal.NewAnyValueDoubleValue()\n\tov.DoubleValue = dv\n\tv.getOrig().Value = ov\n}\n\n// SetBool replaces the bool value associated with this Value,\n// it also changes the type to be ValueTypeBool.\n// Calling this function on zero-initialized Value will cause a panic.\nfunc (v Value) SetBool(bv bool) {\n\tv.getState().AssertMutable()\n\t// Delete everything but the AnyValue object itself.\n\tinternal.DeleteAnyValue(v.getOrig(), false)\n\tov := internal.NewAnyValueBoolValue()\n\tov.BoolValue = bv\n\tv.getOrig().Value = ov\n}\n\n// SetEmptyBytes sets value to an empty byte slice and returns it.\n// Calling this function on zero-initialized Value will cause a panic.\nfunc (v Value) SetEmptyBytes() ByteSlice {\n\tv.getState().AssertMutable()\n\t// Delete everything but the AnyValue object itself.\n\tinternal.DeleteAnyValue(v.getOrig(), false)\n\tbv := internal.NewAnyValueBytesValue()\n\tv.getOrig().Value = bv\n\treturn ByteSlice(internal.NewByteSliceWrapper(&bv.BytesValue, v.getState()))\n}\n\n// SetEmptyMap sets value to an empty map and returns it.\n// Calling this function on zero-initialized Value will cause a panic.\nfunc (v Value) SetEmptyMap() Map {\n\tv.getState().AssertMutable()\n\t// Delete everything but the AnyValue object itself.\n\tinternal.DeleteAnyValue(v.getOrig(), false)\n\tov := internal.NewAnyValueKvlistValue()\n\tov.KvlistValue = internal.NewKeyValueList()\n\tv.getOrig().Value = ov\n\treturn newMap(&ov.KvlistValue.Values, v.getState())\n}\n\n// SetEmptySlice sets value to an empty slice and returns it.\n// Calling this function on zero-initialized Value will cause a panic.\nfunc (v Value) SetEmptySlice() Slice {\n\tv.getState().AssertMutable()\n\t// Delete everything but the AnyValue object itself.\n\tinternal.DeleteAnyValue(v.getOrig(), false)\n\tov := internal.NewAnyValueArrayValue()\n\tov.ArrayValue = internal.NewArrayValue()\n\tv.getOrig().Value = ov\n\treturn newSlice(&ov.ArrayValue.Values, v.getState())\n}\n\n// MoveTo moves the Value from current overriding the destination and\n// resetting the current instance to empty value.\n// Calling this function on zero-initialized Value will cause a panic.\nfunc (v Value) MoveTo(dest Value) {\n\tv.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif v.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = *v.getOrig()\n\tv.getOrig().Value = nil\n}\n\n// CopyTo copies the Value instance overriding the destination.\n// Calling this function on zero-initialized Value will cause a panic.\nfunc (v Value) CopyTo(dest Value) {\n\tdest.getState().AssertMutable()\n\tinternal.CopyAnyValue(dest.getOrig(), v.getOrig())\n}\n\n// AsString converts an OTLP Value object of any type to its equivalent string\n// representation. This differs from Str which only returns a non-empty value\n// if the ValueType is ValueTypeStr.\n// Calling this function on zero-initialized Value will cause a panic.\nfunc (v Value) AsString() string {\n\tswitch v.Type() {\n\tcase ValueTypeEmpty:\n\t\treturn \"\"\n\n\tcase ValueTypeStr:\n\t\treturn v.Str()\n\n\tcase ValueTypeBool:\n\t\treturn strconv.FormatBool(v.Bool())\n\n\tcase ValueTypeDouble:\n\t\treturn float64AsString(v.Double())\n\n\tcase ValueTypeInt:\n\t\treturn strconv.FormatInt(v.Int(), 10)\n\n\tcase ValueTypeMap:\n\t\tjsonStr, _ := json.Marshal(v.Map().AsRaw())\n\t\treturn string(jsonStr)\n\n\tcase ValueTypeBytes:\n\t\treturn base64.StdEncoding.EncodeToString(*v.Bytes().getOrig())\n\n\tcase ValueTypeSlice:\n\t\tjsonStr, _ := json.Marshal(v.Slice().AsRaw())\n\t\treturn string(jsonStr)\n\n\tdefault:\n\t\treturn fmt.Sprintf(\"<Unknown OpenTelemetry attribute value type %q>\", v.Type())\n\t}\n}\n\n// See https://cs.opensource.google/go/go/+/refs/tags/go1.17.7:src/encoding/json/encode.go;l=585.\n// This allows us to avoid using reflection.\nfunc float64AsString(f float64) string {\n\tif math.IsInf(f, 0) || math.IsNaN(f) {\n\t\treturn \"json: unsupported value: \" + strconv.FormatFloat(f, 'g', -1, 64)\n\t}\n\n\t// Convert as if by ES6 number to string conversion.\n\t// This matches most other JSON generators.\n\t// See golang.org/issue/6384 and golang.org/issue/14135.\n\t// Like fmt %g, but the exponent cutoffs are different\n\t// and exponents themselves are not padded to two digits.\n\tscratch := [64]byte{}\n\tb := scratch[:0]\n\tabs := math.Abs(f)\n\tfmt := byte('f')\n\tif abs != 0 && (abs < 1e-6 || abs >= 1e21) {\n\t\tfmt = 'e'\n\t}\n\tb = strconv.AppendFloat(b, f, fmt, -1, 64)\n\tif fmt == 'e' {\n\t\t// clean up e-09 to e-9\n\t\tn := len(b)\n\t\tif n >= 4 && b[n-4] == 'e' && b[n-3] == '-' && b[n-2] == '0' {\n\t\t\tb[n-2] = b[n-1]\n\t\t\tb = b[:n-1]\n\t\t}\n\t}\n\treturn string(b)\n}\n\nfunc (v Value) AsRaw() any {\n\tswitch v.Type() {\n\tcase ValueTypeEmpty:\n\t\treturn nil\n\tcase ValueTypeStr:\n\t\treturn v.Str()\n\tcase ValueTypeBool:\n\t\treturn v.Bool()\n\tcase ValueTypeDouble:\n\t\treturn v.Double()\n\tcase ValueTypeInt:\n\t\treturn v.Int()\n\tcase ValueTypeBytes:\n\t\treturn v.Bytes().AsRaw()\n\tcase ValueTypeMap:\n\t\treturn v.Map().AsRaw()\n\tcase ValueTypeSlice:\n\t\treturn v.Slice().AsRaw()\n\t}\n\treturn fmt.Sprintf(\"<Unknown OpenTelemetry value type %q>\", v.Type())\n}\n\nfunc (v Value) Equal(c Value) bool {\n\tif v.Type() != c.Type() {\n\t\treturn false\n\t}\n\n\tswitch v.Type() {\n\tcase ValueTypeEmpty:\n\t\treturn true\n\tcase ValueTypeStr:\n\t\treturn v.Str() == c.Str()\n\tcase ValueTypeBool:\n\t\treturn v.Bool() == c.Bool()\n\tcase ValueTypeDouble:\n\t\treturn v.Double() == c.Double()\n\tcase ValueTypeInt:\n\t\treturn v.Int() == c.Int()\n\tcase ValueTypeBytes:\n\t\treturn v.Bytes().Equal(c.Bytes())\n\tcase ValueTypeMap:\n\t\treturn v.Map().Equal(c.Map())\n\tcase ValueTypeSlice:\n\t\treturn v.Slice().Equal(c.Slice())\n\t}\n\n\treturn false\n}\n"
  },
  {
    "path": "pdata/pcommon/value_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pcommon\n\nimport (\n\t\"encoding/base64\"\n\t\"math\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestValue(t *testing.T) {\n\tv := NewValueStr(\"abc\")\n\tassert.Equal(t, ValueTypeStr, v.Type())\n\tassert.Equal(t, \"abc\", v.Str())\n\n\tv = NewValueInt(123)\n\tassert.Equal(t, ValueTypeInt, v.Type())\n\tassert.EqualValues(t, 123, v.Int())\n\n\tv = NewValueDouble(3.4)\n\tassert.Equal(t, ValueTypeDouble, v.Type())\n\tassert.InDelta(t, 3.4, v.Double(), 0.01)\n\n\tv = NewValueBool(true)\n\tassert.Equal(t, ValueTypeBool, v.Type())\n\tassert.True(t, v.Bool())\n\n\tv = NewValueBytes()\n\tassert.Equal(t, ValueTypeBytes, v.Type())\n\n\tv = NewValueEmpty()\n\tassert.Equal(t, ValueTypeEmpty, v.Type())\n\n\tv = NewValueMap()\n\tassert.Equal(t, ValueTypeMap, v.Type())\n\n\tv = NewValueSlice()\n\tassert.Equal(t, ValueTypeSlice, v.Type())\n}\n\nfunc TestValueReadOnly(t *testing.T) {\n\tstate := internal.NewState()\n\tstate.MarkReadOnly()\n\tv := newValue(&internal.AnyValue{Value: &internal.AnyValue_StringValue{StringValue: \"v\"}}, state)\n\n\tassert.Equal(t, ValueTypeStr, v.Type())\n\tassert.Equal(t, \"v\", v.Str())\n\tassert.EqualValues(t, 0, v.Int())\n\tassert.InDelta(t, 0, v.Double(), 0.01)\n\tassert.False(t, v.Bool())\n\tassert.Equal(t, ByteSlice{}, v.Bytes())\n\tassert.Equal(t, Map{}, v.Map())\n\tassert.Equal(t, Slice{}, v.Slice())\n\n\tassert.Equal(t, \"v\", v.AsString())\n\n\tassert.Panics(t, func() { v.SetStr(\"abc\") })\n\tassert.Panics(t, func() { v.SetInt(123) })\n\tassert.Panics(t, func() { v.SetDouble(3.4) })\n\tassert.Panics(t, func() { v.SetBool(true) })\n\tassert.Panics(t, func() { v.SetEmptyBytes() })\n\tassert.Panics(t, func() { v.SetEmptyMap() })\n\tassert.Panics(t, func() { v.SetEmptySlice() })\n\n\tv2 := NewValueEmpty()\n\tv.CopyTo(v2)\n\tassert.Equal(t, v.AsRaw(), v2.AsRaw())\n\tassert.Panics(t, func() { v2.CopyTo(v) })\n}\n\nfunc TestValueType(t *testing.T) {\n\tassert.Equal(t, \"Empty\", ValueTypeEmpty.String())\n\tassert.Equal(t, \"Str\", ValueTypeStr.String())\n\tassert.Equal(t, \"Bool\", ValueTypeBool.String())\n\tassert.Equal(t, \"Int\", ValueTypeInt.String())\n\tassert.Equal(t, \"Double\", ValueTypeDouble.String())\n\tassert.Equal(t, \"Map\", ValueTypeMap.String())\n\tassert.Equal(t, \"Slice\", ValueTypeSlice.String())\n\tassert.Equal(t, \"Bytes\", ValueTypeBytes.String())\n\tassert.Empty(t, ValueType(100).String())\n}\n\nfunc TestValueMap(t *testing.T) {\n\tm1 := NewValueMap()\n\tassert.Equal(t, ValueTypeMap, m1.Type())\n\tassert.Equal(t, NewMap(), m1.Map())\n\tassert.Equal(t, 0, m1.Map().Len())\n\n\tm1.Map().PutDouble(\"double_key\", 123)\n\tassert.Equal(t, 1, m1.Map().Len())\n\tgot, exists := m1.Map().Get(\"double_key\")\n\tassert.True(t, exists)\n\tassert.Equal(t, NewValueDouble(123), got)\n\n\t// Create a second map.\n\tm2 := m1.Map().PutEmptyMap(\"child_map\")\n\tassert.Equal(t, 0, m2.Len())\n\n\t// Modify the source map that was inserted.\n\tm2.PutStr(\"key_in_child\", \"somestr\")\n\tassert.Equal(t, 1, m2.Len())\n\tgot, exists = m2.Get(\"key_in_child\")\n\tassert.True(t, exists)\n\tassert.Equal(t, NewValueStr(\"somestr\"), got)\n\n\t// Insert the second map as a child. This should perform a deep copy.\n\tassert.Equal(t, 2, m1.Map().Len())\n\tgot, exists = m1.Map().Get(\"double_key\")\n\tassert.True(t, exists)\n\tassert.Equal(t, NewValueDouble(123), got)\n\tgot, exists = m1.Map().Get(\"child_map\")\n\tassert.True(t, exists)\n\tassert.Equal(t, m2, got.Map())\n\n\t// Modify the source map m2 that was inserted into m1.\n\tm2.PutStr(\"key_in_child\", \"somestr2\")\n\tassert.Equal(t, 1, m2.Len())\n\tgot, exists = m2.Get(\"key_in_child\")\n\tassert.True(t, exists)\n\tassert.Equal(t, NewValueStr(\"somestr2\"), got)\n\n\t// The child map inside m1 should be modified.\n\tchildMap, childMapExists := m1.Map().Get(\"child_map\")\n\trequire.True(t, childMapExists)\n\tgot, exists = childMap.Map().Get(\"key_in_child\")\n\trequire.True(t, exists)\n\tassert.Equal(t, NewValueStr(\"somestr2\"), got)\n\n\t// Now modify the inserted map (not the source)\n\tchildMap.Map().PutStr(\"key_in_child\", \"somestr3\")\n\tassert.Equal(t, 1, childMap.Map().Len())\n\tgot, exists = childMap.Map().Get(\"key_in_child\")\n\trequire.True(t, exists)\n\tassert.Equal(t, NewValueStr(\"somestr3\"), got)\n\n\t// The source child map should be modified.\n\tgot, exists = m2.Get(\"key_in_child\")\n\trequire.True(t, exists)\n\tassert.Equal(t, NewValueStr(\"somestr3\"), got)\n\n\tremoved := m1.Map().Remove(\"double_key\")\n\tassert.True(t, removed)\n\tassert.Equal(t, 1, m1.Map().Len())\n\t_, exists = m1.Map().Get(\"double_key\")\n\tassert.False(t, exists)\n\n\tremoved = m1.Map().Remove(\"child_map\")\n\tassert.True(t, removed)\n\tassert.Equal(t, 0, m1.Map().Len())\n\t_, exists = m1.Map().Get(\"child_map\")\n\tassert.False(t, exists)\n\n\t// Test nil KvlistValue case for MapWrapper() func.\n\torig := &internal.AnyValue{Value: &internal.AnyValue_KvlistValue{KvlistValue: nil}}\n\tm1 = newValue(orig, internal.NewState())\n\tassert.Equal(t, Map{}, m1.Map())\n}\n\nfunc TestValueSlice(t *testing.T) {\n\ta1 := NewValueSlice()\n\tassert.Equal(t, ValueTypeSlice, a1.Type())\n\tassert.Equal(t, NewSlice(), a1.Slice())\n\tassert.Equal(t, 0, a1.Slice().Len())\n\n\ta1.Slice().AppendEmpty().SetDouble(123)\n\tassert.Equal(t, 1, a1.Slice().Len())\n\tassert.Equal(t, NewValueDouble(123), a1.Slice().At(0))\n\t// Create a second array.\n\ta2 := NewValueSlice()\n\tassert.Equal(t, 0, a2.Slice().Len())\n\n\ta2.Slice().AppendEmpty().SetStr(\"somestr\")\n\tassert.Equal(t, 1, a2.Slice().Len())\n\tassert.Equal(t, NewValueStr(\"somestr\"), a2.Slice().At(0))\n\n\t// Insert the second array as a child.\n\ta2.CopyTo(a1.Slice().AppendEmpty())\n\tassert.Equal(t, 2, a1.Slice().Len())\n\tassert.Equal(t, NewValueDouble(123), a1.Slice().At(0))\n\tassert.Equal(t, a2, a1.Slice().At(1))\n\n\t// Check that the array was correctly inserted.\n\tchildArray := a1.Slice().At(1)\n\tassert.Equal(t, ValueTypeSlice, childArray.Type())\n\tassert.Equal(t, 1, childArray.Slice().Len())\n\n\tv := childArray.Slice().At(0)\n\tassert.Equal(t, ValueTypeStr, v.Type())\n\tassert.Equal(t, \"somestr\", v.Str())\n\n\t// Test nil values case for Slice() func.\n\ta1 = newValue(&internal.AnyValue{Value: &internal.AnyValue_ArrayValue{ArrayValue: nil}}, internal.NewState())\n\tassert.Equal(t, newSlice(nil, nil), a1.Slice())\n}\n\nfunc TestNilOrigSetValue(t *testing.T) {\n\tav := NewValueEmpty()\n\tav.SetStr(\"abc\")\n\tassert.Equal(t, \"abc\", av.Str())\n\n\tav = NewValueEmpty()\n\tav.SetInt(123)\n\tassert.EqualValues(t, 123, av.Int())\n\n\tav = NewValueEmpty()\n\tav.SetBool(true)\n\tassert.True(t, av.Bool())\n\n\tav = NewValueEmpty()\n\tav.SetDouble(1.23)\n\tassert.InDelta(t, 1.23, av.Double(), 0.01)\n\n\tav = NewValueEmpty()\n\tav.SetEmptyBytes().FromRaw([]byte{1, 2, 3})\n\tassert.Equal(t, []byte{1, 2, 3}, av.Bytes().AsRaw())\n\n\tav = NewValueEmpty()\n\trequire.NoError(t, av.SetEmptyMap().FromRaw(map[string]any{\"k\": \"v\"}))\n\tassert.Equal(t, map[string]any{\"k\": \"v\"}, av.Map().AsRaw())\n\n\tav = NewValueEmpty()\n\trequire.NoError(t, av.SetEmptySlice().FromRaw([]any{int64(1), \"val\"}))\n\tassert.Equal(t, []any{int64(1), \"val\"}, av.Slice().AsRaw())\n}\n\nfunc TestValue_MoveTo(t *testing.T) {\n\tsrc := NewValueMap()\n\tsrc.Map().PutStr(\"key\", \"value\")\n\n\tdest := NewValueEmpty()\n\tassert.True(t, dest.Equal(NewValueEmpty()))\n\n\tsrc.MoveTo(dest)\n\tassert.True(t, src.Equal(NewValueEmpty()))\n\n\texpected := NewValueMap()\n\texpected.Map().PutStr(\"key\", \"value\")\n\tassert.True(t, dest.Equal(expected))\n\n\tdest.MoveTo(dest)\n\tassert.True(t, dest.Equal(expected))\n}\n\nfunc TestValue_CopyTo(t *testing.T) {\n\tdest := NewValueEmpty()\n\torig := internal.GenTestAnyValue()\n\tnewValue(orig, internal.NewState()).CopyTo(dest)\n\tassert.Equal(t, internal.GenTestAnyValue(), dest.getOrig())\n}\n\nfunc TestSliceWithNilValues(t *testing.T) {\n\torigWithNil := []internal.AnyValue{\n\t\t{},\n\t\t{Value: &internal.AnyValue_StringValue{StringValue: \"test_value\"}},\n\t}\n\tsm := newSlice(&origWithNil, internal.NewState())\n\n\tval := sm.At(0)\n\tassert.Equal(t, ValueTypeEmpty, val.Type())\n\tassert.Empty(t, val.Str())\n\n\tval = sm.At(1)\n\tassert.Equal(t, ValueTypeStr, val.Type())\n\tassert.Equal(t, \"test_value\", val.Str())\n\n\tsm.AppendEmpty().SetStr(\"other_value\")\n\tval = sm.At(2)\n\tassert.Equal(t, ValueTypeStr, val.Type())\n\tassert.Equal(t, \"other_value\", val.Str())\n}\n\nfunc TestValueAsString(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    Value\n\t\texpected string\n\t}{\n\t\t{\n\t\t\tname:     \"string\",\n\t\t\tinput:    NewValueStr(\"string value\"),\n\t\t\texpected: \"string value\",\n\t\t},\n\t\t{\n\t\t\tname:     \"int64\",\n\t\t\tinput:    NewValueInt(42),\n\t\t\texpected: \"42\",\n\t\t},\n\t\t{\n\t\t\tname:     \"float64\",\n\t\t\tinput:    NewValueDouble(1.61803399),\n\t\t\texpected: \"1.61803399\",\n\t\t},\n\t\t{\n\t\t\tname:     \"small float64\",\n\t\t\tinput:    NewValueDouble(.000000009),\n\t\t\texpected: \"9e-9\",\n\t\t},\n\t\t{\n\t\t\tname:     \"bad float64\",\n\t\t\tinput:    NewValueDouble(math.Inf(1)),\n\t\t\texpected: \"json: unsupported value: +Inf\",\n\t\t},\n\t\t{\n\t\t\tname:     \"boolean\",\n\t\t\tinput:    NewValueBool(true),\n\t\t\texpected: \"true\",\n\t\t},\n\t\t{\n\t\t\tname:     \"empty_map\",\n\t\t\tinput:    NewValueMap(),\n\t\t\texpected: \"{}\",\n\t\t},\n\t\t{\n\t\t\tname:     \"simple_map\",\n\t\t\tinput:    generateTestValueMap(),\n\t\t\texpected: \"{\\\"arrKey\\\":[\\\"strOne\\\",\\\"strTwo\\\"],\\\"boolKey\\\":false,\\\"floatKey\\\":18.6,\\\"intKey\\\":7,\\\"mapKey\\\":{\\\"keyOne\\\":\\\"valOne\\\",\\\"keyTwo\\\":\\\"valTwo\\\"},\\\"nullKey\\\":null,\\\"strKey\\\":\\\"strVal\\\"}\",\n\t\t},\n\t\t{\n\t\t\tname:     \"empty_array\",\n\t\t\tinput:    NewValueSlice(),\n\t\t\texpected: \"[]\",\n\t\t},\n\t\t{\n\t\t\tname:     \"simple_array\",\n\t\t\tinput:    generateTestValueSlice(),\n\t\t\texpected: \"[\\\"strVal\\\",7,18.6,false,null]\",\n\t\t},\n\t\t{\n\t\t\tname:     \"empty\",\n\t\t\tinput:    NewValueEmpty(),\n\t\t\texpected: \"\",\n\t\t},\n\t\t{\n\t\t\tname:     \"bytes\",\n\t\t\tinput:    generateTestValueBytes(),\n\t\t\texpected: base64.StdEncoding.EncodeToString([]byte(\"String bytes\")),\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tactual := tt.input.AsString()\n\t\t\tassert.Equal(t, tt.expected, actual)\n\t\t})\n\t}\n}\n\nfunc TestValueAsRaw(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    Value\n\t\texpected any\n\t}{\n\t\t{\n\t\t\tname:     \"string\",\n\t\t\tinput:    NewValueStr(\"value\"),\n\t\t\texpected: \"value\",\n\t\t},\n\t\t{\n\t\t\tname:     \"int\",\n\t\t\tinput:    NewValueInt(11),\n\t\t\texpected: int64(11),\n\t\t},\n\t\t{\n\t\t\tname:     \"double\",\n\t\t\tinput:    NewValueDouble(1.2),\n\t\t\texpected: 1.2,\n\t\t},\n\t\t{\n\t\t\tname:     \"bytes\",\n\t\t\tinput:    generateTestValueBytes(),\n\t\t\texpected: []byte(\"String bytes\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"empty\",\n\t\t\tinput:    NewValueEmpty(),\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tname:     \"slice\",\n\t\t\tinput:    generateTestValueSlice(),\n\t\t\texpected: []any{\"strVal\", int64(7), 18.6, false, nil},\n\t\t},\n\t\t{\n\t\t\tname:  \"map\",\n\t\t\tinput: generateTestValueMap(),\n\t\t\texpected: map[string]any{\n\t\t\t\t\"mapKey\":   map[string]any{\"keyOne\": \"valOne\", \"keyTwo\": \"valTwo\"},\n\t\t\t\t\"nullKey\":  nil,\n\t\t\t\t\"strKey\":   \"strVal\",\n\t\t\t\t\"arrKey\":   []any{\"strOne\", \"strTwo\"},\n\t\t\t\t\"boolKey\":  false,\n\t\t\t\t\"floatKey\": 18.6,\n\t\t\t\t\"intKey\":   int64(7),\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tactual := tt.input.AsRaw()\n\t\t\tassert.Equal(t, tt.expected, actual)\n\t\t})\n\t}\n}\n\nfunc TestNewValueFromRaw(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    any\n\t\texpected Value\n\t}{\n\t\t{\n\t\t\tname:     \"nil\",\n\t\t\tinput:    nil,\n\t\t\texpected: NewValueEmpty(),\n\t\t},\n\t\t{\n\t\t\tname:     \"string\",\n\t\t\tinput:    \"text\",\n\t\t\texpected: NewValueStr(\"text\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"int\",\n\t\t\tinput:    123,\n\t\t\texpected: NewValueInt(int64(123)),\n\t\t},\n\t\t{\n\t\t\tname:     \"int8\",\n\t\t\tinput:    int8(12),\n\t\t\texpected: NewValueInt(int64(12)),\n\t\t},\n\t\t{\n\t\t\tname:     \"int16\",\n\t\t\tinput:    int16(23),\n\t\t\texpected: NewValueInt(int64(23)),\n\t\t},\n\t\t{\n\t\t\tname:     \"int32\",\n\t\t\tinput:    int32(34),\n\t\t\texpected: NewValueInt(int64(34)),\n\t\t},\n\t\t{\n\t\t\tname:     \"int64\",\n\t\t\tinput:    int64(45),\n\t\t\texpected: NewValueInt(45),\n\t\t},\n\t\t{\n\t\t\tname:     \"uint\",\n\t\t\tinput:    uint(56),\n\t\t\texpected: NewValueInt(int64(56)),\n\t\t},\n\t\t{\n\t\t\tname:     \"uint8\",\n\t\t\tinput:    uint8(67),\n\t\t\texpected: NewValueInt(int64(67)),\n\t\t},\n\t\t{\n\t\t\tname:     \"uint16\",\n\t\t\tinput:    uint16(78),\n\t\t\texpected: NewValueInt(int64(78)),\n\t\t},\n\t\t{\n\t\t\tname:     \"uint32\",\n\t\t\tinput:    uint32(89),\n\t\t\texpected: NewValueInt(int64(89)),\n\t\t},\n\t\t{\n\t\t\tname:     \"uint64\",\n\t\t\tinput:    uint64(90),\n\t\t\texpected: NewValueInt(int64(90)),\n\t\t},\n\t\t{\n\t\t\tname:     \"float32\",\n\t\t\tinput:    float32(1.234),\n\t\t\texpected: NewValueDouble(float64(float32(1.234))),\n\t\t},\n\t\t{\n\t\t\tname:     \"float64\",\n\t\t\tinput:    float64(2.345),\n\t\t\texpected: NewValueDouble(float64(2.345)),\n\t\t},\n\t\t{\n\t\t\tname:     \"bool\",\n\t\t\tinput:    true,\n\t\t\texpected: NewValueBool(true),\n\t\t},\n\t\t{\n\t\t\tname:  \"bytes\",\n\t\t\tinput: []byte{1, 2, 3},\n\t\t\texpected: func() Value {\n\t\t\t\tm := NewValueBytes()\n\t\t\t\tm.Bytes().FromRaw([]byte{1, 2, 3})\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"map\",\n\t\t\tinput: map[string]any{\n\t\t\t\t\"k\": \"v\",\n\t\t\t},\n\t\t\texpected: func() Value {\n\t\t\t\tm := NewValueMap()\n\t\t\t\tassert.NoError(t, m.Map().FromRaw(map[string]any{\"k\": \"v\"}))\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname:  \"empty map\",\n\t\t\tinput: map[string]any{},\n\t\t\texpected: func() Value {\n\t\t\t\tm := NewValueMap()\n\t\t\t\tassert.NoError(t, m.Map().FromRaw(map[string]any{}))\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname:  \"slice\",\n\t\t\tinput: []any{\"v1\", \"v2\"},\n\t\t\texpected: (func() Value {\n\t\t\t\ts := NewValueSlice()\n\t\t\t\tassert.NoError(t, s.Slice().FromRaw([]any{\"v1\", \"v2\"}))\n\t\t\t\treturn s\n\t\t\t})(),\n\t\t},\n\t\t{\n\t\t\tname:  \"empty slice\",\n\t\t\tinput: []any{},\n\t\t\texpected: (func() Value {\n\t\t\t\ts := NewValueSlice()\n\t\t\t\tassert.NoError(t, s.Slice().FromRaw([]any{}))\n\t\t\t\treturn s\n\t\t\t})(),\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tactual := NewValueEmpty()\n\t\t\trequire.NoError(t, actual.FromRaw(tt.input))\n\t\t\tassert.Equal(t, tt.expected, actual)\n\t\t})\n\t}\n}\n\nfunc TestNewValueFromRawInvalid(t *testing.T) {\n\tactual := NewValueEmpty()\n\tassert.EqualError(t, actual.FromRaw(ValueTypeDouble), \"<Invalid value type pcommon.ValueType>\")\n}\n\nfunc TestInvalidValue(t *testing.T) {\n\tv := Value{}\n\tassert.False(t, v.Bool())\n\tassert.Equal(t, int64(0), v.Int())\n\tassert.InDelta(t, float64(0), v.Double(), 0.01)\n\tassert.Empty(t, v.Str())\n\tassert.Equal(t, ByteSlice{}, v.Bytes())\n\tassert.Equal(t, Map{}, v.Map())\n\tassert.Equal(t, Slice{}, v.Slice())\n\tassert.Panics(t, func() { v.AsString() })\n\tassert.Panics(t, func() { v.AsRaw() })\n\tassert.Panics(t, func() { _ = v.FromRaw(1) })\n\tassert.Panics(t, func() { v.Type() })\n\tassert.Panics(t, func() { v.SetStr(\"\") })\n\tassert.Panics(t, func() { v.SetInt(0) })\n\tassert.Panics(t, func() { v.SetDouble(0) })\n\tassert.Panics(t, func() { v.SetBool(false) })\n\tassert.Panics(t, func() { v.SetEmptyBytes() })\n\tassert.Panics(t, func() { v.SetEmptyMap() })\n\tassert.Panics(t, func() { v.SetEmptySlice() })\n\tnv := NewValueEmpty()\n\tv.CopyTo(nv)\n\tassert.Nil(t, nv.getOrig().Value)\n}\n\nfunc TestValueEqual(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname       string\n\t\tvalue      Value\n\t\tcomparison Value\n\t\texpected   bool\n\t}{\n\t\t{\n\t\t\tname:       \"different types\",\n\t\t\tvalue:      NewValueEmpty(),\n\t\t\tcomparison: NewValueStr(\"test\"),\n\t\t\texpected:   false,\n\t\t},\n\t\t{\n\t\t\tname:       \"same empty\",\n\t\t\tvalue:      NewValueEmpty(),\n\t\t\tcomparison: NewValueEmpty(),\n\t\t\texpected:   true,\n\t\t},\n\t\t{\n\t\t\tname:       \"same strings\",\n\t\t\tvalue:      NewValueStr(\"test\"),\n\t\t\tcomparison: NewValueStr(\"test\"),\n\t\t\texpected:   true,\n\t\t},\n\t\t{\n\t\t\tname:       \"different strings\",\n\t\t\tvalue:      NewValueStr(\"test\"),\n\t\t\tcomparison: NewValueStr(\"non-test\"),\n\t\t\texpected:   false,\n\t\t},\n\t\t{\n\t\t\tname:       \"same booleans\",\n\t\t\tvalue:      NewValueBool(true),\n\t\t\tcomparison: NewValueBool(true),\n\t\t\texpected:   true,\n\t\t},\n\t\t{\n\t\t\tname:       \"different booleans\",\n\t\t\tvalue:      NewValueBool(true),\n\t\t\tcomparison: NewValueBool(false),\n\t\t\texpected:   false,\n\t\t},\n\t\t{\n\t\t\tname:       \"same int\",\n\t\t\tvalue:      NewValueInt(42),\n\t\t\tcomparison: NewValueInt(42),\n\t\t\texpected:   true,\n\t\t},\n\t\t{\n\t\t\tname:       \"different ints\",\n\t\t\tvalue:      NewValueInt(42),\n\t\t\tcomparison: NewValueInt(1701),\n\t\t\texpected:   false,\n\t\t},\n\t\t{\n\t\t\tname:       \"same double\",\n\t\t\tvalue:      NewValueDouble(13.37),\n\t\t\tcomparison: NewValueDouble(13.37),\n\t\t\texpected:   true,\n\t\t},\n\t\t{\n\t\t\tname:       \"different doubles\",\n\t\t\tvalue:      NewValueDouble(13.37),\n\t\t\tcomparison: NewValueDouble(17.01),\n\t\t\texpected:   false,\n\t\t},\n\t\t{\n\t\t\tname: \"same byte slice\",\n\t\t\tvalue: func() Value {\n\t\t\t\tm := NewValueBytes()\n\t\t\t\tm.Bytes().FromRaw([]byte{1, 3, 3, 7})\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\tcomparison: func() Value {\n\t\t\t\tm := NewValueBytes()\n\t\t\t\tm.Bytes().FromRaw([]byte{1, 3, 3, 7})\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname: \"different byte slice\",\n\t\t\tvalue: func() Value {\n\t\t\t\tm := NewValueBytes()\n\t\t\t\tm.Bytes().FromRaw([]byte{1, 3, 3, 7})\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\tcomparison: func() Value {\n\t\t\t\tm := NewValueBytes()\n\t\t\t\tm.Bytes().FromRaw([]byte{1, 7, 0, 1})\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname: \"same slice\",\n\t\t\tvalue: func() Value {\n\t\t\t\tm := NewValueSlice()\n\t\t\t\trequire.NoError(t, m.Slice().FromRaw([]any{1337}))\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\tcomparison: func() Value {\n\t\t\t\tm := NewValueSlice()\n\t\t\t\trequire.NoError(t, m.Slice().FromRaw([]any{1337}))\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname: \"different slice\",\n\t\t\tvalue: func() Value {\n\t\t\t\tm := NewValueSlice()\n\t\t\t\trequire.NoError(t, m.Slice().FromRaw([]any{1337}))\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\tcomparison: func() Value {\n\t\t\t\tm := NewValueSlice()\n\t\t\t\trequire.NoError(t, m.Slice().FromRaw([]any{1701}))\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\texpected: false,\n\t\t},\n\t\t{\n\t\t\tname: \"same map\",\n\t\t\tvalue: func() Value {\n\t\t\t\tm := NewValueMap()\n\t\t\t\tm.Map().PutStr(\"hello\", \"world\")\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\tcomparison: func() Value {\n\t\t\t\tm := NewValueMap()\n\t\t\t\tm.Map().PutStr(\"hello\", \"world\")\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\texpected: true,\n\t\t},\n\t\t{\n\t\t\tname: \"different maps\",\n\t\t\tvalue: func() Value {\n\t\t\t\tm := NewValueMap()\n\t\t\t\tm.Map().PutStr(\"hello\", \"world\")\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\tcomparison: func() Value {\n\t\t\t\tm := NewValueMap()\n\t\t\t\tm.Map().PutStr(\"bonjour\", \"monde\")\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\texpected: false,\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tassert.Equal(t, tt.expected, tt.value.Equal(tt.comparison))\n\t\t})\n\t}\n}\n\nfunc BenchmarkValueEqual(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\n\tfor _, bb := range []struct {\n\t\tname       string\n\t\tvalue      Value\n\t\tcomparison Value\n\t}{\n\t\t{\n\t\t\tname:       \"nil\",\n\t\t\tvalue:      NewValueEmpty(),\n\t\t\tcomparison: NewValueEmpty(),\n\t\t},\n\t\t{\n\t\t\tname:       \"strings\",\n\t\t\tvalue:      NewValueStr(\"test\"),\n\t\t\tcomparison: NewValueStr(\"test\"),\n\t\t},\n\t\t{\n\t\t\tname:       \"booleans\",\n\t\t\tvalue:      NewValueBool(true),\n\t\t\tcomparison: NewValueBool(true),\n\t\t},\n\t\t{\n\t\t\tname:       \"ints\",\n\t\t\tvalue:      NewValueInt(42),\n\t\t\tcomparison: NewValueInt(42),\n\t\t},\n\t\t{\n\t\t\tname:       \"doubles\",\n\t\t\tvalue:      NewValueDouble(13.37),\n\t\t\tcomparison: NewValueDouble(13.37),\n\t\t},\n\t\t{\n\t\t\tname: \"byte slices\",\n\t\t\tvalue: func() Value {\n\t\t\t\tm := NewValueBytes()\n\t\t\t\tm.Bytes().FromRaw([]byte{1, 3, 3, 7})\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\tcomparison: func() Value {\n\t\t\t\tm := NewValueBytes()\n\t\t\t\tm.Bytes().FromRaw([]byte{1, 3, 3, 7})\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"slices\",\n\t\t\tvalue: func() Value {\n\t\t\t\tm := NewValueSlice()\n\t\t\t\trequire.NoError(b, m.Slice().FromRaw([]any{1337}))\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\tcomparison: func() Value {\n\t\t\t\tm := NewValueSlice()\n\t\t\t\trequire.NoError(b, m.Slice().FromRaw([]any{1337}))\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"maps\",\n\t\t\tvalue: func() Value {\n\t\t\t\tm := NewValueMap()\n\t\t\t\tm.Map().PutStr(\"hello\", \"world\")\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\tcomparison: func() Value {\n\t\t\t\tm := NewValueMap()\n\t\t\t\tm.Map().PutStr(\"hello\", \"world\")\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t},\n\t} {\n\t\tb.Run(bb.name, func(b *testing.B) {\n\t\t\tb.ResetTimer()\n\t\t\tb.ReportAllocs()\n\n\t\t\tfor b.Loop() {\n\t\t\t\t_ = bb.value.Equal(bb.comparison)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc generateTestValueMap() Value {\n\tret := NewValueMap()\n\tattrMap := ret.Map()\n\tattrMap.PutStr(\"strKey\", \"strVal\")\n\tattrMap.PutInt(\"intKey\", 7)\n\tattrMap.PutDouble(\"floatKey\", 18.6)\n\tattrMap.PutBool(\"boolKey\", false)\n\tattrMap.PutEmpty(\"nullKey\")\n\n\tm := attrMap.PutEmptyMap(\"mapKey\")\n\tm.PutStr(\"keyOne\", \"valOne\")\n\tm.PutStr(\"keyTwo\", \"valTwo\")\n\n\ts := attrMap.PutEmptySlice(\"arrKey\")\n\ts.AppendEmpty().SetStr(\"strOne\")\n\ts.AppendEmpty().SetStr(\"strTwo\")\n\n\treturn ret\n}\n\nfunc generateTestValueSlice() Value {\n\tret := NewValueSlice()\n\tattrArr := ret.Slice()\n\tattrArr.AppendEmpty().SetStr(\"strVal\")\n\tattrArr.AppendEmpty().SetInt(7)\n\tattrArr.AppendEmpty().SetDouble(18.6)\n\tattrArr.AppendEmpty().SetBool(false)\n\tattrArr.AppendEmpty()\n\treturn ret\n}\n\nfunc generateTestValueBytes() Value {\n\tv := NewValueBytes()\n\tv.Bytes().FromRaw([]byte(\"String bytes\"))\n\treturn v\n}\n"
  },
  {
    "path": "pdata/plog/config.schema.yaml",
    "content": "$defs:\n  log_record_flags:\n    description: LogRecordFlags defines flags for the LogRecord. The 8 least significant bits are the trace flags as defined in W3C Trace Context specification. 24 most significant bits are reserved and must be set to 0.\n    type: integer\n    x-customType: uint32\n  logs:\n    description: 'Logs is the top-level struct that is propagated through the logs pipeline. Use NewLogs to create new instance, zero-initialized instance is not valid for use. This is a reference type, if passed by value and callee modifies it the caller will see the modification. Must use NewLogs function to create new instances. Important: zero-initialized instance is not valid for use.'\n    $ref: go.opentelemetry.io/collector/pdata/internal.logs_wrapper\n  severity_number:\n    description: SeverityNumber represents severity number of a log record.\n    type: integer\n    x-customType: int32\n"
  },
  {
    "path": "pdata/plog/doc_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plog_test\n\nimport (\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\nfunc ExampleNewLogs() {\n\tlogs := plog.NewLogs()\n\n\tresourceLogs := logs.ResourceLogs().AppendEmpty()\n\n\tresourceLogs.Resource().Attributes().PutStr(\"service.name\", \"my-service\")\n\tresourceLogs.Resource().Attributes().PutStr(\"service.version\", \"1.0.0\")\n\tresourceLogs.Resource().Attributes().PutStr(\"host.name\", \"server-01\")\n\n\tscopeLogs := resourceLogs.ScopeLogs().AppendEmpty()\n\tscopeLogs.Scope().SetName(\"my-logger\")\n\tscopeLogs.Scope().SetVersion(\"1.0.0\")\n\n\tlogRecord := scopeLogs.LogRecords().AppendEmpty()\n\tlogRecord.SetTimestamp(pcommon.Timestamp(1640995200000000000))\n\tlogRecord.SetSeverityNumber(plog.SeverityNumberInfo)\n\tlogRecord.SetSeverityText(\"INFO\")\n\tlogRecord.Body().SetStr(\"User login successful\")\n\n\tlogRecord.Attributes().PutStr(\"user.id\", \"user123\")\n\tlogRecord.Attributes().PutStr(\"session.id\", \"session456\")\n\tlogRecord.Attributes().PutStr(\"action\", \"login\")\n\n\tfmt.Printf(\"Resource logs count: %d\\n\", logs.ResourceLogs().Len())\n\tfmt.Printf(\"Log records count: %d\\n\", scopeLogs.LogRecords().Len())\n\tfmt.Printf(\"Log message: %s\\n\", logRecord.Body().Str())\n\tfmt.Printf(\"Severity: %s\\n\", logRecord.SeverityText())\n\t// Output:\n\t// Resource logs count: 1\n\t// Log records count: 1\n\t// Log message: User login successful\n\t// Severity: INFO\n}\n\nfunc ExampleLogRecord_SetSeverityNumber() {\n\tlogs := plog.NewLogs()\n\tresourceLogs := logs.ResourceLogs().AppendEmpty()\n\tscopeLogs := resourceLogs.ScopeLogs().AppendEmpty()\n\n\tseverities := []struct {\n\t\tlevel plog.SeverityNumber\n\t\ttext  string\n\t\tmsg   string\n\t}{\n\t\t{plog.SeverityNumberDebug, \"DEBUG\", \"Debug information\"},\n\t\t{plog.SeverityNumberInfo, \"INFO\", \"Application started\"},\n\t\t{plog.SeverityNumberWarn, \"WARN\", \"Configuration file not found, using defaults\"},\n\t\t{plog.SeverityNumberError, \"ERROR\", \"Failed to connect to database\"},\n\t\t{plog.SeverityNumberFatal, \"FATAL\", \"Critical system failure\"},\n\t}\n\n\tfor _, s := range severities {\n\t\tlogRecord := scopeLogs.LogRecords().AppendEmpty()\n\t\tlogRecord.SetSeverityNumber(s.level)\n\t\tlogRecord.SetSeverityText(s.text)\n\t\tlogRecord.Body().SetStr(s.msg)\n\t\tlogRecord.SetTimestamp(pcommon.Timestamp(1640995200000000000))\n\t}\n\n\tfmt.Printf(\"Total log records: %d\\n\", scopeLogs.LogRecords().Len())\n\n\tfirst := scopeLogs.LogRecords().At(0)\n\tlast := scopeLogs.LogRecords().At(scopeLogs.LogRecords().Len() - 1)\n\n\tfmt.Printf(\"First log: %s - %s\\n\", first.SeverityText(), first.Body().Str())\n\tfmt.Printf(\"Last log: %s - %s\\n\", last.SeverityText(), last.Body().Str())\n\t// Output:\n\t// Total log records: 5\n\t// First log: DEBUG - Debug information\n\t// Last log: FATAL - Critical system failure\n}\n\nfunc ExampleLogRecord_Body() {\n\tlogs := plog.NewLogs()\n\tresourceLogs := logs.ResourceLogs().AppendEmpty()\n\tscopeLogs := resourceLogs.ScopeLogs().AppendEmpty()\n\n\tlogRecord1 := scopeLogs.LogRecords().AppendEmpty()\n\tlogRecord1.Body().SetStr(\"Simple string message\")\n\tlogRecord1.SetSeverityNumber(plog.SeverityNumberInfo)\n\n\tlogRecord2 := scopeLogs.LogRecords().AppendEmpty()\n\tbody := logRecord2.Body().SetEmptyMap()\n\tbody.PutStr(\"event\", \"user_action\")\n\tbody.PutStr(\"user_id\", \"user123\")\n\tbody.PutInt(\"timestamp\", 1640995200)\n\tbody.PutBool(\"success\", true)\n\tlogRecord2.SetSeverityNumber(plog.SeverityNumberInfo)\n\n\tlogRecord3 := scopeLogs.LogRecords().AppendEmpty()\n\tbodySlice := logRecord3.Body().SetEmptySlice()\n\tbodySlice.AppendEmpty().SetStr(\"Step 1: Initialize connection\")\n\tbodySlice.AppendEmpty().SetStr(\"Step 2: Authenticate user\")\n\tbodySlice.AppendEmpty().SetStr(\"Step 3: Load configuration\")\n\tlogRecord3.SetSeverityNumber(plog.SeverityNumberDebug)\n\n\tfmt.Printf(\"Log 1 body type: %s\\n\", logRecord1.Body().Type())\n\tfmt.Printf(\"Log 2 body type: %s\\n\", logRecord2.Body().Type())\n\tfmt.Printf(\"Log 3 body type: %s\\n\", logRecord3.Body().Type())\n\tfmt.Printf(\"Log 3 steps count: %d\\n\", logRecord3.Body().Slice().Len())\n\t// Output:\n\t// Log 1 body type: Str\n\t// Log 2 body type: Map\n\t// Log 3 body type: Slice\n\t// Log 3 steps count: 3\n}\n\nfunc ExampleLogRecord_TraceID() {\n\tlogs := plog.NewLogs()\n\tresourceLogs := logs.ResourceLogs().AppendEmpty()\n\tscopeLogs := resourceLogs.ScopeLogs().AppendEmpty()\n\n\tlogRecord := scopeLogs.LogRecords().AppendEmpty()\n\tlogRecord.Body().SetStr(\"Processing request\")\n\tlogRecord.SetSeverityNumber(plog.SeverityNumberInfo)\n\n\ttraceID := pcommon.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16})\n\tspanID := pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8})\n\n\tlogRecord.SetTraceID(traceID)\n\tlogRecord.SetSpanID(spanID)\n\tlogRecord.SetFlags(plog.DefaultLogRecordFlags.WithIsSampled(true))\n\n\tfmt.Printf(\"Log message: %s\\n\", logRecord.Body().Str())\n\tfmt.Printf(\"TraceID: %s\\n\", logRecord.TraceID())\n\tfmt.Printf(\"SpanID: %s\\n\", logRecord.SpanID())\n\tfmt.Printf(\"Is sampled: %t\\n\", logRecord.Flags().IsSampled())\n\t// Output:\n\t// Log message: Processing request\n\t// TraceID: 0102030405060708090a0b0c0d0e0f10\n\t// SpanID: 0102030405060708\n\t// Is sampled: true\n}\n\nfunc ExampleLogRecord_ObservedTimestamp() {\n\tlogs := plog.NewLogs()\n\tresourceLogs := logs.ResourceLogs().AppendEmpty()\n\tscopeLogs := resourceLogs.ScopeLogs().AppendEmpty()\n\n\tlogRecord := scopeLogs.LogRecords().AppendEmpty()\n\tlogRecord.Body().SetStr(\"Log entry with observation time\")\n\tlogRecord.SetSeverityNumber(plog.SeverityNumberInfo)\n\n\t// Set both original timestamp and observed timestamp\n\toriginalTime := pcommon.Timestamp(1640995200000000000) // 2022-01-01 00:00:00 UTC\n\tobservedTime := pcommon.Timestamp(1640995200500000000) // 2022-01-01 00:00:00.5 UTC\n\n\tlogRecord.SetTimestamp(originalTime)\n\tlogRecord.SetObservedTimestamp(observedTime)\n\n\tfmt.Printf(\"Original timestamp: %d\\n\", logRecord.Timestamp())\n\tfmt.Printf(\"Observed timestamp: %d\\n\", logRecord.ObservedTimestamp())\n\tfmt.Printf(\"Delay (ns): %d\\n\", logRecord.ObservedTimestamp()-logRecord.Timestamp())\n\t// Output:\n\t// Original timestamp: 1640995200000000000\n\t// Observed timestamp: 1640995200500000000\n\t// Delay (ns): 500000000\n}\n\nfunc ExampleLogRecord_EventName() {\n\tlogs := plog.NewLogs()\n\tresourceLogs := logs.ResourceLogs().AppendEmpty()\n\tscopeLogs := resourceLogs.ScopeLogs().AppendEmpty()\n\n\tlogRecord := scopeLogs.LogRecords().AppendEmpty()\n\tlogRecord.SetEventName(\"user.login\")\n\tlogRecord.Body().SetStr(\"User authentication event\")\n\tlogRecord.SetSeverityNumber(plog.SeverityNumberInfo)\n\n\tlogRecord.Attributes().PutStr(\"user.id\", \"user123\")\n\tlogRecord.Attributes().PutStr(\"session.id\", \"session456\")\n\tlogRecord.Attributes().PutBool(\"success\", true)\n\n\tfmt.Printf(\"Event name: %s\\n\", logRecord.EventName())\n\tfmt.Printf(\"Log body: %s\\n\", logRecord.Body().Str())\n\t// Output:\n\t// Event name: user.login\n\t// Log body: User authentication event\n}\n\nfunc ExampleLogRecordFlags() {\n\tlogs := plog.NewLogs()\n\tresourceLogs := logs.ResourceLogs().AppendEmpty()\n\tscopeLogs := resourceLogs.ScopeLogs().AppendEmpty()\n\n\tlogRecord := scopeLogs.LogRecords().AppendEmpty()\n\tlogRecord.Body().SetStr(\"Log with flags\")\n\tlogRecord.SetSeverityNumber(plog.SeverityNumberInfo)\n\n\t// Test default flags\n\tdefaultFlags := plog.DefaultLogRecordFlags\n\tlogRecord.SetFlags(defaultFlags)\n\tfmt.Printf(\"Default flags IsSampled: %t\\n\", logRecord.Flags().IsSampled())\n\n\t// Test with sampled flag\n\tflagsWithSampled := defaultFlags.WithIsSampled(true)\n\tlogRecord.SetFlags(flagsWithSampled)\n\tfmt.Printf(\"With sampled flag: %t\\n\", logRecord.Flags().IsSampled())\n\n\t// Test removing sampled flag\n\tflagsWithoutSampled := flagsWithSampled.WithIsSampled(false)\n\tlogRecord.SetFlags(flagsWithoutSampled)\n\tfmt.Printf(\"Without sampled flag: %t\\n\", logRecord.Flags().IsSampled())\n\n\t// Output:\n\t// Default flags IsSampled: false\n\t// With sampled flag: true\n\t// Without sampled flag: false\n}\n\nfunc ExampleSeverityNumber() {\n\tlogs := plog.NewLogs()\n\tresourceLogs := logs.ResourceLogs().AppendEmpty()\n\tscopeLogs := resourceLogs.ScopeLogs().AppendEmpty()\n\n\t// Test all severity levels\n\tseverityLevels := []struct {\n\t\tlevel plog.SeverityNumber\n\t\tname  string\n\t}{\n\t\t{plog.SeverityNumberUnspecified, \"Unspecified\"},\n\t\t{plog.SeverityNumberTrace, \"Trace\"},\n\t\t{plog.SeverityNumberTrace2, \"Trace2\"},\n\t\t{plog.SeverityNumberTrace3, \"Trace3\"},\n\t\t{plog.SeverityNumberTrace4, \"Trace4\"},\n\t\t{plog.SeverityNumberDebug, \"Debug\"},\n\t\t{plog.SeverityNumberDebug2, \"Debug2\"},\n\t\t{plog.SeverityNumberDebug3, \"Debug3\"},\n\t\t{plog.SeverityNumberDebug4, \"Debug4\"},\n\t\t{plog.SeverityNumberInfo, \"Info\"},\n\t\t{plog.SeverityNumberInfo2, \"Info2\"},\n\t\t{plog.SeverityNumberInfo3, \"Info3\"},\n\t\t{plog.SeverityNumberInfo4, \"Info4\"},\n\t\t{plog.SeverityNumberWarn, \"Warn\"},\n\t\t{plog.SeverityNumberWarn2, \"Warn2\"},\n\t\t{plog.SeverityNumberWarn3, \"Warn3\"},\n\t\t{plog.SeverityNumberWarn4, \"Warn4\"},\n\t\t{plog.SeverityNumberError, \"Error\"},\n\t\t{plog.SeverityNumberError2, \"Error2\"},\n\t\t{plog.SeverityNumberError3, \"Error3\"},\n\t\t{plog.SeverityNumberError4, \"Error4\"},\n\t\t{plog.SeverityNumberFatal, \"Fatal\"},\n\t\t{plog.SeverityNumberFatal2, \"Fatal2\"},\n\t\t{plog.SeverityNumberFatal3, \"Fatal3\"},\n\t\t{plog.SeverityNumberFatal4, \"Fatal4\"},\n\t}\n\n\tfor i, s := range severityLevels {\n\t\tif i < 5 { // Only create first 5 to keep output manageable\n\t\t\tlogRecord := scopeLogs.LogRecords().AppendEmpty()\n\t\t\tlogRecord.SetSeverityNumber(s.level)\n\t\t\tlogRecord.SetSeverityText(s.name)\n\t\t\tlogRecord.Body().SetStr(\"Log at \" + s.name + \" level\")\n\t\t}\n\t}\n\n\tfmt.Printf(\"Total severity levels tested: %d\\n\", len(severityLevels))\n\tfmt.Printf(\"Created log records: %d\\n\", scopeLogs.LogRecords().Len())\n\tfmt.Printf(\"First severity: %s\\n\", scopeLogs.LogRecords().At(0).SeverityText())\n\tfmt.Printf(\"Last severity: %s\\n\", scopeLogs.LogRecords().At(4).SeverityText())\n\t// Output:\n\t// Total severity levels tested: 25\n\t// Created log records: 5\n\t// First severity: Unspecified\n\t// Last severity: Trace4\n}\n\nfunc ExampleLogRecord_DroppedAttributesCount() {\n\tlogs := plog.NewLogs()\n\tresourceLogs := logs.ResourceLogs().AppendEmpty()\n\tscopeLogs := resourceLogs.ScopeLogs().AppendEmpty()\n\n\tlogRecord := scopeLogs.LogRecords().AppendEmpty()\n\tlogRecord.Body().SetStr(\"Log with some attributes dropped\")\n\tlogRecord.SetSeverityNumber(plog.SeverityNumberWarn)\n\n\t// Add some attributes\n\tlogRecord.Attributes().PutStr(\"included.attr1\", \"value1\")\n\tlogRecord.Attributes().PutStr(\"included.attr2\", \"value2\")\n\tlogRecord.Attributes().PutInt(\"included.count\", 42)\n\n\t// Set dropped attributes count\n\tlogRecord.SetDroppedAttributesCount(7)\n\n\tfmt.Printf(\"Current attributes: %d\\n\", logRecord.Attributes().Len())\n\tfmt.Printf(\"Dropped attributes: %d\\n\", logRecord.DroppedAttributesCount())\n\tfmt.Printf(\"Total original attributes: %d\\n\", logRecord.Attributes().Len()+int(logRecord.DroppedAttributesCount()))\n\t// Output:\n\t// Current attributes: 3\n\t// Dropped attributes: 7\n\t// Total original attributes: 10\n}\n"
  },
  {
    "path": "pdata/plog/encoding.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plog // import \"go.opentelemetry.io/collector/pdata/plog\"\n\n// MarshalSizer is the interface that groups the basic Marshal and Size methods\ntype MarshalSizer interface {\n\tMarshaler\n\tSizer\n}\n\n// Marshaler marshals Logs into bytes.\ntype Marshaler interface {\n\t// MarshalLogs the given Logs into bytes.\n\t// If the error is not nil, the returned bytes slice cannot be used.\n\tMarshalLogs(ld Logs) ([]byte, error)\n}\n\n// Unmarshaler unmarshalls bytes into Logs.\ntype Unmarshaler interface {\n\t// UnmarshalLogs the given bytes into Logs.\n\t// If the error is not nil, the returned Logs cannot be used.\n\tUnmarshalLogs(buf []byte) (Logs, error)\n}\n\n// Sizer is an optional interface implemented by the Marshaler,\n// that calculates the size of a marshaled Logs.\ntype Sizer interface {\n\t// LogsSize returns the size in bytes of a marshaled Logs.\n\tLogsSize(ld Logs) int\n}\n"
  },
  {
    "path": "pdata/plog/fuzz_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plog // import \"go.opentelemetry.io/collector/pdata/plog\"\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar unexpectedBytes = \"expected the same bytes from unmarshaling and marshaling.\"\n\nfunc FuzzUnmarshalJSONLogs(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\tu1 := &JSONUnmarshaler{}\n\t\tld1, err := u1.UnmarshalLogs(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tm1 := &JSONMarshaler{}\n\t\tb1, err := m1.MarshalLogs(ld1)\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\tu2 := &JSONUnmarshaler{}\n\t\tld2, err := u2.UnmarshalLogs(b1)\n\t\trequire.NoError(t, err, \"failed to unmarshal valid bytes\")\n\t\tm2 := &JSONMarshaler{}\n\t\tb2, err := m2.MarshalLogs(ld2)\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n\nfunc FuzzUnmarshalPBLogs(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\tu1 := &ProtoUnmarshaler{}\n\t\tld1, err := u1.UnmarshalLogs(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tm1 := &ProtoMarshaler{}\n\t\tb1, err := m1.MarshalLogs(ld1)\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\tu2 := &ProtoUnmarshaler{}\n\t\tld2, err := u2.UnmarshalLogs(b1)\n\t\trequire.NoError(t, err, \"failed to unmarshal valid bytes\")\n\t\tm2 := &ProtoMarshaler{}\n\t\tb2, err := m2.MarshalLogs(ld2)\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n"
  },
  {
    "path": "pdata/plog/generated_logrecord.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plog\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// LogRecord are experimental implementation of OpenTelemetry Log Data Model.\n\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewLogRecord function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype LogRecord struct {\n\torig  *internal.LogRecord\n\tstate *internal.State\n}\n\nfunc newLogRecord(orig *internal.LogRecord, state *internal.State) LogRecord {\n\treturn LogRecord{orig: orig, state: state}\n}\n\n// NewLogRecord creates a new empty LogRecord.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewLogRecord() LogRecord {\n\treturn newLogRecord(internal.NewLogRecord(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms LogRecord) MoveTo(dest LogRecord) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteLogRecord(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Timestamp returns the timestamp associated with this LogRecord.\nfunc (ms LogRecord) Timestamp() pcommon.Timestamp {\n\treturn pcommon.Timestamp(ms.orig.TimeUnixNano)\n}\n\n// SetTimestamp replaces the timestamp associated with this LogRecord.\nfunc (ms LogRecord) SetTimestamp(v pcommon.Timestamp) {\n\tms.state.AssertMutable()\n\tms.orig.TimeUnixNano = uint64(v)\n}\n\n// ObservedTimestamp returns the observedtimestamp associated with this LogRecord.\nfunc (ms LogRecord) ObservedTimestamp() pcommon.Timestamp {\n\treturn pcommon.Timestamp(ms.orig.ObservedTimeUnixNano)\n}\n\n// SetObservedTimestamp replaces the observedtimestamp associated with this LogRecord.\nfunc (ms LogRecord) SetObservedTimestamp(v pcommon.Timestamp) {\n\tms.state.AssertMutable()\n\tms.orig.ObservedTimeUnixNano = uint64(v)\n}\n\n// SeverityNumber returns the severitynumber associated with this LogRecord.\nfunc (ms LogRecord) SeverityNumber() SeverityNumber {\n\treturn SeverityNumber(ms.orig.SeverityNumber)\n}\n\n// SetSeverityNumber replaces the severitynumber associated with this LogRecord.\nfunc (ms LogRecord) SetSeverityNumber(v SeverityNumber) {\n\tms.state.AssertMutable()\n\tms.orig.SeverityNumber = internal.SeverityNumber(v)\n}\n\n// SeverityText returns the severitytext associated with this LogRecord.\nfunc (ms LogRecord) SeverityText() string {\n\treturn ms.orig.SeverityText\n}\n\n// SetSeverityText replaces the severitytext associated with this LogRecord.\nfunc (ms LogRecord) SetSeverityText(v string) {\n\tms.state.AssertMutable()\n\tms.orig.SeverityText = v\n}\n\n// Body returns the body associated with this LogRecord.\nfunc (ms LogRecord) Body() pcommon.Value {\n\treturn pcommon.Value(internal.NewValueWrapper(&ms.orig.Body, ms.state))\n}\n\n// Attributes returns the Attributes associated with this LogRecord.\nfunc (ms LogRecord) Attributes() pcommon.Map {\n\treturn pcommon.Map(internal.NewMapWrapper(&ms.orig.Attributes, ms.state))\n}\n\n// DroppedAttributesCount returns the droppedattributescount associated with this LogRecord.\nfunc (ms LogRecord) DroppedAttributesCount() uint32 {\n\treturn ms.orig.DroppedAttributesCount\n}\n\n// SetDroppedAttributesCount replaces the droppedattributescount associated with this LogRecord.\nfunc (ms LogRecord) SetDroppedAttributesCount(v uint32) {\n\tms.state.AssertMutable()\n\tms.orig.DroppedAttributesCount = v\n}\n\n// Flags returns the flags associated with this LogRecord.\nfunc (ms LogRecord) Flags() LogRecordFlags {\n\treturn LogRecordFlags(ms.orig.Flags)\n}\n\n// SetFlags replaces the flags associated with this LogRecord.\nfunc (ms LogRecord) SetFlags(v LogRecordFlags) {\n\tms.state.AssertMutable()\n\tms.orig.Flags = uint32(v)\n}\n\n// TraceID returns the traceid associated with this LogRecord.\nfunc (ms LogRecord) TraceID() pcommon.TraceID {\n\treturn pcommon.TraceID(ms.orig.TraceId)\n}\n\n// SetTraceID replaces the traceid associated with this LogRecord.\nfunc (ms LogRecord) SetTraceID(v pcommon.TraceID) {\n\tms.state.AssertMutable()\n\tms.orig.TraceId = internal.TraceID(v)\n}\n\n// SpanID returns the spanid associated with this LogRecord.\nfunc (ms LogRecord) SpanID() pcommon.SpanID {\n\treturn pcommon.SpanID(ms.orig.SpanId)\n}\n\n// SetSpanID replaces the spanid associated with this LogRecord.\nfunc (ms LogRecord) SetSpanID(v pcommon.SpanID) {\n\tms.state.AssertMutable()\n\tms.orig.SpanId = internal.SpanID(v)\n}\n\n// EventName returns the eventname associated with this LogRecord.\nfunc (ms LogRecord) EventName() string {\n\treturn ms.orig.EventName\n}\n\n// SetEventName replaces the eventname associated with this LogRecord.\nfunc (ms LogRecord) SetEventName(v string) {\n\tms.state.AssertMutable()\n\tms.orig.EventName = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms LogRecord) CopyTo(dest LogRecord) {\n\tdest.state.AssertMutable()\n\tinternal.CopyLogRecord(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/plog/generated_logrecord_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plog\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestLogRecord_MoveTo(t *testing.T) {\n\tms := generateTestLogRecord()\n\tdest := NewLogRecord()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewLogRecord(), ms)\n\tassert.Equal(t, generateTestLogRecord(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestLogRecord(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newLogRecord(internal.NewLogRecord(), sharedState)) })\n\tassert.Panics(t, func() { newLogRecord(internal.NewLogRecord(), sharedState).MoveTo(dest) })\n}\n\nfunc TestLogRecord_CopyTo(t *testing.T) {\n\tms := NewLogRecord()\n\torig := NewLogRecord()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestLogRecord()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newLogRecord(internal.NewLogRecord(), sharedState)) })\n}\n\nfunc TestLogRecord_Timestamp(t *testing.T) {\n\tms := NewLogRecord()\n\tassert.Equal(t, pcommon.Timestamp(0), ms.Timestamp())\n\ttestValTimestamp := pcommon.Timestamp(1234567890)\n\tms.SetTimestamp(testValTimestamp)\n\tassert.Equal(t, testValTimestamp, ms.Timestamp())\n}\n\nfunc TestLogRecord_ObservedTimestamp(t *testing.T) {\n\tms := NewLogRecord()\n\tassert.Equal(t, pcommon.Timestamp(0), ms.ObservedTimestamp())\n\ttestValObservedTimestamp := pcommon.Timestamp(1234567890)\n\tms.SetObservedTimestamp(testValObservedTimestamp)\n\tassert.Equal(t, testValObservedTimestamp, ms.ObservedTimestamp())\n}\n\nfunc TestLogRecord_SeverityNumber(t *testing.T) {\n\tms := NewLogRecord()\n\tassert.Equal(t, SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_UNSPECIFIED), ms.SeverityNumber())\n\ttestValSeverityNumber := SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_DEBUG)\n\tms.SetSeverityNumber(testValSeverityNumber)\n\tassert.Equal(t, testValSeverityNumber, ms.SeverityNumber())\n}\n\nfunc TestLogRecord_SeverityText(t *testing.T) {\n\tms := NewLogRecord()\n\tassert.Empty(t, ms.SeverityText())\n\tms.SetSeverityText(\"test_severitytext\")\n\tassert.Equal(t, \"test_severitytext\", ms.SeverityText())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newLogRecord(internal.NewLogRecord(), sharedState).SetSeverityText(\"test_severitytext\") })\n}\n\nfunc TestLogRecord_Body(t *testing.T) {\n\tms := NewLogRecord()\n\tassert.Equal(t, pcommon.NewValueEmpty(), ms.Body())\n\tms.orig.Body = *internal.GenTestAnyValue()\n\tassert.Equal(t, pcommon.Value(internal.GenTestValueWrapper()), ms.Body())\n}\n\nfunc TestLogRecord_Attributes(t *testing.T) {\n\tms := NewLogRecord()\n\tassert.Equal(t, pcommon.NewMap(), ms.Attributes())\n\tms.orig.Attributes = internal.GenTestKeyValueSlice()\n\tassert.Equal(t, pcommon.Map(internal.GenTestMapWrapper()), ms.Attributes())\n}\n\nfunc TestLogRecord_DroppedAttributesCount(t *testing.T) {\n\tms := NewLogRecord()\n\tassert.Equal(t, uint32(0), ms.DroppedAttributesCount())\n\tms.SetDroppedAttributesCount(uint32(13))\n\tassert.Equal(t, uint32(13), ms.DroppedAttributesCount())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newLogRecord(internal.NewLogRecord(), sharedState).SetDroppedAttributesCount(uint32(13)) })\n}\n\nfunc TestLogRecord_Flags(t *testing.T) {\n\tms := NewLogRecord()\n\tassert.Equal(t, LogRecordFlags(0), ms.Flags())\n\ttestValFlags := LogRecordFlags(1)\n\tms.SetFlags(testValFlags)\n\tassert.Equal(t, testValFlags, ms.Flags())\n}\n\nfunc TestLogRecord_TraceID(t *testing.T) {\n\tms := NewLogRecord()\n\tassert.Equal(t, pcommon.TraceID(internal.TraceID([16]byte{})), ms.TraceID())\n\ttestValTraceID := pcommon.TraceID(internal.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1}))\n\tms.SetTraceID(testValTraceID)\n\tassert.Equal(t, testValTraceID, ms.TraceID())\n}\n\nfunc TestLogRecord_SpanID(t *testing.T) {\n\tms := NewLogRecord()\n\tassert.Equal(t, pcommon.SpanID(internal.SpanID([8]byte{})), ms.SpanID())\n\ttestValSpanID := pcommon.SpanID(internal.SpanID([8]byte{8, 7, 6, 5, 4, 3, 2, 1}))\n\tms.SetSpanID(testValSpanID)\n\tassert.Equal(t, testValSpanID, ms.SpanID())\n}\n\nfunc TestLogRecord_EventName(t *testing.T) {\n\tms := NewLogRecord()\n\tassert.Empty(t, ms.EventName())\n\tms.SetEventName(\"test_eventname\")\n\tassert.Equal(t, \"test_eventname\", ms.EventName())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newLogRecord(internal.NewLogRecord(), sharedState).SetEventName(\"test_eventname\") })\n}\n\nfunc generateTestLogRecord() LogRecord {\n\treturn newLogRecord(internal.GenTestLogRecord(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/plog/generated_logrecordslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plog\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// LogRecordSlice logically represents a slice of LogRecord.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewLogRecordSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype LogRecordSlice struct {\n\torig  *[]*internal.LogRecord\n\tstate *internal.State\n}\n\nfunc newLogRecordSlice(orig *[]*internal.LogRecord, state *internal.State) LogRecordSlice {\n\treturn LogRecordSlice{orig: orig, state: state}\n}\n\n// NewLogRecordSlice creates a LogRecordSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewLogRecordSlice() LogRecordSlice {\n\torig := []*internal.LogRecord(nil)\n\treturn newLogRecordSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewLogRecordSlice()\".\nfunc (es LogRecordSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es LogRecordSlice) At(i int) LogRecord {\n\treturn newLogRecord((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es LogRecordSlice) All() iter.Seq2[int, LogRecord] {\n\treturn func(yield func(int, LogRecord) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new LogRecordSlice can be initialized:\n//\n//\tes := NewLogRecordSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es LogRecordSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.LogRecord, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty LogRecord.\n// It returns the newly added LogRecord.\nfunc (es LogRecordSlice) AppendEmpty() LogRecord {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewLogRecord())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es LogRecordSlice) MoveAndAppendTo(dest LogRecordSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es LogRecordSlice) RemoveIf(f func(LogRecord) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteLogRecord((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es LogRecordSlice) CopyTo(dest LogRecordSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyLogRecordPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the LogRecord elements within LogRecordSlice given the\n// provided less function so that two instances of LogRecordSlice\n// can be compared.\nfunc (es LogRecordSlice) Sort(less func(a, b LogRecord) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/plog/generated_logrecordslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plog\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestLogRecordSlice(t *testing.T) {\n\tes := NewLogRecordSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newLogRecordSlice(&[]*internal.LogRecord{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewLogRecord()\n\ttestVal := generateTestLogRecord()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestLogRecord()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestLogRecordSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newLogRecordSlice(&[]*internal.LogRecord{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewLogRecordSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestLogRecordSlice_CopyTo(t *testing.T) {\n\tdest := NewLogRecordSlice()\n\tsrc := generateTestLogRecordSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestLogRecordSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestLogRecordSlice(), dest)\n}\n\nfunc TestLogRecordSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestLogRecordSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestLogRecordSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestLogRecordSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestLogRecordSlice(), es)\n}\n\nfunc TestLogRecordSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestLogRecordSlice()\n\tdest := NewLogRecordSlice()\n\tsrc := generateTestLogRecordSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestLogRecordSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestLogRecordSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestLogRecordSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestLogRecordSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewLogRecordSlice()\n\temptySlice.RemoveIf(func(el LogRecord) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestLogRecordSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el LogRecord) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestLogRecordSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestLogRecordSlice()\n\tgot.RemoveIf(func(el LogRecord) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestLogRecordSliceAll(t *testing.T) {\n\tms := generateTestLogRecordSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestLogRecordSlice_Sort(t *testing.T) {\n\tes := generateTestLogRecordSlice()\n\tes.Sort(func(a, b LogRecord) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b LogRecord) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestLogRecordSlice() LogRecordSlice {\n\tms := NewLogRecordSlice()\n\t*ms.orig = internal.GenTestLogRecordPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/plog/generated_logs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plog\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// Logs is the top-level struct that is propagated through the logs pipeline.\n// Use NewLogs to create new instance, zero-initialized instance is not valid for use.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewLogs function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Logs internal.LogsWrapper\n\nfunc newLogs(orig *internal.ExportLogsServiceRequest, state *internal.State) Logs {\n\treturn Logs(internal.NewLogsWrapper(orig, state))\n}\n\n// NewLogs creates a new empty Logs.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewLogs() Logs {\n\treturn newLogs(internal.NewExportLogsServiceRequest(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Logs) MoveTo(dest Logs) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\tinternal.DeleteExportLogsServiceRequest(dest.getOrig(), false)\n\t*dest.getOrig(), *ms.getOrig() = *ms.getOrig(), *dest.getOrig()\n}\n\n// ResourceLogs returns the ResourceLogs associated with this Logs.\nfunc (ms Logs) ResourceLogs() ResourceLogsSlice {\n\treturn newResourceLogsSlice(&ms.getOrig().ResourceLogs, ms.getState())\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Logs) CopyTo(dest Logs) {\n\tdest.getState().AssertMutable()\n\tinternal.CopyExportLogsServiceRequest(dest.getOrig(), ms.getOrig())\n}\n\nfunc (ms Logs) getOrig() *internal.ExportLogsServiceRequest {\n\treturn internal.GetLogsOrig(internal.LogsWrapper(ms))\n}\n\nfunc (ms Logs) getState() *internal.State {\n\treturn internal.GetLogsState(internal.LogsWrapper(ms))\n}\n"
  },
  {
    "path": "pdata/plog/generated_logs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plog\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestLogs_MoveTo(t *testing.T) {\n\tms := generateTestLogs()\n\tdest := NewLogs()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewLogs(), ms)\n\tassert.Equal(t, generateTestLogs(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestLogs(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newLogs(internal.NewExportLogsServiceRequest(), sharedState)) })\n\tassert.Panics(t, func() { newLogs(internal.NewExportLogsServiceRequest(), sharedState).MoveTo(dest) })\n}\n\nfunc TestLogs_CopyTo(t *testing.T) {\n\tms := NewLogs()\n\torig := NewLogs()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestLogs()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newLogs(internal.NewExportLogsServiceRequest(), sharedState)) })\n}\n\nfunc TestLogs_ResourceLogs(t *testing.T) {\n\tms := NewLogs()\n\tassert.Equal(t, NewResourceLogsSlice(), ms.ResourceLogs())\n\tms.getOrig().ResourceLogs = internal.GenTestResourceLogsPtrSlice()\n\tassert.Equal(t, generateTestResourceLogsSlice(), ms.ResourceLogs())\n}\n\nfunc generateTestLogs() Logs {\n\treturn newLogs(internal.GenTestExportLogsServiceRequest(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/plog/generated_resourcelogs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plog\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ResourceLogs is a collection of logs from a Resource.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewResourceLogs function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ResourceLogs struct {\n\torig  *internal.ResourceLogs\n\tstate *internal.State\n}\n\nfunc newResourceLogs(orig *internal.ResourceLogs, state *internal.State) ResourceLogs {\n\treturn ResourceLogs{orig: orig, state: state}\n}\n\n// NewResourceLogs creates a new empty ResourceLogs.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewResourceLogs() ResourceLogs {\n\treturn newResourceLogs(internal.NewResourceLogs(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ResourceLogs) MoveTo(dest ResourceLogs) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteResourceLogs(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Resource returns the resource associated with this ResourceLogs.\nfunc (ms ResourceLogs) Resource() pcommon.Resource {\n\treturn pcommon.Resource(internal.NewResourceWrapper(&ms.orig.Resource, ms.state))\n}\n\n// ScopeLogs returns the ScopeLogs associated with this ResourceLogs.\nfunc (ms ResourceLogs) ScopeLogs() ScopeLogsSlice {\n\treturn newScopeLogsSlice(&ms.orig.ScopeLogs, ms.state)\n}\n\n// SchemaUrl returns the schemaurl associated with this ResourceLogs.\nfunc (ms ResourceLogs) SchemaUrl() string {\n\treturn ms.orig.SchemaUrl\n}\n\n// SetSchemaUrl replaces the schemaurl associated with this ResourceLogs.\nfunc (ms ResourceLogs) SetSchemaUrl(v string) {\n\tms.state.AssertMutable()\n\tms.orig.SchemaUrl = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ResourceLogs) CopyTo(dest ResourceLogs) {\n\tdest.state.AssertMutable()\n\tinternal.CopyResourceLogs(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/plog/generated_resourcelogs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plog\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestResourceLogs_MoveTo(t *testing.T) {\n\tms := generateTestResourceLogs()\n\tdest := NewResourceLogs()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewResourceLogs(), ms)\n\tassert.Equal(t, generateTestResourceLogs(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestResourceLogs(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newResourceLogs(internal.NewResourceLogs(), sharedState)) })\n\tassert.Panics(t, func() { newResourceLogs(internal.NewResourceLogs(), sharedState).MoveTo(dest) })\n}\n\nfunc TestResourceLogs_CopyTo(t *testing.T) {\n\tms := NewResourceLogs()\n\torig := NewResourceLogs()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestResourceLogs()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newResourceLogs(internal.NewResourceLogs(), sharedState)) })\n}\n\nfunc TestResourceLogs_Resource(t *testing.T) {\n\tms := NewResourceLogs()\n\tassert.Equal(t, pcommon.NewResource(), ms.Resource())\n\tms.orig.Resource = *internal.GenTestResource()\n\tassert.Equal(t, pcommon.Resource(internal.GenTestResourceWrapper()), ms.Resource())\n}\n\nfunc TestResourceLogs_ScopeLogs(t *testing.T) {\n\tms := NewResourceLogs()\n\tassert.Equal(t, NewScopeLogsSlice(), ms.ScopeLogs())\n\tms.orig.ScopeLogs = internal.GenTestScopeLogsPtrSlice()\n\tassert.Equal(t, generateTestScopeLogsSlice(), ms.ScopeLogs())\n}\n\nfunc TestResourceLogs_SchemaUrl(t *testing.T) {\n\tms := NewResourceLogs()\n\tassert.Empty(t, ms.SchemaUrl())\n\tms.SetSchemaUrl(\"test_schemaurl\")\n\tassert.Equal(t, \"test_schemaurl\", ms.SchemaUrl())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newResourceLogs(internal.NewResourceLogs(), sharedState).SetSchemaUrl(\"test_schemaurl\") })\n}\n\nfunc generateTestResourceLogs() ResourceLogs {\n\treturn newResourceLogs(internal.GenTestResourceLogs(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/plog/generated_resourcelogsslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plog\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ResourceLogsSlice logically represents a slice of ResourceLogs.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewResourceLogsSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ResourceLogsSlice struct {\n\torig  *[]*internal.ResourceLogs\n\tstate *internal.State\n}\n\nfunc newResourceLogsSlice(orig *[]*internal.ResourceLogs, state *internal.State) ResourceLogsSlice {\n\treturn ResourceLogsSlice{orig: orig, state: state}\n}\n\n// NewResourceLogsSlice creates a ResourceLogsSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewResourceLogsSlice() ResourceLogsSlice {\n\torig := []*internal.ResourceLogs(nil)\n\treturn newResourceLogsSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewResourceLogsSlice()\".\nfunc (es ResourceLogsSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es ResourceLogsSlice) At(i int) ResourceLogs {\n\treturn newResourceLogs((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es ResourceLogsSlice) All() iter.Seq2[int, ResourceLogs] {\n\treturn func(yield func(int, ResourceLogs) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new ResourceLogsSlice can be initialized:\n//\n//\tes := NewResourceLogsSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es ResourceLogsSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.ResourceLogs, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty ResourceLogs.\n// It returns the newly added ResourceLogs.\nfunc (es ResourceLogsSlice) AppendEmpty() ResourceLogs {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewResourceLogs())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es ResourceLogsSlice) MoveAndAppendTo(dest ResourceLogsSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es ResourceLogsSlice) RemoveIf(f func(ResourceLogs) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteResourceLogs((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es ResourceLogsSlice) CopyTo(dest ResourceLogsSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyResourceLogsPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the ResourceLogs elements within ResourceLogsSlice given the\n// provided less function so that two instances of ResourceLogsSlice\n// can be compared.\nfunc (es ResourceLogsSlice) Sort(less func(a, b ResourceLogs) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/plog/generated_resourcelogsslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plog\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestResourceLogsSlice(t *testing.T) {\n\tes := NewResourceLogsSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newResourceLogsSlice(&[]*internal.ResourceLogs{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewResourceLogs()\n\ttestVal := generateTestResourceLogs()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestResourceLogs()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestResourceLogsSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newResourceLogsSlice(&[]*internal.ResourceLogs{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewResourceLogsSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestResourceLogsSlice_CopyTo(t *testing.T) {\n\tdest := NewResourceLogsSlice()\n\tsrc := generateTestResourceLogsSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestResourceLogsSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestResourceLogsSlice(), dest)\n}\n\nfunc TestResourceLogsSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestResourceLogsSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestResourceLogsSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestResourceLogsSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestResourceLogsSlice(), es)\n}\n\nfunc TestResourceLogsSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestResourceLogsSlice()\n\tdest := NewResourceLogsSlice()\n\tsrc := generateTestResourceLogsSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestResourceLogsSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestResourceLogsSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestResourceLogsSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestResourceLogsSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewResourceLogsSlice()\n\temptySlice.RemoveIf(func(el ResourceLogs) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestResourceLogsSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el ResourceLogs) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestResourceLogsSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestResourceLogsSlice()\n\tgot.RemoveIf(func(el ResourceLogs) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestResourceLogsSliceAll(t *testing.T) {\n\tms := generateTestResourceLogsSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestResourceLogsSlice_Sort(t *testing.T) {\n\tes := generateTestResourceLogsSlice()\n\tes.Sort(func(a, b ResourceLogs) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b ResourceLogs) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestResourceLogsSlice() ResourceLogsSlice {\n\tms := NewResourceLogsSlice()\n\t*ms.orig = internal.GenTestResourceLogsPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/plog/generated_scopelogs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plog\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ScopeLogs is a collection of logs from a LibraryInstrumentation.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewScopeLogs function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ScopeLogs struct {\n\torig  *internal.ScopeLogs\n\tstate *internal.State\n}\n\nfunc newScopeLogs(orig *internal.ScopeLogs, state *internal.State) ScopeLogs {\n\treturn ScopeLogs{orig: orig, state: state}\n}\n\n// NewScopeLogs creates a new empty ScopeLogs.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewScopeLogs() ScopeLogs {\n\treturn newScopeLogs(internal.NewScopeLogs(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ScopeLogs) MoveTo(dest ScopeLogs) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteScopeLogs(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Scope returns the scope associated with this ScopeLogs.\nfunc (ms ScopeLogs) Scope() pcommon.InstrumentationScope {\n\treturn pcommon.InstrumentationScope(internal.NewInstrumentationScopeWrapper(&ms.orig.Scope, ms.state))\n}\n\n// LogRecords returns the LogRecords associated with this ScopeLogs.\nfunc (ms ScopeLogs) LogRecords() LogRecordSlice {\n\treturn newLogRecordSlice(&ms.orig.LogRecords, ms.state)\n}\n\n// SchemaUrl returns the schemaurl associated with this ScopeLogs.\nfunc (ms ScopeLogs) SchemaUrl() string {\n\treturn ms.orig.SchemaUrl\n}\n\n// SetSchemaUrl replaces the schemaurl associated with this ScopeLogs.\nfunc (ms ScopeLogs) SetSchemaUrl(v string) {\n\tms.state.AssertMutable()\n\tms.orig.SchemaUrl = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ScopeLogs) CopyTo(dest ScopeLogs) {\n\tdest.state.AssertMutable()\n\tinternal.CopyScopeLogs(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/plog/generated_scopelogs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plog\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestScopeLogs_MoveTo(t *testing.T) {\n\tms := generateTestScopeLogs()\n\tdest := NewScopeLogs()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewScopeLogs(), ms)\n\tassert.Equal(t, generateTestScopeLogs(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestScopeLogs(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newScopeLogs(internal.NewScopeLogs(), sharedState)) })\n\tassert.Panics(t, func() { newScopeLogs(internal.NewScopeLogs(), sharedState).MoveTo(dest) })\n}\n\nfunc TestScopeLogs_CopyTo(t *testing.T) {\n\tms := NewScopeLogs()\n\torig := NewScopeLogs()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestScopeLogs()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newScopeLogs(internal.NewScopeLogs(), sharedState)) })\n}\n\nfunc TestScopeLogs_Scope(t *testing.T) {\n\tms := NewScopeLogs()\n\tassert.Equal(t, pcommon.NewInstrumentationScope(), ms.Scope())\n\tms.orig.Scope = *internal.GenTestInstrumentationScope()\n\tassert.Equal(t, pcommon.InstrumentationScope(internal.GenTestInstrumentationScopeWrapper()), ms.Scope())\n}\n\nfunc TestScopeLogs_LogRecords(t *testing.T) {\n\tms := NewScopeLogs()\n\tassert.Equal(t, NewLogRecordSlice(), ms.LogRecords())\n\tms.orig.LogRecords = internal.GenTestLogRecordPtrSlice()\n\tassert.Equal(t, generateTestLogRecordSlice(), ms.LogRecords())\n}\n\nfunc TestScopeLogs_SchemaUrl(t *testing.T) {\n\tms := NewScopeLogs()\n\tassert.Empty(t, ms.SchemaUrl())\n\tms.SetSchemaUrl(\"test_schemaurl\")\n\tassert.Equal(t, \"test_schemaurl\", ms.SchemaUrl())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newScopeLogs(internal.NewScopeLogs(), sharedState).SetSchemaUrl(\"test_schemaurl\") })\n}\n\nfunc generateTestScopeLogs() ScopeLogs {\n\treturn newScopeLogs(internal.GenTestScopeLogs(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/plog/generated_scopelogsslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plog\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ScopeLogsSlice logically represents a slice of ScopeLogs.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewScopeLogsSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ScopeLogsSlice struct {\n\torig  *[]*internal.ScopeLogs\n\tstate *internal.State\n}\n\nfunc newScopeLogsSlice(orig *[]*internal.ScopeLogs, state *internal.State) ScopeLogsSlice {\n\treturn ScopeLogsSlice{orig: orig, state: state}\n}\n\n// NewScopeLogsSlice creates a ScopeLogsSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewScopeLogsSlice() ScopeLogsSlice {\n\torig := []*internal.ScopeLogs(nil)\n\treturn newScopeLogsSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewScopeLogsSlice()\".\nfunc (es ScopeLogsSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es ScopeLogsSlice) At(i int) ScopeLogs {\n\treturn newScopeLogs((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es ScopeLogsSlice) All() iter.Seq2[int, ScopeLogs] {\n\treturn func(yield func(int, ScopeLogs) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new ScopeLogsSlice can be initialized:\n//\n//\tes := NewScopeLogsSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es ScopeLogsSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.ScopeLogs, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty ScopeLogs.\n// It returns the newly added ScopeLogs.\nfunc (es ScopeLogsSlice) AppendEmpty() ScopeLogs {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewScopeLogs())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es ScopeLogsSlice) MoveAndAppendTo(dest ScopeLogsSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es ScopeLogsSlice) RemoveIf(f func(ScopeLogs) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteScopeLogs((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es ScopeLogsSlice) CopyTo(dest ScopeLogsSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyScopeLogsPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the ScopeLogs elements within ScopeLogsSlice given the\n// provided less function so that two instances of ScopeLogsSlice\n// can be compared.\nfunc (es ScopeLogsSlice) Sort(less func(a, b ScopeLogs) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/plog/generated_scopelogsslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plog\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestScopeLogsSlice(t *testing.T) {\n\tes := NewScopeLogsSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newScopeLogsSlice(&[]*internal.ScopeLogs{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewScopeLogs()\n\ttestVal := generateTestScopeLogs()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestScopeLogs()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestScopeLogsSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newScopeLogsSlice(&[]*internal.ScopeLogs{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewScopeLogsSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestScopeLogsSlice_CopyTo(t *testing.T) {\n\tdest := NewScopeLogsSlice()\n\tsrc := generateTestScopeLogsSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestScopeLogsSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestScopeLogsSlice(), dest)\n}\n\nfunc TestScopeLogsSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestScopeLogsSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestScopeLogsSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestScopeLogsSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestScopeLogsSlice(), es)\n}\n\nfunc TestScopeLogsSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestScopeLogsSlice()\n\tdest := NewScopeLogsSlice()\n\tsrc := generateTestScopeLogsSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestScopeLogsSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestScopeLogsSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestScopeLogsSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestScopeLogsSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewScopeLogsSlice()\n\temptySlice.RemoveIf(func(el ScopeLogs) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestScopeLogsSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el ScopeLogs) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestScopeLogsSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestScopeLogsSlice()\n\tgot.RemoveIf(func(el ScopeLogs) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestScopeLogsSliceAll(t *testing.T) {\n\tms := generateTestScopeLogsSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestScopeLogsSlice_Sort(t *testing.T) {\n\tes := generateTestScopeLogsSlice()\n\tes.Sort(func(a, b ScopeLogs) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b ScopeLogs) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestScopeLogsSlice() ScopeLogsSlice {\n\tms := NewScopeLogsSlice()\n\t*ms.orig = internal.GenTestScopeLogsPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/plog/json.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plog // import \"go.opentelemetry.io/collector/pdata/plog\"\n\nimport (\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otlp\"\n)\n\n// JSONMarshaler marshals Logs to JSON bytes using the OTLP/JSON format.\ntype JSONMarshaler struct{}\n\n// MarshalLogs to the OTLP/JSON format.\nfunc (*JSONMarshaler) MarshalLogs(ld Logs) ([]byte, error) {\n\tdest := json.BorrowStream(nil)\n\tdefer json.ReturnStream(dest)\n\tld.getOrig().MarshalJSON(dest)\n\tif dest.Error() != nil {\n\t\treturn nil, dest.Error()\n\t}\n\treturn slices.Clone(dest.Buffer()), nil\n}\n\nvar _ Unmarshaler = (*JSONUnmarshaler)(nil)\n\n// JSONUnmarshaler unmarshals OTLP/JSON formatted-bytes to Logs.\ntype JSONUnmarshaler struct{}\n\n// UnmarshalLogs from OTLP/JSON format into Logs.\nfunc (*JSONUnmarshaler) UnmarshalLogs(buf []byte) (Logs, error) {\n\titer := json.BorrowIterator(buf)\n\tdefer json.ReturnIterator(iter)\n\tld := NewLogs()\n\tld.getOrig().UnmarshalJSON(iter)\n\tif iter.Error() != nil {\n\t\treturn Logs{}, iter.Error()\n\t}\n\totlp.MigrateLogs(ld.getOrig().ResourceLogs)\n\treturn ld, nil\n}\n"
  },
  {
    "path": "pdata/plog/log_record_flags.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plog // import \"go.opentelemetry.io/collector/pdata/plog\"\n\nconst isSampledMask = uint32(1)\n\nvar DefaultLogRecordFlags = LogRecordFlags(0)\n\n// LogRecordFlags defines flags for the LogRecord. The 8 least significant bits are the trace flags as\n// defined in W3C Trace Context specification. 24 most significant bits are reserved and must be set to 0.\ntype LogRecordFlags uint32\n\n// IsSampled returns true if the LogRecordFlags contains the IsSampled flag.\nfunc (ms LogRecordFlags) IsSampled() bool {\n\treturn uint32(ms)&isSampledMask != 0\n}\n\n// WithIsSampled returns a new LogRecordFlags, with the IsSampled flag set to the given value.\nfunc (ms LogRecordFlags) WithIsSampled(b bool) LogRecordFlags {\n\torig := uint32(ms)\n\tif b {\n\t\torig |= isSampledMask\n\t} else {\n\t\torig &^= isSampledMask\n\t}\n\treturn LogRecordFlags(orig)\n}\n"
  },
  {
    "path": "pdata/plog/log_record_flags_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plog\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestLogRecordFlags(t *testing.T) {\n\tflags := LogRecordFlags(1)\n\tassert.True(t, flags.IsSampled())\n\tassert.EqualValues(t, uint32(1), flags)\n\n\tflags = flags.WithIsSampled(false)\n\tassert.False(t, flags.IsSampled())\n\tassert.EqualValues(t, uint32(0), flags)\n\n\tflags = flags.WithIsSampled(true)\n\tassert.True(t, flags.IsSampled())\n\tassert.EqualValues(t, uint32(1), flags)\n}\n\nfunc TestDefaultLogRecordFlags(t *testing.T) {\n\tflags := DefaultLogRecordFlags\n\tassert.False(t, flags.IsSampled())\n\tassert.EqualValues(t, uint32(0), flags)\n}\n"
  },
  {
    "path": "pdata/plog/logs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plog // import \"go.opentelemetry.io/collector/pdata/plog\"\n\n// MarkReadOnly marks the Logs as shared so that no further modifications can be done on it.\nfunc (ms Logs) MarkReadOnly() {\n\tms.getState().MarkReadOnly()\n}\n\n// IsReadOnly returns true if this Logs instance is read-only.\nfunc (ms Logs) IsReadOnly() bool {\n\treturn ms.getState().IsReadOnly()\n}\n\n// LogRecordCount calculates the total number of log records.\nfunc (ms Logs) LogRecordCount() int {\n\tlogCount := 0\n\trss := ms.ResourceLogs()\n\tfor i := 0; i < rss.Len(); i++ {\n\t\trs := rss.At(i)\n\t\till := rs.ScopeLogs()\n\t\tfor i := 0; i < ill.Len(); i++ {\n\t\t\tlogs := ill.At(i)\n\t\t\tlogCount += logs.LogRecords().Len()\n\t\t}\n\t}\n\treturn logCount\n}\n"
  },
  {
    "path": "pdata/plog/logs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plog\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestLogRecordCount(t *testing.T) {\n\tlogs := NewLogs()\n\tassert.Equal(t, 0, logs.LogRecordCount())\n\n\trl := logs.ResourceLogs().AppendEmpty()\n\tassert.Equal(t, 0, logs.LogRecordCount())\n\n\till := rl.ScopeLogs().AppendEmpty()\n\tassert.Equal(t, 0, logs.LogRecordCount())\n\n\till.LogRecords().AppendEmpty()\n\tassert.Equal(t, 1, logs.LogRecordCount())\n\n\trms := logs.ResourceLogs()\n\trms.EnsureCapacity(3)\n\trms.AppendEmpty().ScopeLogs().AppendEmpty()\n\tilll := rms.AppendEmpty().ScopeLogs().AppendEmpty().LogRecords()\n\tfor range 5 {\n\t\tilll.AppendEmpty()\n\t}\n\t// 5 + 1 (from rms.At(0) initialized first)\n\tassert.Equal(t, 6, logs.LogRecordCount())\n}\n\nfunc TestLogRecordCountWithEmpty(t *testing.T) {\n\tassert.Zero(t, NewLogs().LogRecordCount())\n\tassert.Zero(t, newLogs(&internal.ExportLogsServiceRequest{\n\t\tResourceLogs: []*internal.ResourceLogs{{}},\n\t}, new(internal.State)).LogRecordCount())\n\tassert.Zero(t, newLogs(&internal.ExportLogsServiceRequest{\n\t\tResourceLogs: []*internal.ResourceLogs{\n\t\t\t{\n\t\t\t\tScopeLogs: []*internal.ScopeLogs{{}},\n\t\t\t},\n\t\t},\n\t}, new(internal.State)).LogRecordCount())\n\tassert.Equal(t, 1, newLogs(&internal.ExportLogsServiceRequest{\n\t\tResourceLogs: []*internal.ResourceLogs{\n\t\t\t{\n\t\t\t\tScopeLogs: []*internal.ScopeLogs{\n\t\t\t\t\t{\n\t\t\t\t\t\tLogRecords: []*internal.LogRecord{{}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, new(internal.State)).LogRecordCount())\n}\n\nfunc TestReadOnlyLogsInvalidUsage(t *testing.T) {\n\tld := NewLogs()\n\tassert.False(t, ld.IsReadOnly())\n\tres := ld.ResourceLogs().AppendEmpty().Resource()\n\tres.Attributes().PutStr(\"k1\", \"v1\")\n\tld.MarkReadOnly()\n\tassert.True(t, ld.IsReadOnly())\n\tassert.Panics(t, func() { res.Attributes().PutStr(\"k2\", \"v2\") })\n}\n\nfunc BenchmarkLogsUsage(b *testing.B) {\n\tld := generateTestLogs()\n\n\tts := pcommon.NewTimestampFromTime(time.Now())\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tfor i := 0; i < ld.ResourceLogs().Len(); i++ {\n\t\t\trl := ld.ResourceLogs().At(i)\n\t\t\tres := rl.Resource()\n\t\t\tres.Attributes().PutStr(\"foo\", \"bar\")\n\t\t\tv, ok := res.Attributes().Get(\"foo\")\n\t\t\tassert.True(b, ok)\n\t\t\tassert.Equal(b, \"bar\", v.Str())\n\t\t\tv.SetStr(\"new-bar\")\n\t\t\tassert.Equal(b, \"new-bar\", v.Str())\n\t\t\tres.Attributes().Remove(\"foo\")\n\t\t\tfor j := 0; j < rl.ScopeLogs().Len(); j++ {\n\t\t\t\tsl := rl.ScopeLogs().At(j)\n\t\t\t\tsl.Scope().SetName(\"new_test_name\")\n\t\t\t\tassert.Equal(b, \"new_test_name\", sl.Scope().Name())\n\t\t\t\tfor k := 0; k < sl.LogRecords().Len(); k++ {\n\t\t\t\t\tlr := sl.LogRecords().At(k)\n\t\t\t\t\tlr.Body().SetStr(\"new_body\")\n\t\t\t\t\tassert.Equal(b, \"new_body\", lr.Body().Str())\n\t\t\t\t\tlr.SetTimestamp(ts)\n\t\t\t\t\tassert.Equal(b, ts, lr.Timestamp())\n\t\t\t\t}\n\t\t\t\tlr := sl.LogRecords().AppendEmpty()\n\t\t\t\tlr.Body().SetStr(\"another_log_record\")\n\t\t\t\tlr.SetTimestamp(ts)\n\t\t\t\tlr.SetObservedTimestamp(ts)\n\t\t\t\tlr.SetSeverityText(\"info\")\n\t\t\t\tlr.SetSeverityNumber(SeverityNumberInfo)\n\t\t\t\tlr.Attributes().PutStr(\"foo\", \"bar\")\n\t\t\t\tlr.SetSpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8})\n\t\t\t\tsl.LogRecords().RemoveIf(func(lr LogRecord) bool {\n\t\t\t\t\treturn lr.Body().Str() == \"another_log_record\"\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc BenchmarkLogsMarshalJSON(b *testing.B) {\n\tld := generateTestLogs()\n\tencoder := &JSONMarshaler{}\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tjsonBuf, err := encoder.MarshalLogs(ld)\n\t\trequire.NoError(b, err)\n\t\trequire.NotNil(b, jsonBuf)\n\t}\n}\n"
  },
  {
    "path": "pdata/plog/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plog\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "pdata/plog/pb.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plog // import \"go.opentelemetry.io/collector/pdata/plog\"\n\nvar _ MarshalSizer = (*ProtoMarshaler)(nil)\n\ntype ProtoMarshaler struct{}\n\nfunc (e *ProtoMarshaler) MarshalLogs(ld Logs) ([]byte, error) {\n\tsize := ld.getOrig().SizeProto()\n\tbuf := make([]byte, size)\n\t_ = ld.getOrig().MarshalProto(buf)\n\treturn buf, nil\n}\n\nfunc (e *ProtoMarshaler) LogsSize(ld Logs) int {\n\treturn ld.getOrig().SizeProto()\n}\n\nfunc (e *ProtoMarshaler) ResourceLogsSize(ld ResourceLogs) int {\n\treturn ld.orig.SizeProto()\n}\n\nfunc (e *ProtoMarshaler) ScopeLogsSize(ld ScopeLogs) int {\n\treturn ld.orig.SizeProto()\n}\n\nfunc (e *ProtoMarshaler) LogRecordSize(ld LogRecord) int {\n\treturn ld.orig.SizeProto()\n}\n\nvar _ Unmarshaler = (*ProtoUnmarshaler)(nil)\n\ntype ProtoUnmarshaler struct{}\n\nfunc (d *ProtoUnmarshaler) UnmarshalLogs(buf []byte) (Logs, error) {\n\tld := NewLogs()\n\terr := ld.getOrig().UnmarshalProto(buf)\n\tif err != nil {\n\t\treturn Logs{}, err\n\t}\n\treturn ld, nil\n}\n"
  },
  {
    "path": "pdata/plog/pb_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plog\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlplogs \"go.opentelemetry.io/proto/slim/otlp/logs/v1\"\n\tgoproto \"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestLogsProtoWireCompatibility(t *testing.T) {\n\t// This test verifies that OTLP ProtoBufs generated using goproto lib in\n\t// opentelemetry-proto repository OTLP ProtoBufs generated using gogoproto lib in\n\t// this repository are wire compatible.\n\n\t// Generate Logs as pdata struct.\n\ttd := generateTestLogs()\n\n\t// Marshal its underlying ProtoBuf to wire.\n\tmarshaler := &ProtoMarshaler{}\n\twire1, err := marshaler.MarshalLogs(td)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, wire1)\n\n\t// Unmarshal from the wire to OTLP Protobuf in goproto's representation.\n\tvar goprotoMessage gootlplogs.LogsData\n\terr = goproto.Unmarshal(wire1, &goprotoMessage)\n\trequire.NoError(t, err)\n\n\t// Marshal to the wire again.\n\twire2, err := goproto.Marshal(&goprotoMessage)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, wire2)\n\n\t// Unmarshal from the wire into gogoproto's representation.\n\tvar td2 Logs\n\tunmarshaler := &ProtoUnmarshaler{}\n\ttd2, err = unmarshaler.UnmarshalLogs(wire2)\n\trequire.NoError(t, err)\n\n\t// Now compare that the original and final ProtoBuf messages are the same.\n\t// This proves that goproto and gogoproto marshaling/unmarshaling are wire compatible.\n\tassert.Equal(t, td, td2)\n}\n\nfunc TestProtoLogsUnmarshalerError(t *testing.T) {\n\tp := &ProtoUnmarshaler{}\n\t_, err := p.UnmarshalLogs([]byte(\"+$%\"))\n\tassert.Error(t, err)\n}\n\nfunc TestProtoSizer(t *testing.T) {\n\tmarshaler := &ProtoMarshaler{}\n\tld := NewLogs()\n\tld.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty().SetSeverityText(\"error\")\n\n\tsize := marshaler.LogsSize(ld)\n\n\tbytes, err := marshaler.MarshalLogs(ld)\n\trequire.NoError(t, err)\n\tassert.Equal(t, len(bytes), size)\n}\n\nfunc TestProtoSizerEmptyLogs(t *testing.T) {\n\tsizer := &ProtoMarshaler{}\n\tassert.Equal(t, 0, sizer.LogsSize(NewLogs()))\n}\n\nfunc BenchmarkLogsToProto2k(b *testing.B) {\n\tmarshaler := &ProtoMarshaler{}\n\tlogs := generateBenchmarkLogs(2_000)\n\n\tfor b.Loop() {\n\t\tbuf, err := marshaler.MarshalLogs(logs)\n\t\trequire.NoError(b, err)\n\t\tassert.NotEmpty(b, buf)\n\t}\n}\n\nfunc BenchmarkLogsFromProto2k(b *testing.B) {\n\tmarshaler := &ProtoMarshaler{}\n\tunmarshaler := &ProtoUnmarshaler{}\n\tbaseLogs := generateBenchmarkLogs(2_000)\n\tbuf, err := marshaler.MarshalLogs(baseLogs)\n\trequire.NoError(b, err)\n\tassert.NotEmpty(b, buf)\n\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tlogs, err := unmarshaler.UnmarshalLogs(buf)\n\t\trequire.NoError(b, err)\n\t\tassert.Equal(b, baseLogs.ResourceLogs().Len(), logs.ResourceLogs().Len())\n\t}\n}\n\nfunc generateBenchmarkLogs(logsCount int) Logs {\n\tendTime := pcommon.NewTimestampFromTime(time.Now())\n\n\tmd := NewLogs()\n\tilm := md.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty()\n\tilm.LogRecords().EnsureCapacity(logsCount)\n\tfor range logsCount {\n\t\tim := ilm.LogRecords().AppendEmpty()\n\t\tim.SetTimestamp(endTime)\n\t}\n\treturn md\n}\n"
  },
  {
    "path": "pdata/plog/plogotlp/fuzz_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plogotlp // import \"go.opentelemetry.io/collector/pdata/plog/plogotlp\"\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar unexpectedBytes = \"expected the same bytes from unmarshaling and marshaling.\"\n\nfunc FuzzRequestUnmarshalJSON(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\ter := NewExportRequest()\n\t\terr := er.UnmarshalJSON(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tb1, err := er.MarshalJSON()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\ter = NewExportRequest()\n\t\trequire.NoError(t, er.UnmarshalJSON(b1), \"failed to unmarshal valid bytes\")\n\t\tb2, err := er.MarshalJSON()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n\nfunc FuzzResponseUnmarshalJSON(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\ter := NewExportResponse()\n\t\terr := er.UnmarshalJSON(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tb1, err := er.MarshalJSON()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\ter = NewExportResponse()\n\t\trequire.NoError(t, er.UnmarshalJSON(b1), \"failed to unmarshal valid bytes\")\n\t\tb2, err := er.MarshalJSON()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n\nfunc FuzzRequestUnmarshalProto(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\ter := NewExportRequest()\n\t\terr := er.UnmarshalProto(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tb1, err := er.MarshalProto()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\t\ter = NewExportRequest()\n\t\trequire.NoError(t, er.UnmarshalProto(b1), \"failed to unmarshal valid bytes\")\n\t\tb2, err := er.MarshalProto()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n\nfunc FuzzResponseUnmarshalProto(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\ter := NewExportResponse()\n\t\terr := er.UnmarshalProto(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tb1, err := er.MarshalProto()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\ter = NewExportResponse()\n\t\trequire.NoError(t, er.UnmarshalProto(b1), \"failed to unmarshal valid bytes\")\n\t\tb2, err := er.MarshalProto()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n"
  },
  {
    "path": "pdata/plog/plogotlp/generated_exportpartialsuccess.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plogotlp\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ExportPartialSuccess represents the details of a partially successful export request.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewExportPartialSuccess function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ExportPartialSuccess struct {\n\torig  *internal.ExportLogsPartialSuccess\n\tstate *internal.State\n}\n\nfunc newExportPartialSuccess(orig *internal.ExportLogsPartialSuccess, state *internal.State) ExportPartialSuccess {\n\treturn ExportPartialSuccess{orig: orig, state: state}\n}\n\n// NewExportPartialSuccess creates a new empty ExportPartialSuccess.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewExportPartialSuccess() ExportPartialSuccess {\n\treturn newExportPartialSuccess(internal.NewExportLogsPartialSuccess(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ExportPartialSuccess) MoveTo(dest ExportPartialSuccess) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteExportLogsPartialSuccess(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// RejectedLogRecords returns the rejectedlogrecords associated with this ExportPartialSuccess.\nfunc (ms ExportPartialSuccess) RejectedLogRecords() int64 {\n\treturn ms.orig.RejectedLogRecords\n}\n\n// SetRejectedLogRecords replaces the rejectedlogrecords associated with this ExportPartialSuccess.\nfunc (ms ExportPartialSuccess) SetRejectedLogRecords(v int64) {\n\tms.state.AssertMutable()\n\tms.orig.RejectedLogRecords = v\n}\n\n// ErrorMessage returns the errormessage associated with this ExportPartialSuccess.\nfunc (ms ExportPartialSuccess) ErrorMessage() string {\n\treturn ms.orig.ErrorMessage\n}\n\n// SetErrorMessage replaces the errormessage associated with this ExportPartialSuccess.\nfunc (ms ExportPartialSuccess) SetErrorMessage(v string) {\n\tms.state.AssertMutable()\n\tms.orig.ErrorMessage = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ExportPartialSuccess) CopyTo(dest ExportPartialSuccess) {\n\tdest.state.AssertMutable()\n\tinternal.CopyExportLogsPartialSuccess(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/plog/plogotlp/generated_exportpartialsuccess_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plogotlp\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestExportPartialSuccess_MoveTo(t *testing.T) {\n\tms := generateTestExportPartialSuccess()\n\tdest := NewExportPartialSuccess()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewExportPartialSuccess(), ms)\n\tassert.Equal(t, generateTestExportPartialSuccess(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestExportPartialSuccess(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newExportPartialSuccess(internal.NewExportLogsPartialSuccess(), sharedState)) })\n\tassert.Panics(t, func() { newExportPartialSuccess(internal.NewExportLogsPartialSuccess(), sharedState).MoveTo(dest) })\n}\n\nfunc TestExportPartialSuccess_CopyTo(t *testing.T) {\n\tms := NewExportPartialSuccess()\n\torig := NewExportPartialSuccess()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestExportPartialSuccess()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newExportPartialSuccess(internal.NewExportLogsPartialSuccess(), sharedState)) })\n}\n\nfunc TestExportPartialSuccess_RejectedLogRecords(t *testing.T) {\n\tms := NewExportPartialSuccess()\n\tassert.Equal(t, int64(0), ms.RejectedLogRecords())\n\tms.SetRejectedLogRecords(int64(13))\n\tassert.Equal(t, int64(13), ms.RejectedLogRecords())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewExportPartialSuccess(internal.NewExportLogsPartialSuccess(), sharedState).SetRejectedLogRecords(int64(13))\n\t})\n}\n\nfunc TestExportPartialSuccess_ErrorMessage(t *testing.T) {\n\tms := NewExportPartialSuccess()\n\tassert.Empty(t, ms.ErrorMessage())\n\tms.SetErrorMessage(\"test_errormessage\")\n\tassert.Equal(t, \"test_errormessage\", ms.ErrorMessage())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewExportPartialSuccess(internal.NewExportLogsPartialSuccess(), sharedState).SetErrorMessage(\"test_errormessage\")\n\t})\n}\n\nfunc generateTestExportPartialSuccess() ExportPartialSuccess {\n\treturn newExportPartialSuccess(internal.GenTestExportLogsPartialSuccess(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/plog/plogotlp/generated_exportresponse.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plogotlp\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ExportResponse represents the response for gRPC/HTTP client/server.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewExportResponse function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ExportResponse struct {\n\torig  *internal.ExportLogsServiceResponse\n\tstate *internal.State\n}\n\nfunc newExportResponse(orig *internal.ExportLogsServiceResponse, state *internal.State) ExportResponse {\n\treturn ExportResponse{orig: orig, state: state}\n}\n\n// NewExportResponse creates a new empty ExportResponse.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewExportResponse() ExportResponse {\n\treturn newExportResponse(internal.NewExportLogsServiceResponse(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ExportResponse) MoveTo(dest ExportResponse) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteExportLogsServiceResponse(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// PartialSuccess returns the partialsuccess associated with this ExportResponse.\nfunc (ms ExportResponse) PartialSuccess() ExportPartialSuccess {\n\treturn newExportPartialSuccess(&ms.orig.PartialSuccess, ms.state)\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ExportResponse) CopyTo(dest ExportResponse) {\n\tdest.state.AssertMutable()\n\tinternal.CopyExportLogsServiceResponse(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/plog/plogotlp/generated_exportresponse_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage plogotlp\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestExportResponse_MoveTo(t *testing.T) {\n\tms := generateTestExportResponse()\n\tdest := NewExportResponse()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewExportResponse(), ms)\n\tassert.Equal(t, generateTestExportResponse(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestExportResponse(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newExportResponse(internal.NewExportLogsServiceResponse(), sharedState)) })\n\tassert.Panics(t, func() { newExportResponse(internal.NewExportLogsServiceResponse(), sharedState).MoveTo(dest) })\n}\n\nfunc TestExportResponse_CopyTo(t *testing.T) {\n\tms := NewExportResponse()\n\torig := NewExportResponse()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestExportResponse()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newExportResponse(internal.NewExportLogsServiceResponse(), sharedState)) })\n}\n\nfunc TestExportResponse_PartialSuccess(t *testing.T) {\n\tms := NewExportResponse()\n\tassert.Equal(t, NewExportPartialSuccess(), ms.PartialSuccess())\n\tms.orig.PartialSuccess = *internal.GenTestExportLogsPartialSuccess()\n\tassert.Equal(t, generateTestExportPartialSuccess(), ms.PartialSuccess())\n}\n\nfunc generateTestExportResponse() ExportResponse {\n\treturn newExportResponse(internal.GenTestExportLogsServiceResponse(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/plog/plogotlp/grpc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plogotlp // import \"go.opentelemetry.io/collector/pdata/plog/plogotlp\"\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otelgrpc\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otlp\"\n)\n\n// GRPCClient is the client API for OTLP-GRPC Logs service.\n//\n// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.\ntype GRPCClient interface {\n\t// Export plog.Logs to the server.\n\t//\n\t// For performance reasons, it is recommended to keep this RPC\n\t// alive for the entire life of the application.\n\tExport(ctx context.Context, request ExportRequest, opts ...grpc.CallOption) (ExportResponse, error)\n\n\t// unexported disallow implementation of the GRPCClient.\n\tunexported()\n}\n\n// NewGRPCClient returns a new GRPCClient connected using the given connection.\nfunc NewGRPCClient(cc *grpc.ClientConn) GRPCClient {\n\treturn &grpcClient{rawClient: otelgrpc.NewLogsServiceClient(cc)}\n}\n\ntype grpcClient struct {\n\trawClient otelgrpc.LogsServiceClient\n}\n\nfunc (c *grpcClient) Export(ctx context.Context, request ExportRequest, opts ...grpc.CallOption) (ExportResponse, error) {\n\trsp, err := c.rawClient.Export(ctx, request.orig, opts...)\n\tif err != nil {\n\t\treturn ExportResponse{}, err\n\t}\n\treturn ExportResponse{orig: rsp, state: internal.NewState()}, err\n}\n\nfunc (c *grpcClient) unexported() {}\n\n// GRPCServer is the server API for OTLP gRPC LogsService service.\n// Implementations MUST embed UnimplementedGRPCServer.\ntype GRPCServer interface {\n\t// Export is called every time a new request is received.\n\t//\n\t// For performance reasons, it is recommended to keep this RPC\n\t// alive for the entire life of the application.\n\tExport(context.Context, ExportRequest) (ExportResponse, error)\n\n\t// unexported disallow implementation of the GRPCServer.\n\tunexported()\n}\n\nvar _ GRPCServer = (*UnimplementedGRPCServer)(nil)\n\n// UnimplementedGRPCServer MUST be embedded to have forward compatible implementations.\ntype UnimplementedGRPCServer struct{}\n\nfunc (*UnimplementedGRPCServer) Export(context.Context, ExportRequest) (ExportResponse, error) {\n\treturn ExportResponse{}, status.Errorf(codes.Unimplemented, \"method Export not implemented\")\n}\n\nfunc (*UnimplementedGRPCServer) unexported() {}\n\n// RegisterGRPCServer registers the Server to the grpc.Server.\nfunc RegisterGRPCServer(s *grpc.Server, srv GRPCServer) {\n\totelgrpc.RegisterLogsServiceServer(s, &rawLogsServer{srv: srv})\n}\n\ntype rawLogsServer struct {\n\tsrv GRPCServer\n}\n\nfunc (s rawLogsServer) Export(ctx context.Context, request *internal.ExportLogsServiceRequest) (*internal.ExportLogsServiceResponse, error) {\n\totlp.MigrateLogs(request.ResourceLogs)\n\trsp, err := s.srv.Export(ctx, ExportRequest{orig: request, state: internal.NewState()})\n\treturn rsp.orig, err\n}\n"
  },
  {
    "path": "pdata/plog/plogotlp/grpc_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plogotlp\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/credentials/insecure\"\n\t\"google.golang.org/grpc/resolver\"\n\t\"google.golang.org/grpc/status\"\n\t\"google.golang.org/grpc/test/bufconn\"\n\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\nfunc TestGrpc(t *testing.T) {\n\tlis := bufconn.Listen(1024 * 1024)\n\ts := grpc.NewServer()\n\tRegisterGRPCServer(s, &fakeLogsServer{t: t})\n\twg := sync.WaitGroup{}\n\twg.Go(func() {\n\t\tassert.NoError(t, s.Serve(lis))\n\t})\n\tt.Cleanup(func() {\n\t\ts.Stop()\n\t\twg.Wait()\n\t})\n\n\tresolver.SetDefaultScheme(\"passthrough\")\n\tcc, err := grpc.NewClient(\"bufnet\",\n\t\tgrpc.WithContextDialer(func(context.Context, string) (net.Conn, error) {\n\t\t\treturn lis.Dial()\n\t\t}),\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, cc.Close())\n\t})\n\n\tlogClient := NewGRPCClient(cc)\n\n\tresp, err := logClient.Export(context.Background(), generateLogsRequest())\n\trequire.NoError(t, err)\n\tassert.Equal(t, NewExportResponse(), resp)\n}\n\nfunc TestGrpcError(t *testing.T) {\n\tlis := bufconn.Listen(1024 * 1024)\n\ts := grpc.NewServer()\n\tRegisterGRPCServer(s, &fakeLogsServer{t: t, err: errors.New(\"my error\")})\n\twg := sync.WaitGroup{}\n\twg.Go(func() {\n\t\tassert.NoError(t, s.Serve(lis))\n\t})\n\tt.Cleanup(func() {\n\t\ts.Stop()\n\t\twg.Wait()\n\t})\n\n\tcc, err := grpc.NewClient(\"bufnet\",\n\t\tgrpc.WithContextDialer(func(context.Context, string) (net.Conn, error) {\n\t\t\treturn lis.Dial()\n\t\t}),\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, cc.Close())\n\t})\n\n\tlogClient := NewGRPCClient(cc)\n\tresp, err := logClient.Export(context.Background(), generateLogsRequest())\n\trequire.Error(t, err)\n\tst, okSt := status.FromError(err)\n\trequire.True(t, okSt)\n\tassert.Equal(t, \"my error\", st.Message())\n\tassert.Equal(t, codes.Unknown, st.Code())\n\tassert.Equal(t, ExportResponse{}, resp)\n}\n\ntype fakeLogsServer struct {\n\tUnimplementedGRPCServer\n\tt   *testing.T\n\terr error\n}\n\nfunc (f fakeLogsServer) Export(_ context.Context, request ExportRequest) (ExportResponse, error) {\n\tassert.Equal(f.t, generateLogsRequest(), request)\n\treturn NewExportResponse(), f.err\n}\n\nfunc generateLogsRequest() ExportRequest {\n\tld := plog.NewLogs()\n\tld.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty().Body().SetStr(\"test_log_record\")\n\treturn NewExportRequestFromLogs(ld)\n}\n"
  },
  {
    "path": "pdata/plog/plogotlp/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plogotlp\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "pdata/plog/plogotlp/request.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plogotlp // import \"go.opentelemetry.io/collector/pdata/plog/plogotlp\"\n\nimport (\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otlp\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\n// ExportRequest represents the request for gRPC/HTTP client/server.\n// It's a wrapper for plog.Logs data.\ntype ExportRequest struct {\n\torig  *internal.ExportLogsServiceRequest\n\tstate *internal.State\n}\n\n// NewExportRequest returns an empty ExportRequest.\nfunc NewExportRequest() ExportRequest {\n\treturn ExportRequest{\n\t\torig:  &internal.ExportLogsServiceRequest{},\n\t\tstate: internal.NewState(),\n\t}\n}\n\n// NewExportRequestFromLogs returns a ExportRequest from plog.Logs.\n// Because ExportRequest is a wrapper for plog.Logs,\n// any changes to the provided Logs struct will be reflected in the ExportRequest and vice versa.\nfunc NewExportRequestFromLogs(ld plog.Logs) ExportRequest {\n\treturn ExportRequest{\n\t\torig:  internal.GetLogsOrig(internal.LogsWrapper(ld)),\n\t\tstate: internal.GetLogsState(internal.LogsWrapper(ld)),\n\t}\n}\n\n// MarshalProto marshals ExportRequest into proto bytes.\nfunc (ms ExportRequest) MarshalProto() ([]byte, error) {\n\tsize := ms.orig.SizeProto()\n\tbuf := make([]byte, size)\n\t_ = ms.orig.MarshalProto(buf)\n\treturn buf, nil\n}\n\n// UnmarshalProto unmarshalls ExportRequest from proto bytes.\nfunc (ms ExportRequest) UnmarshalProto(data []byte) error {\n\terr := ms.orig.UnmarshalProto(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\totlp.MigrateLogs(ms.orig.ResourceLogs)\n\treturn nil\n}\n\n// MarshalJSON marshals ExportRequest into JSON bytes.\nfunc (ms ExportRequest) MarshalJSON() ([]byte, error) {\n\tdest := json.BorrowStream(nil)\n\tdefer json.ReturnStream(dest)\n\tms.orig.MarshalJSON(dest)\n\tif dest.Error() != nil {\n\t\treturn nil, dest.Error()\n\t}\n\treturn slices.Clone(dest.Buffer()), nil\n}\n\n// UnmarshalJSON unmarshalls ExportRequest from JSON bytes.\nfunc (ms ExportRequest) UnmarshalJSON(data []byte) error {\n\titer := json.BorrowIterator(data)\n\tdefer json.ReturnIterator(iter)\n\tms.orig.UnmarshalJSON(iter)\n\treturn iter.Error()\n}\n\nfunc (ms ExportRequest) Logs() plog.Logs {\n\treturn plog.Logs(internal.NewLogsWrapper(ms.orig, ms.state))\n}\n"
  },
  {
    "path": "pdata/plog/plogotlp/request_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plogotlp\n\nimport (\n\t\"encoding/json\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcollectorlogs \"go.opentelemetry.io/proto/slim/otlp/collector/logs/v1\"\n\tgoproto \"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otlp\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\nvar (\n\t_ json.Unmarshaler = ExportRequest{}\n\t_ json.Marshaler   = ExportRequest{}\n)\n\nvar logsRequestJSON = []byte(`\n\t{\n\t\t\"resourceLogs\": [\n\t\t{\n\t\t\t\"resource\": {},\n\t\t\t\"scopeLogs\": [\n\t\t\t\t{\n\t\t\t\t\t\"scope\": {},\n\t\t\t\t\t\"logRecords\": [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\"body\": {\n\t\t\t\t\t\t\t\t\"stringValue\": \"test_log_record\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t]\n\t\t\t\t}\n\t\t\t]\n\t\t}\n\t\t]\n\t}`)\n\nfunc TestRequestToPData(t *testing.T) {\n\ttr := NewExportRequest()\n\tassert.Equal(t, 0, tr.Logs().LogRecordCount())\n\ttr.Logs().ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\tassert.Equal(t, 1, tr.Logs().LogRecordCount())\n}\n\nfunc TestRequestJSON(t *testing.T) {\n\tlr := NewExportRequest()\n\trequire.NoError(t, lr.UnmarshalJSON(logsRequestJSON))\n\tassert.Equal(t, \"test_log_record\", lr.Logs().ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(0).Body().AsString())\n\n\tgot, err := lr.MarshalJSON()\n\trequire.NoError(t, err)\n\tassert.Equal(t, strings.Join(strings.Fields(string(logsRequestJSON)), \"\"), string(got))\n}\n\nfunc TestLogsProtoWireCompatibility(t *testing.T) {\n\t// This test verifies that OTLP ProtoBufs generated using goproto lib in\n\t// opentelemetry-proto repository OTLP ProtoBufs generated using gogoproto lib in\n\t// this repository are wire compatible.\n\n\t// Generate Logs as pdata struct.\n\tld := NewExportRequestFromLogs(plog.Logs(internal.GenTestLogsWrapper()))\n\n\t// Marshal its underlying ProtoBuf to wire.\n\twire1, err := ld.MarshalProto()\n\trequire.NoError(t, err)\n\tassert.NotNil(t, wire1)\n\n\t// Unmarshal from the wire to OTLP Protobuf in goproto's representation.\n\tvar goprotoMessage gootlpcollectorlogs.ExportLogsServiceRequest\n\terr = goproto.Unmarshal(wire1, &goprotoMessage)\n\trequire.NoError(t, err)\n\n\t// Marshal to the wire again.\n\twire2, err := goproto.Marshal(&goprotoMessage)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, wire2)\n\n\t// Unmarshal from the wire into gogoproto's representation.\n\tld2 := NewExportRequest()\n\terr = ld2.UnmarshalProto(wire2)\n\trequire.NoError(t, err)\n\n\t// Now compare that the original and final ProtoBuf messages are the same.\n\t// This proves that goproto and gogoproto marshaling/unmarshaling are wire compatible.\n\t// Migration logic will run, so run it on the original message as well.\n\totlp.MigrateLogs(ld.orig.ResourceLogs)\n\tassert.Equal(t, ld, ld2)\n}\n"
  },
  {
    "path": "pdata/plog/plogotlp/response.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plogotlp // import \"go.opentelemetry.io/collector/pdata/plog/plogotlp\"\n\nimport (\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n)\n\n// MarshalProto marshals ExportResponse into proto bytes.\nfunc (ms ExportResponse) MarshalProto() ([]byte, error) {\n\tsize := ms.orig.SizeProto()\n\tbuf := make([]byte, size)\n\t_ = ms.orig.MarshalProto(buf)\n\treturn buf, nil\n}\n\n// UnmarshalProto unmarshalls ExportResponse from proto bytes.\nfunc (ms ExportResponse) UnmarshalProto(data []byte) error {\n\treturn ms.orig.UnmarshalProto(data)\n}\n\n// MarshalJSON marshals ExportResponse into JSON bytes.\nfunc (ms ExportResponse) MarshalJSON() ([]byte, error) {\n\tdest := json.BorrowStream(nil)\n\tdefer json.ReturnStream(dest)\n\tms.orig.MarshalJSON(dest)\n\treturn slices.Clone(dest.Buffer()), dest.Error()\n}\n\n// UnmarshalJSON unmarshalls ExportResponse from JSON bytes.\nfunc (ms ExportResponse) UnmarshalJSON(data []byte) error {\n\titer := json.BorrowIterator(data)\n\tdefer json.ReturnIterator(iter)\n\tms.orig.UnmarshalJSON(iter)\n\treturn iter.Error()\n}\n"
  },
  {
    "path": "pdata/plog/plogotlp/response_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plogotlp\n\nimport (\n\tstdjson \"encoding/json\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar (\n\t_ stdjson.Unmarshaler = ExportResponse{}\n\t_ stdjson.Marshaler   = ExportResponse{}\n)\n\nfunc TestExportResponseJSON(t *testing.T) {\n\tjsonStr := `{\"partialSuccess\": {\"rejectedLogRecords\":\"1\", \"errorMessage\":\"nothing\"}}`\n\tval := NewExportResponse()\n\trequire.NoError(t, val.UnmarshalJSON([]byte(jsonStr)))\n\texpected := NewExportResponse()\n\texpected.PartialSuccess().SetRejectedLogRecords(1)\n\texpected.PartialSuccess().SetErrorMessage(\"nothing\")\n\tassert.Equal(t, expected, val)\n\tbuf, err := val.MarshalJSON()\n\trequire.NoError(t, err)\n\tassert.JSONEq(t, jsonStr, string(buf))\n}\n\nfunc TestUnmarshalJSONExportResponse(t *testing.T) {\n\tjsonStr := `{\"extra\":\"\", \"partialSuccess\": {\"extra\":\"\"}}`\n\tval := NewExportResponse()\n\trequire.NoError(t, val.UnmarshalJSON([]byte(jsonStr)))\n\tassert.Equal(t, NewExportResponse(), val)\n}\n"
  },
  {
    "path": "pdata/plog/severity_number.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plog // import \"go.opentelemetry.io/collector/pdata/plog\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// SeverityNumber represents severity number of a log record.\ntype SeverityNumber int32\n\nconst (\n\tSeverityNumberUnspecified = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_UNSPECIFIED)\n\tSeverityNumberTrace       = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_TRACE)\n\tSeverityNumberTrace2      = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_TRACE2)\n\tSeverityNumberTrace3      = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_TRACE3)\n\tSeverityNumberTrace4      = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_TRACE4)\n\tSeverityNumberDebug       = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_DEBUG)\n\tSeverityNumberDebug2      = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_DEBUG2)\n\tSeverityNumberDebug3      = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_DEBUG3)\n\tSeverityNumberDebug4      = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_DEBUG4)\n\tSeverityNumberInfo        = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_INFO)\n\tSeverityNumberInfo2       = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_INFO2)\n\tSeverityNumberInfo3       = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_INFO3)\n\tSeverityNumberInfo4       = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_INFO4)\n\tSeverityNumberWarn        = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_WARN)\n\tSeverityNumberWarn2       = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_WARN2)\n\tSeverityNumberWarn3       = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_WARN3)\n\tSeverityNumberWarn4       = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_WARN4)\n\tSeverityNumberError       = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_ERROR)\n\tSeverityNumberError2      = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_ERROR2)\n\tSeverityNumberError3      = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_ERROR3)\n\tSeverityNumberError4      = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_ERROR4)\n\tSeverityNumberFatal       = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_FATAL)\n\tSeverityNumberFatal2      = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_FATAL2)\n\tSeverityNumberFatal3      = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_FATAL3)\n\tSeverityNumberFatal4      = SeverityNumber(internal.SeverityNumber_SEVERITY_NUMBER_FATAL4)\n)\n\n// String returns the string representation of the SeverityNumber.\nfunc (sn SeverityNumber) String() string {\n\tswitch sn {\n\tcase SeverityNumberUnspecified:\n\t\treturn \"Unspecified\"\n\tcase SeverityNumberTrace:\n\t\treturn \"Trace\"\n\tcase SeverityNumberTrace2:\n\t\treturn \"Trace2\"\n\tcase SeverityNumberTrace3:\n\t\treturn \"Trace3\"\n\tcase SeverityNumberTrace4:\n\t\treturn \"Trace4\"\n\tcase SeverityNumberDebug:\n\t\treturn \"Debug\"\n\tcase SeverityNumberDebug2:\n\t\treturn \"Debug2\"\n\tcase SeverityNumberDebug3:\n\t\treturn \"Debug3\"\n\tcase SeverityNumberDebug4:\n\t\treturn \"Debug4\"\n\tcase SeverityNumberInfo:\n\t\treturn \"Info\"\n\tcase SeverityNumberInfo2:\n\t\treturn \"Info2\"\n\tcase SeverityNumberInfo3:\n\t\treturn \"Info3\"\n\tcase SeverityNumberInfo4:\n\t\treturn \"Info4\"\n\tcase SeverityNumberWarn:\n\t\treturn \"Warn\"\n\tcase SeverityNumberWarn2:\n\t\treturn \"Warn2\"\n\tcase SeverityNumberWarn3:\n\t\treturn \"Warn3\"\n\tcase SeverityNumberWarn4:\n\t\treturn \"Warn4\"\n\tcase SeverityNumberError:\n\t\treturn \"Error\"\n\tcase SeverityNumberError2:\n\t\treturn \"Error2\"\n\tcase SeverityNumberError3:\n\t\treturn \"Error3\"\n\tcase SeverityNumberError4:\n\t\treturn \"Error4\"\n\tcase SeverityNumberFatal:\n\t\treturn \"Fatal\"\n\tcase SeverityNumberFatal2:\n\t\treturn \"Fatal2\"\n\tcase SeverityNumberFatal3:\n\t\treturn \"Fatal3\"\n\tcase SeverityNumberFatal4:\n\t\treturn \"Fatal4\"\n\t}\n\treturn \"\"\n}\n"
  },
  {
    "path": "pdata/plog/severity_number_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage plog // import \"go.opentelemetry.io/collector/pdata/plog\"\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestSeverityNumberString(t *testing.T) {\n\tassert.Equal(t, \"Unspecified\", SeverityNumberUnspecified.String())\n\tassert.Equal(t, \"Trace\", SeverityNumberTrace.String())\n\tassert.Equal(t, \"Trace2\", SeverityNumberTrace2.String())\n\tassert.Equal(t, \"Trace3\", SeverityNumberTrace3.String())\n\tassert.Equal(t, \"Trace4\", SeverityNumberTrace4.String())\n\tassert.Equal(t, \"Debug\", SeverityNumberDebug.String())\n\tassert.Equal(t, \"Debug2\", SeverityNumberDebug2.String())\n\tassert.Equal(t, \"Debug3\", SeverityNumberDebug3.String())\n\tassert.Equal(t, \"Debug4\", SeverityNumberDebug4.String())\n\tassert.Equal(t, \"Info\", SeverityNumberInfo.String())\n\tassert.Equal(t, \"Info2\", SeverityNumberInfo2.String())\n\tassert.Equal(t, \"Info3\", SeverityNumberInfo3.String())\n\tassert.Equal(t, \"Info4\", SeverityNumberInfo4.String())\n\tassert.Equal(t, \"Warn\", SeverityNumberWarn.String())\n\tassert.Equal(t, \"Warn2\", SeverityNumberWarn2.String())\n\tassert.Equal(t, \"Warn3\", SeverityNumberWarn3.String())\n\tassert.Equal(t, \"Warn4\", SeverityNumberWarn4.String())\n\tassert.Equal(t, \"Error\", SeverityNumberError.String())\n\tassert.Equal(t, \"Error2\", SeverityNumberError2.String())\n\tassert.Equal(t, \"Error3\", SeverityNumberError3.String())\n\tassert.Equal(t, \"Error4\", SeverityNumberError4.String())\n\tassert.Equal(t, \"Fatal\", SeverityNumberFatal.String())\n\tassert.Equal(t, \"Fatal2\", SeverityNumberFatal2.String())\n\tassert.Equal(t, \"Fatal3\", SeverityNumberFatal3.String())\n\tassert.Equal(t, \"Fatal4\", SeverityNumberFatal4.String())\n\tassert.Empty(t, SeverityNumber(100).String())\n}\n"
  },
  {
    "path": "pdata/pmetric/aggregation_temporality.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric // import \"go.opentelemetry.io/collector/pdata/pmetric\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// AggregationTemporality defines how a metric aggregator reports aggregated values.\n// It describes how those values relate to the time interval over which they are aggregated.\ntype AggregationTemporality int32\n\nconst (\n\t// AggregationTemporalityUnspecified is the default AggregationTemporality, it MUST NOT be used.\n\tAggregationTemporalityUnspecified = AggregationTemporality(internal.AggregationTemporality_AGGREGATION_TEMPORALITY_UNSPECIFIED)\n\t// AggregationTemporalityDelta is a AggregationTemporality for a metric aggregator which reports changes since last report time.\n\tAggregationTemporalityDelta = AggregationTemporality(internal.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA)\n\t// AggregationTemporalityCumulative is a AggregationTemporality for a metric aggregator which reports changes since a fixed start time.\n\tAggregationTemporalityCumulative = AggregationTemporality(internal.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE)\n)\n\n// String returns the string representation of the AggregationTemporality.\nfunc (at AggregationTemporality) String() string {\n\tswitch at {\n\tcase AggregationTemporalityUnspecified:\n\t\treturn \"Unspecified\"\n\tcase AggregationTemporalityDelta:\n\t\treturn \"Delta\"\n\tcase AggregationTemporalityCumulative:\n\t\treturn \"Cumulative\"\n\t}\n\treturn \"\"\n}\n"
  },
  {
    "path": "pdata/pmetric/aggregation_temporality_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric // import \"go.opentelemetry.io/collector/pdata/pmetric\"\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestAggregationTemporalityString(t *testing.T) {\n\tassert.Equal(t, \"Unspecified\", AggregationTemporalityUnspecified.String())\n\tassert.Equal(t, \"Delta\", AggregationTemporalityDelta.String())\n\tassert.Equal(t, \"Cumulative\", AggregationTemporalityCumulative.String())\n\tassert.Empty(t, (AggregationTemporalityCumulative + 1).String())\n}\n"
  },
  {
    "path": "pdata/pmetric/doc_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric_test\n\nimport (\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\nfunc ExampleNewMetrics() {\n\tmetrics := pmetric.NewMetrics()\n\n\tresourceMetrics := metrics.ResourceMetrics().AppendEmpty()\n\n\tresourceMetrics.Resource().Attributes().PutStr(\"service.name\", \"my-service\")\n\tresourceMetrics.Resource().Attributes().PutStr(\"host.name\", \"server-01\")\n\n\tscopeMetrics := resourceMetrics.ScopeMetrics().AppendEmpty()\n\tscopeMetrics.Scope().SetName(\"my-meter\")\n\tscopeMetrics.Scope().SetVersion(\"1.0.0\")\n\n\tmetric := scopeMetrics.Metrics().AppendEmpty()\n\tmetric.SetName(\"requests_total\")\n\tmetric.SetDescription(\"Total number of requests\")\n\tmetric.SetUnit(\"1\")\n\n\tsum := metric.SetEmptySum()\n\tsum.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n\tsum.SetIsMonotonic(true)\n\n\tdataPoint := sum.DataPoints().AppendEmpty()\n\tdataPoint.SetStartTimestamp(pcommon.Timestamp(1640991600000000000)) // 2022-01-01 00:00:00 UTC\n\tdataPoint.SetTimestamp(pcommon.Timestamp(1640995200000000000))      // 2022-01-01 01:00:00 UTC\n\tdataPoint.SetIntValue(1234)\n\tdataPoint.Attributes().PutStr(\"endpoint\", \"/api/v1/users\")\n\tdataPoint.Attributes().PutStr(\"method\", \"GET\")\n\n\tfmt.Printf(\"Resource metrics count: %d\\n\", metrics.ResourceMetrics().Len())\n\tfmt.Printf(\"Metrics count: %d\\n\", scopeMetrics.Metrics().Len())\n\tfmt.Printf(\"Metric name: %s\\n\", metric.Name())\n\tfmt.Printf(\"Data points count: %d\\n\", sum.DataPoints().Len())\n\t// Output:\n\t// Resource metrics count: 1\n\t// Metrics count: 1\n\t// Metric name: requests_total\n\t// Data points count: 1\n}\n\nfunc ExampleMetric_SetEmptyGauge() {\n\tmetrics := pmetric.NewMetrics()\n\tresourceMetrics := metrics.ResourceMetrics().AppendEmpty()\n\tscopeMetrics := resourceMetrics.ScopeMetrics().AppendEmpty()\n\n\tmetric := scopeMetrics.Metrics().AppendEmpty()\n\tmetric.SetName(\"cpu_usage_percent\")\n\tmetric.SetDescription(\"Current CPU usage percentage\")\n\tmetric.SetUnit(\"%\")\n\n\tgauge := metric.SetEmptyGauge()\n\n\tfor i := range 4 {\n\t\tdataPoint := gauge.DataPoints().AppendEmpty()\n\t\tdataPoint.SetTimestamp(pcommon.Timestamp(1640995200000000000))\n\t\tdataPoint.SetDoubleValue(45.5 + float64(i)*2.1)\n\t\tdataPoint.Attributes().PutInt(\"cpu\", int64(i))\n\t}\n\n\tfmt.Printf(\"Metric type: %s\\n\", metric.Type())\n\tfmt.Printf(\"Data points count: %d\\n\", gauge.DataPoints().Len())\n\tfmt.Printf(\"First CPU usage: %.1f%%\\n\", gauge.DataPoints().At(0).DoubleValue())\n\t// Output:\n\t// Metric type: Gauge\n\t// Data points count: 4\n\t// First CPU usage: 45.5%\n}\n\nfunc ExampleMetric_SetEmptyHistogram() {\n\tmetrics := pmetric.NewMetrics()\n\tresourceMetrics := metrics.ResourceMetrics().AppendEmpty()\n\tscopeMetrics := resourceMetrics.ScopeMetrics().AppendEmpty()\n\n\tmetric := scopeMetrics.Metrics().AppendEmpty()\n\tmetric.SetName(\"request_duration_seconds\")\n\tmetric.SetDescription(\"Request duration in seconds\")\n\tmetric.SetUnit(\"s\")\n\n\thistogram := metric.SetEmptyHistogram()\n\thistogram.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n\n\tdataPoint := histogram.DataPoints().AppendEmpty()\n\tdataPoint.SetStartTimestamp(pcommon.Timestamp(1640995140000000000)) // 2022-01-01 00:59:00 UTC\n\tdataPoint.SetTimestamp(pcommon.Timestamp(1640995200000000000))      // 2022-01-01 01:00:00 UTC\n\tdataPoint.SetCount(100)\n\tdataPoint.SetSum(23.5)\n\tdataPoint.SetMin(0.001)\n\tdataPoint.SetMax(5.0)\n\n\tdataPoint.ExplicitBounds().FromRaw([]float64{0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0})\n\tdataPoint.BucketCounts().FromRaw([]uint64{5, 10, 20, 25, 20, 15, 3, 2, 0, 0})\n\n\tdataPoint.Attributes().PutStr(\"endpoint\", \"/api/health\")\n\tdataPoint.SetFlags(pmetric.DefaultDataPointFlags)\n\n\tfmt.Printf(\"Metric type: %s\\n\", metric.Type())\n\tfmt.Printf(\"Total count: %d\\n\", dataPoint.Count())\n\tfmt.Printf(\"Total sum: %.1f\\n\", dataPoint.Sum())\n\tfmt.Printf(\"Min value: %.3f\\n\", dataPoint.Min())\n\tfmt.Printf(\"Max value: %.1f\\n\", dataPoint.Max())\n\tfmt.Printf(\"Bucket count: %d\\n\", dataPoint.BucketCounts().Len())\n\t// Output:\n\t// Metric type: Histogram\n\t// Total count: 100\n\t// Total sum: 23.5\n\t// Min value: 0.001\n\t// Max value: 5.0\n\t// Bucket count: 10\n}\n\nfunc ExampleMetric_SetEmptyExponentialHistogram() {\n\tmetrics := pmetric.NewMetrics()\n\tresourceMetrics := metrics.ResourceMetrics().AppendEmpty()\n\tscopeMetrics := resourceMetrics.ScopeMetrics().AppendEmpty()\n\n\tmetric := scopeMetrics.Metrics().AppendEmpty()\n\tmetric.SetName(\"response_size_bytes\")\n\tmetric.SetDescription(\"Response size in bytes\")\n\tmetric.SetUnit(\"By\")\n\n\texpHist := metric.SetEmptyExponentialHistogram()\n\texpHist.SetAggregationTemporality(pmetric.AggregationTemporalityDelta)\n\n\tdataPoint := expHist.DataPoints().AppendEmpty()\n\tdataPoint.SetStartTimestamp(pcommon.Timestamp(1640995140000000000))\n\tdataPoint.SetTimestamp(pcommon.Timestamp(1640995200000000000))\n\tdataPoint.SetCount(50)\n\tdataPoint.SetSum(1024.5)\n\tdataPoint.SetScale(4)\n\tdataPoint.SetZeroCount(5)\n\tdataPoint.SetZeroThreshold(0.001)\n\n\t// Set positive buckets\n\tpositive := dataPoint.Positive()\n\tpositive.SetOffset(2)\n\tpositive.BucketCounts().FromRaw([]uint64{2, 3, 7, 8, 5})\n\n\t// Set negative buckets\n\tnegative := dataPoint.Negative()\n\tnegative.SetOffset(1)\n\tnegative.BucketCounts().FromRaw([]uint64{1, 2, 3})\n\n\tdataPoint.Attributes().PutStr(\"protocol\", \"http\")\n\n\tfmt.Printf(\"Metric type: %s\\n\", metric.Type())\n\tfmt.Printf(\"Scale: %d\\n\", dataPoint.Scale())\n\tfmt.Printf(\"Zero count: %d\\n\", dataPoint.ZeroCount())\n\tfmt.Printf(\"Positive buckets: %d\\n\", positive.BucketCounts().Len())\n\tfmt.Printf(\"Negative buckets: %d\\n\", negative.BucketCounts().Len())\n\t// Output:\n\t// Metric type: ExponentialHistogram\n\t// Scale: 4\n\t// Zero count: 5\n\t// Positive buckets: 5\n\t// Negative buckets: 3\n}\n\nfunc ExampleMetric_SetEmptySummary() {\n\tmetrics := pmetric.NewMetrics()\n\tresourceMetrics := metrics.ResourceMetrics().AppendEmpty()\n\tscopeMetrics := resourceMetrics.ScopeMetrics().AppendEmpty()\n\n\tmetric := scopeMetrics.Metrics().AppendEmpty()\n\tmetric.SetName(\"latency_seconds\")\n\tmetric.SetDescription(\"Request latency in seconds\")\n\tmetric.SetUnit(\"s\")\n\n\tsummary := metric.SetEmptySummary()\n\n\tdataPoint := summary.DataPoints().AppendEmpty()\n\tdataPoint.SetStartTimestamp(pcommon.Timestamp(1640995140000000000))\n\tdataPoint.SetTimestamp(pcommon.Timestamp(1640995200000000000))\n\tdataPoint.SetCount(1000)\n\tdataPoint.SetSum(125.5)\n\n\t// Add quantile values\n\tq50 := dataPoint.QuantileValues().AppendEmpty()\n\tq50.SetQuantile(0.5)\n\tq50.SetValue(0.1)\n\n\tq95 := dataPoint.QuantileValues().AppendEmpty()\n\tq95.SetQuantile(0.95)\n\tq95.SetValue(0.5)\n\n\tq99 := dataPoint.QuantileValues().AppendEmpty()\n\tq99.SetQuantile(0.99)\n\tq99.SetValue(1.0)\n\n\tdataPoint.Attributes().PutStr(\"service\", \"api\")\n\n\tfmt.Printf(\"Metric type: %s\\n\", metric.Type())\n\tfmt.Printf(\"Count: %d\\n\", dataPoint.Count())\n\tfmt.Printf(\"Sum: %.1f\\n\", dataPoint.Sum())\n\tfmt.Printf(\"Quantiles: %d\\n\", dataPoint.QuantileValues().Len())\n\tfmt.Printf(\"P95: %.1f\\n\", q95.Value())\n\t// Output:\n\t// Metric type: Summary\n\t// Count: 1000\n\t// Sum: 125.5\n\t// Quantiles: 3\n\t// P95: 0.5\n}\n\nfunc ExampleNumberDataPoint_Exemplars() {\n\tmetrics := pmetric.NewMetrics()\n\tresourceMetrics := metrics.ResourceMetrics().AppendEmpty()\n\tscopeMetrics := resourceMetrics.ScopeMetrics().AppendEmpty()\n\n\tmetric := scopeMetrics.Metrics().AppendEmpty()\n\tmetric.SetName(\"http_requests_total\")\n\n\tsum := metric.SetEmptySum()\n\tdataPoint := sum.DataPoints().AppendEmpty()\n\tdataPoint.SetIntValue(5000)\n\n\texemplar := dataPoint.Exemplars().AppendEmpty()\n\texemplar.SetTimestamp(pcommon.Timestamp(1640995200000000000))\n\texemplar.SetIntValue(1)\n\texemplar.FilteredAttributes().PutStr(\"trace_id\", \"abc123\")\n\texemplar.FilteredAttributes().PutStr(\"span_id\", \"def456\")\n\n\tfmt.Printf(\"Data point value: %d\\n\", dataPoint.IntValue())\n\tfmt.Printf(\"Exemplars count: %d\\n\", dataPoint.Exemplars().Len())\n\tfmt.Printf(\"Exemplar value: %d\\n\", exemplar.IntValue())\n\t// Output:\n\t// Data point value: 5000\n\t// Exemplars count: 1\n\t// Exemplar value: 1\n}\n\nfunc ExampleDataPointFlags() {\n\tmetrics := pmetric.NewMetrics()\n\tresourceMetrics := metrics.ResourceMetrics().AppendEmpty()\n\tscopeMetrics := resourceMetrics.ScopeMetrics().AppendEmpty()\n\n\tmetric := scopeMetrics.Metrics().AppendEmpty()\n\tmetric.SetName(\"test_metric\")\n\n\tgauge := metric.SetEmptyGauge()\n\tdataPoint := gauge.DataPoints().AppendEmpty()\n\n\t// Test default flags\n\tdefaultFlags := pmetric.DefaultDataPointFlags\n\tdataPoint.SetFlags(defaultFlags)\n\tfmt.Printf(\"Default flags NoRecordedValue: %t\\n\", dataPoint.Flags().NoRecordedValue())\n\n\t// Test with NoRecordedValue flag\n\tflagsWithNoValue := defaultFlags.WithNoRecordedValue(true)\n\tdataPoint.SetFlags(flagsWithNoValue)\n\tfmt.Printf(\"With NoRecordedValue flag: %t\\n\", dataPoint.Flags().NoRecordedValue())\n\n\t// Test removing NoRecordedValue flag\n\tflagsWithoutNoValue := flagsWithNoValue.WithNoRecordedValue(false)\n\tdataPoint.SetFlags(flagsWithoutNoValue)\n\tfmt.Printf(\"Without NoRecordedValue flag: %t\\n\", dataPoint.Flags().NoRecordedValue())\n\n\t// Output:\n\t// Default flags NoRecordedValue: false\n\t// With NoRecordedValue flag: true\n\t// Without NoRecordedValue flag: false\n}\n"
  },
  {
    "path": "pdata/pmetric/encoding.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric // import \"go.opentelemetry.io/collector/pdata/pmetric\"\n\n// MarshalSizer is the interface that groups the basic Marshal and Size methods\ntype MarshalSizer interface {\n\tMarshaler\n\tSizer\n}\n\n// Marshaler marshals pmetric.Metrics into bytes.\ntype Marshaler interface {\n\t// MarshalMetrics the given pmetric.Metrics into bytes.\n\t// If the error is not nil, the returned bytes slice cannot be used.\n\tMarshalMetrics(md Metrics) ([]byte, error)\n}\n\n// Unmarshaler unmarshalls bytes into pmetric.Metrics.\ntype Unmarshaler interface {\n\t// UnmarshalMetrics the given bytes into pmetric.Metrics.\n\t// If the error is not nil, the returned pmetric.Metrics cannot be used.\n\tUnmarshalMetrics(buf []byte) (Metrics, error)\n}\n\n// Sizer is an optional interface implemented by the Marshaler, that calculates the size of a marshaled Metrics.\ntype Sizer interface {\n\t// MetricsSize returns the size in bytes of a marshaled Metrics.\n\tMetricsSize(md Metrics) int\n}\n"
  },
  {
    "path": "pdata/pmetric/exemplar_value_type.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric // import \"go.opentelemetry.io/collector/pdata/pmetric\"\n\n// ExemplarValueType specifies the type of Exemplar measurement value.\ntype ExemplarValueType int32\n\nconst (\n\t// ExemplarValueTypeEmpty means that exemplar value is unset.\n\tExemplarValueTypeEmpty ExemplarValueType = iota\n\tExemplarValueTypeInt\n\tExemplarValueTypeDouble\n)\n\n// String returns the string representation of the ExemplarValueType.\nfunc (nt ExemplarValueType) String() string {\n\tswitch nt {\n\tcase ExemplarValueTypeEmpty:\n\t\treturn \"Empty\"\n\tcase ExemplarValueTypeInt:\n\t\treturn \"Int\"\n\tcase ExemplarValueTypeDouble:\n\t\treturn \"Double\"\n\t}\n\treturn \"\"\n}\n"
  },
  {
    "path": "pdata/pmetric/exemplar_value_type_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric // import \"go.opentelemetry.io/collector/pdata/pmetric\"\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestExemplarValueTypeString(t *testing.T) {\n\tassert.Equal(t, \"Empty\", ExemplarValueTypeEmpty.String())\n\tassert.Equal(t, \"Int\", ExemplarValueTypeInt.String())\n\tassert.Equal(t, \"Double\", ExemplarValueTypeDouble.String())\n\tassert.Empty(t, (ExemplarValueTypeDouble + 1).String())\n}\n"
  },
  {
    "path": "pdata/pmetric/fuzz_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric // import \"go.opentelemetry.io/collector/pdata/pmetric\"\n\nimport (\n\t\"testing\"\n)\n\nfunc FuzzUnmarshalMetrics(f *testing.F) {\n\tf.Fuzz(func(_ *testing.T, data []byte) {\n\t\tu := &JSONUnmarshaler{}\n\t\t_, _ = u.UnmarshalMetrics(data)\n\t})\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_exemplar.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// Exemplar is a sample input double measurement.\n//\n// Exemplars also hold information about the environment when the measurement was recorded,\n// for example the span and trace ID of the active span when the exemplar was recorded.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewExemplar function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Exemplar struct {\n\torig  *internal.Exemplar\n\tstate *internal.State\n}\n\nfunc newExemplar(orig *internal.Exemplar, state *internal.State) Exemplar {\n\treturn Exemplar{orig: orig, state: state}\n}\n\n// NewExemplar creates a new empty Exemplar.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewExemplar() Exemplar {\n\treturn newExemplar(internal.NewExemplar(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Exemplar) MoveTo(dest Exemplar) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteExemplar(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// FilteredAttributes returns the FilteredAttributes associated with this Exemplar.\nfunc (ms Exemplar) FilteredAttributes() pcommon.Map {\n\treturn pcommon.Map(internal.NewMapWrapper(&ms.orig.FilteredAttributes, ms.state))\n}\n\n// Timestamp returns the timestamp associated with this Exemplar.\nfunc (ms Exemplar) Timestamp() pcommon.Timestamp {\n\treturn pcommon.Timestamp(ms.orig.TimeUnixNano)\n}\n\n// SetTimestamp replaces the timestamp associated with this Exemplar.\nfunc (ms Exemplar) SetTimestamp(v pcommon.Timestamp) {\n\tms.state.AssertMutable()\n\tms.orig.TimeUnixNano = uint64(v)\n}\n\n// ValueType returns the type of the value for this Exemplar.\n// Calling this function on zero-initialized Exemplar will cause a panic.\nfunc (ms Exemplar) ValueType() ExemplarValueType {\n\tswitch ms.orig.Value.(type) {\n\tcase *internal.Exemplar_AsDouble:\n\t\treturn ExemplarValueTypeDouble\n\tcase *internal.Exemplar_AsInt:\n\t\treturn ExemplarValueTypeInt\n\t}\n\treturn ExemplarValueTypeEmpty\n}\n\n// DoubleValue returns the double associated with this Exemplar.\nfunc (ms Exemplar) DoubleValue() float64 {\n\treturn ms.orig.GetAsDouble()\n}\n\n// SetDoubleValue replaces the double associated with this Exemplar.\nfunc (ms Exemplar) SetDoubleValue(v float64) {\n\tms.state.AssertMutable()\n\tvar ov *internal.Exemplar_AsDouble\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\tov = &internal.Exemplar_AsDouble{}\n\t} else {\n\t\tov = internal.ProtoPoolExemplar_AsDouble.Get().(*internal.Exemplar_AsDouble)\n\t}\n\tov.AsDouble = v\n\tms.orig.Value = ov\n} // IntValue returns the int associated with this Exemplar.\nfunc (ms Exemplar) IntValue() int64 {\n\treturn ms.orig.GetAsInt()\n}\n\n// SetIntValue replaces the int associated with this Exemplar.\nfunc (ms Exemplar) SetIntValue(v int64) {\n\tms.state.AssertMutable()\n\tvar ov *internal.Exemplar_AsInt\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\tov = &internal.Exemplar_AsInt{}\n\t} else {\n\t\tov = internal.ProtoPoolExemplar_AsInt.Get().(*internal.Exemplar_AsInt)\n\t}\n\tov.AsInt = v\n\tms.orig.Value = ov\n}\n\n// TraceID returns the traceid associated with this Exemplar.\nfunc (ms Exemplar) TraceID() pcommon.TraceID {\n\treturn pcommon.TraceID(ms.orig.TraceId)\n}\n\n// SetTraceID replaces the traceid associated with this Exemplar.\nfunc (ms Exemplar) SetTraceID(v pcommon.TraceID) {\n\tms.state.AssertMutable()\n\tms.orig.TraceId = internal.TraceID(v)\n}\n\n// SpanID returns the spanid associated with this Exemplar.\nfunc (ms Exemplar) SpanID() pcommon.SpanID {\n\treturn pcommon.SpanID(ms.orig.SpanId)\n}\n\n// SetSpanID replaces the spanid associated with this Exemplar.\nfunc (ms Exemplar) SetSpanID(v pcommon.SpanID) {\n\tms.state.AssertMutable()\n\tms.orig.SpanId = internal.SpanID(v)\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Exemplar) CopyTo(dest Exemplar) {\n\tdest.state.AssertMutable()\n\tinternal.CopyExemplar(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_exemplar_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestExemplar_MoveTo(t *testing.T) {\n\tms := generateTestExemplar()\n\tdest := NewExemplar()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewExemplar(), ms)\n\tassert.Equal(t, generateTestExemplar(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestExemplar(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newExemplar(internal.NewExemplar(), sharedState)) })\n\tassert.Panics(t, func() { newExemplar(internal.NewExemplar(), sharedState).MoveTo(dest) })\n}\n\nfunc TestExemplar_CopyTo(t *testing.T) {\n\tms := NewExemplar()\n\torig := NewExemplar()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestExemplar()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newExemplar(internal.NewExemplar(), sharedState)) })\n}\n\nfunc TestExemplar_FilteredAttributes(t *testing.T) {\n\tms := NewExemplar()\n\tassert.Equal(t, pcommon.NewMap(), ms.FilteredAttributes())\n\tms.orig.FilteredAttributes = internal.GenTestKeyValueSlice()\n\tassert.Equal(t, pcommon.Map(internal.GenTestMapWrapper()), ms.FilteredAttributes())\n}\n\nfunc TestExemplar_Timestamp(t *testing.T) {\n\tms := NewExemplar()\n\tassert.Equal(t, pcommon.Timestamp(0), ms.Timestamp())\n\ttestValTimestamp := pcommon.Timestamp(1234567890)\n\tms.SetTimestamp(testValTimestamp)\n\tassert.Equal(t, testValTimestamp, ms.Timestamp())\n}\n\nfunc TestExemplar_ValueType(t *testing.T) {\n\ttv := NewExemplar()\n\tassert.Equal(t, ExemplarValueTypeEmpty, tv.ValueType())\n}\n\nfunc TestExemplar_DoubleValue(t *testing.T) {\n\tms := NewExemplar()\n\tassert.InDelta(t, float64(0), ms.DoubleValue(), 0.01)\n\tms.SetDoubleValue(float64(3.1415926))\n\tassert.InDelta(t, float64(3.1415926), ms.DoubleValue(), 0.01)\n\tassert.Equal(t, ExemplarValueTypeDouble, ms.ValueType())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newExemplar(internal.NewExemplar(), sharedState).SetDoubleValue(float64(3.1415926)) })\n}\nfunc TestExemplar_IntValue(t *testing.T) {\n\tms := NewExemplar()\n\tassert.Equal(t, int64(0), ms.IntValue())\n\tms.SetIntValue(int64(13))\n\tassert.Equal(t, int64(13), ms.IntValue())\n\tassert.Equal(t, ExemplarValueTypeInt, ms.ValueType())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newExemplar(internal.NewExemplar(), sharedState).SetIntValue(int64(13)) })\n}\n\nfunc TestExemplar_TraceID(t *testing.T) {\n\tms := NewExemplar()\n\tassert.Equal(t, pcommon.TraceID(internal.TraceID([16]byte{})), ms.TraceID())\n\ttestValTraceID := pcommon.TraceID(internal.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1}))\n\tms.SetTraceID(testValTraceID)\n\tassert.Equal(t, testValTraceID, ms.TraceID())\n}\n\nfunc TestExemplar_SpanID(t *testing.T) {\n\tms := NewExemplar()\n\tassert.Equal(t, pcommon.SpanID(internal.SpanID([8]byte{})), ms.SpanID())\n\ttestValSpanID := pcommon.SpanID(internal.SpanID([8]byte{8, 7, 6, 5, 4, 3, 2, 1}))\n\tms.SetSpanID(testValSpanID)\n\tassert.Equal(t, testValSpanID, ms.SpanID())\n}\n\nfunc generateTestExemplar() Exemplar {\n\treturn newExemplar(internal.GenTestExemplar(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_exemplarslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"iter\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ExemplarSlice logically represents a slice of Exemplar.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewExemplarSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ExemplarSlice struct {\n\torig  *[]internal.Exemplar\n\tstate *internal.State\n}\n\nfunc newExemplarSlice(orig *[]internal.Exemplar, state *internal.State) ExemplarSlice {\n\treturn ExemplarSlice{orig: orig, state: state}\n}\n\n// NewExemplarSlice creates a ExemplarSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewExemplarSlice() ExemplarSlice {\n\torig := []internal.Exemplar(nil)\n\treturn newExemplarSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewExemplarSlice()\".\nfunc (es ExemplarSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es ExemplarSlice) At(i int) Exemplar {\n\treturn newExemplar(&(*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es ExemplarSlice) All() iter.Seq2[int, Exemplar] {\n\treturn func(yield func(int, Exemplar) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new ExemplarSlice can be initialized:\n//\n//\tes := NewExemplarSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es ExemplarSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]internal.Exemplar, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty Exemplar.\n// It returns the newly added Exemplar.\nfunc (es ExemplarSlice) AppendEmpty() Exemplar {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.Exemplar{})\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es ExemplarSlice) MoveAndAppendTo(dest ExemplarSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es ExemplarSlice) RemoveIf(f func(Exemplar) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteExemplar(&(*es.orig)[i], false)\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t(*es.orig)[i].Reset()\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es ExemplarSlice) CopyTo(dest ExemplarSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyExemplarSlice(*dest.orig, *es.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_exemplarslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestExemplarSlice(t *testing.T) {\n\tes := NewExemplarSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newExemplarSlice(&[]internal.Exemplar{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewExemplar()\n\ttestVal := generateTestExemplar()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = *internal.GenTestExemplar()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestExemplarSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newExemplarSlice(&[]internal.Exemplar{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewExemplarSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestExemplarSlice_CopyTo(t *testing.T) {\n\tdest := NewExemplarSlice()\n\tsrc := generateTestExemplarSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestExemplarSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestExemplarSlice(), dest)\n}\n\nfunc TestExemplarSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestExemplarSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestExemplarSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestExemplarSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestExemplarSlice(), es)\n}\n\nfunc TestExemplarSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestExemplarSlice()\n\tdest := NewExemplarSlice()\n\tsrc := generateTestExemplarSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestExemplarSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestExemplarSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestExemplarSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestExemplarSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewExemplarSlice()\n\temptySlice.RemoveIf(func(el Exemplar) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestExemplarSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el Exemplar) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestExemplarSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestExemplarSlice()\n\tgot.RemoveIf(func(el Exemplar) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestExemplarSliceAll(t *testing.T) {\n\tms := generateTestExemplarSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc generateTestExemplarSlice() ExemplarSlice {\n\tms := NewExemplarSlice()\n\t*ms.orig = internal.GenTestExemplarSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_exponentialhistogram.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ExponentialHistogram represents the type of a metric that is calculated by aggregating\n// as a ExponentialHistogram of all reported double measurements over a time interval.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewExponentialHistogram function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ExponentialHistogram struct {\n\torig  *internal.ExponentialHistogram\n\tstate *internal.State\n}\n\nfunc newExponentialHistogram(orig *internal.ExponentialHistogram, state *internal.State) ExponentialHistogram {\n\treturn ExponentialHistogram{orig: orig, state: state}\n}\n\n// NewExponentialHistogram creates a new empty ExponentialHistogram.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewExponentialHistogram() ExponentialHistogram {\n\treturn newExponentialHistogram(internal.NewExponentialHistogram(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ExponentialHistogram) MoveTo(dest ExponentialHistogram) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteExponentialHistogram(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// DataPoints returns the DataPoints associated with this ExponentialHistogram.\nfunc (ms ExponentialHistogram) DataPoints() ExponentialHistogramDataPointSlice {\n\treturn newExponentialHistogramDataPointSlice(&ms.orig.DataPoints, ms.state)\n}\n\n// AggregationTemporality returns the aggregationtemporality associated with this ExponentialHistogram.\nfunc (ms ExponentialHistogram) AggregationTemporality() AggregationTemporality {\n\treturn AggregationTemporality(ms.orig.AggregationTemporality)\n}\n\n// SetAggregationTemporality replaces the aggregationtemporality associated with this ExponentialHistogram.\nfunc (ms ExponentialHistogram) SetAggregationTemporality(v AggregationTemporality) {\n\tms.state.AssertMutable()\n\tms.orig.AggregationTemporality = internal.AggregationTemporality(v)\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ExponentialHistogram) CopyTo(dest ExponentialHistogram) {\n\tdest.state.AssertMutable()\n\tinternal.CopyExponentialHistogram(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_exponentialhistogram_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestExponentialHistogram_MoveTo(t *testing.T) {\n\tms := generateTestExponentialHistogram()\n\tdest := NewExponentialHistogram()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewExponentialHistogram(), ms)\n\tassert.Equal(t, generateTestExponentialHistogram(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestExponentialHistogram(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newExponentialHistogram(internal.NewExponentialHistogram(), sharedState)) })\n\tassert.Panics(t, func() { newExponentialHistogram(internal.NewExponentialHistogram(), sharedState).MoveTo(dest) })\n}\n\nfunc TestExponentialHistogram_CopyTo(t *testing.T) {\n\tms := NewExponentialHistogram()\n\torig := NewExponentialHistogram()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestExponentialHistogram()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newExponentialHistogram(internal.NewExponentialHistogram(), sharedState)) })\n}\n\nfunc TestExponentialHistogram_DataPoints(t *testing.T) {\n\tms := NewExponentialHistogram()\n\tassert.Equal(t, NewExponentialHistogramDataPointSlice(), ms.DataPoints())\n\tms.orig.DataPoints = internal.GenTestExponentialHistogramDataPointPtrSlice()\n\tassert.Equal(t, generateTestExponentialHistogramDataPointSlice(), ms.DataPoints())\n}\n\nfunc TestExponentialHistogram_AggregationTemporality(t *testing.T) {\n\tms := NewExponentialHistogram()\n\tassert.Equal(t, AggregationTemporality(internal.AggregationTemporality(0)), ms.AggregationTemporality())\n\ttestValAggregationTemporality := AggregationTemporality(internal.AggregationTemporality(1))\n\tms.SetAggregationTemporality(testValAggregationTemporality)\n\tassert.Equal(t, testValAggregationTemporality, ms.AggregationTemporality())\n}\n\nfunc generateTestExponentialHistogram() ExponentialHistogram {\n\treturn newExponentialHistogram(internal.GenTestExponentialHistogram(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_exponentialhistogramdatapoint.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ExponentialHistogramDataPoint is a single data point in a timeseries that describes the\n// time-varying values of a ExponentialHistogram of double values. A ExponentialHistogram contains\n// summary statistics for a population of values, it may optionally contain the\n// distribution of those values across a set of buckets.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewExponentialHistogramDataPoint function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ExponentialHistogramDataPoint struct {\n\torig  *internal.ExponentialHistogramDataPoint\n\tstate *internal.State\n}\n\nfunc newExponentialHistogramDataPoint(orig *internal.ExponentialHistogramDataPoint, state *internal.State) ExponentialHistogramDataPoint {\n\treturn ExponentialHistogramDataPoint{orig: orig, state: state}\n}\n\n// NewExponentialHistogramDataPoint creates a new empty ExponentialHistogramDataPoint.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewExponentialHistogramDataPoint() ExponentialHistogramDataPoint {\n\treturn newExponentialHistogramDataPoint(internal.NewExponentialHistogramDataPoint(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ExponentialHistogramDataPoint) MoveTo(dest ExponentialHistogramDataPoint) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteExponentialHistogramDataPoint(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Attributes returns the Attributes associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) Attributes() pcommon.Map {\n\treturn pcommon.Map(internal.NewMapWrapper(&ms.orig.Attributes, ms.state))\n}\n\n// StartTimestamp returns the starttimestamp associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) StartTimestamp() pcommon.Timestamp {\n\treturn pcommon.Timestamp(ms.orig.StartTimeUnixNano)\n}\n\n// SetStartTimestamp replaces the starttimestamp associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) SetStartTimestamp(v pcommon.Timestamp) {\n\tms.state.AssertMutable()\n\tms.orig.StartTimeUnixNano = uint64(v)\n}\n\n// Timestamp returns the timestamp associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) Timestamp() pcommon.Timestamp {\n\treturn pcommon.Timestamp(ms.orig.TimeUnixNano)\n}\n\n// SetTimestamp replaces the timestamp associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) SetTimestamp(v pcommon.Timestamp) {\n\tms.state.AssertMutable()\n\tms.orig.TimeUnixNano = uint64(v)\n}\n\n// Count returns the count associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) Count() uint64 {\n\treturn ms.orig.Count\n}\n\n// SetCount replaces the count associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) SetCount(v uint64) {\n\tms.state.AssertMutable()\n\tms.orig.Count = v\n}\n\n// Sum returns the sum associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) Sum() float64 {\n\treturn ms.orig.Sum\n}\n\n// HasSum returns true if the ExponentialHistogramDataPoint contains a\n// Sum value otherwise.\nfunc (ms ExponentialHistogramDataPoint) HasSum() bool {\n\treturn ms.orig.HasSum()\n}\n\n// SetSum replaces the sum associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) SetSum(v float64) {\n\tms.state.AssertMutable()\n\tms.orig.SetSum(v)\n}\n\n// RemoveSum removes the sum associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) RemoveSum() {\n\tms.state.AssertMutable()\n\tms.orig.RemoveSum()\n}\n\n// Scale returns the scale associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) Scale() int32 {\n\treturn ms.orig.Scale\n}\n\n// SetScale replaces the scale associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) SetScale(v int32) {\n\tms.state.AssertMutable()\n\tms.orig.Scale = v\n}\n\n// ZeroCount returns the zerocount associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) ZeroCount() uint64 {\n\treturn ms.orig.ZeroCount\n}\n\n// SetZeroCount replaces the zerocount associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) SetZeroCount(v uint64) {\n\tms.state.AssertMutable()\n\tms.orig.ZeroCount = v\n}\n\n// Positive returns the positive associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) Positive() ExponentialHistogramDataPointBuckets {\n\treturn newExponentialHistogramDataPointBuckets(&ms.orig.Positive, ms.state)\n}\n\n// Negative returns the negative associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) Negative() ExponentialHistogramDataPointBuckets {\n\treturn newExponentialHistogramDataPointBuckets(&ms.orig.Negative, ms.state)\n}\n\n// Flags returns the flags associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) Flags() DataPointFlags {\n\treturn DataPointFlags(ms.orig.Flags)\n}\n\n// SetFlags replaces the flags associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) SetFlags(v DataPointFlags) {\n\tms.state.AssertMutable()\n\tms.orig.Flags = uint32(v)\n}\n\n// Exemplars returns the Exemplars associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) Exemplars() ExemplarSlice {\n\treturn newExemplarSlice(&ms.orig.Exemplars, ms.state)\n}\n\n// Min returns the min associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) Min() float64 {\n\treturn ms.orig.Min\n}\n\n// HasMin returns true if the ExponentialHistogramDataPoint contains a\n// Min value otherwise.\nfunc (ms ExponentialHistogramDataPoint) HasMin() bool {\n\treturn ms.orig.HasMin()\n}\n\n// SetMin replaces the min associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) SetMin(v float64) {\n\tms.state.AssertMutable()\n\tms.orig.SetMin(v)\n}\n\n// RemoveMin removes the min associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) RemoveMin() {\n\tms.state.AssertMutable()\n\tms.orig.RemoveMin()\n}\n\n// Max returns the max associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) Max() float64 {\n\treturn ms.orig.Max\n}\n\n// HasMax returns true if the ExponentialHistogramDataPoint contains a\n// Max value otherwise.\nfunc (ms ExponentialHistogramDataPoint) HasMax() bool {\n\treturn ms.orig.HasMax()\n}\n\n// SetMax replaces the max associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) SetMax(v float64) {\n\tms.state.AssertMutable()\n\tms.orig.SetMax(v)\n}\n\n// RemoveMax removes the max associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) RemoveMax() {\n\tms.state.AssertMutable()\n\tms.orig.RemoveMax()\n}\n\n// ZeroThreshold returns the zerothreshold associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) ZeroThreshold() float64 {\n\treturn ms.orig.ZeroThreshold\n}\n\n// SetZeroThreshold replaces the zerothreshold associated with this ExponentialHistogramDataPoint.\nfunc (ms ExponentialHistogramDataPoint) SetZeroThreshold(v float64) {\n\tms.state.AssertMutable()\n\tms.orig.ZeroThreshold = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ExponentialHistogramDataPoint) CopyTo(dest ExponentialHistogramDataPoint) {\n\tdest.state.AssertMutable()\n\tinternal.CopyExponentialHistogramDataPoint(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_exponentialhistogramdatapoint_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestExponentialHistogramDataPoint_MoveTo(t *testing.T) {\n\tms := generateTestExponentialHistogramDataPoint()\n\tdest := NewExponentialHistogramDataPoint()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewExponentialHistogramDataPoint(), ms)\n\tassert.Equal(t, generateTestExponentialHistogramDataPoint(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestExponentialHistogramDataPoint(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tms.MoveTo(newExponentialHistogramDataPoint(internal.NewExponentialHistogramDataPoint(), sharedState))\n\t})\n\tassert.Panics(t, func() {\n\t\tnewExponentialHistogramDataPoint(internal.NewExponentialHistogramDataPoint(), sharedState).MoveTo(dest)\n\t})\n}\n\nfunc TestExponentialHistogramDataPoint_CopyTo(t *testing.T) {\n\tms := NewExponentialHistogramDataPoint()\n\torig := NewExponentialHistogramDataPoint()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestExponentialHistogramDataPoint()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tms.CopyTo(newExponentialHistogramDataPoint(internal.NewExponentialHistogramDataPoint(), sharedState))\n\t})\n}\n\nfunc TestExponentialHistogramDataPoint_Attributes(t *testing.T) {\n\tms := NewExponentialHistogramDataPoint()\n\tassert.Equal(t, pcommon.NewMap(), ms.Attributes())\n\tms.orig.Attributes = internal.GenTestKeyValueSlice()\n\tassert.Equal(t, pcommon.Map(internal.GenTestMapWrapper()), ms.Attributes())\n}\n\nfunc TestExponentialHistogramDataPoint_StartTimestamp(t *testing.T) {\n\tms := NewExponentialHistogramDataPoint()\n\tassert.Equal(t, pcommon.Timestamp(0), ms.StartTimestamp())\n\ttestValStartTimestamp := pcommon.Timestamp(1234567890)\n\tms.SetStartTimestamp(testValStartTimestamp)\n\tassert.Equal(t, testValStartTimestamp, ms.StartTimestamp())\n}\n\nfunc TestExponentialHistogramDataPoint_Timestamp(t *testing.T) {\n\tms := NewExponentialHistogramDataPoint()\n\tassert.Equal(t, pcommon.Timestamp(0), ms.Timestamp())\n\ttestValTimestamp := pcommon.Timestamp(1234567890)\n\tms.SetTimestamp(testValTimestamp)\n\tassert.Equal(t, testValTimestamp, ms.Timestamp())\n}\n\nfunc TestExponentialHistogramDataPoint_Count(t *testing.T) {\n\tms := NewExponentialHistogramDataPoint()\n\tassert.Equal(t, uint64(0), ms.Count())\n\tms.SetCount(uint64(13))\n\tassert.Equal(t, uint64(13), ms.Count())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewExponentialHistogramDataPoint(internal.NewExponentialHistogramDataPoint(), sharedState).SetCount(uint64(13))\n\t})\n}\n\nfunc TestExponentialHistogramDataPoint_Sum(t *testing.T) {\n\tms := NewExponentialHistogramDataPoint()\n\tassert.InDelta(t, float64(0), ms.Sum(), 0.01)\n\tms.SetSum(float64(3.1415926))\n\tassert.True(t, ms.HasSum())\n\tassert.InDelta(t, float64(3.1415926), ms.Sum(), 0.01)\n\tms.RemoveSum()\n\tassert.False(t, ms.HasSum())\n\tdest := NewExponentialHistogramDataPoint()\n\tdest.SetSum(float64(3.1415926))\n\tms.CopyTo(dest)\n\tassert.False(t, dest.HasSum())\n}\n\nfunc TestExponentialHistogramDataPoint_Scale(t *testing.T) {\n\tms := NewExponentialHistogramDataPoint()\n\tassert.Equal(t, int32(0), ms.Scale())\n\tms.SetScale(int32(13))\n\tassert.Equal(t, int32(13), ms.Scale())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewExponentialHistogramDataPoint(internal.NewExponentialHistogramDataPoint(), sharedState).SetScale(int32(13))\n\t})\n}\n\nfunc TestExponentialHistogramDataPoint_ZeroCount(t *testing.T) {\n\tms := NewExponentialHistogramDataPoint()\n\tassert.Equal(t, uint64(0), ms.ZeroCount())\n\tms.SetZeroCount(uint64(13))\n\tassert.Equal(t, uint64(13), ms.ZeroCount())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewExponentialHistogramDataPoint(internal.NewExponentialHistogramDataPoint(), sharedState).SetZeroCount(uint64(13))\n\t})\n}\n\nfunc TestExponentialHistogramDataPoint_Positive(t *testing.T) {\n\tms := NewExponentialHistogramDataPoint()\n\tassert.Equal(t, NewExponentialHistogramDataPointBuckets(), ms.Positive())\n\tms.orig.Positive = *internal.GenTestExponentialHistogramDataPointBuckets()\n\tassert.Equal(t, generateTestExponentialHistogramDataPointBuckets(), ms.Positive())\n}\n\nfunc TestExponentialHistogramDataPoint_Negative(t *testing.T) {\n\tms := NewExponentialHistogramDataPoint()\n\tassert.Equal(t, NewExponentialHistogramDataPointBuckets(), ms.Negative())\n\tms.orig.Negative = *internal.GenTestExponentialHistogramDataPointBuckets()\n\tassert.Equal(t, generateTestExponentialHistogramDataPointBuckets(), ms.Negative())\n}\n\nfunc TestExponentialHistogramDataPoint_Flags(t *testing.T) {\n\tms := NewExponentialHistogramDataPoint()\n\tassert.Equal(t, DataPointFlags(0), ms.Flags())\n\ttestValFlags := DataPointFlags(1)\n\tms.SetFlags(testValFlags)\n\tassert.Equal(t, testValFlags, ms.Flags())\n}\n\nfunc TestExponentialHistogramDataPoint_Exemplars(t *testing.T) {\n\tms := NewExponentialHistogramDataPoint()\n\tassert.Equal(t, NewExemplarSlice(), ms.Exemplars())\n\tms.orig.Exemplars = internal.GenTestExemplarSlice()\n\tassert.Equal(t, generateTestExemplarSlice(), ms.Exemplars())\n}\n\nfunc TestExponentialHistogramDataPoint_Min(t *testing.T) {\n\tms := NewExponentialHistogramDataPoint()\n\tassert.InDelta(t, float64(0), ms.Min(), 0.01)\n\tms.SetMin(float64(3.1415926))\n\tassert.True(t, ms.HasMin())\n\tassert.InDelta(t, float64(3.1415926), ms.Min(), 0.01)\n\tms.RemoveMin()\n\tassert.False(t, ms.HasMin())\n\tdest := NewExponentialHistogramDataPoint()\n\tdest.SetMin(float64(3.1415926))\n\tms.CopyTo(dest)\n\tassert.False(t, dest.HasMin())\n}\n\nfunc TestExponentialHistogramDataPoint_Max(t *testing.T) {\n\tms := NewExponentialHistogramDataPoint()\n\tassert.InDelta(t, float64(0), ms.Max(), 0.01)\n\tms.SetMax(float64(3.1415926))\n\tassert.True(t, ms.HasMax())\n\tassert.InDelta(t, float64(3.1415926), ms.Max(), 0.01)\n\tms.RemoveMax()\n\tassert.False(t, ms.HasMax())\n\tdest := NewExponentialHistogramDataPoint()\n\tdest.SetMax(float64(3.1415926))\n\tms.CopyTo(dest)\n\tassert.False(t, dest.HasMax())\n}\n\nfunc TestExponentialHistogramDataPoint_ZeroThreshold(t *testing.T) {\n\tms := NewExponentialHistogramDataPoint()\n\tassert.InDelta(t, float64(0), ms.ZeroThreshold(), 0.01)\n\tms.SetZeroThreshold(float64(3.1415926))\n\tassert.InDelta(t, float64(3.1415926), ms.ZeroThreshold(), 0.01)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewExponentialHistogramDataPoint(internal.NewExponentialHistogramDataPoint(), sharedState).SetZeroThreshold(float64(3.1415926))\n\t})\n}\n\nfunc generateTestExponentialHistogramDataPoint() ExponentialHistogramDataPoint {\n\treturn newExponentialHistogramDataPoint(internal.GenTestExponentialHistogramDataPoint(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_exponentialhistogramdatapointbuckets.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ExponentialHistogramDataPointBuckets are a set of bucket counts, encoded in a contiguous array of counts.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewExponentialHistogramDataPointBuckets function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ExponentialHistogramDataPointBuckets struct {\n\torig  *internal.ExponentialHistogramDataPointBuckets\n\tstate *internal.State\n}\n\nfunc newExponentialHistogramDataPointBuckets(orig *internal.ExponentialHistogramDataPointBuckets, state *internal.State) ExponentialHistogramDataPointBuckets {\n\treturn ExponentialHistogramDataPointBuckets{orig: orig, state: state}\n}\n\n// NewExponentialHistogramDataPointBuckets creates a new empty ExponentialHistogramDataPointBuckets.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewExponentialHistogramDataPointBuckets() ExponentialHistogramDataPointBuckets {\n\treturn newExponentialHistogramDataPointBuckets(internal.NewExponentialHistogramDataPointBuckets(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ExponentialHistogramDataPointBuckets) MoveTo(dest ExponentialHistogramDataPointBuckets) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteExponentialHistogramDataPointBuckets(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Offset returns the offset associated with this ExponentialHistogramDataPointBuckets.\nfunc (ms ExponentialHistogramDataPointBuckets) Offset() int32 {\n\treturn ms.orig.Offset\n}\n\n// SetOffset replaces the offset associated with this ExponentialHistogramDataPointBuckets.\nfunc (ms ExponentialHistogramDataPointBuckets) SetOffset(v int32) {\n\tms.state.AssertMutable()\n\tms.orig.Offset = v\n}\n\n// BucketCounts returns the BucketCounts associated with this ExponentialHistogramDataPointBuckets.\nfunc (ms ExponentialHistogramDataPointBuckets) BucketCounts() pcommon.UInt64Slice {\n\treturn pcommon.UInt64Slice(internal.NewUInt64SliceWrapper(&ms.orig.BucketCounts, ms.state))\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ExponentialHistogramDataPointBuckets) CopyTo(dest ExponentialHistogramDataPointBuckets) {\n\tdest.state.AssertMutable()\n\tinternal.CopyExponentialHistogramDataPointBuckets(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_exponentialhistogramdatapointbuckets_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestExponentialHistogramDataPointBuckets_MoveTo(t *testing.T) {\n\tms := generateTestExponentialHistogramDataPointBuckets()\n\tdest := NewExponentialHistogramDataPointBuckets()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewExponentialHistogramDataPointBuckets(), ms)\n\tassert.Equal(t, generateTestExponentialHistogramDataPointBuckets(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestExponentialHistogramDataPointBuckets(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tms.MoveTo(newExponentialHistogramDataPointBuckets(internal.NewExponentialHistogramDataPointBuckets(), sharedState))\n\t})\n\tassert.Panics(t, func() {\n\t\tnewExponentialHistogramDataPointBuckets(internal.NewExponentialHistogramDataPointBuckets(), sharedState).MoveTo(dest)\n\t})\n}\n\nfunc TestExponentialHistogramDataPointBuckets_CopyTo(t *testing.T) {\n\tms := NewExponentialHistogramDataPointBuckets()\n\torig := NewExponentialHistogramDataPointBuckets()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestExponentialHistogramDataPointBuckets()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tms.CopyTo(newExponentialHistogramDataPointBuckets(internal.NewExponentialHistogramDataPointBuckets(), sharedState))\n\t})\n}\n\nfunc TestExponentialHistogramDataPointBuckets_Offset(t *testing.T) {\n\tms := NewExponentialHistogramDataPointBuckets()\n\tassert.Equal(t, int32(0), ms.Offset())\n\tms.SetOffset(int32(13))\n\tassert.Equal(t, int32(13), ms.Offset())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewExponentialHistogramDataPointBuckets(internal.NewExponentialHistogramDataPointBuckets(), sharedState).SetOffset(int32(13))\n\t})\n}\n\nfunc TestExponentialHistogramDataPointBuckets_BucketCounts(t *testing.T) {\n\tms := NewExponentialHistogramDataPointBuckets()\n\tassert.Equal(t, pcommon.NewUInt64Slice(), ms.BucketCounts())\n\tms.orig.BucketCounts = internal.GenTestUint64Slice()\n\tassert.Equal(t, pcommon.UInt64Slice(internal.GenTestUInt64SliceWrapper()), ms.BucketCounts())\n}\n\nfunc generateTestExponentialHistogramDataPointBuckets() ExponentialHistogramDataPointBuckets {\n\treturn newExponentialHistogramDataPointBuckets(internal.GenTestExponentialHistogramDataPointBuckets(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_exponentialhistogramdatapointslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ExponentialHistogramDataPointSlice logically represents a slice of ExponentialHistogramDataPoint.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewExponentialHistogramDataPointSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ExponentialHistogramDataPointSlice struct {\n\torig  *[]*internal.ExponentialHistogramDataPoint\n\tstate *internal.State\n}\n\nfunc newExponentialHistogramDataPointSlice(orig *[]*internal.ExponentialHistogramDataPoint, state *internal.State) ExponentialHistogramDataPointSlice {\n\treturn ExponentialHistogramDataPointSlice{orig: orig, state: state}\n}\n\n// NewExponentialHistogramDataPointSlice creates a ExponentialHistogramDataPointSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewExponentialHistogramDataPointSlice() ExponentialHistogramDataPointSlice {\n\torig := []*internal.ExponentialHistogramDataPoint(nil)\n\treturn newExponentialHistogramDataPointSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewExponentialHistogramDataPointSlice()\".\nfunc (es ExponentialHistogramDataPointSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es ExponentialHistogramDataPointSlice) At(i int) ExponentialHistogramDataPoint {\n\treturn newExponentialHistogramDataPoint((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es ExponentialHistogramDataPointSlice) All() iter.Seq2[int, ExponentialHistogramDataPoint] {\n\treturn func(yield func(int, ExponentialHistogramDataPoint) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new ExponentialHistogramDataPointSlice can be initialized:\n//\n//\tes := NewExponentialHistogramDataPointSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es ExponentialHistogramDataPointSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.ExponentialHistogramDataPoint, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty ExponentialHistogramDataPoint.\n// It returns the newly added ExponentialHistogramDataPoint.\nfunc (es ExponentialHistogramDataPointSlice) AppendEmpty() ExponentialHistogramDataPoint {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewExponentialHistogramDataPoint())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es ExponentialHistogramDataPointSlice) MoveAndAppendTo(dest ExponentialHistogramDataPointSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es ExponentialHistogramDataPointSlice) RemoveIf(f func(ExponentialHistogramDataPoint) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteExponentialHistogramDataPoint((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es ExponentialHistogramDataPointSlice) CopyTo(dest ExponentialHistogramDataPointSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyExponentialHistogramDataPointPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the ExponentialHistogramDataPoint elements within ExponentialHistogramDataPointSlice given the\n// provided less function so that two instances of ExponentialHistogramDataPointSlice\n// can be compared.\nfunc (es ExponentialHistogramDataPointSlice) Sort(less func(a, b ExponentialHistogramDataPoint) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_exponentialhistogramdatapointslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestExponentialHistogramDataPointSlice(t *testing.T) {\n\tes := NewExponentialHistogramDataPointSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newExponentialHistogramDataPointSlice(&[]*internal.ExponentialHistogramDataPoint{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewExponentialHistogramDataPoint()\n\ttestVal := generateTestExponentialHistogramDataPoint()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestExponentialHistogramDataPoint()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestExponentialHistogramDataPointSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newExponentialHistogramDataPointSlice(&[]*internal.ExponentialHistogramDataPoint{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewExponentialHistogramDataPointSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestExponentialHistogramDataPointSlice_CopyTo(t *testing.T) {\n\tdest := NewExponentialHistogramDataPointSlice()\n\tsrc := generateTestExponentialHistogramDataPointSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestExponentialHistogramDataPointSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestExponentialHistogramDataPointSlice(), dest)\n}\n\nfunc TestExponentialHistogramDataPointSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestExponentialHistogramDataPointSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestExponentialHistogramDataPointSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestExponentialHistogramDataPointSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestExponentialHistogramDataPointSlice(), es)\n}\n\nfunc TestExponentialHistogramDataPointSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestExponentialHistogramDataPointSlice()\n\tdest := NewExponentialHistogramDataPointSlice()\n\tsrc := generateTestExponentialHistogramDataPointSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestExponentialHistogramDataPointSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestExponentialHistogramDataPointSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestExponentialHistogramDataPointSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestExponentialHistogramDataPointSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewExponentialHistogramDataPointSlice()\n\temptySlice.RemoveIf(func(el ExponentialHistogramDataPoint) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestExponentialHistogramDataPointSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el ExponentialHistogramDataPoint) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestExponentialHistogramDataPointSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestExponentialHistogramDataPointSlice()\n\tgot.RemoveIf(func(el ExponentialHistogramDataPoint) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestExponentialHistogramDataPointSliceAll(t *testing.T) {\n\tms := generateTestExponentialHistogramDataPointSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestExponentialHistogramDataPointSlice_Sort(t *testing.T) {\n\tes := generateTestExponentialHistogramDataPointSlice()\n\tes.Sort(func(a, b ExponentialHistogramDataPoint) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b ExponentialHistogramDataPoint) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestExponentialHistogramDataPointSlice() ExponentialHistogramDataPointSlice {\n\tms := NewExponentialHistogramDataPointSlice()\n\t*ms.orig = internal.GenTestExponentialHistogramDataPointPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_gauge.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// Gauge represents the type of a numeric metric that always exports the \"current value\" for every data point.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewGauge function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Gauge struct {\n\torig  *internal.Gauge\n\tstate *internal.State\n}\n\nfunc newGauge(orig *internal.Gauge, state *internal.State) Gauge {\n\treturn Gauge{orig: orig, state: state}\n}\n\n// NewGauge creates a new empty Gauge.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewGauge() Gauge {\n\treturn newGauge(internal.NewGauge(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Gauge) MoveTo(dest Gauge) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteGauge(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// DataPoints returns the DataPoints associated with this Gauge.\nfunc (ms Gauge) DataPoints() NumberDataPointSlice {\n\treturn newNumberDataPointSlice(&ms.orig.DataPoints, ms.state)\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Gauge) CopyTo(dest Gauge) {\n\tdest.state.AssertMutable()\n\tinternal.CopyGauge(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_gauge_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestGauge_MoveTo(t *testing.T) {\n\tms := generateTestGauge()\n\tdest := NewGauge()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewGauge(), ms)\n\tassert.Equal(t, generateTestGauge(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestGauge(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newGauge(internal.NewGauge(), sharedState)) })\n\tassert.Panics(t, func() { newGauge(internal.NewGauge(), sharedState).MoveTo(dest) })\n}\n\nfunc TestGauge_CopyTo(t *testing.T) {\n\tms := NewGauge()\n\torig := NewGauge()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestGauge()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newGauge(internal.NewGauge(), sharedState)) })\n}\n\nfunc TestGauge_DataPoints(t *testing.T) {\n\tms := NewGauge()\n\tassert.Equal(t, NewNumberDataPointSlice(), ms.DataPoints())\n\tms.orig.DataPoints = internal.GenTestNumberDataPointPtrSlice()\n\tassert.Equal(t, generateTestNumberDataPointSlice(), ms.DataPoints())\n}\n\nfunc generateTestGauge() Gauge {\n\treturn newGauge(internal.GenTestGauge(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_histogram.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// Histogram represents the type of a metric that is calculated by aggregating as a Histogram of all reported measurements over a time interval.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewHistogram function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Histogram struct {\n\torig  *internal.Histogram\n\tstate *internal.State\n}\n\nfunc newHistogram(orig *internal.Histogram, state *internal.State) Histogram {\n\treturn Histogram{orig: orig, state: state}\n}\n\n// NewHistogram creates a new empty Histogram.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewHistogram() Histogram {\n\treturn newHistogram(internal.NewHistogram(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Histogram) MoveTo(dest Histogram) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteHistogram(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// DataPoints returns the DataPoints associated with this Histogram.\nfunc (ms Histogram) DataPoints() HistogramDataPointSlice {\n\treturn newHistogramDataPointSlice(&ms.orig.DataPoints, ms.state)\n}\n\n// AggregationTemporality returns the aggregationtemporality associated with this Histogram.\nfunc (ms Histogram) AggregationTemporality() AggregationTemporality {\n\treturn AggregationTemporality(ms.orig.AggregationTemporality)\n}\n\n// SetAggregationTemporality replaces the aggregationtemporality associated with this Histogram.\nfunc (ms Histogram) SetAggregationTemporality(v AggregationTemporality) {\n\tms.state.AssertMutable()\n\tms.orig.AggregationTemporality = internal.AggregationTemporality(v)\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Histogram) CopyTo(dest Histogram) {\n\tdest.state.AssertMutable()\n\tinternal.CopyHistogram(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_histogram_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestHistogram_MoveTo(t *testing.T) {\n\tms := generateTestHistogram()\n\tdest := NewHistogram()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewHistogram(), ms)\n\tassert.Equal(t, generateTestHistogram(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestHistogram(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newHistogram(internal.NewHistogram(), sharedState)) })\n\tassert.Panics(t, func() { newHistogram(internal.NewHistogram(), sharedState).MoveTo(dest) })\n}\n\nfunc TestHistogram_CopyTo(t *testing.T) {\n\tms := NewHistogram()\n\torig := NewHistogram()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestHistogram()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newHistogram(internal.NewHistogram(), sharedState)) })\n}\n\nfunc TestHistogram_DataPoints(t *testing.T) {\n\tms := NewHistogram()\n\tassert.Equal(t, NewHistogramDataPointSlice(), ms.DataPoints())\n\tms.orig.DataPoints = internal.GenTestHistogramDataPointPtrSlice()\n\tassert.Equal(t, generateTestHistogramDataPointSlice(), ms.DataPoints())\n}\n\nfunc TestHistogram_AggregationTemporality(t *testing.T) {\n\tms := NewHistogram()\n\tassert.Equal(t, AggregationTemporality(internal.AggregationTemporality(0)), ms.AggregationTemporality())\n\ttestValAggregationTemporality := AggregationTemporality(internal.AggregationTemporality(1))\n\tms.SetAggregationTemporality(testValAggregationTemporality)\n\tassert.Equal(t, testValAggregationTemporality, ms.AggregationTemporality())\n}\n\nfunc generateTestHistogram() Histogram {\n\treturn newHistogram(internal.GenTestHistogram(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_histogramdatapoint.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// HistogramDataPoint is a single data point in a timeseries that describes the time-varying values of a Histogram of values.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewHistogramDataPoint function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype HistogramDataPoint struct {\n\torig  *internal.HistogramDataPoint\n\tstate *internal.State\n}\n\nfunc newHistogramDataPoint(orig *internal.HistogramDataPoint, state *internal.State) HistogramDataPoint {\n\treturn HistogramDataPoint{orig: orig, state: state}\n}\n\n// NewHistogramDataPoint creates a new empty HistogramDataPoint.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewHistogramDataPoint() HistogramDataPoint {\n\treturn newHistogramDataPoint(internal.NewHistogramDataPoint(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms HistogramDataPoint) MoveTo(dest HistogramDataPoint) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteHistogramDataPoint(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Attributes returns the Attributes associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) Attributes() pcommon.Map {\n\treturn pcommon.Map(internal.NewMapWrapper(&ms.orig.Attributes, ms.state))\n}\n\n// StartTimestamp returns the starttimestamp associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) StartTimestamp() pcommon.Timestamp {\n\treturn pcommon.Timestamp(ms.orig.StartTimeUnixNano)\n}\n\n// SetStartTimestamp replaces the starttimestamp associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) SetStartTimestamp(v pcommon.Timestamp) {\n\tms.state.AssertMutable()\n\tms.orig.StartTimeUnixNano = uint64(v)\n}\n\n// Timestamp returns the timestamp associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) Timestamp() pcommon.Timestamp {\n\treturn pcommon.Timestamp(ms.orig.TimeUnixNano)\n}\n\n// SetTimestamp replaces the timestamp associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) SetTimestamp(v pcommon.Timestamp) {\n\tms.state.AssertMutable()\n\tms.orig.TimeUnixNano = uint64(v)\n}\n\n// Count returns the count associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) Count() uint64 {\n\treturn ms.orig.Count\n}\n\n// SetCount replaces the count associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) SetCount(v uint64) {\n\tms.state.AssertMutable()\n\tms.orig.Count = v\n}\n\n// Sum returns the sum associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) Sum() float64 {\n\treturn ms.orig.Sum\n}\n\n// HasSum returns true if the HistogramDataPoint contains a\n// Sum value otherwise.\nfunc (ms HistogramDataPoint) HasSum() bool {\n\treturn ms.orig.HasSum()\n}\n\n// SetSum replaces the sum associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) SetSum(v float64) {\n\tms.state.AssertMutable()\n\tms.orig.SetSum(v)\n}\n\n// RemoveSum removes the sum associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) RemoveSum() {\n\tms.state.AssertMutable()\n\tms.orig.RemoveSum()\n}\n\n// BucketCounts returns the BucketCounts associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) BucketCounts() pcommon.UInt64Slice {\n\treturn pcommon.UInt64Slice(internal.NewUInt64SliceWrapper(&ms.orig.BucketCounts, ms.state))\n}\n\n// ExplicitBounds returns the ExplicitBounds associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) ExplicitBounds() pcommon.Float64Slice {\n\treturn pcommon.Float64Slice(internal.NewFloat64SliceWrapper(&ms.orig.ExplicitBounds, ms.state))\n}\n\n// Exemplars returns the Exemplars associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) Exemplars() ExemplarSlice {\n\treturn newExemplarSlice(&ms.orig.Exemplars, ms.state)\n}\n\n// Flags returns the flags associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) Flags() DataPointFlags {\n\treturn DataPointFlags(ms.orig.Flags)\n}\n\n// SetFlags replaces the flags associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) SetFlags(v DataPointFlags) {\n\tms.state.AssertMutable()\n\tms.orig.Flags = uint32(v)\n}\n\n// Min returns the min associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) Min() float64 {\n\treturn ms.orig.Min\n}\n\n// HasMin returns true if the HistogramDataPoint contains a\n// Min value otherwise.\nfunc (ms HistogramDataPoint) HasMin() bool {\n\treturn ms.orig.HasMin()\n}\n\n// SetMin replaces the min associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) SetMin(v float64) {\n\tms.state.AssertMutable()\n\tms.orig.SetMin(v)\n}\n\n// RemoveMin removes the min associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) RemoveMin() {\n\tms.state.AssertMutable()\n\tms.orig.RemoveMin()\n}\n\n// Max returns the max associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) Max() float64 {\n\treturn ms.orig.Max\n}\n\n// HasMax returns true if the HistogramDataPoint contains a\n// Max value otherwise.\nfunc (ms HistogramDataPoint) HasMax() bool {\n\treturn ms.orig.HasMax()\n}\n\n// SetMax replaces the max associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) SetMax(v float64) {\n\tms.state.AssertMutable()\n\tms.orig.SetMax(v)\n}\n\n// RemoveMax removes the max associated with this HistogramDataPoint.\nfunc (ms HistogramDataPoint) RemoveMax() {\n\tms.state.AssertMutable()\n\tms.orig.RemoveMax()\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms HistogramDataPoint) CopyTo(dest HistogramDataPoint) {\n\tdest.state.AssertMutable()\n\tinternal.CopyHistogramDataPoint(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_histogramdatapoint_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestHistogramDataPoint_MoveTo(t *testing.T) {\n\tms := generateTestHistogramDataPoint()\n\tdest := NewHistogramDataPoint()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewHistogramDataPoint(), ms)\n\tassert.Equal(t, generateTestHistogramDataPoint(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestHistogramDataPoint(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newHistogramDataPoint(internal.NewHistogramDataPoint(), sharedState)) })\n\tassert.Panics(t, func() { newHistogramDataPoint(internal.NewHistogramDataPoint(), sharedState).MoveTo(dest) })\n}\n\nfunc TestHistogramDataPoint_CopyTo(t *testing.T) {\n\tms := NewHistogramDataPoint()\n\torig := NewHistogramDataPoint()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestHistogramDataPoint()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newHistogramDataPoint(internal.NewHistogramDataPoint(), sharedState)) })\n}\n\nfunc TestHistogramDataPoint_Attributes(t *testing.T) {\n\tms := NewHistogramDataPoint()\n\tassert.Equal(t, pcommon.NewMap(), ms.Attributes())\n\tms.orig.Attributes = internal.GenTestKeyValueSlice()\n\tassert.Equal(t, pcommon.Map(internal.GenTestMapWrapper()), ms.Attributes())\n}\n\nfunc TestHistogramDataPoint_StartTimestamp(t *testing.T) {\n\tms := NewHistogramDataPoint()\n\tassert.Equal(t, pcommon.Timestamp(0), ms.StartTimestamp())\n\ttestValStartTimestamp := pcommon.Timestamp(1234567890)\n\tms.SetStartTimestamp(testValStartTimestamp)\n\tassert.Equal(t, testValStartTimestamp, ms.StartTimestamp())\n}\n\nfunc TestHistogramDataPoint_Timestamp(t *testing.T) {\n\tms := NewHistogramDataPoint()\n\tassert.Equal(t, pcommon.Timestamp(0), ms.Timestamp())\n\ttestValTimestamp := pcommon.Timestamp(1234567890)\n\tms.SetTimestamp(testValTimestamp)\n\tassert.Equal(t, testValTimestamp, ms.Timestamp())\n}\n\nfunc TestHistogramDataPoint_Count(t *testing.T) {\n\tms := NewHistogramDataPoint()\n\tassert.Equal(t, uint64(0), ms.Count())\n\tms.SetCount(uint64(13))\n\tassert.Equal(t, uint64(13), ms.Count())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newHistogramDataPoint(internal.NewHistogramDataPoint(), sharedState).SetCount(uint64(13)) })\n}\n\nfunc TestHistogramDataPoint_Sum(t *testing.T) {\n\tms := NewHistogramDataPoint()\n\tassert.InDelta(t, float64(0), ms.Sum(), 0.01)\n\tms.SetSum(float64(3.1415926))\n\tassert.True(t, ms.HasSum())\n\tassert.InDelta(t, float64(3.1415926), ms.Sum(), 0.01)\n\tms.RemoveSum()\n\tassert.False(t, ms.HasSum())\n\tdest := NewHistogramDataPoint()\n\tdest.SetSum(float64(3.1415926))\n\tms.CopyTo(dest)\n\tassert.False(t, dest.HasSum())\n}\n\nfunc TestHistogramDataPoint_BucketCounts(t *testing.T) {\n\tms := NewHistogramDataPoint()\n\tassert.Equal(t, pcommon.NewUInt64Slice(), ms.BucketCounts())\n\tms.orig.BucketCounts = internal.GenTestUint64Slice()\n\tassert.Equal(t, pcommon.UInt64Slice(internal.GenTestUInt64SliceWrapper()), ms.BucketCounts())\n}\n\nfunc TestHistogramDataPoint_ExplicitBounds(t *testing.T) {\n\tms := NewHistogramDataPoint()\n\tassert.Equal(t, pcommon.NewFloat64Slice(), ms.ExplicitBounds())\n\tms.orig.ExplicitBounds = internal.GenTestFloat64Slice()\n\tassert.Equal(t, pcommon.Float64Slice(internal.GenTestFloat64SliceWrapper()), ms.ExplicitBounds())\n}\n\nfunc TestHistogramDataPoint_Exemplars(t *testing.T) {\n\tms := NewHistogramDataPoint()\n\tassert.Equal(t, NewExemplarSlice(), ms.Exemplars())\n\tms.orig.Exemplars = internal.GenTestExemplarSlice()\n\tassert.Equal(t, generateTestExemplarSlice(), ms.Exemplars())\n}\n\nfunc TestHistogramDataPoint_Flags(t *testing.T) {\n\tms := NewHistogramDataPoint()\n\tassert.Equal(t, DataPointFlags(0), ms.Flags())\n\ttestValFlags := DataPointFlags(1)\n\tms.SetFlags(testValFlags)\n\tassert.Equal(t, testValFlags, ms.Flags())\n}\n\nfunc TestHistogramDataPoint_Min(t *testing.T) {\n\tms := NewHistogramDataPoint()\n\tassert.InDelta(t, float64(0), ms.Min(), 0.01)\n\tms.SetMin(float64(3.1415926))\n\tassert.True(t, ms.HasMin())\n\tassert.InDelta(t, float64(3.1415926), ms.Min(), 0.01)\n\tms.RemoveMin()\n\tassert.False(t, ms.HasMin())\n\tdest := NewHistogramDataPoint()\n\tdest.SetMin(float64(3.1415926))\n\tms.CopyTo(dest)\n\tassert.False(t, dest.HasMin())\n}\n\nfunc TestHistogramDataPoint_Max(t *testing.T) {\n\tms := NewHistogramDataPoint()\n\tassert.InDelta(t, float64(0), ms.Max(), 0.01)\n\tms.SetMax(float64(3.1415926))\n\tassert.True(t, ms.HasMax())\n\tassert.InDelta(t, float64(3.1415926), ms.Max(), 0.01)\n\tms.RemoveMax()\n\tassert.False(t, ms.HasMax())\n\tdest := NewHistogramDataPoint()\n\tdest.SetMax(float64(3.1415926))\n\tms.CopyTo(dest)\n\tassert.False(t, dest.HasMax())\n}\n\nfunc generateTestHistogramDataPoint() HistogramDataPoint {\n\treturn newHistogramDataPoint(internal.GenTestHistogramDataPoint(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_histogramdatapointslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// HistogramDataPointSlice logically represents a slice of HistogramDataPoint.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewHistogramDataPointSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype HistogramDataPointSlice struct {\n\torig  *[]*internal.HistogramDataPoint\n\tstate *internal.State\n}\n\nfunc newHistogramDataPointSlice(orig *[]*internal.HistogramDataPoint, state *internal.State) HistogramDataPointSlice {\n\treturn HistogramDataPointSlice{orig: orig, state: state}\n}\n\n// NewHistogramDataPointSlice creates a HistogramDataPointSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewHistogramDataPointSlice() HistogramDataPointSlice {\n\torig := []*internal.HistogramDataPoint(nil)\n\treturn newHistogramDataPointSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewHistogramDataPointSlice()\".\nfunc (es HistogramDataPointSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es HistogramDataPointSlice) At(i int) HistogramDataPoint {\n\treturn newHistogramDataPoint((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es HistogramDataPointSlice) All() iter.Seq2[int, HistogramDataPoint] {\n\treturn func(yield func(int, HistogramDataPoint) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new HistogramDataPointSlice can be initialized:\n//\n//\tes := NewHistogramDataPointSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es HistogramDataPointSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.HistogramDataPoint, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty HistogramDataPoint.\n// It returns the newly added HistogramDataPoint.\nfunc (es HistogramDataPointSlice) AppendEmpty() HistogramDataPoint {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewHistogramDataPoint())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es HistogramDataPointSlice) MoveAndAppendTo(dest HistogramDataPointSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es HistogramDataPointSlice) RemoveIf(f func(HistogramDataPoint) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteHistogramDataPoint((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es HistogramDataPointSlice) CopyTo(dest HistogramDataPointSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyHistogramDataPointPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the HistogramDataPoint elements within HistogramDataPointSlice given the\n// provided less function so that two instances of HistogramDataPointSlice\n// can be compared.\nfunc (es HistogramDataPointSlice) Sort(less func(a, b HistogramDataPoint) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_histogramdatapointslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestHistogramDataPointSlice(t *testing.T) {\n\tes := NewHistogramDataPointSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newHistogramDataPointSlice(&[]*internal.HistogramDataPoint{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewHistogramDataPoint()\n\ttestVal := generateTestHistogramDataPoint()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestHistogramDataPoint()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestHistogramDataPointSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newHistogramDataPointSlice(&[]*internal.HistogramDataPoint{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewHistogramDataPointSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestHistogramDataPointSlice_CopyTo(t *testing.T) {\n\tdest := NewHistogramDataPointSlice()\n\tsrc := generateTestHistogramDataPointSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestHistogramDataPointSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestHistogramDataPointSlice(), dest)\n}\n\nfunc TestHistogramDataPointSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestHistogramDataPointSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestHistogramDataPointSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestHistogramDataPointSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestHistogramDataPointSlice(), es)\n}\n\nfunc TestHistogramDataPointSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestHistogramDataPointSlice()\n\tdest := NewHistogramDataPointSlice()\n\tsrc := generateTestHistogramDataPointSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestHistogramDataPointSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestHistogramDataPointSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestHistogramDataPointSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestHistogramDataPointSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewHistogramDataPointSlice()\n\temptySlice.RemoveIf(func(el HistogramDataPoint) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestHistogramDataPointSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el HistogramDataPoint) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestHistogramDataPointSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestHistogramDataPointSlice()\n\tgot.RemoveIf(func(el HistogramDataPoint) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestHistogramDataPointSliceAll(t *testing.T) {\n\tms := generateTestHistogramDataPointSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestHistogramDataPointSlice_Sort(t *testing.T) {\n\tes := generateTestHistogramDataPointSlice()\n\tes.Sort(func(a, b HistogramDataPoint) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b HistogramDataPoint) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestHistogramDataPointSlice() HistogramDataPointSlice {\n\tms := NewHistogramDataPointSlice()\n\t*ms.orig = internal.GenTestHistogramDataPointPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_metric.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// Metric represents one metric as a collection of datapoints.\n// See Metric definition in OTLP: https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/metrics/v1/metrics.proto\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewMetric function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Metric struct {\n\torig  *internal.Metric\n\tstate *internal.State\n}\n\nfunc newMetric(orig *internal.Metric, state *internal.State) Metric {\n\treturn Metric{orig: orig, state: state}\n}\n\n// NewMetric creates a new empty Metric.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewMetric() Metric {\n\treturn newMetric(internal.NewMetric(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Metric) MoveTo(dest Metric) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteMetric(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Name returns the name associated with this Metric.\nfunc (ms Metric) Name() string {\n\treturn ms.orig.Name\n}\n\n// SetName replaces the name associated with this Metric.\nfunc (ms Metric) SetName(v string) {\n\tms.state.AssertMutable()\n\tms.orig.Name = v\n}\n\n// Description returns the description associated with this Metric.\nfunc (ms Metric) Description() string {\n\treturn ms.orig.Description\n}\n\n// SetDescription replaces the description associated with this Metric.\nfunc (ms Metric) SetDescription(v string) {\n\tms.state.AssertMutable()\n\tms.orig.Description = v\n}\n\n// Unit returns the unit associated with this Metric.\nfunc (ms Metric) Unit() string {\n\treturn ms.orig.Unit\n}\n\n// SetUnit replaces the unit associated with this Metric.\nfunc (ms Metric) SetUnit(v string) {\n\tms.state.AssertMutable()\n\tms.orig.Unit = v\n}\n\n// Type returns the type of the data for this Metric.\n// Calling this function on zero-initialized Metric will cause a panic.\nfunc (ms Metric) Type() MetricType {\n\tswitch ms.orig.Data.(type) {\n\tcase *internal.Metric_Gauge:\n\t\treturn MetricTypeGauge\n\tcase *internal.Metric_Sum:\n\t\treturn MetricTypeSum\n\tcase *internal.Metric_Histogram:\n\t\treturn MetricTypeHistogram\n\tcase *internal.Metric_ExponentialHistogram:\n\t\treturn MetricTypeExponentialHistogram\n\tcase *internal.Metric_Summary:\n\t\treturn MetricTypeSummary\n\t}\n\treturn MetricTypeEmpty\n}\n\n// Gauge returns the gauge associated with this Metric.\n//\n// Calling this function when Type() != MetricTypeGauge returns an invalid\n// zero-initialized instance of Gauge. Note that using such Gauge instance can cause panic.\n//\n// Calling this function on zero-initialized Metric will cause a panic.\nfunc (ms Metric) Gauge() Gauge {\n\tv, ok := ms.orig.GetData().(*internal.Metric_Gauge)\n\tif !ok {\n\t\treturn Gauge{}\n\t}\n\treturn newGauge(v.Gauge, ms.state)\n}\n\n// SetEmptyGauge sets an empty gauge to this Metric.\n//\n// After this, Type() function will return MetricTypeGauge\".\n//\n// Calling this function on zero-initialized Metric will cause a panic.\nfunc (ms Metric) SetEmptyGauge() Gauge {\n\tms.state.AssertMutable()\n\tvar ov *internal.Metric_Gauge\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\tov = &internal.Metric_Gauge{}\n\t} else {\n\t\tov = internal.ProtoPoolMetric_Gauge.Get().(*internal.Metric_Gauge)\n\t}\n\tov.Gauge = internal.NewGauge()\n\tms.orig.Data = ov\n\treturn newGauge(ov.Gauge, ms.state)\n} // Sum returns the sum associated with this Metric.\n// Calling this function when Type() != MetricTypeSum returns an invalid\n// zero-initialized instance of Sum. Note that using such Sum instance can cause panic.\n//\n// Calling this function on zero-initialized Metric will cause a panic.\nfunc (ms Metric) Sum() Sum {\n\tv, ok := ms.orig.GetData().(*internal.Metric_Sum)\n\tif !ok {\n\t\treturn Sum{}\n\t}\n\treturn newSum(v.Sum, ms.state)\n}\n\n// SetEmptySum sets an empty sum to this Metric.\n//\n// After this, Type() function will return MetricTypeSum\".\n//\n// Calling this function on zero-initialized Metric will cause a panic.\nfunc (ms Metric) SetEmptySum() Sum {\n\tms.state.AssertMutable()\n\tvar ov *internal.Metric_Sum\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\tov = &internal.Metric_Sum{}\n\t} else {\n\t\tov = internal.ProtoPoolMetric_Sum.Get().(*internal.Metric_Sum)\n\t}\n\tov.Sum = internal.NewSum()\n\tms.orig.Data = ov\n\treturn newSum(ov.Sum, ms.state)\n} // Histogram returns the histogram associated with this Metric.\n// Calling this function when Type() != MetricTypeHistogram returns an invalid\n// zero-initialized instance of Histogram. Note that using such Histogram instance can cause panic.\n//\n// Calling this function on zero-initialized Metric will cause a panic.\nfunc (ms Metric) Histogram() Histogram {\n\tv, ok := ms.orig.GetData().(*internal.Metric_Histogram)\n\tif !ok {\n\t\treturn Histogram{}\n\t}\n\treturn newHistogram(v.Histogram, ms.state)\n}\n\n// SetEmptyHistogram sets an empty histogram to this Metric.\n//\n// After this, Type() function will return MetricTypeHistogram\".\n//\n// Calling this function on zero-initialized Metric will cause a panic.\nfunc (ms Metric) SetEmptyHistogram() Histogram {\n\tms.state.AssertMutable()\n\tvar ov *internal.Metric_Histogram\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\tov = &internal.Metric_Histogram{}\n\t} else {\n\t\tov = internal.ProtoPoolMetric_Histogram.Get().(*internal.Metric_Histogram)\n\t}\n\tov.Histogram = internal.NewHistogram()\n\tms.orig.Data = ov\n\treturn newHistogram(ov.Histogram, ms.state)\n} // ExponentialHistogram returns the exponentialhistogram associated with this Metric.\n// Calling this function when Type() != MetricTypeExponentialHistogram returns an invalid\n// zero-initialized instance of ExponentialHistogram. Note that using such ExponentialHistogram instance can cause panic.\n//\n// Calling this function on zero-initialized Metric will cause a panic.\nfunc (ms Metric) ExponentialHistogram() ExponentialHistogram {\n\tv, ok := ms.orig.GetData().(*internal.Metric_ExponentialHistogram)\n\tif !ok {\n\t\treturn ExponentialHistogram{}\n\t}\n\treturn newExponentialHistogram(v.ExponentialHistogram, ms.state)\n}\n\n// SetEmptyExponentialHistogram sets an empty exponentialhistogram to this Metric.\n//\n// After this, Type() function will return MetricTypeExponentialHistogram\".\n//\n// Calling this function on zero-initialized Metric will cause a panic.\nfunc (ms Metric) SetEmptyExponentialHistogram() ExponentialHistogram {\n\tms.state.AssertMutable()\n\tvar ov *internal.Metric_ExponentialHistogram\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\tov = &internal.Metric_ExponentialHistogram{}\n\t} else {\n\t\tov = internal.ProtoPoolMetric_ExponentialHistogram.Get().(*internal.Metric_ExponentialHistogram)\n\t}\n\tov.ExponentialHistogram = internal.NewExponentialHistogram()\n\tms.orig.Data = ov\n\treturn newExponentialHistogram(ov.ExponentialHistogram, ms.state)\n} // Summary returns the summary associated with this Metric.\n// Calling this function when Type() != MetricTypeSummary returns an invalid\n// zero-initialized instance of Summary. Note that using such Summary instance can cause panic.\n//\n// Calling this function on zero-initialized Metric will cause a panic.\nfunc (ms Metric) Summary() Summary {\n\tv, ok := ms.orig.GetData().(*internal.Metric_Summary)\n\tif !ok {\n\t\treturn Summary{}\n\t}\n\treturn newSummary(v.Summary, ms.state)\n}\n\n// SetEmptySummary sets an empty summary to this Metric.\n//\n// After this, Type() function will return MetricTypeSummary\".\n//\n// Calling this function on zero-initialized Metric will cause a panic.\nfunc (ms Metric) SetEmptySummary() Summary {\n\tms.state.AssertMutable()\n\tvar ov *internal.Metric_Summary\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\tov = &internal.Metric_Summary{}\n\t} else {\n\t\tov = internal.ProtoPoolMetric_Summary.Get().(*internal.Metric_Summary)\n\t}\n\tov.Summary = internal.NewSummary()\n\tms.orig.Data = ov\n\treturn newSummary(ov.Summary, ms.state)\n}\n\n// Metadata returns the Metadata associated with this Metric.\nfunc (ms Metric) Metadata() pcommon.Map {\n\treturn pcommon.Map(internal.NewMapWrapper(&ms.orig.Metadata, ms.state))\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Metric) CopyTo(dest Metric) {\n\tdest.state.AssertMutable()\n\tinternal.CopyMetric(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_metric_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestMetric_MoveTo(t *testing.T) {\n\tms := generateTestMetric()\n\tdest := NewMetric()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewMetric(), ms)\n\tassert.Equal(t, generateTestMetric(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestMetric(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newMetric(internal.NewMetric(), sharedState)) })\n\tassert.Panics(t, func() { newMetric(internal.NewMetric(), sharedState).MoveTo(dest) })\n}\n\nfunc TestMetric_CopyTo(t *testing.T) {\n\tms := NewMetric()\n\torig := NewMetric()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestMetric()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newMetric(internal.NewMetric(), sharedState)) })\n}\n\nfunc TestMetric_Name(t *testing.T) {\n\tms := NewMetric()\n\tassert.Empty(t, ms.Name())\n\tms.SetName(\"test_name\")\n\tassert.Equal(t, \"test_name\", ms.Name())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newMetric(internal.NewMetric(), sharedState).SetName(\"test_name\") })\n}\n\nfunc TestMetric_Description(t *testing.T) {\n\tms := NewMetric()\n\tassert.Empty(t, ms.Description())\n\tms.SetDescription(\"test_description\")\n\tassert.Equal(t, \"test_description\", ms.Description())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newMetric(internal.NewMetric(), sharedState).SetDescription(\"test_description\") })\n}\n\nfunc TestMetric_Unit(t *testing.T) {\n\tms := NewMetric()\n\tassert.Empty(t, ms.Unit())\n\tms.SetUnit(\"test_unit\")\n\tassert.Equal(t, \"test_unit\", ms.Unit())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newMetric(internal.NewMetric(), sharedState).SetUnit(\"test_unit\") })\n}\n\nfunc TestMetric_Type(t *testing.T) {\n\ttv := NewMetric()\n\tassert.Equal(t, MetricTypeEmpty, tv.Type())\n}\n\nfunc TestMetric_Gauge(t *testing.T) {\n\tms := NewMetric()\n\tms.SetEmptyGauge()\n\tassert.Equal(t, NewGauge(), ms.Gauge())\n\tms.orig.GetData().(*internal.Metric_Gauge).Gauge = internal.GenTestGauge()\n\tassert.Equal(t, MetricTypeGauge, ms.Type())\n\tassert.Equal(t, generateTestGauge(), ms.Gauge())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newMetric(internal.NewMetric(), sharedState).SetEmptyGauge() })\n}\nfunc TestMetric_Sum(t *testing.T) {\n\tms := NewMetric()\n\tms.SetEmptySum()\n\tassert.Equal(t, NewSum(), ms.Sum())\n\tms.orig.GetData().(*internal.Metric_Sum).Sum = internal.GenTestSum()\n\tassert.Equal(t, MetricTypeSum, ms.Type())\n\tassert.Equal(t, generateTestSum(), ms.Sum())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newMetric(internal.NewMetric(), sharedState).SetEmptySum() })\n}\nfunc TestMetric_Histogram(t *testing.T) {\n\tms := NewMetric()\n\tms.SetEmptyHistogram()\n\tassert.Equal(t, NewHistogram(), ms.Histogram())\n\tms.orig.GetData().(*internal.Metric_Histogram).Histogram = internal.GenTestHistogram()\n\tassert.Equal(t, MetricTypeHistogram, ms.Type())\n\tassert.Equal(t, generateTestHistogram(), ms.Histogram())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newMetric(internal.NewMetric(), sharedState).SetEmptyHistogram() })\n}\nfunc TestMetric_ExponentialHistogram(t *testing.T) {\n\tms := NewMetric()\n\tms.SetEmptyExponentialHistogram()\n\tassert.Equal(t, NewExponentialHistogram(), ms.ExponentialHistogram())\n\tms.orig.GetData().(*internal.Metric_ExponentialHistogram).ExponentialHistogram = internal.GenTestExponentialHistogram()\n\tassert.Equal(t, MetricTypeExponentialHistogram, ms.Type())\n\tassert.Equal(t, generateTestExponentialHistogram(), ms.ExponentialHistogram())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newMetric(internal.NewMetric(), sharedState).SetEmptyExponentialHistogram() })\n}\nfunc TestMetric_Summary(t *testing.T) {\n\tms := NewMetric()\n\tms.SetEmptySummary()\n\tassert.Equal(t, NewSummary(), ms.Summary())\n\tms.orig.GetData().(*internal.Metric_Summary).Summary = internal.GenTestSummary()\n\tassert.Equal(t, MetricTypeSummary, ms.Type())\n\tassert.Equal(t, generateTestSummary(), ms.Summary())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newMetric(internal.NewMetric(), sharedState).SetEmptySummary() })\n}\n\nfunc TestMetric_Metadata(t *testing.T) {\n\tms := NewMetric()\n\tassert.Equal(t, pcommon.NewMap(), ms.Metadata())\n\tms.orig.Metadata = internal.GenTestKeyValueSlice()\n\tassert.Equal(t, pcommon.Map(internal.GenTestMapWrapper()), ms.Metadata())\n}\n\nfunc generateTestMetric() Metric {\n\treturn newMetric(internal.GenTestMetric(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// Metrics is the top-level struct that is propagated through the metrics pipeline.\n// Use NewMetrics to create new instance, zero-initialized instance is not valid for use.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewMetrics function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Metrics internal.MetricsWrapper\n\nfunc newMetrics(orig *internal.ExportMetricsServiceRequest, state *internal.State) Metrics {\n\treturn Metrics(internal.NewMetricsWrapper(orig, state))\n}\n\n// NewMetrics creates a new empty Metrics.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewMetrics() Metrics {\n\treturn newMetrics(internal.NewExportMetricsServiceRequest(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Metrics) MoveTo(dest Metrics) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\tinternal.DeleteExportMetricsServiceRequest(dest.getOrig(), false)\n\t*dest.getOrig(), *ms.getOrig() = *ms.getOrig(), *dest.getOrig()\n}\n\n// ResourceMetrics returns the ResourceMetrics associated with this Metrics.\nfunc (ms Metrics) ResourceMetrics() ResourceMetricsSlice {\n\treturn newResourceMetricsSlice(&ms.getOrig().ResourceMetrics, ms.getState())\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Metrics) CopyTo(dest Metrics) {\n\tdest.getState().AssertMutable()\n\tinternal.CopyExportMetricsServiceRequest(dest.getOrig(), ms.getOrig())\n}\n\nfunc (ms Metrics) getOrig() *internal.ExportMetricsServiceRequest {\n\treturn internal.GetMetricsOrig(internal.MetricsWrapper(ms))\n}\n\nfunc (ms Metrics) getState() *internal.State {\n\treturn internal.GetMetricsState(internal.MetricsWrapper(ms))\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_metrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestMetrics_MoveTo(t *testing.T) {\n\tms := generateTestMetrics()\n\tdest := NewMetrics()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewMetrics(), ms)\n\tassert.Equal(t, generateTestMetrics(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestMetrics(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newMetrics(internal.NewExportMetricsServiceRequest(), sharedState)) })\n\tassert.Panics(t, func() { newMetrics(internal.NewExportMetricsServiceRequest(), sharedState).MoveTo(dest) })\n}\n\nfunc TestMetrics_CopyTo(t *testing.T) {\n\tms := NewMetrics()\n\torig := NewMetrics()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestMetrics()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newMetrics(internal.NewExportMetricsServiceRequest(), sharedState)) })\n}\n\nfunc TestMetrics_ResourceMetrics(t *testing.T) {\n\tms := NewMetrics()\n\tassert.Equal(t, NewResourceMetricsSlice(), ms.ResourceMetrics())\n\tms.getOrig().ResourceMetrics = internal.GenTestResourceMetricsPtrSlice()\n\tassert.Equal(t, generateTestResourceMetricsSlice(), ms.ResourceMetrics())\n}\n\nfunc generateTestMetrics() Metrics {\n\treturn newMetrics(internal.GenTestExportMetricsServiceRequest(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_metricslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// MetricSlice logically represents a slice of Metric.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewMetricSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype MetricSlice struct {\n\torig  *[]*internal.Metric\n\tstate *internal.State\n}\n\nfunc newMetricSlice(orig *[]*internal.Metric, state *internal.State) MetricSlice {\n\treturn MetricSlice{orig: orig, state: state}\n}\n\n// NewMetricSlice creates a MetricSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewMetricSlice() MetricSlice {\n\torig := []*internal.Metric(nil)\n\treturn newMetricSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewMetricSlice()\".\nfunc (es MetricSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es MetricSlice) At(i int) Metric {\n\treturn newMetric((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es MetricSlice) All() iter.Seq2[int, Metric] {\n\treturn func(yield func(int, Metric) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new MetricSlice can be initialized:\n//\n//\tes := NewMetricSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es MetricSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.Metric, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty Metric.\n// It returns the newly added Metric.\nfunc (es MetricSlice) AppendEmpty() Metric {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewMetric())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es MetricSlice) MoveAndAppendTo(dest MetricSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es MetricSlice) RemoveIf(f func(Metric) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteMetric((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es MetricSlice) CopyTo(dest MetricSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyMetricPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the Metric elements within MetricSlice given the\n// provided less function so that two instances of MetricSlice\n// can be compared.\nfunc (es MetricSlice) Sort(less func(a, b Metric) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_metricslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestMetricSlice(t *testing.T) {\n\tes := NewMetricSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newMetricSlice(&[]*internal.Metric{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewMetric()\n\ttestVal := generateTestMetric()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestMetric()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestMetricSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newMetricSlice(&[]*internal.Metric{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewMetricSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestMetricSlice_CopyTo(t *testing.T) {\n\tdest := NewMetricSlice()\n\tsrc := generateTestMetricSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestMetricSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestMetricSlice(), dest)\n}\n\nfunc TestMetricSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestMetricSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestMetricSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestMetricSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestMetricSlice(), es)\n}\n\nfunc TestMetricSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestMetricSlice()\n\tdest := NewMetricSlice()\n\tsrc := generateTestMetricSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestMetricSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestMetricSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestMetricSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestMetricSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewMetricSlice()\n\temptySlice.RemoveIf(func(el Metric) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestMetricSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el Metric) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestMetricSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestMetricSlice()\n\tgot.RemoveIf(func(el Metric) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestMetricSliceAll(t *testing.T) {\n\tms := generateTestMetricSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestMetricSlice_Sort(t *testing.T) {\n\tes := generateTestMetricSlice()\n\tes.Sort(func(a, b Metric) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b Metric) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestMetricSlice() MetricSlice {\n\tms := NewMetricSlice()\n\t*ms.orig = internal.GenTestMetricPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_numberdatapoint.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// NumberDataPoint is a single data point in a timeseries that describes the time-varying value of a number metric.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewNumberDataPoint function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype NumberDataPoint struct {\n\torig  *internal.NumberDataPoint\n\tstate *internal.State\n}\n\nfunc newNumberDataPoint(orig *internal.NumberDataPoint, state *internal.State) NumberDataPoint {\n\treturn NumberDataPoint{orig: orig, state: state}\n}\n\n// NewNumberDataPoint creates a new empty NumberDataPoint.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewNumberDataPoint() NumberDataPoint {\n\treturn newNumberDataPoint(internal.NewNumberDataPoint(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms NumberDataPoint) MoveTo(dest NumberDataPoint) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteNumberDataPoint(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Attributes returns the Attributes associated with this NumberDataPoint.\nfunc (ms NumberDataPoint) Attributes() pcommon.Map {\n\treturn pcommon.Map(internal.NewMapWrapper(&ms.orig.Attributes, ms.state))\n}\n\n// StartTimestamp returns the starttimestamp associated with this NumberDataPoint.\nfunc (ms NumberDataPoint) StartTimestamp() pcommon.Timestamp {\n\treturn pcommon.Timestamp(ms.orig.StartTimeUnixNano)\n}\n\n// SetStartTimestamp replaces the starttimestamp associated with this NumberDataPoint.\nfunc (ms NumberDataPoint) SetStartTimestamp(v pcommon.Timestamp) {\n\tms.state.AssertMutable()\n\tms.orig.StartTimeUnixNano = uint64(v)\n}\n\n// Timestamp returns the timestamp associated with this NumberDataPoint.\nfunc (ms NumberDataPoint) Timestamp() pcommon.Timestamp {\n\treturn pcommon.Timestamp(ms.orig.TimeUnixNano)\n}\n\n// SetTimestamp replaces the timestamp associated with this NumberDataPoint.\nfunc (ms NumberDataPoint) SetTimestamp(v pcommon.Timestamp) {\n\tms.state.AssertMutable()\n\tms.orig.TimeUnixNano = uint64(v)\n}\n\n// ValueType returns the type of the value for this NumberDataPoint.\n// Calling this function on zero-initialized NumberDataPoint will cause a panic.\nfunc (ms NumberDataPoint) ValueType() NumberDataPointValueType {\n\tswitch ms.orig.Value.(type) {\n\tcase *internal.NumberDataPoint_AsDouble:\n\t\treturn NumberDataPointValueTypeDouble\n\tcase *internal.NumberDataPoint_AsInt:\n\t\treturn NumberDataPointValueTypeInt\n\t}\n\treturn NumberDataPointValueTypeEmpty\n}\n\n// DoubleValue returns the double associated with this NumberDataPoint.\nfunc (ms NumberDataPoint) DoubleValue() float64 {\n\treturn ms.orig.GetAsDouble()\n}\n\n// SetDoubleValue replaces the double associated with this NumberDataPoint.\nfunc (ms NumberDataPoint) SetDoubleValue(v float64) {\n\tms.state.AssertMutable()\n\tvar ov *internal.NumberDataPoint_AsDouble\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\tov = &internal.NumberDataPoint_AsDouble{}\n\t} else {\n\t\tov = internal.ProtoPoolNumberDataPoint_AsDouble.Get().(*internal.NumberDataPoint_AsDouble)\n\t}\n\tov.AsDouble = v\n\tms.orig.Value = ov\n} // IntValue returns the int associated with this NumberDataPoint.\nfunc (ms NumberDataPoint) IntValue() int64 {\n\treturn ms.orig.GetAsInt()\n}\n\n// SetIntValue replaces the int associated with this NumberDataPoint.\nfunc (ms NumberDataPoint) SetIntValue(v int64) {\n\tms.state.AssertMutable()\n\tvar ov *internal.NumberDataPoint_AsInt\n\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\tov = &internal.NumberDataPoint_AsInt{}\n\t} else {\n\t\tov = internal.ProtoPoolNumberDataPoint_AsInt.Get().(*internal.NumberDataPoint_AsInt)\n\t}\n\tov.AsInt = v\n\tms.orig.Value = ov\n}\n\n// Exemplars returns the Exemplars associated with this NumberDataPoint.\nfunc (ms NumberDataPoint) Exemplars() ExemplarSlice {\n\treturn newExemplarSlice(&ms.orig.Exemplars, ms.state)\n}\n\n// Flags returns the flags associated with this NumberDataPoint.\nfunc (ms NumberDataPoint) Flags() DataPointFlags {\n\treturn DataPointFlags(ms.orig.Flags)\n}\n\n// SetFlags replaces the flags associated with this NumberDataPoint.\nfunc (ms NumberDataPoint) SetFlags(v DataPointFlags) {\n\tms.state.AssertMutable()\n\tms.orig.Flags = uint32(v)\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms NumberDataPoint) CopyTo(dest NumberDataPoint) {\n\tdest.state.AssertMutable()\n\tinternal.CopyNumberDataPoint(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_numberdatapoint_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestNumberDataPoint_MoveTo(t *testing.T) {\n\tms := generateTestNumberDataPoint()\n\tdest := NewNumberDataPoint()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewNumberDataPoint(), ms)\n\tassert.Equal(t, generateTestNumberDataPoint(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestNumberDataPoint(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newNumberDataPoint(internal.NewNumberDataPoint(), sharedState)) })\n\tassert.Panics(t, func() { newNumberDataPoint(internal.NewNumberDataPoint(), sharedState).MoveTo(dest) })\n}\n\nfunc TestNumberDataPoint_CopyTo(t *testing.T) {\n\tms := NewNumberDataPoint()\n\torig := NewNumberDataPoint()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestNumberDataPoint()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newNumberDataPoint(internal.NewNumberDataPoint(), sharedState)) })\n}\n\nfunc TestNumberDataPoint_Attributes(t *testing.T) {\n\tms := NewNumberDataPoint()\n\tassert.Equal(t, pcommon.NewMap(), ms.Attributes())\n\tms.orig.Attributes = internal.GenTestKeyValueSlice()\n\tassert.Equal(t, pcommon.Map(internal.GenTestMapWrapper()), ms.Attributes())\n}\n\nfunc TestNumberDataPoint_StartTimestamp(t *testing.T) {\n\tms := NewNumberDataPoint()\n\tassert.Equal(t, pcommon.Timestamp(0), ms.StartTimestamp())\n\ttestValStartTimestamp := pcommon.Timestamp(1234567890)\n\tms.SetStartTimestamp(testValStartTimestamp)\n\tassert.Equal(t, testValStartTimestamp, ms.StartTimestamp())\n}\n\nfunc TestNumberDataPoint_Timestamp(t *testing.T) {\n\tms := NewNumberDataPoint()\n\tassert.Equal(t, pcommon.Timestamp(0), ms.Timestamp())\n\ttestValTimestamp := pcommon.Timestamp(1234567890)\n\tms.SetTimestamp(testValTimestamp)\n\tassert.Equal(t, testValTimestamp, ms.Timestamp())\n}\n\nfunc TestNumberDataPoint_ValueType(t *testing.T) {\n\ttv := NewNumberDataPoint()\n\tassert.Equal(t, NumberDataPointValueTypeEmpty, tv.ValueType())\n}\n\nfunc TestNumberDataPoint_DoubleValue(t *testing.T) {\n\tms := NewNumberDataPoint()\n\tassert.InDelta(t, float64(0), ms.DoubleValue(), 0.01)\n\tms.SetDoubleValue(float64(3.1415926))\n\tassert.InDelta(t, float64(3.1415926), ms.DoubleValue(), 0.01)\n\tassert.Equal(t, NumberDataPointValueTypeDouble, ms.ValueType())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewNumberDataPoint(internal.NewNumberDataPoint(), sharedState).SetDoubleValue(float64(3.1415926))\n\t})\n}\nfunc TestNumberDataPoint_IntValue(t *testing.T) {\n\tms := NewNumberDataPoint()\n\tassert.Equal(t, int64(0), ms.IntValue())\n\tms.SetIntValue(int64(13))\n\tassert.Equal(t, int64(13), ms.IntValue())\n\tassert.Equal(t, NumberDataPointValueTypeInt, ms.ValueType())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newNumberDataPoint(internal.NewNumberDataPoint(), sharedState).SetIntValue(int64(13)) })\n}\n\nfunc TestNumberDataPoint_Exemplars(t *testing.T) {\n\tms := NewNumberDataPoint()\n\tassert.Equal(t, NewExemplarSlice(), ms.Exemplars())\n\tms.orig.Exemplars = internal.GenTestExemplarSlice()\n\tassert.Equal(t, generateTestExemplarSlice(), ms.Exemplars())\n}\n\nfunc TestNumberDataPoint_Flags(t *testing.T) {\n\tms := NewNumberDataPoint()\n\tassert.Equal(t, DataPointFlags(0), ms.Flags())\n\ttestValFlags := DataPointFlags(1)\n\tms.SetFlags(testValFlags)\n\tassert.Equal(t, testValFlags, ms.Flags())\n}\n\nfunc generateTestNumberDataPoint() NumberDataPoint {\n\treturn newNumberDataPoint(internal.GenTestNumberDataPoint(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_numberdatapointslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// NumberDataPointSlice logically represents a slice of NumberDataPoint.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewNumberDataPointSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype NumberDataPointSlice struct {\n\torig  *[]*internal.NumberDataPoint\n\tstate *internal.State\n}\n\nfunc newNumberDataPointSlice(orig *[]*internal.NumberDataPoint, state *internal.State) NumberDataPointSlice {\n\treturn NumberDataPointSlice{orig: orig, state: state}\n}\n\n// NewNumberDataPointSlice creates a NumberDataPointSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewNumberDataPointSlice() NumberDataPointSlice {\n\torig := []*internal.NumberDataPoint(nil)\n\treturn newNumberDataPointSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewNumberDataPointSlice()\".\nfunc (es NumberDataPointSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es NumberDataPointSlice) At(i int) NumberDataPoint {\n\treturn newNumberDataPoint((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es NumberDataPointSlice) All() iter.Seq2[int, NumberDataPoint] {\n\treturn func(yield func(int, NumberDataPoint) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new NumberDataPointSlice can be initialized:\n//\n//\tes := NewNumberDataPointSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es NumberDataPointSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.NumberDataPoint, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty NumberDataPoint.\n// It returns the newly added NumberDataPoint.\nfunc (es NumberDataPointSlice) AppendEmpty() NumberDataPoint {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewNumberDataPoint())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es NumberDataPointSlice) MoveAndAppendTo(dest NumberDataPointSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es NumberDataPointSlice) RemoveIf(f func(NumberDataPoint) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteNumberDataPoint((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es NumberDataPointSlice) CopyTo(dest NumberDataPointSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyNumberDataPointPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the NumberDataPoint elements within NumberDataPointSlice given the\n// provided less function so that two instances of NumberDataPointSlice\n// can be compared.\nfunc (es NumberDataPointSlice) Sort(less func(a, b NumberDataPoint) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_numberdatapointslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestNumberDataPointSlice(t *testing.T) {\n\tes := NewNumberDataPointSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newNumberDataPointSlice(&[]*internal.NumberDataPoint{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewNumberDataPoint()\n\ttestVal := generateTestNumberDataPoint()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestNumberDataPoint()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestNumberDataPointSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newNumberDataPointSlice(&[]*internal.NumberDataPoint{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewNumberDataPointSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestNumberDataPointSlice_CopyTo(t *testing.T) {\n\tdest := NewNumberDataPointSlice()\n\tsrc := generateTestNumberDataPointSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestNumberDataPointSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestNumberDataPointSlice(), dest)\n}\n\nfunc TestNumberDataPointSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestNumberDataPointSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestNumberDataPointSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestNumberDataPointSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestNumberDataPointSlice(), es)\n}\n\nfunc TestNumberDataPointSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestNumberDataPointSlice()\n\tdest := NewNumberDataPointSlice()\n\tsrc := generateTestNumberDataPointSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestNumberDataPointSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestNumberDataPointSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestNumberDataPointSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestNumberDataPointSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewNumberDataPointSlice()\n\temptySlice.RemoveIf(func(el NumberDataPoint) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestNumberDataPointSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el NumberDataPoint) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestNumberDataPointSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestNumberDataPointSlice()\n\tgot.RemoveIf(func(el NumberDataPoint) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestNumberDataPointSliceAll(t *testing.T) {\n\tms := generateTestNumberDataPointSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestNumberDataPointSlice_Sort(t *testing.T) {\n\tes := generateTestNumberDataPointSlice()\n\tes.Sort(func(a, b NumberDataPoint) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b NumberDataPoint) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestNumberDataPointSlice() NumberDataPointSlice {\n\tms := NewNumberDataPointSlice()\n\t*ms.orig = internal.GenTestNumberDataPointPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_resourcemetrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ResourceMetrics is a collection of metrics from a Resource.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewResourceMetrics function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ResourceMetrics struct {\n\torig  *internal.ResourceMetrics\n\tstate *internal.State\n}\n\nfunc newResourceMetrics(orig *internal.ResourceMetrics, state *internal.State) ResourceMetrics {\n\treturn ResourceMetrics{orig: orig, state: state}\n}\n\n// NewResourceMetrics creates a new empty ResourceMetrics.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewResourceMetrics() ResourceMetrics {\n\treturn newResourceMetrics(internal.NewResourceMetrics(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ResourceMetrics) MoveTo(dest ResourceMetrics) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteResourceMetrics(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Resource returns the resource associated with this ResourceMetrics.\nfunc (ms ResourceMetrics) Resource() pcommon.Resource {\n\treturn pcommon.Resource(internal.NewResourceWrapper(&ms.orig.Resource, ms.state))\n}\n\n// ScopeMetrics returns the ScopeMetrics associated with this ResourceMetrics.\nfunc (ms ResourceMetrics) ScopeMetrics() ScopeMetricsSlice {\n\treturn newScopeMetricsSlice(&ms.orig.ScopeMetrics, ms.state)\n}\n\n// SchemaUrl returns the schemaurl associated with this ResourceMetrics.\nfunc (ms ResourceMetrics) SchemaUrl() string {\n\treturn ms.orig.SchemaUrl\n}\n\n// SetSchemaUrl replaces the schemaurl associated with this ResourceMetrics.\nfunc (ms ResourceMetrics) SetSchemaUrl(v string) {\n\tms.state.AssertMutable()\n\tms.orig.SchemaUrl = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ResourceMetrics) CopyTo(dest ResourceMetrics) {\n\tdest.state.AssertMutable()\n\tinternal.CopyResourceMetrics(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_resourcemetrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestResourceMetrics_MoveTo(t *testing.T) {\n\tms := generateTestResourceMetrics()\n\tdest := NewResourceMetrics()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewResourceMetrics(), ms)\n\tassert.Equal(t, generateTestResourceMetrics(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestResourceMetrics(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newResourceMetrics(internal.NewResourceMetrics(), sharedState)) })\n\tassert.Panics(t, func() { newResourceMetrics(internal.NewResourceMetrics(), sharedState).MoveTo(dest) })\n}\n\nfunc TestResourceMetrics_CopyTo(t *testing.T) {\n\tms := NewResourceMetrics()\n\torig := NewResourceMetrics()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestResourceMetrics()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newResourceMetrics(internal.NewResourceMetrics(), sharedState)) })\n}\n\nfunc TestResourceMetrics_Resource(t *testing.T) {\n\tms := NewResourceMetrics()\n\tassert.Equal(t, pcommon.NewResource(), ms.Resource())\n\tms.orig.Resource = *internal.GenTestResource()\n\tassert.Equal(t, pcommon.Resource(internal.GenTestResourceWrapper()), ms.Resource())\n}\n\nfunc TestResourceMetrics_ScopeMetrics(t *testing.T) {\n\tms := NewResourceMetrics()\n\tassert.Equal(t, NewScopeMetricsSlice(), ms.ScopeMetrics())\n\tms.orig.ScopeMetrics = internal.GenTestScopeMetricsPtrSlice()\n\tassert.Equal(t, generateTestScopeMetricsSlice(), ms.ScopeMetrics())\n}\n\nfunc TestResourceMetrics_SchemaUrl(t *testing.T) {\n\tms := NewResourceMetrics()\n\tassert.Empty(t, ms.SchemaUrl())\n\tms.SetSchemaUrl(\"test_schemaurl\")\n\tassert.Equal(t, \"test_schemaurl\", ms.SchemaUrl())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newResourceMetrics(internal.NewResourceMetrics(), sharedState).SetSchemaUrl(\"test_schemaurl\") })\n}\n\nfunc generateTestResourceMetrics() ResourceMetrics {\n\treturn newResourceMetrics(internal.GenTestResourceMetrics(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_resourcemetricsslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ResourceMetricsSlice logically represents a slice of ResourceMetrics.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewResourceMetricsSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ResourceMetricsSlice struct {\n\torig  *[]*internal.ResourceMetrics\n\tstate *internal.State\n}\n\nfunc newResourceMetricsSlice(orig *[]*internal.ResourceMetrics, state *internal.State) ResourceMetricsSlice {\n\treturn ResourceMetricsSlice{orig: orig, state: state}\n}\n\n// NewResourceMetricsSlice creates a ResourceMetricsSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewResourceMetricsSlice() ResourceMetricsSlice {\n\torig := []*internal.ResourceMetrics(nil)\n\treturn newResourceMetricsSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewResourceMetricsSlice()\".\nfunc (es ResourceMetricsSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es ResourceMetricsSlice) At(i int) ResourceMetrics {\n\treturn newResourceMetrics((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es ResourceMetricsSlice) All() iter.Seq2[int, ResourceMetrics] {\n\treturn func(yield func(int, ResourceMetrics) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new ResourceMetricsSlice can be initialized:\n//\n//\tes := NewResourceMetricsSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es ResourceMetricsSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.ResourceMetrics, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty ResourceMetrics.\n// It returns the newly added ResourceMetrics.\nfunc (es ResourceMetricsSlice) AppendEmpty() ResourceMetrics {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewResourceMetrics())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es ResourceMetricsSlice) MoveAndAppendTo(dest ResourceMetricsSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es ResourceMetricsSlice) RemoveIf(f func(ResourceMetrics) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteResourceMetrics((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es ResourceMetricsSlice) CopyTo(dest ResourceMetricsSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyResourceMetricsPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the ResourceMetrics elements within ResourceMetricsSlice given the\n// provided less function so that two instances of ResourceMetricsSlice\n// can be compared.\nfunc (es ResourceMetricsSlice) Sort(less func(a, b ResourceMetrics) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_resourcemetricsslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestResourceMetricsSlice(t *testing.T) {\n\tes := NewResourceMetricsSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newResourceMetricsSlice(&[]*internal.ResourceMetrics{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewResourceMetrics()\n\ttestVal := generateTestResourceMetrics()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestResourceMetrics()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestResourceMetricsSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newResourceMetricsSlice(&[]*internal.ResourceMetrics{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewResourceMetricsSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestResourceMetricsSlice_CopyTo(t *testing.T) {\n\tdest := NewResourceMetricsSlice()\n\tsrc := generateTestResourceMetricsSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestResourceMetricsSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestResourceMetricsSlice(), dest)\n}\n\nfunc TestResourceMetricsSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestResourceMetricsSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestResourceMetricsSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestResourceMetricsSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestResourceMetricsSlice(), es)\n}\n\nfunc TestResourceMetricsSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestResourceMetricsSlice()\n\tdest := NewResourceMetricsSlice()\n\tsrc := generateTestResourceMetricsSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestResourceMetricsSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestResourceMetricsSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestResourceMetricsSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestResourceMetricsSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewResourceMetricsSlice()\n\temptySlice.RemoveIf(func(el ResourceMetrics) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestResourceMetricsSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el ResourceMetrics) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestResourceMetricsSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestResourceMetricsSlice()\n\tgot.RemoveIf(func(el ResourceMetrics) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestResourceMetricsSliceAll(t *testing.T) {\n\tms := generateTestResourceMetricsSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestResourceMetricsSlice_Sort(t *testing.T) {\n\tes := generateTestResourceMetricsSlice()\n\tes.Sort(func(a, b ResourceMetrics) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b ResourceMetrics) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestResourceMetricsSlice() ResourceMetricsSlice {\n\tms := NewResourceMetricsSlice()\n\t*ms.orig = internal.GenTestResourceMetricsPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_scopemetrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ScopeMetrics is a collection of metrics from a LibraryInstrumentation.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewScopeMetrics function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ScopeMetrics struct {\n\torig  *internal.ScopeMetrics\n\tstate *internal.State\n}\n\nfunc newScopeMetrics(orig *internal.ScopeMetrics, state *internal.State) ScopeMetrics {\n\treturn ScopeMetrics{orig: orig, state: state}\n}\n\n// NewScopeMetrics creates a new empty ScopeMetrics.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewScopeMetrics() ScopeMetrics {\n\treturn newScopeMetrics(internal.NewScopeMetrics(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ScopeMetrics) MoveTo(dest ScopeMetrics) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteScopeMetrics(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Scope returns the scope associated with this ScopeMetrics.\nfunc (ms ScopeMetrics) Scope() pcommon.InstrumentationScope {\n\treturn pcommon.InstrumentationScope(internal.NewInstrumentationScopeWrapper(&ms.orig.Scope, ms.state))\n}\n\n// Metrics returns the Metrics associated with this ScopeMetrics.\nfunc (ms ScopeMetrics) Metrics() MetricSlice {\n\treturn newMetricSlice(&ms.orig.Metrics, ms.state)\n}\n\n// SchemaUrl returns the schemaurl associated with this ScopeMetrics.\nfunc (ms ScopeMetrics) SchemaUrl() string {\n\treturn ms.orig.SchemaUrl\n}\n\n// SetSchemaUrl replaces the schemaurl associated with this ScopeMetrics.\nfunc (ms ScopeMetrics) SetSchemaUrl(v string) {\n\tms.state.AssertMutable()\n\tms.orig.SchemaUrl = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ScopeMetrics) CopyTo(dest ScopeMetrics) {\n\tdest.state.AssertMutable()\n\tinternal.CopyScopeMetrics(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_scopemetrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestScopeMetrics_MoveTo(t *testing.T) {\n\tms := generateTestScopeMetrics()\n\tdest := NewScopeMetrics()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewScopeMetrics(), ms)\n\tassert.Equal(t, generateTestScopeMetrics(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestScopeMetrics(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newScopeMetrics(internal.NewScopeMetrics(), sharedState)) })\n\tassert.Panics(t, func() { newScopeMetrics(internal.NewScopeMetrics(), sharedState).MoveTo(dest) })\n}\n\nfunc TestScopeMetrics_CopyTo(t *testing.T) {\n\tms := NewScopeMetrics()\n\torig := NewScopeMetrics()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestScopeMetrics()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newScopeMetrics(internal.NewScopeMetrics(), sharedState)) })\n}\n\nfunc TestScopeMetrics_Scope(t *testing.T) {\n\tms := NewScopeMetrics()\n\tassert.Equal(t, pcommon.NewInstrumentationScope(), ms.Scope())\n\tms.orig.Scope = *internal.GenTestInstrumentationScope()\n\tassert.Equal(t, pcommon.InstrumentationScope(internal.GenTestInstrumentationScopeWrapper()), ms.Scope())\n}\n\nfunc TestScopeMetrics_Metrics(t *testing.T) {\n\tms := NewScopeMetrics()\n\tassert.Equal(t, NewMetricSlice(), ms.Metrics())\n\tms.orig.Metrics = internal.GenTestMetricPtrSlice()\n\tassert.Equal(t, generateTestMetricSlice(), ms.Metrics())\n}\n\nfunc TestScopeMetrics_SchemaUrl(t *testing.T) {\n\tms := NewScopeMetrics()\n\tassert.Empty(t, ms.SchemaUrl())\n\tms.SetSchemaUrl(\"test_schemaurl\")\n\tassert.Equal(t, \"test_schemaurl\", ms.SchemaUrl())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newScopeMetrics(internal.NewScopeMetrics(), sharedState).SetSchemaUrl(\"test_schemaurl\") })\n}\n\nfunc generateTestScopeMetrics() ScopeMetrics {\n\treturn newScopeMetrics(internal.GenTestScopeMetrics(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_scopemetricsslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ScopeMetricsSlice logically represents a slice of ScopeMetrics.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewScopeMetricsSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ScopeMetricsSlice struct {\n\torig  *[]*internal.ScopeMetrics\n\tstate *internal.State\n}\n\nfunc newScopeMetricsSlice(orig *[]*internal.ScopeMetrics, state *internal.State) ScopeMetricsSlice {\n\treturn ScopeMetricsSlice{orig: orig, state: state}\n}\n\n// NewScopeMetricsSlice creates a ScopeMetricsSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewScopeMetricsSlice() ScopeMetricsSlice {\n\torig := []*internal.ScopeMetrics(nil)\n\treturn newScopeMetricsSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewScopeMetricsSlice()\".\nfunc (es ScopeMetricsSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es ScopeMetricsSlice) At(i int) ScopeMetrics {\n\treturn newScopeMetrics((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es ScopeMetricsSlice) All() iter.Seq2[int, ScopeMetrics] {\n\treturn func(yield func(int, ScopeMetrics) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new ScopeMetricsSlice can be initialized:\n//\n//\tes := NewScopeMetricsSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es ScopeMetricsSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.ScopeMetrics, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty ScopeMetrics.\n// It returns the newly added ScopeMetrics.\nfunc (es ScopeMetricsSlice) AppendEmpty() ScopeMetrics {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewScopeMetrics())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es ScopeMetricsSlice) MoveAndAppendTo(dest ScopeMetricsSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es ScopeMetricsSlice) RemoveIf(f func(ScopeMetrics) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteScopeMetrics((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es ScopeMetricsSlice) CopyTo(dest ScopeMetricsSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyScopeMetricsPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the ScopeMetrics elements within ScopeMetricsSlice given the\n// provided less function so that two instances of ScopeMetricsSlice\n// can be compared.\nfunc (es ScopeMetricsSlice) Sort(less func(a, b ScopeMetrics) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_scopemetricsslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestScopeMetricsSlice(t *testing.T) {\n\tes := NewScopeMetricsSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newScopeMetricsSlice(&[]*internal.ScopeMetrics{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewScopeMetrics()\n\ttestVal := generateTestScopeMetrics()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestScopeMetrics()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestScopeMetricsSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newScopeMetricsSlice(&[]*internal.ScopeMetrics{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewScopeMetricsSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestScopeMetricsSlice_CopyTo(t *testing.T) {\n\tdest := NewScopeMetricsSlice()\n\tsrc := generateTestScopeMetricsSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestScopeMetricsSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestScopeMetricsSlice(), dest)\n}\n\nfunc TestScopeMetricsSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestScopeMetricsSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestScopeMetricsSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestScopeMetricsSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestScopeMetricsSlice(), es)\n}\n\nfunc TestScopeMetricsSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestScopeMetricsSlice()\n\tdest := NewScopeMetricsSlice()\n\tsrc := generateTestScopeMetricsSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestScopeMetricsSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestScopeMetricsSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestScopeMetricsSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestScopeMetricsSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewScopeMetricsSlice()\n\temptySlice.RemoveIf(func(el ScopeMetrics) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestScopeMetricsSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el ScopeMetrics) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestScopeMetricsSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestScopeMetricsSlice()\n\tgot.RemoveIf(func(el ScopeMetrics) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestScopeMetricsSliceAll(t *testing.T) {\n\tms := generateTestScopeMetricsSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestScopeMetricsSlice_Sort(t *testing.T) {\n\tes := generateTestScopeMetricsSlice()\n\tes.Sort(func(a, b ScopeMetrics) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b ScopeMetrics) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestScopeMetricsSlice() ScopeMetricsSlice {\n\tms := NewScopeMetricsSlice()\n\t*ms.orig = internal.GenTestScopeMetricsPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_sum.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// Sum represents the type of a numeric metric that is calculated as a sum of all reported measurements over a time interval.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewSum function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Sum struct {\n\torig  *internal.Sum\n\tstate *internal.State\n}\n\nfunc newSum(orig *internal.Sum, state *internal.State) Sum {\n\treturn Sum{orig: orig, state: state}\n}\n\n// NewSum creates a new empty Sum.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewSum() Sum {\n\treturn newSum(internal.NewSum(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Sum) MoveTo(dest Sum) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteSum(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// DataPoints returns the DataPoints associated with this Sum.\nfunc (ms Sum) DataPoints() NumberDataPointSlice {\n\treturn newNumberDataPointSlice(&ms.orig.DataPoints, ms.state)\n}\n\n// AggregationTemporality returns the aggregationtemporality associated with this Sum.\nfunc (ms Sum) AggregationTemporality() AggregationTemporality {\n\treturn AggregationTemporality(ms.orig.AggregationTemporality)\n}\n\n// SetAggregationTemporality replaces the aggregationtemporality associated with this Sum.\nfunc (ms Sum) SetAggregationTemporality(v AggregationTemporality) {\n\tms.state.AssertMutable()\n\tms.orig.AggregationTemporality = internal.AggregationTemporality(v)\n}\n\n// IsMonotonic returns the ismonotonic associated with this Sum.\nfunc (ms Sum) IsMonotonic() bool {\n\treturn ms.orig.IsMonotonic\n}\n\n// SetIsMonotonic replaces the ismonotonic associated with this Sum.\nfunc (ms Sum) SetIsMonotonic(v bool) {\n\tms.state.AssertMutable()\n\tms.orig.IsMonotonic = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Sum) CopyTo(dest Sum) {\n\tdest.state.AssertMutable()\n\tinternal.CopySum(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_sum_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestSum_MoveTo(t *testing.T) {\n\tms := generateTestSum()\n\tdest := NewSum()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewSum(), ms)\n\tassert.Equal(t, generateTestSum(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestSum(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newSum(internal.NewSum(), sharedState)) })\n\tassert.Panics(t, func() { newSum(internal.NewSum(), sharedState).MoveTo(dest) })\n}\n\nfunc TestSum_CopyTo(t *testing.T) {\n\tms := NewSum()\n\torig := NewSum()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestSum()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newSum(internal.NewSum(), sharedState)) })\n}\n\nfunc TestSum_DataPoints(t *testing.T) {\n\tms := NewSum()\n\tassert.Equal(t, NewNumberDataPointSlice(), ms.DataPoints())\n\tms.orig.DataPoints = internal.GenTestNumberDataPointPtrSlice()\n\tassert.Equal(t, generateTestNumberDataPointSlice(), ms.DataPoints())\n}\n\nfunc TestSum_AggregationTemporality(t *testing.T) {\n\tms := NewSum()\n\tassert.Equal(t, AggregationTemporality(internal.AggregationTemporality(0)), ms.AggregationTemporality())\n\ttestValAggregationTemporality := AggregationTemporality(internal.AggregationTemporality(1))\n\tms.SetAggregationTemporality(testValAggregationTemporality)\n\tassert.Equal(t, testValAggregationTemporality, ms.AggregationTemporality())\n}\n\nfunc TestSum_IsMonotonic(t *testing.T) {\n\tms := NewSum()\n\tassert.False(t, ms.IsMonotonic())\n\tms.SetIsMonotonic(true)\n\tassert.True(t, ms.IsMonotonic())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newSum(internal.NewSum(), sharedState).SetIsMonotonic(true) })\n}\n\nfunc generateTestSum() Sum {\n\treturn newSum(internal.GenTestSum(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_summary.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// Summary represents the type of a metric that is calculated by aggregating as a Summary of all reported double measurements over a time interval.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewSummary function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Summary struct {\n\torig  *internal.Summary\n\tstate *internal.State\n}\n\nfunc newSummary(orig *internal.Summary, state *internal.State) Summary {\n\treturn Summary{orig: orig, state: state}\n}\n\n// NewSummary creates a new empty Summary.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewSummary() Summary {\n\treturn newSummary(internal.NewSummary(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Summary) MoveTo(dest Summary) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteSummary(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// DataPoints returns the DataPoints associated with this Summary.\nfunc (ms Summary) DataPoints() SummaryDataPointSlice {\n\treturn newSummaryDataPointSlice(&ms.orig.DataPoints, ms.state)\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Summary) CopyTo(dest Summary) {\n\tdest.state.AssertMutable()\n\tinternal.CopySummary(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_summary_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestSummary_MoveTo(t *testing.T) {\n\tms := generateTestSummary()\n\tdest := NewSummary()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewSummary(), ms)\n\tassert.Equal(t, generateTestSummary(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestSummary(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newSummary(internal.NewSummary(), sharedState)) })\n\tassert.Panics(t, func() { newSummary(internal.NewSummary(), sharedState).MoveTo(dest) })\n}\n\nfunc TestSummary_CopyTo(t *testing.T) {\n\tms := NewSummary()\n\torig := NewSummary()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestSummary()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newSummary(internal.NewSummary(), sharedState)) })\n}\n\nfunc TestSummary_DataPoints(t *testing.T) {\n\tms := NewSummary()\n\tassert.Equal(t, NewSummaryDataPointSlice(), ms.DataPoints())\n\tms.orig.DataPoints = internal.GenTestSummaryDataPointPtrSlice()\n\tassert.Equal(t, generateTestSummaryDataPointSlice(), ms.DataPoints())\n}\n\nfunc generateTestSummary() Summary {\n\treturn newSummary(internal.GenTestSummary(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_summarydatapoint.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// SummaryDataPoint is a single data point in a timeseries that describes the time-varying values of a Summary of double values.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewSummaryDataPoint function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype SummaryDataPoint struct {\n\torig  *internal.SummaryDataPoint\n\tstate *internal.State\n}\n\nfunc newSummaryDataPoint(orig *internal.SummaryDataPoint, state *internal.State) SummaryDataPoint {\n\treturn SummaryDataPoint{orig: orig, state: state}\n}\n\n// NewSummaryDataPoint creates a new empty SummaryDataPoint.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewSummaryDataPoint() SummaryDataPoint {\n\treturn newSummaryDataPoint(internal.NewSummaryDataPoint(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms SummaryDataPoint) MoveTo(dest SummaryDataPoint) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteSummaryDataPoint(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Attributes returns the Attributes associated with this SummaryDataPoint.\nfunc (ms SummaryDataPoint) Attributes() pcommon.Map {\n\treturn pcommon.Map(internal.NewMapWrapper(&ms.orig.Attributes, ms.state))\n}\n\n// StartTimestamp returns the starttimestamp associated with this SummaryDataPoint.\nfunc (ms SummaryDataPoint) StartTimestamp() pcommon.Timestamp {\n\treturn pcommon.Timestamp(ms.orig.StartTimeUnixNano)\n}\n\n// SetStartTimestamp replaces the starttimestamp associated with this SummaryDataPoint.\nfunc (ms SummaryDataPoint) SetStartTimestamp(v pcommon.Timestamp) {\n\tms.state.AssertMutable()\n\tms.orig.StartTimeUnixNano = uint64(v)\n}\n\n// Timestamp returns the timestamp associated with this SummaryDataPoint.\nfunc (ms SummaryDataPoint) Timestamp() pcommon.Timestamp {\n\treturn pcommon.Timestamp(ms.orig.TimeUnixNano)\n}\n\n// SetTimestamp replaces the timestamp associated with this SummaryDataPoint.\nfunc (ms SummaryDataPoint) SetTimestamp(v pcommon.Timestamp) {\n\tms.state.AssertMutable()\n\tms.orig.TimeUnixNano = uint64(v)\n}\n\n// Count returns the count associated with this SummaryDataPoint.\nfunc (ms SummaryDataPoint) Count() uint64 {\n\treturn ms.orig.Count\n}\n\n// SetCount replaces the count associated with this SummaryDataPoint.\nfunc (ms SummaryDataPoint) SetCount(v uint64) {\n\tms.state.AssertMutable()\n\tms.orig.Count = v\n}\n\n// Sum returns the sum associated with this SummaryDataPoint.\nfunc (ms SummaryDataPoint) Sum() float64 {\n\treturn ms.orig.Sum\n}\n\n// SetSum replaces the sum associated with this SummaryDataPoint.\nfunc (ms SummaryDataPoint) SetSum(v float64) {\n\tms.state.AssertMutable()\n\tms.orig.Sum = v\n}\n\n// QuantileValues returns the QuantileValues associated with this SummaryDataPoint.\nfunc (ms SummaryDataPoint) QuantileValues() SummaryDataPointValueAtQuantileSlice {\n\treturn newSummaryDataPointValueAtQuantileSlice(&ms.orig.QuantileValues, ms.state)\n}\n\n// Flags returns the flags associated with this SummaryDataPoint.\nfunc (ms SummaryDataPoint) Flags() DataPointFlags {\n\treturn DataPointFlags(ms.orig.Flags)\n}\n\n// SetFlags replaces the flags associated with this SummaryDataPoint.\nfunc (ms SummaryDataPoint) SetFlags(v DataPointFlags) {\n\tms.state.AssertMutable()\n\tms.orig.Flags = uint32(v)\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms SummaryDataPoint) CopyTo(dest SummaryDataPoint) {\n\tdest.state.AssertMutable()\n\tinternal.CopySummaryDataPoint(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_summarydatapoint_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestSummaryDataPoint_MoveTo(t *testing.T) {\n\tms := generateTestSummaryDataPoint()\n\tdest := NewSummaryDataPoint()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewSummaryDataPoint(), ms)\n\tassert.Equal(t, generateTestSummaryDataPoint(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestSummaryDataPoint(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newSummaryDataPoint(internal.NewSummaryDataPoint(), sharedState)) })\n\tassert.Panics(t, func() { newSummaryDataPoint(internal.NewSummaryDataPoint(), sharedState).MoveTo(dest) })\n}\n\nfunc TestSummaryDataPoint_CopyTo(t *testing.T) {\n\tms := NewSummaryDataPoint()\n\torig := NewSummaryDataPoint()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestSummaryDataPoint()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newSummaryDataPoint(internal.NewSummaryDataPoint(), sharedState)) })\n}\n\nfunc TestSummaryDataPoint_Attributes(t *testing.T) {\n\tms := NewSummaryDataPoint()\n\tassert.Equal(t, pcommon.NewMap(), ms.Attributes())\n\tms.orig.Attributes = internal.GenTestKeyValueSlice()\n\tassert.Equal(t, pcommon.Map(internal.GenTestMapWrapper()), ms.Attributes())\n}\n\nfunc TestSummaryDataPoint_StartTimestamp(t *testing.T) {\n\tms := NewSummaryDataPoint()\n\tassert.Equal(t, pcommon.Timestamp(0), ms.StartTimestamp())\n\ttestValStartTimestamp := pcommon.Timestamp(1234567890)\n\tms.SetStartTimestamp(testValStartTimestamp)\n\tassert.Equal(t, testValStartTimestamp, ms.StartTimestamp())\n}\n\nfunc TestSummaryDataPoint_Timestamp(t *testing.T) {\n\tms := NewSummaryDataPoint()\n\tassert.Equal(t, pcommon.Timestamp(0), ms.Timestamp())\n\ttestValTimestamp := pcommon.Timestamp(1234567890)\n\tms.SetTimestamp(testValTimestamp)\n\tassert.Equal(t, testValTimestamp, ms.Timestamp())\n}\n\nfunc TestSummaryDataPoint_Count(t *testing.T) {\n\tms := NewSummaryDataPoint()\n\tassert.Equal(t, uint64(0), ms.Count())\n\tms.SetCount(uint64(13))\n\tassert.Equal(t, uint64(13), ms.Count())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newSummaryDataPoint(internal.NewSummaryDataPoint(), sharedState).SetCount(uint64(13)) })\n}\n\nfunc TestSummaryDataPoint_Sum(t *testing.T) {\n\tms := NewSummaryDataPoint()\n\tassert.InDelta(t, float64(0), ms.Sum(), 0.01)\n\tms.SetSum(float64(3.1415926))\n\tassert.InDelta(t, float64(3.1415926), ms.Sum(), 0.01)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newSummaryDataPoint(internal.NewSummaryDataPoint(), sharedState).SetSum(float64(3.1415926)) })\n}\n\nfunc TestSummaryDataPoint_QuantileValues(t *testing.T) {\n\tms := NewSummaryDataPoint()\n\tassert.Equal(t, NewSummaryDataPointValueAtQuantileSlice(), ms.QuantileValues())\n\tms.orig.QuantileValues = internal.GenTestSummaryDataPointValueAtQuantilePtrSlice()\n\tassert.Equal(t, generateTestSummaryDataPointValueAtQuantileSlice(), ms.QuantileValues())\n}\n\nfunc TestSummaryDataPoint_Flags(t *testing.T) {\n\tms := NewSummaryDataPoint()\n\tassert.Equal(t, DataPointFlags(0), ms.Flags())\n\ttestValFlags := DataPointFlags(1)\n\tms.SetFlags(testValFlags)\n\tassert.Equal(t, testValFlags, ms.Flags())\n}\n\nfunc generateTestSummaryDataPoint() SummaryDataPoint {\n\treturn newSummaryDataPoint(internal.GenTestSummaryDataPoint(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_summarydatapointslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// SummaryDataPointSlice logically represents a slice of SummaryDataPoint.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewSummaryDataPointSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype SummaryDataPointSlice struct {\n\torig  *[]*internal.SummaryDataPoint\n\tstate *internal.State\n}\n\nfunc newSummaryDataPointSlice(orig *[]*internal.SummaryDataPoint, state *internal.State) SummaryDataPointSlice {\n\treturn SummaryDataPointSlice{orig: orig, state: state}\n}\n\n// NewSummaryDataPointSlice creates a SummaryDataPointSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewSummaryDataPointSlice() SummaryDataPointSlice {\n\torig := []*internal.SummaryDataPoint(nil)\n\treturn newSummaryDataPointSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewSummaryDataPointSlice()\".\nfunc (es SummaryDataPointSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es SummaryDataPointSlice) At(i int) SummaryDataPoint {\n\treturn newSummaryDataPoint((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es SummaryDataPointSlice) All() iter.Seq2[int, SummaryDataPoint] {\n\treturn func(yield func(int, SummaryDataPoint) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new SummaryDataPointSlice can be initialized:\n//\n//\tes := NewSummaryDataPointSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es SummaryDataPointSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.SummaryDataPoint, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty SummaryDataPoint.\n// It returns the newly added SummaryDataPoint.\nfunc (es SummaryDataPointSlice) AppendEmpty() SummaryDataPoint {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewSummaryDataPoint())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es SummaryDataPointSlice) MoveAndAppendTo(dest SummaryDataPointSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es SummaryDataPointSlice) RemoveIf(f func(SummaryDataPoint) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteSummaryDataPoint((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es SummaryDataPointSlice) CopyTo(dest SummaryDataPointSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopySummaryDataPointPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the SummaryDataPoint elements within SummaryDataPointSlice given the\n// provided less function so that two instances of SummaryDataPointSlice\n// can be compared.\nfunc (es SummaryDataPointSlice) Sort(less func(a, b SummaryDataPoint) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_summarydatapointslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestSummaryDataPointSlice(t *testing.T) {\n\tes := NewSummaryDataPointSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newSummaryDataPointSlice(&[]*internal.SummaryDataPoint{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewSummaryDataPoint()\n\ttestVal := generateTestSummaryDataPoint()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestSummaryDataPoint()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestSummaryDataPointSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newSummaryDataPointSlice(&[]*internal.SummaryDataPoint{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewSummaryDataPointSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestSummaryDataPointSlice_CopyTo(t *testing.T) {\n\tdest := NewSummaryDataPointSlice()\n\tsrc := generateTestSummaryDataPointSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestSummaryDataPointSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestSummaryDataPointSlice(), dest)\n}\n\nfunc TestSummaryDataPointSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestSummaryDataPointSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestSummaryDataPointSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestSummaryDataPointSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestSummaryDataPointSlice(), es)\n}\n\nfunc TestSummaryDataPointSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestSummaryDataPointSlice()\n\tdest := NewSummaryDataPointSlice()\n\tsrc := generateTestSummaryDataPointSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestSummaryDataPointSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestSummaryDataPointSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestSummaryDataPointSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestSummaryDataPointSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewSummaryDataPointSlice()\n\temptySlice.RemoveIf(func(el SummaryDataPoint) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestSummaryDataPointSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el SummaryDataPoint) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestSummaryDataPointSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestSummaryDataPointSlice()\n\tgot.RemoveIf(func(el SummaryDataPoint) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestSummaryDataPointSliceAll(t *testing.T) {\n\tms := generateTestSummaryDataPointSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestSummaryDataPointSlice_Sort(t *testing.T) {\n\tes := generateTestSummaryDataPointSlice()\n\tes.Sort(func(a, b SummaryDataPoint) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b SummaryDataPoint) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestSummaryDataPointSlice() SummaryDataPointSlice {\n\tms := NewSummaryDataPointSlice()\n\t*ms.orig = internal.GenTestSummaryDataPointPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_summarydatapointvalueatquantile.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// SummaryDataPointValueAtQuantile is a quantile value within a Summary data point.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewSummaryDataPointValueAtQuantile function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype SummaryDataPointValueAtQuantile struct {\n\torig  *internal.SummaryDataPointValueAtQuantile\n\tstate *internal.State\n}\n\nfunc newSummaryDataPointValueAtQuantile(orig *internal.SummaryDataPointValueAtQuantile, state *internal.State) SummaryDataPointValueAtQuantile {\n\treturn SummaryDataPointValueAtQuantile{orig: orig, state: state}\n}\n\n// NewSummaryDataPointValueAtQuantile creates a new empty SummaryDataPointValueAtQuantile.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewSummaryDataPointValueAtQuantile() SummaryDataPointValueAtQuantile {\n\treturn newSummaryDataPointValueAtQuantile(internal.NewSummaryDataPointValueAtQuantile(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms SummaryDataPointValueAtQuantile) MoveTo(dest SummaryDataPointValueAtQuantile) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteSummaryDataPointValueAtQuantile(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Quantile returns the quantile associated with this SummaryDataPointValueAtQuantile.\nfunc (ms SummaryDataPointValueAtQuantile) Quantile() float64 {\n\treturn ms.orig.Quantile\n}\n\n// SetQuantile replaces the quantile associated with this SummaryDataPointValueAtQuantile.\nfunc (ms SummaryDataPointValueAtQuantile) SetQuantile(v float64) {\n\tms.state.AssertMutable()\n\tms.orig.Quantile = v\n}\n\n// Value returns the value associated with this SummaryDataPointValueAtQuantile.\nfunc (ms SummaryDataPointValueAtQuantile) Value() float64 {\n\treturn ms.orig.Value\n}\n\n// SetValue replaces the value associated with this SummaryDataPointValueAtQuantile.\nfunc (ms SummaryDataPointValueAtQuantile) SetValue(v float64) {\n\tms.state.AssertMutable()\n\tms.orig.Value = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms SummaryDataPointValueAtQuantile) CopyTo(dest SummaryDataPointValueAtQuantile) {\n\tdest.state.AssertMutable()\n\tinternal.CopySummaryDataPointValueAtQuantile(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_summarydatapointvalueatquantile_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestSummaryDataPointValueAtQuantile_MoveTo(t *testing.T) {\n\tms := generateTestSummaryDataPointValueAtQuantile()\n\tdest := NewSummaryDataPointValueAtQuantile()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewSummaryDataPointValueAtQuantile(), ms)\n\tassert.Equal(t, generateTestSummaryDataPointValueAtQuantile(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestSummaryDataPointValueAtQuantile(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tms.MoveTo(newSummaryDataPointValueAtQuantile(internal.NewSummaryDataPointValueAtQuantile(), sharedState))\n\t})\n\tassert.Panics(t, func() {\n\t\tnewSummaryDataPointValueAtQuantile(internal.NewSummaryDataPointValueAtQuantile(), sharedState).MoveTo(dest)\n\t})\n}\n\nfunc TestSummaryDataPointValueAtQuantile_CopyTo(t *testing.T) {\n\tms := NewSummaryDataPointValueAtQuantile()\n\torig := NewSummaryDataPointValueAtQuantile()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestSummaryDataPointValueAtQuantile()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tms.CopyTo(newSummaryDataPointValueAtQuantile(internal.NewSummaryDataPointValueAtQuantile(), sharedState))\n\t})\n}\n\nfunc TestSummaryDataPointValueAtQuantile_Quantile(t *testing.T) {\n\tms := NewSummaryDataPointValueAtQuantile()\n\tassert.InDelta(t, float64(0), ms.Quantile(), 0.01)\n\tms.SetQuantile(float64(3.1415926))\n\tassert.InDelta(t, float64(3.1415926), ms.Quantile(), 0.01)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewSummaryDataPointValueAtQuantile(internal.NewSummaryDataPointValueAtQuantile(), sharedState).SetQuantile(float64(3.1415926))\n\t})\n}\n\nfunc TestSummaryDataPointValueAtQuantile_Value(t *testing.T) {\n\tms := NewSummaryDataPointValueAtQuantile()\n\tassert.InDelta(t, float64(0), ms.Value(), 0.01)\n\tms.SetValue(float64(3.1415926))\n\tassert.InDelta(t, float64(3.1415926), ms.Value(), 0.01)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewSummaryDataPointValueAtQuantile(internal.NewSummaryDataPointValueAtQuantile(), sharedState).SetValue(float64(3.1415926))\n\t})\n}\n\nfunc generateTestSummaryDataPointValueAtQuantile() SummaryDataPointValueAtQuantile {\n\treturn newSummaryDataPointValueAtQuantile(internal.GenTestSummaryDataPointValueAtQuantile(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_summarydatapointvalueatquantileslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// SummaryDataPointValueAtQuantileSlice logically represents a slice of SummaryDataPointValueAtQuantile.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewSummaryDataPointValueAtQuantileSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype SummaryDataPointValueAtQuantileSlice struct {\n\torig  *[]*internal.SummaryDataPointValueAtQuantile\n\tstate *internal.State\n}\n\nfunc newSummaryDataPointValueAtQuantileSlice(orig *[]*internal.SummaryDataPointValueAtQuantile, state *internal.State) SummaryDataPointValueAtQuantileSlice {\n\treturn SummaryDataPointValueAtQuantileSlice{orig: orig, state: state}\n}\n\n// NewSummaryDataPointValueAtQuantileSlice creates a SummaryDataPointValueAtQuantileSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewSummaryDataPointValueAtQuantileSlice() SummaryDataPointValueAtQuantileSlice {\n\torig := []*internal.SummaryDataPointValueAtQuantile(nil)\n\treturn newSummaryDataPointValueAtQuantileSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewSummaryDataPointValueAtQuantileSlice()\".\nfunc (es SummaryDataPointValueAtQuantileSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es SummaryDataPointValueAtQuantileSlice) At(i int) SummaryDataPointValueAtQuantile {\n\treturn newSummaryDataPointValueAtQuantile((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es SummaryDataPointValueAtQuantileSlice) All() iter.Seq2[int, SummaryDataPointValueAtQuantile] {\n\treturn func(yield func(int, SummaryDataPointValueAtQuantile) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new SummaryDataPointValueAtQuantileSlice can be initialized:\n//\n//\tes := NewSummaryDataPointValueAtQuantileSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es SummaryDataPointValueAtQuantileSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.SummaryDataPointValueAtQuantile, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty SummaryDataPointValueAtQuantile.\n// It returns the newly added SummaryDataPointValueAtQuantile.\nfunc (es SummaryDataPointValueAtQuantileSlice) AppendEmpty() SummaryDataPointValueAtQuantile {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewSummaryDataPointValueAtQuantile())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es SummaryDataPointValueAtQuantileSlice) MoveAndAppendTo(dest SummaryDataPointValueAtQuantileSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es SummaryDataPointValueAtQuantileSlice) RemoveIf(f func(SummaryDataPointValueAtQuantile) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteSummaryDataPointValueAtQuantile((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es SummaryDataPointValueAtQuantileSlice) CopyTo(dest SummaryDataPointValueAtQuantileSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopySummaryDataPointValueAtQuantilePtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the SummaryDataPointValueAtQuantile elements within SummaryDataPointValueAtQuantileSlice given the\n// provided less function so that two instances of SummaryDataPointValueAtQuantileSlice\n// can be compared.\nfunc (es SummaryDataPointValueAtQuantileSlice) Sort(less func(a, b SummaryDataPointValueAtQuantile) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pmetric/generated_summarydatapointvalueatquantileslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestSummaryDataPointValueAtQuantileSlice(t *testing.T) {\n\tes := NewSummaryDataPointValueAtQuantileSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newSummaryDataPointValueAtQuantileSlice(&[]*internal.SummaryDataPointValueAtQuantile{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewSummaryDataPointValueAtQuantile()\n\ttestVal := generateTestSummaryDataPointValueAtQuantile()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestSummaryDataPointValueAtQuantile()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestSummaryDataPointValueAtQuantileSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newSummaryDataPointValueAtQuantileSlice(&[]*internal.SummaryDataPointValueAtQuantile{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewSummaryDataPointValueAtQuantileSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestSummaryDataPointValueAtQuantileSlice_CopyTo(t *testing.T) {\n\tdest := NewSummaryDataPointValueAtQuantileSlice()\n\tsrc := generateTestSummaryDataPointValueAtQuantileSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestSummaryDataPointValueAtQuantileSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestSummaryDataPointValueAtQuantileSlice(), dest)\n}\n\nfunc TestSummaryDataPointValueAtQuantileSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestSummaryDataPointValueAtQuantileSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestSummaryDataPointValueAtQuantileSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestSummaryDataPointValueAtQuantileSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestSummaryDataPointValueAtQuantileSlice(), es)\n}\n\nfunc TestSummaryDataPointValueAtQuantileSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestSummaryDataPointValueAtQuantileSlice()\n\tdest := NewSummaryDataPointValueAtQuantileSlice()\n\tsrc := generateTestSummaryDataPointValueAtQuantileSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestSummaryDataPointValueAtQuantileSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestSummaryDataPointValueAtQuantileSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestSummaryDataPointValueAtQuantileSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestSummaryDataPointValueAtQuantileSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewSummaryDataPointValueAtQuantileSlice()\n\temptySlice.RemoveIf(func(el SummaryDataPointValueAtQuantile) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestSummaryDataPointValueAtQuantileSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el SummaryDataPointValueAtQuantile) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestSummaryDataPointValueAtQuantileSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestSummaryDataPointValueAtQuantileSlice()\n\tgot.RemoveIf(func(el SummaryDataPointValueAtQuantile) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestSummaryDataPointValueAtQuantileSliceAll(t *testing.T) {\n\tms := generateTestSummaryDataPointValueAtQuantileSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestSummaryDataPointValueAtQuantileSlice_Sort(t *testing.T) {\n\tes := generateTestSummaryDataPointValueAtQuantileSlice()\n\tes.Sort(func(a, b SummaryDataPointValueAtQuantile) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b SummaryDataPointValueAtQuantile) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestSummaryDataPointValueAtQuantileSlice() SummaryDataPointValueAtQuantileSlice {\n\tms := NewSummaryDataPointValueAtQuantileSlice()\n\t*ms.orig = internal.GenTestSummaryDataPointValueAtQuantilePtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pmetric/json.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric // import \"go.opentelemetry.io/collector/pdata/pmetric\"\n\nimport (\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otlp\"\n)\n\nvar _ Marshaler = (*JSONMarshaler)(nil)\n\n// JSONMarshaler marshals Metrics to JSON bytes using the OTLP/JSON format.\ntype JSONMarshaler struct{}\n\n// MarshalMetrics to the OTLP/JSON format.\nfunc (*JSONMarshaler) MarshalMetrics(md Metrics) ([]byte, error) {\n\tdest := json.BorrowStream(nil)\n\tdefer json.ReturnStream(dest)\n\tmd.getOrig().MarshalJSON(dest)\n\tif dest.Error() != nil {\n\t\treturn nil, dest.Error()\n\t}\n\treturn slices.Clone(dest.Buffer()), nil\n}\n\n// JSONUnmarshaler unmarshals OTLP/JSON formatted-bytes to Metrics.\ntype JSONUnmarshaler struct{}\n\n// UnmarshalMetrics from OTLP/JSON format into Metrics.\nfunc (*JSONUnmarshaler) UnmarshalMetrics(buf []byte) (Metrics, error) {\n\titer := json.BorrowIterator(buf)\n\tdefer json.ReturnIterator(iter)\n\tmd := NewMetrics()\n\tmd.getOrig().UnmarshalJSON(iter)\n\tif iter.Error() != nil {\n\t\treturn Metrics{}, iter.Error()\n\t}\n\totlp.MigrateMetrics(md.getOrig().ResourceMetrics)\n\treturn md, nil\n}\n"
  },
  {
    "path": "pdata/pmetric/metric_data_point_flags.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric // import \"go.opentelemetry.io/collector/pdata/pmetric\"\n\nconst noRecordValueMask = uint32(1)\n\nvar DefaultDataPointFlags = DataPointFlags(0)\n\n// DataPointFlags defines how a metric aggregator reports aggregated values.\n// It describes how those values relate to the time interval over which they are aggregated.\ntype DataPointFlags uint32\n\n// NoRecordedValue returns true if the DataPointFlags contains the NoRecordedValue flag.\nfunc (ms DataPointFlags) NoRecordedValue() bool {\n\treturn uint32(ms)&noRecordValueMask != 0\n}\n\n// WithNoRecordedValue returns a new DataPointFlags, with the NoRecordedValue flag set to the given value.\nfunc (ms DataPointFlags) WithNoRecordedValue(b bool) DataPointFlags {\n\torig := uint32(ms)\n\tif b {\n\t\torig |= noRecordValueMask\n\t} else {\n\t\torig &^= noRecordValueMask\n\t}\n\treturn DataPointFlags(orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/metric_data_point_flags_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestLogRecordFlags(t *testing.T) {\n\tflags := DataPointFlags(1)\n\tassert.True(t, flags.NoRecordedValue())\n\tassert.EqualValues(t, uint32(1), flags)\n\n\tflags = flags.WithNoRecordedValue(false)\n\tassert.False(t, flags.NoRecordedValue())\n\tassert.EqualValues(t, uint32(0), flags)\n\n\tflags = flags.WithNoRecordedValue(true)\n\tassert.True(t, flags.NoRecordedValue())\n\tassert.EqualValues(t, uint32(1), flags)\n}\n\nfunc TestDefaultLogRecordFlags(t *testing.T) {\n\tflags := DefaultDataPointFlags\n\tassert.False(t, flags.NoRecordedValue())\n\tassert.EqualValues(t, uint32(0), flags)\n}\n"
  },
  {
    "path": "pdata/pmetric/metric_type.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric // import \"go.opentelemetry.io/collector/pdata/pmetric\"\n\n// MetricType specifies the type of data in a Metric.\ntype MetricType int32\n\nconst (\n\t// MetricTypeEmpty means that metric type is unset.\n\tMetricTypeEmpty MetricType = iota\n\tMetricTypeGauge\n\tMetricTypeSum\n\tMetricTypeHistogram\n\tMetricTypeExponentialHistogram\n\tMetricTypeSummary\n)\n\n// String returns the string representation of the MetricType.\nfunc (mdt MetricType) String() string {\n\tswitch mdt {\n\tcase MetricTypeEmpty:\n\t\treturn \"Empty\"\n\tcase MetricTypeGauge:\n\t\treturn \"Gauge\"\n\tcase MetricTypeSum:\n\t\treturn \"Sum\"\n\tcase MetricTypeHistogram:\n\t\treturn \"Histogram\"\n\tcase MetricTypeExponentialHistogram:\n\t\treturn \"ExponentialHistogram\"\n\tcase MetricTypeSummary:\n\t\treturn \"Summary\"\n\t}\n\treturn \"\"\n}\n"
  },
  {
    "path": "pdata/pmetric/metric_type_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric // import \"go.opentelemetry.io/collector/pdata/pmetric\"\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestMetricTypeString(t *testing.T) {\n\tassert.Equal(t, \"Empty\", MetricTypeEmpty.String())\n\tassert.Equal(t, \"Gauge\", MetricTypeGauge.String())\n\tassert.Equal(t, \"Sum\", MetricTypeSum.String())\n\tassert.Equal(t, \"Histogram\", MetricTypeHistogram.String())\n\tassert.Equal(t, \"ExponentialHistogram\", MetricTypeExponentialHistogram.String())\n\tassert.Equal(t, \"Summary\", MetricTypeSummary.String())\n\tassert.Empty(t, (MetricTypeSummary + 1).String())\n}\n"
  },
  {
    "path": "pdata/pmetric/metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric // import \"go.opentelemetry.io/collector/pdata/pmetric\"\n\n// MarkReadOnly marks the Metrics as shared so that no further modifications can be done on it.\nfunc (ms Metrics) MarkReadOnly() {\n\tms.getState().MarkReadOnly()\n}\n\n// IsReadOnly returns true if this Metrics instance is read-only.\nfunc (ms Metrics) IsReadOnly() bool {\n\treturn ms.getState().IsReadOnly()\n}\n\n// MetricCount calculates the total number of metrics.\nfunc (ms Metrics) MetricCount() int {\n\tmetricCount := 0\n\trms := ms.ResourceMetrics()\n\tfor i := 0; i < rms.Len(); i++ {\n\t\trm := rms.At(i)\n\t\tilms := rm.ScopeMetrics()\n\t\tfor j := 0; j < ilms.Len(); j++ {\n\t\t\tilm := ilms.At(j)\n\t\t\tmetricCount += ilm.Metrics().Len()\n\t\t}\n\t}\n\treturn metricCount\n}\n\n// DataPointCount calculates the total number of data points.\nfunc (ms Metrics) DataPointCount() (dataPointCount int) {\n\trms := ms.ResourceMetrics()\n\tfor i := 0; i < rms.Len(); i++ {\n\t\trm := rms.At(i)\n\t\tilms := rm.ScopeMetrics()\n\t\tfor j := 0; j < ilms.Len(); j++ {\n\t\t\tilm := ilms.At(j)\n\t\t\tms := ilm.Metrics()\n\t\t\tfor k := 0; k < ms.Len(); k++ {\n\t\t\t\tm := ms.At(k)\n\t\t\t\tswitch m.Type() {\n\t\t\t\tcase MetricTypeGauge:\n\t\t\t\t\tdataPointCount += m.Gauge().DataPoints().Len()\n\t\t\t\tcase MetricTypeSum:\n\t\t\t\t\tdataPointCount += m.Sum().DataPoints().Len()\n\t\t\t\tcase MetricTypeHistogram:\n\t\t\t\t\tdataPointCount += m.Histogram().DataPoints().Len()\n\t\t\t\tcase MetricTypeExponentialHistogram:\n\t\t\t\t\tdataPointCount += m.ExponentialHistogram().DataPoints().Len()\n\t\t\t\tcase MetricTypeSummary:\n\t\t\t\t\tdataPointCount += m.Summary().DataPoints().Len()\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn dataPointCount\n}\n"
  },
  {
    "path": "pdata/pmetric/metrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nconst (\n\tstartTime = uint64(12578940000000012345)\n\tendTime   = uint64(12578940000000054321)\n)\n\nfunc TestMetricCount(t *testing.T) {\n\tmd := NewMetrics()\n\tassert.Equal(t, 0, md.MetricCount())\n\n\trms := md.ResourceMetrics()\n\trms.EnsureCapacity(3)\n\trm := rms.AppendEmpty()\n\tassert.Equal(t, 0, md.MetricCount())\n\n\tilm := rm.ScopeMetrics().AppendEmpty()\n\tassert.Equal(t, 0, md.MetricCount())\n\n\tilm.Metrics().AppendEmpty()\n\tassert.Equal(t, 1, md.MetricCount())\n\n\trms.AppendEmpty().ScopeMetrics().AppendEmpty()\n\tilmm := rms.AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()\n\tilmm.EnsureCapacity(5)\n\tfor range 5 {\n\t\tilmm.AppendEmpty()\n\t}\n\t// 5 + 1 (from rms.At(0) initialized first)\n\tassert.Equal(t, 6, md.MetricCount())\n}\n\nfunc TestMetricCountWithEmpty(t *testing.T) {\n\tassert.Equal(t, 0, generateMetricsEmptyResource().MetricCount())\n\tassert.Equal(t, 0, generateMetricsEmptyInstrumentation().MetricCount())\n\tassert.Equal(t, 1, generateMetricsEmptyMetrics().MetricCount())\n}\n\nfunc TestMetricAndDataPointCount(t *testing.T) {\n\tmd := NewMetrics()\n\tdps := md.DataPointCount()\n\tassert.Equal(t, 0, dps)\n\n\trms := md.ResourceMetrics()\n\trms.AppendEmpty()\n\tdps = md.DataPointCount()\n\tassert.Equal(t, 0, dps)\n\n\tilms := md.ResourceMetrics().At(0).ScopeMetrics()\n\tilms.AppendEmpty()\n\tdps = md.DataPointCount()\n\tassert.Equal(t, 0, dps)\n\n\tilms.At(0).Metrics().AppendEmpty()\n\tdps = md.DataPointCount()\n\tassert.Equal(t, 0, dps)\n\tintSum := ilms.At(0).Metrics().At(0).SetEmptySum()\n\tintSum.DataPoints().AppendEmpty()\n\tintSum.DataPoints().AppendEmpty()\n\tintSum.DataPoints().AppendEmpty()\n\tassert.Equal(t, 3, md.DataPointCount())\n\n\tmd = NewMetrics()\n\trms = md.ResourceMetrics()\n\trms.EnsureCapacity(3)\n\trms.AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\trms.AppendEmpty().ScopeMetrics().AppendEmpty()\n\trms.AppendEmpty().ScopeMetrics().AppendEmpty()\n\tilms = rms.At(2).ScopeMetrics()\n\tilm := ilms.At(0).Metrics()\n\tfor range 5 {\n\t\tilm.AppendEmpty()\n\t}\n\tassert.Equal(t, 0, md.DataPointCount())\n\n\tilm.At(0).SetEmptyGauge().DataPoints().AppendEmpty()\n\tassert.Equal(t, 1, md.DataPointCount())\n\n\tilm.At(1).SetEmptySum().DataPoints().AppendEmpty()\n\tassert.Equal(t, 2, md.DataPointCount())\n\n\tilm.At(2).SetEmptyHistogram().DataPoints().AppendEmpty()\n\tassert.Equal(t, 3, md.DataPointCount())\n\n\tilm.At(3).SetEmptyExponentialHistogram().DataPoints().AppendEmpty()\n\tassert.Equal(t, 4, md.DataPointCount())\n\n\tilm.At(4).SetEmptySummary().DataPoints().AppendEmpty()\n\tassert.Equal(t, 5, md.DataPointCount())\n}\n\nfunc TestDataPointCountWithEmpty(t *testing.T) {\n\tassert.Equal(t, 0, generateMetricsEmptyResource().DataPointCount())\n\tassert.Equal(t, 0, generateMetricsEmptyInstrumentation().DataPointCount())\n\tassert.Equal(t, 0, generateMetricsEmptyMetrics().DataPointCount())\n\tassert.Equal(t, 1, generateMetricsEmptyDataPoints().DataPointCount())\n}\n\nfunc TestDataPointCountWithNilDataPoints(t *testing.T) {\n\tmd := NewMetrics()\n\tilm := md.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty()\n\tilm.Metrics().AppendEmpty().SetEmptyGauge()\n\tilm.Metrics().AppendEmpty().SetEmptySum()\n\tilm.Metrics().AppendEmpty().SetEmptyHistogram()\n\tilm.Metrics().AppendEmpty().SetEmptyExponentialHistogram()\n\tilm.Metrics().AppendEmpty().SetEmptySummary()\n\tassert.Equal(t, 0, md.DataPointCount())\n}\n\nfunc TestHistogramWithNilSum(t *testing.T) {\n\tmd := NewMetrics()\n\tilm := md.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty()\n\thisto := ilm.Metrics().AppendEmpty()\n\thistogramDataPoints := histo.SetEmptyHistogram().DataPoints()\n\thistogramDataPoints.AppendEmpty()\n\tdest := ilm.Metrics().AppendEmpty()\n\thisto.CopyTo(dest)\n\tassert.Equal(t, histo, dest)\n}\n\nfunc TestHistogramWithValidSum(t *testing.T) {\n\tmd := NewMetrics()\n\tilm := md.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty()\n\thisto := ilm.Metrics().AppendEmpty()\n\thistogramDataPoints := histo.SetEmptyHistogram().DataPoints()\n\thistogramDataPoints.AppendEmpty()\n\thistogramDataPoints.At(0).SetSum(10)\n\tdest := ilm.Metrics().AppendEmpty()\n\thisto.CopyTo(dest)\n\tassert.Equal(t, histo, dest)\n}\n\nfunc TestOtlpToInternalReadOnly(t *testing.T) {\n\tmd := newMetrics(&internal.ExportMetricsServiceRequest{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tResource: generateTestProtoResource(),\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{\n\t\t\t\t\t{\n\t\t\t\t\t\tScope:   generateTestProtoInstrumentationScope(),\n\t\t\t\t\t\tMetrics: []*internal.Metric{generateTestProtoGaugeMetric(), generateTestProtoSumMetric(), generateTestProtoHistogramMetric()},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, new(internal.State))\n\tresourceMetrics := md.ResourceMetrics()\n\tassert.Equal(t, 1, resourceMetrics.Len())\n\n\tresourceMetric := resourceMetrics.At(0)\n\tassert.Equal(t, map[string]any{\n\t\t\"string\": \"string-resource\",\n\t}, resourceMetric.Resource().Attributes().AsRaw())\n\tmetrics := resourceMetric.ScopeMetrics().At(0).Metrics()\n\tassert.Equal(t, 3, metrics.Len())\n\n\t// Check int64 metric\n\tmetricInt := metrics.At(0)\n\tassert.Equal(t, \"my_metric_int\", metricInt.Name())\n\tassert.Equal(t, \"My metric\", metricInt.Description())\n\tassert.Equal(t, \"ms\", metricInt.Unit())\n\tassert.Equal(t, MetricTypeGauge, metricInt.Type())\n\tgaugeDataPoints := metricInt.Gauge().DataPoints()\n\tassert.Equal(t, 2, gaugeDataPoints.Len())\n\t// First point\n\tassert.EqualValues(t, startTime, gaugeDataPoints.At(0).StartTimestamp())\n\tassert.EqualValues(t, endTime, gaugeDataPoints.At(0).Timestamp())\n\tassert.InDelta(t, 123.1, gaugeDataPoints.At(0).DoubleValue(), 0.01)\n\tassert.Equal(t, map[string]any{\"key0\": \"value0\"}, gaugeDataPoints.At(0).Attributes().AsRaw())\n\t// Second point\n\tassert.EqualValues(t, startTime, gaugeDataPoints.At(1).StartTimestamp())\n\tassert.EqualValues(t, endTime, gaugeDataPoints.At(1).Timestamp())\n\tassert.InDelta(t, 456.1, gaugeDataPoints.At(1).DoubleValue(), 0.01)\n\tassert.Equal(t, map[string]any{\"key1\": \"value1\"}, gaugeDataPoints.At(1).Attributes().AsRaw())\n\n\t// Check double metric\n\tmetricDouble := metrics.At(1)\n\tassert.Equal(t, \"my_metric_double\", metricDouble.Name())\n\tassert.Equal(t, \"My metric\", metricDouble.Description())\n\tassert.Equal(t, \"ms\", metricDouble.Unit())\n\tassert.Equal(t, MetricTypeSum, metricDouble.Type())\n\tdsd := metricDouble.Sum()\n\tassert.Equal(t, AggregationTemporalityCumulative, dsd.AggregationTemporality())\n\tsumDataPoints := dsd.DataPoints()\n\tassert.Equal(t, 2, sumDataPoints.Len())\n\t// First point\n\tassert.EqualValues(t, startTime, sumDataPoints.At(0).StartTimestamp())\n\tassert.EqualValues(t, endTime, sumDataPoints.At(0).Timestamp())\n\tassert.InDelta(t, 123.1, sumDataPoints.At(0).DoubleValue(), 0.01)\n\tassert.Equal(t, map[string]any{\"key0\": \"value0\"}, sumDataPoints.At(0).Attributes().AsRaw())\n\t// Second point\n\tassert.EqualValues(t, startTime, sumDataPoints.At(1).StartTimestamp())\n\tassert.EqualValues(t, endTime, sumDataPoints.At(1).Timestamp())\n\tassert.InDelta(t, 456.1, sumDataPoints.At(1).DoubleValue(), 0.01)\n\tassert.Equal(t, map[string]any{\"key1\": \"value1\"}, sumDataPoints.At(1).Attributes().AsRaw())\n\n\t// Check histogram metric\n\tmetricHistogram := metrics.At(2)\n\tassert.Equal(t, \"my_metric_histogram\", metricHistogram.Name())\n\tassert.Equal(t, \"My metric\", metricHistogram.Description())\n\tassert.Equal(t, \"ms\", metricHistogram.Unit())\n\tassert.Equal(t, MetricTypeHistogram, metricHistogram.Type())\n\tdhd := metricHistogram.Histogram()\n\tassert.Equal(t, AggregationTemporalityDelta, dhd.AggregationTemporality())\n\thistogramDataPoints := dhd.DataPoints()\n\tassert.Equal(t, 2, histogramDataPoints.Len())\n\t// First point\n\tassert.EqualValues(t, startTime, histogramDataPoints.At(0).StartTimestamp())\n\tassert.EqualValues(t, endTime, histogramDataPoints.At(0).Timestamp())\n\tassert.Equal(t, []float64{1, 2}, histogramDataPoints.At(0).ExplicitBounds().AsRaw())\n\tassert.Equal(t, map[string]any{\"key0\": \"value0\"}, histogramDataPoints.At(0).Attributes().AsRaw())\n\tassert.Equal(t, []uint64{10, 15, 1}, histogramDataPoints.At(0).BucketCounts().AsRaw())\n\t// Second point\n\tassert.EqualValues(t, startTime, histogramDataPoints.At(1).StartTimestamp())\n\tassert.EqualValues(t, endTime, histogramDataPoints.At(1).Timestamp())\n\tassert.Equal(t, []float64{1}, histogramDataPoints.At(1).ExplicitBounds().AsRaw())\n\tassert.Equal(t, map[string]any{\"key1\": \"value1\"}, histogramDataPoints.At(1).Attributes().AsRaw())\n\tassert.Equal(t, []uint64{10, 1}, histogramDataPoints.At(1).BucketCounts().AsRaw())\n}\n\nfunc TestOtlpToFromInternalReadOnly(t *testing.T) {\n\tmd := newMetrics(&internal.ExportMetricsServiceRequest{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tResource: generateTestProtoResource(),\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{\n\t\t\t\t\t{\n\t\t\t\t\t\tScope:   generateTestProtoInstrumentationScope(),\n\t\t\t\t\t\tMetrics: []*internal.Metric{generateTestProtoGaugeMetric(), generateTestProtoSumMetric(), generateTestProtoHistogramMetric()},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, new(internal.State))\n\t// Test that nothing changed\n\tassert.EqualValues(t, &internal.MetricsData{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tResource: generateTestProtoResource(),\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{\n\t\t\t\t\t{\n\t\t\t\t\t\tScope:   generateTestProtoInstrumentationScope(),\n\t\t\t\t\t\tMetrics: []*internal.Metric{generateTestProtoGaugeMetric(), generateTestProtoSumMetric(), generateTestProtoHistogramMetric()},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, md.getOrig())\n}\n\nfunc TestOtlpToFromInternalGaugeMutating(t *testing.T) {\n\tnewAttributes := map[string]any{\"k\": \"v\"}\n\n\tmd := newMetrics(&internal.ExportMetricsServiceRequest{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tResource: generateTestProtoResource(),\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{\n\t\t\t\t\t{\n\t\t\t\t\t\tScope:   generateTestProtoInstrumentationScope(),\n\t\t\t\t\t\tMetrics: []*internal.Metric{generateTestProtoGaugeMetric()},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, new(internal.State))\n\tresourceMetrics := md.ResourceMetrics()\n\tmetric := resourceMetrics.At(0).ScopeMetrics().At(0).Metrics().At(0)\n\t// Mutate MetricDescriptor\n\tmetric.SetName(\"new_my_metric_int\")\n\tassert.Equal(t, \"new_my_metric_int\", metric.Name())\n\tmetric.SetDescription(\"My new metric\")\n\tassert.Equal(t, \"My new metric\", metric.Description())\n\tmetric.SetUnit(\"1\")\n\tassert.Equal(t, \"1\", metric.Unit())\n\t// Mutate DataPoints\n\tigd := metric.Gauge()\n\tassert.Equal(t, 2, igd.DataPoints().Len())\n\tgaugeDataPoints := metric.SetEmptyGauge().DataPoints()\n\tgaugeDataPoints.AppendEmpty()\n\tassert.Equal(t, 1, gaugeDataPoints.Len())\n\tgaugeDataPoints.At(0).SetStartTimestamp(pcommon.Timestamp(startTime + 1))\n\tassert.EqualValues(t, startTime+1, gaugeDataPoints.At(0).StartTimestamp())\n\tgaugeDataPoints.At(0).SetTimestamp(pcommon.Timestamp(endTime + 1))\n\tassert.EqualValues(t, endTime+1, gaugeDataPoints.At(0).Timestamp())\n\tgaugeDataPoints.At(0).SetDoubleValue(124.1)\n\tassert.InDelta(t, 124.1, gaugeDataPoints.At(0).DoubleValue(), 0.01)\n\tgaugeDataPoints.At(0).Attributes().Remove(\"key0\")\n\tgaugeDataPoints.At(0).Attributes().PutStr(\"k\", \"v\")\n\tassert.Equal(t, newAttributes, gaugeDataPoints.At(0).Attributes().AsRaw())\n\n\t// Test that everything is updated.\n\tassert.EqualValues(t, &internal.MetricsData{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tResource: generateTestProtoResource(),\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{\n\t\t\t\t\t{\n\t\t\t\t\t\tScope: generateTestProtoInstrumentationScope(),\n\t\t\t\t\t\tMetrics: []*internal.Metric{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName:        \"new_my_metric_int\",\n\t\t\t\t\t\t\t\tDescription: \"My new metric\",\n\t\t\t\t\t\t\t\tUnit:        \"1\",\n\t\t\t\t\t\t\t\tData: &internal.Metric_Gauge{\n\t\t\t\t\t\t\t\t\tGauge: &internal.Gauge{\n\t\t\t\t\t\t\t\t\t\tDataPoints: []*internal.NumberDataPoint{\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tAttributes: []internal.KeyValue{\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tKey:   \"k\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tValue: internal.AnyValue{Value: &internal.AnyValue_StringValue{StringValue: \"v\"}},\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\tStartTimeUnixNano: startTime + 1,\n\t\t\t\t\t\t\t\t\t\t\t\tTimeUnixNano:      endTime + 1,\n\t\t\t\t\t\t\t\t\t\t\t\tValue: &internal.NumberDataPoint_AsDouble{\n\t\t\t\t\t\t\t\t\t\t\t\t\tAsDouble: 124.1,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, md.getOrig())\n}\n\nfunc TestOtlpToFromInternalSumMutating(t *testing.T) {\n\tnewAttributes := map[string]any{\"k\": \"v\"}\n\n\tmd := newMetrics(&internal.ExportMetricsServiceRequest{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tResource: generateTestProtoResource(),\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{\n\t\t\t\t\t{\n\t\t\t\t\t\tScope:   generateTestProtoInstrumentationScope(),\n\t\t\t\t\t\tMetrics: []*internal.Metric{generateTestProtoSumMetric()},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, new(internal.State))\n\tresourceMetrics := md.ResourceMetrics()\n\tmetric := resourceMetrics.At(0).ScopeMetrics().At(0).Metrics().At(0)\n\t// Mutate MetricDescriptor\n\tmetric.SetName(\"new_my_metric_double\")\n\tassert.Equal(t, \"new_my_metric_double\", metric.Name())\n\tmetric.SetDescription(\"My new metric\")\n\tassert.Equal(t, \"My new metric\", metric.Description())\n\tmetric.SetUnit(\"1\")\n\tassert.Equal(t, \"1\", metric.Unit())\n\t// Mutate DataPoints\n\tdsd := metric.Sum()\n\tassert.Equal(t, 2, dsd.DataPoints().Len())\n\tmetric.SetEmptySum().SetAggregationTemporality(AggregationTemporalityCumulative)\n\tdoubleDataPoints := metric.Sum().DataPoints()\n\tdoubleDataPoints.AppendEmpty()\n\tassert.Equal(t, 1, doubleDataPoints.Len())\n\tdoubleDataPoints.At(0).SetStartTimestamp(pcommon.Timestamp(startTime + 1))\n\tassert.EqualValues(t, startTime+1, doubleDataPoints.At(0).StartTimestamp())\n\tdoubleDataPoints.At(0).SetTimestamp(pcommon.Timestamp(endTime + 1))\n\tassert.EqualValues(t, endTime+1, doubleDataPoints.At(0).Timestamp())\n\tdoubleDataPoints.At(0).SetDoubleValue(124.1)\n\tassert.InDelta(t, 124.1, doubleDataPoints.At(0).DoubleValue(), 0.01)\n\tdoubleDataPoints.At(0).Attributes().Remove(\"key0\")\n\tdoubleDataPoints.At(0).Attributes().PutStr(\"k\", \"v\")\n\tassert.Equal(t, newAttributes, doubleDataPoints.At(0).Attributes().AsRaw())\n\n\t// Test that everything is updated.\n\tassert.EqualValues(t, &internal.MetricsData{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tResource: generateTestProtoResource(),\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{\n\t\t\t\t\t{\n\t\t\t\t\t\tScope: generateTestProtoInstrumentationScope(),\n\t\t\t\t\t\tMetrics: []*internal.Metric{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName:        \"new_my_metric_double\",\n\t\t\t\t\t\t\t\tDescription: \"My new metric\",\n\t\t\t\t\t\t\t\tUnit:        \"1\",\n\t\t\t\t\t\t\t\tData: &internal.Metric_Sum{\n\t\t\t\t\t\t\t\t\tSum: &internal.Sum{\n\t\t\t\t\t\t\t\t\t\tAggregationTemporality: internal.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE,\n\t\t\t\t\t\t\t\t\t\tDataPoints: []*internal.NumberDataPoint{\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tAttributes: []internal.KeyValue{\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tKey:   \"k\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tValue: internal.AnyValue{Value: &internal.AnyValue_StringValue{StringValue: \"v\"}},\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\tStartTimeUnixNano: startTime + 1,\n\t\t\t\t\t\t\t\t\t\t\t\tTimeUnixNano:      endTime + 1,\n\t\t\t\t\t\t\t\t\t\t\t\tValue: &internal.NumberDataPoint_AsDouble{\n\t\t\t\t\t\t\t\t\t\t\t\t\tAsDouble: 124.1,\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, md.getOrig())\n}\n\nfunc TestOtlpToFromInternalHistogramMutating(t *testing.T) {\n\tnewAttributes := map[string]any{\"k\": \"v\"}\n\n\tmd := newMetrics(&internal.ExportMetricsServiceRequest{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tResource: generateTestProtoResource(),\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{\n\t\t\t\t\t{\n\t\t\t\t\t\tScope:   generateTestProtoInstrumentationScope(),\n\t\t\t\t\t\tMetrics: []*internal.Metric{generateTestProtoHistogramMetric()},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, new(internal.State))\n\tresourceMetrics := md.ResourceMetrics()\n\tmetric := resourceMetrics.At(0).ScopeMetrics().At(0).Metrics().At(0)\n\t// Mutate MetricDescriptor\n\tmetric.SetName(\"new_my_metric_histogram\")\n\tassert.Equal(t, \"new_my_metric_histogram\", metric.Name())\n\tmetric.SetDescription(\"My new metric\")\n\tassert.Equal(t, \"My new metric\", metric.Description())\n\tmetric.SetUnit(\"1\")\n\tassert.Equal(t, \"1\", metric.Unit())\n\t// Mutate DataPoints\n\tdhd := metric.Histogram()\n\tassert.Equal(t, 2, dhd.DataPoints().Len())\n\tmetric.SetEmptyHistogram().SetAggregationTemporality(AggregationTemporalityDelta)\n\thistogramDataPoints := metric.Histogram().DataPoints()\n\thistogramDataPoints.AppendEmpty()\n\tassert.Equal(t, 1, histogramDataPoints.Len())\n\thistogramDataPoints.At(0).SetStartTimestamp(pcommon.Timestamp(startTime + 1))\n\tassert.EqualValues(t, startTime+1, histogramDataPoints.At(0).StartTimestamp())\n\thistogramDataPoints.At(0).SetTimestamp(pcommon.Timestamp(endTime + 1))\n\tassert.EqualValues(t, endTime+1, histogramDataPoints.At(0).Timestamp())\n\thistogramDataPoints.At(0).Attributes().Remove(\"key0\")\n\thistogramDataPoints.At(0).Attributes().PutStr(\"k\", \"v\")\n\tassert.Equal(t, newAttributes, histogramDataPoints.At(0).Attributes().AsRaw())\n\thistogramDataPoints.At(0).ExplicitBounds().FromRaw([]float64{1})\n\tassert.Equal(t, []float64{1}, histogramDataPoints.At(0).ExplicitBounds().AsRaw())\n\thistogramDataPoints.At(0).BucketCounts().FromRaw([]uint64{21, 32})\n\t// Test that everything is updated.\n\tassert.EqualValues(t, &internal.MetricsData{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tResource: generateTestProtoResource(),\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{\n\t\t\t\t\t{\n\t\t\t\t\t\tScope: generateTestProtoInstrumentationScope(),\n\t\t\t\t\t\tMetrics: []*internal.Metric{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName:        \"new_my_metric_histogram\",\n\t\t\t\t\t\t\t\tDescription: \"My new metric\",\n\t\t\t\t\t\t\t\tUnit:        \"1\",\n\t\t\t\t\t\t\t\tData: &internal.Metric_Histogram{\n\t\t\t\t\t\t\t\t\tHistogram: &internal.Histogram{\n\t\t\t\t\t\t\t\t\t\tAggregationTemporality: internal.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA,\n\t\t\t\t\t\t\t\t\t\tDataPoints: []*internal.HistogramDataPoint{\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tAttributes: []internal.KeyValue{\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tKey:   \"k\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tValue: internal.AnyValue{Value: &internal.AnyValue_StringValue{StringValue: \"v\"}},\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\tStartTimeUnixNano: startTime + 1,\n\t\t\t\t\t\t\t\t\t\t\t\tTimeUnixNano:      endTime + 1,\n\t\t\t\t\t\t\t\t\t\t\t\tBucketCounts:      []uint64{21, 32},\n\t\t\t\t\t\t\t\t\t\t\t\tExplicitBounds:    []float64{1},\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, md.getOrig())\n}\n\nfunc TestOtlpToFromInternalExponentialHistogramMutating(t *testing.T) {\n\tnewAttributes := map[string]any{\"k\": \"v\"}\n\n\tmd := newMetrics(&internal.ExportMetricsServiceRequest{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tResource: generateTestProtoResource(),\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{\n\t\t\t\t\t{\n\t\t\t\t\t\tScope:   generateTestProtoInstrumentationScope(),\n\t\t\t\t\t\tMetrics: []*internal.Metric{generateTestProtoHistogramMetric()},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, new(internal.State))\n\tresourceMetrics := md.ResourceMetrics()\n\tmetric := resourceMetrics.At(0).ScopeMetrics().At(0).Metrics().At(0)\n\t// Mutate MetricDescriptor\n\tmetric.SetName(\"new_my_metric_exponential_histogram\")\n\tassert.Equal(t, \"new_my_metric_exponential_histogram\", metric.Name())\n\tmetric.SetDescription(\"My new metric\")\n\tassert.Equal(t, \"My new metric\", metric.Description())\n\tmetric.SetUnit(\"1\")\n\tassert.Equal(t, \"1\", metric.Unit())\n\t// Mutate DataPoints\n\tdhd := metric.Histogram()\n\tassert.Equal(t, 2, dhd.DataPoints().Len())\n\tmetric.SetEmptyExponentialHistogram().SetAggregationTemporality(AggregationTemporalityDelta)\n\thistogramDataPoints := metric.ExponentialHistogram().DataPoints()\n\thistogramDataPoints.AppendEmpty()\n\tassert.Equal(t, 1, histogramDataPoints.Len())\n\thistogramDataPoints.At(0).SetStartTimestamp(pcommon.Timestamp(startTime + 1))\n\tassert.EqualValues(t, startTime+1, histogramDataPoints.At(0).StartTimestamp())\n\thistogramDataPoints.At(0).SetTimestamp(pcommon.Timestamp(endTime + 1))\n\tassert.EqualValues(t, endTime+1, histogramDataPoints.At(0).Timestamp())\n\thistogramDataPoints.At(0).Attributes().Remove(\"key0\")\n\thistogramDataPoints.At(0).Attributes().PutStr(\"k\", \"v\")\n\tassert.Equal(t, newAttributes, histogramDataPoints.At(0).Attributes().AsRaw())\n\t// Test that everything is updated.\n\tassert.EqualValues(t, &internal.MetricsData{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tResource: generateTestProtoResource(),\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{\n\t\t\t\t\t{\n\t\t\t\t\t\tScope: generateTestProtoInstrumentationScope(),\n\t\t\t\t\t\tMetrics: []*internal.Metric{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tName:        \"new_my_metric_exponential_histogram\",\n\t\t\t\t\t\t\t\tDescription: \"My new metric\",\n\t\t\t\t\t\t\t\tUnit:        \"1\",\n\t\t\t\t\t\t\t\tData: &internal.Metric_ExponentialHistogram{\n\t\t\t\t\t\t\t\t\tExponentialHistogram: &internal.ExponentialHistogram{\n\t\t\t\t\t\t\t\t\t\tAggregationTemporality: internal.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA,\n\t\t\t\t\t\t\t\t\t\tDataPoints: []*internal.ExponentialHistogramDataPoint{\n\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\tAttributes: []internal.KeyValue{\n\t\t\t\t\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tKey:   \"k\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tValue: internal.AnyValue{Value: &internal.AnyValue_StringValue{StringValue: \"v\"}},\n\t\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t\t\tStartTimeUnixNano: startTime + 1,\n\t\t\t\t\t\t\t\t\t\t\t\tTimeUnixNano:      endTime + 1,\n\t\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, md.getOrig())\n}\n\nfunc TestMetricsCopyTo(t *testing.T) {\n\tmd := generateTestMetrics()\n\tmetricsCopy := NewMetrics()\n\tmd.CopyTo(metricsCopy)\n\tassert.Equal(t, md, metricsCopy)\n}\n\nfunc TestReadOnlyMetricsInvalidUsage(t *testing.T) {\n\tmetrics := NewMetrics()\n\tassert.False(t, metrics.IsReadOnly())\n\tres := metrics.ResourceMetrics().AppendEmpty().Resource()\n\tres.Attributes().PutStr(\"k1\", \"v1\")\n\tmetrics.MarkReadOnly()\n\tassert.True(t, metrics.IsReadOnly())\n\tassert.Panics(t, func() { res.Attributes().PutStr(\"k2\", \"v2\") })\n}\n\nfunc BenchmarkOtlpToFromInternal_PassThrough(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\treq := &internal.ExportMetricsServiceRequest{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tResource: generateTestProtoResource(),\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{\n\t\t\t\t\t{\n\t\t\t\t\t\tScope:   generateTestProtoInstrumentationScope(),\n\t\t\t\t\t\tMetrics: []*internal.Metric{generateTestProtoGaugeMetric(), generateTestProtoSumMetric(), generateTestProtoHistogramMetric()},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar state internal.State\n\n\tfor b.Loop() {\n\t\tmd := newMetrics(req, &state)\n\t\tnewReq := md.getOrig()\n\t\tif len(req.ResourceMetrics) != len(newReq.ResourceMetrics) {\n\t\t\tb.Fail()\n\t\t}\n\t}\n}\n\nfunc BenchmarkOtlpToFromInternal_Gauge_MutateOneLabel(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\treq := &internal.ExportMetricsServiceRequest{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tResource: generateTestProtoResource(),\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{\n\t\t\t\t\t{\n\t\t\t\t\t\tScope:   generateTestProtoInstrumentationScope(),\n\t\t\t\t\t\tMetrics: []*internal.Metric{generateTestProtoGaugeMetric()},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar state internal.State\n\n\tfor b.Loop() {\n\t\tmd := newMetrics(req, &state)\n\t\tmd.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Gauge().DataPoints().At(0).Attributes().\n\t\t\tPutStr(\"key0\", \"value2\")\n\t\tnewReq := md.getOrig()\n\t\tif len(req.ResourceMetrics) != len(newReq.ResourceMetrics) {\n\t\t\tb.Fail()\n\t\t}\n\t}\n}\n\nfunc BenchmarkOtlpToFromInternal_Sum_MutateOneLabel(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\treq := &internal.ExportMetricsServiceRequest{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tResource: generateTestProtoResource(),\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{\n\t\t\t\t\t{\n\t\t\t\t\t\tScope:   generateTestProtoInstrumentationScope(),\n\t\t\t\t\t\tMetrics: []*internal.Metric{generateTestProtoSumMetric()},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar state internal.State\n\n\tfor b.Loop() {\n\t\tmd := newMetrics(req, &state)\n\t\tmd.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Sum().DataPoints().At(0).Attributes().\n\t\t\tPutStr(\"key0\", \"value2\")\n\t\tnewReq := md.getOrig()\n\t\tif len(req.ResourceMetrics) != len(newReq.ResourceMetrics) {\n\t\t\tb.Fail()\n\t\t}\n\t}\n}\n\nfunc BenchmarkOtlpToFromInternal_HistogramPoints_MutateOneLabel(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\treq := &internal.ExportMetricsServiceRequest{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tResource: generateTestProtoResource(),\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{\n\t\t\t\t\t{\n\t\t\t\t\t\tScope:   generateTestProtoInstrumentationScope(),\n\t\t\t\t\t\tMetrics: []*internal.Metric{generateTestProtoHistogramMetric()},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tvar state internal.State\n\n\tfor b.Loop() {\n\t\tmd := newMetrics(req, &state)\n\t\tmd.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Histogram().DataPoints().At(0).Attributes().\n\t\t\tPutStr(\"key0\", \"value2\")\n\t\tnewReq := md.getOrig()\n\t\tif len(req.ResourceMetrics) != len(newReq.ResourceMetrics) {\n\t\t\tb.Fail()\n\t\t}\n\t}\n}\n\nfunc generateTestProtoResource() internal.Resource {\n\treturn internal.Resource{\n\t\tAttributes: []internal.KeyValue{\n\t\t\t{\n\t\t\t\tKey:   \"string\",\n\t\t\t\tValue: internal.AnyValue{Value: &internal.AnyValue_StringValue{StringValue: \"string-resource\"}},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc generateTestProtoInstrumentationScope() internal.InstrumentationScope {\n\treturn internal.InstrumentationScope{\n\t\tName:    \"test\",\n\t\tVersion: \"\",\n\t}\n}\n\nfunc generateTestProtoGaugeMetric() *internal.Metric {\n\treturn &internal.Metric{\n\t\tName:        \"my_metric_int\",\n\t\tDescription: \"My metric\",\n\t\tUnit:        \"ms\",\n\t\tData: &internal.Metric_Gauge{\n\t\t\tGauge: &internal.Gauge{\n\t\t\t\tDataPoints: []*internal.NumberDataPoint{\n\t\t\t\t\t{\n\t\t\t\t\t\tAttributes: []internal.KeyValue{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tKey:   \"key0\",\n\t\t\t\t\t\t\t\tValue: internal.AnyValue{Value: &internal.AnyValue_StringValue{StringValue: \"value0\"}},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tStartTimeUnixNano: startTime,\n\t\t\t\t\t\tTimeUnixNano:      endTime,\n\t\t\t\t\t\tValue: &internal.NumberDataPoint_AsDouble{\n\t\t\t\t\t\t\tAsDouble: 123.1,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tAttributes: []internal.KeyValue{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tKey:   \"key1\",\n\t\t\t\t\t\t\t\tValue: internal.AnyValue{Value: &internal.AnyValue_StringValue{StringValue: \"value1\"}},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tStartTimeUnixNano: startTime,\n\t\t\t\t\t\tTimeUnixNano:      endTime,\n\t\t\t\t\t\tValue: &internal.NumberDataPoint_AsDouble{\n\t\t\t\t\t\t\tAsDouble: 456.1,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc generateTestProtoSumMetric() *internal.Metric {\n\treturn &internal.Metric{\n\t\tName:        \"my_metric_double\",\n\t\tDescription: \"My metric\",\n\t\tUnit:        \"ms\",\n\t\tData: &internal.Metric_Sum{\n\t\t\tSum: &internal.Sum{\n\t\t\t\tAggregationTemporality: internal.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE,\n\t\t\t\tDataPoints: []*internal.NumberDataPoint{\n\t\t\t\t\t{\n\t\t\t\t\t\tAttributes: []internal.KeyValue{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tKey:   \"key0\",\n\t\t\t\t\t\t\t\tValue: internal.AnyValue{Value: &internal.AnyValue_StringValue{StringValue: \"value0\"}},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tStartTimeUnixNano: startTime,\n\t\t\t\t\t\tTimeUnixNano:      endTime,\n\t\t\t\t\t\tValue: &internal.NumberDataPoint_AsDouble{\n\t\t\t\t\t\t\tAsDouble: 123.1,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tAttributes: []internal.KeyValue{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tKey:   \"key1\",\n\t\t\t\t\t\t\t\tValue: internal.AnyValue{Value: &internal.AnyValue_StringValue{StringValue: \"value1\"}},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tStartTimeUnixNano: startTime,\n\t\t\t\t\t\tTimeUnixNano:      endTime,\n\t\t\t\t\t\tValue: &internal.NumberDataPoint_AsDouble{\n\t\t\t\t\t\t\tAsDouble: 456.1,\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc generateTestProtoHistogramMetric() *internal.Metric {\n\treturn &internal.Metric{\n\t\tName:        \"my_metric_histogram\",\n\t\tDescription: \"My metric\",\n\t\tUnit:        \"ms\",\n\t\tData: &internal.Metric_Histogram{\n\t\t\tHistogram: &internal.Histogram{\n\t\t\t\tAggregationTemporality: internal.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA,\n\t\t\t\tDataPoints: []*internal.HistogramDataPoint{\n\t\t\t\t\t{\n\t\t\t\t\t\tAttributes: []internal.KeyValue{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tKey:   \"key0\",\n\t\t\t\t\t\t\t\tValue: internal.AnyValue{Value: &internal.AnyValue_StringValue{StringValue: \"value0\"}},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tStartTimeUnixNano: startTime,\n\t\t\t\t\t\tTimeUnixNano:      endTime,\n\t\t\t\t\t\tBucketCounts:      []uint64{10, 15, 1},\n\t\t\t\t\t\tExplicitBounds:    []float64{1, 2},\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\tAttributes: []internal.KeyValue{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tKey:   \"key1\",\n\t\t\t\t\t\t\t\tValue: internal.AnyValue{Value: &internal.AnyValue_StringValue{StringValue: \"value1\"}},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tStartTimeUnixNano: startTime,\n\t\t\t\t\t\tTimeUnixNano:      endTime,\n\t\t\t\t\t\tBucketCounts:      []uint64{10, 1},\n\t\t\t\t\t\tExplicitBounds:    []float64{1},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc generateMetricsEmptyResource() Metrics {\n\treturn newMetrics(&internal.ExportMetricsServiceRequest{\n\t\tResourceMetrics: []*internal.ResourceMetrics{{}},\n\t}, new(internal.State))\n}\n\nfunc generateMetricsEmptyInstrumentation() Metrics {\n\treturn newMetrics(&internal.ExportMetricsServiceRequest{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{{}},\n\t\t\t},\n\t\t},\n\t}, new(internal.State))\n}\n\nfunc generateMetricsEmptyMetrics() Metrics {\n\treturn newMetrics(&internal.ExportMetricsServiceRequest{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{\n\t\t\t\t\t{\n\t\t\t\t\t\tMetrics: []*internal.Metric{{}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, new(internal.State))\n}\n\nfunc generateMetricsEmptyDataPoints() Metrics {\n\treturn newMetrics(&internal.ExportMetricsServiceRequest{\n\t\tResourceMetrics: []*internal.ResourceMetrics{\n\t\t\t{\n\t\t\t\tScopeMetrics: []*internal.ScopeMetrics{\n\t\t\t\t\t{\n\t\t\t\t\t\tMetrics: []*internal.Metric{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tData: &internal.Metric_Gauge{\n\t\t\t\t\t\t\t\t\tGauge: &internal.Gauge{\n\t\t\t\t\t\t\t\t\t\tDataPoints: []*internal.NumberDataPoint{\n\t\t\t\t\t\t\t\t\t\t\t{},\n\t\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, new(internal.State))\n}\n\nfunc BenchmarkMetricsUsage(b *testing.B) {\n\tmd := generateTestMetrics()\n\n\tts := pcommon.NewTimestampFromTime(time.Now())\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tfor i := 0; i < md.ResourceMetrics().Len(); i++ {\n\t\t\trm := md.ResourceMetrics().At(i)\n\t\t\tres := rm.Resource()\n\t\t\tres.Attributes().PutStr(\"foo\", \"bar\")\n\t\t\tv, ok := res.Attributes().Get(\"foo\")\n\t\t\tassert.True(b, ok)\n\t\t\tassert.Equal(b, \"bar\", v.Str())\n\t\t\tv.SetStr(\"new-bar\")\n\t\t\tassert.Equal(b, \"new-bar\", v.Str())\n\t\t\tres.Attributes().Remove(\"foo\")\n\t\t\tfor j := 0; j < rm.ScopeMetrics().Len(); j++ {\n\t\t\t\tsm := rm.ScopeMetrics().At(j)\n\t\t\t\tfor k := 0; k < sm.Metrics().Len(); k++ {\n\t\t\t\t\tm := sm.Metrics().At(k)\n\t\t\t\t\tm.SetName(\"new_metric_name\")\n\t\t\t\t\tassert.Equal(b, \"new_metric_name\", m.Name())\n\t\t\t\t\t// Only process Sum metrics to avoid nil pointer dereference\n\t\t\t\t\tif m.Type() == MetricTypeSum {\n\t\t\t\t\t\tassert.Equal(b, MetricTypeSum, m.Type())\n\t\t\t\t\t\tm.Sum().SetAggregationTemporality(AggregationTemporalityCumulative)\n\t\t\t\t\t\tassert.Equal(b, AggregationTemporalityCumulative, m.Sum().AggregationTemporality())\n\t\t\t\t\t\tm.Sum().SetIsMonotonic(true)\n\t\t\t\t\t\tassert.True(b, m.Sum().IsMonotonic())\n\t\t\t\t\t\tfor l := 0; l < m.Sum().DataPoints().Len(); l++ {\n\t\t\t\t\t\t\tdp := m.Sum().DataPoints().At(l)\n\t\t\t\t\t\t\tdp.SetIntValue(123)\n\t\t\t\t\t\t\tassert.Equal(b, int64(123), dp.IntValue())\n\t\t\t\t\t\t\tassert.Equal(b, NumberDataPointValueTypeInt, dp.ValueType())\n\t\t\t\t\t\t\tdp.SetStartTimestamp(ts)\n\t\t\t\t\t\t\tassert.Equal(b, ts, dp.StartTimestamp())\n\t\t\t\t\t\t}\n\t\t\t\t\t\tdp := m.Sum().DataPoints().AppendEmpty()\n\t\t\t\t\t\tdp.Attributes().PutStr(\"foo\", \"bar\")\n\t\t\t\t\t\tdp.SetDoubleValue(123)\n\t\t\t\t\t\tdp.SetStartTimestamp(ts)\n\t\t\t\t\t\tdp.SetTimestamp(ts)\n\t\t\t\t\t\tm.Sum().DataPoints().RemoveIf(func(dp NumberDataPoint) bool {\n\t\t\t\t\t\t\t_, ok := dp.Attributes().Get(\"foo\")\n\t\t\t\t\t\t\treturn ok\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc BenchmarkMetricsMarshalJSON(b *testing.B) {\n\tmd := generateTestMetrics()\n\tencoder := &JSONMarshaler{}\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tjsonBuf, err := encoder.MarshalMetrics(md)\n\t\trequire.NoError(b, err)\n\t\trequire.NotNil(b, jsonBuf)\n\t}\n}\n"
  },
  {
    "path": "pdata/pmetric/number_data_point_value_type.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric // import \"go.opentelemetry.io/collector/pdata/pmetric\"\n\n// NumberDataPointValueType specifies the type of NumberDataPoint value.\ntype NumberDataPointValueType int32\n\nconst (\n\t// NumberDataPointValueTypeEmpty means that data point value is unset.\n\tNumberDataPointValueTypeEmpty NumberDataPointValueType = iota\n\tNumberDataPointValueTypeInt\n\tNumberDataPointValueTypeDouble\n)\n\n// String returns the string representation of the NumberDataPointValueType.\nfunc (nt NumberDataPointValueType) String() string {\n\tswitch nt {\n\tcase NumberDataPointValueTypeEmpty:\n\t\treturn \"Empty\"\n\tcase NumberDataPointValueTypeInt:\n\t\treturn \"Int\"\n\tcase NumberDataPointValueTypeDouble:\n\t\treturn \"Double\"\n\t}\n\treturn \"\"\n}\n"
  },
  {
    "path": "pdata/pmetric/number_data_point_value_type_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric // import \"go.opentelemetry.io/collector/pdata/pmetric\"\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestNumberDataPointValueTypeString(t *testing.T) {\n\tassert.Equal(t, \"Empty\", NumberDataPointValueTypeEmpty.String())\n\tassert.Equal(t, \"Int\", NumberDataPointValueTypeInt.String())\n\tassert.Equal(t, \"Double\", NumberDataPointValueTypeDouble.String())\n\tassert.Empty(t, (NumberDataPointValueTypeDouble + 1).String())\n}\n"
  },
  {
    "path": "pdata/pmetric/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "pdata/pmetric/pb.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric // import \"go.opentelemetry.io/collector/pdata/pmetric\"\n\nvar _ MarshalSizer = (*ProtoMarshaler)(nil)\n\ntype ProtoMarshaler struct{}\n\nfunc (e *ProtoMarshaler) MarshalMetrics(md Metrics) ([]byte, error) {\n\tsize := md.getOrig().SizeProto()\n\tbuf := make([]byte, size)\n\t_ = md.getOrig().MarshalProto(buf)\n\treturn buf, nil\n}\n\nfunc (e *ProtoMarshaler) MetricsSize(md Metrics) int {\n\treturn md.getOrig().SizeProto()\n}\n\nfunc (e *ProtoMarshaler) ResourceMetricsSize(md ResourceMetrics) int {\n\treturn md.orig.SizeProto()\n}\n\nfunc (e *ProtoMarshaler) ScopeMetricsSize(md ScopeMetrics) int {\n\treturn md.orig.SizeProto()\n}\n\nfunc (e *ProtoMarshaler) MetricSize(md Metric) int {\n\treturn md.orig.SizeProto()\n}\n\nfunc (e *ProtoMarshaler) NumberDataPointSize(md NumberDataPoint) int {\n\treturn md.orig.SizeProto()\n}\n\nfunc (e *ProtoMarshaler) SummaryDataPointSize(md SummaryDataPoint) int {\n\treturn md.orig.SizeProto()\n}\n\nfunc (e *ProtoMarshaler) HistogramDataPointSize(md HistogramDataPoint) int {\n\treturn md.orig.SizeProto()\n}\n\nfunc (e *ProtoMarshaler) ExponentialHistogramDataPointSize(md ExponentialHistogramDataPoint) int {\n\treturn md.orig.SizeProto()\n}\n\ntype ProtoUnmarshaler struct{}\n\nfunc (d *ProtoUnmarshaler) UnmarshalMetrics(buf []byte) (Metrics, error) {\n\tmd := NewMetrics()\n\terr := md.getOrig().UnmarshalProto(buf)\n\tif err != nil {\n\t\treturn Metrics{}, err\n\t}\n\treturn md, nil\n}\n"
  },
  {
    "path": "pdata/pmetric/pb_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetric\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpmetrics \"go.opentelemetry.io/proto/slim/otlp/metrics/v1\"\n\tgoproto \"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestMetricsProtoWireCompatibility(t *testing.T) {\n\t// This test verifies that OTLP ProtoBufs generated using goproto lib in\n\t// opentelemetry-proto repository OTLP ProtoBufs generated using gogoproto lib in\n\t// this repository are wire compatible.\n\n\t// Generate Metrics as pdata struct.\n\ttd := generateTestMetrics()\n\n\t// Marshal its underlying ProtoBuf to wire.\n\tmarshaler := &ProtoMarshaler{}\n\twire1, err := marshaler.MarshalMetrics(td)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, wire1)\n\n\t// Unmarshal from the wire to OTLP Protobuf in goproto's representation.\n\tvar goprotoMessage gootlpmetrics.MetricsData\n\terr = goproto.Unmarshal(wire1, &goprotoMessage)\n\trequire.NoError(t, err)\n\n\t// Marshal to the wire again.\n\twire2, err := goproto.Marshal(&goprotoMessage)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, wire2)\n\n\t// Unmarshal from the wire into gogoproto's representation.\n\tvar td2 Metrics\n\tunmarshaler := &ProtoUnmarshaler{}\n\ttd2, err = unmarshaler.UnmarshalMetrics(wire2)\n\trequire.NoError(t, err)\n\n\t// Now compare that the original and final ProtoBuf messages are the same.\n\t// This proves that goproto and gogoproto marshaling/unmarshaling are wire compatible.\n\tassert.Equal(t, td, td2)\n}\n\nfunc TestProtoMetricsUnmarshalerError(t *testing.T) {\n\tp := &ProtoUnmarshaler{}\n\t_, err := p.UnmarshalMetrics([]byte(\"+$%\"))\n\tassert.Error(t, err)\n}\n\nfunc TestProtoSizer(t *testing.T) {\n\tmarshaler := &ProtoMarshaler{}\n\tmd := NewMetrics()\n\tmd.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetName(\"foo\")\n\n\tsize := marshaler.MetricsSize(md)\n\n\tbytes, err := marshaler.MarshalMetrics(md)\n\trequire.NoError(t, err)\n\tassert.Equal(t, len(bytes), size)\n}\n\nfunc TestProtoSizerEmptyMetrics(t *testing.T) {\n\tsizer := &ProtoMarshaler{}\n\tassert.Equal(t, 0, sizer.MetricsSize(NewMetrics()))\n}\n\nfunc BenchmarkMetricsToProto2k(b *testing.B) {\n\tmarshaler := &ProtoMarshaler{}\n\tmetrics := generateBenchmarkMetrics(2_000)\n\n\tfor b.Loop() {\n\t\tbuf, err := marshaler.MarshalMetrics(metrics)\n\t\trequire.NoError(b, err)\n\t\tassert.NotEmpty(b, buf)\n\t}\n}\n\nfunc BenchmarkMetricsFromProto10k(b *testing.B) {\n\tmarshaler := &ProtoMarshaler{}\n\tunmarshaler := &ProtoUnmarshaler{}\n\tbaseMetrics := generateBenchmarkMetrics(2_000)\n\tbuf, err := marshaler.MarshalMetrics(baseMetrics)\n\trequire.NoError(b, err)\n\tassert.NotEmpty(b, buf)\n\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tmetrics, err := unmarshaler.UnmarshalMetrics(buf)\n\t\trequire.NoError(b, err)\n\t\tassert.Equal(b, baseMetrics.ResourceMetrics().Len(), metrics.ResourceMetrics().Len())\n\t}\n}\n\nfunc generateBenchmarkMetrics(metricsCount int) Metrics {\n\tnow := time.Now()\n\tstartTime := pcommon.NewTimestampFromTime(now.Add(-10 * time.Second))\n\tendTime := pcommon.NewTimestampFromTime(now)\n\n\tmd := NewMetrics()\n\tilm := md.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty()\n\tilm.Metrics().EnsureCapacity(metricsCount)\n\tfor range metricsCount {\n\t\tim := ilm.Metrics().AppendEmpty()\n\t\tim.SetName(\"test_name\")\n\t\tidp := im.SetEmptySum().DataPoints().AppendEmpty()\n\t\tidp.SetStartTimestamp(startTime)\n\t\tidp.SetTimestamp(endTime)\n\t\tidp.SetIntValue(123)\n\t}\n\treturn md\n}\n"
  },
  {
    "path": "pdata/pmetric/pmetricotlp/fuzz_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetricotlp // import \"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp\"\n\nimport (\n\t\"testing\"\n)\n\nfunc FuzzRequestUnmarshalJSON(f *testing.F) {\n\tf.Fuzz(func(_ *testing.T, data []byte) {\n\t\ter := NewExportRequest()\n\t\t_ = er.UnmarshalJSON(data)\n\t})\n}\n\nfunc FuzzResponseUnmarshalJSON(f *testing.F) {\n\tf.Fuzz(func(_ *testing.T, data []byte) {\n\t\ter := NewExportResponse()\n\t\t_ = er.UnmarshalJSON(data)\n\t})\n}\n\nfunc FuzzRequestUnmarshalProto(f *testing.F) {\n\tf.Fuzz(func(_ *testing.T, data []byte) {\n\t\ter := NewExportRequest()\n\t\t_ = er.UnmarshalJSON(data)\n\t})\n}\n\nfunc FuzzResponseUnmarshalProto(f *testing.F) {\n\tf.Fuzz(func(_ *testing.T, data []byte) {\n\t\ter := NewExportResponse()\n\t\t_ = er.UnmarshalJSON(data)\n\t})\n}\n"
  },
  {
    "path": "pdata/pmetric/pmetricotlp/generated_exportpartialsuccess.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetricotlp\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ExportPartialSuccess represents the details of a partially successful export request.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewExportPartialSuccess function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ExportPartialSuccess struct {\n\torig  *internal.ExportMetricsPartialSuccess\n\tstate *internal.State\n}\n\nfunc newExportPartialSuccess(orig *internal.ExportMetricsPartialSuccess, state *internal.State) ExportPartialSuccess {\n\treturn ExportPartialSuccess{orig: orig, state: state}\n}\n\n// NewExportPartialSuccess creates a new empty ExportPartialSuccess.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewExportPartialSuccess() ExportPartialSuccess {\n\treturn newExportPartialSuccess(internal.NewExportMetricsPartialSuccess(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ExportPartialSuccess) MoveTo(dest ExportPartialSuccess) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteExportMetricsPartialSuccess(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// RejectedDataPoints returns the rejecteddatapoints associated with this ExportPartialSuccess.\nfunc (ms ExportPartialSuccess) RejectedDataPoints() int64 {\n\treturn ms.orig.RejectedDataPoints\n}\n\n// SetRejectedDataPoints replaces the rejecteddatapoints associated with this ExportPartialSuccess.\nfunc (ms ExportPartialSuccess) SetRejectedDataPoints(v int64) {\n\tms.state.AssertMutable()\n\tms.orig.RejectedDataPoints = v\n}\n\n// ErrorMessage returns the errormessage associated with this ExportPartialSuccess.\nfunc (ms ExportPartialSuccess) ErrorMessage() string {\n\treturn ms.orig.ErrorMessage\n}\n\n// SetErrorMessage replaces the errormessage associated with this ExportPartialSuccess.\nfunc (ms ExportPartialSuccess) SetErrorMessage(v string) {\n\tms.state.AssertMutable()\n\tms.orig.ErrorMessage = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ExportPartialSuccess) CopyTo(dest ExportPartialSuccess) {\n\tdest.state.AssertMutable()\n\tinternal.CopyExportMetricsPartialSuccess(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/pmetricotlp/generated_exportpartialsuccess_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetricotlp\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestExportPartialSuccess_MoveTo(t *testing.T) {\n\tms := generateTestExportPartialSuccess()\n\tdest := NewExportPartialSuccess()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewExportPartialSuccess(), ms)\n\tassert.Equal(t, generateTestExportPartialSuccess(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestExportPartialSuccess(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newExportPartialSuccess(internal.NewExportMetricsPartialSuccess(), sharedState)) })\n\tassert.Panics(t, func() { newExportPartialSuccess(internal.NewExportMetricsPartialSuccess(), sharedState).MoveTo(dest) })\n}\n\nfunc TestExportPartialSuccess_CopyTo(t *testing.T) {\n\tms := NewExportPartialSuccess()\n\torig := NewExportPartialSuccess()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestExportPartialSuccess()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newExportPartialSuccess(internal.NewExportMetricsPartialSuccess(), sharedState)) })\n}\n\nfunc TestExportPartialSuccess_RejectedDataPoints(t *testing.T) {\n\tms := NewExportPartialSuccess()\n\tassert.Equal(t, int64(0), ms.RejectedDataPoints())\n\tms.SetRejectedDataPoints(int64(13))\n\tassert.Equal(t, int64(13), ms.RejectedDataPoints())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewExportPartialSuccess(internal.NewExportMetricsPartialSuccess(), sharedState).SetRejectedDataPoints(int64(13))\n\t})\n}\n\nfunc TestExportPartialSuccess_ErrorMessage(t *testing.T) {\n\tms := NewExportPartialSuccess()\n\tassert.Empty(t, ms.ErrorMessage())\n\tms.SetErrorMessage(\"test_errormessage\")\n\tassert.Equal(t, \"test_errormessage\", ms.ErrorMessage())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewExportPartialSuccess(internal.NewExportMetricsPartialSuccess(), sharedState).SetErrorMessage(\"test_errormessage\")\n\t})\n}\n\nfunc generateTestExportPartialSuccess() ExportPartialSuccess {\n\treturn newExportPartialSuccess(internal.GenTestExportMetricsPartialSuccess(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/pmetricotlp/generated_exportresponse.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetricotlp\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ExportResponse represents the response for gRPC/HTTP client/server.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewExportResponse function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ExportResponse struct {\n\torig  *internal.ExportMetricsServiceResponse\n\tstate *internal.State\n}\n\nfunc newExportResponse(orig *internal.ExportMetricsServiceResponse, state *internal.State) ExportResponse {\n\treturn ExportResponse{orig: orig, state: state}\n}\n\n// NewExportResponse creates a new empty ExportResponse.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewExportResponse() ExportResponse {\n\treturn newExportResponse(internal.NewExportMetricsServiceResponse(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ExportResponse) MoveTo(dest ExportResponse) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteExportMetricsServiceResponse(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// PartialSuccess returns the partialsuccess associated with this ExportResponse.\nfunc (ms ExportResponse) PartialSuccess() ExportPartialSuccess {\n\treturn newExportPartialSuccess(&ms.orig.PartialSuccess, ms.state)\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ExportResponse) CopyTo(dest ExportResponse) {\n\tdest.state.AssertMutable()\n\tinternal.CopyExportMetricsServiceResponse(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pmetric/pmetricotlp/generated_exportresponse_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pmetricotlp\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestExportResponse_MoveTo(t *testing.T) {\n\tms := generateTestExportResponse()\n\tdest := NewExportResponse()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewExportResponse(), ms)\n\tassert.Equal(t, generateTestExportResponse(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestExportResponse(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newExportResponse(internal.NewExportMetricsServiceResponse(), sharedState)) })\n\tassert.Panics(t, func() { newExportResponse(internal.NewExportMetricsServiceResponse(), sharedState).MoveTo(dest) })\n}\n\nfunc TestExportResponse_CopyTo(t *testing.T) {\n\tms := NewExportResponse()\n\torig := NewExportResponse()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestExportResponse()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newExportResponse(internal.NewExportMetricsServiceResponse(), sharedState)) })\n}\n\nfunc TestExportResponse_PartialSuccess(t *testing.T) {\n\tms := NewExportResponse()\n\tassert.Equal(t, NewExportPartialSuccess(), ms.PartialSuccess())\n\tms.orig.PartialSuccess = *internal.GenTestExportMetricsPartialSuccess()\n\tassert.Equal(t, generateTestExportPartialSuccess(), ms.PartialSuccess())\n}\n\nfunc generateTestExportResponse() ExportResponse {\n\treturn newExportResponse(internal.GenTestExportMetricsServiceResponse(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pmetric/pmetricotlp/grpc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetricotlp // import \"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp\"\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otelgrpc\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otlp\"\n)\n\n// GRPCClient is the client API for OTLP-GRPC Metrics service.\n//\n// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.\ntype GRPCClient interface {\n\t// Export pmetric.Metrics to the server.\n\t//\n\t// For performance reasons, it is recommended to keep this RPC\n\t// alive for the entire life of the application.\n\tExport(ctx context.Context, request ExportRequest, opts ...grpc.CallOption) (ExportResponse, error)\n\n\t// unexported disallow implementation of the GRPCClient.\n\tunexported()\n}\n\n// NewGRPCClient returns a new GRPCClient connected using the given connection.\nfunc NewGRPCClient(cc *grpc.ClientConn) GRPCClient {\n\treturn &grpcClient{rawClient: otelgrpc.NewMetricsServiceClient(cc)}\n}\n\ntype grpcClient struct {\n\trawClient otelgrpc.MetricsServiceClient\n}\n\nfunc (c *grpcClient) Export(ctx context.Context, request ExportRequest, opts ...grpc.CallOption) (ExportResponse, error) {\n\trsp, err := c.rawClient.Export(ctx, request.orig, opts...)\n\tif err != nil {\n\t\treturn ExportResponse{}, err\n\t}\n\treturn ExportResponse{orig: rsp, state: internal.NewState()}, err\n}\n\nfunc (c *grpcClient) unexported() {}\n\n// GRPCServer is the server API for OTLP gRPC MetricsService service.\n// Implementations MUST embed UnimplementedGRPCServer.\ntype GRPCServer interface {\n\t// Export is called every time a new request is received.\n\t//\n\t// For performance reasons, it is recommended to keep this RPC\n\t// alive for the entire life of the application.\n\tExport(context.Context, ExportRequest) (ExportResponse, error)\n\n\t// unexported disallow implementation of the GRPCServer.\n\tunexported()\n}\n\nvar _ GRPCServer = (*UnimplementedGRPCServer)(nil)\n\n// UnimplementedGRPCServer MUST be embedded to have forward compatible implementations.\ntype UnimplementedGRPCServer struct{}\n\nfunc (*UnimplementedGRPCServer) Export(context.Context, ExportRequest) (ExportResponse, error) {\n\treturn ExportResponse{}, status.Errorf(codes.Unimplemented, \"method Export not implemented\")\n}\n\nfunc (*UnimplementedGRPCServer) unexported() {}\n\n// RegisterGRPCServer registers the GRPCServer to the grpc.Server.\nfunc RegisterGRPCServer(s *grpc.Server, srv GRPCServer) {\n\totelgrpc.RegisterMetricsServiceServer(s, &rawMetricsServer{srv: srv})\n}\n\ntype rawMetricsServer struct {\n\tsrv GRPCServer\n}\n\nfunc (s rawMetricsServer) Export(ctx context.Context, request *internal.ExportMetricsServiceRequest) (*internal.ExportMetricsServiceResponse, error) {\n\totlp.MigrateMetrics(request.ResourceMetrics)\n\trsp, err := s.srv.Export(ctx, ExportRequest{orig: request, state: internal.NewState()})\n\treturn rsp.orig, err\n}\n"
  },
  {
    "path": "pdata/pmetric/pmetricotlp/grpc_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetricotlp\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/credentials/insecure\"\n\t\"google.golang.org/grpc/resolver\"\n\t\"google.golang.org/grpc/status\"\n\t\"google.golang.org/grpc/test/bufconn\"\n\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\nfunc TestGrpc(t *testing.T) {\n\tlis := bufconn.Listen(1024 * 1024)\n\ts := grpc.NewServer()\n\tRegisterGRPCServer(s, &fakeMetricsServer{t: t})\n\twg := sync.WaitGroup{}\n\twg.Go(func() {\n\t\tassert.NoError(t, s.Serve(lis))\n\t})\n\tt.Cleanup(func() {\n\t\ts.Stop()\n\t\twg.Wait()\n\t})\n\n\tresolver.SetDefaultScheme(\"passthrough\")\n\tcc, err := grpc.NewClient(\"bufnet\",\n\t\tgrpc.WithContextDialer(func(context.Context, string) (net.Conn, error) {\n\t\t\treturn lis.Dial()\n\t\t}),\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, cc.Close())\n\t})\n\n\tlogClient := NewGRPCClient(cc)\n\n\tresp, err := logClient.Export(context.Background(), generateMetricsRequest())\n\trequire.NoError(t, err)\n\tassert.Equal(t, NewExportResponse(), resp)\n}\n\nfunc TestGrpcError(t *testing.T) {\n\tlis := bufconn.Listen(1024 * 1024)\n\ts := grpc.NewServer()\n\tRegisterGRPCServer(s, &fakeMetricsServer{t: t, err: errors.New(\"my error\")})\n\twg := sync.WaitGroup{}\n\twg.Go(func() {\n\t\tassert.NoError(t, s.Serve(lis))\n\t})\n\tt.Cleanup(func() {\n\t\ts.Stop()\n\t\twg.Wait()\n\t})\n\n\tcc, err := grpc.NewClient(\"bufnet\",\n\t\tgrpc.WithContextDialer(func(context.Context, string) (net.Conn, error) {\n\t\t\treturn lis.Dial()\n\t\t}),\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, cc.Close())\n\t})\n\n\tlogClient := NewGRPCClient(cc)\n\tresp, err := logClient.Export(context.Background(), generateMetricsRequest())\n\trequire.Error(t, err)\n\tst, okSt := status.FromError(err)\n\trequire.True(t, okSt)\n\tassert.Equal(t, \"my error\", st.Message())\n\tassert.Equal(t, codes.Unknown, st.Code())\n\tassert.Equal(t, ExportResponse{}, resp)\n}\n\ntype fakeMetricsServer struct {\n\tUnimplementedGRPCServer\n\tt   *testing.T\n\terr error\n}\n\nfunc (f fakeMetricsServer) Export(_ context.Context, request ExportRequest) (ExportResponse, error) {\n\tassert.Equal(f.t, generateMetricsRequest(), request)\n\treturn NewExportResponse(), f.err\n}\n\nfunc generateMetricsRequest() ExportRequest {\n\tmd := pmetric.NewMetrics()\n\tm := md.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\tm.SetName(\"test_metric\")\n\tm.SetEmptyGauge().DataPoints().AppendEmpty()\n\treturn NewExportRequestFromMetrics(md)\n}\n"
  },
  {
    "path": "pdata/pmetric/pmetricotlp/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetricotlp\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "pdata/pmetric/pmetricotlp/request.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetricotlp // import \"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp\"\n\nimport (\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otlp\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\n// ExportRequest represents the request for gRPC/HTTP client/server.\n// It's a wrapper for pmetric.Metrics data.\ntype ExportRequest struct {\n\torig  *internal.ExportMetricsServiceRequest\n\tstate *internal.State\n}\n\n// NewExportRequest returns an empty ExportRequest.\nfunc NewExportRequest() ExportRequest {\n\treturn ExportRequest{\n\t\torig:  &internal.ExportMetricsServiceRequest{},\n\t\tstate: internal.NewState(),\n\t}\n}\n\n// NewExportRequestFromMetrics returns a ExportRequest from pmetric.Metrics.\n// Because ExportRequest is a wrapper for pmetric.Metrics,\n// any changes to the provided Metrics struct will be reflected in the ExportRequest and vice versa.\nfunc NewExportRequestFromMetrics(md pmetric.Metrics) ExportRequest {\n\treturn ExportRequest{\n\t\torig:  internal.GetMetricsOrig(internal.MetricsWrapper(md)),\n\t\tstate: internal.GetMetricsState(internal.MetricsWrapper(md)),\n\t}\n}\n\n// MarshalProto marshals ExportRequest into proto bytes.\nfunc (ms ExportRequest) MarshalProto() ([]byte, error) {\n\tsize := ms.orig.SizeProto()\n\tbuf := make([]byte, size)\n\t_ = ms.orig.MarshalProto(buf)\n\treturn buf, nil\n}\n\n// UnmarshalProto unmarshalls ExportRequest from proto bytes.\nfunc (ms ExportRequest) UnmarshalProto(data []byte) error {\n\terr := ms.orig.UnmarshalProto(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\totlp.MigrateMetrics(ms.orig.ResourceMetrics)\n\treturn nil\n}\n\n// MarshalJSON marshals ExportRequest into JSON bytes.\nfunc (ms ExportRequest) MarshalJSON() ([]byte, error) {\n\tdest := json.BorrowStream(nil)\n\tdefer json.ReturnStream(dest)\n\tms.orig.MarshalJSON(dest)\n\tif dest.Error() != nil {\n\t\treturn nil, dest.Error()\n\t}\n\treturn slices.Clone(dest.Buffer()), nil\n}\n\n// UnmarshalJSON unmarshalls ExportRequest from JSON bytes.\nfunc (ms ExportRequest) UnmarshalJSON(data []byte) error {\n\titer := json.BorrowIterator(data)\n\tdefer json.ReturnIterator(iter)\n\tms.orig.UnmarshalJSON(iter)\n\treturn iter.Error()\n}\n\nfunc (ms ExportRequest) Metrics() pmetric.Metrics {\n\treturn pmetric.Metrics(internal.NewMetricsWrapper(ms.orig, ms.state))\n}\n"
  },
  {
    "path": "pdata/pmetric/pmetricotlp/request_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetricotlp\n\nimport (\n\t\"encoding/json\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcollectormetrics \"go.opentelemetry.io/proto/slim/otlp/collector/metrics/v1\"\n\tgoproto \"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otlp\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\nvar (\n\t_ json.Unmarshaler = ExportRequest{}\n\t_ json.Marshaler   = ExportRequest{}\n)\n\nvar metricsRequestJSON = []byte(`\n\t{\n\t\t\"resourceMetrics\": [\n\t\t\t{\n\t\t\t\t\"resource\": {},\n\t\t\t\t\"scopeMetrics\": [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"scope\": {},\n\t\t\t\t\t\t\"metrics\": [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"name\": \"test_metric\"\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t]\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t}\n\t\t]\n\t}`)\n\nfunc TestRequestToPData(t *testing.T) {\n\ttr := NewExportRequest()\n\tassert.Equal(t, 0, tr.Metrics().MetricCount())\n\ttr.Metrics().ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\tassert.Equal(t, 1, tr.Metrics().MetricCount())\n}\n\nfunc TestRequestJSON(t *testing.T) {\n\tmr := NewExportRequest()\n\trequire.NoError(t, mr.UnmarshalJSON(metricsRequestJSON))\n\tassert.Equal(t, \"test_metric\", mr.Metrics().ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Name())\n\n\tgot, err := mr.MarshalJSON()\n\trequire.NoError(t, err)\n\tassert.Equal(t, strings.Join(strings.Fields(string(metricsRequestJSON)), \"\"), string(got))\n}\n\nfunc TestMetricsProtoWireCompatibility(t *testing.T) {\n\t// This test verifies that OTLP ProtoBufs generated using goproto lib in\n\t// opentelemetry-proto repository OTLP ProtoBufs generated using gogoproto lib in\n\t// this repository are wire compatible.\n\n\t// Generate Metrics as pdata struct.\n\tmd := NewExportRequestFromMetrics(pmetric.Metrics(internal.GenTestMetricsWrapper()))\n\n\t// Marshal its underlying ProtoBuf to wire.\n\twire1, err := md.MarshalProto()\n\trequire.NoError(t, err)\n\tassert.NotNil(t, wire1)\n\n\t// Unmarshal from the wire to OTLP Protobuf in goproto's representation.\n\tvar goprotoMessage gootlpcollectormetrics.ExportMetricsServiceRequest\n\terr = goproto.Unmarshal(wire1, &goprotoMessage)\n\trequire.NoError(t, err)\n\n\t// Marshal to the wire again.\n\twire2, err := goproto.Marshal(&goprotoMessage)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, wire2)\n\n\t// Unmarshal from the wire into gogoproto's representation.\n\tmd2 := NewExportRequest()\n\terr = md2.UnmarshalProto(wire2)\n\trequire.NoError(t, err)\n\n\t// Now compare that the original and final ProtoBuf messages are the same.\n\t// This proves that goproto and gogoproto marshaling/unmarshaling are wire compatible.\n\t// Migration logic will run, so run it on the original message as well.\n\totlp.MigrateMetrics(md.orig.ResourceMetrics)\n\tassert.Equal(t, md, md2)\n}\n"
  },
  {
    "path": "pdata/pmetric/pmetricotlp/response.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetricotlp // import \"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp\"\n\nimport (\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n)\n\n// MarshalProto marshals ExportResponse into proto bytes.\nfunc (ms ExportResponse) MarshalProto() ([]byte, error) {\n\tsize := ms.orig.SizeProto()\n\tbuf := make([]byte, size)\n\t_ = ms.orig.MarshalProto(buf)\n\treturn buf, nil\n}\n\n// UnmarshalProto unmarshalls ExportResponse from proto bytes.\nfunc (ms ExportResponse) UnmarshalProto(data []byte) error {\n\treturn ms.orig.UnmarshalProto(data)\n}\n\n// MarshalJSON marshals ExportResponse into JSON bytes.\nfunc (ms ExportResponse) MarshalJSON() ([]byte, error) {\n\tdest := json.BorrowStream(nil)\n\tdefer json.ReturnStream(dest)\n\tms.orig.MarshalJSON(dest)\n\treturn slices.Clone(dest.Buffer()), dest.Error()\n}\n\n// UnmarshalJSON unmarshalls ExportResponse from JSON bytes.\nfunc (ms ExportResponse) UnmarshalJSON(data []byte) error {\n\titer := json.BorrowIterator(data)\n\tdefer json.ReturnIterator(iter)\n\tms.orig.UnmarshalJSON(iter)\n\treturn iter.Error()\n}\n"
  },
  {
    "path": "pdata/pmetric/pmetricotlp/response_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pmetricotlp\n\nimport (\n\tstdjson \"encoding/json\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar (\n\t_ stdjson.Unmarshaler = ExportResponse{}\n\t_ stdjson.Marshaler   = ExportResponse{}\n)\n\nfunc TestExportResponseJSON(t *testing.T) {\n\tjsonStr := `{\"partialSuccess\": {\"rejectedDataPoints\":\"1\", \"errorMessage\":\"nothing\"}}`\n\tval := NewExportResponse()\n\trequire.NoError(t, val.UnmarshalJSON([]byte(jsonStr)))\n\texpected := NewExportResponse()\n\texpected.PartialSuccess().SetRejectedDataPoints(1)\n\texpected.PartialSuccess().SetErrorMessage(\"nothing\")\n\tassert.Equal(t, expected, val)\n\tbuf, err := val.MarshalJSON()\n\trequire.NoError(t, err)\n\tassert.JSONEq(t, jsonStr, string(buf))\n}\n\nfunc TestUnmarshalJSONExportResponse(t *testing.T) {\n\tjsonStr := `{\"extra\":\"\", \"partialSuccess\": {\"extra\":\"\"}}`\n\tval := NewExportResponse()\n\trequire.NoError(t, val.UnmarshalJSON([]byte(jsonStr)))\n\tassert.Equal(t, NewExportResponse(), val)\n}\n"
  },
  {
    "path": "pdata/pprofile/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "pdata/pprofile/aggregation_temporality.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// AggregationTemporality specifies the method of aggregating metric values,\n// either DELTA (change since last report) or CUMULATIVE (total since a fixed\n// start time).\n//\n// Deprecated: [v0.146.0] Type was removed without replacement in the Profiles signal.\ntype AggregationTemporality int32\n\nconst (\n\t// AggregationTemporalityUnspecified is the default AggregationTemporality, it MUST NOT be used.\n\t//\n\t// Deprecated: [v0.146.0] This is no longer supported by the Profiles signal.\n\tAggregationTemporalityUnspecified = AggregationTemporality(internal.AggregationTemporality_AGGREGATION_TEMPORALITY_UNSPECIFIED)\n\t// AggregationTemporalityDelta is a AggregationTemporality for a metric aggregator which reports changes since last report time.\n\t//\n\t// Deprecated: [v0.146.0] This is no longer supported by the Profiles signal.\n\tAggregationTemporalityDelta = AggregationTemporality(internal.AggregationTemporality_AGGREGATION_TEMPORALITY_DELTA)\n\t// AggregationTemporalityCumulative is a AggregationTemporality for a metric aggregator which reports changes since a fixed start time.\n\t//\n\t// Deprecated: [v0.146.0] This is no longer supported by the Profiles signal.\n\tAggregationTemporalityCumulative = AggregationTemporality(internal.AggregationTemporality_AGGREGATION_TEMPORALITY_CUMULATIVE)\n)\n\n// String returns the string representation of the AggregationTemporality.\n//\n// Deprecated: [v0.146.0] Type was removed without replacement in the Profiles signal.\nfunc (at AggregationTemporality) String() string {\n\tswitch at {\n\tcase AggregationTemporalityUnspecified:\n\t\treturn \"Unspecified\"\n\tcase AggregationTemporalityDelta:\n\t\treturn \"Delta\"\n\tcase AggregationTemporalityCumulative:\n\t\treturn \"Cumulative\"\n\t}\n\treturn \"\"\n}\n"
  },
  {
    "path": "pdata/pprofile/aggregation_temporality_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestAggregationTemporalityString(t *testing.T) {\n\tassert.Equal(t, \"Unspecified\", AggregationTemporalityUnspecified.String())\n\tassert.Equal(t, \"Delta\", AggregationTemporalityDelta.String())\n\tassert.Equal(t, \"Cumulative\", AggregationTemporalityCumulative.String())\n\tassert.Empty(t, (AggregationTemporalityCumulative + 1).String())\n}\n"
  },
  {
    "path": "pdata/pprofile/attributes.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport (\n\t\"errors\"\n\t\"math\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\ntype attributable interface {\n\tAttributeIndices() pcommon.Int32Slice\n}\n\n// FromAttributeIndices builds a [pcommon.Map] containing the attributes of a\n// record.\n// The record can be any struct that implements an `AttributeIndices` method.\n// Updates made to the return map will not be applied back to the record.\nfunc FromAttributeIndices(table KeyValueAndUnitSlice, record attributable, dic ProfilesDictionary) pcommon.Map {\n\tm := pcommon.NewMap()\n\tm.EnsureCapacity(record.AttributeIndices().Len())\n\n\tfor i := 0; i < record.AttributeIndices().Len(); i++ {\n\t\tkv := table.At(int(record.AttributeIndices().At(i)))\n\t\tkey := dic.StringTable().At(int(kv.KeyStrindex()))\n\t\tkv.Value().CopyTo(m.PutEmpty(key))\n\t}\n\n\treturn m\n}\n\nvar errTooManyAttributeTableEntries = errors.New(\"too many entries in AttributeTable\")\n\n// SetAttribute updates an AttributeTable, adding or providing a value and\n// returns its index.\nfunc SetAttribute(table KeyValueAndUnitSlice, attr KeyValueAndUnit) (int32, error) {\n\tfor j, a := range table.All() {\n\t\tif a.Equal(attr) {\n\t\t\tif j > math.MaxInt32 {\n\t\t\t\treturn 0, errTooManyAttributeTableEntries\n\t\t\t}\n\t\t\treturn int32(j), nil\n\t\t}\n\t}\n\n\tif table.Len() >= math.MaxInt32 {\n\t\treturn 0, errTooManyAttributeTableEntries\n\t}\n\n\tattr.CopyTo(table.AppendEmpty())\n\treturn int32(table.Len() - 1), nil\n}\n"
  },
  {
    "path": "pdata/pprofile/attributes_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestFromAttributeIndices(t *testing.T) {\n\tdic := NewProfilesDictionary()\n\tdic.StringTable().Append(\"\")\n\tdic.StringTable().Append(\"hello\")\n\tdic.StringTable().Append(\"bonjour\")\n\n\ttable := NewKeyValueAndUnitSlice()\n\tatt := table.AppendEmpty()\n\tatt.SetKeyStrindex(1)\n\tatt.Value().SetStr(\"world\")\n\tatt2 := table.AppendEmpty()\n\tatt2.SetKeyStrindex(2)\n\tatt2.Value().SetStr(\"monde\")\n\n\tattrs := FromAttributeIndices(table, NewProfile(), dic)\n\tassert.Equal(t, attrs, pcommon.NewMap())\n\n\t// A Location with a single attribute\n\tloc := NewLocation()\n\tloc.AttributeIndices().Append(0)\n\n\tattrs = FromAttributeIndices(table, loc, dic)\n\n\tm := map[string]any{\"hello\": \"world\"}\n\tassert.Equal(t, attrs.AsRaw(), m)\n\n\t// A Mapping with two attributes\n\tmapp := NewLocation()\n\tmapp.AttributeIndices().Append(0, 1)\n\n\tattrs = FromAttributeIndices(table, mapp, dic)\n\n\tm = map[string]any{\"hello\": \"world\", \"bonjour\": \"monde\"}\n\tassert.Equal(t, attrs.AsRaw(), m)\n}\n\nfunc BenchmarkFromAttributeIndices(b *testing.B) {\n\tdic := NewProfilesDictionary()\n\ttable := NewKeyValueAndUnitSlice()\n\n\tfor i := range 10 {\n\t\tdic.StringTable().Append(fmt.Sprintf(\"key_%d\", i))\n\n\t\tatt := table.AppendEmpty()\n\t\tatt.SetKeyStrindex(int32(dic.StringTable().Len()))\n\t\tatt.Value().SetStr(fmt.Sprintf(\"value_%d\", i))\n\t}\n\n\tobj := NewLocation()\n\tobj.AttributeIndices().Append(1, 3, 7)\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\t_ = FromAttributeIndices(table, obj, dic)\n\t}\n}\n\nfunc TestSetAttribute(t *testing.T) {\n\ttable := NewKeyValueAndUnitSlice()\n\tattr := NewKeyValueAndUnit()\n\tattr.SetKeyStrindex(1)\n\tattr.SetUnitStrindex(2)\n\trequire.NoError(t, attr.Value().FromRaw(\"test\"))\n\tattr2 := NewKeyValueAndUnit()\n\tattr2.SetKeyStrindex(3)\n\tattr2.SetUnitStrindex(4)\n\trequire.NoError(t, attr.Value().FromRaw(\"test2\"))\n\n\t// Put a first value\n\tidx, err := SetAttribute(table, attr)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 1, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\n\t// Put the same attribute\n\t// This should be a no-op.\n\tidx, err = SetAttribute(table, attr)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 1, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\n\t// Set a new value\n\t// This sets the index and adds to the table.\n\tidx, err = SetAttribute(table, attr2)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(table.Len()-1), idx)\n\n\t// Set an existing value\n\tidx, err = SetAttribute(table, attr)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\t// Set another existing value\n\tidx, err = SetAttribute(table, attr2)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(table.Len()-1), idx)\n}\n\nfunc BenchmarkSetAttribute(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\tfor _, bb := range []struct {\n\t\tname string\n\t\tattr KeyValueAndUnit\n\n\t\trunBefore func(*testing.B, KeyValueAndUnitSlice)\n\t}{\n\t\t{\n\t\t\tname: \"with a new attribute\",\n\t\t\tattr: NewKeyValueAndUnit(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing attribute\",\n\t\t\tattr: func() KeyValueAndUnit {\n\t\t\t\ta := NewKeyValueAndUnit()\n\t\t\t\ta.SetKeyStrindex(1)\n\t\t\t\treturn a\n\t\t\t}(),\n\n\t\t\trunBefore: func(_ *testing.B, table KeyValueAndUnitSlice) {\n\t\t\t\ta := table.AppendEmpty()\n\t\t\t\ta.SetKeyStrindex(1)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with a duplicate attribute\",\n\t\t\tattr: NewKeyValueAndUnit(),\n\n\t\t\trunBefore: func(_ *testing.B, table KeyValueAndUnitSlice) {\n\t\t\t\t_, err := SetAttribute(table, NewKeyValueAndUnit())\n\t\t\t\trequire.NoError(b, err)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with a hundred locations to loop through\",\n\t\t\tattr: func() KeyValueAndUnit {\n\t\t\t\ta := NewKeyValueAndUnit()\n\t\t\t\ta.SetKeyStrindex(1)\n\t\t\t\treturn a\n\t\t\t}(),\n\n\t\t\trunBefore: func(_ *testing.B, table KeyValueAndUnitSlice) {\n\t\t\t\tfor i := range 100 {\n\t\t\t\t\tl := table.AppendEmpty()\n\t\t\t\t\tl.SetKeyStrindex(int32(i))\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t} {\n\t\tb.Run(bb.name, func(b *testing.B) {\n\t\t\ttable := NewKeyValueAndUnitSlice()\n\n\t\t\tif bb.runBefore != nil {\n\t\t\t\tbb.runBefore(b, table)\n\t\t\t}\n\n\t\t\tb.ResetTimer()\n\t\t\tb.ReportAllocs()\n\n\t\t\tfor b.Loop() {\n\t\t\t\t_, _ = SetAttribute(table, bb.attr)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "pdata/pprofile/dictionary_helpers.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// mapKeyValues returns the underlying KeyValue slice of a pcommon.Map.\nfunc mapKeyValues(m pcommon.Map) []internal.KeyValue {\n\treturn *internal.GetMapOrig(internal.MapWrapper(m))\n}\n\n// resolveProfilesReferences walks through all profiles data after unmarshaling\n// and resolves any string_value_ref and key_ref to their actual string values.\n// This ensures the pdata API works transparently with referenced strings.\nfunc resolveProfilesReferences(profiles Profiles) {\n\tdict := profiles.Dictionary()\n\n\t// Resolve references in resource attributes\n\tfor i := 0; i < profiles.ResourceProfiles().Len(); i++ {\n\t\trp := profiles.ResourceProfiles().At(i)\n\t\tresolveKeyValueReferences(dict, mapKeyValues(rp.Resource().Attributes()))\n\n\t\t// Resolve references in scope attributes\n\t\tfor j := 0; j < rp.ScopeProfiles().Len(); j++ {\n\t\t\tsp := rp.ScopeProfiles().At(j)\n\t\t\tresolveKeyValueReferences(dict, mapKeyValues(sp.Scope().Attributes()))\n\t\t}\n\t}\n}\n\n// resolveKeyValueReferences resolves key_ref and string_value_ref in a KeyValue slice\nfunc resolveKeyValueReferences(dict ProfilesDictionary, kvs []internal.KeyValue) {\n\tfor i := range kvs {\n\t\tkv := &kvs[i]\n\t\t// Resolve key_ref if set\n\t\tif kv.KeyStrindex >= 0 {\n\t\t\tidx := int(kv.KeyStrindex)\n\t\t\tif idx < dict.StringTable().Len() {\n\t\t\t\tkv.Key = dict.StringTable().At(idx)\n\t\t\t\t// N.b. keep KeyStrindex set to optimize re-marshaling. This is\n\t\t\t\t// technically a violation of the proto spec, but acceptable\n\t\t\t\t// for the in-memory pdata API since keys are immutable.\n\t\t\t}\n\t\t}\n\t\t// Resolve string_value_ref if set\n\t\tresolveAnyValueReference(dict, &kv.Value)\n\t}\n}\n\n// resolveAnyValueReference resolves string_value_ref in an AnyValue\nfunc resolveAnyValueReference(dict ProfilesDictionary, anyValue *internal.AnyValue) {\n\tif ref, ok := anyValue.Value.(*internal.AnyValue_StringValueStrindex); ok && ref.StringValueStrindex != 0 {\n\t\tidx := int(ref.StringValueStrindex)\n\t\tif idx >= 0 && idx < dict.StringTable().Len() {\n\t\t\tstr := dict.StringTable().At(idx)\n\t\t\tvar ov *internal.AnyValue_StringValue\n\t\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\t\tov = &internal.AnyValue_StringValue{}\n\t\t\t} else {\n\t\t\t\tov = internal.ProtoPoolAnyValue_StringValue.Get().(*internal.AnyValue_StringValue)\n\t\t\t}\n\t\t\tov.StringValue = str\n\t\t\tanyValue.Value = ov\n\t\t}\n\t} else if kvList, ok := anyValue.Value.(*internal.AnyValue_KvlistValue); ok && kvList.KvlistValue != nil {\n\t\tresolveKeyValueReferences(dict, kvList.KvlistValue.Values)\n\t} else if arrVal, ok := anyValue.Value.(*internal.AnyValue_ArrayValue); ok && arrVal.ArrayValue != nil {\n\t\tfor i := 0; i < len(arrVal.ArrayValue.Values); i++ {\n\t\t\tresolveAnyValueReference(dict, &arrVal.ArrayValue.Values[i])\n\t\t}\n\t}\n}\n\n// convertProfilesToReferences walks through all profiles data before marshaling\n// and converts string values to references for efficient transmission.\n// This builds up the string table in the dictionary and replaces strings with refs.\nfunc convertProfilesToReferences(profiles Profiles) {\n\tdict := profiles.Dictionary()\n\tstringTable := dict.StringTable()\n\n\t// Map for quick string lookups - only allocate if needed\n\tvar stringIndex map[string]int32\n\tgetStringIndex := func(s string) int32 {\n\t\tif stringIndex == nil {\n\t\t\tstringIndex = make(map[string]int32, stringTable.Len())\n\t\t\tfor i := 0; i < stringTable.Len(); i++ {\n\t\t\t\tstringIndex[stringTable.At(i)] = int32(i)\n\t\t\t}\n\t\t}\n\n\t\tif idx, ok := stringIndex[s]; ok {\n\t\t\treturn idx\n\t\t}\n\t\tidx := int32(stringTable.Len())\n\t\tstringTable.Append(s)\n\t\tstringIndex[s] = idx\n\t\treturn idx\n\t}\n\n\t// Convert strings in resource attributes\n\tfor i := 0; i < profiles.ResourceProfiles().Len(); i++ {\n\t\trp := profiles.ResourceProfiles().At(i)\n\t\tconvertKeyValueToReferences(getStringIndex, mapKeyValues(rp.Resource().Attributes()))\n\n\t\t// Convert strings in scope attributes\n\t\tfor j := 0; j < rp.ScopeProfiles().Len(); j++ {\n\t\t\tsp := rp.ScopeProfiles().At(j)\n\t\t\tconvertKeyValueToReferences(getStringIndex, mapKeyValues(sp.Scope().Attributes()))\n\t\t}\n\t}\n}\n\n// convertKeyValueToReferences converts string keys and values to references in a KeyValue slice\nfunc convertKeyValueToReferences(getStringIndex func(string) int32, kvs []internal.KeyValue) {\n\tfor i := range kvs {\n\t\tkv := &kvs[i]\n\n\t\t// Convert key to reference\n\t\tif kv.Key != \"\" && kv.KeyStrindex == 0 {\n\t\t\tkv.KeyStrindex = getStringIndex(kv.Key)\n\t\t\tkv.Key = \"\"\n\t\t}\n\n\t\t// Convert string values to references\n\t\tconvertAnyValueToReference(getStringIndex, &kv.Value)\n\t}\n}\n\n// convertAnyValueToReference converts string values to string_value_ref\nfunc convertAnyValueToReference(getStringIndex func(string) int32, anyValue *internal.AnyValue) {\n\t// Skip if already a reference\n\tif _, ok := anyValue.Value.(*internal.AnyValue_StringValueStrindex); ok {\n\t\treturn\n\t}\n\n\tif strVal, ok := anyValue.Value.(*internal.AnyValue_StringValue); ok && strVal.StringValue != \"\" {\n\t\t// Convert to reference\n\t\tidx := getStringIndex(strVal.StringValue)\n\t\tvar ov *internal.AnyValue_StringValueStrindex\n\t\tif !metadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tov = &internal.AnyValue_StringValueStrindex{}\n\t\t} else {\n\t\t\tov = internal.ProtoPoolAnyValue_StringValueStrindex.Get().(*internal.AnyValue_StringValueStrindex)\n\t\t}\n\t\tov.StringValueStrindex = idx\n\t\tanyValue.Value = ov\n\t} else if kvList, ok := anyValue.Value.(*internal.AnyValue_KvlistValue); ok && kvList.KvlistValue != nil {\n\t\tconvertKeyValueToReferences(getStringIndex, kvList.KvlistValue.Values)\n\t} else if arrVal, ok := anyValue.Value.(*internal.AnyValue_ArrayValue); ok && arrVal.ArrayValue != nil {\n\t\t// Recursively convert arrays\n\t\tfor i := 0; i < len(arrVal.ArrayValue.Values); i++ {\n\t\t\tconvertAnyValueToReference(getStringIndex, &arrVal.ArrayValue.Values[i])\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "pdata/pprofile/dictionary_helpers_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\nfunc TestResolveProfilesReferencesEmpty(t *testing.T) {\n\tprofiles := NewProfiles()\n\t// Should not panic on empty profiles\n\tresolveProfilesReferences(profiles)\n\tassert.Equal(t, 0, profiles.ResourceProfiles().Len())\n}\n\nfunc TestResolveProfilesReferencesWithKeyRef(t *testing.T) {\n\tprofiles := NewProfiles()\n\tdict := profiles.Dictionary()\n\tdict.StringTable().Append(\"\") // index 0\n\tdict.StringTable().Append(\"test-key\")\n\tdict.StringTable().Append(\"test-value\")\n\n\trp := profiles.ResourceProfiles().AppendEmpty()\n\tattrs := rp.Resource().Attributes()\n\n\t// Manually create a KeyValue with key_ref\n\tmapOrig := internal.GetMapOrig(internal.MapWrapper(attrs))\n\t*mapOrig = append(*mapOrig, internal.KeyValue{\n\t\tKeyStrindex: 1, // references \"test-key\"\n\t\tValue: internal.AnyValue{\n\t\t\tValue: &internal.AnyValue_StringValueStrindex{\n\t\t\t\tStringValueStrindex: 2, // references \"test-value\"\n\t\t\t},\n\t\t},\n\t})\n\n\tresolveProfilesReferences(profiles)\n\n\t// Verify key_ref was resolved\n\tkv := &(*mapOrig)[0]\n\tassert.Equal(t, \"test-key\", kv.Key)\n\n\t// Verify string_value_ref was resolved\n\tstrVal, ok := kv.Value.Value.(*internal.AnyValue_StringValue)\n\tassert.True(t, ok)\n\tassert.Equal(t, \"test-value\", strVal.StringValue)\n}\n\nfunc TestResolveProfilesReferencesInvalidIndices(t *testing.T) {\n\tprofiles := NewProfiles()\n\tdict := profiles.Dictionary()\n\tdict.StringTable().Append(\"\") // index 0\n\tdict.StringTable().Append(\"valid\")\n\n\trp := profiles.ResourceProfiles().AppendEmpty()\n\tattrs := rp.Resource().Attributes()\n\n\tmapOrig := internal.GetMapOrig(internal.MapWrapper(attrs))\n\t*mapOrig = append(*mapOrig, internal.KeyValue{\n\t\tKey:         \"fallback-key\",\n\t\tKeyStrindex: 999, // invalid index\n\t\tValue: internal.AnyValue{\n\t\t\tValue: &internal.AnyValue_StringValueStrindex{\n\t\t\t\tStringValueStrindex: 999, // invalid index\n\t\t\t},\n\t\t},\n\t})\n\n\tresolveProfilesReferences(profiles)\n\n\t// Key should remain unchanged since ref is invalid\n\tkv := &(*mapOrig)[0]\n\tassert.Equal(t, \"fallback-key\", kv.Key)\n\n\t// Value should remain as StringValueStrindex since index is invalid\n\t_, ok := kv.Value.Value.(*internal.AnyValue_StringValueStrindex)\n\tassert.True(t, ok)\n}\n\nfunc TestResolveAnyValueReferenceWithPooling(t *testing.T) {\n\t// Test with pooling enabled\n\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), true))\n\tdefer func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t}()\n\n\tprofiles := NewProfiles()\n\tdict := profiles.Dictionary()\n\tdict.StringTable().Append(\"\")\n\tdict.StringTable().Append(\"pooled-value\")\n\n\tanyVal := &internal.AnyValue{\n\t\tValue: &internal.AnyValue_StringValueStrindex{\n\t\t\tStringValueStrindex: 1,\n\t\t},\n\t}\n\n\tresolveAnyValueReference(dict, anyVal)\n\n\tstrVal, ok := anyVal.Value.(*internal.AnyValue_StringValue)\n\tassert.True(t, ok)\n\tassert.Equal(t, \"pooled-value\", strVal.StringValue)\n}\n\nfunc TestResolveAnyValueReferenceNestedKvList(t *testing.T) {\n\tprofiles := NewProfiles()\n\tdict := profiles.Dictionary()\n\tdict.StringTable().Append(\"\")\n\tdict.StringTable().Append(\"nested-key\")\n\tdict.StringTable().Append(\"nested-value\")\n\n\tkvList := &internal.KeyValueList{\n\t\tValues: []internal.KeyValue{\n\t\t\t{\n\t\t\t\tKeyStrindex: 1, // references \"nested-key\"\n\t\t\t\tValue: internal.AnyValue{\n\t\t\t\t\tValue: &internal.AnyValue_StringValueStrindex{\n\t\t\t\t\t\tStringValueStrindex: 2, // references \"nested-value\"\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tanyVal := &internal.AnyValue{\n\t\tValue: &internal.AnyValue_KvlistValue{\n\t\t\tKvlistValue: kvList,\n\t\t},\n\t}\n\n\tresolveAnyValueReference(dict, anyVal)\n\n\t// Verify nested key_ref was resolved\n\tassert.Equal(t, \"nested-key\", kvList.Values[0].Key)\n\n\t// Verify nested value was resolved\n\tstrVal, ok := kvList.Values[0].Value.Value.(*internal.AnyValue_StringValue)\n\tassert.True(t, ok)\n\tassert.Equal(t, \"nested-value\", strVal.StringValue)\n}\n\nfunc TestResolveAnyValueReferenceNestedArray(t *testing.T) {\n\tprofiles := NewProfiles()\n\tdict := profiles.Dictionary()\n\tdict.StringTable().Append(\"\")\n\tdict.StringTable().Append(\"array-item-1\")\n\tdict.StringTable().Append(\"array-item-2\")\n\n\tarrVal := &internal.ArrayValue{\n\t\tValues: []internal.AnyValue{\n\t\t\t{\n\t\t\t\tValue: &internal.AnyValue_StringValueStrindex{\n\t\t\t\t\tStringValueStrindex: 1,\n\t\t\t\t},\n\t\t\t},\n\t\t\t{\n\t\t\t\tValue: &internal.AnyValue_StringValueStrindex{\n\t\t\t\t\tStringValueStrindex: 2,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tanyVal := &internal.AnyValue{\n\t\tValue: &internal.AnyValue_ArrayValue{\n\t\t\tArrayValue: arrVal,\n\t\t},\n\t}\n\n\tresolveAnyValueReference(dict, anyVal)\n\n\t// Verify both array items were resolved\n\tstrVal1, ok := arrVal.Values[0].Value.(*internal.AnyValue_StringValue)\n\tassert.True(t, ok)\n\tassert.Equal(t, \"array-item-1\", strVal1.StringValue)\n\n\tstrVal2, ok := arrVal.Values[1].Value.(*internal.AnyValue_StringValue)\n\tassert.True(t, ok)\n\tassert.Equal(t, \"array-item-2\", strVal2.StringValue)\n}\n\nfunc TestConvertProfilesToReferencesEmpty(t *testing.T) {\n\tprofiles := NewProfiles()\n\tdict := profiles.Dictionary()\n\tdict.StringTable().Append(\"\")\n\n\tconvertProfilesToReferences(profiles)\n\n\t// Should only have the initial empty string\n\tassert.Equal(t, 1, dict.StringTable().Len())\n}\n\nfunc TestConvertProfilesToReferencesDeduplication(t *testing.T) {\n\tprofiles := NewProfiles()\n\tdict := profiles.Dictionary()\n\tdict.StringTable().Append(\"\")\n\n\trp := profiles.ResourceProfiles().AppendEmpty()\n\trp.Resource().Attributes().PutStr(\"key1\", \"duplicated-value\")\n\trp.Resource().Attributes().PutStr(\"key2\", \"duplicated-value\")\n\trp.Resource().Attributes().PutStr(\"key3\", \"unique-value\")\n\n\tconvertProfilesToReferences(profiles)\n\n\t// Should have: \"\", \"key1\", \"duplicated-value\", \"key2\", \"key3\", \"unique-value\"\n\t// But key1, key2, key3 might share indices if they're also deduplicated\n\t// At minimum: \"\", \"key1\", \"duplicated-value\", \"key2\", \"key3\", \"unique-value\" = 6\n\tassert.GreaterOrEqual(t, dict.StringTable().Len(), 5)\n\n\t// Verify references were created\n\tmapOrig := internal.GetMapOrig(internal.MapWrapper(rp.Resource().Attributes()))\n\tfor i := 0; i < len(*mapOrig); i++ {\n\t\tkv := &(*mapOrig)[i]\n\t\tassert.NotEqual(t, int32(0), kv.KeyStrindex, \"Key should have a reference\")\n\n\t\t// Values should be converted to StringValueStrindex\n\t\t_, ok := kv.Value.Value.(*internal.AnyValue_StringValueStrindex)\n\t\tassert.True(t, ok, \"Value should be converted to StringValueStrindex\")\n\t}\n}\n\nfunc TestConvertAnyValueToReferenceWithPooling(t *testing.T) {\n\tprevPooling := metadata.PdataUseProtoPoolingFeatureGate.IsEnabled()\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), true))\n\tdefer func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.PdataUseProtoPoolingFeatureGate.ID(), prevPooling))\n\t}()\n\n\tstringIndex := make(map[string]int32)\n\tstringIndex[\"test-value\"] = 5\n\n\tgetStringIndex := func(s string) int32 {\n\t\tif idx, ok := stringIndex[s]; ok {\n\t\t\treturn idx\n\t\t}\n\t\tidx := int32(len(stringIndex))\n\t\tstringIndex[s] = idx\n\t\treturn idx\n\t}\n\n\tanyVal := &internal.AnyValue{\n\t\tValue: &internal.AnyValue_StringValue{\n\t\t\tStringValue: \"test-value\",\n\t\t},\n\t}\n\n\tconvertAnyValueToReference(getStringIndex, anyVal)\n\n\trefVal, ok := anyVal.Value.(*internal.AnyValue_StringValueStrindex)\n\tassert.True(t, ok)\n\tassert.Equal(t, int32(5), refVal.StringValueStrindex)\n}\n\nfunc TestConvertAnyValueToReferenceEmptyString(t *testing.T) {\n\tstringIndex := make(map[string]int32)\n\tstringIndex[\"\"] = 0\n\n\tgetStringIndex := func(s string) int32 {\n\t\tif idx, ok := stringIndex[s]; ok {\n\t\t\treturn idx\n\t\t}\n\t\tidx := int32(len(stringIndex))\n\t\tstringIndex[s] = idx\n\t\treturn idx\n\t}\n\n\tanyVal := &internal.AnyValue{\n\t\tValue: &internal.AnyValue_StringValue{\n\t\t\tStringValue: \"\", // empty string should not be converted\n\t\t},\n\t}\n\n\tconvertAnyValueToReference(getStringIndex, anyVal)\n\n\t// Empty string should remain as StringValue, not converted to ref\n\t_, ok := anyVal.Value.(*internal.AnyValue_StringValue)\n\tassert.True(t, ok)\n}\n\nfunc TestConvertAnyValueToReferenceNestedKvList(t *testing.T) {\n\tstringIndex := make(map[string]int32)\n\tstringIndex[\"\"] = 0\n\n\tcounter := int32(1)\n\tgetStringIndex := func(s string) int32 {\n\t\tif idx, ok := stringIndex[s]; ok {\n\t\t\treturn idx\n\t\t}\n\t\tidx := counter\n\t\tcounter++\n\t\tstringIndex[s] = idx\n\t\treturn idx\n\t}\n\n\tkvList := &internal.KeyValueList{\n\t\tValues: []internal.KeyValue{\n\t\t\t{\n\t\t\t\tKey: \"nested-key\",\n\t\t\t\tValue: internal.AnyValue{\n\t\t\t\t\tValue: &internal.AnyValue_StringValue{\n\t\t\t\t\t\tStringValue: \"nested-value\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tanyVal := &internal.AnyValue{\n\t\tValue: &internal.AnyValue_KvlistValue{\n\t\t\tKvlistValue: kvList,\n\t\t},\n\t}\n\n\tconvertAnyValueToReference(getStringIndex, anyVal)\n\n\t// Verify nested key was converted\n\tassert.NotEqual(t, int32(0), kvList.Values[0].KeyStrindex)\n\n\t// Verify nested value was converted\n\t_, ok := kvList.Values[0].Value.Value.(*internal.AnyValue_StringValueStrindex)\n\tassert.True(t, ok)\n}\n\nfunc TestConvertAnyValueToReferenceNestedArray(t *testing.T) {\n\tstringIndex := make(map[string]int32)\n\tcounter := int32(0)\n\n\tgetStringIndex := func(s string) int32 {\n\t\tif idx, ok := stringIndex[s]; ok {\n\t\t\treturn idx\n\t\t}\n\t\tidx := counter\n\t\tcounter++\n\t\tstringIndex[s] = idx\n\t\treturn idx\n\t}\n\n\tarrVal := &internal.ArrayValue{\n\t\tValues: []internal.AnyValue{\n\t\t\t{\n\t\t\t\tValue: &internal.AnyValue_StringValue{\n\t\t\t\t\tStringValue: \"array-item\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tanyVal := &internal.AnyValue{\n\t\tValue: &internal.AnyValue_ArrayValue{\n\t\t\tArrayValue: arrVal,\n\t\t},\n\t}\n\n\tconvertAnyValueToReference(getStringIndex, anyVal)\n\n\t// Verify array item was converted\n\t_, ok := arrVal.Values[0].Value.(*internal.AnyValue_StringValueStrindex)\n\tassert.True(t, ok)\n}\n\nfunc TestConvertMapToReferencesEmptyKey(t *testing.T) {\n\tprofiles := NewProfiles()\n\trp := profiles.ResourceProfiles().AppendEmpty()\n\tattrs := rp.Resource().Attributes()\n\n\t// Manually add a KeyValue with empty key\n\tmapOrig := internal.GetMapOrig(internal.MapWrapper(attrs))\n\t*mapOrig = append(*mapOrig, internal.KeyValue{\n\t\tKey: \"\", // empty key should not be converted\n\t\tValue: internal.AnyValue{\n\t\t\tValue: &internal.AnyValue_StringValue{\n\t\t\t\tStringValue: \"value\",\n\t\t\t},\n\t\t},\n\t})\n\n\tgetStringIndex := func(_ string) int32 {\n\t\treturn 1\n\t}\n\n\tconvertKeyValueToReferences(getStringIndex, mapKeyValues(attrs))\n\n\t// Empty key should not have KeyStrindex set\n\tkv := &(*mapOrig)[0]\n\tassert.Equal(t, int32(0), kv.KeyStrindex)\n}\n\nfunc TestConvertMapToReferencesExistingKeyRef(t *testing.T) {\n\tprofiles := NewProfiles()\n\trp := profiles.ResourceProfiles().AppendEmpty()\n\tattrs := rp.Resource().Attributes()\n\n\t// Manually add a KeyValue with existing KeyStrindex\n\tmapOrig := internal.GetMapOrig(internal.MapWrapper(attrs))\n\t*mapOrig = append(*mapOrig, internal.KeyValue{\n\t\tKey:         \"test-key\",\n\t\tKeyStrindex: 5, // already has a ref\n\t\tValue: internal.AnyValue{\n\t\t\tValue: &internal.AnyValue_StringValue{\n\t\t\t\tStringValue: \"value\",\n\t\t\t},\n\t\t},\n\t})\n\n\tgetStringIndex := func(_ string) int32 {\n\t\treturn 99\n\t}\n\n\tconvertKeyValueToReferences(getStringIndex, mapKeyValues(attrs))\n\n\t// KeyStrindex should remain unchanged\n\tkv := &(*mapOrig)[0]\n\tassert.Equal(t, int32(5), kv.KeyStrindex)\n}\n\nfunc TestResolveAnyValueReferenceNonStringTypes(t *testing.T) {\n\tprofiles := NewProfiles()\n\tdict := profiles.Dictionary()\n\tdict.StringTable().Append(\"\")\n\n\t// Test with int value (should not be affected)\n\tanyVal := &internal.AnyValue{\n\t\tValue: &internal.AnyValue_IntValue{\n\t\t\tIntValue: 42,\n\t\t},\n\t}\n\n\tresolveAnyValueReference(dict, anyVal)\n\n\t// Should remain as IntValue\n\tintVal, ok := anyVal.Value.(*internal.AnyValue_IntValue)\n\tassert.True(t, ok)\n\tassert.Equal(t, int64(42), intVal.IntValue)\n}\n\nfunc TestConvertMapToReferencesClearsKey(t *testing.T) {\n\tprofiles := NewProfiles()\n\trp := profiles.ResourceProfiles().AppendEmpty()\n\tattrs := rp.Resource().Attributes()\n\n\tmapOrig := internal.GetMapOrig(internal.MapWrapper(attrs))\n\t*mapOrig = append(*mapOrig, internal.KeyValue{\n\t\tKey: \"my-key\",\n\t\tValue: internal.AnyValue{\n\t\t\tValue: &internal.AnyValue_StringValue{\n\t\t\t\tStringValue: \"my-value\",\n\t\t\t},\n\t\t},\n\t})\n\n\tgetStringIndex := func(s string) int32 {\n\t\tif s == \"my-key\" {\n\t\t\treturn 1\n\t\t}\n\t\treturn 2\n\t}\n\n\tconvertKeyValueToReferences(getStringIndex, mapKeyValues(attrs))\n\n\tkv := &(*mapOrig)[0]\n\t// key_ref should be set\n\tassert.Equal(t, int32(1), kv.KeyStrindex)\n\t// key MUST NOT be set when key_ref is used (per proto spec)\n\tassert.Empty(t, kv.Key, \"Key must be cleared when KeyStrindex is set\")\n}\n\nfunc TestConvertAnyValueToReferenceNestedKvListClearsKey(t *testing.T) {\n\tstringIndex := make(map[string]int32)\n\tcounter := int32(1)\n\tgetStringIndex := func(s string) int32 {\n\t\tif idx, ok := stringIndex[s]; ok {\n\t\t\treturn idx\n\t\t}\n\t\tidx := counter\n\t\tcounter++\n\t\tstringIndex[s] = idx\n\t\treturn idx\n\t}\n\n\tkvList := &internal.KeyValueList{\n\t\tValues: []internal.KeyValue{\n\t\t\t{\n\t\t\t\tKey: \"nested-key\",\n\t\t\t\tValue: internal.AnyValue{\n\t\t\t\t\tValue: &internal.AnyValue_StringValue{\n\t\t\t\t\t\tStringValue: \"nested-value\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\n\tanyVal := &internal.AnyValue{\n\t\tValue: &internal.AnyValue_KvlistValue{\n\t\t\tKvlistValue: kvList,\n\t\t},\n\t}\n\n\tconvertAnyValueToReference(getStringIndex, anyVal)\n\n\t// key_ref should be set\n\tassert.NotEqual(t, int32(0), kvList.Values[0].KeyStrindex)\n\t// key MUST NOT be set when key_ref is used (per proto spec)\n\tassert.Empty(t, kvList.Values[0].Key, \"Key must be cleared when KeyStrindex is set in nested kvlist\")\n}\n\nfunc TestConvertAnyValueToReferenceNonStringTypes(t *testing.T) {\n\tgetStringIndex := func(_ string) int32 {\n\t\treturn 0\n\t}\n\n\t// Test with bool value (should not be affected)\n\tanyVal := &internal.AnyValue{\n\t\tValue: &internal.AnyValue_BoolValue{\n\t\t\tBoolValue: true,\n\t\t},\n\t}\n\n\tconvertAnyValueToReference(getStringIndex, anyVal)\n\n\t// Should remain as BoolValue\n\tboolVal, ok := anyVal.Value.(*internal.AnyValue_BoolValue)\n\tassert.True(t, ok)\n\tassert.True(t, boolVal.BoolValue)\n}\n"
  },
  {
    "path": "pdata/pprofile/encoding.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\n// MarshalSizer is the interface that groups the basic Marshal and Size methods\ntype MarshalSizer interface {\n\tMarshaler\n\tSizer\n}\n\n// Marshaler marshals pprofile.Profiles into bytes.\ntype Marshaler interface {\n\t// MarshalProfiles the given pprofile.Profiles into bytes.\n\t// If the error is not nil, the returned bytes slice cannot be used.\n\tMarshalProfiles(td Profiles) ([]byte, error)\n}\n\n// Unmarshaler unmarshalls bytes into pprofile.Profiles.\ntype Unmarshaler interface {\n\t// UnmarshalProfiles the given bytes into pprofile.Profiles.\n\t// If the error is not nil, the returned pprofile.Profiles cannot be used.\n\tUnmarshalProfiles(buf []byte) (Profiles, error)\n}\n\n// Sizer is an optional interface implemented by the Marshaler,\n// that calculates the size of a marshaled Profiles.\ntype Sizer interface {\n\t// ProfilesSize returns the size in bytes of a marshaled Profiles.\n\tProfilesSize(td Profiles) int\n}\n"
  },
  {
    "path": "pdata/pprofile/function.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport \"fmt\"\n\n// Equal checks equality with another Function\nfunc (fn Function) Equal(val Function) bool {\n\treturn fn.NameStrindex() == val.NameStrindex() &&\n\t\tfn.SystemNameStrindex() == val.SystemNameStrindex() &&\n\t\tfn.FilenameStrindex() == val.FilenameStrindex() &&\n\t\tfn.StartLine() == val.StartLine()\n}\n\n// switchDictionary updates the Function, switching its indices from one\n// dictionary to another.\nfunc (fn Function) switchDictionary(src, dst ProfilesDictionary) error {\n\tif fn.NameStrindex() > 0 {\n\t\tif src.StringTable().Len() <= int(fn.NameStrindex()) {\n\t\t\treturn fmt.Errorf(\"invalid name index %d\", fn.NameStrindex())\n\t\t}\n\n\t\tidx, err := SetString(dst.StringTable(), src.StringTable().At(int(fn.NameStrindex())))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't set name: %w\", err)\n\t\t}\n\t\tfn.SetNameStrindex(idx)\n\t}\n\n\tif fn.SystemNameStrindex() > 0 {\n\t\tif src.StringTable().Len() <= int(fn.SystemNameStrindex()) {\n\t\t\treturn fmt.Errorf(\"invalid system name index %d\", fn.SystemNameStrindex())\n\t\t}\n\n\t\tidx, err := SetString(dst.StringTable(), src.StringTable().At(int(fn.SystemNameStrindex())))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't set system name: %w\", err)\n\t\t}\n\t\tfn.SetSystemNameStrindex(idx)\n\t}\n\n\tif fn.FilenameStrindex() > 0 {\n\t\tif src.StringTable().Len() <= int(fn.FilenameStrindex()) {\n\t\t\treturn fmt.Errorf(\"invalid filename index %d\", fn.FilenameStrindex())\n\t\t}\n\n\t\tidx, err := SetString(dst.StringTable(), src.StringTable().At(int(fn.FilenameStrindex())))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't set filename: %w\", err)\n\t\t}\n\t\tfn.SetFilenameStrindex(idx)\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "pdata/pprofile/function_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc TestFunctionEqual(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname string\n\t\torig Function\n\t\tdest Function\n\t\twant bool\n\t}{\n\t\t{\n\t\t\tname: \"empty functions\",\n\t\t\torig: NewFunction(),\n\t\t\tdest: NewFunction(),\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"non-empty identical functions\",\n\t\t\torig: buildFunction(1, 2, 3, 4),\n\t\t\tdest: buildFunction(1, 2, 3, 4),\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"with different name\",\n\t\t\torig: buildFunction(1, 2, 3, 4),\n\t\t\tdest: buildFunction(2, 2, 3, 4),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with different system name\",\n\t\t\torig: buildFunction(1, 2, 3, 4),\n\t\t\tdest: buildFunction(1, 3, 3, 4),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with different file name\",\n\t\t\torig: buildFunction(1, 2, 3, 4),\n\t\t\tdest: buildFunction(1, 2, 4, 4),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with different start line\",\n\t\t\torig: buildFunction(1, 2, 3, 4),\n\t\t\tdest: buildFunction(1, 2, 3, 5),\n\t\t\twant: false,\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif tt.want {\n\t\t\t\tassert.True(t, tt.orig.Equal(tt.dest))\n\t\t\t} else {\n\t\t\t\tassert.False(t, tt.orig.Equal(tt.dest))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestFunctionSwitchDictionary(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname     string\n\t\tfunction Function\n\n\t\tsrc ProfilesDictionary\n\t\tdst ProfilesDictionary\n\n\t\twantFunction   Function\n\t\twantDictionary ProfilesDictionary\n\t\twantErr        error\n\t}{\n\t\t{\n\t\t\tname:     \"with an empty key value and unit\",\n\t\t\tfunction: NewFunction(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantFunction:   NewFunction(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing name\",\n\t\t\tfunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetNameStrindex(1)\n\t\t\t\treturn fn\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\")\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantFunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetNameStrindex(2)\n\t\t\t\treturn fn\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a name index that does not match anything\",\n\t\t\tfunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetNameStrindex(1)\n\t\t\t\treturn fn\n\t\t\t}(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantFunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetNameStrindex(1)\n\t\t\t\treturn fn\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid name index 1\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with a name index equal to the source table length (boundary condition)\",\n\t\t\tfunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetNameStrindex(2) // Index 2 with length 2 (indices 0,1 are valid)\n\t\t\t\treturn fn\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\") // Length 2: indices 0,1 valid\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantFunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetNameStrindex(2)\n\t\t\t\treturn fn\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid name index 2\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing system name\",\n\t\t\tfunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetSystemNameStrindex(1)\n\t\t\t\treturn fn\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\")\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantFunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetSystemNameStrindex(2)\n\t\t\t\treturn fn\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a system name index that does not match anything\",\n\t\t\tfunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetSystemNameStrindex(1)\n\t\t\t\treturn fn\n\t\t\t}(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantFunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetSystemNameStrindex(1)\n\t\t\t\treturn fn\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid system name index 1\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with a system name index equal to the source table length (boundary condition)\",\n\t\t\tfunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetSystemNameStrindex(2)\n\t\t\t\treturn fn\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantFunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetSystemNameStrindex(2)\n\t\t\t\treturn fn\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid system name index 2\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing filename\",\n\t\t\tfunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetFilenameStrindex(1)\n\t\t\t\treturn fn\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\")\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantFunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetFilenameStrindex(2)\n\t\t\t\treturn fn\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a filename index that does not match anything\",\n\t\t\tfunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetFilenameStrindex(1)\n\t\t\t\treturn fn\n\t\t\t}(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantFunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetFilenameStrindex(1)\n\t\t\t\treturn fn\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid filename index 1\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with a filename index equal to the source table length (boundary condition)\",\n\t\t\tfunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetFilenameStrindex(2)\n\t\t\t\treturn fn\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantFunction: func() Function {\n\t\t\t\tfn := NewFunction()\n\t\t\t\tfn.SetFilenameStrindex(2)\n\t\t\t\treturn fn\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid filename index 2\"),\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tfn := tt.function\n\t\t\tdst := tt.dst\n\t\t\terr := fn.switchDictionary(tt.src, dst)\n\n\t\t\tif tt.wantErr == nil {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.Equal(t, tt.wantErr, err)\n\t\t\t}\n\n\t\t\tassert.Equal(t, tt.wantFunction, fn)\n\t\t\tassert.Equal(t, tt.wantDictionary, dst)\n\t\t})\n\t}\n}\n\nfunc BenchmarkFunctionSwitchDictionary(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\n\tfn := NewFunction()\n\tfn.SetNameStrindex(1)\n\tfn.SetSystemNameStrindex(2)\n\n\tsrc := NewProfilesDictionary()\n\tsrc.StringTable().Append(\"\", \"test\", \"foo\")\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tb.StopTimer()\n\t\tdst := NewProfilesDictionary()\n\t\tdst.StringTable().Append(\"\", \"foo\")\n\t\tb.StartTimer()\n\n\t\t_ = fn.switchDictionary(src, dst)\n\t}\n}\n\nfunc buildFunction(name, sName, fileName int32, startLine int64) Function {\n\tf := NewFunction()\n\tf.SetNameStrindex(name)\n\tf.SetSystemNameStrindex(sName)\n\tf.SetFilenameStrindex(fileName)\n\tf.SetStartLine(startLine)\n\treturn f\n}\n"
  },
  {
    "path": "pdata/pprofile/functions.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport (\n\t\"errors\"\n\t\"math\"\n)\n\nvar errTooManyFunctionTableEntries = errors.New(\"too many entries in FunctionTable\")\n\n// SetFunction updates a FunctionTable, adding or providing a value and returns\n// its index.\nfunc SetFunction(table FunctionSlice, fn Function) (int32, error) {\n\tfor j, m := range table.All() {\n\t\tif m.Equal(fn) {\n\t\t\tif j > math.MaxInt32 {\n\t\t\t\treturn 0, errTooManyFunctionTableEntries\n\t\t\t}\n\t\t\treturn int32(j), nil\n\t\t}\n\t}\n\n\tif table.Len() >= math.MaxInt32 {\n\t\treturn 0, errTooManyFunctionTableEntries\n\t}\n\n\tfn.CopyTo(table.AppendEmpty())\n\treturn int32(table.Len() - 1), nil\n}\n"
  },
  {
    "path": "pdata/pprofile/functions_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc TestSetFunction(t *testing.T) {\n\ttable := NewFunctionSlice()\n\tf := NewFunction()\n\tf.SetNameStrindex(1)\n\tf2 := NewFunction()\n\tf2.SetNameStrindex(2)\n\n\t// Put a first function\n\tidx, err := SetFunction(table, f)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 1, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\n\t// Put the same function\n\t// This should be a no-op.\n\tidx, err = SetFunction(table, f)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 1, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\n\t// Set a new function\n\t// This sets the index and adds to the table.\n\tidx, err = SetFunction(table, f2)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(table.Len()-1), idx)\n\n\t// Set an existing function\n\tidx, err = SetFunction(table, f)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\t// Set another existing function\n\tidx, err = SetFunction(table, f2)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(table.Len()-1), idx)\n}\n\nfunc BenchmarkSetFunction(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\tfor _, bb := range []struct {\n\t\tname string\n\t\tfn   Function\n\n\t\trunBefore func(*testing.B, FunctionSlice)\n\t}{\n\t\t{\n\t\t\tname: \"with a new function\",\n\t\t\tfn:   NewFunction(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing function\",\n\t\t\tfn: func() Function {\n\t\t\t\tf := NewFunction()\n\t\t\t\tf.SetNameStrindex(1)\n\t\t\t\treturn f\n\t\t\t}(),\n\n\t\t\trunBefore: func(_ *testing.B, table FunctionSlice) {\n\t\t\t\tf := table.AppendEmpty()\n\t\t\t\tf.SetNameStrindex(1)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with a duplicate function\",\n\t\t\tfn:   NewFunction(),\n\n\t\t\trunBefore: func(b *testing.B, table FunctionSlice) {\n\t\t\t\t_, err := SetFunction(table, NewFunction())\n\t\t\t\trequire.NoError(b, err)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with a hundred functions to loop through\",\n\t\t\tfn: func() Function {\n\t\t\t\tf := NewFunction()\n\t\t\t\tf.SetNameStrindex(1)\n\t\t\t\treturn f\n\t\t\t}(),\n\n\t\t\trunBefore: func(_ *testing.B, table FunctionSlice) {\n\t\t\t\tfor i := range 100 {\n\t\t\t\t\tf := table.AppendEmpty()\n\t\t\t\t\tf.SetNameStrindex(int32(i))\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t} {\n\t\tb.Run(bb.name, func(b *testing.B) {\n\t\t\ttable := NewFunctionSlice()\n\n\t\t\tif bb.runBefore != nil {\n\t\t\t\tbb.runBefore(b, table)\n\t\t\t}\n\n\t\t\tb.ResetTimer()\n\t\t\tb.ReportAllocs()\n\n\t\t\tfor b.Loop() {\n\t\t\t\t_, _ = SetFunction(table, bb.fn)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "pdata/pprofile/fuzz_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar unexpectedBytes = \"expected the same bytes from unmarshaling and marshaling.\"\n\nfunc FuzzUnmarshalProfiles(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\tu1 := &JSONUnmarshaler{}\n\t\tld1, err := u1.UnmarshalProfiles(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tm1 := &JSONMarshaler{}\n\t\tb1, err := m1.MarshalProfiles(ld1)\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\tu2 := &JSONUnmarshaler{}\n\t\tld2, err := u2.UnmarshalProfiles(b1)\n\t\trequire.NoError(t, err, \"failed to unmarshal valid bytes\")\n\t\tm2 := &JSONMarshaler{}\n\t\tb2, err := m2.MarshalProfiles(ld2)\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_function.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// Function describes a function, including its human-readable name, system name, source file, and starting line number in the source.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewFunction function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Function struct {\n\torig  *internal.Function\n\tstate *internal.State\n}\n\nfunc newFunction(orig *internal.Function, state *internal.State) Function {\n\treturn Function{orig: orig, state: state}\n}\n\n// NewFunction creates a new empty Function.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewFunction() Function {\n\treturn newFunction(internal.NewFunction(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Function) MoveTo(dest Function) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteFunction(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// NameStrindex returns the namestrindex associated with this Function.\nfunc (ms Function) NameStrindex() int32 {\n\treturn ms.orig.NameStrindex\n}\n\n// SetNameStrindex replaces the namestrindex associated with this Function.\nfunc (ms Function) SetNameStrindex(v int32) {\n\tms.state.AssertMutable()\n\tms.orig.NameStrindex = v\n}\n\n// SystemNameStrindex returns the systemnamestrindex associated with this Function.\nfunc (ms Function) SystemNameStrindex() int32 {\n\treturn ms.orig.SystemNameStrindex\n}\n\n// SetSystemNameStrindex replaces the systemnamestrindex associated with this Function.\nfunc (ms Function) SetSystemNameStrindex(v int32) {\n\tms.state.AssertMutable()\n\tms.orig.SystemNameStrindex = v\n}\n\n// FilenameStrindex returns the filenamestrindex associated with this Function.\nfunc (ms Function) FilenameStrindex() int32 {\n\treturn ms.orig.FilenameStrindex\n}\n\n// SetFilenameStrindex replaces the filenamestrindex associated with this Function.\nfunc (ms Function) SetFilenameStrindex(v int32) {\n\tms.state.AssertMutable()\n\tms.orig.FilenameStrindex = v\n}\n\n// StartLine returns the startline associated with this Function.\nfunc (ms Function) StartLine() int64 {\n\treturn ms.orig.StartLine\n}\n\n// SetStartLine replaces the startline associated with this Function.\nfunc (ms Function) SetStartLine(v int64) {\n\tms.state.AssertMutable()\n\tms.orig.StartLine = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Function) CopyTo(dest Function) {\n\tdest.state.AssertMutable()\n\tinternal.CopyFunction(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_function_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestFunction_MoveTo(t *testing.T) {\n\tms := generateTestFunction()\n\tdest := NewFunction()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewFunction(), ms)\n\tassert.Equal(t, generateTestFunction(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestFunction(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newFunction(internal.NewFunction(), sharedState)) })\n\tassert.Panics(t, func() { newFunction(internal.NewFunction(), sharedState).MoveTo(dest) })\n}\n\nfunc TestFunction_CopyTo(t *testing.T) {\n\tms := NewFunction()\n\torig := NewFunction()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestFunction()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newFunction(internal.NewFunction(), sharedState)) })\n}\n\nfunc TestFunction_NameStrindex(t *testing.T) {\n\tms := NewFunction()\n\tassert.Equal(t, int32(0), ms.NameStrindex())\n\tms.SetNameStrindex(int32(13))\n\tassert.Equal(t, int32(13), ms.NameStrindex())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newFunction(internal.NewFunction(), sharedState).SetNameStrindex(int32(13)) })\n}\n\nfunc TestFunction_SystemNameStrindex(t *testing.T) {\n\tms := NewFunction()\n\tassert.Equal(t, int32(0), ms.SystemNameStrindex())\n\tms.SetSystemNameStrindex(int32(13))\n\tassert.Equal(t, int32(13), ms.SystemNameStrindex())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newFunction(internal.NewFunction(), sharedState).SetSystemNameStrindex(int32(13)) })\n}\n\nfunc TestFunction_FilenameStrindex(t *testing.T) {\n\tms := NewFunction()\n\tassert.Equal(t, int32(0), ms.FilenameStrindex())\n\tms.SetFilenameStrindex(int32(13))\n\tassert.Equal(t, int32(13), ms.FilenameStrindex())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newFunction(internal.NewFunction(), sharedState).SetFilenameStrindex(int32(13)) })\n}\n\nfunc TestFunction_StartLine(t *testing.T) {\n\tms := NewFunction()\n\tassert.Equal(t, int64(0), ms.StartLine())\n\tms.SetStartLine(int64(13))\n\tassert.Equal(t, int64(13), ms.StartLine())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newFunction(internal.NewFunction(), sharedState).SetStartLine(int64(13)) })\n}\n\nfunc generateTestFunction() Function {\n\treturn newFunction(internal.GenTestFunction(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_functionslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// FunctionSlice logically represents a slice of Function.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewFunctionSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype FunctionSlice struct {\n\torig  *[]*internal.Function\n\tstate *internal.State\n}\n\nfunc newFunctionSlice(orig *[]*internal.Function, state *internal.State) FunctionSlice {\n\treturn FunctionSlice{orig: orig, state: state}\n}\n\n// NewFunctionSlice creates a FunctionSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewFunctionSlice() FunctionSlice {\n\torig := []*internal.Function(nil)\n\treturn newFunctionSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewFunctionSlice()\".\nfunc (es FunctionSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es FunctionSlice) At(i int) Function {\n\treturn newFunction((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es FunctionSlice) All() iter.Seq2[int, Function] {\n\treturn func(yield func(int, Function) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new FunctionSlice can be initialized:\n//\n//\tes := NewFunctionSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es FunctionSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.Function, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty Function.\n// It returns the newly added Function.\nfunc (es FunctionSlice) AppendEmpty() Function {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewFunction())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es FunctionSlice) MoveAndAppendTo(dest FunctionSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es FunctionSlice) RemoveIf(f func(Function) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteFunction((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es FunctionSlice) CopyTo(dest FunctionSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyFunctionPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the Function elements within FunctionSlice given the\n// provided less function so that two instances of FunctionSlice\n// can be compared.\nfunc (es FunctionSlice) Sort(less func(a, b Function) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_functionslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestFunctionSlice(t *testing.T) {\n\tes := NewFunctionSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newFunctionSlice(&[]*internal.Function{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewFunction()\n\ttestVal := generateTestFunction()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestFunction()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestFunctionSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newFunctionSlice(&[]*internal.Function{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewFunctionSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestFunctionSlice_CopyTo(t *testing.T) {\n\tdest := NewFunctionSlice()\n\tsrc := generateTestFunctionSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestFunctionSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestFunctionSlice(), dest)\n}\n\nfunc TestFunctionSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestFunctionSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestFunctionSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestFunctionSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestFunctionSlice(), es)\n}\n\nfunc TestFunctionSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestFunctionSlice()\n\tdest := NewFunctionSlice()\n\tsrc := generateTestFunctionSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestFunctionSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestFunctionSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestFunctionSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestFunctionSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewFunctionSlice()\n\temptySlice.RemoveIf(func(el Function) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestFunctionSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el Function) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestFunctionSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestFunctionSlice()\n\tgot.RemoveIf(func(el Function) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestFunctionSliceAll(t *testing.T) {\n\tms := generateTestFunctionSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestFunctionSlice_Sort(t *testing.T) {\n\tes := generateTestFunctionSlice()\n\tes.Sort(func(a, b Function) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b Function) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestFunctionSlice() FunctionSlice {\n\tms := NewFunctionSlice()\n\t*ms.orig = internal.GenTestFunctionPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_keyvalueandunit.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// KeyValueAndUnit represents a custom 'dictionary native'\n// style of encoding attributes which is more convenient\n// for profiles than opentelemetry.proto.common.v1.KeyValue.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewKeyValueAndUnit function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype KeyValueAndUnit struct {\n\torig  *internal.KeyValueAndUnit\n\tstate *internal.State\n}\n\nfunc newKeyValueAndUnit(orig *internal.KeyValueAndUnit, state *internal.State) KeyValueAndUnit {\n\treturn KeyValueAndUnit{orig: orig, state: state}\n}\n\n// NewKeyValueAndUnit creates a new empty KeyValueAndUnit.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewKeyValueAndUnit() KeyValueAndUnit {\n\treturn newKeyValueAndUnit(internal.NewKeyValueAndUnit(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms KeyValueAndUnit) MoveTo(dest KeyValueAndUnit) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteKeyValueAndUnit(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// KeyStrindex returns the keystrindex associated with this KeyValueAndUnit.\nfunc (ms KeyValueAndUnit) KeyStrindex() int32 {\n\treturn ms.orig.KeyStrindex\n}\n\n// SetKeyStrindex replaces the keystrindex associated with this KeyValueAndUnit.\nfunc (ms KeyValueAndUnit) SetKeyStrindex(v int32) {\n\tms.state.AssertMutable()\n\tms.orig.KeyStrindex = v\n}\n\n// Value returns the value associated with this KeyValueAndUnit.\nfunc (ms KeyValueAndUnit) Value() pcommon.Value {\n\treturn pcommon.Value(internal.NewValueWrapper(&ms.orig.Value, ms.state))\n}\n\n// UnitStrindex returns the unitstrindex associated with this KeyValueAndUnit.\nfunc (ms KeyValueAndUnit) UnitStrindex() int32 {\n\treturn ms.orig.UnitStrindex\n}\n\n// SetUnitStrindex replaces the unitstrindex associated with this KeyValueAndUnit.\nfunc (ms KeyValueAndUnit) SetUnitStrindex(v int32) {\n\tms.state.AssertMutable()\n\tms.orig.UnitStrindex = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms KeyValueAndUnit) CopyTo(dest KeyValueAndUnit) {\n\tdest.state.AssertMutable()\n\tinternal.CopyKeyValueAndUnit(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_keyvalueandunit_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestKeyValueAndUnit_MoveTo(t *testing.T) {\n\tms := generateTestKeyValueAndUnit()\n\tdest := NewKeyValueAndUnit()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewKeyValueAndUnit(), ms)\n\tassert.Equal(t, generateTestKeyValueAndUnit(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestKeyValueAndUnit(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newKeyValueAndUnit(internal.NewKeyValueAndUnit(), sharedState)) })\n\tassert.Panics(t, func() { newKeyValueAndUnit(internal.NewKeyValueAndUnit(), sharedState).MoveTo(dest) })\n}\n\nfunc TestKeyValueAndUnit_CopyTo(t *testing.T) {\n\tms := NewKeyValueAndUnit()\n\torig := NewKeyValueAndUnit()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestKeyValueAndUnit()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newKeyValueAndUnit(internal.NewKeyValueAndUnit(), sharedState)) })\n}\n\nfunc TestKeyValueAndUnit_KeyStrindex(t *testing.T) {\n\tms := NewKeyValueAndUnit()\n\tassert.Equal(t, int32(0), ms.KeyStrindex())\n\tms.SetKeyStrindex(int32(13))\n\tassert.Equal(t, int32(13), ms.KeyStrindex())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newKeyValueAndUnit(internal.NewKeyValueAndUnit(), sharedState).SetKeyStrindex(int32(13)) })\n}\n\nfunc TestKeyValueAndUnit_Value(t *testing.T) {\n\tms := NewKeyValueAndUnit()\n\tassert.Equal(t, pcommon.NewValueEmpty(), ms.Value())\n\tms.orig.Value = *internal.GenTestAnyValue()\n\tassert.Equal(t, pcommon.Value(internal.GenTestValueWrapper()), ms.Value())\n}\n\nfunc TestKeyValueAndUnit_UnitStrindex(t *testing.T) {\n\tms := NewKeyValueAndUnit()\n\tassert.Equal(t, int32(0), ms.UnitStrindex())\n\tms.SetUnitStrindex(int32(13))\n\tassert.Equal(t, int32(13), ms.UnitStrindex())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newKeyValueAndUnit(internal.NewKeyValueAndUnit(), sharedState).SetUnitStrindex(int32(13)) })\n}\n\nfunc generateTestKeyValueAndUnit() KeyValueAndUnit {\n\treturn newKeyValueAndUnit(internal.GenTestKeyValueAndUnit(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_keyvalueandunitslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// KeyValueAndUnitSlice logically represents a slice of KeyValueAndUnit.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewKeyValueAndUnitSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype KeyValueAndUnitSlice struct {\n\torig  *[]*internal.KeyValueAndUnit\n\tstate *internal.State\n}\n\nfunc newKeyValueAndUnitSlice(orig *[]*internal.KeyValueAndUnit, state *internal.State) KeyValueAndUnitSlice {\n\treturn KeyValueAndUnitSlice{orig: orig, state: state}\n}\n\n// NewKeyValueAndUnitSlice creates a KeyValueAndUnitSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewKeyValueAndUnitSlice() KeyValueAndUnitSlice {\n\torig := []*internal.KeyValueAndUnit(nil)\n\treturn newKeyValueAndUnitSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewKeyValueAndUnitSlice()\".\nfunc (es KeyValueAndUnitSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es KeyValueAndUnitSlice) At(i int) KeyValueAndUnit {\n\treturn newKeyValueAndUnit((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es KeyValueAndUnitSlice) All() iter.Seq2[int, KeyValueAndUnit] {\n\treturn func(yield func(int, KeyValueAndUnit) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new KeyValueAndUnitSlice can be initialized:\n//\n//\tes := NewKeyValueAndUnitSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es KeyValueAndUnitSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.KeyValueAndUnit, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty KeyValueAndUnit.\n// It returns the newly added KeyValueAndUnit.\nfunc (es KeyValueAndUnitSlice) AppendEmpty() KeyValueAndUnit {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewKeyValueAndUnit())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es KeyValueAndUnitSlice) MoveAndAppendTo(dest KeyValueAndUnitSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es KeyValueAndUnitSlice) RemoveIf(f func(KeyValueAndUnit) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteKeyValueAndUnit((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es KeyValueAndUnitSlice) CopyTo(dest KeyValueAndUnitSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyKeyValueAndUnitPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the KeyValueAndUnit elements within KeyValueAndUnitSlice given the\n// provided less function so that two instances of KeyValueAndUnitSlice\n// can be compared.\nfunc (es KeyValueAndUnitSlice) Sort(less func(a, b KeyValueAndUnit) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_keyvalueandunitslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestKeyValueAndUnitSlice(t *testing.T) {\n\tes := NewKeyValueAndUnitSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newKeyValueAndUnitSlice(&[]*internal.KeyValueAndUnit{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewKeyValueAndUnit()\n\ttestVal := generateTestKeyValueAndUnit()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestKeyValueAndUnit()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestKeyValueAndUnitSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newKeyValueAndUnitSlice(&[]*internal.KeyValueAndUnit{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewKeyValueAndUnitSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestKeyValueAndUnitSlice_CopyTo(t *testing.T) {\n\tdest := NewKeyValueAndUnitSlice()\n\tsrc := generateTestKeyValueAndUnitSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestKeyValueAndUnitSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestKeyValueAndUnitSlice(), dest)\n}\n\nfunc TestKeyValueAndUnitSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestKeyValueAndUnitSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestKeyValueAndUnitSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestKeyValueAndUnitSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestKeyValueAndUnitSlice(), es)\n}\n\nfunc TestKeyValueAndUnitSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestKeyValueAndUnitSlice()\n\tdest := NewKeyValueAndUnitSlice()\n\tsrc := generateTestKeyValueAndUnitSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestKeyValueAndUnitSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestKeyValueAndUnitSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestKeyValueAndUnitSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestKeyValueAndUnitSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewKeyValueAndUnitSlice()\n\temptySlice.RemoveIf(func(el KeyValueAndUnit) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestKeyValueAndUnitSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el KeyValueAndUnit) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestKeyValueAndUnitSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestKeyValueAndUnitSlice()\n\tgot.RemoveIf(func(el KeyValueAndUnit) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestKeyValueAndUnitSliceAll(t *testing.T) {\n\tms := generateTestKeyValueAndUnitSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestKeyValueAndUnitSlice_Sort(t *testing.T) {\n\tes := generateTestKeyValueAndUnitSlice()\n\tes.Sort(func(a, b KeyValueAndUnit) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b KeyValueAndUnit) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestKeyValueAndUnitSlice() KeyValueAndUnitSlice {\n\tms := NewKeyValueAndUnitSlice()\n\t*ms.orig = internal.GenTestKeyValueAndUnitPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_line.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// Line details a specific line in a source code, linked to a function.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewLine function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Line struct {\n\torig  *internal.Line\n\tstate *internal.State\n}\n\nfunc newLine(orig *internal.Line, state *internal.State) Line {\n\treturn Line{orig: orig, state: state}\n}\n\n// NewLine creates a new empty Line.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewLine() Line {\n\treturn newLine(internal.NewLine(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Line) MoveTo(dest Line) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteLine(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// FunctionIndex returns the functionindex associated with this Line.\nfunc (ms Line) FunctionIndex() int32 {\n\treturn ms.orig.FunctionIndex\n}\n\n// SetFunctionIndex replaces the functionindex associated with this Line.\nfunc (ms Line) SetFunctionIndex(v int32) {\n\tms.state.AssertMutable()\n\tms.orig.FunctionIndex = v\n}\n\n// Line returns the line associated with this Line.\nfunc (ms Line) Line() int64 {\n\treturn ms.orig.Line\n}\n\n// SetLine replaces the line associated with this Line.\nfunc (ms Line) SetLine(v int64) {\n\tms.state.AssertMutable()\n\tms.orig.Line = v\n}\n\n// Column returns the column associated with this Line.\nfunc (ms Line) Column() int64 {\n\treturn ms.orig.Column\n}\n\n// SetColumn replaces the column associated with this Line.\nfunc (ms Line) SetColumn(v int64) {\n\tms.state.AssertMutable()\n\tms.orig.Column = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Line) CopyTo(dest Line) {\n\tdest.state.AssertMutable()\n\tinternal.CopyLine(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_line_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestLine_MoveTo(t *testing.T) {\n\tms := generateTestLine()\n\tdest := NewLine()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewLine(), ms)\n\tassert.Equal(t, generateTestLine(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestLine(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newLine(internal.NewLine(), sharedState)) })\n\tassert.Panics(t, func() { newLine(internal.NewLine(), sharedState).MoveTo(dest) })\n}\n\nfunc TestLine_CopyTo(t *testing.T) {\n\tms := NewLine()\n\torig := NewLine()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestLine()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newLine(internal.NewLine(), sharedState)) })\n}\n\nfunc TestLine_FunctionIndex(t *testing.T) {\n\tms := NewLine()\n\tassert.Equal(t, int32(0), ms.FunctionIndex())\n\tms.SetFunctionIndex(int32(13))\n\tassert.Equal(t, int32(13), ms.FunctionIndex())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newLine(internal.NewLine(), sharedState).SetFunctionIndex(int32(13)) })\n}\n\nfunc TestLine_Line(t *testing.T) {\n\tms := NewLine()\n\tassert.Equal(t, int64(0), ms.Line())\n\tms.SetLine(int64(13))\n\tassert.Equal(t, int64(13), ms.Line())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newLine(internal.NewLine(), sharedState).SetLine(int64(13)) })\n}\n\nfunc TestLine_Column(t *testing.T) {\n\tms := NewLine()\n\tassert.Equal(t, int64(0), ms.Column())\n\tms.SetColumn(int64(13))\n\tassert.Equal(t, int64(13), ms.Column())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newLine(internal.NewLine(), sharedState).SetColumn(int64(13)) })\n}\n\nfunc generateTestLine() Line {\n\treturn newLine(internal.GenTestLine(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_lineslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// LineSlice logically represents a slice of Line.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewLineSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype LineSlice struct {\n\torig  *[]*internal.Line\n\tstate *internal.State\n}\n\nfunc newLineSlice(orig *[]*internal.Line, state *internal.State) LineSlice {\n\treturn LineSlice{orig: orig, state: state}\n}\n\n// NewLineSlice creates a LineSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewLineSlice() LineSlice {\n\torig := []*internal.Line(nil)\n\treturn newLineSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewLineSlice()\".\nfunc (es LineSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es LineSlice) At(i int) Line {\n\treturn newLine((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es LineSlice) All() iter.Seq2[int, Line] {\n\treturn func(yield func(int, Line) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new LineSlice can be initialized:\n//\n//\tes := NewLineSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es LineSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.Line, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty Line.\n// It returns the newly added Line.\nfunc (es LineSlice) AppendEmpty() Line {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewLine())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es LineSlice) MoveAndAppendTo(dest LineSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es LineSlice) RemoveIf(f func(Line) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteLine((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es LineSlice) CopyTo(dest LineSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyLinePtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the Line elements within LineSlice given the\n// provided less function so that two instances of LineSlice\n// can be compared.\nfunc (es LineSlice) Sort(less func(a, b Line) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_lineslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestLineSlice(t *testing.T) {\n\tes := NewLineSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newLineSlice(&[]*internal.Line{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewLine()\n\ttestVal := generateTestLine()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestLine()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestLineSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newLineSlice(&[]*internal.Line{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewLineSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestLineSlice_CopyTo(t *testing.T) {\n\tdest := NewLineSlice()\n\tsrc := generateTestLineSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestLineSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestLineSlice(), dest)\n}\n\nfunc TestLineSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestLineSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestLineSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestLineSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestLineSlice(), es)\n}\n\nfunc TestLineSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestLineSlice()\n\tdest := NewLineSlice()\n\tsrc := generateTestLineSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestLineSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestLineSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestLineSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestLineSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewLineSlice()\n\temptySlice.RemoveIf(func(el Line) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestLineSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el Line) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestLineSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestLineSlice()\n\tgot.RemoveIf(func(el Line) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestLineSliceAll(t *testing.T) {\n\tms := generateTestLineSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestLineSlice_Sort(t *testing.T) {\n\tes := generateTestLineSlice()\n\tes.Sort(func(a, b Line) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b Line) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestLineSlice() LineSlice {\n\tms := NewLineSlice()\n\t*ms.orig = internal.GenTestLinePtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_link.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// Link represents a pointer from a profile Sample to a trace Span.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewLink function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Link struct {\n\torig  *internal.Link\n\tstate *internal.State\n}\n\nfunc newLink(orig *internal.Link, state *internal.State) Link {\n\treturn Link{orig: orig, state: state}\n}\n\n// NewLink creates a new empty Link.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewLink() Link {\n\treturn newLink(internal.NewLink(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Link) MoveTo(dest Link) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteLink(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// TraceID returns the traceid associated with this Link.\nfunc (ms Link) TraceID() pcommon.TraceID {\n\treturn pcommon.TraceID(ms.orig.TraceId)\n}\n\n// SetTraceID replaces the traceid associated with this Link.\nfunc (ms Link) SetTraceID(v pcommon.TraceID) {\n\tms.state.AssertMutable()\n\tms.orig.TraceId = internal.TraceID(v)\n}\n\n// SpanID returns the spanid associated with this Link.\nfunc (ms Link) SpanID() pcommon.SpanID {\n\treturn pcommon.SpanID(ms.orig.SpanId)\n}\n\n// SetSpanID replaces the spanid associated with this Link.\nfunc (ms Link) SetSpanID(v pcommon.SpanID) {\n\tms.state.AssertMutable()\n\tms.orig.SpanId = internal.SpanID(v)\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Link) CopyTo(dest Link) {\n\tdest.state.AssertMutable()\n\tinternal.CopyLink(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_link_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestLink_MoveTo(t *testing.T) {\n\tms := generateTestLink()\n\tdest := NewLink()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewLink(), ms)\n\tassert.Equal(t, generateTestLink(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestLink(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newLink(internal.NewLink(), sharedState)) })\n\tassert.Panics(t, func() { newLink(internal.NewLink(), sharedState).MoveTo(dest) })\n}\n\nfunc TestLink_CopyTo(t *testing.T) {\n\tms := NewLink()\n\torig := NewLink()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestLink()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newLink(internal.NewLink(), sharedState)) })\n}\n\nfunc TestLink_TraceID(t *testing.T) {\n\tms := NewLink()\n\tassert.Equal(t, pcommon.TraceID(internal.TraceID([16]byte{})), ms.TraceID())\n\ttestValTraceID := pcommon.TraceID(internal.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1}))\n\tms.SetTraceID(testValTraceID)\n\tassert.Equal(t, testValTraceID, ms.TraceID())\n}\n\nfunc TestLink_SpanID(t *testing.T) {\n\tms := NewLink()\n\tassert.Equal(t, pcommon.SpanID(internal.SpanID([8]byte{})), ms.SpanID())\n\ttestValSpanID := pcommon.SpanID(internal.SpanID([8]byte{8, 7, 6, 5, 4, 3, 2, 1}))\n\tms.SetSpanID(testValSpanID)\n\tassert.Equal(t, testValSpanID, ms.SpanID())\n}\n\nfunc generateTestLink() Link {\n\treturn newLink(internal.GenTestLink(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_linkslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// LinkSlice logically represents a slice of Link.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewLinkSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype LinkSlice struct {\n\torig  *[]*internal.Link\n\tstate *internal.State\n}\n\nfunc newLinkSlice(orig *[]*internal.Link, state *internal.State) LinkSlice {\n\treturn LinkSlice{orig: orig, state: state}\n}\n\n// NewLinkSlice creates a LinkSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewLinkSlice() LinkSlice {\n\torig := []*internal.Link(nil)\n\treturn newLinkSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewLinkSlice()\".\nfunc (es LinkSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es LinkSlice) At(i int) Link {\n\treturn newLink((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es LinkSlice) All() iter.Seq2[int, Link] {\n\treturn func(yield func(int, Link) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new LinkSlice can be initialized:\n//\n//\tes := NewLinkSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es LinkSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.Link, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty Link.\n// It returns the newly added Link.\nfunc (es LinkSlice) AppendEmpty() Link {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewLink())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es LinkSlice) MoveAndAppendTo(dest LinkSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es LinkSlice) RemoveIf(f func(Link) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteLink((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es LinkSlice) CopyTo(dest LinkSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyLinkPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the Link elements within LinkSlice given the\n// provided less function so that two instances of LinkSlice\n// can be compared.\nfunc (es LinkSlice) Sort(less func(a, b Link) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_linkslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestLinkSlice(t *testing.T) {\n\tes := NewLinkSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newLinkSlice(&[]*internal.Link{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewLink()\n\ttestVal := generateTestLink()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestLink()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestLinkSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newLinkSlice(&[]*internal.Link{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewLinkSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestLinkSlice_CopyTo(t *testing.T) {\n\tdest := NewLinkSlice()\n\tsrc := generateTestLinkSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestLinkSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestLinkSlice(), dest)\n}\n\nfunc TestLinkSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestLinkSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestLinkSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestLinkSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestLinkSlice(), es)\n}\n\nfunc TestLinkSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestLinkSlice()\n\tdest := NewLinkSlice()\n\tsrc := generateTestLinkSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestLinkSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestLinkSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestLinkSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestLinkSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewLinkSlice()\n\temptySlice.RemoveIf(func(el Link) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestLinkSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el Link) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestLinkSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestLinkSlice()\n\tgot.RemoveIf(func(el Link) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestLinkSliceAll(t *testing.T) {\n\tms := generateTestLinkSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestLinkSlice_Sort(t *testing.T) {\n\tes := generateTestLinkSlice()\n\tes.Sort(func(a, b Link) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b Link) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestLinkSlice() LinkSlice {\n\tms := NewLinkSlice()\n\t*ms.orig = internal.GenTestLinkPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_location.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// Location describes function and line table debug information.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewLocation function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Location struct {\n\torig  *internal.Location\n\tstate *internal.State\n}\n\nfunc newLocation(orig *internal.Location, state *internal.State) Location {\n\treturn Location{orig: orig, state: state}\n}\n\n// NewLocation creates a new empty Location.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewLocation() Location {\n\treturn newLocation(internal.NewLocation(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Location) MoveTo(dest Location) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteLocation(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// MappingIndex returns the mappingindex associated with this Location.\nfunc (ms Location) MappingIndex() int32 {\n\treturn ms.orig.MappingIndex\n}\n\n// SetMappingIndex replaces the mappingindex associated with this Location.\nfunc (ms Location) SetMappingIndex(v int32) {\n\tms.state.AssertMutable()\n\tms.orig.MappingIndex = v\n}\n\n// Address returns the address associated with this Location.\nfunc (ms Location) Address() uint64 {\n\treturn ms.orig.Address\n}\n\n// SetAddress replaces the address associated with this Location.\nfunc (ms Location) SetAddress(v uint64) {\n\tms.state.AssertMutable()\n\tms.orig.Address = v\n}\n\n// Lines returns the Lines associated with this Location.\nfunc (ms Location) Lines() LineSlice {\n\treturn newLineSlice(&ms.orig.Lines, ms.state)\n}\n\n// AttributeIndices returns the AttributeIndices associated with this Location.\nfunc (ms Location) AttributeIndices() pcommon.Int32Slice {\n\treturn pcommon.Int32Slice(internal.NewInt32SliceWrapper(&ms.orig.AttributeIndices, ms.state))\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Location) CopyTo(dest Location) {\n\tdest.state.AssertMutable()\n\tinternal.CopyLocation(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_location_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestLocation_MoveTo(t *testing.T) {\n\tms := generateTestLocation()\n\tdest := NewLocation()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewLocation(), ms)\n\tassert.Equal(t, generateTestLocation(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestLocation(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newLocation(internal.NewLocation(), sharedState)) })\n\tassert.Panics(t, func() { newLocation(internal.NewLocation(), sharedState).MoveTo(dest) })\n}\n\nfunc TestLocation_CopyTo(t *testing.T) {\n\tms := NewLocation()\n\torig := NewLocation()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestLocation()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newLocation(internal.NewLocation(), sharedState)) })\n}\n\nfunc TestLocation_MappingIndex(t *testing.T) {\n\tms := NewLocation()\n\tassert.Equal(t, int32(0), ms.MappingIndex())\n\tms.SetMappingIndex(int32(13))\n\tassert.Equal(t, int32(13), ms.MappingIndex())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newLocation(internal.NewLocation(), sharedState).SetMappingIndex(int32(13)) })\n}\n\nfunc TestLocation_Address(t *testing.T) {\n\tms := NewLocation()\n\tassert.Equal(t, uint64(0), ms.Address())\n\tms.SetAddress(uint64(13))\n\tassert.Equal(t, uint64(13), ms.Address())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newLocation(internal.NewLocation(), sharedState).SetAddress(uint64(13)) })\n}\n\nfunc TestLocation_Lines(t *testing.T) {\n\tms := NewLocation()\n\tassert.Equal(t, NewLineSlice(), ms.Lines())\n\tms.orig.Lines = internal.GenTestLinePtrSlice()\n\tassert.Equal(t, generateTestLineSlice(), ms.Lines())\n}\n\nfunc TestLocation_AttributeIndices(t *testing.T) {\n\tms := NewLocation()\n\tassert.Equal(t, pcommon.NewInt32Slice(), ms.AttributeIndices())\n\tms.orig.AttributeIndices = internal.GenTestInt32Slice()\n\tassert.Equal(t, pcommon.Int32Slice(internal.GenTestInt32SliceWrapper()), ms.AttributeIndices())\n}\n\nfunc generateTestLocation() Location {\n\treturn newLocation(internal.GenTestLocation(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_locationslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// LocationSlice logically represents a slice of Location.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewLocationSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype LocationSlice struct {\n\torig  *[]*internal.Location\n\tstate *internal.State\n}\n\nfunc newLocationSlice(orig *[]*internal.Location, state *internal.State) LocationSlice {\n\treturn LocationSlice{orig: orig, state: state}\n}\n\n// NewLocationSlice creates a LocationSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewLocationSlice() LocationSlice {\n\torig := []*internal.Location(nil)\n\treturn newLocationSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewLocationSlice()\".\nfunc (es LocationSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es LocationSlice) At(i int) Location {\n\treturn newLocation((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es LocationSlice) All() iter.Seq2[int, Location] {\n\treturn func(yield func(int, Location) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new LocationSlice can be initialized:\n//\n//\tes := NewLocationSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es LocationSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.Location, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty Location.\n// It returns the newly added Location.\nfunc (es LocationSlice) AppendEmpty() Location {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewLocation())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es LocationSlice) MoveAndAppendTo(dest LocationSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es LocationSlice) RemoveIf(f func(Location) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteLocation((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es LocationSlice) CopyTo(dest LocationSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyLocationPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the Location elements within LocationSlice given the\n// provided less function so that two instances of LocationSlice\n// can be compared.\nfunc (es LocationSlice) Sort(less func(a, b Location) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_locationslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestLocationSlice(t *testing.T) {\n\tes := NewLocationSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newLocationSlice(&[]*internal.Location{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewLocation()\n\ttestVal := generateTestLocation()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestLocation()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestLocationSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newLocationSlice(&[]*internal.Location{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewLocationSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestLocationSlice_CopyTo(t *testing.T) {\n\tdest := NewLocationSlice()\n\tsrc := generateTestLocationSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestLocationSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestLocationSlice(), dest)\n}\n\nfunc TestLocationSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestLocationSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestLocationSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestLocationSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestLocationSlice(), es)\n}\n\nfunc TestLocationSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestLocationSlice()\n\tdest := NewLocationSlice()\n\tsrc := generateTestLocationSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestLocationSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestLocationSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestLocationSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestLocationSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewLocationSlice()\n\temptySlice.RemoveIf(func(el Location) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestLocationSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el Location) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestLocationSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestLocationSlice()\n\tgot.RemoveIf(func(el Location) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestLocationSliceAll(t *testing.T) {\n\tms := generateTestLocationSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestLocationSlice_Sort(t *testing.T) {\n\tes := generateTestLocationSlice()\n\tes.Sort(func(a, b Location) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b Location) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestLocationSlice() LocationSlice {\n\tms := NewLocationSlice()\n\t*ms.orig = internal.GenTestLocationPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_mapping.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// Mapping describes the mapping of a binary in memory, including its address range, file offset, and metadata like build ID\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewMapping function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Mapping struct {\n\torig  *internal.Mapping\n\tstate *internal.State\n}\n\nfunc newMapping(orig *internal.Mapping, state *internal.State) Mapping {\n\treturn Mapping{orig: orig, state: state}\n}\n\n// NewMapping creates a new empty Mapping.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewMapping() Mapping {\n\treturn newMapping(internal.NewMapping(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Mapping) MoveTo(dest Mapping) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteMapping(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// MemoryStart returns the memorystart associated with this Mapping.\nfunc (ms Mapping) MemoryStart() uint64 {\n\treturn ms.orig.MemoryStart\n}\n\n// SetMemoryStart replaces the memorystart associated with this Mapping.\nfunc (ms Mapping) SetMemoryStart(v uint64) {\n\tms.state.AssertMutable()\n\tms.orig.MemoryStart = v\n}\n\n// MemoryLimit returns the memorylimit associated with this Mapping.\nfunc (ms Mapping) MemoryLimit() uint64 {\n\treturn ms.orig.MemoryLimit\n}\n\n// SetMemoryLimit replaces the memorylimit associated with this Mapping.\nfunc (ms Mapping) SetMemoryLimit(v uint64) {\n\tms.state.AssertMutable()\n\tms.orig.MemoryLimit = v\n}\n\n// FileOffset returns the fileoffset associated with this Mapping.\nfunc (ms Mapping) FileOffset() uint64 {\n\treturn ms.orig.FileOffset\n}\n\n// SetFileOffset replaces the fileoffset associated with this Mapping.\nfunc (ms Mapping) SetFileOffset(v uint64) {\n\tms.state.AssertMutable()\n\tms.orig.FileOffset = v\n}\n\n// FilenameStrindex returns the filenamestrindex associated with this Mapping.\nfunc (ms Mapping) FilenameStrindex() int32 {\n\treturn ms.orig.FilenameStrindex\n}\n\n// SetFilenameStrindex replaces the filenamestrindex associated with this Mapping.\nfunc (ms Mapping) SetFilenameStrindex(v int32) {\n\tms.state.AssertMutable()\n\tms.orig.FilenameStrindex = v\n}\n\n// AttributeIndices returns the AttributeIndices associated with this Mapping.\nfunc (ms Mapping) AttributeIndices() pcommon.Int32Slice {\n\treturn pcommon.Int32Slice(internal.NewInt32SliceWrapper(&ms.orig.AttributeIndices, ms.state))\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Mapping) CopyTo(dest Mapping) {\n\tdest.state.AssertMutable()\n\tinternal.CopyMapping(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_mapping_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestMapping_MoveTo(t *testing.T) {\n\tms := generateTestMapping()\n\tdest := NewMapping()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewMapping(), ms)\n\tassert.Equal(t, generateTestMapping(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestMapping(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newMapping(internal.NewMapping(), sharedState)) })\n\tassert.Panics(t, func() { newMapping(internal.NewMapping(), sharedState).MoveTo(dest) })\n}\n\nfunc TestMapping_CopyTo(t *testing.T) {\n\tms := NewMapping()\n\torig := NewMapping()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestMapping()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newMapping(internal.NewMapping(), sharedState)) })\n}\n\nfunc TestMapping_MemoryStart(t *testing.T) {\n\tms := NewMapping()\n\tassert.Equal(t, uint64(0), ms.MemoryStart())\n\tms.SetMemoryStart(uint64(13))\n\tassert.Equal(t, uint64(13), ms.MemoryStart())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newMapping(internal.NewMapping(), sharedState).SetMemoryStart(uint64(13)) })\n}\n\nfunc TestMapping_MemoryLimit(t *testing.T) {\n\tms := NewMapping()\n\tassert.Equal(t, uint64(0), ms.MemoryLimit())\n\tms.SetMemoryLimit(uint64(13))\n\tassert.Equal(t, uint64(13), ms.MemoryLimit())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newMapping(internal.NewMapping(), sharedState).SetMemoryLimit(uint64(13)) })\n}\n\nfunc TestMapping_FileOffset(t *testing.T) {\n\tms := NewMapping()\n\tassert.Equal(t, uint64(0), ms.FileOffset())\n\tms.SetFileOffset(uint64(13))\n\tassert.Equal(t, uint64(13), ms.FileOffset())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newMapping(internal.NewMapping(), sharedState).SetFileOffset(uint64(13)) })\n}\n\nfunc TestMapping_FilenameStrindex(t *testing.T) {\n\tms := NewMapping()\n\tassert.Equal(t, int32(0), ms.FilenameStrindex())\n\tms.SetFilenameStrindex(int32(13))\n\tassert.Equal(t, int32(13), ms.FilenameStrindex())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newMapping(internal.NewMapping(), sharedState).SetFilenameStrindex(int32(13)) })\n}\n\nfunc TestMapping_AttributeIndices(t *testing.T) {\n\tms := NewMapping()\n\tassert.Equal(t, pcommon.NewInt32Slice(), ms.AttributeIndices())\n\tms.orig.AttributeIndices = internal.GenTestInt32Slice()\n\tassert.Equal(t, pcommon.Int32Slice(internal.GenTestInt32SliceWrapper()), ms.AttributeIndices())\n}\n\nfunc generateTestMapping() Mapping {\n\treturn newMapping(internal.GenTestMapping(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_mappingslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// MappingSlice logically represents a slice of Mapping.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewMappingSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype MappingSlice struct {\n\torig  *[]*internal.Mapping\n\tstate *internal.State\n}\n\nfunc newMappingSlice(orig *[]*internal.Mapping, state *internal.State) MappingSlice {\n\treturn MappingSlice{orig: orig, state: state}\n}\n\n// NewMappingSlice creates a MappingSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewMappingSlice() MappingSlice {\n\torig := []*internal.Mapping(nil)\n\treturn newMappingSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewMappingSlice()\".\nfunc (es MappingSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es MappingSlice) At(i int) Mapping {\n\treturn newMapping((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es MappingSlice) All() iter.Seq2[int, Mapping] {\n\treturn func(yield func(int, Mapping) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new MappingSlice can be initialized:\n//\n//\tes := NewMappingSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es MappingSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.Mapping, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty Mapping.\n// It returns the newly added Mapping.\nfunc (es MappingSlice) AppendEmpty() Mapping {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewMapping())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es MappingSlice) MoveAndAppendTo(dest MappingSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es MappingSlice) RemoveIf(f func(Mapping) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteMapping((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es MappingSlice) CopyTo(dest MappingSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyMappingPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the Mapping elements within MappingSlice given the\n// provided less function so that two instances of MappingSlice\n// can be compared.\nfunc (es MappingSlice) Sort(less func(a, b Mapping) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_mappingslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestMappingSlice(t *testing.T) {\n\tes := NewMappingSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newMappingSlice(&[]*internal.Mapping{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewMapping()\n\ttestVal := generateTestMapping()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestMapping()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestMappingSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newMappingSlice(&[]*internal.Mapping{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewMappingSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestMappingSlice_CopyTo(t *testing.T) {\n\tdest := NewMappingSlice()\n\tsrc := generateTestMappingSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestMappingSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestMappingSlice(), dest)\n}\n\nfunc TestMappingSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestMappingSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestMappingSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestMappingSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestMappingSlice(), es)\n}\n\nfunc TestMappingSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestMappingSlice()\n\tdest := NewMappingSlice()\n\tsrc := generateTestMappingSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestMappingSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestMappingSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestMappingSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestMappingSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewMappingSlice()\n\temptySlice.RemoveIf(func(el Mapping) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestMappingSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el Mapping) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestMappingSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestMappingSlice()\n\tgot.RemoveIf(func(el Mapping) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestMappingSliceAll(t *testing.T) {\n\tms := generateTestMappingSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestMappingSlice_Sort(t *testing.T) {\n\tes := generateTestMappingSlice()\n\tes.Sort(func(a, b Mapping) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b Mapping) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestMappingSlice() MappingSlice {\n\tms := NewMappingSlice()\n\t*ms.orig = internal.GenTestMappingPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_profile.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// Profile are an implementation of the pprofextended data model.\n\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewProfile function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Profile struct {\n\torig  *internal.Profile\n\tstate *internal.State\n}\n\nfunc newProfile(orig *internal.Profile, state *internal.State) Profile {\n\treturn Profile{orig: orig, state: state}\n}\n\n// NewProfile creates a new empty Profile.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewProfile() Profile {\n\treturn newProfile(internal.NewProfile(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Profile) MoveTo(dest Profile) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteProfile(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// SampleType returns the sampletype associated with this Profile.\nfunc (ms Profile) SampleType() ValueType {\n\treturn newValueType(&ms.orig.SampleType, ms.state)\n}\n\n// Samples returns the Samples associated with this Profile.\nfunc (ms Profile) Samples() SampleSlice {\n\treturn newSampleSlice(&ms.orig.Samples, ms.state)\n}\n\n// Time returns the time associated with this Profile.\nfunc (ms Profile) Time() pcommon.Timestamp {\n\treturn pcommon.Timestamp(ms.orig.TimeUnixNano)\n}\n\n// SetTime replaces the time associated with this Profile.\nfunc (ms Profile) SetTime(v pcommon.Timestamp) {\n\tms.state.AssertMutable()\n\tms.orig.TimeUnixNano = uint64(v)\n}\n\n// DurationNano returns the durationnano associated with this Profile.\nfunc (ms Profile) DurationNano() uint64 {\n\treturn ms.orig.DurationNano\n}\n\n// SetDurationNano replaces the durationnano associated with this Profile.\nfunc (ms Profile) SetDurationNano(v uint64) {\n\tms.state.AssertMutable()\n\tms.orig.DurationNano = v\n}\n\n// PeriodType returns the periodtype associated with this Profile.\nfunc (ms Profile) PeriodType() ValueType {\n\treturn newValueType(&ms.orig.PeriodType, ms.state)\n}\n\n// Period returns the period associated with this Profile.\nfunc (ms Profile) Period() int64 {\n\treturn ms.orig.Period\n}\n\n// SetPeriod replaces the period associated with this Profile.\nfunc (ms Profile) SetPeriod(v int64) {\n\tms.state.AssertMutable()\n\tms.orig.Period = v\n}\n\n// ProfileID returns the profileid associated with this Profile.\nfunc (ms Profile) ProfileID() ProfileID {\n\treturn ProfileID(ms.orig.ProfileId)\n}\n\n// SetProfileID replaces the profileid associated with this Profile.\nfunc (ms Profile) SetProfileID(v ProfileID) {\n\tms.state.AssertMutable()\n\tms.orig.ProfileId = internal.ProfileID(v)\n}\n\n// DroppedAttributesCount returns the droppedattributescount associated with this Profile.\nfunc (ms Profile) DroppedAttributesCount() uint32 {\n\treturn ms.orig.DroppedAttributesCount\n}\n\n// SetDroppedAttributesCount replaces the droppedattributescount associated with this Profile.\nfunc (ms Profile) SetDroppedAttributesCount(v uint32) {\n\tms.state.AssertMutable()\n\tms.orig.DroppedAttributesCount = v\n}\n\n// OriginalPayloadFormat returns the originalpayloadformat associated with this Profile.\nfunc (ms Profile) OriginalPayloadFormat() string {\n\treturn ms.orig.OriginalPayloadFormat\n}\n\n// SetOriginalPayloadFormat replaces the originalpayloadformat associated with this Profile.\nfunc (ms Profile) SetOriginalPayloadFormat(v string) {\n\tms.state.AssertMutable()\n\tms.orig.OriginalPayloadFormat = v\n}\n\n// OriginalPayload returns the OriginalPayload associated with this Profile.\nfunc (ms Profile) OriginalPayload() pcommon.ByteSlice {\n\treturn pcommon.ByteSlice(internal.NewByteSliceWrapper(&ms.orig.OriginalPayload, ms.state))\n}\n\n// AttributeIndices returns the AttributeIndices associated with this Profile.\nfunc (ms Profile) AttributeIndices() pcommon.Int32Slice {\n\treturn pcommon.Int32Slice(internal.NewInt32SliceWrapper(&ms.orig.AttributeIndices, ms.state))\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Profile) CopyTo(dest Profile) {\n\tdest.state.AssertMutable()\n\tinternal.CopyProfile(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_profile_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestProfile_MoveTo(t *testing.T) {\n\tms := generateTestProfile()\n\tdest := NewProfile()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewProfile(), ms)\n\tassert.Equal(t, generateTestProfile(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestProfile(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newProfile(internal.NewProfile(), sharedState)) })\n\tassert.Panics(t, func() { newProfile(internal.NewProfile(), sharedState).MoveTo(dest) })\n}\n\nfunc TestProfile_CopyTo(t *testing.T) {\n\tms := NewProfile()\n\torig := NewProfile()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestProfile()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newProfile(internal.NewProfile(), sharedState)) })\n}\n\nfunc TestProfile_SampleType(t *testing.T) {\n\tms := NewProfile()\n\tassert.Equal(t, NewValueType(), ms.SampleType())\n\tms.orig.SampleType = *internal.GenTestValueType()\n\tassert.Equal(t, generateTestValueType(), ms.SampleType())\n}\n\nfunc TestProfile_Samples(t *testing.T) {\n\tms := NewProfile()\n\tassert.Equal(t, NewSampleSlice(), ms.Samples())\n\tms.orig.Samples = internal.GenTestSamplePtrSlice()\n\tassert.Equal(t, generateTestSampleSlice(), ms.Samples())\n}\n\nfunc TestProfile_Time(t *testing.T) {\n\tms := NewProfile()\n\tassert.Equal(t, pcommon.Timestamp(0), ms.Time())\n\ttestValTime := pcommon.Timestamp(1234567890)\n\tms.SetTime(testValTime)\n\tassert.Equal(t, testValTime, ms.Time())\n}\n\nfunc TestProfile_DurationNano(t *testing.T) {\n\tms := NewProfile()\n\tassert.Equal(t, uint64(0), ms.DurationNano())\n\tms.SetDurationNano(uint64(13))\n\tassert.Equal(t, uint64(13), ms.DurationNano())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newProfile(internal.NewProfile(), sharedState).SetDurationNano(uint64(13)) })\n}\n\nfunc TestProfile_PeriodType(t *testing.T) {\n\tms := NewProfile()\n\tassert.Equal(t, NewValueType(), ms.PeriodType())\n\tms.orig.PeriodType = *internal.GenTestValueType()\n\tassert.Equal(t, generateTestValueType(), ms.PeriodType())\n}\n\nfunc TestProfile_Period(t *testing.T) {\n\tms := NewProfile()\n\tassert.Equal(t, int64(0), ms.Period())\n\tms.SetPeriod(int64(13))\n\tassert.Equal(t, int64(13), ms.Period())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newProfile(internal.NewProfile(), sharedState).SetPeriod(int64(13)) })\n}\n\nfunc TestProfile_ProfileID(t *testing.T) {\n\tms := NewProfile()\n\tassert.Equal(t, ProfileID(internal.ProfileID([16]byte{})), ms.ProfileID())\n\ttestValProfileID := ProfileID(internal.ProfileID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1}))\n\tms.SetProfileID(testValProfileID)\n\tassert.Equal(t, testValProfileID, ms.ProfileID())\n}\n\nfunc TestProfile_DroppedAttributesCount(t *testing.T) {\n\tms := NewProfile()\n\tassert.Equal(t, uint32(0), ms.DroppedAttributesCount())\n\tms.SetDroppedAttributesCount(uint32(13))\n\tassert.Equal(t, uint32(13), ms.DroppedAttributesCount())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newProfile(internal.NewProfile(), sharedState).SetDroppedAttributesCount(uint32(13)) })\n}\n\nfunc TestProfile_OriginalPayloadFormat(t *testing.T) {\n\tms := NewProfile()\n\tassert.Empty(t, ms.OriginalPayloadFormat())\n\tms.SetOriginalPayloadFormat(\"test_originalpayloadformat\")\n\tassert.Equal(t, \"test_originalpayloadformat\", ms.OriginalPayloadFormat())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewProfile(internal.NewProfile(), sharedState).SetOriginalPayloadFormat(\"test_originalpayloadformat\")\n\t})\n}\n\nfunc TestProfile_OriginalPayload(t *testing.T) {\n\tms := NewProfile()\n\tassert.Equal(t, pcommon.NewByteSlice(), ms.OriginalPayload())\n\tms.orig.OriginalPayload = internal.GenTestByteSlice()\n\tassert.Equal(t, pcommon.ByteSlice(internal.GenTestByteSliceWrapper()), ms.OriginalPayload())\n}\n\nfunc TestProfile_AttributeIndices(t *testing.T) {\n\tms := NewProfile()\n\tassert.Equal(t, pcommon.NewInt32Slice(), ms.AttributeIndices())\n\tms.orig.AttributeIndices = internal.GenTestInt32Slice()\n\tassert.Equal(t, pcommon.Int32Slice(internal.GenTestInt32SliceWrapper()), ms.AttributeIndices())\n}\n\nfunc generateTestProfile() Profile {\n\treturn newProfile(internal.GenTestProfile(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_profiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// Profiles is the top-level struct that is propagated through the profiles pipeline.\n// Use NewProfiles to create new instance, zero-initialized instance is not valid for use.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewProfiles function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Profiles internal.ProfilesWrapper\n\nfunc newProfiles(orig *internal.ExportProfilesServiceRequest, state *internal.State) Profiles {\n\treturn Profiles(internal.NewProfilesWrapper(orig, state))\n}\n\n// NewProfiles creates a new empty Profiles.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewProfiles() Profiles {\n\treturn newProfiles(internal.NewExportProfilesServiceRequest(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Profiles) MoveTo(dest Profiles) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\tinternal.DeleteExportProfilesServiceRequest(dest.getOrig(), false)\n\t*dest.getOrig(), *ms.getOrig() = *ms.getOrig(), *dest.getOrig()\n}\n\n// ResourceProfiles returns the ResourceProfiles associated with this Profiles.\nfunc (ms Profiles) ResourceProfiles() ResourceProfilesSlice {\n\treturn newResourceProfilesSlice(&ms.getOrig().ResourceProfiles, ms.getState())\n}\n\n// Dictionary returns the dictionary associated with this Profiles.\nfunc (ms Profiles) Dictionary() ProfilesDictionary {\n\treturn newProfilesDictionary(&ms.getOrig().Dictionary, ms.getState())\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Profiles) CopyTo(dest Profiles) {\n\tdest.getState().AssertMutable()\n\tinternal.CopyExportProfilesServiceRequest(dest.getOrig(), ms.getOrig())\n}\n\nfunc (ms Profiles) getOrig() *internal.ExportProfilesServiceRequest {\n\treturn internal.GetProfilesOrig(internal.ProfilesWrapper(ms))\n}\n\nfunc (ms Profiles) getState() *internal.State {\n\treturn internal.GetProfilesState(internal.ProfilesWrapper(ms))\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_profiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestProfiles_MoveTo(t *testing.T) {\n\tms := generateTestProfiles()\n\tdest := NewProfiles()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewProfiles(), ms)\n\tassert.Equal(t, generateTestProfiles(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestProfiles(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newProfiles(internal.NewExportProfilesServiceRequest(), sharedState)) })\n\tassert.Panics(t, func() { newProfiles(internal.NewExportProfilesServiceRequest(), sharedState).MoveTo(dest) })\n}\n\nfunc TestProfiles_CopyTo(t *testing.T) {\n\tms := NewProfiles()\n\torig := NewProfiles()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestProfiles()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newProfiles(internal.NewExportProfilesServiceRequest(), sharedState)) })\n}\n\nfunc TestProfiles_ResourceProfiles(t *testing.T) {\n\tms := NewProfiles()\n\tassert.Equal(t, NewResourceProfilesSlice(), ms.ResourceProfiles())\n\tms.getOrig().ResourceProfiles = internal.GenTestResourceProfilesPtrSlice()\n\tassert.Equal(t, generateTestResourceProfilesSlice(), ms.ResourceProfiles())\n}\n\nfunc TestProfiles_Dictionary(t *testing.T) {\n\tms := NewProfiles()\n\tassert.Equal(t, NewProfilesDictionary(), ms.Dictionary())\n\tms.getOrig().Dictionary = *internal.GenTestProfilesDictionary()\n\tassert.Equal(t, generateTestProfilesDictionary(), ms.Dictionary())\n}\n\nfunc generateTestProfiles() Profiles {\n\treturn newProfiles(internal.GenTestExportProfilesServiceRequest(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_profilesdata.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ProfilesData represents the profiles data that can be stored in persistent storage,\n// OR can be embedded by other protocols that transfer OTLP profiles data but do not\n// implement the OTLP protocol.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewProfilesData function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ProfilesData internal.ProfilesDataWrapper\n\nfunc newProfilesData(orig *internal.ProfilesData, state *internal.State) ProfilesData {\n\treturn ProfilesData(internal.NewProfilesDataWrapper(orig, state))\n}\n\n// NewProfilesData creates a new empty ProfilesData.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewProfilesData() ProfilesData {\n\treturn newProfilesData(internal.NewProfilesData(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ProfilesData) MoveTo(dest ProfilesData) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\tinternal.DeleteProfilesData(dest.getOrig(), false)\n\t*dest.getOrig(), *ms.getOrig() = *ms.getOrig(), *dest.getOrig()\n}\n\n// ResourceProfiles returns the ResourceProfiles associated with this ProfilesData.\nfunc (ms ProfilesData) ResourceProfiles() ResourceProfilesSlice {\n\treturn newResourceProfilesSlice(&ms.getOrig().ResourceProfiles, ms.getState())\n}\n\n// Dictionary returns the dictionary associated with this ProfilesData.\nfunc (ms ProfilesData) Dictionary() ProfilesDictionary {\n\treturn newProfilesDictionary(&ms.getOrig().Dictionary, ms.getState())\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ProfilesData) CopyTo(dest ProfilesData) {\n\tdest.getState().AssertMutable()\n\tinternal.CopyProfilesData(dest.getOrig(), ms.getOrig())\n}\n\nfunc (ms ProfilesData) getOrig() *internal.ProfilesData {\n\treturn internal.GetProfilesDataOrig(internal.ProfilesDataWrapper(ms))\n}\n\nfunc (ms ProfilesData) getState() *internal.State {\n\treturn internal.GetProfilesDataState(internal.ProfilesDataWrapper(ms))\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_profilesdata_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestProfilesData_MoveTo(t *testing.T) {\n\tms := generateTestProfilesData()\n\tdest := NewProfilesData()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewProfilesData(), ms)\n\tassert.Equal(t, generateTestProfilesData(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestProfilesData(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newProfilesData(internal.NewProfilesData(), sharedState)) })\n\tassert.Panics(t, func() { newProfilesData(internal.NewProfilesData(), sharedState).MoveTo(dest) })\n}\n\nfunc TestProfilesData_CopyTo(t *testing.T) {\n\tms := NewProfilesData()\n\torig := NewProfilesData()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestProfilesData()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newProfilesData(internal.NewProfilesData(), sharedState)) })\n}\n\nfunc TestProfilesData_ResourceProfiles(t *testing.T) {\n\tms := NewProfilesData()\n\tassert.Equal(t, NewResourceProfilesSlice(), ms.ResourceProfiles())\n\tms.getOrig().ResourceProfiles = internal.GenTestResourceProfilesPtrSlice()\n\tassert.Equal(t, generateTestResourceProfilesSlice(), ms.ResourceProfiles())\n}\n\nfunc TestProfilesData_Dictionary(t *testing.T) {\n\tms := NewProfilesData()\n\tassert.Equal(t, NewProfilesDictionary(), ms.Dictionary())\n\tms.getOrig().Dictionary = *internal.GenTestProfilesDictionary()\n\tassert.Equal(t, generateTestProfilesDictionary(), ms.Dictionary())\n}\n\nfunc generateTestProfilesData() ProfilesData {\n\treturn newProfilesData(internal.GenTestProfilesData(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_profilesdictionary.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ProfilesDictionary is the reference table containing all data shared by profiles across the message being sent.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewProfilesDictionary function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ProfilesDictionary struct {\n\torig  *internal.ProfilesDictionary\n\tstate *internal.State\n}\n\nfunc newProfilesDictionary(orig *internal.ProfilesDictionary, state *internal.State) ProfilesDictionary {\n\treturn ProfilesDictionary{orig: orig, state: state}\n}\n\n// NewProfilesDictionary creates a new empty ProfilesDictionary.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewProfilesDictionary() ProfilesDictionary {\n\treturn newProfilesDictionary(internal.NewProfilesDictionary(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ProfilesDictionary) MoveTo(dest ProfilesDictionary) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteProfilesDictionary(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// MappingTable returns the MappingTable associated with this ProfilesDictionary.\nfunc (ms ProfilesDictionary) MappingTable() MappingSlice {\n\treturn newMappingSlice(&ms.orig.MappingTable, ms.state)\n}\n\n// LocationTable returns the LocationTable associated with this ProfilesDictionary.\nfunc (ms ProfilesDictionary) LocationTable() LocationSlice {\n\treturn newLocationSlice(&ms.orig.LocationTable, ms.state)\n}\n\n// FunctionTable returns the FunctionTable associated with this ProfilesDictionary.\nfunc (ms ProfilesDictionary) FunctionTable() FunctionSlice {\n\treturn newFunctionSlice(&ms.orig.FunctionTable, ms.state)\n}\n\n// LinkTable returns the LinkTable associated with this ProfilesDictionary.\nfunc (ms ProfilesDictionary) LinkTable() LinkSlice {\n\treturn newLinkSlice(&ms.orig.LinkTable, ms.state)\n}\n\n// StringTable returns the StringTable associated with this ProfilesDictionary.\nfunc (ms ProfilesDictionary) StringTable() pcommon.StringSlice {\n\treturn pcommon.StringSlice(internal.NewStringSliceWrapper(&ms.orig.StringTable, ms.state))\n}\n\n// AttributeTable returns the AttributeTable associated with this ProfilesDictionary.\nfunc (ms ProfilesDictionary) AttributeTable() KeyValueAndUnitSlice {\n\treturn newKeyValueAndUnitSlice(&ms.orig.AttributeTable, ms.state)\n}\n\n// StackTable returns the StackTable associated with this ProfilesDictionary.\nfunc (ms ProfilesDictionary) StackTable() StackSlice {\n\treturn newStackSlice(&ms.orig.StackTable, ms.state)\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ProfilesDictionary) CopyTo(dest ProfilesDictionary) {\n\tdest.state.AssertMutable()\n\tinternal.CopyProfilesDictionary(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_profilesdictionary_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestProfilesDictionary_MoveTo(t *testing.T) {\n\tms := generateTestProfilesDictionary()\n\tdest := NewProfilesDictionary()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewProfilesDictionary(), ms)\n\tassert.Equal(t, generateTestProfilesDictionary(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestProfilesDictionary(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newProfilesDictionary(internal.NewProfilesDictionary(), sharedState)) })\n\tassert.Panics(t, func() { newProfilesDictionary(internal.NewProfilesDictionary(), sharedState).MoveTo(dest) })\n}\n\nfunc TestProfilesDictionary_CopyTo(t *testing.T) {\n\tms := NewProfilesDictionary()\n\torig := NewProfilesDictionary()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestProfilesDictionary()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newProfilesDictionary(internal.NewProfilesDictionary(), sharedState)) })\n}\n\nfunc TestProfilesDictionary_MappingTable(t *testing.T) {\n\tms := NewProfilesDictionary()\n\tassert.Equal(t, NewMappingSlice(), ms.MappingTable())\n\tms.orig.MappingTable = internal.GenTestMappingPtrSlice()\n\tassert.Equal(t, generateTestMappingSlice(), ms.MappingTable())\n}\n\nfunc TestProfilesDictionary_LocationTable(t *testing.T) {\n\tms := NewProfilesDictionary()\n\tassert.Equal(t, NewLocationSlice(), ms.LocationTable())\n\tms.orig.LocationTable = internal.GenTestLocationPtrSlice()\n\tassert.Equal(t, generateTestLocationSlice(), ms.LocationTable())\n}\n\nfunc TestProfilesDictionary_FunctionTable(t *testing.T) {\n\tms := NewProfilesDictionary()\n\tassert.Equal(t, NewFunctionSlice(), ms.FunctionTable())\n\tms.orig.FunctionTable = internal.GenTestFunctionPtrSlice()\n\tassert.Equal(t, generateTestFunctionSlice(), ms.FunctionTable())\n}\n\nfunc TestProfilesDictionary_LinkTable(t *testing.T) {\n\tms := NewProfilesDictionary()\n\tassert.Equal(t, NewLinkSlice(), ms.LinkTable())\n\tms.orig.LinkTable = internal.GenTestLinkPtrSlice()\n\tassert.Equal(t, generateTestLinkSlice(), ms.LinkTable())\n}\n\nfunc TestProfilesDictionary_StringTable(t *testing.T) {\n\tms := NewProfilesDictionary()\n\tassert.Equal(t, pcommon.NewStringSlice(), ms.StringTable())\n\tms.orig.StringTable = internal.GenTestStringSlice()\n\tassert.Equal(t, pcommon.StringSlice(internal.GenTestStringSliceWrapper()), ms.StringTable())\n}\n\nfunc TestProfilesDictionary_AttributeTable(t *testing.T) {\n\tms := NewProfilesDictionary()\n\tassert.Equal(t, NewKeyValueAndUnitSlice(), ms.AttributeTable())\n\tms.orig.AttributeTable = internal.GenTestKeyValueAndUnitPtrSlice()\n\tassert.Equal(t, generateTestKeyValueAndUnitSlice(), ms.AttributeTable())\n}\n\nfunc TestProfilesDictionary_StackTable(t *testing.T) {\n\tms := NewProfilesDictionary()\n\tassert.Equal(t, NewStackSlice(), ms.StackTable())\n\tms.orig.StackTable = internal.GenTestStackPtrSlice()\n\tassert.Equal(t, generateTestStackSlice(), ms.StackTable())\n}\n\nfunc generateTestProfilesDictionary() ProfilesDictionary {\n\treturn newProfilesDictionary(internal.GenTestProfilesDictionary(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_profilesslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ProfilesSlice logically represents a slice of Profile.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewProfilesSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ProfilesSlice struct {\n\torig  *[]*internal.Profile\n\tstate *internal.State\n}\n\nfunc newProfilesSlice(orig *[]*internal.Profile, state *internal.State) ProfilesSlice {\n\treturn ProfilesSlice{orig: orig, state: state}\n}\n\n// NewProfilesSlice creates a ProfilesSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewProfilesSlice() ProfilesSlice {\n\torig := []*internal.Profile(nil)\n\treturn newProfilesSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewProfilesSlice()\".\nfunc (es ProfilesSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es ProfilesSlice) At(i int) Profile {\n\treturn newProfile((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es ProfilesSlice) All() iter.Seq2[int, Profile] {\n\treturn func(yield func(int, Profile) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new ProfilesSlice can be initialized:\n//\n//\tes := NewProfilesSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es ProfilesSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.Profile, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty Profile.\n// It returns the newly added Profile.\nfunc (es ProfilesSlice) AppendEmpty() Profile {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewProfile())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es ProfilesSlice) MoveAndAppendTo(dest ProfilesSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es ProfilesSlice) RemoveIf(f func(Profile) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteProfile((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es ProfilesSlice) CopyTo(dest ProfilesSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyProfilePtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the Profile elements within ProfilesSlice given the\n// provided less function so that two instances of ProfilesSlice\n// can be compared.\nfunc (es ProfilesSlice) Sort(less func(a, b Profile) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_profilesslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestProfilesSlice(t *testing.T) {\n\tes := NewProfilesSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newProfilesSlice(&[]*internal.Profile{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewProfile()\n\ttestVal := generateTestProfile()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestProfile()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestProfilesSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newProfilesSlice(&[]*internal.Profile{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewProfilesSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestProfilesSlice_CopyTo(t *testing.T) {\n\tdest := NewProfilesSlice()\n\tsrc := generateTestProfilesSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestProfilesSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestProfilesSlice(), dest)\n}\n\nfunc TestProfilesSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestProfilesSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestProfilesSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestProfilesSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestProfilesSlice(), es)\n}\n\nfunc TestProfilesSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestProfilesSlice()\n\tdest := NewProfilesSlice()\n\tsrc := generateTestProfilesSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestProfilesSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestProfilesSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestProfilesSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestProfilesSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewProfilesSlice()\n\temptySlice.RemoveIf(func(el Profile) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestProfilesSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el Profile) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestProfilesSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestProfilesSlice()\n\tgot.RemoveIf(func(el Profile) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestProfilesSliceAll(t *testing.T) {\n\tms := generateTestProfilesSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestProfilesSlice_Sort(t *testing.T) {\n\tes := generateTestProfilesSlice()\n\tes.Sort(func(a, b Profile) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b Profile) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestProfilesSlice() ProfilesSlice {\n\tms := NewProfilesSlice()\n\t*ms.orig = internal.GenTestProfilePtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_resourceprofiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ResourceProfiles is a collection of profiles from a Resource.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewResourceProfiles function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ResourceProfiles struct {\n\torig  *internal.ResourceProfiles\n\tstate *internal.State\n}\n\nfunc newResourceProfiles(orig *internal.ResourceProfiles, state *internal.State) ResourceProfiles {\n\treturn ResourceProfiles{orig: orig, state: state}\n}\n\n// NewResourceProfiles creates a new empty ResourceProfiles.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewResourceProfiles() ResourceProfiles {\n\treturn newResourceProfiles(internal.NewResourceProfiles(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ResourceProfiles) MoveTo(dest ResourceProfiles) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteResourceProfiles(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Resource returns the resource associated with this ResourceProfiles.\nfunc (ms ResourceProfiles) Resource() pcommon.Resource {\n\treturn pcommon.Resource(internal.NewResourceWrapper(&ms.orig.Resource, ms.state))\n}\n\n// ScopeProfiles returns the ScopeProfiles associated with this ResourceProfiles.\nfunc (ms ResourceProfiles) ScopeProfiles() ScopeProfilesSlice {\n\treturn newScopeProfilesSlice(&ms.orig.ScopeProfiles, ms.state)\n}\n\n// SchemaUrl returns the schemaurl associated with this ResourceProfiles.\nfunc (ms ResourceProfiles) SchemaUrl() string {\n\treturn ms.orig.SchemaUrl\n}\n\n// SetSchemaUrl replaces the schemaurl associated with this ResourceProfiles.\nfunc (ms ResourceProfiles) SetSchemaUrl(v string) {\n\tms.state.AssertMutable()\n\tms.orig.SchemaUrl = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ResourceProfiles) CopyTo(dest ResourceProfiles) {\n\tdest.state.AssertMutable()\n\tinternal.CopyResourceProfiles(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_resourceprofiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestResourceProfiles_MoveTo(t *testing.T) {\n\tms := generateTestResourceProfiles()\n\tdest := NewResourceProfiles()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewResourceProfiles(), ms)\n\tassert.Equal(t, generateTestResourceProfiles(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestResourceProfiles(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newResourceProfiles(internal.NewResourceProfiles(), sharedState)) })\n\tassert.Panics(t, func() { newResourceProfiles(internal.NewResourceProfiles(), sharedState).MoveTo(dest) })\n}\n\nfunc TestResourceProfiles_CopyTo(t *testing.T) {\n\tms := NewResourceProfiles()\n\torig := NewResourceProfiles()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestResourceProfiles()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newResourceProfiles(internal.NewResourceProfiles(), sharedState)) })\n}\n\nfunc TestResourceProfiles_Resource(t *testing.T) {\n\tms := NewResourceProfiles()\n\tassert.Equal(t, pcommon.NewResource(), ms.Resource())\n\tms.orig.Resource = *internal.GenTestResource()\n\tassert.Equal(t, pcommon.Resource(internal.GenTestResourceWrapper()), ms.Resource())\n}\n\nfunc TestResourceProfiles_ScopeProfiles(t *testing.T) {\n\tms := NewResourceProfiles()\n\tassert.Equal(t, NewScopeProfilesSlice(), ms.ScopeProfiles())\n\tms.orig.ScopeProfiles = internal.GenTestScopeProfilesPtrSlice()\n\tassert.Equal(t, generateTestScopeProfilesSlice(), ms.ScopeProfiles())\n}\n\nfunc TestResourceProfiles_SchemaUrl(t *testing.T) {\n\tms := NewResourceProfiles()\n\tassert.Empty(t, ms.SchemaUrl())\n\tms.SetSchemaUrl(\"test_schemaurl\")\n\tassert.Equal(t, \"test_schemaurl\", ms.SchemaUrl())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewResourceProfiles(internal.NewResourceProfiles(), sharedState).SetSchemaUrl(\"test_schemaurl\")\n\t})\n}\n\nfunc generateTestResourceProfiles() ResourceProfiles {\n\treturn newResourceProfiles(internal.GenTestResourceProfiles(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_resourceprofilesslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ResourceProfilesSlice logically represents a slice of ResourceProfiles.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewResourceProfilesSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ResourceProfilesSlice struct {\n\torig  *[]*internal.ResourceProfiles\n\tstate *internal.State\n}\n\nfunc newResourceProfilesSlice(orig *[]*internal.ResourceProfiles, state *internal.State) ResourceProfilesSlice {\n\treturn ResourceProfilesSlice{orig: orig, state: state}\n}\n\n// NewResourceProfilesSlice creates a ResourceProfilesSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewResourceProfilesSlice() ResourceProfilesSlice {\n\torig := []*internal.ResourceProfiles(nil)\n\treturn newResourceProfilesSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewResourceProfilesSlice()\".\nfunc (es ResourceProfilesSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es ResourceProfilesSlice) At(i int) ResourceProfiles {\n\treturn newResourceProfiles((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es ResourceProfilesSlice) All() iter.Seq2[int, ResourceProfiles] {\n\treturn func(yield func(int, ResourceProfiles) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new ResourceProfilesSlice can be initialized:\n//\n//\tes := NewResourceProfilesSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es ResourceProfilesSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.ResourceProfiles, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty ResourceProfiles.\n// It returns the newly added ResourceProfiles.\nfunc (es ResourceProfilesSlice) AppendEmpty() ResourceProfiles {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewResourceProfiles())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es ResourceProfilesSlice) MoveAndAppendTo(dest ResourceProfilesSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es ResourceProfilesSlice) RemoveIf(f func(ResourceProfiles) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteResourceProfiles((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es ResourceProfilesSlice) CopyTo(dest ResourceProfilesSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyResourceProfilesPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the ResourceProfiles elements within ResourceProfilesSlice given the\n// provided less function so that two instances of ResourceProfilesSlice\n// can be compared.\nfunc (es ResourceProfilesSlice) Sort(less func(a, b ResourceProfiles) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_resourceprofilesslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestResourceProfilesSlice(t *testing.T) {\n\tes := NewResourceProfilesSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newResourceProfilesSlice(&[]*internal.ResourceProfiles{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewResourceProfiles()\n\ttestVal := generateTestResourceProfiles()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestResourceProfiles()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestResourceProfilesSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newResourceProfilesSlice(&[]*internal.ResourceProfiles{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewResourceProfilesSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestResourceProfilesSlice_CopyTo(t *testing.T) {\n\tdest := NewResourceProfilesSlice()\n\tsrc := generateTestResourceProfilesSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestResourceProfilesSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestResourceProfilesSlice(), dest)\n}\n\nfunc TestResourceProfilesSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestResourceProfilesSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestResourceProfilesSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestResourceProfilesSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestResourceProfilesSlice(), es)\n}\n\nfunc TestResourceProfilesSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestResourceProfilesSlice()\n\tdest := NewResourceProfilesSlice()\n\tsrc := generateTestResourceProfilesSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestResourceProfilesSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestResourceProfilesSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestResourceProfilesSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestResourceProfilesSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewResourceProfilesSlice()\n\temptySlice.RemoveIf(func(el ResourceProfiles) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestResourceProfilesSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el ResourceProfiles) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestResourceProfilesSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestResourceProfilesSlice()\n\tgot.RemoveIf(func(el ResourceProfiles) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestResourceProfilesSliceAll(t *testing.T) {\n\tms := generateTestResourceProfilesSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestResourceProfilesSlice_Sort(t *testing.T) {\n\tes := generateTestResourceProfilesSlice()\n\tes.Sort(func(a, b ResourceProfiles) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b ResourceProfiles) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestResourceProfilesSlice() ResourceProfilesSlice {\n\tms := NewResourceProfilesSlice()\n\t*ms.orig = internal.GenTestResourceProfilesPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_sample.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// Sample represents each record value encountered within a profiled program.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewSample function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Sample struct {\n\torig  *internal.Sample\n\tstate *internal.State\n}\n\nfunc newSample(orig *internal.Sample, state *internal.State) Sample {\n\treturn Sample{orig: orig, state: state}\n}\n\n// NewSample creates a new empty Sample.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewSample() Sample {\n\treturn newSample(internal.NewSample(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Sample) MoveTo(dest Sample) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteSample(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// StackIndex returns the stackindex associated with this Sample.\nfunc (ms Sample) StackIndex() int32 {\n\treturn ms.orig.StackIndex\n}\n\n// SetStackIndex replaces the stackindex associated with this Sample.\nfunc (ms Sample) SetStackIndex(v int32) {\n\tms.state.AssertMutable()\n\tms.orig.StackIndex = v\n}\n\n// AttributeIndices returns the AttributeIndices associated with this Sample.\nfunc (ms Sample) AttributeIndices() pcommon.Int32Slice {\n\treturn pcommon.Int32Slice(internal.NewInt32SliceWrapper(&ms.orig.AttributeIndices, ms.state))\n}\n\n// LinkIndex returns the linkindex associated with this Sample.\nfunc (ms Sample) LinkIndex() int32 {\n\treturn ms.orig.LinkIndex\n}\n\n// SetLinkIndex replaces the linkindex associated with this Sample.\nfunc (ms Sample) SetLinkIndex(v int32) {\n\tms.state.AssertMutable()\n\tms.orig.LinkIndex = v\n}\n\n// Values returns the Values associated with this Sample.\nfunc (ms Sample) Values() pcommon.Int64Slice {\n\treturn pcommon.Int64Slice(internal.NewInt64SliceWrapper(&ms.orig.Values, ms.state))\n}\n\n// TimestampsUnixNano returns the TimestampsUnixNano associated with this Sample.\nfunc (ms Sample) TimestampsUnixNano() pcommon.UInt64Slice {\n\treturn pcommon.UInt64Slice(internal.NewUInt64SliceWrapper(&ms.orig.TimestampsUnixNano, ms.state))\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Sample) CopyTo(dest Sample) {\n\tdest.state.AssertMutable()\n\tinternal.CopySample(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_sample_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestSample_MoveTo(t *testing.T) {\n\tms := generateTestSample()\n\tdest := NewSample()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewSample(), ms)\n\tassert.Equal(t, generateTestSample(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestSample(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newSample(internal.NewSample(), sharedState)) })\n\tassert.Panics(t, func() { newSample(internal.NewSample(), sharedState).MoveTo(dest) })\n}\n\nfunc TestSample_CopyTo(t *testing.T) {\n\tms := NewSample()\n\torig := NewSample()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestSample()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newSample(internal.NewSample(), sharedState)) })\n}\n\nfunc TestSample_StackIndex(t *testing.T) {\n\tms := NewSample()\n\tassert.Equal(t, int32(0), ms.StackIndex())\n\tms.SetStackIndex(int32(13))\n\tassert.Equal(t, int32(13), ms.StackIndex())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newSample(internal.NewSample(), sharedState).SetStackIndex(int32(13)) })\n}\n\nfunc TestSample_AttributeIndices(t *testing.T) {\n\tms := NewSample()\n\tassert.Equal(t, pcommon.NewInt32Slice(), ms.AttributeIndices())\n\tms.orig.AttributeIndices = internal.GenTestInt32Slice()\n\tassert.Equal(t, pcommon.Int32Slice(internal.GenTestInt32SliceWrapper()), ms.AttributeIndices())\n}\n\nfunc TestSample_LinkIndex(t *testing.T) {\n\tms := NewSample()\n\tassert.Equal(t, int32(0), ms.LinkIndex())\n\tms.SetLinkIndex(int32(13))\n\tassert.Equal(t, int32(13), ms.LinkIndex())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newSample(internal.NewSample(), sharedState).SetLinkIndex(int32(13)) })\n}\n\nfunc TestSample_Values(t *testing.T) {\n\tms := NewSample()\n\tassert.Equal(t, pcommon.NewInt64Slice(), ms.Values())\n\tms.orig.Values = internal.GenTestInt64Slice()\n\tassert.Equal(t, pcommon.Int64Slice(internal.GenTestInt64SliceWrapper()), ms.Values())\n}\n\nfunc TestSample_TimestampsUnixNano(t *testing.T) {\n\tms := NewSample()\n\tassert.Equal(t, pcommon.NewUInt64Slice(), ms.TimestampsUnixNano())\n\tms.orig.TimestampsUnixNano = internal.GenTestUint64Slice()\n\tassert.Equal(t, pcommon.UInt64Slice(internal.GenTestUInt64SliceWrapper()), ms.TimestampsUnixNano())\n}\n\nfunc generateTestSample() Sample {\n\treturn newSample(internal.GenTestSample(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_sampleslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// SampleSlice logically represents a slice of Sample.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewSampleSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype SampleSlice struct {\n\torig  *[]*internal.Sample\n\tstate *internal.State\n}\n\nfunc newSampleSlice(orig *[]*internal.Sample, state *internal.State) SampleSlice {\n\treturn SampleSlice{orig: orig, state: state}\n}\n\n// NewSampleSlice creates a SampleSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewSampleSlice() SampleSlice {\n\torig := []*internal.Sample(nil)\n\treturn newSampleSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewSampleSlice()\".\nfunc (es SampleSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es SampleSlice) At(i int) Sample {\n\treturn newSample((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es SampleSlice) All() iter.Seq2[int, Sample] {\n\treturn func(yield func(int, Sample) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new SampleSlice can be initialized:\n//\n//\tes := NewSampleSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es SampleSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.Sample, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty Sample.\n// It returns the newly added Sample.\nfunc (es SampleSlice) AppendEmpty() Sample {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewSample())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es SampleSlice) MoveAndAppendTo(dest SampleSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es SampleSlice) RemoveIf(f func(Sample) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteSample((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es SampleSlice) CopyTo(dest SampleSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopySamplePtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the Sample elements within SampleSlice given the\n// provided less function so that two instances of SampleSlice\n// can be compared.\nfunc (es SampleSlice) Sort(less func(a, b Sample) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_sampleslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestSampleSlice(t *testing.T) {\n\tes := NewSampleSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newSampleSlice(&[]*internal.Sample{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewSample()\n\ttestVal := generateTestSample()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestSample()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestSampleSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newSampleSlice(&[]*internal.Sample{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewSampleSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestSampleSlice_CopyTo(t *testing.T) {\n\tdest := NewSampleSlice()\n\tsrc := generateTestSampleSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestSampleSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestSampleSlice(), dest)\n}\n\nfunc TestSampleSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestSampleSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestSampleSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestSampleSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestSampleSlice(), es)\n}\n\nfunc TestSampleSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestSampleSlice()\n\tdest := NewSampleSlice()\n\tsrc := generateTestSampleSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestSampleSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestSampleSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestSampleSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestSampleSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewSampleSlice()\n\temptySlice.RemoveIf(func(el Sample) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestSampleSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el Sample) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestSampleSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestSampleSlice()\n\tgot.RemoveIf(func(el Sample) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestSampleSliceAll(t *testing.T) {\n\tms := generateTestSampleSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestSampleSlice_Sort(t *testing.T) {\n\tes := generateTestSampleSlice()\n\tes.Sort(func(a, b Sample) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b Sample) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestSampleSlice() SampleSlice {\n\tms := NewSampleSlice()\n\t*ms.orig = internal.GenTestSamplePtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_scopeprofiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ScopeProfiles is a collection of profiles from a LibraryInstrumentation.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewScopeProfiles function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ScopeProfiles struct {\n\torig  *internal.ScopeProfiles\n\tstate *internal.State\n}\n\nfunc newScopeProfiles(orig *internal.ScopeProfiles, state *internal.State) ScopeProfiles {\n\treturn ScopeProfiles{orig: orig, state: state}\n}\n\n// NewScopeProfiles creates a new empty ScopeProfiles.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewScopeProfiles() ScopeProfiles {\n\treturn newScopeProfiles(internal.NewScopeProfiles(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ScopeProfiles) MoveTo(dest ScopeProfiles) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteScopeProfiles(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Scope returns the scope associated with this ScopeProfiles.\nfunc (ms ScopeProfiles) Scope() pcommon.InstrumentationScope {\n\treturn pcommon.InstrumentationScope(internal.NewInstrumentationScopeWrapper(&ms.orig.Scope, ms.state))\n}\n\n// Profiles returns the Profiles associated with this ScopeProfiles.\nfunc (ms ScopeProfiles) Profiles() ProfilesSlice {\n\treturn newProfilesSlice(&ms.orig.Profiles, ms.state)\n}\n\n// SchemaUrl returns the schemaurl associated with this ScopeProfiles.\nfunc (ms ScopeProfiles) SchemaUrl() string {\n\treturn ms.orig.SchemaUrl\n}\n\n// SetSchemaUrl replaces the schemaurl associated with this ScopeProfiles.\nfunc (ms ScopeProfiles) SetSchemaUrl(v string) {\n\tms.state.AssertMutable()\n\tms.orig.SchemaUrl = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ScopeProfiles) CopyTo(dest ScopeProfiles) {\n\tdest.state.AssertMutable()\n\tinternal.CopyScopeProfiles(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_scopeprofiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestScopeProfiles_MoveTo(t *testing.T) {\n\tms := generateTestScopeProfiles()\n\tdest := NewScopeProfiles()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewScopeProfiles(), ms)\n\tassert.Equal(t, generateTestScopeProfiles(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestScopeProfiles(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newScopeProfiles(internal.NewScopeProfiles(), sharedState)) })\n\tassert.Panics(t, func() { newScopeProfiles(internal.NewScopeProfiles(), sharedState).MoveTo(dest) })\n}\n\nfunc TestScopeProfiles_CopyTo(t *testing.T) {\n\tms := NewScopeProfiles()\n\torig := NewScopeProfiles()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestScopeProfiles()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newScopeProfiles(internal.NewScopeProfiles(), sharedState)) })\n}\n\nfunc TestScopeProfiles_Scope(t *testing.T) {\n\tms := NewScopeProfiles()\n\tassert.Equal(t, pcommon.NewInstrumentationScope(), ms.Scope())\n\tms.orig.Scope = *internal.GenTestInstrumentationScope()\n\tassert.Equal(t, pcommon.InstrumentationScope(internal.GenTestInstrumentationScopeWrapper()), ms.Scope())\n}\n\nfunc TestScopeProfiles_Profiles(t *testing.T) {\n\tms := NewScopeProfiles()\n\tassert.Equal(t, NewProfilesSlice(), ms.Profiles())\n\tms.orig.Profiles = internal.GenTestProfilePtrSlice()\n\tassert.Equal(t, generateTestProfilesSlice(), ms.Profiles())\n}\n\nfunc TestScopeProfiles_SchemaUrl(t *testing.T) {\n\tms := NewScopeProfiles()\n\tassert.Empty(t, ms.SchemaUrl())\n\tms.SetSchemaUrl(\"test_schemaurl\")\n\tassert.Equal(t, \"test_schemaurl\", ms.SchemaUrl())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newScopeProfiles(internal.NewScopeProfiles(), sharedState).SetSchemaUrl(\"test_schemaurl\") })\n}\n\nfunc generateTestScopeProfiles() ScopeProfiles {\n\treturn newScopeProfiles(internal.GenTestScopeProfiles(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_scopeprofilesslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ScopeProfilesSlice logically represents a slice of ScopeProfiles.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewScopeProfilesSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ScopeProfilesSlice struct {\n\torig  *[]*internal.ScopeProfiles\n\tstate *internal.State\n}\n\nfunc newScopeProfilesSlice(orig *[]*internal.ScopeProfiles, state *internal.State) ScopeProfilesSlice {\n\treturn ScopeProfilesSlice{orig: orig, state: state}\n}\n\n// NewScopeProfilesSlice creates a ScopeProfilesSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewScopeProfilesSlice() ScopeProfilesSlice {\n\torig := []*internal.ScopeProfiles(nil)\n\treturn newScopeProfilesSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewScopeProfilesSlice()\".\nfunc (es ScopeProfilesSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es ScopeProfilesSlice) At(i int) ScopeProfiles {\n\treturn newScopeProfiles((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es ScopeProfilesSlice) All() iter.Seq2[int, ScopeProfiles] {\n\treturn func(yield func(int, ScopeProfiles) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new ScopeProfilesSlice can be initialized:\n//\n//\tes := NewScopeProfilesSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es ScopeProfilesSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.ScopeProfiles, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty ScopeProfiles.\n// It returns the newly added ScopeProfiles.\nfunc (es ScopeProfilesSlice) AppendEmpty() ScopeProfiles {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewScopeProfiles())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es ScopeProfilesSlice) MoveAndAppendTo(dest ScopeProfilesSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es ScopeProfilesSlice) RemoveIf(f func(ScopeProfiles) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteScopeProfiles((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es ScopeProfilesSlice) CopyTo(dest ScopeProfilesSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyScopeProfilesPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the ScopeProfiles elements within ScopeProfilesSlice given the\n// provided less function so that two instances of ScopeProfilesSlice\n// can be compared.\nfunc (es ScopeProfilesSlice) Sort(less func(a, b ScopeProfiles) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_scopeprofilesslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestScopeProfilesSlice(t *testing.T) {\n\tes := NewScopeProfilesSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newScopeProfilesSlice(&[]*internal.ScopeProfiles{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewScopeProfiles()\n\ttestVal := generateTestScopeProfiles()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestScopeProfiles()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestScopeProfilesSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newScopeProfilesSlice(&[]*internal.ScopeProfiles{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewScopeProfilesSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestScopeProfilesSlice_CopyTo(t *testing.T) {\n\tdest := NewScopeProfilesSlice()\n\tsrc := generateTestScopeProfilesSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestScopeProfilesSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestScopeProfilesSlice(), dest)\n}\n\nfunc TestScopeProfilesSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestScopeProfilesSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestScopeProfilesSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestScopeProfilesSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestScopeProfilesSlice(), es)\n}\n\nfunc TestScopeProfilesSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestScopeProfilesSlice()\n\tdest := NewScopeProfilesSlice()\n\tsrc := generateTestScopeProfilesSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestScopeProfilesSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestScopeProfilesSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestScopeProfilesSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestScopeProfilesSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewScopeProfilesSlice()\n\temptySlice.RemoveIf(func(el ScopeProfiles) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestScopeProfilesSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el ScopeProfiles) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestScopeProfilesSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestScopeProfilesSlice()\n\tgot.RemoveIf(func(el ScopeProfiles) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestScopeProfilesSliceAll(t *testing.T) {\n\tms := generateTestScopeProfilesSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestScopeProfilesSlice_Sort(t *testing.T) {\n\tes := generateTestScopeProfilesSlice()\n\tes.Sort(func(a, b ScopeProfiles) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b ScopeProfiles) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestScopeProfilesSlice() ScopeProfilesSlice {\n\tms := NewScopeProfilesSlice()\n\t*ms.orig = internal.GenTestScopeProfilesPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_stack.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// Stack represents a stack trace as a list of locations.\n\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewStack function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Stack struct {\n\torig  *internal.Stack\n\tstate *internal.State\n}\n\nfunc newStack(orig *internal.Stack, state *internal.State) Stack {\n\treturn Stack{orig: orig, state: state}\n}\n\n// NewStack creates a new empty Stack.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewStack() Stack {\n\treturn newStack(internal.NewStack(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Stack) MoveTo(dest Stack) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteStack(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// LocationIndices returns the LocationIndices associated with this Stack.\nfunc (ms Stack) LocationIndices() pcommon.Int32Slice {\n\treturn pcommon.Int32Slice(internal.NewInt32SliceWrapper(&ms.orig.LocationIndices, ms.state))\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Stack) CopyTo(dest Stack) {\n\tdest.state.AssertMutable()\n\tinternal.CopyStack(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_stack_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestStack_MoveTo(t *testing.T) {\n\tms := generateTestStack()\n\tdest := NewStack()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewStack(), ms)\n\tassert.Equal(t, generateTestStack(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestStack(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newStack(internal.NewStack(), sharedState)) })\n\tassert.Panics(t, func() { newStack(internal.NewStack(), sharedState).MoveTo(dest) })\n}\n\nfunc TestStack_CopyTo(t *testing.T) {\n\tms := NewStack()\n\torig := NewStack()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestStack()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newStack(internal.NewStack(), sharedState)) })\n}\n\nfunc TestStack_LocationIndices(t *testing.T) {\n\tms := NewStack()\n\tassert.Equal(t, pcommon.NewInt32Slice(), ms.LocationIndices())\n\tms.orig.LocationIndices = internal.GenTestInt32Slice()\n\tassert.Equal(t, pcommon.Int32Slice(internal.GenTestInt32SliceWrapper()), ms.LocationIndices())\n}\n\nfunc generateTestStack() Stack {\n\treturn newStack(internal.GenTestStack(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_stackslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// StackSlice logically represents a slice of Stack.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewStackSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype StackSlice struct {\n\torig  *[]*internal.Stack\n\tstate *internal.State\n}\n\nfunc newStackSlice(orig *[]*internal.Stack, state *internal.State) StackSlice {\n\treturn StackSlice{orig: orig, state: state}\n}\n\n// NewStackSlice creates a StackSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewStackSlice() StackSlice {\n\torig := []*internal.Stack(nil)\n\treturn newStackSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewStackSlice()\".\nfunc (es StackSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es StackSlice) At(i int) Stack {\n\treturn newStack((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es StackSlice) All() iter.Seq2[int, Stack] {\n\treturn func(yield func(int, Stack) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new StackSlice can be initialized:\n//\n//\tes := NewStackSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es StackSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.Stack, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty Stack.\n// It returns the newly added Stack.\nfunc (es StackSlice) AppendEmpty() Stack {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewStack())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es StackSlice) MoveAndAppendTo(dest StackSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es StackSlice) RemoveIf(f func(Stack) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteStack((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es StackSlice) CopyTo(dest StackSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyStackPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the Stack elements within StackSlice given the\n// provided less function so that two instances of StackSlice\n// can be compared.\nfunc (es StackSlice) Sort(less func(a, b Stack) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_stackslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestStackSlice(t *testing.T) {\n\tes := NewStackSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newStackSlice(&[]*internal.Stack{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewStack()\n\ttestVal := generateTestStack()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestStack()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestStackSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newStackSlice(&[]*internal.Stack{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewStackSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestStackSlice_CopyTo(t *testing.T) {\n\tdest := NewStackSlice()\n\tsrc := generateTestStackSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestStackSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestStackSlice(), dest)\n}\n\nfunc TestStackSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestStackSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestStackSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestStackSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestStackSlice(), es)\n}\n\nfunc TestStackSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestStackSlice()\n\tdest := NewStackSlice()\n\tsrc := generateTestStackSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestStackSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestStackSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestStackSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestStackSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewStackSlice()\n\temptySlice.RemoveIf(func(el Stack) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestStackSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el Stack) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestStackSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestStackSlice()\n\tgot.RemoveIf(func(el Stack) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestStackSliceAll(t *testing.T) {\n\tms := generateTestStackSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestStackSlice_Sort(t *testing.T) {\n\tes := generateTestStackSlice()\n\tes.Sort(func(a, b Stack) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b Stack) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestStackSlice() StackSlice {\n\tms := NewStackSlice()\n\t*ms.orig = internal.GenTestStackPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_valuetype.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ValueType describes the type and units of a value.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewValueType function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ValueType struct {\n\torig  *internal.ValueType\n\tstate *internal.State\n}\n\nfunc newValueType(orig *internal.ValueType, state *internal.State) ValueType {\n\treturn ValueType{orig: orig, state: state}\n}\n\n// NewValueType creates a new empty ValueType.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewValueType() ValueType {\n\treturn newValueType(internal.NewValueType(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ValueType) MoveTo(dest ValueType) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteValueType(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// TypeStrindex returns the typestrindex associated with this ValueType.\nfunc (ms ValueType) TypeStrindex() int32 {\n\treturn ms.orig.TypeStrindex\n}\n\n// SetTypeStrindex replaces the typestrindex associated with this ValueType.\nfunc (ms ValueType) SetTypeStrindex(v int32) {\n\tms.state.AssertMutable()\n\tms.orig.TypeStrindex = v\n}\n\n// UnitStrindex returns the unitstrindex associated with this ValueType.\nfunc (ms ValueType) UnitStrindex() int32 {\n\treturn ms.orig.UnitStrindex\n}\n\n// SetUnitStrindex replaces the unitstrindex associated with this ValueType.\nfunc (ms ValueType) SetUnitStrindex(v int32) {\n\tms.state.AssertMutable()\n\tms.orig.UnitStrindex = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ValueType) CopyTo(dest ValueType) {\n\tdest.state.AssertMutable()\n\tinternal.CopyValueType(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_valuetype_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestValueType_MoveTo(t *testing.T) {\n\tms := generateTestValueType()\n\tdest := NewValueType()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewValueType(), ms)\n\tassert.Equal(t, generateTestValueType(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestValueType(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newValueType(internal.NewValueType(), sharedState)) })\n\tassert.Panics(t, func() { newValueType(internal.NewValueType(), sharedState).MoveTo(dest) })\n}\n\nfunc TestValueType_CopyTo(t *testing.T) {\n\tms := NewValueType()\n\torig := NewValueType()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestValueType()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newValueType(internal.NewValueType(), sharedState)) })\n}\n\nfunc TestValueType_TypeStrindex(t *testing.T) {\n\tms := NewValueType()\n\tassert.Equal(t, int32(0), ms.TypeStrindex())\n\tms.SetTypeStrindex(int32(13))\n\tassert.Equal(t, int32(13), ms.TypeStrindex())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newValueType(internal.NewValueType(), sharedState).SetTypeStrindex(int32(13)) })\n}\n\nfunc TestValueType_UnitStrindex(t *testing.T) {\n\tms := NewValueType()\n\tassert.Equal(t, int32(0), ms.UnitStrindex())\n\tms.SetUnitStrindex(int32(13))\n\tassert.Equal(t, int32(13), ms.UnitStrindex())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newValueType(internal.NewValueType(), sharedState).SetUnitStrindex(int32(13)) })\n}\n\nfunc generateTestValueType() ValueType {\n\treturn newValueType(internal.GenTestValueType(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_valuetypeslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ValueTypeSlice logically represents a slice of ValueType.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewValueTypeSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ValueTypeSlice struct {\n\torig  *[]*internal.ValueType\n\tstate *internal.State\n}\n\nfunc newValueTypeSlice(orig *[]*internal.ValueType, state *internal.State) ValueTypeSlice {\n\treturn ValueTypeSlice{orig: orig, state: state}\n}\n\n// NewValueTypeSlice creates a ValueTypeSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewValueTypeSlice() ValueTypeSlice {\n\torig := []*internal.ValueType(nil)\n\treturn newValueTypeSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewValueTypeSlice()\".\nfunc (es ValueTypeSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es ValueTypeSlice) At(i int) ValueType {\n\treturn newValueType((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es ValueTypeSlice) All() iter.Seq2[int, ValueType] {\n\treturn func(yield func(int, ValueType) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new ValueTypeSlice can be initialized:\n//\n//\tes := NewValueTypeSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es ValueTypeSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.ValueType, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty ValueType.\n// It returns the newly added ValueType.\nfunc (es ValueTypeSlice) AppendEmpty() ValueType {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewValueType())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es ValueTypeSlice) MoveAndAppendTo(dest ValueTypeSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es ValueTypeSlice) RemoveIf(f func(ValueType) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteValueType((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es ValueTypeSlice) CopyTo(dest ValueTypeSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyValueTypePtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the ValueType elements within ValueTypeSlice given the\n// provided less function so that two instances of ValueTypeSlice\n// can be compared.\nfunc (es ValueTypeSlice) Sort(less func(a, b ValueType) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/pprofile/generated_valuetypeslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestValueTypeSlice(t *testing.T) {\n\tes := NewValueTypeSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newValueTypeSlice(&[]*internal.ValueType{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewValueType()\n\ttestVal := generateTestValueType()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestValueType()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestValueTypeSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newValueTypeSlice(&[]*internal.ValueType{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewValueTypeSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestValueTypeSlice_CopyTo(t *testing.T) {\n\tdest := NewValueTypeSlice()\n\tsrc := generateTestValueTypeSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestValueTypeSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestValueTypeSlice(), dest)\n}\n\nfunc TestValueTypeSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestValueTypeSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestValueTypeSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestValueTypeSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestValueTypeSlice(), es)\n}\n\nfunc TestValueTypeSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestValueTypeSlice()\n\tdest := NewValueTypeSlice()\n\tsrc := generateTestValueTypeSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestValueTypeSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestValueTypeSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestValueTypeSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestValueTypeSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewValueTypeSlice()\n\temptySlice.RemoveIf(func(el ValueType) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestValueTypeSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el ValueType) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestValueTypeSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestValueTypeSlice()\n\tgot.RemoveIf(func(el ValueType) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestValueTypeSliceAll(t *testing.T) {\n\tms := generateTestValueTypeSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestValueTypeSlice_Sort(t *testing.T) {\n\tes := generateTestValueTypeSlice()\n\tes.Sort(func(a, b ValueType) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b ValueType) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestValueTypeSlice() ValueTypeSlice {\n\tms := NewValueTypeSlice()\n\t*ms.orig = internal.GenTestValueTypePtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/pprofile/go.mod",
    "content": "module go.opentelemetry.io/collector/pdata/pprofile\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/featuregate v1.54.0\n\tgo.opentelemetry.io/collector/internal/testutil v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/otel v1.40.0\n\tgo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0\n\tgo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0\n\tgo.uber.org/goleak v1.3.0\n\tgoogle.golang.org/grpc v1.79.3\n\tgoogle.golang.org/protobuf v1.36.11\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/proto/slim/otlp v1.10.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/pdata => ../\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n"
  },
  {
    "path": "pdata/pprofile/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.40.0 h1:oA5YeOcpRTXq6NN7frwmwFR0Cn3RhTVZvXsP4duvCms=\ngo.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlV14J0g=\ngo.opentelemetry.io/otel/metric v1.40.0 h1:rcZe317KPftE2rstWIBitCdVp89A2HqjkxR3c11+p9g=\ngo.opentelemetry.io/otel/metric v1.40.0/go.mod h1:ib/crwQH7N3r5kfiBZQbwrTge743UDc7DTFVZrrXnqc=\ngo.opentelemetry.io/otel/sdk v1.39.0 h1:nMLYcjVsvdui1B/4FRkwjzoRVsMK8uL/cj0OyhKzt18=\ngo.opentelemetry.io/otel/sdk v1.39.0/go.mod h1:vDojkC4/jsTJsE+kh+LXYQlbL8CgrEcwmt1ENZszdJE=\ngo.opentelemetry.io/otel/sdk/metric v1.39.0 h1:cXMVVFVgsIf2YL6QkRF4Urbr/aMInf+2WKg+sEJTtB8=\ngo.opentelemetry.io/otel/sdk/metric v1.39.0/go.mod h1:xq9HEVH7qeX69/JnwEfp6fVq5wosJsY1mt4lLfYdVew=\ngo.opentelemetry.io/otel/trace v1.40.0 h1:WA4etStDttCSYuhwvEa8OP8I5EWu24lkOzp+ZYblVjw=\ngo.opentelemetry.io/otel/trace v1.40.0/go.mod h1:zeAhriXecNGP/s2SEG3+Y8X9ujcJOTqQ5RgdEJcawiA=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=\ngonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "pdata/pprofile/json.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport (\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otlp\"\n)\n\n// JSONMarshaler marshals pprofile.Profiles to JSON bytes using the OTLP/JSON format.\ntype JSONMarshaler struct{}\n\n// MarshalProfiles to the OTLP/JSON format.\nfunc (*JSONMarshaler) MarshalProfiles(pd Profiles) ([]byte, error) {\n\t// Convert strings to references for efficient transmission\n\tconvertProfilesToReferences(pd)\n\n\tdest := json.BorrowStream(nil)\n\tdefer json.ReturnStream(dest)\n\tpd.getOrig().MarshalJSON(dest)\n\tif dest.Error() != nil {\n\t\treturn nil, dest.Error()\n\t}\n\treturn slices.Clone(dest.Buffer()), nil\n}\n\n// JSONUnmarshaler unmarshals OTLP/JSON formatted-bytes to pprofile.Profiles.\ntype JSONUnmarshaler struct{}\n\n// UnmarshalProfiles from OTLP/JSON format into pprofile.Profiles.\nfunc (*JSONUnmarshaler) UnmarshalProfiles(buf []byte) (Profiles, error) {\n\titer := json.BorrowIterator(buf)\n\tdefer json.ReturnIterator(iter)\n\tpd := NewProfiles()\n\tpd.getOrig().UnmarshalJSON(iter)\n\tif iter.Error() != nil {\n\t\treturn Profiles{}, iter.Error()\n\t}\n\totlp.MigrateProfiles(pd.getOrig().ResourceProfiles)\n\n\t// Resolve all string_value_ref and key_ref to their actual strings\n\t// so the pdata API works transparently\n\tresolveProfilesReferences(pd)\n\n\treturn pd, nil\n}\n"
  },
  {
    "path": "pdata/pprofile/json_references_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\tstdjson \"encoding/json\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\n// newProfilesWithAttributes creates a Profiles with resource and scope\n// attributes for testing reference conversion.\nfunc newProfilesWithAttributes() Profiles {\n\tprofiles := NewProfiles()\n\tprofiles.Dictionary().StringTable().Append(\"\") // index 0\n\n\trp := profiles.ResourceProfiles().AppendEmpty()\n\trp.Resource().Attributes().PutStr(\"service.name\", \"test-service\")\n\trp.Resource().Attributes().PutStr(\"host.name\", \"test-host\")\n\n\tsp := rp.ScopeProfiles().AppendEmpty()\n\tsp.Scope().Attributes().PutStr(\"scope.attr\", \"scope-value\")\n\n\treturn profiles\n}\n\nfunc TestJSONMarshalConvertsToReferences(t *testing.T) {\n\tmarshaler := JSONMarshaler{}\n\tjsonBytes, err := marshaler.MarshalProfiles(newProfilesWithAttributes())\n\trequire.NoError(t, err)\n\n\t// Parse the JSON output to verify references were used\n\tvar parsed map[string]any\n\trequire.NoError(t, stdjson.Unmarshal(jsonBytes, &parsed))\n\n\t// The dictionary's stringTable should contain the attribute keys and values\n\tdictionary, ok := parsed[\"dictionary\"].(map[string]any)\n\trequire.True(t, ok, \"JSON output should contain a dictionary object\")\n\tstringTable, ok := dictionary[\"stringTable\"].([]any)\n\trequire.True(t, ok, \"dictionary should contain a stringTable array\")\n\n\ttableStrs := make([]string, len(stringTable))\n\tfor i, v := range stringTable {\n\t\ttableStrs[i], _ = v.(string)\n\t}\n\tassert.Contains(t, tableStrs, \"service.name\")\n\tassert.Contains(t, tableStrs, \"test-service\")\n\tassert.Contains(t, tableStrs, \"host.name\")\n\tassert.Contains(t, tableStrs, \"test-host\")\n\tassert.Contains(t, tableStrs, \"scope.attr\")\n\tassert.Contains(t, tableStrs, \"scope-value\")\n}\n\nfunc TestJSONUnmarshalResolvesReferences(t *testing.T) {\n\tprofiles := newProfilesWithAttributes()\n\n\t// Manually convert to references before marshaling, so the JSON output\n\t// contains key_ref/string_value_ref regardless of whether the JSON\n\t// marshaler itself calls convertProfilesToReferences.\n\tconvertProfilesToReferences(profiles)\n\n\tmarshaler := JSONMarshaler{}\n\tjsonBytes, err := marshaler.MarshalProfiles(profiles)\n\trequire.NoError(t, err)\n\n\t// Unmarshal and verify references were resolved\n\tunmarshaler := JSONUnmarshaler{}\n\trestored, err := unmarshaler.UnmarshalProfiles(jsonBytes)\n\trequire.NoError(t, err)\n\n\trp := restored.ResourceProfiles().At(0)\n\tserviceNameVal, ok := rp.Resource().Attributes().Get(\"service.name\")\n\tassert.True(t, ok, \"service.name attribute should be accessible after JSON unmarshal\")\n\tassert.Equal(t, \"test-service\", serviceNameVal.Str())\n\n\thostNameVal, ok := rp.Resource().Attributes().Get(\"host.name\")\n\tassert.True(t, ok, \"host.name attribute should be accessible after JSON unmarshal\")\n\tassert.Equal(t, \"test-host\", hostNameVal.Str())\n\n\tsp := rp.ScopeProfiles().At(0)\n\tscopeAttrVal, ok := sp.Scope().Attributes().Get(\"scope.attr\")\n\tassert.True(t, ok, \"scope.attr should be accessible after JSON unmarshal\")\n\tassert.Equal(t, \"scope-value\", scopeAttrVal.Str())\n}\n"
  },
  {
    "path": "pdata/pprofile/keyvalueandunit.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport \"fmt\"\n\n// Equal checks equality with another KeyValueAndUnit\n// It assumes both structs refer to the same dictionary.\nfunc (ms KeyValueAndUnit) Equal(val KeyValueAndUnit) bool {\n\treturn ms.KeyStrindex() == val.KeyStrindex() &&\n\t\tms.UnitStrindex() == val.UnitStrindex() &&\n\t\tms.Value().Equal(val.Value())\n}\n\n// switchDictionary updates the KeyValueAndUnit, switching its indices from one\n// dictionary to another.\nfunc (ms KeyValueAndUnit) switchDictionary(src, dst ProfilesDictionary) error {\n\tif ms.KeyStrindex() > 0 {\n\t\tif src.StringTable().Len() <= int(ms.KeyStrindex()) {\n\t\t\treturn fmt.Errorf(\"invalid key index %d\", ms.KeyStrindex())\n\t\t}\n\n\t\tidx, err := SetString(dst.StringTable(), src.StringTable().At(int(ms.KeyStrindex())))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't set key: %w\", err)\n\t\t}\n\t\tms.SetKeyStrindex(idx)\n\t}\n\n\tif ms.UnitStrindex() > 0 {\n\t\tif src.StringTable().Len() <= int(ms.UnitStrindex()) {\n\t\t\treturn fmt.Errorf(\"invalid unit index %d\", ms.UnitStrindex())\n\t\t}\n\n\t\tidx, err := SetString(dst.StringTable(), src.StringTable().At(int(ms.UnitStrindex())))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't set unit: %w\", err)\n\t\t}\n\t\tms.SetUnitStrindex(idx)\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "pdata/pprofile/keyvalueandunit_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestKeyValueAndUnitEqual(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname string\n\t\torig KeyValueAndUnit\n\t\tdest KeyValueAndUnit\n\t\twant bool\n\t}{\n\t\t{\n\t\t\tname: \"empty keyvalueandunit\",\n\t\t\torig: NewKeyValueAndUnit(),\n\t\t\tdest: NewKeyValueAndUnit(),\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"non-empty identical keyvalueandunit\",\n\t\t\torig: buildKeyValueAndUnit(1, 2, pcommon.NewValueStr(\"test\")),\n\t\t\tdest: buildKeyValueAndUnit(1, 2, pcommon.NewValueStr(\"test\")),\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"with different key index\",\n\t\t\torig: buildKeyValueAndUnit(1, 2, pcommon.NewValueStr(\"test\")),\n\t\t\tdest: buildKeyValueAndUnit(2, 2, pcommon.NewValueStr(\"test\")),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with different unit index\",\n\t\t\torig: buildKeyValueAndUnit(1, 2, pcommon.NewValueStr(\"test\")),\n\t\t\tdest: buildKeyValueAndUnit(1, 3, pcommon.NewValueStr(\"test\")),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with different value\",\n\t\t\torig: buildKeyValueAndUnit(1, 2, pcommon.NewValueStr(\"test\")),\n\t\t\tdest: buildKeyValueAndUnit(1, 2, pcommon.NewValueStr(\"hello\")),\n\t\t\twant: false,\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif tt.want {\n\t\t\t\tassert.True(t, tt.orig.Equal(tt.dest))\n\t\t\t} else {\n\t\t\t\tassert.False(t, tt.orig.Equal(tt.dest))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestKeyValueAndUnitSwitchDictionary(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname            string\n\t\tkeyValueAndUnit KeyValueAndUnit\n\n\t\tsrc ProfilesDictionary\n\t\tdst ProfilesDictionary\n\n\t\twantKeyValueAndUnit KeyValueAndUnit\n\t\twantDictionary      ProfilesDictionary\n\t\twantErr             error\n\t}{\n\t\t{\n\t\t\tname:            \"with an empty key value and unit\",\n\t\t\tkeyValueAndUnit: NewKeyValueAndUnit(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantKeyValueAndUnit: NewKeyValueAndUnit(),\n\t\t\twantDictionary:      NewProfilesDictionary(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing key\",\n\t\t\tkeyValueAndUnit: func() KeyValueAndUnit {\n\t\t\t\tkvu := NewKeyValueAndUnit()\n\t\t\t\tkvu.SetKeyStrindex(1)\n\t\t\t\treturn kvu\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\")\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantKeyValueAndUnit: func() KeyValueAndUnit {\n\t\t\t\tkvu := NewKeyValueAndUnit()\n\t\t\t\tkvu.SetKeyStrindex(2)\n\t\t\t\treturn kvu\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a key index that does not match anything\",\n\t\t\tkeyValueAndUnit: func() KeyValueAndUnit {\n\t\t\t\tkvu := NewKeyValueAndUnit()\n\t\t\t\tkvu.SetKeyStrindex(1)\n\t\t\t\treturn kvu\n\t\t\t}(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantKeyValueAndUnit: func() KeyValueAndUnit {\n\t\t\t\tkvu := NewKeyValueAndUnit()\n\t\t\t\tkvu.SetKeyStrindex(1)\n\t\t\t\treturn kvu\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid key index 1\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with a key index equal to the source table length (boundary condition)\",\n\t\t\tkeyValueAndUnit: func() KeyValueAndUnit {\n\t\t\t\tkvu := NewKeyValueAndUnit()\n\t\t\t\tkvu.SetKeyStrindex(2)\n\t\t\t\treturn kvu\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantKeyValueAndUnit: func() KeyValueAndUnit {\n\t\t\t\tkvu := NewKeyValueAndUnit()\n\t\t\t\tkvu.SetKeyStrindex(2)\n\t\t\t\treturn kvu\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid key index 2\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing unit\",\n\t\t\tkeyValueAndUnit: func() KeyValueAndUnit {\n\t\t\t\tkvu := NewKeyValueAndUnit()\n\t\t\t\tkvu.SetUnitStrindex(1)\n\t\t\t\treturn kvu\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\")\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantKeyValueAndUnit: func() KeyValueAndUnit {\n\t\t\t\tkvu := NewKeyValueAndUnit()\n\t\t\t\tkvu.SetUnitStrindex(2)\n\t\t\t\treturn kvu\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a unit index that does not match anything\",\n\t\t\tkeyValueAndUnit: func() KeyValueAndUnit {\n\t\t\t\tkvu := NewKeyValueAndUnit()\n\t\t\t\tkvu.SetUnitStrindex(1)\n\t\t\t\treturn kvu\n\t\t\t}(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantKeyValueAndUnit: func() KeyValueAndUnit {\n\t\t\t\tkvu := NewKeyValueAndUnit()\n\t\t\t\tkvu.SetUnitStrindex(1)\n\t\t\t\treturn kvu\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid unit index 1\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with a unit index equal to the source table length (boundary condition)\",\n\t\t\tkeyValueAndUnit: func() KeyValueAndUnit {\n\t\t\t\tkvu := NewKeyValueAndUnit()\n\t\t\t\tkvu.SetUnitStrindex(2)\n\t\t\t\treturn kvu\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantKeyValueAndUnit: func() KeyValueAndUnit {\n\t\t\t\tkvu := NewKeyValueAndUnit()\n\t\t\t\tkvu.SetUnitStrindex(2)\n\t\t\t\treturn kvu\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid unit index 2\"),\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tkvu := tt.keyValueAndUnit\n\t\t\tdst := tt.dst\n\t\t\terr := kvu.switchDictionary(tt.src, dst)\n\n\t\t\tif tt.wantErr == nil {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.Equal(t, tt.wantErr, err)\n\t\t\t}\n\n\t\t\tassert.Equal(t, tt.wantKeyValueAndUnit, kvu)\n\t\t\tassert.Equal(t, tt.wantDictionary, dst)\n\t\t})\n\t}\n}\n\nfunc BenchmarkKeyValueAndUnitSwitchDictionary(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\n\tkvu := NewKeyValueAndUnit()\n\tkvu.SetKeyStrindex(1)\n\n\tsrc := NewProfilesDictionary()\n\tsrc.StringTable().Append(\"\", \"test\")\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tb.StopTimer()\n\t\tdst := NewProfilesDictionary()\n\t\tb.StartTimer()\n\n\t\t_ = kvu.switchDictionary(src, dst)\n\t}\n}\n\nfunc buildKeyValueAndUnit(keyIdx, unitIdx int32, val pcommon.Value) KeyValueAndUnit {\n\tkvu := NewKeyValueAndUnit()\n\tkvu.SetKeyStrindex(keyIdx)\n\tkvu.SetUnitStrindex(unitIdx)\n\tval.CopyTo(kvu.Value())\n\treturn kvu\n}\n"
  },
  {
    "path": "pdata/pprofile/line.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport \"fmt\"\n\n// Equal checks equality with another LineSlice\nfunc (l LineSlice) Equal(val LineSlice) bool {\n\tif l.Len() != val.Len() {\n\t\treturn false\n\t}\n\n\tfor i := range l.Len() {\n\t\tif !l.At(i).Equal(val.At(i)) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n// Equal checks equality with another Line\nfunc (l Line) Equal(val Line) bool {\n\treturn l.Column() == val.Column() &&\n\t\tl.FunctionIndex() == val.FunctionIndex() &&\n\t\tl.Line() == val.Line()\n}\n\n// switchDictionary updates the Line, switching its indices from one\n// dictionary to another.\nfunc (l Line) switchDictionary(src, dst ProfilesDictionary) error {\n\tif l.FunctionIndex() > 0 {\n\t\tif src.FunctionTable().Len() <= int(l.FunctionIndex()) {\n\t\t\treturn fmt.Errorf(\"invalid function index %d\", l.FunctionIndex())\n\t\t}\n\n\t\tfn := src.FunctionTable().At(int(l.FunctionIndex()))\n\t\tidx, err := SetFunction(dst.FunctionTable(), fn)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't set function: %w\", err)\n\t\t}\n\t\tl.SetFunctionIndex(idx)\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "pdata/pprofile/line_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc TestLineSliceEqual(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname string\n\t\torig LineSlice\n\t\tdest LineSlice\n\t\twant bool\n\t}{\n\t\t{\n\t\t\tname: \"with empty slices\",\n\t\t\torig: NewLineSlice(),\n\t\t\tdest: NewLineSlice(),\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"with non-empty equal slices\",\n\t\t\torig: func() LineSlice {\n\t\t\t\tls := NewLineSlice()\n\t\t\t\tls.AppendEmpty().SetLine(1)\n\t\t\t\treturn ls\n\t\t\t}(),\n\t\t\tdest: func() LineSlice {\n\t\t\t\tls := NewLineSlice()\n\t\t\t\tls.AppendEmpty().SetLine(1)\n\t\t\t\treturn ls\n\t\t\t}(),\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"with different lengths\",\n\t\t\torig: func() LineSlice {\n\t\t\t\tls := NewLineSlice()\n\t\t\t\tls.AppendEmpty()\n\t\t\t\treturn ls\n\t\t\t}(),\n\t\t\tdest: NewLineSlice(),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with non-equal slices\",\n\t\t\torig: func() LineSlice {\n\t\t\t\tls := NewLineSlice()\n\t\t\t\tls.AppendEmpty().SetLine(2)\n\t\t\t\treturn ls\n\t\t\t}(),\n\t\t\tdest: func() LineSlice {\n\t\t\t\tls := NewLineSlice()\n\t\t\t\tls.AppendEmpty().SetLine(1)\n\t\t\t\treturn ls\n\t\t\t}(),\n\t\t\twant: false,\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif tt.want {\n\t\t\t\tassert.True(t, tt.orig.Equal(tt.dest))\n\t\t\t} else {\n\t\t\t\tassert.False(t, tt.orig.Equal(tt.dest))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestLineEqual(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname string\n\t\torig Line\n\t\tdest Line\n\t\twant bool\n\t}{\n\t\t{\n\t\t\tname: \"with empty lines\",\n\t\t\torig: NewLine(),\n\t\t\tdest: NewLine(),\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"with non-empty lines\",\n\t\t\torig: buildLine(1, 2, 3),\n\t\t\tdest: buildLine(1, 2, 3),\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"with non-equal column\",\n\t\t\torig: buildLine(1, 2, 3),\n\t\t\tdest: buildLine(2, 2, 3),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with non-equal function index\",\n\t\t\torig: buildLine(1, 2, 3),\n\t\t\tdest: buildLine(1, 3, 3),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with non-equal line\",\n\t\t\torig: buildLine(1, 2, 3),\n\t\t\tdest: buildLine(1, 2, 4),\n\t\t\twant: false,\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif tt.want {\n\t\t\t\tassert.True(t, tt.orig.Equal(tt.dest))\n\t\t\t} else {\n\t\t\t\tassert.False(t, tt.orig.Equal(tt.dest))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestLineSwitchDictionary(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname string\n\t\tline Line\n\n\t\tsrc ProfilesDictionary\n\t\tdst ProfilesDictionary\n\n\t\twantLine       Line\n\t\twantDictionary ProfilesDictionary\n\t\twantErr        error\n\t}{\n\t\t{\n\t\t\tname: \"with an empty line\",\n\t\t\tline: NewLine(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantLine:       NewLine(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing function\",\n\t\t\tline: func() Line {\n\t\t\t\tl := NewLine()\n\t\t\t\tl.SetFunctionIndex(1)\n\t\t\t\treturn l\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.FunctionTable().AppendEmpty()\n\t\t\t\tf := d.FunctionTable().AppendEmpty()\n\t\t\t\tf.SetNameStrindex(1)\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.FunctionTable().AppendEmpty()\n\t\t\t\tf := d.FunctionTable().AppendEmpty()\n\t\t\t\tf.SetNameStrindex(1)\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantLine: func() Line {\n\t\t\t\tl := NewLine()\n\t\t\t\tl.SetFunctionIndex(1)\n\t\t\t\treturn l\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.FunctionTable().AppendEmpty()\n\t\t\t\tf := d.FunctionTable().AppendEmpty()\n\t\t\t\tf.SetNameStrindex(1)\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a function index that does not match anything\",\n\t\t\tline: func() Line {\n\t\t\t\tl := NewLine()\n\t\t\t\tl.SetFunctionIndex(1)\n\t\t\t\treturn l\n\t\t\t}(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantLine: func() Line {\n\t\t\t\tl := NewLine()\n\t\t\t\tl.SetFunctionIndex(1)\n\t\t\t\treturn l\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid function index 1\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with a function index equal to the source table length (boundary condition)\",\n\t\t\tline: func() Line {\n\t\t\t\tl := NewLine()\n\t\t\t\tl.SetFunctionIndex(2)\n\t\t\t\treturn l\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.FunctionTable().AppendEmpty()\n\t\t\t\td.FunctionTable().AppendEmpty() // Length 2: indices 0,1 valid\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantLine: func() Line {\n\t\t\t\tl := NewLine()\n\t\t\t\tl.SetFunctionIndex(2)\n\t\t\t\treturn l\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid function index 2\"),\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tline := tt.line\n\t\t\tdst := tt.dst\n\t\t\terr := line.switchDictionary(tt.src, dst)\n\n\t\t\tif tt.wantErr == nil {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.Equal(t, tt.wantErr, err)\n\t\t\t}\n\n\t\t\tassert.Equal(t, tt.wantLine, line)\n\t\t\tassert.Equal(t, tt.wantDictionary, dst)\n\t\t})\n\t}\n}\n\nfunc BenchmarkLineSwitchDictionary(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\n\tl := NewLine()\n\tl.SetFunctionIndex(1)\n\n\tsrc := NewProfilesDictionary()\n\tsrc.StringTable().Append(\"\", \"test\")\n\n\tsrc.FunctionTable().AppendEmpty()\n\tsrc.FunctionTable().AppendEmpty().SetNameStrindex(1)\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tb.StopTimer()\n\t\tdst := NewProfilesDictionary()\n\t\tb.StartTimer()\n\n\t\t_ = l.switchDictionary(src, dst)\n\t}\n}\n\nfunc buildLine(col int64, funcIdx int32, line int64) Line {\n\tl := NewLine()\n\tl.SetColumn(col)\n\tl.SetFunctionIndex(funcIdx)\n\tl.SetLine(line)\n\n\treturn l\n}\n"
  },
  {
    "path": "pdata/pprofile/link.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\n// Equal checks equality with another Link\nfunc (ms Link) Equal(val Link) bool {\n\treturn ms.TraceID() == val.TraceID() &&\n\t\tms.SpanID() == val.SpanID()\n}\n"
  },
  {
    "path": "pdata/pprofile/link_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestLinkEqual(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname string\n\t\torig Link\n\t\tdest Link\n\t\twant bool\n\t}{\n\t\t{\n\t\t\tname: \"empty links\",\n\t\t\torig: NewLink(),\n\t\t\tdest: NewLink(),\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"non-empty identical links\",\n\t\t\torig: buildLink(\n\t\t\t\tpcommon.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1}),\n\t\t\t\tpcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}),\n\t\t\t),\n\t\t\tdest: buildLink(\n\t\t\t\tpcommon.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1}),\n\t\t\t\tpcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}),\n\t\t\t),\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"with different trace IDs\",\n\t\t\torig: buildLink(\n\t\t\t\tpcommon.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1}),\n\t\t\t\tpcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}),\n\t\t\t),\n\t\t\tdest: buildLink(\n\t\t\t\tpcommon.TraceID([16]byte{8, 7, 6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6, 7, 8}),\n\t\t\t\tpcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}),\n\t\t\t),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with different span IDs\",\n\t\t\torig: buildLink(\n\t\t\t\tpcommon.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1}),\n\t\t\t\tpcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}),\n\t\t\t),\n\t\t\tdest: buildLink(\n\t\t\t\tpcommon.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1}),\n\t\t\t\tpcommon.SpanID([8]byte{8, 7, 6, 5, 4, 3, 2, 1}),\n\t\t\t),\n\t\t\twant: false,\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif tt.want {\n\t\t\t\tassert.True(t, tt.orig.Equal(tt.dest))\n\t\t\t} else {\n\t\t\t\tassert.False(t, tt.orig.Equal(tt.dest))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc buildLink(traceID pcommon.TraceID, spanID pcommon.SpanID) Link {\n\tl := NewLink()\n\tl.SetTraceID(traceID)\n\tl.SetSpanID(spanID)\n\treturn l\n}\n"
  },
  {
    "path": "pdata/pprofile/links.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport (\n\t\"errors\"\n\t\"math\"\n)\n\nvar errTooManyLinkTableEntries = errors.New(\"too many entries in LinkTable\")\n\n// SetLink updates a LinkTable, adding or providing a value and returns its\n// index.\nfunc SetLink(table LinkSlice, li Link) (int32, error) {\n\tfor j, l := range table.All() {\n\t\tif l.Equal(li) {\n\t\t\tif j > math.MaxInt32 {\n\t\t\t\treturn 0, errTooManyLinkTableEntries\n\t\t\t}\n\t\t\treturn int32(j), nil\n\t\t}\n\t}\n\n\tif table.Len() >= math.MaxInt32 {\n\t\treturn 0, errTooManyLinkTableEntries\n\t}\n\n\tli.CopyTo(table.AppendEmpty())\n\treturn int32(table.Len() - 1), nil\n}\n"
  },
  {
    "path": "pdata/pprofile/links_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestSetLink(t *testing.T) {\n\ttable := NewLinkSlice()\n\tl := NewLink()\n\tl.SetTraceID(pcommon.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1}))\n\tl2 := NewLink()\n\tl.SetTraceID(pcommon.TraceID([16]byte{2, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 2}))\n\n\t// Put a first link\n\tidx, err := SetLink(table, l)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 1, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\n\t// Put the same link\n\t// This should be a no-op.\n\tidx, err = SetLink(table, l)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 1, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\n\t// Set a new link\n\t// This sets the index and adds to the table.\n\tidx, err = SetLink(table, l2)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(table.Len()-1), idx)\n\n\t// Set an existing link\n\tidx, err = SetLink(table, l)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\t// Set another existing link\n\tidx, err = SetLink(table, l2)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(table.Len()-1), idx)\n}\n\nfunc BenchmarkSetLink(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\tfor _, bb := range []struct {\n\t\tname string\n\t\tlink Link\n\n\t\trunBefore func(*testing.B, LinkSlice)\n\t}{\n\t\t{\n\t\t\tname: \"with a new link\",\n\t\t\tlink: NewLink(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing link\",\n\t\t\tlink: func() Link {\n\t\t\t\tl := NewLink()\n\t\t\t\tl.SetTraceID(pcommon.NewTraceIDEmpty())\n\t\t\t\treturn l\n\t\t\t}(),\n\n\t\t\trunBefore: func(_ *testing.B, table LinkSlice) {\n\t\t\t\tl := table.AppendEmpty()\n\t\t\t\tl.SetTraceID(pcommon.NewTraceIDEmpty())\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with a duplicate link\",\n\t\t\tlink: NewLink(),\n\n\t\t\trunBefore: func(b *testing.B, table LinkSlice) {\n\t\t\t\t_, err := SetLink(table, NewLink())\n\t\t\t\trequire.NoError(b, err)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with a hundred links to loop through\",\n\t\t\tlink: func() Link {\n\t\t\t\tl := NewLink()\n\t\t\t\tl.SetTraceID(pcommon.NewTraceIDEmpty())\n\t\t\t\treturn l\n\t\t\t}(),\n\n\t\t\trunBefore: func(_ *testing.B, table LinkSlice) {\n\t\t\t\tfor range 100 {\n\t\t\t\t\ttable.AppendEmpty()\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t} {\n\t\tb.Run(bb.name, func(b *testing.B) {\n\t\t\ttable := NewLinkSlice()\n\n\t\t\tif bb.runBefore != nil {\n\t\t\t\tbb.runBefore(b, table)\n\t\t\t}\n\n\t\t\tb.ResetTimer()\n\t\t\tb.ReportAllocs()\n\n\t\t\tfor b.Loop() {\n\t\t\t\t_, _ = SetLink(table, bb.link)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "pdata/pprofile/location.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport \"fmt\"\n\n// Equal checks equality with another Location\nfunc (ms Location) Equal(val Location) bool {\n\treturn ms.MappingIndex() == val.MappingIndex() &&\n\t\tms.Address() == val.Address() &&\n\t\tms.AttributeIndices().Equal(val.AttributeIndices()) &&\n\t\tms.Lines().Equal(val.Lines())\n}\n\n// switchDictionary updates the Location, switching its indices from one\n// dictionary to another.\nfunc (ms Location) switchDictionary(src, dst ProfilesDictionary) error {\n\tif ms.MappingIndex() > 0 {\n\t\tif src.MappingTable().Len() <= int(ms.MappingIndex()) {\n\t\t\treturn fmt.Errorf(\"invalid mapping index %d\", ms.MappingIndex())\n\t\t}\n\n\t\tmapping := src.MappingTable().At(int(ms.MappingIndex()))\n\t\tidx, err := SetMapping(dst.MappingTable(), mapping)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't set mapping: %w\", err)\n\t\t}\n\t\tms.SetMappingIndex(idx)\n\t}\n\n\tfor i, v := range ms.AttributeIndices().All() {\n\t\tif src.AttributeTable().Len() <= int(v) {\n\t\t\treturn fmt.Errorf(\"invalid attribute index %d\", v)\n\t\t}\n\n\t\tattr := src.AttributeTable().At(int(v))\n\t\tidx, err := SetAttribute(dst.AttributeTable(), attr)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't set attribute %d: %w\", i, err)\n\t\t}\n\t\tms.AttributeIndices().SetAt(i, idx)\n\t}\n\n\tfor i, v := range ms.Lines().All() {\n\t\terr := v.switchDictionary(src, dst)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't switch dictionary for line %d: %w\", i, err)\n\t\t}\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "pdata/pprofile/location_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc TestLocationEqual(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname string\n\t\torig Location\n\t\tdest Location\n\t\twant bool\n\t}{\n\t\t{\n\t\t\tname: \"empty locations\",\n\t\t\torig: NewLocation(),\n\t\t\tdest: NewLocation(),\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"non-empty locations\",\n\t\t\torig: buildLocation(1, 2, []int32{3}, buildLine(1, 2, 3)),\n\t\t\tdest: buildLocation(1, 2, []int32{3}, buildLine(1, 2, 3)),\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"with non-equal mapping index\",\n\t\t\torig: buildLocation(1, 2, []int32{3}, buildLine(1, 2, 3)),\n\t\t\tdest: buildLocation(2, 2, []int32{3}, buildLine(1, 2, 3)),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with non-equal address\",\n\t\t\torig: buildLocation(1, 2, []int32{3}, buildLine(1, 2, 3)),\n\t\t\tdest: buildLocation(1, 3, []int32{3}, buildLine(1, 2, 3)),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with non-equal attribute indices\",\n\t\t\torig: buildLocation(1, 2, []int32{3}, buildLine(1, 2, 3)),\n\t\t\tdest: buildLocation(1, 2, []int32{5}, buildLine(1, 2, 3)),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with non-equal lines\",\n\t\t\torig: buildLocation(1, 2, []int32{3}, buildLine(4, 5, 6)),\n\t\t\tdest: buildLocation(1, 2, []int32{3}, buildLine(1, 2, 3)),\n\t\t\twant: false,\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif tt.want {\n\t\t\t\tassert.True(t, tt.orig.Equal(tt.dest))\n\t\t\t} else {\n\t\t\t\tassert.False(t, tt.orig.Equal(tt.dest))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestLocationSwitchDictionary(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname     string\n\t\tlocation Location\n\n\t\tsrc ProfilesDictionary\n\t\tdst ProfilesDictionary\n\n\t\twantLocation   Location\n\t\twantDictionary ProfilesDictionary\n\t\twantErr        error\n\t}{\n\t\t{\n\t\t\tname:     \"with an empty location\",\n\t\t\tlocation: NewLocation(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantLocation:   NewLocation(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing mapping\",\n\t\t\tlocation: func() Location {\n\t\t\t\tl := NewLocation()\n\t\t\t\tl.SetMappingIndex(1)\n\t\t\t\treturn l\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.MappingTable().AppendEmpty()\n\t\t\t\tm := d.MappingTable().AppendEmpty()\n\t\t\t\tm.SetFilenameStrindex(1)\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.MappingTable().AppendEmpty()\n\t\t\t\tm := d.MappingTable().AppendEmpty()\n\t\t\t\tm.SetFilenameStrindex(1)\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantLocation: func() Location {\n\t\t\t\tl := NewLocation()\n\t\t\t\tl.SetMappingIndex(1)\n\t\t\t\treturn l\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.MappingTable().AppendEmpty()\n\t\t\t\tm := d.MappingTable().AppendEmpty()\n\t\t\t\tm.SetFilenameStrindex(1)\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a mapping that cannot be found\",\n\t\t\tlocation: func() Location {\n\t\t\t\tl := NewLocation()\n\t\t\t\tl.SetMappingIndex(1)\n\t\t\t\treturn l\n\t\t\t}(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantLocation: func() Location {\n\t\t\t\tl := NewLocation()\n\t\t\t\tl.SetMappingIndex(1)\n\t\t\t\treturn l\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid mapping index 1\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with a mapping index equal to the source table length (boundary condition)\",\n\t\t\tlocation: func() Location {\n\t\t\t\tl := NewLocation()\n\t\t\t\tl.SetMappingIndex(2)\n\t\t\t\treturn l\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.MappingTable().AppendEmpty()\n\t\t\t\td.MappingTable().AppendEmpty()\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantLocation: func() Location {\n\t\t\t\tl := NewLocation()\n\t\t\t\tl.SetMappingIndex(2)\n\t\t\t\treturn l\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid mapping index 2\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing attribute\",\n\t\t\tlocation: func() Location {\n\t\t\t\tl := NewLocation()\n\t\t\t\tl.AttributeIndices().Append(1)\n\t\t\t\treturn l\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\ta := d.AttributeTable().AppendEmpty()\n\t\t\t\ta.SetKeyStrindex(1)\n\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\ta := d.AttributeTable().AppendEmpty()\n\t\t\t\ta.SetKeyStrindex(1)\n\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantLocation: func() Location {\n\t\t\t\tl := NewLocation()\n\t\t\t\tl.AttributeIndices().Append(1)\n\t\t\t\treturn l\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\ta := d.AttributeTable().AppendEmpty()\n\t\t\t\ta.SetKeyStrindex(1)\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an attribute index that does not match anything\",\n\t\t\tlocation: func() Location {\n\t\t\t\tl := NewLocation()\n\t\t\t\tl.AttributeIndices().Append(1)\n\t\t\t\treturn l\n\t\t\t}(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantLocation: func() Location {\n\t\t\t\tl := NewLocation()\n\t\t\t\tl.AttributeIndices().Append(1)\n\t\t\t\treturn l\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid attribute index 1\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with an attribute index equal to the source table length (boundary condition)\",\n\t\t\tlocation: func() Location {\n\t\t\t\tl := NewLocation()\n\t\t\t\tl.AttributeIndices().Append(2)\n\t\t\t\treturn l\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantLocation: func() Location {\n\t\t\t\tl := NewLocation()\n\t\t\t\tl.AttributeIndices().Append(2)\n\t\t\t\treturn l\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid attribute index 2\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing line\",\n\t\t\tlocation: func() Location {\n\t\t\t\tl := NewLocation()\n\t\t\t\tl.Lines().AppendEmpty().SetFunctionIndex(1)\n\t\t\t\treturn l\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.FunctionTable().AppendEmpty()\n\t\t\t\tf := d.FunctionTable().AppendEmpty()\n\t\t\t\tf.SetNameStrindex(1)\n\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.FunctionTable().AppendEmpty()\n\t\t\t\tf := d.FunctionTable().AppendEmpty()\n\t\t\t\tf.SetNameStrindex(1)\n\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantLocation: func() Location {\n\t\t\t\tl := NewLocation()\n\t\t\t\tl.Lines().AppendEmpty().SetFunctionIndex(1)\n\t\t\t\treturn l\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.FunctionTable().AppendEmpty()\n\t\t\t\tf := d.FunctionTable().AppendEmpty()\n\t\t\t\tf.SetNameStrindex(1)\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tl := tt.location\n\t\t\tdst := tt.dst\n\t\t\terr := l.switchDictionary(tt.src, dst)\n\n\t\t\tif tt.wantErr == nil {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.Equal(t, tt.wantErr, err)\n\t\t\t}\n\n\t\t\tassert.Equal(t, tt.wantLocation, l)\n\t\t\tassert.Equal(t, tt.wantDictionary, dst)\n\t\t})\n\t}\n}\n\nfunc BenchmarkLocationSwitchDictionary(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\n\tl := NewLocation()\n\tl.AttributeIndices().Append(1, 2)\n\n\tsrc := NewProfilesDictionary()\n\tsrc.StringTable().Append(\"\", \"test\")\n\tsrc.AttributeTable().AppendEmpty()\n\tsrc.AttributeTable().AppendEmpty().SetKeyStrindex(1)\n\tsrc.AttributeTable().AppendEmpty().SetKeyStrindex(2)\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tb.StopTimer()\n\t\tdst := NewProfilesDictionary()\n\t\tdst.StringTable().Append(\"\", \"foo\")\n\t\tdst.AttributeTable().AppendEmpty()\n\t\tdst.AttributeTable().AppendEmpty().SetKeyStrindex(1)\n\t\tb.StartTimer()\n\n\t\t_ = l.switchDictionary(src, dst)\n\t}\n}\n\nfunc buildLocation(mapIdx int32, addr uint64, attrIdxs []int32, line Line) Location {\n\tl := NewLocation()\n\tl.SetMappingIndex(mapIdx)\n\tl.SetAddress(addr)\n\tl.AttributeIndices().FromRaw(attrIdxs)\n\tline.MoveTo(l.Lines().AppendEmpty())\n\treturn l\n}\n"
  },
  {
    "path": "pdata/pprofile/locations.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport (\n\t\"errors\"\n\t\"math\"\n)\n\n// FromLocationIndices builds a slice containing all the locations of a Stack.\n// Updates made to the returned map will not be applied back to the Stack.\nfunc FromLocationIndices(table LocationSlice, record Stack) LocationSlice {\n\tm := NewLocationSlice()\n\tm.EnsureCapacity(record.LocationIndices().Len())\n\n\tfor _, idx := range record.LocationIndices().All() {\n\t\tl := table.At(int(idx))\n\t\tl.CopyTo(m.AppendEmpty())\n\t}\n\n\treturn m\n}\n\nvar errTooManyLocationTableEntries = errors.New(\"too many entries in LocationTable\")\n\n// SetLocation updates a LocationTable, adding or providing a value and returns\n// its index.\nfunc SetLocation(table LocationSlice, loc Location) (int32, error) {\n\tfor j, a := range table.All() {\n\t\tif a.Equal(loc) {\n\t\t\tif j > math.MaxInt32 {\n\t\t\t\treturn 0, errTooManyLocationTableEntries\n\t\t\t}\n\t\t\treturn int32(j), nil\n\t\t}\n\t}\n\n\tif table.Len() >= math.MaxInt32 {\n\t\treturn 0, errTooManyLocationTableEntries\n\t}\n\n\tloc.CopyTo(table.AppendEmpty())\n\treturn int32(table.Len() - 1), nil\n}\n"
  },
  {
    "path": "pdata/pprofile/locations_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc TestFromLocationIndices(t *testing.T) {\n\ttable := NewLocationSlice()\n\ttable.AppendEmpty().SetAddress(1)\n\ttable.AppendEmpty().SetAddress(2)\n\n\tstack := NewStack()\n\tlocs := FromLocationIndices(table, stack)\n\tassert.Equal(t, locs, NewLocationSlice())\n\n\t// Add a location\n\tstack.LocationIndices().Append(0)\n\tlocs = FromLocationIndices(table, stack)\n\n\ttLoc := NewLocationSlice()\n\ttLoc.AppendEmpty().SetAddress(1)\n\tassert.Equal(t, tLoc, locs)\n\n\t// Add another location\n\tstack.LocationIndices().Append(1)\n\n\tlocs = FromLocationIndices(table, stack)\n\tassert.Equal(t, table, locs)\n}\n\nfunc TestSetLocation(t *testing.T) {\n\ttable := NewLocationSlice()\n\tl := NewLocation()\n\tl.SetAddress(1)\n\tl2 := NewLocation()\n\tl2.SetAddress(2)\n\n\t// Put a first value\n\tidx, err := SetLocation(table, l)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 1, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\n\t// Put the same string\n\t// This should be a no-op.\n\tidx, err = SetLocation(table, l)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 1, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\n\t// Set a new value\n\t// This sets the index and adds to the table.\n\tidx, err = SetLocation(table, l2)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(table.Len()-1), idx)\n\n\t// Set an existing value\n\tidx, err = SetLocation(table, l)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\t// Set another existing value\n\tidx, err = SetLocation(table, l2)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(table.Len()-1), idx)\n}\n\nfunc BenchmarkFromLocationIndices(b *testing.B) {\n\ttable := NewLocationSlice()\n\n\tfor i := range 100 {\n\t\ttable.AppendEmpty().SetAddress(uint64(i))\n\t}\n\n\tobj := NewStack()\n\tfor i := range int32(50) {\n\t\tobj.LocationIndices().Append(2*i + 1)\n\t}\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\t_ = FromLocationIndices(table, obj)\n\t}\n}\n\nfunc BenchmarkSetLocation(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\tfor _, bb := range []struct {\n\t\tname     string\n\t\tlocation Location\n\n\t\trunBefore func(*testing.B, LocationSlice)\n\t}{\n\t\t{\n\t\t\tname:     \"with a new location\",\n\t\t\tlocation: NewLocation(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing location\",\n\t\t\tlocation: func() Location {\n\t\t\t\tl := NewLocation()\n\t\t\t\tl.SetAddress(1)\n\t\t\t\treturn l\n\t\t\t}(),\n\n\t\t\trunBefore: func(_ *testing.B, table LocationSlice) {\n\t\t\t\tl := table.AppendEmpty()\n\t\t\t\tl.SetAddress(1)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:     \"with a duplicate location\",\n\t\t\tlocation: NewLocation(),\n\n\t\t\trunBefore: func(_ *testing.B, table LocationSlice) {\n\t\t\t\t_, err := SetLocation(table, NewLocation())\n\t\t\t\trequire.NoError(b, err)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with a hundred locations to loop through\",\n\t\t\tlocation: func() Location {\n\t\t\t\tl := NewLocation()\n\t\t\t\tl.SetMappingIndex(1)\n\t\t\t\treturn l\n\t\t\t}(),\n\n\t\t\trunBefore: func(_ *testing.B, table LocationSlice) {\n\t\t\t\tfor i := range 100 {\n\t\t\t\t\tl := table.AppendEmpty()\n\t\t\t\t\tl.SetAddress(uint64(i))\n\t\t\t\t}\n\n\t\t\t\tl := table.AppendEmpty()\n\t\t\t\tl.SetMappingIndex(1)\n\t\t\t},\n\t\t},\n\t} {\n\t\tb.Run(bb.name, func(b *testing.B) {\n\t\t\ttable := NewLocationSlice()\n\n\t\t\tif bb.runBefore != nil {\n\t\t\t\tbb.runBefore(b, table)\n\t\t\t}\n\n\t\t\tb.ResetTimer()\n\t\t\tb.ReportAllocs()\n\n\t\t\tfor b.Loop() {\n\t\t\t\t_, _ = SetLocation(table, bb.location)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "pdata/pprofile/mapping.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport \"fmt\"\n\n// Equal checks equality with another Mapping\nfunc (ms Mapping) Equal(val Mapping) bool {\n\treturn ms.MemoryStart() == val.MemoryStart() &&\n\t\tms.MemoryLimit() == val.MemoryLimit() &&\n\t\tms.FileOffset() == val.FileOffset() &&\n\t\tms.FilenameStrindex() == val.FilenameStrindex() &&\n\t\tms.AttributeIndices().Equal(val.AttributeIndices())\n}\n\n// switchDictionary updates the Mapping, switching its indices from one\n// dictionary to another.\nfunc (ms Mapping) switchDictionary(src, dst ProfilesDictionary) error {\n\tif ms.FilenameStrindex() > 0 {\n\t\tif src.StringTable().Len() <= int(ms.FilenameStrindex()) {\n\t\t\treturn fmt.Errorf(\"invalid filename index %d\", ms.FilenameStrindex())\n\t\t}\n\n\t\tidx, err := SetString(dst.StringTable(), src.StringTable().At(int(ms.FilenameStrindex())))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't set filename: %w\", err)\n\t\t}\n\t\tms.SetFilenameStrindex(idx)\n\t}\n\n\tfor i, v := range ms.AttributeIndices().All() {\n\t\tif src.AttributeTable().Len() <= int(v) {\n\t\t\treturn fmt.Errorf(\"invalid attribute index %d\", v)\n\t\t}\n\n\t\tattr := src.AttributeTable().At(int(v))\n\t\tidx, err := SetAttribute(dst.AttributeTable(), attr)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't set attribute %d: %w\", i, err)\n\t\t}\n\t\tms.AttributeIndices().SetAt(i, idx)\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "pdata/pprofile/mapping_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc TestMappingEqual(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname string\n\t\torig Mapping\n\t\tdest Mapping\n\t\twant bool\n\t}{\n\t\t{\n\t\t\tname: \"empty mappings\",\n\t\t\torig: NewMapping(),\n\t\t\tdest: NewMapping(),\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"non-empty identical mappings\",\n\t\t\torig: buildMapping(1, 2, 3, 4, []int32{1, 2}),\n\t\t\tdest: buildMapping(1, 2, 3, 4, []int32{1, 2}),\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"with different MemoryStart\",\n\t\t\torig: buildMapping(1, 2, 3, 4, []int32{1, 2}),\n\t\t\tdest: buildMapping(2, 2, 3, 4, []int32{1, 2}),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with different MemoryLimit\",\n\t\t\torig: buildMapping(1, 2, 3, 4, []int32{1, 2}),\n\t\t\tdest: buildMapping(1, 3, 3, 4, []int32{1, 2}),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with different FileOffset\",\n\t\t\torig: buildMapping(1, 2, 3, 4, []int32{1, 2}),\n\t\t\tdest: buildMapping(1, 2, 4, 4, []int32{1, 2}),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with different FilenameStrindex\",\n\t\t\torig: buildMapping(1, 2, 3, 4, []int32{1, 2}),\n\t\t\tdest: buildMapping(1, 2, 3, 5, []int32{1, 2}),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with different AttributeIndices\",\n\t\t\torig: buildMapping(1, 2, 3, 4, []int32{1, 2}),\n\t\t\tdest: buildMapping(1, 2, 3, 4, []int32{1, 3}),\n\t\t\twant: false,\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif tt.want {\n\t\t\t\tassert.True(t, tt.orig.Equal(tt.dest))\n\t\t\t} else {\n\t\t\t\tassert.False(t, tt.orig.Equal(tt.dest))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMappingSwitchDictionary(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname    string\n\t\tmapping Mapping\n\n\t\tsrc ProfilesDictionary\n\t\tdst ProfilesDictionary\n\n\t\twantMapping    Mapping\n\t\twantDictionary ProfilesDictionary\n\t\twantErr        error\n\t}{\n\t\t{\n\t\t\tname:    \"with an empty mapping\",\n\t\t\tmapping: NewMapping(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantMapping:    NewMapping(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing filename\",\n\t\t\tmapping: func() Mapping {\n\t\t\t\tm := NewMapping()\n\t\t\t\tm.SetFilenameStrindex(1)\n\t\t\t\treturn m\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\")\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantMapping: func() Mapping {\n\t\t\t\tm := NewMapping()\n\t\t\t\tm.SetFilenameStrindex(2)\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a filename index that does not match anything\",\n\t\t\tmapping: func() Mapping {\n\t\t\t\tm := NewMapping()\n\t\t\t\tm.SetFilenameStrindex(1)\n\t\t\t\treturn m\n\t\t\t}(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantMapping: func() Mapping {\n\t\t\t\tm := NewMapping()\n\t\t\t\tm.SetFilenameStrindex(1)\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid filename index 1\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with a filename index equal to the source table length (boundary condition)\",\n\t\t\tmapping: func() Mapping {\n\t\t\t\tm := NewMapping()\n\t\t\t\tm.SetFilenameStrindex(2)\n\t\t\t\treturn m\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantMapping: func() Mapping {\n\t\t\t\tm := NewMapping()\n\t\t\t\tm.SetFilenameStrindex(2)\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid filename index 2\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing attribute\",\n\t\t\tmapping: func() Mapping {\n\t\t\t\tm := NewMapping()\n\t\t\t\tm.AttributeIndices().Append(1)\n\t\t\t\treturn m\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\ta := d.AttributeTable().AppendEmpty()\n\t\t\t\ta.SetKeyStrindex(1)\n\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\ta := d.AttributeTable().AppendEmpty()\n\t\t\t\ta.SetKeyStrindex(1)\n\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantMapping: func() Mapping {\n\t\t\t\tm := NewMapping()\n\t\t\t\tm.AttributeIndices().Append(1)\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\ta := d.AttributeTable().AppendEmpty()\n\t\t\t\ta.SetKeyStrindex(1)\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an attribute index that does not match anything\",\n\t\t\tmapping: func() Mapping {\n\t\t\t\tm := NewMapping()\n\t\t\t\tm.AttributeIndices().Append(1)\n\t\t\t\treturn m\n\t\t\t}(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantMapping: func() Mapping {\n\t\t\t\tm := NewMapping()\n\t\t\t\tm.AttributeIndices().Append(1)\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid attribute index 1\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with an attribute index equal to the source table length (boundary condition)\",\n\t\t\tmapping: func() Mapping {\n\t\t\t\tm := NewMapping()\n\t\t\t\tm.AttributeIndices().Append(2)\n\t\t\t\treturn m\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantMapping: func() Mapping {\n\t\t\t\tm := NewMapping()\n\t\t\t\tm.AttributeIndices().Append(2)\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid attribute index 2\"),\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tm := tt.mapping\n\t\t\tdst := tt.dst\n\t\t\terr := m.switchDictionary(tt.src, dst)\n\n\t\t\tif tt.wantErr == nil {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.Equal(t, tt.wantErr, err)\n\t\t\t}\n\n\t\t\tassert.Equal(t, tt.wantMapping, m)\n\t\t\tassert.Equal(t, tt.wantDictionary, dst)\n\t\t})\n\t}\n}\n\nfunc BenchmarkMappingSwitchDictionary(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\n\tm := NewMapping()\n\tm.AttributeIndices().Append(1, 2)\n\n\tsrc := NewProfilesDictionary()\n\tsrc.StringTable().Append(\"\", \"test\", \"foo\")\n\tsrc.AttributeTable().AppendEmpty()\n\tsrc.AttributeTable().AppendEmpty().SetKeyStrindex(1)\n\tsrc.AttributeTable().AppendEmpty().SetKeyStrindex(2)\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tb.StopTimer()\n\t\tdst := NewProfilesDictionary()\n\t\tdst.StringTable().Append(\"\", \"foo\")\n\t\tdst.AttributeTable().AppendEmpty()\n\t\tdst.AttributeTable().AppendEmpty().SetKeyStrindex(1)\n\t\tb.StartTimer()\n\n\t\t_ = m.switchDictionary(src, dst)\n\t}\n}\n\nfunc buildMapping(memStart, memLimit, fileOffset uint64, filenameIdx int32, attrIdxs []int32) Mapping {\n\tm := NewMapping()\n\tm.SetMemoryStart(memStart)\n\tm.SetMemoryLimit(memLimit)\n\tm.SetFileOffset(fileOffset)\n\tm.SetFilenameStrindex(filenameIdx)\n\tm.AttributeIndices().FromRaw(attrIdxs)\n\treturn m\n}\n"
  },
  {
    "path": "pdata/pprofile/mappings.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport (\n\t\"errors\"\n\t\"math\"\n)\n\nvar errTooManyMappingTableEntries = errors.New(\"too many entries in MappingTable\")\n\n// SetMapping updates a MappingTable, adding or providing a value and returns\n// its index.\nfunc SetMapping(table MappingSlice, ma Mapping) (int32, error) {\n\tfor j, m := range table.All() {\n\t\tif m.Equal(ma) {\n\t\t\tif j > math.MaxInt32 {\n\t\t\t\treturn 0, errTooManyMappingTableEntries\n\t\t\t}\n\t\t\treturn int32(j), nil\n\t\t}\n\t}\n\n\tif table.Len() >= math.MaxInt32 {\n\t\treturn 0, errTooManyMappingTableEntries\n\t}\n\n\tma.CopyTo(table.AppendEmpty())\n\treturn int32(table.Len() - 1), nil\n}\n"
  },
  {
    "path": "pdata/pprofile/mappings_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc TestSetMapping(t *testing.T) {\n\ttable := NewMappingSlice()\n\tm := NewMapping()\n\tm.SetMemoryLimit(1)\n\tm2 := NewMapping()\n\tm2.SetMemoryLimit(2)\n\n\t// Put a first mapping\n\tidx, err := SetMapping(table, m)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 1, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\n\t// Put the same mapping\n\t// This should be a no-op.\n\tidx, err = SetMapping(table, m)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 1, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\n\t// Set a new mapping\n\t// This sets the index and adds to the table.\n\tidx, err = SetMapping(table, m2)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(table.Len()-1), idx)\n\n\t// Set an existing mapping\n\tidx, err = SetMapping(table, m)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\t// Set another existing mapping\n\tidx, err = SetMapping(table, m2)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(table.Len()-1), idx)\n}\n\nfunc BenchmarkSetMapping(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\tfor _, bb := range []struct {\n\t\tname    string\n\t\tmapping Mapping\n\n\t\trunBefore func(*testing.B, MappingSlice)\n\t}{\n\t\t{\n\t\t\tname:    \"with a new mapping\",\n\t\t\tmapping: NewMapping(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing mapping\",\n\t\t\tmapping: func() Mapping {\n\t\t\t\tm := NewMapping()\n\t\t\t\tm.SetMemoryLimit(1)\n\t\t\t\treturn m\n\t\t\t}(),\n\n\t\t\trunBefore: func(_ *testing.B, table MappingSlice) {\n\t\t\t\tm := table.AppendEmpty()\n\t\t\t\tm.SetMemoryLimit(1)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:    \"with a duplicate mapping\",\n\t\t\tmapping: NewMapping(),\n\n\t\t\trunBefore: func(_ *testing.B, table MappingSlice) {\n\t\t\t\t_, err := SetMapping(table, NewMapping())\n\t\t\t\trequire.NoError(b, err)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with a hundred mappings to loop through\",\n\t\t\tmapping: func() Mapping {\n\t\t\t\tm := NewMapping()\n\t\t\t\tm.SetMemoryLimit(1)\n\t\t\t\treturn m\n\t\t\t}(),\n\n\t\t\trunBefore: func(_ *testing.B, table MappingSlice) {\n\t\t\t\tfor i := range 100 {\n\t\t\t\t\tm := table.AppendEmpty()\n\t\t\t\t\tm.SetMemoryLimit(uint64(i))\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t} {\n\t\tb.Run(bb.name, func(b *testing.B) {\n\t\t\ttable := NewMappingSlice()\n\n\t\t\tif bb.runBefore != nil {\n\t\t\t\tbb.runBefore(b, table)\n\t\t\t}\n\n\t\t\tb.ResetTimer()\n\t\t\tb.ReportAllocs()\n\n\t\t\tfor b.Loop() {\n\t\t\t\t_, _ = SetMapping(table, bb.mapping)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "pdata/pprofile/metadata.yaml",
    "content": "type: pprofile\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pdata\n  codeowners:\n    active:\n      - mx-psi\n      - dmathieu\n  stability:\n    alpha: [profiles]\n"
  },
  {
    "path": "pdata/pprofile/pb.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nvar _ MarshalSizer = (*ProtoMarshaler)(nil)\n\ntype ProtoMarshaler struct{}\n\nfunc (e *ProtoMarshaler) MarshalProfiles(pd Profiles) ([]byte, error) {\n\t// Convert strings to references for efficient transmission\n\tconvertProfilesToReferences(pd)\n\n\tsize := pd.getOrig().SizeProto()\n\tbuf := make([]byte, size)\n\t_ = pd.getOrig().MarshalProto(buf)\n\treturn buf, nil\n}\n\nfunc (e *ProtoMarshaler) ProfilesSize(pd Profiles) int {\n\treturn pd.getOrig().SizeProto()\n}\n\nfunc (e *ProtoMarshaler) ResourceProfilesSize(pd ResourceProfiles) int {\n\treturn pd.orig.SizeProto()\n}\n\nfunc (e *ProtoMarshaler) ScopeProfilesSize(pd ScopeProfiles) int {\n\treturn pd.orig.SizeProto()\n}\n\nfunc (e *ProtoMarshaler) ProfileSize(pd Profile) int {\n\treturn pd.orig.SizeProto()\n}\n\ntype ProtoUnmarshaler struct{}\n\nfunc (d *ProtoUnmarshaler) UnmarshalProfiles(buf []byte) (Profiles, error) {\n\tpd := NewProfiles()\n\terr := pd.getOrig().UnmarshalProto(buf)\n\tif err != nil {\n\t\treturn Profiles{}, err\n\t}\n\n\t// Resolve all string_value_ref and key_ref to their actual strings\n\t// so the pdata API works transparently\n\tresolveProfilesReferences(pd)\n\n\treturn pd, nil\n}\n"
  },
  {
    "path": "pdata/pprofile/pb_references_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestMarshalUnmarshalWithReferences(t *testing.T) {\n\tprofiles := NewProfiles()\n\n\tdict := profiles.Dictionary()\n\tdict.StringTable().Append(\"\") // index 0, required empty string\n\n\trp := profiles.ResourceProfiles().AppendEmpty()\n\trp.Resource().Attributes().PutStr(\"service.name\", \"test-service\")\n\trp.Resource().Attributes().PutStr(\"host.name\", \"test-host\")\n\n\tsp := rp.ScopeProfiles().AppendEmpty()\n\tsp.Scope().SetName(\"test-scope\")\n\tsp.Scope().Attributes().PutStr(\"scope.attr\", \"scope-value\")\n\n\tprofile := sp.Profiles().AppendEmpty()\n\tprofile.SetProfileID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16})\n\n\t// Marshal to proto bytes\n\tmarshaler := ProtoMarshaler{}\n\tbytes, err := marshaler.MarshalProfiles(profiles)\n\trequire.NoError(t, err)\n\trequire.NotEmpty(t, bytes)\n\n\t// Verify that string table was populated (should have more than just the empty string)\n\tassert.Greater(t, dict.StringTable().Len(), 1, \"String table should be populated during marshal\")\n\n\t// Verify references were created in the resource attributes\n\tmapOrig := internal.GetMapOrig(internal.MapWrapper(rp.Resource().Attributes()))\n\tfoundRef := false\n\tfor i := 0; i < len(*mapOrig); i++ {\n\t\tkv := (*mapOrig)[i]\n\t\tif kv.KeyStrindex != 0 {\n\t\t\tfoundRef = true\n\t\t\tbreak\n\t\t}\n\t\t// Check if value is a string reference\n\t\tif ref, ok := kv.Value.Value.(*internal.AnyValue_StringValueStrindex); ok && ref.StringValueStrindex != 0 {\n\t\t\tfoundRef = true\n\t\t\tbreak\n\t\t}\n\t}\n\tassert.True(t, foundRef, \"At least one reference should be created in attributes\")\n\n\t// Unmarshal from proto bytes\n\tunmarshaler := ProtoUnmarshaler{}\n\tprofiles2, err := unmarshaler.UnmarshalProfiles(bytes)\n\trequire.NoError(t, err)\n\n\t// Verify that the API works correctly - attributes should be accessible as strings\n\trp2 := profiles2.ResourceProfiles().At(0)\n\tserviceNameVal, ok := rp2.Resource().Attributes().Get(\"service.name\")\n\tassert.True(t, ok, \"service.name attribute should exist\")\n\tassert.Equal(t, \"test-service\", serviceNameVal.Str(), \"service.name should be resolved to string\")\n\n\thostNameVal, ok := rp2.Resource().Attributes().Get(\"host.name\")\n\tassert.True(t, ok, \"host.name attribute should exist\")\n\tassert.Equal(t, \"test-host\", hostNameVal.Str(), \"host.name should be resolved to string\")\n\n\tsp2 := rp2.ScopeProfiles().At(0)\n\tscopeAttrVal, ok := sp2.Scope().Attributes().Get(\"scope.attr\")\n\tassert.True(t, ok, \"scope.attr attribute should exist\")\n\tassert.Equal(t, \"scope-value\", scopeAttrVal.Str(), \"scope.attr should be resolved to string\")\n\n\t// Verify the string table is preserved\n\tdict2 := profiles2.Dictionary()\n\tassert.Greater(t, dict2.StringTable().Len(), 1, \"String table should be preserved after unmarshal\")\n}\n\nfunc TestMarshalUnmarshalNestedValues(t *testing.T) {\n\tprofiles := NewProfiles()\n\tdict := profiles.Dictionary()\n\tdict.StringTable().Append(\"\") // index 0\n\n\trp := profiles.ResourceProfiles().AppendEmpty()\n\tattrs := rp.Resource().Attributes()\n\n\tkvlist := attrs.PutEmptyMap(\"nested.map\")\n\tkvlist.PutStr(\"inner.key1\", \"inner.value1\")\n\tkvlist.PutStr(\"inner.key2\", \"inner.value2\")\n\n\tarr := attrs.PutEmptySlice(\"string.array\")\n\tarr.AppendEmpty().SetStr(\"string1\")\n\tarr.AppendEmpty().SetStr(\"string2\")\n\tarr.AppendEmpty().SetStr(\"string3\")\n\n\t// Marshal and unmarshal\n\tmarshaler := ProtoMarshaler{}\n\tbytes, err := marshaler.MarshalProfiles(profiles)\n\trequire.NoError(t, err)\n\n\tunmarshaler := ProtoUnmarshaler{}\n\tprofiles2, err := unmarshaler.UnmarshalProfiles(bytes)\n\trequire.NoError(t, err)\n\n\t// Verify nested map values are accessible\n\trp2 := profiles2.ResourceProfiles().At(0)\n\tkvlist2, ok := rp2.Resource().Attributes().Get(\"nested.map\")\n\tassert.True(t, ok)\n\tassert.Equal(t, pcommon.ValueTypeMap, kvlist2.Type())\n\n\tinnerMap := kvlist2.Map()\n\tinnerVal1, ok := innerMap.Get(\"inner.key1\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"inner.value1\", innerVal1.Str())\n\n\tinnerVal2, ok := innerMap.Get(\"inner.key2\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"inner.value2\", innerVal2.Str())\n\n\t// Verify array values are accessible\n\tarr2, ok := rp2.Resource().Attributes().Get(\"string.array\")\n\tassert.True(t, ok)\n\tassert.Equal(t, pcommon.ValueTypeSlice, arr2.Type())\n\n\tslice := arr2.Slice()\n\tassert.Equal(t, 3, slice.Len())\n\tassert.Equal(t, \"string1\", slice.At(0).Str())\n\tassert.Equal(t, \"string2\", slice.At(1).Str())\n\tassert.Equal(t, \"string3\", slice.At(2).Str())\n}\n\nfunc TestRoundTripWithReferences(t *testing.T) {\n\toriginal := NewProfiles()\n\tdict := original.Dictionary()\n\tdict.StringTable().Append(\"\")\n\n\tfor i := range 3 {\n\t\trp := original.ResourceProfiles().AppendEmpty()\n\t\trp.Resource().Attributes().PutStr(\"resource.id\", \"resource-\"+string(rune('A'+i)))\n\n\t\tfor j := range 2 {\n\t\t\tsp := rp.ScopeProfiles().AppendEmpty()\n\t\t\tsp.Scope().SetName(\"scope-\" + string(rune('X'+j)))\n\t\t\tsp.Scope().Attributes().PutStr(\"scope.version\", \"1.0.0\")\n\n\t\t\tprofile := sp.Profiles().AppendEmpty()\n\t\t\tprofile.SetProfileID([16]byte{byte(i), byte(j)})\n\t\t}\n\t}\n\n\t// Marshal\n\tmarshaler := ProtoMarshaler{}\n\tbytes, err := marshaler.MarshalProfiles(original)\n\trequire.NoError(t, err)\n\n\t// Unmarshal\n\tunmarshaler := ProtoUnmarshaler{}\n\trestored, err := unmarshaler.UnmarshalProfiles(bytes)\n\trequire.NoError(t, err)\n\n\t// Verify structure is preserved\n\tassert.Equal(t, 3, restored.ResourceProfiles().Len())\n\n\tfor i := range 3 {\n\t\trp := restored.ResourceProfiles().At(i)\n\t\tresourceID, ok := rp.Resource().Attributes().Get(\"resource.id\")\n\t\tassert.True(t, ok)\n\t\tassert.Equal(t, \"resource-\"+string(rune('A'+i)), resourceID.Str())\n\n\t\tassert.Equal(t, 2, rp.ScopeProfiles().Len())\n\t\tfor j := range 2 {\n\t\t\tsp := rp.ScopeProfiles().At(j)\n\t\t\tassert.Equal(t, \"scope-\"+string(rune('X'+j)), sp.Scope().Name())\n\n\t\t\tscopeVersion, ok := sp.Scope().Attributes().Get(\"scope.version\")\n\t\t\tassert.True(t, ok)\n\t\t\tassert.Equal(t, \"1.0.0\", scopeVersion.Str())\n\n\t\t\tassert.Equal(t, 1, sp.Profiles().Len())\n\t\t}\n\t}\n\n\t// Verify the string table deduplication worked\n\t// We should have fewer strings than if everything was duplicated\n\tdictRestored := restored.Dictionary()\n\t// At minimum we have: \"\", \"resource.id\", \"resource-A\", \"resource-B\", \"resource-C\",\n\t// \"scope.version\", \"1.0.0\" = 7 entries\n\t// May have more due to scope names\n\tassert.LessOrEqual(t, dictRestored.StringTable().Len(), 7,\n\t\t\"String table should deduplicate strings efficiently\")\n}\n"
  },
  {
    "path": "pdata/pprofile/pb_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tsemconv \"go.opentelemetry.io/otel/semconv/v1.38.0\"\n\tgootlpprofiles \"go.opentelemetry.io/proto/slim/otlp/profiles/v1development\"\n\tgoproto \"google.golang.org/protobuf/proto\"\n)\n\nfunc TestProfilesProtoWireCompatibility(t *testing.T) {\n\t// This test verifies that OTLP ProtoBufs generated using goproto lib in\n\t// opentelemetry-proto repository OTLP ProtoBufs generated using gogoproto lib in\n\t// this repository are wire compatible.\n\n\t// Generate Profiles as pdata struct.\n\ttd := generateTestProfiles()\n\n\t// Marshal its underlying ProtoBuf to wire.\n\tmarshaler := &ProtoMarshaler{}\n\twire1, err := marshaler.MarshalProfiles(td)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, wire1)\n\n\t// Unmarshal from the wire to OTLP Protobuf in goproto's representation.\n\tvar goprotoMessage gootlpprofiles.ProfilesData\n\terr = goproto.Unmarshal(wire1, &goprotoMessage)\n\trequire.NoError(t, err)\n\n\t// Marshal to the wire again.\n\twire2, err := goproto.Marshal(&goprotoMessage)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, wire2)\n\n\t// Unmarshal from the wire into gogoproto's representation.\n\tvar td2 Profiles\n\tunmarshaler := &ProtoUnmarshaler{}\n\ttd2, err = unmarshaler.UnmarshalProfiles(wire2)\n\trequire.NoError(t, err)\n\n\t// After unmarshal, td2 will have resolved references (strings instead of string_value_ref/key_ref)\n\t// while td may have references. Marshal td2 again to verify wire compatibility.\n\twire3, err := marshaler.MarshalProfiles(td2)\n\trequire.NoError(t, err)\n\n\t// Verify full round-trip fidelity: unmarshal both wire1 and wire3 into goproto\n\t// messages and compare them semantically. This ensures all data (attributes,\n\t// dictionary, profiles, etc.) survives the round-trip through both libraries.\n\tvar check1, check2 gootlpprofiles.ProfilesData\n\trequire.NoError(t, goproto.Unmarshal(wire1, &check1))\n\trequire.NoError(t, goproto.Unmarshal(wire3, &check2))\n\tassert.True(t, goproto.Equal(&check1, &check2), \"round-trip through goproto did not preserve profile data\")\n}\n\nfunc TestProtoProfilesUnmarshalerError(t *testing.T) {\n\tp := &ProtoUnmarshaler{}\n\t_, err := p.UnmarshalProfiles([]byte(\"+$%\"))\n\tassert.Error(t, err)\n}\n\nfunc TestProtoSizer(t *testing.T) {\n\tmarshaler := &ProtoMarshaler{}\n\ttd := NewProfiles()\n\ttd.ResourceProfiles().AppendEmpty().ScopeProfiles().AppendEmpty().Profiles().AppendEmpty()\n\ttd.Dictionary().StringTable().Append(\"foobar\")\n\n\tsize := marshaler.ProfilesSize(td)\n\n\tbytes, err := marshaler.MarshalProfiles(td)\n\trequire.NoError(t, err)\n\tassert.Equal(t, len(bytes), size)\n}\n\nfunc TestProtoSizerEmptyProfiles(t *testing.T) {\n\tsizer := &ProtoMarshaler{}\n\tassert.Equal(t, 2, sizer.ProfilesSize(NewProfiles()))\n}\n\nfunc BenchmarkProfilesToProto(b *testing.B) {\n\tmarshaler := &ProtoMarshaler{}\n\tprofiles := generateBenchmarkProfiles(128)\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tbuf, err := marshaler.MarshalProfiles(profiles)\n\t\trequire.NoError(b, err)\n\t\tassert.NotEmpty(b, buf)\n\t}\n}\n\nfunc BenchmarkProfilesFromProto(b *testing.B) {\n\tmarshaler := &ProtoMarshaler{}\n\tunmarshaler := &ProtoUnmarshaler{}\n\tbaseProfiles := generateBenchmarkProfiles(128)\n\tbuf, err := marshaler.MarshalProfiles(baseProfiles)\n\trequire.NoError(b, err)\n\tassert.NotEmpty(b, buf)\n\n\tb.ResetTimer()\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\tprofiles, err := unmarshaler.UnmarshalProfiles(buf)\n\t\trequire.NoError(b, err)\n\t\tassert.Equal(b, baseProfiles.ResourceProfiles().Len(), profiles.ResourceProfiles().Len())\n\t}\n}\n\nfunc generateBenchmarkProfiles(samplesCount int) Profiles {\n\tmd := NewProfiles()\n\tilm := md.ResourceProfiles().AppendEmpty().ScopeProfiles().AppendEmpty().Profiles().AppendEmpty()\n\tilm.Samples().EnsureCapacity(samplesCount)\n\tfor range samplesCount {\n\t\tim := ilm.Samples().AppendEmpty()\n\t\tim.SetStackIndex(0)\n\t}\n\treturn md\n}\n\n// generateProfiles creates a Profiles object with the specified number of resources, scopes, profiles, and samples.\nfunc generateProfiles(b *testing.B, resourceCount, scopeCount, profileCount, sampleCount int) Profiles {\n\tb.Helper()\n\n\tprofiles := NewProfiles()\n\tdict := profiles.Dictionary()\n\n\t// Pre-populate dictionary with common strings\n\tdict.StringTable().Append(\"\") // Index 0 is always empty string\n\tdict.StringTable().Append(\"cpu\")\n\tdict.StringTable().Append(\"nanoseconds\")\n\tdict.StringTable().Append(\"samples\")\n\tdict.StringTable().Append(\"count\")\n\n\t// Generate resource profiles\n\tfor r := range resourceCount {\n\t\trp := profiles.ResourceProfiles().AppendEmpty()\n\t\trp.SetSchemaUrl(semconv.SchemaURL)\n\t\tresource := rp.Resource()\n\n\t\t// Add resource attributes\n\t\tattrs := resource.Attributes()\n\t\tattrs.PutStr(string(semconv.ServiceNameKey), fmt.Sprintf(\"service-%d\", r))\n\t\tattrs.PutStr(string(semconv.ServiceVersionKey), fmt.Sprintf(\"version-%d\", r))\n\t\tattrs.PutStr(string(semconv.ProcessPIDKey), strconv.Itoa(1000+r))\n\t\tattrs.PutStr(string(semconv.K8SPodNameKey), fmt.Sprintf(\"pod-%d\", r%10))\n\t\tattrs.PutStr(string(semconv.K8SNamespaceNameKey), \"default\")\n\t\tattrs.PutStr(string(semconv.TelemetrySDKNameKey), \"opentelemetry\")\n\n\t\t// Generate scope profiles\n\t\tfor s := range scopeCount {\n\t\t\tsp := rp.ScopeProfiles().AppendEmpty()\n\t\t\tsp.SetSchemaUrl(semconv.SchemaURL)\n\t\t\tscope := sp.Scope()\n\t\t\tscope.SetName(fmt.Sprintf(\"profiler-scope-%d\", s))\n\t\t\tscope.SetVersion(\"1.0.0\")\n\n\t\t\t// Generate profiles\n\t\t\tfor range profileCount {\n\t\t\t\tprofile := sp.Profiles().AppendEmpty()\n\n\t\t\t\t// Add sample types\n\t\t\t\tsampleType := profile.SampleType()\n\t\t\t\tsampleType.SetTypeStrindex(1) // \"cpu\"\n\t\t\t\tsampleType.SetUnitStrindex(2) // \"nanoseconds\"\n\n\t\t\t\t// Add period type\n\t\t\t\tperiodType := profile.PeriodType()\n\t\t\t\tperiodType.SetTypeStrindex(1) // \"cpu\"\n\t\t\t\tperiodType.SetUnitStrindex(2) // \"nanoseconds\"\n\t\t\t\tprofile.SetPeriod(1000000)\n\n\t\t\t\t// Generate samples\n\t\t\t\tsamples := profile.Samples()\n\t\t\t\tfor i := range sampleCount {\n\t\t\t\t\tsample := samples.AppendEmpty()\n\t\t\t\t\tsample.SetStackIndex(int32(i % 100))\n\n\t\t\t\t\t// Add attribute indices for samples\n\t\t\t\t\tsample.AttributeIndices().Append(int32(i % 10))\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\treturn profiles\n}\n\nfunc BenchmarkUnmarshalProfiles(b *testing.B) {\n\ttestCases := []struct {\n\t\tname          string\n\t\tresourceCount int\n\t\tscopeCount    int\n\t\tprofileCount  int\n\t\tsampleCount   int\n\t}{\n\t\t{\n\t\t\tname:          \"small\",\n\t\t\tresourceCount: 1,\n\t\t\tscopeCount:    1,\n\t\t\tprofileCount:  1,\n\t\t\tsampleCount:   100,\n\t\t},\n\t\t{\n\t\t\tname:          \"medium\",\n\t\t\tresourceCount: 5,\n\t\t\tscopeCount:    2,\n\t\t\tprofileCount:  2,\n\t\t\tsampleCount:   500,\n\t\t},\n\t\t{\n\t\t\tname:          \"large\",\n\t\t\tresourceCount: 20,\n\t\t\tscopeCount:    3,\n\t\t\tprofileCount:  5,\n\t\t\tsampleCount:   1000,\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tb.Run(tc.name, func(b *testing.B) {\n\t\t\t// Generate profile data and marshal it\n\t\t\tprofiles := generateProfiles(b, tc.resourceCount, tc.scopeCount, tc.profileCount, tc.sampleCount)\n\t\t\tmarshaler := &ProtoMarshaler{}\n\t\t\tdata, err := marshaler.MarshalProfiles(profiles)\n\t\t\tif err != nil {\n\t\t\t\tb.Fatalf(\"failed to marshal profiles: %v\", err)\n\t\t\t}\n\n\t\t\tunmarshaler := &ProtoUnmarshaler{}\n\t\t\tb.ResetTimer()\n\t\t\tb.ReportAllocs()\n\n\t\t\tfor i := 0; i < b.N; i++ {\n\t\t\t\tprofiles, err := unmarshaler.UnmarshalProfiles(data)\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Fatalf(\"failed to unmarshal: %v\", err)\n\t\t\t\t}\n\t\t\t\t_ = profiles\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc BenchmarkMarshalProfiles(b *testing.B) {\n\ttestCases := []struct {\n\t\tname          string\n\t\tresourceCount int\n\t\tscopeCount    int\n\t\tprofileCount  int\n\t\tsampleCount   int\n\t}{\n\t\t{\n\t\t\tname:          \"small\",\n\t\t\tresourceCount: 1,\n\t\t\tscopeCount:    1,\n\t\t\tprofileCount:  1,\n\t\t\tsampleCount:   100,\n\t\t},\n\t\t{\n\t\t\tname:          \"medium\",\n\t\t\tresourceCount: 5,\n\t\t\tscopeCount:    2,\n\t\t\tprofileCount:  2,\n\t\t\tsampleCount:   500,\n\t\t},\n\t\t{\n\t\t\tname:          \"large\",\n\t\t\tresourceCount: 20,\n\t\t\tscopeCount:    3,\n\t\t\tprofileCount:  5,\n\t\t\tsampleCount:   1000,\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tb.Run(tc.name, func(b *testing.B) {\n\t\t\tmarshaler := &ProtoMarshaler{}\n\n\t\t\t// with_refs: simulate the normal ingest path where data was\n\t\t\t// received on the wire (refs present), then unmarshaled (refs\n\t\t\t// resolved but KeyRef kept), and is now being re-marshaled\n\t\t\t// without any attribute modifications.\n\t\t\tb.Run(\"with_refs\", func(b *testing.B) {\n\t\t\t\tprofiles := generateProfiles(b, tc.resourceCount, tc.scopeCount, tc.profileCount, tc.sampleCount)\n\t\t\t\tunmarshaler := &ProtoUnmarshaler{}\n\t\t\t\tbuf, err := marshaler.MarshalProfiles(profiles)\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Fatalf(\"failed to marshal: %v\", err)\n\t\t\t\t}\n\t\t\t\tprofiles, err = unmarshaler.UnmarshalProfiles(buf)\n\t\t\t\tif err != nil {\n\t\t\t\t\tb.Fatalf(\"failed to unmarshal: %v\", err)\n\t\t\t\t}\n\n\t\t\t\tb.ResetTimer()\n\t\t\t\tb.ReportAllocs()\n\n\t\t\t\tfor i := 0; i < b.N; i++ {\n\t\t\t\t\tbuf, err := marshaler.MarshalProfiles(profiles)\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tb.Fatalf(\"failed to marshal: %v\", err)\n\t\t\t\t\t}\n\t\t\t\t\t_ = buf\n\t\t\t\t}\n\t\t\t})\n\n\t\t\t// without_refs: each iteration gets a fresh copy with no refs,\n\t\t\t// simulating data that was constructed or had attributes modified.\n\t\t\tb.Run(\"without_refs\", func(b *testing.B) {\n\t\t\t\tcopies := make([]Profiles, b.N)\n\t\t\t\tfor i := range copies {\n\t\t\t\t\tcopies[i] = generateProfiles(b, tc.resourceCount, tc.scopeCount, tc.profileCount, tc.sampleCount)\n\t\t\t\t}\n\n\t\t\t\tb.ResetTimer()\n\t\t\t\tb.ReportAllocs()\n\n\t\t\t\tfor i := 0; i < b.N; i++ {\n\t\t\t\t\tbuf, err := marshaler.MarshalProfiles(copies[i])\n\t\t\t\t\tif err != nil {\n\t\t\t\t\t\tb.Fatalf(\"failed to marshal: %v\", err)\n\t\t\t\t\t}\n\t\t\t\t\t_ = buf\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "pdata/pprofile/pprofileotlp/fuzz_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofileotlp // import \"go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp\"\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar unexpectedBytes = \"expected the same bytes from unmarshaling and marshaling.\"\n\nfunc FuzzRequestUnmarshalJSON(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\ter := NewExportRequest()\n\t\terr := er.UnmarshalJSON(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tb1, err := er.MarshalJSON()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\ter = NewExportRequest()\n\t\trequire.NoError(t, er.UnmarshalJSON(b1), \"failed to unmarshal valid bytes\")\n\t\tb2, err := er.MarshalJSON()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n\nfunc FuzzResponseUnmarshalJSON(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\ter := NewExportResponse()\n\t\terr := er.UnmarshalJSON(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tb1, err := er.MarshalJSON()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\ter = NewExportResponse()\n\t\trequire.NoError(t, er.UnmarshalJSON(b1), \"failed to unmarshal valid bytes\")\n\t\tb2, err := er.MarshalJSON()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n\nfunc FuzzRequestUnmarshalProto(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\ter := NewExportRequest()\n\t\terr := er.UnmarshalProto(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tb1, err := er.MarshalProto()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\ter = NewExportRequest()\n\t\trequire.NoError(t, er.UnmarshalProto(b1), \"failed to unmarshal valid bytes\")\n\t\tb2, err := er.MarshalProto()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n\nfunc FuzzResponseUnmarshalProto(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\ter := NewExportResponse()\n\t\terr := er.UnmarshalProto(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tb1, err := er.MarshalProto()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\ter = NewExportResponse()\n\t\trequire.NoError(t, er.UnmarshalProto(b1), \"failed to unmarshal valid bytes\")\n\t\tb2, err := er.MarshalProto()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n"
  },
  {
    "path": "pdata/pprofile/pprofileotlp/generated_exportpartialsuccess.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofileotlp\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ExportPartialSuccess represents the details of a partially successful export request.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewExportPartialSuccess function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ExportPartialSuccess struct {\n\torig  *internal.ExportProfilesPartialSuccess\n\tstate *internal.State\n}\n\nfunc newExportPartialSuccess(orig *internal.ExportProfilesPartialSuccess, state *internal.State) ExportPartialSuccess {\n\treturn ExportPartialSuccess{orig: orig, state: state}\n}\n\n// NewExportPartialSuccess creates a new empty ExportPartialSuccess.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewExportPartialSuccess() ExportPartialSuccess {\n\treturn newExportPartialSuccess(internal.NewExportProfilesPartialSuccess(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ExportPartialSuccess) MoveTo(dest ExportPartialSuccess) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteExportProfilesPartialSuccess(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// RejectedProfiles returns the rejectedprofiles associated with this ExportPartialSuccess.\nfunc (ms ExportPartialSuccess) RejectedProfiles() int64 {\n\treturn ms.orig.RejectedProfiles\n}\n\n// SetRejectedProfiles replaces the rejectedprofiles associated with this ExportPartialSuccess.\nfunc (ms ExportPartialSuccess) SetRejectedProfiles(v int64) {\n\tms.state.AssertMutable()\n\tms.orig.RejectedProfiles = v\n}\n\n// ErrorMessage returns the errormessage associated with this ExportPartialSuccess.\nfunc (ms ExportPartialSuccess) ErrorMessage() string {\n\treturn ms.orig.ErrorMessage\n}\n\n// SetErrorMessage replaces the errormessage associated with this ExportPartialSuccess.\nfunc (ms ExportPartialSuccess) SetErrorMessage(v string) {\n\tms.state.AssertMutable()\n\tms.orig.ErrorMessage = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ExportPartialSuccess) CopyTo(dest ExportPartialSuccess) {\n\tdest.state.AssertMutable()\n\tinternal.CopyExportProfilesPartialSuccess(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pprofile/pprofileotlp/generated_exportpartialsuccess_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofileotlp\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestExportPartialSuccess_MoveTo(t *testing.T) {\n\tms := generateTestExportPartialSuccess()\n\tdest := NewExportPartialSuccess()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewExportPartialSuccess(), ms)\n\tassert.Equal(t, generateTestExportPartialSuccess(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestExportPartialSuccess(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newExportPartialSuccess(internal.NewExportProfilesPartialSuccess(), sharedState)) })\n\tassert.Panics(t, func() { newExportPartialSuccess(internal.NewExportProfilesPartialSuccess(), sharedState).MoveTo(dest) })\n}\n\nfunc TestExportPartialSuccess_CopyTo(t *testing.T) {\n\tms := NewExportPartialSuccess()\n\torig := NewExportPartialSuccess()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestExportPartialSuccess()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newExportPartialSuccess(internal.NewExportProfilesPartialSuccess(), sharedState)) })\n}\n\nfunc TestExportPartialSuccess_RejectedProfiles(t *testing.T) {\n\tms := NewExportPartialSuccess()\n\tassert.Equal(t, int64(0), ms.RejectedProfiles())\n\tms.SetRejectedProfiles(int64(13))\n\tassert.Equal(t, int64(13), ms.RejectedProfiles())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewExportPartialSuccess(internal.NewExportProfilesPartialSuccess(), sharedState).SetRejectedProfiles(int64(13))\n\t})\n}\n\nfunc TestExportPartialSuccess_ErrorMessage(t *testing.T) {\n\tms := NewExportPartialSuccess()\n\tassert.Empty(t, ms.ErrorMessage())\n\tms.SetErrorMessage(\"test_errormessage\")\n\tassert.Equal(t, \"test_errormessage\", ms.ErrorMessage())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewExportPartialSuccess(internal.NewExportProfilesPartialSuccess(), sharedState).SetErrorMessage(\"test_errormessage\")\n\t})\n}\n\nfunc generateTestExportPartialSuccess() ExportPartialSuccess {\n\treturn newExportPartialSuccess(internal.GenTestExportProfilesPartialSuccess(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pprofile/pprofileotlp/generated_exportresponse.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofileotlp\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ExportResponse represents the response for gRPC/HTTP client/server.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewExportResponse function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ExportResponse struct {\n\torig  *internal.ExportProfilesServiceResponse\n\tstate *internal.State\n}\n\nfunc newExportResponse(orig *internal.ExportProfilesServiceResponse, state *internal.State) ExportResponse {\n\treturn ExportResponse{orig: orig, state: state}\n}\n\n// NewExportResponse creates a new empty ExportResponse.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewExportResponse() ExportResponse {\n\treturn newExportResponse(internal.NewExportProfilesServiceResponse(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ExportResponse) MoveTo(dest ExportResponse) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteExportProfilesServiceResponse(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// PartialSuccess returns the partialsuccess associated with this ExportResponse.\nfunc (ms ExportResponse) PartialSuccess() ExportPartialSuccess {\n\treturn newExportPartialSuccess(&ms.orig.PartialSuccess, ms.state)\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ExportResponse) CopyTo(dest ExportResponse) {\n\tdest.state.AssertMutable()\n\tinternal.CopyExportProfilesServiceResponse(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/pprofile/pprofileotlp/generated_exportresponse_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage pprofileotlp\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestExportResponse_MoveTo(t *testing.T) {\n\tms := generateTestExportResponse()\n\tdest := NewExportResponse()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewExportResponse(), ms)\n\tassert.Equal(t, generateTestExportResponse(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestExportResponse(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newExportResponse(internal.NewExportProfilesServiceResponse(), sharedState)) })\n\tassert.Panics(t, func() { newExportResponse(internal.NewExportProfilesServiceResponse(), sharedState).MoveTo(dest) })\n}\n\nfunc TestExportResponse_CopyTo(t *testing.T) {\n\tms := NewExportResponse()\n\torig := NewExportResponse()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestExportResponse()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newExportResponse(internal.NewExportProfilesServiceResponse(), sharedState)) })\n}\n\nfunc TestExportResponse_PartialSuccess(t *testing.T) {\n\tms := NewExportResponse()\n\tassert.Equal(t, NewExportPartialSuccess(), ms.PartialSuccess())\n\tms.orig.PartialSuccess = *internal.GenTestExportProfilesPartialSuccess()\n\tassert.Equal(t, generateTestExportPartialSuccess(), ms.PartialSuccess())\n}\n\nfunc generateTestExportResponse() ExportResponse {\n\treturn newExportResponse(internal.GenTestExportProfilesServiceResponse(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/pprofile/pprofileotlp/grpc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofileotlp // import \"go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp\"\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otelgrpc\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otlp\"\n)\n\n// GRPCClient is the client API for OTLP-GRPC Profiles service.\n//\n// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.\ntype GRPCClient interface {\n\t// Export pprofile.Profiles to the server.\n\t//\n\t// For performance reasons, it is recommended to keep this RPC\n\t// alive for the entire life of the application.\n\tExport(ctx context.Context, request ExportRequest, opts ...grpc.CallOption) (ExportResponse, error)\n\n\t// unexported disallow implementation of the GRPCClient.\n\tunexported()\n}\n\n// NewGRPCClient returns a new GRPCClient connected using the given connection.\nfunc NewGRPCClient(cc *grpc.ClientConn) GRPCClient {\n\treturn &grpcClient{rawClient: otelgrpc.NewProfilesServiceClient(cc)}\n}\n\ntype grpcClient struct {\n\trawClient otelgrpc.ProfilesServiceClient\n}\n\n// Export implements the Client interface.\nfunc (c *grpcClient) Export(ctx context.Context, request ExportRequest, opts ...grpc.CallOption) (ExportResponse, error) {\n\trsp, err := c.rawClient.Export(ctx, request.orig, opts...)\n\tif err != nil {\n\t\treturn ExportResponse{}, err\n\t}\n\treturn ExportResponse{orig: rsp, state: internal.NewState()}, err\n}\n\nfunc (c *grpcClient) unexported() {}\n\n// GRPCServer is the server API for OTLP gRPC ProfilesService service.\n// Implementations MUST embed UnimplementedGRPCServer.\ntype GRPCServer interface {\n\t// Export is called every time a new request is received.\n\t//\n\t// For performance reasons, it is recommended to keep this RPC\n\t// alive for the entire life of the application.\n\tExport(context.Context, ExportRequest) (ExportResponse, error)\n\n\t// unexported disallow implementation of the GRPCServer.\n\tunexported()\n}\n\nvar _ GRPCServer = (*UnimplementedGRPCServer)(nil)\n\n// UnimplementedGRPCServer MUST be embedded to have forward compatible implementations.\ntype UnimplementedGRPCServer struct{}\n\nfunc (*UnimplementedGRPCServer) Export(context.Context, ExportRequest) (ExportResponse, error) {\n\treturn ExportResponse{}, status.Errorf(codes.Unimplemented, \"method Export not implemented\")\n}\n\nfunc (*UnimplementedGRPCServer) unexported() {}\n\n// RegisterGRPCServer registers the GRPCServer to the grpc.Server.\nfunc RegisterGRPCServer(s *grpc.Server, srv GRPCServer) {\n\totelgrpc.RegisterProfilesServiceServer(s, &rawProfilesServer{srv: srv})\n}\n\ntype rawProfilesServer struct {\n\tsrv GRPCServer\n}\n\nfunc (s rawProfilesServer) Export(ctx context.Context, request *internal.ExportProfilesServiceRequest) (*internal.ExportProfilesServiceResponse, error) {\n\totlp.MigrateProfiles(request.ResourceProfiles)\n\trsp, err := s.srv.Export(ctx, ExportRequest{orig: request, state: internal.NewState()})\n\treturn rsp.orig, err\n}\n"
  },
  {
    "path": "pdata/pprofile/pprofileotlp/grpc_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofileotlp\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/credentials/insecure\"\n\t\"google.golang.org/grpc/resolver\"\n\t\"google.golang.org/grpc/status\"\n\t\"google.golang.org/grpc/test/bufconn\"\n\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n)\n\nfunc TestGrpc(t *testing.T) {\n\tlis := bufconn.Listen(1024 * 1024)\n\ts := grpc.NewServer()\n\tRegisterGRPCServer(s, &fakeProfilesServer{t: t})\n\twg := sync.WaitGroup{}\n\twg.Go(func() {\n\t\tassert.NoError(t, s.Serve(lis))\n\t})\n\tt.Cleanup(func() {\n\t\ts.Stop()\n\t\twg.Wait()\n\t})\n\n\tresolver.SetDefaultScheme(\"passthrough\")\n\tcc, err := grpc.NewClient(\"bufnet\",\n\t\tgrpc.WithContextDialer(func(context.Context, string) (net.Conn, error) {\n\t\t\treturn lis.Dial()\n\t\t}),\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, cc.Close())\n\t})\n\n\tlogClient := NewGRPCClient(cc)\n\n\tresp, err := logClient.Export(context.Background(), generateProfilesRequest())\n\trequire.NoError(t, err)\n\tassert.Equal(t, NewExportResponse(), resp)\n}\n\nfunc TestGrpcError(t *testing.T) {\n\tlis := bufconn.Listen(1024 * 1024)\n\ts := grpc.NewServer()\n\tRegisterGRPCServer(s, &fakeProfilesServer{t: t, err: errors.New(\"my error\")})\n\twg := sync.WaitGroup{}\n\twg.Go(func() {\n\t\tassert.NoError(t, s.Serve(lis))\n\t})\n\tt.Cleanup(func() {\n\t\ts.Stop()\n\t\twg.Wait()\n\t})\n\n\tcc, err := grpc.NewClient(\"bufnet\",\n\t\tgrpc.WithContextDialer(func(context.Context, string) (net.Conn, error) {\n\t\t\treturn lis.Dial()\n\t\t}),\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, cc.Close())\n\t})\n\n\tlogClient := NewGRPCClient(cc)\n\tresp, err := logClient.Export(context.Background(), generateProfilesRequest())\n\trequire.Error(t, err)\n\tst, okSt := status.FromError(err)\n\trequire.True(t, okSt)\n\tassert.Equal(t, \"my error\", st.Message())\n\tassert.Equal(t, codes.Unknown, st.Code())\n\tassert.Equal(t, ExportResponse{}, resp)\n}\n\ntype fakeProfilesServer struct {\n\tUnimplementedGRPCServer\n\tt   *testing.T\n\terr error\n}\n\nfunc (f fakeProfilesServer) Export(_ context.Context, request ExportRequest) (ExportResponse, error) {\n\tassert.Equal(f.t, generateProfilesRequest(), request)\n\treturn NewExportResponse(), f.err\n}\n\nfunc generateProfilesRequest() ExportRequest {\n\ttd := pprofile.NewProfiles()\n\ttd.ResourceProfiles().AppendEmpty().ScopeProfiles().AppendEmpty().Profiles().AppendEmpty()\n\treturn NewExportRequestFromProfiles(td)\n}\n"
  },
  {
    "path": "pdata/pprofile/pprofileotlp/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofileotlp\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "pdata/pprofile/pprofileotlp/request.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofileotlp // import \"go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp\"\n\nimport (\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otlp\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n)\n\n// ExportRequest represents the request for gRPC/HTTP client/server.\n// It's a wrapper for pprofile.Profiles data.\ntype ExportRequest struct {\n\torig  *internal.ExportProfilesServiceRequest\n\tstate *internal.State\n}\n\n// NewExportRequest returns an empty ExportRequest.\nfunc NewExportRequest() ExportRequest {\n\treturn ExportRequest{\n\t\torig:  &internal.ExportProfilesServiceRequest{},\n\t\tstate: internal.NewState(),\n\t}\n}\n\n// NewExportRequestFromProfiles returns a ExportRequest from pprofile.Profiles.\n// Because ExportRequest is a wrapper for pprofile.Profiles,\n// any changes to the provided Profiles struct will be reflected in the ExportRequest and vice versa.\nfunc NewExportRequestFromProfiles(td pprofile.Profiles) ExportRequest {\n\treturn ExportRequest{\n\t\torig:  internal.GetProfilesOrig(internal.ProfilesWrapper(td)),\n\t\tstate: internal.GetProfilesState(internal.ProfilesWrapper(td)),\n\t}\n}\n\n// MarshalProto marshals ExportRequest into proto bytes.\nfunc (ms ExportRequest) MarshalProto() ([]byte, error) {\n\tsize := ms.orig.SizeProto()\n\tbuf := make([]byte, size)\n\t_ = ms.orig.MarshalProto(buf)\n\treturn buf, nil\n}\n\n// UnmarshalProto unmarshalls ExportRequest from proto bytes.\nfunc (ms ExportRequest) UnmarshalProto(data []byte) error {\n\terr := ms.orig.UnmarshalProto(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\totlp.MigrateProfiles(ms.orig.ResourceProfiles)\n\treturn nil\n}\n\n// MarshalJSON marshals ExportRequest into JSON bytes.\nfunc (ms ExportRequest) MarshalJSON() ([]byte, error) {\n\tdest := json.BorrowStream(nil)\n\tdefer json.ReturnStream(dest)\n\tms.orig.MarshalJSON(dest)\n\tif dest.Error() != nil {\n\t\treturn nil, dest.Error()\n\t}\n\treturn slices.Clone(dest.Buffer()), nil\n}\n\n// UnmarshalJSON unmarshalls ExportRequest from JSON bytes.\nfunc (ms ExportRequest) UnmarshalJSON(data []byte) error {\n\titer := json.BorrowIterator(data)\n\tdefer json.ReturnIterator(iter)\n\tms.orig.UnmarshalJSON(iter)\n\treturn iter.Error()\n}\n\nfunc (ms ExportRequest) Profiles() pprofile.Profiles {\n\treturn pprofile.Profiles(internal.NewProfilesWrapper(ms.orig, ms.state))\n}\n"
  },
  {
    "path": "pdata/pprofile/pprofileotlp/request_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofileotlp\n\nimport (\n\t\"encoding/json\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcollectorprofiles \"go.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development\"\n\tgoproto \"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otlp\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n)\n\nvar (\n\t_ json.Unmarshaler = ExportRequest{}\n\t_ json.Marshaler   = ExportRequest{}\n)\n\nvar profilesRequestJSON = []byte(`\n\t{\n\t\t\"resourceProfiles\": [\n\t\t\t{\n\t\t\t\t\"resource\": {},\n\t\t\t\t\"scopeProfiles\": [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"scope\": {},\n\t\t\t\t\t\t\"profiles\": [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"sampleType\": {},\n\t\t\t\t\t\t\t\t\"samples\": [\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\"stackIndex\": 42\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\"periodType\": {}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t]\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t}\n\t\t],\n\t\t\"dictionary\": {}\n\t}`)\n\nfunc TestRequestToPData(t *testing.T) {\n\ttr := NewExportRequest()\n\tassert.Equal(t, 0, tr.Profiles().SampleCount())\n\ttr.Profiles().ResourceProfiles().AppendEmpty().ScopeProfiles().AppendEmpty().Profiles().AppendEmpty().Samples().AppendEmpty()\n\tassert.Equal(t, 1, tr.Profiles().SampleCount())\n}\n\nfunc TestRequestJSON(t *testing.T) {\n\ttr := NewExportRequest()\n\trequire.NoError(t, tr.UnmarshalJSON(profilesRequestJSON))\n\tassert.Equal(t, int32(42), tr.Profiles().ResourceProfiles().At(0).ScopeProfiles().At(0).Profiles().At(0).Samples().At(0).StackIndex())\n\n\tgot, err := tr.MarshalJSON()\n\trequire.NoError(t, err)\n\tassert.Equal(t, strings.Join(strings.Fields(string(profilesRequestJSON)), \"\"), string(got))\n}\n\nfunc TestProfilesProtoWireCompatibility(t *testing.T) {\n\t// This test verifies that OTLP ProtoBufs generated using goproto lib in\n\t// opentelemetry-proto repository OTLP ProtoBufs generated using gogoproto lib in\n\t// this repository are wire compatible.\n\n\t// Generate Profiles as pdata struct.\n\tpd := NewExportRequestFromProfiles(pprofile.Profiles(internal.GenTestProfilesWrapper()))\n\n\t// Marshal its underlying ProtoBuf to wire.\n\twire1, err := pd.MarshalProto()\n\trequire.NoError(t, err)\n\tassert.NotNil(t, wire1)\n\n\t// Unmarshal from the wire to OTLP Protobuf in goproto's representation.\n\tvar goprotoMessage gootlpcollectorprofiles.ExportProfilesServiceRequest\n\terr = goproto.Unmarshal(wire1, &goprotoMessage)\n\trequire.NoError(t, err)\n\n\t// Marshal to the wire again.\n\twire2, err := goproto.Marshal(&goprotoMessage)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, wire2)\n\n\t// Unmarshal from the wire into gogoproto's representation.\n\tpd2 := NewExportRequest()\n\terr = pd2.UnmarshalProto(wire2)\n\trequire.NoError(t, err)\n\n\t// Now compare that the original and final ProtoBuf messages are the same.\n\t// This proves that goproto and gogoproto marshaling/unmarshaling are wire compatible.\n\t// Migration logic will run, so run it on the original message as well.\n\totlp.MigrateProfiles(pd.orig.ResourceProfiles)\n\tassert.Equal(t, pd, pd2)\n}\n"
  },
  {
    "path": "pdata/pprofile/pprofileotlp/response.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofileotlp // import \"go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp\"\n\nimport (\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n)\n\n// MarshalProto marshals ExportResponse into proto bytes.\nfunc (ms ExportResponse) MarshalProto() ([]byte, error) {\n\tsize := ms.orig.SizeProto()\n\tbuf := make([]byte, size)\n\t_ = ms.orig.MarshalProto(buf)\n\treturn buf, nil\n}\n\n// UnmarshalProto unmarshalls ExportResponse from proto bytes.\nfunc (ms ExportResponse) UnmarshalProto(data []byte) error {\n\treturn ms.orig.UnmarshalProto(data)\n}\n\n// MarshalJSON marshals ExportResponse into JSON bytes.\nfunc (ms ExportResponse) MarshalJSON() ([]byte, error) {\n\tdest := json.BorrowStream(nil)\n\tdefer json.ReturnStream(dest)\n\tms.orig.MarshalJSON(dest)\n\treturn slices.Clone(dest.Buffer()), dest.Error()\n}\n\n// UnmarshalJSON unmarshalls ExportResponse from JSON bytes.\nfunc (ms ExportResponse) UnmarshalJSON(data []byte) error {\n\titer := json.BorrowIterator(data)\n\tdefer json.ReturnIterator(iter)\n\tms.orig.UnmarshalJSON(iter)\n\treturn iter.Error()\n}\n"
  },
  {
    "path": "pdata/pprofile/pprofileotlp/response_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofileotlp\n\nimport (\n\tstdjson \"encoding/json\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar (\n\t_ stdjson.Unmarshaler = ExportResponse{}\n\t_ stdjson.Marshaler   = ExportResponse{}\n)\n\nfunc TestExportResponseJSON(t *testing.T) {\n\tjsonStr := `{\"partialSuccess\": {\"rejectedProfiles\":\"1\", \"errorMessage\":\"nothing\"}}`\n\tval := NewExportResponse()\n\trequire.NoError(t, val.UnmarshalJSON([]byte(jsonStr)))\n\texpected := NewExportResponse()\n\texpected.PartialSuccess().SetRejectedProfiles(1)\n\texpected.PartialSuccess().SetErrorMessage(\"nothing\")\n\tassert.Equal(t, expected, val)\n\tbuf, err := val.MarshalJSON()\n\trequire.NoError(t, err)\n\tassert.JSONEq(t, jsonStr, string(buf))\n}\n\nfunc TestUnmarshalJSONExportResponse(t *testing.T) {\n\tjsonStr := `{\"extra\":\"\", \"partialSuccess\": {\"extra\":\"\"}}`\n\tval := NewExportResponse()\n\trequire.NoError(t, val.UnmarshalJSON([]byte(jsonStr)))\n\tassert.Equal(t, NewExportResponse(), val)\n}\n"
  },
  {
    "path": "pdata/pprofile/profile.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport (\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// switchDictionary updates the Profile, switching its indices from one\n// dictionary to another.\nfunc (ms Profile) switchDictionary(src, dst ProfilesDictionary) error {\n\tfor i, v := range ms.AttributeIndices().All() {\n\t\tif src.AttributeTable().Len() <= int(v) {\n\t\t\treturn fmt.Errorf(\"invalid attribute index %d\", v)\n\t\t}\n\n\t\tattr := src.AttributeTable().At(int(v))\n\t\tidx, err := SetAttribute(dst.AttributeTable(), attr)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't set attribute %d: %w\", i, err)\n\t\t}\n\t\tms.AttributeIndices().SetAt(i, idx)\n\t}\n\n\tfor i, v := range ms.Samples().All() {\n\t\terr := v.switchDictionary(src, dst)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error switching dictionary for sample %d: %w\", i, err)\n\t\t}\n\t}\n\n\terr := ms.PeriodType().switchDictionary(src, dst)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error switching dictionary for period type: %w\", err)\n\t}\n\terr = ms.SampleType().switchDictionary(src, dst)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"error switching dictionary for sample type: %w\", err)\n\t}\n\n\treturn nil\n}\n\n// Duration returns the duration associated with this Profile.\n//\n// Deprecated: Use Profile.DurationNano instead.\nfunc (ms Profile) Duration() pcommon.Timestamp {\n\treturn pcommon.Timestamp(0)\n}\n\n// SetDuration replaces the duration associated with this Profile.\n//\n// Deprecated: Use Profile.SetDurationNano instead.\nfunc (ms Profile) SetDuration(_ pcommon.Timestamp) {\n}\n"
  },
  {
    "path": "pdata/pprofile/profile_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestProfileSwitchDictionary(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname    string\n\t\tprofile Profile\n\n\t\tsrc ProfilesDictionary\n\t\tdst ProfilesDictionary\n\n\t\twantProfile    Profile\n\t\twantDictionary ProfilesDictionary\n\t\twantErr        error\n\t}{\n\t\t{\n\t\t\tname:    \"with an empty profile\",\n\t\t\tprofile: NewProfile(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantProfile:    NewProfile(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing attribute\",\n\t\t\tprofile: func() Profile {\n\t\t\t\tp := NewProfile()\n\t\t\t\tp.AttributeIndices().Append(1)\n\t\t\t\treturn p\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\ta := d.AttributeTable().AppendEmpty()\n\t\t\t\ta.SetKeyStrindex(1)\n\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantProfile: func() Profile {\n\t\t\t\tp := NewProfile()\n\t\t\t\tp.AttributeIndices().Append(2)\n\t\t\t\treturn p\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\ta := d.AttributeTable().AppendEmpty()\n\t\t\t\ta.SetKeyStrindex(1)\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an attribute index that does not match anything\",\n\t\t\tprofile: func() Profile {\n\t\t\t\tp := NewProfile()\n\t\t\t\tp.AttributeIndices().Append(1)\n\t\t\t\treturn p\n\t\t\t}(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantProfile: func() Profile {\n\t\t\t\tp := NewProfile()\n\t\t\t\tp.AttributeIndices().Append(1)\n\t\t\t\treturn p\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid attribute index 1\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with an attribute index equal to the source table length (boundary condition)\",\n\t\t\tprofile: func() Profile {\n\t\t\t\tp := NewProfile()\n\t\t\t\tp.AttributeIndices().Append(2)\n\t\t\t\treturn p\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantProfile: func() Profile {\n\t\t\t\tp := NewProfile()\n\t\t\t\tp.AttributeIndices().Append(2)\n\t\t\t\treturn p\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid attribute index 2\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with a profile that has a sample\",\n\t\t\tprofile: func() Profile {\n\t\t\t\tp := NewProfile()\n\t\t\t\tp.Samples().AppendEmpty().SetLinkIndex(1)\n\t\t\t\treturn p\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\tl := d.LinkTable().AppendEmpty()\n\t\t\t\tl.SetSpanID(pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}))\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantProfile: func() Profile {\n\t\t\t\tp := NewProfile()\n\t\t\t\tp.Samples().AppendEmpty().SetLinkIndex(2)\n\t\t\t\treturn p\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\tl := d.LinkTable().AppendEmpty()\n\t\t\t\tl.SetSpanID(pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}))\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a profile that has a period type\",\n\t\t\tprofile: func() Profile {\n\t\t\t\tp := NewProfile()\n\t\t\t\tp.PeriodType().SetTypeStrindex(1)\n\t\t\t\treturn p\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\")\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantProfile: func() Profile {\n\t\t\t\tp := NewProfile()\n\t\t\t\tp.PeriodType().SetTypeStrindex(2)\n\t\t\t\treturn p\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a profile that has a sample type\",\n\t\t\tprofile: func() Profile {\n\t\t\t\tp := NewProfile()\n\t\t\t\tp.SampleType().SetTypeStrindex(1)\n\t\t\t\treturn p\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\")\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantProfile: func() Profile {\n\t\t\t\tp := NewProfile()\n\t\t\t\tp.SampleType().SetTypeStrindex(2)\n\t\t\t\treturn p\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"Profile with various elements\",\n\t\t\tprofile: func() Profile {\n\t\t\t\tp := NewProfile()\n\n\t\t\t\tp.SampleType().SetTypeStrindex(1)\n\t\t\t\tp.SampleType().SetUnitStrindex(2)\n\n\t\t\t\tp.PeriodType().SetTypeStrindex(3)\n\t\t\t\tp.PeriodType().SetUnitStrindex(4)\n\n\t\t\t\tp.AttributeIndices().Append(1)\n\n\t\t\t\treturn p\n\t\t\t}(),\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\t// Make sure we are conform with the protocol\n\t\t\t\td.MappingTable().AppendEmpty()\n\t\t\t\td.LocationTable().AppendEmpty()\n\t\t\t\td.FunctionTable().AppendEmpty()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\td.StringTable().Append(\"\")\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\td.StackTable().AppendEmpty()\n\n\t\t\t\td.StringTable().Append(\"sample-type\")    // 1\n\t\t\t\td.StringTable().Append(\"sample-unit\")    // 2\n\t\t\t\td.StringTable().Append(\"period-type\")    // 3\n\t\t\t\td.StringTable().Append(\"period-unit\")    // 4\n\t\t\t\td.StringTable().Append(\"unrelated-1\")    // 5\n\t\t\t\td.StringTable().Append(\"unrelated-2\")    // 6\n\t\t\t\td.StringTable().Append(\"attribute-key\")  // 7\n\t\t\t\td.StringTable().Append(\"attribute-unit\") // 8\n\n\t\t\t\ta := d.AttributeTable().AppendEmpty()\n\t\t\t\ta.SetKeyStrindex(7)\n\t\t\t\ta.Value().SetStr(\"AnyValue\")\n\t\t\t\ta.SetUnitStrindex(8)\n\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\t// Make sure we are conform with the protocol\n\t\t\t\td.MappingTable().AppendEmpty()\n\t\t\t\td.LocationTable().AppendEmpty()\n\t\t\t\td.FunctionTable().AppendEmpty()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\td.StringTable().Append(\"\")\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\td.StackTable().AppendEmpty()\n\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\twantProfile: func() Profile {\n\t\t\t\tp := NewProfile()\n\n\t\t\t\tp.AttributeIndices().Append(1)\n\n\t\t\t\t// Order of entries depend on the order of\n\t\t\t\t// processing in switchDictionary()\n\t\t\t\tp.SampleType().SetTypeStrindex(3)\n\t\t\t\tp.SampleType().SetUnitStrindex(4)\n\n\t\t\t\tp.PeriodType().SetTypeStrindex(1)\n\t\t\t\tp.PeriodType().SetUnitStrindex(2)\n\n\t\t\t\treturn p\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\t// Make sure we are conform with the protocol\n\t\t\t\td.MappingTable().AppendEmpty()\n\t\t\t\td.LocationTable().AppendEmpty()\n\t\t\t\td.FunctionTable().AppendEmpty()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\td.StringTable().Append(\"\")\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\td.StackTable().AppendEmpty()\n\n\t\t\t\ta := d.AttributeTable().AppendEmpty()\n\t\t\t\ta.SetKeyStrindex(7)\n\t\t\t\ta.SetUnitStrindex(8)\n\t\t\t\ta.Value().SetStr(\"AnyValue\")\n\n\t\t\t\t// Order of entries depend on the order of\n\t\t\t\t// processing in switchDictionary()\n\t\t\t\td.StringTable().Append(\"period-type\") // 1\n\t\t\t\td.StringTable().Append(\"period-unit\") // 2\n\t\t\t\td.StringTable().Append(\"sample-type\") // 3\n\t\t\t\td.StringTable().Append(\"sample-unit\") // 4\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tprofile := tt.profile\n\t\t\tdst := tt.dst\n\t\t\terr := profile.switchDictionary(tt.src, dst)\n\n\t\t\tif tt.wantErr == nil {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.Equal(t, tt.wantErr, err)\n\t\t\t}\n\n\t\t\tassert.Equal(t, tt.wantProfile, profile)\n\t\t\tassert.Equal(t, tt.wantDictionary, dst)\n\t\t})\n\t}\n}\n\nfunc BenchmarkProfileSwitchDictionary(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\n\tp := NewProfile()\n\tp.AttributeIndices().Append(1, 2)\n\n\tsrc := NewProfilesDictionary()\n\tsrc.StringTable().Append(\"\", \"test\", \"foo\")\n\tsrc.AttributeTable().AppendEmpty()\n\tsrc.AttributeTable().AppendEmpty().SetKeyStrindex(1)\n\tsrc.AttributeTable().AppendEmpty().SetKeyStrindex(2)\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tb.StopTimer()\n\t\tdst := NewProfilesDictionary()\n\t\tdst.StringTable().Append(\"\", \"foo\")\n\t\tdst.AttributeTable().AppendEmpty()\n\t\tdst.AttributeTable().AppendEmpty().SetKeyStrindex(1)\n\t\tb.StartTimer()\n\n\t\t_ = p.switchDictionary(src, dst)\n\t}\n}\n\nfunc TestProfile_Duration(_ *testing.T) {\n\tms := NewProfile()\n\tms.SetDuration(0)\n\n\tts := ms.Duration()\n\t_ = ts\n}\n"
  },
  {
    "path": "pdata/pprofile/profileid.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport (\n\t\"encoding/hex\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nvar emptyProfileID = ProfileID([16]byte{})\n\n// ProfileID is a profile identifier.\ntype ProfileID [16]byte\n\n// NewProfileIDEmpty returns a new empty (all zero bytes) ProfileID.\nfunc NewProfileIDEmpty() ProfileID {\n\treturn emptyProfileID\n}\n\n// String returns string representation of the ProfileID.\n//\n// Important: Don't rely on this method to get a string identifier of ProfileID.\n// Use hex.EncodeToString explicitly instead.\n// This method is meant to implement Stringer interface for display purposes only.\nfunc (ms ProfileID) String() string {\n\tif ms.IsEmpty() {\n\t\treturn \"\"\n\t}\n\treturn hex.EncodeToString(ms[:])\n}\n\n// IsEmpty returns true if id doesn't contain at least one non-zero byte.\nfunc (ms ProfileID) IsEmpty() bool {\n\treturn internal.ProfileID(ms).IsEmpty()\n}\n"
  },
  {
    "path": "pdata/pprofile/profileid_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestProfileID(t *testing.T) {\n\tpid := ProfileID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1})\n\tassert.Equal(t, [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1}, [16]byte(pid))\n\tassert.False(t, pid.IsEmpty())\n}\n\nfunc TestNewProfileIDEmpty(t *testing.T) {\n\tpid := NewProfileIDEmpty()\n\tassert.Equal(t, [16]byte{}, [16]byte(pid))\n\tassert.True(t, pid.IsEmpty())\n}\n\nfunc TestProfileIDString(t *testing.T) {\n\tpid := ProfileID([16]byte{})\n\tassert.Empty(t, pid.String())\n\n\tpid = [16]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}\n\tassert.Equal(t, \"12345678123456781234567812345678\", pid.String())\n}\n\nfunc TestProfileIDImmutable(t *testing.T) {\n\tinitialBytes := [16]byte{0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78, 0x12, 0x34, 0x56, 0x78}\n\tpid := ProfileID(initialBytes)\n\tassert.Equal(t, ProfileID(initialBytes), pid)\n\n\t// Get the bytes and try to mutate.\n\tpid[4] = 0x23\n\n\t// Does not change the already created ProfileID.\n\tassert.NotEqual(t, ProfileID(initialBytes), pid)\n}\n"
  },
  {
    "path": "pdata/pprofile/profiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport \"fmt\"\n\n// MarkReadOnly marks the ResourceProfiles as shared so that no further modifications can be done on it.\nfunc (ms Profiles) MarkReadOnly() {\n\tms.getState().MarkReadOnly()\n}\n\n// IsReadOnly returns true if this ResourceProfiles instance is read-only.\nfunc (ms Profiles) IsReadOnly() bool {\n\treturn ms.getState().IsReadOnly()\n}\n\n// SampleCount calculates the total number of samples.\nfunc (ms Profiles) SampleCount() int {\n\tsampleCount := 0\n\trps := ms.ResourceProfiles()\n\tfor i := 0; i < rps.Len(); i++ {\n\t\trp := rps.At(i)\n\t\tsps := rp.ScopeProfiles()\n\t\tfor j := 0; j < sps.Len(); j++ {\n\t\t\tpcs := sps.At(j).Profiles()\n\t\t\tfor k := 0; k < pcs.Len(); k++ {\n\t\t\t\tsampleCount += pcs.At(k).Samples().Len()\n\t\t\t}\n\t\t}\n\t}\n\treturn sampleCount\n}\n\n// switchDictionary updates the Profiles, switching its indices from one\n// dictionary to another.\nfunc (ms Profiles) switchDictionary(src, dst ProfilesDictionary) error {\n\tfor i, v := range ms.Dictionary().AttributeTable().All() {\n\t\terr := v.switchDictionary(src, dst)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't switch attribute %d: %w\", i, err)\n\t\t}\n\t}\n\tfor i, v := range ms.Dictionary().FunctionTable().All() {\n\t\terr := v.switchDictionary(src, dst)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't switch function %d: %w\", i, err)\n\t\t}\n\t}\n\tfor i, v := range ms.Dictionary().MappingTable().All() {\n\t\terr := v.switchDictionary(src, dst)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't switch mapping %d: %w\", i, err)\n\t\t}\n\t}\n\tfor i, v := range ms.Dictionary().LocationTable().All() {\n\t\terr := v.switchDictionary(src, dst)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't switch location %d: %w\", i, err)\n\t\t}\n\t}\n\tfor i, v := range ms.Dictionary().StackTable().All() {\n\t\terr := v.switchDictionary(src, dst)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't switch stack %d: %w\", i, err)\n\t\t}\n\t}\n\n\tfor i, v := range ms.ResourceProfiles().All() {\n\t\terr := v.switchDictionary(src, dst)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error switching dictionary for resource profile %d: %w\", i, err)\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// ProfileCount calculates the total number of profile records.\nfunc (ms Profiles) ProfileCount() int {\n\tprofileCount := 0\n\trps := ms.ResourceProfiles()\n\tfor i := 0; i < rps.Len(); i++ {\n\t\trp := rps.At(i)\n\t\tsps := rp.ScopeProfiles()\n\t\tfor j := 0; j < sps.Len(); j++ {\n\t\t\tprofileCount += sps.At(j).Profiles().Len()\n\t\t}\n\t}\n\treturn profileCount\n}\n"
  },
  {
    "path": "pdata/pprofile/profiles_merge.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\n// MergeTo merges the current Profiles into dest, updating the destination\n// dictionary as needed and appending the resource profiles.\n// The source Profiles is consumed and marked read-only after this operation.\nfunc (ms Profiles) MergeTo(dest Profiles) error {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn nil\n\t}\n\n\tif err := ms.switchDictionary(ms.Dictionary(), dest.Dictionary()); err != nil {\n\t\treturn err\n\t}\n\n\tms.ResourceProfiles().MoveAndAppendTo(dest.ResourceProfiles())\n\tms.MarkReadOnly()\n\n\treturn nil\n}\n"
  },
  {
    "path": "pdata/pprofile/profiles_merge_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestProfilesMergeTo(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname        string\n\t\tsrcProfiles Profiles\n\t\tdstProfiles Profiles\n\n\t\t// Expected results after merge\n\t\texpectedDictionarySizes struct {\n\t\t\tStringTable    int\n\t\t\tAttributeTable int\n\t\t\tStackTable     int\n\t\t\tLocationTable  int\n\t\t\tFunctionTable  int\n\t\t\tMappingTable   int\n\t\t\tLinkTable      int\n\t\t}\n\t\texpectedProfileCount int\n\t}{\n\t\t{\n\t\t\tname: \"Empty Profiles\",\n\t\t\texpectedDictionarySizes: struct {\n\t\t\t\tStringTable    int\n\t\t\t\tAttributeTable int\n\t\t\t\tStackTable     int\n\t\t\t\tLocationTable  int\n\t\t\t\tFunctionTable  int\n\t\t\t\tMappingTable   int\n\t\t\t\tLinkTable      int\n\t\t\t}{\n\t\t\t\tStringTable:    1, // Just the empty string\n\t\t\t\tAttributeTable: 1,\n\t\t\t\tStackTable:     1,\n\t\t\t\tLocationTable:  1,\n\t\t\t\tFunctionTable:  1,\n\t\t\t\tMappingTable:   1,\n\t\t\t\tLinkTable:      1,\n\t\t\t},\n\t\t\texpectedProfileCount: 0,\n\t\t\tsrcProfiles: func() Profiles {\n\t\t\t\tp := NewProfiles()\n\n\t\t\t\t// Make sure we are conform with the protocol\n\t\t\t\tp.Dictionary().MappingTable().AppendEmpty()\n\t\t\t\tp.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tp.Dictionary().FunctionTable().AppendEmpty()\n\t\t\t\tp.Dictionary().LinkTable().AppendEmpty()\n\t\t\t\tp.Dictionary().StringTable().Append(\"\")\n\t\t\t\tp.Dictionary().AttributeTable().AppendEmpty()\n\t\t\t\tp.Dictionary().StackTable().AppendEmpty()\n\t\t\t\treturn p\n\t\t\t}(),\n\t\t\tdstProfiles: func() Profiles {\n\t\t\t\tp := NewProfiles()\n\n\t\t\t\t// Make sure we are conform with the protocol\n\t\t\t\tp.Dictionary().MappingTable().AppendEmpty()\n\t\t\t\tp.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tp.Dictionary().FunctionTable().AppendEmpty()\n\t\t\t\tp.Dictionary().LinkTable().AppendEmpty()\n\t\t\t\tp.Dictionary().StringTable().Append(\"\")\n\t\t\t\tp.Dictionary().AttributeTable().AppendEmpty()\n\t\t\t\tp.Dictionary().StackTable().AppendEmpty()\n\t\t\t\treturn p\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"Single Profile\",\n\t\t\texpectedDictionarySizes: struct {\n\t\t\t\tStringTable    int\n\t\t\t\tAttributeTable int\n\t\t\t\tStackTable     int\n\t\t\t\tLocationTable  int\n\t\t\t\tFunctionTable  int\n\t\t\t\tMappingTable   int\n\t\t\t\tLinkTable      int\n\t\t\t}{\n\t\t\t\tStringTable:    7, // empty + 6 strings\n\t\t\t\tAttributeTable: 2, // empty + a1\n\t\t\t\tStackTable:     2, // empty + st1\n\t\t\t\tLocationTable:  3, // empty + loc1 + loc2\n\t\t\t\tFunctionTable:  1,\n\t\t\t\tMappingTable:   1,\n\t\t\t\tLinkTable:      1,\n\t\t\t},\n\t\t\texpectedProfileCount: 1,\n\t\t\tsrcProfiles: func() Profiles {\n\t\t\t\tps := NewProfiles()\n\n\t\t\t\t// Make sure we are conform with the protocol\n\t\t\t\tps.Dictionary().MappingTable().AppendEmpty()\n\t\t\t\tps.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tps.Dictionary().FunctionTable().AppendEmpty()\n\t\t\t\tps.Dictionary().LinkTable().AppendEmpty()\n\t\t\t\tps.Dictionary().StringTable().Append(\"\")\n\t\t\t\tps.Dictionary().AttributeTable().AppendEmpty()\n\t\t\t\tps.Dictionary().StackTable().AppendEmpty()\n\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-type\")     // 1\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-unit\")     // 2\n\t\t\t\tps.Dictionary().StringTable().Append(\"period-type\")     // 3\n\t\t\t\tps.Dictionary().StringTable().Append(\"period-unit\")     // 4\n\t\t\t\tps.Dictionary().StringTable().Append(\"attribute1-key\")  // 5\n\t\t\t\tps.Dictionary().StringTable().Append(\"attribute1-unit\") // 6\n\n\t\t\t\ta1 := ps.Dictionary().AttributeTable().AppendEmpty()\n\t\t\t\ta1.SetKeyStrindex(5)\n\t\t\t\ta1.SetUnitStrindex(6)\n\t\t\t\ta1.Value().SetStr(\"AnyValue\")\n\n\t\t\t\tst1 := ps.Dictionary().StackTable().AppendEmpty()\n\t\t\t\tst1.LocationIndices().Append(1, 2)\n\n\t\t\t\tloc1 := ps.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tloc1.SetAddress(1337)\n\t\t\t\tloc2 := ps.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tln1 := loc2.Lines().AppendEmpty()\n\t\t\t\tln1.SetLine(42)\n\n\t\t\t\trp := ps.ResourceProfiles().AppendEmpty()\n\t\t\t\trp.SetSchemaUrl(\"resource-schema-url\")\n\t\t\t\trp.Resource().Attributes().PutStr(\"resource-attribute-key\",\n\t\t\t\t\t\"resource-attribute-value\")\n\n\t\t\t\tsp := rp.ScopeProfiles().AppendEmpty()\n\t\t\t\tsp.SetSchemaUrl(\"scope-schema-url\")\n\n\t\t\t\tp := sp.Profiles().AppendEmpty()\n\t\t\t\tp.SampleType().SetTypeStrindex(1)\n\t\t\t\tp.SampleType().SetUnitStrindex(2)\n\t\t\t\tp.PeriodType().SetTypeStrindex(3)\n\t\t\t\tp.PeriodType().SetUnitStrindex(4)\n\n\t\t\t\ts1 := p.Samples().AppendEmpty()\n\t\t\t\ts1.AttributeIndices().Append(1)\n\t\t\t\ts1.SetStackIndex(1)\n\n\t\t\t\treturn ps\n\t\t\t}(),\n\t\t\tdstProfiles: func() Profiles {\n\t\t\t\tp := NewProfiles()\n\n\t\t\t\t// Make sure we are conform with the protocol\n\t\t\t\tp.Dictionary().MappingTable().AppendEmpty()\n\t\t\t\tp.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tp.Dictionary().FunctionTable().AppendEmpty()\n\t\t\t\tp.Dictionary().LinkTable().AppendEmpty()\n\t\t\t\tp.Dictionary().StringTable().Append(\"\")\n\t\t\t\tp.Dictionary().AttributeTable().AppendEmpty()\n\t\t\t\tp.Dictionary().StackTable().AppendEmpty()\n\t\t\t\treturn p\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"Multiple Profile\",\n\t\t\texpectedDictionarySizes: struct {\n\t\t\t\tStringTable    int\n\t\t\t\tAttributeTable int\n\t\t\t\tStackTable     int\n\t\t\t\tLocationTable  int\n\t\t\t\tFunctionTable  int\n\t\t\t\tMappingTable   int\n\t\t\t\tLinkTable      int\n\t\t\t}{\n\t\t\t\tStringTable:    7, // empty + 6 strings\n\t\t\t\tAttributeTable: 1,\n\t\t\t\tStackTable:     1,\n\t\t\t\tLocationTable:  1,\n\t\t\t\tFunctionTable:  1,\n\t\t\t\tMappingTable:   1,\n\t\t\t\tLinkTable:      1,\n\t\t\t},\n\t\t\texpectedProfileCount: 3,\n\t\t\tsrcProfiles: func() Profiles {\n\t\t\t\tps := NewProfiles()\n\n\t\t\t\t// Make sure we are conform with the protocol\n\t\t\t\tps.Dictionary().MappingTable().AppendEmpty()\n\t\t\t\tps.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tps.Dictionary().FunctionTable().AppendEmpty()\n\t\t\t\tps.Dictionary().LinkTable().AppendEmpty()\n\t\t\t\tps.Dictionary().StringTable().Append(\"\")\n\t\t\t\tps.Dictionary().AttributeTable().AppendEmpty()\n\t\t\t\tps.Dictionary().StackTable().AppendEmpty()\n\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-type-1\") // 1\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-unit-1\") // 2\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-type-2\") // 3\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-unit-2\") // 4\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-type-3\") // 5\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-unit-3\") // 6\n\n\t\t\t\trp := ps.ResourceProfiles().AppendEmpty()\n\t\t\t\trp.SetSchemaUrl(\"resource-schema-url\")\n\t\t\t\trp.Resource().Attributes().PutStr(\"resource-attribute-key\",\n\t\t\t\t\t\"resource-attribute-value\")\n\n\t\t\t\tsp := rp.ScopeProfiles().AppendEmpty()\n\t\t\t\tsp.SetSchemaUrl(\"scope-schema-url\")\n\n\t\t\t\tp1 := sp.Profiles().AppendEmpty()\n\t\t\t\tp1.SampleType().SetTypeStrindex(1)\n\t\t\t\tp1.SampleType().SetUnitStrindex(2)\n\n\t\t\t\tp2 := sp.Profiles().AppendEmpty()\n\t\t\t\tp2.SampleType().SetTypeStrindex(3)\n\t\t\t\tp2.SampleType().SetUnitStrindex(4)\n\n\t\t\t\tp3 := sp.Profiles().AppendEmpty()\n\t\t\t\tp3.SampleType().SetTypeStrindex(5)\n\t\t\t\tp3.SampleType().SetUnitStrindex(6)\n\n\t\t\t\treturn ps\n\t\t\t}(),\n\t\t\tdstProfiles: func() Profiles {\n\t\t\t\tp := NewProfiles()\n\n\t\t\t\t// Make sure we are conform with the protocol\n\t\t\t\tp.Dictionary().MappingTable().AppendEmpty()\n\t\t\t\tp.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tp.Dictionary().FunctionTable().AppendEmpty()\n\t\t\t\tp.Dictionary().LinkTable().AppendEmpty()\n\t\t\t\tp.Dictionary().StringTable().Append(\"\")\n\t\t\t\tp.Dictionary().AttributeTable().AppendEmpty()\n\t\t\t\tp.Dictionary().StackTable().AppendEmpty()\n\t\t\t\treturn p\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"Multiple Profile with partly prepopulated destination\",\n\t\t\texpectedDictionarySizes: struct {\n\t\t\t\tStringTable    int\n\t\t\t\tAttributeTable int\n\t\t\t\tStackTable     int\n\t\t\t\tLocationTable  int\n\t\t\t\tFunctionTable  int\n\t\t\t\tMappingTable   int\n\t\t\t\tLinkTable      int\n\t\t\t}{\n\t\t\t\tStringTable:    10, // empty + 3 unrelated + 6 from src\n\t\t\t\tAttributeTable: 1,\n\t\t\t\tStackTable:     1,\n\t\t\t\tLocationTable:  1,\n\t\t\t\tFunctionTable:  1,\n\t\t\t\tMappingTable:   1,\n\t\t\t\tLinkTable:      1,\n\t\t\t},\n\t\t\texpectedProfileCount: 3,\n\t\t\tsrcProfiles: func() Profiles {\n\t\t\t\tps := NewProfiles()\n\n\t\t\t\t// Make sure we are conform with the protocol\n\t\t\t\tps.Dictionary().MappingTable().AppendEmpty()\n\t\t\t\tps.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tps.Dictionary().FunctionTable().AppendEmpty()\n\t\t\t\tps.Dictionary().LinkTable().AppendEmpty()\n\t\t\t\tps.Dictionary().StringTable().Append(\"\")\n\t\t\t\tps.Dictionary().AttributeTable().AppendEmpty()\n\t\t\t\tps.Dictionary().StackTable().AppendEmpty()\n\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-type-1\") // 1\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-unit-1\") // 2\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-type-2\") // 3\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-unit-2\") // 4\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-type-3\") // 5\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-unit-3\") // 6\n\n\t\t\t\trp := ps.ResourceProfiles().AppendEmpty()\n\t\t\t\trp.SetSchemaUrl(\"resource-schema-url\")\n\t\t\t\trp.Resource().Attributes().PutStr(\"resource-attribute-key\",\n\t\t\t\t\t\"resource-attribute-value\")\n\n\t\t\t\tsp := rp.ScopeProfiles().AppendEmpty()\n\t\t\t\tsp.SetSchemaUrl(\"scope-schema-url\")\n\n\t\t\t\tp1 := sp.Profiles().AppendEmpty()\n\t\t\t\tp1.SampleType().SetTypeStrindex(1)\n\t\t\t\tp1.SampleType().SetUnitStrindex(2)\n\n\t\t\t\tp2 := sp.Profiles().AppendEmpty()\n\t\t\t\tp2.SampleType().SetTypeStrindex(3)\n\t\t\t\tp2.SampleType().SetUnitStrindex(4)\n\n\t\t\t\tp3 := sp.Profiles().AppendEmpty()\n\t\t\t\tp3.SampleType().SetTypeStrindex(5)\n\t\t\t\tp3.SampleType().SetUnitStrindex(6)\n\n\t\t\t\treturn ps\n\t\t\t}(),\n\t\t\tdstProfiles: func() Profiles {\n\t\t\t\tps := NewProfiles()\n\n\t\t\t\t// Make sure we are conform with the protocol\n\t\t\t\tps.Dictionary().MappingTable().AppendEmpty()\n\t\t\t\tps.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tps.Dictionary().FunctionTable().AppendEmpty()\n\t\t\t\tps.Dictionary().LinkTable().AppendEmpty()\n\t\t\t\tps.Dictionary().StringTable().Append(\"\")\n\t\t\t\tps.Dictionary().AttributeTable().AppendEmpty()\n\t\t\t\tps.Dictionary().StackTable().AppendEmpty()\n\n\t\t\t\tps.Dictionary().StringTable().Append(\"unrelated-1\") // 1\n\t\t\t\tps.Dictionary().StringTable().Append(\"unrelated-2\") // 2\n\t\t\t\tps.Dictionary().StringTable().Append(\"unrelated-3\") // 3\n\t\t\t\treturn ps\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"Multiple Profile with reused samples\",\n\t\t\texpectedDictionarySizes: struct {\n\t\t\t\tStringTable    int\n\t\t\t\tAttributeTable int\n\t\t\t\tStackTable     int\n\t\t\t\tLocationTable  int\n\t\t\t\tFunctionTable  int\n\t\t\t\tMappingTable   int\n\t\t\t\tLinkTable      int\n\t\t\t}{\n\t\t\t\tStringTable:    9, // empty + 8 unique strings after merge\n\t\t\t\tAttributeTable: 1,\n\t\t\t\tStackTable:     3, // empty + 2 unique stacks\n\t\t\t\tLocationTable:  3, // empty + 2 unique locations\n\t\t\t\tFunctionTable:  2, // empty + fn1\n\t\t\t\tMappingTable:   1,\n\t\t\t\tLinkTable:      1,\n\t\t\t},\n\t\t\texpectedProfileCount: 3,\n\t\t\tsrcProfiles: func() Profiles {\n\t\t\t\tps := NewProfiles()\n\n\t\t\t\t// Make sure we are conform with the protocol\n\t\t\t\tps.Dictionary().MappingTable().AppendEmpty()\n\t\t\t\tps.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tps.Dictionary().FunctionTable().AppendEmpty()\n\t\t\t\tps.Dictionary().LinkTable().AppendEmpty()\n\t\t\t\tps.Dictionary().StringTable().Append(\"\")\n\t\t\t\tps.Dictionary().AttributeTable().AppendEmpty()\n\t\t\t\tps.Dictionary().StackTable().AppendEmpty()\n\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-type-1\")  // 1\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-unit-1\")  // 2\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-type-2\")  // 3\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-unit-2\")  // 4\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-type-3\")  // 5\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-unit-3\")  // 6\n\t\t\t\tps.Dictionary().StringTable().Append(\"filename-1\")     // 7\n\t\t\t\tps.Dictionary().StringTable().Append(\"functionname-1\") // 8\n\n\t\t\t\tst1 := ps.Dictionary().StackTable().AppendEmpty()\n\t\t\t\tst1.LocationIndices().Append(1)\n\n\t\t\t\tst2 := ps.Dictionary().StackTable().AppendEmpty()\n\t\t\t\tst2.LocationIndices().Append(2)\n\n\t\t\t\tloc1 := ps.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tloc1.SetAddress(42)\n\n\t\t\t\tloc2 := ps.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tln1 := loc2.Lines().AppendEmpty()\n\t\t\t\tln1.SetFunctionIndex(1)\n\t\t\t\tln1.SetLine(1337)\n\n\t\t\t\tfn1 := ps.Dictionary().FunctionTable().AppendEmpty()\n\t\t\t\tfn1.SetFilenameStrindex(7)\n\t\t\t\tfn1.SetNameStrindex(8)\n\n\t\t\t\trp := ps.ResourceProfiles().AppendEmpty()\n\t\t\t\trp.SetSchemaUrl(\"resource-schema-url\")\n\t\t\t\trp.Resource().Attributes().PutStr(\"resource-attribute-key\",\n\t\t\t\t\t\"resource-attribute-value\")\n\n\t\t\t\tsp := rp.ScopeProfiles().AppendEmpty()\n\t\t\t\tsp.SetSchemaUrl(\"scope-schema-url\")\n\n\t\t\t\tp1 := sp.Profiles().AppendEmpty()\n\t\t\t\tp1.SampleType().SetTypeStrindex(1)\n\t\t\t\tp1.SampleType().SetUnitStrindex(2)\n\t\t\t\ts1 := p1.Samples().AppendEmpty()\n\t\t\t\ts1.SetStackIndex(1)\n\n\t\t\t\tp2 := sp.Profiles().AppendEmpty()\n\t\t\t\tp2.SampleType().SetTypeStrindex(3)\n\t\t\t\tp2.SampleType().SetUnitStrindex(4)\n\t\t\t\ts2 := p2.Samples().AppendEmpty()\n\t\t\t\ts2.SetStackIndex(2)\n\n\t\t\t\tp3 := sp.Profiles().AppendEmpty()\n\t\t\t\tp3.SampleType().SetTypeStrindex(5)\n\t\t\t\tp3.SampleType().SetUnitStrindex(6)\n\t\t\t\ts3 := p3.Samples().AppendEmpty()\n\t\t\t\ts3.SetStackIndex(1)\n\n\t\t\t\treturn ps\n\t\t\t}(),\n\t\t\tdstProfiles: func() Profiles {\n\t\t\t\tp := NewProfiles()\n\n\t\t\t\t// Make sure we are conform with the protocol\n\t\t\t\tp.Dictionary().MappingTable().AppendEmpty()\n\t\t\t\tp.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tp.Dictionary().FunctionTable().AppendEmpty()\n\t\t\t\tp.Dictionary().LinkTable().AppendEmpty()\n\t\t\t\tp.Dictionary().StringTable().Append(\"\")\n\t\t\t\tp.Dictionary().AttributeTable().AppendEmpty()\n\t\t\t\tp.Dictionary().StackTable().AppendEmpty()\n\t\t\t\treturn p\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"Multiple ResourceProfiles with reused samples\",\n\t\t\texpectedDictionarySizes: struct {\n\t\t\t\tStringTable    int\n\t\t\t\tAttributeTable int\n\t\t\t\tStackTable     int\n\t\t\t\tLocationTable  int\n\t\t\t\tFunctionTable  int\n\t\t\t\tMappingTable   int\n\t\t\t\tLinkTable      int\n\t\t\t}{\n\t\t\t\tStringTable:    9, // empty + 8 unique strings\n\t\t\t\tAttributeTable: 1,\n\t\t\t\tStackTable:     3, // empty + 2 unique stacks\n\t\t\t\tLocationTable:  3, // empty + 2 unique locations\n\t\t\t\tFunctionTable:  2, // empty + fn1\n\t\t\t\tMappingTable:   2, // empty + m1\n\t\t\t\tLinkTable:      1,\n\t\t\t},\n\t\t\texpectedProfileCount: 6,\n\t\t\tsrcProfiles: func() Profiles {\n\t\t\t\tps := NewProfiles()\n\n\t\t\t\t// Make sure we are conform with the protocol\n\t\t\t\tps.Dictionary().MappingTable().AppendEmpty()\n\t\t\t\tps.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tps.Dictionary().FunctionTable().AppendEmpty()\n\t\t\t\tps.Dictionary().LinkTable().AppendEmpty()\n\t\t\t\tps.Dictionary().StringTable().Append(\"\")\n\t\t\t\tps.Dictionary().AttributeTable().AppendEmpty()\n\t\t\t\tps.Dictionary().StackTable().AppendEmpty()\n\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-type-1\")  // 1\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-unit-1\")  // 2\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-type-2\")  // 3\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-unit-2\")  // 4\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-type-3\")  // 5\n\t\t\t\tps.Dictionary().StringTable().Append(\"sample-unit-3\")  // 6\n\t\t\t\tps.Dictionary().StringTable().Append(\"filename-1\")     // 7\n\t\t\t\tps.Dictionary().StringTable().Append(\"functionname-1\") // 8\n\n\t\t\t\tst1 := ps.Dictionary().StackTable().AppendEmpty()\n\t\t\t\tst1.LocationIndices().Append(1)\n\n\t\t\t\tst2 := ps.Dictionary().StackTable().AppendEmpty()\n\t\t\t\tst2.LocationIndices().Append(2)\n\n\t\t\t\tloc1 := ps.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tloc1.SetAddress(42)\n\t\t\t\tloc1.SetMappingIndex(1)\n\n\t\t\t\tloc2 := ps.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tln1 := loc2.Lines().AppendEmpty()\n\t\t\t\tln1.SetFunctionIndex(1)\n\t\t\t\tln1.SetLine(1337)\n\n\t\t\t\tfn1 := ps.Dictionary().FunctionTable().AppendEmpty()\n\t\t\t\tfn1.SetFilenameStrindex(7)\n\t\t\t\tfn1.SetNameStrindex(8)\n\n\t\t\t\tm1 := ps.Dictionary().MappingTable().AppendEmpty()\n\t\t\t\tm1.SetFilenameStrindex(8)\n\n\t\t\t\trp1 := ps.ResourceProfiles().AppendEmpty()\n\t\t\t\trp1.SetSchemaUrl(\"resource-schema-url\")\n\t\t\t\trp1.Resource().Attributes().PutStr(\"resource-attribute-key\",\n\t\t\t\t\t\"resource-attribute-value\")\n\n\t\t\t\tsp1 := rp1.ScopeProfiles().AppendEmpty()\n\t\t\t\tsp1.SetSchemaUrl(\"scope-schema-url\")\n\n\t\t\t\tp11 := sp1.Profiles().AppendEmpty()\n\t\t\t\tp11.SampleType().SetTypeStrindex(1)\n\t\t\t\tp11.SampleType().SetUnitStrindex(2)\n\t\t\t\ts11 := p11.Samples().AppendEmpty()\n\t\t\t\ts11.SetStackIndex(1)\n\n\t\t\t\tp12 := sp1.Profiles().AppendEmpty()\n\t\t\t\tp12.SampleType().SetTypeStrindex(3)\n\t\t\t\tp12.SampleType().SetUnitStrindex(4)\n\t\t\t\ts12 := p12.Samples().AppendEmpty()\n\t\t\t\ts12.SetStackIndex(2)\n\n\t\t\t\tp13 := sp1.Profiles().AppendEmpty()\n\t\t\t\tp13.SampleType().SetTypeStrindex(5)\n\t\t\t\tp13.SampleType().SetUnitStrindex(6)\n\t\t\t\ts13 := p13.Samples().AppendEmpty()\n\t\t\t\ts13.SetStackIndex(1)\n\n\t\t\t\trp2 := ps.ResourceProfiles().AppendEmpty()\n\t\t\t\trp2.SetSchemaUrl(\"resource-schema-url\")\n\t\t\t\trp2.Resource().Attributes().PutStr(\"resource-attribute-key\",\n\t\t\t\t\t\"resource-attribute-value\")\n\n\t\t\t\tsp2 := rp2.ScopeProfiles().AppendEmpty()\n\t\t\t\tsp2.SetSchemaUrl(\"scope-schema-url\")\n\n\t\t\t\tp21 := sp2.Profiles().AppendEmpty()\n\t\t\t\tp21.SampleType().SetTypeStrindex(1)\n\t\t\t\tp21.SampleType().SetUnitStrindex(2)\n\t\t\t\ts21 := p21.Samples().AppendEmpty()\n\t\t\t\ts21.SetStackIndex(1)\n\n\t\t\t\tp22 := sp2.Profiles().AppendEmpty()\n\t\t\t\tp22.SampleType().SetTypeStrindex(3)\n\t\t\t\tp22.SampleType().SetUnitStrindex(4)\n\t\t\t\ts22 := p22.Samples().AppendEmpty()\n\t\t\t\ts22.SetStackIndex(2)\n\n\t\t\t\tp23 := sp2.Profiles().AppendEmpty()\n\t\t\t\tp23.SampleType().SetTypeStrindex(5)\n\t\t\t\tp23.SampleType().SetUnitStrindex(6)\n\t\t\t\ts23 := p23.Samples().AppendEmpty()\n\t\t\t\ts23.SetStackIndex(1)\n\n\t\t\t\treturn ps\n\t\t\t}(),\n\t\t\tdstProfiles: func() Profiles {\n\t\t\t\tp := NewProfiles()\n\n\t\t\t\t// Make sure we are conform with the protocol\n\t\t\t\tp.Dictionary().MappingTable().AppendEmpty()\n\t\t\t\tp.Dictionary().LocationTable().AppendEmpty()\n\t\t\t\tp.Dictionary().FunctionTable().AppendEmpty()\n\t\t\t\tp.Dictionary().LinkTable().AppendEmpty()\n\t\t\t\tp.Dictionary().StringTable().Append(\"\")\n\t\t\t\tp.Dictionary().AttributeTable().AppendEmpty()\n\t\t\t\tp.Dictionary().StackTable().AppendEmpty()\n\t\t\t\treturn p\n\t\t\t}(),\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsrcProfiles := tt.srcProfiles\n\t\t\tdstProfiles := tt.dstProfiles\n\t\t\terr := srcProfiles.MergeTo(dstProfiles)\n\t\t\trequire.NoError(t, err)\n\n\t\t\t// Verify dictionary sizes\n\t\t\tassert.Equal(t, tt.expectedDictionarySizes.StringTable, dstProfiles.Dictionary().StringTable().Len(),\n\t\t\t\t\"StringTable size mismatch\")\n\t\t\tassert.Equal(t, tt.expectedDictionarySizes.AttributeTable, dstProfiles.Dictionary().AttributeTable().Len(),\n\t\t\t\t\"AttributeTable size mismatch\")\n\t\t\tassert.Equal(t, tt.expectedDictionarySizes.StackTable, dstProfiles.Dictionary().StackTable().Len(),\n\t\t\t\t\"StackTable size mismatch\")\n\t\t\tassert.Equal(t, tt.expectedDictionarySizes.LocationTable, dstProfiles.Dictionary().LocationTable().Len(),\n\t\t\t\t\"LocationTable size mismatch\")\n\t\t\tassert.Equal(t, tt.expectedDictionarySizes.FunctionTable, dstProfiles.Dictionary().FunctionTable().Len(),\n\t\t\t\t\"FunctionTable size mismatch\")\n\t\t\tassert.Equal(t, tt.expectedDictionarySizes.MappingTable, dstProfiles.Dictionary().MappingTable().Len(),\n\t\t\t\t\"MappingTable size mismatch\")\n\t\t\tassert.Equal(t, tt.expectedDictionarySizes.LinkTable, dstProfiles.Dictionary().LinkTable().Len(),\n\t\t\t\t\"LinkTable size mismatch\")\n\n\t\t\t// Verify profile count\n\t\t\ttotalProfiles := 0\n\t\t\tfor _, rp := range dstProfiles.ResourceProfiles().All() {\n\t\t\t\tfor _, sp := range rp.ScopeProfiles().All() {\n\t\t\t\t\ttotalProfiles += sp.Profiles().Len()\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert.Equal(t, tt.expectedProfileCount, totalProfiles, \"Total profile count mismatch\")\n\t\t})\n\t}\n}\n\nfunc TestProfilesMergeToSelf(t *testing.T) {\n\tprofiles := NewProfiles()\n\tprofiles.Dictionary().StringTable().Append(\"\", \"test\")\n\tprofiles.ResourceProfiles().AppendEmpty()\n\n\trequire.NoError(t, profiles.MergeTo(profiles))\n\n\tassert.Equal(t, 2, profiles.Dictionary().StringTable().Len())\n\tassert.Equal(t, 1, profiles.ResourceProfiles().Len())\n}\n\nfunc TestProfilesMergeToError(t *testing.T) {\n\tsrc := NewProfiles()\n\tdest := NewProfiles()\n\n\tstackTable := src.Dictionary().StackTable()\n\tstackTable.AppendEmpty()\n\tstack := stackTable.AppendEmpty()\n\tstack.LocationIndices().Append(1)\n\n\tlocationTable := src.Dictionary().LocationTable()\n\tlocationTable.AppendEmpty()\n\tlocationTable.AppendEmpty().SetMappingIndex(1)\n\n\tsample := src.ResourceProfiles().AppendEmpty().\n\t\tScopeProfiles().AppendEmpty().\n\t\tProfiles().AppendEmpty().\n\t\tSamples().AppendEmpty()\n\tsample.SetStackIndex(1)\n\n\terr := src.MergeTo(dest)\n\trequire.Error(t, err)\n\n\tassert.Equal(t, 0, dest.ResourceProfiles().Len())\n}\n"
  },
  {
    "path": "pdata/pprofile/profiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestReadOnlyProfilesInvalidUsage(t *testing.T) {\n\tpd := NewProfiles()\n\tassert.False(t, pd.IsReadOnly())\n\tres := pd.ResourceProfiles().AppendEmpty().Resource()\n\tres.Attributes().PutStr(\"k1\", \"v1\")\n\tpd.MarkReadOnly()\n\tassert.True(t, pd.IsReadOnly())\n\tassert.Panics(t, func() { res.Attributes().PutStr(\"k2\", \"v2\") })\n}\n\nfunc TestSampleCount(t *testing.T) {\n\tpd := NewProfiles()\n\tassert.Equal(t, 0, pd.SampleCount())\n\n\trs := pd.ResourceProfiles().AppendEmpty()\n\tassert.Equal(t, 0, pd.SampleCount())\n\n\tils := rs.ScopeProfiles().AppendEmpty()\n\tassert.Equal(t, 0, pd.SampleCount())\n\n\tps := ils.Profiles().AppendEmpty()\n\tassert.Equal(t, 0, pd.SampleCount())\n\n\tps.Samples().AppendEmpty()\n\tassert.Equal(t, 1, pd.SampleCount())\n\n\tils2 := rs.ScopeProfiles().AppendEmpty()\n\tassert.Equal(t, 1, pd.SampleCount())\n\n\tps2 := ils2.Profiles().AppendEmpty()\n\tassert.Equal(t, 1, pd.SampleCount())\n\n\tps2.Samples().AppendEmpty()\n\tassert.Equal(t, 2, pd.SampleCount())\n\n\trms := pd.ResourceProfiles()\n\trms.EnsureCapacity(3)\n\trms.AppendEmpty().ScopeProfiles().AppendEmpty()\n\tilss := rms.AppendEmpty().ScopeProfiles().AppendEmpty().Profiles().AppendEmpty().Samples()\n\tfor range 5 {\n\t\tilss.AppendEmpty()\n\t}\n\t// 5 + 2 (from rms.At(0) and rms.At(1) initialized first)\n\tassert.Equal(t, 7, pd.SampleCount())\n}\n\nfunc TestProfileCount(t *testing.T) {\n\tpd := NewProfiles()\n\tassert.Equal(t, 0, pd.ProfileCount())\n\n\trs := pd.ResourceProfiles().AppendEmpty()\n\tassert.Equal(t, 0, pd.ProfileCount())\n\n\tils := rs.ScopeProfiles().AppendEmpty()\n\tassert.Equal(t, 0, pd.ProfileCount())\n\n\tps := ils.Profiles().AppendEmpty()\n\tassert.Equal(t, 1, pd.ProfileCount())\n\n\tps.Samples().AppendEmpty()\n\tassert.Equal(t, 1, pd.ProfileCount())\n\n\tils2 := rs.ScopeProfiles().AppendEmpty()\n\tassert.Equal(t, 1, pd.ProfileCount())\n\n\tps2 := ils2.Profiles().AppendEmpty()\n\tassert.Equal(t, 2, pd.ProfileCount())\n\n\tps2.Samples().AppendEmpty()\n\tassert.Equal(t, 2, pd.ProfileCount())\n\n\trms := pd.ResourceProfiles()\n\trms.EnsureCapacity(3)\n\trms.AppendEmpty().ScopeProfiles().AppendEmpty()\n\tilss := rms.AppendEmpty().ScopeProfiles().AppendEmpty().Profiles().AppendEmpty().Samples()\n\tfor range 5 {\n\t\tilss.AppendEmpty()\n\t}\n\t// 5 + 2 (from rms.At(0) and rms.At(1) initialized first)\n\tassert.Equal(t, 3, pd.ProfileCount())\n}\n\nfunc TestSampleCountWithEmpty(t *testing.T) {\n\tassert.Equal(t, 0, newProfiles(&internal.ExportProfilesServiceRequest{\n\t\tResourceProfiles: []*internal.ResourceProfiles{{}},\n\t}, new(internal.State)).SampleCount())\n\tassert.Equal(t, 0, newProfiles(&internal.ExportProfilesServiceRequest{\n\t\tResourceProfiles: []*internal.ResourceProfiles{\n\t\t\t{\n\t\t\t\tScopeProfiles: []*internal.ScopeProfiles{{}},\n\t\t\t},\n\t\t},\n\t}, new(internal.State)).SampleCount())\n\tassert.Equal(t, 1, newProfiles(&internal.ExportProfilesServiceRequest{\n\t\tResourceProfiles: []*internal.ResourceProfiles{\n\t\t\t{\n\t\t\t\tScopeProfiles: []*internal.ScopeProfiles{\n\t\t\t\t\t{\n\t\t\t\t\t\tProfiles: []*internal.Profile{\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\tSamples: []*internal.Sample{\n\t\t\t\t\t\t\t\t\t{},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, new(internal.State)).SampleCount())\n}\n\nfunc TestProfilesSwitchDictionary(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname     string\n\t\tprofiles Profiles\n\n\t\tsrc ProfilesDictionary\n\t\tdst ProfilesDictionary\n\n\t\twantProfiles   Profiles\n\t\twantDictionary ProfilesDictionary\n\t\twantErr        error\n\t}{\n\t\t{\n\t\t\tname:     \"with an empty profiles\",\n\t\t\tprofiles: NewProfiles(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantProfiles:   NewProfiles(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a profiles that has a profile\",\n\t\t\tprofiles: func() Profiles {\n\t\t\t\tp := NewProfiles()\n\t\t\t\tprofile := p.ResourceProfiles().AppendEmpty().ScopeProfiles().AppendEmpty().Profiles().AppendEmpty()\n\t\t\t\tprofile.Samples().AppendEmpty().SetLinkIndex(1)\n\t\t\t\treturn p\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\tl := d.LinkTable().AppendEmpty()\n\t\t\t\tl.SetSpanID(pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}))\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantProfiles: func() Profiles {\n\t\t\t\tp := NewProfiles()\n\t\t\t\tprofile := p.ResourceProfiles().AppendEmpty().ScopeProfiles().AppendEmpty().Profiles().AppendEmpty()\n\t\t\t\tprofile.Samples().AppendEmpty().SetLinkIndex(2)\n\t\t\t\treturn p\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\tl := d.LinkTable().AppendEmpty()\n\t\t\t\tl.SetSpanID(pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}))\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tp := tt.profiles\n\t\t\tdst := tt.dst\n\t\t\terr := p.switchDictionary(tt.src, dst)\n\n\t\t\tif tt.wantErr == nil {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.Equal(t, tt.wantErr, err)\n\t\t\t}\n\n\t\t\tassert.Equal(t, tt.wantProfiles, p)\n\t\t\tassert.Equal(t, tt.wantDictionary, dst)\n\t\t})\n\t}\n}\n\nfunc BenchmarkProfilesSwitchDictionary(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\n\tp := NewProfiles()\n\tprofile := p.ResourceProfiles().AppendEmpty().ScopeProfiles().AppendEmpty().Profiles().AppendEmpty()\n\tprofile.Samples().AppendEmpty().SetLinkIndex(1)\n\n\tsrc := NewProfilesDictionary()\n\tsrc.LinkTable().AppendEmpty()\n\tsrc.LinkTable().AppendEmpty().SetSpanID(pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}))\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tb.StopTimer()\n\t\tdst := NewProfilesDictionary()\n\t\tb.StartTimer()\n\n\t\t_ = p.switchDictionary(src, dst)\n\t}\n}\n\nfunc BenchmarkProfilesUsage(b *testing.B) {\n\tpd := generateTestProfiles()\n\tts := pcommon.NewTimestampFromTime(time.Now())\n\tdur := uint64(1_000_000_000)\n\ttestValProfileID := ProfileID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1})\n\ttestSecondValProfileID := ProfileID([16]byte{2, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1})\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tfor i := 0; i < pd.ResourceProfiles().Len(); i++ {\n\t\t\trs := pd.ResourceProfiles().At(i)\n\t\t\tres := rs.Resource()\n\t\t\tres.Attributes().PutStr(\"foo\", \"bar\")\n\t\t\tv, ok := res.Attributes().Get(\"foo\")\n\t\t\tassert.True(b, ok)\n\t\t\tassert.Equal(b, \"bar\", v.Str())\n\t\t\tv.SetStr(\"new-bar\")\n\t\t\tassert.Equal(b, \"new-bar\", v.Str())\n\t\t\tres.Attributes().Remove(\"foo\")\n\t\t\tfor j := 0; j < rs.ScopeProfiles().Len(); j++ {\n\t\t\t\tiss := rs.ScopeProfiles().At(j)\n\t\t\t\tiss.Scope().SetName(\"new_test_name\")\n\t\t\t\tassert.Equal(b, \"new_test_name\", iss.Scope().Name())\n\t\t\t\tfor k := 0; k < iss.Profiles().Len(); k++ {\n\t\t\t\t\ts := iss.Profiles().At(k)\n\t\t\t\t\ts.SetProfileID(testValProfileID)\n\t\t\t\t\tassert.Equal(b, testValProfileID, s.ProfileID())\n\t\t\t\t\ts.SetTime(ts)\n\t\t\t\t\tassert.Equal(b, ts, s.Time())\n\t\t\t\t\ts.SetDurationNano(dur)\n\t\t\t\t\tassert.Equal(b, dur, s.DurationNano())\n\t\t\t\t}\n\t\t\t\ts := iss.Profiles().AppendEmpty()\n\t\t\t\ts.SetProfileID(testSecondValProfileID)\n\t\t\t\ts.SetTime(ts)\n\t\t\t\ts.SetDurationNano(dur)\n\t\t\t\ts.AttributeIndices().Append(1)\n\t\t\t\tiss.Profiles().RemoveIf(func(lr Profile) bool {\n\t\t\t\t\treturn lr.ProfileID() == testSecondValProfileID\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc BenchmarkProfilesMarshalJSON(b *testing.B) {\n\tpd := generateTestProfiles()\n\tencoder := &JSONMarshaler{}\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tjsonBuf, err := encoder.MarshalProfiles(pd)\n\t\trequire.NoError(b, err)\n\t\trequire.NotNil(b, jsonBuf)\n\t}\n}\n"
  },
  {
    "path": "pdata/pprofile/resourceprofiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport \"fmt\"\n\n// switchDictionary updates the ResourceProfiles, switching its indices from one\n// dictionary to another.\nfunc (ms ResourceProfiles) switchDictionary(src, dst ProfilesDictionary) error {\n\tfor i, v := range ms.ScopeProfiles().All() {\n\t\terr := v.switchDictionary(src, dst)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error switching dictionary for scope profile %d: %w\", i, err)\n\t\t}\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "pdata/pprofile/resourceprofiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestResourceProfilesSwitchDictionary(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname             string\n\t\tresourceProfiles ResourceProfiles\n\n\t\tsrc ProfilesDictionary\n\t\tdst ProfilesDictionary\n\n\t\twantResourceProfiles ResourceProfiles\n\t\twantDictionary       ProfilesDictionary\n\t\twantErr              error\n\t}{\n\t\t{\n\t\t\tname:             \"with an empty resource profile\",\n\t\t\tresourceProfiles: NewResourceProfiles(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantResourceProfiles: NewResourceProfiles(),\n\t\t\twantDictionary:       NewProfilesDictionary(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a resource profiles that has a profile\",\n\t\t\tresourceProfiles: func() ResourceProfiles {\n\t\t\t\tr := NewResourceProfiles()\n\t\t\t\tprofile := r.ScopeProfiles().AppendEmpty().Profiles().AppendEmpty()\n\t\t\t\tprofile.Samples().AppendEmpty().SetLinkIndex(1)\n\t\t\t\treturn r\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\tl := d.LinkTable().AppendEmpty()\n\t\t\t\tl.SetSpanID(pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}))\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantResourceProfiles: func() ResourceProfiles {\n\t\t\t\tr := NewResourceProfiles()\n\t\t\t\tprofile := r.ScopeProfiles().AppendEmpty().Profiles().AppendEmpty()\n\t\t\t\tprofile.Samples().AppendEmpty().SetLinkIndex(2)\n\t\t\t\treturn r\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\tl := d.LinkTable().AppendEmpty()\n\t\t\t\tl.SetSpanID(pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}))\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\trp := tt.resourceProfiles\n\t\t\tdst := tt.dst\n\t\t\terr := rp.switchDictionary(tt.src, dst)\n\n\t\t\tif tt.wantErr == nil {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.Equal(t, tt.wantErr, err)\n\t\t\t}\n\n\t\t\tassert.Equal(t, tt.wantResourceProfiles, rp)\n\t\t\tassert.Equal(t, tt.wantDictionary, dst)\n\t\t})\n\t}\n}\n\nfunc BenchmarkResourceProfilesSwitchDictionary(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\n\tr := NewResourceProfiles()\n\tprofile := r.ScopeProfiles().AppendEmpty().Profiles().AppendEmpty()\n\tprofile.Samples().AppendEmpty().SetLinkIndex(1)\n\n\tsrc := NewProfilesDictionary()\n\tsrc.LinkTable().AppendEmpty()\n\tsrc.LinkTable().AppendEmpty().SetSpanID(pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}))\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tb.StopTimer()\n\t\tdst := NewProfilesDictionary()\n\t\tb.StartTimer()\n\n\t\t_ = r.switchDictionary(src, dst)\n\t}\n}\n"
  },
  {
    "path": "pdata/pprofile/sample.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport \"fmt\"\n\n// switchDictionary updates the Sample, switching its indices from one\n// dictionary to another.\nfunc (ms Sample) switchDictionary(src, dst ProfilesDictionary) error {\n\tfor i, v := range ms.AttributeIndices().All() {\n\t\tif src.AttributeTable().Len() <= int(v) {\n\t\t\treturn fmt.Errorf(\"invalid attribute index %d\", v)\n\t\t}\n\n\t\tattr := src.AttributeTable().At(int(v))\n\t\tidx, err := SetAttribute(dst.AttributeTable(), attr)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't set attribute %d: %w\", i, err)\n\t\t}\n\t\tms.AttributeIndices().SetAt(i, idx)\n\t}\n\n\tif ms.LinkIndex() > 0 {\n\t\tif src.LinkTable().Len() <= int(ms.LinkIndex()) {\n\t\t\treturn fmt.Errorf(\"invalid link index %d\", ms.LinkIndex())\n\t\t}\n\n\t\tidx, err := SetLink(dst.LinkTable(), src.LinkTable().At(int(ms.LinkIndex())))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't set link: %w\", err)\n\t\t}\n\t\tms.SetLinkIndex(idx)\n\t}\n\n\tif ms.StackIndex() > 0 {\n\t\tif src.StackTable().Len() <= int(ms.StackIndex()) {\n\t\t\treturn fmt.Errorf(\"invalid stack index %d\", ms.StackIndex())\n\t\t}\n\n\t\tstack := src.StackTable().At(int(ms.StackIndex()))\n\t\tidx, err := SetStack(dst.StackTable(), stack)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't set stack: %w\", err)\n\t\t}\n\t\tms.SetStackIndex(idx)\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "pdata/pprofile/sample_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestSampleSwitchDictionary(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname   string\n\t\tsample Sample\n\n\t\tsrc ProfilesDictionary\n\t\tdst ProfilesDictionary\n\n\t\twantSample     Sample\n\t\twantDictionary ProfilesDictionary\n\t\twantErr        error\n\t}{\n\t\t{\n\t\t\tname:   \"with an empty sample\",\n\t\t\tsample: NewSample(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantSample:     NewSample(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing attribute\",\n\t\t\tsample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.AttributeIndices().Append(1)\n\t\t\t\treturn s\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\ta := d.AttributeTable().AppendEmpty()\n\t\t\t\ta.SetKeyStrindex(1)\n\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\ta := d.AttributeTable().AppendEmpty()\n\t\t\t\ta.SetKeyStrindex(1)\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantSample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.AttributeIndices().Append(2)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\ta := d.AttributeTable().AppendEmpty()\n\t\t\t\ta.SetKeyStrindex(1)\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an attribute index that does not match anything\",\n\t\t\tsample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.AttributeIndices().Append(1)\n\t\t\t\treturn s\n\t\t\t}(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantSample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.AttributeIndices().Append(1)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid attribute index 1\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with an attribute index equal to the source table length (boundary condition)\",\n\t\t\tsample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.AttributeIndices().Append(2)\n\t\t\t\treturn s\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\td.AttributeTable().AppendEmpty()\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantSample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.AttributeIndices().Append(2)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid attribute index 2\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing link\",\n\t\t\tsample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.SetLinkIndex(1)\n\t\t\t\treturn s\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\tl := d.LinkTable().AppendEmpty()\n\t\t\t\tl.SetSpanID(pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}))\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantSample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.SetLinkIndex(2)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\tl := d.LinkTable().AppendEmpty()\n\t\t\t\tl.SetSpanID(pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}))\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a link index that does not match anything\",\n\t\t\tsample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.SetLinkIndex(1)\n\t\t\t\treturn s\n\t\t\t}(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantSample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.SetLinkIndex(1)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid link index 1\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with a link index equal to the source table length (boundary condition)\",\n\t\t\tsample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.SetLinkIndex(2)\n\t\t\t\treturn s\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantSample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.SetLinkIndex(2)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid link index 2\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing stack\",\n\t\t\tsample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.SetStackIndex(1)\n\t\t\t\treturn s\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LocationTable().AppendEmpty().SetAddress(1)\n\t\t\t\td.LocationTable().AppendEmpty().SetAddress(2)\n\n\t\t\t\td.StackTable().AppendEmpty()\n\t\t\t\ts := d.StackTable().AppendEmpty()\n\t\t\t\ts.LocationIndices().Append(1)\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LocationTable().AppendEmpty()\n\t\t\t\td.LocationTable().AppendEmpty().SetAddress(2)\n\n\t\t\t\td.StackTable().AppendEmpty()\n\t\t\t\td.StackTable().AppendEmpty()\n\t\t\t\ts := d.StackTable().AppendEmpty()\n\t\t\t\ts.LocationIndices().Append(1)\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantSample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.SetStackIndex(2)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LocationTable().AppendEmpty()\n\t\t\t\td.LocationTable().AppendEmpty().SetAddress(2)\n\n\t\t\t\td.StackTable().AppendEmpty()\n\t\t\t\td.StackTable().AppendEmpty()\n\t\t\t\ts := d.StackTable().AppendEmpty()\n\t\t\t\ts.LocationIndices().Append(1)\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a stack index that does not match anything\",\n\t\t\tsample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.SetStackIndex(1)\n\t\t\t\treturn s\n\t\t\t}(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantSample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.SetStackIndex(1)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid stack index 1\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with a stack index equal to the source table length (boundary condition)\",\n\t\t\tsample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.SetStackIndex(2)\n\t\t\t\treturn s\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StackTable().AppendEmpty()\n\t\t\t\td.StackTable().AppendEmpty()\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantSample: func() Sample {\n\t\t\t\ts := NewSample()\n\t\t\t\ts.SetStackIndex(2)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid stack index 2\"),\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsample := tt.sample\n\t\t\tdst := tt.dst\n\t\t\terr := sample.switchDictionary(tt.src, dst)\n\n\t\t\tif tt.wantErr == nil {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.Equal(t, tt.wantErr, err)\n\t\t\t}\n\n\t\t\tassert.Equal(t, tt.wantSample, sample)\n\t\t\tassert.Equal(t, tt.wantDictionary, dst)\n\t\t})\n\t}\n}\n\nfunc BenchmarkSampleSwitchDictionary(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\n\ts := NewSample()\n\ts.SetLinkIndex(1)\n\ts.SetStackIndex(1)\n\n\tsrc := NewProfilesDictionary()\n\tsrc.LocationTable().AppendEmpty()\n\tsrc.LocationTable().AppendEmpty().SetAddress(2)\n\tsrc.LinkTable().AppendEmpty()\n\tsrc.LinkTable().AppendEmpty().SetSpanID(pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}))\n\tsrc.StackTable().AppendEmpty()\n\tsrc.StackTable().AppendEmpty().LocationIndices().Append(1)\n\n\tdst := NewProfilesDictionary()\n\tsrc.LinkTable().AppendEmpty()\n\tsrc.LinkTable().AppendEmpty().SetSpanID(pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}))\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\t_ = s.switchDictionary(src, dst)\n\t}\n}\n"
  },
  {
    "path": "pdata/pprofile/scopeprofiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport \"fmt\"\n\n// switchDictionary updates the ScopeProfiles, switching its indices from one\n// dictionary to another.\nfunc (ms ScopeProfiles) switchDictionary(src, dst ProfilesDictionary) error {\n\tfor i, v := range ms.Profiles().All() {\n\t\terr := v.switchDictionary(src, dst)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"error switching dictionary for profile %d: %w\", i, err)\n\t\t}\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "pdata/pprofile/scopeprofiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestScopeProfilesSwitchDictionary(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname          string\n\t\tscopeProfiles ScopeProfiles\n\n\t\tsrc ProfilesDictionary\n\t\tdst ProfilesDictionary\n\n\t\twantScopeProfiles ScopeProfiles\n\t\twantDictionary    ProfilesDictionary\n\t\twantErr           error\n\t}{\n\t\t{\n\t\t\tname:          \"with an empty scope profile\",\n\t\t\tscopeProfiles: NewScopeProfiles(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantScopeProfiles: NewScopeProfiles(),\n\t\t\twantDictionary:    NewProfilesDictionary(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a scope profiles that has a profile\",\n\t\t\tscopeProfiles: func() ScopeProfiles {\n\t\t\t\ts := NewScopeProfiles()\n\t\t\t\tprofile := s.Profiles().AppendEmpty()\n\t\t\t\tprofile.Samples().AppendEmpty().SetLinkIndex(1)\n\t\t\t\treturn s\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\tl := d.LinkTable().AppendEmpty()\n\t\t\t\tl.SetSpanID(pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}))\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantScopeProfiles: func() ScopeProfiles {\n\t\t\t\ts := NewScopeProfiles()\n\t\t\t\tprofile := s.Profiles().AppendEmpty()\n\t\t\t\tprofile.Samples().AppendEmpty().SetLinkIndex(2)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\td.LinkTable().AppendEmpty()\n\t\t\t\tl := d.LinkTable().AppendEmpty()\n\t\t\t\tl.SetSpanID(pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}))\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsp := tt.scopeProfiles\n\t\t\tdst := tt.dst\n\t\t\terr := sp.switchDictionary(tt.src, dst)\n\n\t\t\tif tt.wantErr == nil {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.Equal(t, tt.wantErr, err)\n\t\t\t}\n\n\t\t\tassert.Equal(t, tt.wantScopeProfiles, sp)\n\t\t\tassert.Equal(t, tt.wantDictionary, dst)\n\t\t})\n\t}\n}\n\nfunc BenchmarkScopeProfilesSwitchDictionary(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\n\ts := NewScopeProfiles()\n\tprofile := s.Profiles().AppendEmpty()\n\tprofile.Samples().AppendEmpty().SetLinkIndex(1)\n\n\tsrc := NewProfilesDictionary()\n\tsrc.LinkTable().AppendEmpty()\n\tsrc.LinkTable().AppendEmpty().SetSpanID(pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}))\n\n\tdst := NewProfilesDictionary()\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\t_ = s.switchDictionary(src, dst)\n\t}\n}\n"
  },
  {
    "path": "pdata/pprofile/stack.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport (\n\t\"fmt\"\n)\n\n// Equal checks equality with another Stack\nfunc (ms Stack) Equal(val Stack) bool {\n\tif ms.LocationIndices().Len() != val.LocationIndices().Len() {\n\t\treturn false\n\t}\n\n\tfor i := range ms.LocationIndices().Len() {\n\t\tif ms.LocationIndices().At(i) != val.LocationIndices().At(i) {\n\t\t\treturn false\n\t\t}\n\t}\n\n\treturn true\n}\n\n// switchDictionary updates the Stack, switching its indices from one\n// dictionary to another.\nfunc (ms Stack) switchDictionary(src, dst ProfilesDictionary) error {\n\tfor i, v := range ms.LocationIndices().All() {\n\t\tif src.LocationTable().Len() <= int(v) {\n\t\t\treturn fmt.Errorf(\"invalid location index %d\", v)\n\t\t}\n\n\t\tloc := src.LocationTable().At(int(v))\n\t\tidx, err := SetLocation(dst.LocationTable(), loc)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't set location %d: %w\", i, err)\n\t\t}\n\t\tms.LocationIndices().SetAt(i, idx)\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "pdata/pprofile/stack_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc TestStackEqual(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname string\n\t\torig Stack\n\t\tdest Stack\n\t\twant bool\n\t}{\n\t\t{\n\t\t\tname: \"with empty stacks\",\n\t\t\torig: NewStack(),\n\t\t\tdest: NewStack(),\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"with non-empty equal stacks\",\n\t\t\torig: func() Stack {\n\t\t\t\ts := NewStack()\n\t\t\t\ts.LocationIndices().Append(1)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\tdest: func() Stack {\n\t\t\t\ts := NewStack()\n\t\t\t\ts.LocationIndices().Append(1)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\twant: true,\n\t\t},\n\t\t{\n\t\t\tname: \"with different location indices lengths\",\n\t\t\torig: func() Stack {\n\t\t\t\ts := NewStack()\n\t\t\t\ts.LocationIndices().Append(1)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\tdest: NewStack(),\n\t\t\twant: false,\n\t\t},\n\t\t{\n\t\t\tname: \"with non-equal location indices\",\n\t\t\torig: func() Stack {\n\t\t\t\ts := NewStack()\n\t\t\t\ts.LocationIndices().Append(2)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\tdest: func() Stack {\n\t\t\t\ts := NewStack()\n\t\t\t\ts.LocationIndices().Append(1)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\twant: false,\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tif tt.want {\n\t\t\t\tassert.True(t, tt.orig.Equal(tt.dest))\n\t\t\t} else {\n\t\t\t\tassert.False(t, tt.orig.Equal(tt.dest))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestStackSwitchDictionary(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname  string\n\t\tstack Stack\n\n\t\tsrc ProfilesDictionary\n\t\tdst ProfilesDictionary\n\n\t\twantStack      Stack\n\t\twantDictionary ProfilesDictionary\n\t\twantErr        error\n\t}{\n\t\t{\n\t\t\tname:  \"with an empty stack\",\n\t\t\tstack: NewStack(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantStack:      NewStack(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing location\",\n\t\t\tstack: func() Stack {\n\t\t\t\ts := NewStack()\n\t\t\t\ts.LocationIndices().Append(0)\n\t\t\t\treturn s\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\tloc := d.LocationTable().AppendEmpty()\n\t\t\t\tloc.SetAddress(42)\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantStack: func() Stack {\n\t\t\t\ts := NewStack()\n\t\t\t\ts.LocationIndices().Append(0)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\tloc := d.LocationTable().AppendEmpty()\n\t\t\t\tloc.SetAddress(42)\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing location that needs a new indice\",\n\t\t\tstack: func() Stack {\n\t\t\t\ts := NewStack()\n\t\t\t\ts.LocationIndices().Append(0)\n\t\t\t\treturn s\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\tloc := d.LocationTable().AppendEmpty()\n\t\t\t\tloc.SetAddress(42)\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\tloc := d.LocationTable().AppendEmpty()\n\t\t\t\tloc.SetAddress(2)\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantStack: func() Stack {\n\t\t\t\ts := NewStack()\n\t\t\t\ts.LocationIndices().Append(1)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\tloc := d.LocationTable().AppendEmpty()\n\t\t\t\tloc.SetAddress(2)\n\t\t\t\tloc = d.LocationTable().AppendEmpty()\n\t\t\t\tloc.SetAddress(42)\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a location index that does not match anything\",\n\t\t\tstack: func() Stack {\n\t\t\t\ts := NewStack()\n\t\t\t\ts.LocationIndices().Append(2)\n\t\t\t\treturn s\n\t\t\t}(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantStack: func() Stack {\n\t\t\t\ts := NewStack()\n\t\t\t\ts.LocationIndices().Append(2)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\n\t\t\twantErr: errors.New(\"invalid location index 2\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with a location index equal to the source table length (boundary condition)\",\n\t\t\tstack: func() Stack {\n\t\t\t\ts := NewStack()\n\t\t\t\ts.LocationIndices().Append(2) // Index 2 with length 2 (indices 0,1 are valid)\n\t\t\t\treturn s\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.LocationTable().AppendEmpty() // Index 0\n\t\t\t\td.LocationTable().AppendEmpty() // Index 1\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantStack: func() Stack {\n\t\t\t\ts := NewStack()\n\t\t\t\ts.LocationIndices().Append(2)\n\t\t\t\treturn s\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\n\t\t\twantErr: errors.New(\"invalid location index 2\"),\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tstack := tt.stack\n\t\t\tdst := tt.dst\n\t\t\terr := stack.switchDictionary(tt.src, dst)\n\n\t\t\tif tt.wantErr == nil {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.Equal(t, tt.wantErr, err)\n\t\t\t}\n\n\t\t\tassert.Equal(t, tt.wantStack, stack)\n\t\t\tassert.Equal(t, tt.wantDictionary, dst)\n\t\t})\n\t}\n}\n\nfunc BenchmarkStackSwitchDictionary(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\n\ts := NewStack()\n\ts.LocationIndices().Append(1, 2)\n\n\tsrc := NewProfilesDictionary()\n\tsrc.LocationTable().AppendEmpty()\n\tsrc.LocationTable().AppendEmpty().SetAddress(42)\n\tsrc.LocationTable().AppendEmpty().SetAddress(43)\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tb.StopTimer()\n\t\tdst := NewProfilesDictionary()\n\t\tdst.LocationTable().AppendEmpty()\n\t\tdst.LocationTable().AppendEmpty().SetAddress(43)\n\t\tb.StartTimer()\n\n\t\t_ = s.switchDictionary(src, dst)\n\t}\n}\n"
  },
  {
    "path": "pdata/pprofile/stacks.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport (\n\t\"errors\"\n\t\"math\"\n)\n\nvar errTooManyStackTableEntries = errors.New(\"too many entries in StackTable\")\n\n// SetStack updates a StackSlice, adding or providing a stack and returns its\n// index.\nfunc SetStack(table StackSlice, st Stack) (int32, error) {\n\tfor j, l := range table.All() {\n\t\tif l.Equal(st) {\n\t\t\tif j > math.MaxInt32 {\n\t\t\t\treturn 0, errTooManyStackTableEntries\n\t\t\t}\n\t\t\treturn int32(j), nil\n\t\t}\n\t}\n\n\tif table.Len() >= math.MaxInt32 {\n\t\treturn 0, errTooManyStackTableEntries\n\t}\n\n\tst.CopyTo(table.AppendEmpty())\n\treturn int32(table.Len() - 1), nil\n}\n"
  },
  {
    "path": "pdata/pprofile/stacks_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc TestSetStack(t *testing.T) {\n\ttable := NewStackSlice()\n\ts := NewStack()\n\ts.LocationIndices().Append(1)\n\ts2 := NewStack()\n\ts.LocationIndices().Append(2)\n\n\t// Put a first stack\n\tidx, err := SetStack(table, s)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 1, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\n\t// Put the same stack\n\t// This should be a no-op.\n\tidx, err = SetStack(table, s)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 1, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\n\t// Set a new stack\n\t// This sets the index and adds to the table.\n\tidx, err = SetStack(table, s2)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(table.Len()-1), idx)\n\n\t// Set an existing stack\n\tidx, err = SetStack(table, s)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\t// Set another existing stack\n\tidx, err = SetStack(table, s2)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(table.Len()-1), idx)\n}\n\nfunc BenchmarkSetStack(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\tfor _, bb := range []struct {\n\t\tname  string\n\t\tstack Stack\n\n\t\trunBefore func(*testing.B, StackSlice)\n\t}{\n\t\t{\n\t\t\tname:  \"with a new stack\",\n\t\t\tstack: NewStack(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing stack\",\n\t\t\tstack: func() Stack {\n\t\t\t\ts := NewStack()\n\t\t\t\ts.LocationIndices().Append(1)\n\t\t\t\treturn s\n\t\t\t}(),\n\n\t\t\trunBefore: func(_ *testing.B, table StackSlice) {\n\t\t\t\ts := table.AppendEmpty()\n\t\t\t\ts.LocationIndices().Append(1)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:  \"with a duplicate stack\",\n\t\t\tstack: NewStack(),\n\n\t\t\trunBefore: func(_ *testing.B, table StackSlice) {\n\t\t\t\t_, err := SetStack(table, NewStack())\n\t\t\t\trequire.NoError(b, err)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with a hundred stacks to loop through\",\n\t\t\tstack: func() Stack {\n\t\t\t\ts := NewStack()\n\t\t\t\ts.LocationIndices().Append(1)\n\t\t\t\treturn s\n\t\t\t}(),\n\n\t\t\trunBefore: func(_ *testing.B, table StackSlice) {\n\t\t\t\tfor range 100 {\n\t\t\t\t\ttable.AppendEmpty()\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t} {\n\t\tb.Run(bb.name, func(b *testing.B) {\n\t\t\ttable := NewStackSlice()\n\n\t\t\tif bb.runBefore != nil {\n\t\t\t\tbb.runBefore(b, table)\n\t\t\t}\n\n\t\t\tb.ResetTimer()\n\t\t\tb.ReportAllocs()\n\n\t\t\tfor b.Loop() {\n\t\t\t\t_, _ = SetStack(table, bb.stack)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "pdata/pprofile/string_table.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport (\n\t\"errors\"\n\t\"math\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nvar errTooManyStringTableEntries = errors.New(\"too many entries in StringTable\")\n\n// SetString updates a StringTable, adding or providing a value and returns its index.\nfunc SetString(table pcommon.StringSlice, val string) (int32, error) {\n\tfor j, v := range table.All() {\n\t\tif v == val {\n\t\t\tif j > math.MaxInt32 {\n\t\t\t\treturn 0, errTooManyStringTableEntries\n\t\t\t}\n\t\t\t// Return the index of the existing value.\n\t\t\treturn int32(j), nil\n\t\t}\n\t}\n\n\tif table.Len() >= math.MaxInt32 {\n\t\treturn 0, errTooManyMappingTableEntries\n\t}\n\n\ttable.Append(val)\n\treturn int32(table.Len() - 1), nil\n}\n"
  },
  {
    "path": "pdata/pprofile/string_table_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestSetString(t *testing.T) {\n\ttable := pcommon.NewStringSlice()\n\tv := \"test\"\n\tv2 := \"test2\"\n\n\t// Put a first value\n\tidx, err := SetString(table, v)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 1, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\n\t// Put the same string\n\t// This should be a no-op.\n\tidx, err = SetString(table, v)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 1, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\n\t// Set a new value\n\t// This sets the index and adds to the table.\n\tidx, err = SetString(table, v2)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(table.Len()-1), idx)\n\n\t// Set an existing value\n\tidx, err = SetString(table, v)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(0), idx)\n\t// Set another existing value\n\tidx, err = SetString(table, v2)\n\trequire.NoError(t, err)\n\tassert.Equal(t, 2, table.Len())\n\tassert.Equal(t, int32(table.Len()-1), idx)\n}\n\nfunc BenchmarkSetString(b *testing.B) {\n\tfor _, bb := range []struct {\n\t\tname string\n\t\tval  string\n\n\t\trunBefore func(*testing.B, pcommon.StringSlice)\n\t}{\n\t\t{\n\t\t\tname: \"with a new value\",\n\t\t\tval:  \"test\",\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing value\",\n\t\t\tval:  \"test\",\n\n\t\t\trunBefore: func(_ *testing.B, table pcommon.StringSlice) {\n\t\t\t\ttable.Append(\"test\")\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with a duplicate value\",\n\t\t\tval:  \"test\",\n\n\t\t\trunBefore: func(_ *testing.B, table pcommon.StringSlice) {\n\t\t\t\t_, err := SetString(table, \"test\")\n\t\t\t\trequire.NoError(b, err)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with a hundred values to loop through\",\n\t\t\tval:  \"test\",\n\n\t\t\trunBefore: func(_ *testing.B, table pcommon.StringSlice) {\n\t\t\t\tfor i := range 100 {\n\t\t\t\t\ttable.Append(strconv.Itoa(i))\n\t\t\t\t}\n\t\t\t},\n\t\t},\n\t} {\n\t\tb.Run(bb.name, func(b *testing.B) {\n\t\t\ttable := pcommon.NewStringSlice()\n\n\t\t\tif bb.runBefore != nil {\n\t\t\t\tbb.runBefore(b, table)\n\t\t\t}\n\n\t\t\tb.ResetTimer()\n\t\t\tb.ReportAllocs()\n\n\t\t\tfor b.Loop() {\n\t\t\t\t_, _ = SetString(table, bb.val)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "pdata/pprofile/valuetype.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile // import \"go.opentelemetry.io/collector/pdata/pprofile\"\n\nimport \"fmt\"\n\n// switchDictionary updates the ValueType, switching its indices from one\n// dictionary to another.\nfunc (ms ValueType) switchDictionary(src, dst ProfilesDictionary) error {\n\tif ms.TypeStrindex() > 0 {\n\t\tif src.StringTable().Len() <= int(ms.TypeStrindex()) {\n\t\t\treturn fmt.Errorf(\"invalid type index %d\", ms.TypeStrindex())\n\t\t}\n\n\t\tidx, err := SetString(dst.StringTable(), src.StringTable().At(int(ms.TypeStrindex())))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't set type: %w\", err)\n\t\t}\n\t\tms.SetTypeStrindex(idx)\n\t}\n\n\tif ms.UnitStrindex() > 0 {\n\t\tif src.StringTable().Len() <= int(ms.UnitStrindex()) {\n\t\t\treturn fmt.Errorf(\"invalid unit index %d\", ms.UnitStrindex())\n\t\t}\n\n\t\tidx, err := SetString(dst.StringTable(), src.StringTable().At(int(ms.UnitStrindex())))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"couldn't set unit: %w\", err)\n\t\t}\n\t\tms.SetUnitStrindex(idx)\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "pdata/pprofile/valuetype_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pprofile\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc TestValueTypeSwitchDictionary(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname      string\n\t\tvalueType ValueType\n\n\t\tsrc ProfilesDictionary\n\t\tdst ProfilesDictionary\n\n\t\twantValueType  ValueType\n\t\twantDictionary ProfilesDictionary\n\t\twantErr        error\n\t}{\n\t\t{\n\t\t\tname:      \"with an empty value type\",\n\t\t\tvalueType: NewValueType(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantValueType:  NewValueType(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing type\",\n\t\t\tvalueType: func() ValueType {\n\t\t\t\tvt := NewValueType()\n\t\t\t\tvt.SetTypeStrindex(1)\n\t\t\t\treturn vt\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\")\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantValueType: func() ValueType {\n\t\t\t\tvt := NewValueType()\n\t\t\t\tvt.SetTypeStrindex(2)\n\t\t\t\treturn vt\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a type index that does not match anything\",\n\t\t\tvalueType: func() ValueType {\n\t\t\t\tvt := NewValueType()\n\t\t\t\tvt.SetTypeStrindex(1)\n\t\t\t\treturn vt\n\t\t\t}(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantValueType: func() ValueType {\n\t\t\t\tvt := NewValueType()\n\t\t\t\tvt.SetTypeStrindex(1)\n\t\t\t\treturn vt\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid type index 1\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with a type index equal to the source table length (boundary condition)\",\n\t\t\tvalueType: func() ValueType {\n\t\t\t\tvt := NewValueType()\n\t\t\t\tvt.SetTypeStrindex(2)\n\t\t\t\treturn vt\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantValueType: func() ValueType {\n\t\t\t\tvt := NewValueType()\n\t\t\t\tvt.SetTypeStrindex(2)\n\t\t\t\treturn vt\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid type index 2\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with an existing unit\",\n\t\t\tvalueType: func() ValueType {\n\t\t\t\tvt := NewValueType()\n\t\t\t\tvt.SetUnitStrindex(1)\n\t\t\t\treturn vt\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\")\n\t\t\t\treturn d\n\t\t\t}(),\n\n\t\t\twantValueType: func() ValueType {\n\t\t\t\tvt := NewValueType()\n\t\t\t\tvt.SetUnitStrindex(2)\n\t\t\t\treturn vt\n\t\t\t}(),\n\t\t\twantDictionary: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"foo\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"with a unit index that does not match anything\",\n\t\t\tvalueType: func() ValueType {\n\t\t\t\tvt := NewValueType()\n\t\t\t\tvt.SetUnitStrindex(1)\n\t\t\t\treturn vt\n\t\t\t}(),\n\n\t\t\tsrc: NewProfilesDictionary(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantValueType: func() ValueType {\n\t\t\t\tvt := NewValueType()\n\t\t\t\tvt.SetUnitStrindex(1)\n\t\t\t\treturn vt\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid unit index 1\"),\n\t\t},\n\t\t{\n\t\t\tname: \"with a unit index equal to the source table length (boundary condition)\",\n\t\t\tvalueType: func() ValueType {\n\t\t\t\tvt := NewValueType()\n\t\t\t\tvt.SetUnitStrindex(2)\n\t\t\t\treturn vt\n\t\t\t}(),\n\n\t\t\tsrc: func() ProfilesDictionary {\n\t\t\t\td := NewProfilesDictionary()\n\t\t\t\td.StringTable().Append(\"\", \"test\")\n\t\t\t\treturn d\n\t\t\t}(),\n\t\t\tdst: NewProfilesDictionary(),\n\n\t\t\twantValueType: func() ValueType {\n\t\t\t\tvt := NewValueType()\n\t\t\t\tvt.SetUnitStrindex(2)\n\t\t\t\treturn vt\n\t\t\t}(),\n\t\t\twantDictionary: NewProfilesDictionary(),\n\t\t\twantErr:        errors.New(\"invalid unit index 2\"),\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvt := tt.valueType\n\t\t\tdst := tt.dst\n\t\t\terr := vt.switchDictionary(tt.src, dst)\n\n\t\t\tif tt.wantErr == nil {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.Equal(t, tt.wantErr, err)\n\t\t\t}\n\n\t\t\tassert.Equal(t, tt.wantValueType, vt)\n\t\t\tassert.Equal(t, tt.wantDictionary, dst)\n\t\t})\n\t}\n}\n\nfunc BenchmarkValueTypeSwitchDictionary(b *testing.B) {\n\ttestutil.SkipMemoryBench(b)\n\n\tvt := NewValueType()\n\tvt.SetTypeStrindex(1)\n\tvt.SetUnitStrindex(2)\n\n\tsrc := NewProfilesDictionary()\n\tsrc.StringTable().Append(\"\", \"test\", \"foo\")\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tb.StopTimer()\n\t\tdst := NewProfilesDictionary()\n\t\tdst.StringTable().Append(\"\", \"foo\")\n\t\tb.StartTimer()\n\n\t\t_ = vt.switchDictionary(src, dst)\n\t}\n}\n"
  },
  {
    "path": "pdata/ptrace/doc_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptrace_test\n\nimport (\n\t\"fmt\"\n\t\"strconv\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nfunc ExampleNewTraces() {\n\ttraces := ptrace.NewTraces()\n\n\tresourceSpans := traces.ResourceSpans().AppendEmpty()\n\n\tresourceSpans.Resource().Attributes().PutStr(\"service.name\", \"my-service\")\n\tresourceSpans.Resource().Attributes().PutStr(\"service.version\", \"1.0.0\")\n\n\tscopeSpans := resourceSpans.ScopeSpans().AppendEmpty()\n\tscopeSpans.Scope().SetName(\"my-instrumentation-library\")\n\tscopeSpans.Scope().SetVersion(\"1.0.0\")\n\n\tspan := scopeSpans.Spans().AppendEmpty()\n\tspan.SetName(\"my-operation\")\n\tspan.SetKind(ptrace.SpanKindServer)\n\tspan.SetStartTimestamp(pcommon.Timestamp(1640995200000000000)) // 2022-01-01 00:00:00 UTC\n\tspan.SetEndTimestamp(pcommon.Timestamp(1640995200100000000))   // 2022-01-01 00:00:00.1 UTC\n\n\tspan.Attributes().PutStr(\"http.method\", \"GET\")\n\tspan.Attributes().PutStr(\"http.url\", \"/api/v1/users\")\n\tspan.Attributes().PutInt(\"http.status_code\", 200)\n\n\tfmt.Printf(\"Resource spans count: %d\\n\", traces.ResourceSpans().Len())\n\tfmt.Printf(\"Spans count: %d\\n\", scopeSpans.Spans().Len())\n\tfmt.Printf(\"Span name: %s\\n\", span.Name())\n\t// Output:\n\t// Resource spans count: 1\n\t// Spans count: 1\n\t// Span name: my-operation\n}\n\nfunc ExampleSpan_SetTraceID() {\n\ttraces := ptrace.NewTraces()\n\tresourceSpans := traces.ResourceSpans().AppendEmpty()\n\tscopeSpans := resourceSpans.ScopeSpans().AppendEmpty()\n\tspan := scopeSpans.Spans().AppendEmpty()\n\n\ttraceID := pcommon.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16})\n\tspanID := pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8})\n\tparentSpanID := pcommon.SpanID([8]byte{9, 10, 11, 12, 13, 14, 15, 16})\n\n\tspan.SetTraceID(traceID)\n\tspan.SetSpanID(spanID)\n\tspan.SetParentSpanID(parentSpanID)\n\tspan.SetName(\"child-operation\")\n\n\tfmt.Printf(\"TraceID: %s\\n\", span.TraceID())\n\tfmt.Printf(\"SpanID: %s\\n\", span.SpanID())\n\tfmt.Printf(\"ParentSpanID: %s\\n\", span.ParentSpanID())\n\t// Output:\n\t// TraceID: 0102030405060708090a0b0c0d0e0f10\n\t// SpanID: 0102030405060708\n\t// ParentSpanID: 090a0b0c0d0e0f10\n}\n\nfunc ExampleSpan_Events() {\n\ttraces := ptrace.NewTraces()\n\tresourceSpans := traces.ResourceSpans().AppendEmpty()\n\tscopeSpans := resourceSpans.ScopeSpans().AppendEmpty()\n\tspan := scopeSpans.Spans().AppendEmpty()\n\n\tspan.SetName(\"database-query\")\n\n\tevent1 := span.Events().AppendEmpty()\n\tevent1.SetName(\"query.start\")\n\tevent1.SetTimestamp(pcommon.Timestamp(1640995200000000000))\n\tevent1.Attributes().PutStr(\"query\", \"SELECT * FROM users\")\n\n\tevent2 := span.Events().AppendEmpty()\n\tevent2.SetName(\"query.end\")\n\tevent2.SetTimestamp(pcommon.Timestamp(1640995200050000000))\n\tevent2.Attributes().PutInt(\"rows_returned\", 42)\n\n\tfmt.Printf(\"Events count: %d\\n\", span.Events().Len())\n\tfmt.Printf(\"First event name: %s\\n\", span.Events().At(0).Name())\n\tfmt.Printf(\"Second event name: %s\\n\", span.Events().At(1).Name())\n\t// Output:\n\t// Events count: 2\n\t// First event name: query.start\n\t// Second event name: query.end\n}\n\nfunc ExampleSpan_Status() {\n\ttraces := ptrace.NewTraces()\n\tresourceSpans := traces.ResourceSpans().AppendEmpty()\n\tscopeSpans := resourceSpans.ScopeSpans().AppendEmpty()\n\tspan := scopeSpans.Spans().AppendEmpty()\n\n\tspan.SetName(\"failed-operation\")\n\n\tstatus := span.Status()\n\tstatus.SetCode(ptrace.StatusCodeError)\n\tstatus.SetMessage(\"Connection timeout\")\n\n\tfmt.Printf(\"Status code: %s\\n\", status.Code())\n\tfmt.Printf(\"Status message: %s\\n\", status.Message())\n\t// Output:\n\t// Status code: Error\n\t// Status message: Connection timeout\n}\n\nfunc ExampleSpanKind() {\n\ttraces := ptrace.NewTraces()\n\tresourceSpans := traces.ResourceSpans().AppendEmpty()\n\tscopeSpans := resourceSpans.ScopeSpans().AppendEmpty()\n\n\t// Different span kinds\n\tkinds := []ptrace.SpanKind{\n\t\tptrace.SpanKindUnspecified,\n\t\tptrace.SpanKindInternal,\n\t\tptrace.SpanKindServer,\n\t\tptrace.SpanKindClient,\n\t\tptrace.SpanKindProducer,\n\t\tptrace.SpanKindConsumer,\n\t}\n\n\tfor i, kind := range kinds {\n\t\tspan := scopeSpans.Spans().AppendEmpty()\n\t\tspan.SetName(\"operation-\" + strconv.Itoa(i))\n\t\tspan.SetKind(kind)\n\t\tspan.SetStartTimestamp(pcommon.Timestamp(1640995200000000000))\n\t\tspan.SetEndTimestamp(pcommon.Timestamp(1640995200100000000))\n\t}\n\n\tfmt.Printf(\"Total spans: %d\\n\", scopeSpans.Spans().Len())\n\tfmt.Printf(\"First span kind: %s\\n\", scopeSpans.Spans().At(0).Kind())\n\tfmt.Printf(\"Server span kind: %s\\n\", scopeSpans.Spans().At(2).Kind())\n\tfmt.Printf(\"Client span kind: %s\\n\", scopeSpans.Spans().At(3).Kind())\n\t// Output:\n\t// Total spans: 6\n\t// First span kind: Unspecified\n\t// Server span kind: Server\n\t// Client span kind: Client\n}\n\nfunc ExampleSpan_Links() {\n\ttraces := ptrace.NewTraces()\n\tresourceSpans := traces.ResourceSpans().AppendEmpty()\n\tscopeSpans := resourceSpans.ScopeSpans().AppendEmpty()\n\tspan := scopeSpans.Spans().AppendEmpty()\n\n\tspan.SetName(\"memlimit-processor\")\n\tspan.SetKind(ptrace.SpanKindInternal)\n\n\t// Add links to other spans\n\tlink1 := span.Links().AppendEmpty()\n\tlink1.SetTraceID(pcommon.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}))\n\tlink1.SetSpanID(pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}))\n\tlink1.TraceState().FromRaw(\"rojo=00f067aa0ba902b7,congo=t61rcWkgMzE\")\n\tlink1.Attributes().PutStr(\"link.type\", \"follows_from\")\n\tlink1.SetFlags(0x01)\n\n\tlink2 := span.Links().AppendEmpty()\n\tlink2.SetTraceID(pcommon.TraceID([16]byte{16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1}))\n\tlink2.SetSpanID(pcommon.SpanID([8]byte{8, 7, 6, 5, 4, 3, 2, 1}))\n\tlink2.Attributes().PutStr(\"link.type\", \"child_of\")\n\tlink2.SetDroppedAttributesCount(2)\n\n\tspan.SetDroppedLinksCount(1)\n\n\tfmt.Printf(\"Links count: %d\\n\", span.Links().Len())\n\tfmt.Printf(\"First link trace state: %s\\n\", link1.TraceState().AsRaw())\n\tfmt.Printf(\"First link flags: %d\\n\", link1.Flags())\n\tfmt.Printf(\"Dropped links count: %d\\n\", span.DroppedLinksCount())\n\t// Output:\n\t// Links count: 2\n\t// First link trace state: rojo=00f067aa0ba902b7,congo=t61rcWkgMzE\n\t// First link flags: 1\n\t// Dropped links count: 1\n}\n\nfunc ExampleSpan_TraceState() {\n\ttraces := ptrace.NewTraces()\n\tresourceSpans := traces.ResourceSpans().AppendEmpty()\n\tscopeSpans := resourceSpans.ScopeSpans().AppendEmpty()\n\tspan := scopeSpans.Spans().AppendEmpty()\n\n\tspan.SetName(\"traced-operation\")\n\n\t// Set trace state (W3C Trace Context)\n\tspan.TraceState().FromRaw(\"rojo=00f067aa0ba902b7,congo=t61rcWkgMzE\")\n\n\tfmt.Printf(\"Trace state: %s\\n\", span.TraceState().AsRaw())\n\t// Output:\n\t// Trace state: rojo=00f067aa0ba902b7,congo=t61rcWkgMzE\n}\n\nfunc ExampleSpan_Flags() {\n\ttraces := ptrace.NewTraces()\n\tresourceSpans := traces.ResourceSpans().AppendEmpty()\n\tscopeSpans := resourceSpans.ScopeSpans().AppendEmpty()\n\tspan := scopeSpans.Spans().AppendEmpty()\n\n\tspan.SetName(\"sampled-span\")\n\n\t// Set trace flags (W3C Trace Context)\n\tspan.SetFlags(0x01) // Sampled flag\n\n\tfmt.Printf(\"Span flags: %d\\n\", span.Flags())\n\t// Output:\n\t// Span flags: 1\n}\n\nfunc ExampleStatusCode() {\n\ttraces := ptrace.NewTraces()\n\tresourceSpans := traces.ResourceSpans().AppendEmpty()\n\tscopeSpans := resourceSpans.ScopeSpans().AppendEmpty()\n\n\t// Different status codes\n\tstatuses := []struct {\n\t\tcode ptrace.StatusCode\n\t\tmsg  string\n\t\tname string\n\t}{\n\t\t{ptrace.StatusCodeUnset, \"\", \"unset\"},\n\t\t{ptrace.StatusCodeOk, \"Success\", \"ok\"},\n\t\t{ptrace.StatusCodeError, \"Internal server error\", \"error\"},\n\t}\n\n\tfor _, s := range statuses {\n\t\tspan := scopeSpans.Spans().AppendEmpty()\n\t\tspan.SetName(\"operation-\" + s.name)\n\t\tstatus := span.Status()\n\t\tstatus.SetCode(s.code)\n\t\tstatus.SetMessage(s.msg)\n\t}\n\n\tfmt.Printf(\"Total spans: %d\\n\", scopeSpans.Spans().Len())\n\tfmt.Printf(\"Unset status: %s\\n\", scopeSpans.Spans().At(0).Status().Code())\n\tfmt.Printf(\"Ok status: %s\\n\", scopeSpans.Spans().At(1).Status().Code())\n\tfmt.Printf(\"Error status: %s\\n\", scopeSpans.Spans().At(2).Status().Code())\n\tfmt.Printf(\"Error message: %s\\n\", scopeSpans.Spans().At(2).Status().Message())\n\t// Output:\n\t// Total spans: 3\n\t// Unset status: Unset\n\t// Ok status: Ok\n\t// Error status: Error\n\t// Error message: Internal server error\n}\n\nfunc ExampleSpan_DroppedAttributesCount() {\n\ttraces := ptrace.NewTraces()\n\tresourceSpans := traces.ResourceSpans().AppendEmpty()\n\tscopeSpans := resourceSpans.ScopeSpans().AppendEmpty()\n\tspan := scopeSpans.Spans().AppendEmpty()\n\n\tspan.SetName(\"span-with-dropped-data\")\n\n\t// Add some attributes and events\n\tspan.Attributes().PutStr(\"key1\", \"value1\")\n\tspan.Attributes().PutStr(\"key2\", \"value2\")\n\n\tevent := span.Events().AppendEmpty()\n\tevent.SetName(\"event1\")\n\tevent.SetTimestamp(pcommon.Timestamp(1640995200000000000))\n\n\t// Set dropped counts\n\tspan.SetDroppedAttributesCount(5)\n\tspan.SetDroppedEventsCount(3)\n\tspan.SetDroppedLinksCount(2)\n\n\tfmt.Printf(\"Current attributes: %d\\n\", span.Attributes().Len())\n\tfmt.Printf(\"Dropped attributes: %d\\n\", span.DroppedAttributesCount())\n\tfmt.Printf(\"Current events: %d\\n\", span.Events().Len())\n\tfmt.Printf(\"Dropped events: %d\\n\", span.DroppedEventsCount())\n\tfmt.Printf(\"Dropped links: %d\\n\", span.DroppedLinksCount())\n\t// Output:\n\t// Current attributes: 2\n\t// Dropped attributes: 5\n\t// Current events: 1\n\t// Dropped events: 3\n\t// Dropped links: 2\n}\n"
  },
  {
    "path": "pdata/ptrace/encoding.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptrace // import \"go.opentelemetry.io/collector/pdata/ptrace\"\n\n// MarshalSizer is the interface that groups the basic Marshal and Size methods\ntype MarshalSizer interface {\n\tMarshaler\n\tSizer\n}\n\n// Marshaler marshals Traces into bytes.\ntype Marshaler interface {\n\t// MarshalTraces the given Traces into bytes.\n\t// If the error is not nil, the returned bytes slice cannot be used.\n\tMarshalTraces(td Traces) ([]byte, error)\n}\n\n// Unmarshaler unmarshalls bytes into Traces.\ntype Unmarshaler interface {\n\t// UnmarshalTraces the given bytes into Traces.\n\t// If the error is not nil, the returned Traces cannot be used.\n\tUnmarshalTraces(buf []byte) (Traces, error)\n}\n\n// Sizer is an optional interface implemented by the Marshaler,\n// that calculates the size of a marshaled Traces.\ntype Sizer interface {\n\t// TracesSize returns the size in bytes of a marshaled Traces.\n\tTracesSize(td Traces) int\n}\n"
  },
  {
    "path": "pdata/ptrace/fuzz_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptrace // import \"go.opentelemetry.io/collector/pdata/ptrace\"\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar unexpectedBytes = \"expected the same bytes from unmarshaling and marshaling.\"\n\nfunc FuzzUnmarshalJSONTraces(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\tu1 := &JSONUnmarshaler{}\n\t\tld1, err := u1.UnmarshalTraces(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tm1 := &JSONMarshaler{}\n\t\tb1, err := m1.MarshalTraces(ld1)\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\tu2 := &JSONUnmarshaler{}\n\t\tld2, err := u2.UnmarshalTraces(b1)\n\t\trequire.NoError(t, err, \"failed to unmarshal valid bytes\")\n\t\tm2 := &JSONMarshaler{}\n\t\tb2, err := m2.MarshalTraces(ld2)\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n\nfunc FuzzUnmarshalPBTraces(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\tu1 := &ProtoUnmarshaler{}\n\t\tld1, err := u1.UnmarshalTraces(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tm1 := &ProtoMarshaler{}\n\t\tb1, err := m1.MarshalTraces(ld1)\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\tu2 := &ProtoUnmarshaler{}\n\t\tld2, err := u2.UnmarshalTraces(b1)\n\t\trequire.NoError(t, err, \"failed to unmarshal valid bytes\")\n\t\tm2 := &ProtoMarshaler{}\n\t\tb2, err := m2.MarshalTraces(ld2)\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_resourcespans.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ResourceSpans is a collection of spans from a Resource.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewResourceSpans function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ResourceSpans struct {\n\torig  *internal.ResourceSpans\n\tstate *internal.State\n}\n\nfunc newResourceSpans(orig *internal.ResourceSpans, state *internal.State) ResourceSpans {\n\treturn ResourceSpans{orig: orig, state: state}\n}\n\n// NewResourceSpans creates a new empty ResourceSpans.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewResourceSpans() ResourceSpans {\n\treturn newResourceSpans(internal.NewResourceSpans(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ResourceSpans) MoveTo(dest ResourceSpans) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteResourceSpans(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Resource returns the resource associated with this ResourceSpans.\nfunc (ms ResourceSpans) Resource() pcommon.Resource {\n\treturn pcommon.Resource(internal.NewResourceWrapper(&ms.orig.Resource, ms.state))\n}\n\n// ScopeSpans returns the ScopeSpans associated with this ResourceSpans.\nfunc (ms ResourceSpans) ScopeSpans() ScopeSpansSlice {\n\treturn newScopeSpansSlice(&ms.orig.ScopeSpans, ms.state)\n}\n\n// SchemaUrl returns the schemaurl associated with this ResourceSpans.\nfunc (ms ResourceSpans) SchemaUrl() string {\n\treturn ms.orig.SchemaUrl\n}\n\n// SetSchemaUrl replaces the schemaurl associated with this ResourceSpans.\nfunc (ms ResourceSpans) SetSchemaUrl(v string) {\n\tms.state.AssertMutable()\n\tms.orig.SchemaUrl = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ResourceSpans) CopyTo(dest ResourceSpans) {\n\tdest.state.AssertMutable()\n\tinternal.CopyResourceSpans(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_resourcespans_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestResourceSpans_MoveTo(t *testing.T) {\n\tms := generateTestResourceSpans()\n\tdest := NewResourceSpans()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewResourceSpans(), ms)\n\tassert.Equal(t, generateTestResourceSpans(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestResourceSpans(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newResourceSpans(internal.NewResourceSpans(), sharedState)) })\n\tassert.Panics(t, func() { newResourceSpans(internal.NewResourceSpans(), sharedState).MoveTo(dest) })\n}\n\nfunc TestResourceSpans_CopyTo(t *testing.T) {\n\tms := NewResourceSpans()\n\torig := NewResourceSpans()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestResourceSpans()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newResourceSpans(internal.NewResourceSpans(), sharedState)) })\n}\n\nfunc TestResourceSpans_Resource(t *testing.T) {\n\tms := NewResourceSpans()\n\tassert.Equal(t, pcommon.NewResource(), ms.Resource())\n\tms.orig.Resource = *internal.GenTestResource()\n\tassert.Equal(t, pcommon.Resource(internal.GenTestResourceWrapper()), ms.Resource())\n}\n\nfunc TestResourceSpans_ScopeSpans(t *testing.T) {\n\tms := NewResourceSpans()\n\tassert.Equal(t, NewScopeSpansSlice(), ms.ScopeSpans())\n\tms.orig.ScopeSpans = internal.GenTestScopeSpansPtrSlice()\n\tassert.Equal(t, generateTestScopeSpansSlice(), ms.ScopeSpans())\n}\n\nfunc TestResourceSpans_SchemaUrl(t *testing.T) {\n\tms := NewResourceSpans()\n\tassert.Empty(t, ms.SchemaUrl())\n\tms.SetSchemaUrl(\"test_schemaurl\")\n\tassert.Equal(t, \"test_schemaurl\", ms.SchemaUrl())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newResourceSpans(internal.NewResourceSpans(), sharedState).SetSchemaUrl(\"test_schemaurl\") })\n}\n\nfunc generateTestResourceSpans() ResourceSpans {\n\treturn newResourceSpans(internal.GenTestResourceSpans(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_resourcespansslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ResourceSpansSlice logically represents a slice of ResourceSpans.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewResourceSpansSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ResourceSpansSlice struct {\n\torig  *[]*internal.ResourceSpans\n\tstate *internal.State\n}\n\nfunc newResourceSpansSlice(orig *[]*internal.ResourceSpans, state *internal.State) ResourceSpansSlice {\n\treturn ResourceSpansSlice{orig: orig, state: state}\n}\n\n// NewResourceSpansSlice creates a ResourceSpansSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewResourceSpansSlice() ResourceSpansSlice {\n\torig := []*internal.ResourceSpans(nil)\n\treturn newResourceSpansSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewResourceSpansSlice()\".\nfunc (es ResourceSpansSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es ResourceSpansSlice) At(i int) ResourceSpans {\n\treturn newResourceSpans((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es ResourceSpansSlice) All() iter.Seq2[int, ResourceSpans] {\n\treturn func(yield func(int, ResourceSpans) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new ResourceSpansSlice can be initialized:\n//\n//\tes := NewResourceSpansSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es ResourceSpansSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.ResourceSpans, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty ResourceSpans.\n// It returns the newly added ResourceSpans.\nfunc (es ResourceSpansSlice) AppendEmpty() ResourceSpans {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewResourceSpans())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es ResourceSpansSlice) MoveAndAppendTo(dest ResourceSpansSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es ResourceSpansSlice) RemoveIf(f func(ResourceSpans) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteResourceSpans((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es ResourceSpansSlice) CopyTo(dest ResourceSpansSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyResourceSpansPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the ResourceSpans elements within ResourceSpansSlice given the\n// provided less function so that two instances of ResourceSpansSlice\n// can be compared.\nfunc (es ResourceSpansSlice) Sort(less func(a, b ResourceSpans) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_resourcespansslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestResourceSpansSlice(t *testing.T) {\n\tes := NewResourceSpansSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newResourceSpansSlice(&[]*internal.ResourceSpans{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewResourceSpans()\n\ttestVal := generateTestResourceSpans()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestResourceSpans()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestResourceSpansSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newResourceSpansSlice(&[]*internal.ResourceSpans{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewResourceSpansSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestResourceSpansSlice_CopyTo(t *testing.T) {\n\tdest := NewResourceSpansSlice()\n\tsrc := generateTestResourceSpansSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestResourceSpansSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestResourceSpansSlice(), dest)\n}\n\nfunc TestResourceSpansSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestResourceSpansSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestResourceSpansSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestResourceSpansSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestResourceSpansSlice(), es)\n}\n\nfunc TestResourceSpansSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestResourceSpansSlice()\n\tdest := NewResourceSpansSlice()\n\tsrc := generateTestResourceSpansSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestResourceSpansSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestResourceSpansSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestResourceSpansSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestResourceSpansSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewResourceSpansSlice()\n\temptySlice.RemoveIf(func(el ResourceSpans) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestResourceSpansSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el ResourceSpans) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestResourceSpansSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestResourceSpansSlice()\n\tgot.RemoveIf(func(el ResourceSpans) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestResourceSpansSliceAll(t *testing.T) {\n\tms := generateTestResourceSpansSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestResourceSpansSlice_Sort(t *testing.T) {\n\tes := generateTestResourceSpansSlice()\n\tes.Sort(func(a, b ResourceSpans) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b ResourceSpans) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestResourceSpansSlice() ResourceSpansSlice {\n\tms := NewResourceSpansSlice()\n\t*ms.orig = internal.GenTestResourceSpansPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_scopespans.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ScopeSpans is a collection of spans from a LibraryInstrumentation.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewScopeSpans function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ScopeSpans struct {\n\torig  *internal.ScopeSpans\n\tstate *internal.State\n}\n\nfunc newScopeSpans(orig *internal.ScopeSpans, state *internal.State) ScopeSpans {\n\treturn ScopeSpans{orig: orig, state: state}\n}\n\n// NewScopeSpans creates a new empty ScopeSpans.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewScopeSpans() ScopeSpans {\n\treturn newScopeSpans(internal.NewScopeSpans(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ScopeSpans) MoveTo(dest ScopeSpans) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteScopeSpans(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Scope returns the scope associated with this ScopeSpans.\nfunc (ms ScopeSpans) Scope() pcommon.InstrumentationScope {\n\treturn pcommon.InstrumentationScope(internal.NewInstrumentationScopeWrapper(&ms.orig.Scope, ms.state))\n}\n\n// Spans returns the Spans associated with this ScopeSpans.\nfunc (ms ScopeSpans) Spans() SpanSlice {\n\treturn newSpanSlice(&ms.orig.Spans, ms.state)\n}\n\n// SchemaUrl returns the schemaurl associated with this ScopeSpans.\nfunc (ms ScopeSpans) SchemaUrl() string {\n\treturn ms.orig.SchemaUrl\n}\n\n// SetSchemaUrl replaces the schemaurl associated with this ScopeSpans.\nfunc (ms ScopeSpans) SetSchemaUrl(v string) {\n\tms.state.AssertMutable()\n\tms.orig.SchemaUrl = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ScopeSpans) CopyTo(dest ScopeSpans) {\n\tdest.state.AssertMutable()\n\tinternal.CopyScopeSpans(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_scopespans_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestScopeSpans_MoveTo(t *testing.T) {\n\tms := generateTestScopeSpans()\n\tdest := NewScopeSpans()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewScopeSpans(), ms)\n\tassert.Equal(t, generateTestScopeSpans(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestScopeSpans(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newScopeSpans(internal.NewScopeSpans(), sharedState)) })\n\tassert.Panics(t, func() { newScopeSpans(internal.NewScopeSpans(), sharedState).MoveTo(dest) })\n}\n\nfunc TestScopeSpans_CopyTo(t *testing.T) {\n\tms := NewScopeSpans()\n\torig := NewScopeSpans()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestScopeSpans()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newScopeSpans(internal.NewScopeSpans(), sharedState)) })\n}\n\nfunc TestScopeSpans_Scope(t *testing.T) {\n\tms := NewScopeSpans()\n\tassert.Equal(t, pcommon.NewInstrumentationScope(), ms.Scope())\n\tms.orig.Scope = *internal.GenTestInstrumentationScope()\n\tassert.Equal(t, pcommon.InstrumentationScope(internal.GenTestInstrumentationScopeWrapper()), ms.Scope())\n}\n\nfunc TestScopeSpans_Spans(t *testing.T) {\n\tms := NewScopeSpans()\n\tassert.Equal(t, NewSpanSlice(), ms.Spans())\n\tms.orig.Spans = internal.GenTestSpanPtrSlice()\n\tassert.Equal(t, generateTestSpanSlice(), ms.Spans())\n}\n\nfunc TestScopeSpans_SchemaUrl(t *testing.T) {\n\tms := NewScopeSpans()\n\tassert.Empty(t, ms.SchemaUrl())\n\tms.SetSchemaUrl(\"test_schemaurl\")\n\tassert.Equal(t, \"test_schemaurl\", ms.SchemaUrl())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newScopeSpans(internal.NewScopeSpans(), sharedState).SetSchemaUrl(\"test_schemaurl\") })\n}\n\nfunc generateTestScopeSpans() ScopeSpans {\n\treturn newScopeSpans(internal.GenTestScopeSpans(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_scopespansslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ScopeSpansSlice logically represents a slice of ScopeSpans.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewScopeSpansSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ScopeSpansSlice struct {\n\torig  *[]*internal.ScopeSpans\n\tstate *internal.State\n}\n\nfunc newScopeSpansSlice(orig *[]*internal.ScopeSpans, state *internal.State) ScopeSpansSlice {\n\treturn ScopeSpansSlice{orig: orig, state: state}\n}\n\n// NewScopeSpansSlice creates a ScopeSpansSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewScopeSpansSlice() ScopeSpansSlice {\n\torig := []*internal.ScopeSpans(nil)\n\treturn newScopeSpansSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewScopeSpansSlice()\".\nfunc (es ScopeSpansSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es ScopeSpansSlice) At(i int) ScopeSpans {\n\treturn newScopeSpans((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es ScopeSpansSlice) All() iter.Seq2[int, ScopeSpans] {\n\treturn func(yield func(int, ScopeSpans) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new ScopeSpansSlice can be initialized:\n//\n//\tes := NewScopeSpansSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es ScopeSpansSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.ScopeSpans, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty ScopeSpans.\n// It returns the newly added ScopeSpans.\nfunc (es ScopeSpansSlice) AppendEmpty() ScopeSpans {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewScopeSpans())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es ScopeSpansSlice) MoveAndAppendTo(dest ScopeSpansSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es ScopeSpansSlice) RemoveIf(f func(ScopeSpans) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteScopeSpans((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es ScopeSpansSlice) CopyTo(dest ScopeSpansSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopyScopeSpansPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the ScopeSpans elements within ScopeSpansSlice given the\n// provided less function so that two instances of ScopeSpansSlice\n// can be compared.\nfunc (es ScopeSpansSlice) Sort(less func(a, b ScopeSpans) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_scopespansslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestScopeSpansSlice(t *testing.T) {\n\tes := NewScopeSpansSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newScopeSpansSlice(&[]*internal.ScopeSpans{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewScopeSpans()\n\ttestVal := generateTestScopeSpans()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestScopeSpans()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestScopeSpansSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newScopeSpansSlice(&[]*internal.ScopeSpans{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewScopeSpansSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestScopeSpansSlice_CopyTo(t *testing.T) {\n\tdest := NewScopeSpansSlice()\n\tsrc := generateTestScopeSpansSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestScopeSpansSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestScopeSpansSlice(), dest)\n}\n\nfunc TestScopeSpansSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestScopeSpansSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestScopeSpansSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestScopeSpansSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestScopeSpansSlice(), es)\n}\n\nfunc TestScopeSpansSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestScopeSpansSlice()\n\tdest := NewScopeSpansSlice()\n\tsrc := generateTestScopeSpansSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestScopeSpansSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestScopeSpansSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestScopeSpansSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestScopeSpansSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewScopeSpansSlice()\n\temptySlice.RemoveIf(func(el ScopeSpans) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestScopeSpansSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el ScopeSpans) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestScopeSpansSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestScopeSpansSlice()\n\tgot.RemoveIf(func(el ScopeSpans) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestScopeSpansSliceAll(t *testing.T) {\n\tms := generateTestScopeSpansSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestScopeSpansSlice_Sort(t *testing.T) {\n\tes := generateTestScopeSpansSlice()\n\tes.Sort(func(a, b ScopeSpans) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b ScopeSpans) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestScopeSpansSlice() ScopeSpansSlice {\n\tms := NewScopeSpansSlice()\n\t*ms.orig = internal.GenTestScopeSpansPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_span.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// Span represents a single operation within a trace.\n// See Span definition in OTLP: https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/trace/v1/trace.proto\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewSpan function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Span struct {\n\torig  *internal.Span\n\tstate *internal.State\n}\n\nfunc newSpan(orig *internal.Span, state *internal.State) Span {\n\treturn Span{orig: orig, state: state}\n}\n\n// NewSpan creates a new empty Span.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewSpan() Span {\n\treturn newSpan(internal.NewSpan(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Span) MoveTo(dest Span) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteSpan(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// TraceID returns the traceid associated with this Span.\nfunc (ms Span) TraceID() pcommon.TraceID {\n\treturn pcommon.TraceID(ms.orig.TraceId)\n}\n\n// SetTraceID replaces the traceid associated with this Span.\nfunc (ms Span) SetTraceID(v pcommon.TraceID) {\n\tms.state.AssertMutable()\n\tms.orig.TraceId = internal.TraceID(v)\n}\n\n// SpanID returns the spanid associated with this Span.\nfunc (ms Span) SpanID() pcommon.SpanID {\n\treturn pcommon.SpanID(ms.orig.SpanId)\n}\n\n// SetSpanID replaces the spanid associated with this Span.\nfunc (ms Span) SetSpanID(v pcommon.SpanID) {\n\tms.state.AssertMutable()\n\tms.orig.SpanId = internal.SpanID(v)\n}\n\n// TraceState returns the tracestate associated with this Span.\nfunc (ms Span) TraceState() pcommon.TraceState {\n\treturn pcommon.TraceState(internal.NewTraceStateWrapper(&ms.orig.TraceState, ms.state))\n}\n\n// ParentSpanID returns the parentspanid associated with this Span.\nfunc (ms Span) ParentSpanID() pcommon.SpanID {\n\treturn pcommon.SpanID(ms.orig.ParentSpanId)\n}\n\n// SetParentSpanID replaces the parentspanid associated with this Span.\nfunc (ms Span) SetParentSpanID(v pcommon.SpanID) {\n\tms.state.AssertMutable()\n\tms.orig.ParentSpanId = internal.SpanID(v)\n}\n\n// Flags returns the flags associated with this Span.\nfunc (ms Span) Flags() uint32 {\n\treturn ms.orig.Flags\n}\n\n// SetFlags replaces the flags associated with this Span.\nfunc (ms Span) SetFlags(v uint32) {\n\tms.state.AssertMutable()\n\tms.orig.Flags = v\n}\n\n// Name returns the name associated with this Span.\nfunc (ms Span) Name() string {\n\treturn ms.orig.Name\n}\n\n// SetName replaces the name associated with this Span.\nfunc (ms Span) SetName(v string) {\n\tms.state.AssertMutable()\n\tms.orig.Name = v\n}\n\n// Kind returns the kind associated with this Span.\nfunc (ms Span) Kind() SpanKind {\n\treturn SpanKind(ms.orig.Kind)\n}\n\n// SetKind replaces the kind associated with this Span.\nfunc (ms Span) SetKind(v SpanKind) {\n\tms.state.AssertMutable()\n\tms.orig.Kind = internal.SpanKind(v)\n}\n\n// StartTimestamp returns the starttimestamp associated with this Span.\nfunc (ms Span) StartTimestamp() pcommon.Timestamp {\n\treturn pcommon.Timestamp(ms.orig.StartTimeUnixNano)\n}\n\n// SetStartTimestamp replaces the starttimestamp associated with this Span.\nfunc (ms Span) SetStartTimestamp(v pcommon.Timestamp) {\n\tms.state.AssertMutable()\n\tms.orig.StartTimeUnixNano = uint64(v)\n}\n\n// EndTimestamp returns the endtimestamp associated with this Span.\nfunc (ms Span) EndTimestamp() pcommon.Timestamp {\n\treturn pcommon.Timestamp(ms.orig.EndTimeUnixNano)\n}\n\n// SetEndTimestamp replaces the endtimestamp associated with this Span.\nfunc (ms Span) SetEndTimestamp(v pcommon.Timestamp) {\n\tms.state.AssertMutable()\n\tms.orig.EndTimeUnixNano = uint64(v)\n}\n\n// Attributes returns the Attributes associated with this Span.\nfunc (ms Span) Attributes() pcommon.Map {\n\treturn pcommon.Map(internal.NewMapWrapper(&ms.orig.Attributes, ms.state))\n}\n\n// DroppedAttributesCount returns the droppedattributescount associated with this Span.\nfunc (ms Span) DroppedAttributesCount() uint32 {\n\treturn ms.orig.DroppedAttributesCount\n}\n\n// SetDroppedAttributesCount replaces the droppedattributescount associated with this Span.\nfunc (ms Span) SetDroppedAttributesCount(v uint32) {\n\tms.state.AssertMutable()\n\tms.orig.DroppedAttributesCount = v\n}\n\n// Events returns the Events associated with this Span.\nfunc (ms Span) Events() SpanEventSlice {\n\treturn newSpanEventSlice(&ms.orig.Events, ms.state)\n}\n\n// DroppedEventsCount returns the droppedeventscount associated with this Span.\nfunc (ms Span) DroppedEventsCount() uint32 {\n\treturn ms.orig.DroppedEventsCount\n}\n\n// SetDroppedEventsCount replaces the droppedeventscount associated with this Span.\nfunc (ms Span) SetDroppedEventsCount(v uint32) {\n\tms.state.AssertMutable()\n\tms.orig.DroppedEventsCount = v\n}\n\n// Links returns the Links associated with this Span.\nfunc (ms Span) Links() SpanLinkSlice {\n\treturn newSpanLinkSlice(&ms.orig.Links, ms.state)\n}\n\n// DroppedLinksCount returns the droppedlinkscount associated with this Span.\nfunc (ms Span) DroppedLinksCount() uint32 {\n\treturn ms.orig.DroppedLinksCount\n}\n\n// SetDroppedLinksCount replaces the droppedlinkscount associated with this Span.\nfunc (ms Span) SetDroppedLinksCount(v uint32) {\n\tms.state.AssertMutable()\n\tms.orig.DroppedLinksCount = v\n}\n\n// Status returns the status associated with this Span.\nfunc (ms Span) Status() Status {\n\treturn newStatus(&ms.orig.Status, ms.state)\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Span) CopyTo(dest Span) {\n\tdest.state.AssertMutable()\n\tinternal.CopySpan(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_span_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestSpan_MoveTo(t *testing.T) {\n\tms := generateTestSpan()\n\tdest := NewSpan()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewSpan(), ms)\n\tassert.Equal(t, generateTestSpan(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestSpan(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newSpan(internal.NewSpan(), sharedState)) })\n\tassert.Panics(t, func() { newSpan(internal.NewSpan(), sharedState).MoveTo(dest) })\n}\n\nfunc TestSpan_CopyTo(t *testing.T) {\n\tms := NewSpan()\n\torig := NewSpan()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestSpan()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newSpan(internal.NewSpan(), sharedState)) })\n}\n\nfunc TestSpan_TraceID(t *testing.T) {\n\tms := NewSpan()\n\tassert.Equal(t, pcommon.TraceID(internal.TraceID([16]byte{})), ms.TraceID())\n\ttestValTraceID := pcommon.TraceID(internal.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1}))\n\tms.SetTraceID(testValTraceID)\n\tassert.Equal(t, testValTraceID, ms.TraceID())\n}\n\nfunc TestSpan_SpanID(t *testing.T) {\n\tms := NewSpan()\n\tassert.Equal(t, pcommon.SpanID(internal.SpanID([8]byte{})), ms.SpanID())\n\ttestValSpanID := pcommon.SpanID(internal.SpanID([8]byte{8, 7, 6, 5, 4, 3, 2, 1}))\n\tms.SetSpanID(testValSpanID)\n\tassert.Equal(t, testValSpanID, ms.SpanID())\n}\n\nfunc TestSpan_TraceState(t *testing.T) {\n\tms := NewSpan()\n\tassert.Equal(t, pcommon.NewTraceState(), ms.TraceState())\n\tms.orig.TraceState = *internal.GenTestTraceState()\n\tassert.Equal(t, pcommon.TraceState(internal.GenTestTraceStateWrapper()), ms.TraceState())\n}\n\nfunc TestSpan_ParentSpanID(t *testing.T) {\n\tms := NewSpan()\n\tassert.Equal(t, pcommon.SpanID(internal.SpanID([8]byte{})), ms.ParentSpanID())\n\ttestValParentSpanID := pcommon.SpanID(internal.SpanID([8]byte{8, 7, 6, 5, 4, 3, 2, 1}))\n\tms.SetParentSpanID(testValParentSpanID)\n\tassert.Equal(t, testValParentSpanID, ms.ParentSpanID())\n}\n\nfunc TestSpan_Flags(t *testing.T) {\n\tms := NewSpan()\n\tassert.Equal(t, uint32(0), ms.Flags())\n\tms.SetFlags(uint32(13))\n\tassert.Equal(t, uint32(13), ms.Flags())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newSpan(internal.NewSpan(), sharedState).SetFlags(uint32(13)) })\n}\n\nfunc TestSpan_Name(t *testing.T) {\n\tms := NewSpan()\n\tassert.Empty(t, ms.Name())\n\tms.SetName(\"test_name\")\n\tassert.Equal(t, \"test_name\", ms.Name())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newSpan(internal.NewSpan(), sharedState).SetName(\"test_name\") })\n}\n\nfunc TestSpan_Kind(t *testing.T) {\n\tms := NewSpan()\n\tassert.Equal(t, SpanKind(internal.SpanKind_SPAN_KIND_UNSPECIFIED), ms.Kind())\n\ttestValKind := SpanKind(internal.SpanKind_SPAN_KIND_CLIENT)\n\tms.SetKind(testValKind)\n\tassert.Equal(t, testValKind, ms.Kind())\n}\n\nfunc TestSpan_StartTimestamp(t *testing.T) {\n\tms := NewSpan()\n\tassert.Equal(t, pcommon.Timestamp(0), ms.StartTimestamp())\n\ttestValStartTimestamp := pcommon.Timestamp(1234567890)\n\tms.SetStartTimestamp(testValStartTimestamp)\n\tassert.Equal(t, testValStartTimestamp, ms.StartTimestamp())\n}\n\nfunc TestSpan_EndTimestamp(t *testing.T) {\n\tms := NewSpan()\n\tassert.Equal(t, pcommon.Timestamp(0), ms.EndTimestamp())\n\ttestValEndTimestamp := pcommon.Timestamp(1234567890)\n\tms.SetEndTimestamp(testValEndTimestamp)\n\tassert.Equal(t, testValEndTimestamp, ms.EndTimestamp())\n}\n\nfunc TestSpan_Attributes(t *testing.T) {\n\tms := NewSpan()\n\tassert.Equal(t, pcommon.NewMap(), ms.Attributes())\n\tms.orig.Attributes = internal.GenTestKeyValueSlice()\n\tassert.Equal(t, pcommon.Map(internal.GenTestMapWrapper()), ms.Attributes())\n}\n\nfunc TestSpan_DroppedAttributesCount(t *testing.T) {\n\tms := NewSpan()\n\tassert.Equal(t, uint32(0), ms.DroppedAttributesCount())\n\tms.SetDroppedAttributesCount(uint32(13))\n\tassert.Equal(t, uint32(13), ms.DroppedAttributesCount())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newSpan(internal.NewSpan(), sharedState).SetDroppedAttributesCount(uint32(13)) })\n}\n\nfunc TestSpan_Events(t *testing.T) {\n\tms := NewSpan()\n\tassert.Equal(t, NewSpanEventSlice(), ms.Events())\n\tms.orig.Events = internal.GenTestSpanEventPtrSlice()\n\tassert.Equal(t, generateTestSpanEventSlice(), ms.Events())\n}\n\nfunc TestSpan_DroppedEventsCount(t *testing.T) {\n\tms := NewSpan()\n\tassert.Equal(t, uint32(0), ms.DroppedEventsCount())\n\tms.SetDroppedEventsCount(uint32(13))\n\tassert.Equal(t, uint32(13), ms.DroppedEventsCount())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newSpan(internal.NewSpan(), sharedState).SetDroppedEventsCount(uint32(13)) })\n}\n\nfunc TestSpan_Links(t *testing.T) {\n\tms := NewSpan()\n\tassert.Equal(t, NewSpanLinkSlice(), ms.Links())\n\tms.orig.Links = internal.GenTestSpanLinkPtrSlice()\n\tassert.Equal(t, generateTestSpanLinkSlice(), ms.Links())\n}\n\nfunc TestSpan_DroppedLinksCount(t *testing.T) {\n\tms := NewSpan()\n\tassert.Equal(t, uint32(0), ms.DroppedLinksCount())\n\tms.SetDroppedLinksCount(uint32(13))\n\tassert.Equal(t, uint32(13), ms.DroppedLinksCount())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newSpan(internal.NewSpan(), sharedState).SetDroppedLinksCount(uint32(13)) })\n}\n\nfunc TestSpan_Status(t *testing.T) {\n\tms := NewSpan()\n\tassert.Equal(t, NewStatus(), ms.Status())\n\tms.orig.Status = *internal.GenTestStatus()\n\tassert.Equal(t, generateTestStatus(), ms.Status())\n}\n\nfunc generateTestSpan() Span {\n\treturn newSpan(internal.GenTestSpan(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_spanevent.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// SpanEvent is a time-stamped annotation of the span, consisting of user-supplied\n// text description and key-value pairs. See OTLP for event definition.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewSpanEvent function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype SpanEvent struct {\n\torig  *internal.SpanEvent\n\tstate *internal.State\n}\n\nfunc newSpanEvent(orig *internal.SpanEvent, state *internal.State) SpanEvent {\n\treturn SpanEvent{orig: orig, state: state}\n}\n\n// NewSpanEvent creates a new empty SpanEvent.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewSpanEvent() SpanEvent {\n\treturn newSpanEvent(internal.NewSpanEvent(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms SpanEvent) MoveTo(dest SpanEvent) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteSpanEvent(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Timestamp returns the timestamp associated with this SpanEvent.\nfunc (ms SpanEvent) Timestamp() pcommon.Timestamp {\n\treturn pcommon.Timestamp(ms.orig.TimeUnixNano)\n}\n\n// SetTimestamp replaces the timestamp associated with this SpanEvent.\nfunc (ms SpanEvent) SetTimestamp(v pcommon.Timestamp) {\n\tms.state.AssertMutable()\n\tms.orig.TimeUnixNano = uint64(v)\n}\n\n// Name returns the name associated with this SpanEvent.\nfunc (ms SpanEvent) Name() string {\n\treturn ms.orig.Name\n}\n\n// SetName replaces the name associated with this SpanEvent.\nfunc (ms SpanEvent) SetName(v string) {\n\tms.state.AssertMutable()\n\tms.orig.Name = v\n}\n\n// Attributes returns the Attributes associated with this SpanEvent.\nfunc (ms SpanEvent) Attributes() pcommon.Map {\n\treturn pcommon.Map(internal.NewMapWrapper(&ms.orig.Attributes, ms.state))\n}\n\n// DroppedAttributesCount returns the droppedattributescount associated with this SpanEvent.\nfunc (ms SpanEvent) DroppedAttributesCount() uint32 {\n\treturn ms.orig.DroppedAttributesCount\n}\n\n// SetDroppedAttributesCount replaces the droppedattributescount associated with this SpanEvent.\nfunc (ms SpanEvent) SetDroppedAttributesCount(v uint32) {\n\tms.state.AssertMutable()\n\tms.orig.DroppedAttributesCount = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms SpanEvent) CopyTo(dest SpanEvent) {\n\tdest.state.AssertMutable()\n\tinternal.CopySpanEvent(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_spanevent_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestSpanEvent_MoveTo(t *testing.T) {\n\tms := generateTestSpanEvent()\n\tdest := NewSpanEvent()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewSpanEvent(), ms)\n\tassert.Equal(t, generateTestSpanEvent(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestSpanEvent(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newSpanEvent(internal.NewSpanEvent(), sharedState)) })\n\tassert.Panics(t, func() { newSpanEvent(internal.NewSpanEvent(), sharedState).MoveTo(dest) })\n}\n\nfunc TestSpanEvent_CopyTo(t *testing.T) {\n\tms := NewSpanEvent()\n\torig := NewSpanEvent()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestSpanEvent()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newSpanEvent(internal.NewSpanEvent(), sharedState)) })\n}\n\nfunc TestSpanEvent_Timestamp(t *testing.T) {\n\tms := NewSpanEvent()\n\tassert.Equal(t, pcommon.Timestamp(0), ms.Timestamp())\n\ttestValTimestamp := pcommon.Timestamp(1234567890)\n\tms.SetTimestamp(testValTimestamp)\n\tassert.Equal(t, testValTimestamp, ms.Timestamp())\n}\n\nfunc TestSpanEvent_Name(t *testing.T) {\n\tms := NewSpanEvent()\n\tassert.Empty(t, ms.Name())\n\tms.SetName(\"test_name\")\n\tassert.Equal(t, \"test_name\", ms.Name())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newSpanEvent(internal.NewSpanEvent(), sharedState).SetName(\"test_name\") })\n}\n\nfunc TestSpanEvent_Attributes(t *testing.T) {\n\tms := NewSpanEvent()\n\tassert.Equal(t, pcommon.NewMap(), ms.Attributes())\n\tms.orig.Attributes = internal.GenTestKeyValueSlice()\n\tassert.Equal(t, pcommon.Map(internal.GenTestMapWrapper()), ms.Attributes())\n}\n\nfunc TestSpanEvent_DroppedAttributesCount(t *testing.T) {\n\tms := NewSpanEvent()\n\tassert.Equal(t, uint32(0), ms.DroppedAttributesCount())\n\tms.SetDroppedAttributesCount(uint32(13))\n\tassert.Equal(t, uint32(13), ms.DroppedAttributesCount())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newSpanEvent(internal.NewSpanEvent(), sharedState).SetDroppedAttributesCount(uint32(13)) })\n}\n\nfunc generateTestSpanEvent() SpanEvent {\n\treturn newSpanEvent(internal.GenTestSpanEvent(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_spaneventslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// SpanEventSlice logically represents a slice of SpanEvent.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewSpanEventSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype SpanEventSlice struct {\n\torig  *[]*internal.SpanEvent\n\tstate *internal.State\n}\n\nfunc newSpanEventSlice(orig *[]*internal.SpanEvent, state *internal.State) SpanEventSlice {\n\treturn SpanEventSlice{orig: orig, state: state}\n}\n\n// NewSpanEventSlice creates a SpanEventSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewSpanEventSlice() SpanEventSlice {\n\torig := []*internal.SpanEvent(nil)\n\treturn newSpanEventSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewSpanEventSlice()\".\nfunc (es SpanEventSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es SpanEventSlice) At(i int) SpanEvent {\n\treturn newSpanEvent((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es SpanEventSlice) All() iter.Seq2[int, SpanEvent] {\n\treturn func(yield func(int, SpanEvent) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new SpanEventSlice can be initialized:\n//\n//\tes := NewSpanEventSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es SpanEventSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.SpanEvent, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty SpanEvent.\n// It returns the newly added SpanEvent.\nfunc (es SpanEventSlice) AppendEmpty() SpanEvent {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewSpanEvent())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es SpanEventSlice) MoveAndAppendTo(dest SpanEventSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es SpanEventSlice) RemoveIf(f func(SpanEvent) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteSpanEvent((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es SpanEventSlice) CopyTo(dest SpanEventSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopySpanEventPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the SpanEvent elements within SpanEventSlice given the\n// provided less function so that two instances of SpanEventSlice\n// can be compared.\nfunc (es SpanEventSlice) Sort(less func(a, b SpanEvent) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_spaneventslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestSpanEventSlice(t *testing.T) {\n\tes := NewSpanEventSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newSpanEventSlice(&[]*internal.SpanEvent{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewSpanEvent()\n\ttestVal := generateTestSpanEvent()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestSpanEvent()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestSpanEventSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newSpanEventSlice(&[]*internal.SpanEvent{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewSpanEventSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestSpanEventSlice_CopyTo(t *testing.T) {\n\tdest := NewSpanEventSlice()\n\tsrc := generateTestSpanEventSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestSpanEventSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestSpanEventSlice(), dest)\n}\n\nfunc TestSpanEventSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestSpanEventSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestSpanEventSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestSpanEventSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestSpanEventSlice(), es)\n}\n\nfunc TestSpanEventSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestSpanEventSlice()\n\tdest := NewSpanEventSlice()\n\tsrc := generateTestSpanEventSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestSpanEventSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestSpanEventSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestSpanEventSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestSpanEventSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewSpanEventSlice()\n\temptySlice.RemoveIf(func(el SpanEvent) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestSpanEventSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el SpanEvent) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestSpanEventSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestSpanEventSlice()\n\tgot.RemoveIf(func(el SpanEvent) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestSpanEventSliceAll(t *testing.T) {\n\tms := generateTestSpanEventSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestSpanEventSlice_Sort(t *testing.T) {\n\tes := generateTestSpanEventSlice()\n\tes.Sort(func(a, b SpanEvent) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b SpanEvent) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestSpanEventSlice() SpanEventSlice {\n\tms := NewSpanEventSlice()\n\t*ms.orig = internal.GenTestSpanEventPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_spanlink.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// SpanLink is a pointer from the current span to another span in the same trace or in a\n// different trace.\n// See Link definition in OTLP: https://github.com/open-telemetry/opentelemetry-proto/blob/main/opentelemetry/proto/trace/v1/trace.proto\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewSpanLink function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype SpanLink struct {\n\torig  *internal.SpanLink\n\tstate *internal.State\n}\n\nfunc newSpanLink(orig *internal.SpanLink, state *internal.State) SpanLink {\n\treturn SpanLink{orig: orig, state: state}\n}\n\n// NewSpanLink creates a new empty SpanLink.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewSpanLink() SpanLink {\n\treturn newSpanLink(internal.NewSpanLink(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms SpanLink) MoveTo(dest SpanLink) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteSpanLink(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// TraceID returns the traceid associated with this SpanLink.\nfunc (ms SpanLink) TraceID() pcommon.TraceID {\n\treturn pcommon.TraceID(ms.orig.TraceId)\n}\n\n// SetTraceID replaces the traceid associated with this SpanLink.\nfunc (ms SpanLink) SetTraceID(v pcommon.TraceID) {\n\tms.state.AssertMutable()\n\tms.orig.TraceId = internal.TraceID(v)\n}\n\n// SpanID returns the spanid associated with this SpanLink.\nfunc (ms SpanLink) SpanID() pcommon.SpanID {\n\treturn pcommon.SpanID(ms.orig.SpanId)\n}\n\n// SetSpanID replaces the spanid associated with this SpanLink.\nfunc (ms SpanLink) SetSpanID(v pcommon.SpanID) {\n\tms.state.AssertMutable()\n\tms.orig.SpanId = internal.SpanID(v)\n}\n\n// TraceState returns the tracestate associated with this SpanLink.\nfunc (ms SpanLink) TraceState() pcommon.TraceState {\n\treturn pcommon.TraceState(internal.NewTraceStateWrapper(&ms.orig.TraceState, ms.state))\n}\n\n// Attributes returns the Attributes associated with this SpanLink.\nfunc (ms SpanLink) Attributes() pcommon.Map {\n\treturn pcommon.Map(internal.NewMapWrapper(&ms.orig.Attributes, ms.state))\n}\n\n// DroppedAttributesCount returns the droppedattributescount associated with this SpanLink.\nfunc (ms SpanLink) DroppedAttributesCount() uint32 {\n\treturn ms.orig.DroppedAttributesCount\n}\n\n// SetDroppedAttributesCount replaces the droppedattributescount associated with this SpanLink.\nfunc (ms SpanLink) SetDroppedAttributesCount(v uint32) {\n\tms.state.AssertMutable()\n\tms.orig.DroppedAttributesCount = v\n}\n\n// Flags returns the flags associated with this SpanLink.\nfunc (ms SpanLink) Flags() uint32 {\n\treturn ms.orig.Flags\n}\n\n// SetFlags replaces the flags associated with this SpanLink.\nfunc (ms SpanLink) SetFlags(v uint32) {\n\tms.state.AssertMutable()\n\tms.orig.Flags = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms SpanLink) CopyTo(dest SpanLink) {\n\tdest.state.AssertMutable()\n\tinternal.CopySpanLink(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_spanlink_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestSpanLink_MoveTo(t *testing.T) {\n\tms := generateTestSpanLink()\n\tdest := NewSpanLink()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewSpanLink(), ms)\n\tassert.Equal(t, generateTestSpanLink(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestSpanLink(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newSpanLink(internal.NewSpanLink(), sharedState)) })\n\tassert.Panics(t, func() { newSpanLink(internal.NewSpanLink(), sharedState).MoveTo(dest) })\n}\n\nfunc TestSpanLink_CopyTo(t *testing.T) {\n\tms := NewSpanLink()\n\torig := NewSpanLink()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestSpanLink()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newSpanLink(internal.NewSpanLink(), sharedState)) })\n}\n\nfunc TestSpanLink_TraceID(t *testing.T) {\n\tms := NewSpanLink()\n\tassert.Equal(t, pcommon.TraceID(internal.TraceID([16]byte{})), ms.TraceID())\n\ttestValTraceID := pcommon.TraceID(internal.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 8, 7, 6, 5, 4, 3, 2, 1}))\n\tms.SetTraceID(testValTraceID)\n\tassert.Equal(t, testValTraceID, ms.TraceID())\n}\n\nfunc TestSpanLink_SpanID(t *testing.T) {\n\tms := NewSpanLink()\n\tassert.Equal(t, pcommon.SpanID(internal.SpanID([8]byte{})), ms.SpanID())\n\ttestValSpanID := pcommon.SpanID(internal.SpanID([8]byte{8, 7, 6, 5, 4, 3, 2, 1}))\n\tms.SetSpanID(testValSpanID)\n\tassert.Equal(t, testValSpanID, ms.SpanID())\n}\n\nfunc TestSpanLink_TraceState(t *testing.T) {\n\tms := NewSpanLink()\n\tassert.Equal(t, pcommon.NewTraceState(), ms.TraceState())\n\tms.orig.TraceState = *internal.GenTestTraceState()\n\tassert.Equal(t, pcommon.TraceState(internal.GenTestTraceStateWrapper()), ms.TraceState())\n}\n\nfunc TestSpanLink_Attributes(t *testing.T) {\n\tms := NewSpanLink()\n\tassert.Equal(t, pcommon.NewMap(), ms.Attributes())\n\tms.orig.Attributes = internal.GenTestKeyValueSlice()\n\tassert.Equal(t, pcommon.Map(internal.GenTestMapWrapper()), ms.Attributes())\n}\n\nfunc TestSpanLink_DroppedAttributesCount(t *testing.T) {\n\tms := NewSpanLink()\n\tassert.Equal(t, uint32(0), ms.DroppedAttributesCount())\n\tms.SetDroppedAttributesCount(uint32(13))\n\tassert.Equal(t, uint32(13), ms.DroppedAttributesCount())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newSpanLink(internal.NewSpanLink(), sharedState).SetDroppedAttributesCount(uint32(13)) })\n}\n\nfunc TestSpanLink_Flags(t *testing.T) {\n\tms := NewSpanLink()\n\tassert.Equal(t, uint32(0), ms.Flags())\n\tms.SetFlags(uint32(13))\n\tassert.Equal(t, uint32(13), ms.Flags())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newSpanLink(internal.NewSpanLink(), sharedState).SetFlags(uint32(13)) })\n}\n\nfunc generateTestSpanLink() SpanLink {\n\treturn newSpanLink(internal.GenTestSpanLink(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_spanlinkslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// SpanLinkSlice logically represents a slice of SpanLink.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewSpanLinkSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype SpanLinkSlice struct {\n\torig  *[]*internal.SpanLink\n\tstate *internal.State\n}\n\nfunc newSpanLinkSlice(orig *[]*internal.SpanLink, state *internal.State) SpanLinkSlice {\n\treturn SpanLinkSlice{orig: orig, state: state}\n}\n\n// NewSpanLinkSlice creates a SpanLinkSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewSpanLinkSlice() SpanLinkSlice {\n\torig := []*internal.SpanLink(nil)\n\treturn newSpanLinkSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewSpanLinkSlice()\".\nfunc (es SpanLinkSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es SpanLinkSlice) At(i int) SpanLink {\n\treturn newSpanLink((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es SpanLinkSlice) All() iter.Seq2[int, SpanLink] {\n\treturn func(yield func(int, SpanLink) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new SpanLinkSlice can be initialized:\n//\n//\tes := NewSpanLinkSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es SpanLinkSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.SpanLink, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty SpanLink.\n// It returns the newly added SpanLink.\nfunc (es SpanLinkSlice) AppendEmpty() SpanLink {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewSpanLink())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es SpanLinkSlice) MoveAndAppendTo(dest SpanLinkSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es SpanLinkSlice) RemoveIf(f func(SpanLink) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteSpanLink((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es SpanLinkSlice) CopyTo(dest SpanLinkSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopySpanLinkPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the SpanLink elements within SpanLinkSlice given the\n// provided less function so that two instances of SpanLinkSlice\n// can be compared.\nfunc (es SpanLinkSlice) Sort(less func(a, b SpanLink) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_spanlinkslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestSpanLinkSlice(t *testing.T) {\n\tes := NewSpanLinkSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newSpanLinkSlice(&[]*internal.SpanLink{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewSpanLink()\n\ttestVal := generateTestSpanLink()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestSpanLink()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestSpanLinkSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newSpanLinkSlice(&[]*internal.SpanLink{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewSpanLinkSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestSpanLinkSlice_CopyTo(t *testing.T) {\n\tdest := NewSpanLinkSlice()\n\tsrc := generateTestSpanLinkSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestSpanLinkSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestSpanLinkSlice(), dest)\n}\n\nfunc TestSpanLinkSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestSpanLinkSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestSpanLinkSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestSpanLinkSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestSpanLinkSlice(), es)\n}\n\nfunc TestSpanLinkSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestSpanLinkSlice()\n\tdest := NewSpanLinkSlice()\n\tsrc := generateTestSpanLinkSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestSpanLinkSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestSpanLinkSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestSpanLinkSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestSpanLinkSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewSpanLinkSlice()\n\temptySlice.RemoveIf(func(el SpanLink) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestSpanLinkSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el SpanLink) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestSpanLinkSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestSpanLinkSlice()\n\tgot.RemoveIf(func(el SpanLink) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestSpanLinkSliceAll(t *testing.T) {\n\tms := generateTestSpanLinkSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestSpanLinkSlice_Sort(t *testing.T) {\n\tes := generateTestSpanLinkSlice()\n\tes.Sort(func(a, b SpanLink) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b SpanLink) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestSpanLinkSlice() SpanLinkSlice {\n\tms := NewSpanLinkSlice()\n\t*ms.orig = internal.GenTestSpanLinkPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_spanslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// SpanSlice logically represents a slice of Span.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewSpanSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype SpanSlice struct {\n\torig  *[]*internal.Span\n\tstate *internal.State\n}\n\nfunc newSpanSlice(orig *[]*internal.Span, state *internal.State) SpanSlice {\n\treturn SpanSlice{orig: orig, state: state}\n}\n\n// NewSpanSlice creates a SpanSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewSpanSlice() SpanSlice {\n\torig := []*internal.Span(nil)\n\treturn newSpanSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewSpanSlice()\".\nfunc (es SpanSlice) Len() int {\n\treturn len(*es.orig)\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es SpanSlice) At(i int) Span {\n\treturn newSpan((*es.orig)[i], es.state)\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es SpanSlice) All() iter.Seq2[int, Span] {\n\treturn func(yield func(int, Span) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new SpanSlice can be initialized:\n//\n//\tes := NewSpanSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es SpanSlice) EnsureCapacity(newCap int) {\n\tes.state.AssertMutable()\n\toldCap := cap(*es.orig)\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.Span, len(*es.orig), newCap)\n\tcopy(newOrig, *es.orig)\n\t*es.orig = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty Span.\n// It returns the newly added Span.\nfunc (es SpanSlice) AppendEmpty() Span {\n\tes.state.AssertMutable()\n\t*es.orig = append(*es.orig, internal.NewSpan())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es SpanSlice) MoveAndAppendTo(dest SpanSlice) {\n\tes.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\tif *dest.orig == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.orig = *es.orig\n\t} else {\n\t\t*dest.orig = append(*dest.orig, *es.orig...)\n\t}\n\t*es.orig = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es SpanSlice) RemoveIf(f func(Span) bool) {\n\tes.state.AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.orig); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteSpan((*es.orig)[i], true)\n\t\t\t(*es.orig)[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.orig)[newLen] = (*es.orig)[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.orig)[i] = nil\n\t\tnewLen++\n\t}\n\t*es.orig = (*es.orig)[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es SpanSlice) CopyTo(dest SpanSlice) {\n\tdest.state.AssertMutable()\n\tif es.orig == dest.orig {\n\t\treturn\n\t}\n\t*dest.orig = internal.CopySpanPtrSlice(*dest.orig, *es.orig)\n}\n\n// Sort sorts the Span elements within SpanSlice given the\n// provided less function so that two instances of SpanSlice\n// can be compared.\nfunc (es SpanSlice) Sort(less func(a, b Span) bool) {\n\tes.state.AssertMutable()\n\tsort.SliceStable(*es.orig, func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_spanslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestSpanSlice(t *testing.T) {\n\tes := NewSpanSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newSpanSlice(&[]*internal.Span{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewSpan()\n\ttestVal := generateTestSpan()\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.orig)[i] = internal.GenTestSpan()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestSpanSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newSpanSlice(&[]*internal.Span{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewSpanSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestSpanSlice_CopyTo(t *testing.T) {\n\tdest := NewSpanSlice()\n\tsrc := generateTestSpanSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestSpanSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestSpanSlice(), dest)\n}\n\nfunc TestSpanSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestSpanSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.orig))\n\tassert.Equal(t, generateTestSpanSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestSpanSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.orig))\n\tassert.Equal(t, generateTestSpanSlice(), es)\n}\n\nfunc TestSpanSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestSpanSlice()\n\tdest := NewSpanSlice()\n\tsrc := generateTestSpanSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestSpanSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestSpanSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestSpanSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestSpanSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewSpanSlice()\n\temptySlice.RemoveIf(func(el Span) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestSpanSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el Span) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestSpanSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestSpanSlice()\n\tgot.RemoveIf(func(el Span) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestSpanSliceAll(t *testing.T) {\n\tms := generateTestSpanSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestSpanSlice_Sort(t *testing.T) {\n\tes := generateTestSpanSlice()\n\tes.Sort(func(a, b Span) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) < uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n\tes.Sort(func(a, b Span) bool {\n\t\treturn uintptr(unsafe.Pointer(a.orig)) > uintptr(unsafe.Pointer(b.orig))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).orig)), uintptr(unsafe.Pointer(es.At(i).orig)))\n\t}\n}\n\nfunc generateTestSpanSlice() SpanSlice {\n\tms := NewSpanSlice()\n\t*ms.orig = internal.GenTestSpanPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_status.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// Status is an optional final status for this span. Semantically, when Status was not\n// set, that means the span ended without errors and to assume Status.Ok (code = 0).\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewStatus function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Status struct {\n\torig  *internal.Status\n\tstate *internal.State\n}\n\nfunc newStatus(orig *internal.Status, state *internal.State) Status {\n\treturn Status{orig: orig, state: state}\n}\n\n// NewStatus creates a new empty Status.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewStatus() Status {\n\treturn newStatus(internal.NewStatus(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Status) MoveTo(dest Status) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteStatus(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// Message returns the message associated with this Status.\nfunc (ms Status) Message() string {\n\treturn ms.orig.Message\n}\n\n// SetMessage replaces the message associated with this Status.\nfunc (ms Status) SetMessage(v string) {\n\tms.state.AssertMutable()\n\tms.orig.Message = v\n}\n\n// Code returns the code associated with this Status.\nfunc (ms Status) Code() StatusCode {\n\treturn StatusCode(ms.orig.Code)\n}\n\n// SetCode replaces the code associated with this Status.\nfunc (ms Status) SetCode(v StatusCode) {\n\tms.state.AssertMutable()\n\tms.orig.Code = internal.StatusCode(v)\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Status) CopyTo(dest Status) {\n\tdest.state.AssertMutable()\n\tinternal.CopyStatus(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_status_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestStatus_MoveTo(t *testing.T) {\n\tms := generateTestStatus()\n\tdest := NewStatus()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewStatus(), ms)\n\tassert.Equal(t, generateTestStatus(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestStatus(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newStatus(internal.NewStatus(), sharedState)) })\n\tassert.Panics(t, func() { newStatus(internal.NewStatus(), sharedState).MoveTo(dest) })\n}\n\nfunc TestStatus_CopyTo(t *testing.T) {\n\tms := NewStatus()\n\torig := NewStatus()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestStatus()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newStatus(internal.NewStatus(), sharedState)) })\n}\n\nfunc TestStatus_Message(t *testing.T) {\n\tms := NewStatus()\n\tassert.Empty(t, ms.Message())\n\tms.SetMessage(\"test_message\")\n\tassert.Equal(t, \"test_message\", ms.Message())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newStatus(internal.NewStatus(), sharedState).SetMessage(\"test_message\") })\n}\n\nfunc TestStatus_Code(t *testing.T) {\n\tms := NewStatus()\n\tassert.Equal(t, StatusCode(internal.StatusCode_STATUS_CODE_UNSET), ms.Code())\n\ttestValCode := StatusCode(internal.StatusCode_STATUS_CODE_OK)\n\tms.SetCode(testValCode)\n\tassert.Equal(t, testValCode, ms.Code())\n}\n\nfunc generateTestStatus() Status {\n\treturn newStatus(internal.GenTestStatus(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_traces.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// Traces is the top-level struct that is propagated through the traces pipeline.\n// Use NewTraces to create new instance, zero-initialized instance is not valid for use.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewTraces function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype Traces internal.TracesWrapper\n\nfunc newTraces(orig *internal.ExportTraceServiceRequest, state *internal.State) Traces {\n\treturn Traces(internal.NewTracesWrapper(orig, state))\n}\n\n// NewTraces creates a new empty Traces.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewTraces() Traces {\n\treturn newTraces(internal.NewExportTraceServiceRequest(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms Traces) MoveTo(dest Traces) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\tinternal.DeleteExportTraceServiceRequest(dest.getOrig(), false)\n\t*dest.getOrig(), *ms.getOrig() = *ms.getOrig(), *dest.getOrig()\n}\n\n// ResourceSpans returns the ResourceSpans associated with this Traces.\nfunc (ms Traces) ResourceSpans() ResourceSpansSlice {\n\treturn newResourceSpansSlice(&ms.getOrig().ResourceSpans, ms.getState())\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms Traces) CopyTo(dest Traces) {\n\tdest.getState().AssertMutable()\n\tinternal.CopyExportTraceServiceRequest(dest.getOrig(), ms.getOrig())\n}\n\nfunc (ms Traces) getOrig() *internal.ExportTraceServiceRequest {\n\treturn internal.GetTracesOrig(internal.TracesWrapper(ms))\n}\n\nfunc (ms Traces) getState() *internal.State {\n\treturn internal.GetTracesState(internal.TracesWrapper(ms))\n}\n"
  },
  {
    "path": "pdata/ptrace/generated_traces_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptrace\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestTraces_MoveTo(t *testing.T) {\n\tms := generateTestTraces()\n\tdest := NewTraces()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewTraces(), ms)\n\tassert.Equal(t, generateTestTraces(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestTraces(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newTraces(internal.NewExportTraceServiceRequest(), sharedState)) })\n\tassert.Panics(t, func() { newTraces(internal.NewExportTraceServiceRequest(), sharedState).MoveTo(dest) })\n}\n\nfunc TestTraces_CopyTo(t *testing.T) {\n\tms := NewTraces()\n\torig := NewTraces()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestTraces()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newTraces(internal.NewExportTraceServiceRequest(), sharedState)) })\n}\n\nfunc TestTraces_ResourceSpans(t *testing.T) {\n\tms := NewTraces()\n\tassert.Equal(t, NewResourceSpansSlice(), ms.ResourceSpans())\n\tms.getOrig().ResourceSpans = internal.GenTestResourceSpansPtrSlice()\n\tassert.Equal(t, generateTestResourceSpansSlice(), ms.ResourceSpans())\n}\n\nfunc generateTestTraces() Traces {\n\treturn newTraces(internal.GenTestExportTraceServiceRequest(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/ptrace/json.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptrace // import \"go.opentelemetry.io/collector/pdata/ptrace\"\n\nimport (\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otlp\"\n)\n\n// JSONMarshaler marshals Traces to JSON bytes using the OTLP/JSON format.\ntype JSONMarshaler struct{}\n\n// MarshalTraces to the OTLP/JSON format.\nfunc (*JSONMarshaler) MarshalTraces(td Traces) ([]byte, error) {\n\tdest := json.BorrowStream(nil)\n\tdefer json.ReturnStream(dest)\n\ttd.getOrig().MarshalJSON(dest)\n\tif dest.Error() != nil {\n\t\treturn nil, dest.Error()\n\t}\n\treturn slices.Clone(dest.Buffer()), nil\n}\n\n// JSONUnmarshaler unmarshals OTLP/JSON formatted-bytes to Traces.\ntype JSONUnmarshaler struct{}\n\n// UnmarshalTraces from OTLP/JSON format into Traces.\nfunc (*JSONUnmarshaler) UnmarshalTraces(buf []byte) (Traces, error) {\n\titer := json.BorrowIterator(buf)\n\tdefer json.ReturnIterator(iter)\n\ttd := NewTraces()\n\ttd.getOrig().UnmarshalJSON(iter)\n\tif iter.Error() != nil {\n\t\treturn Traces{}, iter.Error()\n\t}\n\totlp.MigrateTraces(td.getOrig().ResourceSpans)\n\treturn td, nil\n}\n"
  },
  {
    "path": "pdata/ptrace/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptrace\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "pdata/ptrace/pb.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptrace // import \"go.opentelemetry.io/collector/pdata/ptrace\"\n\nvar _ MarshalSizer = (*ProtoMarshaler)(nil)\n\ntype ProtoMarshaler struct{}\n\nfunc (e *ProtoMarshaler) MarshalTraces(td Traces) ([]byte, error) {\n\tsize := td.getOrig().SizeProto()\n\tbuf := make([]byte, size)\n\t_ = td.getOrig().MarshalProto(buf)\n\treturn buf, nil\n}\n\nfunc (e *ProtoMarshaler) TracesSize(td Traces) int {\n\treturn td.getOrig().SizeProto()\n}\n\nfunc (e *ProtoMarshaler) ResourceSpansSize(td ResourceSpans) int {\n\treturn td.orig.SizeProto()\n}\n\nfunc (e *ProtoMarshaler) ScopeSpansSize(td ScopeSpans) int {\n\treturn td.orig.SizeProto()\n}\n\nfunc (e *ProtoMarshaler) SpanSize(td Span) int {\n\treturn td.orig.SizeProto()\n}\n\ntype ProtoUnmarshaler struct{}\n\nfunc (d *ProtoUnmarshaler) UnmarshalTraces(buf []byte) (Traces, error) {\n\ttd := NewTraces()\n\terr := td.getOrig().UnmarshalProto(buf)\n\tif err != nil {\n\t\treturn Traces{}, err\n\t}\n\treturn td, nil\n}\n"
  },
  {
    "path": "pdata/ptrace/pb_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptrace\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlptrace \"go.opentelemetry.io/proto/slim/otlp/trace/v1\"\n\tgoproto \"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestTracesProtoWireCompatibility(t *testing.T) {\n\t// This test verifies that OTLP ProtoBufs generated using goproto lib in\n\t// opentelemetry-proto repository OTLP ProtoBufs generated using gogoproto lib in\n\t// this repository are wire compatible.\n\n\t// Generate Traces as pdata struct.\n\ttd := generateTestTraces()\n\n\t// Marshal its underlying ProtoBuf to wire.\n\tmarshaler := &ProtoMarshaler{}\n\twire1, err := marshaler.MarshalTraces(td)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, wire1)\n\n\t// Unmarshal from the wire to OTLP Protobuf in goproto's representation.\n\tvar goprotoMessage gootlptrace.TracesData\n\terr = goproto.Unmarshal(wire1, &goprotoMessage)\n\trequire.NoError(t, err)\n\n\t// Marshal to the wire again.\n\twire2, err := goproto.Marshal(&goprotoMessage)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, wire2)\n\n\t// Unmarshal from the wire into gogoproto's representation.\n\tvar td2 Traces\n\tunmarshaler := &ProtoUnmarshaler{}\n\ttd2, err = unmarshaler.UnmarshalTraces(wire2)\n\trequire.NoError(t, err)\n\n\t// Now compare that the original and final ProtoBuf messages are the same.\n\t// This proves that goproto and gogoproto marshaling/unmarshaling are wire compatible.\n\tassert.Equal(t, td, td2)\n}\n\nfunc TestProtoTracesUnmarshalerError(t *testing.T) {\n\tp := &ProtoUnmarshaler{}\n\t_, err := p.UnmarshalTraces([]byte(\"+$%\"))\n\tassert.Error(t, err)\n}\n\nfunc TestProtoSizer(t *testing.T) {\n\tmarshaler := &ProtoMarshaler{}\n\ttd := NewTraces()\n\trms := td.ResourceSpans()\n\trms.AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty().SetName(\"foo\")\n\n\tsize := marshaler.TracesSize(td)\n\n\tbytes, err := marshaler.MarshalTraces(td)\n\trequire.NoError(t, err)\n\tassert.Equal(t, len(bytes), size)\n}\n\nfunc TestProtoSizerEmptyTraces(t *testing.T) {\n\tsizer := &ProtoMarshaler{}\n\tassert.Equal(t, 0, sizer.TracesSize(NewTraces()))\n}\n\nfunc BenchmarkTracesToProto2k(b *testing.B) {\n\tmarshaler := &ProtoMarshaler{}\n\ttraces := generateBenchmarkTraces(2_000)\n\n\tfor b.Loop() {\n\t\tbuf, err := marshaler.MarshalTraces(traces)\n\t\trequire.NoError(b, err)\n\t\tassert.NotEmpty(b, buf)\n\t}\n}\n\nfunc BenchmarkTracesFromProto2k(b *testing.B) {\n\tmarshaler := &ProtoMarshaler{}\n\tunmarshaler := &ProtoUnmarshaler{}\n\tbaseTraces := generateBenchmarkTraces(2_000)\n\tbuf, err := marshaler.MarshalTraces(baseTraces)\n\trequire.NoError(b, err)\n\tassert.NotEmpty(b, buf)\n\n\tb.ReportAllocs()\n\tfor b.Loop() {\n\t\ttraces, err := unmarshaler.UnmarshalTraces(buf)\n\t\trequire.NoError(b, err)\n\t\tassert.Equal(b, baseTraces.ResourceSpans().Len(), traces.ResourceSpans().Len())\n\t}\n}\n\nfunc generateBenchmarkTraces(metricsCount int) Traces {\n\tnow := time.Now()\n\tstartTime := pcommon.NewTimestampFromTime(now.Add(-10 * time.Second))\n\tendTime := pcommon.NewTimestampFromTime(now)\n\n\tmd := NewTraces()\n\tilm := md.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty()\n\tilm.Spans().EnsureCapacity(metricsCount)\n\tfor range metricsCount {\n\t\tim := ilm.Spans().AppendEmpty()\n\t\tim.SetName(\"test_name\")\n\t\tim.SetStartTimestamp(startTime)\n\t\tim.SetEndTimestamp(endTime)\n\t}\n\treturn md\n}\n"
  },
  {
    "path": "pdata/ptrace/ptraceotlp/fuzz_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptraceotlp // import \"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar unexpectedBytes = \"expected the same bytes from unmarshaling and marshaling.\"\n\nfunc FuzzRequestUnmarshalJSON(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\ter := NewExportRequest()\n\t\terr := er.UnmarshalJSON(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tb1, err := er.MarshalJSON()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\ter = NewExportRequest()\n\t\trequire.NoError(t, er.UnmarshalJSON(b1), \"failed to unmarshal valid bytes\")\n\t\tb2, err := er.MarshalJSON()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n\nfunc FuzzResponseUnmarshalJSON(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\ter := NewExportResponse()\n\t\terr := er.UnmarshalJSON(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tb1, err := er.MarshalJSON()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\ter = NewExportResponse()\n\t\trequire.NoError(t, er.UnmarshalJSON(b1), \"failed to unmarshal valid bytes\")\n\t\tb2, err := er.MarshalJSON()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n\nfunc FuzzRequestUnmarshalProto(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\ter := NewExportRequest()\n\t\terr := er.UnmarshalProto(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tb1, err := er.MarshalProto()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\ter = NewExportRequest()\n\t\trequire.NoError(t, er.UnmarshalProto(b1), \"failed to unmarshal valid bytes\")\n\t\tb2, err := er.MarshalProto()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n\nfunc FuzzResponseUnmarshalProto(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\ter := NewExportResponse()\n\t\terr := er.UnmarshalProto(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tb1, err := er.MarshalProto()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\ter = NewExportResponse()\n\t\trequire.NoError(t, er.UnmarshalProto(b1), \"failed to unmarshal valid bytes\")\n\t\tb2, err := er.MarshalProto()\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n"
  },
  {
    "path": "pdata/ptrace/ptraceotlp/generated_exportpartialsuccess.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptraceotlp\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ExportPartialSuccess represents the details of a partially successful export request.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewExportPartialSuccess function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ExportPartialSuccess struct {\n\torig  *internal.ExportTracePartialSuccess\n\tstate *internal.State\n}\n\nfunc newExportPartialSuccess(orig *internal.ExportTracePartialSuccess, state *internal.State) ExportPartialSuccess {\n\treturn ExportPartialSuccess{orig: orig, state: state}\n}\n\n// NewExportPartialSuccess creates a new empty ExportPartialSuccess.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewExportPartialSuccess() ExportPartialSuccess {\n\treturn newExportPartialSuccess(internal.NewExportTracePartialSuccess(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ExportPartialSuccess) MoveTo(dest ExportPartialSuccess) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteExportTracePartialSuccess(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// RejectedSpans returns the rejectedspans associated with this ExportPartialSuccess.\nfunc (ms ExportPartialSuccess) RejectedSpans() int64 {\n\treturn ms.orig.RejectedSpans\n}\n\n// SetRejectedSpans replaces the rejectedspans associated with this ExportPartialSuccess.\nfunc (ms ExportPartialSuccess) SetRejectedSpans(v int64) {\n\tms.state.AssertMutable()\n\tms.orig.RejectedSpans = v\n}\n\n// ErrorMessage returns the errormessage associated with this ExportPartialSuccess.\nfunc (ms ExportPartialSuccess) ErrorMessage() string {\n\treturn ms.orig.ErrorMessage\n}\n\n// SetErrorMessage replaces the errormessage associated with this ExportPartialSuccess.\nfunc (ms ExportPartialSuccess) SetErrorMessage(v string) {\n\tms.state.AssertMutable()\n\tms.orig.ErrorMessage = v\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ExportPartialSuccess) CopyTo(dest ExportPartialSuccess) {\n\tdest.state.AssertMutable()\n\tinternal.CopyExportTracePartialSuccess(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/ptrace/ptraceotlp/generated_exportpartialsuccess_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptraceotlp\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestExportPartialSuccess_MoveTo(t *testing.T) {\n\tms := generateTestExportPartialSuccess()\n\tdest := NewExportPartialSuccess()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewExportPartialSuccess(), ms)\n\tassert.Equal(t, generateTestExportPartialSuccess(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestExportPartialSuccess(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newExportPartialSuccess(internal.NewExportTracePartialSuccess(), sharedState)) })\n\tassert.Panics(t, func() { newExportPartialSuccess(internal.NewExportTracePartialSuccess(), sharedState).MoveTo(dest) })\n}\n\nfunc TestExportPartialSuccess_CopyTo(t *testing.T) {\n\tms := NewExportPartialSuccess()\n\torig := NewExportPartialSuccess()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestExportPartialSuccess()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newExportPartialSuccess(internal.NewExportTracePartialSuccess(), sharedState)) })\n}\n\nfunc TestExportPartialSuccess_RejectedSpans(t *testing.T) {\n\tms := NewExportPartialSuccess()\n\tassert.Equal(t, int64(0), ms.RejectedSpans())\n\tms.SetRejectedSpans(int64(13))\n\tassert.Equal(t, int64(13), ms.RejectedSpans())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewExportPartialSuccess(internal.NewExportTracePartialSuccess(), sharedState).SetRejectedSpans(int64(13))\n\t})\n}\n\nfunc TestExportPartialSuccess_ErrorMessage(t *testing.T) {\n\tms := NewExportPartialSuccess()\n\tassert.Empty(t, ms.ErrorMessage())\n\tms.SetErrorMessage(\"test_errormessage\")\n\tassert.Equal(t, \"test_errormessage\", ms.ErrorMessage())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() {\n\t\tnewExportPartialSuccess(internal.NewExportTracePartialSuccess(), sharedState).SetErrorMessage(\"test_errormessage\")\n\t})\n}\n\nfunc generateTestExportPartialSuccess() ExportPartialSuccess {\n\treturn newExportPartialSuccess(internal.GenTestExportTracePartialSuccess(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/ptrace/ptraceotlp/generated_exportresponse.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptraceotlp\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// ExportResponse represents the response for gRPC/HTTP client/server.\n//\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewExportResponse function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype ExportResponse struct {\n\torig  *internal.ExportTraceServiceResponse\n\tstate *internal.State\n}\n\nfunc newExportResponse(orig *internal.ExportTraceServiceResponse, state *internal.State) ExportResponse {\n\treturn ExportResponse{orig: orig, state: state}\n}\n\n// NewExportResponse creates a new empty ExportResponse.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewExportResponse() ExportResponse {\n\treturn newExportResponse(internal.NewExportTraceServiceResponse(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms ExportResponse) MoveTo(dest ExportResponse) {\n\tms.state.AssertMutable()\n\tdest.state.AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.orig == dest.orig {\n\t\treturn\n\t}\n\tinternal.DeleteExportTraceServiceResponse(dest.orig, false)\n\t*dest.orig, *ms.orig = *ms.orig, *dest.orig\n}\n\n// PartialSuccess returns the partialsuccess associated with this ExportResponse.\nfunc (ms ExportResponse) PartialSuccess() ExportPartialSuccess {\n\treturn newExportPartialSuccess(&ms.orig.PartialSuccess, ms.state)\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms ExportResponse) CopyTo(dest ExportResponse) {\n\tdest.state.AssertMutable()\n\tinternal.CopyExportTraceServiceResponse(dest.orig, ms.orig)\n}\n"
  },
  {
    "path": "pdata/ptrace/ptraceotlp/generated_exportresponse_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage ptraceotlp\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestExportResponse_MoveTo(t *testing.T) {\n\tms := generateTestExportResponse()\n\tdest := NewExportResponse()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewExportResponse(), ms)\n\tassert.Equal(t, generateTestExportResponse(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestExportResponse(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newExportResponse(internal.NewExportTraceServiceResponse(), sharedState)) })\n\tassert.Panics(t, func() { newExportResponse(internal.NewExportTraceServiceResponse(), sharedState).MoveTo(dest) })\n}\n\nfunc TestExportResponse_CopyTo(t *testing.T) {\n\tms := NewExportResponse()\n\torig := NewExportResponse()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestExportResponse()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newExportResponse(internal.NewExportTraceServiceResponse(), sharedState)) })\n}\n\nfunc TestExportResponse_PartialSuccess(t *testing.T) {\n\tms := NewExportResponse()\n\tassert.Equal(t, NewExportPartialSuccess(), ms.PartialSuccess())\n\tms.orig.PartialSuccess = *internal.GenTestExportTracePartialSuccess()\n\tassert.Equal(t, generateTestExportPartialSuccess(), ms.PartialSuccess())\n}\n\nfunc generateTestExportResponse() ExportResponse {\n\treturn newExportResponse(internal.GenTestExportTraceServiceResponse(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/ptrace/ptraceotlp/grpc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptraceotlp // import \"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n\nimport (\n\t\"context\"\n\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otelgrpc\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otlp\"\n)\n\n// GRPCClient is the client API for OTLP-GRPC Traces service.\n//\n// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.\ntype GRPCClient interface {\n\t// Export ptrace.Traces to the server.\n\t//\n\t// For performance reasons, it is recommended to keep this RPC\n\t// alive for the entire life of the application.\n\tExport(ctx context.Context, request ExportRequest, opts ...grpc.CallOption) (ExportResponse, error)\n\n\t// unexported disallow implementation of the GRPCClient.\n\tunexported()\n}\n\n// NewGRPCClient returns a new GRPCClient connected using the given connection.\nfunc NewGRPCClient(cc *grpc.ClientConn) GRPCClient {\n\treturn &grpcClient{rawClient: otelgrpc.NewTraceServiceClient(cc)}\n}\n\ntype grpcClient struct {\n\trawClient otelgrpc.TraceServiceClient\n}\n\n// Export implements the Client interface.\nfunc (c *grpcClient) Export(ctx context.Context, request ExportRequest, opts ...grpc.CallOption) (ExportResponse, error) {\n\trsp, err := c.rawClient.Export(ctx, request.orig, opts...)\n\tif err != nil {\n\t\treturn ExportResponse{}, err\n\t}\n\treturn ExportResponse{orig: rsp, state: internal.NewState()}, err\n}\n\nfunc (c *grpcClient) unexported() {}\n\n// GRPCServer is the server API for OTLP gRPC TracesService service.\n// Implementations MUST embed UnimplementedGRPCServer.\ntype GRPCServer interface {\n\t// Export is called every time a new request is received.\n\t//\n\t// For performance reasons, it is recommended to keep this RPC\n\t// alive for the entire life of the application.\n\tExport(context.Context, ExportRequest) (ExportResponse, error)\n\n\t// unexported disallow implementation of the GRPCServer.\n\tunexported()\n}\n\nvar _ GRPCServer = (*UnimplementedGRPCServer)(nil)\n\n// UnimplementedGRPCServer MUST be embedded to have forward compatible implementations.\ntype UnimplementedGRPCServer struct{}\n\nfunc (*UnimplementedGRPCServer) Export(context.Context, ExportRequest) (ExportResponse, error) {\n\treturn ExportResponse{}, status.Errorf(codes.Unimplemented, \"method Export not implemented\")\n}\n\nfunc (*UnimplementedGRPCServer) unexported() {}\n\n// RegisterGRPCServer registers the GRPCServer to the grpc.Server.\nfunc RegisterGRPCServer(s *grpc.Server, srv GRPCServer) {\n\totelgrpc.RegisterTraceServiceServer(s, &rawTracesServer{srv: srv})\n}\n\ntype rawTracesServer struct {\n\tsrv GRPCServer\n}\n\nfunc (s rawTracesServer) Export(ctx context.Context, request *internal.ExportTraceServiceRequest) (*internal.ExportTraceServiceResponse, error) {\n\totlp.MigrateTraces(request.ResourceSpans)\n\trsp, err := s.srv.Export(ctx, ExportRequest{orig: request, state: internal.NewState()})\n\treturn rsp.orig, err\n}\n"
  },
  {
    "path": "pdata/ptrace/ptraceotlp/grpc_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptraceotlp\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/credentials/insecure\"\n\t\"google.golang.org/grpc/resolver\"\n\t\"google.golang.org/grpc/status\"\n\t\"google.golang.org/grpc/test/bufconn\"\n\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nfunc TestGrpc(t *testing.T) {\n\tlis := bufconn.Listen(1024 * 1024)\n\ts := grpc.NewServer()\n\tRegisterGRPCServer(s, &fakeTracesServer{t: t})\n\twg := sync.WaitGroup{}\n\twg.Go(func() {\n\t\tassert.NoError(t, s.Serve(lis))\n\t})\n\tt.Cleanup(func() {\n\t\ts.Stop()\n\t\twg.Wait()\n\t})\n\n\tresolver.SetDefaultScheme(\"passthrough\")\n\tcc, err := grpc.NewClient(\"bufnet\",\n\t\tgrpc.WithContextDialer(func(context.Context, string) (net.Conn, error) {\n\t\t\treturn lis.Dial()\n\t\t}),\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, cc.Close())\n\t})\n\n\tlogClient := NewGRPCClient(cc)\n\n\tresp, err := logClient.Export(context.Background(), generateTracesRequest())\n\trequire.NoError(t, err)\n\tassert.Equal(t, NewExportResponse(), resp)\n}\n\nfunc TestGrpcError(t *testing.T) {\n\tlis := bufconn.Listen(1024 * 1024)\n\ts := grpc.NewServer()\n\tRegisterGRPCServer(s, &fakeTracesServer{t: t, err: errors.New(\"my error\")})\n\twg := sync.WaitGroup{}\n\twg.Go(func() {\n\t\tassert.NoError(t, s.Serve(lis))\n\t})\n\tt.Cleanup(func() {\n\t\ts.Stop()\n\t\twg.Wait()\n\t})\n\n\tcc, err := grpc.NewClient(\"bufnet\",\n\t\tgrpc.WithContextDialer(func(context.Context, string) (net.Conn, error) {\n\t\t\treturn lis.Dial()\n\t\t}),\n\t\tgrpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, cc.Close())\n\t})\n\n\tlogClient := NewGRPCClient(cc)\n\tresp, err := logClient.Export(context.Background(), generateTracesRequest())\n\trequire.Error(t, err)\n\tst, okSt := status.FromError(err)\n\trequire.True(t, okSt)\n\tassert.Equal(t, \"my error\", st.Message())\n\tassert.Equal(t, codes.Unknown, st.Code())\n\tassert.Equal(t, ExportResponse{}, resp)\n}\n\ntype fakeTracesServer struct {\n\tUnimplementedGRPCServer\n\tt   *testing.T\n\terr error\n}\n\nfunc (f fakeTracesServer) Export(_ context.Context, request ExportRequest) (ExportResponse, error) {\n\tassert.Equal(f.t, generateTracesRequest(), request)\n\treturn NewExportResponse(), f.err\n}\n\nfunc generateTracesRequest() ExportRequest {\n\ttd := ptrace.NewTraces()\n\ttd.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty().SetName(\"test_span\")\n\treturn NewExportRequestFromTraces(td)\n}\n"
  },
  {
    "path": "pdata/ptrace/ptraceotlp/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptraceotlp\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "pdata/ptrace/ptraceotlp/request.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptraceotlp // import \"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n\nimport (\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otlp\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\n// ExportRequest represents the request for gRPC/HTTP client/server.\n// It's a wrapper for ptrace.Traces data.\ntype ExportRequest struct {\n\torig  *internal.ExportTraceServiceRequest\n\tstate *internal.State\n}\n\n// NewExportRequest returns an empty ExportRequest.\nfunc NewExportRequest() ExportRequest {\n\treturn ExportRequest{\n\t\torig:  &internal.ExportTraceServiceRequest{},\n\t\tstate: internal.NewState(),\n\t}\n}\n\n// NewExportRequestFromTraces returns a ExportRequest from ptrace.Traces.\n// Because ExportRequest is a wrapper for ptrace.Traces,\n// any changes to the provided Traces struct will be reflected in the ExportRequest and vice versa.\nfunc NewExportRequestFromTraces(td ptrace.Traces) ExportRequest {\n\treturn ExportRequest{\n\t\torig:  internal.GetTracesOrig(internal.TracesWrapper(td)),\n\t\tstate: internal.GetTracesState(internal.TracesWrapper(td)),\n\t}\n}\n\n// MarshalProto marshals ExportRequest into proto bytes.\nfunc (ms ExportRequest) MarshalProto() ([]byte, error) {\n\tsize := ms.orig.SizeProto()\n\tbuf := make([]byte, size)\n\t_ = ms.orig.MarshalProto(buf)\n\treturn buf, nil\n}\n\n// UnmarshalProto unmarshalls ExportRequest from proto bytes.\nfunc (ms ExportRequest) UnmarshalProto(data []byte) error {\n\terr := ms.orig.UnmarshalProto(data)\n\tif err != nil {\n\t\treturn err\n\t}\n\totlp.MigrateTraces(ms.orig.ResourceSpans)\n\treturn nil\n}\n\n// MarshalJSON marshals ExportRequest into JSON bytes.\nfunc (ms ExportRequest) MarshalJSON() ([]byte, error) {\n\tdest := json.BorrowStream(nil)\n\tdefer json.ReturnStream(dest)\n\tms.orig.MarshalJSON(dest)\n\tif dest.Error() != nil {\n\t\treturn nil, dest.Error()\n\t}\n\treturn slices.Clone(dest.Buffer()), nil\n}\n\n// UnmarshalJSON unmarshalls ExportRequest from JSON bytes.\nfunc (ms ExportRequest) UnmarshalJSON(data []byte) error {\n\titer := json.BorrowIterator(data)\n\tdefer json.ReturnIterator(iter)\n\tms.orig.UnmarshalJSON(iter)\n\treturn iter.Error()\n}\n\nfunc (ms ExportRequest) Traces() ptrace.Traces {\n\treturn ptrace.Traces(internal.NewTracesWrapper(ms.orig, ms.state))\n}\n"
  },
  {
    "path": "pdata/ptrace/ptraceotlp/request_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptraceotlp\n\nimport (\n\t\"encoding/json\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tgootlpcollectortrace \"go.opentelemetry.io/proto/slim/otlp/collector/trace/v1\"\n\tgoproto \"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/otlp\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nvar (\n\t_ json.Unmarshaler = ExportRequest{}\n\t_ json.Marshaler   = ExportRequest{}\n)\n\nvar tracesRequestJSON = []byte(`\n\t{\n\t\t\"resourceSpans\": [\n\t\t\t{\n\t\t\t\t\"resource\": {},\n\t\t\t\t\"scopeSpans\": [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"scope\": {},\n\t\t\t\t\t\t\"spans\": [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"name\": \"test_span\",\n\t\t\t\t\t\t\t\t\"status\": {}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t]\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t}\n\t\t]\n\t}`)\n\nfunc TestRequestToPData(t *testing.T) {\n\ttr := NewExportRequest()\n\tassert.Equal(t, 0, tr.Traces().SpanCount())\n\ttr.Traces().ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty()\n\tassert.Equal(t, 1, tr.Traces().SpanCount())\n}\n\nfunc TestRequestJSON(t *testing.T) {\n\ttr := NewExportRequest()\n\trequire.NoError(t, tr.UnmarshalJSON(tracesRequestJSON))\n\tassert.Equal(t, \"test_span\", tr.Traces().ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).Name())\n\n\tgot, err := tr.MarshalJSON()\n\trequire.NoError(t, err)\n\tassert.Equal(t, strings.Join(strings.Fields(string(tracesRequestJSON)), \"\"), string(got))\n}\n\nfunc TestTracesProtoWireCompatibility(t *testing.T) {\n\t// This test verifies that OTLP ProtoBufs generated using goproto lib in\n\t// opentelemetry-proto repository OTLP ProtoBufs generated using gogoproto lib in\n\t// this repository are wire compatible.\n\n\t// Generate Traces as pdata struct.\n\ttd := NewExportRequestFromTraces(ptrace.Traces(internal.GenTestTracesWrapper()))\n\n\t// Marshal its underlying ProtoBuf to wire.\n\twire1, err := td.MarshalProto()\n\trequire.NoError(t, err)\n\tassert.NotNil(t, wire1)\n\n\t// Unmarshal from the wire to OTLP Protobuf in goproto's representation.\n\tvar goprotoMessage gootlpcollectortrace.ExportTraceServiceRequest\n\terr = goproto.Unmarshal(wire1, &goprotoMessage)\n\trequire.NoError(t, err)\n\n\t// Marshal to the wire again.\n\twire2, err := goproto.Marshal(&goprotoMessage)\n\trequire.NoError(t, err)\n\tassert.NotNil(t, wire2)\n\n\t// Unmarshal from the wire into gogoproto's representation.\n\ttd2 := NewExportRequest()\n\terr = td2.UnmarshalProto(wire2)\n\trequire.NoError(t, err)\n\n\t// Now compare that the original and final ProtoBuf messages are the same.\n\t// This proves that goproto and gogoproto marshaling/unmarshaling are wire compatible.\n\t// Migration logic will run, so run it on the original message as well.\n\totlp.MigrateTraces(td.orig.ResourceSpans)\n\tassert.Equal(t, td, td2)\n}\n"
  },
  {
    "path": "pdata/ptrace/ptraceotlp/response.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptraceotlp // import \"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n\nimport (\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n)\n\n// MarshalProto marshals ExportResponse into proto bytes.\nfunc (ms ExportResponse) MarshalProto() ([]byte, error) {\n\tsize := ms.orig.SizeProto()\n\tbuf := make([]byte, size)\n\t_ = ms.orig.MarshalProto(buf)\n\treturn buf, nil\n}\n\n// UnmarshalProto unmarshalls ExportResponse from proto bytes.\nfunc (ms ExportResponse) UnmarshalProto(data []byte) error {\n\treturn ms.orig.UnmarshalProto(data)\n}\n\n// MarshalJSON marshals ExportResponse into JSON bytes.\nfunc (ms ExportResponse) MarshalJSON() ([]byte, error) {\n\tdest := json.BorrowStream(nil)\n\tdefer json.ReturnStream(dest)\n\tms.orig.MarshalJSON(dest)\n\treturn slices.Clone(dest.Buffer()), dest.Error()\n}\n\n// UnmarshalJSON unmarshalls ExportResponse from JSON bytes.\nfunc (ms ExportResponse) UnmarshalJSON(data []byte) error {\n\titer := json.BorrowIterator(data)\n\tdefer json.ReturnIterator(iter)\n\tms.orig.UnmarshalJSON(iter)\n\treturn iter.Error()\n}\n"
  },
  {
    "path": "pdata/ptrace/ptraceotlp/response_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptraceotlp\n\nimport (\n\tstdjson \"encoding/json\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar (\n\t_ stdjson.Unmarshaler = ExportResponse{}\n\t_ stdjson.Marshaler   = ExportResponse{}\n)\n\nfunc TestExportResponseJSON(t *testing.T) {\n\tjsonStr := `{\"partialSuccess\": {\"rejectedSpans\":\"1\", \"errorMessage\":\"nothing\"}}`\n\tval := NewExportResponse()\n\trequire.NoError(t, val.UnmarshalJSON([]byte(jsonStr)))\n\texpected := NewExportResponse()\n\texpected.PartialSuccess().SetRejectedSpans(1)\n\texpected.PartialSuccess().SetErrorMessage(\"nothing\")\n\tassert.Equal(t, expected, val)\n\tbuf, err := val.MarshalJSON()\n\trequire.NoError(t, err)\n\tassert.JSONEq(t, jsonStr, string(buf))\n}\n\nfunc TestUnmarshalJSONExportResponse(t *testing.T) {\n\tjsonStr := `{\"extra\":\"\", \"partialSuccess\": {\"extra\":\"\"}}`\n\tval := NewExportResponse()\n\trequire.NoError(t, val.UnmarshalJSON([]byte(jsonStr)))\n\tassert.Equal(t, NewExportResponse(), val)\n}\n"
  },
  {
    "path": "pdata/ptrace/span_kind.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptrace // import \"go.opentelemetry.io/collector/pdata/ptrace\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// SpanKind is the type of span. Can be used to specify additional relationships between spans\n// in addition to a parent/child relationship.\ntype SpanKind int32\n\nconst (\n\t// SpanKindUnspecified represents that the SpanKind is unspecified, it MUST NOT be used.\n\tSpanKindUnspecified = SpanKind(internal.SpanKind_SPAN_KIND_UNSPECIFIED)\n\t// SpanKindInternal indicates that the span represents an internal operation within an application,\n\t// as opposed to an operation happening at the boundaries. Default value.\n\tSpanKindInternal = SpanKind(internal.SpanKind_SPAN_KIND_INTERNAL)\n\t// SpanKindServer indicates that the span covers server-side handling of an RPC or other\n\t// remote network request.\n\tSpanKindServer = SpanKind(internal.SpanKind_SPAN_KIND_SERVER)\n\t// SpanKindClient indicates that the span describes a request to some remote service.\n\tSpanKindClient = SpanKind(internal.SpanKind_SPAN_KIND_CLIENT)\n\t// SpanKindProducer indicates that the span describes a producer sending a message to a broker.\n\t// Unlike CLIENT and SERVER, there is often no direct critical path latency relationship\n\t// between producer and consumer spans.\n\t// A PRODUCER span ends when the message was accepted by the broker while the logical processing of\n\t// the message might span a much longer time.\n\tSpanKindProducer = SpanKind(internal.SpanKind_SPAN_KIND_PRODUCER)\n\t// SpanKindConsumer indicates that the span describes consumer receiving a message from a broker.\n\t// Like the PRODUCER kind, there is often no direct critical path latency relationship between\n\t// producer and consumer spans.\n\tSpanKindConsumer = SpanKind(internal.SpanKind_SPAN_KIND_CONSUMER)\n)\n\n// String returns the string representation of the SpanKind.\nfunc (sk SpanKind) String() string {\n\tswitch sk {\n\tcase SpanKindUnspecified:\n\t\treturn \"Unspecified\"\n\tcase SpanKindInternal:\n\t\treturn \"Internal\"\n\tcase SpanKindServer:\n\t\treturn \"Server\"\n\tcase SpanKindClient:\n\t\treturn \"Client\"\n\tcase SpanKindProducer:\n\t\treturn \"Producer\"\n\tcase SpanKindConsumer:\n\t\treturn \"Consumer\"\n\t}\n\treturn \"\"\n}\n"
  },
  {
    "path": "pdata/ptrace/span_kind_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptrace // import \"go.opentelemetry.io/collector/pdata/ptrace\"\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestSpanKindString(t *testing.T) {\n\tassert.Equal(t, \"Unspecified\", SpanKindUnspecified.String())\n\tassert.Equal(t, \"Internal\", SpanKindInternal.String())\n\tassert.Equal(t, \"Server\", SpanKindServer.String())\n\tassert.Equal(t, \"Client\", SpanKindClient.String())\n\tassert.Equal(t, \"Producer\", SpanKindProducer.String())\n\tassert.Equal(t, \"Consumer\", SpanKindConsumer.String())\n\tassert.Empty(t, SpanKind(100).String())\n}\n"
  },
  {
    "path": "pdata/ptrace/status_code.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptrace // import \"go.opentelemetry.io/collector/pdata/ptrace\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// StatusCode mirrors the codes defined at\n// https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/api.md#set-status\ntype StatusCode int32\n\nconst (\n\tStatusCodeUnset = StatusCode(internal.StatusCode_STATUS_CODE_UNSET)\n\tStatusCodeOk    = StatusCode(internal.StatusCode_STATUS_CODE_OK)\n\tStatusCodeError = StatusCode(internal.StatusCode_STATUS_CODE_ERROR)\n)\n\n// String returns the string representation of the StatusCode.\nfunc (sc StatusCode) String() string {\n\tswitch sc {\n\tcase StatusCodeUnset:\n\t\treturn \"Unset\"\n\tcase StatusCodeOk:\n\t\treturn \"Ok\"\n\tcase StatusCodeError:\n\t\treturn \"Error\"\n\t}\n\treturn \"\"\n}\n"
  },
  {
    "path": "pdata/ptrace/status_code_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptrace // import \"go.opentelemetry.io/collector/pdata/ptrace\"\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestStatusCodeString(t *testing.T) {\n\tassert.Equal(t, \"Unset\", StatusCodeUnset.String())\n\tassert.Equal(t, \"Ok\", StatusCodeOk.String())\n\tassert.Equal(t, \"Error\", StatusCodeError.String())\n\tassert.Empty(t, StatusCode(100).String())\n}\n"
  },
  {
    "path": "pdata/ptrace/traces.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptrace // import \"go.opentelemetry.io/collector/pdata/ptrace\"\n\n// MarkReadOnly marks the Traces as shared so that no further modifications can be done on it.\nfunc (ms Traces) MarkReadOnly() {\n\tms.getState().MarkReadOnly()\n}\n\n// IsReadOnly returns true if this Traces instance is read-only.\nfunc (ms Traces) IsReadOnly() bool {\n\treturn ms.getState().IsReadOnly()\n}\n\n// SpanCount calculates the total number of spans.\nfunc (ms Traces) SpanCount() int {\n\tspanCount := 0\n\trss := ms.ResourceSpans()\n\tfor i := 0; i < rss.Len(); i++ {\n\t\trs := rss.At(i)\n\t\tilss := rs.ScopeSpans()\n\t\tfor j := 0; j < ilss.Len(); j++ {\n\t\t\tspanCount += ilss.At(j).Spans().Len()\n\t\t}\n\t}\n\treturn spanCount\n}\n"
  },
  {
    "path": "pdata/ptrace/traces_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage ptrace\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestSpanCount(t *testing.T) {\n\ttraces := NewTraces()\n\tassert.Equal(t, 0, traces.SpanCount())\n\n\trs := traces.ResourceSpans().AppendEmpty()\n\tassert.Equal(t, 0, traces.SpanCount())\n\n\tils := rs.ScopeSpans().AppendEmpty()\n\tassert.Equal(t, 0, traces.SpanCount())\n\n\tils.Spans().AppendEmpty()\n\tassert.Equal(t, 1, traces.SpanCount())\n\n\trms := traces.ResourceSpans()\n\trms.EnsureCapacity(3)\n\trms.AppendEmpty().ScopeSpans().AppendEmpty()\n\tilss := rms.AppendEmpty().ScopeSpans().AppendEmpty().Spans()\n\tfor range 5 {\n\t\tilss.AppendEmpty()\n\t}\n\t// 5 + 1 (from rms.At(0) initialized first)\n\tassert.Equal(t, 6, traces.SpanCount())\n}\n\nfunc TestSpanCountWithEmpty(t *testing.T) {\n\tassert.Equal(t, 0, newTraces(&internal.ExportTraceServiceRequest{\n\t\tResourceSpans: []*internal.ResourceSpans{{}},\n\t}, new(internal.State)).SpanCount())\n\tassert.Equal(t, 0, newTraces(&internal.ExportTraceServiceRequest{\n\t\tResourceSpans: []*internal.ResourceSpans{\n\t\t\t{\n\t\t\t\tScopeSpans: []*internal.ScopeSpans{{}},\n\t\t\t},\n\t\t},\n\t}, new(internal.State)).SpanCount())\n\tassert.Equal(t, 1, newTraces(&internal.ExportTraceServiceRequest{\n\t\tResourceSpans: []*internal.ResourceSpans{\n\t\t\t{\n\t\t\t\tScopeSpans: []*internal.ScopeSpans{\n\t\t\t\t\t{\n\t\t\t\t\t\tSpans: []*internal.Span{{}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}, new(internal.State)).SpanCount())\n}\n\nfunc TestTracesCopyTo(t *testing.T) {\n\ttd := generateTestTraces()\n\ttracesCopy := NewTraces()\n\ttd.CopyTo(tracesCopy)\n\tassert.Equal(t, td, tracesCopy)\n}\n\nfunc TestReadOnlyTracesInvalidUsage(t *testing.T) {\n\ttd := NewTraces()\n\tassert.False(t, td.IsReadOnly())\n\tres := td.ResourceSpans().AppendEmpty().Resource()\n\tres.Attributes().PutStr(\"k1\", \"v1\")\n\ttd.MarkReadOnly()\n\tassert.True(t, td.IsReadOnly())\n\tassert.Panics(t, func() { res.Attributes().PutStr(\"k2\", \"v2\") })\n}\n\nfunc BenchmarkTracesUsage(b *testing.B) {\n\ttd := generateTestTraces()\n\tts := pcommon.NewTimestampFromTime(time.Now())\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tfor i := 0; i < td.ResourceSpans().Len(); i++ {\n\t\t\trs := td.ResourceSpans().At(i)\n\t\t\tres := rs.Resource()\n\t\t\tres.Attributes().PutStr(\"foo\", \"bar\")\n\t\t\tv, ok := res.Attributes().Get(\"foo\")\n\t\t\tassert.True(b, ok)\n\t\t\tassert.Equal(b, \"bar\", v.Str())\n\t\t\tv.SetStr(\"new-bar\")\n\t\t\tassert.Equal(b, \"new-bar\", v.Str())\n\t\t\tres.Attributes().Remove(\"foo\")\n\t\t\tfor j := 0; j < rs.ScopeSpans().Len(); j++ {\n\t\t\t\tiss := rs.ScopeSpans().At(j)\n\t\t\t\tiss.Scope().SetName(\"new_test_name\")\n\t\t\t\tassert.Equal(b, \"new_test_name\", iss.Scope().Name())\n\t\t\t\tfor k := 0; k < iss.Spans().Len(); k++ {\n\t\t\t\t\ts := iss.Spans().At(k)\n\t\t\t\t\ts.SetName(\"new_span\")\n\t\t\t\t\tassert.Equal(b, \"new_span\", s.Name())\n\t\t\t\t\ts.SetStartTimestamp(ts)\n\t\t\t\t\tassert.Equal(b, ts, s.StartTimestamp())\n\t\t\t\t\ts.SetEndTimestamp(ts)\n\t\t\t\t\tassert.Equal(b, ts, s.EndTimestamp())\n\t\t\t\t\ts.SetTraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16})\n\t\t\t\t\tassert.Equal(b, pcommon.TraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}), s.TraceID())\n\t\t\t\t\ts.SetSpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8})\n\t\t\t\t\tassert.Equal(b, pcommon.SpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8}), s.SpanID())\n\t\t\t\t}\n\t\t\t\ts := iss.Spans().AppendEmpty()\n\t\t\t\ts.SetName(\"another_span\")\n\t\t\t\ts.SetStartTimestamp(ts)\n\t\t\t\ts.SetEndTimestamp(ts)\n\t\t\t\ts.SetTraceID([16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16})\n\t\t\t\ts.SetParentSpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8})\n\t\t\t\ts.SetSpanID([8]byte{1, 2, 3, 4, 5, 6, 7, 8})\n\t\t\t\ts.Attributes().PutStr(\"foo1\", \"bar1\")\n\t\t\t\ts.Attributes().PutStr(\"foo2\", \"bar2\")\n\t\t\t\tiss.Spans().RemoveIf(func(lr Span) bool {\n\t\t\t\t\treturn lr.Name() == \"another_span\"\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc BenchmarkTracesMarshalJSON(b *testing.B) {\n\ttd := generateTestTraces()\n\tencoder := &JSONMarshaler{}\n\n\tb.ReportAllocs()\n\n\tfor b.Loop() {\n\t\tjsonBuf, err := encoder.MarshalTraces(td)\n\t\trequire.NoError(b, err)\n\t\trequire.NotNil(b, jsonBuf)\n\t}\n}\n"
  },
  {
    "path": "pdata/testdata/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "pdata/testdata/common.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testdata\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc initMetricExemplarAttributes(dest pcommon.Map) {\n\tdest.PutStr(\"exemplar-attachment\", \"exemplar-attachment-value\")\n}\n\nfunc initMetricAttributes1(dest pcommon.Map) {\n\tdest.PutStr(\"label-1\", \"label-value-1\")\n}\n\nfunc initMetricAttributes2(dest pcommon.Map) {\n\tdest.PutStr(\"label-2\", \"label-value-2\")\n}\n\nfunc initMetricAttributes12(dest pcommon.Map) {\n\tinitMetricAttributes1(dest)\n\tinitMetricAttributes2(dest)\n}\n\nfunc initMetricAttributes13(dest pcommon.Map) {\n\tinitMetricAttributes1(dest)\n\tdest.PutStr(\"label-3\", \"label-value-3\")\n}\n"
  },
  {
    "path": "pdata/testdata/go.mod",
    "content": "module go.opentelemetry.io/collector/pdata/testdata\n\ngo 1.25.0\n\nrequire (\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n)\n\nrequire (\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n)\n\nreplace go.opentelemetry.io/collector/pdata => ../\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../pprofile\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n"
  },
  {
    "path": "pdata/testdata/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/otel v1.40.0 h1:oA5YeOcpRTXq6NN7frwmwFR0Cn3RhTVZvXsP4duvCms=\ngo.opentelemetry.io/otel v1.40.0/go.mod h1:IMb+uXZUKkMXdPddhwAHm6UfOwJyh4ct1ybIlV14J0g=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "pdata/testdata/log.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testdata\n\nimport (\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\nvar logTimestamp = pcommon.NewTimestampFromTime(time.Date(2020, 2, 11, 20, 26, 13, 789, time.UTC))\n\nfunc GenerateLogs(count int) plog.Logs {\n\tld := plog.NewLogs()\n\tinitResource(ld.ResourceLogs().AppendEmpty().Resource())\n\tlogs := ld.ResourceLogs().At(0).ScopeLogs().AppendEmpty().LogRecords()\n\tlogs.EnsureCapacity(count)\n\tfor i := range count {\n\t\tswitch i % 2 {\n\t\tcase 0:\n\t\t\tfillLogOne(logs.AppendEmpty())\n\t\tcase 1:\n\t\t\tfillLogTwo(logs.AppendEmpty())\n\t\t}\n\t}\n\treturn ld\n}\n\nfunc fillLogOne(log plog.LogRecord) {\n\tlog.SetTimestamp(logTimestamp)\n\tlog.SetDroppedAttributesCount(1)\n\tlog.SetSeverityNumber(plog.SeverityNumberInfo)\n\tlog.SetSeverityText(\"Info\")\n\tlog.SetSpanID([8]byte{0x01, 0x02, 0x04, 0x08})\n\tlog.SetTraceID([16]byte{0x08, 0x04, 0x02, 0x01})\n\n\tattrs := log.Attributes()\n\tattrs.PutStr(\"app\", \"server\")\n\tattrs.PutInt(\"instance_num\", 1)\n\n\tlog.Body().SetStr(\"This is a log message\")\n}\n\nfunc fillLogTwo(log plog.LogRecord) {\n\tlog.SetTimestamp(logTimestamp)\n\tlog.SetDroppedAttributesCount(1)\n\tlog.SetSeverityNumber(plog.SeverityNumberInfo)\n\tlog.SetSeverityText(\"Info\")\n\n\tattrs := log.Attributes()\n\tattrs.PutStr(\"customer\", \"acme\")\n\tattrs.PutStr(\"env\", \"dev\")\n\n\tlog.Body().SetStr(\"something happened\")\n}\n"
  },
  {
    "path": "pdata/testdata/metric.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testdata\n\nimport (\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\nvar (\n\tmetricStartTimestamp    = pcommon.NewTimestampFromTime(time.Date(2020, 2, 11, 20, 26, 12, 321, time.UTC))\n\tmetricExemplarTimestamp = pcommon.NewTimestampFromTime(time.Date(2020, 2, 11, 20, 26, 13, 123, time.UTC))\n\tmetricTimestamp         = pcommon.NewTimestampFromTime(time.Date(2020, 2, 11, 20, 26, 13, 789, time.UTC))\n)\n\nconst (\n\tTestGaugeDoubleMetricName          = \"gauge-double\"\n\tTestGaugeIntMetricName             = \"gauge-int\"\n\tTestSumDoubleMetricName            = \"sum-double\"\n\tTestSumIntMetricName               = \"sum-int\"\n\tTestHistogramMetricName            = \"histogram\"\n\tTestExponentialHistogramMetricName = \"exponential-histogram\"\n\tTestSummaryMetricName              = \"summary\"\n)\n\nfunc generateMetricsOneEmptyInstrumentationScope() pmetric.Metrics {\n\tmd := pmetric.NewMetrics()\n\tinitResource(md.ResourceMetrics().AppendEmpty().Resource())\n\tmd.ResourceMetrics().At(0).ScopeMetrics().AppendEmpty()\n\treturn md\n}\n\nfunc GenerateMetricsAllTypesEmpty() pmetric.Metrics {\n\tmd := generateMetricsOneEmptyInstrumentationScope()\n\tms := md.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics()\n\n\tdoubleGauge := ms.AppendEmpty()\n\tinitMetric(doubleGauge, TestGaugeDoubleMetricName, pmetric.MetricTypeGauge)\n\tdoubleGauge.Gauge().DataPoints().AppendEmpty()\n\tintGauge := ms.AppendEmpty()\n\tinitMetric(intGauge, TestGaugeIntMetricName, pmetric.MetricTypeGauge)\n\tintGauge.Gauge().DataPoints().AppendEmpty()\n\tdoubleSum := ms.AppendEmpty()\n\tinitMetric(doubleSum, TestSumDoubleMetricName, pmetric.MetricTypeSum)\n\tdoubleSum.Sum().DataPoints().AppendEmpty()\n\tintSum := ms.AppendEmpty()\n\tinitMetric(intSum, TestSumIntMetricName, pmetric.MetricTypeSum)\n\tintSum.Sum().DataPoints().AppendEmpty()\n\thistogram := ms.AppendEmpty()\n\tinitMetric(histogram, TestHistogramMetricName, pmetric.MetricTypeHistogram)\n\thistogram.Histogram().DataPoints().AppendEmpty()\n\tsummary := ms.AppendEmpty()\n\tinitMetric(summary, TestSummaryMetricName, pmetric.MetricTypeSummary)\n\tsummary.Summary().DataPoints().AppendEmpty()\n\treturn md\n}\n\nfunc GenerateMetricsMetricTypeInvalid() pmetric.Metrics {\n\tmd := generateMetricsOneEmptyInstrumentationScope()\n\tinitMetric(md.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().AppendEmpty(), TestSumIntMetricName, pmetric.MetricTypeEmpty)\n\treturn md\n}\n\nfunc GenerateMetricsAllTypes() pmetric.Metrics {\n\tmd := generateMetricsOneEmptyInstrumentationScope()\n\tms := md.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics()\n\tinitGaugeIntMetric(ms.AppendEmpty())\n\tinitGaugeDoubleMetric(ms.AppendEmpty())\n\tinitSumIntMetric(ms.AppendEmpty())\n\tinitSumDoubleMetric(ms.AppendEmpty())\n\tinitHistogramMetric(ms.AppendEmpty())\n\tinitExponentialHistogramMetric(ms.AppendEmpty())\n\tinitSummaryMetric(ms.AppendEmpty())\n\treturn md\n}\n\nfunc GenerateMetrics(count int) pmetric.Metrics {\n\tmd := generateMetricsOneEmptyInstrumentationScope()\n\tms := md.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics()\n\tms.EnsureCapacity(count)\n\tfor i := range count {\n\t\tswitch i % 7 {\n\t\tcase 0:\n\t\t\tinitGaugeIntMetric(ms.AppendEmpty())\n\t\tcase 1:\n\t\t\tinitGaugeDoubleMetric(ms.AppendEmpty())\n\t\tcase 2:\n\t\t\tinitSumIntMetric(ms.AppendEmpty())\n\t\tcase 3:\n\t\t\tinitSumDoubleMetric(ms.AppendEmpty())\n\t\tcase 4:\n\t\t\tinitHistogramMetric(ms.AppendEmpty())\n\t\tcase 5:\n\t\t\tinitExponentialHistogramMetric(ms.AppendEmpty())\n\t\tcase 6:\n\t\t\tinitSummaryMetric(ms.AppendEmpty())\n\t\t}\n\t}\n\treturn md\n}\n\nfunc initGaugeIntMetric(im pmetric.Metric) {\n\tinitMetric(im, TestGaugeIntMetricName, pmetric.MetricTypeGauge)\n\n\tidps := im.Gauge().DataPoints()\n\tidp0 := idps.AppendEmpty()\n\tinitMetricAttributes1(idp0.Attributes())\n\tidp0.SetStartTimestamp(metricStartTimestamp)\n\tidp0.SetTimestamp(metricTimestamp)\n\tidp0.SetIntValue(123)\n\tidp1 := idps.AppendEmpty()\n\tinitMetricAttributes2(idp1.Attributes())\n\tidp1.SetStartTimestamp(metricStartTimestamp)\n\tidp1.SetTimestamp(metricTimestamp)\n\tidp1.SetIntValue(456)\n}\n\nfunc initGaugeDoubleMetric(im pmetric.Metric) {\n\tinitMetric(im, TestGaugeDoubleMetricName, pmetric.MetricTypeGauge)\n\n\tidps := im.Gauge().DataPoints()\n\tidp0 := idps.AppendEmpty()\n\tinitMetricAttributes12(idp0.Attributes())\n\tidp0.SetStartTimestamp(metricStartTimestamp)\n\tidp0.SetTimestamp(metricTimestamp)\n\tidp0.SetDoubleValue(1.23)\n\tidp1 := idps.AppendEmpty()\n\tinitMetricAttributes13(idp1.Attributes())\n\tidp1.SetStartTimestamp(metricStartTimestamp)\n\tidp1.SetTimestamp(metricTimestamp)\n\tidp1.SetDoubleValue(4.56)\n}\n\nfunc initSumIntMetric(im pmetric.Metric) {\n\tinitMetric(im, TestSumIntMetricName, pmetric.MetricTypeSum)\n\n\tidps := im.Sum().DataPoints()\n\tidp0 := idps.AppendEmpty()\n\tinitMetricAttributes1(idp0.Attributes())\n\tidp0.SetStartTimestamp(metricStartTimestamp)\n\tidp0.SetTimestamp(metricTimestamp)\n\tidp0.SetIntValue(123)\n\tidp1 := idps.AppendEmpty()\n\tinitMetricAttributes2(idp1.Attributes())\n\tidp1.SetStartTimestamp(metricStartTimestamp)\n\tidp1.SetTimestamp(metricTimestamp)\n\tidp1.SetIntValue(456)\n}\n\nfunc initSumDoubleMetric(dm pmetric.Metric) {\n\tinitMetric(dm, TestSumDoubleMetricName, pmetric.MetricTypeSum)\n\n\tddps := dm.Sum().DataPoints()\n\tddp0 := ddps.AppendEmpty()\n\tinitMetricAttributes12(ddp0.Attributes())\n\tddp0.SetStartTimestamp(metricStartTimestamp)\n\tddp0.SetTimestamp(metricTimestamp)\n\tddp0.SetDoubleValue(1.23)\n\n\tddp1 := ddps.AppendEmpty()\n\tinitMetricAttributes13(ddp1.Attributes())\n\tddp1.SetStartTimestamp(metricStartTimestamp)\n\tddp1.SetTimestamp(metricTimestamp)\n\tddp1.SetDoubleValue(4.56)\n}\n\nfunc initHistogramMetric(hm pmetric.Metric) {\n\tinitMetric(hm, TestHistogramMetricName, pmetric.MetricTypeHistogram)\n\n\thdps := hm.Histogram().DataPoints()\n\thdp0 := hdps.AppendEmpty()\n\tinitMetricAttributes13(hdp0.Attributes())\n\thdp0.SetStartTimestamp(metricStartTimestamp)\n\thdp0.SetTimestamp(metricTimestamp)\n\thdp0.SetCount(1)\n\thdp0.SetSum(15)\n\n\thdp1 := hdps.AppendEmpty()\n\tinitMetricAttributes2(hdp1.Attributes())\n\thdp1.SetStartTimestamp(metricStartTimestamp)\n\thdp1.SetTimestamp(metricTimestamp)\n\thdp1.SetCount(1)\n\thdp1.SetSum(15)\n\thdp1.SetMin(15)\n\thdp1.SetMax(15)\n\thdp1.BucketCounts().FromRaw([]uint64{0, 1})\n\texemplar := hdp1.Exemplars().AppendEmpty()\n\texemplar.SetTraceID([16]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10})\n\texemplar.SetSpanID([8]byte{0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18})\n\texemplar.SetTimestamp(metricExemplarTimestamp)\n\texemplar.SetDoubleValue(15)\n\tinitMetricExemplarAttributes(exemplar.FilteredAttributes())\n\thdp1.ExplicitBounds().FromRaw([]float64{1})\n}\n\nfunc initExponentialHistogramMetric(hm pmetric.Metric) {\n\tinitMetric(hm, TestExponentialHistogramMetricName, pmetric.MetricTypeExponentialHistogram)\n\n\thdps := hm.ExponentialHistogram().DataPoints()\n\thdp0 := hdps.AppendEmpty()\n\tinitMetricAttributes13(hdp0.Attributes())\n\thdp0.SetStartTimestamp(metricStartTimestamp)\n\thdp0.SetTimestamp(metricTimestamp)\n\thdp0.SetCount(5)\n\thdp0.SetSum(0.15)\n\thdp0.SetZeroCount(1)\n\thdp0.SetScale(1)\n\n\t// positive index 1 and 2 are values sqrt(2), 2 at scale 1\n\thdp0.Positive().SetOffset(1)\n\thdp0.Positive().BucketCounts().FromRaw([]uint64{1, 1})\n\t// negative index -1 and 0 are values -1/sqrt(2), -1 at scale 1\n\thdp0.Negative().SetOffset(-1)\n\thdp0.Negative().BucketCounts().FromRaw([]uint64{1, 1})\n\n\t// The above will print:\n\t// Bucket (-1.414214, -1.000000], Count: 1\n\t// Bucket (-1.000000, -0.707107], Count: 1\n\t// Bucket [0, 0], Count: 1\n\t// Bucket [0.707107, 1.000000), Count: 1\n\t// Bucket [1.000000, 1.414214), Count: 1\n\n\thdp1 := hdps.AppendEmpty()\n\tinitMetricAttributes2(hdp1.Attributes())\n\thdp1.SetStartTimestamp(metricStartTimestamp)\n\thdp1.SetTimestamp(metricTimestamp)\n\thdp1.SetCount(3)\n\thdp1.SetSum(1.25)\n\thdp1.SetMin(0)\n\thdp1.SetMax(1)\n\thdp1.SetZeroCount(1)\n\thdp1.SetScale(-1)\n\n\t// index -1 and 0 are values 0.25, 1 at scale -1\n\thdp1.Positive().SetOffset(-1)\n\thdp1.Positive().BucketCounts().FromRaw([]uint64{1, 1})\n\n\t// The above will print:\n\t// Bucket [0, 0], Count: 1\n\t// Bucket [0.250000, 1.000000), Count: 1\n\t// Bucket [1.000000, 4.000000), Count: 1\n\n\texemplar := hdp1.Exemplars().AppendEmpty()\n\texemplar.SetTraceID([16]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10})\n\texemplar.SetSpanID([8]byte{0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18})\n\texemplar.SetTimestamp(metricExemplarTimestamp)\n\texemplar.SetIntValue(15)\n\tinitMetricExemplarAttributes(exemplar.FilteredAttributes())\n}\n\nfunc initSummaryMetric(sm pmetric.Metric) {\n\tinitMetric(sm, TestSummaryMetricName, pmetric.MetricTypeSummary)\n\n\tsdps := sm.Summary().DataPoints()\n\tsdp0 := sdps.AppendEmpty()\n\tinitMetricAttributes13(sdp0.Attributes())\n\tsdp0.SetStartTimestamp(metricStartTimestamp)\n\tsdp0.SetTimestamp(metricTimestamp)\n\tsdp0.SetCount(1)\n\tsdp0.SetSum(15)\n\n\tsdp1 := sdps.AppendEmpty()\n\tinitMetricAttributes2(sdp1.Attributes())\n\tsdp1.SetStartTimestamp(metricStartTimestamp)\n\tsdp1.SetTimestamp(metricTimestamp)\n\tsdp1.SetCount(1)\n\tsdp1.SetSum(15)\n\n\tquantile := sdp1.QuantileValues().AppendEmpty()\n\tquantile.SetQuantile(0.01)\n\tquantile.SetValue(15)\n}\n\nfunc initMetric(m pmetric.Metric, name string, ty pmetric.MetricType) {\n\tm.SetName(name)\n\tm.SetDescription(\"\")\n\tm.SetUnit(\"1\")\n\tswitch ty {\n\tcase pmetric.MetricTypeGauge:\n\t\tm.SetEmptyGauge()\n\tcase pmetric.MetricTypeSum:\n\t\tsum := m.SetEmptySum()\n\t\tsum.SetIsMonotonic(true)\n\t\tsum.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n\tcase pmetric.MetricTypeHistogram:\n\t\thisto := m.SetEmptyHistogram()\n\t\thisto.SetAggregationTemporality(pmetric.AggregationTemporalityCumulative)\n\tcase pmetric.MetricTypeExponentialHistogram:\n\t\thisto := m.SetEmptyExponentialHistogram()\n\t\thisto.SetAggregationTemporality(pmetric.AggregationTemporalityDelta)\n\tcase pmetric.MetricTypeSummary:\n\t\tm.SetEmptySummary()\n\t}\n}\n"
  },
  {
    "path": "pdata/testdata/profile.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testdata // import \"go.opentelemetry.io/collector/pdata/testdata\"\n\nimport (\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n)\n\nvar profileStartTimestamp = pcommon.NewTimestampFromTime(time.Date(2020, 2, 11, 20, 26, 12, 321, time.UTC))\n\n// GenerateProfiles generates dummy profiling data for tests\nfunc GenerateProfiles(profilesCount int) pprofile.Profiles {\n\ttd := pprofile.NewProfiles()\n\tinitResource(td.ResourceProfiles().AppendEmpty().Resource())\n\tss := td.ResourceProfiles().At(0).ScopeProfiles().AppendEmpty().Profiles()\n\n\tdic := td.Dictionary()\n\t// By convention, the first element is empty\n\tdic.StringTable().Append(\"\")\n\tdic.StringTable().Append(\"key\")\n\n\t// By convention, the first element is empty\n\tdic.AttributeTable().AppendEmpty()\n\tattr := dic.AttributeTable().AppendEmpty()\n\tattr.SetKeyStrindex(1)\n\tattr.Value().SetStr(\"value-1\")\n\tattr2 := dic.AttributeTable().AppendEmpty()\n\tattr2.SetKeyStrindex(1)\n\tattr2.Value().SetStr(\"value-2\")\n\n\tss.EnsureCapacity(profilesCount)\n\tfor i := range profilesCount {\n\t\tswitch i % 2 {\n\t\tcase 0:\n\t\t\tfillProfileOne(dic, ss.AppendEmpty())\n\t\tcase 1:\n\t\t\tfillProfileTwo(dic, ss.AppendEmpty())\n\t\t}\n\t}\n\n\treturn td\n}\n\nfunc fillProfileOne(dic pprofile.ProfilesDictionary, profile pprofile.Profile) {\n\tprofile.SetProfileID([16]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10})\n\tprofile.SetTime(profileStartTimestamp)\n\tprofile.SetDurationNano(uint64(time.Second.Nanoseconds()))\n\tprofile.SetDroppedAttributesCount(1)\n\n\tloc := pprofile.NewLocation()\n\tloc.SetAddress(1)\n\tlocID, _ := pprofile.SetLocation(dic.LocationTable(), loc)\n\tstack := pprofile.NewStack()\n\tstack.LocationIndices().Append(locID)\n\tstackID, _ := pprofile.SetStack(dic.StackTable(), stack)\n\n\tsample := profile.Samples().AppendEmpty()\n\tsample.SetStackIndex(stackID)\n\tsample.Values().Append(4)\n\tsample.AttributeIndices().Append(1)\n}\n\nfunc fillProfileTwo(dic pprofile.ProfilesDictionary, profile pprofile.Profile) {\n\tprofile.SetProfileID([16]byte{0x02, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10})\n\tprofile.SetTime(profileStartTimestamp)\n\tprofile.SetDurationNano(uint64(time.Second.Nanoseconds()))\n\n\tloc := pprofile.NewLocation()\n\tloc.SetAddress(2)\n\tlocID, _ := pprofile.SetLocation(dic.LocationTable(), loc)\n\tstack := pprofile.NewStack()\n\tstack.LocationIndices().Append(locID)\n\tstackID, _ := pprofile.SetStack(dic.StackTable(), stack)\n\n\tsample := profile.Samples().AppendEmpty()\n\tsample.SetStackIndex(stackID)\n\tsample.Values().Append(9)\n\tsample.AttributeIndices().Append(2)\n}\n"
  },
  {
    "path": "pdata/testdata/resource.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testdata\n\nimport \"go.opentelemetry.io/collector/pdata/pcommon\"\n\nfunc initResource(r pcommon.Resource) {\n\tr.Attributes().PutStr(\"resource-attr\", \"resource-attr-val-1\")\n}\n"
  },
  {
    "path": "pdata/testdata/trace.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testdata\n\nimport (\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nvar (\n\tspanStartTimestamp = pcommon.NewTimestampFromTime(time.Date(2020, 2, 11, 20, 26, 12, 321, time.UTC))\n\tspanEventTimestamp = pcommon.NewTimestampFromTime(time.Date(2020, 2, 11, 20, 26, 13, 123, time.UTC))\n\tspanEndTimestamp   = pcommon.NewTimestampFromTime(time.Date(2020, 2, 11, 20, 26, 13, 789, time.UTC))\n)\n\nfunc GenerateTraces(spanCount int) ptrace.Traces {\n\ttd := ptrace.NewTraces()\n\tinitResource(td.ResourceSpans().AppendEmpty().Resource())\n\tss := td.ResourceSpans().At(0).ScopeSpans().AppendEmpty().Spans()\n\tss.EnsureCapacity(spanCount)\n\tfor i := range spanCount {\n\t\tswitch i % 2 {\n\t\tcase 0:\n\t\t\tfillSpanOne(ss.AppendEmpty())\n\t\tcase 1:\n\t\t\tfillSpanTwo(ss.AppendEmpty())\n\t\t}\n\t}\n\treturn td\n}\n\nfunc fillSpanOne(span ptrace.Span) {\n\tspan.SetName(\"operationA\")\n\tspan.SetStartTimestamp(spanStartTimestamp)\n\tspan.SetEndTimestamp(spanEndTimestamp)\n\tspan.SetDroppedAttributesCount(1)\n\tspan.TraceState().FromRaw(\"ot=th:0\") // 100% sampling\n\tspan.SetTraceID([16]byte{0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10})\n\tspan.SetSpanID([8]byte{0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18})\n\tevs := span.Events()\n\tev0 := evs.AppendEmpty()\n\tev0.SetTimestamp(spanEventTimestamp)\n\tev0.SetName(\"event-with-attr\")\n\tev0.Attributes().PutStr(\"span-event-attr\", \"span-event-attr-val\")\n\tev0.SetDroppedAttributesCount(2)\n\tev1 := evs.AppendEmpty()\n\tev1.SetTimestamp(spanEventTimestamp)\n\tev1.SetName(\"event\")\n\tev1.SetDroppedAttributesCount(2)\n\tspan.SetDroppedEventsCount(1)\n\tstatus := span.Status()\n\tstatus.SetCode(ptrace.StatusCodeError)\n\tstatus.SetMessage(\"status-cancelled\")\n}\n\nfunc fillSpanTwo(span ptrace.Span) {\n\tspan.SetName(\"operationB\")\n\tspan.SetStartTimestamp(spanStartTimestamp)\n\tspan.SetEndTimestamp(spanEndTimestamp)\n\tlink0 := span.Links().AppendEmpty()\n\tlink0.Attributes().PutStr(\"span-link-attr\", \"span-link-attr-val\")\n\tlink0.SetDroppedAttributesCount(4)\n\tlink1 := span.Links().AppendEmpty()\n\tlink1.SetDroppedAttributesCount(4)\n\tspan.SetDroppedLinksCount(3)\n}\n"
  },
  {
    "path": "pdata/xpdata/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "pdata/xpdata/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# xpdata\n\n## Feature Gates\n\nThis component has the following feature gates:\n\n| Feature Gate | Stage | Description | From Version | To Version | Reference |\n| ------------ | ----- | ----------- | ------------ | ---------- | --------- |\n| `pdata.enableRefCounting` | beta | When enabled, enables using ref counting to know when pdata memory can be freed up. This featuregate is here only to protect if unexpected bugs happens because of ref counting logic. | v0.133.0 | N/A | [Link](https://github.com/open-telemetry/opentelemetry-collector/issues/13631) |\n\nFor more information about feature gates, see the [Feature Gates](https://github.com/open-telemetry/opentelemetry-collector/blob/main/featuregate/README.md) documentation.\n"
  },
  {
    "path": "pdata/xpdata/entity/entity.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage entity // import \"go.opentelemetry.io/collector/pdata/xpdata/entity\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// Entity is a helper struct that represents an entity in a more user-friendly way than the underlying\n// EntityRef protobuf message. After adding an entity to a resource, the entity shares the resource's\n// attributes map, so modifications to the entity's attributes are immediately reflected in the resource.\n// To create an Entity, use the EntityMap's PutEmpty method.\ntype Entity struct {\n\tref        EntityRef\n\tattributes pcommon.Map\n}\n\nfunc NewEntity(t string) Entity {\n\tref := NewEntityRef()\n\tref.SetType(t)\n\treturn Entity{\n\t\tref:        ref,\n\t\tattributes: pcommon.NewMap(),\n\t}\n}\n\nfunc (e Entity) Type() string {\n\treturn e.ref.Type()\n}\n\nfunc (e Entity) SchemaURL() string {\n\treturn e.ref.SchemaUrl()\n}\n\nfunc (e Entity) SetSchemaURL(schemaURL string) {\n\te.ref.SetSchemaUrl(schemaURL)\n}\n\n// IdentifyingAttributes returns an EntityAttributeMap for managing the entity's identifying attributes.\nfunc (e Entity) IdentifyingAttributes() EntityAttributeMap {\n\treturn EntityAttributeMap{\n\t\tkeys:       e.ref.IdKeys(),\n\t\tattributes: e.attributes,\n\t}\n}\n\n// DescriptiveAttributes returns an EntityAttributeMap for managing the entity's descriptive attributes.\nfunc (e Entity) DescriptiveAttributes() EntityAttributeMap {\n\treturn EntityAttributeMap{\n\t\tkeys:       e.ref.DescriptionKeys(),\n\t\tattributes: e.attributes,\n\t}\n}\n\n// CopyToResource moves the entity to the provided resource by overriding existing entities and attributes.\nfunc (e Entity) CopyToResource(res pcommon.Resource) {\n\tent := ResourceEntities(res).PutEmpty(e.Type())\n\tfor k, v := range e.IdentifyingAttributes().All() {\n\t\tv.CopyTo(ent.IdentifyingAttributes().PutEmpty(k))\n\t}\n\tfor k, v := range e.DescriptiveAttributes().All() {\n\t\tv.CopyTo(ent.DescriptiveAttributes().PutEmpty(k))\n\t}\n}\n"
  },
  {
    "path": "pdata/xpdata/entity/entity_attribute_map.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage entity // import \"go.opentelemetry.io/collector/pdata/xpdata/entity\"\n\nimport (\n\t\"iter\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// EntityAttributeMap is a wrapper around pcommon.Map that restricts operations to only the keys\n// that belong to a specific set of entity attributes (either ID or Description attributes).\ntype EntityAttributeMap struct {\n\tkeys       pcommon.StringSlice\n\tattributes pcommon.Map\n}\n\n// Get returns the Value associated with the key and true. Returned\n// Value is not a copy, it is a reference to the value stored in this map. It is\n// allowed to modify the returned value using Value.Set* functions.\n//\n// If the key does not exist in the entity's key list or in the underlying map,\n// returns an invalid instance and false. Calling any functions on the returned\n// invalid instance will cause a panic.\nfunc (m EntityAttributeMap) Get(key string) (pcommon.Value, bool) {\n\tif !m.containsKey(key) {\n\t\treturn pcommon.Value{}, false\n\t}\n\treturn m.attributes.Get(key)\n}\n\n// CanPut returns true if it's safe to call Put methods on the given key.\n// Returns true if:\n//   - The key is already owned by this entity (in the entity's key list), OR\n//   - The key doesn't exist in the shared attributes map (available to claim)\n//\n// Returns false if the key exists in the shared map but belongs to another entity.\n//\n// Use this method before calling Put* methods to avoid conflicts:\n//\n//\tif entity.IdentifyingAttributes().CanPut(\"service.name\") {\n//\t    entity.IdentifyingAttributes().PutStr(\"service.name\", \"my-service\")\n//\t}\nfunc (m EntityAttributeMap) CanPut(key string) bool {\n\tif m.containsKey(key) {\n\t\treturn true\n\t}\n\t_, exists := m.attributes.Get(key)\n\treturn !exists\n}\n\n// PutEmpty inserts or updates an empty value to the map under given key\n// and returns the updated/inserted value.\n// The key is also added to the entity's key list if not already present.\n//\n// WARNING: This method is destructive and will overwrite any existing value in the shared\n// attributes map, even if it belongs to another entity. Use CanPut() to check safety first\n// if you need to avoid conflicts with other entities.\nfunc (m EntityAttributeMap) PutEmpty(k string) pcommon.Value {\n\tif !m.containsKey(k) {\n\t\tm.keys.Append(k)\n\t}\n\treturn m.attributes.PutEmpty(k)\n}\n\n// PutStr performs the Insert or Update action. The Value is\n// inserted to the map that did not originally have the key. The key/value is\n// updated to the map where the key already existed.\n// The key is also added to the entity's key list if not already present.\n//\n// WARNING: This method is destructive and will overwrite any existing value in the shared\n// attributes map, even if it belongs to another entity. Use CanPut() to check safety first\n// if you need to avoid conflicts with other entities.\nfunc (m EntityAttributeMap) PutStr(k, v string) {\n\tif !m.containsKey(k) {\n\t\tm.keys.Append(k)\n\t}\n\tm.attributes.PutStr(k, v)\n}\n\n// Remove removes the entry associated with the key and returns true if the key existed.\n// The key is also removed from the entity's key list.\nfunc (m EntityAttributeMap) Remove(key string) bool {\n\tvar keyFound bool\n\tm.keys.RemoveIf(func(k string) bool {\n\t\tif k == key {\n\t\t\tkeyFound = true\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t})\n\tif !keyFound {\n\t\treturn false\n\t}\n\tm.attributes.Remove(key)\n\treturn true\n}\n\nfunc (m EntityAttributeMap) containsKey(key string) bool {\n\tfor _, k := range m.keys.All() {\n\t\tif k == key {\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// All returns an iterator over the key-value pairs of the attributes belonging to this map's key set.\nfunc (m EntityAttributeMap) All() iter.Seq2[string, pcommon.Value] {\n\treturn func(yield func(string, pcommon.Value) bool) {\n\t\tfor _, k := range m.keys.All() {\n\t\t\tv, ok := m.attributes.Get(k)\n\t\t\tif ok && !yield(k, v) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "pdata/xpdata/entity/entity_attribute_map_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage entity\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestEntityAttributeMap(t *testing.T) {\n\tm := newTestEntityAttributeMap()\n\n\tval, ok := m.Get(\"non-existent\")\n\tassert.False(t, ok)\n\tassert.Equal(t, pcommon.Value{}, val)\n\n\tm.PutStr(\"k1\", \"v1\")\n\tval, ok = m.Get(\"k1\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"v1\", val.Str())\n\n\tassert.True(t, m.Remove(\"k1\"))\n\t_, ok = m.Get(\"k1\")\n\tassert.False(t, ok)\n\n\tassert.False(t, m.Remove(\"non-existent\"))\n}\n\nfunc TestEntityAttributeMap_Get(t *testing.T) {\n\tm := newTestEntityAttributeMap()\n\tm.attributes.PutStr(\"owned\", \"value1\")\n\tm.attributes.PutStr(\"not-owned\", \"value2\")\n\tm.keys.Append(\"owned\")\n\n\tval, ok := m.Get(\"owned\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"value1\", val.Str())\n\n\t_, ok = m.Get(\"not-owned\")\n\tassert.False(t, ok)\n\n\t_, ok = m.Get(\"non-existent\")\n\tassert.False(t, ok)\n}\n\nfunc TestEntityAttributeMap_PutStr(t *testing.T) {\n\tm := newTestEntityAttributeMap()\n\n\tm.PutStr(\"k1\", \"v1\")\n\tassert.Equal(t, 1, m.keys.Len())\n\tassert.Equal(t, \"k1\", m.keys.At(0))\n\tval, ok := m.attributes.Get(\"k1\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"v1\", val.Str())\n\n\tm.PutStr(\"k1\", \"v2\")\n\tassert.Equal(t, 1, m.keys.Len())\n\tval, ok = m.attributes.Get(\"k1\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"v2\", val.Str())\n}\n\nfunc TestEntityAttributeMap_PutStr_Overwrites(t *testing.T) {\n\tm := newTestEntityAttributeMap()\n\tm.attributes.PutStr(\"existing\", \"old-value\")\n\n\tm.PutStr(\"existing\", \"new-value\")\n\n\tassert.Equal(t, 1, m.keys.Len())\n\tassert.Equal(t, \"existing\", m.keys.At(0))\n\tval, ok := m.attributes.Get(\"existing\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"new-value\", val.Str())\n}\n\nfunc TestEntityAttributeMap_PutEmpty(t *testing.T) {\n\tm := newTestEntityAttributeMap()\n\n\tval := m.PutEmpty(\"k1\")\n\tval.SetStr(\"v1\")\n\n\tassert.Equal(t, 1, m.keys.Len())\n\tassert.Equal(t, \"k1\", m.keys.At(0))\n\tresVal, ok := m.attributes.Get(\"k1\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"v1\", resVal.Str())\n}\n\nfunc TestEntityAttributeMap_PutEmpty_Overwrites(t *testing.T) {\n\tm := newTestEntityAttributeMap()\n\tm.attributes.PutStr(\"existing\", \"old-value\")\n\n\tval := m.PutEmpty(\"existing\")\n\tval.SetStr(\"new-value\")\n\n\tassert.Equal(t, 1, m.keys.Len())\n\tassert.Equal(t, \"existing\", m.keys.At(0))\n\tresVal, ok := m.attributes.Get(\"existing\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"new-value\", resVal.Str())\n}\n\nfunc TestEntityAttributeMap_Remove(t *testing.T) {\n\tm := newTestEntityAttributeMap()\n\tm.keys.Append(\"k1\")\n\tm.keys.Append(\"k2\")\n\tm.attributes.PutStr(\"k1\", \"v1\")\n\tm.attributes.PutStr(\"k2\", \"v2\")\n\n\tassert.True(t, m.Remove(\"k1\"))\n\tassert.Equal(t, 1, m.keys.Len())\n\tassert.Equal(t, \"k2\", m.keys.At(0))\n\t_, ok := m.attributes.Get(\"k1\")\n\tassert.False(t, ok)\n\n\tval, ok := m.attributes.Get(\"k2\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"v2\", val.Str())\n}\n\nfunc TestEntityAttributeMap_Remove_NotOwned(t *testing.T) {\n\tm := newTestEntityAttributeMap()\n\tm.attributes.PutStr(\"not-owned\", \"value\")\n\n\tassert.False(t, m.Remove(\"not-owned\"))\n\n\tval, ok := m.attributes.Get(\"not-owned\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"value\", val.Str())\n}\n\nfunc TestEntityAttributeMap_Remove_NonExistent(t *testing.T) {\n\tm := newTestEntityAttributeMap()\n\n\tassert.False(t, m.Remove(\"non-existent\"))\n}\n\nfunc TestEntityAttributeMap_CanPut(t *testing.T) {\n\tm := newTestEntityAttributeMap()\n\tm.keys.Append(\"owned\")\n\tm.attributes.PutStr(\"owned\", \"value\")\n\tm.attributes.PutStr(\"other\", \"value\")\n\n\tassert.True(t, m.CanPut(\"owned\"))\n\tassert.False(t, m.CanPut(\"other\"))\n\tassert.True(t, m.CanPut(\"new-key\"))\n}\n\nfunc TestEntityAttributeMap_All(t *testing.T) {\n\tm := newTestEntityAttributeMap()\n\tm.PutStr(\"k1\", \"v1\")\n\tm.PutStr(\"k2\", \"v2\")\n\n\t// Add an attribute not owned by this map — it should not appear in All().\n\tm.attributes.PutStr(\"not-owned\", \"v3\")\n\n\tgot := make(map[string]string)\n\tfor k, v := range m.All() {\n\t\tgot[k] = v.Str()\n\t}\n\n\tassert.Equal(t, map[string]string{\"k1\": \"v1\", \"k2\": \"v2\"}, got)\n\n\t// Verify early termination: breaking out of the loop stops iteration.\n\tvar count int\n\tfor range m.All() {\n\t\tcount++\n\t\tbreak\n\t}\n\tassert.Equal(t, 1, count)\n}\n\nfunc newTestEntityAttributeMap() EntityAttributeMap {\n\treturn EntityAttributeMap{\n\t\tkeys:       pcommon.NewStringSlice(),\n\t\tattributes: pcommon.NewMap(),\n\t}\n}\n"
  },
  {
    "path": "pdata/xpdata/entity/entity_map.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage entity // import \"go.opentelemetry.io/collector/pdata/xpdata/entity\"\n\nimport (\n\t\"iter\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// EntityMap logically represents a map of Entity keyed by entity type.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewEntityMap function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype EntityMap struct {\n\trefs       EntityRefSlice\n\tattributes pcommon.Map\n}\n\n// NewEntityMap creates a EntityMap with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewEntityMap() EntityMap {\n\treturn EntityMap{\n\t\trefs:       NewEntityRefSlice(),\n\t\tattributes: pcommon.NewMap(),\n\t}\n}\n\n// Len returns the number of elements in the map.\n//\n// Returns \"0\" for a newly instance created with \"NewEntityMap()\".\nfunc (em EntityMap) Len() int {\n\treturn em.refs.Len()\n}\n\n// EnsureCapacity is an operation that ensures the map has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the map capacity will be expanded to equal newCap.\nfunc (em EntityMap) EnsureCapacity(newCap int) {\n\tem.refs.EnsureCapacity(newCap)\n}\n\n// Get returns the Entity associated with the entityType and true. The returned\n// Entity is not a copy, it is a reference to the entity stored in this map.\n// It is allowed to modify the returned entity.\n// Such modification will be applied to the entity stored in this map.\n//\n// If the entityType does not exist, returns a zero-initialized Entity and false.\n// Calling any functions on the returned invalid instance may cause a panic.\nfunc (em EntityMap) Get(entityType string) (Entity, bool) {\n\tif entityType == \"\" {\n\t\treturn Entity{}, false\n\t}\n\tfor i := 0; i < em.Len(); i++ {\n\t\tif em.refs.At(i).Type() == entityType {\n\t\t\treturn Entity{\n\t\t\t\tref:        em.refs.At(i),\n\t\t\t\tattributes: em.attributes,\n\t\t\t}, true\n\t\t}\n\t}\n\treturn Entity{}, false\n}\n\n// All returns an iterator over entity type-Entity pairs in the EntityMap.\n//\n//\tfor entityType, entity := range em.All() {\n//\t    ... // Do something with entity type and entity\n//\t}\nfunc (em EntityMap) All() iter.Seq2[string, Entity] {\n\treturn func(yield func(string, Entity) bool) {\n\t\tfor i := 0; i < em.Len(); i++ {\n\t\t\tref := em.refs.At(i)\n\t\t\tentity := Entity{\n\t\t\t\tref:        ref,\n\t\t\t\tattributes: em.attributes,\n\t\t\t}\n\t\t\tif !yield(ref.Type(), entity) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// Remove removes the entity associated with the entityType and returns true if the entity\n// was present in the map, otherwise returns false. All attributes associated with the entity\n// are also removed.\nfunc (em EntityMap) Remove(entityType string) bool {\n\tfor i := 0; i < em.refs.Len(); i++ {\n\t\tref := em.refs.At(i)\n\t\tif ref.Type() == entityType {\n\t\t\tfor _, k := range ref.IdKeys().All() {\n\t\t\t\tem.attributes.Remove(k)\n\t\t\t}\n\t\t\tfor _, k := range ref.DescriptionKeys().All() {\n\t\t\t\tem.attributes.Remove(k)\n\t\t\t}\n\t\t\tem.refs.RemoveIf(func(er EntityRef) bool {\n\t\t\t\treturn er.Type() == entityType\n\t\t\t})\n\t\t\treturn true\n\t\t}\n\t}\n\treturn false\n}\n\n// PutEmpty inserts or replaces an empty Entity with the specified type and returns it.\n// If an entity with the given type already exists, it replaces it and removes all attributes associated with it.\nfunc (em EntityMap) PutEmpty(entityType string) Entity {\n\tem.Remove(entityType)\n\tref := em.refs.AppendEmpty()\n\tref.SetType(entityType)\n\treturn Entity{\n\t\tref:        ref,\n\t\tattributes: em.attributes,\n\t}\n}\n"
  },
  {
    "path": "pdata/xpdata/entity/entity_map_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage entity\n\nimport (\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestEntityMap(t *testing.T) {\n\tem := NewEntityMap()\n\tassert.Equal(t, 0, em.Len())\n\n\te1 := em.PutEmpty(\"service\")\n\tassert.Equal(t, 1, em.Len())\n\tassert.Equal(t, \"service\", e1.Type())\n\n\te2 := em.PutEmpty(\"host\")\n\tassert.Equal(t, 2, em.Len())\n\tassert.Equal(t, \"host\", e2.Type())\n}\n\nfunc TestEntityMap_PutEmpty(t *testing.T) {\n\tem := NewEntityMap()\n\te := em.PutEmpty(\"service\")\n\tretrieved, ok := em.Get(\"service\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"service\", retrieved.Type())\n\tassert.Equal(t, \"service\", e.Type())\n}\n\nfunc TestEntityMap_PutEmpty_Override(t *testing.T) {\n\tem := NewEntityMap()\n\te1 := em.PutEmpty(\"service\")\n\te1.IdentifyingAttributes().PutStr(\"service.name\", \"my-service\")\n\tassert.Equal(t, 1, em.Len())\n\n\te2 := em.PutEmpty(\"service\")\n\tassert.Equal(t, 1, em.Len())\n\n\t_, ok := e2.IdentifyingAttributes().Get(\"service.name\")\n\tassert.False(t, ok)\n}\n\nfunc TestEntityMap_EnsureCapacity(t *testing.T) {\n\tem := NewEntityMap()\n\tem.EnsureCapacity(5)\n\tfor i := range 5 {\n\t\tem.PutEmpty(fmt.Sprintf(\"type%d\", i))\n\t}\n\tassert.Equal(t, 5, em.Len())\n\n\tem.EnsureCapacity(3)\n\tassert.Equal(t, 5, em.Len())\n}\n\nfunc TestEntityMap_AttributesIsolation(t *testing.T) {\n\tem := NewEntityMap()\n\n\te1 := em.PutEmpty(\"service\")\n\te1.IdentifyingAttributes().PutStr(\"service.name\", \"my-service\")\n\n\te2 := em.PutEmpty(\"host\")\n\te2.IdentifyingAttributes().PutStr(\"host.name\", \"my-host\")\n\n\tservice, ok := em.Get(\"service\")\n\tassert.True(t, ok)\n\tval, ok := service.IdentifyingAttributes().Get(\"service.name\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"my-service\", val.Str())\n\n\thost, ok := em.Get(\"host\")\n\tassert.True(t, ok)\n\tval, ok = host.IdentifyingAttributes().Get(\"host.name\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"my-host\", val.Str())\n\n\t_, ok = service.IdentifyingAttributes().Get(\"host.name\")\n\tassert.False(t, ok)\n\n\t_, ok = host.IdentifyingAttributes().Get(\"service.name\")\n\tassert.False(t, ok)\n}\n\nfunc TestEntityMap_Get(t *testing.T) {\n\tem := NewEntityMap()\n\te1 := em.PutEmpty(\"service\")\n\te1.IdentifyingAttributes().PutStr(\"service.name\", \"my-service\")\n\n\te2, ok := em.Get(\"service\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"service\", e2.Type())\n\tval, ok := e2.IdentifyingAttributes().Get(\"service.name\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"my-service\", val.Str())\n\n\t_, ok = em.Get(\"host\")\n\tassert.False(t, ok)\n}\n\nfunc TestEntityMap_Remove(t *testing.T) {\n\tem := NewEntityMap()\n\te1 := em.PutEmpty(\"service\")\n\te1.IdentifyingAttributes().PutStr(\"service.name\", \"my-service\")\n\te1.DescriptiveAttributes().PutStr(\"service.version\", \"1.0.0\")\n\n\tassert.Equal(t, 1, em.Len())\n\tassert.Equal(t, 2, em.attributes.Len())\n\n\tremoved := em.Remove(\"service\")\n\tassert.True(t, removed)\n\tassert.Empty(t, em.Len())\n\tassert.Empty(t, em.attributes.Len())\n\n\tassert.False(t, em.Remove(\"service\"))\n}\n\nfunc TestEntityMap_All(t *testing.T) {\n\tem := NewEntityMap()\n\te1 := em.PutEmpty(\"service\")\n\te1.IdentifyingAttributes().PutStr(\"service.name\", \"my-service\")\n\n\te2 := em.PutEmpty(\"host\")\n\te2.IdentifyingAttributes().PutStr(\"host.name\", \"my-host\")\n\n\te3 := em.PutEmpty(\"process\")\n\te3.IdentifyingAttributes().PutStr(\"process.pid\", \"1234\")\n\n\ttypes := make(map[string]bool)\n\tattributes := make(map[string]string)\n\n\tfor entityType, entity := range em.All() {\n\t\ttypes[entityType] = true\n\t\tswitch entityType {\n\t\tcase \"service\":\n\t\t\tval, ok := entity.IdentifyingAttributes().Get(\"service.name\")\n\t\t\tassert.True(t, ok)\n\t\t\tattributes[entityType] = val.Str()\n\t\tcase \"host\":\n\t\t\tval, ok := entity.IdentifyingAttributes().Get(\"host.name\")\n\t\t\tassert.True(t, ok)\n\t\t\tattributes[entityType] = val.Str()\n\t\tcase \"process\":\n\t\t\tval, ok := entity.IdentifyingAttributes().Get(\"process.pid\")\n\t\t\tassert.True(t, ok)\n\t\t\tattributes[entityType] = val.Str()\n\t\t}\n\t}\n\n\tassert.Len(t, types, 3)\n\tassert.True(t, types[\"service\"])\n\tassert.True(t, types[\"host\"])\n\tassert.True(t, types[\"process\"])\n\tassert.Equal(t, \"my-service\", attributes[\"service\"])\n\tassert.Equal(t, \"my-host\", attributes[\"host\"])\n\tassert.Equal(t, \"1234\", attributes[\"process\"])\n}\n\nfunc TestEntityMap_All_Empty(t *testing.T) {\n\tem := NewEntityMap()\n\n\tcount := 0\n\tfor range em.All() {\n\t\tcount++\n\t}\n\n\tassert.Equal(t, 0, count)\n}\n\nfunc TestEntityMap_All_EarlyBreak(t *testing.T) {\n\tem := NewEntityMap()\n\tem.PutEmpty(\"service\")\n\tem.PutEmpty(\"host\")\n\tem.PutEmpty(\"process\")\n\n\tcount := 0\n\tfor range em.All() {\n\t\tcount++\n\t\tif count == 2 {\n\t\t\tbreak\n\t\t}\n\t}\n\n\tassert.Equal(t, 2, count)\n}\n"
  },
  {
    "path": "pdata/xpdata/entity/entity_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage entity\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestNewEntity(t *testing.T) {\n\te := NewEntity(\"service\")\n\tassert.Equal(t, \"service\", e.Type())\n\tassert.Empty(t, e.SchemaURL())\n}\n\nfunc TestEntity_CopyToResource(t *testing.T) {\n\te := NewEntity(\"service\")\n\te.IdentifyingAttributes().PutStr(\"service.name\", \"my-service\")\n\te.DescriptiveAttributes().PutStr(\"service.version\", \"1.0.0\")\n\n\tres := pcommon.NewResource()\n\te.CopyToResource(res)\n\n\tentities := ResourceEntities(res)\n\tcopied, ok := entities.Get(\"service\")\n\tassert.True(t, ok)\n\n\tidVal, ok := copied.IdentifyingAttributes().Get(\"service.name\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"my-service\", idVal.Str())\n\n\tdescVal, ok := copied.DescriptiveAttributes().Get(\"service.version\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"1.0.0\", descVal.Str())\n}\n\nfunc TestEntity_Type(t *testing.T) {\n\tem := NewEntityMap()\n\te := em.PutEmpty(\"service\")\n\n\tassert.Equal(t, \"service\", e.Type())\n}\n\nfunc TestEntity_SchemaURL(t *testing.T) {\n\tem := NewEntityMap()\n\te := em.PutEmpty(\"service\")\n\n\tassert.Empty(t, e.SchemaURL())\n\n\te.SetSchemaURL(\"https://opentelemetry.io/schemas/1.0.0\")\n\tassert.Equal(t, \"https://opentelemetry.io/schemas/1.0.0\", e.SchemaURL())\n\n\te.SetSchemaURL(\"https://opentelemetry.io/schemas/1.1.0\")\n\tassert.Equal(t, \"https://opentelemetry.io/schemas/1.1.0\", e.SchemaURL())\n}\n\nfunc TestEntity_IdentifyingAttributes(t *testing.T) {\n\tem := NewEntityMap()\n\te := em.PutEmpty(\"service\")\n\n\tidAttrs := e.IdentifyingAttributes()\n\tidAttrs.PutStr(\"key1\", \"value1\")\n\n\tval, ok := e.IdentifyingAttributes().Get(\"key1\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"value1\", val.Str())\n}\n\nfunc TestEntity_DescriptiveAttributes(t *testing.T) {\n\tem := NewEntityMap()\n\te := em.PutEmpty(\"service\")\n\n\tdescAttrs := e.DescriptiveAttributes()\n\tdescAttrs.PutStr(\"key1\", \"value1\")\n\n\tval, ok := e.DescriptiveAttributes().Get(\"key1\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"value1\", val.Str())\n}\n\nfunc TestEntity_IdAndDescriptionAttributes_Isolated(t *testing.T) {\n\tem := NewEntityMap()\n\te := em.PutEmpty(\"service\")\n\n\te.IdentifyingAttributes().PutStr(\"id.key\", \"id-value\")\n\te.DescriptiveAttributes().PutStr(\"desc.key\", \"desc-value\")\n\n\tval, ok := e.IdentifyingAttributes().Get(\"id.key\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"id-value\", val.Str())\n\n\t_, ok = e.IdentifyingAttributes().Get(\"desc.key\")\n\tassert.False(t, ok)\n\n\tval, ok = e.DescriptiveAttributes().Get(\"desc.key\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"desc-value\", val.Str())\n\n\t_, ok = e.DescriptiveAttributes().Get(\"id.key\")\n\tassert.False(t, ok)\n}\n\nfunc TestEntity_IdAndDescriptionAttributes_CanPut(t *testing.T) {\n\tem := NewEntityMap()\n\te := em.PutEmpty(\"service\")\n\n\te.IdentifyingAttributes().PutStr(\"shared.key\", \"id-value\")\n\n\tassert.True(t, e.IdentifyingAttributes().CanPut(\"shared.key\"))\n\tassert.False(t, e.DescriptiveAttributes().CanPut(\"shared.key\"))\n\n\te.DescriptiveAttributes().PutStr(\"shared.key\", \"desc-value\")\n\n\tval, ok := e.IdentifyingAttributes().Get(\"shared.key\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"desc-value\", val.Str())\n\n\tval, ok = e.DescriptiveAttributes().Get(\"shared.key\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"desc-value\", val.Str())\n}\n"
  },
  {
    "path": "pdata/xpdata/entity/generated_entityref.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage entity\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// This is a reference type, if passed by value and callee modifies it the\n// caller will see the modification.\n//\n// Must use NewEntityRef function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype EntityRef internal.EntityRefWrapper\n\nfunc newEntityRef(orig *internal.EntityRef, state *internal.State) EntityRef {\n\treturn EntityRef(internal.NewEntityRefWrapper(orig, state))\n}\n\n// NewEntityRef creates a new empty EntityRef.\n//\n// This must be used only in testing code. Users should use \"AppendEmpty\" when part of a Slice,\n// OR directly access the member if this is embedded in another struct.\nfunc NewEntityRef() EntityRef {\n\treturn newEntityRef(internal.NewEntityRef(), internal.NewState())\n}\n\n// MoveTo moves all properties from the current struct overriding the destination and\n// resetting the current instance to its zero value\nfunc (ms EntityRef) MoveTo(dest EntityRef) {\n\tms.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif ms.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\tinternal.DeleteEntityRef(dest.getOrig(), false)\n\t*dest.getOrig(), *ms.getOrig() = *ms.getOrig(), *dest.getOrig()\n}\n\n// SchemaUrl returns the schemaurl associated with this EntityRef.\nfunc (ms EntityRef) SchemaUrl() string {\n\treturn ms.getOrig().SchemaUrl\n}\n\n// SetSchemaUrl replaces the schemaurl associated with this EntityRef.\nfunc (ms EntityRef) SetSchemaUrl(v string) {\n\tms.getState().AssertMutable()\n\tms.getOrig().SchemaUrl = v\n}\n\n// Type returns the type associated with this EntityRef.\nfunc (ms EntityRef) Type() string {\n\treturn ms.getOrig().Type\n}\n\n// SetType replaces the type associated with this EntityRef.\nfunc (ms EntityRef) SetType(v string) {\n\tms.getState().AssertMutable()\n\tms.getOrig().Type = v\n}\n\n// IdKeys returns the IdKeys associated with this EntityRef.\nfunc (ms EntityRef) IdKeys() pcommon.StringSlice {\n\treturn pcommon.StringSlice(internal.NewStringSliceWrapper(&ms.getOrig().IdKeys, ms.getState()))\n}\n\n// DescriptionKeys returns the DescriptionKeys associated with this EntityRef.\nfunc (ms EntityRef) DescriptionKeys() pcommon.StringSlice {\n\treturn pcommon.StringSlice(internal.NewStringSliceWrapper(&ms.getOrig().DescriptionKeys, ms.getState()))\n}\n\n// CopyTo copies all properties from the current struct overriding the destination.\nfunc (ms EntityRef) CopyTo(dest EntityRef) {\n\tdest.getState().AssertMutable()\n\tinternal.CopyEntityRef(dest.getOrig(), ms.getOrig())\n}\n\nfunc (ms EntityRef) getOrig() *internal.EntityRef {\n\treturn internal.GetEntityRefOrig(internal.EntityRefWrapper(ms))\n}\n\nfunc (ms EntityRef) getState() *internal.State {\n\treturn internal.GetEntityRefState(internal.EntityRefWrapper(ms))\n}\n"
  },
  {
    "path": "pdata/xpdata/entity/generated_entityref_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage entity\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestEntityRef_MoveTo(t *testing.T) {\n\tms := generateTestEntityRef()\n\tdest := NewEntityRef()\n\tms.MoveTo(dest)\n\tassert.Equal(t, NewEntityRef(), ms)\n\tassert.Equal(t, generateTestEntityRef(), dest)\n\tdest.MoveTo(dest)\n\tassert.Equal(t, generateTestEntityRef(), dest)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.MoveTo(newEntityRef(internal.NewEntityRef(), sharedState)) })\n\tassert.Panics(t, func() { newEntityRef(internal.NewEntityRef(), sharedState).MoveTo(dest) })\n}\n\nfunc TestEntityRef_CopyTo(t *testing.T) {\n\tms := NewEntityRef()\n\torig := NewEntityRef()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\torig = generateTestEntityRef()\n\torig.CopyTo(ms)\n\tassert.Equal(t, orig, ms)\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { ms.CopyTo(newEntityRef(internal.NewEntityRef(), sharedState)) })\n}\n\nfunc TestEntityRef_SchemaUrl(t *testing.T) {\n\tms := NewEntityRef()\n\tassert.Empty(t, ms.SchemaUrl())\n\tms.SetSchemaUrl(\"test_schemaurl\")\n\tassert.Equal(t, \"test_schemaurl\", ms.SchemaUrl())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newEntityRef(internal.NewEntityRef(), sharedState).SetSchemaUrl(\"test_schemaurl\") })\n}\n\nfunc TestEntityRef_Type(t *testing.T) {\n\tms := NewEntityRef()\n\tassert.Empty(t, ms.Type())\n\tms.SetType(\"test_type\")\n\tassert.Equal(t, \"test_type\", ms.Type())\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tassert.Panics(t, func() { newEntityRef(internal.NewEntityRef(), sharedState).SetType(\"test_type\") })\n}\n\nfunc TestEntityRef_IdKeys(t *testing.T) {\n\tms := NewEntityRef()\n\tassert.Equal(t, pcommon.NewStringSlice(), ms.IdKeys())\n\tms.getOrig().IdKeys = internal.GenTestStringSlice()\n\tassert.Equal(t, pcommon.StringSlice(internal.GenTestStringSliceWrapper()), ms.IdKeys())\n}\n\nfunc TestEntityRef_DescriptionKeys(t *testing.T) {\n\tms := NewEntityRef()\n\tassert.Equal(t, pcommon.NewStringSlice(), ms.DescriptionKeys())\n\tms.getOrig().DescriptionKeys = internal.GenTestStringSlice()\n\tassert.Equal(t, pcommon.StringSlice(internal.GenTestStringSliceWrapper()), ms.DescriptionKeys())\n}\n\nfunc generateTestEntityRef() EntityRef {\n\treturn newEntityRef(internal.GenTestEntityRef(), internal.NewState())\n}\n"
  },
  {
    "path": "pdata/xpdata/entity/generated_entityrefslice.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage entity\n\nimport (\n\t\"iter\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// EntityRefSlice logically represents a slice of EntityRef.\n//\n// This is a reference type. If passed by value and callee modifies it, the\n// caller will see the modification.\n//\n// Must use NewEntityRefSlice function to create new instances.\n// Important: zero-initialized instance is not valid for use.\ntype EntityRefSlice internal.EntityRefSliceWrapper\n\nfunc newEntityRefSlice(orig *[]*internal.EntityRef, state *internal.State) EntityRefSlice {\n\treturn EntityRefSlice(internal.NewEntityRefSliceWrapper(orig, state))\n}\n\n// NewEntityRefSlice creates a EntityRefSliceWrapper with 0 elements.\n// Can use \"EnsureCapacity\" to initialize with a given capacity.\nfunc NewEntityRefSlice() EntityRefSlice {\n\torig := []*internal.EntityRef(nil)\n\treturn newEntityRefSlice(&orig, internal.NewState())\n}\n\n// Len returns the number of elements in the slice.\n//\n// Returns \"0\" for a newly instance created with \"NewEntityRefSlice()\".\nfunc (es EntityRefSlice) Len() int {\n\treturn len(*es.getOrig())\n}\n\n// At returns the element at the given index.\n//\n// This function is used mostly for iterating over all the values in the slice:\n//\n//\tfor i := 0; i < es.Len(); i++ {\n//\t    e := es.At(i)\n//\t    ... // Do something with the element\n//\t}\nfunc (es EntityRefSlice) At(i int) EntityRef {\n\treturn newEntityRef((*es.getOrig())[i], es.getState())\n}\n\n// All returns an iterator over index-value pairs in the slice.\n//\n//\tfor i, v := range es.All() {\n//\t    ... // Do something with index-value pair\n//\t}\nfunc (es EntityRefSlice) All() iter.Seq2[int, EntityRef] {\n\treturn func(yield func(int, EntityRef) bool) {\n\t\tfor i := 0; i < es.Len(); i++ {\n\t\t\tif !yield(i, es.At(i)) {\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}\n}\n\n// EnsureCapacity is an operation that ensures the slice has at least the specified capacity.\n// 1. If the newCap <= cap then no change in capacity.\n// 2. If the newCap > cap then the slice capacity will be expanded to equal newCap.\n//\n// Here is how a new EntityRefSlice can be initialized:\n//\n//\tes := NewEntityRefSlice()\n//\tes.EnsureCapacity(4)\n//\tfor i := 0; i < 4; i++ {\n//\t    e := es.AppendEmpty()\n//\t    // Here should set all the values for e.\n//\t}\nfunc (es EntityRefSlice) EnsureCapacity(newCap int) {\n\tes.getState().AssertMutable()\n\toldCap := cap(*es.getOrig())\n\tif newCap <= oldCap {\n\t\treturn\n\t}\n\n\tnewOrig := make([]*internal.EntityRef, len(*es.getOrig()), newCap)\n\tcopy(newOrig, *es.getOrig())\n\t*es.getOrig() = newOrig\n}\n\n// AppendEmpty will append to the end of the slice an empty EntityRef.\n// It returns the newly added EntityRef.\nfunc (es EntityRefSlice) AppendEmpty() EntityRef {\n\tes.getState().AssertMutable()\n\t*es.getOrig() = append(*es.getOrig(), internal.NewEntityRef())\n\treturn es.At(es.Len() - 1)\n}\n\n// MoveAndAppendTo moves all elements from the current slice and appends them to the dest.\n// The current slice will be cleared.\nfunc (es EntityRefSlice) MoveAndAppendTo(dest EntityRefSlice) {\n\tes.getState().AssertMutable()\n\tdest.getState().AssertMutable()\n\t// If they point to the same data, they are the same, nothing to do.\n\tif es.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\tif *dest.getOrig() == nil {\n\t\t// We can simply move the entire vector and avoid any allocations.\n\t\t*dest.getOrig() = *es.getOrig()\n\t} else {\n\t\t*dest.getOrig() = append(*dest.getOrig(), *es.getOrig()...)\n\t}\n\t*es.getOrig() = nil\n}\n\n// RemoveIf calls f sequentially for each element present in the slice.\n// If f returns true, the element is removed from the slice.\nfunc (es EntityRefSlice) RemoveIf(f func(EntityRef) bool) {\n\tes.getState().AssertMutable()\n\tnewLen := 0\n\tfor i := 0; i < len(*es.getOrig()); i++ {\n\t\tif f(es.At(i)) {\n\t\t\tinternal.DeleteEntityRef((*es.getOrig())[i], true)\n\t\t\t(*es.getOrig())[i] = nil\n\n\t\t\tcontinue\n\t\t}\n\t\tif newLen == i {\n\t\t\t// Nothing to move, element is at the right place.\n\t\t\tnewLen++\n\t\t\tcontinue\n\t\t}\n\t\t(*es.getOrig())[newLen] = (*es.getOrig())[i]\n\t\t// Cannot delete here since we just move the data(or pointer to data) to a different position in the slice.\n\t\t(*es.getOrig())[i] = nil\n\t\tnewLen++\n\t}\n\t*es.getOrig() = (*es.getOrig())[:newLen]\n}\n\n// CopyTo copies all elements from the current slice overriding the destination.\nfunc (es EntityRefSlice) CopyTo(dest EntityRefSlice) {\n\tdest.getState().AssertMutable()\n\tif es.getOrig() == dest.getOrig() {\n\t\treturn\n\t}\n\t*dest.getOrig() = internal.CopyEntityRefPtrSlice(*dest.getOrig(), *es.getOrig())\n}\n\n// Sort sorts the EntityRef elements within EntityRefSlice given the\n// provided less function so that two instances of EntityRefSlice\n// can be compared.\nfunc (es EntityRefSlice) Sort(less func(a, b EntityRef) bool) {\n\tes.getState().AssertMutable()\n\tsort.SliceStable(*es.getOrig(), func(i, j int) bool { return less(es.At(i), es.At(j)) })\n}\n\nfunc (ms EntityRefSlice) getOrig() *[]*internal.EntityRef {\n\treturn internal.GetEntityRefSliceOrig(internal.EntityRefSliceWrapper(ms))\n}\n\nfunc (ms EntityRefSlice) getState() *internal.State {\n\treturn internal.GetEntityRefSliceState(internal.EntityRefSliceWrapper(ms))\n}\n"
  },
  {
    "path": "pdata/xpdata/entity/generated_entityrefslice_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Code generated by \"internal/cmd/pdatagen/main.go\". DO NOT EDIT.\n// To regenerate this file run \"make genpdata\".\n\npackage entity\n\nimport (\n\t\"testing\"\n\t\"unsafe\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestEntityRefSlice(t *testing.T) {\n\tes := NewEntityRefSlice()\n\tassert.Equal(t, 0, es.Len())\n\tes = newEntityRefSlice(&[]*internal.EntityRef{}, internal.NewState())\n\tassert.Equal(t, 0, es.Len())\n\n\temptyVal := NewEntityRef()\n\ttestVal := EntityRef(internal.GenTestEntityRefWrapper())\n\tfor i := 0; i < 7; i++ {\n\t\tes.AppendEmpty()\n\t\tassert.Equal(t, emptyVal, es.At(i))\n\t\t(*es.getOrig())[i] = internal.GenTestEntityRef()\n\t\tassert.Equal(t, testVal, es.At(i))\n\t}\n\tassert.Equal(t, 7, es.Len())\n}\n\nfunc TestEntityRefSliceReadOnly(t *testing.T) {\n\tsharedState := internal.NewState()\n\tsharedState.MarkReadOnly()\n\tes := newEntityRefSlice(&[]*internal.EntityRef{}, sharedState)\n\tassert.Equal(t, 0, es.Len())\n\tassert.Panics(t, func() { es.AppendEmpty() })\n\tassert.Panics(t, func() { es.EnsureCapacity(2) })\n\tes2 := NewEntityRefSlice()\n\tes.CopyTo(es2)\n\tassert.Panics(t, func() { es2.CopyTo(es) })\n\tassert.Panics(t, func() { es.MoveAndAppendTo(es2) })\n\tassert.Panics(t, func() { es2.MoveAndAppendTo(es) })\n}\n\nfunc TestEntityRefSlice_CopyTo(t *testing.T) {\n\tdest := NewEntityRefSlice()\n\tsrc := generateTestEntityRefSlice()\n\tsrc.CopyTo(dest)\n\tassert.Equal(t, generateTestEntityRefSlice(), dest)\n\tdest.CopyTo(dest)\n\tassert.Equal(t, generateTestEntityRefSlice(), dest)\n}\n\nfunc TestEntityRefSlice_EnsureCapacity(t *testing.T) {\n\tes := generateTestEntityRefSlice()\n\n\t// Test ensure smaller capacity.\n\tconst ensureSmallLen = 4\n\tes.EnsureCapacity(ensureSmallLen)\n\tassert.Less(t, ensureSmallLen, es.Len())\n\tassert.Equal(t, es.Len(), cap(*es.getOrig()))\n\tassert.Equal(t, generateTestEntityRefSlice(), es)\n\n\t// Test ensure larger capacity\n\tconst ensureLargeLen = 9\n\tes.EnsureCapacity(ensureLargeLen)\n\tassert.Less(t, generateTestEntityRefSlice().Len(), ensureLargeLen)\n\tassert.Equal(t, ensureLargeLen, cap(*es.getOrig()))\n\tassert.Equal(t, generateTestEntityRefSlice(), es)\n}\n\nfunc TestEntityRefSlice_MoveAndAppendTo(t *testing.T) {\n\t// Test MoveAndAppendTo to empty\n\texpectedSlice := generateTestEntityRefSlice()\n\tdest := NewEntityRefSlice()\n\tsrc := generateTestEntityRefSlice()\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestEntityRefSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo empty slice\n\tsrc.MoveAndAppendTo(dest)\n\tassert.Equal(t, generateTestEntityRefSlice(), dest)\n\tassert.Equal(t, 0, src.Len())\n\tassert.Equal(t, expectedSlice.Len(), dest.Len())\n\n\t// Test MoveAndAppendTo not empty slice\n\tgenerateTestEntityRefSlice().MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n\n\tdest.MoveAndAppendTo(dest)\n\tassert.Equal(t, 2*expectedSlice.Len(), dest.Len())\n\tfor i := 0; i < expectedSlice.Len(); i++ {\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i))\n\t\tassert.Equal(t, expectedSlice.At(i), dest.At(i+expectedSlice.Len()))\n\t}\n}\n\nfunc TestEntityRefSlice_RemoveIf(t *testing.T) {\n\t// Test RemoveIf on empty slice\n\temptySlice := NewEntityRefSlice()\n\temptySlice.RemoveIf(func(el EntityRef) bool {\n\t\tt.Fail()\n\t\treturn false\n\t})\n\n\t// Test RemoveIf\n\tfiltered := generateTestEntityRefSlice()\n\tpos := 0\n\tfiltered.RemoveIf(func(el EntityRef) bool {\n\t\tpos++\n\t\treturn pos%2 == 1\n\t})\n\tassert.Equal(t, 2, filtered.Len())\n}\n\nfunc TestEntityRefSlice_RemoveIfAll(t *testing.T) {\n\tgot := generateTestEntityRefSlice()\n\tgot.RemoveIf(func(el EntityRef) bool {\n\t\treturn true\n\t})\n\tassert.Equal(t, 0, got.Len())\n}\n\nfunc TestEntityRefSliceAll(t *testing.T) {\n\tms := generateTestEntityRefSlice()\n\tassert.NotEmpty(t, ms.Len())\n\n\tvar c int\n\tfor i, v := range ms.All() {\n\t\tassert.Equal(t, ms.At(i), v, \"element should match\")\n\t\tc++\n\t}\n\tassert.Equal(t, ms.Len(), c, \"All elements should have been visited\")\n}\n\nfunc TestEntityRefSlice_Sort(t *testing.T) {\n\tes := generateTestEntityRefSlice()\n\tes.Sort(func(a, b EntityRef) bool {\n\t\treturn uintptr(unsafe.Pointer(a.getOrig())) < uintptr(unsafe.Pointer(b.getOrig()))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Less(t, uintptr(unsafe.Pointer(es.At(i-1).getOrig())), uintptr(unsafe.Pointer(es.At(i).getOrig())))\n\t}\n\tes.Sort(func(a, b EntityRef) bool {\n\t\treturn uintptr(unsafe.Pointer(a.getOrig())) > uintptr(unsafe.Pointer(b.getOrig()))\n\t})\n\tfor i := 1; i < es.Len(); i++ {\n\t\tassert.Greater(t, uintptr(unsafe.Pointer(es.At(i-1).getOrig())), uintptr(unsafe.Pointer(es.At(i).getOrig())))\n\t}\n}\n\nfunc generateTestEntityRefSlice() EntityRefSlice {\n\tms := NewEntityRefSlice()\n\t*ms.getOrig() = internal.GenTestEntityRefPtrSlice()\n\treturn ms\n}\n"
  },
  {
    "path": "pdata/xpdata/entity/resource_entities.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage entity // import \"go.opentelemetry.io/collector/pdata/xpdata/entity\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// ResourceEntityRefs returns the EntityRefs associated with this Resource.\n// Once EntityRefs is stabilized in the proto definition,\n// this function will be available in the pcommon package as part of a Resource method.\nfunc ResourceEntityRefs(res pcommon.Resource) EntityRefSlice {\n\tir := internal.ResourceWrapper(res)\n\treturn newEntityRefSlice(&internal.GetResourceOrig(ir).EntityRefs, internal.GetResourceState(ir))\n}\n\n// ResourceEntities returns the Entities associated with this Resource.\n// The returned EntityMap shares the resource's attributes map, so modifications\n// to entity attributes are immediately reflected in the resource.\nfunc ResourceEntities(res pcommon.Resource) EntityMap {\n\treturn EntityMap{\n\t\trefs:       ResourceEntityRefs(res),\n\t\tattributes: res.Attributes(),\n\t}\n}\n"
  },
  {
    "path": "pdata/xpdata/entity/resource_entities_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage entity\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestResourceEntityRefs(t *testing.T) {\n\tres := pcommon.NewResource()\n\trefs := ResourceEntityRefs(res)\n\tassert.Equal(t, 0, refs.Len())\n\n\tref := refs.AppendEmpty()\n\tref.SetType(\"service\")\n\n\tassert.Equal(t, 1, refs.Len())\n\tassert.Equal(t, \"service\", refs.At(0).Type())\n}\n\nfunc TestResourceEntities(t *testing.T) {\n\tres := pcommon.NewResource()\n\tentities := ResourceEntities(res)\n\tassert.Equal(t, 0, entities.Len())\n\n\te := entities.PutEmpty(\"service\")\n\n\tassert.Equal(t, 1, entities.Len())\n\tretrieved, ok := entities.Get(\"service\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"service\", retrieved.Type())\n\tassert.Equal(t, \"service\", e.Type())\n}\n"
  },
  {
    "path": "pdata/xpdata/fuzz_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xpdata\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n)\n\nvar unexpectedBytes = \"expected the same bytes from unmarshaling and marshaling.\"\n\nfunc FuzzUnmarshalJSONValue(f *testing.F) {\n\tf.Fuzz(func(t *testing.T, data []byte) {\n\t\tu1 := &JSONUnmarshaler{}\n\t\tld1, err := u1.UnmarshalValue(data)\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tm1 := &JSONMarshaler{}\n\t\tb1, err := m1.MarshalValue(ld1)\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\tu2 := &JSONUnmarshaler{}\n\t\tld2, err := u2.UnmarshalValue(b1)\n\t\trequire.NoError(t, err, \"failed to unmarshal valid bytes\")\n\t\tm2 := &JSONMarshaler{}\n\t\tb2, err := m2.MarshalValue(ld2)\n\t\trequire.NoError(t, err, \"failed to marshal valid struct\")\n\n\t\trequire.True(t, bytes.Equal(b1, b2), \"%s. \\nexpected %d but got %d\\n\", unexpectedBytes, b1, b2)\n\t})\n}\n"
  },
  {
    "path": "pdata/xpdata/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage xpdata\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "pdata/xpdata/go.mod",
    "content": "module go.opentelemetry.io/collector/pdata/xpdata\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/client v1.54.0\n\tgo.opentelemetry.io/collector/featuregate v1.54.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.opentelemetry.io/otel/trace v1.42.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/pdata => ..\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../pprofile\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../testdata\n\nreplace go.opentelemetry.io/collector/client => ../../client\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n"
  },
  {
    "path": "pdata/xpdata/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=\ngithub.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "pdata/xpdata/internal/metadata/generated_feature_gates.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\nvar PdataEnableRefCountingFeatureGate = featuregate.GlobalRegistry().MustRegister(\n\t\"pdata.enableRefCounting\",\n\tfeaturegate.StageBeta,\n\tfeaturegate.WithRegisterDescription(\"When enabled, enables using ref counting to know when pdata memory can be freed up. This featuregate is here only to protect if unexpected bugs happens because of ref counting logic.\"),\n\tfeaturegate.WithRegisterReferenceURL(\"https://github.com/open-telemetry/opentelemetry-collector/issues/13631\"),\n\tfeaturegate.WithRegisterFromVersion(\"v0.133.0\"),\n)\n"
  },
  {
    "path": "pdata/xpdata/json.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xpdata // import \"go.opentelemetry.io/collector/pdata/xpdata\"\n\nimport (\n\t\"slices\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/internal/json\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\ntype JSONMarshaler struct{}\n\nfunc (*JSONMarshaler) MarshalValue(value pcommon.Value) ([]byte, error) {\n\tav := internal.GetValueOrig(internal.ValueWrapper(value))\n\tdest := json.BorrowStream(nil)\n\tdefer json.ReturnStream(dest)\n\tav.MarshalJSON(dest)\n\tif dest.Error() != nil {\n\t\treturn nil, dest.Error()\n\t}\n\treturn slices.Clone(dest.Buffer()), nil\n}\n\ntype JSONUnmarshaler struct{}\n\nfunc (*JSONUnmarshaler) UnmarshalValue(buf []byte) (pcommon.Value, error) {\n\titer := json.BorrowIterator(buf)\n\tdefer json.ReturnIterator(iter)\n\tvalue := &internal.AnyValue{}\n\tvalue.UnmarshalJSON(iter)\n\tif iter.Error() != nil {\n\t\treturn pcommon.NewValueEmpty(), iter.Error()\n\t}\n\treturn pcommon.Value(internal.NewValueWrapper(value, internal.NewState())), nil\n}\n"
  },
  {
    "path": "pdata/xpdata/json_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xpdata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestMarshalAndUnmarshalValue(t *testing.T) {\n\tfor name, src := range genTestEncodingValues() {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tm := &JSONMarshaler{}\n\t\t\tb, err := m.MarshalValue(src)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tu := &JSONUnmarshaler{}\n\t\t\tdest, err := u.UnmarshalValue(b)\n\t\t\trequire.NoError(t, err)\n\n\t\t\trequire.Equal(t, src, dest)\n\t\t})\n\t}\n}\n\nfunc TestUnmarshalValueUnknown(t *testing.T) {\n\tm := &JSONUnmarshaler{}\n\n\tb, err := m.UnmarshalValue([]byte(`{\"unknown\": \"string\"}`))\n\trequire.NoError(t, err)\n\tassert.Equal(t, pcommon.NewValueEmpty(), b)\n}\n\nfunc genTestEncodingValues() map[string]pcommon.Value {\n\treturn map[string]pcommon.Value{\n\t\t\"empty\":               pcommon.NewValueEmpty(),\n\t\t\"StringValue/default\": pcommon.NewValueStr(\"\"),\n\t\t\"StringValue/test\":    pcommon.NewValueStr(\"test_stringvalue\"),\n\t\t\"BoolValue/default\":   pcommon.NewValueBool(false),\n\t\t\"BoolValue/test\":      pcommon.NewValueBool(true),\n\t\t\"IntValue/default\":    pcommon.NewValueInt(0),\n\t\t\"IntValue/test\":       pcommon.NewValueInt(13),\n\t\t\"DoubleValue/default\": pcommon.NewValueDouble(0),\n\t\t\"DoubleValue/test\":    pcommon.NewValueDouble(3.1415926),\n\t\t\"ArrayValue/default\":  pcommon.NewValueSlice(),\n\t\t\"ArrayValue/test\": func() pcommon.Value {\n\t\t\ts := pcommon.NewValueSlice()\n\t\t\ts.Slice().AppendEmpty().SetStr(\"test1\")\n\t\t\ts.Slice().AppendEmpty().SetInt(13)\n\t\t\ts.Slice().AppendEmpty().SetBool(true)\n\t\t\ts.Slice().AppendEmpty().SetDouble(3.1415926)\n\n\t\t\ts1 := s.Slice().AppendEmpty().SetEmptySlice()\n\t\t\ts1.AppendEmpty().SetStr(\"nested\")\n\n\t\t\tm := s.Slice().AppendEmpty().SetEmptyMap()\n\t\t\tm.PutStr(\"key1\", \"value1\")\n\n\t\t\treturn s\n\t\t}(),\n\t\t\"KvlistValue/default\": pcommon.NewValueMap(),\n\t\t\"KvlistValue/test\": func() pcommon.Value {\n\t\t\tm := pcommon.NewValueMap()\n\t\t\tm.Map().PutStr(\"key1\", \"value1\")\n\t\t\tm.Map().PutInt(\"key2\", 13)\n\t\t\tm.Map().PutBool(\"key3\", true)\n\t\t\tm.Map().PutDouble(\"key4\", 3.1415926)\n\t\t\tm.Map().PutEmpty(\"key5\").SetStr(\"value5\")\n\n\t\t\ts := m.Map().PutEmptySlice(\"key6\")\n\t\t\ts.AppendEmpty().SetStr(\"nested1\")\n\n\t\t\tm1 := m.Map().PutEmptyMap(\"key6\")\n\t\t\tm1.PutStr(\"nestedKey1\", \"nestedValue1\")\n\n\t\t\treturn m\n\t\t}(),\n\t\t\"BytesValue/test\": func() pcommon.Value {\n\t\t\tv := pcommon.NewValueBytes()\n\t\t\tv.Bytes().FromRaw([]byte{1, 2, 3})\n\t\t\treturn v\n\t\t}(),\n\t}\n}\n"
  },
  {
    "path": "pdata/xpdata/map_builder.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xpdata // import \"go.opentelemetry.io/collector/pdata/xpdata\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// MapBuilder is an experimental struct which can be used to create a pcommon.Map more efficiently\n// than by repeated use of the Put family of methods, which check for duplicate keys on every call\n// (a linear time operation).\n// A zero-initialized MapBuilder is ready for use.\ntype MapBuilder struct {\n\tstate internal.State\n\tpairs []internal.KeyValue\n}\n\n// EnsureCapacity increases the capacity of this MapBuilder instance, if necessary,\n// to ensure that it can hold at least the number of elements specified by the capacity argument.\nfunc (mb *MapBuilder) EnsureCapacity(capacity int) {\n\toldValues := mb.pairs\n\tif capacity <= cap(oldValues) {\n\t\treturn\n\t}\n\tmb.pairs = make([]internal.KeyValue, len(oldValues), capacity)\n\tcopy(mb.pairs, oldValues)\n}\n\nfunc (mb *MapBuilder) getValue(i int) pcommon.Value {\n\treturn pcommon.Value(internal.NewValueWrapper(&mb.pairs[i].Value, &mb.state))\n}\n\n// AppendEmpty appends a key/value pair to the MapBuilder and return the inserted value.\n// This method does not check for duplicate keys and has an amortized constant time complexity.\nfunc (mb *MapBuilder) AppendEmpty(k string) pcommon.Value {\n\tmb.pairs = append(mb.pairs, internal.KeyValue{Key: k})\n\treturn mb.getValue(len(mb.pairs) - 1)\n}\n\n// UnsafeIntoMap transfers the contents of a MapBuilder into a MapWrapper, without checking for duplicate keys.\n// If the MapBuilder contains duplicate keys, the behavior of the resulting MapWrapper is unspecified.\n// This operation has constant time complexity and makes no allocations.\n// After this operation, the MapBuilder is reset to an empty state.\nfunc (mb *MapBuilder) UnsafeIntoMap(m pcommon.Map) {\n\tinternal.GetMapState(internal.MapWrapper(m)).AssertMutable()\n\t*internal.GetMapOrig(internal.MapWrapper(m)) = mb.pairs\n\tmb.pairs = nil\n}\n"
  },
  {
    "path": "pdata/xpdata/map_builder_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xpdata_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata\"\n)\n\nfunc TestMapBuilder(t *testing.T) {\n\tvar mb xpdata.MapBuilder\n\tmb.EnsureCapacity(3)\n\tmb.AppendEmpty(\"key1\").SetStr(\"val\")\n\tmb.AppendEmpty(\"key2\").SetInt(42)\n\n\tm := pcommon.NewMap()\n\tmb.UnsafeIntoMap(m)\n\n\tassert.Equal(t, 2, m.Len())\n\tval, ok := m.Get(\"key1\")\n\tassert.True(t, ok && val.Type() == pcommon.ValueTypeStr && val.Str() == \"val\")\n\tval, ok = m.Get(\"key2\")\n\tassert.True(t, ok && val.Type() == pcommon.ValueTypeInt && val.Int() == 42)\n}\n"
  },
  {
    "path": "pdata/xpdata/metadata.yaml",
    "content": "type: xpdata\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  stability:\n    development: [traces, metrics, logs, profiles]\n\nfeature_gates:\n  - id: pdata.enableRefCounting\n    description: 'When enabled, enables using ref counting to know when pdata memory can be freed up. This featuregate is here only to protect if unexpected bugs happens because of ref counting logic.'\n    stage: beta\n    from_version: 'v0.133.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/issues/13631'\n"
  },
  {
    "path": "pdata/xpdata/pref/gate.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pref // import \"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/internal/metadata\"\n)\n\n// UseProtoPooling temporary expose public to allow testing.\nvar UseProtoPooling = metadata.PdataUseProtoPoolingFeatureGate\n"
  },
  {
    "path": "pdata/xpdata/pref/logs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pref // import \"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n\nimport (\n\t\"reflect\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\tpmetadata \"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/internal/metadata\"\n)\n\n// MarkPipelineOwnedLogs marks the plog.Logs data as owned by the pipeline, returns true if the data were\n// previously not owned by the pipeline, otherwise false.\nfunc MarkPipelineOwnedLogs(ld plog.Logs) bool {\n\treturn internal.GetLogsState(internal.LogsWrapper(ld)).MarkPipelineOwned()\n}\n\nfunc RefLogs(ld plog.Logs) {\n\tif metadata.PdataEnableRefCountingFeatureGate.IsEnabled() {\n\t\tinternal.GetLogsState(internal.LogsWrapper(ld)).Ref()\n\t}\n}\n\nfunc UnrefLogs(ld plog.Logs) {\n\tif metadata.PdataEnableRefCountingFeatureGate.IsEnabled() {\n\t\tif !internal.GetLogsState(internal.LogsWrapper(ld)).Unref() {\n\t\t\treturn\n\t\t}\n\t\t// Don't call DeleteExportLogsServiceRequest without the gate because we reset the data and that may still cause issues.\n\t\tif pmetadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tinternal.DeleteExportLogsServiceRequest(internal.GetLogsOrig(internal.LogsWrapper(ld)), true)\n\t\t}\n\t}\n}\n\n// TODO: Generate this in pdata.\n\nfunc EqualLogs(ld1, ld2 plog.Logs) bool {\n\treturn reflect.DeepEqual(internal.GetLogsOrig(internal.LogsWrapper(ld1)), internal.GetLogsOrig(internal.LogsWrapper(ld2)))\n}\n"
  },
  {
    "path": "pdata/xpdata/pref/metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pref // import \"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n\nimport (\n\t\"reflect\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\tpmetadata \"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/internal/metadata\"\n)\n\n// MarkPipelineOwnedMetrics marks the pmetric.Metrics data as owned by the pipeline, returns true if the data were\n// previously not owned by the pipeline, otherwise false.\nfunc MarkPipelineOwnedMetrics(md pmetric.Metrics) bool {\n\treturn internal.GetMetricsState(internal.MetricsWrapper(md)).MarkPipelineOwned()\n}\n\nfunc RefMetrics(md pmetric.Metrics) {\n\tif metadata.PdataEnableRefCountingFeatureGate.IsEnabled() {\n\t\tinternal.GetMetricsState(internal.MetricsWrapper(md)).Ref()\n\t}\n}\n\nfunc UnrefMetrics(md pmetric.Metrics) {\n\tif metadata.PdataEnableRefCountingFeatureGate.IsEnabled() {\n\t\tif !internal.GetMetricsState(internal.MetricsWrapper(md)).Unref() {\n\t\t\treturn\n\t\t}\n\t\t// Don't call DeleteExportLogsServiceRequest without the gate because we reset the data and that may still cause issues.\n\t\tif pmetadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tinternal.DeleteExportMetricsServiceRequest(internal.GetMetricsOrig(internal.MetricsWrapper(md)), true)\n\t\t}\n\t}\n}\n\n// TODO: Generate this in pdata.\n\nfunc EqualMetrics(md1, md2 pmetric.Metrics) bool {\n\treturn reflect.DeepEqual(internal.GetMetricsOrig(internal.MetricsWrapper(md1)), internal.GetMetricsOrig(internal.MetricsWrapper(md2)))\n}\n"
  },
  {
    "path": "pdata/xpdata/pref/profiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pref // import \"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n\nimport (\n\t\"reflect\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\tpmetadata \"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/internal/metadata\"\n)\n\n// MarkPipelineOwnedProfiles marks the pprofile.Profiles data as owned by the pipeline, returns true if the data were\n// previously not owned by the pipeline, otherwise false.\nfunc MarkPipelineOwnedProfiles(pd pprofile.Profiles) bool {\n\treturn internal.GetProfilesState(internal.ProfilesWrapper(pd)).MarkPipelineOwned()\n}\n\nfunc RefProfiles(pd pprofile.Profiles) {\n\tif metadata.PdataEnableRefCountingFeatureGate.IsEnabled() {\n\t\tinternal.GetProfilesState(internal.ProfilesWrapper(pd)).Ref()\n\t}\n}\n\nfunc UnrefProfiles(pd pprofile.Profiles) {\n\tif metadata.PdataEnableRefCountingFeatureGate.IsEnabled() {\n\t\tif !internal.GetProfilesState(internal.ProfilesWrapper(pd)).Unref() {\n\t\t\treturn\n\t\t}\n\t\t// Don't call DeleteExportLogsServiceRequest without the gate because we reset the data and that may still cause issues.\n\t\tif pmetadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tinternal.DeleteExportProfilesServiceRequest(internal.GetProfilesOrig(internal.ProfilesWrapper(pd)), true)\n\t\t}\n\t}\n}\n\n// TODO: Generate this in pdata.\n\nfunc EqualProfiles(pd1, pd2 pprofile.Profiles) bool {\n\treturn reflect.DeepEqual(internal.GetProfilesOrig(internal.ProfilesWrapper(pd1)), internal.GetProfilesOrig(internal.ProfilesWrapper(pd2)))\n}\n"
  },
  {
    "path": "pdata/xpdata/pref/traces.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pref // import \"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n\nimport (\n\t\"reflect\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\tpmetadata \"go.opentelemetry.io/collector/pdata/internal/metadata\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/internal/metadata\"\n)\n\n// MarkPipelineOwnedTraces marks the ptrace.Traces data as owned by the pipeline, returns true if the data were\n// previously not owned by the pipeline, otherwise false.\nfunc MarkPipelineOwnedTraces(td ptrace.Traces) bool {\n\treturn internal.GetTracesState(internal.TracesWrapper(td)).MarkPipelineOwned()\n}\n\nfunc RefTraces(td ptrace.Traces) {\n\tinternal.GetTracesState(internal.TracesWrapper(td)).Ref()\n}\n\nfunc UnrefTraces(td ptrace.Traces) {\n\tif metadata.PdataEnableRefCountingFeatureGate.IsEnabled() {\n\t\tif !internal.GetTracesState(internal.TracesWrapper(td)).Unref() {\n\t\t\treturn\n\t\t}\n\t\t// Don't call DeleteExportLogsServiceRequest without the gate because we reset the data and that may still cause issues.\n\t\tif pmetadata.PdataUseProtoPoolingFeatureGate.IsEnabled() {\n\t\t\tinternal.DeleteExportTraceServiceRequest(internal.GetTracesOrig(internal.TracesWrapper(td)), true)\n\t\t}\n\t}\n}\n\n// TODO: Generate this in pdata.\n\nfunc EqualTraces(td1, td2 ptrace.Traces) bool {\n\treturn reflect.DeepEqual(internal.GetTracesOrig(internal.TracesWrapper(td1)), internal.GetTracesOrig(internal.TracesWrapper(td2)))\n}\n"
  },
  {
    "path": "pdata/xpdata/request/context.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage request // import \"go.opentelemetry.io/collector/pdata/xpdata/request\"\n\nimport (\n\t\"context\"\n\t\"net\"\n\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/client\"\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\n// encodeContext encodes the context into a map of strings.\nfunc encodeContext(ctx context.Context) *internal.RequestContext {\n\trc := internal.RequestContext{}\n\tencodeSpanContext(ctx, &rc)\n\tencodeClientMetadata(ctx, &rc)\n\tencodeClientAddress(ctx, &rc)\n\treturn &rc\n}\n\nfunc encodeSpanContext(ctx context.Context, rc *internal.RequestContext) {\n\tspanCtx := trace.SpanContextFromContext(ctx)\n\tif !spanCtx.IsValid() {\n\t\treturn\n\t}\n\trc.SpanContext = &internal.SpanContext{\n\t\tTraceID:    internal.TraceID(spanCtx.TraceID()),\n\t\tSpanID:     internal.SpanID(spanCtx.SpanID()),\n\t\tTraceFlags: uint32(spanCtx.TraceFlags()),\n\t\tTraceState: spanCtx.TraceState().String(),\n\t\tRemote:     spanCtx.IsRemote(),\n\t}\n}\n\nfunc encodeClientMetadata(ctx context.Context, rc *internal.RequestContext) {\n\tclientMetadata := client.FromContext(ctx).Metadata\n\tfor k := range clientMetadata.Keys() {\n\t\tvals := clientMetadata.Get(k)\n\t\tswitch len(vals) {\n\t\tcase 1:\n\t\t\trc.ClientMetadata = append(rc.ClientMetadata, internal.KeyValue{\n\t\t\t\tKey:   k,\n\t\t\t\tValue: internal.AnyValue{Value: &internal.AnyValue_StringValue{StringValue: vals[0]}},\n\t\t\t})\n\t\tdefault:\n\t\t\tmetadataArray := make([]internal.AnyValue, 0, len(vals))\n\t\t\tfor i := range vals {\n\t\t\t\tmetadataArray = append(metadataArray, internal.AnyValue{Value: &internal.AnyValue_StringValue{StringValue: vals[i]}})\n\t\t\t}\n\t\t\trc.ClientMetadata = append(rc.ClientMetadata, internal.KeyValue{\n\t\t\t\tKey:   k,\n\t\t\t\tValue: internal.AnyValue{Value: &internal.AnyValue_ArrayValue{ArrayValue: &internal.ArrayValue{Values: metadataArray}}},\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc encodeClientAddress(ctx context.Context, rc *internal.RequestContext) {\n\tswitch a := client.FromContext(ctx).Addr.(type) {\n\tcase *net.IPAddr:\n\t\trc.ClientAddress = &internal.RequestContext_IP{IP: &internal.IPAddr{\n\t\t\tIP:   a.IP,\n\t\t\tZone: a.Zone,\n\t\t}}\n\tcase *net.TCPAddr:\n\t\trc.ClientAddress = &internal.RequestContext_TCP{TCP: &internal.TCPAddr{\n\t\t\tIP:   a.IP,\n\t\t\tPort: int64(a.Port),\n\t\t\tZone: a.Zone,\n\t\t}}\n\tcase *net.UDPAddr:\n\t\trc.ClientAddress = &internal.RequestContext_UDP{UDP: &internal.UDPAddr{\n\t\t\tIP:   a.IP,\n\t\t\tPort: int64(a.Port),\n\t\t\tZone: a.Zone,\n\t\t}}\n\tcase *net.UnixAddr:\n\t\trc.ClientAddress = &internal.RequestContext_Unix{Unix: &internal.UnixAddr{\n\t\t\tName: a.Name,\n\t\t\tNet:  a.Net,\n\t\t}}\n\t}\n}\n\n// decodeContext decodes the context from the bytes map.\nfunc decodeContext(ctx context.Context, rc *internal.RequestContext) context.Context {\n\tif rc == nil {\n\t\treturn ctx\n\t}\n\tctx = decodeSpanContext(ctx, rc.SpanContext)\n\tmetadataMap := decodeClientMetadata(rc.ClientMetadata)\n\tclientAddress := decodeClientAddress(rc)\n\tif len(metadataMap) > 0 || clientAddress != nil {\n\t\tctx = client.NewContext(ctx, client.Info{\n\t\t\tMetadata: client.NewMetadata(metadataMap),\n\t\t\tAddr:     clientAddress,\n\t\t})\n\t}\n\treturn ctx\n}\n\nfunc decodeSpanContext(ctx context.Context, sc *internal.SpanContext) context.Context {\n\tif sc == nil {\n\t\treturn ctx\n\t}\n\ttraceID := trace.TraceID(sc.TraceID)\n\tspanID := trace.SpanID(sc.SpanID)\n\ttraceState, _ := trace.ParseTraceState(sc.TraceState)\n\treturn trace.ContextWithSpanContext(context.Background(), trace.NewSpanContext(trace.SpanContextConfig{\n\t\tTraceID:    traceID,\n\t\tSpanID:     spanID,\n\t\tTraceFlags: trace.TraceFlags(sc.TraceFlags),\n\t\tTraceState: traceState,\n\t\tRemote:     sc.Remote,\n\t}))\n}\n\nfunc decodeClientMetadata(clientMetadata []internal.KeyValue) map[string][]string {\n\tif len(clientMetadata) == 0 {\n\t\treturn nil\n\t}\n\tmetadataMap := make(map[string][]string, len(clientMetadata))\n\tfor _, kv := range clientMetadata {\n\t\tswitch val := kv.Value.Value.(type) {\n\t\tcase *internal.AnyValue_StringValue:\n\t\t\tmetadataMap[kv.Key] = make([]string, 1)\n\t\t\tmetadataMap[kv.Key][0] = val.StringValue\n\t\tcase *internal.AnyValue_ArrayValue:\n\t\t\tmetadataMap[kv.Key] = make([]string, len(val.ArrayValue.Values))\n\t\t\tfor i, v := range val.ArrayValue.Values {\n\t\t\t\tmetadataMap[kv.Key][i] = v.GetStringValue()\n\t\t\t}\n\t\t}\n\t}\n\treturn metadataMap\n}\n\nfunc decodeClientAddress(rc *internal.RequestContext) net.Addr {\n\tswitch a := rc.ClientAddress.(type) {\n\tcase *internal.RequestContext_IP:\n\t\treturn &net.IPAddr{\n\t\t\tIP:   a.IP.IP,\n\t\t\tZone: a.IP.Zone,\n\t\t}\n\tcase *internal.RequestContext_TCP:\n\t\treturn &net.TCPAddr{\n\t\t\tIP:   a.TCP.IP,\n\t\t\tPort: int(a.TCP.Port),\n\t\t\tZone: a.TCP.Zone,\n\t\t}\n\tcase *internal.RequestContext_UDP:\n\t\treturn &net.UDPAddr{\n\t\t\tIP:   a.UDP.IP,\n\t\t\tPort: int(a.UDP.Port),\n\t\t\tZone: a.UDP.Zone,\n\t\t}\n\tcase *internal.RequestContext_Unix:\n\t\treturn &net.UnixAddr{\n\t\t\tName: a.Unix.Name,\n\t\t\tNet:  a.Unix.Net,\n\t\t}\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "pdata/xpdata/request/context_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage request // import \"go.opentelemetry.io/collector/pdata/xpdata/request\"\n\nimport (\n\t\"context\"\n\t\"net\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/client\"\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n)\n\nfunc TestEncodeDecodeContext(t *testing.T) {\n\tspanCtx := fakeSpanContext(t)\n\tclientMetadata := client.NewMetadata(map[string][]string{\n\t\t\"key1\": {\"value1\"},\n\t\t\"key2\": {\"value2\", \"value3\"},\n\t})\n\ttests := []struct {\n\t\tname       string\n\t\tclientInfo client.Info\n\t}{\n\t\t{\n\t\t\tname:       \"without_client_address\",\n\t\t\tclientInfo: client.Info{Metadata: clientMetadata},\n\t\t},\n\t\t{\n\t\t\tname: \"with_client_IP_address\",\n\t\t\tclientInfo: client.Info{\n\t\t\t\tMetadata: clientMetadata,\n\t\t\t\tAddr: &net.IPAddr{\n\t\t\t\t\tIP:   net.IPv6loopback,\n\t\t\t\t\tZone: \"eth0\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with_client_TCP_address\",\n\t\t\tclientInfo: client.Info{\n\t\t\t\tMetadata: clientMetadata,\n\t\t\t\tAddr: &net.TCPAddr{\n\t\t\t\t\tIP:   net.IPv4(127, 0, 0, 1),\n\t\t\t\t\tPort: 8080,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with_client_UDP_address\",\n\t\t\tclientInfo: client.Info{\n\t\t\t\tMetadata: clientMetadata,\n\t\t\t\tAddr: &net.UDPAddr{\n\t\t\t\t\tIP:   net.IPv4(127, 0, 0, 1),\n\t\t\t\t\tPort: 8080,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"with_client_unix_address\",\n\t\t\tclientInfo: client.Info{\n\t\t\t\tMetadata: clientMetadata,\n\t\t\t\tAddr: &net.UnixAddr{\n\t\t\t\t\tName: \"/var/run/test.sock\",\n\t\t\t\t\tNet:  \"unixpacket\",\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// Encode a context with a span and client metadata\n\t\t\tctx := trace.ContextWithSpanContext(context.Background(), spanCtx)\n\t\t\tctx = client.NewContext(ctx, tt.clientInfo)\n\t\t\treqCtx := encodeContext(ctx)\n\t\t\tbuf := make([]byte, reqCtx.SizeProto())\n\t\t\treqCtx.MarshalProto(buf)\n\n\t\t\t// Decode the context\n\t\t\tgotReqCtx := internal.RequestContext{}\n\t\t\trequire.NoError(t, gotReqCtx.UnmarshalProto(buf))\n\t\t\tgotCtx := decodeContext(context.Background(), &gotReqCtx)\n\t\t\tassert.Equal(t, spanCtx, trace.SpanContextFromContext(gotCtx))\n\t\t\tassert.Equal(t, tt.clientInfo, client.FromContext(gotCtx))\n\t\t})\n\t}\n\n\t// Decode a nil context\n\tassert.Equal(t, context.Background(), decodeContext(context.Background(), nil))\n}\n"
  },
  {
    "path": "pdata/xpdata/request/internal/request.proto",
    "content": "syntax = \"proto3\";\n\npackage opentelemetry.collector.pdata.xpdata.internal;\n\noption go_package = \"go.opentelemetry.io/collector/pdata/xpdata/internal\";\n\nimport \"gogoproto/gogo.proto\";\n\nimport \"opentelemetry/proto/trace/v1/trace.proto\";\nimport \"opentelemetry/proto/metrics/v1/metrics.proto\";\nimport \"opentelemetry/proto/logs/v1/logs.proto\";\nimport \"opentelemetry/proto/common/v1/common.proto\";\nimport \"opentelemetry/proto/profiles/v1development/profiles.proto\";\n\n// SpanContext represents a span context encoded associated with a telemetry export request.\nmessage SpanContext {\n  bytes trace_id = 1;\n  bytes span_id = 2;\n  fixed32 trace_flags = 3;\n  string trace_state = 4;\n  bool remote = 5;\n}\n\nmessage IPAddr {\n  bytes ip = 1;\n  string zone = 2;\n}\n\nmessage TCPAddr {\n  bytes ip = 1;\n  int64 port = 2;\n  string zone = 3;\n}\n\nmessage UDPAddr {\n  bytes ip = 1;\n  int64 port = 2;\n  string zone = 3;\n}\n\nmessage UnixAddr {\n  string name = 1;\n  string net = 2;\n}\n\n// RequestContext represents metadata associated with a telemetry export request.\nmessage RequestContext {\n  SpanContext span_context = 1;\n\n  // ClientMetadata contains additional metadata about the client making the request.\n  repeated opentelemetry.proto.common.v1.KeyValue client_metadata = 2 [ (gogoproto.nullable) = false ];\n\n  // ClientAddress contains the address of the client making the request.\n  oneof client_address {\n    IPAddr ip = 3;\n    TCPAddr tcp = 4;\n    UDPAddr udp = 5;\n    UnixAddr unix = 6;\n  }\n}\n\n// The following messages are wrappers around standard OpenTelemetry data types.\n// They embed request-level context and a version discriminator to ensure they are not wire-compatible with\n// the canonical OpenTelemetry proto messages.\n//\n// Each wrapper reserves field tag 1 for a `fixed32` (protobuf wire type 5) format_version field, which makes it\n// structurally incompatible with the standard OTLP messages which use tag 1 for the data message field (protobuf wire type 2).\n// This ensures old and new formats cannot be confused during decoding.\n\nmessage TracesRequest {\n  fixed32 format_version = 1;\n  RequestContext request_context = 2;\n  opentelemetry.proto.trace.v1.TracesData traces_data = 3;\n}\n\nmessage MetricsRequest {\n  fixed32 format_version = 1;\n  RequestContext request_context = 2;\n  opentelemetry.proto.metrics.v1.MetricsData metrics_data = 3;\n}\n\nmessage LogsRequest {\n  fixed32 format_version = 1;\n  RequestContext request_context = 2;\n  opentelemetry.proto.logs.v1.LogsData logs_data = 3;\n}\n\nmessage ProfilesRequest {\n  fixed32 format_version = 1;\n  RequestContext request_context = 2;\n  opentelemetry.proto.profiles.v1development.ProfilesData profiles_data = 3;\n}\n"
  },
  {
    "path": "pdata/xpdata/request/logs_request.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage request // import \"go.opentelemetry.io/collector/pdata/xpdata/request\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\n// MarshalLogs marshals plog.Logs along with the context into a byte slice.\nfunc MarshalLogs(ctx context.Context, ld plog.Logs) ([]byte, error) {\n\tlr := internal.LogsRequest{\n\t\tFormatVersion:  requestFormatVersion,\n\t\tLogsData:       internal.LogsToProto(internal.LogsWrapper(ld)),\n\t\tRequestContext: encodeContext(ctx),\n\t}\n\tbuf := make([]byte, lr.SizeProto())\n\tlr.MarshalProto(buf)\n\treturn buf, nil\n}\n\n// UnmarshalLogs unmarshals a byte slice into plog.Logs and the context.\nfunc UnmarshalLogs(buf []byte) (context.Context, plog.Logs, error) {\n\tctx := context.Background()\n\tif !isRequestPayloadV1(buf) {\n\t\treturn ctx, plog.Logs{}, ErrInvalidFormat\n\t}\n\tlr := internal.LogsRequest{}\n\tif err := lr.UnmarshalProto(buf); err != nil {\n\t\treturn ctx, plog.Logs{}, fmt.Errorf(\"failed to unmarshal logs request: %w\", err)\n\t}\n\treturn decodeContext(ctx, lr.RequestContext), plog.Logs(internal.LogsFromProto(lr.LogsData)), nil\n}\n"
  },
  {
    "path": "pdata/xpdata/request/logs_request_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage request // import \"go.opentelemetry.io/collector/pdata/xpdata/request\"\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestMarshalUnmarshalLogsRequest(t *testing.T) {\n\tlogs := testdata.GenerateLogs(3)\n\n\t// unmarshal logs request with a context\n\tspanCtx := fakeSpanContext(t)\n\tbuf, err := MarshalLogs(trace.ContextWithSpanContext(context.Background(), spanCtx), logs)\n\trequire.NoError(t, err)\n\tgotCtx, gotLogs, err := UnmarshalLogs(buf)\n\trequire.NoError(t, err)\n\tassert.Equal(t, spanCtx, trace.SpanContextFromContext(gotCtx))\n\tassert.Equal(t, logs, gotLogs)\n\n\t// unmarshal logs request with empty context\n\tbuf, err = MarshalLogs(context.Background(), logs)\n\trequire.NoError(t, err)\n\tgotCtx, gotLogs, err = UnmarshalLogs(buf)\n\trequire.NoError(t, err)\n\tassert.Equal(t, context.Background(), gotCtx)\n\tassert.Equal(t, logs, gotLogs)\n\n\t// unmarshal corrupted data\n\t_, _, err = UnmarshalLogs(buf[:len(buf)-1])\n\trequire.ErrorContains(t, err, \"failed to unmarshal logs request\")\n\n\t// unmarshal invalid format (bare logs)\n\tbuf, err = (&plog.ProtoMarshaler{}).MarshalLogs(logs)\n\trequire.NoError(t, err)\n\t_, _, err = UnmarshalLogs(buf)\n\trequire.ErrorIs(t, err, ErrInvalidFormat)\n}\n"
  },
  {
    "path": "pdata/xpdata/request/metrics_request.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage request // import \"go.opentelemetry.io/collector/pdata/xpdata/request\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\n// MarshalMetrics marshals pmetric.Metrics along with the context into a byte slice.\nfunc MarshalMetrics(ctx context.Context, ld pmetric.Metrics) ([]byte, error) {\n\tmr := internal.MetricsRequest{\n\t\tFormatVersion:  requestFormatVersion,\n\t\tMetricsData:    internal.MetricsToProto(internal.MetricsWrapper(ld)),\n\t\tRequestContext: encodeContext(ctx),\n\t}\n\tbuf := make([]byte, mr.SizeProto())\n\tmr.MarshalProto(buf)\n\treturn buf, nil\n}\n\n// UnmarshalMetrics unmarshals a byte slice into pmetric.Metrics and the context.\nfunc UnmarshalMetrics(buf []byte) (context.Context, pmetric.Metrics, error) {\n\tctx := context.Background()\n\tif !isRequestPayloadV1(buf) {\n\t\treturn ctx, pmetric.Metrics{}, ErrInvalidFormat\n\t}\n\tmr := internal.MetricsRequest{}\n\tif err := mr.UnmarshalProto(buf); err != nil {\n\t\treturn ctx, pmetric.Metrics{}, fmt.Errorf(\"failed to unmarshal metrics request: %w\", err)\n\t}\n\treturn decodeContext(ctx, mr.RequestContext), pmetric.Metrics(internal.MetricsFromProto(mr.MetricsData)), nil\n}\n"
  },
  {
    "path": "pdata/xpdata/request/metrics_request_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage request // import \"go.opentelemetry.io/collector/pdata/xpdata/request\"\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestMarshalUnmarshalMetricsRequest(t *testing.T) {\n\tmetrics := testdata.GenerateMetrics(3)\n\n\t// unmarshal metrics request with a context\n\tspanCtx := fakeSpanContext(t)\n\tbuf, err := MarshalMetrics(trace.ContextWithSpanContext(context.Background(), spanCtx), metrics)\n\trequire.NoError(t, err)\n\tgotCtx, gotMetrics, err := UnmarshalMetrics(buf)\n\trequire.NoError(t, err)\n\tassert.Equal(t, spanCtx, trace.SpanContextFromContext(gotCtx))\n\tassert.Equal(t, metrics, gotMetrics)\n\n\t// unmarshal metrics request with empty context\n\tbuf, err = MarshalMetrics(context.Background(), metrics)\n\trequire.NoError(t, err)\n\tgotCtx, gotMetrics, err = UnmarshalMetrics(buf)\n\trequire.NoError(t, err)\n\tassert.Equal(t, context.Background(), gotCtx)\n\tassert.Equal(t, metrics, gotMetrics)\n\n\t// unmarshal corrupted data\n\t_, _, err = UnmarshalMetrics(buf[:len(buf)-1])\n\trequire.ErrorContains(t, err, \"failed to unmarshal metrics request\")\n\n\t// unmarshal invalid format (bare metrics)\n\tbuf, err = (&pmetric.ProtoMarshaler{}).MarshalMetrics(metrics)\n\trequire.NoError(t, err)\n\t_, _, err = UnmarshalMetrics(buf)\n\trequire.ErrorIs(t, err, ErrInvalidFormat)\n}\n"
  },
  {
    "path": "pdata/xpdata/request/profiles_request.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage request // import \"go.opentelemetry.io/collector/pdata/xpdata/request\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n)\n\n// MarshalProfiles marshals pprofile.Profiles along with the context into a byte slice.\nfunc MarshalProfiles(ctx context.Context, ld pprofile.Profiles) ([]byte, error) {\n\tpr := internal.ProfilesRequest{\n\t\tFormatVersion:  requestFormatVersion,\n\t\tProfilesData:   internal.ProfilesToProto(internal.ProfilesWrapper(ld)),\n\t\tRequestContext: encodeContext(ctx),\n\t}\n\tbuf := make([]byte, pr.SizeProto())\n\tpr.MarshalProto(buf)\n\treturn buf, nil\n}\n\n// UnmarshalProfiles unmarshals a byte slice into pprofile.Profiles and the context.\nfunc UnmarshalProfiles(buf []byte) (context.Context, pprofile.Profiles, error) {\n\tctx := context.Background()\n\tif !isRequestPayloadV1(buf) {\n\t\treturn ctx, pprofile.Profiles{}, ErrInvalidFormat\n\t}\n\tpr := internal.ProfilesRequest{}\n\tif err := pr.UnmarshalProto(buf); err != nil {\n\t\treturn ctx, pprofile.Profiles{}, fmt.Errorf(\"failed to unmarshal profiles request: %w\", err)\n\t}\n\treturn decodeContext(ctx, pr.RequestContext), pprofile.Profiles(internal.ProfilesFromProto(pr.ProfilesData)), nil\n}\n"
  },
  {
    "path": "pdata/xpdata/request/profiles_request_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage request // import \"go.opentelemetry.io/collector/pdata/xpdata/request\"\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestMarshalUnmarshalProfilesRequest(t *testing.T) {\n\tprofiles := testdata.GenerateProfiles(3)\n\n\t// unmarshal profiles request with a context\n\tspanCtx := fakeSpanContext(t)\n\tbuf, err := MarshalProfiles(trace.ContextWithSpanContext(context.Background(), spanCtx), profiles)\n\trequire.NoError(t, err)\n\tgotCtx, gotProfiles, err := UnmarshalProfiles(buf)\n\trequire.NoError(t, err)\n\tassert.Equal(t, spanCtx, trace.SpanContextFromContext(gotCtx))\n\tassert.Equal(t, profiles, gotProfiles)\n\n\t// unmarshal profiles request with empty context\n\tbuf, err = MarshalProfiles(context.Background(), profiles)\n\trequire.NoError(t, err)\n\tgotCtx, gotProfiles, err = UnmarshalProfiles(buf)\n\trequire.NoError(t, err)\n\tassert.Equal(t, context.Background(), gotCtx)\n\tassert.Equal(t, profiles, gotProfiles)\n\n\t// unmarshal corrupted data\n\t_, _, err = UnmarshalProfiles(buf[:len(buf)-1])\n\trequire.ErrorContains(t, err, \"failed to unmarshal profiles request\")\n\n\t// unmarshal invalid format (bare profiles)\n\tbuf, err = (&pprofile.ProtoMarshaler{}).MarshalProfiles(profiles)\n\trequire.NoError(t, err)\n\t_, _, err = UnmarshalProfiles(buf)\n\trequire.ErrorIs(t, err, ErrInvalidFormat)\n}\n"
  },
  {
    "path": "pdata/xpdata/request/requesttest.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage request // import \"go.opentelemetry.io/collector/pdata/xpdata/request\"\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/trace\"\n)\n\nfunc fakeSpanContext(tb testing.TB) trace.SpanContext {\n\ttraceID, err := trace.TraceIDFromHex(\"0102030405060708090a0b0c0d0e0f10\")\n\trequire.NoError(tb, err)\n\tspanID, err := trace.SpanIDFromHex(\"0102030405060708\")\n\trequire.NoError(tb, err)\n\ttraceState, err := trace.ParseTraceState(\"key1=value1,key2=value2,key3=value3\")\n\trequire.NoError(tb, err)\n\treturn trace.NewSpanContext(trace.SpanContextConfig{\n\t\tTraceID:    traceID,\n\t\tSpanID:     spanID,\n\t\tTraceFlags: 0x01,\n\t\tTraceState: traceState,\n\t\tRemote:     true,\n\t})\n}\n"
  },
  {
    "path": "pdata/xpdata/request/traces_request.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage request // import \"go.opentelemetry.io/collector/pdata/xpdata/request\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/pdata/internal\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\n// MarshalTraces marshals ptrace.Traces along with the context into a byte slice.\nfunc MarshalTraces(ctx context.Context, ld ptrace.Traces) ([]byte, error) {\n\ttr := internal.TracesRequest{\n\t\tFormatVersion:  requestFormatVersion,\n\t\tTracesData:     internal.TracesToProto(internal.TracesWrapper(ld)),\n\t\tRequestContext: encodeContext(ctx),\n\t}\n\tbuf := make([]byte, tr.SizeProto())\n\ttr.MarshalProto(buf)\n\treturn buf, nil\n}\n\n// UnmarshalTraces unmarshals a byte slice into ptrace.Traces and the context.\nfunc UnmarshalTraces(buf []byte) (context.Context, ptrace.Traces, error) {\n\tctx := context.Background()\n\tif !isRequestPayloadV1(buf) {\n\t\treturn ctx, ptrace.Traces{}, ErrInvalidFormat\n\t}\n\ttr := internal.TracesRequest{}\n\tif err := tr.UnmarshalProto(buf); err != nil {\n\t\treturn ctx, ptrace.Traces{}, fmt.Errorf(\"failed to unmarshal traces request: %w\", err)\n\t}\n\treturn decodeContext(ctx, tr.RequestContext), ptrace.Traces(internal.TracesFromProto(tr.TracesData)), nil\n}\n"
  },
  {
    "path": "pdata/xpdata/request/traces_request_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage request // import \"go.opentelemetry.io/collector/pdata/xpdata/request\"\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestMarshalUnmarshalTracesRequest(t *testing.T) {\n\ttraces := testdata.GenerateTraces(3)\n\n\t// unmarshal traces request with a context\n\tspanCtx := fakeSpanContext(t)\n\tbuf, err := MarshalTraces(trace.ContextWithSpanContext(context.Background(), spanCtx), traces)\n\trequire.NoError(t, err)\n\tgotCtx, gotTraces, err := UnmarshalTraces(buf)\n\trequire.NoError(t, err)\n\tassert.Equal(t, spanCtx, trace.SpanContextFromContext(gotCtx))\n\tassert.Equal(t, traces, gotTraces)\n\n\t// unmarshal traces request with empty context\n\tbuf, err = MarshalTraces(context.Background(), traces)\n\trequire.NoError(t, err)\n\tgotCtx, gotTraces, err = UnmarshalTraces(buf)\n\trequire.NoError(t, err)\n\tassert.Equal(t, context.Background(), gotCtx)\n\tassert.Equal(t, traces, gotTraces)\n\n\t// unmarshal corrupted data\n\t_, _, err = UnmarshalTraces(buf[:len(buf)-1])\n\trequire.ErrorContains(t, err, \"failed to unmarshal traces request\")\n\n\t// unmarshal invalid format (bare traces)\n\tbuf, err = (&ptrace.ProtoMarshaler{}).MarshalTraces(traces)\n\trequire.NoError(t, err)\n\t_, _, err = UnmarshalTraces(buf)\n\trequire.ErrorIs(t, err, ErrInvalidFormat)\n}\n"
  },
  {
    "path": "pdata/xpdata/request/version_check.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage request // import \"go.opentelemetry.io/collector/pdata/xpdata/request\"\n\nimport (\n\t\"encoding/binary\"\n\t\"errors\"\n)\n\nconst (\n\t// field 1 << 3, wire type 5 (fixed32)\n\tprotoTag1TypeByte = 0x0D\n\n\t// version of the request payload format set in the `format_version` field\n\trequestFormatVersion = uint32(1)\n)\n\nvar ErrInvalidFormat = errors.New(\"invalid request payload format\")\n\n// isRequestPayloadV1 returns true if the given payload represents one of the wrappers around standard OpenTelemetry\n// data types defined in internal/request.go and has the version set to 1.\nfunc isRequestPayloadV1(data []byte) bool {\n\tif len(data) < 5 {\n\t\treturn false\n\t}\n\tif data[0] != protoTag1TypeByte {\n\t\treturn false\n\t}\n\treturn binary.LittleEndian.Uint32(data[1:5]) == requestFormatVersion\n}\n"
  },
  {
    "path": "pdata/xpdata/request/version_check_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage request\n\nimport (\n\t\"context\"\n\t\"encoding/binary\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nfunc TestIsRequestPayloadV1(t *testing.T) {\n\t// too short\n\tassert.False(t, isRequestPayloadV1([]byte{protoTag1TypeByte, 0x00}))\n\n\tbuf := make([]byte, 5)\n\n\t// wrong type: field 1, wire type 2 (length-delimited)\n\tbuf[0] = 0x0A\n\tassert.False(t, isRequestPayloadV1([]byte{protoTag1TypeByte, 0x00}))\n\n\t// wrong version\n\tbuf[0] = protoTag1TypeByte\n\tbinary.LittleEndian.PutUint32(buf[1:], 2)\n\tassert.False(t, isRequestPayloadV1(buf))\n\n\tbinary.LittleEndian.PutUint32(buf[1:], requestFormatVersion)\n\tassert.True(t, isRequestPayloadV1(buf))\n\n\tbuf, err := MarshalMetrics(context.Background(), pmetric.NewMetrics())\n\trequire.NoError(t, err)\n\tassert.True(t, isRequestPayloadV1(buf))\n\n\tbuf, err = MarshalTraces(context.Background(), ptrace.NewTraces())\n\trequire.NoError(t, err)\n\tassert.True(t, isRequestPayloadV1(buf))\n\n\tbuf, err = MarshalLogs(context.Background(), plog.NewLogs())\n\trequire.NoError(t, err)\n\tassert.True(t, isRequestPayloadV1(buf))\n\n\tbuf, err = MarshalProfiles(context.Background(), pprofile.NewProfiles())\n\trequire.NoError(t, err)\n\tassert.True(t, isRequestPayloadV1(buf))\n}\n"
  },
  {
    "path": "pdata/xpdata/xpdata.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\npackage xpdata // import \"go.opentelemetry.io/collector/pdata/xpdata\"\n"
  },
  {
    "path": "pipeline/Makefile",
    "content": "include ../Makefile.Common\n"
  },
  {
    "path": "pipeline/go.mod",
    "content": "module go.opentelemetry.io/collector/pipeline\n\ngo 1.25.0\n\nrequire github.com/stretchr/testify v1.11.1\n\nrequire (\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n"
  },
  {
    "path": "pipeline/go.sum",
    "content": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "pipeline/internal/globalsignal/signal.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage globalsignal // import \"go.opentelemetry.io/collector/pipeline/internal/globalsignal\"\n\nimport (\n\t\"encoding\"\n\t\"fmt\"\n)\n\nvar (\n\tSignalProfiles = Signal{name: \"profiles\"}\n\tSignalTraces   = Signal{name: \"traces\"}\n\tSignalMetrics  = Signal{name: \"metrics\"}\n\tSignalLogs     = Signal{name: \"logs\"}\n\n\t_ encoding.TextMarshaler   = (*Signal)(nil)\n\t_ encoding.TextUnmarshaler = (*Signal)(nil)\n)\n\n// Signal represents the signals supported by the collector.\ntype Signal struct {\n\tname string\n}\n\n// String returns the string representation of the signal.\nfunc (s Signal) String() string {\n\treturn s.name\n}\n\n// MarshalText marshals the Signal.\nfunc (s Signal) MarshalText() ([]byte, error) {\n\treturn []byte(s.name), nil\n}\n\n// UnmarshalText marshals the Signal.\nfunc (s *Signal) UnmarshalText(text []byte) error {\n\tswitch string(text) {\n\tcase SignalProfiles.name:\n\t\t*s = SignalProfiles\n\tcase SignalTraces.name:\n\t\t*s = SignalTraces\n\tcase SignalMetrics.name:\n\t\t*s = SignalMetrics\n\tcase SignalLogs.name:\n\t\t*s = SignalLogs\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown pipeline signal: %q\", string(text))\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "pipeline/internal/globalsignal/signal_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage globalsignal\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestSignal_String(t *testing.T) {\n\tassert.Equal(t, \"traces\", SignalTraces.String())\n\tassert.Equal(t, \"metrics\", SignalMetrics.String())\n\tassert.Equal(t, \"logs\", SignalLogs.String())\n\tassert.Equal(t, \"profiles\", SignalProfiles.String())\n}\n\nfunc TestSignal_MarshalText(t *testing.T) {\n\tb, err := SignalTraces.MarshalText()\n\trequire.NoError(t, err)\n\tassert.Equal(t, []byte(\"traces\"), b)\n\n\tb, err = SignalMetrics.MarshalText()\n\trequire.NoError(t, err)\n\tassert.Equal(t, []byte(\"metrics\"), b)\n\n\tb, err = SignalLogs.MarshalText()\n\trequire.NoError(t, err)\n\tassert.Equal(t, []byte(\"logs\"), b)\n\n\tb, err = SignalProfiles.MarshalText()\n\trequire.NoError(t, err)\n\tassert.Equal(t, []byte(\"profiles\"), b)\n\n\tvar s Signal\n\tb, err = s.MarshalText()\n\trequire.NoError(t, err)\n\tassert.Equal(t, []byte(\"\"), b)\n}\n\nfunc TestSignal_UnmarshalText(t *testing.T) {\n\tvar s Signal\n\trequire.NoError(t, s.UnmarshalText([]byte(\"traces\")))\n\tassert.Equal(t, SignalTraces, s)\n\n\trequire.NoError(t, s.UnmarshalText([]byte(\"metrics\")))\n\tassert.Equal(t, SignalMetrics, s)\n\n\trequire.NoError(t, s.UnmarshalText([]byte(\"logs\")))\n\tassert.Equal(t, SignalLogs, s)\n\n\trequire.NoError(t, s.UnmarshalText([]byte(\"profiles\")))\n\tassert.Equal(t, SignalProfiles, s)\n\n\trequire.Error(t, s.UnmarshalText([]byte(\"unknown\")))\n}\n"
  },
  {
    "path": "pipeline/metadata.yaml",
    "content": "type: pipeline\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "pipeline/pipeline.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pipeline // import \"go.opentelemetry.io/collector/pipeline\"\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"regexp\"\n\t\"strings\"\n)\n\n// typeAndNameSeparator is the separator that is used between type and name in type/name composite keys.\nconst typeAndNameSeparator = \"/\"\n\n// ID represents the identity for a pipeline. It combines two values:\n// * signal - the Signal of the pipeline.\n// * name - the name of that pipeline.\ntype ID struct {\n\tsignal Signal `mapstructure:\"-\"`\n\tname   string `mapstructure:\"-\"`\n}\n\n// NewID returns a new ID with the given Signal and empty name.\nfunc NewID(signal Signal) ID {\n\treturn NewIDWithName(signal, \"\")\n}\n\n// NewIDWithName returns a new ID with the given Signal and name.\nfunc NewIDWithName(signal Signal, name string) ID {\n\treturn ID{signal: signal, name: name}\n}\n\n// Signal returns the Signal of the ID.\nfunc (i ID) Signal() Signal {\n\treturn i.signal\n}\n\n// Name returns the name of the ID.\nfunc (i ID) Name() string {\n\treturn i.name\n}\n\n// MarshalText implements the encoding.TextMarshaler interface.\n// This marshals the Signal and name as one string in the config.\nfunc (i ID) MarshalText() (text []byte, err error) {\n\treturn []byte(i.String()), nil\n}\n\n// UnmarshalText implements the encoding.TextUnmarshaler interface.\nfunc (i *ID) UnmarshalText(text []byte) error {\n\tidStr := string(text)\n\tsignalStr, nameStr, hasName := strings.Cut(idStr, typeAndNameSeparator)\n\tsignalStr = strings.TrimSpace(signalStr)\n\n\tif signalStr == \"\" {\n\t\tif hasName {\n\t\t\treturn fmt.Errorf(\"in %q id: the part before %s should not be empty\", idStr, typeAndNameSeparator)\n\t\t}\n\t\treturn errors.New(\"id must not be empty\")\n\t}\n\n\tif hasName {\n\t\t// \"name\" part is present.\n\t\tnameStr = strings.TrimSpace(nameStr)\n\t\tif nameStr == \"\" {\n\t\t\treturn fmt.Errorf(\"in %q id: the part after %s should not be empty\", idStr, typeAndNameSeparator)\n\t\t}\n\t\tif err := validateName(nameStr); err != nil {\n\t\t\treturn fmt.Errorf(\"in %q id: %w\", nameStr, err)\n\t\t}\n\t}\n\n\tif err := i.signal.UnmarshalText([]byte(signalStr)); err != nil {\n\t\treturn fmt.Errorf(\"in %q id: %w\", idStr, err)\n\t}\n\ti.name = nameStr\n\n\treturn nil\n}\n\n// String returns the ID string representation as \"signal[/name]\" format.\nfunc (i ID) String() string {\n\tif i.name == \"\" {\n\t\treturn i.signal.String()\n\t}\n\n\treturn i.signal.String() + typeAndNameSeparator + i.name\n}\n\n// nameRegexp is used to validate the name of an ID. A name can consist of\n// 1 to 1024 unicode characters excluding whitespace, control characters, and\n// symbols.\nvar nameRegexp = regexp.MustCompile(`^[^\\pZ\\pC\\pS]+$`)\n\nfunc validateName(nameStr string) error {\n\tif len(nameStr) > 1024 {\n\t\treturn fmt.Errorf(\"name %q is longer than 1024 characters (%d characters)\", nameStr, len(nameStr))\n\t}\n\tif !nameRegexp.MatchString(nameStr) {\n\t\treturn fmt.Errorf(\"invalid character(s) in name %q\", nameStr)\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "pipeline/pipeline_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pipeline\n\nimport (\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/pipeline/internal/globalsignal\"\n)\n\nfunc Test_NewID(t *testing.T) {\n\tid := NewID(SignalTraces)\n\tassert.Equal(t, ID{signal: SignalTraces}, id)\n}\n\nfunc Test_NewIDWithName(t *testing.T) {\n\tid := NewIDWithName(SignalTraces, \"test\")\n\tassert.Equal(t, ID{signal: SignalTraces, name: \"test\"}, id)\n}\n\nfunc TestMarshalText(t *testing.T) {\n\tid := NewIDWithName(SignalTraces, \"name\")\n\tgot, err := id.MarshalText()\n\trequire.NoError(t, err)\n\tassert.Equal(t, id.String(), string(got))\n}\n\nfunc TestUnmarshalText(t *testing.T) {\n\ttestCases := []struct {\n\t\tidStr       string\n\t\texpectedErr bool\n\t\texpectedID  ID\n\t}{\n\t\t{\n\t\t\tidStr:      \"traces\",\n\t\t\texpectedID: ID{signal: globalsignal.SignalTraces, name: \"\"},\n\t\t},\n\t\t{\n\t\t\tidStr:      \"traces/valid_name\",\n\t\t\texpectedID: ID{signal: globalsignal.SignalTraces, name: \"valid_name\"},\n\t\t},\n\t\t{\n\t\t\tidStr:      \"   traces   /   valid_name  \",\n\t\t\texpectedID: ID{signal: globalsignal.SignalTraces, name: \"valid_name\"},\n\t\t},\n\t\t{\n\t\t\tidStr:      \"traces/中文好\",\n\t\t\texpectedID: ID{signal: globalsignal.SignalTraces, name: \"中文好\"},\n\t\t},\n\t\t{\n\t\t\tidStr:      \"traces/name-with-dashes\",\n\t\t\texpectedID: ID{signal: globalsignal.SignalTraces, name: \"name-with-dashes\"},\n\t\t},\n\t\t// issue 10816\n\t\t{\n\t\t\tidStr:      \"traces/Linux-Messages-File_01J49HCH3SWFXRVASWFZFRT3J2__processor0__logs\",\n\t\t\texpectedID: ID{signal: globalsignal.SignalTraces, name: \"Linux-Messages-File_01J49HCH3SWFXRVASWFZFRT3J2__processor0__logs\"},\n\t\t},\n\t\t{\n\t\t\tidStr:      \"traces/1\",\n\t\t\texpectedID: ID{signal: globalsignal.SignalTraces, name: \"1\"},\n\t\t},\n\t\t{\n\t\t\tidStr:       \"/valid_name\",\n\t\t\texpectedErr: true,\n\t\t},\n\t\t{\n\t\t\tidStr:       \"     /valid_name\",\n\t\t\texpectedErr: true,\n\t\t},\n\t\t{\n\t\t\tidStr:       \"traces/\",\n\t\t\texpectedErr: true,\n\t\t},\n\t\t{\n\t\t\tidStr:       \"traces/      \",\n\t\t\texpectedErr: true,\n\t\t},\n\t\t{\n\t\t\tidStr:       \"      \",\n\t\t\texpectedErr: true,\n\t\t},\n\t\t{\n\t\t\tidStr:       \"traces/invalid name\",\n\t\t\texpectedErr: true,\n\t\t},\n\t\t{\n\t\t\tidStr:       \"traces/\" + strings.Repeat(\"a\", 1025),\n\t\t\texpectedErr: true,\n\t\t},\n\t\t{\n\t\t\tidStr:       \"INVALID\",\n\t\t\texpectedErr: true,\n\t\t},\n\t\t{\n\t\t\tidStr:       \"INVALID/name\",\n\t\t\texpectedErr: true,\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\tt.Run(test.idStr, func(t *testing.T) {\n\t\t\tid := ID{}\n\t\t\terr := id.UnmarshalText([]byte(test.idStr))\n\t\t\tif test.expectedErr {\n\t\t\t\tassert.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, test.expectedID, id)\n\t\t\tassert.Equal(t, test.expectedID.Signal(), id.Signal())\n\t\t\tassert.Equal(t, test.expectedID.Name(), id.Name())\n\t\t\tassert.Equal(t, test.expectedID.String(), id.String())\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "pipeline/signal.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pipeline // import \"go.opentelemetry.io/collector/pipeline\"\n\nimport (\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/pipeline/internal/globalsignal\"\n)\n\n// Signal represents the signals supported by the collector. We currently support\n// collecting metrics, traces and logs, this can expand in the future.\ntype Signal = globalsignal.Signal\n\nvar ErrSignalNotSupported = errors.New(\"telemetry type is not supported\")\n\nvar (\n\tSignalTraces  = globalsignal.SignalTraces\n\tSignalMetrics = globalsignal.SignalMetrics\n\tSignalLogs    = globalsignal.SignalLogs\n)\n"
  },
  {
    "path": "pipeline/xpipeline/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "pipeline/xpipeline/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xpipeline // import \"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\nimport \"go.opentelemetry.io/collector/pipeline/internal/globalsignal\"\n\nvar SignalProfiles = globalsignal.SignalProfiles\n"
  },
  {
    "path": "pipeline/xpipeline/go.mod",
    "content": "module go.opentelemetry.io/collector/pipeline/xpipeline\n\ngo 1.25.0\n\nrequire go.opentelemetry.io/collector/pipeline v1.54.0\n\nreplace go.opentelemetry.io/collector/pipeline => ../\n"
  },
  {
    "path": "pipeline/xpipeline/go.sum",
    "content": "github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "pipeline/xpipeline/metadata.yaml",
    "content": "type: xpipeline\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "processor/Makefile",
    "content": "include ../Makefile.Common\n"
  },
  {
    "path": "processor/README.md",
    "content": "# General Information\n\nProcessors are used at various stages of a pipeline. Generally, a processor\npre-processes data before it is exported (e.g. modify attributes or sample).\n\nSome important aspects of pipelines and processors to be aware of:\n- [Recommended Processors](#recommended-processors)\n- [Data Ownership](#data-ownership)\n- [Exclusive Ownership](#exclusive-ownership)\n- [Shared Ownership](#shared-ownership)\n- [Ordering Processors](#ordering-processors)\n- [Creating Custom Processor](#creating-custom-processors)\n\nSupported processors (sorted alphabetically):\n- [Batch Processor](batchprocessor/README.md)\n- [Memory Limiter Processor](memorylimiterprocessor/README.md)\n\nThe [contrib repository](https://github.com/open-telemetry/opentelemetry-collector-contrib)\n has more processors that can be added to a custom build of the Collector.\n\n## Recommended Processors\n\nBy default, no processors are enabled. Depending on the data source, it may be\nrecommended that multiple processors be enabled. Processors must be enabled\nfor every data source and not all processors support all data sources.\nIn addition, it is important to note that the order of processors matters. The\norder in each section below is the best practice. Refer to the individual\nprocessor documentation for more information.\n\n1. [memory_limiter](memorylimiterprocessor/README.md)\n2. Any sampling or initial filtering processors\n3. Any processor relying on sending source from `Context` (e.g. `k8sattributes`)\n3. [batch](batchprocessor/README.md), although prefer using the exporter's batching capabilities\n4. Any other processors\n\n## Data Ownership\n\nThe ownership of the `pdata.Traces`, `pdata.Metrics` and `pdata.Logs` data in a pipeline\nis passed as the data travels through the pipeline. The data is created by the receiver\nand then the ownership is passed to the first processor when `ConsumeTraces`/`ConsumeMetrics`/`ConsumeLogs`\nfunction is called.\n\nNote: the receiver may be attached to multiple pipelines, in which case the same data\nwill be passed to all attached pipelines via a data fan-out connector.\n\nFrom data ownership perspective pipelines can work in 2 modes:\n* Exclusive data ownership\n* Shared data ownership\n\nThe mode is defined during startup based on data modification intent reported by the\nprocessors. The intent is reported by each processor via `MutatesData` field of\nthe struct returned by `Capabilities` function. If any processor in the pipeline\ndeclares an intent to modify the data then that pipeline will work in exclusive ownership\nmode. In addition, any other pipeline that receives data from a receiver that is attached\nto a pipeline with exclusive ownership mode will be also operating in exclusive ownership\nmode.\n\n### Exclusive Ownership\n\nIn exclusive ownership mode the data is owned exclusively by a particular processor at a\ngiven moment of time, and the processor is free to modify the data it owns.\n\nExclusive ownership mode is only applicable for pipelines that receive data from the\nsame receiver. If a pipeline is marked to be in exclusive ownership mode then any data\nreceived from a shared receiver will be cloned at the fan-out connector before passing\nfurther to each pipeline. This ensures that each pipeline has its own exclusive copy of\ndata, and the data can be safely modified in the pipeline.\n\nThe exclusive ownership of data allows processors to freely modify the data while\nthey own it (e.g. see `attributesprocessor`). The duration of ownership of the data\nby processor is from the beginning of `ConsumeTraces`/`ConsumeMetrics`/`ConsumeLogs` \ncall until the processor calls the next processor's `ConsumeTraces`/`ConsumeMetrics`/`ConsumeLogs`\nfunction, which passes the ownership to the next processor. After that the processor\nmust no longer read or write the data since it may be concurrently modified by the\nnew owner.\n\nExclusive Ownership mode allows to easily implement processors that need to modify\nthe data by simply declaring such intent.\n\n### Shared Ownership\n\nIn shared ownership mode no particular processor owns the data and no processor is\nallowed the modify the shared data.\n\nIn this mode no cloning is performed at the fan-out connector of receivers that\nare attached to multiple pipelines. In this case all such pipelines will see\nthe same single shared copy of the data. Processors in pipelines operating in shared\nownership mode are prohibited from modifying the original data that they receive\nvia `ConsumeTraces`/`ConsumeMetrics`/`ConsumeLogs` call. Processors may only read\nthe data but must not modify the data.\n\nIf the processor needs to modify the data while performing the processing but\ndoes not want to incur the cost of data cloning that Exclusive mode brings then\nthe processor can declare that it does not modify the data and use any\ndifferent technique that ensures original data is not modified. For example,\nthe processor can implement copy-on-write approach for individual sub-parts of\n`pdata.Traces`/`pdata.Metrics`/`pdata.Logs` argument. Any approach that does not\nmutate the original `pdata.Traces`/`pdata.Metrics`/`pdata.Logs` is allowed.\n\nIf the processor uses such technique it should declare that it does not intend\nto modify the original data by setting `MutatesData=false` in its capabilities\nto avoid marking the pipeline for Exclusive ownership and to avoid the cost of\ndata cloning described in Exclusive Ownership section.\n\n## Ordering Processors\n\nThe order processors are specified in a pipeline is important as this is the\norder in which each processor is applied.\n\n## Creating Custom Processors\n\nTo create a custom processor for the OpenTelemetry Collector, you need to implement the processor interface, define the processor's configuration, and register it with the Collector. The process typically involves creating a factory, implementing the required processing logic, and handling configuration options. For a practical example and guidance, refer to the [`processorhelper`](https://pkg.go.dev/go.opentelemetry.io/collector/processor/processorhelper) package, which provides utilities and patterns to simplify processor development.\n\n"
  },
  {
    "path": "processor/batchprocessor/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "processor/batchprocessor/README.md",
    "content": "<!-- status autogenerated section -->\n# Batch Processor\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [beta]: traces, metrics, logs   |\n| Distributions | [core], [contrib], [k8s] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Aprocessor%2Fbatch%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Aprocessor%2Fbatch) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Aprocessor%2Fbatch%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Aprocessor%2Fbatch) |\n\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[core]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n[k8s]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\n<!-- end autogenerated section -->\n\nThe batch processor accepts spans, metrics, or logs and places them into\nbatches. Batching helps better compress the data and reduce the number of\noutgoing connections required to transmit the data. This processor supports\nboth size and time based batching.\n\nThe batch processor should be defined in the pipeline after the `memory_limiter`\nas well as any sampling processors. This is because batching should happen after\nany data drops such as sampling.\n\nPlease refer to [config.go](./config.go) for the config spec.\n\nThe following configuration options can be modified:\n- `send_batch_size` (default = 8192): Number of spans, metric data points, or log\nrecords after which a batch will be sent regardless of the timeout. `send_batch_size`\nacts as a trigger and does not affect the size of the batch. If you need to\nenforce batch size limits sent to the next component in the pipeline\nsee `send_batch_max_size`.\n- `timeout` (default = 200ms): Time duration after which a batch will\nbe sent regardless of size.  If set to zero, `send_batch_size` is\nignored as data will be sent immediately, subject to only `send_batch_max_size`.\n- `send_batch_max_size` (default = 0): The upper limit of the batch size.\n  `0` means no upper limit of the batch size.\n  This property ensures that larger batches are split into smaller units.\n  It must be greater than or equal to `send_batch_size`.\n- `metadata_keys` (default = empty): When set, this processor will\n  create one batcher instance per distinct combination of values in\n  the `client.Metadata`.\n- `metadata_cardinality_limit` (default = 1000): When `metadata_keys` is \n  not empty, this setting limits the number of unique combinations of \n  metadata key values that will be processed over the lifetime of the\n  process.\n\nSee notes about metadata batching below.\n\nExamples:\n\nThis configuration contains one default batch processor and a second\nwith custom settings.  The `batch/2` processor will buffer up to 10000\nspans, metric data points, or log records for up to 10 seconds without\nsplitting data items to enforce a maximum batch size.\n\n```yaml\nprocessors:\n  batch:\n  batch/2:\n    send_batch_size: 10000\n    timeout: 10s\n```\n\nThis configuration will enforce a maximum batch size limit of 10000\nspans, metric data points, or log records without introducing any\nartificial delays.\n\n```yaml\nprocessors:\n  batch:\n    send_batch_max_size: 10000\n    timeout: 0s\n```\n\nRefer to [config.yaml](./testdata/config.yaml) for detailed\nexamples on using the processor.\n\n## Batching and client metadata\n\nBatching by metadata enables support for multi-tenant OpenTelemetry\nCollector pipelines with batching over groups of data having the same\nauthorization metadata.  For example:\n\n```yaml\nprocessors:\n  batch:\n    # batch data by tenant-id\n    metadata_keys:\n    - tenant_id\n\n    # limit to 10 batcher processes before raising errors\n    metadata_cardinality_limit: 10\n```\n\nReceivers should be configured with `include_metadata: true` so that\nmetadata keys are available to the processor.\n\nNote that each distinct combination of metadata triggers the\nallocation of a new background task in the Collector that runs for the\nlifetime of the process, and each background task holds one pending\nbatch of up to `send_batch_size` records.  Batching by metadata can\ntherefore substantially increase the amount of memory dedicated to\nbatching.\n\nThe maximum number of distinct combinations is limited to the\nconfigured `metadata_cardinality_limit`, which defaults to 1000 to\nlimit memory impact.\n\nUsers of the batching processor configured with metadata keys should\nconsider use of an Auth extension to validate the relevant\nmetadata-key values.\n\nThe number of batch processors currently in use is exported as the\n`otelcol_processor_batch_metadata_cardinality` metric.\n"
  },
  {
    "path": "processor/batchprocessor/batch_processor.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage batchprocessor // import \"go.opentelemetry.io/collector/processor/batchprocessor\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"runtime\"\n\t\"sort\"\n\t\"strings\"\n\t\"sync\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/client\"\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n\t\"go.opentelemetry.io/collector/processor\"\n)\n\n// errTooManyBatchers is returned when the MetadataCardinalityLimit has been reached.\nvar errTooManyBatchers = consumererror.NewPermanent(errors.New(\"too many batcher metadata-value combinations\"))\n\n// batch_processor is a component that accepts spans and metrics, places them\n// into batches and sends downstream.\n//\n// batch_processor implements consumer.Traces and consumer.Metrics\n//\n// Batches are sent out with any of the following conditions:\n// - batch size reaches cfg.SendBatchSize\n// - cfg.Timeout is elapsed since the timestamp when the previous batch was sent out.\ntype batchProcessor[T any] struct {\n\tlogger           *zap.Logger\n\ttimeout          time.Duration\n\tsendBatchSize    int\n\tsendBatchMaxSize int\n\n\t// batchFunc is a factory for new batch objects corresponding\n\t// with the appropriate signal.\n\tbatchFunc func() batch[T]\n\n\tshutdownC  chan struct{}\n\tgoroutines sync.WaitGroup\n\n\ttelemetry *batchProcessorTelemetry\n\n\t// batcher will be either *singletonBatcher or *multiBatcher\n\tbatcher batcher[T]\n}\n\n// batcher is describes a *singletonBatcher or *multiBatcher.\ntype batcher[T any] interface {\n\t// start initializes background resources used by this batcher.\n\tstart(ctx context.Context) error\n\n\t// consume incorporates a new item of data into the pending batch.\n\tconsume(ctx context.Context, data T) error\n\n\t// currentMetadataCardinality returns the number of shards.\n\tcurrentMetadataCardinality() int\n}\n\n// shard is a single instance of the batch logic.  When metadata\n// keys are in use, one of these is created per distinct combination\n// of values.\ntype shard[T any] struct {\n\t// processor refers to this processor, for access to common\n\t// configuration.\n\tprocessor *batchProcessor[T]\n\n\t// exportCtx is a context with the metadata key-values\n\t// corresponding with this shard set.\n\texportCtx context.Context\n\n\t// timer informs the shard send a batch.\n\ttimer *time.Timer\n\n\t// newItem is used to receive data items from producers.\n\tnewItem chan T\n\n\t// batch is an in-flight data item containing one of the\n\t// underlying data types.\n\tbatch batch[T]\n}\n\n// batch is an interface generalizing the individual signal types.\ntype batch[T any] interface {\n\t// export the current batch\n\texport(ctx context.Context, req T) error\n\n\t// split returns a full request built from pending items.\n\tsplit(sendBatchMaxSize int) (sentBatchSize int, req T)\n\n\t// itemCount returns the size of the current batch\n\titemCount() int\n\n\t// add item to the current batch\n\tadd(item T)\n\n\t// sizeBytes counts the OTLP encoding size of the batch\n\tsizeBytes(item T) int\n}\n\n// newBatchProcessor returns a new batch processor component.\nfunc newBatchProcessor[T any](set processor.Settings, cfg *Config, batchFunc func() batch[T]) (*batchProcessor[T], error) {\n\t// use lower-case, to be consistent with http/2 headers.\n\tmks := make([]string, len(cfg.MetadataKeys))\n\tfor i, k := range cfg.MetadataKeys {\n\t\tmks[i] = strings.ToLower(k)\n\t}\n\tsort.Strings(mks)\n\tbp := &batchProcessor[T]{\n\t\tlogger: set.Logger,\n\n\t\tsendBatchSize:    int(cfg.SendBatchSize),\n\t\tsendBatchMaxSize: int(cfg.SendBatchMaxSize),\n\t\ttimeout:          cfg.Timeout,\n\t\tbatchFunc:        batchFunc,\n\t\tshutdownC:        make(chan struct{}, 1),\n\t}\n\tif len(mks) == 0 {\n\t\tbp.batcher = &singleShardBatcher[T]{\n\t\t\tprocessor: bp,\n\t\t\tsingle:    bp.newShard(nil),\n\t\t}\n\t} else {\n\t\tbp.batcher = &multiShardBatcher[T]{\n\t\t\tmetadataKeys:  mks,\n\t\t\tmetadataLimit: int(cfg.MetadataCardinalityLimit),\n\t\t\tprocessor:     bp,\n\t\t}\n\t}\n\n\tbpt, err := newBatchProcessorTelemetry(set, bp.batcher.currentMetadataCardinality)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating batch processor telemetry: %w\", err)\n\t}\n\tbp.telemetry = bpt\n\n\treturn bp, nil\n}\n\n// newShard gets or creates a batcher corresponding with attrs.\nfunc (bp *batchProcessor[T]) newShard(md map[string][]string) *shard[T] {\n\texportCtx := client.NewContext(context.Background(), client.Info{\n\t\tMetadata: client.NewMetadata(md),\n\t})\n\tb := &shard[T]{\n\t\tprocessor: bp,\n\t\tnewItem:   make(chan T, runtime.NumCPU()),\n\t\texportCtx: exportCtx,\n\t\tbatch:     bp.batchFunc(),\n\t}\n\treturn b\n}\n\nfunc (bp *batchProcessor[T]) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: true}\n}\n\n// Start is invoked during service startup.\nfunc (bp *batchProcessor[T]) Start(ctx context.Context, _ component.Host) error {\n\treturn bp.batcher.start(ctx)\n}\n\n// Shutdown is invoked during service shutdown.\nfunc (bp *batchProcessor[T]) Shutdown(context.Context) error {\n\tclose(bp.shutdownC)\n\n\t// Wait until all goroutines are done.\n\tbp.goroutines.Wait()\n\n\treturn nil\n}\n\nfunc (b *shard[T]) start() {\n\tb.processor.goroutines.Go(b.startLoop)\n}\n\nfunc (b *shard[T]) startLoop() {\n\t// timerCh ensures we only block when there is a\n\t// timer, since <- from a nil channel is blocking.\n\tvar timerCh <-chan time.Time\n\tif b.processor.timeout != 0 && b.processor.sendBatchSize != 0 {\n\t\tb.timer = time.NewTimer(b.processor.timeout)\n\t\ttimerCh = b.timer.C\n\t}\n\tfor {\n\t\tselect {\n\t\tcase <-b.processor.shutdownC:\n\t\tDONE:\n\t\t\tfor {\n\t\t\t\tselect {\n\t\t\t\tcase item := <-b.newItem:\n\t\t\t\t\tb.processItem(item)\n\t\t\t\tdefault:\n\t\t\t\t\tbreak DONE\n\t\t\t\t}\n\t\t\t}\n\t\t\t// This is the close of the channel\n\t\t\tif b.batch.itemCount() > 0 {\n\t\t\t\t// TODO: Set a timeout on sendTraces or\n\t\t\t\t// make it cancellable using the context that Shutdown gets as a parameter\n\t\t\t\tb.sendItems(triggerTimeout)\n\t\t\t}\n\t\t\treturn\n\t\tcase item := <-b.newItem:\n\t\t\tb.processItem(item)\n\t\tcase <-timerCh:\n\t\t\tif b.batch.itemCount() > 0 {\n\t\t\t\tb.sendItems(triggerTimeout)\n\t\t\t}\n\t\t\tb.resetTimer()\n\t\t}\n\t}\n}\n\nfunc (b *shard[T]) processItem(item T) {\n\tb.batch.add(item)\n\tsent := false\n\tfor b.batch.itemCount() > 0 && (!b.hasTimer() || b.batch.itemCount() >= b.processor.sendBatchSize) {\n\t\tsent = true\n\t\tb.sendItems(triggerBatchSize)\n\t}\n\n\tif sent {\n\t\tb.stopTimer()\n\t\tb.resetTimer()\n\t}\n}\n\nfunc (b *shard[T]) hasTimer() bool {\n\treturn b.timer != nil\n}\n\nfunc (b *shard[T]) stopTimer() {\n\tif b.hasTimer() && !b.timer.Stop() {\n\t\t<-b.timer.C\n\t}\n}\n\nfunc (b *shard[T]) resetTimer() {\n\tif b.hasTimer() {\n\t\tb.timer.Reset(b.processor.timeout)\n\t}\n}\n\nfunc (b *shard[T]) sendItems(trigger trigger) {\n\tsent, req := b.batch.split(b.processor.sendBatchMaxSize)\n\n\tbpt := b.processor.telemetry\n\tvar bytes int\n\t// Check if the instrument is enabled to calculate the size of the batch in bytes.\n\t// See https://pkg.go.dev/go.opentelemetry.io/otel/sdk/metric/internal/x#readme-instrument-enabled\n\tbatchSendSizeBytes := bpt.telemetryBuilder.ProcessorBatchBatchSendSizeBytes\n\tinstr, ok := batchSendSizeBytes.(interface{ Enabled(context.Context) bool })\n\tif !ok || instr.Enabled(bpt.exportCtx) {\n\t\tbytes = b.batch.sizeBytes(req)\n\t}\n\n\terr := b.batch.export(b.exportCtx, req)\n\tif err != nil {\n\t\tb.processor.logger.Warn(\"Sender failed\", zap.Error(err))\n\t\treturn\n\t}\n\tbpt.record(trigger, int64(sent), int64(bytes))\n}\n\n// singleShardBatcher is used when metadataKeys is empty, to avoid the\n// additional lock and map operations used in multiBatcher.\ntype singleShardBatcher[T any] struct {\n\tprocessor *batchProcessor[T]\n\tsingle    *shard[T]\n}\n\nfunc (sb *singleShardBatcher[T]) start(context.Context) error {\n\tsb.single.start()\n\treturn nil\n}\n\nfunc (sb *singleShardBatcher[T]) consume(_ context.Context, data T) error {\n\tsb.single.newItem <- data\n\treturn nil\n}\n\nfunc (sb *singleShardBatcher[T]) currentMetadataCardinality() int {\n\treturn 1\n}\n\n// multiShardBatcher is used when metadataKeys is not empty.\ntype multiShardBatcher[T any] struct {\n\t// metadataKeys is the configured list of metadata keys.  When\n\t// empty, the `singleton` batcher is used.  When non-empty,\n\t// each distinct combination of metadata keys and values\n\t// triggers a new batcher, counted in `goroutines`.\n\tmetadataKeys []string\n\n\t// metadataLimit is the limiting size of the batchers map.\n\tmetadataLimit int\n\n\tprocessor *batchProcessor[T]\n\tbatchers  sync.Map\n\n\t// Guards the size and the storing logic to ensure no more than limit items are stored.\n\t// If we are willing to allow \"some\" extra items than the limit this can be removed and size can be made atomic.\n\tlock sync.Mutex\n\tsize int\n}\n\nfunc (mb *multiShardBatcher[T]) start(context.Context) error {\n\treturn nil\n}\n\nfunc (mb *multiShardBatcher[T]) consume(ctx context.Context, data T) error {\n\t// Get each metadata key value, form the corresponding\n\t// attribute set for use as a map lookup key.\n\tinfo := client.FromContext(ctx)\n\tattrs := make([]attribute.KeyValue, 0, len(mb.metadataKeys))\n\tfor _, k := range mb.metadataKeys {\n\t\t// Lookup the value in the incoming metadata, copy it\n\t\t// into the outgoing metadata, and create a unique\n\t\t// value for the attributeSet.\n\t\tvs := info.Metadata.Get(k)\n\t\tif len(vs) == 1 {\n\t\t\tattrs = append(attrs, attribute.String(k, vs[0]))\n\t\t} else {\n\t\t\tattrs = append(attrs, attribute.StringSlice(k, vs))\n\t\t}\n\t}\n\taset := attribute.NewSet(attrs...)\n\n\tb, ok := mb.batchers.Load(aset)\n\tif !ok {\n\t\tmb.lock.Lock()\n\t\tif mb.metadataLimit != 0 && mb.size >= mb.metadataLimit {\n\t\t\tmb.lock.Unlock()\n\t\t\treturn errTooManyBatchers\n\t\t}\n\n\t\t// aset.ToSlice() returns the sorted, deduplicated,\n\t\t// and name-lowercased list of attributes.\n\t\tvar loaded bool\n\t\tmd := make(map[string][]string, len(mb.metadataKeys))\n\t\tfor _, k := range mb.metadataKeys {\n\t\t\tmd[k] = info.Metadata.Get(k)\n\t\t}\n\t\tb, loaded = mb.batchers.LoadOrStore(aset, mb.processor.newShard(md))\n\t\tif !loaded {\n\t\t\t// Start the goroutine only if we added the object to the map, otherwise is already started.\n\t\t\tb.(*shard[T]).start()\n\t\t\tmb.size++\n\t\t}\n\t\tmb.lock.Unlock()\n\t}\n\tb.(*shard[T]).newItem <- data\n\treturn nil\n}\n\nfunc (mb *multiShardBatcher[T]) currentMetadataCardinality() int {\n\tmb.lock.Lock()\n\tdefer mb.lock.Unlock()\n\treturn mb.size\n}\n\ntype tracesBatchProcessor struct {\n\t*batchProcessor[ptrace.Traces]\n}\n\n// newTracesBatchProcessor creates a new batch processor that batches traces by size or with timeout\nfunc newTracesBatchProcessor(set processor.Settings, next consumer.Traces, cfg *Config) (processor.Traces, error) {\n\tbp, err := newBatchProcessor(set, cfg, func() batch[ptrace.Traces] { return newBatchTraces(next) })\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &tracesBatchProcessor{batchProcessor: bp}, nil\n}\n\nfunc (t *tracesBatchProcessor) ConsumeTraces(ctx context.Context, td ptrace.Traces) error {\n\tpref.RefTraces(td)\n\treturn t.batcher.consume(ctx, td)\n}\n\ntype metricsBatchProcessor struct {\n\t*batchProcessor[pmetric.Metrics]\n}\n\n// newMetricsBatchProcessor creates a new batch processor that batches metrics by size or with timeout\nfunc newMetricsBatchProcessor(set processor.Settings, next consumer.Metrics, cfg *Config) (processor.Metrics, error) {\n\tbp, err := newBatchProcessor(set, cfg, func() batch[pmetric.Metrics] { return newMetricsBatch(next) })\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &metricsBatchProcessor{batchProcessor: bp}, nil\n}\n\n// ConsumeMetrics implements processor.Metrics\nfunc (m *metricsBatchProcessor) ConsumeMetrics(ctx context.Context, md pmetric.Metrics) error {\n\tpref.RefMetrics(md)\n\treturn m.batcher.consume(ctx, md)\n}\n\ntype logsBatchProcessor struct {\n\t*batchProcessor[plog.Logs]\n}\n\n// newLogsBatchProcessor creates a new batch processor that batches logs by size or with timeout\nfunc newLogsBatchProcessor(set processor.Settings, next consumer.Logs, cfg *Config) (processor.Logs, error) {\n\tbp, err := newBatchProcessor(set, cfg, func() batch[plog.Logs] { return newBatchLogs(next) })\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &logsBatchProcessor{batchProcessor: bp}, nil\n}\n\n// ConsumeLogs implements processor.Logs\nfunc (l *logsBatchProcessor) ConsumeLogs(ctx context.Context, ld plog.Logs) error {\n\tpref.RefLogs(ld)\n\treturn l.batcher.consume(ctx, ld)\n}\n\ntype batchTraces struct {\n\tnextConsumer consumer.Traces\n\ttraceData    ptrace.Traces\n\tspanCount    int\n\tsizer        ptrace.Sizer\n}\n\nfunc newBatchTraces(nextConsumer consumer.Traces) *batchTraces {\n\treturn &batchTraces{nextConsumer: nextConsumer, traceData: ptrace.NewTraces(), sizer: &ptrace.ProtoMarshaler{}}\n}\n\n// add updates current batchTraces by adding new TraceData object\nfunc (bt *batchTraces) add(td ptrace.Traces) {\n\tdefer pref.UnrefTraces(td)\n\tnewSpanCount := td.SpanCount()\n\tif newSpanCount == 0 {\n\t\treturn\n\t}\n\n\tbt.spanCount += newSpanCount\n\ttd.ResourceSpans().MoveAndAppendTo(bt.traceData.ResourceSpans())\n}\n\nfunc (bt *batchTraces) sizeBytes(td ptrace.Traces) int {\n\treturn bt.sizer.TracesSize(td)\n}\n\nfunc (bt *batchTraces) export(ctx context.Context, td ptrace.Traces) error {\n\treturn bt.nextConsumer.ConsumeTraces(ctx, td)\n}\n\nfunc (bt *batchTraces) split(sendBatchMaxSize int) (int, ptrace.Traces) {\n\tvar td ptrace.Traces\n\tvar sent int\n\tif sendBatchMaxSize > 0 && bt.itemCount() > sendBatchMaxSize {\n\t\ttd = splitTraces(sendBatchMaxSize, bt.traceData)\n\t\tbt.spanCount -= sendBatchMaxSize\n\t\tsent = sendBatchMaxSize\n\t} else {\n\t\ttd = bt.traceData\n\t\tsent = bt.spanCount\n\t\tbt.traceData = ptrace.NewTraces()\n\t\tbt.spanCount = 0\n\t}\n\treturn sent, td\n}\n\nfunc (bt *batchTraces) itemCount() int {\n\treturn bt.spanCount\n}\n\ntype batchMetrics struct {\n\tnextConsumer   consumer.Metrics\n\tmetricData     pmetric.Metrics\n\tdataPointCount int\n\tsizer          pmetric.Sizer\n}\n\nfunc newMetricsBatch(nextConsumer consumer.Metrics) *batchMetrics {\n\treturn &batchMetrics{nextConsumer: nextConsumer, metricData: pmetric.NewMetrics(), sizer: &pmetric.ProtoMarshaler{}}\n}\n\nfunc (bm *batchMetrics) sizeBytes(md pmetric.Metrics) int {\n\treturn bm.sizer.MetricsSize(md)\n}\n\nfunc (bm *batchMetrics) export(ctx context.Context, md pmetric.Metrics) error {\n\treturn bm.nextConsumer.ConsumeMetrics(ctx, md)\n}\n\nfunc (bm *batchMetrics) split(sendBatchMaxSize int) (int, pmetric.Metrics) {\n\tvar md pmetric.Metrics\n\tvar sent int\n\tif sendBatchMaxSize > 0 && bm.dataPointCount > sendBatchMaxSize {\n\t\tmd = splitMetrics(sendBatchMaxSize, bm.metricData)\n\t\tbm.dataPointCount -= sendBatchMaxSize\n\t\tsent = sendBatchMaxSize\n\t} else {\n\t\tmd = bm.metricData\n\t\tsent = bm.dataPointCount\n\t\tbm.metricData = pmetric.NewMetrics()\n\t\tbm.dataPointCount = 0\n\t}\n\n\treturn sent, md\n}\n\nfunc (bm *batchMetrics) itemCount() int {\n\treturn bm.dataPointCount\n}\n\nfunc (bm *batchMetrics) add(md pmetric.Metrics) {\n\tdefer pref.UnrefMetrics(md)\n\tnewDataPointCount := md.DataPointCount()\n\tif newDataPointCount == 0 {\n\t\treturn\n\t}\n\tbm.dataPointCount += newDataPointCount\n\tmd.ResourceMetrics().MoveAndAppendTo(bm.metricData.ResourceMetrics())\n}\n\ntype batchLogs struct {\n\tnextConsumer consumer.Logs\n\tlogData      plog.Logs\n\tlogCount     int\n\tsizer        plog.Sizer\n}\n\nfunc newBatchLogs(nextConsumer consumer.Logs) *batchLogs {\n\treturn &batchLogs{nextConsumer: nextConsumer, logData: plog.NewLogs(), sizer: &plog.ProtoMarshaler{}}\n}\n\nfunc (bl *batchLogs) sizeBytes(ld plog.Logs) int {\n\treturn bl.sizer.LogsSize(ld)\n}\n\nfunc (bl *batchLogs) export(ctx context.Context, ld plog.Logs) error {\n\treturn bl.nextConsumer.ConsumeLogs(ctx, ld)\n}\n\nfunc (bl *batchLogs) split(sendBatchMaxSize int) (int, plog.Logs) {\n\tvar ld plog.Logs\n\tvar sent int\n\n\tif sendBatchMaxSize > 0 && bl.logCount > sendBatchMaxSize {\n\t\tld = splitLogs(sendBatchMaxSize, bl.logData)\n\t\tbl.logCount -= sendBatchMaxSize\n\t\tsent = sendBatchMaxSize\n\t} else {\n\t\tld = bl.logData\n\t\tsent = bl.logCount\n\t\tbl.logData = plog.NewLogs()\n\t\tbl.logCount = 0\n\t}\n\treturn sent, ld\n}\n\nfunc (bl *batchLogs) itemCount() int {\n\treturn bl.logCount\n}\n\nfunc (bl *batchLogs) add(ld plog.Logs) {\n\tdefer pref.UnrefLogs(ld)\n\tnewLogsCount := ld.LogRecordCount()\n\tif newLogsCount == 0 {\n\t\treturn\n\t}\n\tbl.logCount += newLogsCount\n\tld.ResourceLogs().MoveAndAppendTo(bl.logData.ResourceLogs())\n}\n"
  },
  {
    "path": "processor/batchprocessor/batch_processor_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage batchprocessor\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"math\"\n\t\"strconv\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/client\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/processor/batchprocessor/internal/metadata\"\n\t\"go.opentelemetry.io/collector/processor/batchprocessor/internal/metadatatest\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n)\n\nfunc TestProcessorShutdown(t *testing.T) {\n\tfactory := NewFactory()\n\n\tctx := context.Background()\n\tprocessorCreationSet := processortest.NewNopSettings(metadata.Type)\n\n\tfor range 5 {\n\t\trequire.NotPanics(t, func() {\n\t\t\ttProc, err := factory.CreateTraces(ctx, processorCreationSet, factory.CreateDefaultConfig(), consumertest.NewNop())\n\t\t\trequire.NoError(t, err)\n\t\t\t_ = tProc.Shutdown(ctx)\n\t\t})\n\n\t\trequire.NotPanics(t, func() {\n\t\t\tmProc, err := factory.CreateMetrics(ctx, processorCreationSet, factory.CreateDefaultConfig(), consumertest.NewNop())\n\t\t\trequire.NoError(t, err)\n\t\t\t_ = mProc.Shutdown(ctx)\n\t\t})\n\n\t\trequire.NotPanics(t, func() {\n\t\t\tlProc, err := factory.CreateLogs(ctx, processorCreationSet, factory.CreateDefaultConfig(), consumertest.NewNop())\n\t\t\trequire.NoError(t, err)\n\t\t\t_ = lProc.Shutdown(ctx)\n\t\t})\n\t}\n}\n\nfunc TestProcessorLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\tctx := context.Background()\n\tprocessorCreationSet := processortest.NewNopSettings(metadata.Type)\n\n\tfor range 5 {\n\t\ttProc, err := factory.CreateTraces(ctx, processorCreationSet, factory.CreateDefaultConfig(), consumertest.NewNop())\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, tProc.Start(ctx, componenttest.NewNopHost()))\n\t\trequire.NoError(t, tProc.Shutdown(ctx))\n\n\t\tmProc, err := factory.CreateMetrics(ctx, processorCreationSet, factory.CreateDefaultConfig(), consumertest.NewNop())\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, mProc.Start(ctx, componenttest.NewNopHost()))\n\t\trequire.NoError(t, mProc.Shutdown(ctx))\n\n\t\tlProc, err := factory.CreateLogs(ctx, processorCreationSet, factory.CreateDefaultConfig(), consumertest.NewNop())\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, lProc.Start(ctx, componenttest.NewNopHost()))\n\t\trequire.NoError(t, lProc.Shutdown(ctx))\n\t}\n}\n\nfunc TestBatchProcessorSpansDelivered(t *testing.T) {\n\tsink := new(consumertest.TracesSink)\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.SendBatchSize = 128\n\ttraces, err := NewFactory().CreateTraces(context.Background(), processortest.NewNopSettings(metadata.Type), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, traces.Start(context.Background(), componenttest.NewNopHost()))\n\n\trequestCount := 1000\n\tspansPerRequest := 100\n\tsentResourceSpans := ptrace.NewTraces().ResourceSpans()\n\tfor requestNum := range requestCount {\n\t\ttd := testdata.GenerateTraces(spansPerRequest)\n\t\tspans := td.ResourceSpans().At(0).ScopeSpans().At(0).Spans()\n\t\tfor spanIndex := range spansPerRequest {\n\t\t\tspans.At(spanIndex).SetName(getTestSpanName(requestNum, spanIndex))\n\t\t}\n\t\ttd.ResourceSpans().At(0).CopyTo(sentResourceSpans.AppendEmpty())\n\t\trequire.NoError(t, traces.ConsumeTraces(context.Background(), td))\n\t}\n\n\t// Added to test logic that check for empty resources.\n\ttd := ptrace.NewTraces()\n\tassert.NoError(t, traces.ConsumeTraces(context.Background(), td))\n\n\trequire.NoError(t, traces.Shutdown(context.Background()))\n\n\trequire.Equal(t, requestCount*spansPerRequest, sink.SpanCount())\n\treceivedTraces := sink.AllTraces()\n\tspansReceivedByName := spansReceivedByName(receivedTraces)\n\tfor requestNum := range requestCount {\n\t\tspans := sentResourceSpans.At(requestNum).ScopeSpans().At(0).Spans()\n\t\tfor spanIndex := range spansPerRequest {\n\t\t\trequire.Equal(t,\n\t\t\t\tspans.At(spanIndex),\n\t\t\t\tspansReceivedByName[getTestSpanName(requestNum, spanIndex)])\n\t\t}\n\t}\n}\n\nfunc TestBatchProcessorSpansDeliveredEnforceBatchSize(t *testing.T) {\n\tsink := new(consumertest.TracesSink)\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.SendBatchSize = 128\n\tcfg.SendBatchMaxSize = 130\n\ttraces, err := NewFactory().CreateTraces(context.Background(), processortest.NewNopSettings(metadata.Type), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, traces.Start(context.Background(), componenttest.NewNopHost()))\n\n\trequestCount := 1000\n\tspansPerRequest := 150\n\tfor requestNum := range requestCount {\n\t\ttd := testdata.GenerateTraces(spansPerRequest)\n\t\tspans := td.ResourceSpans().At(0).ScopeSpans().At(0).Spans()\n\t\tfor spanIndex := range spansPerRequest {\n\t\t\tspans.At(spanIndex).SetName(getTestSpanName(requestNum, spanIndex))\n\t\t}\n\t\trequire.NoError(t, traces.ConsumeTraces(context.Background(), td))\n\t}\n\n\t// Added to test logic that check for empty resources.\n\ttd := ptrace.NewTraces()\n\trequire.NoError(t, traces.ConsumeTraces(context.Background(), td))\n\n\t// wait for all spans to be reported\n\tfor sink.SpanCount() != requestCount*spansPerRequest {\n\t\t<-time.After(cfg.Timeout)\n\t}\n\n\trequire.NoError(t, traces.Shutdown(context.Background()))\n\n\trequire.Equal(t, requestCount*spansPerRequest, sink.SpanCount())\n\tfor i := 0; i < len(sink.AllTraces())-1; i++ {\n\t\tassert.Equal(t, int(cfg.SendBatchMaxSize), sink.AllTraces()[i].SpanCount())\n\t}\n\t// the last batch has the remaining size\n\tassert.Equal(t, (requestCount*spansPerRequest)%int(cfg.SendBatchMaxSize), sink.AllTraces()[len(sink.AllTraces())-1].SpanCount())\n}\n\nfunc TestBatchProcessorSentBySize(t *testing.T) {\n\tconst (\n\t\tsendBatchSize          = 20\n\t\trequestCount           = 100\n\t\tspansPerRequest        = 5\n\t\texpectedBatchesNum     = requestCount * spansPerRequest / sendBatchSize\n\t\texpectedBatchingFactor = sendBatchSize / spansPerRequest\n\t)\n\n\ttel := componenttest.NewTelemetry()\n\tsizer := &ptrace.ProtoMarshaler{}\n\tsink := new(consumertest.TracesSink)\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.SendBatchSize = sendBatchSize\n\tcfg.Timeout = 500 * time.Millisecond\n\n\ttraces, err := NewFactory().CreateTraces(context.Background(), metadatatest.NewSettings(tel), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, traces.Start(context.Background(), componenttest.NewNopHost()))\n\n\tstart := time.Now()\n\tsizeSum := 0\n\tfor range requestCount {\n\t\ttd := testdata.GenerateTraces(spansPerRequest)\n\n\t\trequire.NoError(t, traces.ConsumeTraces(context.Background(), td))\n\t}\n\n\trequire.NoError(t, traces.Shutdown(context.Background()))\n\n\telapsed := time.Since(start)\n\trequire.LessOrEqual(t, elapsed.Nanoseconds(), cfg.Timeout.Nanoseconds())\n\n\trequire.Equal(t, requestCount*spansPerRequest, sink.SpanCount())\n\treceivedTraces := sink.AllTraces()\n\trequire.Len(t, receivedTraces, expectedBatchesNum)\n\tfor _, td := range receivedTraces {\n\t\tsizeSum += sizer.TracesSize(td)\n\t\trss := td.ResourceSpans()\n\t\trequire.Equal(t, expectedBatchingFactor, rss.Len())\n\t\tfor i := range expectedBatchingFactor {\n\t\t\trequire.Equal(t, spansPerRequest, rss.At(i).ScopeSpans().At(0).Spans().Len())\n\t\t}\n\t}\n\n\tmetadatatest.AssertEqualProcessorBatchBatchSendSizeBytes(t, tel,\n\t\t[]metricdata.HistogramDataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"batch\")),\n\t\t\t\tCount:      uint64(expectedBatchesNum),\n\t\t\t\tBounds: []float64{\n\t\t\t\t\t10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000,\n\t\t\t\t\t100_000, 200_000, 300_000, 400_000, 500_000, 600_000, 700_000, 800_000, 900_000,\n\t\t\t\t\t1000_000, 2000_000, 3000_000, 4000_000, 5000_000, 6000_000, 7000_000, 8000_000, 9000_000,\n\t\t\t\t},\n\t\t\t\tBucketCounts: []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, uint64(expectedBatchesNum), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\tSum:          int64(sizeSum),\n\t\t\t\tMin:          metricdata.NewExtrema(int64(sizeSum / expectedBatchesNum)),\n\t\t\t\tMax:          metricdata.NewExtrema(int64(sizeSum / expectedBatchesNum)),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\n\tmetadatatest.AssertEqualProcessorBatchBatchSendSize(t, tel,\n\t\t[]metricdata.HistogramDataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes:   attribute.NewSet(attribute.String(\"processor\", \"batch\")),\n\t\t\t\tCount:        uint64(expectedBatchesNum),\n\t\t\t\tBounds:       []float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, 100000},\n\t\t\t\tBucketCounts: []uint64{0, uint64(expectedBatchesNum), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\tSum:          int64(sink.SpanCount()),\n\t\t\t\tMin:          metricdata.NewExtrema(int64(sendBatchSize)),\n\t\t\t\tMax:          metricdata.NewExtrema(int64(sendBatchSize)),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\n\tmetadatatest.AssertEqualProcessorBatchBatchSizeTriggerSend(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      int64(expectedBatchesNum),\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"batch\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\n\tmetadatatest.AssertEqualProcessorBatchMetadataCardinality(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      1,\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"batch\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\n\trequire.NoError(t, tel.Shutdown(context.Background()))\n}\n\nfunc TestBatchProcessorSentBySizeWithMaxSize(t *testing.T) {\n\tconst (\n\t\tsendBatchSize    = 20\n\t\tsendBatchMaxSize = 37\n\t\trequestCount     = 1\n\t\tspansPerRequest  = 500\n\t\ttotalSpans       = requestCount * spansPerRequest\n\t)\n\n\ttel := componenttest.NewTelemetry()\n\tsizer := &ptrace.ProtoMarshaler{}\n\tsink := new(consumertest.TracesSink)\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.SendBatchSize = uint32(sendBatchSize)\n\tcfg.SendBatchMaxSize = uint32(sendBatchMaxSize)\n\tcfg.Timeout = 500 * time.Millisecond\n\n\ttraces, err := NewFactory().CreateTraces(context.Background(), metadatatest.NewSettings(tel), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, traces.Start(context.Background(), componenttest.NewNopHost()))\n\n\tstart := time.Now()\n\n\tsizeSum := 0\n\tfor range requestCount {\n\t\ttd := testdata.GenerateTraces(spansPerRequest)\n\t\trequire.NoError(t, traces.ConsumeTraces(context.Background(), td))\n\t}\n\n\trequire.NoError(t, traces.Shutdown(context.Background()))\n\n\telapsed := time.Since(start)\n\trequire.LessOrEqual(t, elapsed.Nanoseconds(), cfg.Timeout.Nanoseconds())\n\n\t// The max batch size is not a divisor of the total number of spans\n\texpectedBatchesNum := math.Ceil(float64(totalSpans) / float64(sendBatchMaxSize))\n\n\trequire.Equal(t, totalSpans, sink.SpanCount())\n\treceivedTraces := sink.AllTraces()\n\trequire.Len(t, receivedTraces, int(expectedBatchesNum))\n\t// we have to count the size after it was processed since splitTraces will cause some\n\t// repeated ResourceSpan data to be sent through the processor\n\tminSize := math.MaxInt\n\tmaxSize := math.MinInt\n\tfor _, td := range receivedTraces {\n\t\tminSize = min(minSize, sizer.TracesSize(td))\n\t\tmaxSize = max(maxSize, sizer.TracesSize(td))\n\t\tsizeSum += sizer.TracesSize(td)\n\t}\n\n\tmetadatatest.AssertEqualProcessorBatchBatchSendSizeBytes(t, tel,\n\t\t[]metricdata.HistogramDataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"batch\")),\n\t\t\t\tCount:      uint64(expectedBatchesNum),\n\t\t\t\tBounds: []float64{\n\t\t\t\t\t10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000,\n\t\t\t\t\t100_000, 200_000, 300_000, 400_000, 500_000, 600_000, 700_000, 800_000, 900_000,\n\t\t\t\t\t1000_000, 2000_000, 3000_000, 4000_000, 5000_000, 6000_000, 7000_000, 8000_000, 9000_000,\n\t\t\t\t},\n\t\t\t\tBucketCounts: []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, uint64(expectedBatchesNum - 1), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\tSum:          int64(sizeSum),\n\t\t\t\tMin:          metricdata.NewExtrema(int64(minSize)),\n\t\t\t\tMax:          metricdata.NewExtrema(int64(maxSize)),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\n\tmetadatatest.AssertEqualProcessorBatchBatchSendSize(t, tel,\n\t\t[]metricdata.HistogramDataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes:   attribute.NewSet(attribute.String(\"processor\", \"batch\")),\n\t\t\t\tCount:        uint64(expectedBatchesNum),\n\t\t\t\tBounds:       []float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, 100000},\n\t\t\t\tBucketCounts: []uint64{0, 1, uint64(expectedBatchesNum - 1), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\tSum:          int64(sink.SpanCount()),\n\t\t\t\tMin:          metricdata.NewExtrema(int64(sendBatchSize - 1)),\n\t\t\t\tMax:          metricdata.NewExtrema(int64(cfg.SendBatchMaxSize)),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\n\tmetadatatest.AssertEqualProcessorBatchBatchSizeTriggerSend(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      int64(expectedBatchesNum - 1),\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"batch\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\n\tmetadatatest.AssertEqualProcessorBatchMetadataCardinality(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      1,\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"batch\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\n\trequire.NoError(t, tel.Shutdown(context.Background()))\n}\n\nfunc TestBatchProcessorSentByTimeout(t *testing.T) {\n\tsink := new(consumertest.TracesSink)\n\tcfg := createDefaultConfig().(*Config)\n\tsendBatchSize := 100\n\tcfg.SendBatchSize = uint32(sendBatchSize)\n\tcfg.Timeout = 100 * time.Millisecond\n\n\trequestCount := 5\n\tspansPerRequest := 10\n\tstart := time.Now()\n\n\ttraces, err := NewFactory().CreateTraces(context.Background(), processortest.NewNopSettings(metadata.Type), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, traces.Start(context.Background(), componenttest.NewNopHost()))\n\n\tfor range requestCount {\n\t\ttd := testdata.GenerateTraces(spansPerRequest)\n\t\trequire.NoError(t, traces.ConsumeTraces(context.Background(), td))\n\t}\n\n\t// Wait for at least one batch to be sent.\n\tfor sink.SpanCount() == 0 {\n\t\t<-time.After(cfg.Timeout)\n\t}\n\n\telapsed := time.Since(start)\n\trequire.LessOrEqual(t, cfg.Timeout.Nanoseconds(), elapsed.Nanoseconds())\n\n\t// This should not change the results in the sink, verified by the expectedBatchesNum\n\trequire.NoError(t, traces.Shutdown(context.Background()))\n\n\texpectedBatchesNum := 1\n\texpectedBatchingFactor := 5\n\n\trequire.Equal(t, requestCount*spansPerRequest, sink.SpanCount())\n\treceivedTraces := sink.AllTraces()\n\trequire.Len(t, receivedTraces, expectedBatchesNum)\n\tfor _, td := range receivedTraces {\n\t\trss := td.ResourceSpans()\n\t\trequire.Equal(t, expectedBatchingFactor, rss.Len())\n\t\tfor i := range expectedBatchingFactor {\n\t\t\trequire.Equal(t, spansPerRequest, rss.At(i).ScopeSpans().At(0).Spans().Len())\n\t\t}\n\t}\n}\n\nfunc TestBatchProcessorTraceSendWhenClosing(t *testing.T) {\n\tcfg := &Config{\n\t\tTimeout:       3 * time.Second,\n\t\tSendBatchSize: 1000,\n\t}\n\tsink := new(consumertest.TracesSink)\n\n\ttraces, err := NewFactory().CreateTraces(context.Background(), processortest.NewNopSettings(metadata.Type), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, traces.Start(context.Background(), componenttest.NewNopHost()))\n\n\trequestCount := 10\n\tspansPerRequest := 10\n\tfor range requestCount {\n\t\ttd := testdata.GenerateTraces(spansPerRequest)\n\t\trequire.NoError(t, traces.ConsumeTraces(context.Background(), td))\n\t}\n\n\trequire.NoError(t, traces.Shutdown(context.Background()))\n\n\trequire.Equal(t, requestCount*spansPerRequest, sink.SpanCount())\n\trequire.Len(t, sink.AllTraces(), 1)\n}\n\nfunc TestBatchMetricProcessor_ReceivingData(t *testing.T) {\n\t// Instantiate the batch processor with low config values to test data\n\t// gets sent through the processor.\n\tcfg := &Config{\n\t\tTimeout:       200 * time.Millisecond,\n\t\tSendBatchSize: 50,\n\t}\n\n\trequestCount := 100\n\tmetricsPerRequest := 5\n\tsink := new(consumertest.MetricsSink)\n\n\tmetrics, err := NewFactory().CreateMetrics(context.Background(), processortest.NewNopSettings(metadata.Type), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, metrics.Start(context.Background(), componenttest.NewNopHost()))\n\n\tsentResourceMetrics := pmetric.NewMetrics().ResourceMetrics()\n\n\tfor requestNum := range requestCount {\n\t\tmd := testdata.GenerateMetrics(metricsPerRequest)\n\t\tms := md.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics()\n\t\tfor metricIndex := range metricsPerRequest {\n\t\t\tms.At(metricIndex).SetName(getTestMetricName(requestNum, metricIndex))\n\t\t}\n\t\tmd.ResourceMetrics().At(0).CopyTo(sentResourceMetrics.AppendEmpty())\n\t\trequire.NoError(t, metrics.ConsumeMetrics(context.Background(), md))\n\t}\n\n\t// Added to test case with empty resources sent.\n\tmd := pmetric.NewMetrics()\n\tassert.NoError(t, metrics.ConsumeMetrics(context.Background(), md))\n\n\trequire.NoError(t, metrics.Shutdown(context.Background()))\n\n\trequire.Equal(t, requestCount*2*metricsPerRequest, sink.DataPointCount())\n\treceivedMds := sink.AllMetrics()\n\tmetricsReceivedByName := metricsReceivedByName(receivedMds)\n\tfor requestNum := range requestCount {\n\t\tms := sentResourceMetrics.At(requestNum).ScopeMetrics().At(0).Metrics()\n\t\tfor metricIndex := range metricsPerRequest {\n\t\t\trequire.Equal(t,\n\t\t\t\tms.At(metricIndex),\n\t\t\t\tmetricsReceivedByName[getTestMetricName(requestNum, metricIndex)])\n\t\t}\n\t}\n}\n\nfunc TestBatchMetricProcessorBatchSize(t *testing.T) {\n\ttel := componenttest.NewTelemetry()\n\tsizer := &pmetric.ProtoMarshaler{}\n\n\t// Instantiate the batch processor with low config values to test data\n\t// gets sent through the processor.\n\tcfg := &Config{\n\t\tTimeout:       100 * time.Millisecond,\n\t\tSendBatchSize: 50,\n\t}\n\n\tconst (\n\t\trequestCount         = 100\n\t\tmetricsPerRequest    = 5\n\t\tdataPointsPerMetric  = 2 // Since the int counter uses two datapoints.\n\t\tdataPointsPerRequest = metricsPerRequest * dataPointsPerMetric\n\t)\n\tsink := new(consumertest.MetricsSink)\n\n\tmetrics, err := NewFactory().CreateMetrics(context.Background(), metadatatest.NewSettings(tel), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, metrics.Start(context.Background(), componenttest.NewNopHost()))\n\n\tstart := time.Now()\n\tsize := 0\n\tfor range requestCount {\n\t\tmd := testdata.GenerateMetrics(metricsPerRequest)\n\t\tsize += sizer.MetricsSize(md)\n\t\trequire.NoError(t, metrics.ConsumeMetrics(context.Background(), md))\n\t}\n\trequire.NoError(t, metrics.Shutdown(context.Background()))\n\n\telapsed := time.Since(start)\n\trequire.LessOrEqual(t, elapsed.Nanoseconds(), cfg.Timeout.Nanoseconds())\n\n\texpectedBatchesNum := requestCount * dataPointsPerRequest / cfg.SendBatchSize\n\texpectedBatchingFactor := int(cfg.SendBatchSize) / dataPointsPerRequest\n\n\trequire.Equal(t, requestCount*2*metricsPerRequest, sink.DataPointCount())\n\treceivedMds := sink.AllMetrics()\n\trequire.Len(t, receivedMds, int(expectedBatchesNum))\n\tfor _, md := range receivedMds {\n\t\trequire.Equal(t, expectedBatchingFactor, md.ResourceMetrics().Len())\n\t\tfor i := range expectedBatchingFactor {\n\t\t\trequire.Equal(t, metricsPerRequest, md.ResourceMetrics().At(i).ScopeMetrics().At(0).Metrics().Len())\n\t\t}\n\t}\n\n\tmetadatatest.AssertEqualProcessorBatchBatchSendSizeBytes(t, tel,\n\t\t[]metricdata.HistogramDataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"batch\")),\n\t\t\t\tCount:      uint64(expectedBatchesNum),\n\t\t\t\tBounds: []float64{\n\t\t\t\t\t10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000,\n\t\t\t\t\t100_000, 200_000, 300_000, 400_000, 500_000, 600_000, 700_000, 800_000, 900_000,\n\t\t\t\t\t1000_000, 2000_000, 3000_000, 4000_000, 5000_000, 6000_000, 7000_000, 8000_000, 9000_000,\n\t\t\t\t},\n\t\t\t\tBucketCounts: []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, uint64(expectedBatchesNum), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\tSum:          int64(size),\n\t\t\t\tMin:          metricdata.NewExtrema(int64(size / int(expectedBatchesNum))),\n\t\t\t\tMax:          metricdata.NewExtrema(int64(size / int(expectedBatchesNum))),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\n\tmetadatatest.AssertEqualProcessorBatchBatchSendSize(t, tel,\n\t\t[]metricdata.HistogramDataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes:   attribute.NewSet(attribute.String(\"processor\", \"batch\")),\n\t\t\t\tCount:        uint64(expectedBatchesNum),\n\t\t\t\tBounds:       []float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, 100000},\n\t\t\t\tBucketCounts: []uint64{0, 0, uint64(expectedBatchesNum), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\tSum:          int64(sink.DataPointCount()),\n\t\t\t\tMin:          metricdata.NewExtrema(int64(cfg.SendBatchSize)),\n\t\t\t\tMax:          metricdata.NewExtrema(int64(cfg.SendBatchSize)),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\n\tmetadatatest.AssertEqualProcessorBatchBatchSizeTriggerSend(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      int64(expectedBatchesNum),\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"batch\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\n\tmetadatatest.AssertEqualProcessorBatchMetadataCardinality(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      1,\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"batch\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\n\trequire.NoError(t, tel.Shutdown(context.Background()))\n}\n\nfunc TestBatchMetrics_UnevenBatchMaxSize(t *testing.T) {\n\tctx := context.Background()\n\tsink := new(metricsSink)\n\tmetricsCount := 50\n\tdataPointsPerMetric := 2\n\tsendBatchMaxSize := 99\n\n\tbatchMetrics := newMetricsBatch(sink)\n\tmd := testdata.GenerateMetrics(metricsCount)\n\n\tbatchMetrics.add(md)\n\trequire.Equal(t, dataPointsPerMetric*metricsCount, batchMetrics.dataPointCount)\n\tsent, req := batchMetrics.split(sendBatchMaxSize)\n\tsendErr := batchMetrics.export(ctx, req)\n\trequire.NoError(t, sendErr)\n\trequire.Equal(t, sendBatchMaxSize, sent)\n\tremainingDataPointCount := metricsCount*dataPointsPerMetric - sendBatchMaxSize\n\trequire.Equal(t, remainingDataPointCount, batchMetrics.dataPointCount)\n}\n\nfunc TestBatchMetricsProcessor_Timeout(t *testing.T) {\n\tcfg := &Config{\n\t\tTimeout:       100 * time.Millisecond,\n\t\tSendBatchSize: 101,\n\t}\n\trequestCount := 5\n\tmetricsPerRequest := 10\n\tsink := new(consumertest.MetricsSink)\n\n\tmetrics, err := NewFactory().CreateMetrics(context.Background(), processortest.NewNopSettings(metadata.Type), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, metrics.Start(context.Background(), componenttest.NewNopHost()))\n\n\tstart := time.Now()\n\tfor range requestCount {\n\t\tmd := testdata.GenerateMetrics(metricsPerRequest)\n\t\trequire.NoError(t, metrics.ConsumeMetrics(context.Background(), md))\n\t}\n\n\t// Wait for at least one batch to be sent.\n\tfor sink.DataPointCount() == 0 {\n\t\t<-time.After(cfg.Timeout)\n\t}\n\n\telapsed := time.Since(start)\n\trequire.LessOrEqual(t, cfg.Timeout.Nanoseconds(), elapsed.Nanoseconds())\n\n\t// This should not change the results in the sink, verified by the expectedBatchesNum\n\trequire.NoError(t, metrics.Shutdown(context.Background()))\n\n\texpectedBatchesNum := 1\n\texpectedBatchingFactor := 5\n\n\trequire.Equal(t, requestCount*2*metricsPerRequest, sink.DataPointCount())\n\treceivedMds := sink.AllMetrics()\n\trequire.Len(t, receivedMds, expectedBatchesNum)\n\tfor _, md := range receivedMds {\n\t\trequire.Equal(t, expectedBatchingFactor, md.ResourceMetrics().Len())\n\t\tfor i := range expectedBatchingFactor {\n\t\t\trequire.Equal(t, metricsPerRequest, md.ResourceMetrics().At(i).ScopeMetrics().At(0).Metrics().Len())\n\t\t}\n\t}\n}\n\nfunc TestBatchMetricProcessor_Shutdown(t *testing.T) {\n\tcfg := &Config{\n\t\tTimeout:       3 * time.Second,\n\t\tSendBatchSize: 1000,\n\t}\n\trequestCount := 5\n\tmetricsPerRequest := 10\n\tsink := new(consumertest.MetricsSink)\n\n\tmetrics, err := NewFactory().CreateMetrics(context.Background(), processortest.NewNopSettings(metadata.Type), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, metrics.Start(context.Background(), componenttest.NewNopHost()))\n\n\tfor range requestCount {\n\t\tmd := testdata.GenerateMetrics(metricsPerRequest)\n\t\trequire.NoError(t, metrics.ConsumeMetrics(context.Background(), md))\n\t}\n\n\trequire.NoError(t, metrics.Shutdown(context.Background()))\n\n\trequire.Equal(t, requestCount*2*metricsPerRequest, sink.DataPointCount())\n\trequire.Len(t, sink.AllMetrics(), 1)\n}\n\nfunc getTestSpanName(requestNum, index int) string {\n\treturn fmt.Sprintf(\"test-span-%d-%d\", requestNum, index)\n}\n\nfunc spansReceivedByName(tds []ptrace.Traces) map[string]ptrace.Span {\n\tspansReceivedByName := map[string]ptrace.Span{}\n\tfor i := range tds {\n\t\trss := tds[i].ResourceSpans()\n\t\tfor i := 0; i < rss.Len(); i++ {\n\t\t\tilss := rss.At(i).ScopeSpans()\n\t\t\tfor j := 0; j < ilss.Len(); j++ {\n\t\t\t\tspans := ilss.At(j).Spans()\n\t\t\t\tfor k := 0; k < spans.Len(); k++ {\n\t\t\t\t\tspan := spans.At(k)\n\t\t\t\t\tspansReceivedByName[spans.At(k).Name()] = span\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn spansReceivedByName\n}\n\nfunc metricsReceivedByName(mds []pmetric.Metrics) map[string]pmetric.Metric {\n\tmetricsReceivedByName := map[string]pmetric.Metric{}\n\tfor _, md := range mds {\n\t\trms := md.ResourceMetrics()\n\t\tfor i := 0; i < rms.Len(); i++ {\n\t\t\tilms := rms.At(i).ScopeMetrics()\n\t\t\tfor j := 0; j < ilms.Len(); j++ {\n\t\t\t\tmetrics := ilms.At(j).Metrics()\n\t\t\t\tfor k := 0; k < metrics.Len(); k++ {\n\t\t\t\t\tmetric := metrics.At(k)\n\t\t\t\t\tmetricsReceivedByName[metric.Name()] = metric\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn metricsReceivedByName\n}\n\nfunc getTestMetricName(requestNum, index int) string {\n\treturn fmt.Sprintf(\"test-metric-int-%d-%d\", requestNum, index)\n}\n\nfunc BenchmarkTraceSizeBytes(b *testing.B) {\n\tsizer := &ptrace.ProtoMarshaler{}\n\ttd := testdata.GenerateTraces(8192)\n\tfor b.Loop() {\n\t\tfmt.Println(sizer.TracesSize(td))\n\t}\n}\n\nfunc BenchmarkTraceSizeSpanCount(b *testing.B) {\n\ttd := testdata.GenerateTraces(8192)\n\tfor b.Loop() {\n\t\ttd.SpanCount()\n\t}\n}\n\nfunc BenchmarkBatchMetricProcessor2k(b *testing.B) {\n\tb.StopTimer()\n\tcfg := &Config{\n\t\tTimeout:       100 * time.Millisecond,\n\t\tSendBatchSize: 2000,\n\t}\n\trunMetricsProcessorBenchmark(b, cfg)\n}\n\nfunc BenchmarkMultiBatchMetricProcessor2k(b *testing.B) {\n\tb.StopTimer()\n\tcfg := &Config{\n\t\tTimeout:       100 * time.Millisecond,\n\t\tSendBatchSize: 2000,\n\t\tMetadataKeys:  []string{\"test\", \"test2\"},\n\t}\n\trunMetricsProcessorBenchmark(b, cfg)\n}\n\nfunc runMetricsProcessorBenchmark(b *testing.B, cfg *Config) {\n\tctx := context.Background()\n\tsink := new(metricsSink)\n\tmetrics, err := NewFactory().CreateMetrics(context.Background(), processortest.NewNopSettings(metadata.Type), cfg, sink)\n\trequire.NoError(b, err)\n\trequire.NoError(b, metrics.Start(ctx, componenttest.NewNopHost()))\n\n\tconst metricsPerRequest = 150_000\n\tb.StartTimer()\n\tb.RunParallel(func(pb *testing.PB) {\n\t\tfor pb.Next() {\n\t\t\trequire.NoError(b, metrics.ConsumeMetrics(ctx, testdata.GenerateMetrics(metricsPerRequest)))\n\t\t}\n\t})\n\tb.StopTimer()\n\trequire.NoError(b, metrics.Shutdown(ctx))\n\trequire.Equal(b, b.N*metricsPerRequest, sink.metricsCount)\n}\n\ntype metricsSink struct {\n\tmu           sync.Mutex\n\tmetricsCount int\n}\n\nfunc (sme *metricsSink) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{\n\t\tMutatesData: false,\n\t}\n}\n\nfunc (sme *metricsSink) ConsumeMetrics(_ context.Context, md pmetric.Metrics) error {\n\tsme.mu.Lock()\n\tdefer sme.mu.Unlock()\n\tsme.metricsCount += md.MetricCount()\n\treturn nil\n}\n\nfunc TestBatchLogProcessor_ReceivingData(t *testing.T) {\n\t// Instantiate the batch processor with low config values to test data\n\t// gets sent through the processor.\n\tcfg := &Config{\n\t\tTimeout:       200 * time.Millisecond,\n\t\tSendBatchSize: 50,\n\t}\n\n\trequestCount := 100\n\tlogsPerRequest := 5\n\tsink := new(consumertest.LogsSink)\n\n\tlogs, err := NewFactory().CreateLogs(context.Background(), processortest.NewNopSettings(metadata.Type), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, logs.Start(context.Background(), componenttest.NewNopHost()))\n\n\tsentResourceLogs := plog.NewLogs().ResourceLogs()\n\n\tfor requestNum := range requestCount {\n\t\tld := testdata.GenerateLogs(logsPerRequest)\n\t\tlrs := ld.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords()\n\t\tfor logIndex := range logsPerRequest {\n\t\t\tlrs.At(logIndex).SetSeverityText(getTestLogSeverityText(requestNum, logIndex))\n\t\t}\n\t\tld.ResourceLogs().At(0).CopyTo(sentResourceLogs.AppendEmpty())\n\t\trequire.NoError(t, logs.ConsumeLogs(context.Background(), ld))\n\t}\n\n\t// Added to test case with empty resources sent.\n\tld := plog.NewLogs()\n\tassert.NoError(t, logs.ConsumeLogs(context.Background(), ld))\n\n\trequire.NoError(t, logs.Shutdown(context.Background()))\n\n\trequire.Equal(t, requestCount*logsPerRequest, sink.LogRecordCount())\n\treceivedMds := sink.AllLogs()\n\tlogsReceivedBySeverityText := logsReceivedBySeverityText(receivedMds)\n\tfor requestNum := range requestCount {\n\t\tlrs := sentResourceLogs.At(requestNum).ScopeLogs().At(0).LogRecords()\n\t\tfor logIndex := range logsPerRequest {\n\t\t\trequire.Equal(t,\n\t\t\t\tlrs.At(logIndex),\n\t\t\t\tlogsReceivedBySeverityText[getTestLogSeverityText(requestNum, logIndex)])\n\t\t}\n\t}\n}\n\nfunc TestBatchLogProcessor_BatchSize(t *testing.T) {\n\ttel := componenttest.NewTelemetry()\n\tsizer := &plog.ProtoMarshaler{}\n\n\t// Instantiate the batch processor with low config values to test data\n\t// gets sent through the processor.\n\tcfg := &Config{\n\t\tTimeout:       100 * time.Millisecond,\n\t\tSendBatchSize: 50,\n\t}\n\n\tconst (\n\t\trequestCount   = 100\n\t\tlogsPerRequest = 5\n\t)\n\tsink := new(consumertest.LogsSink)\n\n\tlogs, err := NewFactory().CreateLogs(context.Background(), metadatatest.NewSettings(tel), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, logs.Start(context.Background(), componenttest.NewNopHost()))\n\n\tstart := time.Now()\n\tsize := 0\n\tfor range requestCount {\n\t\tld := testdata.GenerateLogs(logsPerRequest)\n\t\tsize += sizer.LogsSize(ld)\n\t\trequire.NoError(t, logs.ConsumeLogs(context.Background(), ld))\n\t}\n\trequire.NoError(t, logs.Shutdown(context.Background()))\n\n\telapsed := time.Since(start)\n\trequire.LessOrEqual(t, elapsed.Nanoseconds(), cfg.Timeout.Nanoseconds())\n\n\texpectedBatchesNum := requestCount * logsPerRequest / cfg.SendBatchSize\n\texpectedBatchingFactor := int(cfg.SendBatchSize) / logsPerRequest\n\n\trequire.Equal(t, requestCount*logsPerRequest, sink.LogRecordCount())\n\treceivedMds := sink.AllLogs()\n\trequire.Len(t, receivedMds, int(expectedBatchesNum))\n\tfor _, ld := range receivedMds {\n\t\trequire.Equal(t, expectedBatchingFactor, ld.ResourceLogs().Len())\n\t\tfor i := range expectedBatchingFactor {\n\t\t\trequire.Equal(t, logsPerRequest, ld.ResourceLogs().At(i).ScopeLogs().At(0).LogRecords().Len())\n\t\t}\n\t}\n\n\tmetadatatest.AssertEqualProcessorBatchBatchSendSizeBytes(t, tel,\n\t\t[]metricdata.HistogramDataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"batch\")),\n\t\t\t\tCount:      uint64(expectedBatchesNum),\n\t\t\t\tBounds: []float64{\n\t\t\t\t\t10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000,\n\t\t\t\t\t100_000, 200_000, 300_000, 400_000, 500_000, 600_000, 700_000, 800_000, 900_000,\n\t\t\t\t\t1000_000, 2000_000, 3000_000, 4000_000, 5000_000, 6000_000, 7000_000, 8000_000, 9000_000,\n\t\t\t\t},\n\t\t\t\tBucketCounts: []uint64{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, uint64(expectedBatchesNum), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\tSum:          int64(size),\n\t\t\t\tMin:          metricdata.NewExtrema(int64(size / int(expectedBatchesNum))),\n\t\t\t\tMax:          metricdata.NewExtrema(int64(size / int(expectedBatchesNum))),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\n\tmetadatatest.AssertEqualProcessorBatchBatchSendSize(t, tel,\n\t\t[]metricdata.HistogramDataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes:   attribute.NewSet(attribute.String(\"processor\", \"batch\")),\n\t\t\t\tCount:        uint64(expectedBatchesNum),\n\t\t\t\tBounds:       []float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, 100000},\n\t\t\t\tBucketCounts: []uint64{0, 0, uint64(expectedBatchesNum), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n\t\t\t\tSum:          int64(sink.LogRecordCount()),\n\t\t\t\tMin:          metricdata.NewExtrema(int64(cfg.SendBatchSize)),\n\t\t\t\tMax:          metricdata.NewExtrema(int64(cfg.SendBatchSize)),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\n\tmetadatatest.AssertEqualProcessorBatchBatchSizeTriggerSend(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      int64(expectedBatchesNum),\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"batch\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\n\tmetadatatest.AssertEqualProcessorBatchMetadataCardinality(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      1,\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"batch\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\n\trequire.NoError(t, tel.Shutdown(context.Background()))\n}\n\nfunc TestBatchLogsProcessor_Timeout(t *testing.T) {\n\tcfg := &Config{\n\t\tTimeout:       100 * time.Millisecond,\n\t\tSendBatchSize: 100,\n\t}\n\trequestCount := 5\n\tlogsPerRequest := 10\n\tsink := new(consumertest.LogsSink)\n\n\tlogs, err := NewFactory().CreateLogs(context.Background(), processortest.NewNopSettings(metadata.Type), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, logs.Start(context.Background(), componenttest.NewNopHost()))\n\n\tstart := time.Now()\n\tfor range requestCount {\n\t\tld := testdata.GenerateLogs(logsPerRequest)\n\t\trequire.NoError(t, logs.ConsumeLogs(context.Background(), ld))\n\t}\n\n\t// Wait for at least one batch to be sent.\n\tfor sink.LogRecordCount() == 0 {\n\t\t<-time.After(cfg.Timeout)\n\t}\n\n\telapsed := time.Since(start)\n\trequire.LessOrEqual(t, cfg.Timeout.Nanoseconds(), elapsed.Nanoseconds())\n\n\t// This should not change the results in the sink, verified by the expectedBatchesNum\n\trequire.NoError(t, logs.Shutdown(context.Background()))\n\n\texpectedBatchesNum := 1\n\texpectedBatchingFactor := 5\n\n\trequire.Equal(t, requestCount*logsPerRequest, sink.LogRecordCount())\n\treceivedMds := sink.AllLogs()\n\trequire.Len(t, receivedMds, expectedBatchesNum)\n\tfor _, ld := range receivedMds {\n\t\trequire.Equal(t, expectedBatchingFactor, ld.ResourceLogs().Len())\n\t\tfor i := range expectedBatchingFactor {\n\t\t\trequire.Equal(t, logsPerRequest, ld.ResourceLogs().At(i).ScopeLogs().At(0).LogRecords().Len())\n\t\t}\n\t}\n}\n\nfunc TestBatchLogProcessor_Shutdown(t *testing.T) {\n\tcfg := &Config{\n\t\tTimeout:       3 * time.Second,\n\t\tSendBatchSize: 1000,\n\t}\n\trequestCount := 5\n\tlogsPerRequest := 10\n\tsink := new(consumertest.LogsSink)\n\n\tlogs, err := NewFactory().CreateLogs(context.Background(), processortest.NewNopSettings(metadata.Type), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, logs.Start(context.Background(), componenttest.NewNopHost()))\n\n\tfor range requestCount {\n\t\tld := testdata.GenerateLogs(logsPerRequest)\n\t\trequire.NoError(t, logs.ConsumeLogs(context.Background(), ld))\n\t}\n\n\trequire.NoError(t, logs.Shutdown(context.Background()))\n\n\trequire.Equal(t, requestCount*logsPerRequest, sink.LogRecordCount())\n\trequire.Len(t, sink.AllLogs(), 1)\n}\n\nfunc getTestLogSeverityText(requestNum, index int) string {\n\treturn fmt.Sprintf(\"test-log-int-%d-%d\", requestNum, index)\n}\n\nfunc logsReceivedBySeverityText(lds []plog.Logs) map[string]plog.LogRecord {\n\tlogsReceivedBySeverityText := map[string]plog.LogRecord{}\n\tfor i := range lds {\n\t\tld := lds[i]\n\t\trms := ld.ResourceLogs()\n\t\tfor i := 0; i < rms.Len(); i++ {\n\t\t\tilms := rms.At(i).ScopeLogs()\n\t\t\tfor j := 0; j < ilms.Len(); j++ {\n\t\t\t\tlogs := ilms.At(j).LogRecords()\n\t\t\t\tfor k := 0; k < logs.Len(); k++ {\n\t\t\t\t\tlog := logs.At(k)\n\t\t\t\t\tlogsReceivedBySeverityText[log.SeverityText()] = log\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn logsReceivedBySeverityText\n}\n\nfunc TestShutdown(t *testing.T) {\n\tfactory := NewFactory()\n\tprocessortest.VerifyShutdown(t, factory, factory.CreateDefaultConfig())\n}\n\ntype metadataTracesSink struct {\n\t*consumertest.TracesSink\n\n\tlock               sync.Mutex\n\tspanCountByToken12 map[string]int\n}\n\nfunc formatTwo(first, second []string) string {\n\treturn fmt.Sprintf(\"%s;%s\", first, second)\n}\n\nfunc (mts *metadataTracesSink) ConsumeTraces(ctx context.Context, td ptrace.Traces) error {\n\tinfo := client.FromContext(ctx)\n\ttoken1 := info.Metadata.Get(\"token1\")\n\ttoken2 := info.Metadata.Get(\"token2\")\n\tmts.lock.Lock()\n\tdefer mts.lock.Unlock()\n\n\tmts.spanCountByToken12[formatTwo(\n\t\ttoken1,\n\t\ttoken2,\n\t)] += td.SpanCount()\n\treturn mts.TracesSink.ConsumeTraces(ctx, td)\n}\n\nfunc TestBatchProcessorSpansBatchedByMetadata(t *testing.T) {\n\tsink := &metadataTracesSink{\n\t\tTracesSink:         &consumertest.TracesSink{},\n\t\tspanCountByToken12: map[string]int{},\n\t}\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.SendBatchSize = 1000\n\tcfg.Timeout = 10 * time.Minute\n\tcfg.MetadataKeys = []string{\"token1\", \"token2\"}\n\ttraces, err := NewFactory().CreateTraces(context.Background(), processortest.NewNopSettings(metadata.Type), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, traces.Start(context.Background(), componenttest.NewNopHost()))\n\n\tbg := context.Background()\n\tcallCtxs := []context.Context{\n\t\tclient.NewContext(bg, client.Info{\n\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\"token1\": {\"single\"},\n\t\t\t\t\"token3\": {\"n/a\"},\n\t\t\t}),\n\t\t}),\n\t\tclient.NewContext(bg, client.Info{\n\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\"token1\": {\"single\"},\n\t\t\t\t\"token2\": {\"one\", \"two\"},\n\t\t\t\t\"token4\": {\"n/a\"},\n\t\t\t}),\n\t\t}),\n\t\tclient.NewContext(bg, client.Info{\n\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\"token1\": nil,\n\t\t\t\t\"token2\": {\"single\"},\n\t\t\t}),\n\t\t}),\n\t\tclient.NewContext(bg, client.Info{\n\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\"token1\": {\"one\", \"two\", \"three\"},\n\t\t\t\t\"token2\": {\"single\"},\n\t\t\t\t\"token3\": {\"n/a\"},\n\t\t\t\t\"token4\": {\"n/a\", \"d/c\"},\n\t\t\t}),\n\t\t}),\n\t}\n\texpectByContext := make([]int, len(callCtxs))\n\n\trequestCount := 1000\n\tspansPerRequest := 33\n\tsentResourceSpans := ptrace.NewTraces().ResourceSpans()\n\tfor requestNum := range requestCount {\n\t\ttd := testdata.GenerateTraces(spansPerRequest)\n\t\tspans := td.ResourceSpans().At(0).ScopeSpans().At(0).Spans()\n\t\tfor spanIndex := range spansPerRequest {\n\t\t\tspans.At(spanIndex).SetName(getTestSpanName(requestNum, spanIndex))\n\t\t}\n\t\ttd.ResourceSpans().At(0).CopyTo(sentResourceSpans.AppendEmpty())\n\t\t// use round-robin to assign context.\n\t\tnum := requestNum % len(callCtxs)\n\t\texpectByContext[num] += spansPerRequest\n\t\trequire.NoError(t, traces.ConsumeTraces(callCtxs[num], td))\n\t}\n\n\trequire.NoError(t, traces.Shutdown(context.Background()))\n\n\t// The following tests are the same as TestBatchProcessorSpansDelivered().\n\trequire.Equal(t, requestCount*spansPerRequest, sink.SpanCount())\n\treceivedTraces := sink.AllTraces()\n\tspansReceivedByName := spansReceivedByName(receivedTraces)\n\tfor requestNum := range requestCount {\n\t\tspans := sentResourceSpans.At(requestNum).ScopeSpans().At(0).Spans()\n\t\tfor spanIndex := range spansPerRequest {\n\t\t\trequire.Equal(t,\n\t\t\t\tspans.At(spanIndex),\n\t\t\t\tspansReceivedByName[getTestSpanName(requestNum, spanIndex)])\n\t\t}\n\t}\n\n\t// This test ensures each context had the expected number of spans.\n\trequire.Len(t, sink.spanCountByToken12, len(callCtxs))\n\tfor idx, ctx := range callCtxs {\n\t\tmd := client.FromContext(ctx).Metadata\n\t\texp := formatTwo(md.Get(\"token1\"), md.Get(\"token2\"))\n\t\trequire.Equal(t, expectByContext[idx], sink.spanCountByToken12[exp])\n\t}\n}\n\nfunc TestBatchProcessorDuplicateMetadataKeys(t *testing.T) {\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.MetadataKeys = []string{\"myTOKEN\", \"mytoken\"}\n\terr := cfg.Validate()\n\trequire.ErrorContains(t, err, \"duplicate\")\n\trequire.ErrorContains(t, err, \"mytoken\")\n}\n\nfunc TestBatchProcessorMetadataCardinalityLimit(t *testing.T) {\n\tconst cardLimit = 10\n\n\tsink := new(consumertest.TracesSink)\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.MetadataKeys = []string{\"token\"}\n\tcfg.MetadataCardinalityLimit = cardLimit\n\ttraces, err := NewFactory().CreateTraces(context.Background(), processortest.NewNopSettings(metadata.Type), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, traces.Start(context.Background(), componenttest.NewNopHost()))\n\n\tbg := context.Background()\n\tfor requestNum := range cardLimit {\n\t\ttd := testdata.GenerateTraces(1)\n\t\tctx := client.NewContext(bg, client.Info{\n\t\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\t\"token\": {strconv.Itoa(requestNum)},\n\t\t\t}),\n\t\t})\n\n\t\trequire.NoError(t, traces.ConsumeTraces(ctx, td))\n\t}\n\n\ttd := testdata.GenerateTraces(1)\n\tctx := client.NewContext(bg, client.Info{\n\t\tMetadata: client.NewMetadata(map[string][]string{\n\t\t\t\"token\": {\"limit_exceeded\"},\n\t\t}),\n\t})\n\terr = traces.ConsumeTraces(ctx, td)\n\n\trequire.Error(t, err)\n\tassert.True(t, consumererror.IsPermanent(err))\n\trequire.ErrorContains(t, err, \"too many\")\n\n\trequire.NoError(t, traces.Shutdown(context.Background()))\n}\n\nfunc TestBatchZeroConfig(t *testing.T) {\n\t// This is a no-op configuration. No need for a timer, no\n\t// minimum, no maximum, just a pass through.\n\tcfg := &Config{}\n\n\trequire.NoError(t, cfg.Validate())\n\n\tconst requestCount = 5\n\tconst logsPerRequest = 10\n\tsink := new(consumertest.LogsSink)\n\tlogs, err := NewFactory().CreateLogs(context.Background(), processortest.NewNopSettings(metadata.Type), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, logs.Start(context.Background(), componenttest.NewNopHost()))\n\tdefer func() { require.NoError(t, logs.Shutdown(context.Background())) }()\n\n\texpect := 0\n\tfor requestNum := range requestCount {\n\t\tcnt := logsPerRequest + requestNum\n\t\texpect += cnt\n\t\tld := testdata.GenerateLogs(cnt)\n\t\trequire.NoError(t, logs.ConsumeLogs(context.Background(), ld))\n\t}\n\n\t// Wait for all batches.\n\trequire.Eventually(t, func() bool {\n\t\treturn sink.LogRecordCount() == expect\n\t}, time.Second, 5*time.Millisecond)\n\n\t// Expect them to be the original sizes.\n\treceivedMds := sink.AllLogs()\n\trequire.Len(t, receivedMds, requestCount)\n\tfor i, ld := range receivedMds {\n\t\trequire.Equal(t, 1, ld.ResourceLogs().Len())\n\t\trequire.Equal(t, logsPerRequest+i, ld.LogRecordCount())\n\t}\n}\n\nfunc TestBatchSplitOnly(t *testing.T) {\n\tconst maxBatch = 10\n\tconst requestCount = 5\n\tconst logsPerRequest = 100\n\n\tcfg := &Config{\n\t\tSendBatchMaxSize: maxBatch,\n\t}\n\n\trequire.NoError(t, cfg.Validate())\n\n\tsink := new(consumertest.LogsSink)\n\tlogs, err := NewFactory().CreateLogs(context.Background(), processortest.NewNopSettings(metadata.Type), cfg, sink)\n\trequire.NoError(t, err)\n\trequire.NoError(t, logs.Start(context.Background(), componenttest.NewNopHost()))\n\tdefer func() { require.NoError(t, logs.Shutdown(context.Background())) }()\n\n\tfor range requestCount {\n\t\tld := testdata.GenerateLogs(logsPerRequest)\n\t\trequire.NoError(t, logs.ConsumeLogs(context.Background(), ld))\n\t}\n\n\t// Wait for all batches.\n\trequire.Eventually(t, func() bool {\n\t\treturn sink.LogRecordCount() == logsPerRequest*requestCount\n\t}, time.Second, 5*time.Millisecond)\n\n\t// Expect them to be the limited by maxBatch.\n\treceivedMds := sink.AllLogs()\n\trequire.Len(t, receivedMds, requestCount*logsPerRequest/maxBatch)\n\tfor _, ld := range receivedMds {\n\t\trequire.Equal(t, maxBatch, ld.LogRecordCount())\n\t}\n}\n"
  },
  {
    "path": "processor/batchprocessor/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage batchprocessor // import \"go.opentelemetry.io/collector/processor/batchprocessor\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\n// Config defines configuration for batch processor.\ntype Config struct {\n\t// Timeout sets the time after which a batch will be sent regardless of size.\n\t// When this is set to zero, batched data will be sent immediately.\n\tTimeout time.Duration `mapstructure:\"timeout\"`\n\n\t// SendBatchSize is the size of a batch which after hit, will trigger it to be sent.\n\t// When this is set to zero, the batch size is ignored and data will be sent immediately\n\t// subject to only send_batch_max_size.\n\tSendBatchSize uint32 `mapstructure:\"send_batch_size\"`\n\n\t// SendBatchMaxSize is the maximum size of a batch. It must be larger than SendBatchSize.\n\t// Larger batches are split into smaller units.\n\t// Default value is 0, that means no maximum size.\n\tSendBatchMaxSize uint32 `mapstructure:\"send_batch_max_size\"`\n\n\t// MetadataKeys is a list of client.Metadata keys that will be\n\t// used to form distinct batchers.  If this setting is empty,\n\t// a single batcher instance will be used.  When this setting\n\t// is not empty, one batcher will be used per distinct\n\t// combination of values for the listed metadata keys.\n\t//\n\t// Empty value and unset metadata are treated as distinct cases.\n\t//\n\t// Entries are case-insensitive.  Duplicated entries will\n\t// trigger a validation error.\n\tMetadataKeys []string `mapstructure:\"metadata_keys\"`\n\n\t// MetadataCardinalityLimit indicates the maximum number of\n\t// batcher instances that will be created through a distinct\n\t// combination of MetadataKeys.\n\tMetadataCardinalityLimit uint32 `mapstructure:\"metadata_cardinality_limit\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\nvar _ component.Config = (*Config)(nil)\n\n// Validate checks if the processor configuration is valid\nfunc (cfg *Config) Validate() error {\n\tif cfg.SendBatchMaxSize > 0 && cfg.SendBatchMaxSize < cfg.SendBatchSize {\n\t\treturn errors.New(\"send_batch_max_size must be greater or equal to send_batch_size\")\n\t}\n\tuniq := map[string]bool{}\n\tfor _, k := range cfg.MetadataKeys {\n\t\tl := strings.ToLower(k)\n\t\tif _, has := uniq[l]; has {\n\t\t\treturn fmt.Errorf(\"duplicate entry in metadata_keys: %q (case-insensitive)\", l)\n\t\t}\n\t\tuniq[l] = true\n\t}\n\tif cfg.Timeout < 0 {\n\t\treturn errors.New(\"timeout must be greater or equal to 0\")\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "processor/batchprocessor/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage batchprocessor\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n)\n\nfunc TestUnmarshalDefaultConfig(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, confmap.New().Unmarshal(&cfg))\n\tassert.Equal(t, factory.CreateDefaultConfig(), cfg)\n}\n\nfunc TestUnmarshalConfig(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\tassert.Equal(t,\n\t\t&Config{\n\t\t\tSendBatchSize:            uint32(10000),\n\t\t\tSendBatchMaxSize:         uint32(11000),\n\t\t\tTimeout:                  time.Second * 10,\n\t\t\tMetadataCardinalityLimit: 1000,\n\t\t}, cfg)\n}\n\nfunc TestValidateConfig_DefaultBatchMaxSize(t *testing.T) {\n\tcfg := &Config{\n\t\tSendBatchSize:    100,\n\t\tSendBatchMaxSize: 0,\n\t}\n\tassert.NoError(t, cfg.Validate())\n}\n\nfunc TestValidateConfig_ValidBatchSizes(t *testing.T) {\n\tcfg := &Config{\n\t\tSendBatchSize:    100,\n\t\tSendBatchMaxSize: 1000,\n\t}\n\tassert.NoError(t, cfg.Validate())\n}\n\nfunc TestValidateConfig_InvalidBatchSize(t *testing.T) {\n\tcfg := &Config{\n\t\tSendBatchSize:    1000,\n\t\tSendBatchMaxSize: 100,\n\t}\n\tassert.Error(t, cfg.Validate())\n}\n\nfunc TestValidateConfig_InvalidTimeout(t *testing.T) {\n\tcfg := &Config{\n\t\tTimeout: -time.Second,\n\t}\n\tassert.Error(t, cfg.Validate())\n}\n\nfunc TestValidateConfig_ValidZero(t *testing.T) {\n\tcfg := &Config{}\n\tassert.NoError(t, cfg.Validate())\n}\n"
  },
  {
    "path": "processor/batchprocessor/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# batch\n\n## Internal Telemetry\n\nThe following telemetry is emitted by this component.\n\n### otelcol_processor_batch_batch_send_size\n\nNumber of units in the batch\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| {unit} | Histogram | Int | Development |\n\n### otelcol_processor_batch_batch_send_size_bytes\n\nNumber of bytes in batch that was sent. Only available on detailed level.\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| By | Histogram | Int | Development |\n\n### otelcol_processor_batch_batch_size_trigger_send\n\nNumber of times the batch was sent due to a size trigger\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {time} | Sum | Int | true | Development |\n\n### otelcol_processor_batch_metadata_cardinality\n\nNumber of distinct metadata value combinations being processed\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {combination} | Sum | Int | false | Development |\n\n### otelcol_processor_batch_timeout_trigger_send\n\nNumber of times the batch was sent due to a timeout trigger\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {time} | Sum | Int | true | Development |\n"
  },
  {
    "path": "processor/batchprocessor/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\npackage batchprocessor // import \"go.opentelemetry.io/collector/processor/batchprocessor\"\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/batchprocessor/internal/metadata\"\n)\n\nconst (\n\tdefaultSendBatchSize = uint32(8192)\n\tdefaultTimeout       = 200 * time.Millisecond\n\n\t// defaultMetadataCardinalityLimit should be set to the number\n\t// of metadata configurations the user expects to submit to\n\t// the collector.\n\tdefaultMetadataCardinalityLimit = 1000\n)\n\n// NewFactory returns a new factory for the Batch processor.\nfunc NewFactory() processor.Factory {\n\treturn processor.NewFactory(\n\t\tmetadata.Type,\n\t\tcreateDefaultConfig,\n\t\tprocessor.WithTraces(createTraces, metadata.TracesStability),\n\t\tprocessor.WithMetrics(createMetrics, metadata.MetricsStability),\n\t\tprocessor.WithLogs(createLogs, metadata.LogsStability))\n}\n\nfunc createDefaultConfig() component.Config {\n\treturn &Config{\n\t\tSendBatchSize:            defaultSendBatchSize,\n\t\tTimeout:                  defaultTimeout,\n\t\tMetadataCardinalityLimit: defaultMetadataCardinalityLimit,\n\t}\n}\n\nfunc createTraces(\n\t_ context.Context,\n\tset processor.Settings,\n\tcfg component.Config,\n\tnextConsumer consumer.Traces,\n) (processor.Traces, error) {\n\treturn newTracesBatchProcessor(set, nextConsumer, cfg.(*Config))\n}\n\nfunc createMetrics(\n\t_ context.Context,\n\tset processor.Settings,\n\tcfg component.Config,\n\tnextConsumer consumer.Metrics,\n) (processor.Metrics, error) {\n\treturn newMetricsBatchProcessor(set, nextConsumer, cfg.(*Config))\n}\n\nfunc createLogs(\n\t_ context.Context,\n\tset processor.Settings,\n\tcfg component.Config,\n\tnextConsumer consumer.Logs,\n) (processor.Logs, error) {\n\treturn newLogsBatchProcessor(set, nextConsumer, cfg.(*Config))\n}\n"
  },
  {
    "path": "processor/batchprocessor/factory_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage batchprocessor\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n)\n\nfunc TestCreateDefaultConfig(t *testing.T) {\n\tfactory := NewFactory()\n\n\tcfg := factory.CreateDefaultConfig()\n\tassert.NotNil(t, cfg, \"failed to create default config\")\n\tassert.NoError(t, componenttest.CheckConfigStruct(cfg))\n}\n\nfunc TestCreateProcessor(t *testing.T) {\n\tfactory := NewFactory()\n\n\tcfg := factory.CreateDefaultConfig()\n\tcreationSet := processortest.NewNopSettings(factory.Type())\n\ttp, err := factory.CreateTraces(context.Background(), creationSet, cfg, nil)\n\tassert.NotNil(t, tp)\n\tassert.NoError(t, err, \"cannot create trace processor\")\n\tassert.NoError(t, tp.Shutdown(context.Background()))\n\n\tmp, err := factory.CreateMetrics(context.Background(), creationSet, cfg, nil)\n\tassert.NotNil(t, mp)\n\tassert.NoError(t, err, \"cannot create metric processor\")\n\tassert.NoError(t, mp.Shutdown(context.Background()))\n\n\tlp, err := factory.CreateLogs(context.Background(), creationSet, cfg, nil)\n\tassert.NotNil(t, lp)\n\tassert.NoError(t, err, \"cannot create logs processor\")\n\tassert.NoError(t, lp.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "processor/batchprocessor/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage batchprocessor\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n)\n\nvar typ = component.MustNewType(\"batch\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct {\n\t\tcreateFn func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error)\n\t\tname     string\n\t}{\n\n\t\t{\n\t\t\tname: \"logs\",\n\t\t\tcreateFn: func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateLogs(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"traces\",\n\t\t\tcreateFn: func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateTraces(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name+\"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), processortest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\tt.Run(tt.name+\"-lifecycle\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), processortest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := newMdatagenNopHost()\n\t\t\terr = c.Start(context.Background(), host)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NotPanics(t, func() {\n\t\t\t\tswitch tt.name {\n\t\t\t\tcase \"logs\":\n\t\t\t\t\te, ok := c.(processor.Logs)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tlogs := generateLifecycleTestLogs()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tlogs.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeLogs(context.Background(), logs)\n\t\t\t\tcase \"metrics\":\n\t\t\t\t\te, ok := c.(processor.Metrics)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tmetrics := generateLifecycleTestMetrics()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tmetrics.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeMetrics(context.Background(), metrics)\n\t\t\t\tcase \"traces\":\n\t\t\t\t\te, ok := c.(processor.Traces)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\ttraces := generateLifecycleTestTraces()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\ttraces.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeTraces(context.Background(), traces)\n\t\t\t\t}\n\t\t\t})\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t}\n}\n\nfunc generateLifecycleTestLogs() plog.Logs {\n\tlogs := plog.NewLogs()\n\trl := logs.ResourceLogs().AppendEmpty()\n\trl.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tl := rl.ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\tl.Body().SetStr(\"test log message\")\n\tl.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn logs\n}\n\nfunc generateLifecycleTestMetrics() pmetric.Metrics {\n\tmetrics := pmetric.NewMetrics()\n\trm := metrics.ResourceMetrics().AppendEmpty()\n\trm.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tm := rm.ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\tm.SetName(\"test_metric\")\n\tdp := m.SetEmptyGauge().DataPoints().AppendEmpty()\n\tdp.Attributes().PutStr(\"test_attr\", \"value_1\")\n\tdp.SetIntValue(123)\n\tdp.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn metrics\n}\n\nfunc generateLifecycleTestTraces() ptrace.Traces {\n\ttraces := ptrace.NewTraces()\n\trs := traces.ResourceSpans().AppendEmpty()\n\trs.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tspan := rs.ScopeSpans().AppendEmpty().Spans().AppendEmpty()\n\tspan.Attributes().PutStr(\"test_attr\", \"value_1\")\n\tspan.SetName(\"test_span\")\n\tspan.SetStartTimestamp(pcommon.NewTimestampFromTime(time.Now().Add(-1 * time.Second)))\n\tspan.SetEndTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn traces\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "processor/batchprocessor/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage batchprocessor\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "processor/batchprocessor/go.mod",
    "content": "module go.opentelemetry.io/collector/processor/batchprocessor\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/client v1.54.0\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.opentelemetry.io/collector/pdata/xpdata v0.148.0\n\tgo.opentelemetry.io/collector/processor v1.54.0\n\tgo.opentelemetry.io/collector/processor/processortest v0.148.0\n\tgo.opentelemetry.io/otel v1.42.0\n\tgo.opentelemetry.io/otel/metric v1.42.0\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0\n\tgo.opentelemetry.io/otel/trace v1.42.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/zap v1.27.1\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/component/componentstatus v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/processor/xprocessor v0.148.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/processor => ../\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/client => ../../client\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nretract (\n\tv0.76.0 // Depends on retracted pdata v1.0.0-rc10 module, use v0.76.1\n\tv0.69.0 // Release failed, use v0.69.1\n)\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/component/componentstatus => ../../component/componentstatus\n\nreplace go.opentelemetry.io/collector/processor/xprocessor => ../xprocessor\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/processor/processortest => ../processortest\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "processor/batchprocessor/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "processor/batchprocessor/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"batch\")\n\tScopeName = \"go.opentelemetry.io/collector/processor/batchprocessor\"\n)\n\nconst (\n\tTracesStability  = component.StabilityLevelBeta\n\tMetricsStability = component.StabilityLevelBeta\n\tLogsStability    = component.StabilityLevelBeta\n)\n"
  },
  {
    "path": "processor/batchprocessor/internal/metadata/generated_telemetry.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/metric/embedded\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc Meter(settings component.TelemetrySettings) metric.Meter {\n\treturn settings.MeterProvider.Meter(\"go.opentelemetry.io/collector/processor/batchprocessor\")\n}\n\nfunc Tracer(settings component.TelemetrySettings) trace.Tracer {\n\treturn settings.TracerProvider.Tracer(\"go.opentelemetry.io/collector/processor/batchprocessor\")\n}\n\n// TelemetryBuilder provides an interface for components to report telemetry\n// as defined in metadata and user config.\ntype TelemetryBuilder struct {\n\tmeter                              metric.Meter\n\tmu                                 sync.Mutex\n\tregistrations                      []metric.Registration\n\tProcessorBatchBatchSendSize        metric.Int64Histogram\n\tProcessorBatchBatchSendSizeBytes   metric.Int64Histogram\n\tProcessorBatchBatchSizeTriggerSend metric.Int64Counter\n\tProcessorBatchMetadataCardinality  metric.Int64ObservableUpDownCounter\n\tProcessorBatchTimeoutTriggerSend   metric.Int64Counter\n}\n\n// TelemetryBuilderOption applies changes to default builder.\ntype TelemetryBuilderOption interface {\n\tapply(*TelemetryBuilder)\n}\n\ntype telemetryBuilderOptionFunc func(mb *TelemetryBuilder)\n\nfunc (tbof telemetryBuilderOptionFunc) apply(mb *TelemetryBuilder) {\n\ttbof(mb)\n}\n\n// RegisterProcessorBatchMetadataCardinalityCallback sets callback for observable ProcessorBatchMetadataCardinality metric.\nfunc (builder *TelemetryBuilder) RegisterProcessorBatchMetadataCardinalityCallback(cb metric.Int64Callback) error {\n\treg, err := builder.meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {\n\t\tcb(ctx, &observerInt64{inst: builder.ProcessorBatchMetadataCardinality, obs: o})\n\t\treturn nil\n\t}, builder.ProcessorBatchMetadataCardinality)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tbuilder.registrations = append(builder.registrations, reg)\n\treturn nil\n}\n\ntype observerInt64 struct {\n\tembedded.Int64Observer\n\tinst metric.Int64Observable\n\tobs  metric.Observer\n}\n\nfunc (oi *observerInt64) Observe(value int64, opts ...metric.ObserveOption) {\n\toi.obs.ObserveInt64(oi.inst, value, opts...)\n}\n\n// Shutdown unregister all registered callbacks for async instruments.\nfunc (builder *TelemetryBuilder) Shutdown() {\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tfor _, reg := range builder.registrations {\n\t\treg.Unregister()\n\t}\n}\n\n// NewTelemetryBuilder provides a struct with methods to update all internal telemetry\n// for a component\nfunc NewTelemetryBuilder(settings component.TelemetrySettings, options ...TelemetryBuilderOption) (*TelemetryBuilder, error) {\n\tbuilder := TelemetryBuilder{}\n\tfor _, op := range options {\n\t\top.apply(&builder)\n\t}\n\tbuilder.meter = Meter(settings)\n\tvar err, errs error\n\tbuilder.ProcessorBatchBatchSendSize, err = builder.meter.Int64Histogram(\n\t\t\"otelcol_processor_batch_batch_send_size\",\n\t\tmetric.WithDescription(\"Number of units in the batch [Development]\"),\n\t\tmetric.WithUnit(\"{unit}\"),\n\t\tmetric.WithExplicitBucketBoundaries([]float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, 100000}...),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessorBatchBatchSendSizeBytes, err = builder.meter.Int64Histogram(\n\t\t\"otelcol_processor_batch_batch_send_size_bytes\",\n\t\tmetric.WithDescription(\"Number of bytes in batch that was sent. Only available on detailed level. [Development]\"),\n\t\tmetric.WithUnit(\"By\"),\n\t\tmetric.WithExplicitBucketBoundaries([]float64{10, 25, 50, 75, 100, 250, 500, 750, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000, 20000, 30000, 50000, 100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000, 1e+06, 2e+06, 3e+06, 4e+06, 5e+06, 6e+06, 7e+06, 8e+06, 9e+06}...),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessorBatchBatchSizeTriggerSend, err = builder.meter.Int64Counter(\n\t\t\"otelcol_processor_batch_batch_size_trigger_send\",\n\t\tmetric.WithDescription(\"Number of times the batch was sent due to a size trigger [Development]\"),\n\t\tmetric.WithUnit(\"{time}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessorBatchMetadataCardinality, err = builder.meter.Int64ObservableUpDownCounter(\n\t\t\"otelcol_processor_batch_metadata_cardinality\",\n\t\tmetric.WithDescription(\"Number of distinct metadata value combinations being processed [Development]\"),\n\t\tmetric.WithUnit(\"{combination}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessorBatchTimeoutTriggerSend, err = builder.meter.Int64Counter(\n\t\t\"otelcol_processor_batch_timeout_trigger_send\",\n\t\tmetric.WithDescription(\"Number of times the batch was sent due to a timeout trigger [Development]\"),\n\t\tmetric.WithUnit(\"{time}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\treturn &builder, errs\n}\n"
  },
  {
    "path": "processor/batchprocessor/internal/metadata/generated_telemetry_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/metric\"\n\tembeddedmetric \"go.opentelemetry.io/otel/metric/embedded\"\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\t\"go.opentelemetry.io/otel/trace\"\n\tembeddedtrace \"go.opentelemetry.io/otel/trace/embedded\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\ntype mockMeter struct {\n\tnoopmetric.Meter\n\tname string\n}\ntype mockMeterProvider struct {\n\tembeddedmetric.MeterProvider\n}\n\nfunc (m mockMeterProvider) Meter(name string, opts ...metric.MeterOption) metric.Meter {\n\treturn mockMeter{name: name}\n}\n\ntype mockTracer struct {\n\tnooptrace.Tracer\n\tname string\n}\n\ntype mockTracerProvider struct {\n\tembeddedtrace.TracerProvider\n}\n\nfunc (m mockTracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer {\n\treturn mockTracer{name: name}\n}\n\nfunc TestProviders(t *testing.T) {\n\tset := component.TelemetrySettings{\n\t\tMeterProvider:  mockMeterProvider{},\n\t\tTracerProvider: mockTracerProvider{},\n\t}\n\n\tmeter := Meter(set)\n\tif m, ok := meter.(mockMeter); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/processor/batchprocessor\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockMeter\")\n\t}\n\n\ttracer := Tracer(set)\n\tif m, ok := tracer.(mockTracer); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/processor/batchprocessor\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockTracer\")\n\t}\n}\n\nfunc TestNewTelemetryBuilder(t *testing.T) {\n\tset := componenttest.NewNopTelemetrySettings()\n\tapplied := false\n\t_, err := NewTelemetryBuilder(set, telemetryBuilderOptionFunc(func(b *TelemetryBuilder) {\n\t\tapplied = true\n\t}))\n\trequire.NoError(t, err)\n\trequire.True(t, applied)\n}\n"
  },
  {
    "path": "processor/batchprocessor/internal/metadatatest/generated_telemetrytest.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n)\n\nfunc NewSettings(tt *componenttest.Telemetry) processor.Settings {\n\tset := processortest.NewNopSettings(processortest.NopType)\n\tset.ID = component.NewID(component.MustNewType(\"batch\"))\n\tset.TelemetrySettings = tt.NewTelemetrySettings()\n\treturn set\n}\n\nfunc AssertEqualProcessorBatchBatchSendSize(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.HistogramDataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_processor_batch_batch_send_size\",\n\t\tDescription: \"Number of units in the batch [Development]\",\n\t\tUnit:        \"{unit}\",\n\t\tData: metricdata.Histogram[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_processor_batch_batch_send_size\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessorBatchBatchSendSizeBytes(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.HistogramDataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_processor_batch_batch_send_size_bytes\",\n\t\tDescription: \"Number of bytes in batch that was sent. Only available on detailed level. [Development]\",\n\t\tUnit:        \"By\",\n\t\tData: metricdata.Histogram[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_processor_batch_batch_send_size_bytes\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessorBatchBatchSizeTriggerSend(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_processor_batch_batch_size_trigger_send\",\n\t\tDescription: \"Number of times the batch was sent due to a size trigger [Development]\",\n\t\tUnit:        \"{time}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_processor_batch_batch_size_trigger_send\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessorBatchMetadataCardinality(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_processor_batch_metadata_cardinality\",\n\t\tDescription: \"Number of distinct metadata value combinations being processed [Development]\",\n\t\tUnit:        \"{combination}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: false,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_processor_batch_metadata_cardinality\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessorBatchTimeoutTriggerSend(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_processor_batch_timeout_trigger_send\",\n\t\tDescription: \"Number of times the batch was sent due to a timeout trigger [Development]\",\n\t\tUnit:        \"{time}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_processor_batch_timeout_trigger_send\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n"
  },
  {
    "path": "processor/batchprocessor/internal/metadatatest/generated_telemetrytest_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/processor/batchprocessor/internal/metadata\"\n)\n\nfunc TestSetupTelemetry(t *testing.T) {\n\ttestTel := componenttest.NewTelemetry()\n\ttb, err := metadata.NewTelemetryBuilder(testTel.NewTelemetrySettings())\n\trequire.NoError(t, err)\n\tdefer tb.Shutdown()\n\trequire.NoError(t, tb.RegisterProcessorBatchMetadataCardinalityCallback(func(_ context.Context, observer metric.Int64Observer) error {\n\t\tobserver.Observe(1)\n\t\treturn nil\n\t}))\n\ttb.ProcessorBatchBatchSendSize.Record(context.Background(), 1)\n\ttb.ProcessorBatchBatchSendSizeBytes.Record(context.Background(), 1)\n\ttb.ProcessorBatchBatchSizeTriggerSend.Add(context.Background(), 1)\n\ttb.ProcessorBatchTimeoutTriggerSend.Add(context.Background(), 1)\n\tAssertEqualProcessorBatchBatchSendSize(t, testTel,\n\t\t[]metricdata.HistogramDataPoint[int64]{{}}, metricdatatest.IgnoreValue(),\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessorBatchBatchSendSizeBytes(t, testTel,\n\t\t[]metricdata.HistogramDataPoint[int64]{{}}, metricdatatest.IgnoreValue(),\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessorBatchBatchSizeTriggerSend(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessorBatchMetadataCardinality(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessorBatchTimeoutTriggerSend(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\n\trequire.NoError(t, testTel.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "processor/batchprocessor/metadata.yaml",
    "content": "display_name: Batch Processor\ntype: batch\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: processor\n  stability:\n    beta: [traces, metrics, logs]\n  distributions: [core, contrib, k8s]\n\ntests:\n\ntelemetry:\n  metrics:\n    processor_batch_batch_send_size:\n      enabled: true\n      stability: development\n      description: Number of units in the batch\n      unit: \"{unit}\"\n      histogram:\n        value_type: int\n        bucket_boundaries:\n          [\n            10,\n            25,\n            50,\n            75,\n            100,\n            250,\n            500,\n            750,\n            1000,\n            2000,\n            3000,\n            4000,\n            5000,\n            6000,\n            7000,\n            8000,\n            9000,\n            10000,\n            20000,\n            30000,\n            50000,\n            100000,\n          ]\n    processor_batch_batch_send_size_bytes:\n      enabled: true\n      stability: development\n      description: Number of bytes in batch that was sent. Only available on detailed level.\n      unit: By\n      histogram:\n        value_type: int\n        bucket_boundaries:\n          [\n            10,\n            25,\n            50,\n            75,\n            100,\n            250,\n            500,\n            750,\n            1000,\n            2000,\n            3000,\n            4000,\n            5000,\n            6000,\n            7000,\n            8000,\n            9000,\n            10000,\n            20000,\n            30000,\n            50000,\n            100_000,\n            200_000,\n            300_000,\n            400_000,\n            500_000,\n            600_000,\n            700_000,\n            800_000,\n            900_000,\n            1000_000,\n            2000_000,\n            3000_000,\n            4000_000,\n            5000_000,\n            6000_000,\n            7000_000,\n            8000_000,\n            9000_000,\n          ]\n    processor_batch_batch_size_trigger_send:\n      enabled: true\n      stability: development\n      description: Number of times the batch was sent due to a size trigger\n      unit: \"{time}\"\n      sum:\n        value_type: int\n        monotonic: true\n    processor_batch_metadata_cardinality:\n      enabled: true\n      stability: development\n      description: Number of distinct metadata value combinations being processed\n      unit: \"{combination}\"\n      sum:\n        value_type: int\n        async: true\n    processor_batch_timeout_trigger_send:\n      enabled: true\n      stability: development\n      description: Number of times the batch was sent due to a timeout trigger\n      unit: \"{time}\"\n      sum:\n        value_type: int\n        monotonic: true\n"
  },
  {
    "path": "processor/batchprocessor/metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage batchprocessor // import \"go.opentelemetry.io/collector/processor/batchprocessor\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/metric\"\n\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/batchprocessor/internal/metadata\"\n\t\"go.opentelemetry.io/collector/processor/internal\"\n)\n\ntype trigger int\n\nconst (\n\ttriggerTimeout trigger = iota\n\ttriggerBatchSize\n)\n\ntype batchProcessorTelemetry struct {\n\texportCtx context.Context\n\n\tprocessorAttr    metric.MeasurementOption\n\ttelemetryBuilder *metadata.TelemetryBuilder\n}\n\nfunc newBatchProcessorTelemetry(set processor.Settings, currentMetadataCardinality func() int) (*batchProcessorTelemetry, error) {\n\tattrs := metric.WithAttributeSet(attribute.NewSet(attribute.String(internal.ProcessorKey, set.ID.String())))\n\n\ttelemetryBuilder, err := metadata.NewTelemetryBuilder(set.TelemetrySettings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\terr = telemetryBuilder.RegisterProcessorBatchMetadataCardinalityCallback(func(_ context.Context, observer metric.Int64Observer) error {\n\t\tobserver.Observe(int64(currentMetadataCardinality()), attrs)\n\t\treturn nil\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &batchProcessorTelemetry{\n\t\texportCtx:        context.Background(),\n\t\ttelemetryBuilder: telemetryBuilder,\n\t\tprocessorAttr:    attrs,\n\t}, nil\n}\n\nfunc (bpt *batchProcessorTelemetry) record(trigger trigger, sent, bytes int64) {\n\tswitch trigger {\n\tcase triggerBatchSize:\n\t\tbpt.telemetryBuilder.ProcessorBatchBatchSizeTriggerSend.Add(bpt.exportCtx, 1, bpt.processorAttr)\n\tcase triggerTimeout:\n\t\tbpt.telemetryBuilder.ProcessorBatchTimeoutTriggerSend.Add(bpt.exportCtx, 1, bpt.processorAttr)\n\t}\n\n\tbpt.telemetryBuilder.ProcessorBatchBatchSendSize.Record(bpt.exportCtx, sent, bpt.processorAttr)\n\tbpt.telemetryBuilder.ProcessorBatchBatchSendSizeBytes.Record(bpt.exportCtx, bytes, bpt.processorAttr)\n}\n"
  },
  {
    "path": "processor/batchprocessor/splitlogs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage batchprocessor // import \"go.opentelemetry.io/collector/processor/batchprocessor\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\n// splitLogs removes logrecords from the input data and returns a new data of the specified size.\nfunc splitLogs(size int, src plog.Logs) plog.Logs {\n\tif src.LogRecordCount() <= size {\n\t\treturn src\n\t}\n\ttotalCopiedLogRecords := 0\n\tdest := plog.NewLogs()\n\n\tsrc.ResourceLogs().RemoveIf(func(srcRl plog.ResourceLogs) bool {\n\t\t// If we are done skip everything else.\n\t\tif totalCopiedLogRecords == size {\n\t\t\treturn false\n\t\t}\n\n\t\t// If it fully fits\n\t\tsrcRlLRC := resourceLRC(srcRl)\n\t\tif (totalCopiedLogRecords + srcRlLRC) <= size {\n\t\t\ttotalCopiedLogRecords += srcRlLRC\n\t\t\tsrcRl.MoveTo(dest.ResourceLogs().AppendEmpty())\n\t\t\treturn true\n\t\t}\n\n\t\tdestRl := dest.ResourceLogs().AppendEmpty()\n\t\tsrcRl.Resource().CopyTo(destRl.Resource())\n\t\tdestRl.SetSchemaUrl(srcRl.SchemaUrl())\n\t\tsrcRl.ScopeLogs().RemoveIf(func(srcIll plog.ScopeLogs) bool {\n\t\t\t// If we are done skip everything else.\n\t\t\tif totalCopiedLogRecords == size {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// If possible to move all metrics do that.\n\t\t\tsrcIllLRC := srcIll.LogRecords().Len()\n\t\t\tif size >= srcIllLRC+totalCopiedLogRecords {\n\t\t\t\ttotalCopiedLogRecords += srcIllLRC\n\t\t\t\tsrcIll.MoveTo(destRl.ScopeLogs().AppendEmpty())\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tdestIll := destRl.ScopeLogs().AppendEmpty()\n\t\t\tsrcIll.Scope().CopyTo(destIll.Scope())\n\t\t\tdestIll.SetSchemaUrl(srcIll.SchemaUrl())\n\t\t\tsrcIll.LogRecords().RemoveIf(func(srcMetric plog.LogRecord) bool {\n\t\t\t\t// If we are done skip everything else.\n\t\t\t\tif totalCopiedLogRecords == size {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tsrcMetric.MoveTo(destIll.LogRecords().AppendEmpty())\n\t\t\t\ttotalCopiedLogRecords++\n\t\t\t\treturn true\n\t\t\t})\n\t\t\treturn false\n\t\t})\n\t\treturn srcRl.ScopeLogs().Len() == 0\n\t})\n\n\treturn dest\n}\n\n// resourceLRC calculates the total number of log records in the plog.ResourceLogs.\nfunc resourceLRC(rs plog.ResourceLogs) (count int) {\n\tfor k := 0; k < rs.ScopeLogs().Len(); k++ {\n\t\tcount += rs.ScopeLogs().At(k).LogRecords().Len()\n\t}\n\treturn count\n}\n"
  },
  {
    "path": "processor/batchprocessor/splitlogs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage batchprocessor\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestSplitLogs_noop(t *testing.T) {\n\ttd := testdata.GenerateLogs(20)\n\tsplitSize := 40\n\tsplit := splitLogs(splitSize, td)\n\tassert.Equal(t, td, split)\n\n\ti := 0\n\ttd.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().RemoveIf(func(plog.LogRecord) bool {\n\t\ti++\n\t\treturn i > 5\n\t})\n\tassert.Equal(t, td, split)\n}\n\nfunc TestSplitLogs(t *testing.T) {\n\tld := testdata.GenerateLogs(20)\n\tlogs := ld.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords()\n\tfor i := 0; i < logs.Len(); i++ {\n\t\tlogs.At(i).SetSeverityText(getTestLogSeverityText(0, i))\n\t}\n\tcp := plog.NewLogs()\n\tcpLogs := cp.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords()\n\tcpLogs.EnsureCapacity(5)\n\tld.ResourceLogs().At(0).Resource().CopyTo(\n\t\tcp.ResourceLogs().At(0).Resource())\n\tld.ResourceLogs().At(0).ScopeLogs().At(0).Scope().CopyTo(\n\t\tcp.ResourceLogs().At(0).ScopeLogs().At(0).Scope())\n\tlogs.At(0).CopyTo(cpLogs.AppendEmpty())\n\tlogs.At(1).CopyTo(cpLogs.AppendEmpty())\n\tlogs.At(2).CopyTo(cpLogs.AppendEmpty())\n\tlogs.At(3).CopyTo(cpLogs.AppendEmpty())\n\tlogs.At(4).CopyTo(cpLogs.AppendEmpty())\n\n\tsplitSize := 5\n\tsplit := splitLogs(splitSize, ld)\n\tassert.Equal(t, splitSize, split.LogRecordCount())\n\tassert.Equal(t, cp, split)\n\tassert.Equal(t, 15, ld.LogRecordCount())\n\tassert.Equal(t, \"test-log-int-0-0\", split.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(0).SeverityText())\n\tassert.Equal(t, \"test-log-int-0-4\", split.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(4).SeverityText())\n\n\tsplit = splitLogs(splitSize, ld)\n\tassert.Equal(t, 10, ld.LogRecordCount())\n\tassert.Equal(t, \"test-log-int-0-5\", split.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(0).SeverityText())\n\tassert.Equal(t, \"test-log-int-0-9\", split.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(4).SeverityText())\n\n\tsplit = splitLogs(splitSize, ld)\n\tassert.Equal(t, 5, ld.LogRecordCount())\n\tassert.Equal(t, \"test-log-int-0-10\", split.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(0).SeverityText())\n\tassert.Equal(t, \"test-log-int-0-14\", split.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(4).SeverityText())\n\n\tsplit = splitLogs(splitSize, ld)\n\tassert.Equal(t, 5, ld.LogRecordCount())\n\tassert.Equal(t, \"test-log-int-0-15\", split.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(0).SeverityText())\n\tassert.Equal(t, \"test-log-int-0-19\", split.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(4).SeverityText())\n}\n\nfunc TestSplitLogsMultipleResourceLogs(t *testing.T) {\n\ttd := testdata.GenerateLogs(20)\n\tlogs := td.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords()\n\tfor i := 0; i < logs.Len(); i++ {\n\t\tlogs.At(i).SetSeverityText(getTestLogSeverityText(0, i))\n\t}\n\t// add second index to resource logs\n\ttestdata.GenerateLogs(20).\n\t\tResourceLogs().At(0).CopyTo(td.ResourceLogs().AppendEmpty())\n\tlogs = td.ResourceLogs().At(1).ScopeLogs().At(0).LogRecords()\n\tfor i := 0; i < logs.Len(); i++ {\n\t\tlogs.At(i).SetSeverityText(getTestLogSeverityText(1, i))\n\t}\n\n\tsplitSize := 5\n\tsplit := splitLogs(splitSize, td)\n\tassert.Equal(t, splitSize, split.LogRecordCount())\n\tassert.Equal(t, 35, td.LogRecordCount())\n\tassert.Equal(t, \"test-log-int-0-0\", split.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(0).SeverityText())\n\tassert.Equal(t, \"test-log-int-0-4\", split.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(4).SeverityText())\n}\n\nfunc TestSplitLogsMultipleResourceLogs_split_size_greater_than_log_size(t *testing.T) {\n\ttd := testdata.GenerateLogs(20)\n\tlogs := td.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords()\n\tfor i := 0; i < logs.Len(); i++ {\n\t\tlogs.At(i).SetSeverityText(getTestLogSeverityText(0, i))\n\t}\n\t// add second index to resource logs\n\ttestdata.GenerateLogs(20).\n\t\tResourceLogs().At(0).CopyTo(td.ResourceLogs().AppendEmpty())\n\tlogs = td.ResourceLogs().At(1).ScopeLogs().At(0).LogRecords()\n\tfor i := 0; i < logs.Len(); i++ {\n\t\tlogs.At(i).SetSeverityText(getTestLogSeverityText(1, i))\n\t}\n\n\tsplitSize := 25\n\tsplit := splitLogs(splitSize, td)\n\tassert.Equal(t, splitSize, split.LogRecordCount())\n\tassert.Equal(t, 40-splitSize, td.LogRecordCount())\n\tassert.Equal(t, 1, td.ResourceLogs().Len())\n\tassert.Equal(t, \"test-log-int-0-0\", split.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(0).SeverityText())\n\tassert.Equal(t, \"test-log-int-0-19\", split.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(19).SeverityText())\n\tassert.Equal(t, \"test-log-int-1-0\", split.ResourceLogs().At(1).ScopeLogs().At(0).LogRecords().At(0).SeverityText())\n\tassert.Equal(t, \"test-log-int-1-4\", split.ResourceLogs().At(1).ScopeLogs().At(0).LogRecords().At(4).SeverityText())\n}\n\nfunc TestSplitLogsMultipleILL(t *testing.T) {\n\ttd := testdata.GenerateLogs(20)\n\tlogs := td.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords()\n\tfor i := 0; i < logs.Len(); i++ {\n\t\tlogs.At(i).SetSeverityText(getTestLogSeverityText(0, i))\n\t}\n\t// add second index to ILL\n\ttd.ResourceLogs().At(0).ScopeLogs().At(0).\n\t\tCopyTo(td.ResourceLogs().At(0).ScopeLogs().AppendEmpty())\n\tlogs = td.ResourceLogs().At(0).ScopeLogs().At(1).LogRecords()\n\tfor i := 0; i < logs.Len(); i++ {\n\t\tlogs.At(i).SetSeverityText(getTestLogSeverityText(1, i))\n\t}\n\n\t// add third index to ILL\n\ttd.ResourceLogs().At(0).ScopeLogs().At(0).\n\t\tCopyTo(td.ResourceLogs().At(0).ScopeLogs().AppendEmpty())\n\tlogs = td.ResourceLogs().At(0).ScopeLogs().At(2).LogRecords()\n\tfor i := 0; i < logs.Len(); i++ {\n\t\tlogs.At(i).SetSeverityText(getTestLogSeverityText(2, i))\n\t}\n\n\tsplitSize := 40\n\tsplit := splitLogs(splitSize, td)\n\tassert.Equal(t, splitSize, split.LogRecordCount())\n\tassert.Equal(t, 20, td.LogRecordCount())\n\tassert.Equal(t, \"test-log-int-0-0\", split.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(0).SeverityText())\n\tassert.Equal(t, \"test-log-int-0-4\", split.ResourceLogs().At(0).ScopeLogs().At(0).LogRecords().At(4).SeverityText())\n}\n\nfunc TestSplitLogsPreserveSchemaURLOnPartialSplit(t *testing.T) {\n\tresourceSchemaURL := \"https://test-resource-schema-url.com/\"\n\tscopeSchemaURL := \"https://test-scope-schema-url.com/\"\n\ttd := testdata.GenerateLogs(2)\n\ttd.ResourceLogs().At(0).SetSchemaUrl(resourceSchemaURL)\n\ttd.ResourceLogs().At(0).ScopeLogs().At(0).SetSchemaUrl(scopeSchemaURL)\n\n\tsplitSize := 1\n\tsplit := splitLogs(splitSize, td)\n\tassert.Equal(t, resourceSchemaURL, split.ResourceLogs().At(0).SchemaUrl())\n\tassert.Equal(t, scopeSchemaURL, split.ResourceLogs().At(0).ScopeLogs().At(0).SchemaUrl())\n}\n"
  },
  {
    "path": "processor/batchprocessor/splitmetrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage batchprocessor // import \"go.opentelemetry.io/collector/processor/batchprocessor\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\n// splitMetrics removes metrics from the input data and returns a new data of the specified size.\nfunc splitMetrics(size int, src pmetric.Metrics) pmetric.Metrics {\n\tdataPoints := src.DataPointCount()\n\tif dataPoints <= size {\n\t\treturn src\n\t}\n\ttotalCopiedDataPoints := 0\n\tdest := pmetric.NewMetrics()\n\n\tsrc.ResourceMetrics().RemoveIf(func(srcRs pmetric.ResourceMetrics) bool {\n\t\t// If we are done skip everything else.\n\t\tif totalCopiedDataPoints == size {\n\t\t\treturn false\n\t\t}\n\n\t\t// If it fully fits\n\t\tsrcRsDataPointCount := resourceMetricsDPC(srcRs)\n\t\tif (totalCopiedDataPoints + srcRsDataPointCount) <= size {\n\t\t\ttotalCopiedDataPoints += srcRsDataPointCount\n\t\t\tsrcRs.MoveTo(dest.ResourceMetrics().AppendEmpty())\n\t\t\treturn true\n\t\t}\n\n\t\tdestRs := dest.ResourceMetrics().AppendEmpty()\n\t\tsrcRs.Resource().CopyTo(destRs.Resource())\n\t\tdestRs.SetSchemaUrl(srcRs.SchemaUrl())\n\t\tsrcRs.ScopeMetrics().RemoveIf(func(srcIlm pmetric.ScopeMetrics) bool {\n\t\t\t// If we are done skip everything else.\n\t\t\tif totalCopiedDataPoints == size {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// If possible to move all metrics do that.\n\t\t\tsrcIlmDataPointCount := scopeMetricsDPC(srcIlm)\n\t\t\tif srcIlmDataPointCount+totalCopiedDataPoints <= size {\n\t\t\t\ttotalCopiedDataPoints += srcIlmDataPointCount\n\t\t\t\tsrcIlm.MoveTo(destRs.ScopeMetrics().AppendEmpty())\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tdestIlm := destRs.ScopeMetrics().AppendEmpty()\n\t\t\tsrcIlm.Scope().CopyTo(destIlm.Scope())\n\t\t\tdestIlm.SetSchemaUrl(srcIlm.SchemaUrl())\n\t\t\tsrcIlm.Metrics().RemoveIf(func(srcMetric pmetric.Metric) bool {\n\t\t\t\t// If we are done skip everything else.\n\t\t\t\tif totalCopiedDataPoints == size {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\n\t\t\t\t// If possible to move all points do that.\n\t\t\t\tsrcMetricPointCount := metricDPC(srcMetric)\n\t\t\t\tif srcMetricPointCount+totalCopiedDataPoints <= size {\n\t\t\t\t\ttotalCopiedDataPoints += srcMetricPointCount\n\t\t\t\t\tsrcMetric.MoveTo(destIlm.Metrics().AppendEmpty())\n\t\t\t\t\treturn true\n\t\t\t\t}\n\n\t\t\t\t// If the metric has more data points than free slots we should split it.\n\t\t\t\tcopiedDataPoints, remove := splitMetric(srcMetric, destIlm.Metrics().AppendEmpty(), size-totalCopiedDataPoints)\n\t\t\t\ttotalCopiedDataPoints += copiedDataPoints\n\t\t\t\treturn remove\n\t\t\t})\n\t\t\treturn false\n\t\t})\n\t\treturn srcRs.ScopeMetrics().Len() == 0\n\t})\n\n\treturn dest\n}\n\n// resourceMetricsDPC calculates the total number of data points in the pmetric.ResourceMetrics.\nfunc resourceMetricsDPC(rs pmetric.ResourceMetrics) int {\n\tdataPointCount := 0\n\tilms := rs.ScopeMetrics()\n\tfor k := 0; k < ilms.Len(); k++ {\n\t\tdataPointCount += scopeMetricsDPC(ilms.At(k))\n\t}\n\treturn dataPointCount\n}\n\n// scopeMetricsDPC calculates the total number of data points in the pmetric.ScopeMetrics.\nfunc scopeMetricsDPC(ilm pmetric.ScopeMetrics) int {\n\tdataPointCount := 0\n\tms := ilm.Metrics()\n\tfor k := 0; k < ms.Len(); k++ {\n\t\tdataPointCount += metricDPC(ms.At(k))\n\t}\n\treturn dataPointCount\n}\n\n// metricDPC calculates the total number of data points in the pmetric.Metric.\nfunc metricDPC(ms pmetric.Metric) int {\n\tswitch ms.Type() {\n\tcase pmetric.MetricTypeGauge:\n\t\treturn ms.Gauge().DataPoints().Len()\n\tcase pmetric.MetricTypeSum:\n\t\treturn ms.Sum().DataPoints().Len()\n\tcase pmetric.MetricTypeHistogram:\n\t\treturn ms.Histogram().DataPoints().Len()\n\tcase pmetric.MetricTypeExponentialHistogram:\n\t\treturn ms.ExponentialHistogram().DataPoints().Len()\n\tcase pmetric.MetricTypeSummary:\n\t\treturn ms.Summary().DataPoints().Len()\n\t}\n\treturn 0\n}\n\n// splitMetric removes metric points from the input data and moves data of the specified size to destination.\n// Returns size of moved data and boolean describing, whether the metric should be removed from original slice.\nfunc splitMetric(ms, dest pmetric.Metric, size int) (int, bool) {\n\tdest.SetName(ms.Name())\n\tdest.SetDescription(ms.Description())\n\tdest.SetUnit(ms.Unit())\n\n\tswitch ms.Type() {\n\tcase pmetric.MetricTypeGauge:\n\t\treturn splitNumberDataPoints(ms.Gauge().DataPoints(), dest.SetEmptyGauge().DataPoints(), size)\n\tcase pmetric.MetricTypeSum:\n\t\tdestSum := dest.SetEmptySum()\n\t\tdestSum.SetAggregationTemporality(ms.Sum().AggregationTemporality())\n\t\tdestSum.SetIsMonotonic(ms.Sum().IsMonotonic())\n\t\treturn splitNumberDataPoints(ms.Sum().DataPoints(), destSum.DataPoints(), size)\n\tcase pmetric.MetricTypeHistogram:\n\t\tdestHistogram := dest.SetEmptyHistogram()\n\t\tdestHistogram.SetAggregationTemporality(ms.Histogram().AggregationTemporality())\n\t\treturn splitHistogramDataPoints(ms.Histogram().DataPoints(), destHistogram.DataPoints(), size)\n\tcase pmetric.MetricTypeExponentialHistogram:\n\t\tdestHistogram := dest.SetEmptyExponentialHistogram()\n\t\tdestHistogram.SetAggregationTemporality(ms.ExponentialHistogram().AggregationTemporality())\n\t\treturn splitExponentialHistogramDataPoints(ms.ExponentialHistogram().DataPoints(), destHistogram.DataPoints(), size)\n\tcase pmetric.MetricTypeSummary:\n\t\treturn splitSummaryDataPoints(ms.Summary().DataPoints(), dest.SetEmptySummary().DataPoints(), size)\n\t}\n\treturn size, false\n}\n\nfunc splitNumberDataPoints(src, dst pmetric.NumberDataPointSlice, size int) (int, bool) {\n\tdst.EnsureCapacity(size)\n\ti := 0\n\tsrc.RemoveIf(func(dp pmetric.NumberDataPoint) bool {\n\t\tif i < size {\n\t\t\tdp.MoveTo(dst.AppendEmpty())\n\t\t\ti++\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t})\n\treturn size, false\n}\n\nfunc splitHistogramDataPoints(src, dst pmetric.HistogramDataPointSlice, size int) (int, bool) {\n\tdst.EnsureCapacity(size)\n\ti := 0\n\tsrc.RemoveIf(func(dp pmetric.HistogramDataPoint) bool {\n\t\tif i < size {\n\t\t\tdp.MoveTo(dst.AppendEmpty())\n\t\t\ti++\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t})\n\treturn size, false\n}\n\nfunc splitExponentialHistogramDataPoints(src, dst pmetric.ExponentialHistogramDataPointSlice, size int) (int, bool) {\n\tdst.EnsureCapacity(size)\n\ti := 0\n\tsrc.RemoveIf(func(dp pmetric.ExponentialHistogramDataPoint) bool {\n\t\tif i < size {\n\t\t\tdp.MoveTo(dst.AppendEmpty())\n\t\t\ti++\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t})\n\treturn size, false\n}\n\nfunc splitSummaryDataPoints(src, dst pmetric.SummaryDataPointSlice, size int) (int, bool) {\n\tdst.EnsureCapacity(size)\n\ti := 0\n\tsrc.RemoveIf(func(dp pmetric.SummaryDataPoint) bool {\n\t\tif i < size {\n\t\t\tdp.MoveTo(dst.AppendEmpty())\n\t\t\ti++\n\t\t\treturn true\n\t\t}\n\t\treturn false\n\t})\n\treturn size, false\n}\n"
  },
  {
    "path": "processor/batchprocessor/splitmetrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage batchprocessor\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestSplitMetrics_noop(t *testing.T) {\n\ttd := testdata.GenerateMetrics(20)\n\tsplitSize := 40\n\tsplit := splitMetrics(splitSize, td)\n\tassert.Equal(t, td, split)\n\n\ti := 0\n\ttd.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().RemoveIf(func(pmetric.Metric) bool {\n\t\ti++\n\t\treturn i > 5\n\t})\n\tassert.Equal(t, td, split)\n}\n\nfunc TestSplitMetrics(t *testing.T) {\n\tmd := testdata.GenerateMetrics(20)\n\tmetrics := md.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics()\n\tdataPointCount := metricDPC(metrics.At(0))\n\tfor i := 0; i < metrics.Len(); i++ {\n\t\tmetrics.At(i).SetName(getTestMetricName(0, i))\n\t\tassert.Equal(t, dataPointCount, metricDPC(metrics.At(i)))\n\t}\n\tcp := pmetric.NewMetrics()\n\tcpMetrics := cp.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()\n\tcpMetrics.EnsureCapacity(5)\n\tmd.ResourceMetrics().At(0).ScopeMetrics().At(0).Scope().CopyTo(\n\t\tcp.ResourceMetrics().At(0).ScopeMetrics().At(0).Scope())\n\tmd.ResourceMetrics().At(0).Resource().CopyTo(\n\t\tcp.ResourceMetrics().At(0).Resource())\n\tmetrics.At(0).CopyTo(cpMetrics.AppendEmpty())\n\tmetrics.At(1).CopyTo(cpMetrics.AppendEmpty())\n\tmetrics.At(2).CopyTo(cpMetrics.AppendEmpty())\n\tmetrics.At(3).CopyTo(cpMetrics.AppendEmpty())\n\tmetrics.At(4).CopyTo(cpMetrics.AppendEmpty())\n\n\tsplitMetricCount := 5\n\tsplitSize := splitMetricCount * dataPointCount\n\tsplit := splitMetrics(splitSize, md)\n\tassert.Equal(t, splitMetricCount, split.MetricCount())\n\tassert.Equal(t, cp, split)\n\tassert.Equal(t, 15, md.MetricCount())\n\tassert.Equal(t, \"test-metric-int-0-0\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Name())\n\tassert.Equal(t, \"test-metric-int-0-4\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(4).Name())\n\n\tsplit = splitMetrics(splitSize, md)\n\tassert.Equal(t, 10, md.MetricCount())\n\tassert.Equal(t, \"test-metric-int-0-5\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Name())\n\tassert.Equal(t, \"test-metric-int-0-9\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(4).Name())\n\n\tsplit = splitMetrics(splitSize, md)\n\tassert.Equal(t, 5, md.MetricCount())\n\tassert.Equal(t, \"test-metric-int-0-10\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Name())\n\tassert.Equal(t, \"test-metric-int-0-14\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(4).Name())\n\n\tsplit = splitMetrics(splitSize, md)\n\tassert.Equal(t, 5, md.MetricCount())\n\tassert.Equal(t, \"test-metric-int-0-15\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Name())\n\tassert.Equal(t, \"test-metric-int-0-19\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(4).Name())\n}\n\nfunc TestSplitMetricsMultipleResourceSpans(t *testing.T) {\n\tmd := testdata.GenerateMetrics(20)\n\tmetrics := md.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics()\n\tdataPointCount := metricDPC(metrics.At(0))\n\tfor i := 0; i < metrics.Len(); i++ {\n\t\tmetrics.At(i).SetName(getTestMetricName(0, i))\n\t\tassert.Equal(t, dataPointCount, metricDPC(metrics.At(i)))\n\t}\n\t// add second index to resource metrics\n\ttestdata.GenerateMetrics(20).\n\t\tResourceMetrics().At(0).CopyTo(md.ResourceMetrics().AppendEmpty())\n\tmetrics = md.ResourceMetrics().At(1).ScopeMetrics().At(0).Metrics()\n\tfor i := 0; i < metrics.Len(); i++ {\n\t\tmetrics.At(i).SetName(getTestMetricName(1, i))\n\t}\n\n\tsplitMetricCount := 5\n\tsplitSize := splitMetricCount * dataPointCount\n\tsplit := splitMetrics(splitSize, md)\n\tassert.Equal(t, splitMetricCount, split.MetricCount())\n\tassert.Equal(t, 35, md.MetricCount())\n\tassert.Equal(t, \"test-metric-int-0-0\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Name())\n\tassert.Equal(t, \"test-metric-int-0-4\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(4).Name())\n}\n\nfunc TestSplitMetricsMultipleResourceSpans_SplitSizeGreaterThanMetricSize(t *testing.T) {\n\ttd := testdata.GenerateMetrics(20)\n\tmetrics := td.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics()\n\tdataPointCount := metricDPC(metrics.At(0))\n\tfor i := 0; i < metrics.Len(); i++ {\n\t\tmetrics.At(i).SetName(getTestMetricName(0, i))\n\t\tassert.Equal(t, dataPointCount, metricDPC(metrics.At(i)))\n\t}\n\t// add second index to resource metrics\n\ttestdata.GenerateMetrics(20).\n\t\tResourceMetrics().At(0).CopyTo(td.ResourceMetrics().AppendEmpty())\n\tmetrics = td.ResourceMetrics().At(1).ScopeMetrics().At(0).Metrics()\n\tfor i := 0; i < metrics.Len(); i++ {\n\t\tmetrics.At(i).SetName(getTestMetricName(1, i))\n\t}\n\n\tsplitMetricCount := 25\n\tsplitSize := splitMetricCount * dataPointCount\n\tsplit := splitMetrics(splitSize, td)\n\tassert.Equal(t, splitMetricCount, split.MetricCount())\n\tassert.Equal(t, 40-splitMetricCount, td.MetricCount())\n\tassert.Equal(t, 1, td.ResourceMetrics().Len())\n\tassert.Equal(t, \"test-metric-int-0-0\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Name())\n\tassert.Equal(t, \"test-metric-int-0-19\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(19).Name())\n\tassert.Equal(t, \"test-metric-int-1-0\", split.ResourceMetrics().At(1).ScopeMetrics().At(0).Metrics().At(0).Name())\n\tassert.Equal(t, \"test-metric-int-1-4\", split.ResourceMetrics().At(1).ScopeMetrics().At(0).Metrics().At(4).Name())\n}\n\nfunc TestSplitMetricsUneven(t *testing.T) {\n\tmd := testdata.GenerateMetrics(10)\n\tmetrics := md.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics()\n\tdataPointCount := 2\n\tfor i := 0; i < metrics.Len(); i++ {\n\t\tmetrics.At(i).SetName(getTestMetricName(0, i))\n\t\tassert.Equal(t, dataPointCount, metricDPC(metrics.At(i)))\n\t}\n\n\tsplitSize := 9\n\tsplit := splitMetrics(splitSize, md)\n\tassert.Equal(t, 5, split.MetricCount())\n\tassert.Equal(t, 6, md.MetricCount())\n\tassert.Equal(t, \"test-metric-int-0-0\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Name())\n\tassert.Equal(t, \"test-metric-int-0-4\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(4).Name())\n\n\tsplit = splitMetrics(splitSize, md)\n\tassert.Equal(t, 5, split.MetricCount())\n\tassert.Equal(t, 1, md.MetricCount())\n\tassert.Equal(t, \"test-metric-int-0-4\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Name())\n\tassert.Equal(t, \"test-metric-int-0-8\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(4).Name())\n\n\tsplit = splitMetrics(splitSize, md)\n\tassert.Equal(t, 1, split.MetricCount())\n\tassert.Equal(t, \"test-metric-int-0-9\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Name())\n}\n\nfunc TestSplitMetricsAllTypes(t *testing.T) {\n\tmd := testdata.GenerateMetricsAllTypes()\n\tdataPointCount := 2\n\tmetrics := md.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics()\n\tfor i := 0; i < metrics.Len(); i++ {\n\t\tmetrics.At(i).SetName(getTestMetricName(0, i))\n\t\tassert.Equal(t, dataPointCount, metricDPC(metrics.At(i)))\n\t}\n\n\tsplitSize := 2\n\t// Start with 7 metric types, and 2 points per-metric. Split out the first,\n\t// and then split by 2 for the rest so that each metric is split in half.\n\t// Verify that descriptors are preserved for all data types across splits.\n\n\tsplit := splitMetrics(1, md)\n\tassert.Equal(t, 1, split.MetricCount())\n\tassert.Equal(t, 7, md.MetricCount())\n\tgaugeInt := split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0)\n\tassert.Equal(t, 1, gaugeInt.Gauge().DataPoints().Len())\n\tassert.Equal(t, \"test-metric-int-0-0\", gaugeInt.Name())\n\n\tsplit = splitMetrics(splitSize, md)\n\tassert.Equal(t, 2, split.MetricCount())\n\tassert.Equal(t, 6, md.MetricCount())\n\tgaugeInt = split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0)\n\tgaugeDouble := split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(1)\n\tassert.Equal(t, 1, gaugeInt.Gauge().DataPoints().Len())\n\tassert.Equal(t, \"test-metric-int-0-0\", gaugeInt.Name())\n\tassert.Equal(t, 1, gaugeDouble.Gauge().DataPoints().Len())\n\tassert.Equal(t, \"test-metric-int-0-1\", gaugeDouble.Name())\n\n\tsplit = splitMetrics(splitSize, md)\n\tassert.Equal(t, 2, split.MetricCount())\n\tassert.Equal(t, 5, md.MetricCount())\n\tgaugeDouble = split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0)\n\tsumInt := split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(1)\n\tassert.Equal(t, 1, gaugeDouble.Gauge().DataPoints().Len())\n\tassert.Equal(t, \"test-metric-int-0-1\", gaugeDouble.Name())\n\tassert.Equal(t, 1, sumInt.Sum().DataPoints().Len())\n\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, sumInt.Sum().AggregationTemporality())\n\tassert.True(t, sumInt.Sum().IsMonotonic())\n\tassert.Equal(t, \"test-metric-int-0-2\", sumInt.Name())\n\n\tsplit = splitMetrics(splitSize, md)\n\tassert.Equal(t, 2, split.MetricCount())\n\tassert.Equal(t, 4, md.MetricCount())\n\tsumInt = split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0)\n\tsumDouble := split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(1)\n\tassert.Equal(t, 1, sumInt.Sum().DataPoints().Len())\n\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, sumInt.Sum().AggregationTemporality())\n\tassert.True(t, sumInt.Sum().IsMonotonic())\n\tassert.Equal(t, \"test-metric-int-0-2\", sumInt.Name())\n\tassert.Equal(t, 1, sumDouble.Sum().DataPoints().Len())\n\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, sumDouble.Sum().AggregationTemporality())\n\tassert.True(t, sumDouble.Sum().IsMonotonic())\n\tassert.Equal(t, \"test-metric-int-0-3\", sumDouble.Name())\n\n\tsplit = splitMetrics(splitSize, md)\n\tassert.Equal(t, 2, split.MetricCount())\n\tassert.Equal(t, 3, md.MetricCount())\n\tsumDouble = split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0)\n\thistogram := split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(1)\n\tassert.Equal(t, 1, sumDouble.Sum().DataPoints().Len())\n\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, sumDouble.Sum().AggregationTemporality())\n\tassert.True(t, sumDouble.Sum().IsMonotonic())\n\tassert.Equal(t, \"test-metric-int-0-3\", sumDouble.Name())\n\tassert.Equal(t, 1, histogram.Histogram().DataPoints().Len())\n\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, histogram.Histogram().AggregationTemporality())\n\tassert.Equal(t, \"test-metric-int-0-4\", histogram.Name())\n\n\tsplit = splitMetrics(splitSize, md)\n\tassert.Equal(t, 2, split.MetricCount())\n\tassert.Equal(t, 2, md.MetricCount())\n\thistogram = split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0)\n\texponentialHistogram := split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(1)\n\tassert.Equal(t, 1, histogram.Histogram().DataPoints().Len())\n\tassert.Equal(t, pmetric.AggregationTemporalityCumulative, histogram.Histogram().AggregationTemporality())\n\tassert.Equal(t, \"test-metric-int-0-4\", histogram.Name())\n\tassert.Equal(t, 1, exponentialHistogram.ExponentialHistogram().DataPoints().Len())\n\tassert.Equal(t, pmetric.AggregationTemporalityDelta, exponentialHistogram.ExponentialHistogram().AggregationTemporality())\n\tassert.Equal(t, \"test-metric-int-0-5\", exponentialHistogram.Name())\n\n\tsplit = splitMetrics(splitSize, md)\n\tassert.Equal(t, 2, split.MetricCount())\n\tassert.Equal(t, 1, md.MetricCount())\n\texponentialHistogram = split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0)\n\tsummary := split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(1)\n\tassert.Equal(t, 1, exponentialHistogram.ExponentialHistogram().DataPoints().Len())\n\tassert.Equal(t, pmetric.AggregationTemporalityDelta, exponentialHistogram.ExponentialHistogram().AggregationTemporality())\n\tassert.Equal(t, \"test-metric-int-0-5\", exponentialHistogram.Name())\n\tassert.Equal(t, 1, summary.Summary().DataPoints().Len())\n\tassert.Equal(t, \"test-metric-int-0-6\", summary.Name())\n\n\tsplit = splitMetrics(splitSize, md)\n\tsummary = split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0)\n\tassert.Equal(t, 1, summary.Summary().DataPoints().Len())\n\tassert.Equal(t, \"test-metric-int-0-6\", summary.Name())\n}\n\nfunc TestSplitMetricsBatchSizeSmallerThanDataPointCount(t *testing.T) {\n\tmd := testdata.GenerateMetrics(2)\n\tmetrics := md.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics()\n\tdataPointCount := 2\n\tfor i := 0; i < metrics.Len(); i++ {\n\t\tmetrics.At(i).SetName(getTestMetricName(0, i))\n\t\tassert.Equal(t, dataPointCount, metricDPC(metrics.At(i)))\n\t}\n\n\tsplitSize := 1\n\tsplit := splitMetrics(splitSize, md)\n\tsplitMetric := split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0)\n\tassert.Equal(t, 1, split.MetricCount())\n\tassert.Equal(t, 2, md.MetricCount())\n\tassert.Equal(t, \"test-metric-int-0-0\", splitMetric.Name())\n\n\tsplit = splitMetrics(splitSize, md)\n\tsplitMetric = split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0)\n\tassert.Equal(t, 1, split.MetricCount())\n\tassert.Equal(t, 1, md.MetricCount())\n\tassert.Equal(t, \"test-metric-int-0-0\", splitMetric.Name())\n\n\tsplit = splitMetrics(splitSize, md)\n\tsplitMetric = split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0)\n\tassert.Equal(t, 1, split.MetricCount())\n\tassert.Equal(t, 1, md.MetricCount())\n\tassert.Equal(t, \"test-metric-int-0-1\", splitMetric.Name())\n\n\tsplit = splitMetrics(splitSize, md)\n\tsplitMetric = split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0)\n\tassert.Equal(t, 1, split.MetricCount())\n\tassert.Equal(t, 1, md.MetricCount())\n\tassert.Equal(t, \"test-metric-int-0-1\", splitMetric.Name())\n}\n\nfunc TestSplitMetricsMultipleILM(t *testing.T) {\n\tmd := testdata.GenerateMetrics(20)\n\tmetrics := md.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics()\n\tdataPointCount := metricDPC(metrics.At(0))\n\tfor i := 0; i < metrics.Len(); i++ {\n\t\tmetrics.At(i).SetName(getTestMetricName(0, i))\n\t\tassert.Equal(t, dataPointCount, metricDPC(metrics.At(i)))\n\t}\n\t// add second index to ilm\n\tmd.ResourceMetrics().At(0).ScopeMetrics().At(0).\n\t\tCopyTo(md.ResourceMetrics().At(0).ScopeMetrics().AppendEmpty())\n\n\t// add a third index to ilm\n\tmd.ResourceMetrics().At(0).ScopeMetrics().At(0).\n\t\tCopyTo(md.ResourceMetrics().At(0).ScopeMetrics().AppendEmpty())\n\tmetrics = md.ResourceMetrics().At(0).ScopeMetrics().At(2).Metrics()\n\tfor i := 0; i < metrics.Len(); i++ {\n\t\tmetrics.At(i).SetName(getTestMetricName(2, i))\n\t}\n\n\tsplitMetricCount := 40\n\tsplitSize := splitMetricCount * dataPointCount\n\tsplit := splitMetrics(splitSize, md)\n\tassert.Equal(t, splitMetricCount, split.MetricCount())\n\tassert.Equal(t, 20, md.MetricCount())\n\tassert.Equal(t, \"test-metric-int-0-0\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(0).Name())\n\tassert.Equal(t, \"test-metric-int-0-4\", split.ResourceMetrics().At(0).ScopeMetrics().At(0).Metrics().At(4).Name())\n}\n\nfunc TestSplitMetricsPreserveSchemaURLOnPartialSplit(t *testing.T) {\n\tresourceSchemaURL := \"https://test-resource-schema-url.com/\"\n\tscopeSchemaURL := \"https://test-scope-schema-url.com/\"\n\tmd := testdata.GenerateMetrics(2)\n\tmd.ResourceMetrics().At(0).SetSchemaUrl(resourceSchemaURL)\n\tmd.ResourceMetrics().At(0).ScopeMetrics().At(0).SetSchemaUrl(scopeSchemaURL)\n\n\tsplitSize := 1\n\tsplit := splitMetrics(splitSize, md)\n\tassert.Equal(t, resourceSchemaURL, split.ResourceMetrics().At(0).SchemaUrl())\n\tassert.Equal(t, scopeSchemaURL, split.ResourceMetrics().At(0).ScopeMetrics().At(0).SchemaUrl())\n}\n"
  },
  {
    "path": "processor/batchprocessor/splittraces.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage batchprocessor // import \"go.opentelemetry.io/collector/processor/batchprocessor\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\n// splitTraces removes spans from the input trace and returns a new trace of the specified size.\nfunc splitTraces(size int, src ptrace.Traces) ptrace.Traces {\n\tif src.SpanCount() <= size {\n\t\treturn src\n\t}\n\ttotalCopiedSpans := 0\n\tdest := ptrace.NewTraces()\n\n\tsrc.ResourceSpans().RemoveIf(func(srcRs ptrace.ResourceSpans) bool {\n\t\t// If we are done skip everything else.\n\t\tif totalCopiedSpans == size {\n\t\t\treturn false\n\t\t}\n\n\t\t// If it fully fits\n\t\tsrcRsSC := resourceSC(srcRs)\n\t\tif (totalCopiedSpans + srcRsSC) <= size {\n\t\t\ttotalCopiedSpans += srcRsSC\n\t\t\tsrcRs.MoveTo(dest.ResourceSpans().AppendEmpty())\n\t\t\treturn true\n\t\t}\n\n\t\tdestRs := dest.ResourceSpans().AppendEmpty()\n\t\tsrcRs.Resource().CopyTo(destRs.Resource())\n\t\tdestRs.SetSchemaUrl(srcRs.SchemaUrl())\n\t\tsrcRs.ScopeSpans().RemoveIf(func(srcIls ptrace.ScopeSpans) bool {\n\t\t\t// If we are done skip everything else.\n\t\t\tif totalCopiedSpans == size {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\t// If possible to move all metrics do that.\n\t\t\tsrcIlsSC := srcIls.Spans().Len()\n\t\t\tif size-totalCopiedSpans >= srcIlsSC {\n\t\t\t\ttotalCopiedSpans += srcIlsSC\n\t\t\t\tsrcIls.MoveTo(destRs.ScopeSpans().AppendEmpty())\n\t\t\t\treturn true\n\t\t\t}\n\n\t\t\tdestIls := destRs.ScopeSpans().AppendEmpty()\n\t\t\tsrcIls.Scope().CopyTo(destIls.Scope())\n\t\t\tdestIls.SetSchemaUrl(srcIls.SchemaUrl())\n\t\t\tsrcIls.Spans().RemoveIf(func(srcSpan ptrace.Span) bool {\n\t\t\t\t// If we are done skip everything else.\n\t\t\t\tif totalCopiedSpans == size {\n\t\t\t\t\treturn false\n\t\t\t\t}\n\t\t\t\tsrcSpan.MoveTo(destIls.Spans().AppendEmpty())\n\t\t\t\ttotalCopiedSpans++\n\t\t\t\treturn true\n\t\t\t})\n\t\t\treturn false\n\t\t})\n\t\treturn srcRs.ScopeSpans().Len() == 0\n\t})\n\n\treturn dest\n}\n\n// resourceSC calculates the total number of spans in the ptrace.ResourceSpans.\nfunc resourceSC(rs ptrace.ResourceSpans) (count int) {\n\tfor k := 0; k < rs.ScopeSpans().Len(); k++ {\n\t\tcount += rs.ScopeSpans().At(k).Spans().Len()\n\t}\n\treturn count\n}\n"
  },
  {
    "path": "processor/batchprocessor/splittraces_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage batchprocessor\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestSplitTraces_noop(t *testing.T) {\n\ttd := testdata.GenerateTraces(20)\n\tsplitSize := 40\n\tsplit := splitTraces(splitSize, td)\n\tassert.Equal(t, td, split)\n\n\ti := 0\n\ttd.ResourceSpans().At(0).ScopeSpans().At(0).Spans().RemoveIf(func(ptrace.Span) bool {\n\t\ti++\n\t\treturn i > 5\n\t})\n\tassert.Equal(t, td, split)\n}\n\nfunc TestSplitTraces(t *testing.T) {\n\ttd := testdata.GenerateTraces(20)\n\tspans := td.ResourceSpans().At(0).ScopeSpans().At(0).Spans()\n\tfor i := 0; i < spans.Len(); i++ {\n\t\tspans.At(i).SetName(getTestSpanName(0, i))\n\t}\n\tcp := ptrace.NewTraces()\n\tcpSpans := cp.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans()\n\tcpSpans.EnsureCapacity(5)\n\ttd.ResourceSpans().At(0).Resource().CopyTo(\n\t\tcp.ResourceSpans().At(0).Resource())\n\ttd.ResourceSpans().At(0).ScopeSpans().At(0).Scope().CopyTo(\n\t\tcp.ResourceSpans().At(0).ScopeSpans().At(0).Scope())\n\tspans.At(0).CopyTo(cpSpans.AppendEmpty())\n\tspans.At(1).CopyTo(cpSpans.AppendEmpty())\n\tspans.At(2).CopyTo(cpSpans.AppendEmpty())\n\tspans.At(3).CopyTo(cpSpans.AppendEmpty())\n\tspans.At(4).CopyTo(cpSpans.AppendEmpty())\n\n\tsplitSize := 5\n\tsplit := splitTraces(splitSize, td)\n\tassert.Equal(t, splitSize, split.SpanCount())\n\tassert.Equal(t, cp, split)\n\tassert.Equal(t, 15, td.SpanCount())\n\tassert.Equal(t, \"test-span-0-0\", split.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).Name())\n\tassert.Equal(t, \"test-span-0-4\", split.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(4).Name())\n\n\tsplit = splitTraces(splitSize, td)\n\tassert.Equal(t, 10, td.SpanCount())\n\tassert.Equal(t, \"test-span-0-5\", split.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).Name())\n\tassert.Equal(t, \"test-span-0-9\", split.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(4).Name())\n\n\tsplit = splitTraces(splitSize, td)\n\tassert.Equal(t, 5, td.SpanCount())\n\tassert.Equal(t, \"test-span-0-10\", split.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).Name())\n\tassert.Equal(t, \"test-span-0-14\", split.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(4).Name())\n\n\tsplit = splitTraces(splitSize, td)\n\tassert.Equal(t, 5, td.SpanCount())\n\tassert.Equal(t, \"test-span-0-15\", split.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).Name())\n\tassert.Equal(t, \"test-span-0-19\", split.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(4).Name())\n}\n\nfunc TestSplitTracesMultipleResourceSpans(t *testing.T) {\n\ttd := testdata.GenerateTraces(20)\n\tspans := td.ResourceSpans().At(0).ScopeSpans().At(0).Spans()\n\tfor i := 0; i < spans.Len(); i++ {\n\t\tspans.At(i).SetName(getTestSpanName(0, i))\n\t}\n\t// add second index to resource spans\n\ttestdata.GenerateTraces(20).\n\t\tResourceSpans().At(0).CopyTo(td.ResourceSpans().AppendEmpty())\n\tspans = td.ResourceSpans().At(1).ScopeSpans().At(0).Spans()\n\tfor i := 0; i < spans.Len(); i++ {\n\t\tspans.At(i).SetName(getTestSpanName(1, i))\n\t}\n\n\tsplitSize := 5\n\tsplit := splitTraces(splitSize, td)\n\tassert.Equal(t, splitSize, split.SpanCount())\n\tassert.Equal(t, 35, td.SpanCount())\n\tassert.Equal(t, \"test-span-0-0\", split.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).Name())\n\tassert.Equal(t, \"test-span-0-4\", split.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(4).Name())\n}\n\nfunc TestSplitTracesMultipleResourceSpans_SplitSizeGreaterThanSpanSize(t *testing.T) {\n\ttd := testdata.GenerateTraces(20)\n\tspans := td.ResourceSpans().At(0).ScopeSpans().At(0).Spans()\n\tfor i := 0; i < spans.Len(); i++ {\n\t\tspans.At(i).SetName(getTestSpanName(0, i))\n\t}\n\t// add second index to resource spans\n\ttestdata.GenerateTraces(20).\n\t\tResourceSpans().At(0).CopyTo(td.ResourceSpans().AppendEmpty())\n\tspans = td.ResourceSpans().At(1).ScopeSpans().At(0).Spans()\n\tfor i := 0; i < spans.Len(); i++ {\n\t\tspans.At(i).SetName(getTestSpanName(1, i))\n\t}\n\n\tsplitSize := 25\n\tsplit := splitTraces(splitSize, td)\n\tassert.Equal(t, splitSize, split.SpanCount())\n\tassert.Equal(t, 40-splitSize, td.SpanCount())\n\tassert.Equal(t, 1, td.ResourceSpans().Len())\n\tassert.Equal(t, \"test-span-0-0\", split.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).Name())\n\tassert.Equal(t, \"test-span-0-19\", split.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(19).Name())\n\tassert.Equal(t, \"test-span-1-0\", split.ResourceSpans().At(1).ScopeSpans().At(0).Spans().At(0).Name())\n\tassert.Equal(t, \"test-span-1-4\", split.ResourceSpans().At(1).ScopeSpans().At(0).Spans().At(4).Name())\n}\n\nfunc TestSplitTracesMultipleILS(t *testing.T) {\n\ttd := testdata.GenerateTraces(20)\n\tspans := td.ResourceSpans().At(0).ScopeSpans().At(0).Spans()\n\tfor i := 0; i < spans.Len(); i++ {\n\t\tspans.At(i).SetName(getTestSpanName(0, i))\n\t}\n\t// add second index to ILS\n\ttd.ResourceSpans().At(0).ScopeSpans().At(0).\n\t\tCopyTo(td.ResourceSpans().At(0).ScopeSpans().AppendEmpty())\n\tspans = td.ResourceSpans().At(0).ScopeSpans().At(1).Spans()\n\tfor i := 0; i < spans.Len(); i++ {\n\t\tspans.At(i).SetName(getTestSpanName(1, i))\n\t}\n\n\t// add third index to ILS\n\ttd.ResourceSpans().At(0).ScopeSpans().At(0).\n\t\tCopyTo(td.ResourceSpans().At(0).ScopeSpans().AppendEmpty())\n\tspans = td.ResourceSpans().At(0).ScopeSpans().At(2).Spans()\n\tfor i := 0; i < spans.Len(); i++ {\n\t\tspans.At(i).SetName(getTestSpanName(2, i))\n\t}\n\n\tsplitSize := 40\n\tsplit := splitTraces(splitSize, td)\n\tassert.Equal(t, splitSize, split.SpanCount())\n\tassert.Equal(t, 20, td.SpanCount())\n\tassert.Equal(t, \"test-span-0-0\", split.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).Name())\n\tassert.Equal(t, \"test-span-0-4\", split.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(4).Name())\n}\n\nfunc TestSplitTracesPreserveSchemaURLOnPartialSplit(t *testing.T) {\n\tresourceSchemaURL := \"https://test-resource-schema-url.com/\"\n\tscopeSchemaURL := \"https://test-scope-schema-url.com/\"\n\ttd := testdata.GenerateTraces(2)\n\ttd.ResourceSpans().At(0).SetSchemaUrl(resourceSchemaURL)\n\ttd.ResourceSpans().At(0).ScopeSpans().At(0).SetSchemaUrl(scopeSchemaURL)\n\n\tsplitSize := 1\n\tsplit := splitTraces(splitSize, td)\n\tassert.Equal(t, resourceSchemaURL, split.ResourceSpans().At(0).SchemaUrl())\n\tassert.Equal(t, scopeSchemaURL, split.ResourceSpans().At(0).ScopeSpans().At(0).SchemaUrl())\n}\n"
  },
  {
    "path": "processor/batchprocessor/testdata/config.yaml",
    "content": "timeout: 10s\nsend_batch_size: 10000\nsend_batch_max_size: 11000\n"
  },
  {
    "path": "processor/go.mod",
    "content": "module go.opentelemetry.io/collector/processor\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../component\n\nreplace go.opentelemetry.io/collector/consumer => ../consumer\n\nreplace go.opentelemetry.io/collector/pdata => ../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/pipeline => ../pipeline\n\nreplace go.opentelemetry.io/collector/featuregate => ../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../internal/componentalias\n"
  },
  {
    "path": "processor/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "processor/internal/err.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/processor/internal\"\n\nimport (\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc ErrIDMismatch(id component.ID, typ component.Type) error {\n\treturn fmt.Errorf(\"component type mismatch: component ID %q does not have type %q\", id, typ)\n}\n"
  },
  {
    "path": "processor/internal/obsmetrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/processor/internal\"\n\nconst (\n\tMetricNameSep = \"_\"\n\n\t// ProcessorKey is the key used to identify processors in metrics and traces.\n\tProcessorKey = \"processor\"\n\n\tProcessorMetricPrefix = ProcessorKey + MetricNameSep\n)\n"
  },
  {
    "path": "processor/memorylimiterprocessor/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "processor/memorylimiterprocessor/README.md",
    "content": "<!-- status autogenerated section -->\n# Memory Limiter Processor\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [alpha]: profiles   |\n|               | [beta]: traces, metrics, logs   |\n| Distributions | [core], [contrib], [k8s] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Aprocessor%2Fmemorylimiter%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Aprocessor%2Fmemorylimiter) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Aprocessor%2Fmemorylimiter%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Aprocessor%2Fmemorylimiter) |\n\n[alpha]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#alpha\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[core]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n[k8s]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\n<!-- end autogenerated section -->\n\n## Overview\n\nThe memory limiter processor is used to prevent out of memory situations on\nthe collector. Given that the amount and type of data the collector processes is\nenvironment-specific and resource utilization of the collector is also dependent\non the configured processors, it is important to put checks in place regarding\nmemory usage.\n\n## Functionality\n\nThe memory limiter processor performs periodic checks of memory\nusage and will begin refusing data and forcing GC to reduce\nmemory consumption when defined limits have been exceeded.\n\nThe processor uses soft and hard memory limits. The hard limit is defined via the\n`limit_mib` configuration option, and is always above or equal\nto the soft limit. The difference between the soft limit and hard limit is defined via\nthe `spike_limit_mib` configuration option.\n\nThe processor will enter memory limited mode and will start refusing the data when\nmemory usage exceeds the soft limit. This is done by returning errors to the preceding component\nin the pipeline that made the ConsumeLogs/Trace/Metrics function call.\n\n> Warning: Incoming data can consume additional memory in a Collector before the\n> memory limiter processor is able to reject it. Be sure to consider this when\n> setting your limits, particularly for non-OTLP receivers.\n>\n> See <https://github.com/open-telemetry/opentelemetry-collector/issues/8632> for\n> more.\n\nIn memory limited mode the error returned by ConsumeLogs/Trace/Metrics function is a\nnon-permanent error. When receivers see this error they are expected to retry sending\nthe same data. The receivers may also apply backpressure to their own data sources\nin order to slow the inflow of data into the Collector, and to allow memory usage\nto go below the set limits.\n\n> Warning: Data will be permanently lost if the component preceding the memory limiter\n> in the telemetry pipeline does not correctly retry sending data after it has\n> been refused by the memory limiter.\n> We consider such components to be incorrectly implemented.\n\nWhen the memory usage is above the hard limit the processor will additionally\nforce garbage collection to be performed.\n\nNormal operation is resumed when memory usage drops below the soft limit, meaning data\nwill no longer be refused and the processor won't force garbage collection to\nbe performed.\n\n## Best Practices\n\nNote that while the processor can help mitigate out of memory situations,\nit is not a replacement for properly sizing and configuring the\ncollector. Keep in mind that if the soft limit is crossed, the collector will\nreturn errors to all receive operations until enough memory is freed. This may\neventually result in dropped data since the receivers may not be able to\nretry the data indefinitely.\n\nIt is highly recommended to configure the `GOMEMLIMIT`\n[environment variable](https://pkg.go.dev/runtime#hdr-Environment_Variables) as well\nas the `memory_limiter` processor on every collector. `GOMEMLIMIT` should be set to\n80% of the hard memory limit of your collector. For the `memory_limiter` processor, the\nbest practice is to add it as the first processor in a pipeline. This is to ensure that backpressure\ncan be sent to applicable receivers and minimize the likelihood of dropped data when the\n`memory_limiter` gets triggered.\n\nThe value of the `spike_limit_mib` configuration option should be selected in a way\nthat ensures that memory usage cannot increase by more than this value within a single\nmemory check interval. Otherwise, memory usage may exceed the hard limit, even if temporarily.\nA good starting point for `spike_limit_mib` is 20% of the hard limit. Bigger\n`spike_limit_mib` values may be necessary for spiky traffic or for longer check intervals.\n\nIt's recommended to coordinate the hard memory limit with the host environment\nof the Collector. As always, you know your environment best, so use your own\njudgement to determine the best configuration for your situation. However, the\nfollowing points are worth considering when configuring the processor:\n\nFor containerized environments or other similar environments that support\nsetting memory restrictions on the Collector, `limit_percentage` should\ngenerally be used, which allows the host environment to determine the\nCollector's max memory allocation without tying the Collector's own config to\nits deployment config. The percentage should be large enough to use the majority\nof the Collector's allocated memory, but not so much that it risks running out\nof memory.\n\nFor bare metal or virtualized environments where the Collector's memory is not\nconstrained by the host environment, it is recommended to use `limit_mib` for\nenvironments where you know the rough data throughput and memory consumption you\nexpect for a given Collector, regardless of the memory capacity of the machine\nit runs on. If the Collector's memory consumption is expected to scale with its\nhost machine's memory capacity, `limit_percentage` may be more appropriate.\n\n## Configuration\n\nPlease refer to [config.go](../../internal/memorylimiter/config.go) for the config spec.\n\nThe following configuration options are available. Note that one of `limit_mib`\nor `limit_percentage` must be set.\n\n- `check_interval` (default = 0s): Time between measurements of memory\nusage. The recommended value is 1 second.\nIf the expected traffic to the Collector is very spiky then decrease the `check_interval`\nor increase `spike_limit_mib` to avoid memory usage going over the hard limit.\n- `limit_mib` (default = 0): Maximum amount of memory, in MiB, targeted to be\nallocated by the process heap. Note that typically the total memory usage of\nprocess will be about 50MiB higher than this value.  This defines the hard limit.\n- `spike_limit_mib` (default = 20% of `limit_mib`): Maximum spike expected between the\nmeasurements of memory usage. The value must be less than `limit_mib`. The soft limit\nvalue will be equal to (`limit_mib - spike_limit_mib`).\nThe recommended value for `spike_limit_mib` is about 20% `limit_mib`.\n- `limit_percentage` (default = 0): Maximum amount of total memory targeted to be\nallocated by the process heap. This configuration is supported on Linux systems with cgroups\nand it's intended to be used in dynamic platforms like docker.\nThis option is used to calculate `memory_limit` from the total available memory.\nFor instance setting of 75% with the total memory of 1GiB will result in the limit of 750 MiB.\nThe fixed memory setting (`limit_mib`) takes precedence\nover the percentage configuration.\n- `spike_limit_percentage` (default = 20% of `limit_percentage`): Maximum spike expected between the\nmeasurements of memory usage. The value must be less than `limit_percentage`.\nThis option is used to calculate `spike_limit_mib` from the total available memory.\nFor instance setting of 25% with the total memory of 1GiB will result in the spike limit of 250MiB.\nThis option is intended to be used only with `limit_percentage`.\n\nExamples:\n\n```yaml\nprocessors:\n  memory_limiter:\n    check_interval: 1s\n    limit_mib: 4000\n    spike_limit_mib: 800\n```\n\n- Hard limit will be set to **4000 MiB**.\n- Soft limit will be set to 4000 - 800 = **3200 MiB**.\n\n```yaml\nprocessors:\n  memory_limiter:\n    check_interval: 1s\n    limit_percentage: 80\n    spike_limit_percentage: 15\n```\n\nOn a machine with 1000 MiB total memory available:\n\n- Hard limit will be set to 1000 * 0.80 = **800 MiB**.\n- Soft limit will be set to 1000 * 0.80 - 1000 * 0.15 = 1000 * 0.65 = **650 MiB**.\n"
  },
  {
    "path": "processor/memorylimiterprocessor/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage memorylimiterprocessor // import \"go.opentelemetry.io/collector/processor/memorylimiterprocessor\"\nimport \"go.opentelemetry.io/collector/internal/memorylimiter\"\n\ntype Config = memorylimiter.Config\n"
  },
  {
    "path": "processor/memorylimiterprocessor/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# memory_limiter\n\n## Internal Telemetry\n\nThe following telemetry is emitted by this component.\n\n### otelcol_processor_accepted_log_records\n\nNumber of log records successfully pushed into the next component in the pipeline.\n\n> **Deprecated since 0.110.0**\n> This metric is deprecated\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {record} | Sum | Int | true | Deprecated since 0.110.0 |\n\n**Deprecation note**: This metric is deprecated\n\n### otelcol_processor_accepted_metric_points\n\nNumber of metric points successfully pushed into the next component in the pipeline.\n\n> **Deprecated since 0.110.0**\n> This metric is deprecated\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {datapoint} | Sum | Int | true | Deprecated since 0.110.0 |\n\n**Deprecation note**: This metric is deprecated\n\n### otelcol_processor_accepted_spans\n\nNumber of spans successfully pushed into the next component in the pipeline.\n\n> **Deprecated since 0.110.0**\n> This metric is deprecated\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {span} | Sum | Int | true | Deprecated since 0.110.0 |\n\n**Deprecation note**: This metric is deprecated\n\n### otelcol_processor_refused_log_records\n\nNumber of log records that were rejected by the next component in the pipeline.\n\n> **Deprecated since 0.110.0**\n> This metric is deprecated\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {record} | Sum | Int | true | Deprecated since 0.110.0 |\n\n**Deprecation note**: This metric is deprecated\n\n### otelcol_processor_refused_metric_points\n\nNumber of metric points that were rejected by the next component in the pipeline.\n\n> **Deprecated since 0.110.0**\n> This metric is deprecated\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {datapoint} | Sum | Int | true | Deprecated since 0.110.0 |\n\n**Deprecation note**: This metric is deprecated\n\n### otelcol_processor_refused_spans\n\nNumber of spans that were rejected by the next component in the pipeline.\n\n> **Deprecated since 0.110.0**\n> This metric is deprecated\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {span} | Sum | Int | true | Deprecated since 0.110.0 |\n\n**Deprecation note**: This metric is deprecated\n"
  },
  {
    "path": "processor/memorylimiterprocessor/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\npackage memorylimiterprocessor // import \"go.opentelemetry.io/collector/processor/memorylimiterprocessor\"\n\nimport (\n\t\"context\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/internal/memorylimiter\"\n\t\"go.opentelemetry.io/collector/internal/telemetry\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/memorylimiterprocessor/internal/metadata\"\n\t\"go.opentelemetry.io/collector/processor/processorhelper\"\n\t\"go.opentelemetry.io/collector/processor/processorhelper/xprocessorhelper\"\n\t\"go.opentelemetry.io/collector/processor/xprocessor\"\n)\n\nvar processorCapabilities = consumer.Capabilities{MutatesData: false}\n\ntype factory struct {\n\t// memoryLimiters stores memoryLimiter instances with unique configs that multiple processors can reuse.\n\t// This avoids running multiple memory checks (ie: GC) for every processor using the same processor config.\n\tmemoryLimiters map[component.Config]*memoryLimiterProcessor\n\tlock           sync.Mutex\n}\n\n// NewFactory returns a new factory for the Memory Limiter processor.\nfunc NewFactory() xprocessor.Factory {\n\tf := &factory{\n\t\tmemoryLimiters: map[component.Config]*memoryLimiterProcessor{},\n\t}\n\treturn xprocessor.NewFactory(\n\t\tmetadata.Type,\n\t\tcreateDefaultConfig,\n\t\txprocessor.WithTraces(f.createTraces, metadata.TracesStability),\n\t\txprocessor.WithMetrics(f.createMetrics, metadata.MetricsStability),\n\t\txprocessor.WithLogs(f.createLogs, metadata.LogsStability),\n\t\txprocessor.WithProfiles(f.createProfiles, metadata.ProfilesStability))\n}\n\n// CreateDefaultConfig creates the default configuration for processor. Notice\n// that the default configuration is expected to fail for this processor.\nfunc createDefaultConfig() component.Config {\n\treturn memorylimiter.NewDefaultConfig()\n}\n\nfunc (f *factory) createTraces(\n\tctx context.Context,\n\tset processor.Settings,\n\tcfg component.Config,\n\tnextConsumer consumer.Traces,\n) (processor.Traces, error) {\n\tmemLimiter, err := f.getMemoryLimiter(set, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn processorhelper.NewTraces(ctx, set, cfg, nextConsumer,\n\t\tmemLimiter.processTraces,\n\t\tprocessorhelper.WithCapabilities(processorCapabilities),\n\t\tprocessorhelper.WithStart(memLimiter.start),\n\t\tprocessorhelper.WithShutdown(memLimiter.shutdown))\n}\n\nfunc (f *factory) createMetrics(\n\tctx context.Context,\n\tset processor.Settings,\n\tcfg component.Config,\n\tnextConsumer consumer.Metrics,\n) (processor.Metrics, error) {\n\tmemLimiter, err := f.getMemoryLimiter(set, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn processorhelper.NewMetrics(ctx, set, cfg, nextConsumer,\n\t\tmemLimiter.processMetrics,\n\t\tprocessorhelper.WithCapabilities(processorCapabilities),\n\t\tprocessorhelper.WithStart(memLimiter.start),\n\t\tprocessorhelper.WithShutdown(memLimiter.shutdown))\n}\n\nfunc (f *factory) createLogs(\n\tctx context.Context,\n\tset processor.Settings,\n\tcfg component.Config,\n\tnextConsumer consumer.Logs,\n) (processor.Logs, error) {\n\tmemLimiter, err := f.getMemoryLimiter(set, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn processorhelper.NewLogs(ctx, set, cfg, nextConsumer,\n\t\tmemLimiter.processLogs,\n\t\tprocessorhelper.WithCapabilities(processorCapabilities),\n\t\tprocessorhelper.WithStart(memLimiter.start),\n\t\tprocessorhelper.WithShutdown(memLimiter.shutdown))\n}\n\nfunc (f *factory) createProfiles(\n\tctx context.Context,\n\tset processor.Settings,\n\tcfg component.Config,\n\tnextConsumer xconsumer.Profiles,\n) (xprocessor.Profiles, error) {\n\tmemLimiter, err := f.getMemoryLimiter(set, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn xprocessorhelper.NewProfiles(\n\t\tctx,\n\t\tset,\n\t\tcfg,\n\t\tnextConsumer,\n\t\tmemLimiter.processProfiles,\n\t\txprocessorhelper.WithCapabilities(processorCapabilities),\n\t\txprocessorhelper.WithStart(memLimiter.start),\n\t\txprocessorhelper.WithShutdown(memLimiter.shutdown),\n\t)\n}\n\n// getMemoryLimiter checks if we have a cached memoryLimiter with a specific config,\n// otherwise initialize and add one to the store.\nfunc (f *factory) getMemoryLimiter(set processor.Settings, cfg component.Config) (*memoryLimiterProcessor, error) {\n\tf.lock.Lock()\n\tdefer f.lock.Unlock()\n\n\tif memLimiter, ok := f.memoryLimiters[cfg]; ok {\n\t\treturn memLimiter, nil\n\t}\n\n\tset.TelemetrySettings = telemetry.DropInjectedAttributes(\n\t\tset.TelemetrySettings,\n\t\ttelemetry.SignalKey,\n\t\ttelemetry.PipelineIDKey,\n\t\ttelemetry.ComponentIDKey,\n\t)\n\tset.Logger.Debug(\"created singleton logger\")\n\n\tmemLimiter, err := newMemoryLimiterProcessor(set, cfg.(*Config))\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tf.memoryLimiters[cfg] = memLimiter\n\treturn memLimiter, nil\n}\n"
  },
  {
    "path": "processor/memorylimiterprocessor/factory_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage memorylimiterprocessor\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/internal/telemetry\"\n\t\"go.opentelemetry.io/collector/internal/telemetry/telemetrytest\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n)\n\nfunc TestCreateDefaultConfig(t *testing.T) {\n\tfactory := NewFactory()\n\trequire.NotNil(t, factory)\n\n\tcfg := factory.CreateDefaultConfig()\n\tassert.NotNil(t, cfg, \"failed to create default config\")\n\tassert.NoError(t, componenttest.CheckConfigStruct(cfg))\n}\n\nfunc TestCreateProcessor(t *testing.T) {\n\tfactory := NewFactory()\n\trequire.NotNil(t, factory)\n\n\tcfg := factory.CreateDefaultConfig()\n\n\t// Create processor with a valid config.\n\tpCfg := cfg.(*Config)\n\tpCfg.MemoryLimitMiB = 5722\n\tpCfg.MemorySpikeLimitMiB = 1907\n\tpCfg.CheckInterval = 100 * time.Millisecond\n\n\tset := processortest.NewNopSettings(factory.Type())\n\tvar droppedAttrs []string\n\tset.Logger = telemetrytest.MockInjectorLogger(set.Logger, &droppedAttrs)\n\n\ttp, err := factory.CreateTraces(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NotNil(t, tp)\n\t// test if we can shutdown a monitoring routine that has not started\n\trequire.NoError(t, tp.Shutdown(context.Background()))\n\trequire.NoError(t, tp.Start(context.Background(), componenttest.NewNopHost()))\n\n\tmp, err := factory.CreateMetrics(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NotNil(t, mp)\n\trequire.NoError(t, mp.Start(context.Background(), componenttest.NewNopHost()))\n\n\tlp, err := factory.CreateLogs(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NotNil(t, lp)\n\trequire.NoError(t, lp.Start(context.Background(), componenttest.NewNopHost()))\n\n\tpp, err := factory.CreateProfiles(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NotNil(t, pp)\n\trequire.NoError(t, pp.Start(context.Background(), componenttest.NewNopHost()))\n\n\t// Test that we've dropped the relevant injected attributes exactly once\n\tassert.ElementsMatch(t, droppedAttrs, []string{\n\t\ttelemetry.SignalKey, telemetry.ComponentIDKey, telemetry.PipelineIDKey,\n\t})\n\n\tassert.NoError(t, lp.Shutdown(context.Background()))\n\tassert.NoError(t, tp.Shutdown(context.Background()))\n\tassert.NoError(t, mp.Shutdown(context.Background()))\n\tassert.NoError(t, pp.Shutdown(context.Background()))\n\t// verify that no monitoring routine is running\n\trequire.NoError(t, tp.Shutdown(context.Background()))\n\n\t// start and shutdown a new monitoring routine\n\tassert.NoError(t, lp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, lp.Shutdown(context.Background()))\n\t// calling it again should throw no error\n\trequire.NoError(t, lp.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "processor/memorylimiterprocessor/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage memorylimiterprocessor\n\nimport (\n\t\"context\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n\t\"go.opentelemetry.io/collector/processor/xprocessor\"\n)\n\nvar typ = component.MustNewType(\"memory_limiter\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct {\n\t\tcreateFn func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error)\n\t\tname     string\n\t}{\n\n\t\t{\n\t\t\tname: \"logs\",\n\t\t\tcreateFn: func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateLogs(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"traces\",\n\t\t\tcreateFn: func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateTraces(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"profiles\",\n\t\t\tcreateFn: func(ctx context.Context, set processor.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.(xprocessor.Factory).CreateProfiles(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name+\"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), processortest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\tt.Run(tt.name+\"-lifecycle\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), processortest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := newMdatagenNopHost()\n\t\t\terr = c.Start(context.Background(), host)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NotPanics(t, func() {\n\t\t\t\tswitch tt.name {\n\t\t\t\tcase \"logs\":\n\t\t\t\t\te, ok := c.(processor.Logs)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tlogs := generateLifecycleTestLogs()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tlogs.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeLogs(context.Background(), logs)\n\t\t\t\tcase \"metrics\":\n\t\t\t\t\te, ok := c.(processor.Metrics)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tmetrics := generateLifecycleTestMetrics()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\tmetrics.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeMetrics(context.Background(), metrics)\n\t\t\t\tcase \"traces\":\n\t\t\t\t\te, ok := c.(processor.Traces)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\ttraces := generateLifecycleTestTraces()\n\t\t\t\t\tif !e.Capabilities().MutatesData {\n\t\t\t\t\t\ttraces.MarkReadOnly()\n\t\t\t\t\t}\n\t\t\t\t\terr = e.ConsumeTraces(context.Background(), traces)\n\t\t\t\t}\n\t\t\t})\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t}\n}\n\nfunc generateLifecycleTestLogs() plog.Logs {\n\tlogs := plog.NewLogs()\n\trl := logs.ResourceLogs().AppendEmpty()\n\trl.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tl := rl.ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\tl.Body().SetStr(\"test log message\")\n\tl.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn logs\n}\n\nfunc generateLifecycleTestMetrics() pmetric.Metrics {\n\tmetrics := pmetric.NewMetrics()\n\trm := metrics.ResourceMetrics().AppendEmpty()\n\trm.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tm := rm.ScopeMetrics().AppendEmpty().Metrics().AppendEmpty()\n\tm.SetName(\"test_metric\")\n\tdp := m.SetEmptyGauge().DataPoints().AppendEmpty()\n\tdp.Attributes().PutStr(\"test_attr\", \"value_1\")\n\tdp.SetIntValue(123)\n\tdp.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn metrics\n}\n\nfunc generateLifecycleTestTraces() ptrace.Traces {\n\ttraces := ptrace.NewTraces()\n\trs := traces.ResourceSpans().AppendEmpty()\n\trs.Resource().Attributes().PutStr(\"resource\", \"R1\")\n\tspan := rs.ScopeSpans().AppendEmpty().Spans().AppendEmpty()\n\tspan.Attributes().PutStr(\"test_attr\", \"value_1\")\n\tspan.SetName(\"test_span\")\n\tspan.SetStartTimestamp(pcommon.NewTimestampFromTime(time.Now().Add(-1 * time.Second)))\n\tspan.SetEndTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\treturn traces\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "processor/memorylimiterprocessor/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage memorylimiterprocessor\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "processor/memorylimiterprocessor/go.mod",
    "content": "module go.opentelemetry.io/collector/processor/memorylimiterprocessor\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/internal/memorylimiter v0.148.0\n\tgo.opentelemetry.io/collector/internal/telemetry v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0\n\tgo.opentelemetry.io/collector/processor v1.54.0\n\tgo.opentelemetry.io/collector/processor/processorhelper v0.148.0\n\tgo.opentelemetry.io/collector/processor/processorhelper/xprocessorhelper v0.148.0\n\tgo.opentelemetry.io/collector/processor/processortest v0.148.0\n\tgo.opentelemetry.io/collector/processor/xprocessor v0.148.0\n\tgo.opentelemetry.io/otel v1.42.0\n\tgo.opentelemetry.io/otel/metric v1.42.0\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0\n\tgo.opentelemetry.io/otel/trace v1.42.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/ebitengine/purego v0.10.0 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-ole/go-ole v1.2.6 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect\n\tgithub.com/shirou/gopsutil/v4 v4.26.2 // indirect\n\tgithub.com/tklauser/go-sysconf v0.3.16 // indirect\n\tgithub.com/tklauser/numcpus v0.11.0 // indirect\n\tgithub.com/yusufpapurcu/wmi v1.2.4 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/component/componentstatus v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/processor => ../\n\nreplace go.opentelemetry.io/collector/processor/processortest => ../processortest\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nretract (\n\tv0.76.0 // Depends on retracted pdata v1.0.0-rc10 module, use v0.76.1\n\tv0.69.0 // Release failed, use v0.69.1\n)\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/component/componentstatus => ../../component/componentstatus\n\nreplace go.opentelemetry.io/collector/processor/xprocessor => ../xprocessor\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/internal/memorylimiter => ../../internal/memorylimiter\n\nreplace go.opentelemetry.io/collector/internal/telemetry => ../../internal/telemetry\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/processor/processorhelper/xprocessorhelper => ../processorhelper/xprocessorhelper\n\nreplace go.opentelemetry.io/collector/processor/processorhelper => ../processorhelper\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "processor/memorylimiterprocessor/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=\ngithub.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=\ngithub.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3 h1:PwQumkgq4/acIiZhtifTV5OUqqiP82UAl0h87xj/l9k=\ngithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/shirou/gopsutil/v4 v4.26.2 h1:X8i6sicvUFih4BmYIGT1m2wwgw2VG9YgrDTi7cIRGUI=\ngithub.com/shirou/gopsutil/v4 v4.26.2/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngithub.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYICU0nA=\ngithub.com/tklauser/go-sysconf v0.3.16/go.mod h1:/qNL9xxDhc7tx3HSRsLWNnuzbVfh3e7gh/BmM179nYI=\ngithub.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9RXw=\ngithub.com/tklauser/numcpus v0.11.0/go.mod h1:z+LwcLq54uWZTX0u/bGobaV34u6V7KNlTZejzM6/3MQ=\ngithub.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=\ngithub.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "processor/memorylimiterprocessor/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"memory_limiter\")\n\tScopeName = \"go.opentelemetry.io/collector/processor/memorylimiterprocessor\"\n)\n\nconst (\n\tProfilesStability = component.StabilityLevelAlpha\n\tTracesStability   = component.StabilityLevelBeta\n\tMetricsStability  = component.StabilityLevelBeta\n\tLogsStability     = component.StabilityLevelBeta\n)\n"
  },
  {
    "path": "processor/memorylimiterprocessor/internal/metadata/generated_telemetry.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc Meter(settings component.TelemetrySettings) metric.Meter {\n\treturn settings.MeterProvider.Meter(\"go.opentelemetry.io/collector/processor/memorylimiterprocessor\")\n}\n\nfunc Tracer(settings component.TelemetrySettings) trace.Tracer {\n\treturn settings.TracerProvider.Tracer(\"go.opentelemetry.io/collector/processor/memorylimiterprocessor\")\n}\n\n// TelemetryBuilder provides an interface for components to report telemetry\n// as defined in metadata and user config.\ntype TelemetryBuilder struct {\n\tmeter                         metric.Meter\n\tmu                            sync.Mutex\n\tregistrations                 []metric.Registration\n\tProcessorAcceptedLogRecords   metric.Int64Counter\n\tProcessorAcceptedMetricPoints metric.Int64Counter\n\tProcessorAcceptedSpans        metric.Int64Counter\n\tProcessorRefusedLogRecords    metric.Int64Counter\n\tProcessorRefusedMetricPoints  metric.Int64Counter\n\tProcessorRefusedSpans         metric.Int64Counter\n}\n\n// TelemetryBuilderOption applies changes to default builder.\ntype TelemetryBuilderOption interface {\n\tapply(*TelemetryBuilder)\n}\n\ntype telemetryBuilderOptionFunc func(mb *TelemetryBuilder)\n\nfunc (tbof telemetryBuilderOptionFunc) apply(mb *TelemetryBuilder) {\n\ttbof(mb)\n}\n\n// Shutdown unregister all registered callbacks for async instruments.\nfunc (builder *TelemetryBuilder) Shutdown() {\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tfor _, reg := range builder.registrations {\n\t\treg.Unregister()\n\t}\n}\n\n// NewTelemetryBuilder provides a struct with methods to update all internal telemetry\n// for a component\nfunc NewTelemetryBuilder(settings component.TelemetrySettings, options ...TelemetryBuilderOption) (*TelemetryBuilder, error) {\n\tbuilder := TelemetryBuilder{}\n\tfor _, op := range options {\n\t\top.apply(&builder)\n\t}\n\tbuilder.meter = Meter(settings)\n\tvar err, errs error\n\tbuilder.ProcessorAcceptedLogRecords, err = builder.meter.Int64Counter(\n\t\t\"otelcol_processor_accepted_log_records\",\n\t\tmetric.WithDescription(\"Number of log records successfully pushed into the next component in the pipeline. [Deprecated]\"),\n\t\tmetric.WithUnit(\"{record}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessorAcceptedMetricPoints, err = builder.meter.Int64Counter(\n\t\t\"otelcol_processor_accepted_metric_points\",\n\t\tmetric.WithDescription(\"Number of metric points successfully pushed into the next component in the pipeline. [Deprecated]\"),\n\t\tmetric.WithUnit(\"{datapoint}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessorAcceptedSpans, err = builder.meter.Int64Counter(\n\t\t\"otelcol_processor_accepted_spans\",\n\t\tmetric.WithDescription(\"Number of spans successfully pushed into the next component in the pipeline. [Deprecated]\"),\n\t\tmetric.WithUnit(\"{span}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessorRefusedLogRecords, err = builder.meter.Int64Counter(\n\t\t\"otelcol_processor_refused_log_records\",\n\t\tmetric.WithDescription(\"Number of log records that were rejected by the next component in the pipeline. [Deprecated]\"),\n\t\tmetric.WithUnit(\"{record}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessorRefusedMetricPoints, err = builder.meter.Int64Counter(\n\t\t\"otelcol_processor_refused_metric_points\",\n\t\tmetric.WithDescription(\"Number of metric points that were rejected by the next component in the pipeline. [Deprecated]\"),\n\t\tmetric.WithUnit(\"{datapoint}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessorRefusedSpans, err = builder.meter.Int64Counter(\n\t\t\"otelcol_processor_refused_spans\",\n\t\tmetric.WithDescription(\"Number of spans that were rejected by the next component in the pipeline. [Deprecated]\"),\n\t\tmetric.WithUnit(\"{span}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\treturn &builder, errs\n}\n"
  },
  {
    "path": "processor/memorylimiterprocessor/internal/metadata/generated_telemetry_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/metric\"\n\tembeddedmetric \"go.opentelemetry.io/otel/metric/embedded\"\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\t\"go.opentelemetry.io/otel/trace\"\n\tembeddedtrace \"go.opentelemetry.io/otel/trace/embedded\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\ntype mockMeter struct {\n\tnoopmetric.Meter\n\tname string\n}\ntype mockMeterProvider struct {\n\tembeddedmetric.MeterProvider\n}\n\nfunc (m mockMeterProvider) Meter(name string, opts ...metric.MeterOption) metric.Meter {\n\treturn mockMeter{name: name}\n}\n\ntype mockTracer struct {\n\tnooptrace.Tracer\n\tname string\n}\n\ntype mockTracerProvider struct {\n\tembeddedtrace.TracerProvider\n}\n\nfunc (m mockTracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer {\n\treturn mockTracer{name: name}\n}\n\nfunc TestProviders(t *testing.T) {\n\tset := component.TelemetrySettings{\n\t\tMeterProvider:  mockMeterProvider{},\n\t\tTracerProvider: mockTracerProvider{},\n\t}\n\n\tmeter := Meter(set)\n\tif m, ok := meter.(mockMeter); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/processor/memorylimiterprocessor\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockMeter\")\n\t}\n\n\ttracer := Tracer(set)\n\tif m, ok := tracer.(mockTracer); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/processor/memorylimiterprocessor\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockTracer\")\n\t}\n}\n\nfunc TestNewTelemetryBuilder(t *testing.T) {\n\tset := componenttest.NewNopTelemetrySettings()\n\tapplied := false\n\t_, err := NewTelemetryBuilder(set, telemetryBuilderOptionFunc(func(b *TelemetryBuilder) {\n\t\tapplied = true\n\t}))\n\trequire.NoError(t, err)\n\trequire.True(t, applied)\n}\n"
  },
  {
    "path": "processor/memorylimiterprocessor/internal/metadatatest/generated_telemetrytest.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n)\n\nfunc NewSettings(tt *componenttest.Telemetry) processor.Settings {\n\tset := processortest.NewNopSettings(processortest.NopType)\n\tset.ID = component.NewID(component.MustNewType(\"memory_limiter\"))\n\tset.TelemetrySettings = tt.NewTelemetrySettings()\n\treturn set\n}\n\nfunc AssertEqualProcessorAcceptedLogRecords(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_processor_accepted_log_records\",\n\t\tDescription: \"Number of log records successfully pushed into the next component in the pipeline. [Deprecated]\",\n\t\tUnit:        \"{record}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_processor_accepted_log_records\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessorAcceptedMetricPoints(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_processor_accepted_metric_points\",\n\t\tDescription: \"Number of metric points successfully pushed into the next component in the pipeline. [Deprecated]\",\n\t\tUnit:        \"{datapoint}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_processor_accepted_metric_points\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessorAcceptedSpans(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_processor_accepted_spans\",\n\t\tDescription: \"Number of spans successfully pushed into the next component in the pipeline. [Deprecated]\",\n\t\tUnit:        \"{span}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_processor_accepted_spans\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessorRefusedLogRecords(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_processor_refused_log_records\",\n\t\tDescription: \"Number of log records that were rejected by the next component in the pipeline. [Deprecated]\",\n\t\tUnit:        \"{record}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_processor_refused_log_records\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessorRefusedMetricPoints(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_processor_refused_metric_points\",\n\t\tDescription: \"Number of metric points that were rejected by the next component in the pipeline. [Deprecated]\",\n\t\tUnit:        \"{datapoint}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_processor_refused_metric_points\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessorRefusedSpans(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_processor_refused_spans\",\n\t\tDescription: \"Number of spans that were rejected by the next component in the pipeline. [Deprecated]\",\n\t\tUnit:        \"{span}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_processor_refused_spans\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n"
  },
  {
    "path": "processor/memorylimiterprocessor/internal/metadatatest/generated_telemetrytest_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/processor/memorylimiterprocessor/internal/metadata\"\n)\n\nfunc TestSetupTelemetry(t *testing.T) {\n\ttestTel := componenttest.NewTelemetry()\n\ttb, err := metadata.NewTelemetryBuilder(testTel.NewTelemetrySettings())\n\trequire.NoError(t, err)\n\tdefer tb.Shutdown()\n\ttb.ProcessorAcceptedLogRecords.Add(context.Background(), 1)\n\ttb.ProcessorAcceptedMetricPoints.Add(context.Background(), 1)\n\ttb.ProcessorAcceptedSpans.Add(context.Background(), 1)\n\ttb.ProcessorRefusedLogRecords.Add(context.Background(), 1)\n\ttb.ProcessorRefusedMetricPoints.Add(context.Background(), 1)\n\ttb.ProcessorRefusedSpans.Add(context.Background(), 1)\n\tAssertEqualProcessorAcceptedLogRecords(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessorAcceptedMetricPoints(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessorAcceptedSpans(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessorRefusedLogRecords(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessorRefusedMetricPoints(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessorRefusedSpans(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\n\trequire.NoError(t, testTel.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "processor/memorylimiterprocessor/internal/mock_exporter.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/processor/memorylimiterprocessor/internal\"\n\nimport (\n\t\"context\"\n\t\"sync/atomic\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\ntype MockExporter struct {\n\tdestAvailable     atomic.Bool\n\tacceptedLogCount  atomic.Int64\n\tdeliveredLogCount atomic.Int64\n\tLogs              consumertest.LogsSink\n}\n\nvar _ consumer.Logs = (*MockExporter)(nil)\n\nfunc (e *MockExporter) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{}\n}\n\nfunc (e *MockExporter) ConsumeLogs(ctx context.Context, ld plog.Logs) error {\n\te.acceptedLogCount.Add(int64(ld.LogRecordCount()))\n\n\tif !e.destAvailable.Load() {\n\t\t// Destination is not available. Queue the logs in the exporter.\n\t\treturn e.Logs.ConsumeLogs(ctx, ld)\n\t}\n\t// Destination is available, immediately deliver.\n\te.deliveredLogCount.Add(int64(ld.LogRecordCount()))\n\treturn nil\n}\n\nfunc (e *MockExporter) SetDestAvailable(available bool) {\n\tif available {\n\t\t// Pretend we delivered all queued accepted logs.\n\t\te.deliveredLogCount.Add(int64(e.Logs.LogRecordCount()))\n\n\t\t// Get rid of the delivered logs so that memory can be collected.\n\t\te.Logs.Reset()\n\n\t\t// Now mark destination available so that subsequent ConsumeLogs\n\t\t// don't queue the logs anymore.\n\t\te.destAvailable.Store(true)\n\t} else {\n\t\te.destAvailable.Store(false)\n\t}\n}\n\nfunc (e *MockExporter) AcceptedLogCount() int {\n\treturn int(e.acceptedLogCount.Load())\n}\n\nfunc (e *MockExporter) DeliveredLogCount() int {\n\treturn int(e.deliveredLogCount.Load())\n}\n\nfunc NewMockExporter() *MockExporter {\n\treturn &MockExporter{\n\t\tdestAvailable:     atomic.Bool{},\n\t\tacceptedLogCount:  atomic.Int64{},\n\t\tdeliveredLogCount: atomic.Int64{},\n\t\tLogs:              consumertest.LogsSink{},\n\t}\n}\n"
  },
  {
    "path": "processor/memorylimiterprocessor/internal/mock_receiver.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/processor/memorylimiterprocessor/internal\"\n\nimport (\n\t\"context\"\n\t\"strings\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\ntype MockReceiver struct {\n\tProduceCount      int\n\tNextConsumer      consumer.Logs\n\tlastConsumeResult error\n\tmux               sync.Mutex\n}\n\nfunc (m *MockReceiver) Start() {\n\tgo m.produce()\n}\n\n// This function demonstrates how the receivers should behave when the ConsumeLogs/Traces/Metrics\n// call returns an error.\nfunc (m *MockReceiver) produce() {\n\tfor i := 0; i < m.ProduceCount; i++ {\n\t\t// Create a large log to consume some memory.\n\t\tld := plog.NewLogs()\n\t\tlr := ld.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\t\tkiloStr := strings.Repeat(\"x\", 10*1024)\n\t\tlr.SetSeverityText(kiloStr)\n\n\tretry:\n\t\t// Send to the pipeline.\n\t\terr := m.NextConsumer.ConsumeLogs(context.Background(), ld)\n\n\t\t// Remember the result to be used in the tests.\n\t\tm.mux.Lock()\n\t\tm.lastConsumeResult = err\n\t\tm.mux.Unlock()\n\n\t\tif err != nil {\n\t\t\t// Sending to the pipeline failed.\n\t\t\tif !consumererror.IsPermanent(err) {\n\t\t\t\t// Retryable error. Try the same data again.\n\t\t\t\tgoto retry\n\t\t\t}\n\t\t\t// Permanent error. Drop it.\n\t\t}\n\t}\n}\n\nfunc (m *MockReceiver) LastConsumeResult() error {\n\tm.mux.Lock()\n\tdefer m.mux.Unlock()\n\treturn m.lastConsumeResult\n}\n"
  },
  {
    "path": "processor/memorylimiterprocessor/memorylimiter.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage memorylimiterprocessor // import \"go.opentelemetry.io/collector/processor/memorylimiterprocessor\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/internal/memorylimiter\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\t\"go.opentelemetry.io/collector/processor\"\n)\n\ntype memoryLimiterProcessor struct {\n\tmemlimiter *memorylimiter.MemoryLimiter\n\tobsrep     *obsReport\n}\n\n// newMemoryLimiter returns a new memorylimiter processor.\nfunc newMemoryLimiterProcessor(set processor.Settings, cfg *Config) (*memoryLimiterProcessor, error) {\n\tml, err := memorylimiter.NewMemoryLimiter(cfg, set.Logger)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tobsrep, err := newObsReport(set)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tp := &memoryLimiterProcessor{\n\t\tmemlimiter: ml,\n\t\tobsrep:     obsrep,\n\t}\n\n\treturn p, nil\n}\n\nfunc (p *memoryLimiterProcessor) start(ctx context.Context, host component.Host) error {\n\treturn p.memlimiter.Start(ctx, host)\n}\n\nfunc (p *memoryLimiterProcessor) shutdown(ctx context.Context) error {\n\treturn p.memlimiter.Shutdown(ctx)\n}\n\nfunc (p *memoryLimiterProcessor) processTraces(ctx context.Context, td ptrace.Traces) (ptrace.Traces, error) {\n\tnumSpans := td.SpanCount()\n\tif p.memlimiter.MustRefuse() {\n\t\t// TODO:\n\t\t// https://github.com/open-telemetry/opentelemetry-collector/issues/12463\n\t\tp.obsrep.refused(ctx, numSpans, pipeline.SignalTraces)\n\t\treturn td, memorylimiter.ErrDataRefused\n\t}\n\n\t// Even if the next consumer returns error record the data as accepted by\n\t// this processor.\n\tp.obsrep.accepted(ctx, numSpans, pipeline.SignalTraces)\n\treturn td, nil\n}\n\nfunc (p *memoryLimiterProcessor) processMetrics(ctx context.Context, md pmetric.Metrics) (pmetric.Metrics, error) {\n\tnumDataPoints := md.DataPointCount()\n\tif p.memlimiter.MustRefuse() {\n\t\t// TODO:\n\t\t// https://github.com/open-telemetry/opentelemetry-collector/issues/12463\n\t\tp.obsrep.refused(ctx, numDataPoints, pipeline.SignalMetrics)\n\t\treturn md, memorylimiter.ErrDataRefused\n\t}\n\n\t// Even if the next consumer returns error record the data as accepted by\n\t// this processor.\n\tp.obsrep.accepted(ctx, numDataPoints, pipeline.SignalMetrics)\n\treturn md, nil\n}\n\nfunc (p *memoryLimiterProcessor) processLogs(ctx context.Context, ld plog.Logs) (plog.Logs, error) {\n\tnumRecords := ld.LogRecordCount()\n\tif p.memlimiter.MustRefuse() {\n\t\t// TODO:\n\t\t// https://github.com/open-telemetry/opentelemetry-collector/issues/12463\n\t\tp.obsrep.refused(ctx, numRecords, pipeline.SignalLogs)\n\t\treturn ld, memorylimiter.ErrDataRefused\n\t}\n\n\t// Even if the next consumer returns error record the data as accepted by\n\t// this processor.\n\tp.obsrep.accepted(ctx, numRecords, pipeline.SignalLogs)\n\treturn ld, nil\n}\n\nfunc (p *memoryLimiterProcessor) processProfiles(ctx context.Context, td pprofile.Profiles) (pprofile.Profiles, error) {\n\tnumProfiles := td.SampleCount()\n\tif p.memlimiter.MustRefuse() {\n\t\t// TODO:\n\t\t// https://github.com/open-telemetry/opentelemetry-collector/issues/12463\n\t\tp.obsrep.refused(ctx, numProfiles, xpipeline.SignalProfiles)\n\t\treturn td, memorylimiter.ErrDataRefused\n\t}\n\n\t// Even if the next consumer returns error record the data as accepted by\n\t// this processor.\n\tp.obsrep.accepted(ctx, numProfiles, xpipeline.SignalProfiles)\n\treturn td, nil\n}\n"
  },
  {
    "path": "processor/memorylimiterprocessor/memorylimiter_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage memorylimiterprocessor\n\nimport (\n\t\"context\"\n\t\"runtime\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/internal/memorylimiter\"\n\t\"go.opentelemetry.io/collector/internal/memorylimiter/iruntime\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/memorylimiterprocessor/internal\"\n\t\"go.opentelemetry.io/collector/processor/memorylimiterprocessor/internal/metadata\"\n\t\"go.opentelemetry.io/collector/processor/memorylimiterprocessor/internal/metadatatest\"\n\t\"go.opentelemetry.io/collector/processor/processorhelper\"\n\t\"go.opentelemetry.io/collector/processor/processorhelper/xprocessorhelper\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n)\n\nfunc TestNoDataLoss(t *testing.T) {\n\t// Create an exporter.\n\texporter := internal.NewMockExporter()\n\n\t// Mark exporter's destination unavailable. The exporter will accept data and will queue it,\n\t// thus increasing the memory usage of the Collector.\n\texporter.SetDestAvailable(false)\n\n\t// Create a memory limiter processor.\n\n\tcfg := createDefaultConfig().(*Config)\n\n\t// Check frequently to make the test quick.\n\tcfg.CheckInterval = time.Millisecond * 10\n\n\t// By how much we expect memory usage to increase because of queuing up of produced data.\n\tconst expectedMemoryIncreaseMiB = 10\n\n\tvar ms runtime.MemStats\n\truntime.ReadMemStats(&ms)\n\n\t// Set the limit to current usage plus expected increase. This means initially we will not be limited.\n\tcfg.MemoryLimitMiB = uint32(ms.Alloc/(1024*1024) + expectedMemoryIncreaseMiB)\n\tcfg.MemorySpikeLimitMiB = 1\n\n\tset := processortest.NewNopSettings(metadata.Type)\n\n\tlimiter, err := newMemoryLimiterProcessor(set, cfg)\n\trequire.NoError(t, err)\n\n\tprocessor, err := processorhelper.NewLogs(context.Background(), processor.Settings{\n\t\tID:                component.MustNewID(\"nop\"),\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t}, cfg, exporter,\n\t\tlimiter.processLogs,\n\t\tprocessorhelper.WithStart(limiter.start),\n\t\tprocessorhelper.WithShutdown(limiter.shutdown))\n\trequire.NoError(t, err)\n\n\t// Create a receiver.\n\n\treceiver := &internal.MockReceiver{\n\t\tProduceCount: 1e5, // Must produce enough logs to make sure memory increases by at least expectedMemoryIncreaseMiB\n\t\tNextConsumer: processor,\n\t}\n\n\terr = processor.Start(context.Background(), componenttest.NewNopHost())\n\trequire.NoError(t, err)\n\n\t// Start producing data.\n\treceiver.Start()\n\n\t// The exporter was created such that its destination is not available.\n\t// This will result in queuing of produced data inside the exporter and memory usage\n\t// will increase.\n\n\t// We must eventually hit the memory limit and the receiver must see an error from memory limiter.\n\trequire.Eventually(t, func() bool {\n\t\t// Did last ConsumeLogs call return an error?\n\t\treturn receiver.LastConsumeResult() != nil\n\t}, 5*time.Second, 1*time.Millisecond)\n\n\t// We are now memory limited and receiver can't produce data anymore.\n\n\t// Now make the exporter's destination available.\n\texporter.SetDestAvailable(true)\n\n\t// We should now see that exporter's queue is purged and memory usage goes down.\n\n\t// Eventually we must see that receiver's ConsumeLog call returns success again.\n\trequire.Eventually(t, func() bool {\n\t\treturn receiver.LastConsumeResult() == nil\n\t}, 5*time.Second, 1*time.Millisecond)\n\n\t// And eventually the exporter must confirm that it delivered exact number of produced logs.\n\trequire.Eventually(t, func() bool {\n\t\td := exporter.DeliveredLogCount()\n\t\tt.Logf(\"received: %d, expected: %d\\n\", d, receiver.ProduceCount)\n\t\treturn receiver.ProduceCount == d\n\t}, 5*time.Second, 100*time.Millisecond)\n\n\t// Double check that the number of logs accepted by exporter matches the number of produced by receiver.\n\tassert.Equal(t, receiver.ProduceCount, exporter.AcceptedLogCount())\n\n\terr = processor.Shutdown(context.Background())\n\trequire.NoError(t, err)\n}\n\n// TestMetricsMemoryPressureResponse manipulates results from querying memory and\n// check expected side effects.\nfunc TestMetricsMemoryPressureResponse(t *testing.T) {\n\tmd := pmetric.NewMetrics()\n\n\ttests := []struct {\n\t\tname        string\n\t\tmlCfg       *Config\n\t\tmemAlloc    uint64\n\t\texpectError bool\n\t}{\n\t\t{\n\t\t\tname: \"Below memAllocLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 1,\n\t\t\t},\n\t\t\tmemAlloc:    800,\n\t\t\texpectError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Above memAllocLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 1,\n\t\t\t},\n\t\t\tmemAlloc:    1800,\n\t\t\texpectError: true,\n\t\t},\n\t\t{\n\t\t\tname: \"Below memSpikeLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 10,\n\t\t\t},\n\t\t\tmemAlloc:    800,\n\t\t\texpectError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Above memSpikeLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 11,\n\t\t\t},\n\t\t\tmemAlloc:    800,\n\t\t\texpectError: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tctx := context.Background()\n\t\t\tmemorylimiter.GetMemoryFn = totalMemory\n\t\t\tmemorylimiter.ReadMemStatsFn = func(ms *runtime.MemStats) {\n\t\t\t\tms.Alloc = tt.memAlloc\n\t\t\t}\n\n\t\t\tml, err := newMemoryLimiterProcessor(processortest.NewNopSettings(metadata.Type), tt.mlCfg)\n\t\t\trequire.NoError(t, err)\n\t\t\tmp, err := processorhelper.NewMetrics(\n\t\t\t\tctx,\n\t\t\t\tprocessortest.NewNopSettings(metadata.Type),\n\t\t\t\ttt.mlCfg,\n\t\t\t\tconsumertest.NewNop(),\n\t\t\t\tml.processMetrics,\n\t\t\t\tprocessorhelper.WithCapabilities(processorCapabilities),\n\t\t\t\tprocessorhelper.WithStart(ml.start),\n\t\t\t\tprocessorhelper.WithShutdown(ml.shutdown))\n\t\t\trequire.NoError(t, err)\n\n\t\t\tassert.NoError(t, mp.Start(ctx, &host{}))\n\t\t\tml.memlimiter.CheckMemLimits()\n\t\t\terr = mp.ConsumeMetrics(ctx, md)\n\t\t\tif tt.expectError {\n\t\t\t\tassert.Equal(t, memorylimiter.ErrDataRefused, err)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\t\t\tassert.NoError(t, mp.Shutdown(ctx))\n\t\t})\n\t}\n\tt.Cleanup(func() {\n\t\tmemorylimiter.GetMemoryFn = iruntime.TotalMemory\n\t\tmemorylimiter.ReadMemStatsFn = runtime.ReadMemStats\n\t})\n}\n\nfunc TestMetricsTelemetry(t *testing.T) {\n\ttel := componenttest.NewTelemetry()\n\tcfg := &Config{\n\t\tCheckInterval:         time.Second,\n\t\tMemoryLimitPercentage: 50,\n\t\tMemorySpikePercentage: 10,\n\t}\n\tmetrics, err := NewFactory().CreateMetrics(context.Background(), metadatatest.NewSettings(tel), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\trequire.NoError(t, metrics.Start(context.Background(), componenttest.NewNopHost()))\n\n\tmd := pmetric.NewMetrics()\n\tmd.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptySum().DataPoints().AppendEmpty()\n\tfor range 10 {\n\t\trequire.NoError(t, metrics.ConsumeMetrics(context.Background(), md))\n\t}\n\trequire.NoError(t, metrics.Shutdown(context.Background()))\n\n\tmetadatatest.AssertEqualProcessorAcceptedMetricPoints(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      10,\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"memory_limiter\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\n\trequire.NoError(t, tel.Shutdown(context.Background()))\n}\n\n// TestTraceMemoryPressureResponse manipulates results from querying memory and\n// check expected side effects.\nfunc TestTraceMemoryPressureResponse(t *testing.T) {\n\ttd := ptrace.NewTraces()\n\n\ttests := []struct {\n\t\tname        string\n\t\tmlCfg       *Config\n\t\tmemAlloc    uint64\n\t\texpectError bool\n\t}{\n\t\t{\n\t\t\tname: \"Below memAllocLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 1,\n\t\t\t},\n\t\t\tmemAlloc:    800,\n\t\t\texpectError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Above memAllocLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 1,\n\t\t\t},\n\t\t\tmemAlloc:    1800,\n\t\t\texpectError: true,\n\t\t},\n\t\t{\n\t\t\tname: \"Below memSpikeLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 10,\n\t\t\t},\n\t\t\tmemAlloc:    800,\n\t\t\texpectError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Above memSpikeLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 11,\n\t\t\t},\n\t\t\tmemAlloc:    800,\n\t\t\texpectError: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tctx := context.Background()\n\t\t\tmemorylimiter.GetMemoryFn = totalMemory\n\t\t\tmemorylimiter.ReadMemStatsFn = func(ms *runtime.MemStats) {\n\t\t\t\tms.Alloc = tt.memAlloc\n\t\t\t}\n\n\t\t\tml, err := newMemoryLimiterProcessor(processortest.NewNopSettings(metadata.Type), tt.mlCfg)\n\t\t\trequire.NoError(t, err)\n\t\t\ttp, err := processorhelper.NewTraces(\n\t\t\t\tctx,\n\t\t\t\tprocessortest.NewNopSettings(metadata.Type),\n\t\t\t\ttt.mlCfg,\n\t\t\t\tconsumertest.NewNop(),\n\t\t\t\tml.processTraces,\n\t\t\t\tprocessorhelper.WithCapabilities(processorCapabilities),\n\t\t\t\tprocessorhelper.WithStart(ml.start),\n\t\t\t\tprocessorhelper.WithShutdown(ml.shutdown))\n\t\t\trequire.NoError(t, err)\n\n\t\t\tassert.NoError(t, tp.Start(ctx, &host{}))\n\t\t\tml.memlimiter.CheckMemLimits()\n\t\t\terr = tp.ConsumeTraces(ctx, td)\n\t\t\tif tt.expectError {\n\t\t\t\tassert.Equal(t, memorylimiter.ErrDataRefused, err)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\t\t\tassert.NoError(t, tp.Shutdown(ctx))\n\t\t})\n\t}\n\tt.Cleanup(func() {\n\t\tmemorylimiter.GetMemoryFn = iruntime.TotalMemory\n\t\tmemorylimiter.ReadMemStatsFn = runtime.ReadMemStats\n\t})\n}\n\n// TestLogMemoryPressureResponse manipulates results from querying memory and\n// check expected side effects.\nfunc TestLogMemoryPressureResponse(t *testing.T) {\n\tld := plog.NewLogs()\n\n\ttests := []struct {\n\t\tname        string\n\t\tmlCfg       *Config\n\t\tmemAlloc    uint64\n\t\texpectError bool\n\t}{\n\t\t{\n\t\t\tname: \"Below memAllocLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 1,\n\t\t\t},\n\t\t\tmemAlloc:    800,\n\t\t\texpectError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Above memAllocLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 1,\n\t\t\t},\n\t\t\tmemAlloc:    1800,\n\t\t\texpectError: true,\n\t\t},\n\t\t{\n\t\t\tname: \"Below memSpikeLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 10,\n\t\t\t},\n\t\t\tmemAlloc:    800,\n\t\t\texpectError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Above memSpikeLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 11,\n\t\t\t},\n\t\t\tmemAlloc:    800,\n\t\t\texpectError: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tctx := context.Background()\n\t\t\tmemorylimiter.GetMemoryFn = totalMemory\n\t\t\tmemorylimiter.ReadMemStatsFn = func(ms *runtime.MemStats) {\n\t\t\t\tms.Alloc = tt.memAlloc\n\t\t\t}\n\n\t\t\tml, err := newMemoryLimiterProcessor(processortest.NewNopSettings(metadata.Type), tt.mlCfg)\n\t\t\trequire.NoError(t, err)\n\t\t\ttp, err := processorhelper.NewLogs(\n\t\t\t\tctx,\n\t\t\t\tprocessortest.NewNopSettings(metadata.Type),\n\t\t\t\ttt.mlCfg,\n\t\t\t\tconsumertest.NewNop(),\n\t\t\t\tml.processLogs,\n\t\t\t\tprocessorhelper.WithCapabilities(processorCapabilities),\n\t\t\t\tprocessorhelper.WithStart(ml.start),\n\t\t\t\tprocessorhelper.WithShutdown(ml.shutdown))\n\t\t\trequire.NoError(t, err)\n\n\t\t\tassert.NoError(t, tp.Start(ctx, &host{}))\n\t\t\tml.memlimiter.CheckMemLimits()\n\t\t\terr = tp.ConsumeLogs(ctx, ld)\n\t\t\tif tt.expectError {\n\t\t\t\tassert.Equal(t, memorylimiter.ErrDataRefused, err)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\t\t\tassert.NoError(t, tp.Shutdown(ctx))\n\t\t})\n\t}\n\tt.Cleanup(func() {\n\t\tmemorylimiter.GetMemoryFn = iruntime.TotalMemory\n\t\tmemorylimiter.ReadMemStatsFn = runtime.ReadMemStats\n\t})\n}\n\n// TestProfileMemoryPressureResponse manipulates results from querying memory and\n// check expected side effects.\nfunc TestProfileMemoryPressureResponse(t *testing.T) {\n\tpd := pprofile.NewProfiles()\n\n\ttests := []struct {\n\t\tname        string\n\t\tmlCfg       *Config\n\t\tmemAlloc    uint64\n\t\texpectError bool\n\t}{\n\t\t{\n\t\t\tname: \"Below memAllocLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 1,\n\t\t\t},\n\t\t\tmemAlloc:    800,\n\t\t\texpectError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Above memAllocLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 1,\n\t\t\t},\n\t\t\tmemAlloc:    1800,\n\t\t\texpectError: true,\n\t\t},\n\t\t{\n\t\t\tname: \"Below memSpikeLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 10,\n\t\t\t},\n\t\t\tmemAlloc:    800,\n\t\t\texpectError: false,\n\t\t},\n\t\t{\n\t\t\tname: \"Above memSpikeLimit\",\n\t\t\tmlCfg: &Config{\n\t\t\t\tCheckInterval:         time.Second,\n\t\t\t\tMemoryLimitPercentage: 50,\n\t\t\t\tMemorySpikePercentage: 11,\n\t\t\t},\n\t\t\tmemAlloc:    800,\n\t\t\texpectError: true,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tctx := context.Background()\n\t\t\tmemorylimiter.GetMemoryFn = totalMemory\n\t\t\tmemorylimiter.ReadMemStatsFn = func(ms *runtime.MemStats) {\n\t\t\t\tms.Alloc = tt.memAlloc\n\t\t\t}\n\n\t\t\tml, err := newMemoryLimiterProcessor(processortest.NewNopSettings(metadata.Type), tt.mlCfg)\n\t\t\trequire.NoError(t, err)\n\t\t\ttp, err := xprocessorhelper.NewProfiles(\n\t\t\t\tctx,\n\t\t\t\tprocessortest.NewNopSettings(metadata.Type),\n\t\t\t\ttt.mlCfg,\n\t\t\t\tconsumertest.NewNop(),\n\t\t\t\tml.processProfiles,\n\t\t\t\txprocessorhelper.WithCapabilities(processorCapabilities),\n\t\t\t\txprocessorhelper.WithStart(ml.start),\n\t\t\t\txprocessorhelper.WithShutdown(ml.shutdown))\n\t\t\trequire.NoError(t, err)\n\n\t\t\tassert.NoError(t, tp.Start(ctx, &host{}))\n\t\t\tml.memlimiter.CheckMemLimits()\n\t\t\terr = tp.ConsumeProfiles(ctx, pd)\n\t\t\tif tt.expectError {\n\t\t\t\tassert.Equal(t, memorylimiter.ErrDataRefused, err)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t}\n\t\t\tassert.NoError(t, tp.Shutdown(ctx))\n\t\t})\n\t}\n\tt.Cleanup(func() {\n\t\tmemorylimiter.GetMemoryFn = iruntime.TotalMemory\n\t\tmemorylimiter.ReadMemStatsFn = runtime.ReadMemStats\n\t})\n}\n\ntype host struct {\n\tcomponent.Host\n}\n\nfunc (h *host) GetExtensions() map[component.ID]component.Component {\n\tret := make(map[component.ID]component.Component)\n\treturn ret\n}\n\nfunc totalMemory() (uint64, error) {\n\treturn uint64(2048), nil\n}\n"
  },
  {
    "path": "processor/memorylimiterprocessor/metadata.yaml",
    "content": "display_name: Memory Limiter Processor\ntype: memory_limiter\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: processor\n  stability:\n    alpha: [profiles]\n    beta: [traces, metrics, logs]\n  distributions: [core, contrib, k8s]\n\ntests:\n  config:\n    check_interval: 5s\n    limit_mib: 400\n    spike_limit_mib: 50\n\ntelemetry:\n  metrics:\n    processor_accepted_log_records:\n      enabled: true\n      description: Number of log records successfully pushed into the next component in the pipeline.\n      stability: deprecated\n      deprecated:\n        since: \"0.110.0\"\n        note: \"This metric is deprecated\"\n      unit: \"{record}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    processor_accepted_metric_points:\n      enabled: true\n      description: Number of metric points successfully pushed into the next component in the pipeline.\n      stability: deprecated\n      deprecated:\n        since: \"0.110.0\"\n        note: \"This metric is deprecated\"\n      unit: \"{datapoint}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    processor_accepted_spans:\n      enabled: true\n      description: Number of spans successfully pushed into the next component in the pipeline.\n      stability: deprecated\n      deprecated:\n        since: \"0.110.0\"\n        note: \"This metric is deprecated\"\n      unit: \"{span}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    processor_refused_log_records:\n      enabled: true\n      description: Number of log records that were rejected by the next component in the pipeline.\n      stability: deprecated\n      deprecated:\n        since: \"0.110.0\"\n        note: \"This metric is deprecated\"\n      unit: \"{record}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    processor_refused_metric_points:\n      enabled: true\n      description: Number of metric points that were rejected by the next component in the pipeline.\n      stability: deprecated\n      deprecated:\n        since: \"0.110.0\"\n        note: \"This metric is deprecated\"\n      unit: \"{datapoint}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    processor_refused_spans:\n      enabled: true\n      description: Number of spans that were rejected by the next component in the pipeline.\n      stability: deprecated\n      deprecated:\n        since: \"0.110.0\"\n        note: \"This metric is deprecated\"\n      unit: \"{span}\"\n      sum:\n        value_type: int\n        monotonic: true\n"
  },
  {
    "path": "processor/memorylimiterprocessor/obsreport.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage memorylimiterprocessor // import \"go.opentelemetry.io/collector/processor/memorylimiterprocessor\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/metric\"\n\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/internal\"\n\t\"go.opentelemetry.io/collector/processor/memorylimiterprocessor/internal/metadata\"\n)\n\ntype obsReport struct {\n\totelAttrs        metric.MeasurementOption\n\ttelemetryBuilder *metadata.TelemetryBuilder\n}\n\nfunc newObsReport(set processor.Settings) (*obsReport, error) {\n\ttelemetryBuilder, err := metadata.NewTelemetryBuilder(set.TelemetrySettings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &obsReport{\n\t\totelAttrs:        metric.WithAttributeSet(attribute.NewSet(attribute.String(internal.ProcessorKey, set.ID.String()))),\n\t\ttelemetryBuilder: telemetryBuilder,\n\t}, nil\n}\n\n// accepted reports that the num data was accepted.\nfunc (or *obsReport) accepted(ctx context.Context, num int, signal pipeline.Signal) {\n\tswitch signal {\n\tcase pipeline.SignalTraces:\n\t\tor.telemetryBuilder.ProcessorAcceptedSpans.Add(ctx, int64(num), or.otelAttrs)\n\tcase pipeline.SignalMetrics:\n\t\tor.telemetryBuilder.ProcessorAcceptedMetricPoints.Add(ctx, int64(num), or.otelAttrs)\n\tcase pipeline.SignalLogs:\n\t\tor.telemetryBuilder.ProcessorAcceptedLogRecords.Add(ctx, int64(num), or.otelAttrs)\n\t}\n}\n\n// refused reports that the num data was refused.\nfunc (or *obsReport) refused(ctx context.Context, num int, signal pipeline.Signal) {\n\tswitch signal {\n\tcase pipeline.SignalTraces:\n\t\tor.telemetryBuilder.ProcessorRefusedSpans.Add(ctx, int64(num), or.otelAttrs)\n\tcase pipeline.SignalMetrics:\n\t\tor.telemetryBuilder.ProcessorRefusedMetricPoints.Add(ctx, int64(num), or.otelAttrs)\n\tcase pipeline.SignalLogs:\n\t\tor.telemetryBuilder.ProcessorRefusedLogRecords.Add(ctx, int64(num), or.otelAttrs)\n\t}\n}\n"
  },
  {
    "path": "processor/metadata.yaml",
    "content": "type: processor\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "processor/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processor\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "processor/processor.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processor // import \"go.opentelemetry.io/collector/processor\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\n// Traces is a processor that can consume traces.\ntype Traces interface {\n\tcomponent.Component\n\tconsumer.Traces\n}\n\n// Metrics is a processor that can consume metrics.\ntype Metrics interface {\n\tcomponent.Component\n\tconsumer.Metrics\n}\n\n// Logs is a processor that can consume logs.\ntype Logs interface {\n\tcomponent.Component\n\tconsumer.Logs\n}\n\n// Settings is passed to Create* functions in Factory.\ntype Settings struct {\n\t// ID returns the ID of the component that will be created.\n\tID component.ID\n\n\tcomponent.TelemetrySettings\n\n\t// BuildInfo can be used by components for informational purposes\n\tBuildInfo component.BuildInfo\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// Factory is Factory interface for processors.\n//\n// This interface cannot be directly implemented. Implementations must\n// use the NewFactory to implement it.\ntype Factory interface {\n\tcomponent.Factory\n\n\t// CreateTraces creates a Traces processor based on this config.\n\t// If the processor type does not support traces,\n\t// this function returns the error [pipeline.ErrSignalNotSupported].\n\t// Implementers can assume `next` is never nil.\n\tCreateTraces(ctx context.Context, set Settings, cfg component.Config, next consumer.Traces) (Traces, error)\n\n\t// TracesStability gets the stability level of the Traces processor.\n\tTracesStability() component.StabilityLevel\n\n\t// CreateMetrics creates a Metrics processor based on this config.\n\t// If the processor type does not support metrics,\n\t// this function returns the error [pipeline.ErrSignalNotSupported].\n\t// Implementers can assume `next` is never nil.\n\tCreateMetrics(ctx context.Context, set Settings, cfg component.Config, next consumer.Metrics) (Metrics, error)\n\n\t// MetricsStability gets the stability level of the Metrics processor.\n\tMetricsStability() component.StabilityLevel\n\n\t// CreateLogs creates a Logs processor based on the config.\n\t// If the processor type does not support logs,\n\t// this function returns the error [pipeline.ErrSignalNotSupported].\n\t// Implementers can assume `next` is never nil.\n\tCreateLogs(ctx context.Context, set Settings, cfg component.Config, next consumer.Logs) (Logs, error)\n\n\t// LogsStability gets the stability level of the Logs processor.\n\tLogsStability() component.StabilityLevel\n\n\tunexportedFactoryFunc()\n}\n\n// FactoryOption apply changes to Options.\ntype FactoryOption interface {\n\t// applyOption applies the option.\n\tapplyOption(o *factory)\n}\n\nvar _ FactoryOption = (*factoryOptionFunc)(nil)\n\n// factoryOptionFunc is a FactoryOption created through a function.\ntype factoryOptionFunc func(*factory)\n\nfunc (f factoryOptionFunc) applyOption(o *factory) {\n\tf(o)\n}\n\ntype factory struct {\n\tcfgType component.Type\n\tcomponent.CreateDefaultConfigFunc\n\tcomponentalias.TypeAliasHolder\n\tcreateTracesFunc      CreateTracesFunc\n\ttracesStabilityLevel  component.StabilityLevel\n\tcreateMetricsFunc     CreateMetricsFunc\n\tmetricsStabilityLevel component.StabilityLevel\n\tcreateLogsFunc        CreateLogsFunc\n\tlogsStabilityLevel    component.StabilityLevel\n}\n\nfunc (f *factory) Type() component.Type {\n\treturn f.cfgType\n}\n\nfunc (f *factory) unexportedFactoryFunc() {}\n\nfunc (f *factory) TracesStability() component.StabilityLevel {\n\treturn f.tracesStabilityLevel\n}\n\nfunc (f *factory) MetricsStability() component.StabilityLevel {\n\treturn f.metricsStabilityLevel\n}\n\nfunc (f *factory) LogsStability() component.StabilityLevel {\n\treturn f.logsStabilityLevel\n}\n\nfunc (f *factory) CreateTraces(ctx context.Context, set Settings, cfg component.Config, next consumer.Traces) (Traces, error) {\n\tif f.createTracesFunc == nil {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createTracesFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateMetrics(ctx context.Context, set Settings, cfg component.Config, next consumer.Metrics) (Metrics, error) {\n\tif f.createMetricsFunc == nil {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createMetricsFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateLogs(ctx context.Context, set Settings, cfg component.Config, next consumer.Logs) (Logs, error) {\n\tif f.createLogsFunc == nil {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createLogsFunc(ctx, set, cfg, next)\n}\n\n// CreateTracesFunc is the equivalent of Factory.CreateTraces().\ntype CreateTracesFunc func(context.Context, Settings, component.Config, consumer.Traces) (Traces, error)\n\n// CreateMetricsFunc is the equivalent of Factory.CreateMetrics().\ntype CreateMetricsFunc func(context.Context, Settings, component.Config, consumer.Metrics) (Metrics, error)\n\n// CreateLogsFunc is the equivalent of Factory.CreateLogs.\ntype CreateLogsFunc func(context.Context, Settings, component.Config, consumer.Logs) (Logs, error)\n\n// WithTraces overrides the default \"error not supported\" implementation for CreateTraces and the default \"undefined\" stability level.\nfunc WithTraces(createTraces CreateTracesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.tracesStabilityLevel = sl\n\t\to.createTracesFunc = createTraces\n\t})\n}\n\n// WithMetrics overrides the default \"error not supported\" implementation for CreateMetrics and the default \"undefined\" stability level.\nfunc WithMetrics(createMetrics CreateMetricsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.metricsStabilityLevel = sl\n\t\to.createMetricsFunc = createMetrics\n\t})\n}\n\n// WithLogs overrides the default \"error not supported\" implementation for CreateLogs and the default \"undefined\" stability level.\nfunc WithLogs(createLogs CreateLogsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.logsStabilityLevel = sl\n\t\to.createLogsFunc = createLogs\n\t})\n}\n\n// NewFactory returns a Factory.\nfunc NewFactory(cfgType component.Type, createDefaultConfig component.CreateDefaultConfigFunc, options ...FactoryOption) Factory {\n\tf := &factory{\n\t\tcfgType:                 cfgType,\n\t\tCreateDefaultConfigFunc: createDefaultConfig,\n\t\tTypeAliasHolder:         componentalias.NewTypeAliasHolder(),\n\t}\n\tfor _, opt := range options {\n\t\topt.applyOption(f)\n\t}\n\treturn f\n}\n"
  },
  {
    "path": "processor/processor_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processor\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/processor/internal\"\n)\n\nvar (\n\ttestType = component.MustNewType(\"test\")\n\ttestID   = component.NewID(testType)\n)\n\nfunc TestNewFactory(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tf := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg })\n\tassert.Equal(t, testType, f.Type())\n\tassert.EqualValues(t, &defaultCfg, f.CreateDefaultConfig())\n\t_, err := f.CreateTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.ErrorIs(t, err, pipeline.ErrSignalNotSupported)\n\t_, err = f.CreateMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.ErrorIs(t, err, pipeline.ErrSignalNotSupported)\n\t_, err = f.CreateLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.ErrorIs(t, err, pipeline.ErrSignalNotSupported)\n}\n\nfunc TestNewFactoryWithOptions(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tf := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg },\n\t\tWithTraces(createTraces, component.StabilityLevelAlpha),\n\t\tWithMetrics(createMetrics, component.StabilityLevelBeta),\n\t\tWithLogs(createLogs, component.StabilityLevelUnmaintained))\n\tassert.Equal(t, testType, f.Type())\n\tassert.EqualValues(t, &defaultCfg, f.CreateDefaultConfig())\n\n\twrongID := component.MustNewID(\"wrong\")\n\twrongIDErrStr := internal.ErrIDMismatch(wrongID, testType).Error()\n\n\tassert.Equal(t, component.StabilityLevelAlpha, f.TracesStability())\n\t_, err := f.CreateTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = f.CreateTraces(context.Background(), Settings{ID: wrongID}, &defaultCfg, consumertest.NewNop())\n\trequire.EqualError(t, err, wrongIDErrStr)\n\n\tassert.Equal(t, component.StabilityLevelBeta, f.MetricsStability())\n\t_, err = f.CreateMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = f.CreateMetrics(context.Background(), Settings{ID: wrongID}, &defaultCfg, consumertest.NewNop())\n\trequire.EqualError(t, err, wrongIDErrStr)\n\n\tassert.Equal(t, component.StabilityLevelUnmaintained, f.LogsStability())\n\t_, err = f.CreateLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = f.CreateLogs(context.Background(), Settings{ID: wrongID}, &defaultCfg, consumertest.NewNop())\n\trequire.EqualError(t, err, wrongIDErrStr)\n}\n\nvar nopInstance = &nopProcessor{\n\tConsumer: consumertest.NewNop(),\n}\n\n// nopProcessor stores consumed traces and metrics for testing purposes.\ntype nopProcessor struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumertest.Consumer\n}\n\nfunc createTraces(context.Context, Settings, component.Config, consumer.Traces) (Traces, error) {\n\treturn nopInstance, nil\n}\n\nfunc createMetrics(context.Context, Settings, component.Config, consumer.Metrics) (Metrics, error) {\n\treturn nopInstance, nil\n}\n\nfunc createLogs(context.Context, Settings, component.Config, consumer.Logs) (Logs, error) {\n\treturn nopInstance, nil\n}\n"
  },
  {
    "path": "processor/processorhelper/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "processor/processorhelper/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# processorhelper\n\n## Internal Telemetry\n\nThe following telemetry is emitted by this component.\n\n### otelcol_processor_incoming_items\n\nNumber of items passed to the processor.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {item} | Sum | Int | true | Alpha |\n\n### otelcol_processor_internal_duration\n\nDuration of time taken to process a batch of telemetry data through the processor.\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| s | Histogram | Double | Alpha |\n\n### otelcol_processor_outgoing_items\n\nNumber of items emitted from the processor.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {item} | Sum | Int | true | Alpha |\n"
  },
  {
    "path": "processor/processorhelper/example_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processorhelper_test\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/processorhelper\"\n)\n\n// typeStr defines the unique type identifier for the processor.\nvar typeStr = component.MustNewType(\"example\")\n\n// exampleConfig holds configuration settings for the processor.\ntype exampleConfig struct{}\n\n// exampleProcessor implements the OpenTelemetry processor interface.\ntype exampleProcessor struct {\n\tcancel context.CancelFunc\n\tconfig exampleConfig\n}\n\n// Example demonstrates the usage of the processor factory.\nfunc Example() {\n\t// Instantiate the processor factory and print its type.\n\texampleProcessor := NewFactory()\n\tfmt.Println(exampleProcessor.Type())\n\n\t// Output:\n\t// example\n}\n\n// NewFactory creates a new processor factory.\nfunc NewFactory() processor.Factory {\n\treturn processor.NewFactory(\n\t\ttypeStr,\n\t\tcreateDefaultConfig,\n\t\tprocessor.WithMetrics(createExampleProcessor, component.StabilityLevelAlpha),\n\t)\n}\n\n// createDefaultConfig returns the default configuration for the processor.\nfunc createDefaultConfig() component.Config {\n\treturn &exampleConfig{}\n}\n\n// createExampleProcessor initializes an instance of the example processor.\nfunc createExampleProcessor(ctx context.Context, params processor.Settings, baseCfg component.Config, next consumer.Metrics) (processor.Metrics, error) {\n\t// Convert baseCfg to the correct type.\n\tcfg := baseCfg.(*exampleConfig)\n\n\t// Create a new processor instance.\n\tpcsr := newExampleProcessor(ctx, cfg)\n\n\t// Wrap the processor with the helper utilities.\n\treturn processorhelper.NewMetrics(\n\t\tctx,\n\t\tparams,\n\t\tcfg,\n\t\tnext,\n\t\tpcsr.consumeMetrics,\n\t\tprocessorhelper.WithCapabilities(consumer.Capabilities{MutatesData: true}),\n\t\tprocessorhelper.WithShutdown(pcsr.shutdown),\n\t)\n}\n\n// newExampleProcessor constructs a new instance of the example processor.\nfunc newExampleProcessor(ctx context.Context, cfg *exampleConfig) *exampleProcessor {\n\tpcsr := &exampleProcessor{\n\t\tconfig: *cfg,\n\t}\n\n\t// Create a cancelable context.\n\t_, pcsr.cancel = context.WithCancel(ctx)\n\n\treturn pcsr\n}\n\n// ConsumeMetrics modify metrics adding one attribute to resource.\nfunc (pcsr *exampleProcessor) consumeMetrics(_ context.Context, md pmetric.Metrics) (pmetric.Metrics, error) {\n\trm := md.ResourceMetrics()\n\tfor i := 0; i < rm.Len(); i++ {\n\t\trm.At(i).Resource().Attributes().PutStr(\"processed_by\", \"exampleProcessor\")\n\t}\n\n\treturn md, nil\n}\n\n// Shutdown properly stops the processor and releases resources.\nfunc (pcsr *exampleProcessor) shutdown(_ context.Context) error {\n\tpcsr.cancel()\n\treturn nil\n}\n"
  },
  {
    "path": "processor/processorhelper/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage processorhelper\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "processor/processorhelper/go.mod",
    "content": "module go.opentelemetry.io/collector/processor/processorhelper\n\ngo 1.25.0\n\nreplace go.opentelemetry.io/collector/processor => ../\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/processor v1.54.0\n\tgo.opentelemetry.io/collector/processor/processortest v0.148.0\n\tgo.opentelemetry.io/otel v1.42.0\n\tgo.opentelemetry.io/otel/metric v1.42.0\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0\n\tgo.opentelemetry.io/otel/trace v1.42.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/component/componentstatus v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/processor/xprocessor v0.148.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/processor/xprocessor => ../xprocessor\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/processor/processortest => ../processortest\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/component/componentstatus => ../../component/componentstatus\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "processor/processorhelper/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "processor/processorhelper/internal/metadata/generated_telemetry.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc Meter(settings component.TelemetrySettings) metric.Meter {\n\treturn settings.MeterProvider.Meter(\"go.opentelemetry.io/collector/processor/processorhelper\")\n}\n\nfunc Tracer(settings component.TelemetrySettings) trace.Tracer {\n\treturn settings.TracerProvider.Tracer(\"go.opentelemetry.io/collector/processor/processorhelper\")\n}\n\n// TelemetryBuilder provides an interface for components to report telemetry\n// as defined in metadata and user config.\ntype TelemetryBuilder struct {\n\tmeter                     metric.Meter\n\tmu                        sync.Mutex\n\tregistrations             []metric.Registration\n\tProcessorIncomingItems    metric.Int64Counter\n\tProcessorInternalDuration metric.Float64Histogram\n\tProcessorOutgoingItems    metric.Int64Counter\n}\n\n// TelemetryBuilderOption applies changes to default builder.\ntype TelemetryBuilderOption interface {\n\tapply(*TelemetryBuilder)\n}\n\ntype telemetryBuilderOptionFunc func(mb *TelemetryBuilder)\n\nfunc (tbof telemetryBuilderOptionFunc) apply(mb *TelemetryBuilder) {\n\ttbof(mb)\n}\n\n// Shutdown unregister all registered callbacks for async instruments.\nfunc (builder *TelemetryBuilder) Shutdown() {\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tfor _, reg := range builder.registrations {\n\t\treg.Unregister()\n\t}\n}\n\n// NewTelemetryBuilder provides a struct with methods to update all internal telemetry\n// for a component\nfunc NewTelemetryBuilder(settings component.TelemetrySettings, options ...TelemetryBuilderOption) (*TelemetryBuilder, error) {\n\tbuilder := TelemetryBuilder{}\n\tfor _, op := range options {\n\t\top.apply(&builder)\n\t}\n\tbuilder.meter = Meter(settings)\n\tvar err, errs error\n\tbuilder.ProcessorIncomingItems, err = builder.meter.Int64Counter(\n\t\t\"otelcol_processor_incoming_items\",\n\t\tmetric.WithDescription(\"Number of items passed to the processor. [Alpha]\"),\n\t\tmetric.WithUnit(\"{item}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessorInternalDuration, err = builder.meter.Float64Histogram(\n\t\t\"otelcol_processor_internal_duration\",\n\t\tmetric.WithDescription(\"Duration of time taken to process a batch of telemetry data through the processor. [Alpha]\"),\n\t\tmetric.WithUnit(\"s\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessorOutgoingItems, err = builder.meter.Int64Counter(\n\t\t\"otelcol_processor_outgoing_items\",\n\t\tmetric.WithDescription(\"Number of items emitted from the processor. [Alpha]\"),\n\t\tmetric.WithUnit(\"{item}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\treturn &builder, errs\n}\n"
  },
  {
    "path": "processor/processorhelper/internal/metadata/generated_telemetry_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/metric\"\n\tembeddedmetric \"go.opentelemetry.io/otel/metric/embedded\"\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\t\"go.opentelemetry.io/otel/trace\"\n\tembeddedtrace \"go.opentelemetry.io/otel/trace/embedded\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\ntype mockMeter struct {\n\tnoopmetric.Meter\n\tname string\n}\ntype mockMeterProvider struct {\n\tembeddedmetric.MeterProvider\n}\n\nfunc (m mockMeterProvider) Meter(name string, opts ...metric.MeterOption) metric.Meter {\n\treturn mockMeter{name: name}\n}\n\ntype mockTracer struct {\n\tnooptrace.Tracer\n\tname string\n}\n\ntype mockTracerProvider struct {\n\tembeddedtrace.TracerProvider\n}\n\nfunc (m mockTracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer {\n\treturn mockTracer{name: name}\n}\n\nfunc TestProviders(t *testing.T) {\n\tset := component.TelemetrySettings{\n\t\tMeterProvider:  mockMeterProvider{},\n\t\tTracerProvider: mockTracerProvider{},\n\t}\n\n\tmeter := Meter(set)\n\tif m, ok := meter.(mockMeter); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/processor/processorhelper\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockMeter\")\n\t}\n\n\ttracer := Tracer(set)\n\tif m, ok := tracer.(mockTracer); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/processor/processorhelper\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockTracer\")\n\t}\n}\n\nfunc TestNewTelemetryBuilder(t *testing.T) {\n\tset := componenttest.NewNopTelemetrySettings()\n\tapplied := false\n\t_, err := NewTelemetryBuilder(set, telemetryBuilderOptionFunc(func(b *TelemetryBuilder) {\n\t\tapplied = true\n\t}))\n\trequire.NoError(t, err)\n\trequire.True(t, applied)\n}\n"
  },
  {
    "path": "processor/processorhelper/internal/metadatatest/generated_telemetrytest.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\nfunc AssertEqualProcessorIncomingItems(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_processor_incoming_items\",\n\t\tDescription: \"Number of items passed to the processor. [Alpha]\",\n\t\tUnit:        \"{item}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_processor_incoming_items\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessorInternalDuration(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.HistogramDataPoint[float64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_processor_internal_duration\",\n\t\tDescription: \"Duration of time taken to process a batch of telemetry data through the processor. [Alpha]\",\n\t\tUnit:        \"s\",\n\t\tData: metricdata.Histogram[float64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_processor_internal_duration\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessorOutgoingItems(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_processor_outgoing_items\",\n\t\tDescription: \"Number of items emitted from the processor. [Alpha]\",\n\t\tUnit:        \"{item}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_processor_outgoing_items\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n"
  },
  {
    "path": "processor/processorhelper/internal/metadatatest/generated_telemetrytest_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/processor/processorhelper/internal/metadata\"\n)\n\nfunc TestSetupTelemetry(t *testing.T) {\n\ttestTel := componenttest.NewTelemetry()\n\ttb, err := metadata.NewTelemetryBuilder(testTel.NewTelemetrySettings())\n\trequire.NoError(t, err)\n\tdefer tb.Shutdown()\n\ttb.ProcessorIncomingItems.Add(context.Background(), 1)\n\ttb.ProcessorInternalDuration.Record(context.Background(), 1)\n\ttb.ProcessorOutgoingItems.Add(context.Background(), 1)\n\tAssertEqualProcessorIncomingItems(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessorInternalDuration(t, testTel,\n\t\t[]metricdata.HistogramDataPoint[float64]{{}}, metricdatatest.IgnoreValue(),\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessorOutgoingItems(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\n\trequire.NoError(t, testTel.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "processor/processorhelper/logs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processorhelper // import \"go.opentelemetry.io/collector/processor/processorhelper\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/processor\"\n)\n\n// ProcessLogsFunc is a helper function that processes the incoming data and returns the data to be sent to the next component.\n// If error is returned then returned data are ignored. It MUST not call the next component.\ntype ProcessLogsFunc func(context.Context, plog.Logs) (plog.Logs, error)\n\ntype logs struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumer.Logs\n}\n\n// NewLogs creates a processor.Logs that ensure context propagation and the right tags are set.\nfunc NewLogs(\n\t_ context.Context,\n\tset processor.Settings,\n\t_ component.Config,\n\tnextConsumer consumer.Logs,\n\tlogsFunc ProcessLogsFunc,\n\toptions ...Option,\n) (processor.Logs, error) {\n\tif logsFunc == nil {\n\t\treturn nil, errors.New(\"nil logsFunc\")\n\t}\n\n\tobs, err := newObsReport(set, pipeline.SignalLogs)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\teventOptions := spanAttributes(set.ID)\n\tbs := fromOptions(options)\n\tlogsConsumer, err := consumer.NewLogs(func(ctx context.Context, ld plog.Logs) error {\n\t\tspan := trace.SpanFromContext(ctx)\n\t\tspan.AddEvent(\"Start processing.\", eventOptions)\n\n\t\tstartTime := time.Now()\n\n\t\trecordsIn := ld.LogRecordCount()\n\n\t\tvar errFunc error\n\t\tld, errFunc = logsFunc(ctx, ld)\n\t\tobs.recordInternalDuration(ctx, startTime)\n\t\tspan.AddEvent(\"End processing.\", eventOptions)\n\t\tif errFunc != nil {\n\t\t\tobs.recordInOut(ctx, recordsIn, 0)\n\t\t\tif errors.Is(errFunc, ErrSkipProcessingData) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn errFunc\n\t\t}\n\t\trecordsOut := ld.LogRecordCount()\n\t\tobs.recordInOut(ctx, recordsIn, recordsOut)\n\t\treturn nextConsumer.ConsumeLogs(ctx, ld)\n\t}, bs.consumerOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &logs{\n\t\tStartFunc:    bs.StartFunc,\n\t\tShutdownFunc: bs.ShutdownFunc,\n\t\tLogs:         logsConsumer,\n\t}, nil\n}\n"
  },
  {
    "path": "processor/processorhelper/logs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processorhelper\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/processorhelper/internal/metadatatest\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n)\n\nvar testLogsCfg = struct{}{}\n\nfunc TestNewLogs(t *testing.T) {\n\tlp, err := NewLogs(context.Background(), processortest.NewNopSettings(processortest.NopType), &testLogsCfg, consumertest.NewNop(), newTestLProcessor(nil))\n\trequire.NoError(t, err)\n\n\tassert.True(t, lp.Capabilities().MutatesData)\n\tassert.NoError(t, lp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, lp.ConsumeLogs(context.Background(), plog.NewLogs()))\n\tassert.NoError(t, lp.Shutdown(context.Background()))\n}\n\nfunc TestNewLogs_WithOptions(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tlp, err := NewLogs(context.Background(), processortest.NewNopSettings(processortest.NopType), &testLogsCfg, consumertest.NewNop(), newTestLProcessor(nil),\n\t\tWithStart(func(context.Context, component.Host) error { return want }),\n\t\tWithShutdown(func(context.Context) error { return want }),\n\t\tWithCapabilities(consumer.Capabilities{MutatesData: false}))\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, want, lp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.Equal(t, want, lp.Shutdown(context.Background()))\n\tassert.False(t, lp.Capabilities().MutatesData)\n}\n\nfunc TestNewLogs_NilRequiredFields(t *testing.T) {\n\t_, err := NewLogs(context.Background(), processortest.NewNopSettings(processortest.NopType), &testLogsCfg, consumertest.NewNop(), nil)\n\tassert.Error(t, err)\n}\n\nfunc TestNewLogs_ProcessLogError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tlp, err := NewLogs(context.Background(), processortest.NewNopSettings(processortest.NopType), &testLogsCfg, consumertest.NewNop(), newTestLProcessor(want))\n\trequire.NoError(t, err)\n\tassert.Equal(t, want, lp.ConsumeLogs(context.Background(), plog.NewLogs()))\n}\n\nfunc TestNewLogs_ProcessLogsErrSkipProcessingData(t *testing.T) {\n\tlp, err := NewLogs(context.Background(), processortest.NewNopSettings(processortest.NopType), &testLogsCfg, consumertest.NewNop(), newTestLProcessor(ErrSkipProcessingData))\n\trequire.NoError(t, err)\n\tassert.NoError(t, lp.ConsumeLogs(context.Background(), plog.NewLogs()))\n}\n\nfunc newTestLProcessor(retError error) ProcessLogsFunc {\n\treturn func(_ context.Context, ld plog.Logs) (plog.Logs, error) {\n\t\treturn ld, retError\n\t}\n}\n\nfunc TestLogsConcurrency(t *testing.T) {\n\tlogsFunc := func(_ context.Context, ld plog.Logs) (plog.Logs, error) {\n\t\treturn ld, nil\n\t}\n\n\tincomingLogs := plog.NewLogs()\n\tincomingLogRecords := incomingLogs.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords()\n\n\t// Add 3 records to the incoming\n\tincomingLogRecords.AppendEmpty()\n\tincomingLogRecords.AppendEmpty()\n\tincomingLogRecords.AppendEmpty()\n\n\tlp, err := NewLogs(context.Background(), processortest.NewNopSettings(processortest.NopType), &testLogsCfg, consumertest.NewNop(), logsFunc)\n\trequire.NoError(t, err)\n\tassert.NoError(t, lp.Start(context.Background(), componenttest.NewNopHost()))\n\n\tvar wg sync.WaitGroup\n\tfor range 10 {\n\t\twg.Go(func() {\n\t\t\tfor range 10000 {\n\t\t\t\tassert.NoError(t, lp.ConsumeLogs(context.Background(), incomingLogs))\n\t\t\t}\n\t\t})\n\t}\n\twg.Wait()\n\tassert.NoError(t, lp.Shutdown(context.Background()))\n}\n\nfunc TestLogs_RecordInOut(t *testing.T) {\n\t// Regardless of how many logs are ingested, emit just one\n\tmockAggregate := func(_ context.Context, _ plog.Logs) (plog.Logs, error) {\n\t\tld := plog.NewLogs()\n\t\tld.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\t\treturn ld, nil\n\t}\n\n\tincomingLogs := plog.NewLogs()\n\tincomingLogRecords := incomingLogs.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords()\n\n\t// Add 3 records to the incoming\n\tincomingLogRecords.AppendEmpty()\n\tincomingLogRecords.AppendEmpty()\n\tincomingLogRecords.AppendEmpty()\n\n\ttel := componenttest.NewTelemetry()\n\tlp, err := NewLogs(context.Background(), newSettings(tel), &testLogsCfg, consumertest.NewNop(), mockAggregate)\n\trequire.NoError(t, err)\n\n\tassert.NoError(t, lp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, lp.ConsumeLogs(context.Background(), incomingLogs))\n\tassert.NoError(t, lp.Shutdown(context.Background()))\n\n\tmetadatatest.AssertEqualProcessorIncomingItems(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      3,\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"processorhelper\"), attribute.String(\"otel.signal\", \"logs\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\tmetadatatest.AssertEqualProcessorOutgoingItems(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      1,\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"processorhelper\"), attribute.String(\"otel.signal\", \"logs\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n}\n\nfunc TestLogs_RecordIn_ErrorOut(t *testing.T) {\n\t// Regardless of input, return error\n\tmockErr := func(_ context.Context, _ plog.Logs) (plog.Logs, error) {\n\t\treturn plog.NewLogs(), errors.New(\"fake\")\n\t}\n\n\tincomingLogs := plog.NewLogs()\n\tincomingLogRecords := incomingLogs.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords()\n\n\t// Add 3 records to the incoming\n\tincomingLogRecords.AppendEmpty()\n\tincomingLogRecords.AppendEmpty()\n\tincomingLogRecords.AppendEmpty()\n\n\ttel := componenttest.NewTelemetry()\n\tlp, err := NewLogs(context.Background(), newSettings(tel), &testLogsCfg, consumertest.NewNop(), mockErr)\n\trequire.NoError(t, err)\n\n\trequire.NoError(t, lp.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.Error(t, lp.ConsumeLogs(context.Background(), incomingLogs))\n\trequire.NoError(t, lp.Shutdown(context.Background()))\n\n\tmetadatatest.AssertEqualProcessorIncomingItems(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      3,\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"processorhelper\"), attribute.String(\"otel.signal\", \"logs\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\tmetadatatest.AssertEqualProcessorOutgoingItems(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      0,\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"processorhelper\"), attribute.String(\"otel.signal\", \"logs\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n}\n\nfunc TestLogs_ProcessInternalDuration(t *testing.T) {\n\tmockAggregate := func(_ context.Context, _ plog.Logs) (plog.Logs, error) {\n\t\tld := plog.NewLogs()\n\t\tld.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\t\treturn ld, nil\n\t}\n\n\tincomingLogs := plog.NewLogs()\n\n\ttel := componenttest.NewTelemetry()\n\tlp, err := NewLogs(context.Background(), newSettings(tel), &testLogsCfg, consumertest.NewNop(), mockAggregate)\n\trequire.NoError(t, err)\n\n\tassert.NoError(t, lp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, lp.ConsumeLogs(context.Background(), incomingLogs))\n\tassert.NoError(t, lp.Shutdown(context.Background()))\n\n\tmetadatatest.AssertEqualProcessorInternalDuration(t, tel,\n\t\t[]metricdata.HistogramDataPoint[float64]{\n\t\t\t{\n\t\t\t\tCount:        1,\n\t\t\t\tBucketCounts: []uint64{1},\n\t\t\t\tAttributes:   attribute.NewSet(attribute.String(\"processor\", \"processorhelper\"), attribute.String(\"otel.signal\", \"logs\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue())\n}\n\nfunc newSettings(tel *componenttest.Telemetry) processor.Settings {\n\tset := processortest.NewNopSettings(component.MustNewType(\"processorhelper\"))\n\tset.TelemetrySettings = tel.NewTelemetrySettings()\n\treturn set\n}\n"
  },
  {
    "path": "processor/processorhelper/metadata.yaml",
    "content": "type: processorhelper\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  stability:\n    beta: [traces, metrics, logs]\n\ntelemetry:\n  metrics:\n    processor_incoming_items:\n      enabled: true\n      stability: alpha\n      description: Number of items passed to the processor.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    processor_internal_duration:\n      enabled: true\n      stability: alpha\n      description: Duration of time taken to process a batch of telemetry data through the processor.\n      unit: s\n      histogram:\n        async: false\n        value_type: double\n\n    processor_outgoing_items:\n      enabled: true\n      stability: alpha\n      description: Number of items emitted from the processor.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n"
  },
  {
    "path": "processor/processorhelper/metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processorhelper // import \"go.opentelemetry.io/collector/processor/processorhelper\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/processor\"\n)\n\n// ProcessMetricsFunc is a helper function that processes the incoming data and returns the data to be sent to the next component.\n// If error is returned then returned data are ignored. It MUST not call the next component.\ntype ProcessMetricsFunc func(context.Context, pmetric.Metrics) (pmetric.Metrics, error)\n\ntype metrics struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumer.Metrics\n}\n\n// NewMetrics creates a processor.Metrics that ensure context propagation and the right tags are set.\nfunc NewMetrics(\n\t_ context.Context,\n\tset processor.Settings,\n\t_ component.Config,\n\tnextConsumer consumer.Metrics,\n\tmetricsFunc ProcessMetricsFunc,\n\toptions ...Option,\n) (processor.Metrics, error) {\n\tif metricsFunc == nil {\n\t\treturn nil, errors.New(\"nil metricsFunc\")\n\t}\n\n\tobs, err := newObsReport(set, pipeline.SignalMetrics)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\teventOptions := spanAttributes(set.ID)\n\tbs := fromOptions(options)\n\tmetricsConsumer, err := consumer.NewMetrics(func(ctx context.Context, md pmetric.Metrics) error {\n\t\tspan := trace.SpanFromContext(ctx)\n\t\tspan.AddEvent(\"Start processing.\", eventOptions)\n\n\t\tstartTime := time.Now()\n\n\t\tpointsIn := md.DataPointCount()\n\n\t\tvar errFunc error\n\t\tmd, errFunc = metricsFunc(ctx, md)\n\t\tobs.recordInternalDuration(ctx, startTime)\n\t\tspan.AddEvent(\"End processing.\", eventOptions)\n\t\tif errFunc != nil {\n\t\t\tobs.recordInOut(ctx, pointsIn, 0)\n\t\t\tif errors.Is(errFunc, ErrSkipProcessingData) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn errFunc\n\t\t}\n\t\tpointsOut := md.DataPointCount()\n\t\tobs.recordInOut(ctx, pointsIn, pointsOut)\n\t\treturn nextConsumer.ConsumeMetrics(ctx, md)\n\t}, bs.consumerOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &metrics{\n\t\tStartFunc:    bs.StartFunc,\n\t\tShutdownFunc: bs.ShutdownFunc,\n\t\tMetrics:      metricsConsumer,\n\t}, nil\n}\n"
  },
  {
    "path": "processor/processorhelper/metrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processorhelper\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/processor/processorhelper/internal/metadatatest\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n)\n\nvar testMetricsCfg = struct{}{}\n\nfunc TestNewMetrics(t *testing.T) {\n\tmp, err := NewMetrics(context.Background(), processortest.NewNopSettings(processortest.NopType), &testMetricsCfg, consumertest.NewNop(), newTestMProcessor(nil))\n\trequire.NoError(t, err)\n\n\tassert.True(t, mp.Capabilities().MutatesData)\n\tassert.NoError(t, mp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, mp.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n\tassert.NoError(t, mp.Shutdown(context.Background()))\n}\n\nfunc TestNewMetrics_WithOptions(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tmp, err := NewMetrics(context.Background(), processortest.NewNopSettings(processortest.NopType), &testMetricsCfg, consumertest.NewNop(), newTestMProcessor(nil),\n\t\tWithStart(func(context.Context, component.Host) error { return want }),\n\t\tWithShutdown(func(context.Context) error { return want }),\n\t\tWithCapabilities(consumer.Capabilities{MutatesData: false}))\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, want, mp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.Equal(t, want, mp.Shutdown(context.Background()))\n\tassert.False(t, mp.Capabilities().MutatesData)\n}\n\nfunc TestNewMetrics_NilRequiredFields(t *testing.T) {\n\t_, err := NewMetrics(context.Background(), processortest.NewNopSettings(processortest.NopType), &testMetricsCfg, consumertest.NewNop(), nil)\n\tassert.Error(t, err)\n}\n\nfunc TestNewMetrics_ProcessMetricsError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tmp, err := NewMetrics(context.Background(), processortest.NewNopSettings(processortest.NopType), &testMetricsCfg, consumertest.NewNop(), newTestMProcessor(want))\n\trequire.NoError(t, err)\n\tassert.Equal(t, want, mp.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n}\n\nfunc TestNewMetrics_ProcessMetricsErrSkipProcessingData(t *testing.T) {\n\tmp, err := NewMetrics(context.Background(), processortest.NewNopSettings(processortest.NopType), &testMetricsCfg, consumertest.NewNop(), newTestMProcessor(ErrSkipProcessingData))\n\trequire.NoError(t, err)\n\tassert.NoError(t, mp.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n}\n\nfunc newTestMProcessor(retError error) ProcessMetricsFunc {\n\treturn func(_ context.Context, md pmetric.Metrics) (pmetric.Metrics, error) {\n\t\treturn md, retError\n\t}\n}\n\nfunc TestMetricsConcurrency(t *testing.T) {\n\tmetricsFunc := func(_ context.Context, md pmetric.Metrics) (pmetric.Metrics, error) {\n\t\treturn md, nil\n\t}\n\n\tincomingMetrics := pmetric.NewMetrics()\n\tdps := incomingMetrics.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptySum().DataPoints()\n\n\t// Add 2 data points to the incoming\n\tdps.AppendEmpty()\n\tdps.AppendEmpty()\n\n\tmp, err := NewMetrics(context.Background(), processortest.NewNopSettings(processortest.NopType), &testLogsCfg, consumertest.NewNop(), metricsFunc)\n\trequire.NoError(t, err)\n\tassert.NoError(t, mp.Start(context.Background(), componenttest.NewNopHost()))\n\n\tvar wg sync.WaitGroup\n\tfor range 10 {\n\t\twg.Go(func() {\n\t\t\tfor range 10000 {\n\t\t\t\tassert.NoError(t, mp.ConsumeMetrics(context.Background(), incomingMetrics))\n\t\t\t}\n\t\t})\n\t}\n\twg.Wait()\n\tassert.NoError(t, mp.Shutdown(context.Background()))\n}\n\nfunc TestMetrics_RecordInOut(t *testing.T) {\n\t// Regardless of how many data points are ingested, emit 3\n\tmockAggregate := func(_ context.Context, _ pmetric.Metrics) (pmetric.Metrics, error) {\n\t\tmd := pmetric.NewMetrics()\n\t\tmd.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptySum().DataPoints().AppendEmpty()\n\t\tmd.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptySum().DataPoints().AppendEmpty()\n\t\tmd.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptySum().DataPoints().AppendEmpty()\n\t\treturn md, nil\n\t}\n\n\tincomingMetrics := pmetric.NewMetrics()\n\tdps := incomingMetrics.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptySum().DataPoints()\n\n\t// Add 2 data points to the incoming\n\tdps.AppendEmpty()\n\tdps.AppendEmpty()\n\n\ttel := componenttest.NewTelemetry()\n\tmp, err := NewMetrics(context.Background(), newSettings(tel), &testMetricsCfg, consumertest.NewNop(), mockAggregate)\n\trequire.NoError(t, err)\n\n\tassert.NoError(t, mp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, mp.ConsumeMetrics(context.Background(), incomingMetrics))\n\tassert.NoError(t, mp.Shutdown(context.Background()))\n\n\tmetadatatest.AssertEqualProcessorIncomingItems(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      2,\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"processorhelper\"), attribute.String(\"otel.signal\", \"metrics\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\tmetadatatest.AssertEqualProcessorOutgoingItems(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      3,\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"processorhelper\"), attribute.String(\"otel.signal\", \"metrics\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n}\n\nfunc TestMetrics_RecordIn_ErrorOut(t *testing.T) {\n\t/// Regardless of input, return error\n\tmockErr := func(_ context.Context, _ pmetric.Metrics) (pmetric.Metrics, error) {\n\t\treturn pmetric.NewMetrics(), errors.New(\"fake\")\n\t}\n\n\tincomingMetrics := pmetric.NewMetrics()\n\tdps := incomingMetrics.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptySum().DataPoints()\n\n\t// Add 2 data points to the incoming\n\tdps.AppendEmpty()\n\tdps.AppendEmpty()\n\n\ttel := componenttest.NewTelemetry()\n\tmp, err := NewMetrics(context.Background(), newSettings(tel), &testMetricsCfg, consumertest.NewNop(), mockErr)\n\trequire.NoError(t, err)\n\n\trequire.NoError(t, mp.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.Error(t, mp.ConsumeMetrics(context.Background(), incomingMetrics))\n\trequire.NoError(t, mp.Shutdown(context.Background()))\n\n\tmetadatatest.AssertEqualProcessorIncomingItems(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      2,\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"processorhelper\"), attribute.String(\"otel.signal\", \"metrics\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\tmetadatatest.AssertEqualProcessorOutgoingItems(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      0,\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"processorhelper\"), attribute.String(\"otel.signal\", \"metrics\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n}\n\nfunc TestMetrics_ProcessInternalDuration(t *testing.T) {\n\tmockAggregate := func(_ context.Context, _ pmetric.Metrics) (pmetric.Metrics, error) {\n\t\tmd := pmetric.NewMetrics()\n\t\tmd.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptySum().DataPoints().AppendEmpty()\n\t\tmd.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptySum().DataPoints().AppendEmpty()\n\t\tmd.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptySum().DataPoints().AppendEmpty()\n\t\treturn md, nil\n\t}\n\n\tincomingMetrics := pmetric.NewMetrics()\n\n\ttel := componenttest.NewTelemetry()\n\tmp, err := NewMetrics(context.Background(), newSettings(tel), &testMetricsCfg, consumertest.NewNop(), mockAggregate)\n\trequire.NoError(t, err)\n\n\tassert.NoError(t, mp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, mp.ConsumeMetrics(context.Background(), incomingMetrics))\n\tassert.NoError(t, mp.Shutdown(context.Background()))\n\n\tmetadatatest.AssertEqualProcessorInternalDuration(t, tel,\n\t\t[]metricdata.HistogramDataPoint[float64]{\n\t\t\t{\n\t\t\t\tCount:        1,\n\t\t\t\tBucketCounts: []uint64{1},\n\t\t\t\tAttributes:   attribute.NewSet(attribute.String(\"processor\", \"processorhelper\"), attribute.String(\"otel.signal\", \"metrics\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue())\n}\n"
  },
  {
    "path": "processor/processorhelper/obsreport.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processorhelper // import \"go.opentelemetry.io/collector/processor/processorhelper\"\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/metric\"\n\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/internal\"\n\t\"go.opentelemetry.io/collector/processor/processorhelper/internal/metadata\"\n)\n\nconst signalKey = \"otel.signal\"\n\ntype obsReport struct {\n\totelAttrs        metric.MeasurementOption\n\ttelemetryBuilder *metadata.TelemetryBuilder\n}\n\nfunc newObsReport(set processor.Settings, signal pipeline.Signal) (*obsReport, error) {\n\ttelemetryBuilder, err := metadata.NewTelemetryBuilder(set.TelemetrySettings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &obsReport{\n\t\totelAttrs: metric.WithAttributeSet(attribute.NewSet(\n\t\t\tattribute.String(internal.ProcessorKey, set.ID.String()),\n\t\t\tattribute.String(signalKey, signal.String()),\n\t\t)),\n\t\ttelemetryBuilder: telemetryBuilder,\n\t}, nil\n}\n\nfunc (or *obsReport) recordInOut(ctx context.Context, incoming, outgoing int) {\n\tor.telemetryBuilder.ProcessorIncomingItems.Add(ctx, int64(incoming), or.otelAttrs)\n\tor.telemetryBuilder.ProcessorOutgoingItems.Add(ctx, int64(outgoing), or.otelAttrs)\n}\n\nfunc (or *obsReport) recordInternalDuration(ctx context.Context, startTime time.Time) {\n\tduration := time.Since(startTime)\n\tor.telemetryBuilder.ProcessorInternalDuration.Record(ctx, duration.Seconds(), or.otelAttrs)\n}\n"
  },
  {
    "path": "processor/processorhelper/processor.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\npackage processorhelper // import \"go.opentelemetry.io/collector/processor/processorhelper\"\n\nimport (\n\t\"errors\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/processor/internal\"\n)\n\n// ErrSkipProcessingData is a sentinel value to indicate when traces or metrics should intentionally be dropped\n// from further processing in the pipeline because the data is determined to be irrelevant. A processor can return this error\n// to stop further processing without propagating an error back up the pipeline to logs.\nvar ErrSkipProcessingData = errors.New(\"sentinel error to skip processing data from the remainder of the pipeline\")\n\n// Option apply changes to internalOptions.\ntype Option interface {\n\tapply(*baseSettings)\n}\n\ntype optionFunc func(*baseSettings)\n\nfunc (of optionFunc) apply(e *baseSettings) {\n\tof(e)\n}\n\n// WithStart overrides the default Start function for an processor.\n// The default shutdown function does nothing and always returns nil.\nfunc WithStart(start component.StartFunc) Option {\n\treturn optionFunc(func(o *baseSettings) {\n\t\to.StartFunc = start\n\t})\n}\n\n// WithShutdown overrides the default Shutdown function for an processor.\n// The default shutdown function does nothing and always returns nil.\nfunc WithShutdown(shutdown component.ShutdownFunc) Option {\n\treturn optionFunc(func(o *baseSettings) {\n\t\to.ShutdownFunc = shutdown\n\t})\n}\n\n// WithCapabilities overrides the default GetCapabilities function for an processor.\n// The default GetCapabilities function returns mutable capabilities.\nfunc WithCapabilities(capabilities consumer.Capabilities) Option {\n\treturn optionFunc(func(o *baseSettings) {\n\t\to.consumerOptions = append(o.consumerOptions, consumer.WithCapabilities(capabilities))\n\t})\n}\n\ntype baseSettings struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumerOptions []consumer.Option\n}\n\n// fromOptions returns the internal settings starting from the default and applying all options.\nfunc fromOptions(options []Option) *baseSettings {\n\t// Start from the default options:\n\topts := &baseSettings{\n\t\tconsumerOptions: []consumer.Option{consumer.WithCapabilities(consumer.Capabilities{MutatesData: true})},\n\t}\n\n\tfor _, op := range options {\n\t\top.apply(opts)\n\t}\n\n\treturn opts\n}\n\nfunc spanAttributes(id component.ID) trace.EventOption {\n\treturn trace.WithAttributes(attribute.String(internal.ProcessorKey, id.String()))\n}\n"
  },
  {
    "path": "processor/processorhelper/traces.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processorhelper // import \"go.opentelemetry.io/collector/processor/processorhelper\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/processor\"\n)\n\n// ProcessTracesFunc is a helper function that processes the incoming data and returns the data to be sent to the next component.\n// If error is returned then returned data are ignored. It MUST not call the next component.\ntype ProcessTracesFunc func(context.Context, ptrace.Traces) (ptrace.Traces, error)\n\ntype traces struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumer.Traces\n}\n\n// NewTraces creates a processor.Traces that ensure context propagation and the right tags are set.\nfunc NewTraces(\n\t_ context.Context,\n\tset processor.Settings,\n\t_ component.Config,\n\tnextConsumer consumer.Traces,\n\ttracesFunc ProcessTracesFunc,\n\toptions ...Option,\n) (processor.Traces, error) {\n\tif tracesFunc == nil {\n\t\treturn nil, errors.New(\"nil tracesFunc\")\n\t}\n\n\tobs, err := newObsReport(set, pipeline.SignalTraces)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\teventOptions := spanAttributes(set.ID)\n\tbs := fromOptions(options)\n\ttraceConsumer, err := consumer.NewTraces(func(ctx context.Context, td ptrace.Traces) error {\n\t\tspan := trace.SpanFromContext(ctx)\n\t\tspan.AddEvent(\"Start processing.\", eventOptions)\n\n\t\tstartTime := time.Now()\n\n\t\tspansIn := td.SpanCount()\n\n\t\tvar errFunc error\n\t\ttd, errFunc = tracesFunc(ctx, td)\n\t\tobs.recordInternalDuration(ctx, startTime)\n\t\tspan.AddEvent(\"End processing.\", eventOptions)\n\t\tif errFunc != nil {\n\t\t\tobs.recordInOut(ctx, spansIn, 0)\n\t\t\tif errors.Is(errFunc, ErrSkipProcessingData) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn errFunc\n\t\t}\n\t\tspansOut := td.SpanCount()\n\t\tobs.recordInOut(ctx, spansIn, spansOut)\n\t\treturn nextConsumer.ConsumeTraces(ctx, td)\n\t}, bs.consumerOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &traces{\n\t\tStartFunc:    bs.StartFunc,\n\t\tShutdownFunc: bs.ShutdownFunc,\n\t\tTraces:       traceConsumer,\n\t}, nil\n}\n"
  },
  {
    "path": "processor/processorhelper/traces_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processorhelper\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/processor/processorhelper/internal/metadatatest\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n)\n\nvar testTracesCfg = struct{}{}\n\nfunc TestNewTraces(t *testing.T) {\n\ttp, err := NewTraces(context.Background(), processortest.NewNopSettings(processortest.NopType), &testTracesCfg, consumertest.NewNop(), newTestTProcessor(nil))\n\trequire.NoError(t, err)\n\n\tassert.True(t, tp.Capabilities().MutatesData)\n\tassert.NoError(t, tp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, tp.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n\tassert.NoError(t, tp.Shutdown(context.Background()))\n}\n\nfunc TestNewTraces_WithOptions(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\ttp, err := NewTraces(context.Background(), processortest.NewNopSettings(processortest.NopType), &testTracesCfg, consumertest.NewNop(), newTestTProcessor(nil),\n\t\tWithStart(func(context.Context, component.Host) error { return want }),\n\t\tWithShutdown(func(context.Context) error { return want }),\n\t\tWithCapabilities(consumer.Capabilities{MutatesData: false}))\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, want, tp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.Equal(t, want, tp.Shutdown(context.Background()))\n\tassert.False(t, tp.Capabilities().MutatesData)\n}\n\nfunc TestNewTraces_NilRequiredFields(t *testing.T) {\n\t_, err := NewTraces(context.Background(), processortest.NewNopSettings(processortest.NopType), &testTracesCfg, consumertest.NewNop(), nil)\n\tassert.Error(t, err)\n}\n\nfunc TestNewTraces_ProcessTraceError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\ttp, err := NewTraces(context.Background(), processortest.NewNopSettings(processortest.NopType), &testTracesCfg, consumertest.NewNop(), newTestTProcessor(want))\n\trequire.NoError(t, err)\n\tassert.Equal(t, want, tp.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n}\n\nfunc TestNewTraces_ProcessTracesErrSkipProcessingData(t *testing.T) {\n\ttp, err := NewTraces(context.Background(), processortest.NewNopSettings(processortest.NopType), &testTracesCfg, consumertest.NewNop(), newTestTProcessor(ErrSkipProcessingData))\n\trequire.NoError(t, err)\n\tassert.NoError(t, tp.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n}\n\nfunc newTestTProcessor(retError error) ProcessTracesFunc {\n\treturn func(_ context.Context, td ptrace.Traces) (ptrace.Traces, error) {\n\t\treturn td, retError\n\t}\n}\n\nfunc TestTracesConcurrency(t *testing.T) {\n\ttracesFunc := func(_ context.Context, td ptrace.Traces) (ptrace.Traces, error) {\n\t\treturn td, nil\n\t}\n\n\tincomingTraces := ptrace.NewTraces()\n\tincomingSpans := incomingTraces.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans()\n\n\t// Add 4 records to the incoming\n\tincomingSpans.AppendEmpty()\n\tincomingSpans.AppendEmpty()\n\tincomingSpans.AppendEmpty()\n\tincomingSpans.AppendEmpty()\n\n\tmp, err := NewTraces(context.Background(), processortest.NewNopSettings(processortest.NopType), &testLogsCfg, consumertest.NewNop(), tracesFunc)\n\trequire.NoError(t, err)\n\tassert.NoError(t, mp.Start(context.Background(), componenttest.NewNopHost()))\n\n\tvar wg sync.WaitGroup\n\tfor range 10 {\n\t\twg.Go(func() {\n\t\t\tfor range 10000 {\n\t\t\t\tassert.NoError(t, mp.ConsumeTraces(context.Background(), incomingTraces))\n\t\t\t}\n\t\t})\n\t}\n\twg.Wait()\n\tassert.NoError(t, mp.Shutdown(context.Background()))\n}\n\nfunc TestTraces_RecordInOut(t *testing.T) {\n\t// Regardless of how many spans are ingested, emit just one\n\tmockAggregate := func(_ context.Context, _ ptrace.Traces) (ptrace.Traces, error) {\n\t\ttd := ptrace.NewTraces()\n\t\ttd.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty()\n\t\treturn td, nil\n\t}\n\n\tincomingTraces := ptrace.NewTraces()\n\tincomingSpans := incomingTraces.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans()\n\n\t// Add 4 records to the incoming\n\tincomingSpans.AppendEmpty()\n\tincomingSpans.AppendEmpty()\n\tincomingSpans.AppendEmpty()\n\tincomingSpans.AppendEmpty()\n\n\ttel := componenttest.NewTelemetry()\n\ttp, err := NewTraces(context.Background(), newSettings(tel), &testLogsCfg, consumertest.NewNop(), mockAggregate)\n\trequire.NoError(t, err)\n\n\tassert.NoError(t, tp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, tp.ConsumeTraces(context.Background(), incomingTraces))\n\tassert.NoError(t, tp.Shutdown(context.Background()))\n\n\tmetadatatest.AssertEqualProcessorIncomingItems(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      4,\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"processorhelper\"), attribute.String(\"otel.signal\", \"traces\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\tmetadatatest.AssertEqualProcessorOutgoingItems(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      1,\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"processorhelper\"), attribute.String(\"otel.signal\", \"traces\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n}\n\nfunc TestTraces_RecordIn_ErrorOut(t *testing.T) {\n\t// Regardless of input, return error\n\tmockErr := func(_ context.Context, _ ptrace.Traces) (ptrace.Traces, error) {\n\t\treturn ptrace.NewTraces(), errors.New(\"fake\")\n\t}\n\n\tincomingTraces := ptrace.NewTraces()\n\tincomingSpans := incomingTraces.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans()\n\n\t// Add 4 records to the incoming\n\tincomingSpans.AppendEmpty()\n\tincomingSpans.AppendEmpty()\n\tincomingSpans.AppendEmpty()\n\tincomingSpans.AppendEmpty()\n\n\ttel := componenttest.NewTelemetry()\n\ttp, err := NewTraces(context.Background(), newSettings(tel), &testLogsCfg, consumertest.NewNop(), mockErr)\n\trequire.NoError(t, err)\n\n\trequire.NoError(t, tp.Start(context.Background(), componenttest.NewNopHost()))\n\trequire.Error(t, tp.ConsumeTraces(context.Background(), incomingTraces))\n\trequire.NoError(t, tp.Shutdown(context.Background()))\n\n\tmetadatatest.AssertEqualProcessorIncomingItems(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      4,\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"processorhelper\"), attribute.String(\"otel.signal\", \"traces\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n\tmetadatatest.AssertEqualProcessorOutgoingItems(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tValue:      0,\n\t\t\t\tAttributes: attribute.NewSet(attribute.String(\"processor\", \"processorhelper\"), attribute.String(\"otel.signal\", \"traces\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp())\n}\n\nfunc TestTraces_ProcessInternalDuration(t *testing.T) {\n\tmockAggregate := func(_ context.Context, _ ptrace.Traces) (ptrace.Traces, error) {\n\t\ttd := ptrace.NewTraces()\n\t\ttd.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty()\n\t\treturn td, nil\n\t}\n\n\tincomingTraces := ptrace.NewTraces()\n\n\ttel := componenttest.NewTelemetry()\n\ttp, err := NewTraces(context.Background(), newSettings(tel), &testLogsCfg, consumertest.NewNop(), mockAggregate)\n\trequire.NoError(t, err)\n\n\tassert.NoError(t, tp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, tp.ConsumeTraces(context.Background(), incomingTraces))\n\tassert.NoError(t, tp.Shutdown(context.Background()))\n\n\tmetadatatest.AssertEqualProcessorInternalDuration(t, tel,\n\t\t[]metricdata.HistogramDataPoint[float64]{\n\t\t\t{\n\t\t\t\tCount:        1,\n\t\t\t\tBucketCounts: []uint64{1},\n\t\t\t\tAttributes:   attribute.NewSet(attribute.String(\"processor\", \"processorhelper\"), attribute.String(\"otel.signal\", \"traces\")),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue())\n}\n"
  },
  {
    "path": "processor/processorhelper/xprocessorhelper/Makefile",
    "content": "include ../../../Makefile.Common\n"
  },
  {
    "path": "processor/processorhelper/xprocessorhelper/go.mod",
    "content": "module go.opentelemetry.io/collector/processor/processorhelper/xprocessorhelper\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/processor v1.54.0\n\tgo.opentelemetry.io/collector/processor/processorhelper v0.148.0\n\tgo.opentelemetry.io/collector/processor/processortest v0.148.0\n\tgo.opentelemetry.io/collector/processor/xprocessor v0.148.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/component/componentstatus v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/processor => ../../../processor\n\nreplace go.opentelemetry.io/collector/consumer => ../../../consumer\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/component => ../../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../../component/componenttest\n\nreplace go.opentelemetry.io/collector/pdata => ../../../pdata\n\nreplace go.opentelemetry.io/collector/pipeline => ../../../pipeline\n\nreplace go.opentelemetry.io/collector/component/componentstatus => ../../../component/componentstatus\n\nreplace go.opentelemetry.io/collector/processor/processortest => ../../processortest\n\nreplace go.opentelemetry.io/collector/processor/processorhelper => ../\n\nreplace go.opentelemetry.io/collector/processor/xprocessor => ../../xprocessor\n\nreplace go.opentelemetry.io/collector/featuregate => ../../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../../internal/componentalias\n"
  },
  {
    "path": "processor/processorhelper/xprocessorhelper/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "processor/processorhelper/xprocessorhelper/metadata.yaml",
    "content": "type: xprocessorhelper\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "processor/processorhelper/xprocessorhelper/processor.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xprocessorhelper // import \"go.opentelemetry.io/collector/processor/processorhelper/xprocessorhelper\"\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n)\n\n// Option apply changes to internalOptions.\ntype Option interface {\n\tapply(*baseSettings)\n}\n\ntype optionFunc func(*baseSettings)\n\nfunc (of optionFunc) apply(e *baseSettings) {\n\tof(e)\n}\n\n// WithStart overrides the default Start function for an processor.\n// The default shutdown function does nothing and always returns nil.\nfunc WithStart(start component.StartFunc) Option {\n\treturn optionFunc(func(o *baseSettings) {\n\t\to.StartFunc = start\n\t})\n}\n\n// WithShutdown overrides the default Shutdown function for an processor.\n// The default shutdown function does nothing and always returns nil.\nfunc WithShutdown(shutdown component.ShutdownFunc) Option {\n\treturn optionFunc(func(o *baseSettings) {\n\t\to.ShutdownFunc = shutdown\n\t})\n}\n\n// WithCapabilities overrides the default GetCapabilities function for an processor.\n// The default GetCapabilities function returns mutable capabilities.\nfunc WithCapabilities(capabilities consumer.Capabilities) Option {\n\treturn optionFunc(func(o *baseSettings) {\n\t\to.consumerOptions = append(o.consumerOptions, consumer.WithCapabilities(capabilities))\n\t})\n}\n\ntype baseSettings struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumerOptions []consumer.Option\n}\n\n// fromOptions returns the internal settings starting from the default and applying all options.\nfunc fromOptions(options []Option) *baseSettings {\n\t// Start from the default options:\n\topts := &baseSettings{\n\t\tconsumerOptions: []consumer.Option{consumer.WithCapabilities(consumer.Capabilities{MutatesData: true})},\n\t}\n\n\tfor _, op := range options {\n\t\top.apply(opts)\n\t}\n\n\treturn opts\n}\n"
  },
  {
    "path": "processor/processorhelper/xprocessorhelper/profiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xprocessorhelper // import \"go.opentelemetry.io/collector/processor/processorhelper/xprocessorhelper\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/processorhelper\"\n\t\"go.opentelemetry.io/collector/processor/xprocessor\"\n)\n\n// ProcessProfilesFunc is a helper function that processes the incoming data and returns the data to be sent to the next component.\n// If error is returned then returned data are ignored. It MUST not call the next component.\ntype ProcessProfilesFunc func(context.Context, pprofile.Profiles) (pprofile.Profiles, error)\n\ntype profiles struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\txconsumer.Profiles\n}\n\n// NewProfiles creates a xprocessor.Profiles that ensure context propagation.\nfunc NewProfiles(\n\t_ context.Context,\n\t_ processor.Settings,\n\t_ component.Config,\n\tnextConsumer xconsumer.Profiles,\n\tprofilesFunc ProcessProfilesFunc,\n\toptions ...Option,\n) (xprocessor.Profiles, error) {\n\tif profilesFunc == nil {\n\t\treturn nil, errors.New(\"nil profilesFunc\")\n\t}\n\n\tbs := fromOptions(options)\n\tprofilesConsumer, err := xconsumer.NewProfiles(func(ctx context.Context, pd pprofile.Profiles) (err error) {\n\t\tpd, err = profilesFunc(ctx, pd)\n\t\tif err != nil {\n\t\t\tif errors.Is(err, processorhelper.ErrSkipProcessingData) {\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn err\n\t\t}\n\t\treturn nextConsumer.ConsumeProfiles(ctx, pd)\n\t}, bs.consumerOptions...)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn &profiles{\n\t\tStartFunc:    bs.StartFunc,\n\t\tShutdownFunc: bs.ShutdownFunc,\n\t\tProfiles:     profilesConsumer,\n\t}, nil\n}\n"
  },
  {
    "path": "processor/processorhelper/xprocessorhelper/profiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xprocessorhelper\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/processor/processorhelper\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n)\n\nvar testProfilesCfg = struct{}{}\n\nfunc TestNewProfiles(t *testing.T) {\n\tpp, err := NewProfiles(context.Background(), processortest.NewNopSettings(processortest.NopType), &testProfilesCfg, consumertest.NewNop(), newTestPProcessor(nil))\n\trequire.NoError(t, err)\n\n\tassert.True(t, pp.Capabilities().MutatesData)\n\tassert.NoError(t, pp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, pp.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n\tassert.NoError(t, pp.Shutdown(context.Background()))\n}\n\nfunc TestNewProfiles_WithOptions(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tpp, err := NewProfiles(context.Background(), processortest.NewNopSettings(processortest.NopType), &testProfilesCfg, consumertest.NewNop(), newTestPProcessor(nil),\n\t\tWithStart(func(context.Context, component.Host) error { return want }),\n\t\tWithShutdown(func(context.Context) error { return want }),\n\t\tWithCapabilities(consumer.Capabilities{MutatesData: false}))\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, want, pp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.Equal(t, want, pp.Shutdown(context.Background()))\n\tassert.False(t, pp.Capabilities().MutatesData)\n}\n\nfunc TestNewProfiles_NilRequiredFields(t *testing.T) {\n\t_, err := NewProfiles(context.Background(), processortest.NewNopSettings(processortest.NopType), &testProfilesCfg, consumertest.NewNop(), nil)\n\tassert.Error(t, err)\n}\n\nfunc TestNewProfiles_ProcessProfileError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tpp, err := NewProfiles(context.Background(), processortest.NewNopSettings(processortest.NopType), &testProfilesCfg, consumertest.NewNop(), newTestPProcessor(want))\n\trequire.NoError(t, err)\n\tassert.Equal(t, want, pp.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n}\n\nfunc TestNewProfiles_ProcessProfilesErrSkipProcessingData(t *testing.T) {\n\tpp, err := NewProfiles(context.Background(), processortest.NewNopSettings(processortest.NopType), &testProfilesCfg, consumertest.NewNop(), newTestPProcessor(processorhelper.ErrSkipProcessingData))\n\trequire.NoError(t, err)\n\tassert.NoError(t, pp.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n}\n\nfunc newTestPProcessor(retError error) ProcessProfilesFunc {\n\treturn func(_ context.Context, pd pprofile.Profiles) (pprofile.Profiles, error) {\n\t\treturn pd, retError\n\t}\n}\n\nfunc TestProfilesConcurrency(t *testing.T) {\n\tprofilesFunc := func(_ context.Context, pd pprofile.Profiles) (pprofile.Profiles, error) {\n\t\treturn pd, nil\n\t}\n\n\tincomingProfiles := pprofile.NewProfiles()\n\tps := incomingProfiles.ResourceProfiles().AppendEmpty().ScopeProfiles().AppendEmpty().Profiles()\n\n\t// Add 3 profiles to the incoming\n\tps.AppendEmpty()\n\tps.AppendEmpty()\n\tps.AppendEmpty()\n\n\tpp, err := NewProfiles(context.Background(), processortest.NewNopSettings(processortest.NopType), &testProfilesCfg, consumertest.NewNop(), profilesFunc)\n\trequire.NoError(t, err)\n\tassert.NoError(t, pp.Start(context.Background(), componenttest.NewNopHost()))\n\n\tvar wg sync.WaitGroup\n\tfor range 10 {\n\t\twg.Go(func() {\n\t\t\tfor range 10000 {\n\t\t\t\tassert.NoError(t, pp.ConsumeProfiles(context.Background(), incomingProfiles))\n\t\t\t}\n\t\t})\n\t}\n\twg.Wait()\n\tassert.NoError(t, pp.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "processor/processortest/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "processor/processortest/go.mod",
    "content": "module go.opentelemetry.io/collector/processor/processortest\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componentstatus v0.148.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/processor v1.54.0\n\tgo.opentelemetry.io/collector/processor/xprocessor v0.148.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/component/componentstatus => ../../component/componentstatus\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/processor => ../../processor\n\nreplace go.opentelemetry.io/collector/processor/xprocessor => ../../processor/xprocessor\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "processor/processortest/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "processor/processortest/metadata.yaml",
    "content": "type: processor/processortest\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "processor/processortest/nop_processor.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processortest // import \"go.opentelemetry.io/collector/processor/processortest\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/xprocessor\"\n)\n\nvar NopType = component.MustNewType(\"nop\")\n\n// NewNopSettings returns a new nop settings for Create* functions with the given type.\nfunc NewNopSettings(typ component.Type) processor.Settings {\n\treturn processor.Settings{\n\t\tID:                component.NewID(typ),\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t\tBuildInfo:         component.NewDefaultBuildInfo(),\n\t}\n}\n\n// NewNopFactory returns a component.ProcessorFactory that constructs nop processors.\nfunc NewNopFactory() processor.Factory {\n\treturn xprocessor.NewFactory(\n\t\tNopType,\n\t\tfunc() component.Config { return &nopConfig{} },\n\t\txprocessor.WithTraces(createTraces, component.StabilityLevelStable),\n\t\txprocessor.WithMetrics(createMetrics, component.StabilityLevelStable),\n\t\txprocessor.WithLogs(createLogs, component.StabilityLevelStable),\n\t\txprocessor.WithProfiles(createProfiles, component.StabilityLevelAlpha),\n\t)\n}\n\nfunc createTraces(context.Context, processor.Settings, component.Config, consumer.Traces) (processor.Traces, error) {\n\treturn nopInstance, nil\n}\n\nfunc createMetrics(context.Context, processor.Settings, component.Config, consumer.Metrics) (processor.Metrics, error) {\n\treturn nopInstance, nil\n}\n\nfunc createLogs(context.Context, processor.Settings, component.Config, consumer.Logs) (processor.Logs, error) {\n\treturn nopInstance, nil\n}\n\nfunc createProfiles(context.Context, processor.Settings, component.Config, xconsumer.Profiles) (xprocessor.Profiles, error) {\n\treturn nopInstance, nil\n}\n\ntype nopConfig struct{}\n\nvar nopInstance = &nop{\n\tConsumer: consumertest.NewNop(),\n}\n\n// nop acts as a processor for testing purposes.\ntype nop struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumertest.Consumer\n}\n"
  },
  {
    "path": "processor/processortest/nop_processor_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processortest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/processor/xprocessor\"\n)\n\nfunc TestNewNopFactory(t *testing.T) {\n\tfactory := NewNopFactory()\n\trequire.NotNil(t, factory)\n\tassert.Equal(t, component.MustNewType(\"nop\"), factory.Type())\n\tcfg := factory.CreateDefaultConfig()\n\tassert.Equal(t, &nopConfig{}, cfg)\n\n\ttraces, err := factory.CreateTraces(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.Equal(t, consumer.Capabilities{MutatesData: false}, traces.Capabilities())\n\tassert.NoError(t, traces.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, traces.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n\tassert.NoError(t, traces.Shutdown(context.Background()))\n\n\tmetrics, err := factory.CreateMetrics(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.Equal(t, consumer.Capabilities{MutatesData: false}, metrics.Capabilities())\n\tassert.NoError(t, metrics.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, metrics.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n\tassert.NoError(t, metrics.Shutdown(context.Background()))\n\n\tlogs, err := factory.CreateLogs(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.Equal(t, consumer.Capabilities{MutatesData: false}, logs.Capabilities())\n\tassert.NoError(t, logs.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, logs.ConsumeLogs(context.Background(), plog.NewLogs()))\n\tassert.NoError(t, logs.Shutdown(context.Background()))\n\n\tprofiles, err := factory.(xprocessor.Factory).CreateProfiles(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.Equal(t, consumer.Capabilities{MutatesData: false}, profiles.Capabilities())\n\tassert.NoError(t, profiles.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, profiles.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n\tassert.NoError(t, profiles.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "processor/processortest/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processortest\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "processor/processortest/shutdown_verifier.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processortest // import \"go.opentelemetry.io/collector/processor/processortest\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/processor\"\n)\n\nfunc verifyTracesDoesNotProduceAfterShutdown(t *testing.T, factory processor.Factory, cfg component.Config) {\n\t// Create a proc and output its produce to a sink.\n\tnextSink := new(consumertest.TracesSink)\n\tproc, err := factory.CreateTraces(context.Background(), NewNopSettings(factory.Type()), cfg, nextSink)\n\tif errors.Is(err, pipeline.ErrSignalNotSupported) {\n\t\treturn\n\t}\n\trequire.NoError(t, err)\n\tassert.NoError(t, proc.Start(context.Background(), componenttest.NewNopHost()))\n\n\t// Send some traces to the proc.\n\tconst generatedCount = 10\n\tfor range generatedCount {\n\t\trequire.NoError(t, proc.ConsumeTraces(context.Background(), testdata.GenerateTraces(1)))\n\t}\n\n\t// Now shutdown the proc.\n\tassert.NoError(t, proc.Shutdown(context.Background()))\n\n\t// The Shutdown() is done. It means the proc must have sent everything we\n\t// gave it to the next sink.\n\tassert.Equal(t, generatedCount, nextSink.SpanCount())\n}\n\nfunc verifyLogsDoesNotProduceAfterShutdown(t *testing.T, factory processor.Factory, cfg component.Config) {\n\t// Create a proc and output its produce to a sink.\n\tnextSink := new(consumertest.LogsSink)\n\tproc, err := factory.CreateLogs(context.Background(), NewNopSettings(factory.Type()), cfg, nextSink)\n\tif errors.Is(err, pipeline.ErrSignalNotSupported) {\n\t\treturn\n\t}\n\trequire.NoError(t, err)\n\tassert.NoError(t, proc.Start(context.Background(), componenttest.NewNopHost()))\n\n\t// Send some logs to the proc.\n\tconst generatedCount = 10\n\tfor range generatedCount {\n\t\trequire.NoError(t, proc.ConsumeLogs(context.Background(), testdata.GenerateLogs(1)))\n\t}\n\n\t// Now shutdown the proc.\n\tassert.NoError(t, proc.Shutdown(context.Background()))\n\n\t// The Shutdown() is done. It means the proc must have sent everything we\n\t// gave it to the next sink.\n\tassert.Equal(t, generatedCount, nextSink.LogRecordCount())\n}\n\nfunc verifyMetricsDoesNotProduceAfterShutdown(t *testing.T, factory processor.Factory, cfg component.Config) {\n\t// Create a proc and output its produce to a sink.\n\tnextSink := new(consumertest.MetricsSink)\n\tproc, err := factory.CreateMetrics(context.Background(), NewNopSettings(factory.Type()), cfg, nextSink)\n\tif errors.Is(err, pipeline.ErrSignalNotSupported) {\n\t\treturn\n\t}\n\trequire.NoError(t, err)\n\tassert.NoError(t, proc.Start(context.Background(), componenttest.NewNopHost()))\n\n\t// Send some metrics to the proc. testdata.GenerateMetrics creates metrics with 2 data points each.\n\tconst generatedCount = 10\n\tfor range generatedCount {\n\t\trequire.NoError(t, proc.ConsumeMetrics(context.Background(), testdata.GenerateMetrics(1)))\n\t}\n\n\t// Now shutdown the proc.\n\tassert.NoError(t, proc.Shutdown(context.Background()))\n\n\t// The Shutdown() is done. It means the proc must have sent everything we\n\t// gave it to the next sink.\n\tassert.Equal(t, generatedCount*2, nextSink.DataPointCount())\n}\n\n// VerifyShutdown verifies the processor doesn't produce telemetry data after shutdown.\nfunc VerifyShutdown(t *testing.T, factory processor.Factory, cfg component.Config) {\n\tverifyTracesDoesNotProduceAfterShutdown(t, factory, cfg)\n\tverifyLogsDoesNotProduceAfterShutdown(t, factory, cfg)\n\tverifyMetricsDoesNotProduceAfterShutdown(t, factory, cfg)\n}\n"
  },
  {
    "path": "processor/processortest/shutdown_verifier_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processortest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/processor\"\n)\n\nfunc TestShutdownVerifier(t *testing.T) {\n\tf := processor.NewFactory(\n\t\tcomponent.MustNewType(\"passthrough\"),\n\t\tfunc() component.Config { return struct{}{} },\n\t\tprocessor.WithTraces(createPassthroughTraces, component.StabilityLevelStable),\n\t\tprocessor.WithMetrics(createPassthroughMetrics, component.StabilityLevelStable),\n\t\tprocessor.WithLogs(createPassthroughLogs, component.StabilityLevelStable),\n\t)\n\tVerifyShutdown(t, f, &struct{}{})\n}\n\nfunc TestShutdownVerifierLogsOnly(t *testing.T) {\n\tf := processor.NewFactory(\n\t\tcomponent.MustNewType(\"passthrough\"),\n\t\tfunc() component.Config { return struct{}{} },\n\t\tprocessor.WithLogs(createPassthroughLogs, component.StabilityLevelStable),\n\t)\n\tVerifyShutdown(t, f, &struct{}{})\n}\n\nfunc TestShutdownVerifierMetricsOnly(t *testing.T) {\n\tf := processor.NewFactory(\n\t\tcomponent.MustNewType(\"passthrough\"),\n\t\tfunc() component.Config { return struct{}{} },\n\t\tprocessor.WithMetrics(createPassthroughMetrics, component.StabilityLevelStable),\n\t)\n\tVerifyShutdown(t, f, &struct{}{})\n}\n\nfunc TestShutdownVerifierTracesOnly(t *testing.T) {\n\tf := processor.NewFactory(\n\t\tcomponent.MustNewType(\"passthrough\"),\n\t\tfunc() component.Config { return struct{}{} },\n\t\tprocessor.WithTraces(createPassthroughTraces, component.StabilityLevelStable),\n\t)\n\tVerifyShutdown(t, f, &struct{}{})\n}\n\ntype passthrough struct {\n\tprocessor.Traces\n\tnextLogs    consumer.Logs\n\tnextMetrics consumer.Metrics\n\tnextTraces  consumer.Traces\n}\n\nfunc (passthrough) Start(context.Context, component.Host) error {\n\treturn nil\n}\n\nfunc (passthrough) Shutdown(context.Context) error {\n\treturn nil\n}\n\nfunc (passthrough) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{}\n}\n\nfunc createPassthroughLogs(_ context.Context, _ processor.Settings, _ component.Config, logs consumer.Logs) (processor.Logs, error) {\n\treturn passthrough{\n\t\tnextLogs: logs,\n\t}, nil\n}\n\nfunc createPassthroughMetrics(_ context.Context, _ processor.Settings, _ component.Config, metrics consumer.Metrics) (processor.Metrics, error) {\n\treturn passthrough{\n\t\tnextMetrics: metrics,\n\t}, nil\n}\n\nfunc createPassthroughTraces(_ context.Context, _ processor.Settings, _ component.Config, traces consumer.Traces) (processor.Traces, error) {\n\treturn passthrough{\n\t\tnextTraces: traces,\n\t}, nil\n}\n\nfunc (p passthrough) ConsumeTraces(ctx context.Context, td ptrace.Traces) error {\n\treturn p.nextTraces.ConsumeTraces(ctx, td)\n}\n\nfunc (p passthrough) ConsumeMetrics(ctx context.Context, md pmetric.Metrics) error {\n\treturn p.nextMetrics.ConsumeMetrics(ctx, md)\n}\n\nfunc (p passthrough) ConsumeLogs(ctx context.Context, ld plog.Logs) error {\n\treturn p.nextLogs.ConsumeLogs(ctx, ld)\n}\n"
  },
  {
    "path": "processor/processortest/unhealthy_processor.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processortest // import \"go.opentelemetry.io/collector/processor/processortest\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componentstatus\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/processor\"\n)\n\n// NewUnhealthyProcessorFactory returns a processor.Factory that constructs nop processors.\nfunc NewUnhealthyProcessorFactory() processor.Factory {\n\treturn processor.NewFactory(\n\t\tcomponent.MustNewType(\"unhealthy\"),\n\t\tfunc() component.Config {\n\t\t\treturn &struct{}{}\n\t\t},\n\t\tprocessor.WithTraces(createUnhealthyTraces, component.StabilityLevelStable),\n\t\tprocessor.WithMetrics(createUnhealthyMetrics, component.StabilityLevelStable),\n\t\tprocessor.WithLogs(createUnhealthyLogs, component.StabilityLevelStable),\n\t)\n}\n\nfunc createUnhealthyTraces(_ context.Context, set processor.Settings, _ component.Config, _ consumer.Traces) (processor.Traces, error) {\n\treturn &unhealthy{\n\t\tConsumer:  consumertest.NewNop(),\n\t\ttelemetry: set.TelemetrySettings,\n\t}, nil\n}\n\nfunc createUnhealthyMetrics(_ context.Context, set processor.Settings, _ component.Config, _ consumer.Metrics) (processor.Metrics, error) {\n\treturn &unhealthy{\n\t\tConsumer:  consumertest.NewNop(),\n\t\ttelemetry: set.TelemetrySettings,\n\t}, nil\n}\n\nfunc createUnhealthyLogs(_ context.Context, set processor.Settings, _ component.Config, _ consumer.Logs) (processor.Logs, error) {\n\treturn &unhealthy{\n\t\tConsumer:  consumertest.NewNop(),\n\t\ttelemetry: set.TelemetrySettings,\n\t}, nil\n}\n\ntype unhealthy struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumertest.Consumer\n\ttelemetry component.TelemetrySettings\n}\n\nfunc (p unhealthy) Start(_ context.Context, host component.Host) error {\n\tgo func() {\n\t\tcomponentstatus.ReportStatus(host, componentstatus.NewEvent(componentstatus.StatusRecoverableError))\n\t}()\n\treturn nil\n}\n"
  },
  {
    "path": "processor/processortest/unhealthy_processor_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage processortest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nfunc TestNewUnhealthyProcessorFactory(t *testing.T) {\n\tfactory := NewUnhealthyProcessorFactory()\n\trequire.NotNil(t, factory)\n\tassert.Equal(t, component.MustNewType(\"unhealthy\"), factory.Type())\n\tcfg := factory.CreateDefaultConfig()\n\tassert.Equal(t, &struct{}{}, cfg)\n\n\ttraces, err := factory.CreateTraces(context.Background(), NewNopSettings(factory.Type()), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.Equal(t, consumer.Capabilities{MutatesData: false}, traces.Capabilities())\n\tassert.NoError(t, traces.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, traces.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n\tassert.NoError(t, traces.Shutdown(context.Background()))\n\n\tmetrics, err := factory.CreateMetrics(context.Background(), NewNopSettings(factory.Type()), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.Equal(t, consumer.Capabilities{MutatesData: false}, metrics.Capabilities())\n\tassert.NoError(t, metrics.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, metrics.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n\tassert.NoError(t, metrics.Shutdown(context.Background()))\n\n\tlogs, err := factory.CreateLogs(context.Background(), NewNopSettings(factory.Type()), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.Equal(t, consumer.Capabilities{MutatesData: false}, logs.Capabilities())\n\tassert.NoError(t, logs.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, logs.ConsumeLogs(context.Background(), plog.NewLogs()))\n\tassert.NoError(t, logs.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "processor/xprocessor/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "processor/xprocessor/go.mod",
    "content": "module go.opentelemetry.io/collector/processor/xprocessor\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/processor v1.54.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/rogpeppe/go-internal v1.14.1 // indirect\n\tgo.opentelemetry.io/collector/consumer v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/processor => ../\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "processor/xprocessor/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "processor/xprocessor/metadata.yaml",
    "content": "type: xprocessor\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  codeowners:\n    active:\n      - mx-psi\n      - dmathieu\n  stability:\n    alpha: [profiles]\n"
  },
  {
    "path": "processor/xprocessor/processor.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xprocessor // import \"go.opentelemetry.io/collector/processor/xprocessor\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/processor\"\n)\n\n// Factory is a component.Factory interface for processors.\n//\n// This interface cannot be directly implemented. Implementations must\n// use the NewFactory to implement it.\ntype Factory interface {\n\tprocessor.Factory\n\n\t// CreateProfiles creates a Profiles processor based on this config.\n\t// If the processor type does not support tracing or if the config is not valid,\n\t// an error will be returned instead.\n\tCreateProfiles(ctx context.Context, set processor.Settings, cfg component.Config, next xconsumer.Profiles) (Profiles, error)\n\n\t// ProfilesStability gets the stability level of the Profiles processor.\n\tProfilesStability() component.StabilityLevel\n}\n\n// Profiles is a processor that can consume profiles.\ntype Profiles interface {\n\tcomponent.Component\n\txconsumer.Profiles\n}\n\n// CreateProfilesFunc is the equivalent of Factory.CreateProfiles().\n// CreateProfilesFunc is the equivalent of Factory.CreateProfiles().\ntype CreateProfilesFunc func(context.Context, processor.Settings, component.Config, xconsumer.Profiles) (Profiles, error)\n\n// FactoryOption apply changes to ReceiverOptions.\ntype FactoryOption interface {\n\t// applyOption applies the option.\n\tapplyOption(o *factory)\n}\n\n// factoryOptionFunc is an ReceiverFactoryOption created through a function.\ntype factoryOptionFunc func(*factory)\n\nfunc (f factoryOptionFunc) applyOption(o *factory) {\n\tf(o)\n}\n\ntype factory struct {\n\tprocessor.Factory\n\tcomponentalias.TypeAliasHolder\n\topts                   []processor.FactoryOption\n\tcreateProfilesFunc     CreateProfilesFunc\n\tprofilesStabilityLevel component.StabilityLevel\n}\n\nfunc (f *factory) ProfilesStability() component.StabilityLevel {\n\treturn f.profilesStabilityLevel\n}\n\nfunc (f *factory) CreateProfiles(ctx context.Context, set processor.Settings, cfg component.Config, next xconsumer.Profiles) (Profiles, error) {\n\tif f.createProfilesFunc == nil {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\tif err := componentalias.ValidateComponentType(f.Factory, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.createProfilesFunc(ctx, set, cfg, next)\n}\n\n// WithTraces overrides the default \"error not supported\" implementation for CreateTraces and the default \"undefined\" stability level.\nfunc WithTraces(createTraces processor.CreateTracesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, processor.WithTraces(createTraces, sl))\n\t})\n}\n\n// WithMetrics overrides the default \"error not supported\" implementation for CreateMetrics and the default \"undefined\" stability level.\nfunc WithMetrics(createMetrics processor.CreateMetricsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, processor.WithMetrics(createMetrics, sl))\n\t})\n}\n\n// WithLogs overrides the default \"error not supported\" implementation for CreateLogs and the default \"undefined\" stability level.\nfunc WithLogs(createLogs processor.CreateLogsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, processor.WithLogs(createLogs, sl))\n\t})\n}\n\n// WithProfiles overrides the default \"error not supported\" implementation for CreateProfiles and the default \"undefined\" stability level.\nfunc WithProfiles(createProfiles CreateProfilesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.profilesStabilityLevel = sl\n\t\to.createProfilesFunc = createProfiles\n\t})\n}\n\n// WithDeprecatedTypeAlias configures a deprecated type alias for the processor. Only one alias is supported per processor.\n// When the alias is used in configuration, a deprecation warning is automatically logged.\nfunc WithDeprecatedTypeAlias(alias component.Type) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.SetDeprecatedAlias(alias)\n\t})\n}\n\n// NewFactory creates a wrapped processor.Factory with experimental capabilities.\nfunc NewFactory(cfgType component.Type, createDefaultConfig component.CreateDefaultConfigFunc, options ...FactoryOption) Factory {\n\tf := &factory{TypeAliasHolder: componentalias.NewTypeAliasHolder()}\n\tfor _, opt := range options {\n\t\topt.applyOption(f)\n\t}\n\tf.Factory = processor.NewFactory(cfgType, createDefaultConfig, f.opts...)\n\tf.Factory.(componentalias.TypeAliasHolder).SetDeprecatedAlias(f.DeprecatedAlias())\n\treturn f\n}\n"
  },
  {
    "path": "processor/xprocessor/processor_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xprocessor\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/internal\"\n)\n\nvar testID = component.MustNewID(\"test\")\n\nfunc TestNewFactoryWithProfiles(t *testing.T) {\n\ttestType := component.MustNewType(\"test\")\n\tdefaultCfg := struct{}{}\n\tfactory := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg },\n\t\tWithProfiles(createProfiles, component.StabilityLevelAlpha),\n\t)\n\tassert.Equal(t, testType, factory.Type())\n\tassert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())\n\n\tassert.Equal(t, component.StabilityLevelAlpha, factory.ProfilesStability())\n\t_, err := factory.CreateProfiles(context.Background(), processor.Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\n\twrongID := component.MustNewID(\"wrong\")\n\twrongIDErrStr := internal.ErrIDMismatch(wrongID, testType).Error()\n\t_, err = factory.CreateProfiles(context.Background(), processor.Settings{ID: wrongID}, &defaultCfg, consumertest.NewNop())\n\tassert.EqualError(t, err, wrongIDErrStr)\n}\n\nvar nopInstance = &nopProcessor{\n\tConsumer: consumertest.NewNop(),\n}\n\n// nopProcessor stores consumed traces and metrics for testing purposes.\ntype nopProcessor struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumertest.Consumer\n}\n\nfunc createProfiles(context.Context, processor.Settings, component.Config, xconsumer.Profiles) (Profiles, error) {\n\treturn nopInstance, nil\n}\n\nfunc TestNewFactoryWithDeprecatedAlias(t *testing.T) {\n\ttestType := component.MustNewType(\"newname\")\n\taliasType := component.MustNewType(\"oldname\")\n\tdefaultCfg := struct{}{}\n\n\tf := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg },\n\t\tWithProfiles(createProfiles, component.StabilityLevelAlpha),\n\t\tWithDeprecatedTypeAlias(aliasType),\n\t)\n\n\tassert.Equal(t, testType, f.Type())\n\tassert.Equal(t, aliasType, f.(*factory).Factory.(componentalias.TypeAliasHolder).DeprecatedAlias())\n\tassert.EqualValues(t, &defaultCfg, f.CreateDefaultConfig())\n\n\t_, err := f.CreateProfiles(context.Background(), processor.Settings{ID: component.MustNewID(\"newname\")}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = f.CreateProfiles(context.Background(), processor.Settings{ID: component.MustNewID(\"oldname\")}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = f.CreateProfiles(context.Background(), processor.Settings{ID: component.MustNewID(\"wrongname\")}, &defaultCfg, consumertest.NewNop())\n\trequire.Error(t, err)\n}\n"
  },
  {
    "path": "receiver/Makefile",
    "content": "include ../Makefile.Common\n"
  },
  {
    "path": "receiver/README.md",
    "content": "# General Information\n\nA receiver is how data gets into the OpenTelemetry Collector. Generally, a\nreceiver accepts data in a specified format, translates it into the internal\nformat and passes it to [processors](../processor/README.md) and [exporters](../exporter/README.md) defined \nin the applicable pipelines.\n\nThis repository hosts the following receiver available in traces, metrics\nand logs pipelines:\n\n- [OTLP Receiver](otlpreceiver/README.md)\n\nThe [contrib repository](https://github.com/open-telemetry/opentelemetry-collector-contrib)\nhas more receivers available in its builds.\n\n## Configuring Receivers\n\nReceivers are configured via YAML under the top-level `receivers` tag. There\nmust be at least one enabled receiver for a configuration to be considered\nvalid.\n\nThe following is a sample configuration for the `examplereceiver`.\n\n```yaml\nreceivers:\n  # Receiver 1.\n  # <receiver type>:\n  examplereceiver:\n    # <setting one>: <value one>\n    endpoint: 1.2.3.4:8080\n    # ...\n  # Receiver 2.\n  # <receiver type>/<name>:\n  examplereceiver/settings:\n    # <setting two>: <value two>\n    endpoint: 0.0.0.0:9211\n```\n\nA receiver instance is referenced by its full name in other parts of the config,\nsuch as in pipelines. A full name consists of the receiver type, '/' and the\nname appended to the receiver type in the configuration. All receiver full names\nmust be unique.\n\nFor the example above:\n\n- Receiver 1 has full name `examplereceiver`.\n- Receiver 2 has full name `examplereceiver/settings`.\n\nReceivers are enabled upon being added to a pipeline. For example:\n\n```yaml\nservice:\n  pipelines:\n    # Valid pipelines are: traces, metrics or logs\n    # Trace pipeline 1.\n    traces:\n      receivers: [examplereceiver, examplereceiver/settings]\n      processors: []\n      exporters: [exampleexporter]\n    # Trace pipeline 2.\n    traces/another:\n      receivers: [examplereceiver, examplereceiver/settings]\n      processors: []\n      exporters: [exampleexporter]\n```\n\n> At least one receiver must be enabled per pipeline to be a valid configuration.\n"
  },
  {
    "path": "receiver/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package receiver defines components that allow the Collector to receive metrics, traces and logs.\n//\n// A receiver receives data from a source (either from a remote source via network\n// or scrapes from a local host) and pushes the data to the pipelines it is attached\n// to by calling the nextConsumer.Consume*() function.\n//\n// # Error Handling\n//\n// The nextConsumer.Consume*() function may return an error to indicate that the data was not\n// accepted. This error should be handled as documented in the consumererror package.\n//\n// Depending on the error type, the receiver must indicate to the source from which it received the\n// data the type of error in a protocol-dependent way, if that is supported by the receiving protocol.\n// For example, a receiver for the OTLP/HTTP protocol would use the HTTP status codes as defined in\n// the OTLP specification.\n//\n// # Acknowledgment and Checkpointing\n//\n// The receivers that receive data via a network protocol that support acknowledgments\n// MUST follow this order of operations:\n//   - Receive data from some sender (typically from a network).\n//   - Push received data to the pipeline by calling nextConsumer.Consume*() function.\n//   - Acknowledge successful data receipt to the sender if Consume*() succeeded or\n//     return a failure to the sender if Consume*() returned an error.\n//\n// This ensures there are strong delivery guarantees once the data is acknowledged\n// by the Collector.\n//\n// Similarly, receivers that use checkpointing to remember the position of last processed\n// data (e.g. via storage extension) MUST store the checkpoint only AFTER the Consume*()\n// call returns.\npackage receiver // import \"go.opentelemetry.io/collector/receiver\"\n"
  },
  {
    "path": "receiver/example_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage receiver_test\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/receiver\"\n)\n\nvar typeStr = component.MustNewType(\"example\")\n\ntype exampleConfig struct {\n\tInterval time.Duration\n}\n\n// Reciver must implement the Start() and Shutdown() methods so the receiver type can be compliant\n// with the receiver.Traces interface.\ntype exampleReceiver struct {\n\thost         component.Host\n\tcancel       context.CancelFunc\n\tnextConsumer consumer.Traces\n\tconfig       exampleConfig\n}\n\nfunc (rcvr *exampleReceiver) Start(ctx context.Context, host component.Host) error {\n\trcvr.host = host\n\tctx, rcvr.cancel = context.WithCancel(ctx)\n\n\tgo func() {\n\t\tticker := time.NewTicker(rcvr.config.Interval)\n\t\tdefer ticker.Stop()\n\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-ticker.C:\n\t\t\t\t// Your receiver processing code should come here\n\t\t\t\terr := rcvr.nextConsumer.ConsumeTraces(ctx, generateTrace())\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Println(\"Error when consuming trace: %w\", err)\n\t\t\t\t}\n\t\t\tcase <-ctx.Done():\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t}()\n\n\treturn nil\n}\n\nfunc (rcvr *exampleReceiver) Shutdown(_ context.Context) error {\n\tif rcvr.cancel != nil {\n\t\trcvr.cancel()\n\t}\n\treturn nil\n}\n\nfunc generateTrace() ptrace.Traces {\n\ttraces := ptrace.NewTraces()\n\n\t// In reallity you may need to fetch or receive and transform\n\t// some telemetry data.\n\t// For this example we will just generate some dummy data\n\tresourceSpan := traces.ResourceSpans().AppendEmpty()\n\tresource := resourceSpan.Resource()\n\n\tattrs := resource.Attributes()\n\tattrs.PutInt(\"id\", 1)\n\n\tscopeSpans := resourceSpan.ScopeSpans().AppendEmpty()\n\tscopeSpans.Scope().SetName(\"example-system\")\n\tscopeSpans.Scope().SetVersion(\"v1.0\")\n\n\ttraceID := pcommon.TraceID([]byte(\"1\"))\n\tspanID := pcommon.SpanID([]byte(\"2\"))\n\n\tspan := scopeSpans.Spans().AppendEmpty()\n\tspan.SetTraceID(traceID)\n\tspan.SetSpanID(spanID)\n\tspan.SetName(\"Operation 1\")\n\tspan.SetKind(ptrace.SpanKindClient)\n\tspan.Status().SetCode(ptrace.StatusCodeOk)\n\tspan.SetStartTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\tspan.SetEndTimestamp(pcommon.NewTimestampFromTime(time.Now().Add(4 * time.Millisecond)))\n\n\t// Other resources and spans could also be added.\n\n\treturn traces\n}\n\nfunc createDefaultConfig() component.Config {\n\treturn &exampleConfig{\n\t\tInterval: time.Minute,\n\t}\n}\n\nfunc createExampleReceiver(_ context.Context, _ receiver.Settings,\n\tbaseCfg component.Config, consumer consumer.Traces,\n) (receiver.Traces, error) {\n\texampleCfg := baseCfg.(*exampleConfig)\n\n\trcvr := &exampleReceiver{\n\t\tnextConsumer: consumer,\n\t\tconfig:       *exampleCfg,\n\t}\n\n\treturn rcvr, nil\n}\n\nfunc NewFactory() receiver.Factory {\n\treturn receiver.NewFactory(\n\t\ttypeStr,\n\t\tcreateDefaultConfig,\n\t\treceiver.WithTraces(createExampleReceiver, component.StabilityLevelAlpha))\n}\n\nfunc Example() {\n\t// The NewFactory method can then be used on the Collector's initialization process\n\t// on your components.go file.\n\n\t// In this example we will just instantiate and print it's type\n\n\texampleReceiver := NewFactory()\n\tfmt.Println(exampleReceiver.Type())\n\n\t// Output:\n\t// example\n}\n"
  },
  {
    "path": "receiver/go.mod",
    "content": "module go.opentelemetry.io/collector/receiver\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../component\n\nreplace go.opentelemetry.io/collector/consumer => ../consumer\n\nreplace go.opentelemetry.io/collector/pdata => ../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../consumer/consumertest\n\nretract v0.76.0 // Depends on retracted pdata v1.0.0-rc10 module\n\nreplace go.opentelemetry.io/collector/pipeline => ../pipeline\n\nreplace go.opentelemetry.io/collector/featuregate => ../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../internal/componentalias\n"
  },
  {
    "path": "receiver/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "receiver/internal/err.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/receiver/internal\"\n\nimport (\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc ErrIDMismatch(id component.ID, typ component.Type) error {\n\treturn fmt.Errorf(\"component type mismatch: component ID %q does not have type %q\", id, typ)\n}\n"
  },
  {
    "path": "receiver/metadata.yaml",
    "content": "type: receiver\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "receiver/nopreceiver/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "receiver/nopreceiver/README.md",
    "content": "<!-- status autogenerated section -->\n# No-op Receiver\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [alpha]: profiles   |\n|               | [beta]: traces, metrics, logs   |\n| Distributions | [core], [contrib] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Areceiver%2Fnop%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Areceiver%2Fnop) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Areceiver%2Fnop%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Areceiver%2Fnop) |\n| [Code Owners](https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/main/CONTRIBUTING.md#becoming-a-code-owner)    | [@evan-bradley](https://www.github.com/evan-bradley) |\n\n[alpha]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#alpha\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n[core]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n<!-- end autogenerated section -->\n\nServes as a placeholder receiver in a pipeline. This can be useful if you want\nto e.g. start a Collector with only extensions enabled.\n\n## Getting Started\n\nAll that is required to enable the No-op receiver is to include it in the\nreceiver definitions. It takes no configuration.\n\n```yaml\nreceivers:\n  nop:\n```\n"
  },
  {
    "path": "receiver/nopreceiver/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\n// Package nopreceiver serves as a placeholder receiver.\npackage nopreceiver // import \"go.opentelemetry.io/collector/receiver/nopreceiver\"\n"
  },
  {
    "path": "receiver/nopreceiver/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage nopreceiver\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n)\n\nvar typ = component.MustNewType(\"nop\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct {\n\t\tcreateFn func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error)\n\t\tname     string\n\t}{\n\n\t\t{\n\t\t\tname: \"logs\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateLogs(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"traces\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateTraces(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"profiles\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.(xreceiver.Factory).CreateProfiles(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name+\"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\tt.Run(tt.name+\"-lifecycle\", func(t *testing.T) {\n\t\t\tfirstRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := newMdatagenNopHost()\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, firstRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, firstRcvr.Shutdown(context.Background()))\n\t\t\tsecondRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, secondRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, secondRcvr.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "receiver/nopreceiver/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage nopreceiver\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "receiver/nopreceiver/go.mod",
    "content": "module go.opentelemetry.io/collector/receiver/nopreceiver\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/receiver v1.54.0\n\tgo.opentelemetry.io/collector/receiver/receivertest v0.148.0\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/zap v1.27.1\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/receiver => ../\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../xreceiver\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../receivertest\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "receiver/nopreceiver/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "receiver/nopreceiver/internal/metadata/generated_logs.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/receiver\"\n)\n\n// LogsBuilder provides an interface for scrapers to report logs while taking care of all the transformations\n// required to produce log representation defined in metadata and user config.\ntype LogsBuilder struct {\n\tlogsBuffer       plog.Logs\n\tlogRecordsBuffer plog.LogRecordSlice\n\tbuildInfo        component.BuildInfo // contains version information.\n}\n\n// LogBuilderOption applies changes to default logs builder.\ntype LogBuilderOption interface {\n\tapply(*LogsBuilder)\n}\n\nfunc NewLogsBuilder(settings receiver.Settings) *LogsBuilder {\n\tlb := &LogsBuilder{\n\t\tlogsBuffer:       plog.NewLogs(),\n\t\tlogRecordsBuffer: plog.NewLogRecordSlice(),\n\t\tbuildInfo:        settings.BuildInfo,\n\t}\n\n\treturn lb\n}\n\n// ResourceLogsOption applies changes to provided resource logs.\ntype ResourceLogsOption interface {\n\tapply(plog.ResourceLogs)\n}\n\ntype resourceLogsOptionFunc func(plog.ResourceLogs)\n\nfunc (rlof resourceLogsOptionFunc) apply(rl plog.ResourceLogs) {\n\trlof(rl)\n}\n\n// WithLogsResource sets the provided resource on the emitted ResourceLogs.\n// It's recommended to use ResourceBuilder to create the resource.\nfunc WithLogsResource(res pcommon.Resource) ResourceLogsOption {\n\treturn resourceLogsOptionFunc(func(rl plog.ResourceLogs) {\n\t\tres.CopyTo(rl.Resource())\n\t})\n}\n\n// AppendLogRecord adds a log record to the logs builder.\nfunc (lb *LogsBuilder) AppendLogRecord(lr plog.LogRecord) {\n\tlr.MoveTo(lb.logRecordsBuffer.AppendEmpty())\n}\n\n// EmitForResource saves all the generated logs under a new resource and updates the internal state to be ready for\n// recording another set of log records as part of another resource. This function can be helpful when one scraper\n// needs to emit logs from several resources. Otherwise calling this function is not required,\n// just `Emit` function can be called instead.\n// Resource attributes should be provided as ResourceLogsOption arguments.\nfunc (lb *LogsBuilder) EmitForResource(options ...ResourceLogsOption) {\n\trl := plog.NewResourceLogs()\n\tils := rl.ScopeLogs().AppendEmpty()\n\tils.Scope().SetName(ScopeName)\n\tils.Scope().SetVersion(lb.buildInfo.Version)\n\n\tfor _, op := range options {\n\t\top.apply(rl)\n\t}\n\n\tif lb.logRecordsBuffer.Len() > 0 {\n\t\tlb.logRecordsBuffer.MoveAndAppendTo(ils.LogRecords())\n\t\tlb.logRecordsBuffer = plog.NewLogRecordSlice()\n\t}\n\n\tif ils.LogRecords().Len() > 0 {\n\t\trl.MoveTo(lb.logsBuffer.ResourceLogs().AppendEmpty())\n\t}\n}\n\n// Emit returns all the logs accumulated by the logs builder and updates the internal state to be ready for\n// recording another set of logs. This function will be responsible for applying all the transformations required to\n// produce logs representation defined in metadata and user config.\nfunc (lb *LogsBuilder) Emit(options ...ResourceLogsOption) plog.Logs {\n\tlb.EmitForResource(options...)\n\tlogs := lb.logsBuffer\n\tlb.logsBuffer = plog.NewLogs()\n\treturn logs\n}\n"
  },
  {
    "path": "receiver/nopreceiver/internal/metadata/generated_logs_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\nfunc TestLogsBuilderAppendLogRecord(t *testing.T) {\n\tobservedZapCore, _ := observer.New(zap.WarnLevel)\n\tsettings := receivertest.NewNopSettings(receivertest.NopType)\n\tsettings.Logger = zap.New(observedZapCore)\n\tlb := NewLogsBuilder(settings)\n\n\tres := pcommon.NewResource()\n\n\t// append the first log record\n\tlr := plog.NewLogRecord()\n\tlr.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\tlr.Attributes().PutStr(\"type\", \"log\")\n\tlr.Body().SetStr(\"the first log record\")\n\n\t// append the second log record\n\tlr2 := plog.NewLogRecord()\n\tlr2.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\tlr2.Attributes().PutStr(\"type\", \"event\")\n\tlr2.Body().SetStr(\"the second log record\")\n\n\tlb.AppendLogRecord(lr)\n\tlb.AppendLogRecord(lr2)\n\n\tlogs := lb.Emit(WithLogsResource(res))\n\tassert.Equal(t, 1, logs.ResourceLogs().Len())\n\n\trl := logs.ResourceLogs().At(0)\n\tassert.Equal(t, 1, rl.ScopeLogs().Len())\n\n\tsl := rl.ScopeLogs().At(0)\n\tassert.Equal(t, ScopeName, sl.Scope().Name())\n\tassert.Equal(t, lb.buildInfo.Version, sl.Scope().Version())\n\n\tassert.Equal(t, 2, sl.LogRecords().Len())\n\n\tattrVal, ok := sl.LogRecords().At(0).Attributes().Get(\"type\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"log\", attrVal.Str())\n\n\tassert.Equal(t, pcommon.ValueTypeStr, sl.LogRecords().At(0).Body().Type())\n\tassert.Equal(t, \"the first log record\", sl.LogRecords().At(0).Body().Str())\n\n\tattrVal, ok = sl.LogRecords().At(1).Attributes().Get(\"type\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"event\", attrVal.Str())\n\n\tassert.Equal(t, pcommon.ValueTypeStr, sl.LogRecords().At(1).Body().Type())\n\tassert.Equal(t, \"the second log record\", sl.LogRecords().At(1).Body().Str())\n}\n"
  },
  {
    "path": "receiver/nopreceiver/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"nop\")\n\tScopeName = \"go.opentelemetry.io/collector/receiver/nopreceiver\"\n)\n\nconst (\n\tProfilesStability = component.StabilityLevelAlpha\n\tTracesStability   = component.StabilityLevelBeta\n\tMetricsStability  = component.StabilityLevelBeta\n\tLogsStability     = component.StabilityLevelBeta\n)\n"
  },
  {
    "path": "receiver/nopreceiver/metadata.yaml",
    "content": "display_name: No-op Receiver\ntype: nop\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  codeowners:\n    active:\n      - evan-bradley\n  class: receiver\n  stability:\n    beta: [traces, metrics, logs]\n    alpha: [profiles]\n  distributions: [core, contrib]\n"
  },
  {
    "path": "receiver/nopreceiver/nop_receiver.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage nopreceiver // import \"go.opentelemetry.io/collector/receiver/nopreceiver\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/nopreceiver/internal/metadata\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n)\n\n// NewFactory returns a receiver.Factory that constructs nop receivers.\nfunc NewFactory() xreceiver.Factory {\n\treturn xreceiver.NewFactory(\n\t\tmetadata.Type,\n\t\tfunc() component.Config { return &struct{}{} },\n\t\txreceiver.WithTraces(createTraces, metadata.TracesStability),\n\t\txreceiver.WithMetrics(createMetrics, metadata.MetricsStability),\n\t\txreceiver.WithProfiles(createProfiles, metadata.ProfilesStability),\n\t\txreceiver.WithLogs(createLogs, metadata.LogsStability))\n}\n\nfunc createTraces(context.Context, receiver.Settings, component.Config, consumer.Traces) (receiver.Traces, error) {\n\treturn nopInstance, nil\n}\n\nfunc createMetrics(context.Context, receiver.Settings, component.Config, consumer.Metrics) (receiver.Metrics, error) {\n\treturn nopInstance, nil\n}\n\nfunc createLogs(context.Context, receiver.Settings, component.Config, consumer.Logs) (receiver.Logs, error) {\n\treturn nopInstance, nil\n}\n\nfunc createProfiles(context.Context, receiver.Settings, component.Config, xconsumer.Profiles) (xreceiver.Profiles, error) {\n\treturn nopInstance, nil\n}\n\nvar nopInstance = &nopReceiver{}\n\ntype nopReceiver struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n}\n"
  },
  {
    "path": "receiver/nopreceiver/nop_receiver_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage nopreceiver // import \"go.opentelemetry.io/collector/receiver/nopreceiver\"\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\nfunc TestNewNopFactory(t *testing.T) {\n\tfactory := NewFactory()\n\trequire.NotNil(t, factory)\n\tassert.Equal(t, component.MustNewType(\"nop\"), factory.Type())\n\tcfg := factory.CreateDefaultConfig()\n\tassert.Equal(t, &struct{}{}, cfg)\n\n\ttraces, err := factory.CreateTraces(context.Background(), receivertest.NewNopSettings(receivertest.NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, traces.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, traces.Shutdown(context.Background()))\n\n\tmetrics, err := factory.CreateMetrics(context.Background(), receivertest.NewNopSettings(receivertest.NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, metrics.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, metrics.Shutdown(context.Background()))\n\n\tlogs, err := factory.CreateLogs(context.Background(), receivertest.NewNopSettings(receivertest.NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, logs.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, logs.Shutdown(context.Background()))\n\n\tprofiles, err := factory.CreateProfiles(context.Background(), receivertest.NewNopSettings(receivertest.NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, profiles.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, profiles.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "receiver/otlpreceiver/README.md",
    "content": "<!-- status autogenerated section -->\n# OTLP Receiver\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [alpha]: profiles   |\n|               | [stable]: traces, metrics, logs   |\n| Distributions | [core], [contrib], [k8s], [otlp] |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Areceiver%2Fotlp%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Areceiver%2Fotlp) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Areceiver%2Fotlp%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Areceiver%2Fotlp) |\n\n[alpha]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#alpha\n[stable]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#stable\n[core]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n[k8s]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\n[otlp]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-otlp\n<!-- end autogenerated section -->\n\nReceives data via gRPC or HTTP using [OTLP](\nhttps://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/protocol/otlp.md)\nformat.\n\n## Getting Started\n\nAll that is required to enable the OTLP receiver is to include it in the\nreceiver definitions. A protocol can be disabled by simply not specifying it in\nthe list of protocols.\n\n```yaml\nreceivers:\n  otlp:\n    protocols:\n      grpc:\n      http:\n```\n\nThe following settings are configurable:\n\n- `endpoint` (default = localhost:4317 for grpc protocol, localhost:4318 http protocol):\n  host:port to which the receiver is going to receive data. The valid syntax is\n  described at https://github.com/grpc/grpc/blob/master/doc/naming.md. See our \n  [security best practices doc](https://opentelemetry.io/docs/security/config-best-practices/#protect-against-denial-of-service-attacks)\n  to understand how to set the endpoint in different environments.\n\n## Advanced Configuration\n\nSeveral helper files are leveraged to provide additional capabilities automatically:\n\n- [gRPC settings](https://github.com/open-telemetry/opentelemetry-collector/blob/main/config/configgrpc/README.md) including CORS\n- [HTTP settings](https://github.com/open-telemetry/opentelemetry-collector/blob/main/config/confighttp/README.md)\n- [TLS and mTLS settings](https://github.com/open-telemetry/opentelemetry-collector/blob/main/config/configtls/README.md)\n- [Auth settings](https://github.com/open-telemetry/opentelemetry-collector/blob/main/config/configauth/README.md)\n\n## Writing with HTTP/JSON\n\nThe OTLP receiver can receive trace export calls via HTTP/JSON in addition to\ngRPC. The HTTP/JSON address is the same as gRPC as the protocol is recognized\nand processed accordingly. Note the serialization format needs to be [OTLP JSON](https://opentelemetry.io/docs/specs/otlp/#json-protobuf-encoding).\n\nThe HTTP/JSON configuration also provides `traces_url_path`,\n`metrics_url_path`, `logs_url_path`, and `profiles_url_path` configurations to\nallow the URL paths that signal data needs to be sent to be modified per signal\ntype.  These default to `/v1/traces`, `/v1/metrics`, `/v1/logs`, and\n`/v1/profiles` respectively.\n\nTo write traces with HTTP/JSON, `POST` to `[address]/[traces_url_path]` for\ntraces, to `[address]/[metrics_url_path]` for metrics, to\n`[address]/[logs_url_path]` for logs, and to `[address]/[profiles_url_path]` for\nprofiles.\nThe default port is `4318`.  When using the `otlphttpexporter` peer to\ncommunicate with this component, use the `traces_endpoint`,\n`metrics_endpoint`, `logs_endpoint`, and `profiles_endpoint` settings in the\n`otlphttpexporter` to set the proper URL to match the address and URL signal\npath on the `otlpreceiver`.\n\n### CORS (Cross-origin resource sharing)\n\nThe HTTP/JSON endpoint can also optionally configure [CORS][cors] under `cors:`.\nSpecify what origins (or wildcard patterns) to allow requests from as\n`allowed_origins`. To allow additional request headers outside of the [default\nsafelist][cors-headers], set `allowed_headers`. Browsers can be instructed to\n[cache][cors-max-age] responses to preflight requests by setting `max_age`.\n\n[cors]: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS\n[cors-headers]: https://developer.mozilla.org/en-US/docs/Glossary/CORS-safelisted_request_header\n[cors-max-age]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Max-Age\n\n```yaml\nreceivers:\n  otlp:\n    protocols:\n      http:\n        endpoint: \"localhost:4318\"\n        cors:\n          allowed_origins:\n            - http://test.com\n            # Origins can have wildcards with *, use * by itself to match any origin.\n            - https://*.example.com\n          allowed_headers:\n            - Example-Header\n          max_age: 7200\n```\n\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n[core]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n"
  },
  {
    "path": "receiver/otlpreceiver/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlpreceiver // import \"go.opentelemetry.io/collector/receiver/otlpreceiver\"\n\nimport (\n\t\"encoding\"\n\t\"errors\"\n\t\"fmt\"\n\t\"net/url\"\n\t\"path\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configgrpc\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n)\n\ntype SanitizedURLPath string\n\nvar _ encoding.TextUnmarshaler = (*SanitizedURLPath)(nil)\n\nfunc (s *SanitizedURLPath) UnmarshalText(text []byte) error {\n\tu, err := url.Parse(string(text))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"invalid HTTP URL path set for signal: %w\", err)\n\t}\n\n\tif !path.IsAbs(u.Path) {\n\t\tu.Path = \"/\" + u.Path\n\t}\n\n\t*s = SanitizedURLPath(u.Path)\n\treturn nil\n}\n\ntype HTTPConfig struct {\n\tServerConfig confighttp.ServerConfig `mapstructure:\",squash\"`\n\n\t// The URL path to receive traces on. If omitted \"/v1/traces\" will be used.\n\tTracesURLPath SanitizedURLPath `mapstructure:\"traces_url_path,omitempty\"`\n\n\t// The URL path to receive metrics on. If omitted \"/v1/metrics\" will be used.\n\tMetricsURLPath SanitizedURLPath `mapstructure:\"metrics_url_path,omitempty\"`\n\n\t// The URL path to receive logs on. If omitted \"/v1/logs\" will be used.\n\tLogsURLPath SanitizedURLPath `mapstructure:\"logs_url_path,omitempty\"`\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// Protocols is the configuration for the supported protocols.\ntype Protocols struct {\n\tGRPC configoptional.Optional[configgrpc.ServerConfig] `mapstructure:\"grpc\"`\n\tHTTP configoptional.Optional[HTTPConfig]              `mapstructure:\"http\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// Config defines configuration for OTLP receiver.\ntype Config struct {\n\t// Protocols is the configuration for the supported protocols, currently gRPC and HTTP (Proto and JSON).\n\tProtocols `mapstructure:\"protocols\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\nvar _ component.Config = (*Config)(nil)\n\n// Validate checks the receiver configuration is valid\nfunc (cfg *Config) Validate() error {\n\tif !cfg.GRPC.HasValue() && !cfg.HTTP.HasValue() {\n\t\treturn errors.New(\"must specify at least one protocol when using the OTLP receiver\")\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/config.md",
    "content": "# \"otlp\" Receiver Reference\n\nConfig defines configuration for OTLP receiver.\n\n\n### Config\n\n| Name      | Type                                              | Default    | Docs                                                                                                  |\n|-----------|---------------------------------------------------|------------|-------------------------------------------------------------------------------------------------------|\n| protocols | [otlpreceiver-Protocols](#otlpreceiver-protocols) | <no value> | Protocols is the configuration for the supported protocols, currently gRPC and HTTP (Proto and JSON). |\n\n### otlpreceiver-Protocols\n\n| Name | Type                                                            | Default    | Docs                                                                        |\n|------|-----------------------------------------------------------------|------------|-----------------------------------------------------------------------------|\n| grpc | [configgrpc-GRPCServerSettings](#configgrpc-grpcserversettings) | <no value> | GRPCServerSettings defines common settings for a gRPC server configuration. |\n| http | [confighttp-HTTPServerSettings](#confighttp-httpserversettings) | <no value> | HTTPServerSettings defines settings for creating an HTTP server.            |\n\n### configgrpc-GRPCServerSettings\n\n| Name                   | Type                                                                  | Default      | Docs                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |\n|------------------------|-----------------------------------------------------------------------|--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| endpoint               | string                                                                | localhost:4317 | Endpoint configures the address for this network connection. For TCP and UDP networks, the address has the form \"host:port\". The host must be a literal IP address, or a host name that can be resolved to IP addresses. The port must be a literal port number or a service name. If the host is a literal IPv6 address it must be enclosed in square brackets, as in \"[2001:db8::1]:80\" or \"[fe80::1%zone]:80\". The zone specifies the scope of the literal IPv6 address as defined in RFC 4007. |\n| transport              | string                                                                | tcp          | Transport to use. Known protocols are \"tcp\", \"tcp4\" (IPv4-only), \"tcp6\" (IPv6-only), \"udp\", \"udp4\" (IPv4-only), \"udp6\" (IPv6-only), \"ip\", \"ip4\" (IPv4-only), \"ip6\" (IPv6-only), \"unix\", \"unixgram\" and \"unixpacket\".                                                                                                                                                                                                                                                                               |\n| tls                    | [configtls-TLSServerSetting](#configtls-tlsserversetting)             | <no value>   | Configures the protocol to use TLS. The default value is nil, which will cause the protocol to not use TLS.                                                                                                                                                                                                                                                                                                                                                                                        |\n| max_recv_msg_size_mib  | uint64                                                                | <no value>   | MaxRecvMsgSizeMiB sets the maximum size (in MiB) of messages accepted by the server.                                                                                                                                                                                                                                                                                                                                                                                                               |\n| max_concurrent_streams | uint32                                                                | <no value>   | MaxConcurrentStreams sets the limit on the number of concurrent streams to each ServerTransport. It has effect only for streaming RPCs.                                                                                                                                                                                                                                                                                                                                                            |\n| read_buffer_size       | int                                                                   | 524288       | ReadBufferSize for gRPC server. See grpc.ReadBufferSize (https://godoc.org/google.golang.org/grpc#ReadBufferSize).                                                                                                                                                                                                                                                                                                                                                                                 |\n| write_buffer_size      | int                                                                   | <no value>   | WriteBufferSize for gRPC server. See grpc.WriteBufferSize (https://godoc.org/google.golang.org/grpc#WriteBufferSize).                                                                                                                                                                                                                                                                                                                                                                              |\n| keepalive              | [configgrpc-KeepaliveServerConfig](#configgrpc-keepaliveserverconfig) | <no value>   | Keepalive anchor for all the settings related to keepalive.                                                                                                                                                                                                                                                                                                                                                                                                                                        |\n| auth                   | [configauth-Authentication](#configauth-authentication)               | <no value>   | Auth for this receiver                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |\n\n### configtls-TLSServerSetting\n\n| Name           | Type   | Default    | Docs                                                                                                                                                                                                                                                             |\n|----------------|--------|------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| ca_file        | string | <no value> | Path to the CA cert. For a client this verifies the server certificate. For a server this verifies client certificates. If empty uses system root CA. (optional)                                                                                                 |\n| cert_file      | string | <no value> | Path to the TLS cert to use for TLS required connections. (optional)                                                                                                                                                                                             |\n| key_file       | string | <no value> | Path to the TLS key to use for TLS required connections. (optional)                                                                                                                                                                                              |\n| client_ca_file | string | <no value> | Path to the TLS cert to use by the server to verify a client certificate. (optional) This sets the ClientCAs and ClientAuth to RequireAndVerifyClientCert in the TLSConfig. Please refer to https://godoc.org/crypto/tls#Config for more information. (optional) |\n\n### configgrpc-KeepaliveServerConfig\n\n| Name               | Type                                                                            | Default    | Docs                                                                                                                                                                                                                                                                          |\n|--------------------|---------------------------------------------------------------------------------|------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| server_parameters  | [configgrpc-KeepaliveServerParameters](#configgrpc-keepaliveserverparameters)   | <no value> | KeepaliveServerParameters allow configuration of the keepalive.ServerParameters. The same default values as keepalive.ServerParameters are applicable and get applied by the server. See https://godoc.org/google.golang.org/grpc/keepalive#ServerParameters for details.     |\n| enforcement_policy | [configgrpc-KeepaliveEnforcementPolicy](#configgrpc-keepaliveenforcementpolicy) | <no value> | KeepaliveEnforcementPolicy allow configuration of the keepalive.EnforcementPolicy. The same default values as keepalive.EnforcementPolicy are applicable and get applied by the server. See https://godoc.org/google.golang.org/grpc/keepalive#EnforcementPolicy for details. |\n\n### configgrpc-KeepaliveServerParameters\n\n| Name                     | Type                            | Default    | Docs |\n|--------------------------|---------------------------------|------------|------|\n| max_connection_idle      | [time-Duration](#time-duration) | <no value> |      |\n| max_connection_age       | [time-Duration](#time-duration) | <no value> |      |\n| max_connection_age_grace | [time-Duration](#time-duration) | <no value> |      |\n| time                     | [time-Duration](#time-duration) | <no value> |      |\n| timeout                  | [time-Duration](#time-duration) | <no value> |      |\n\n### configgrpc-KeepaliveEnforcementPolicy\n\n| Name                  | Type                            | Default    | Docs |\n|-----------------------|---------------------------------|------------|------|\n| min_time              | [time-Duration](#time-duration) | <no value> |      |\n| permit_without_stream | bool                            | <no value> |      |\n\n### configauth-Authentication\n\n| Name          | Type   | Default    | Docs                                                                                                           |\n|---------------|--------|------------|----------------------------------------------------------------------------------------------------------------|\n| authenticator | string | <no value> | AuthenticatorName specifies the name of the extension to use in order to authenticate the incoming data point. |\n\n### confighttp-HTTPServerSettings\n\n| Name                  | Type                                                      | Default      | Docs                                                                                                                                    |\n|-----------------------|-----------------------------------------------------------|--------------|-----------------------------------------------------------------------------------------------------------------------------------------|\n| endpoint              | string                                                    | localhost:4318 | Endpoint configures the listening address for the server.                                                                               |\n| tls                   | [configtls-TLSServerSetting](#configtls-tlsserversetting) | <no value>   | TLSSetting struct exposes TLS client configuration.                                                                                     |\n| cors                  | [confighttp-CORSConfig](#confighttp-corsconfig)           | <no value>   | CORSConfig configures a receiver for HTTP cross-origin resource sharing (CORS).                                                       |\n| max_request_body_size | int                                                       | 20971520     | MaxRequestBodySize configures the maximum allowed body size in bytes for a single request. The default `20971520` means 20MiB           |\n\n### confighttp-CORSConfig\n\n| Name            | Type     | Default    | Docs                                                                                                                                                                                                                                                                                       |\n|-----------------|----------|------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| allowed_origins | []string | <no value> | AllowedOrigins sets the allowed values of the Origin header for HTTP/JSON requests to an OTLP receiver. An origin may contain a wildcard (`*`) to replace 0 or more characters (e.g., `\"https://*.example.com\"`, or `\"*\"` to allow any origin).                                            |\n| allowed_headers | []string | <no value> | AllowedHeaders sets what headers will be allowed in CORS requests. The Accept, Accept-Language, Content-Type, and Content-Language headers are implicitly allowed. If no headers are listed, X-Requested-With will also be accepted by default. Include `\"*\"` to allow any request header. |\n| max_age         | int      | <no value> | MaxAge sets the value of the Access-Control-Max-Age response header.  Set it to the number of seconds that browsers should cache a CORS preflight response for.                                                                                                                            |\n\n### configtls-TLSServerSetting\n\n| Name           | Type   | Default    | Docs                                                                                                                                                                                                                                                             |\n|----------------|--------|------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|\n| ca_file        | string | <no value> | Path to the CA cert. For a client this verifies the server certificate. For a server this verifies client certificates. If empty uses system root CA. (optional)                                                                                                 |\n| cert_file      | string | <no value> | Path to the TLS cert to use for TLS required connections. (optional)                                                                                                                                                                                             |\n| key_file       | string | <no value> | Path to the TLS key to use for TLS required connections. (optional)                                                                                                                                                                                              |\n| client_ca_file | string | <no value> | Path to the TLS cert to use by the server to verify a client certificate. (optional) This sets the ClientCAs and ClientAuth to RequireAndVerifyClientCert in the TLSConfig. Please refer to https://godoc.org/crypto/tls#Config for more information. (optional) |\n\n### time-Duration \nAn optionally signed sequence of decimal numbers, each with a unit suffix, such as `300ms`, `-1.5h`, or `2h45m`. Valid time units are `ns`, `us`, `ms`, `s`, `m`, `h`.\n"
  },
  {
    "path": "receiver/otlpreceiver/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlpreceiver\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configauth\"\n\t\"go.opentelemetry.io/collector/config/configgrpc\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n)\n\nfunc TestUnmarshalDefaultConfig(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"default.yaml\"))\n\trequire.NoError(t, err)\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\texpectedCfg := factory.CreateDefaultConfig().(*Config)\n\texpectedCfg.GRPC.GetOrInsertDefault()\n\texpectedCfg.HTTP.GetOrInsertDefault()\n\tassert.Equal(t, expectedCfg, cfg)\n}\n\nfunc TestUnmarshalConfigOnlyGRPC(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"only_grpc.yaml\"))\n\trequire.NoError(t, err)\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\n\tdefaultOnlyGRPC := factory.CreateDefaultConfig().(*Config)\n\tdefaultOnlyGRPC.GRPC.GetOrInsertDefault()\n\tassert.Equal(t, defaultOnlyGRPC, cfg)\n}\n\nfunc TestUnmarshalConfigOnlyHTTP(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"only_http.yaml\"))\n\trequire.NoError(t, err)\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\n\tdefaultOnlyHTTP := factory.CreateDefaultConfig().(*Config)\n\tdefaultOnlyHTTP.HTTP.GetOrInsertDefault()\n\tassert.Equal(t, defaultOnlyHTTP, cfg)\n}\n\nfunc TestUnmarshalConfigOnlyHTTPNull(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"only_http_null.yaml\"))\n\trequire.NoError(t, err)\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\n\tdefaultOnlyHTTP := factory.CreateDefaultConfig().(*Config)\n\tdefaultOnlyHTTP.HTTP.GetOrInsertDefault()\n\tassert.Equal(t, defaultOnlyHTTP, cfg)\n}\n\nfunc TestUnmarshalConfigOnlyHTTPEmptyMap(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"only_http_empty_map.yaml\"))\n\trequire.NoError(t, err)\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\n\tdefaultOnlyHTTP := factory.CreateDefaultConfig().(*Config)\n\tdefaultOnlyHTTP.HTTP.GetOrInsertDefault()\n\tassert.Equal(t, defaultOnlyHTTP, cfg)\n}\n\nfunc TestUnmarshalConfig(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"config.yaml\"))\n\trequire.NoError(t, err)\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\tassert.Equal(t,\n\t\t&Config{\n\t\t\tProtocols: Protocols{\n\t\t\t\tGRPC: configoptional.Some(configgrpc.ServerConfig{\n\t\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\t\tEndpoint:  \"localhost:4317\",\n\t\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t\t},\n\t\t\t\t\tTLS: configoptional.Some(configtls.ServerConfig{\n\t\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\t\tCertFile: \"test.crt\",\n\t\t\t\t\t\t\tKeyFile:  \"test.key\",\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t\tMaxRecvMsgSizeMiB:    32,\n\t\t\t\t\tMaxConcurrentStreams: 16,\n\t\t\t\t\tReadBufferSize:       1024,\n\t\t\t\t\tWriteBufferSize:      1024,\n\t\t\t\t\tKeepalive: configoptional.Some(configgrpc.KeepaliveServerConfig{\n\t\t\t\t\t\tServerParameters: configoptional.Some(configgrpc.KeepaliveServerParameters{\n\t\t\t\t\t\t\tMaxConnectionIdle:     11 * time.Second,\n\t\t\t\t\t\t\tMaxConnectionAge:      12 * time.Second,\n\t\t\t\t\t\t\tMaxConnectionAgeGrace: 13 * time.Second,\n\t\t\t\t\t\t\tTime:                  30 * time.Second,\n\t\t\t\t\t\t\tTimeout:               5 * time.Second,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tEnforcementPolicy: configoptional.Some(configgrpc.KeepaliveEnforcementPolicy{\n\t\t\t\t\t\t\tMinTime:             10 * time.Second,\n\t\t\t\t\t\t\tPermitWithoutStream: true,\n\t\t\t\t\t\t}),\n\t\t\t\t\t}),\n\t\t\t\t}),\n\t\t\t\tHTTP: configoptional.Some(HTTPConfig{\n\t\t\t\t\tServerConfig: confighttp.ServerConfig{\n\t\t\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\t\t\tEndpoint:  \"localhost:4318\",\n\t\t\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tAuth: configoptional.Some(confighttp.AuthConfig{\n\t\t\t\t\t\t\tConfig: configauth.Config{\n\t\t\t\t\t\t\t\tAuthenticatorID: component.MustNewID(\"test\"),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tTLS: configoptional.Some(configtls.ServerConfig{\n\t\t\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\t\t\tCertFile: \"test.crt\",\n\t\t\t\t\t\t\t\tKeyFile:  \"test.key\",\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tCORS: configoptional.Some(confighttp.CORSConfig{\n\t\t\t\t\t\t\tAllowedOrigins: []string{\"https://*.test.com\", \"https://test.com\"},\n\t\t\t\t\t\t\tMaxAge:         7200,\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tKeepAlivesEnabled: true,\n\t\t\t\t\t},\n\t\t\t\t\tTracesURLPath:  \"/traces\",\n\t\t\t\t\tMetricsURLPath: \"/v2/metrics\",\n\t\t\t\t\tLogsURLPath:    \"/log/ingest\",\n\t\t\t\t}),\n\t\t\t},\n\t\t}, cfg)\n}\n\nfunc TestUnmarshalConfigUnix(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"uds.yaml\"))\n\trequire.NoError(t, err)\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\tassert.Equal(t,\n\t\t&Config{\n\t\t\tProtocols: Protocols{\n\t\t\t\tGRPC: configoptional.Some(configgrpc.ServerConfig{\n\t\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\t\tEndpoint:  \"/tmp/grpc_otlp.sock\",\n\t\t\t\t\t\tTransport: confignet.TransportTypeUnix,\n\t\t\t\t\t},\n\t\t\t\t\tReadBufferSize: 512 * 1024,\n\t\t\t\t\tKeepalive:      configoptional.Some(configgrpc.NewDefaultKeepaliveServerConfig()),\n\t\t\t\t}),\n\t\t\t\tHTTP: configoptional.Some(HTTPConfig{\n\t\t\t\t\tServerConfig: confighttp.ServerConfig{\n\t\t\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\t\t\tEndpoint:  \"/tmp/http_otlp.sock\",\n\t\t\t\t\t\t\tTransport: confignet.TransportTypeUnix,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tKeepAlivesEnabled: true,\n\t\t\t\t\t},\n\t\t\t\t\tTracesURLPath:  defaultTracesURLPath,\n\t\t\t\t\tMetricsURLPath: defaultMetricsURLPath,\n\t\t\t\t\tLogsURLPath:    defaultLogsURLPath,\n\t\t\t\t}),\n\t\t\t},\n\t\t}, cfg)\n}\n\n// cspell:ignore htttp\nfunc TestUnmarshalConfigTypoDefaultProtocol(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"typo_default_proto_config.yaml\"))\n\trequire.NoError(t, err)\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tassert.ErrorContains(t, cm.Unmarshal(&cfg), \"'protocols' has invalid keys: htttp\")\n}\n\nfunc TestUnmarshalConfigInvalidProtocol(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"bad_proto_config.yaml\"))\n\trequire.NoError(t, err)\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tassert.ErrorContains(t, cm.Unmarshal(&cfg), \"'protocols' has invalid keys: thrift\")\n}\n\nfunc TestUnmarshalConfigEmptyProtocols(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"bad_no_proto_config.yaml\"))\n\trequire.NoError(t, err)\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\tassert.EqualError(t, xconfmap.Validate(cfg), \"must specify at least one protocol when using the OTLP receiver\")\n}\n\nfunc TestUnmarshalConfigInvalidSignalPath(t *testing.T) {\n\ttests := []struct {\n\t\tname       string\n\t\ttestDataFn string\n\t}{\n\t\t{\n\t\t\tname:       \"Invalid traces URL path\",\n\t\t\ttestDataFn: \"invalid_traces_path.yaml\",\n\t\t},\n\t\t{\n\t\t\tname:       \"Invalid metrics URL path\",\n\t\t\ttestDataFn: \"invalid_metrics_path.yaml\",\n\t\t},\n\t\t{\n\t\t\tname:       \"Invalid logs URL path\",\n\t\t\ttestDataFn: \"invalid_logs_path.yaml\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", tt.testDataFn))\n\t\t\trequire.NoError(t, err)\n\t\t\tfactory := NewFactory()\n\t\t\tcfg := factory.CreateDefaultConfig()\n\t\t\tassert.ErrorContains(t, cm.Unmarshal(&cfg), \"invalid HTTP URL path set for signal: parse \\\":invalid\\\": missing protocol scheme\")\n\t\t})\n\t}\n}\n\nfunc TestUnmarshalConfigEmpty(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, confmap.New().Unmarshal(&cfg))\n\tassert.EqualError(t, xconfmap.Validate(cfg), \"must specify at least one protocol when using the OTLP receiver\")\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\n// Package otlpreceiver receives data in OTLP format.\npackage otlpreceiver // import \"go.opentelemetry.io/collector/receiver/otlpreceiver\"\n"
  },
  {
    "path": "receiver/otlpreceiver/encoder.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlpreceiver // import \"go.opentelemetry.io/collector/receiver/otlpreceiver\"\n\nimport (\n\tspb \"google.golang.org/genproto/googleapis/rpc/status\"\n\t\"google.golang.org/protobuf/encoding/protojson\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/pdata/plog/plogotlp\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n)\n\nconst (\n\tpbContentType   = \"application/x-protobuf\"\n\tjsonContentType = \"application/json\"\n)\n\nvar (\n\tpbEncoder = &protoEncoder{}\n\tjsEncoder = &jsonEncoder{}\n)\n\ntype encoder interface {\n\tunmarshalTracesRequest(buf []byte) (ptraceotlp.ExportRequest, error)\n\tunmarshalMetricsRequest(buf []byte) (pmetricotlp.ExportRequest, error)\n\tunmarshalLogsRequest(buf []byte) (plogotlp.ExportRequest, error)\n\tunmarshalProfilesRequest(buf []byte) (pprofileotlp.ExportRequest, error)\n\n\tmarshalTracesResponse(ptraceotlp.ExportResponse) ([]byte, error)\n\tmarshalMetricsResponse(pmetricotlp.ExportResponse) ([]byte, error)\n\tmarshalLogsResponse(plogotlp.ExportResponse) ([]byte, error)\n\tmarshalProfilesResponse(pprofileotlp.ExportResponse) ([]byte, error)\n\n\tmarshalStatus(rsp *spb.Status) ([]byte, error)\n\n\tcontentType() string\n}\n\ntype protoEncoder struct{}\n\nfunc (protoEncoder) unmarshalTracesRequest(buf []byte) (ptraceotlp.ExportRequest, error) {\n\treq := ptraceotlp.NewExportRequest()\n\terr := req.UnmarshalProto(buf)\n\treturn req, err\n}\n\nfunc (protoEncoder) unmarshalMetricsRequest(buf []byte) (pmetricotlp.ExportRequest, error) {\n\treq := pmetricotlp.NewExportRequest()\n\terr := req.UnmarshalProto(buf)\n\treturn req, err\n}\n\nfunc (protoEncoder) unmarshalLogsRequest(buf []byte) (plogotlp.ExportRequest, error) {\n\treq := plogotlp.NewExportRequest()\n\terr := req.UnmarshalProto(buf)\n\treturn req, err\n}\n\nfunc (protoEncoder) unmarshalProfilesRequest(buf []byte) (pprofileotlp.ExportRequest, error) {\n\treq := pprofileotlp.NewExportRequest()\n\terr := req.UnmarshalProto(buf)\n\treturn req, err\n}\n\nfunc (protoEncoder) marshalTracesResponse(resp ptraceotlp.ExportResponse) ([]byte, error) {\n\treturn resp.MarshalProto()\n}\n\nfunc (protoEncoder) marshalMetricsResponse(resp pmetricotlp.ExportResponse) ([]byte, error) {\n\treturn resp.MarshalProto()\n}\n\nfunc (protoEncoder) marshalLogsResponse(resp plogotlp.ExportResponse) ([]byte, error) {\n\treturn resp.MarshalProto()\n}\n\nfunc (protoEncoder) marshalProfilesResponse(resp pprofileotlp.ExportResponse) ([]byte, error) {\n\treturn resp.MarshalProto()\n}\n\nfunc (protoEncoder) marshalStatus(resp *spb.Status) ([]byte, error) {\n\treturn proto.Marshal(resp)\n}\n\nfunc (protoEncoder) contentType() string {\n\treturn pbContentType\n}\n\ntype jsonEncoder struct{}\n\nfunc (jsonEncoder) unmarshalTracesRequest(buf []byte) (ptraceotlp.ExportRequest, error) {\n\treq := ptraceotlp.NewExportRequest()\n\terr := req.UnmarshalJSON(buf)\n\treturn req, err\n}\n\nfunc (jsonEncoder) unmarshalMetricsRequest(buf []byte) (pmetricotlp.ExportRequest, error) {\n\treq := pmetricotlp.NewExportRequest()\n\terr := req.UnmarshalJSON(buf)\n\treturn req, err\n}\n\nfunc (jsonEncoder) unmarshalLogsRequest(buf []byte) (plogotlp.ExportRequest, error) {\n\treq := plogotlp.NewExportRequest()\n\terr := req.UnmarshalJSON(buf)\n\treturn req, err\n}\n\nfunc (jsonEncoder) unmarshalProfilesRequest(buf []byte) (pprofileotlp.ExportRequest, error) {\n\treq := pprofileotlp.NewExportRequest()\n\terr := req.UnmarshalJSON(buf)\n\treturn req, err\n}\n\nfunc (jsonEncoder) marshalTracesResponse(resp ptraceotlp.ExportResponse) ([]byte, error) {\n\treturn resp.MarshalJSON()\n}\n\nfunc (jsonEncoder) marshalMetricsResponse(resp pmetricotlp.ExportResponse) ([]byte, error) {\n\treturn resp.MarshalJSON()\n}\n\nfunc (jsonEncoder) marshalLogsResponse(resp plogotlp.ExportResponse) ([]byte, error) {\n\treturn resp.MarshalJSON()\n}\n\nfunc (jsonEncoder) marshalProfilesResponse(resp pprofileotlp.ExportResponse) ([]byte, error) {\n\treturn resp.MarshalJSON()\n}\n\nfunc (jsonEncoder) marshalStatus(resp *spb.Status) ([]byte, error) {\n\treturn protojson.Marshal(resp)\n}\n\nfunc (jsonEncoder) contentType() string {\n\treturn jsonContentType\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlpreceiver // import \"go.opentelemetry.io/collector/receiver/otlpreceiver\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configgrpc\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/internal/sharedcomponent\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/metadata\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n)\n\nconst (\n\tdefaultTracesURLPath   = \"/v1/traces\"\n\tdefaultMetricsURLPath  = \"/v1/metrics\"\n\tdefaultLogsURLPath     = \"/v1/logs\"\n\tdefaultProfilesURLPath = \"/v1development/profiles\"\n)\n\n// NewFactory creates a new OTLP receiver factory.\nfunc NewFactory() receiver.Factory {\n\treturn xreceiver.NewFactory(\n\t\tmetadata.Type,\n\t\tcreateDefaultConfig,\n\t\txreceiver.WithTraces(createTraces, metadata.TracesStability),\n\t\txreceiver.WithMetrics(createMetrics, metadata.MetricsStability),\n\t\txreceiver.WithLogs(createLog, metadata.LogsStability),\n\t\txreceiver.WithProfiles(createProfiles, metadata.ProfilesStability),\n\t)\n}\n\n// createDefaultConfig creates the default configuration for receiver.\nfunc createDefaultConfig() component.Config {\n\tgrpcCfg := configgrpc.NewDefaultServerConfig()\n\tgrpcCfg.NetAddr.Endpoint = \"localhost:4317\"\n\t// We almost write 0 bytes, so no need to tune WriteBufferSize.\n\tgrpcCfg.ReadBufferSize = 512 * 1024\n\n\thttpCfg := confighttp.NewDefaultServerConfig()\n\thttpCfg.NetAddr.Endpoint = \"localhost:4318\"\n\t// For backward compatibility:\n\thttpCfg.TLS = configoptional.None[configtls.ServerConfig]()\n\thttpCfg.WriteTimeout = 0\n\thttpCfg.ReadHeaderTimeout = 0\n\thttpCfg.IdleTimeout = 0\n\n\treturn &Config{\n\t\tProtocols: Protocols{\n\t\t\tGRPC: configoptional.Default(grpcCfg),\n\t\t\tHTTP: configoptional.Default(HTTPConfig{\n\t\t\t\tServerConfig:   httpCfg,\n\t\t\t\tTracesURLPath:  defaultTracesURLPath,\n\t\t\t\tMetricsURLPath: defaultMetricsURLPath,\n\t\t\t\tLogsURLPath:    defaultLogsURLPath,\n\t\t\t}),\n\t\t},\n\t}\n}\n\n// createTraces creates a trace receiver based on provided config.\nfunc createTraces(\n\t_ context.Context,\n\tset receiver.Settings,\n\tcfg component.Config,\n\tnextConsumer consumer.Traces,\n) (receiver.Traces, error) {\n\toCfg := cfg.(*Config)\n\tr, err := receivers.LoadOrStore(\n\t\toCfg,\n\t\tfunc() (*otlpReceiver, error) {\n\t\t\treturn newOtlpReceiver(oCfg, &set)\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr.Unwrap().registerTraceConsumer(nextConsumer)\n\treturn r, nil\n}\n\n// createMetrics creates a metrics receiver based on provided config.\nfunc createMetrics(\n\t_ context.Context,\n\tset receiver.Settings,\n\tcfg component.Config,\n\tconsumer consumer.Metrics,\n) (receiver.Metrics, error) {\n\toCfg := cfg.(*Config)\n\tr, err := receivers.LoadOrStore(\n\t\toCfg,\n\t\tfunc() (*otlpReceiver, error) {\n\t\t\treturn newOtlpReceiver(oCfg, &set)\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr.Unwrap().registerMetricsConsumer(consumer)\n\treturn r, nil\n}\n\n// createLog creates a log receiver based on provided config.\nfunc createLog(\n\t_ context.Context,\n\tset receiver.Settings,\n\tcfg component.Config,\n\tconsumer consumer.Logs,\n) (receiver.Logs, error) {\n\toCfg := cfg.(*Config)\n\tr, err := receivers.LoadOrStore(\n\t\toCfg,\n\t\tfunc() (*otlpReceiver, error) {\n\t\t\treturn newOtlpReceiver(oCfg, &set)\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr.Unwrap().registerLogsConsumer(consumer)\n\treturn r, nil\n}\n\n// createProfiles creates a trace receiver based on provided config.\nfunc createProfiles(\n\t_ context.Context,\n\tset receiver.Settings,\n\tcfg component.Config,\n\tnextConsumer xconsumer.Profiles,\n) (xreceiver.Profiles, error) {\n\toCfg := cfg.(*Config)\n\tr, err := receivers.LoadOrStore(\n\t\toCfg,\n\t\tfunc() (*otlpReceiver, error) {\n\t\t\treturn newOtlpReceiver(oCfg, &set)\n\t\t},\n\t)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tr.Unwrap().registerProfilesConsumer(nextConsumer)\n\treturn r, nil\n}\n\n// This is the map of already created OTLP receivers for particular configurations.\n// We maintain this map because the receiver.Factory is asked trace and metric receivers separately\n// when it gets CreateTraces() and CreateMetrics() but they must not\n// create separate objects, they must use one otlpReceiver object per configuration.\n// When the receiver is shutdown it should be removed from this map so the same configuration\n// can be recreated successfully.\nvar receivers = sharedcomponent.NewMap[*Config, *otlpReceiver]()\n"
  },
  {
    "path": "receiver/otlpreceiver/factory_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlpreceiver\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configgrpc\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/internal/telemetry\"\n\t\"go.opentelemetry.io/collector/internal/telemetry/telemetrytest\"\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/metadata\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n)\n\nfunc TestCreateDefaultConfig(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tassert.NotNil(t, cfg, \"failed to create default config\")\n\tassert.NoError(t, componenttest.CheckConfigStruct(cfg))\n}\n\nfunc TestCreateSameReceiver(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.GRPC.GetOrInsertDefault().NetAddr.Endpoint = testutil.GetAvailableLocalAddress(t)\n\tcfg.HTTP.GetOrInsertDefault().ServerConfig.NetAddr.Endpoint = testutil.GetAvailableLocalAddress(t)\n\n\tcreationSet := receivertest.NewNopSettings(factory.Type())\n\tvar droppedAttrs []string\n\tcreationSet.Logger = telemetrytest.MockInjectorLogger(creationSet.Logger, &droppedAttrs)\n\n\ttReceiver, err := factory.CreateTraces(context.Background(), creationSet, cfg, consumertest.NewNop())\n\tassert.NotNil(t, tReceiver)\n\trequire.NoError(t, err)\n\n\tmReceiver, err := factory.CreateMetrics(context.Background(), creationSet, cfg, consumertest.NewNop())\n\tassert.NotNil(t, mReceiver)\n\trequire.NoError(t, err)\n\n\tlReceiver, err := factory.CreateMetrics(context.Background(), creationSet, cfg, consumertest.NewNop())\n\tassert.NotNil(t, lReceiver)\n\trequire.NoError(t, err)\n\n\tpReceiver, err := factory.(xreceiver.Factory).CreateProfiles(context.Background(), creationSet, cfg, consumertest.NewNop())\n\tassert.NotNil(t, pReceiver)\n\trequire.NoError(t, err)\n\n\tassert.Same(t, tReceiver, mReceiver)\n\tassert.Same(t, tReceiver, lReceiver)\n\tassert.Same(t, tReceiver, pReceiver)\n\n\t// Test that we've dropped the relevant injected attributes exactly once\n\tassert.ElementsMatch(t, droppedAttrs, []string{telemetry.SignalKey})\n}\n\nfunc TestCreateTraces(t *testing.T) {\n\tfactory := NewFactory()\n\tdefaultGRPCSettings := configoptional.Some(configgrpc.ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  testutil.GetAvailableLocalAddress(t),\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t})\n\tdefaultServerConfig := confighttp.NewDefaultServerConfig()\n\tdefaultServerConfig.NetAddr.Endpoint = testutil.GetAvailableLocalAddress(t)\n\tdefaultHTTPSettings := configoptional.Some(HTTPConfig{\n\t\tServerConfig:   defaultServerConfig,\n\t\tTracesURLPath:  defaultTracesURLPath,\n\t\tMetricsURLPath: defaultMetricsURLPath,\n\t\tLogsURLPath:    defaultLogsURLPath,\n\t})\n\n\ttests := []struct {\n\t\tname         string\n\t\tcfg          *Config\n\t\twantStartErr bool\n\t\twantErr      bool\n\t\tsink         consumer.Traces\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\tcfg: &Config{\n\t\t\t\tProtocols: Protocols{\n\t\t\t\t\tGRPC: defaultGRPCSettings,\n\t\t\t\t\tHTTP: defaultHTTPSettings,\n\t\t\t\t},\n\t\t\t},\n\t\t\tsink: consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid_grpc_port\",\n\t\t\tcfg: &Config{\n\t\t\t\tProtocols: Protocols{\n\t\t\t\t\tGRPC: configoptional.Some(configgrpc.ServerConfig{\n\t\t\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\t\t\tEndpoint:  \"localhost:112233\",\n\t\t\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t\tHTTP: defaultHTTPSettings,\n\t\t\t\t},\n\t\t\t},\n\t\t\twantStartErr: true,\n\t\t\tsink:         consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid_http_port\",\n\t\t\tcfg: &Config{\n\t\t\t\tProtocols: Protocols{\n\t\t\t\t\tGRPC: defaultGRPCSettings,\n\t\t\t\t\tHTTP: configoptional.Some(HTTPConfig{\n\t\t\t\t\t\tServerConfig: confighttp.ServerConfig{\n\t\t\t\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\t\t\t\tEndpoint:  \"localhost:112233\",\n\t\t\t\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tTracesURLPath: defaultTracesURLPath,\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t},\n\t\t\twantStartErr: true,\n\t\t\tsink:         consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname: \"no_http_or_grcp_config\",\n\t\t\tcfg: &Config{\n\t\t\t\tProtocols: Protocols{},\n\t\t\t},\n\t\t\tsink: consumertest.NewNop(),\n\t\t},\n\t}\n\tcreationSet := receivertest.NewNopSettings(metadata.Type)\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tctx := context.Background()\n\t\t\ttr, err := factory.CreateTraces(ctx, creationSet, tt.cfg, tt.sink)\n\t\t\tif tt.wantErr {\n\t\t\t\tassert.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\tif tt.wantStartErr {\n\t\t\t\tassert.Error(t, tr.Start(ctx, componenttest.NewNopHost()))\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, tr.Start(ctx, componenttest.NewNopHost()))\n\t\t\t\tassert.NoError(t, tr.Shutdown(ctx))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCreateMetric(t *testing.T) {\n\tfactory := NewFactory()\n\tdefaultGRPCSettings := configoptional.Some(configgrpc.ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  \"127.0.0.1:0\",\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t})\n\tdefaultServerConfig := confighttp.NewDefaultServerConfig()\n\tdefaultServerConfig.NetAddr.Endpoint = \"127.0.0.1:0\"\n\tdefaultHTTPSettings := configoptional.Some(HTTPConfig{\n\t\tServerConfig:   defaultServerConfig,\n\t\tTracesURLPath:  defaultTracesURLPath,\n\t\tMetricsURLPath: defaultMetricsURLPath,\n\t\tLogsURLPath:    defaultLogsURLPath,\n\t})\n\n\ttests := []struct {\n\t\tname         string\n\t\tcfg          *Config\n\t\twantStartErr bool\n\t\twantErr      bool\n\t\tsink         consumer.Metrics\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\tcfg: &Config{\n\t\t\t\tProtocols: Protocols{\n\t\t\t\t\tGRPC: defaultGRPCSettings,\n\t\t\t\t\tHTTP: defaultHTTPSettings,\n\t\t\t\t},\n\t\t\t},\n\t\t\tsink: consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid_grpc_address\",\n\t\t\tcfg: &Config{\n\t\t\t\tProtocols: Protocols{\n\t\t\t\t\tGRPC: configoptional.Some(configgrpc.ServerConfig{\n\t\t\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\t\t\tEndpoint:  \"327.0.0.1:1122\",\n\t\t\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t\tHTTP: defaultHTTPSettings,\n\t\t\t\t},\n\t\t\t},\n\t\t\twantStartErr: true,\n\t\t\tsink:         consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid_http_address\",\n\t\t\tcfg: &Config{\n\t\t\t\tProtocols: Protocols{\n\t\t\t\t\tGRPC: defaultGRPCSettings,\n\t\t\t\t\tHTTP: configoptional.Some(HTTPConfig{\n\t\t\t\t\t\tServerConfig: confighttp.ServerConfig{\n\t\t\t\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\t\t\t\tEndpoint:  \"327.0.0.1:1122\",\n\t\t\t\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tMetricsURLPath: defaultMetricsURLPath,\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t},\n\t\t\twantStartErr: true,\n\t\t\tsink:         consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname: \"no_http_or_grcp_config\",\n\t\t\tcfg: &Config{\n\t\t\t\tProtocols: Protocols{},\n\t\t\t},\n\t\t\tsink: consumertest.NewNop(),\n\t\t},\n\t}\n\tcreationSet := receivertest.NewNopSettings(metadata.Type)\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tctx := context.Background()\n\t\t\tmr, err := factory.CreateMetrics(ctx, creationSet, tt.cfg, tt.sink)\n\t\t\tif tt.wantErr {\n\t\t\t\tassert.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\tif tt.wantStartErr {\n\t\t\t\tassert.Error(t, mr.Start(ctx, componenttest.NewNopHost()))\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, mr.Start(ctx, componenttest.NewNopHost()))\n\t\t\t\tassert.NoError(t, mr.Shutdown(ctx))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCreateLogs(t *testing.T) {\n\tfactory := NewFactory()\n\tdefaultGRPCSettings := configoptional.Some(configgrpc.ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  testutil.GetAvailableLocalAddress(t),\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t})\n\tdefaultServerConfig := confighttp.NewDefaultServerConfig()\n\tdefaultServerConfig.NetAddr.Endpoint = testutil.GetAvailableLocalAddress(t)\n\tdefaultHTTPSettings := configoptional.Some(HTTPConfig{\n\t\tServerConfig:   defaultServerConfig,\n\t\tTracesURLPath:  defaultTracesURLPath,\n\t\tMetricsURLPath: defaultMetricsURLPath,\n\t\tLogsURLPath:    defaultLogsURLPath,\n\t})\n\n\ttests := []struct {\n\t\tname         string\n\t\tcfg          *Config\n\t\twantStartErr bool\n\t\twantErr      bool\n\t\tsink         consumer.Logs\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\tcfg: &Config{\n\t\t\t\tProtocols: Protocols{\n\t\t\t\t\tGRPC: defaultGRPCSettings,\n\t\t\t\t\tHTTP: defaultHTTPSettings,\n\t\t\t\t},\n\t\t\t},\n\t\t\tsink: consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid_grpc_address\",\n\t\t\tcfg: &Config{\n\t\t\t\tProtocols: Protocols{\n\t\t\t\t\tGRPC: configoptional.Some(configgrpc.ServerConfig{\n\t\t\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\t\t\tEndpoint:  \"327.0.0.1:1122\",\n\t\t\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t\tHTTP: defaultHTTPSettings,\n\t\t\t\t},\n\t\t\t},\n\t\t\twantStartErr: true,\n\t\t\tsink:         consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid_http_address\",\n\t\t\tcfg: &Config{\n\t\t\t\tProtocols: Protocols{\n\t\t\t\t\tGRPC: defaultGRPCSettings,\n\t\t\t\t\tHTTP: configoptional.Some(HTTPConfig{\n\t\t\t\t\t\tServerConfig: confighttp.ServerConfig{\n\t\t\t\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\t\t\t\tEndpoint:  \"327.0.0.1:1122\",\n\t\t\t\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t\tLogsURLPath: defaultLogsURLPath,\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t},\n\t\t\twantStartErr: true,\n\t\t\tsink:         consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname: \"no_http_or_grcp_config\",\n\t\t\tcfg: &Config{\n\t\t\t\tProtocols: Protocols{},\n\t\t\t},\n\t\t\tsink: consumertest.NewNop(),\n\t\t},\n\t}\n\tcreationSet := receivertest.NewNopSettings(metadata.Type)\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tctx := context.Background()\n\t\t\tmr, err := factory.CreateLogs(ctx, creationSet, tt.cfg, tt.sink)\n\t\t\tif tt.wantErr {\n\t\t\t\tassert.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\tif tt.wantStartErr {\n\t\t\t\tassert.Error(t, mr.Start(ctx, componenttest.NewNopHost()))\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, mr.Start(ctx, componenttest.NewNopHost()))\n\t\t\t\tassert.NoError(t, mr.Shutdown(ctx))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCreateProfiles(t *testing.T) {\n\tfactory := NewFactory()\n\tdefaultGRPCSettings := configoptional.Some(configgrpc.ServerConfig{\n\t\tNetAddr: confignet.AddrConfig{\n\t\t\tEndpoint:  testutil.GetAvailableLocalAddress(t),\n\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t},\n\t})\n\tdefaultServerConfig := confighttp.NewDefaultServerConfig()\n\tdefaultServerConfig.NetAddr.Endpoint = testutil.GetAvailableLocalAddress(t)\n\tdefaultHTTPSettings := configoptional.Some(HTTPConfig{\n\t\tServerConfig:   defaultServerConfig,\n\t\tTracesURLPath:  defaultTracesURLPath,\n\t\tMetricsURLPath: defaultMetricsURLPath,\n\t\tLogsURLPath:    defaultLogsURLPath,\n\t})\n\n\ttests := []struct {\n\t\tname         string\n\t\tcfg          *Config\n\t\twantStartErr bool\n\t\twantErr      bool\n\t\tsink         xconsumer.Profiles\n\t}{\n\t\t{\n\t\t\tname: \"default\",\n\t\t\tcfg: &Config{\n\t\t\t\tProtocols: Protocols{\n\t\t\t\t\tGRPC: defaultGRPCSettings,\n\t\t\t\t\tHTTP: defaultHTTPSettings,\n\t\t\t\t},\n\t\t\t},\n\t\t\tsink: consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid_grpc_port\",\n\t\t\tcfg: &Config{\n\t\t\t\tProtocols: Protocols{\n\t\t\t\t\tGRPC: configoptional.Some(configgrpc.ServerConfig{\n\t\t\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\t\t\tEndpoint:  \"localhost:112233\",\n\t\t\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t\tHTTP: defaultHTTPSettings,\n\t\t\t\t},\n\t\t\t},\n\t\t\twantStartErr: true,\n\t\t\tsink:         consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid_http_port\",\n\t\t\tcfg: &Config{\n\t\t\t\tProtocols: Protocols{\n\t\t\t\t\tGRPC: defaultGRPCSettings,\n\t\t\t\t\tHTTP: configoptional.Some(HTTPConfig{\n\t\t\t\t\t\tServerConfig: confighttp.ServerConfig{\n\t\t\t\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\t\t\t\tEndpoint:  \"localhost:112233\",\n\t\t\t\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t},\n\t\t\twantStartErr: true,\n\t\t\tsink:         consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname: \"no_http_or_grcp_config\",\n\t\t\tcfg: &Config{\n\t\t\t\tProtocols: Protocols{},\n\t\t\t},\n\t\t\tsink: consumertest.NewNop(),\n\t\t},\n\t}\n\tcreationSet := receivertest.NewNopSettings(metadata.Type)\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tctx := context.Background()\n\t\t\ttr, err := factory.(xreceiver.Factory).CreateProfiles(ctx, creationSet, tt.cfg, tt.sink)\n\t\t\tif tt.wantErr {\n\t\t\t\tassert.Error(t, err)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\t\t\tif tt.wantStartErr {\n\t\t\t\tassert.Error(t, tr.Start(ctx, componenttest.NewNopHost()))\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, tr.Start(ctx, componenttest.NewNopHost()))\n\t\t\t\tassert.NoError(t, tr.Shutdown(ctx))\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/fuzz_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlpreceiver\n\nimport (\n\t\"bytes\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/logs\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/metrics\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/trace\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\nfunc FuzzReceiverHandlers(f *testing.F) {\n\tf.Fuzz(func(_ *testing.T, data []byte, pb bool, handler int) {\n\t\treq, err := http.NewRequest(http.MethodPost, \"\", bytes.NewReader(data))\n\t\tif err != nil {\n\t\t\treturn\n\t\t}\n\t\tif pb {\n\t\t\treq.Header.Add(\"Content-Type\", pbContentType)\n\t\t} else {\n\t\t\treq.Header.Add(\"Content-Type\", jsonContentType)\n\t\t}\n\t\tset := receivertest.NewNopSettings(receivertest.NopType)\n\t\tset.TelemetrySettings = componenttest.NewNopTelemetrySettings()\n\t\tset.ID = otlpReceiverID\n\t\tcfg := createDefaultConfig().(*Config)\n\t\tr, err := newOtlpReceiver(cfg, &set)\n\t\tif err != nil {\n\t\t\tpanic(err)\n\t\t}\n\t\tr.nextTraces = consumertest.NewNop()\n\t\tr.nextLogs = consumertest.NewNop()\n\t\tr.nextMetrics = consumertest.NewNop()\n\t\tr.nextProfiles = consumertest.NewNop()\n\t\tresp := httptest.NewRecorder()\n\t\tswitch handler % 3 {\n\t\tcase 0:\n\t\t\thttpTracesReceiver := trace.New(r.nextTraces, r.obsrepHTTP)\n\t\t\thandleTraces(resp, req, httpTracesReceiver)\n\t\tcase 1:\n\t\t\thttpMetricsReceiver := metrics.New(r.nextMetrics, r.obsrepHTTP)\n\t\t\thandleMetrics(resp, req, httpMetricsReceiver)\n\t\tcase 2:\n\t\t\thttpLogsReceiver := logs.New(r.nextLogs, r.obsrepHTTP)\n\t\t\thandleLogs(resp, req, httpLogsReceiver)\n\t\t}\n\t})\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/generated_component_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage otlpreceiver\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n)\n\nvar typ = component.MustNewType(\"otlp\")\n\nfunc TestComponentFactoryType(t *testing.T) {\n\trequire.Equal(t, typ, NewFactory().Type())\n}\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(NewFactory().CreateDefaultConfig()))\n}\n\nfunc TestComponentLifecycle(t *testing.T) {\n\tfactory := NewFactory()\n\n\ttests := []struct {\n\t\tcreateFn func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error)\n\t\tname     string\n\t}{\n\n\t\t{\n\t\t\tname: \"logs\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateLogs(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateMetrics(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"traces\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.CreateTraces(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\n\t\t{\n\t\t\tname: \"profiles\",\n\t\t\tcreateFn: func(ctx context.Context, set receiver.Settings, cfg component.Config) (component.Component, error) {\n\t\t\t\treturn factory.(xreceiver.Factory).CreateProfiles(ctx, set, cfg, consumertest.NewNop())\n\t\t\t},\n\t\t},\n\t}\n\n\tcm, err := confmaptest.LoadConf(\"metadata.yaml\")\n\trequire.NoError(t, err)\n\tcfg := factory.CreateDefaultConfig()\n\tsub, err := cm.Sub(\"tests::config\")\n\trequire.NoError(t, err)\n\trequire.NoError(t, sub.Unmarshal(&cfg))\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name+\"-shutdown\", func(t *testing.T) {\n\t\t\tc, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\terr = c.Shutdown(context.Background())\n\t\t\trequire.NoError(t, err)\n\t\t})\n\t\tt.Run(tt.name+\"-lifecycle\", func(t *testing.T) {\n\t\t\tfirstRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\thost := newMdatagenNopHost()\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, firstRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, firstRcvr.Shutdown(context.Background()))\n\t\t\tsecondRcvr, err := tt.createFn(context.Background(), receivertest.NewNopSettings(typ), cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, secondRcvr.Start(context.Background(), host))\n\t\t\trequire.NoError(t, secondRcvr.Shutdown(context.Background()))\n\t\t})\n\t}\n}\n\nvar _ component.Host = (*mdatagenNopHost)(nil)\n\ntype mdatagenNopHost struct{}\n\nfunc newMdatagenNopHost() component.Host {\n\treturn &mdatagenNopHost{}\n}\n\nfunc (mnh *mdatagenNopHost) GetExtensions() map[component.ID]component.Component {\n\treturn nil\n}\n\nfunc (mnh *mdatagenNopHost) GetFactory(_ component.Kind, _ component.Type) component.Factory {\n\treturn nil\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage otlpreceiver\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/go.mod",
    "content": "module go.opentelemetry.io/collector/receiver/otlpreceiver\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/klauspost/compress v1.18.4\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector v0.148.0\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componentstatus v0.148.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/config/configauth v1.54.0\n\tgo.opentelemetry.io/collector/config/configgrpc v0.148.0\n\tgo.opentelemetry.io/collector/config/confighttp v0.148.0\n\tgo.opentelemetry.io/collector/config/confignet v1.54.0\n\tgo.opentelemetry.io/collector/config/configoptional v1.54.0\n\tgo.opentelemetry.io/collector/config/configtls v1.54.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/internal/sharedcomponent v0.148.0\n\tgo.opentelemetry.io/collector/internal/telemetry v0.148.0\n\tgo.opentelemetry.io/collector/internal/testutil v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.opentelemetry.io/collector/receiver v1.54.0\n\tgo.opentelemetry.io/collector/receiver/receiverhelper v0.148.0\n\tgo.opentelemetry.io/collector/receiver/receivertest v0.148.0\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0\n\tgo.opentelemetry.io/otel v1.42.0\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/zap v1.27.1\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171\n\tgoogle.golang.org/grpc v1.79.3\n\tgoogle.golang.org/protobuf v1.36.11\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/felixge/httpsnoop v1.0.4 // indirect\n\tgithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f // indirect\n\tgithub.com/fsnotify/fsnotify v1.9.0 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/golang/snappy v1.0.0 // indirect\n\tgithub.com/google/go-tpm v0.9.8 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/mostynb/go-grpc-compression v1.2.3 // indirect\n\tgithub.com/pierrec/lz4/v4 v4.1.26 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgithub.com/rs/cors v1.11.1 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/client v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configcompression v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configmiddleware v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configopaque v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionauth v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionmiddleware v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0 // indirect\n\tgo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 // indirect\n\tgo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/crypto v0.48.0 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector => ../../\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/config/configauth => ../../config/configauth\n\nreplace go.opentelemetry.io/collector/config/configcompression => ../../config/configcompression\n\nreplace go.opentelemetry.io/collector/config/confighttp => ../../config/confighttp\n\nreplace go.opentelemetry.io/collector/config/configgrpc => ../../config/configgrpc\n\nreplace go.opentelemetry.io/collector/config/confignet => ../../config/confignet\n\nreplace go.opentelemetry.io/collector/config/configopaque => ../../config/configopaque\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../../config/configoptional\n\nreplace go.opentelemetry.io/collector/config/configtls => ../../config/configtls\n\nreplace go.opentelemetry.io/collector/confmap => ../../confmap\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/extension => ../../extension\n\nreplace go.opentelemetry.io/collector/extension/extensionauth => ../../extension/extensionauth\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/receiver => ../\n\nreplace go.opentelemetry.io/collector/receiver/receiverhelper => ../receiverhelper\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/client => ../../client\n\nreplace go.opentelemetry.io/collector/component/componentstatus => ../../component/componentstatus\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../xreceiver\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../receivertest\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/internal/sharedcomponent => ../../internal/sharedcomponent\n\nreplace go.opentelemetry.io/collector/internal/telemetry => ../../internal/telemetry\n\nretract (\n\tv0.76.0 // Depends on retracted pdata v1.0.0-rc10 module, use v0.76.1\n\tv0.69.0 // Release failed, use v0.69.1\n)\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest => ../../extension/extensionauth/extensionauthtest\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ../../extension/extensionmiddleware\n\nreplace go.opentelemetry.io/collector/config/configmiddleware => ../../config/configmiddleware\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest => ../../extension/extensionmiddleware/extensionmiddlewaretest\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "receiver/otlpreceiver/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=\ngithub.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f h1:RJ+BDPLSHQO7cSjKBqjPJSbi1qfk9WcsjQDtZiw3dZw=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f/go.mod h1:VHbbch/X4roIY22jL1s3qRbZhCiRIgUAF/PdSUcx2io=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=\ngithub.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=\ngithub.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=\ngithub.com/google/go-tpm-tools v0.4.7 h1:J3ycC8umYxM9A4eF73EofRZu4BxY0jjQnUnkhIBbvws=\ngithub.com/google/go-tpm-tools v0.4.7/go.mod h1:gSyXTZHe3fgbzb6WEGd90QucmsnT1SRdlye82gH8QjQ=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=\ngithub.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/mostynb/go-grpc-compression v1.2.3 h1:42/BKWMy0KEJGSdWvzqIyOZ95YcR9mLPqKctH7Uo//I=\ngithub.com/mostynb/go-grpc-compression v1.2.3/go.mod h1:AghIxF3P57umzqM9yz795+y1Vjs47Km/Y2FE6ouQ7Lg=\ngithub.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=\ngithub.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=\ngithub.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 h1:yI1/OhfEPy7J9eoa6Sj051C7n5dvpj0QX8g4sRchg04=\ngo.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0/go.mod h1:NoUCKYWK+3ecatC4HjkRktREheMeEtrXoQxrqYFeHSc=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=\ngolang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=\ngonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "receiver/otlpreceiver/internal/errors/errors.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage errors // import \"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/errors\"\n\nimport (\n\t\"net/http\"\n\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n)\n\nfunc GetStatusFromError(err error) error {\n\ts, ok := status.FromError(err)\n\tif !ok {\n\t\t// Default to a retryable error\n\t\t// https://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md#failures\n\t\tcode := codes.Unavailable\n\t\tif consumererror.IsPermanent(err) {\n\t\t\t// If an error is permanent but doesn't have an attached gRPC status, assume it is server-side.\n\t\t\tcode = codes.Internal\n\t\t}\n\t\ts = status.New(code, err.Error())\n\t}\n\treturn s.Err()\n}\n\nfunc GetHTTPStatusCodeFromStatus(s *status.Status) int {\n\t// See https://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md#failures\n\t// to see if a code is retryable.\n\t// See https://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md#failures-1\n\t// to see a list of retryable http status codes.\n\tswitch s.Code() {\n\t// Retryable\n\tcase codes.Canceled, codes.DeadlineExceeded, codes.Aborted, codes.OutOfRange, codes.Unavailable, codes.DataLoss:\n\t\treturn http.StatusServiceUnavailable\n\t// Retryable\n\tcase codes.ResourceExhausted:\n\t\treturn http.StatusTooManyRequests\n\t// Not Retryable\n\tcase codes.InvalidArgument:\n\t\treturn http.StatusBadRequest\n\t// Not Retryable\n\tcase codes.Unauthenticated:\n\t\treturn http.StatusUnauthorized\n\t// Not Retryable\n\tcase codes.PermissionDenied:\n\t\treturn http.StatusForbidden\n\t// Not Retryable\n\tcase codes.Unimplemented:\n\t\treturn http.StatusNotFound\n\t// Not Retryable\n\tdefault:\n\t\treturn http.StatusInternalServerError\n\t}\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/internal/errors/errors_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage errors // import \"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/util\"\n\nimport (\n\t\"errors\"\n\t\"net/http\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n)\n\nfunc Test_GetStatusFromError(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    error\n\t\texpected *status.Status\n\t}{\n\t\t{\n\t\t\tname:     \"Status\",\n\t\t\tinput:    status.Error(codes.Aborted, \"test\"),\n\t\t\texpected: status.New(codes.Aborted, \"test\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"Permanent Error\",\n\t\t\tinput:    consumererror.NewPermanent(errors.New(\"test\")),\n\t\t\texpected: status.New(codes.Internal, \"Permanent error: test\"),\n\t\t},\n\t\t{\n\t\t\tname:     \"Non-Permanent Error\",\n\t\t\tinput:    errors.New(\"test\"),\n\t\t\texpected: status.New(codes.Unavailable, \"test\"),\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := GetStatusFromError(tt.input)\n\t\t\tassert.Equal(t, tt.expected.Err(), result)\n\t\t})\n\t}\n}\n\nfunc Test_GetHTTPStatusCodeFromStatus(t *testing.T) {\n\ttests := []struct {\n\t\tname     string\n\t\tinput    *status.Status\n\t\texpected int\n\t}{\n\t\t{\n\t\t\tname:     \"Retryable Status\",\n\t\t\tinput:    status.New(codes.Unavailable, \"test\"),\n\t\t\texpected: http.StatusServiceUnavailable,\n\t\t},\n\t\t{\n\t\t\tname:     \"Non-retryable Status\",\n\t\t\tinput:    status.New(codes.Internal, \"test\"),\n\t\t\texpected: http.StatusInternalServerError,\n\t\t},\n\t\t{\n\t\t\tname:     \"Specifically 429\",\n\t\t\tinput:    status.New(codes.ResourceExhausted, \"test\"),\n\t\t\texpected: http.StatusTooManyRequests,\n\t\t},\n\t\t{\n\t\t\tname:     \"Specifically 400\",\n\t\t\tinput:    status.New(codes.InvalidArgument, \"test\"),\n\t\t\texpected: http.StatusBadRequest,\n\t\t},\n\t\t{\n\t\t\tname:     \"Specifically 401\",\n\t\t\tinput:    status.New(codes.Unauthenticated, \"test\"),\n\t\t\texpected: http.StatusUnauthorized,\n\t\t},\n\t\t{\n\t\t\tname:     \"Specifically 403\",\n\t\t\tinput:    status.New(codes.PermissionDenied, \"test\"),\n\t\t\texpected: http.StatusForbidden,\n\t\t},\n\t\t{\n\t\t\tname:     \"Specifically 404\",\n\t\t\tinput:    status.New(codes.Unimplemented, \"test\"),\n\t\t\texpected: http.StatusNotFound,\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresult := GetHTTPStatusCodeFromStatus(tt.input)\n\t\t\tassert.Equal(t, tt.expected, result)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/internal/logs/otlp.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage logs // import \"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/logs\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/plog/plogotlp\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/errors\"\n\t\"go.opentelemetry.io/collector/receiver/receiverhelper\"\n)\n\nconst dataFormatProtobuf = \"protobuf\"\n\n// Receiver is the type used to handle logs from OpenTelemetry exporters.\ntype Receiver struct {\n\tplogotlp.UnimplementedGRPCServer\n\tnextConsumer consumer.Logs\n\tobsreport    *receiverhelper.ObsReport\n}\n\n// New creates a new Receiver reference.\nfunc New(nextConsumer consumer.Logs, obsreport *receiverhelper.ObsReport) *Receiver {\n\treturn &Receiver{\n\t\tnextConsumer: nextConsumer,\n\t\tobsreport:    obsreport,\n\t}\n}\n\n// Export implements the service Export logs func.\nfunc (r *Receiver) Export(ctx context.Context, req plogotlp.ExportRequest) (plogotlp.ExportResponse, error) {\n\tld := req.Logs()\n\tnumSpans := ld.LogRecordCount()\n\tif numSpans == 0 {\n\t\treturn plogotlp.NewExportResponse(), nil\n\t}\n\n\tctx = r.obsreport.StartLogsOp(ctx)\n\terr := r.nextConsumer.ConsumeLogs(ctx, ld)\n\tr.obsreport.EndLogsOp(ctx, dataFormatProtobuf, numSpans, err)\n\n\t// Use appropriate status codes for permanent/non-permanent errors\n\t// If we return the error straightaway, then the grpc implementation will set status code to Unknown\n\t// Refer: https://github.com/grpc/grpc-go/blob/v1.59.0/server.go#L1345\n\t// So, convert the error to appropriate grpc status and return the error\n\t// NonPermanent errors will be converted to codes.Unavailable (equivalent to HTTP 503)\n\t// Permanent errors will be converted to codes.InvalidArgument (equivalent to HTTP 400)\n\tif err != nil {\n\t\treturn plogotlp.NewExportResponse(), errors.GetStatusFromError(err)\n\t}\n\n\treturn plogotlp.NewExportResponse(), nil\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/internal/logs/otlp_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage logs\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/credentials/insecure\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/plog/plogotlp\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/metadata\"\n\t\"go.opentelemetry.io/collector/receiver/receiverhelper\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\nfunc TestExport(t *testing.T) {\n\tld := testdata.GenerateLogs(1)\n\treq := plogotlp.NewExportRequestFromLogs(ld)\n\n\tlogSink := new(consumertest.LogsSink)\n\tlogClient := makeLogsServiceClient(t, logSink)\n\tresp, err := logClient.Export(context.Background(), req)\n\trequire.NoError(t, err, \"Failed to export trace: %v\", err)\n\trequire.NotNil(t, resp, \"The response is missing\")\n\n\tlds := logSink.AllLogs()\n\trequire.Len(t, lds, 1)\n\tassert.Equal(t, ld, lds[0])\n}\n\nfunc TestExport_EmptyRequest(t *testing.T) {\n\tlogSink := new(consumertest.LogsSink)\n\n\tlogClient := makeLogsServiceClient(t, logSink)\n\tresp, err := logClient.Export(context.Background(), plogotlp.NewExportRequest())\n\trequire.NoError(t, err, \"Failed to export trace: %v\", err)\n\tassert.NotNil(t, resp, \"The response is missing\")\n}\n\nfunc TestExport_NonPermanentErrorConsumer(t *testing.T) {\n\tld := testdata.GenerateLogs(1)\n\treq := plogotlp.NewExportRequestFromLogs(ld)\n\n\tlogClient := makeLogsServiceClient(t, consumertest.NewErr(errors.New(\"my error\")))\n\tresp, err := logClient.Export(context.Background(), req)\n\trequire.EqualError(t, err, \"rpc error: code = Unavailable desc = my error\")\n\trequire.ErrorIs(t, err, status.Error(codes.Unavailable, \"my error\"))\n\tassert.Equal(t, plogotlp.ExportResponse{}, resp)\n}\n\nfunc TestExport_PermanentErrorConsumer(t *testing.T) {\n\tld := testdata.GenerateLogs(1)\n\treq := plogotlp.NewExportRequestFromLogs(ld)\n\n\tlogClient := makeLogsServiceClient(t, consumertest.NewErr(consumererror.NewPermanent(errors.New(\"my error\"))))\n\tresp, err := logClient.Export(context.Background(), req)\n\trequire.EqualError(t, err, \"rpc error: code = Internal desc = Permanent error: my error\")\n\trequire.ErrorIs(t, err, status.Error(codes.Internal, \"Permanent error: my error\"))\n\tassert.Equal(t, plogotlp.ExportResponse{}, resp)\n}\n\nfunc makeLogsServiceClient(t *testing.T, lc consumer.Logs) plogotlp.GRPCClient {\n\taddr := otlpReceiverOnGRPCServer(t, lc)\n\tcc, err := grpc.NewClient(addr.String(), grpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err, \"Failed to create the TraceServiceClient: %v\", err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, cc.Close())\n\t})\n\n\treturn plogotlp.NewGRPCClient(cc)\n}\n\nfunc otlpReceiverOnGRPCServer(t *testing.T, lc consumer.Logs) net.Addr {\n\tln, err := net.Listen(\"tcp\", \"localhost:\")\n\trequire.NoError(t, err, \"Failed to find an available address to run the gRPC server: %v\", err)\n\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, ln.Close())\n\t})\n\n\tset := receivertest.NewNopSettings(metadata.Type)\n\tset.ID = component.MustNewIDWithName(\"otlp\", \"log\")\n\tobsreport, err := receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{\n\t\tReceiverID:             set.ID,\n\t\tTransport:              \"grpc\",\n\t\tReceiverCreateSettings: set,\n\t})\n\trequire.NoError(t, err)\n\tr := New(lc, obsreport)\n\t// Now run it as a gRPC server\n\tsrv := grpc.NewServer()\n\tplogotlp.RegisterGRPCServer(srv, r)\n\tgo func() {\n\t\t_ = srv.Serve(ln)\n\t}()\n\n\treturn ln.Addr()\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/internal/logs/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage logs\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/internal/metadata/generated_logs.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/receiver\"\n)\n\n// LogsBuilder provides an interface for scrapers to report logs while taking care of all the transformations\n// required to produce log representation defined in metadata and user config.\ntype LogsBuilder struct {\n\tlogsBuffer       plog.Logs\n\tlogRecordsBuffer plog.LogRecordSlice\n\tbuildInfo        component.BuildInfo // contains version information.\n}\n\n// LogBuilderOption applies changes to default logs builder.\ntype LogBuilderOption interface {\n\tapply(*LogsBuilder)\n}\n\nfunc NewLogsBuilder(settings receiver.Settings) *LogsBuilder {\n\tlb := &LogsBuilder{\n\t\tlogsBuffer:       plog.NewLogs(),\n\t\tlogRecordsBuffer: plog.NewLogRecordSlice(),\n\t\tbuildInfo:        settings.BuildInfo,\n\t}\n\n\treturn lb\n}\n\n// ResourceLogsOption applies changes to provided resource logs.\ntype ResourceLogsOption interface {\n\tapply(plog.ResourceLogs)\n}\n\ntype resourceLogsOptionFunc func(plog.ResourceLogs)\n\nfunc (rlof resourceLogsOptionFunc) apply(rl plog.ResourceLogs) {\n\trlof(rl)\n}\n\n// WithLogsResource sets the provided resource on the emitted ResourceLogs.\n// It's recommended to use ResourceBuilder to create the resource.\nfunc WithLogsResource(res pcommon.Resource) ResourceLogsOption {\n\treturn resourceLogsOptionFunc(func(rl plog.ResourceLogs) {\n\t\tres.CopyTo(rl.Resource())\n\t})\n}\n\n// AppendLogRecord adds a log record to the logs builder.\nfunc (lb *LogsBuilder) AppendLogRecord(lr plog.LogRecord) {\n\tlr.MoveTo(lb.logRecordsBuffer.AppendEmpty())\n}\n\n// EmitForResource saves all the generated logs under a new resource and updates the internal state to be ready for\n// recording another set of log records as part of another resource. This function can be helpful when one scraper\n// needs to emit logs from several resources. Otherwise calling this function is not required,\n// just `Emit` function can be called instead.\n// Resource attributes should be provided as ResourceLogsOption arguments.\nfunc (lb *LogsBuilder) EmitForResource(options ...ResourceLogsOption) {\n\trl := plog.NewResourceLogs()\n\tils := rl.ScopeLogs().AppendEmpty()\n\tils.Scope().SetName(ScopeName)\n\tils.Scope().SetVersion(lb.buildInfo.Version)\n\n\tfor _, op := range options {\n\t\top.apply(rl)\n\t}\n\n\tif lb.logRecordsBuffer.Len() > 0 {\n\t\tlb.logRecordsBuffer.MoveAndAppendTo(ils.LogRecords())\n\t\tlb.logRecordsBuffer = plog.NewLogRecordSlice()\n\t}\n\n\tif ils.LogRecords().Len() > 0 {\n\t\trl.MoveTo(lb.logsBuffer.ResourceLogs().AppendEmpty())\n\t}\n}\n\n// Emit returns all the logs accumulated by the logs builder and updates the internal state to be ready for\n// recording another set of logs. This function will be responsible for applying all the transformations required to\n// produce logs representation defined in metadata and user config.\nfunc (lb *LogsBuilder) Emit(options ...ResourceLogsOption) plog.Logs {\n\tlb.EmitForResource(options...)\n\tlogs := lb.logsBuffer\n\tlb.logsBuffer = plog.NewLogs()\n\treturn logs\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/internal/metadata/generated_logs_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\nfunc TestLogsBuilderAppendLogRecord(t *testing.T) {\n\tobservedZapCore, _ := observer.New(zap.WarnLevel)\n\tsettings := receivertest.NewNopSettings(receivertest.NopType)\n\tsettings.Logger = zap.New(observedZapCore)\n\tlb := NewLogsBuilder(settings)\n\n\tres := pcommon.NewResource()\n\n\t// append the first log record\n\tlr := plog.NewLogRecord()\n\tlr.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\tlr.Attributes().PutStr(\"type\", \"log\")\n\tlr.Body().SetStr(\"the first log record\")\n\n\t// append the second log record\n\tlr2 := plog.NewLogRecord()\n\tlr2.SetTimestamp(pcommon.NewTimestampFromTime(time.Now()))\n\tlr2.Attributes().PutStr(\"type\", \"event\")\n\tlr2.Body().SetStr(\"the second log record\")\n\n\tlb.AppendLogRecord(lr)\n\tlb.AppendLogRecord(lr2)\n\n\tlogs := lb.Emit(WithLogsResource(res))\n\tassert.Equal(t, 1, logs.ResourceLogs().Len())\n\n\trl := logs.ResourceLogs().At(0)\n\tassert.Equal(t, 1, rl.ScopeLogs().Len())\n\n\tsl := rl.ScopeLogs().At(0)\n\tassert.Equal(t, ScopeName, sl.Scope().Name())\n\tassert.Equal(t, lb.buildInfo.Version, sl.Scope().Version())\n\n\tassert.Equal(t, 2, sl.LogRecords().Len())\n\n\tattrVal, ok := sl.LogRecords().At(0).Attributes().Get(\"type\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"log\", attrVal.Str())\n\n\tassert.Equal(t, pcommon.ValueTypeStr, sl.LogRecords().At(0).Body().Type())\n\tassert.Equal(t, \"the first log record\", sl.LogRecords().At(0).Body().Str())\n\n\tattrVal, ok = sl.LogRecords().At(1).Attributes().Get(\"type\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"event\", attrVal.Str())\n\n\tassert.Equal(t, pcommon.ValueTypeStr, sl.LogRecords().At(1).Body().Type())\n\tassert.Equal(t, \"the second log record\", sl.LogRecords().At(1).Body().Str())\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/internal/metadata/generated_status.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar (\n\tType      = component.MustNewType(\"otlp\")\n\tScopeName = \"go.opentelemetry.io/collector/receiver/otlpreceiver\"\n)\n\nconst (\n\tProfilesStability = component.StabilityLevelAlpha\n\tTracesStability   = component.StabilityLevelStable\n\tMetricsStability  = component.StabilityLevelStable\n\tLogsStability     = component.StabilityLevelStable\n)\n"
  },
  {
    "path": "receiver/otlpreceiver/internal/metrics/otlp.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage metrics // import \"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/metrics\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/errors\"\n\t\"go.opentelemetry.io/collector/receiver/receiverhelper\"\n)\n\nconst dataFormatProtobuf = \"protobuf\"\n\n// Receiver is the type used to handle metrics from OpenTelemetry exporters.\ntype Receiver struct {\n\tpmetricotlp.UnimplementedGRPCServer\n\tnextConsumer consumer.Metrics\n\tobsreport    *receiverhelper.ObsReport\n}\n\n// New creates a new Receiver reference.\nfunc New(nextConsumer consumer.Metrics, obsreport *receiverhelper.ObsReport) *Receiver {\n\treturn &Receiver{\n\t\tnextConsumer: nextConsumer,\n\t\tobsreport:    obsreport,\n\t}\n}\n\n// Export implements the service Export metrics func.\nfunc (r *Receiver) Export(ctx context.Context, req pmetricotlp.ExportRequest) (pmetricotlp.ExportResponse, error) {\n\tmd := req.Metrics()\n\tdataPointCount := md.DataPointCount()\n\tif dataPointCount == 0 {\n\t\treturn pmetricotlp.NewExportResponse(), nil\n\t}\n\n\tctx = r.obsreport.StartMetricsOp(ctx)\n\terr := r.nextConsumer.ConsumeMetrics(ctx, md)\n\tr.obsreport.EndMetricsOp(ctx, dataFormatProtobuf, dataPointCount, err)\n\n\t// Use appropriate status codes for permanent/non-permanent errors\n\t// If we return the error straightaway, then the grpc implementation will set status code to Unknown\n\t// Refer: https://github.com/grpc/grpc-go/blob/v1.59.0/server.go#L1345\n\t// So, convert the error to appropriate grpc status and return the error\n\t// NonPermanent errors will be converted to codes.Unavailable (equivalent to HTTP 503)\n\t// Permanent errors will be converted to codes.InvalidArgument (equivalent to HTTP 400)\n\tif err != nil {\n\t\treturn pmetricotlp.NewExportResponse(), errors.GetStatusFromError(err)\n\t}\n\n\treturn pmetricotlp.NewExportResponse(), nil\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/internal/metrics/otlp_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage metrics\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/credentials/insecure\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/metadata\"\n\t\"go.opentelemetry.io/collector/receiver/receiverhelper\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\nfunc TestExport(t *testing.T) {\n\tmd := testdata.GenerateMetrics(1)\n\treq := pmetricotlp.NewExportRequestFromMetrics(md)\n\n\tmetricSink := new(consumertest.MetricsSink)\n\tmetricsClient := makeMetricsServiceClient(t, metricSink)\n\tresp, err := metricsClient.Export(context.Background(), req)\n\n\trequire.NoError(t, err, \"Failed to export metrics: %v\", err)\n\trequire.NotNil(t, resp, \"The response is missing\")\n\n\tmds := metricSink.AllMetrics()\n\trequire.Len(t, mds, 1)\n\tassert.Equal(t, md, mds[0])\n}\n\nfunc TestExport_EmptyRequest(t *testing.T) {\n\tmetricSink := new(consumertest.MetricsSink)\n\tmetricsClient := makeMetricsServiceClient(t, metricSink)\n\tresp, err := metricsClient.Export(context.Background(), pmetricotlp.NewExportRequest())\n\trequire.NoError(t, err)\n\trequire.NotNil(t, resp)\n}\n\nfunc TestExport_NonPermanentErrorConsumer(t *testing.T) {\n\tmd := testdata.GenerateMetrics(1)\n\treq := pmetricotlp.NewExportRequestFromMetrics(md)\n\n\tmetricsClient := makeMetricsServiceClient(t, consumertest.NewErr(errors.New(\"my error\")))\n\tresp, err := metricsClient.Export(context.Background(), req)\n\trequire.EqualError(t, err, \"rpc error: code = Unavailable desc = my error\")\n\trequire.ErrorIs(t, err, status.Error(codes.Unavailable, \"my error\"))\n\tassert.Equal(t, pmetricotlp.ExportResponse{}, resp)\n}\n\nfunc TestExport_PermanentErrorConsumer(t *testing.T) {\n\tld := testdata.GenerateMetrics(1)\n\treq := pmetricotlp.NewExportRequestFromMetrics(ld)\n\n\tmetricsClient := makeMetricsServiceClient(t, consumertest.NewErr(consumererror.NewPermanent(errors.New(\"my error\"))))\n\tresp, err := metricsClient.Export(context.Background(), req)\n\trequire.EqualError(t, err, \"rpc error: code = Internal desc = Permanent error: my error\")\n\trequire.ErrorIs(t, err, status.Error(codes.Internal, \"Permanent error: my error\"))\n\tassert.Equal(t, pmetricotlp.ExportResponse{}, resp)\n}\n\nfunc makeMetricsServiceClient(t *testing.T, mc consumer.Metrics) pmetricotlp.GRPCClient {\n\taddr := otlpReceiverOnGRPCServer(t, mc)\n\n\tcc, err := grpc.NewClient(addr.String(), grpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err, \"Failed to create the MetricsServiceClient: %v\", err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, cc.Close())\n\t})\n\n\treturn pmetricotlp.NewGRPCClient(cc)\n}\n\nfunc otlpReceiverOnGRPCServer(t *testing.T, mc consumer.Metrics) net.Addr {\n\tln, err := net.Listen(\"tcp\", \"localhost:\")\n\trequire.NoError(t, err, \"Failed to find an available address to run the gRPC server: %v\", err)\n\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, ln.Close())\n\t})\n\n\tset := receivertest.NewNopSettings(metadata.Type)\n\tset.ID = component.MustNewIDWithName(\"otlp\", \"metrics\")\n\tobsreport, err := receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{\n\t\tReceiverID:             set.ID,\n\t\tTransport:              \"grpc\",\n\t\tReceiverCreateSettings: set,\n\t})\n\trequire.NoError(t, err)\n\tr := New(mc, obsreport)\n\t// Now run it as a gRPC server\n\tsrv := grpc.NewServer()\n\tpmetricotlp.RegisterGRPCServer(srv, r)\n\tgo func() {\n\t\t_ = srv.Serve(ln)\n\t}()\n\n\treturn ln.Addr()\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/internal/metrics/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage metrics\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/internal/profiles/otlp.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage profiles // import \"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/profiles\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/errors\"\n\t\"go.opentelemetry.io/collector/receiver/receiverhelper\"\n)\n\nconst dataFormatProtobuf = \"protobuf\"\n\n// Receiver is the type used to handle spans from OpenTelemetry exporters.\ntype Receiver struct {\n\tpprofileotlp.UnimplementedGRPCServer\n\tnextConsumer xconsumer.Profiles\n\tobsreport    *receiverhelper.ObsReport\n}\n\n// New creates a new Receiver reference.\nfunc New(nextConsumer xconsumer.Profiles, obsreport *receiverhelper.ObsReport) *Receiver {\n\treturn &Receiver{\n\t\tnextConsumer: nextConsumer,\n\t\tobsreport:    obsreport,\n\t}\n}\n\n// Export implements the service Export profiles func.\nfunc (r *Receiver) Export(ctx context.Context, req pprofileotlp.ExportRequest) (pprofileotlp.ExportResponse, error) {\n\ttd := req.Profiles()\n\t// We need to ensure that it propagates the receiver name as a tag\n\tnumSamples := td.SampleCount()\n\tif numSamples == 0 {\n\t\treturn pprofileotlp.NewExportResponse(), nil\n\t}\n\n\tctx = r.obsreport.StartTracesOp(ctx)\n\terr := r.nextConsumer.ConsumeProfiles(ctx, td)\n\tr.obsreport.EndTracesOp(ctx, dataFormatProtobuf, numSamples, err)\n\n\t// Use appropriate status codes for permanent/non-permanent errors\n\t// If we return the error straightaway, then the grpc implementation will set status code to Unknown\n\t// Refer: https://github.com/grpc/grpc-go/blob/v1.59.0/server.go#L1345\n\t// So, convert the error to appropriate grpc status and return the error\n\t// NonPermanent errors will be converted to codes.Unavailable (equivalent to HTTP 503)\n\t// Permanent errors will be converted to codes.InvalidArgument (equivalent to HTTP 400)\n\tif err != nil {\n\t\treturn pprofileotlp.NewExportResponse(), errors.GetStatusFromError(err)\n\t}\n\n\treturn pprofileotlp.NewExportResponse(), nil\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/internal/profiles/otlp_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage profiles\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/credentials/insecure\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/metadata\"\n\t\"go.opentelemetry.io/collector/receiver/receiverhelper\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\nfunc TestExport(t *testing.T) {\n\ttd := testdata.GenerateProfiles(1)\n\treq := pprofileotlp.NewExportRequestFromProfiles(td)\n\n\tprofileSink := new(consumertest.ProfilesSink)\n\tprofileClient := makeProfileServiceClient(t, profileSink)\n\tresp, err := profileClient.Export(context.Background(), req)\n\trequire.NoError(t, err, \"Failed to export profile: %v\", err)\n\trequire.NotNil(t, resp, \"The response is missing\")\n\n\trequire.Len(t, profileSink.AllProfiles(), 1)\n\tassert.Equal(t, td, profileSink.AllProfiles()[0])\n}\n\nfunc TestExport_EmptyRequest(t *testing.T) {\n\tprofileSink := new(consumertest.ProfilesSink)\n\tprofileClient := makeProfileServiceClient(t, profileSink)\n\tresp, err := profileClient.Export(context.Background(), pprofileotlp.NewExportRequest())\n\trequire.NoError(t, err, \"Failed to export profile: %v\", err)\n\tassert.NotNil(t, resp, \"The response is missing\")\n}\n\nfunc TestExport_NonPermanentErrorConsumer(t *testing.T) {\n\ttd := testdata.GenerateProfiles(1)\n\treq := pprofileotlp.NewExportRequestFromProfiles(td)\n\n\tprofileClient := makeProfileServiceClient(t, consumertest.NewErr(errors.New(\"my error\")))\n\tresp, err := profileClient.Export(context.Background(), req)\n\trequire.EqualError(t, err, \"rpc error: code = Unavailable desc = my error\")\n\trequire.ErrorIs(t, err, status.Error(codes.Unavailable, \"my error\"))\n\tassert.Equal(t, pprofileotlp.ExportResponse{}, resp)\n}\n\nfunc TestExport_PermanentErrorConsumer(t *testing.T) {\n\tld := testdata.GenerateProfiles(1)\n\treq := pprofileotlp.NewExportRequestFromProfiles(ld)\n\n\tprofileClient := makeProfileServiceClient(t, consumertest.NewErr(consumererror.NewPermanent(errors.New(\"my error\"))))\n\tresp, err := profileClient.Export(context.Background(), req)\n\trequire.EqualError(t, err, \"rpc error: code = Internal desc = Permanent error: my error\")\n\trequire.ErrorIs(t, err, status.Error(codes.Internal, \"Permanent error: my error\"))\n\tassert.Equal(t, pprofileotlp.ExportResponse{}, resp)\n}\n\nfunc makeProfileServiceClient(t *testing.T, tc xconsumer.Profiles) pprofileotlp.GRPCClient {\n\taddr := otlpReceiverOnGRPCServer(t, tc)\n\tcc, err := grpc.NewClient(addr.String(), grpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err, \"Failed to create the profileServiceClient: %v\", err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, cc.Close())\n\t})\n\n\treturn pprofileotlp.NewGRPCClient(cc)\n}\n\nfunc otlpReceiverOnGRPCServer(t *testing.T, tc xconsumer.Profiles) net.Addr {\n\tln, err := net.Listen(\"tcp\", \"localhost:\")\n\trequire.NoError(t, err, \"Failed to find an available address to run the gRPC server: %v\", err)\n\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, ln.Close())\n\t})\n\n\tset := receivertest.NewNopSettings(metadata.Type)\n\tset.ID = component.MustNewIDWithName(\"otlp\", \"profiles\")\n\tobsreport, err := receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{\n\t\tReceiverID:             set.ID,\n\t\tTransport:              \"grpc\",\n\t\tReceiverCreateSettings: set,\n\t})\n\trequire.NoError(t, err)\n\n\tr := New(tc, obsreport)\n\t// Now run it as a gRPC server\n\tsrv := grpc.NewServer()\n\tpprofileotlp.RegisterGRPCServer(srv, r)\n\tgo func() {\n\t\t_ = srv.Serve(ln)\n\t}()\n\n\treturn ln.Addr()\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/internal/profiles/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage profiles\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/internal/trace/otlp.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage trace // import \"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/trace\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/errors\"\n\t\"go.opentelemetry.io/collector/receiver/receiverhelper\"\n)\n\nconst dataFormatProtobuf = \"protobuf\"\n\n// Receiver is the type used to handle spans from OpenTelemetry exporters.\ntype Receiver struct {\n\tptraceotlp.UnimplementedGRPCServer\n\tnextConsumer consumer.Traces\n\tobsreport    *receiverhelper.ObsReport\n}\n\n// New creates a new Receiver reference.\nfunc New(nextConsumer consumer.Traces, obsreport *receiverhelper.ObsReport) *Receiver {\n\treturn &Receiver{\n\t\tnextConsumer: nextConsumer,\n\t\tobsreport:    obsreport,\n\t}\n}\n\n// Export implements the service Export traces func.\nfunc (r *Receiver) Export(ctx context.Context, req ptraceotlp.ExportRequest) (ptraceotlp.ExportResponse, error) {\n\ttd := req.Traces()\n\t// We need to ensure that it propagates the receiver name as a tag\n\tnumSpans := td.SpanCount()\n\tif numSpans == 0 {\n\t\treturn ptraceotlp.NewExportResponse(), nil\n\t}\n\n\tctx = r.obsreport.StartTracesOp(ctx)\n\terr := r.nextConsumer.ConsumeTraces(ctx, td)\n\tr.obsreport.EndTracesOp(ctx, dataFormatProtobuf, numSpans, err)\n\n\t// Use appropriate status codes for permanent/non-permanent errors\n\t// If we return the error straightaway, then the grpc implementation will set status code to Unknown\n\t// Refer: https://github.com/grpc/grpc-go/blob/v1.59.0/server.go#L1345\n\t// So, convert the error to appropriate grpc status and return the error\n\t// NonPermanent errors will be converted to codes.Unavailable (equivalent to HTTP 503)\n\t// Permanent errors will be converted to codes.InvalidArgument (equivalent to HTTP 400)\n\tif err != nil {\n\t\treturn ptraceotlp.NewExportResponse(), errors.GetStatusFromError(err)\n\t}\n\n\treturn ptraceotlp.NewExportResponse(), nil\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/internal/trace/otlp_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage trace\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/credentials/insecure\"\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/metadata\"\n\t\"go.opentelemetry.io/collector/receiver/receiverhelper\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\nfunc TestExport(t *testing.T) {\n\ttd := testdata.GenerateTraces(1)\n\treq := ptraceotlp.NewExportRequestFromTraces(td)\n\n\ttraceSink := new(consumertest.TracesSink)\n\ttraceClient := makeTraceServiceClient(t, traceSink)\n\tresp, err := traceClient.Export(context.Background(), req)\n\trequire.NoError(t, err, \"Failed to export trace: %v\", err)\n\trequire.NotNil(t, resp, \"The response is missing\")\n\n\trequire.Len(t, traceSink.AllTraces(), 1)\n\tassert.Equal(t, td, traceSink.AllTraces()[0])\n}\n\nfunc TestExport_EmptyRequest(t *testing.T) {\n\ttraceSink := new(consumertest.TracesSink)\n\ttraceClient := makeTraceServiceClient(t, traceSink)\n\tresp, err := traceClient.Export(context.Background(), ptraceotlp.NewExportRequest())\n\trequire.NoError(t, err, \"Failed to export trace: %v\", err)\n\tassert.NotNil(t, resp, \"The response is missing\")\n}\n\nfunc TestExport_NonPermanentErrorConsumer(t *testing.T) {\n\ttd := testdata.GenerateTraces(1)\n\treq := ptraceotlp.NewExportRequestFromTraces(td)\n\n\ttraceClient := makeTraceServiceClient(t, consumertest.NewErr(errors.New(\"my error\")))\n\tresp, err := traceClient.Export(context.Background(), req)\n\trequire.EqualError(t, err, \"rpc error: code = Unavailable desc = my error\")\n\trequire.ErrorIs(t, err, status.Error(codes.Unavailable, \"my error\"))\n\tassert.Equal(t, ptraceotlp.ExportResponse{}, resp)\n}\n\nfunc TestExport_PermanentErrorConsumer(t *testing.T) {\n\tld := testdata.GenerateTraces(1)\n\treq := ptraceotlp.NewExportRequestFromTraces(ld)\n\n\ttraceClient := makeTraceServiceClient(t, consumertest.NewErr(consumererror.NewPermanent(errors.New(\"my error\"))))\n\tresp, err := traceClient.Export(context.Background(), req)\n\trequire.EqualError(t, err, \"rpc error: code = Internal desc = Permanent error: my error\")\n\trequire.ErrorIs(t, err, status.Error(codes.Internal, \"Permanent error: my error\"))\n\tassert.Equal(t, ptraceotlp.ExportResponse{}, resp)\n}\n\nfunc makeTraceServiceClient(t *testing.T, tc consumer.Traces) ptraceotlp.GRPCClient {\n\taddr := otlpReceiverOnGRPCServer(t, tc)\n\tcc, err := grpc.NewClient(addr.String(), grpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err, \"Failed to create the TraceServiceClient: %v\", err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, cc.Close())\n\t})\n\n\treturn ptraceotlp.NewGRPCClient(cc)\n}\n\nfunc otlpReceiverOnGRPCServer(t *testing.T, tc consumer.Traces) net.Addr {\n\tln, err := net.Listen(\"tcp\", \"localhost:\")\n\trequire.NoError(t, err, \"Failed to find an available address to run the gRPC server: %v\", err)\n\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, ln.Close())\n\t})\n\n\tset := receivertest.NewNopSettings(metadata.Type)\n\tset.ID = component.MustNewIDWithName(\"otlp\", \"trace\")\n\tobsreport, err := receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{\n\t\tReceiverID:             set.ID,\n\t\tTransport:              \"grpc\",\n\t\tReceiverCreateSettings: set,\n\t})\n\trequire.NoError(t, err)\n\tr := New(tc, obsreport)\n\t// Now run it as a gRPC server\n\tsrv := grpc.NewServer()\n\tptraceotlp.RegisterGRPCServer(srv, r)\n\tgo func() {\n\t\t_ = srv.Serve(ln)\n\t}()\n\n\treturn ln.Addr()\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/internal/trace/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage trace\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/metadata.yaml",
    "content": "display_name: OTLP Receiver\ntype: otlp\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: receiver\n  stability:\n    stable: [traces, metrics, logs]\n    alpha: [profiles]\n  distributions: [core, contrib, k8s, otlp]\n"
  },
  {
    "path": "receiver/otlpreceiver/otlp.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlpreceiver // import \"go.opentelemetry.io/collector/receiver/otlpreceiver\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net\"\n\t\"net/http\"\n\t\"sync\"\n\n\t\"go.uber.org/zap\"\n\t\"google.golang.org/grpc\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componentstatus\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/internal/telemetry\"\n\t\"go.opentelemetry.io/collector/pdata/plog/plogotlp\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile/pprofileotlp\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/logs\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/metrics\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/profiles\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/trace\"\n\t\"go.opentelemetry.io/collector/receiver/receiverhelper\"\n)\n\n// otlpReceiver is the type that exposes Trace and Metrics reception.\ntype otlpReceiver struct {\n\tcfg        *Config\n\tserverGRPC *grpc.Server\n\tserverHTTP *http.Server\n\n\tnextTraces   consumer.Traces\n\tnextMetrics  consumer.Metrics\n\tnextLogs     consumer.Logs\n\tnextProfiles xconsumer.Profiles\n\tshutdownWG   sync.WaitGroup\n\n\tobsrepGRPC *receiverhelper.ObsReport\n\tobsrepHTTP *receiverhelper.ObsReport\n\n\tsettings *receiver.Settings\n}\n\n// newOtlpReceiver just creates the OpenTelemetry receiver services. It is the caller's\n// responsibility to invoke the respective Start*Reception methods as well\n// as the various Stop*Reception methods to end it.\nfunc newOtlpReceiver(cfg *Config, set *receiver.Settings) (*otlpReceiver, error) {\n\tset.TelemetrySettings = telemetry.DropInjectedAttributes(set.TelemetrySettings, telemetry.SignalKey)\n\tset.Logger.Debug(\"created signal-agnostic logger\")\n\tr := &otlpReceiver{\n\t\tcfg:          cfg,\n\t\tnextTraces:   nil,\n\t\tnextMetrics:  nil,\n\t\tnextLogs:     nil,\n\t\tnextProfiles: nil,\n\t\tsettings:     set,\n\t}\n\n\tvar err error\n\tr.obsrepGRPC, err = receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{\n\t\tReceiverID:             set.ID,\n\t\tTransport:              \"grpc\",\n\t\tReceiverCreateSettings: *set,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tr.obsrepHTTP, err = receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{\n\t\tReceiverID:             set.ID,\n\t\tTransport:              \"http\",\n\t\tReceiverCreateSettings: *set,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn r, nil\n}\n\nfunc (r *otlpReceiver) startGRPCServer(ctx context.Context, host component.Host) error {\n\t// If GRPC is not enabled, nothing to start.\n\tif !r.cfg.GRPC.HasValue() {\n\t\treturn nil\n\t}\n\n\tgrpcCfg := r.cfg.GRPC.Get()\n\tvar err error\n\tif r.serverGRPC, err = grpcCfg.ToServer(ctx, host.GetExtensions(), r.settings.TelemetrySettings); err != nil {\n\t\treturn err\n\t}\n\n\tif r.nextTraces != nil {\n\t\tptraceotlp.RegisterGRPCServer(r.serverGRPC, trace.New(r.nextTraces, r.obsrepGRPC))\n\t}\n\n\tif r.nextMetrics != nil {\n\t\tpmetricotlp.RegisterGRPCServer(r.serverGRPC, metrics.New(r.nextMetrics, r.obsrepGRPC))\n\t}\n\n\tif r.nextLogs != nil {\n\t\tplogotlp.RegisterGRPCServer(r.serverGRPC, logs.New(r.nextLogs, r.obsrepGRPC))\n\t}\n\n\tif r.nextProfiles != nil {\n\t\tpprofileotlp.RegisterGRPCServer(r.serverGRPC, profiles.New(r.nextProfiles, r.obsrepGRPC))\n\t}\n\n\tvar gln net.Listener\n\tif gln, err = grpcCfg.NetAddr.Listen(ctx); err != nil {\n\t\treturn err\n\t}\n\tr.settings.Logger.Info(\"Starting GRPC server\", zap.String(\"endpoint\", gln.Addr().String()))\n\n\tr.shutdownWG.Go(func() {\n\t\tif errGrpc := r.serverGRPC.Serve(gln); errGrpc != nil && !errors.Is(errGrpc, grpc.ErrServerStopped) {\n\t\t\tcomponentstatus.ReportStatus(host, componentstatus.NewFatalErrorEvent(errGrpc))\n\t\t}\n\t})\n\treturn nil\n}\n\nfunc (r *otlpReceiver) startHTTPServer(ctx context.Context, host component.Host) error {\n\t// If HTTP is not enabled, nothing to start.\n\tif !r.cfg.HTTP.HasValue() {\n\t\treturn nil\n\t}\n\n\thttpCfg := r.cfg.HTTP.Get()\n\thttpMux := http.NewServeMux()\n\tif r.nextTraces != nil {\n\t\thttpTracesReceiver := trace.New(r.nextTraces, r.obsrepHTTP)\n\t\thttpMux.HandleFunc(string(httpCfg.TracesURLPath), func(resp http.ResponseWriter, req *http.Request) {\n\t\t\thandleTraces(resp, req, httpTracesReceiver)\n\t\t})\n\t}\n\n\tif r.nextMetrics != nil {\n\t\thttpMetricsReceiver := metrics.New(r.nextMetrics, r.obsrepHTTP)\n\t\thttpMux.HandleFunc(string(httpCfg.MetricsURLPath), func(resp http.ResponseWriter, req *http.Request) {\n\t\t\thandleMetrics(resp, req, httpMetricsReceiver)\n\t\t})\n\t}\n\n\tif r.nextLogs != nil {\n\t\thttpLogsReceiver := logs.New(r.nextLogs, r.obsrepHTTP)\n\t\thttpMux.HandleFunc(string(httpCfg.LogsURLPath), func(resp http.ResponseWriter, req *http.Request) {\n\t\t\thandleLogs(resp, req, httpLogsReceiver)\n\t\t})\n\t}\n\n\tif r.nextProfiles != nil {\n\t\thttpProfilesReceiver := profiles.New(r.nextProfiles, r.obsrepHTTP)\n\t\thttpMux.HandleFunc(defaultProfilesURLPath, func(resp http.ResponseWriter, req *http.Request) {\n\t\t\thandleProfiles(resp, req, httpProfilesReceiver)\n\t\t})\n\t}\n\n\tvar err error\n\tif r.serverHTTP, err = httpCfg.ServerConfig.ToServer(ctx, host.GetExtensions(), r.settings.TelemetrySettings, httpMux, confighttp.WithErrorHandler(errorHandler)); err != nil {\n\t\treturn err\n\t}\n\n\tvar hln net.Listener\n\tif hln, err = httpCfg.ServerConfig.ToListener(ctx); err != nil {\n\t\treturn err\n\t}\n\tr.settings.Logger.Info(\"Starting HTTP server\", zap.String(\"endpoint\", hln.Addr().String()))\n\n\tr.shutdownWG.Go(func() {\n\t\tif errHTTP := r.serverHTTP.Serve(hln); errHTTP != nil && !errors.Is(errHTTP, http.ErrServerClosed) {\n\t\t\tcomponentstatus.ReportStatus(host, componentstatus.NewFatalErrorEvent(errHTTP))\n\t\t}\n\t})\n\treturn nil\n}\n\n// Start runs the trace receiver on the gRPC server. Currently\n// it also enables the metrics receiver too.\nfunc (r *otlpReceiver) Start(ctx context.Context, host component.Host) error {\n\tif err := r.startGRPCServer(ctx, host); err != nil {\n\t\treturn err\n\t}\n\tif err := r.startHTTPServer(ctx, host); err != nil {\n\t\t// It's possible that a valid GRPC server configuration was specified,\n\t\t// but an invalid HTTP configuration. If that's the case, the successfully\n\t\t// started GRPC server must be shutdown to ensure no goroutines are leaked.\n\t\treturn errors.Join(err, r.Shutdown(ctx))\n\t}\n\n\treturn nil\n}\n\n// Shutdown is a method to turn off receiving.\nfunc (r *otlpReceiver) Shutdown(ctx context.Context) error {\n\tvar err error\n\n\tif r.serverHTTP != nil {\n\t\terr = r.serverHTTP.Shutdown(ctx)\n\t}\n\n\tif r.serverGRPC != nil {\n\t\tr.serverGRPC.GracefulStop()\n\t}\n\n\tr.shutdownWG.Wait()\n\treturn err\n}\n\nfunc (r *otlpReceiver) registerTraceConsumer(tc consumer.Traces) {\n\tr.nextTraces = tc\n}\n\nfunc (r *otlpReceiver) registerMetricsConsumer(mc consumer.Metrics) {\n\tr.nextMetrics = mc\n}\n\nfunc (r *otlpReceiver) registerLogsConsumer(lc consumer.Logs) {\n\tr.nextLogs = lc\n}\n\nfunc (r *otlpReceiver) registerProfilesConsumer(tc xconsumer.Profiles) {\n\tr.nextProfiles = tc\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/otlp_benchmark_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlpreceiver\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"io\"\n\t\"net/http\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/credentials/insecure\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/plog/plogotlp\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/metadata\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\nconst (\n\titemsPerRequest     = 10_000\n\tprotobufContentType = \"application/x-protobuf\"\n)\n\nfunc startLogsReceiver(b *testing.B, cfg *Config, sink *consumertest.LogsSink) {\n\tset := receivertest.NewNopSettings(metadata.Type)\n\tfactory := NewFactory()\n\tr, err := factory.CreateLogs(b.Context(), set, cfg, sink)\n\trequire.NoError(b, err)\n\n\trequire.NoError(b, r.Start(b.Context(), componenttest.NewNopHost()))\n\tb.Cleanup(func() {\n\t\trequire.NoError(b, r.Shutdown(context.Background()))\n\t})\n}\n\n// BenchmarkGRPCLogsSequential benchmarks sequentially receiving logs over OTLP/gRPC.\n// A typical deployment would receive multiple concurrent requests, this benchmark tries to\n// measure the performance of the receiver without concurrency to have a more stable benchmark.\nfunc BenchmarkGRPCLogsSequential(b *testing.B) {\n\tendpoint := testutil.GetAvailableLocalAddress(b)\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.GRPC.GetOrInsertDefault().NetAddr.Endpoint = endpoint\n\tvar sink consumertest.LogsSink\n\tstartLogsReceiver(b, cfg, &sink)\n\n\tcc, err := grpc.NewClient(endpoint, grpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(b, err)\n\tb.Cleanup(func() { require.NoError(b, cc.Close()) })\n\tlogClient := plogotlp.NewGRPCClient(cc)\n\treq := plogotlp.NewExportRequestFromLogs(testdata.GenerateLogs(itemsPerRequest))\n\n\tfor b.Loop() {\n\t\t_, err := logClient.Export(b.Context(), req)\n\t\trequire.NoError(b, err)\n\t}\n\n\trequire.Equal(b, b.N*itemsPerRequest, sink.LogRecordCount())\n}\n\n// BenchmarkHTTPProtoLogsSequential benchmarks sequentially receiving logs over OTLP/HTTP (proto).\n// A typical deployment would receive multiple concurrent requests, this benchmark tries to\n// measure the performance of the receiver without concurrency to have a more stable benchmark.\nfunc BenchmarkHTTPProtoLogsSequential(b *testing.B) {\n\tendpoint := testutil.GetAvailableLocalAddress(b)\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.HTTP.GetOrInsertDefault().ServerConfig.NetAddr.Endpoint = endpoint\n\tvar sink consumertest.LogsSink\n\tstartLogsReceiver(b, cfg, &sink)\n\n\tmarshaler := &plog.ProtoMarshaler{}\n\tbodyBytes, err := marshaler.MarshalLogs(testdata.GenerateLogs(itemsPerRequest))\n\trequire.NoError(b, err)\n\treq, err := http.NewRequest(http.MethodPost, \"http://\"+endpoint+defaultLogsURLPath, bytes.NewReader(bodyBytes))\n\trequire.NoError(b, err)\n\treq.Header.Set(\"Content-Type\", protobufContentType)\n\n\treader := bytes.NewReader(bodyBytes)\n\tfor b.Loop() {\n\t\treader.Reset(bodyBytes)\n\t\treq.Body = io.NopCloser(reader)\n\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\trequire.NoError(b, err)\n\t\trequire.Equal(b, http.StatusOK, resp.StatusCode)\n\t\tresp.Body.Close()\n\t}\n\n\trequire.Equal(b, b.N*itemsPerRequest, sink.LogRecordCount())\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/otlp_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlpreceiver\n\nimport (\n\t\"bytes\"\n\t\"compress/gzip\"\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"net\"\n\t\"net/http\"\n\t\"strings\"\n\t\"sync\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/klauspost/compress/zstd\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\tspb \"google.golang.org/genproto/googleapis/rpc/status\"\n\t\"google.golang.org/grpc\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/credentials/insecure\"\n\t\"google.golang.org/grpc/status\"\n\t\"google.golang.org/protobuf/proto\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configgrpc\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n\t\"go.opentelemetry.io/collector/config/configoptional\"\n\t\"go.opentelemetry.io/collector/config/configtls\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/metadata\"\n\t\"go.opentelemetry.io/collector/receiver/receiverhelper\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n)\n\nconst otlpReceiverName = \"receiver_test\"\n\nvar otlpReceiverID = component.MustNewIDWithName(\"otlp\", otlpReceiverName)\n\nfunc TestJSONHTTP(t *testing.T) {\n\ttests := []struct {\n\t\tname               string\n\t\tencoding           string\n\t\tcontentType        string\n\t\terr                error\n\t\texpectedStatus     *spb.Status\n\t\texpectedStatusCode int\n\t}{\n\t\t{\n\t\t\tname:        \"JSONUncompressed\",\n\t\t\tencoding:    \"\",\n\t\t\tcontentType: \"application/json\",\n\t\t},\n\t\t{\n\t\t\tname:        \"JSONUncompressedUTF8\",\n\t\t\tencoding:    \"\",\n\t\t\tcontentType: \"application/json; charset=utf-8\",\n\t\t},\n\t\t{\n\t\t\tname:        \"JSONUncompressedUppercase\",\n\t\t\tencoding:    \"\",\n\t\t\tcontentType: \"APPLICATION/JSON\",\n\t\t},\n\t\t{\n\t\t\tname:        \"JSONGzipCompressed\",\n\t\t\tencoding:    \"gzip\",\n\t\t\tcontentType: \"application/json\",\n\t\t},\n\t\t{\n\t\t\tname:        \"JSONZstdCompressed\",\n\t\t\tencoding:    \"zstd\",\n\t\t\tcontentType: \"application/json\",\n\t\t},\n\t\t{\n\t\t\tname:               \"Permanent NotGRPCError\",\n\t\t\tencoding:           \"\",\n\t\t\tcontentType:        \"application/json\",\n\t\t\terr:                consumererror.NewPermanent(errors.New(\"my error\")),\n\t\t\texpectedStatus:     &spb.Status{Code: int32(codes.Internal), Message: \"Permanent error: my error\"},\n\t\t\texpectedStatusCode: http.StatusInternalServerError,\n\t\t},\n\t\t{\n\t\t\tname:               \"Retryable NotGRPCError\",\n\t\t\tencoding:           \"\",\n\t\t\tcontentType:        \"application/json\",\n\t\t\terr:                errors.New(\"my error\"),\n\t\t\texpectedStatus:     &spb.Status{Code: int32(codes.Unavailable), Message: \"my error\"},\n\t\t\texpectedStatusCode: http.StatusServiceUnavailable,\n\t\t},\n\t\t{\n\t\t\tname:               \"Permanent GRPCError\",\n\t\t\tencoding:           \"\",\n\t\t\tcontentType:        \"application/json\",\n\t\t\terr:                status.New(codes.Internal, \"\").Err(),\n\t\t\texpectedStatus:     &spb.Status{Code: int32(codes.Internal), Message: \"\"},\n\t\t\texpectedStatusCode: http.StatusInternalServerError,\n\t\t},\n\t\t{\n\t\t\tname:               \"Retryable GRPCError\",\n\t\t\tencoding:           \"\",\n\t\t\tcontentType:        \"application/json\",\n\t\t\terr:                status.New(codes.Unavailable, \"Service Unavailable\").Err(),\n\t\t\texpectedStatus:     &spb.Status{Code: int32(codes.Unavailable), Message: \"Service Unavailable\"},\n\t\t\texpectedStatusCode: http.StatusServiceUnavailable,\n\t\t},\n\t}\n\taddr := testutil.GetAvailableLocalAddress(t)\n\tsink := newErrOrSinkConsumer()\n\trecv := newHTTPReceiver(t, componenttest.NewNopTelemetrySettings(), addr, sink)\n\trequire.NoError(t, recv.Start(context.Background(), componenttest.NewNopHost()), \"Failed to start trace receiver\")\n\tt.Cleanup(func() { require.NoError(t, recv.Shutdown(context.Background())) })\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsink.Reset()\n\t\t\tsink.SetConsumeError(tt.err)\n\n\t\t\tfor _, dr := range generateDataRequests(t) {\n\t\t\t\turl := \"http://\" + addr + dr.path\n\t\t\t\trespBytes := doHTTPRequest(t, url, tt.encoding, tt.contentType, dr.jsonBytes, tt.expectedStatusCode)\n\t\t\t\tif tt.err == nil {\n\t\t\t\t\ttr := ptraceotlp.NewExportResponse()\n\t\t\t\t\trequire.NoError(t, tr.UnmarshalJSON(respBytes), \"Unable to unmarshal response to Response\")\n\t\t\t\t\tsink.checkData(t, dr.data, 1)\n\t\t\t\t} else {\n\t\t\t\t\terrStatus := &spb.Status{}\n\t\t\t\t\trequire.NoError(t, json.Unmarshal(respBytes, errStatus))\n\t\t\t\t\tif s, ok := status.FromError(tt.err); ok {\n\t\t\t\t\t\tassert.Equal(t, s.Proto().Code, errStatus.Code)\n\t\t\t\t\t\tassert.Equal(t, s.Proto().Message, errStatus.Message)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Println(errStatus)\n\t\t\t\t\t\tassert.True(t, proto.Equal(errStatus, tt.expectedStatus))\n\t\t\t\t\t}\n\t\t\t\t\tsink.checkData(t, dr.data, 0)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestHandleInvalidRequests(t *testing.T) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\tsink := newErrOrSinkConsumer()\n\trecv := newHTTPReceiver(t, componenttest.NewNopTelemetrySettings(), addr, sink)\n\trequire.NoError(t, recv.Start(context.Background(), componenttest.NewNopHost()), \"Failed to start trace receiver\")\n\tt.Cleanup(func() { require.NoError(t, recv.Shutdown(context.Background())) })\n\n\ttests := []struct {\n\t\tname        string\n\t\turi         string\n\t\tmethod      string\n\t\tcontentType string\n\n\t\texpectedStatus       int\n\t\texpectedResponseBody string\n\t}{\n\t\t{\n\t\t\tname:        \"no content type\",\n\t\t\turi:         defaultTracesURLPath,\n\t\t\tmethod:      http.MethodPost,\n\t\t\tcontentType: \"\",\n\n\t\t\texpectedStatus:       http.StatusUnsupportedMediaType,\n\t\t\texpectedResponseBody: \"415 unsupported media type, supported: [application/json, application/x-protobuf]\",\n\t\t},\n\t\t{\n\t\t\tname:        \"invalid content type\",\n\t\t\turi:         defaultTracesURLPath,\n\t\t\tmethod:      http.MethodPost,\n\t\t\tcontentType: \"invalid\",\n\n\t\t\texpectedStatus:       http.StatusUnsupportedMediaType,\n\t\t\texpectedResponseBody: \"415 unsupported media type, supported: [application/json, application/x-protobuf]\",\n\t\t},\n\t\t{\n\t\t\tname:        \"invalid request\",\n\t\t\turi:         defaultTracesURLPath,\n\t\t\tmethod:      http.MethodPost,\n\t\t\tcontentType: \"application/json\",\n\n\t\t\texpectedStatus: http.StatusBadRequest,\n\t\t},\n\t\t{\n\t\t\turi:         defaultTracesURLPath,\n\t\t\tmethod:      http.MethodPatch,\n\t\t\tcontentType: \"application/json\",\n\n\t\t\texpectedStatus:       http.StatusMethodNotAllowed,\n\t\t\texpectedResponseBody: \"405 method not allowed, supported: [POST]\",\n\t\t},\n\t\t{\n\t\t\turi:         defaultTracesURLPath,\n\t\t\tmethod:      http.MethodGet,\n\t\t\tcontentType: \"application/json\",\n\n\t\t\texpectedStatus:       http.StatusMethodNotAllowed,\n\t\t\texpectedResponseBody: \"405 method not allowed, supported: [POST]\",\n\t\t},\n\t\t{\n\t\t\tname:        \"no content type\",\n\t\t\turi:         defaultMetricsURLPath,\n\t\t\tmethod:      http.MethodPost,\n\t\t\tcontentType: \"\",\n\n\t\t\texpectedStatus:       http.StatusUnsupportedMediaType,\n\t\t\texpectedResponseBody: \"415 unsupported media type, supported: [application/json, application/x-protobuf]\",\n\t\t},\n\t\t{\n\t\t\tname:        \"invalid content type\",\n\t\t\turi:         defaultMetricsURLPath,\n\t\t\tmethod:      http.MethodPost,\n\t\t\tcontentType: \"invalid\",\n\n\t\t\texpectedStatus:       http.StatusUnsupportedMediaType,\n\t\t\texpectedResponseBody: \"415 unsupported media type, supported: [application/json, application/x-protobuf]\",\n\t\t},\n\t\t{\n\t\t\tname:        \"invalid request\",\n\t\t\turi:         defaultMetricsURLPath,\n\t\t\tmethod:      http.MethodPost,\n\t\t\tcontentType: \"application/json\",\n\n\t\t\texpectedStatus: http.StatusBadRequest,\n\t\t},\n\t\t{\n\t\t\turi:         defaultMetricsURLPath,\n\t\t\tmethod:      http.MethodPatch,\n\t\t\tcontentType: \"application/json\",\n\n\t\t\texpectedStatus:       http.StatusMethodNotAllowed,\n\t\t\texpectedResponseBody: \"405 method not allowed, supported: [POST]\",\n\t\t},\n\t\t{\n\t\t\turi:         defaultMetricsURLPath,\n\t\t\tmethod:      http.MethodGet,\n\t\t\tcontentType: \"application/json\",\n\n\t\t\texpectedStatus:       http.StatusMethodNotAllowed,\n\t\t\texpectedResponseBody: \"405 method not allowed, supported: [POST]\",\n\t\t},\n\t\t{\n\t\t\tname:        \"no content type\",\n\t\t\turi:         defaultLogsURLPath,\n\t\t\tmethod:      http.MethodPost,\n\t\t\tcontentType: \"\",\n\n\t\t\texpectedStatus:       http.StatusUnsupportedMediaType,\n\t\t\texpectedResponseBody: \"415 unsupported media type, supported: [application/json, application/x-protobuf]\",\n\t\t},\n\t\t{\n\t\t\tname:        \"invalid content type\",\n\t\t\turi:         defaultLogsURLPath,\n\t\t\tmethod:      http.MethodPost,\n\t\t\tcontentType: \"invalid\",\n\n\t\t\texpectedStatus:       http.StatusUnsupportedMediaType,\n\t\t\texpectedResponseBody: \"415 unsupported media type, supported: [application/json, application/x-protobuf]\",\n\t\t},\n\t\t{\n\t\t\tname:        \"invalid request\",\n\t\t\turi:         defaultLogsURLPath,\n\t\t\tmethod:      http.MethodPost,\n\t\t\tcontentType: \"application/json\",\n\n\t\t\texpectedStatus: http.StatusBadRequest,\n\t\t},\n\t\t{\n\t\t\turi:         defaultLogsURLPath,\n\t\t\tmethod:      http.MethodPatch,\n\t\t\tcontentType: \"application/json\",\n\n\t\t\texpectedStatus:       http.StatusMethodNotAllowed,\n\t\t\texpectedResponseBody: \"405 method not allowed, supported: [POST]\",\n\t\t},\n\t\t{\n\t\t\turi:         defaultLogsURLPath,\n\t\t\tmethod:      http.MethodGet,\n\t\t\tcontentType: \"application/json\",\n\n\t\t\texpectedStatus:       http.StatusMethodNotAllowed,\n\t\t\texpectedResponseBody: \"405 method not allowed, supported: [POST]\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.method+\" \"+tt.uri+\" \"+tt.name, func(t *testing.T) {\n\t\t\turl := \"http://\" + addr + tt.uri\n\t\t\treq, err := http.NewRequest(tt.method, url, bytes.NewReader([]byte(`1234`)))\n\t\t\trequire.NoError(t, err)\n\t\t\treq.Header.Set(\"Content-Type\", tt.contentType)\n\n\t\t\tresp, err := http.DefaultClient.Do(req)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tbody, err := io.ReadAll(resp.Body)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tif tt.name == \"invalid request\" {\n\t\t\t\tassert.Equal(t, \"application/json\", resp.Header.Get(\"Content-Type\"))\n\t\t\t\tassert.Equal(t, tt.expectedStatus, resp.StatusCode)\n\t\t\t\treturn\n\t\t\t}\n\t\t\tassert.Equal(t, \"text/plain\", resp.Header.Get(\"Content-Type\"))\n\t\t\tassert.Equal(t, tt.expectedStatus, resp.StatusCode)\n\t\t\tassert.Equal(t, tt.expectedResponseBody, string(body))\n\t\t})\n\t}\n\n\trequire.NoError(t, recv.Shutdown(context.Background()))\n}\n\nfunc TestProtoHTTP(t *testing.T) {\n\ttests := []struct {\n\t\tname               string\n\t\tencoding           string\n\t\terr                error\n\t\texpectedStatus     *spb.Status\n\t\texpectedStatusCode int\n\t}{\n\t\t{\n\t\t\tname:     \"ProtoUncompressed\",\n\t\t\tencoding: \"\",\n\t\t},\n\t\t{\n\t\t\tname:     \"ProtoGzipCompressed\",\n\t\t\tencoding: \"gzip\",\n\t\t},\n\t\t{\n\t\t\tname:     \"ProtoZstdCompressed\",\n\t\t\tencoding: \"zstd\",\n\t\t},\n\t\t{\n\t\t\tname:               \"Permanent NotGRPCError\",\n\t\t\tencoding:           \"\",\n\t\t\terr:                consumererror.NewPermanent(errors.New(\"my error\")),\n\t\t\texpectedStatus:     &spb.Status{Code: int32(codes.Internal), Message: \"Permanent error: my error\"},\n\t\t\texpectedStatusCode: http.StatusInternalServerError,\n\t\t},\n\t\t{\n\t\t\tname:               \"Retryable NotGRPCError\",\n\t\t\tencoding:           \"\",\n\t\t\terr:                errors.New(\"my error\"),\n\t\t\texpectedStatus:     &spb.Status{Code: int32(codes.Unavailable), Message: \"my error\"},\n\t\t\texpectedStatusCode: http.StatusServiceUnavailable,\n\t\t},\n\t\t{\n\t\t\tname:               \"Permanent GRPCError\",\n\t\t\tencoding:           \"\",\n\t\t\terr:                status.New(codes.InvalidArgument, \"Bad Request\").Err(),\n\t\t\texpectedStatus:     &spb.Status{Code: int32(codes.InvalidArgument), Message: \"Bad Request\"},\n\t\t\texpectedStatusCode: http.StatusBadRequest,\n\t\t},\n\t\t{\n\t\t\tname:               \"Retryable GRPCError\",\n\t\t\tencoding:           \"\",\n\t\t\terr:                status.New(codes.Unavailable, \"Service Unavailable\").Err(),\n\t\t\texpectedStatus:     &spb.Status{Code: int32(codes.Unavailable), Message: \"Service Unavailable\"},\n\t\t\texpectedStatusCode: http.StatusServiceUnavailable,\n\t\t},\n\t}\n\taddr := testutil.GetAvailableLocalAddress(t)\n\n\t// Set the buffer count to 1 to make it flush the test span immediately.\n\tsink := newErrOrSinkConsumer()\n\trecv := newHTTPReceiver(t, componenttest.NewNopTelemetrySettings(), addr, sink)\n\n\trequire.NoError(t, recv.Start(context.Background(), componenttest.NewNopHost()), \"Failed to start trace receiver\")\n\tt.Cleanup(func() { require.NoError(t, recv.Shutdown(context.Background())) })\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsink.Reset()\n\t\t\tsink.SetConsumeError(tt.err)\n\n\t\t\tfor _, dr := range generateDataRequests(t) {\n\t\t\t\turl := \"http://\" + addr + dr.path\n\t\t\t\trespBytes := doHTTPRequest(t, url, tt.encoding, \"application/x-protobuf\", dr.protoBytes, tt.expectedStatusCode)\n\t\t\t\tif tt.err == nil {\n\t\t\t\t\ttr := ptraceotlp.NewExportResponse()\n\t\t\t\t\trequire.NoError(t, tr.UnmarshalProto(respBytes))\n\t\t\t\t\tsink.checkData(t, dr.data, 1)\n\t\t\t\t} else {\n\t\t\t\t\terrStatus := &spb.Status{}\n\t\t\t\t\trequire.NoError(t, proto.Unmarshal(respBytes, errStatus))\n\t\t\t\t\tif s, ok := status.FromError(tt.err); ok {\n\t\t\t\t\t\tassert.True(t, proto.Equal(errStatus, s.Proto()))\n\t\t\t\t\t} else {\n\t\t\t\t\t\tassert.True(t, proto.Equal(errStatus, tt.expectedStatus))\n\t\t\t\t\t}\n\t\t\t\t\tsink.checkData(t, dr.data, 0)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestOTLPReceiverInvalidContentEncoding(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tcontent     string\n\t\tencoding    string\n\t\treqBodyFunc func() (*bytes.Buffer, error)\n\t\tcheckBody   func(tb testing.TB, got []byte)\n\t\tstatus      int\n\t}{\n\t\t{\n\t\t\tname:     \"JsonGzipUncompressed\",\n\t\t\tcontent:  \"application/json\",\n\t\t\tencoding: \"gzip\",\n\t\t\treqBodyFunc: func() (*bytes.Buffer, error) {\n\t\t\t\treturn bytes.NewBuffer([]byte(`{\"key\": \"value\"}`)), nil\n\t\t\t},\n\t\t\tcheckBody: func(tb testing.TB, got []byte) {\n\t\t\t\tassert.JSONEq(tb, `{\"code\":3,\"message\": \"gzip: invalid header\"}`, string(got))\n\t\t\t},\n\t\t\tstatus: 400,\n\t\t},\n\t\t{\n\t\t\tname:     \"ProtoGzipUncompressed\",\n\t\t\tcontent:  \"application/x-protobuf\",\n\t\t\tencoding: \"gzip\",\n\t\t\treqBodyFunc: func() (*bytes.Buffer, error) {\n\t\t\t\treturn bytes.NewBuffer([]byte(`{\"key\": \"value\"}`)), nil\n\t\t\t},\n\t\t\tcheckBody: func(tb testing.TB, got []byte) {\n\t\t\t\texpected, err := proto.Marshal(status.New(codes.InvalidArgument, \"gzip: invalid header\").Proto())\n\t\t\t\trequire.NoError(tb, err)\n\t\t\t\tassert.Equal(tb, expected, got)\n\t\t\t},\n\t\t\tstatus: 400,\n\t\t},\n\t\t{\n\t\t\tname:     \"ProtoZstdUncompressed\",\n\t\t\tcontent:  \"application/x-protobuf\",\n\t\t\tencoding: \"zstd\",\n\t\t\treqBodyFunc: func() (*bytes.Buffer, error) {\n\t\t\t\treturn bytes.NewBuffer([]byte(`{\"key\": \"value\"}`)), nil\n\t\t\t},\n\t\t\tcheckBody: func(tb testing.TB, got []byte) {\n\t\t\t\texpected, err := proto.Marshal(status.New(codes.InvalidArgument, \"invalid input: magic number mismatch\").Proto())\n\t\t\t\trequire.NoError(tb, err)\n\t\t\t\tassert.Equal(tb, expected, got)\n\t\t\t},\n\t\t\tstatus: 400,\n\t\t},\n\t}\n\taddr := testutil.GetAvailableLocalAddress(t)\n\n\t// Set the buffer count to 1 to make it flush the test span immediately.\n\trecv := newHTTPReceiver(t, componenttest.NewNopTelemetrySettings(), addr, consumertest.NewNop())\n\n\trequire.NoError(t, recv.Start(context.Background(), componenttest.NewNopHost()), \"Failed to start trace receiver\")\n\tt.Cleanup(func() { require.NoError(t, recv.Shutdown(context.Background())) })\n\n\turl := fmt.Sprintf(\"http://%s%s\", addr, defaultTracesURLPath)\n\n\tfor _, test := range tests {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\tbody, err := test.reqBodyFunc()\n\t\t\trequire.NoError(t, err)\n\n\t\t\treq, err := http.NewRequest(http.MethodPost, url, body)\n\t\t\trequire.NoError(t, err)\n\t\t\treq.Header.Set(\"Content-Type\", test.content)\n\t\t\treq.Header.Set(\"Content-Encoding\", test.encoding)\n\n\t\t\tresp, err := http.DefaultClient.Do(req)\n\t\t\trequire.NoError(t, err)\n\t\t\tassert.Equal(t, test.status, resp.StatusCode, \"Unexpected return status\")\n\t\t\tassert.Equal(t, test.content, resp.Header.Get(\"Content-Type\"), \"Unexpected response Content-Type\")\n\n\t\t\trespBytes, err := io.ReadAll(resp.Body)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.NoError(t, resp.Body.Close())\n\t\t\ttest.checkBody(t, respBytes)\n\t\t})\n\t}\n}\n\nfunc TestOTLPReceiverNoContentType(t *testing.T) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\n\t// Set the buffer count to 1 to make it flush the test span immediately.\n\trecv := newHTTPReceiver(t, componenttest.NewNopTelemetrySettings(), addr, consumertest.NewNop())\n\n\trequire.NoError(t, recv.Start(context.Background(), componenttest.NewNopHost()), \"Failed to start trace receiver\")\n\tt.Cleanup(func() { require.NoError(t, recv.Shutdown(context.Background())) })\n\n\turl := fmt.Sprintf(\"http://%s%s\", addr, defaultTracesURLPath)\n\n\tt.Run(\"NoContentType\", func(t *testing.T) {\n\t\tbody := bytes.NewBuffer([]byte(`{\"key\": \"value\"}`))\n\n\t\treq, err := http.NewRequest(http.MethodPost, url, body)\n\t\trequire.NoError(t, err, \"Error creating trace POST request: %v\", err)\n\n\t\t// Set invalid encoding to trigger an error\n\t\treq.Header.Set(\"Content-Encoding\", \"invalid\")\n\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\trequire.NoError(t, err, \"Error posting to server: %v\", err)\n\t\t// Don't care about the response body, just check the content type\n\t\tdefer resp.Body.Close()\n\n\t\trequire.Equal(t, fallbackContentType, resp.Header.Get(\"Content-Type\"), \"Unexpected response Content-Type\")\n\t})\n}\n\nfunc TestGRPCNewPortAlreadyUsed(t *testing.T) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\tln, err := net.Listen(\"tcp\", addr)\n\trequire.NoError(t, err, \"failed to listen on %q: %v\", addr, err)\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, ln.Close())\n\t})\n\n\tr := newGRPCReceiver(t, componenttest.NewNopTelemetrySettings(), addr, consumertest.NewNop())\n\trequire.NotNil(t, r)\n\n\trequire.Error(t, r.Start(context.Background(), componenttest.NewNopHost()))\n}\n\nfunc TestHTTPNewPortAlreadyUsed(t *testing.T) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\tln, err := net.Listen(\"tcp\", addr)\n\trequire.NoError(t, err, \"failed to listen on %q: %v\", addr, err)\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, ln.Close())\n\t})\n\n\tr := newHTTPReceiver(t, componenttest.NewNopTelemetrySettings(), addr, consumertest.NewNop())\n\trequire.NotNil(t, r)\n\n\trequire.Error(t, r.Start(context.Background(), componenttest.NewNopHost()))\n}\n\n// TestOTLPReceiverGRPCMetricsIngestTest checks that the metrics receiver\n// is returning the proper response (return and metrics) when the next consumer\n// in the pipeline reports error.\nfunc TestOTLPReceiverGRPCMetricsIngestTest(t *testing.T) {\n\t// Get a new available port\n\taddr := testutil.GetAvailableLocalAddress(t)\n\n\t// Create a sink\n\tsink := &errOrSinkConsumer{MetricsSink: new(consumertest.MetricsSink)}\n\n\t// Create a telemetry instance\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\t// Create telemetry settings\n\tsettings := tt.NewTelemetrySettings()\n\n\trecv := newGRPCReceiver(t, settings, addr, sink)\n\trequire.NotNil(t, recv)\n\trequire.NoError(t, recv.Start(context.Background(), componenttest.NewNopHost()))\n\tt.Cleanup(func() { require.NoError(t, recv.Shutdown(context.Background())) })\n\n\tcc, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err)\n\tdefer func() {\n\t\tassert.NoError(t, cc.Close())\n\t}()\n\t// Set up the error case\n\tsink.SetConsumeError(errors.New(\"consumer error\"))\n\n\tmd := testdata.GenerateMetrics(1)\n\t_, err = pmetricotlp.NewGRPCClient(cc).Export(context.Background(), pmetricotlp.NewExportRequestFromMetrics(md))\n\terrStatus, ok := status.FromError(err)\n\trequire.True(t, ok)\n\tassert.Equal(t, codes.Unavailable, errStatus.Code())\n\n\t// Assert receiver metrics including receiver_requests\n\tassertReceiverMetrics(t, tt, otlpReceiverID, \"grpc\", 0, 2)\n}\n\n// TestOTLPReceiverGRPCTracesIngestTest checks that the gRPC trace receiver\n// is returning the proper response (return and metrics) when the next consumer\n// in the pipeline reports error. The test changes the responses returned by the\n// next trace consumer, checks if data was passed down the pipeline and if\n// proper metrics were recorded. It also uses all endpoints supported by the\n// trace receiver.\nfunc TestOTLPReceiverGRPCTracesIngestTest(t *testing.T) {\n\ttype ingestionStateTest struct {\n\t\tokToIngest   bool\n\t\tpermanent    bool\n\t\texpectedCode codes.Code\n\t}\n\n\texpectedReceivedBatches := 2\n\texpectedIngestionBlockedRPCs := 2\n\tingestionStates := []ingestionStateTest{\n\t\t{\n\t\t\tokToIngest:   true,\n\t\t\texpectedCode: codes.OK,\n\t\t},\n\t\t{\n\t\t\tokToIngest:   false,\n\t\t\texpectedCode: codes.Unavailable,\n\t\t},\n\t\t{\n\t\t\tokToIngest:   false,\n\t\t\texpectedCode: codes.Internal,\n\t\t\tpermanent:    true,\n\t\t},\n\t\t{\n\t\t\tokToIngest:   true,\n\t\t\texpectedCode: codes.OK,\n\t\t},\n\t}\n\n\taddr := testutil.GetAvailableLocalAddress(t)\n\ttd := testdata.GenerateTraces(1)\n\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tsink := &errOrSinkConsumer{TracesSink: new(consumertest.TracesSink)}\n\n\trecv := newGRPCReceiver(t, tt.NewTelemetrySettings(), addr, sink)\n\trequire.NotNil(t, recv)\n\trequire.NoError(t, recv.Start(context.Background(), componenttest.NewNopHost()))\n\tt.Cleanup(func() { require.NoError(t, recv.Shutdown(context.Background())) })\n\n\tcc, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err)\n\tdefer func() {\n\t\tassert.NoError(t, cc.Close())\n\t}()\n\n\tfor _, ingestionState := range ingestionStates {\n\t\tif ingestionState.okToIngest {\n\t\t\tsink.SetConsumeError(nil)\n\t\t} else {\n\t\t\tif ingestionState.permanent {\n\t\t\t\tsink.SetConsumeError(consumererror.NewPermanent(errors.New(\"consumer error\")))\n\t\t\t} else {\n\t\t\t\tsink.SetConsumeError(errors.New(\"consumer error\"))\n\t\t\t}\n\t\t}\n\n\t\t_, err = ptraceotlp.NewGRPCClient(cc).Export(context.Background(), ptraceotlp.NewExportRequestFromTraces(td))\n\t\terrStatus, ok := status.FromError(err)\n\t\trequire.True(t, ok)\n\t\tassert.Equal(t, ingestionState.expectedCode, errStatus.Code())\n\t}\n\n\trequire.Len(t, sink.AllTraces(), expectedReceivedBatches)\n\n\tassertReceiverTraces(t, tt, otlpReceiverID, \"grpc\", int64(expectedReceivedBatches), int64(expectedIngestionBlockedRPCs))\n}\n\n// TestOTLPReceiverHTTPTracesIngestTest checks that the HTTP trace receiver\n// is returning the proper response (return and metrics) when the next consumer\n// in the pipeline reports error. The test changes the responses returned by the\n// next trace consumer, checks if data was passed down the pipeline and if\n// proper metrics were recorded. It also uses all endpoints supported by the\n// trace receiver.\nfunc TestOTLPReceiverHTTPTracesIngestTest(t *testing.T) {\n\ttype ingestionStateTest struct {\n\t\tokToIngest         bool\n\t\terr                error\n\t\texpectedCode       codes.Code\n\t\texpectedStatusCode int\n\t}\n\n\texpectedReceivedBatches := 2\n\texpectedIngestionBlockedRPCs := 2\n\tingestionStates := []ingestionStateTest{\n\t\t{\n\t\t\tokToIngest:   true,\n\t\t\texpectedCode: codes.OK,\n\t\t},\n\t\t{\n\t\t\tokToIngest:         false,\n\t\t\terr:                consumererror.NewPermanent(errors.New(\"consumer error\")),\n\t\t\texpectedCode:       codes.Internal,\n\t\t\texpectedStatusCode: http.StatusInternalServerError,\n\t\t},\n\t\t{\n\t\t\tokToIngest:         false,\n\t\t\terr:                errors.New(\"consumer error\"),\n\t\t\texpectedCode:       codes.Unavailable,\n\t\t\texpectedStatusCode: http.StatusServiceUnavailable,\n\t\t},\n\t\t{\n\t\t\tokToIngest:   true,\n\t\t\texpectedCode: codes.OK,\n\t\t},\n\t}\n\n\taddr := testutil.GetAvailableLocalAddress(t)\n\ttd := testdata.GenerateTraces(1)\n\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\tsink := &errOrSinkConsumer{TracesSink: new(consumertest.TracesSink)}\n\n\trecv := newHTTPReceiver(t, tt.NewTelemetrySettings(), addr, sink)\n\trequire.NotNil(t, recv)\n\trequire.NoError(t, recv.Start(context.Background(), componenttest.NewNopHost()))\n\tt.Cleanup(func() { require.NoError(t, recv.Shutdown(context.Background())) })\n\n\tfor _, ingestionState := range ingestionStates {\n\t\tif ingestionState.okToIngest {\n\t\t\tsink.SetConsumeError(nil)\n\t\t} else {\n\t\t\tsink.SetConsumeError(ingestionState.err)\n\t\t}\n\n\t\tpbMarshaler := ptrace.ProtoMarshaler{}\n\t\tpbBytes, err := pbMarshaler.MarshalTraces(td)\n\t\trequire.NoError(t, err)\n\t\treq, err := http.NewRequest(http.MethodPost, \"http://\"+addr+defaultTracesURLPath, bytes.NewReader(pbBytes))\n\t\trequire.NoError(t, err)\n\t\treq.Header.Set(\"Content-Type\", pbContentType)\n\t\tresp, err := http.DefaultClient.Do(req)\n\t\trequire.NoError(t, err)\n\t\trespBytes, err := io.ReadAll(resp.Body)\n\t\trequire.NoError(t, err)\n\n\t\tif ingestionState.expectedCode == codes.OK {\n\t\t\trequire.Equal(t, 200, resp.StatusCode)\n\t\t\ttr := ptraceotlp.NewExportResponse()\n\t\t\trequire.NoError(t, tr.UnmarshalProto(respBytes))\n\t\t} else {\n\t\t\terrStatus := &spb.Status{}\n\t\t\trequire.NoError(t, proto.Unmarshal(respBytes, errStatus))\n\t\t\tassert.Equal(t, ingestionState.expectedStatusCode, resp.StatusCode)\n\t\t\tassert.EqualValues(t, ingestionState.expectedCode, errStatus.Code)\n\t\t}\n\t}\n\n\trequire.Len(t, sink.AllTraces(), expectedReceivedBatches)\n\n\tassertReceiverTraces(t, tt, otlpReceiverID, \"http\", int64(expectedReceivedBatches), int64(expectedIngestionBlockedRPCs))\n}\n\nfunc TestGRPCInvalidTLSCredentials(t *testing.T) {\n\tcfg := &Config{\n\t\tProtocols: Protocols{\n\t\t\tGRPC: configoptional.Some(configgrpc.ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  testutil.GetAvailableLocalAddress(t),\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t\tTLS: configoptional.Some(configtls.ServerConfig{\n\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\tCertFile: \"willfail\",\n\t\t\t\t\t},\n\t\t\t\t}),\n\t\t\t}),\n\t\t},\n\t}\n\n\tr, err := NewFactory().CreateTraces(\n\t\tcontext.Background(),\n\t\treceivertest.NewNopSettings(metadata.Type),\n\t\tcfg,\n\t\tconsumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NotNil(t, r)\n\n\tassert.EqualError(t,\n\t\tr.Start(context.Background(), componenttest.NewNopHost()),\n\t\t`failed to load TLS config: failed to load TLS cert and key: for auth via TLS, provide both certificate and key, or neither`)\n}\n\nfunc TestGRPCMaxRecvSize(t *testing.T) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\tsink := newErrOrSinkConsumer()\n\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.GRPC.GetOrInsertDefault().NetAddr.Endpoint = addr\n\trecv := newReceiver(t, componenttest.NewNopTelemetrySettings(), cfg, otlpReceiverID, sink)\n\trequire.NoError(t, recv.Start(context.Background(), componenttest.NewNopHost()))\n\n\tcc, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err)\n\n\ttd := testdata.GenerateTraces(50000)\n\terr = exportTraces(cc, td)\n\trequire.Error(t, err)\n\tassert.NoError(t, cc.Close())\n\trequire.NoError(t, recv.Shutdown(context.Background()))\n\n\tcfg.GRPC.Get().MaxRecvMsgSizeMiB = 100\n\trecv = newReceiver(t, componenttest.NewNopTelemetrySettings(), cfg, otlpReceiverID, sink)\n\trequire.NoError(t, recv.Start(context.Background(), componenttest.NewNopHost()))\n\tt.Cleanup(func() { require.NoError(t, recv.Shutdown(context.Background())) })\n\n\tcc, err = grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err)\n\tdefer func() {\n\t\tassert.NoError(t, cc.Close())\n\t}()\n\n\ttd = testdata.GenerateTraces(50000)\n\trequire.NoError(t, exportTraces(cc, td))\n\trequire.Len(t, sink.AllTraces(), 1)\n\tassert.Equal(t, td, sink.AllTraces()[0])\n}\n\nfunc TestHTTPInvalidTLSCredentials(t *testing.T) {\n\tcfg := &Config{\n\t\tProtocols: Protocols{\n\t\t\tHTTP: configoptional.Some(HTTPConfig{\n\t\t\t\tServerConfig: confighttp.ServerConfig{\n\t\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\t\tEndpoint:  testutil.GetAvailableLocalAddress(t),\n\t\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t\t},\n\t\t\t\t\tTLS: configoptional.Some(configtls.ServerConfig{\n\t\t\t\t\t\tConfig: configtls.Config{\n\t\t\t\t\t\t\tCertFile: \"willfail\",\n\t\t\t\t\t\t},\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t\tTracesURLPath:  defaultTracesURLPath,\n\t\t\t\tMetricsURLPath: defaultMetricsURLPath,\n\t\t\t\tLogsURLPath:    defaultLogsURLPath,\n\t\t\t}),\n\t\t},\n\t}\n\n\t// TLS is resolved during Start for HTTP.\n\tr, err := NewFactory().CreateTraces(\n\t\tcontext.Background(),\n\t\treceivertest.NewNopSettings(metadata.Type),\n\t\tcfg,\n\t\tconsumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NotNil(t, r)\n\tassert.EqualError(t, r.Start(context.Background(), componenttest.NewNopHost()),\n\t\t`failed to load TLS config: failed to load TLS cert and key: for auth via TLS, provide both certificate and key, or neither`)\n}\n\nfunc testHTTPMaxRequestBodySize(t *testing.T, path, contentType string, payload []byte, size, expectedStatusCode int) {\n\taddr := testutil.GetAvailableLocalAddress(t)\n\turl := \"http://\" + addr + path\n\tcfg := &Config{\n\t\tProtocols: Protocols{\n\t\t\tHTTP: configoptional.Some(HTTPConfig{\n\t\t\t\tServerConfig: confighttp.ServerConfig{\n\t\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\t\tEndpoint:  addr,\n\t\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t\t},\n\t\t\t\t\tMaxRequestBodySize: int64(size),\n\t\t\t\t},\n\t\t\t\tTracesURLPath:  defaultTracesURLPath,\n\t\t\t\tMetricsURLPath: defaultMetricsURLPath,\n\t\t\t\tLogsURLPath:    defaultLogsURLPath,\n\t\t\t}),\n\t\t},\n\t}\n\n\trecv := newReceiver(t, componenttest.NewNopTelemetrySettings(), cfg, otlpReceiverID, consumertest.NewNop())\n\trequire.NoError(t, recv.Start(context.Background(), componenttest.NewNopHost()))\n\n\treq := createHTTPRequest(t, url, \"\", contentType, payload)\n\tresp, err := http.DefaultClient.Do(req)\n\trequire.NoError(t, err)\n\t_, err = io.ReadAll(resp.Body)\n\trequire.NoError(t, err)\n\trequire.Equal(t, expectedStatusCode, resp.StatusCode)\n\n\trequire.NoError(t, recv.Shutdown(context.Background()))\n}\n\nfunc TestHTTPMaxRequestBodySize(t *testing.T) {\n\tdataReqs := generateDataRequests(t)\n\n\tfor _, dr := range dataReqs {\n\t\ttestHTTPMaxRequestBodySize(t, dr.path, \"application/json\", dr.jsonBytes, len(dr.jsonBytes), 200)\n\t\ttestHTTPMaxRequestBodySize(t, dr.path, \"application/json\", dr.jsonBytes, len(dr.jsonBytes)-1, 400)\n\n\t\ttestHTTPMaxRequestBodySize(t, dr.path, \"application/x-protobuf\", dr.protoBytes, len(dr.protoBytes), 200)\n\t\ttestHTTPMaxRequestBodySize(t, dr.path, \"application/x-protobuf\", dr.protoBytes, len(dr.protoBytes)-1, 400)\n\t}\n}\n\nfunc newGRPCReceiver(t *testing.T, settings component.TelemetrySettings, endpoint string, c consumertest.Consumer) component.Component {\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.GRPC.GetOrInsertDefault().NetAddr.Endpoint = endpoint\n\treturn newReceiver(t, settings, cfg, otlpReceiverID, c)\n}\n\nfunc newHTTPReceiver(t *testing.T, settings component.TelemetrySettings, endpoint string, c consumertest.Consumer) component.Component {\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.HTTP.GetOrInsertDefault().ServerConfig.NetAddr.Endpoint = endpoint\n\treturn newReceiver(t, settings, cfg, otlpReceiverID, c)\n}\n\nfunc newReceiver(t *testing.T, settings component.TelemetrySettings, cfg *Config, id component.ID, c consumertest.Consumer) component.Component {\n\tset := receivertest.NewNopSettings(metadata.Type)\n\tset.TelemetrySettings = settings\n\tset.ID = id\n\tr, err := newOtlpReceiver(cfg, &set)\n\trequire.NoError(t, err)\n\tr.registerTraceConsumer(c)\n\tr.registerMetricsConsumer(c)\n\tr.registerLogsConsumer(c)\n\tr.registerProfilesConsumer(c)\n\treturn r\n}\n\ntype dataRequest struct {\n\tdata       any\n\tpath       string\n\tjsonBytes  []byte\n\tprotoBytes []byte\n}\n\nfunc generateDataRequests(t *testing.T) []dataRequest {\n\treturn []dataRequest{generateTracesRequest(t), generateMetricsRequests(t), generateLogsRequest(t), generateProfilesRequest(t)}\n}\n\nfunc generateTracesRequest(t *testing.T) dataRequest {\n\tprotoMarshaler := &ptrace.ProtoMarshaler{}\n\tjsonMarshaler := &ptrace.JSONMarshaler{}\n\n\ttd := testdata.GenerateTraces(2)\n\ttraceProto, err := protoMarshaler.MarshalTraces(td)\n\trequire.NoError(t, err)\n\n\ttraceJSON, err := jsonMarshaler.MarshalTraces(td)\n\trequire.NoError(t, err)\n\n\treturn dataRequest{data: td, path: defaultTracesURLPath, jsonBytes: traceJSON, protoBytes: traceProto}\n}\n\nfunc generateMetricsRequests(t *testing.T) dataRequest {\n\tprotoMarshaler := &pmetric.ProtoMarshaler{}\n\tjsonMarshaler := &pmetric.JSONMarshaler{}\n\n\tmd := testdata.GenerateMetrics(2)\n\tmetricProto, err := protoMarshaler.MarshalMetrics(md)\n\trequire.NoError(t, err)\n\n\tmetricJSON, err := jsonMarshaler.MarshalMetrics(md)\n\trequire.NoError(t, err)\n\n\treturn dataRequest{data: md, path: defaultMetricsURLPath, jsonBytes: metricJSON, protoBytes: metricProto}\n}\n\nfunc generateLogsRequest(t *testing.T) dataRequest {\n\tprotoMarshaler := &plog.ProtoMarshaler{}\n\tjsonMarshaler := &plog.JSONMarshaler{}\n\n\tld := testdata.GenerateLogs(2)\n\tlogProto, err := protoMarshaler.MarshalLogs(ld)\n\trequire.NoError(t, err)\n\n\tlogJSON, err := jsonMarshaler.MarshalLogs(ld)\n\trequire.NoError(t, err)\n\n\treturn dataRequest{data: ld, path: defaultLogsURLPath, jsonBytes: logJSON, protoBytes: logProto}\n}\n\nfunc generateProfilesRequest(t *testing.T) dataRequest {\n\tprotoMarshaler := &pprofile.ProtoMarshaler{}\n\tjsonMarshaler := &pprofile.JSONMarshaler{}\n\n\tmd := testdata.GenerateProfiles(2)\n\tprofileProto, err := protoMarshaler.MarshalProfiles(md)\n\trequire.NoError(t, err)\n\n\tprofileJSON, err := jsonMarshaler.MarshalProfiles(md)\n\trequire.NoError(t, err)\n\n\treturn dataRequest{data: md, path: defaultProfilesURLPath, jsonBytes: profileJSON, protoBytes: profileProto}\n}\n\nfunc doHTTPRequest(\n\tt *testing.T,\n\turl string,\n\tencoding string,\n\tcontentType string,\n\tdata []byte,\n\texpectStatusCode int,\n) []byte {\n\treq := createHTTPRequest(t, url, encoding, contentType, data)\n\tresp, err := http.DefaultClient.Do(req)\n\trequire.NoError(t, err)\n\n\trespBytes, err := io.ReadAll(resp.Body)\n\trequire.NoError(t, err)\n\n\trequire.NoError(t, resp.Body.Close())\n\t// For cases like \"application/json; charset=utf-8\", the response will be only \"application/json\"\n\trequire.True(t, strings.HasPrefix(strings.ToLower(contentType), resp.Header.Get(\"Content-Type\")))\n\n\tif expectStatusCode == 0 {\n\t\trequire.Equal(t, http.StatusOK, resp.StatusCode)\n\t} else {\n\t\trequire.Equal(t, expectStatusCode, resp.StatusCode)\n\t}\n\n\treturn respBytes\n}\n\nfunc createHTTPRequest(\n\tt *testing.T,\n\turl string,\n\tencoding string,\n\tcontentType string,\n\tdata []byte,\n) *http.Request {\n\tvar buf *bytes.Buffer\n\tswitch encoding {\n\tcase \"gzip\":\n\t\tbuf = compressGzip(t, data)\n\tcase \"zstd\":\n\t\tbuf = compressZstd(t, data)\n\tcase \"\":\n\t\tbuf = bytes.NewBuffer(data)\n\tdefault:\n\t\tt.Fatalf(\"Unsupported compression type %v\", encoding)\n\t}\n\n\treq, err := http.NewRequest(http.MethodPost, url, buf)\n\trequire.NoError(t, err)\n\treq.Header.Set(\"Content-Type\", contentType)\n\treq.Header.Set(\"Content-Encoding\", encoding)\n\n\treturn req\n}\n\nfunc compressGzip(t *testing.T, body []byte) *bytes.Buffer {\n\tvar buf bytes.Buffer\n\n\tgw := gzip.NewWriter(&buf)\n\tdefer func() {\n\t\trequire.NoError(t, gw.Close())\n\t}()\n\n\t_, err := gw.Write(body)\n\trequire.NoError(t, err)\n\n\treturn &buf\n}\n\nfunc compressZstd(t *testing.T, body []byte) *bytes.Buffer {\n\tvar buf bytes.Buffer\n\n\tzw, err := zstd.NewWriter(&buf)\n\trequire.NoError(t, err)\n\n\tdefer func() {\n\t\trequire.NoError(t, zw.Close())\n\t}()\n\n\t_, err = zw.Write(body)\n\trequire.NoError(t, err)\n\n\treturn &buf\n}\n\ntype senderFunc func(td ptrace.Traces)\n\nfunc TestShutdown(t *testing.T) {\n\tendpointGrpc := testutil.GetAvailableLocalAddress(t)\n\tendpointHTTP := testutil.GetAvailableLocalAddress(t)\n\n\tnextSink := new(consumertest.TracesSink)\n\n\t// Create OTLP receiver with gRPC and HTTP protocols.\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig().(*Config)\n\tcfg.GRPC.GetOrInsertDefault().NetAddr.Endpoint = endpointGrpc\n\tcfg.HTTP.GetOrInsertDefault().ServerConfig.NetAddr.Endpoint = endpointHTTP\n\tset := receivertest.NewNopSettings(metadata.Type)\n\tset.ID = otlpReceiverID\n\tr, err := NewFactory().CreateTraces(\n\t\tcontext.Background(),\n\t\tset,\n\t\tcfg,\n\t\tnextSink)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, r)\n\trequire.NoError(t, r.Start(context.Background(), componenttest.NewNopHost()))\n\n\tconn, err := grpc.NewClient(endpointGrpc, grpc.WithTransportCredentials(insecure.NewCredentials()))\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, conn.Close())\n\t})\n\n\tdoneSignalGrpc := make(chan bool)\n\tdoneSignalHTTP := make(chan bool)\n\n\tsenderGrpc := func(td ptrace.Traces) {\n\t\t// Ignore error, may be executed after the receiver shutdown.\n\t\t_ = exportTraces(conn, td)\n\t}\n\tsenderHTTP := func(td ptrace.Traces) {\n\t\t// Send request via OTLP/HTTP.\n\t\tmarshaler := &ptrace.ProtoMarshaler{}\n\t\ttraceBytes, err2 := marshaler.MarshalTraces(td)\n\t\trequire.NoError(t, err2)\n\t\turl := \"http://\" + endpointHTTP + defaultTracesURLPath\n\t\treq := createHTTPRequest(t, url, \"\", \"application/x-protobuf\", traceBytes)\n\t\tif resp, errResp := http.DefaultClient.Do(req); errResp == nil {\n\t\t\trequire.NoError(t, resp.Body.Close())\n\t\t}\n\t}\n\n\t// Send traces to the receiver until we signal via done channel, and then\n\t// send one more trace after that.\n\tgo generateTraces(senderGrpc, doneSignalGrpc)\n\tgo generateTraces(senderHTTP, doneSignalHTTP)\n\n\t// Wait until the receiver outputs anything to the sink.\n\tassert.Eventually(t, func() bool {\n\t\treturn nextSink.SpanCount() > 0\n\t}, time.Second, 10*time.Millisecond)\n\n\t// Now shutdown the receiver, while continuing sending traces to it.\n\tctx, cancelFn := context.WithTimeout(context.Background(), 10*time.Second)\n\tdefer cancelFn()\n\trequire.NoError(t, r.Shutdown(ctx))\n\n\t// Remember how many spans the sink received. This number should not change after this\n\t// point because after Shutdown() returns the component is not allowed to produce\n\t// any more data.\n\tsinkSpanCountAfterShutdown := nextSink.SpanCount()\n\n\t// Now signal to generateTraces to exit the main generation loop, then send\n\t// one more trace and stop.\n\tdoneSignalGrpc <- true\n\tdoneSignalHTTP <- true\n\n\t// Wait until all follow up traces are sent.\n\t<-doneSignalGrpc\n\t<-doneSignalHTTP\n\n\t// The last, additional trace should not be received by sink, so the number of spans in\n\t// the sink should not change.\n\tassert.Equal(t, sinkSpanCountAfterShutdown, nextSink.SpanCount())\n}\n\nfunc generateTraces(senderFn senderFunc, doneSignal chan bool) {\n\t// Continuously generate spans until signaled to stop.\nloop:\n\tfor {\n\t\tselect {\n\t\tcase <-doneSignal:\n\t\t\tbreak loop\n\t\tdefault:\n\t\t}\n\t\tsenderFn(testdata.GenerateTraces(1))\n\t}\n\n\t// After getting the signal to stop, send one more span and then\n\t// finally stop. We should never receive this last span.\n\tsenderFn(testdata.GenerateTraces(1))\n\n\t// Indicate that we are done.\n\tclose(doneSignal)\n}\n\nfunc exportTraces(cc *grpc.ClientConn, td ptrace.Traces) error {\n\tacc := ptraceotlp.NewGRPCClient(cc)\n\treq := ptraceotlp.NewExportRequestFromTraces(td)\n\t_, err := acc.Export(context.Background(), req)\n\n\treturn err\n}\n\ntype errOrSinkConsumer struct {\n\tconsumertest.Consumer\n\t*consumertest.TracesSink\n\t*consumertest.MetricsSink\n\t*consumertest.LogsSink\n\t*consumertest.ProfilesSink\n\tmu           sync.Mutex\n\tconsumeError error // to be returned by ConsumeTraces, if set\n}\n\nfunc newErrOrSinkConsumer() *errOrSinkConsumer {\n\treturn &errOrSinkConsumer{\n\t\tTracesSink:   new(consumertest.TracesSink),\n\t\tMetricsSink:  new(consumertest.MetricsSink),\n\t\tLogsSink:     new(consumertest.LogsSink),\n\t\tProfilesSink: new(consumertest.ProfilesSink),\n\t}\n}\n\n// SetConsumeError sets an error that will be returned by the Consume function.\nfunc (esc *errOrSinkConsumer) SetConsumeError(err error) {\n\tesc.mu.Lock()\n\tdefer esc.mu.Unlock()\n\tesc.consumeError = err\n}\n\nfunc (esc *errOrSinkConsumer) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: false}\n}\n\n// ConsumeTraces stores traces to this sink.\nfunc (esc *errOrSinkConsumer) ConsumeTraces(ctx context.Context, td ptrace.Traces) error {\n\tesc.mu.Lock()\n\tdefer esc.mu.Unlock()\n\n\tif esc.consumeError != nil {\n\t\treturn esc.consumeError\n\t}\n\n\treturn esc.TracesSink.ConsumeTraces(ctx, td)\n}\n\n// ConsumeMetrics stores metrics to this sink.\nfunc (esc *errOrSinkConsumer) ConsumeMetrics(ctx context.Context, md pmetric.Metrics) error {\n\tesc.mu.Lock()\n\tdefer esc.mu.Unlock()\n\n\tif esc.consumeError != nil {\n\t\treturn esc.consumeError\n\t}\n\n\treturn esc.MetricsSink.ConsumeMetrics(ctx, md)\n}\n\n// ConsumeLogs stores metrics to this sink.\nfunc (esc *errOrSinkConsumer) ConsumeLogs(ctx context.Context, ld plog.Logs) error {\n\tesc.mu.Lock()\n\tdefer esc.mu.Unlock()\n\n\tif esc.consumeError != nil {\n\t\treturn esc.consumeError\n\t}\n\n\treturn esc.LogsSink.ConsumeLogs(ctx, ld)\n}\n\n// ConsumeProfiles stores profiles to this sink.\nfunc (esc *errOrSinkConsumer) ConsumeProfiles(ctx context.Context, md pprofile.Profiles) error {\n\tesc.mu.Lock()\n\tdefer esc.mu.Unlock()\n\n\tif esc.consumeError != nil {\n\t\treturn esc.consumeError\n\t}\n\n\treturn esc.ProfilesSink.ConsumeProfiles(ctx, md)\n}\n\n// Reset deletes any stored in the sinks, resets error to nil.\nfunc (esc *errOrSinkConsumer) Reset() {\n\tesc.mu.Lock()\n\tdefer esc.mu.Unlock()\n\n\tesc.consumeError = nil\n\tesc.TracesSink.Reset()\n\tesc.MetricsSink.Reset()\n\tesc.LogsSink.Reset()\n\tesc.ProfilesSink.Reset()\n}\n\n// Reset deletes any stored in the sinks, resets error to nil.\nfunc (esc *errOrSinkConsumer) checkData(t *testing.T, data any, dataLen int) {\n\tswitch data.(type) {\n\tcase ptrace.Traces:\n\t\tallTraces := esc.AllTraces()\n\t\trequire.Len(t, allTraces, dataLen)\n\t\tif dataLen > 0 {\n\t\t\trequire.Equal(t, allTraces[0], data)\n\t\t}\n\tcase pmetric.Metrics:\n\t\tallMetrics := esc.AllMetrics()\n\t\trequire.Len(t, allMetrics, dataLen)\n\t\tif dataLen > 0 {\n\t\t\trequire.Equal(t, allMetrics[0], data)\n\t\t}\n\tcase plog.Logs:\n\t\tallLogs := esc.AllLogs()\n\t\trequire.Len(t, allLogs, dataLen)\n\t\tif dataLen > 0 {\n\t\t\trequire.Equal(t, allLogs[0], data)\n\t\t}\n\tcase pprofile.Profiles:\n\t\tallProfiles := esc.AllProfiles()\n\t\trequire.Len(t, allProfiles, dataLen)\n\t\tif dataLen > 0 {\n\t\t\trequire.Equal(t, allProfiles[0], data)\n\t\t}\n\t}\n}\n\nfunc assertReceiverTraces(t *testing.T, tt *componenttest.Telemetry, id component.ID, transport string, accepted, rejected int64) {\n\tvar refused, failed int64\n\tvar outcome string\n\tgateEnabled := receiverhelper.NewReceiverMetricsGate.IsEnabled()\n\t// The errors in the OTLP tests are not downstream, so they should be \"failed\" when the gate is enabled.\n\tif gateEnabled {\n\t\tfailed = rejected\n\t\toutcome = \"failure\"\n\t} else {\n\t\t// When the gate is disabled, all errors are \"refused\".\n\t\trefused = rejected\n\t}\n\n\tgot, err := tt.GetMetric(\"otelcol_receiver_failed_spans\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t,\n\t\tmetricdata.Metrics{\n\t\t\tName:        \"otelcol_receiver_failed_spans\",\n\t\t\tDescription: \"The number of spans that failed to be processed by the receiver due to internal errors. [Alpha]\",\n\t\t\tUnit:        \"{span}\",\n\t\t\tData: metricdata.Sum[int64]{\n\t\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\t\tIsMonotonic: true,\n\t\t\t\tDataPoints: []metricdata.DataPoint[int64]{\n\t\t\t\t\t{\n\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\tattribute.String(\"receiver\", id.String()),\n\t\t\t\t\t\t\tattribute.String(\"transport\", transport)),\n\t\t\t\t\t\tValue: failed,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}, got, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\tgot, err = tt.GetMetric(\"otelcol_receiver_accepted_spans\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t,\n\t\tmetricdata.Metrics{\n\t\t\tName:        \"otelcol_receiver_accepted_spans\",\n\t\t\tDescription: \"Number of spans successfully pushed into the pipeline. [Alpha]\",\n\t\t\tUnit:        \"{span}\",\n\t\t\tData: metricdata.Sum[int64]{\n\t\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\t\tIsMonotonic: true,\n\t\t\t\tDataPoints: []metricdata.DataPoint[int64]{\n\t\t\t\t\t{\n\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\tattribute.String(\"receiver\", id.String()),\n\t\t\t\t\t\t\tattribute.String(\"transport\", transport)),\n\t\t\t\t\t\tValue: accepted,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}, got, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\tgot, err = tt.GetMetric(\"otelcol_receiver_refused_spans\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t,\n\t\tmetricdata.Metrics{\n\t\t\tName:        \"otelcol_receiver_refused_spans\",\n\t\t\tDescription: \"Number of spans that could not be pushed into the pipeline. [Alpha]\",\n\t\t\tUnit:        \"{span}\",\n\t\t\tData: metricdata.Sum[int64]{\n\t\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\t\tIsMonotonic: true,\n\t\t\t\tDataPoints: []metricdata.DataPoint[int64]{\n\t\t\t\t\t{\n\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\tattribute.String(\"receiver\", id.String()),\n\t\t\t\t\t\t\tattribute.String(\"transport\", transport)),\n\t\t\t\t\t\tValue: refused,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}, got, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\t// Assert receiver_requests metric\n\tif gateEnabled {\n\t\tgot, err := tt.GetMetric(\"otelcol_receiver_requests\")\n\t\trequire.NoError(t, err)\n\n\t\t// Calculate expected requests based on accepted and refused counts\n\t\tvar expectedRequests []metricdata.DataPoint[int64]\n\t\tif accepted > 0 {\n\t\t\texpectedRequests = append(expectedRequests, metricdata.DataPoint[int64]{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(\"receiver\", id.String()),\n\t\t\t\t\tattribute.String(\"transport\", transport),\n\t\t\t\t\tattribute.String(\"outcome\", \"success\")),\n\t\t\t\tValue: accepted,\n\t\t\t})\n\t\t}\n\t\tif rejected > 0 {\n\t\t\texpectedRequests = append(expectedRequests, metricdata.DataPoint[int64]{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(\"receiver\", id.String()),\n\t\t\t\t\tattribute.String(\"transport\", transport),\n\t\t\t\t\tattribute.String(\"outcome\", outcome)),\n\t\t\t\tValue: rejected,\n\t\t\t})\n\t\t}\n\n\t\tmetricdatatest.AssertEqual(t,\n\t\t\tmetricdata.Metrics{\n\t\t\t\tName:        \"otelcol_receiver_requests\",\n\t\t\t\tDescription: \"The number of requests performed.\",\n\t\t\t\tUnit:        \"{request}\",\n\t\t\t\tData: metricdata.Sum[int64]{\n\t\t\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\t\t\tIsMonotonic: true,\n\t\t\t\t\tDataPoints:  expectedRequests,\n\t\t\t\t},\n\t\t\t}, got, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t} else {\n\t\t_, err := tt.GetMetric(\"otelcol_receiver_requests\")\n\t\trequire.Error(t, err)\n\t}\n}\n\nfunc assertReceiverMetrics(t *testing.T, tt *componenttest.Telemetry, id component.ID, transport string, accepted, rejected int64) {\n\tvar refused, failed int64\n\tvar outcome string\n\tgateEnabled := receiverhelper.NewReceiverMetricsGate.IsEnabled()\n\t// The error used in the metrics test is not downstream.\n\tif gateEnabled {\n\t\tfailed = rejected\n\t\toutcome = \"failure\"\n\t} else {\n\t\t// When the gate is disabled, all errors are \"refused\".\n\t\trefused = rejected\n\t}\n\n\tgot, err := tt.GetMetric(\"otelcol_receiver_failed_metric_points\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t,\n\t\tmetricdata.Metrics{\n\t\t\tName:        \"otelcol_receiver_failed_metric_points\",\n\t\t\tDescription: \"The number of metric points that failed to be processed by the receiver due to internal errors. [Alpha]\",\n\t\t\tUnit:        \"{datapoint}\",\n\t\t\tData: metricdata.Sum[int64]{\n\t\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\t\tIsMonotonic: true,\n\t\t\t\tDataPoints: []metricdata.DataPoint[int64]{\n\t\t\t\t\t{\n\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\tattribute.String(\"receiver\", id.String()),\n\t\t\t\t\t\t\tattribute.String(\"transport\", transport)),\n\t\t\t\t\t\tValue: failed,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}, got, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\tgot, err = tt.GetMetric(\"otelcol_receiver_accepted_metric_points\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t,\n\t\tmetricdata.Metrics{\n\t\t\tName:        \"otelcol_receiver_accepted_metric_points\",\n\t\t\tDescription: \"Number of metric points successfully pushed into the pipeline. [Alpha]\",\n\t\t\tUnit:        \"{datapoint}\",\n\t\t\tData: metricdata.Sum[int64]{\n\t\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\t\tIsMonotonic: true,\n\t\t\t\tDataPoints: []metricdata.DataPoint[int64]{\n\t\t\t\t\t{\n\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\tattribute.String(\"receiver\", id.String()),\n\t\t\t\t\t\t\tattribute.String(\"transport\", transport)),\n\t\t\t\t\t\tValue: accepted,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}, got, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\tgot, err = tt.GetMetric(\"otelcol_receiver_refused_metric_points\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t,\n\t\tmetricdata.Metrics{\n\t\t\tName:        \"otelcol_receiver_refused_metric_points\",\n\t\t\tDescription: \"Number of metric points that could not be pushed into the pipeline. [Alpha]\",\n\t\t\tUnit:        \"{datapoint}\",\n\t\t\tData: metricdata.Sum[int64]{\n\t\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\t\tIsMonotonic: true,\n\t\t\t\tDataPoints: []metricdata.DataPoint[int64]{\n\t\t\t\t\t{\n\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\tattribute.String(\"receiver\", id.String()),\n\t\t\t\t\t\t\tattribute.String(\"transport\", transport)),\n\t\t\t\t\t\tValue: refused,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t}, got, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\t// Assert receiver_requests metric\n\tif gateEnabled {\n\t\tgot, err := tt.GetMetric(\"otelcol_receiver_requests\")\n\t\trequire.NoError(t, err)\n\n\t\t// Calculate expected requests based on accepted and refused counts\n\t\tvar expectedRequests []metricdata.DataPoint[int64]\n\t\tif accepted > 0 {\n\t\t\texpectedRequests = append(expectedRequests, metricdata.DataPoint[int64]{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(\"receiver\", id.String()),\n\t\t\t\t\tattribute.String(\"transport\", transport),\n\t\t\t\t\tattribute.String(\"outcome\", \"success\")),\n\t\t\t\tValue: accepted,\n\t\t\t})\n\t\t}\n\t\tif rejected > 0 {\n\t\t\texpectedRequests = append(expectedRequests, metricdata.DataPoint[int64]{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(\"receiver\", id.String()),\n\t\t\t\t\tattribute.String(\"transport\", transport),\n\t\t\t\t\tattribute.String(\"outcome\", outcome)),\n\t\t\t\tValue: 1, // One request failed\n\t\t\t})\n\t\t}\n\n\t\tmetricdatatest.AssertEqual(t,\n\t\t\tmetricdata.Metrics{\n\t\t\t\tName:        \"otelcol_receiver_requests\",\n\t\t\t\tDescription: \"The number of requests performed.\",\n\t\t\t\tUnit:        \"{request}\",\n\t\t\t\tData: metricdata.Sum[int64]{\n\t\t\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\t\t\tIsMonotonic: true,\n\t\t\t\t\tDataPoints:  expectedRequests,\n\t\t\t\t},\n\t\t\t}, got, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t} else {\n\t\t_, err := tt.GetMetric(\"otelcol_receiver_requests\")\n\t\trequire.Error(t, err)\n\t}\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/otlphttp.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlpreceiver // import \"go.opentelemetry.io/collector/receiver/otlpreceiver\"\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"mime\"\n\t\"net/http\"\n\t\"strconv\"\n\t\"time\"\n\n\t\"google.golang.org/grpc/status\"\n\n\t\"go.opentelemetry.io/collector/internal/statusutil\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/errors\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/logs\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/metrics\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/profiles\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/trace\"\n)\n\n// Pre-computed status with code=Internal to be used in case of a marshaling error.\nvar fallbackMsg = []byte(`{\"code\": 13, \"message\": \"failed to marshal error message\"}`)\n\nconst fallbackContentType = \"application/json\"\n\nfunc handleTraces(resp http.ResponseWriter, req *http.Request, tracesReceiver *trace.Receiver) {\n\tenc, ok := readContentType(resp, req)\n\tif !ok {\n\t\treturn\n\t}\n\n\tbody, ok := readAndCloseBody(resp, req, enc)\n\tif !ok {\n\t\treturn\n\t}\n\n\totlpReq, err := enc.unmarshalTracesRequest(body)\n\tif err != nil {\n\t\twriteError(resp, enc, err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\totlpResp, err := tracesReceiver.Export(req.Context(), otlpReq)\n\tif err != nil {\n\t\twriteError(resp, enc, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tmsg, err := enc.marshalTracesResponse(otlpResp)\n\tif err != nil {\n\t\twriteError(resp, enc, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\twriteResponse(resp, enc.contentType(), http.StatusOK, msg)\n}\n\nfunc handleMetrics(resp http.ResponseWriter, req *http.Request, metricsReceiver *metrics.Receiver) {\n\tenc, ok := readContentType(resp, req)\n\tif !ok {\n\t\treturn\n\t}\n\n\tbody, ok := readAndCloseBody(resp, req, enc)\n\tif !ok {\n\t\treturn\n\t}\n\n\totlpReq, err := enc.unmarshalMetricsRequest(body)\n\tif err != nil {\n\t\twriteError(resp, enc, err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\totlpResp, err := metricsReceiver.Export(req.Context(), otlpReq)\n\tif err != nil {\n\t\twriteError(resp, enc, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tmsg, err := enc.marshalMetricsResponse(otlpResp)\n\tif err != nil {\n\t\twriteError(resp, enc, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\twriteResponse(resp, enc.contentType(), http.StatusOK, msg)\n}\n\nfunc handleLogs(resp http.ResponseWriter, req *http.Request, logsReceiver *logs.Receiver) {\n\tenc, ok := readContentType(resp, req)\n\tif !ok {\n\t\treturn\n\t}\n\n\tbody, ok := readAndCloseBody(resp, req, enc)\n\tif !ok {\n\t\treturn\n\t}\n\n\totlpReq, err := enc.unmarshalLogsRequest(body)\n\tif err != nil {\n\t\twriteError(resp, enc, err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\totlpResp, err := logsReceiver.Export(req.Context(), otlpReq)\n\tif err != nil {\n\t\twriteError(resp, enc, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tmsg, err := enc.marshalLogsResponse(otlpResp)\n\tif err != nil {\n\t\twriteError(resp, enc, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\twriteResponse(resp, enc.contentType(), http.StatusOK, msg)\n}\n\nfunc handleProfiles(resp http.ResponseWriter, req *http.Request, profilesReceiver *profiles.Receiver) {\n\tenc, ok := readContentType(resp, req)\n\tif !ok {\n\t\treturn\n\t}\n\n\tbody, ok := readAndCloseBody(resp, req, enc)\n\tif !ok {\n\t\treturn\n\t}\n\n\totlpReq, err := enc.unmarshalProfilesRequest(body)\n\tif err != nil {\n\t\twriteError(resp, enc, err, http.StatusBadRequest)\n\t\treturn\n\t}\n\n\totlpResp, err := profilesReceiver.Export(req.Context(), otlpReq)\n\tif err != nil {\n\t\twriteError(resp, enc, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\n\tmsg, err := enc.marshalProfilesResponse(otlpResp)\n\tif err != nil {\n\t\twriteError(resp, enc, err, http.StatusInternalServerError)\n\t\treturn\n\t}\n\twriteResponse(resp, enc.contentType(), http.StatusOK, msg)\n}\n\nfunc readContentType(resp http.ResponseWriter, req *http.Request) (encoder, bool) {\n\tif req.Method != http.MethodPost {\n\t\thandleUnmatchedMethod(resp)\n\t\treturn nil, false\n\t}\n\n\tswitch getMimeTypeFromContentType(req.Header.Get(\"Content-Type\")) {\n\tcase pbContentType:\n\t\treturn pbEncoder, true\n\tcase jsonContentType:\n\t\treturn jsEncoder, true\n\tdefault:\n\t\thandleUnmatchedContentType(resp)\n\t\treturn nil, false\n\t}\n}\n\nfunc readAndCloseBody(resp http.ResponseWriter, req *http.Request, enc encoder) ([]byte, bool) {\n\tbody, err := io.ReadAll(req.Body)\n\tif err != nil {\n\t\twriteError(resp, enc, err, http.StatusBadRequest)\n\t\treturn nil, false\n\t}\n\tif err = req.Body.Close(); err != nil {\n\t\twriteError(resp, enc, err, http.StatusBadRequest)\n\t\treturn nil, false\n\t}\n\treturn body, true\n}\n\n// writeError encodes the HTTP error inside a rpc.Status message as required by the OTLP protocol.\nfunc writeError(w http.ResponseWriter, encoder encoder, err error, statusCode int) {\n\ts, ok := status.FromError(err)\n\tif ok {\n\t\tstatusCode = errors.GetHTTPStatusCodeFromStatus(s)\n\t} else {\n\t\ts = statusutil.NewStatusFromMsgAndHTTPCode(err.Error(), statusCode)\n\t}\n\twriteStatusResponse(w, encoder, statusCode, s)\n}\n\n// errorHandler encodes the HTTP error message inside a rpc.Status message as required\n// by the OTLP protocol.\nfunc errorHandler(w http.ResponseWriter, r *http.Request, errMsg string, statusCode int) {\n\ts := statusutil.NewStatusFromMsgAndHTTPCode(errMsg, statusCode)\n\tcontentType := r.Header.Get(\"Content-Type\")\n\tif contentType == \"\" {\n\t\tcontentType = fallbackContentType\n\t}\n\tswitch getMimeTypeFromContentType(contentType) {\n\tcase pbContentType:\n\t\twriteStatusResponse(w, pbEncoder, statusCode, s)\n\t\treturn\n\tcase jsonContentType:\n\t\twriteStatusResponse(w, jsEncoder, statusCode, s)\n\t\treturn\n\t}\n\twriteResponse(w, fallbackContentType, http.StatusInternalServerError, fallbackMsg)\n}\n\nfunc writeStatusResponse(w http.ResponseWriter, enc encoder, statusCode int, st *status.Status) {\n\t// https://github.com/open-telemetry/opentelemetry-proto/blob/main/docs/specification.md#otlphttp-throttling\n\tif statusCode == http.StatusTooManyRequests || statusCode == http.StatusServiceUnavailable {\n\t\tretryInfo := statusutil.GetRetryInfo(st)\n\t\t// Check if server returned throttling information.\n\t\tif retryInfo != nil {\n\t\t\t// We are throttled. Wait before retrying as requested by the server.\n\t\t\t// The value of Retry-After field can be either an HTTP-date or a number of\n\t\t\t// seconds to delay after the response is received. See https://datatracker.ietf.org/doc/html/rfc7231#section-7.1.3\n\t\t\t//\n\t\t\t// Retry-After = HTTP-date / delay-seconds\n\t\t\t//\n\t\t\t// Use delay-seconds since is easier to format as well as does not require clock synchronization.\n\t\t\tw.Header().Set(\"Retry-After\", strconv.FormatInt(int64(retryInfo.GetRetryDelay().AsDuration()/time.Second), 10))\n\t\t}\n\t}\n\tmsg, err := enc.marshalStatus(st.Proto())\n\tif err != nil {\n\t\twriteResponse(w, fallbackContentType, http.StatusInternalServerError, fallbackMsg)\n\t\treturn\n\t}\n\n\twriteResponse(w, enc.contentType(), statusCode, msg)\n}\n\nfunc writeResponse(w http.ResponseWriter, contentType string, statusCode int, msg []byte) {\n\tw.Header().Set(\"Content-Type\", contentType)\n\tw.WriteHeader(statusCode)\n\t// Nothing we can do with the error if we cannot write to the response.\n\t_, _ = w.Write(msg)\n}\n\nfunc getMimeTypeFromContentType(contentType string) string {\n\tmediatype, _, err := mime.ParseMediaType(contentType)\n\tif err != nil {\n\t\treturn \"\"\n\t}\n\treturn mediatype\n}\n\nfunc handleUnmatchedMethod(resp http.ResponseWriter) {\n\thst := http.StatusMethodNotAllowed\n\twriteResponse(resp, \"text/plain\", hst, fmt.Appendf(nil, \"%v method not allowed, supported: [POST]\", hst))\n}\n\nfunc handleUnmatchedContentType(resp http.ResponseWriter) {\n\thst := http.StatusUnsupportedMediaType\n\twriteResponse(resp, \"text/plain\", hst, fmt.Appendf(nil, \"%v unsupported media type, supported: [%s, %s]\", hst, jsonContentType, pbContentType))\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/otlphttp_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otlpreceiver\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"net/http\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"google.golang.org/genproto/googleapis/rpc/errdetails\"\n\tspb \"google.golang.org/genproto/googleapis/rpc/status\"\n\t\"google.golang.org/grpc/codes\"\n\t\"google.golang.org/grpc/status\"\n\t\"google.golang.org/protobuf/proto\"\n\t\"google.golang.org/protobuf/types/known/durationpb\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n\t\"go.opentelemetry.io/collector/receiver/otlpreceiver/internal/errors\"\n)\n\nfunc TestHTTPRetryAfter(t *testing.T) {\n\ttests := []struct {\n\t\tname                  string\n\t\tcontentType           string\n\t\terr                   error\n\t\texpectedStatusCode    int\n\t\texpectedHasRetryAfter bool\n\t\texpectedRetryAfter    string\n\t}{\n\t\t{\n\t\t\tname:               \"StatusErrorRetryableNoRetryAfter\",\n\t\t\terr:                status.New(codes.DeadlineExceeded, \"\").Err(),\n\t\t\texpectedStatusCode: http.StatusServiceUnavailable,\n\t\t},\n\t\t{\n\t\t\tname: \"StatusErrorRetryableWithZeroRetryAfter\",\n\t\t\terr: func() error {\n\t\t\t\tst := status.New(codes.ResourceExhausted, \"\")\n\t\t\t\tdt, err := st.WithDetails(&errdetails.RetryInfo{\n\t\t\t\t\tRetryDelay: durationpb.New(0),\n\t\t\t\t})\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\treturn dt.Err()\n\t\t\t}(),\n\t\t\texpectedStatusCode:    http.StatusTooManyRequests,\n\t\t\texpectedHasRetryAfter: true,\n\t\t\texpectedRetryAfter:    \"0\",\n\t\t},\n\t\t{\n\t\t\tname: \"StatusErrorRetryableRetryAfter\",\n\t\t\terr: func() error {\n\t\t\t\tst := status.New(codes.ResourceExhausted, \"\")\n\t\t\t\tdt, err := st.WithDetails(&errdetails.RetryInfo{\n\t\t\t\t\tRetryDelay: durationpb.New(13 * time.Second),\n\t\t\t\t})\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\treturn dt.Err()\n\t\t\t}(),\n\t\t\texpectedStatusCode:    http.StatusTooManyRequests,\n\t\t\texpectedHasRetryAfter: true,\n\t\t\texpectedRetryAfter:    \"13\",\n\t\t},\n\t\t{\n\t\t\tname: \"StatusErrorNotRetryableRetryAfter\",\n\t\t\terr: func() error {\n\t\t\t\tst := status.New(codes.Unknown, \"\")\n\t\t\t\tdt, err := st.WithDetails(&errdetails.RetryInfo{\n\t\t\t\t\tRetryDelay: durationpb.New(12 * time.Second),\n\t\t\t\t})\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\treturn dt.Err()\n\t\t\t}(),\n\t\t\texpectedStatusCode: http.StatusInternalServerError,\n\t\t},\n\t\t{\n\t\t\tname:               \"StatusErrorNotRetryableNoRetryAfter\",\n\t\t\terr:                status.New(codes.InvalidArgument, \"\").Err(),\n\t\t\texpectedStatusCode: http.StatusBadRequest,\n\t\t},\n\t}\n\taddr := testutil.GetAvailableLocalAddress(t)\n\n\t// Set the buffer count to 1 to make it flush the test span immediately.\n\tsink := newErrOrSinkConsumer()\n\trecv := newHTTPReceiver(t, componenttest.NewNopTelemetrySettings(), addr, sink)\n\n\trequire.NoError(t, recv.Start(context.Background(), componenttest.NewNopHost()), \"Failed to start trace receiver\")\n\tt.Cleanup(func() { require.NoError(t, recv.Shutdown(context.Background())) })\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tsink.Reset()\n\t\t\tsink.SetConsumeError(tt.err)\n\n\t\t\tfor _, dr := range generateDataRequests(t) {\n\t\t\t\turl := \"http://\" + addr + dr.path\n\t\t\t\treq := createHTTPRequest(t, url, \"\", \"application/x-protobuf\", dr.protoBytes)\n\t\t\t\tresp, err := http.DefaultClient.Do(req)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\trespBytes, err := io.ReadAll(resp.Body)\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\trequire.NoError(t, resp.Body.Close())\n\t\t\t\t// For cases like \"application/json; charset=utf-8\", the response will be only \"application/json\"\n\t\t\t\trequire.True(t, strings.HasPrefix(strings.ToLower(\"application/x-protobuf\"), resp.Header.Get(\"Content-Type\")))\n\t\t\t\tif tt.expectedHasRetryAfter {\n\t\t\t\t\trequire.Equal(t, tt.expectedRetryAfter, resp.Header.Get(\"Retry-After\"))\n\t\t\t\t} else {\n\t\t\t\t\trequire.Empty(t, resp.Header.Get(\"Retry-After\"))\n\t\t\t\t}\n\n\t\t\t\tassert.Equal(t, tt.expectedStatusCode, resp.StatusCode)\n\n\t\t\t\tif tt.err == nil {\n\t\t\t\t\ttr := ptraceotlp.NewExportResponse()\n\t\t\t\t\trequire.NoError(t, tr.UnmarshalProto(respBytes))\n\t\t\t\t\tsink.checkData(t, dr.data, 1)\n\t\t\t\t} else {\n\t\t\t\t\terrStatus := &spb.Status{}\n\t\t\t\t\trequire.NoError(t, proto.Unmarshal(respBytes, errStatus))\n\t\t\t\t\t// The HTTP receiver transforms errors through GetStatusFromError\n\t\t\t\t\t// We need to get the expected transformed error, not the original\n\t\t\t\t\texpectedErr := errors.GetStatusFromError(tt.err)\n\t\t\t\t\ts, ok := status.FromError(expectedErr)\n\t\t\t\t\trequire.True(t, ok)\n\t\t\t\t\tassert.True(t, proto.Equal(errStatus, s.Proto()))\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "receiver/otlpreceiver/testdata/bad_no_proto_config.yaml",
    "content": "protocols:\n"
  },
  {
    "path": "receiver/otlpreceiver/testdata/bad_proto_config.yaml",
    "content": "protocols:\n  thrift:\n    endpoint: \"127.0.0.1:1234\"\n"
  },
  {
    "path": "receiver/otlpreceiver/testdata/config.yaml",
    "content": "protocols:\n  grpc:\n    # The following entry demonstrates how to specify TLS credentials for the server.\n    # Note: These files do not exist. If the receiver is started with this configuration, it will fail.\n    tls:\n      cert_file: test.crt\n      key_file: test.key\n\n    # The following demonstrates how to set maximum limits on stream, message size and connection idle time.\n    # Note: The test yaml has demonstrated configuration on a grouped by their structure; however, all of the settings can\n    # be mix and matched like adding the maximum connection idle setting in this example.\n    max_recv_msg_size_mib: 32\n    max_concurrent_streams: 16\n    read_buffer_size: 1024\n    write_buffer_size: 1024\n\n    # The following entry configures all of the keep alive settings. These settings are used to configure the receiver.\n    keepalive:\n      server_parameters:\n        max_connection_idle: 11s\n        max_connection_age: 12s\n        max_connection_age_grace: 13s\n        time: 30s\n        timeout: 5s\n      enforcement_policy:\n        min_time: 10s\n        permit_without_stream: true\n  http:\n    auth:\n      authenticator: test\n    # The following entry demonstrates how to specify TLS credentials for the server.\n    # Note: These files do not exist. If the receiver is started with this configuration, it will fail.\n    tls:\n      cert_file: test.crt\n      key_file: test.key\n\n    # The following entry demonstrates how to configure the OTLP receiver to allow Cross-Origin Resource Sharing (CORS).\n    # Both fully qualified domain names and the use of wildcards are supported.\n    cors:\n      allowed_origins:\n        - https://*.test.com # Wildcard subdomain. Allows domains like https://www.test.com and https://foo.test.com but not https://wwwtest.com.\n        - https://test.com # Fully qualified domain name. Allows https://test.com only.\n      max_age: 7200\n\n    # The following shows URL paths for endpoints where signals are listened for bt the OTLP receiver\n    traces_url_path: traces\n    metrics_url_path: /v2/metrics\n    logs_url_path: log/ingest\n"
  },
  {
    "path": "receiver/otlpreceiver/testdata/default.yaml",
    "content": "# The following entry initializes the default OTLP receiver.\n# The full name of this receiver is `otlp` and can be referenced in pipelines by 'otlp'.\nprotocols:\n  grpc:\n  http:\n"
  },
  {
    "path": "receiver/otlpreceiver/testdata/invalid_logs_path.yaml",
    "content": "protocols:\n  http:\n    logs_url_path: \":invalid\"\n"
  },
  {
    "path": "receiver/otlpreceiver/testdata/invalid_metrics_path.yaml",
    "content": "protocols:\n  http:\n    metrics_url_path: \":invalid\"\n"
  },
  {
    "path": "receiver/otlpreceiver/testdata/invalid_profiles_path.yaml",
    "content": "protocols:\n  http:\n    profiles_url_path: \":invalid\"\n"
  },
  {
    "path": "receiver/otlpreceiver/testdata/invalid_traces_path.yaml",
    "content": "protocols:\n  http:\n    traces_url_path: \":invalid\"\n"
  },
  {
    "path": "receiver/otlpreceiver/testdata/only_grpc.yaml",
    "content": "# The following entry initializes the default OTLP receiver with only gRPC support.\nprotocols:\n  grpc:\n"
  },
  {
    "path": "receiver/otlpreceiver/testdata/only_http.yaml",
    "content": "# The following entry initializes the default OTLP receiver with only http support.\nprotocols:\n  http:\n"
  },
  {
    "path": "receiver/otlpreceiver/testdata/only_http_empty_map.yaml",
    "content": "# The following entry initializes the default OTLP receiver with only http support by setting it explicitly to an empty map.\nprotocols:\n  http: {}\n"
  },
  {
    "path": "receiver/otlpreceiver/testdata/only_http_null.yaml",
    "content": "# The following entry initializes the default OTLP receiver with only http support by setting it explicitly to null.\nprotocols:\n  http: null\n"
  },
  {
    "path": "receiver/otlpreceiver/testdata/typo_default_proto_config.yaml",
    "content": "# cspell:ignore htttp\nprotocols:\n  grpc:\n  htttp:\n"
  },
  {
    "path": "receiver/otlpreceiver/testdata/uds.yaml",
    "content": "# The following entry demonstrates how to specify a Unix Domain Socket for the server.\nprotocols:\n  grpc:\n    transport: unix\n    endpoint: /tmp/grpc_otlp.sock\n  http:\n    transport: unix\n    endpoint: /tmp/http_otlp.sock\n"
  },
  {
    "path": "receiver/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage receiver\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "receiver/receiver.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage receiver // import \"go.opentelemetry.io/collector/receiver\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\n// Traces receiver receives traces.\n// Its purpose is to translate data from any format to the collector's internal trace format.\n// Traces receiver feeds a consumer.Traces with data.\n//\n// For example, it could be Zipkin data source which translates Zipkin spans into ptrace.Traces.\ntype Traces interface {\n\tcomponent.Component\n}\n\n// Metrics receiver receives metrics.\n// Its purpose is to translate data from any format to the collector's internal metrics format.\n// Metrics receiver feeds a consumer.Metrics with data.\n//\n// For example, it could be Prometheus data source which translates Prometheus metrics into pmetric.Metrics.\ntype Metrics interface {\n\tcomponent.Component\n}\n\n// Logs receiver receives logs.\n// Its purpose is to translate data from any format to the collector's internal logs data format.\n// Logs receiver feeds a consumer.Logs with data.\n//\n// For example, it could be a receiver that reads syslogs and convert them into plog.Logs.\ntype Logs interface {\n\tcomponent.Component\n}\n\n// Settings configures receiver creators.\ntype Settings struct {\n\t// ID returns the ID of the component that will be created.\n\tID component.ID\n\n\tcomponent.TelemetrySettings\n\n\t// BuildInfo can be used by components for informational purposes.\n\tBuildInfo component.BuildInfo\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// Factory is a factory interface for receivers.\n//\n// This interface cannot be directly implemented. Implementations must\n// use the NewFactory to implement it.\ntype Factory interface {\n\tcomponent.Factory\n\n\t// CreateTraces creates a Traces based on this config.\n\t// If the receiver type does not support traces,\n\t// this function returns the error [pipeline.ErrSignalNotSupported].\n\t// Implementers can assume `next` is never nil.\n\tCreateTraces(ctx context.Context, set Settings, cfg component.Config, next consumer.Traces) (Traces, error)\n\n\t// TracesStability gets the stability level of the Traces receiver.\n\tTracesStability() component.StabilityLevel\n\n\t// CreateMetrics creates a Metrics based on this config.\n\t// If the receiver type does not support metrics,\n\t// this function returns the error [pipeline.ErrSignalNotSupported].\n\t// Implementers can assume `next` is never nil.\n\tCreateMetrics(ctx context.Context, set Settings, cfg component.Config, next consumer.Metrics) (Metrics, error)\n\n\t// MetricsStability gets the stability level of the Metrics receiver.\n\tMetricsStability() component.StabilityLevel\n\n\t// CreateLogs creates a Logs based on this config.\n\t// If the receiver type does not support logs,\n\t// this function returns the error [pipeline.ErrSignalNotSupported].\n\t// Implementers can assume `next` is never nil.\n\tCreateLogs(ctx context.Context, set Settings, cfg component.Config, next consumer.Logs) (Logs, error)\n\n\t// LogsStability gets the stability level of the Logs receiver.\n\tLogsStability() component.StabilityLevel\n\n\tunexportedFactoryFunc()\n}\n\n// FactoryOption apply changes to Factory.\ntype FactoryOption interface {\n\t// applyOption applies the option.\n\tapplyOption(o *factory)\n}\n\n// factoryOptionFunc is an FactoryOption created through a function.\ntype factoryOptionFunc func(*factory)\n\nfunc (f factoryOptionFunc) applyOption(o *factory) {\n\tf(o)\n}\n\n// CreateTracesFunc is the equivalent of Factory.CreateTraces.\ntype CreateTracesFunc func(context.Context, Settings, component.Config, consumer.Traces) (Traces, error)\n\n// CreateMetricsFunc is the equivalent of Factory.CreateMetrics.\ntype CreateMetricsFunc func(context.Context, Settings, component.Config, consumer.Metrics) (Metrics, error)\n\n// CreateLogsFunc is the equivalent of Factory.CreateLogs.\ntype CreateLogsFunc func(context.Context, Settings, component.Config, consumer.Logs) (Logs, error)\n\ntype factory struct {\n\tcfgType component.Type\n\tcomponent.CreateDefaultConfigFunc\n\tcomponentalias.TypeAliasHolder\n\tcreateTracesFunc      CreateTracesFunc\n\ttracesStabilityLevel  component.StabilityLevel\n\tcreateMetricsFunc     CreateMetricsFunc\n\tmetricsStabilityLevel component.StabilityLevel\n\tcreateLogsFunc        CreateLogsFunc\n\tlogsStabilityLevel    component.StabilityLevel\n}\n\nfunc (f *factory) Type() component.Type {\n\treturn f.cfgType\n}\n\nfunc (f *factory) unexportedFactoryFunc() {}\n\nfunc (f *factory) TracesStability() component.StabilityLevel {\n\treturn f.tracesStabilityLevel\n}\n\nfunc (f *factory) MetricsStability() component.StabilityLevel {\n\treturn f.metricsStabilityLevel\n}\n\nfunc (f *factory) LogsStability() component.StabilityLevel {\n\treturn f.logsStabilityLevel\n}\n\nfunc (f *factory) CreateTraces(ctx context.Context, set Settings, cfg component.Config, next consumer.Traces) (Traces, error) {\n\tif f.createTracesFunc == nil {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createTracesFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateMetrics(ctx context.Context, set Settings, cfg component.Config, next consumer.Metrics) (Metrics, error) {\n\tif f.createMetricsFunc == nil {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createMetricsFunc(ctx, set, cfg, next)\n}\n\nfunc (f *factory) CreateLogs(ctx context.Context, set Settings, cfg component.Config, next consumer.Logs) (Logs, error) {\n\tif f.createLogsFunc == nil {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\n\tif err := componentalias.ValidateComponentType(f, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn f.createLogsFunc(ctx, set, cfg, next)\n}\n\n// WithTraces overrides the default \"error not supported\" implementation for Factory.CreateTraces and the default \"undefined\" stability level.\nfunc WithTraces(createTraces CreateTracesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.tracesStabilityLevel = sl\n\t\to.createTracesFunc = createTraces\n\t})\n}\n\n// WithMetrics overrides the default \"error not supported\" implementation for Factory.CreateMetrics and the default \"undefined\" stability level.\nfunc WithMetrics(createMetrics CreateMetricsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.metricsStabilityLevel = sl\n\t\to.createMetricsFunc = createMetrics\n\t})\n}\n\n// WithLogs overrides the default \"error not supported\" implementation for Factory.CreateLogs and the default \"undefined\" stability level.\nfunc WithLogs(createLogs CreateLogsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.logsStabilityLevel = sl\n\t\to.createLogsFunc = createLogs\n\t})\n}\n\n// NewFactory returns a Factory.\nfunc NewFactory(cfgType component.Type, createDefaultConfig component.CreateDefaultConfigFunc, options ...FactoryOption) Factory {\n\tf := &factory{\n\t\tcfgType:                 cfgType,\n\t\tCreateDefaultConfigFunc: createDefaultConfig,\n\t\tTypeAliasHolder:         componentalias.NewTypeAliasHolder(),\n\t}\n\tfor _, opt := range options {\n\t\topt.applyOption(f)\n\t}\n\treturn f\n}\n"
  },
  {
    "path": "receiver/receiver_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage receiver\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/receiver/internal\"\n)\n\nvar (\n\ttestType = component.MustNewType(\"test\")\n\ttestID   = component.NewID(testType)\n)\n\nfunc TestNewFactory(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tf := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg })\n\tassert.Equal(t, testType, f.Type())\n\tassert.EqualValues(t, &defaultCfg, f.CreateDefaultConfig())\n\t_, err := f.CreateTraces(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.ErrorIs(t, err, pipeline.ErrSignalNotSupported)\n\t_, err = f.CreateMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.ErrorIs(t, err, pipeline.ErrSignalNotSupported)\n\t_, err = f.CreateLogs(context.Background(), Settings{ID: testID}, &defaultCfg, consumertest.NewNop())\n\trequire.ErrorIs(t, err, pipeline.ErrSignalNotSupported)\n}\n\nfunc TestNewFactoryWithOptions(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tf := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg },\n\t\tWithTraces(createTraces, component.StabilityLevelDeprecated),\n\t\tWithMetrics(createMetrics, component.StabilityLevelAlpha),\n\t\tWithLogs(createLogs, component.StabilityLevelStable))\n\tassert.Equal(t, testType, f.Type())\n\tassert.EqualValues(t, &defaultCfg, f.CreateDefaultConfig())\n\n\twrongID := component.MustNewID(\"wrong\")\n\twrongIDErrStr := internal.ErrIDMismatch(wrongID, testType).Error()\n\n\tassert.Equal(t, component.StabilityLevelDeprecated, f.TracesStability())\n\t_, err := f.CreateTraces(context.Background(), Settings{ID: testID}, &defaultCfg, nil)\n\trequire.NoError(t, err)\n\t_, err = f.CreateTraces(context.Background(), Settings{ID: wrongID}, &defaultCfg, nil)\n\trequire.EqualError(t, err, wrongIDErrStr)\n\n\tassert.Equal(t, component.StabilityLevelAlpha, f.MetricsStability())\n\t_, err = f.CreateMetrics(context.Background(), Settings{ID: testID}, &defaultCfg, nil)\n\trequire.NoError(t, err)\n\t_, err = f.CreateMetrics(context.Background(), Settings{ID: wrongID}, &defaultCfg, nil)\n\trequire.EqualError(t, err, wrongIDErrStr)\n\n\tassert.Equal(t, component.StabilityLevelStable, f.LogsStability())\n\t_, err = f.CreateLogs(context.Background(), Settings{ID: testID}, &defaultCfg, nil)\n\trequire.NoError(t, err)\n\t_, err = f.CreateLogs(context.Background(), Settings{ID: wrongID}, &defaultCfg, nil)\n\trequire.EqualError(t, err, wrongIDErrStr)\n}\n\nvar nopInstance = &nopReceiver{\n\tConsumer: consumertest.NewNop(),\n}\n\n// nopReceiver stores consumed traces and metrics for testing purposes.\ntype nopReceiver struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumertest.Consumer\n}\n\nfunc createTraces(context.Context, Settings, component.Config, consumer.Traces) (Traces, error) {\n\treturn nopInstance, nil\n}\n\nfunc createMetrics(context.Context, Settings, component.Config, consumer.Metrics) (Metrics, error) {\n\treturn nopInstance, nil\n}\n\nfunc createLogs(context.Context, Settings, component.Config, consumer.Logs) (Logs, error) {\n\treturn nopInstance, nil\n}\n"
  },
  {
    "path": "receiver/receiverhelper/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "receiver/receiverhelper/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# receiverhelper\n\n## Internal Telemetry\n\nThe following telemetry is emitted by this component.\n\n### otelcol_receiver_accepted_log_records\n\nNumber of log records successfully pushed into the pipeline.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {record} | Sum | Int | true | Alpha |\n\n### otelcol_receiver_accepted_metric_points\n\nNumber of metric points successfully pushed into the pipeline.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {datapoint} | Sum | Int | true | Alpha |\n\n### otelcol_receiver_accepted_profile_samples\n\nNumber of profile samples successfully pushed into the pipeline.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {sample} | Sum | Int | true | Alpha |\n\n### otelcol_receiver_accepted_spans\n\nNumber of spans successfully pushed into the pipeline.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {span} | Sum | Int | true | Alpha |\n\n### otelcol_receiver_failed_log_records\n\nThe number of log records that failed to be processed by the receiver due to internal errors.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {record} | Sum | Int | true | Alpha |\n\n### otelcol_receiver_failed_metric_points\n\nThe number of metric points that failed to be processed by the receiver due to internal errors.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {datapoint} | Sum | Int | true | Alpha |\n\n### otelcol_receiver_failed_profile_samples\n\nThe number of profile samples that failed to be processed by the receiver due to internal errors.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {sample} | Sum | Int | true | Alpha |\n\n### otelcol_receiver_failed_spans\n\nThe number of spans that failed to be processed by the receiver due to internal errors.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {span} | Sum | Int | true | Alpha |\n\n### otelcol_receiver_refused_log_records\n\nNumber of log records that could not be pushed into the pipeline.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {record} | Sum | Int | true | Alpha |\n\n### otelcol_receiver_refused_metric_points\n\nNumber of metric points that could not be pushed into the pipeline.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {datapoint} | Sum | Int | true | Alpha |\n\n### otelcol_receiver_refused_profile_samples\n\nNumber of profile samples that could not be pushed into the pipeline.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {sample} | Sum | Int | true | Alpha |\n\n### otelcol_receiver_refused_spans\n\nNumber of spans that could not be pushed into the pipeline.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {span} | Sum | Int | true | Alpha |\n\n### otelcol_receiver_requests\n\nThe number of requests performed.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {request} | Sum | Int | true | Alpha |\n\n#### Attributes\n\n| Name | Description | Values |\n| ---- | ----------- | ------ |\n| outcome | The outcome of receiver requests | Str: ``success``, ``refused``, ``failure`` |\n\n## Feature Gates\n\nThis component has the following feature gates:\n\n| Feature Gate | Stage | Description | From Version | To Version | Reference |\n| ------------ | ----- | ----------- | ------------ | ---------- | --------- |\n| `receiverhelper.newReceiverMetrics` | alpha | Controls whether receivers emit new metrics and span attributes to distinguish downstream errors from internal errors. This is a breaking change for the semantics of the otelcol_receiver_refused_metric_points,  otelcol_receiver_refused_log_records and otelcol_receiver_refused_spans. | v0.138.0 | N/A | [Link](https://github.com/open-telemetry/opentelemetry-collector/pull/12802) |\n\nFor more information about feature gates, see the [Feature Gates](https://github.com/open-telemetry/opentelemetry-collector/blob/main/featuregate/README.md) documentation.\n"
  },
  {
    "path": "receiver/receiverhelper/featuregates.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage receiverhelper // import \"go.opentelemetry.io/collector/receiver/receiverhelper\"\n\nimport \"go.opentelemetry.io/collector/receiver/receiverhelper/internal/metadata\"\n\n// NewReceiverMetricsGate is the feature gate that controls whether to distinguish downstream errors from internal errors in pipeline telemetry.\n// This feature gate is used in OTLP receiver tests, and therefore needs to be public.\nvar NewReceiverMetricsGate = metadata.ReceiverhelperNewReceiverMetricsFeatureGate\n"
  },
  {
    "path": "receiver/receiverhelper/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage receiverhelper\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "receiver/receiverhelper/go.mod",
    "content": "module go.opentelemetry.io/collector/receiver/receiverhelper\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0\n\tgo.opentelemetry.io/collector/featuregate v1.54.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0\n\tgo.opentelemetry.io/collector/receiver v1.54.0\n\tgo.opentelemetry.io/otel v1.42.0\n\tgo.opentelemetry.io/otel/metric v1.42.0\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0\n\tgo.opentelemetry.io/otel/trace v1.42.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/consumer v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/receiver => ../\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "receiver/receiverhelper/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "receiver/receiverhelper/internal/metadata/generated_feature_gates.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\nvar ReceiverhelperNewReceiverMetricsFeatureGate = featuregate.GlobalRegistry().MustRegister(\n\t\"receiverhelper.newReceiverMetrics\",\n\tfeaturegate.StageAlpha,\n\tfeaturegate.WithRegisterDescription(\"Controls whether receivers emit new metrics and span attributes to distinguish downstream errors from internal errors. This is a breaking change for the semantics of the otelcol_receiver_refused_metric_points,  otelcol_receiver_refused_log_records and otelcol_receiver_refused_spans.\"),\n\tfeaturegate.WithRegisterReferenceURL(\"https://github.com/open-telemetry/opentelemetry-collector/pull/12802\"),\n\tfeaturegate.WithRegisterFromVersion(\"v0.138.0\"),\n)\n"
  },
  {
    "path": "receiver/receiverhelper/internal/metadata/generated_telemetry.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc Meter(settings component.TelemetrySettings) metric.Meter {\n\treturn settings.MeterProvider.Meter(\"go.opentelemetry.io/collector/receiver/receiverhelper\")\n}\n\nfunc Tracer(settings component.TelemetrySettings) trace.Tracer {\n\treturn settings.TracerProvider.Tracer(\"go.opentelemetry.io/collector/receiver/receiverhelper\")\n}\n\n// TelemetryBuilder provides an interface for components to report telemetry\n// as defined in metadata and user config.\ntype TelemetryBuilder struct {\n\tmeter                          metric.Meter\n\tmu                             sync.Mutex\n\tregistrations                  []metric.Registration\n\tReceiverAcceptedLogRecords     metric.Int64Counter\n\tReceiverAcceptedMetricPoints   metric.Int64Counter\n\tReceiverAcceptedProfileSamples metric.Int64Counter\n\tReceiverAcceptedSpans          metric.Int64Counter\n\tReceiverFailedLogRecords       metric.Int64Counter\n\tReceiverFailedMetricPoints     metric.Int64Counter\n\tReceiverFailedProfileSamples   metric.Int64Counter\n\tReceiverFailedSpans            metric.Int64Counter\n\tReceiverRefusedLogRecords      metric.Int64Counter\n\tReceiverRefusedMetricPoints    metric.Int64Counter\n\tReceiverRefusedProfileSamples  metric.Int64Counter\n\tReceiverRefusedSpans           metric.Int64Counter\n\tReceiverRequests               metric.Int64Counter\n}\n\n// TelemetryBuilderOption applies changes to default builder.\ntype TelemetryBuilderOption interface {\n\tapply(*TelemetryBuilder)\n}\n\ntype telemetryBuilderOptionFunc func(mb *TelemetryBuilder)\n\nfunc (tbof telemetryBuilderOptionFunc) apply(mb *TelemetryBuilder) {\n\ttbof(mb)\n}\n\n// Shutdown unregister all registered callbacks for async instruments.\nfunc (builder *TelemetryBuilder) Shutdown() {\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tfor _, reg := range builder.registrations {\n\t\treg.Unregister()\n\t}\n}\n\n// NewTelemetryBuilder provides a struct with methods to update all internal telemetry\n// for a component\nfunc NewTelemetryBuilder(settings component.TelemetrySettings, options ...TelemetryBuilderOption) (*TelemetryBuilder, error) {\n\tbuilder := TelemetryBuilder{}\n\tfor _, op := range options {\n\t\top.apply(&builder)\n\t}\n\tbuilder.meter = Meter(settings)\n\tvar err, errs error\n\tbuilder.ReceiverAcceptedLogRecords, err = builder.meter.Int64Counter(\n\t\t\"otelcol_receiver_accepted_log_records\",\n\t\tmetric.WithDescription(\"Number of log records successfully pushed into the pipeline. [Alpha]\"),\n\t\tmetric.WithUnit(\"{record}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ReceiverAcceptedMetricPoints, err = builder.meter.Int64Counter(\n\t\t\"otelcol_receiver_accepted_metric_points\",\n\t\tmetric.WithDescription(\"Number of metric points successfully pushed into the pipeline. [Alpha]\"),\n\t\tmetric.WithUnit(\"{datapoint}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ReceiverAcceptedProfileSamples, err = builder.meter.Int64Counter(\n\t\t\"otelcol_receiver_accepted_profile_samples\",\n\t\tmetric.WithDescription(\"Number of profile samples successfully pushed into the pipeline. [Alpha]\"),\n\t\tmetric.WithUnit(\"{sample}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ReceiverAcceptedSpans, err = builder.meter.Int64Counter(\n\t\t\"otelcol_receiver_accepted_spans\",\n\t\tmetric.WithDescription(\"Number of spans successfully pushed into the pipeline. [Alpha]\"),\n\t\tmetric.WithUnit(\"{span}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ReceiverFailedLogRecords, err = builder.meter.Int64Counter(\n\t\t\"otelcol_receiver_failed_log_records\",\n\t\tmetric.WithDescription(\"The number of log records that failed to be processed by the receiver due to internal errors. [Alpha]\"),\n\t\tmetric.WithUnit(\"{record}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ReceiverFailedMetricPoints, err = builder.meter.Int64Counter(\n\t\t\"otelcol_receiver_failed_metric_points\",\n\t\tmetric.WithDescription(\"The number of metric points that failed to be processed by the receiver due to internal errors. [Alpha]\"),\n\t\tmetric.WithUnit(\"{datapoint}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ReceiverFailedProfileSamples, err = builder.meter.Int64Counter(\n\t\t\"otelcol_receiver_failed_profile_samples\",\n\t\tmetric.WithDescription(\"The number of profile samples that failed to be processed by the receiver due to internal errors. [Alpha]\"),\n\t\tmetric.WithUnit(\"{sample}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ReceiverFailedSpans, err = builder.meter.Int64Counter(\n\t\t\"otelcol_receiver_failed_spans\",\n\t\tmetric.WithDescription(\"The number of spans that failed to be processed by the receiver due to internal errors. [Alpha]\"),\n\t\tmetric.WithUnit(\"{span}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ReceiverRefusedLogRecords, err = builder.meter.Int64Counter(\n\t\t\"otelcol_receiver_refused_log_records\",\n\t\tmetric.WithDescription(\"Number of log records that could not be pushed into the pipeline. [Alpha]\"),\n\t\tmetric.WithUnit(\"{record}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ReceiverRefusedMetricPoints, err = builder.meter.Int64Counter(\n\t\t\"otelcol_receiver_refused_metric_points\",\n\t\tmetric.WithDescription(\"Number of metric points that could not be pushed into the pipeline. [Alpha]\"),\n\t\tmetric.WithUnit(\"{datapoint}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ReceiverRefusedProfileSamples, err = builder.meter.Int64Counter(\n\t\t\"otelcol_receiver_refused_profile_samples\",\n\t\tmetric.WithDescription(\"Number of profile samples that could not be pushed into the pipeline. [Alpha]\"),\n\t\tmetric.WithUnit(\"{sample}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ReceiverRefusedSpans, err = builder.meter.Int64Counter(\n\t\t\"otelcol_receiver_refused_spans\",\n\t\tmetric.WithDescription(\"Number of spans that could not be pushed into the pipeline. [Alpha]\"),\n\t\tmetric.WithUnit(\"{span}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ReceiverRequests, err = builder.meter.Int64Counter(\n\t\t\"otelcol_receiver_requests\",\n\t\tmetric.WithDescription(\"The number of requests performed. [Alpha]\"),\n\t\tmetric.WithUnit(\"{request}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\treturn &builder, errs\n}\n"
  },
  {
    "path": "receiver/receiverhelper/internal/metadata/generated_telemetry_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/metric\"\n\tembeddedmetric \"go.opentelemetry.io/otel/metric/embedded\"\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\t\"go.opentelemetry.io/otel/trace\"\n\tembeddedtrace \"go.opentelemetry.io/otel/trace/embedded\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\ntype mockMeter struct {\n\tnoopmetric.Meter\n\tname string\n}\ntype mockMeterProvider struct {\n\tembeddedmetric.MeterProvider\n}\n\nfunc (m mockMeterProvider) Meter(name string, opts ...metric.MeterOption) metric.Meter {\n\treturn mockMeter{name: name}\n}\n\ntype mockTracer struct {\n\tnooptrace.Tracer\n\tname string\n}\n\ntype mockTracerProvider struct {\n\tembeddedtrace.TracerProvider\n}\n\nfunc (m mockTracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer {\n\treturn mockTracer{name: name}\n}\n\nfunc TestProviders(t *testing.T) {\n\tset := component.TelemetrySettings{\n\t\tMeterProvider:  mockMeterProvider{},\n\t\tTracerProvider: mockTracerProvider{},\n\t}\n\n\tmeter := Meter(set)\n\tif m, ok := meter.(mockMeter); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/receiver/receiverhelper\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockMeter\")\n\t}\n\n\ttracer := Tracer(set)\n\tif m, ok := tracer.(mockTracer); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/receiver/receiverhelper\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockTracer\")\n\t}\n}\n\nfunc TestNewTelemetryBuilder(t *testing.T) {\n\tset := componenttest.NewNopTelemetrySettings()\n\tapplied := false\n\t_, err := NewTelemetryBuilder(set, telemetryBuilderOptionFunc(func(b *TelemetryBuilder) {\n\t\tapplied = true\n\t}))\n\trequire.NoError(t, err)\n\trequire.True(t, applied)\n}\n"
  },
  {
    "path": "receiver/receiverhelper/internal/metadatatest/generated_telemetrytest.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\nfunc AssertEqualReceiverAcceptedLogRecords(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_receiver_accepted_log_records\",\n\t\tDescription: \"Number of log records successfully pushed into the pipeline. [Alpha]\",\n\t\tUnit:        \"{record}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_receiver_accepted_log_records\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualReceiverAcceptedMetricPoints(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_receiver_accepted_metric_points\",\n\t\tDescription: \"Number of metric points successfully pushed into the pipeline. [Alpha]\",\n\t\tUnit:        \"{datapoint}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_receiver_accepted_metric_points\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualReceiverAcceptedProfileSamples(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_receiver_accepted_profile_samples\",\n\t\tDescription: \"Number of profile samples successfully pushed into the pipeline. [Alpha]\",\n\t\tUnit:        \"{sample}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_receiver_accepted_profile_samples\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualReceiverAcceptedSpans(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_receiver_accepted_spans\",\n\t\tDescription: \"Number of spans successfully pushed into the pipeline. [Alpha]\",\n\t\tUnit:        \"{span}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_receiver_accepted_spans\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualReceiverFailedLogRecords(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_receiver_failed_log_records\",\n\t\tDescription: \"The number of log records that failed to be processed by the receiver due to internal errors. [Alpha]\",\n\t\tUnit:        \"{record}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_receiver_failed_log_records\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualReceiverFailedMetricPoints(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_receiver_failed_metric_points\",\n\t\tDescription: \"The number of metric points that failed to be processed by the receiver due to internal errors. [Alpha]\",\n\t\tUnit:        \"{datapoint}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_receiver_failed_metric_points\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualReceiverFailedProfileSamples(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_receiver_failed_profile_samples\",\n\t\tDescription: \"The number of profile samples that failed to be processed by the receiver due to internal errors. [Alpha]\",\n\t\tUnit:        \"{sample}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_receiver_failed_profile_samples\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualReceiverFailedSpans(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_receiver_failed_spans\",\n\t\tDescription: \"The number of spans that failed to be processed by the receiver due to internal errors. [Alpha]\",\n\t\tUnit:        \"{span}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_receiver_failed_spans\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualReceiverRefusedLogRecords(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_receiver_refused_log_records\",\n\t\tDescription: \"Number of log records that could not be pushed into the pipeline. [Alpha]\",\n\t\tUnit:        \"{record}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_receiver_refused_log_records\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualReceiverRefusedMetricPoints(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_receiver_refused_metric_points\",\n\t\tDescription: \"Number of metric points that could not be pushed into the pipeline. [Alpha]\",\n\t\tUnit:        \"{datapoint}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_receiver_refused_metric_points\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualReceiverRefusedProfileSamples(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_receiver_refused_profile_samples\",\n\t\tDescription: \"Number of profile samples that could not be pushed into the pipeline. [Alpha]\",\n\t\tUnit:        \"{sample}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_receiver_refused_profile_samples\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualReceiverRefusedSpans(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_receiver_refused_spans\",\n\t\tDescription: \"Number of spans that could not be pushed into the pipeline. [Alpha]\",\n\t\tUnit:        \"{span}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_receiver_refused_spans\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualReceiverRequests(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_receiver_requests\",\n\t\tDescription: \"The number of requests performed. [Alpha]\",\n\t\tUnit:        \"{request}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_receiver_requests\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n"
  },
  {
    "path": "receiver/receiverhelper/internal/metadatatest/generated_telemetrytest_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/receiver/receiverhelper/internal/metadata\"\n)\n\nfunc TestSetupTelemetry(t *testing.T) {\n\ttestTel := componenttest.NewTelemetry()\n\ttb, err := metadata.NewTelemetryBuilder(testTel.NewTelemetrySettings())\n\trequire.NoError(t, err)\n\tdefer tb.Shutdown()\n\ttb.ReceiverAcceptedLogRecords.Add(context.Background(), 1)\n\ttb.ReceiverAcceptedMetricPoints.Add(context.Background(), 1)\n\ttb.ReceiverAcceptedProfileSamples.Add(context.Background(), 1)\n\ttb.ReceiverAcceptedSpans.Add(context.Background(), 1)\n\ttb.ReceiverFailedLogRecords.Add(context.Background(), 1)\n\ttb.ReceiverFailedMetricPoints.Add(context.Background(), 1)\n\ttb.ReceiverFailedProfileSamples.Add(context.Background(), 1)\n\ttb.ReceiverFailedSpans.Add(context.Background(), 1)\n\ttb.ReceiverRefusedLogRecords.Add(context.Background(), 1)\n\ttb.ReceiverRefusedMetricPoints.Add(context.Background(), 1)\n\ttb.ReceiverRefusedProfileSamples.Add(context.Background(), 1)\n\ttb.ReceiverRefusedSpans.Add(context.Background(), 1)\n\ttb.ReceiverRequests.Add(context.Background(), 1)\n\tAssertEqualReceiverAcceptedLogRecords(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualReceiverAcceptedMetricPoints(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualReceiverAcceptedProfileSamples(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualReceiverAcceptedSpans(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualReceiverFailedLogRecords(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualReceiverFailedMetricPoints(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualReceiverFailedProfileSamples(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualReceiverFailedSpans(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualReceiverRefusedLogRecords(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualReceiverRefusedMetricPoints(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualReceiverRefusedProfileSamples(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualReceiverRefusedSpans(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualReceiverRequests(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\n\trequire.NoError(t, testTel.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "receiver/receiverhelper/internal/obsmetrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage internal // import \"go.opentelemetry.io/collector/receiver/receiverhelper/internal\"\n\nconst (\n\t// SpanNameSep is duplicate between receiver and exporter.\n\tSpanNameSep = \"/\"\n\n\t// ReceiverKey used to identify receivers in metrics and traces.\n\tReceiverKey = \"receiver\"\n\t// TransportKey used to identify the transport used to received the data.\n\tTransportKey = \"transport\"\n\t// FormatKey used to identify the format of the data received.\n\tFormatKey = \"format\"\n\n\t// AcceptedSpansKey used to identify spans accepted by the Collector.\n\tAcceptedSpansKey = \"accepted_spans\"\n\t// RefusedSpansKey used to identify spans refused (ie.: not ingested) by the Collector.\n\tRefusedSpansKey = \"refused_spans\"\n\t// FailedSpansKey used to identify spans failed to be processed by the Collector.\n\tFailedSpansKey = \"failed_spans\"\n\n\t// AcceptedMetricPointsKey used to identify metric points accepted by the Collector.\n\tAcceptedMetricPointsKey = \"accepted_metric_points\"\n\t// RefusedMetricPointsKey used to identify metric points refused (ie.: not ingested) by the\n\t// Collector.\n\tRefusedMetricPointsKey = \"refused_metric_points\"\n\t// FailedMetricPointKey used to identify metric points failed to be processed by the Collector.\n\tFailedMetricPointsKey = \"failed_metric_points\"\n\n\t// AcceptedLogRecordsKey used to identify log records accepted by the Collector.\n\tAcceptedLogRecordsKey = \"accepted_log_records\"\n\t// RefusedLogRecordsKey used to identify log records refused (ie.: not ingested) by the\n\t// Collector.\n\tRefusedLogRecordsKey = \"refused_log_records\"\n\n\t// FailedLogRecordsKey used to identify log records failed to be processed by the Collector.\n\tFailedLogRecordsKey = \"failed_log_records\"\n\n\t// AcceptedProfileSamplesKey used to identify profile samples accepted by the Collector.\n\tAcceptedProfileSamplesKey = \"accepted_profile_samples\"\n\t// RefusedProfileSamplesKey used to identify profile samples refused (ie.: not ingested) by the Collector.\n\tRefusedProfileSamplesKey = \"refused_profile_samples\"\n\t// FailedProfileSamplesKey used to identify profile samples failed to be processed by the Collector.\n\tFailedProfileSamplesKey = \"failed_profile_samples\"\n\n\tReceiveTraceDataOperationSuffix = SpanNameSep + \"TraceDataReceived\"\n\tReceiverMetricsOperationSuffix  = SpanNameSep + \"MetricsReceived\"\n\tReceiverLogsOperationSuffix     = SpanNameSep + \"LogsReceived\"\n\tReceiverProfilesOperationSuffix = SpanNameSep + \"ProfilesReceived\"\n)\n"
  },
  {
    "path": "receiver/receiverhelper/metadata.yaml",
    "content": "type: receiverhelper\ngithub_project: open-telemetry/opentelemetry-collector\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  stability:\n    beta: [metrics, traces, logs]\ntelemetry:\n  metrics:\n    receiver_accepted_log_records:\n      enabled: true\n      stability: alpha\n      description: Number of log records successfully pushed into the pipeline.\n      unit: \"{record}\"\n      sum:\n        value_type: int\n        monotonic: true\n    receiver_accepted_metric_points:\n      stability: alpha\n      enabled: true\n      description: Number of metric points successfully pushed into the pipeline.\n      unit: \"{datapoint}\"\n      sum:\n        value_type: int\n        monotonic: true\n    receiver_accepted_profile_samples:\n      enabled: true\n      stability: alpha\n      description: Number of profile samples successfully pushed into the pipeline.\n      unit: \"{sample}\"\n      sum:\n        value_type: int\n        monotonic: true\n    receiver_accepted_spans:\n      enabled: true\n      stability: alpha\n      description: Number of spans successfully pushed into the pipeline.\n      unit: \"{span}\"\n      sum:\n        value_type: int\n        monotonic: true\n    receiver_failed_log_records:\n      enabled: true\n      stability: alpha\n      description: The number of log records that failed to be processed by the receiver due to internal errors.\n      unit: \"{record}\"\n      sum:\n        value_type: int\n        monotonic: true\n    receiver_failed_metric_points:\n      enabled: true\n      stability: alpha\n      description: The number of metric points that failed to be processed by the receiver due to internal errors.\n      unit: \"{datapoint}\"\n      sum:\n        value_type: int\n        monotonic: true\n    receiver_failed_profile_samples:\n      enabled: true\n      stability: alpha\n      description: The number of profile samples that failed to be processed by the receiver due to internal errors.\n      unit: \"{sample}\"\n      sum:\n        value_type: int\n        monotonic: true\n    receiver_failed_spans:\n      enabled: true\n      stability: alpha\n      description: The number of spans that failed to be processed by the receiver due to internal errors.\n      unit: \"{span}\"\n      sum:\n        value_type: int\n        monotonic: true\n    receiver_refused_log_records:\n      enabled: true\n      stability: alpha\n      description: Number of log records that could not be pushed into the pipeline.\n      unit: \"{record}\"\n      sum:\n        value_type: int\n        monotonic: true\n    receiver_refused_metric_points:\n      enabled: true\n      stability: alpha\n      description: Number of metric points that could not be pushed into the pipeline.\n      unit: \"{datapoint}\"\n      sum:\n        value_type: int\n        monotonic: true\n    receiver_refused_profile_samples:\n      enabled: true\n      stability: alpha\n      description: Number of profile samples that could not be pushed into the pipeline.\n      unit: \"{sample}\"\n      sum:\n        value_type: int\n        monotonic: true\n    receiver_refused_spans:\n      enabled: true\n      stability: alpha\n      description: Number of spans that could not be pushed into the pipeline.\n      unit: \"{span}\"\n      sum:\n        value_type: int\n        monotonic: true\n    receiver_requests:\n      enabled: true\n      stability: alpha\n      description: The number of requests performed.\n      unit: \"{request}\"\n      sum:\n        value_type: int\n        monotonic: true\n      attributes:\n        - outcome\nattributes:\n  outcome:\n    description: The outcome of receiver requests\n    type: string\n    enum:\n      - success\n      - refused\n      - failure\n\nfeature_gates:\n  - id: receiverhelper.newReceiverMetrics\n    description: 'Controls whether receivers emit new metrics and span attributes to distinguish downstream errors from internal errors. This is a breaking change for the semantics of the otelcol_receiver_refused_metric_points,  otelcol_receiver_refused_log_records and otelcol_receiver_refused_spans.'\n    stage: alpha\n    from_version: 'v0.138.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/pull/12802'\n"
  },
  {
    "path": "receiver/receiverhelper/obsreport.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\npackage receiverhelper // import \"go.opentelemetry.io/collector/receiver/receiverhelper\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/codes\"\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receiverhelper/internal\"\n\t\"go.opentelemetry.io/collector/receiver/receiverhelper/internal/metadata\"\n)\n\n// ObsReport is a helper to add observability to a receiver.\ntype ObsReport struct {\n\tspanNamePrefix string\n\ttransport      string\n\tlongLivedCtx   bool\n\ttracer         trace.Tracer\n\n\totelAttrs        metric.MeasurementOption\n\ttelemetryBuilder *metadata.TelemetryBuilder\n}\n\n// ObsReportSettings are settings for creating an ObsReport.\ntype ObsReportSettings struct {\n\tReceiverID component.ID\n\tTransport  string\n\t// LongLivedCtx when true indicates that the context passed in the call\n\t// outlives the individual receive operation.\n\t// Typically the long lived context is associated to a connection,\n\t// eg.: a gRPC stream, for which many batches of data are received in individual\n\t// operations without a corresponding new context per operation.\n\tLongLivedCtx           bool\n\tReceiverCreateSettings receiver.Settings\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// NewObsReport creates a new ObsReport.\nfunc NewObsReport(cfg ObsReportSettings) (*ObsReport, error) {\n\treturn newReceiver(cfg)\n}\n\nfunc newReceiver(cfg ObsReportSettings) (*ObsReport, error) {\n\ttelemetryBuilder, err := metadata.NewTelemetryBuilder(cfg.ReceiverCreateSettings.TelemetrySettings)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn &ObsReport{\n\t\tspanNamePrefix: internal.ReceiverKey + internal.SpanNameSep + cfg.ReceiverID.String(),\n\t\ttransport:      cfg.Transport,\n\t\tlongLivedCtx:   cfg.LongLivedCtx,\n\t\ttracer:         cfg.ReceiverCreateSettings.TracerProvider.Tracer(cfg.ReceiverID.String()),\n\n\t\totelAttrs: metric.WithAttributeSet(attribute.NewSet(\n\t\t\tattribute.String(internal.ReceiverKey, cfg.ReceiverID.String()),\n\t\t\tattribute.String(internal.TransportKey, cfg.Transport),\n\t\t)),\n\t\ttelemetryBuilder: telemetryBuilder,\n\t}, nil\n}\n\n// StartTracesOp is called when a request is received from a client.\n// The returned context should be used in other calls to the obsreport functions\n// dealing with the same receive operation.\nfunc (rec *ObsReport) StartTracesOp(operationCtx context.Context) context.Context {\n\treturn rec.startOp(operationCtx, internal.ReceiveTraceDataOperationSuffix)\n}\n\n// EndTracesOp completes the receive operation that was started with\n// StartTracesOp.\nfunc (rec *ObsReport) EndTracesOp(\n\treceiverCtx context.Context,\n\tformat string,\n\tnumReceivedSpans int,\n\terr error,\n) {\n\trec.endOp(receiverCtx, format, numReceivedSpans, err, pipeline.SignalTraces)\n}\n\n// StartLogsOp is called when a request is received from a client.\n// The returned context should be used in other calls to the obsreport functions\n// dealing with the same receive operation.\nfunc (rec *ObsReport) StartLogsOp(operationCtx context.Context) context.Context {\n\treturn rec.startOp(operationCtx, internal.ReceiverLogsOperationSuffix)\n}\n\n// EndLogsOp completes the receive operation that was started with\n// StartLogsOp.\nfunc (rec *ObsReport) EndLogsOp(\n\treceiverCtx context.Context,\n\tformat string,\n\tnumReceivedLogRecords int,\n\terr error,\n) {\n\trec.endOp(receiverCtx, format, numReceivedLogRecords, err, pipeline.SignalLogs)\n}\n\n// StartMetricsOp is called when a request is received from a client.\n// The returned context should be used in other calls to the obsreport functions\n// dealing with the same receive operation.\nfunc (rec *ObsReport) StartMetricsOp(operationCtx context.Context) context.Context {\n\treturn rec.startOp(operationCtx, internal.ReceiverMetricsOperationSuffix)\n}\n\n// EndMetricsOp completes the receive operation that was started with\n// StartMetricsOp.\nfunc (rec *ObsReport) EndMetricsOp(\n\treceiverCtx context.Context,\n\tformat string,\n\tnumReceivedPoints int,\n\terr error,\n) {\n\trec.endOp(receiverCtx, format, numReceivedPoints, err, pipeline.SignalMetrics)\n}\n\n// StartProfilesOp is called when a request is received from a client.\n// The returned context should be used in other calls to the obsreport functions\n// dealing with the same receive operation.\nfunc (rec *ObsReport) StartProfilesOp(operationCtx context.Context) context.Context {\n\treturn rec.startOp(operationCtx, internal.ReceiverProfilesOperationSuffix)\n}\n\n// EndProfilesOp completes the receive operation that was started with\n// StartProfilesOp.\nfunc (rec *ObsReport) EndProfilesOp(\n\treceiverCtx context.Context,\n\tformat string,\n\tnumReceivedProfileSamples int,\n\terr error,\n) {\n\trec.endOp(receiverCtx, format, numReceivedProfileSamples, err, xpipeline.SignalProfiles)\n}\n\n// startOp creates the span used to trace the operation. Returning\n// the updated context with the created span.\nfunc (rec *ObsReport) startOp(receiverCtx context.Context, operationSuffix string) context.Context {\n\tvar ctx context.Context\n\tvar span trace.Span\n\tspanName := rec.spanNamePrefix + operationSuffix\n\tif !rec.longLivedCtx {\n\t\tctx, span = rec.tracer.Start(receiverCtx, spanName)\n\t} else {\n\t\t// Since the receiverCtx is long lived do not use it to start the span.\n\t\t// This way this trace ends when the EndTracesOp is called.\n\t\t// Here is safe to ignore the returned context since it is not used below.\n\t\t_, span = rec.tracer.Start(context.Background(), spanName, trace.WithLinks(trace.Link{\n\t\t\tSpanContext: trace.SpanContextFromContext(receiverCtx),\n\t\t}))\n\n\t\tctx = trace.ContextWithSpan(receiverCtx, span)\n\t}\n\n\tif rec.transport != \"\" {\n\t\tspan.SetAttributes(attribute.String(internal.TransportKey, rec.transport))\n\t}\n\treturn ctx\n}\n\n// endOp records the observability signals at the end of an operation.\nfunc (rec *ObsReport) endOp(\n\treceiverCtx context.Context,\n\tformat string,\n\tnumReceivedItems int,\n\terr error,\n\tsignal pipeline.Signal,\n) {\n\tnumAccepted := numReceivedItems\n\tnumRefused := 0\n\tnumFailedErrors := 0\n\tif err != nil {\n\t\tnumAccepted = 0\n\t\t// If gate is enabled, we distinguish between refused and failed.\n\t\tif metadata.ReceiverhelperNewReceiverMetricsFeatureGate.IsEnabled() {\n\t\t\tif consumererror.IsDownstream(err) {\n\t\t\t\tnumRefused = numReceivedItems\n\t\t\t} else {\n\t\t\t\tnumFailedErrors = numReceivedItems\n\t\t\t}\n\t\t} else {\n\t\t\t// When the gate is disabled, all errors are considered \"refused\".\n\t\t\tnumRefused = numReceivedItems\n\t\t}\n\t}\n\n\tspan := trace.SpanFromContext(receiverCtx)\n\n\trec.recordMetrics(receiverCtx, signal, numAccepted, numRefused, numFailedErrors)\n\n\t// The new otelcol_receiver_requests metric is only emitted when the feature gate is enabled.\n\tif metadata.ReceiverhelperNewReceiverMetricsFeatureGate.IsEnabled() {\n\t\tvar outcome string\n\t\tswitch {\n\t\tcase err == nil:\n\t\t\toutcome = \"success\"\n\t\tcase consumererror.IsDownstream(err):\n\t\t\toutcome = \"refused\"\n\t\tdefault:\n\t\t\toutcome = \"failure\"\n\t\t}\n\t\trec.telemetryBuilder.ReceiverRequests.Add(receiverCtx, 1, rec.otelAttrs, metric.WithAttributeSet(attribute.NewSet(attribute.String(\"outcome\", outcome))))\n\t}\n\n\t// end span according to errors\n\tif span.IsRecording() {\n\t\tvar acceptedItemsKey, refusedItemsKey, failedItemsKey string\n\t\tswitch signal {\n\t\tcase pipeline.SignalTraces:\n\t\t\tacceptedItemsKey = internal.AcceptedSpansKey\n\t\t\trefusedItemsKey = internal.RefusedSpansKey\n\t\t\tfailedItemsKey = internal.FailedSpansKey\n\t\tcase pipeline.SignalMetrics:\n\t\t\tacceptedItemsKey = internal.AcceptedMetricPointsKey\n\t\t\trefusedItemsKey = internal.RefusedMetricPointsKey\n\t\t\tfailedItemsKey = internal.FailedMetricPointsKey\n\t\tcase pipeline.SignalLogs:\n\t\t\tacceptedItemsKey = internal.AcceptedLogRecordsKey\n\t\t\trefusedItemsKey = internal.RefusedLogRecordsKey\n\t\t\tfailedItemsKey = internal.FailedLogRecordsKey\n\t\tcase xpipeline.SignalProfiles:\n\t\t\tacceptedItemsKey = internal.AcceptedProfileSamplesKey\n\t\t\trefusedItemsKey = internal.RefusedProfileSamplesKey\n\t\t\tfailedItemsKey = internal.FailedProfileSamplesKey\n\t\t}\n\n\t\tspan.SetAttributes(\n\t\t\tattribute.String(internal.FormatKey, format),\n\t\t\tattribute.Int64(acceptedItemsKey, int64(numAccepted)),\n\t\t\tattribute.Int64(refusedItemsKey, int64(numRefused)),\n\t\t\tattribute.Int64(failedItemsKey, int64(numFailedErrors)),\n\t\t)\n\t\tif err != nil {\n\t\t\tspan.SetStatus(codes.Error, err.Error())\n\t\t}\n\t}\n\tspan.End()\n}\n\nfunc (rec *ObsReport) recordMetrics(receiverCtx context.Context, signal pipeline.Signal, numAccepted, numRefused, numFailedErrors int) {\n\tvar acceptedMeasure, refusedMeasure, failedMeasure metric.Int64Counter\n\tswitch signal {\n\tcase pipeline.SignalTraces:\n\t\tacceptedMeasure = rec.telemetryBuilder.ReceiverAcceptedSpans\n\t\trefusedMeasure = rec.telemetryBuilder.ReceiverRefusedSpans\n\t\tfailedMeasure = rec.telemetryBuilder.ReceiverFailedSpans\n\tcase pipeline.SignalMetrics:\n\t\tacceptedMeasure = rec.telemetryBuilder.ReceiverAcceptedMetricPoints\n\t\trefusedMeasure = rec.telemetryBuilder.ReceiverRefusedMetricPoints\n\t\tfailedMeasure = rec.telemetryBuilder.ReceiverFailedMetricPoints\n\tcase pipeline.SignalLogs:\n\t\tacceptedMeasure = rec.telemetryBuilder.ReceiverAcceptedLogRecords\n\t\trefusedMeasure = rec.telemetryBuilder.ReceiverRefusedLogRecords\n\t\tfailedMeasure = rec.telemetryBuilder.ReceiverFailedLogRecords\n\tcase xpipeline.SignalProfiles:\n\t\tacceptedMeasure = rec.telemetryBuilder.ReceiverAcceptedProfileSamples\n\t\trefusedMeasure = rec.telemetryBuilder.ReceiverRefusedProfileSamples\n\t\tfailedMeasure = rec.telemetryBuilder.ReceiverFailedProfileSamples\n\t}\n\n\tacceptedMeasure.Add(receiverCtx, int64(numAccepted), rec.otelAttrs)\n\trefusedMeasure.Add(receiverCtx, int64(numRefused), rec.otelAttrs)\n\tfailedMeasure.Add(receiverCtx, int64(numFailedErrors), rec.otelAttrs)\n}\n"
  },
  {
    "path": "receiver/receiverhelper/obsreport_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage receiverhelper\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/codes\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receiverhelper/internal\"\n\t\"go.opentelemetry.io/collector/receiver/receiverhelper/internal/metadata\"\n\t\"go.opentelemetry.io/collector/receiver/receiverhelper/internal/metadatatest\"\n)\n\nconst (\n\ttransport = \"fakeTransport\"\n\tformat    = \"fakeFormat\"\n)\n\nvar (\n\treceiverID = component.MustNewID(\"fakeReceiver\")\n\n\terrFake = errors.New(\"errFake\")\n)\n\ntype testParams struct {\n\titems int\n\terr   error\n}\n\nfunc TestReceiveTraceDataOp(t *testing.T) {\n\toriginalState := metadata.ReceiverhelperNewReceiverMetricsFeatureGate.IsEnabled()\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ReceiverhelperNewReceiverMetricsFeatureGate.ID(), originalState))\n\t})\n\n\tfor _, tc := range []struct {\n\t\tname    string\n\t\tenabled bool\n\t}{{\"gate_enabled\", true}, {\"gate_disabled\", false}} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ReceiverhelperNewReceiverMetricsFeatureGate.ID(), tc.enabled))\n\t\t\ttestTelemetry(t, func(t *testing.T, tt *componenttest.Telemetry) {\n\t\t\t\tparentCtx, parentSpan := tt.NewTelemetrySettings().TracerProvider.Tracer(\"test\").Start(context.Background(), t.Name())\n\t\t\t\tdefer parentSpan.End()\n\n\t\t\t\tparams := []testParams{\n\t\t\t\t\t{items: 13, err: consumererror.NewDownstream(errFake)},\n\t\t\t\t\t{items: 42, err: nil},\n\t\t\t\t\t{items: 7, err: errors.New(\"non-downstream error\")}, // Regular error to test numFailedErrors path\n\t\t\t\t}\n\t\t\t\tfor i, param := range params {\n\t\t\t\t\trec, err := newReceiver(ObsReportSettings{\n\t\t\t\t\t\tReceiverID:             receiverID,\n\t\t\t\t\t\tTransport:              transport,\n\t\t\t\t\t\tReceiverCreateSettings: receiver.Settings{ID: receiverID, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t\t\t\t\t})\n\t\t\t\t\trequire.NoError(t, err)\n\t\t\t\t\tctx := rec.StartTracesOp(parentCtx)\n\t\t\t\t\tassert.NotNil(t, ctx)\n\t\t\t\t\trec.EndTracesOp(ctx, format, params[i].items, param.err)\n\t\t\t\t}\n\n\t\t\t\tspans := tt.SpanRecorder.Ended()\n\t\t\t\trequire.Len(t, spans, len(params))\n\n\t\t\t\tvar acceptedSpans, refusedSpans, failedSpans int\n\t\t\t\tfor i, span := range spans {\n\t\t\t\t\tassert.Equal(t, \"receiver/\"+receiverID.String()+\"/TraceDataReceived\", span.Name())\n\t\t\t\t\terr := params[i].err\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tacceptedSpans += params[i].items\n\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.AcceptedSpansKey, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.RefusedSpansKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedSpansKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\tassert.Equal(t, codes.Unset, span.Status().Code)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tisDownstream := consumererror.IsDownstream(err)\n\t\t\t\t\t\tif !tc.enabled || (tc.enabled && isDownstream) {\n\t\t\t\t\t\t\trefusedSpans += params[i].items\n\t\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.RefusedSpansKey, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedSpansKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfailedSpans += params[i].items\n\t\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.RefusedSpansKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedSpansKey, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\t\t\t\t}\n\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.AcceptedSpansKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\tassert.Equal(t, codes.Error, span.Status().Code)\n\t\t\t\t\t\tassert.Equal(t, err.Error(), span.Status().Description)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tmetadatatest.AssertEqualReceiverAcceptedSpans(t, tt,\n\t\t\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\t\t\t\tValue: int64(acceptedSpans),\n\t\t\t\t\t\t},\n\t\t\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t\t\t\tmetadatatest.AssertEqualReceiverRefusedSpans(t, tt,\n\t\t\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\t\t\t\tValue: int64(refusedSpans),\n\t\t\t\t\t\t},\n\t\t\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t\t\t\tmetadatatest.AssertEqualReceiverFailedSpans(t, tt,\n\t\t\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\t\t\t\tValue: int64(failedSpans),\n\t\t\t\t\t\t},\n\t\t\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\t\t\t\t// Assert otelcol_receiver_requests metric with outcome attribute\n\t\t\t\tif tc.enabled {\n\t\t\t\t\toutcomes := make(map[string]int64)\n\t\t\t\t\tfor _, param := range params {\n\t\t\t\t\t\tvar outcome string\n\t\t\t\t\t\tswitch {\n\t\t\t\t\t\tcase param.err == nil:\n\t\t\t\t\t\t\toutcome = \"success\"\n\t\t\t\t\t\tcase consumererror.IsDownstream(param.err):\n\t\t\t\t\t\t\toutcome = \"refused\"\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\toutcome = \"failure\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\toutcomes[outcome]++\n\t\t\t\t\t}\n\t\t\t\t\tvar expectedRequests []metricdata.DataPoint[int64]\n\t\t\t\t\tfor outcome, count := range outcomes {\n\t\t\t\t\t\texpectedRequests = append(expectedRequests, metricdata.DataPoint[int64]{\n\t\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\t\t\t\tattribute.String(internal.TransportKey, transport),\n\t\t\t\t\t\t\t\tattribute.String(\"outcome\", outcome)),\n\t\t\t\t\t\t\tValue: count,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tmetadatatest.AssertEqualReceiverRequests(t, tt, expectedRequests, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}\n}\n\nfunc TestReceiveLogsOp(t *testing.T) {\n\toriginalState := metadata.ReceiverhelperNewReceiverMetricsFeatureGate.IsEnabled()\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ReceiverhelperNewReceiverMetricsFeatureGate.ID(), originalState))\n\t})\n\n\tfor _, tc := range []struct {\n\t\tname    string\n\t\tenabled bool\n\t}{{\"gate_enabled\", true}, {\"gate_disabled\", false}} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ReceiverhelperNewReceiverMetricsFeatureGate.ID(), tc.enabled))\n\t\t\ttestTelemetry(t, func(t *testing.T, tt *componenttest.Telemetry) {\n\t\t\t\tparentCtx, parentSpan := tt.NewTelemetrySettings().TracerProvider.Tracer(\"test\").Start(context.Background(), t.Name())\n\t\t\t\tdefer parentSpan.End()\n\n\t\t\t\tparams := []testParams{\n\t\t\t\t\t{items: 13, err: consumererror.NewDownstream(errFake)},\n\t\t\t\t\t{items: 42, err: nil},\n\t\t\t\t\t{items: 7, err: errors.New(\"non-downstream error\")},\n\t\t\t\t}\n\t\t\t\tfor i, param := range params {\n\t\t\t\t\trec, err := newReceiver(ObsReportSettings{\n\t\t\t\t\t\tReceiverID:             receiverID,\n\t\t\t\t\t\tTransport:              transport,\n\t\t\t\t\t\tReceiverCreateSettings: receiver.Settings{ID: receiverID, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t\t\t\t\t})\n\t\t\t\t\trequire.NoError(t, err)\n\t\t\t\t\tctx := rec.StartLogsOp(parentCtx)\n\t\t\t\t\tassert.NotNil(t, ctx)\n\t\t\t\t\trec.EndLogsOp(ctx, format, params[i].items, param.err)\n\t\t\t\t}\n\n\t\t\t\tspans := tt.SpanRecorder.Ended()\n\t\t\t\trequire.Len(t, spans, len(params))\n\n\t\t\t\tvar acceptedLogRecords, refusedLogRecords, failedLogRecords int\n\t\t\t\tfor i, span := range spans {\n\t\t\t\t\tassert.Equal(t, \"receiver/\"+receiverID.String()+\"/LogsReceived\", span.Name())\n\t\t\t\t\terr := params[i].err\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tacceptedLogRecords += params[i].items\n\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.AcceptedLogRecordsKey, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.RefusedLogRecordsKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedLogRecordsKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\tassert.Equal(t, codes.Unset, span.Status().Code)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tisDownstream := consumererror.IsDownstream(err)\n\t\t\t\t\t\tif !tc.enabled || (tc.enabled && isDownstream) {\n\t\t\t\t\t\t\trefusedLogRecords += params[i].items\n\t\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.RefusedLogRecordsKey, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedLogRecordsKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfailedLogRecords += params[i].items\n\t\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.RefusedLogRecordsKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedLogRecordsKey, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\t\t\t\t}\n\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.AcceptedLogRecordsKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\tassert.Equal(t, codes.Error, span.Status().Code)\n\t\t\t\t\t\tassert.Equal(t, err.Error(), span.Status().Description)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmetadatatest.AssertEqualReceiverAcceptedLogRecords(t, tt,\n\t\t\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\t\t\t\tValue: int64(acceptedLogRecords),\n\t\t\t\t\t\t},\n\t\t\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t\t\t\tmetadatatest.AssertEqualReceiverRefusedLogRecords(t, tt,\n\t\t\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\t\t\t\tValue: int64(refusedLogRecords),\n\t\t\t\t\t\t},\n\t\t\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t\t\t\tmetadatatest.AssertEqualReceiverFailedLogRecords(t, tt,\n\t\t\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\t\t\t\tValue: int64(failedLogRecords),\n\t\t\t\t\t\t},\n\t\t\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\t\t\t\t// Assert otelcol_receiver_requests metric with outcome attribute\n\t\t\t\tif tc.enabled {\n\t\t\t\t\toutcomes := make(map[string]int64)\n\t\t\t\t\tfor _, param := range params {\n\t\t\t\t\t\tvar outcome string\n\t\t\t\t\t\tswitch {\n\t\t\t\t\t\tcase param.err == nil:\n\t\t\t\t\t\t\toutcome = \"success\"\n\t\t\t\t\t\tcase consumererror.IsDownstream(param.err):\n\t\t\t\t\t\t\toutcome = \"refused\"\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\toutcome = \"failure\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\toutcomes[outcome]++\n\t\t\t\t\t}\n\t\t\t\t\tvar expectedRequests []metricdata.DataPoint[int64]\n\t\t\t\t\tfor outcome, count := range outcomes {\n\t\t\t\t\t\texpectedRequests = append(expectedRequests, metricdata.DataPoint[int64]{\n\t\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\t\t\t\tattribute.String(internal.TransportKey, transport),\n\t\t\t\t\t\t\t\tattribute.String(\"outcome\", outcome)),\n\t\t\t\t\t\t\tValue: count,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tmetadatatest.AssertEqualReceiverRequests(t, tt, expectedRequests, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}\n}\n\nfunc TestReceiveMetricsOp(t *testing.T) {\n\toriginalState := metadata.ReceiverhelperNewReceiverMetricsFeatureGate.IsEnabled()\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ReceiverhelperNewReceiverMetricsFeatureGate.ID(), originalState))\n\t})\n\n\tfor _, tc := range []struct {\n\t\tname    string\n\t\tenabled bool\n\t}{{\"gate_enabled\", true}, {\"gate_disabled\", false}} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ReceiverhelperNewReceiverMetricsFeatureGate.ID(), tc.enabled))\n\t\t\ttestTelemetry(t, func(t *testing.T, tt *componenttest.Telemetry) {\n\t\t\t\tparentCtx, parentSpan := tt.NewTelemetrySettings().TracerProvider.Tracer(\"test\").Start(context.Background(), t.Name())\n\t\t\t\tdefer parentSpan.End()\n\n\t\t\t\tparams := []testParams{\n\t\t\t\t\t{items: 13, err: consumererror.NewDownstream(errFake)},\n\t\t\t\t\t{items: 42, err: nil},\n\t\t\t\t\t{items: 7, err: errors.New(\"non-downstream error\")},\n\t\t\t\t}\n\t\t\t\tfor i, param := range params {\n\t\t\t\t\trec, err := newReceiver(ObsReportSettings{\n\t\t\t\t\t\tReceiverID:             receiverID,\n\t\t\t\t\t\tTransport:              transport,\n\t\t\t\t\t\tReceiverCreateSettings: receiver.Settings{ID: receiverID, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t\t\t\t\t})\n\t\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\t\tctx := rec.StartMetricsOp(parentCtx)\n\t\t\t\t\tassert.NotNil(t, ctx)\n\t\t\t\t\trec.EndMetricsOp(ctx, format, params[i].items, param.err)\n\t\t\t\t}\n\n\t\t\t\tspans := tt.SpanRecorder.Ended()\n\t\t\t\trequire.Len(t, spans, len(params))\n\n\t\t\t\tvar acceptedMetricPoints, refusedMetricPoints, failedMetricPoints int\n\t\t\t\tfor i, span := range spans {\n\t\t\t\t\tassert.Equal(t, \"receiver/\"+receiverID.String()+\"/MetricsReceived\", span.Name())\n\t\t\t\t\terr := params[i].err\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tacceptedMetricPoints += params[i].items\n\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.AcceptedMetricPointsKey, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.RefusedMetricPointsKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedMetricPointsKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\tassert.Equal(t, codes.Unset, span.Status().Code)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tisDownstream := consumererror.IsDownstream(err)\n\t\t\t\t\t\tif !tc.enabled || (tc.enabled && isDownstream) {\n\t\t\t\t\t\t\trefusedMetricPoints += params[i].items\n\t\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.RefusedMetricPointsKey, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedMetricPointsKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfailedMetricPoints += params[i].items\n\t\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.RefusedMetricPointsKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedMetricPointsKey, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\t\t\t\t}\n\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.AcceptedMetricPointsKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\tassert.Equal(t, codes.Error, span.Status().Code)\n\t\t\t\t\t\tassert.Equal(t, err.Error(), span.Status().Description)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tmetadatatest.AssertEqualReceiverAcceptedMetricPoints(t, tt,\n\t\t\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\t\t\t\tValue: int64(acceptedMetricPoints),\n\t\t\t\t\t\t},\n\t\t\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t\t\t\tmetadatatest.AssertEqualReceiverRefusedMetricPoints(t, tt,\n\t\t\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\t\t\t\tValue: int64(refusedMetricPoints),\n\t\t\t\t\t\t},\n\t\t\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t\t\t\tmetadatatest.AssertEqualReceiverFailedMetricPoints(t, tt,\n\t\t\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\t\t\t\tValue: int64(failedMetricPoints),\n\t\t\t\t\t\t},\n\t\t\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\t\t\t\t// Assert otelcol_receiver_requests metric with outcome attribute\n\t\t\t\tif tc.enabled {\n\t\t\t\t\toutcomes := make(map[string]int64)\n\t\t\t\t\tfor _, param := range params {\n\t\t\t\t\t\tvar outcome string\n\t\t\t\t\t\tswitch {\n\t\t\t\t\t\tcase param.err == nil:\n\t\t\t\t\t\t\toutcome = \"success\"\n\t\t\t\t\t\tcase consumererror.IsDownstream(param.err):\n\t\t\t\t\t\t\toutcome = \"refused\"\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\toutcome = \"failure\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\toutcomes[outcome]++\n\t\t\t\t\t}\n\t\t\t\t\tvar expectedRequests []metricdata.DataPoint[int64]\n\t\t\t\t\tfor outcome, count := range outcomes {\n\t\t\t\t\t\texpectedRequests = append(expectedRequests, metricdata.DataPoint[int64]{\n\t\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\t\t\t\tattribute.String(internal.TransportKey, transport),\n\t\t\t\t\t\t\t\tattribute.String(\"outcome\", outcome)),\n\t\t\t\t\t\t\tValue: count,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tmetadatatest.AssertEqualReceiverRequests(t, tt, expectedRequests, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}\n}\n\nfunc TestReceiveProfilesOp(t *testing.T) {\n\toriginalState := metadata.ReceiverhelperNewReceiverMetricsFeatureGate.IsEnabled()\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ReceiverhelperNewReceiverMetricsFeatureGate.ID(), originalState))\n\t})\n\n\tfor _, tc := range []struct {\n\t\tname    string\n\t\tenabled bool\n\t}{{\"gate_enabled\", true}, {\"gate_disabled\", false}} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ReceiverhelperNewReceiverMetricsFeatureGate.ID(), tc.enabled))\n\t\t\ttestTelemetry(t, func(t *testing.T, tt *componenttest.Telemetry) {\n\t\t\t\tparentCtx, parentSpan := tt.NewTelemetrySettings().TracerProvider.Tracer(\"test\").Start(context.Background(), t.Name())\n\t\t\t\tdefer parentSpan.End()\n\n\t\t\t\tparams := []testParams{\n\t\t\t\t\t{items: 13, err: consumererror.NewDownstream(errFake)},\n\t\t\t\t\t{items: 42, err: nil},\n\t\t\t\t\t{items: 7, err: errors.New(\"non-downstream error\")},\n\t\t\t\t}\n\t\t\t\tfor i, param := range params {\n\t\t\t\t\trec, err := newReceiver(ObsReportSettings{\n\t\t\t\t\t\tReceiverID:             receiverID,\n\t\t\t\t\t\tTransport:              transport,\n\t\t\t\t\t\tReceiverCreateSettings: receiver.Settings{ID: receiverID, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t\t\t\t\t})\n\t\t\t\t\trequire.NoError(t, err)\n\t\t\t\t\tctx := rec.StartProfilesOp(parentCtx)\n\t\t\t\t\tassert.NotNil(t, ctx)\n\t\t\t\t\trec.EndProfilesOp(ctx, format, params[i].items, param.err)\n\t\t\t\t}\n\n\t\t\t\tspans := tt.SpanRecorder.Ended()\n\t\t\t\trequire.Len(t, spans, len(params))\n\n\t\t\t\tvar acceptedSamples, refusedSamples, failedSamples int\n\t\t\t\tfor i, span := range spans {\n\t\t\t\t\tassert.Equal(t, \"receiver/\"+receiverID.String()+\"/ProfilesReceived\", span.Name())\n\t\t\t\t\terr := params[i].err\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tacceptedSamples += params[i].items\n\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.AcceptedProfileSamplesKey, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.RefusedProfileSamplesKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedProfileSamplesKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\tassert.Equal(t, codes.Unset, span.Status().Code)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tisDownstream := consumererror.IsDownstream(err)\n\t\t\t\t\t\tif !tc.enabled || (tc.enabled && isDownstream) {\n\t\t\t\t\t\t\trefusedSamples += params[i].items\n\t\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.RefusedProfileSamplesKey, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedProfileSamplesKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tfailedSamples += params[i].items\n\t\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.RefusedProfileSamplesKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedProfileSamplesKey, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\t\t\t\t}\n\t\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.AcceptedProfileSamplesKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t\tassert.Equal(t, codes.Error, span.Status().Code)\n\t\t\t\t\t\tassert.Equal(t, err.Error(), span.Status().Description)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tmetadatatest.AssertEqualReceiverAcceptedProfileSamples(t, tt,\n\t\t\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\t\t\t\tValue: int64(acceptedSamples),\n\t\t\t\t\t\t},\n\t\t\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t\t\t\tmetadatatest.AssertEqualReceiverRefusedProfileSamples(t, tt,\n\t\t\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\t\t\t\tValue: int64(refusedSamples),\n\t\t\t\t\t\t},\n\t\t\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t\t\t\tmetadatatest.AssertEqualReceiverFailedProfileSamples(t, tt,\n\t\t\t\t\t[]metricdata.DataPoint[int64]{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\t\t\t\tValue: int64(failedSamples),\n\t\t\t\t\t\t},\n\t\t\t\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\t\t\t\t// Assert otelcol_receiver_requests metric with outcome attribute\n\t\t\t\tif tc.enabled {\n\t\t\t\t\toutcomes := make(map[string]int64)\n\t\t\t\t\tfor _, param := range params {\n\t\t\t\t\t\tvar outcome string\n\t\t\t\t\t\tswitch {\n\t\t\t\t\t\tcase param.err == nil:\n\t\t\t\t\t\t\toutcome = \"success\"\n\t\t\t\t\t\tcase consumererror.IsDownstream(param.err):\n\t\t\t\t\t\t\toutcome = \"refused\"\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\toutcome = \"failure\"\n\t\t\t\t\t\t}\n\t\t\t\t\t\toutcomes[outcome]++\n\t\t\t\t\t}\n\t\t\t\t\tvar expectedRequests []metricdata.DataPoint[int64]\n\t\t\t\t\tfor outcome, count := range outcomes {\n\t\t\t\t\t\texpectedRequests = append(expectedRequests, metricdata.DataPoint[int64]{\n\t\t\t\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\t\t\t\tattribute.String(internal.TransportKey, transport),\n\t\t\t\t\t\t\t\tattribute.String(\"outcome\", outcome)),\n\t\t\t\t\t\t\tValue: count,\n\t\t\t\t\t\t})\n\t\t\t\t\t}\n\t\t\t\t\tmetadatatest.AssertEqualReceiverRequests(t, tt, expectedRequests, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\t\t\t\t}\n\t\t\t})\n\t\t})\n\t}\n}\n\nfunc TestReceiveWithLongLivedCtx(t *testing.T) {\n\toriginalState := metadata.ReceiverhelperNewReceiverMetricsFeatureGate.IsEnabled()\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ReceiverhelperNewReceiverMetricsFeatureGate.ID(), originalState))\n\t})\n\n\tfor _, tc := range []struct {\n\t\tname    string\n\t\tenabled bool\n\t}{{\"gate_enabled\", true}, {\"gate_disabled\", false}} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ReceiverhelperNewReceiverMetricsFeatureGate.ID(), tc.enabled))\n\t\t\ttt := componenttest.NewTelemetry()\n\t\t\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\t\t\tlongLivedCtx, parentSpan := tt.NewTelemetrySettings().TracerProvider.Tracer(\"test\").Start(context.Background(), t.Name())\n\t\t\tdefer parentSpan.End()\n\n\t\t\tparams := []testParams{\n\t\t\t\t{items: 17, err: nil},\n\t\t\t\t{items: 23, err: consumererror.NewDownstream(errFake)},\n\t\t\t}\n\t\t\tfor i := range params {\n\t\t\t\t// Use a new context on each operation to simulate distinct operations\n\t\t\t\t// under the same long lived context.\n\t\t\t\trec, rerr := NewObsReport(ObsReportSettings{\n\t\t\t\t\tReceiverID:             receiverID,\n\t\t\t\t\tTransport:              transport,\n\t\t\t\t\tLongLivedCtx:           true,\n\t\t\t\t\tReceiverCreateSettings: receiver.Settings{ID: receiverID, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t\t\t\t})\n\t\t\t\trequire.NoError(t, rerr)\n\t\t\t\tctx := rec.StartTracesOp(longLivedCtx)\n\t\t\t\tassert.NotNil(t, ctx)\n\t\t\t\trec.EndTracesOp(ctx, format, params[i].items, params[i].err)\n\t\t\t}\n\n\t\t\tspans := tt.SpanRecorder.Ended()\n\t\t\trequire.Len(t, spans, len(params))\n\n\t\t\tfor i, span := range spans {\n\t\t\t\tassert.False(t, span.Parent().IsValid())\n\t\t\t\trequire.Len(t, span.Links(), 1)\n\t\t\t\tlink := span.Links()[0]\n\t\t\t\tassert.Equal(t, parentSpan.SpanContext().TraceID(), link.SpanContext.TraceID())\n\t\t\t\tassert.Equal(t, parentSpan.SpanContext().SpanID(), link.SpanContext.SpanID())\n\t\t\t\tassert.Equal(t, \"receiver/\"+receiverID.String()+\"/TraceDataReceived\", span.Name())\n\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.TransportKey, Value: attribute.StringValue(transport)})\n\t\t\t\tswitch {\n\t\t\t\tcase params[i].err == nil:\n\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.AcceptedSpansKey, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.RefusedSpansKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedSpansKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\tassert.Equal(t, codes.Unset, span.Status().Code)\n\t\t\t\tcase consumererror.IsDownstream(params[i].err):\n\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.AcceptedSpansKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\t// For downstream errors\n\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.RefusedSpansKey, Value: attribute.Int64Value(int64(params[i].items))})\n\t\t\t\t\trequire.Contains(t, span.Attributes(), attribute.KeyValue{Key: internal.FailedSpansKey, Value: attribute.Int64Value(0)})\n\t\t\t\t\tassert.Equal(t, codes.Error, span.Status().Code)\n\t\t\t\t\tassert.Equal(t, params[i].err.Error(), span.Status().Description)\n\t\t\t\tdefault:\n\t\t\t\t\tt.Fatalf(\"unexpected error: %v\", params[i].err)\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCheckReceiverTracesViews(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\trec, err := NewObsReport(ObsReportSettings{\n\t\tReceiverID:             receiverID,\n\t\tTransport:              transport,\n\t\tReceiverCreateSettings: receiver.Settings{ID: receiverID, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t})\n\trequire.NoError(t, err)\n\tctx := rec.StartTracesOp(context.Background())\n\trequire.NotNil(t, ctx)\n\trec.EndTracesOp(ctx, format, 7, nil)\n\n\tmetadatatest.AssertEqualReceiverAcceptedSpans(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\tValue: int64(7),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\tmetadatatest.AssertEqualReceiverRefusedSpans(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\tValue: int64(0),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\tmetadatatest.AssertEqualReceiverFailedSpans(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\tValue: int64(0),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\nfunc TestCheckReceiverMetricsViews(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\trec, err := NewObsReport(ObsReportSettings{\n\t\tReceiverID:             receiverID,\n\t\tTransport:              transport,\n\t\tReceiverCreateSettings: receiver.Settings{ID: receiverID, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t})\n\trequire.NoError(t, err)\n\tctx := rec.StartMetricsOp(context.Background())\n\trequire.NotNil(t, ctx)\n\trec.EndMetricsOp(ctx, format, 7, nil)\n\n\tmetadatatest.AssertEqualReceiverAcceptedMetricPoints(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\tValue: int64(7),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\tmetadatatest.AssertEqualReceiverRefusedMetricPoints(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\tValue: int64(0),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\tmetadatatest.AssertEqualReceiverFailedMetricPoints(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\tValue: int64(0),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\nfunc TestCheckReceiverLogsViews(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\trec, err := NewObsReport(ObsReportSettings{\n\t\tReceiverID:             receiverID,\n\t\tTransport:              transport,\n\t\tReceiverCreateSettings: receiver.Settings{ID: receiverID, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t})\n\trequire.NoError(t, err)\n\tctx := rec.StartLogsOp(context.Background())\n\trequire.NotNil(t, ctx)\n\trec.EndLogsOp(ctx, format, 7, nil)\n\n\tmetadatatest.AssertEqualReceiverAcceptedLogRecords(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\tValue: int64(7),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\tmetadatatest.AssertEqualReceiverRefusedLogRecords(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\tValue: int64(0),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\tmetadatatest.AssertEqualReceiverFailedLogRecords(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\tValue: int64(0),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\nfunc TestCheckReceiverProfilesViews(t *testing.T) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\trec, err := NewObsReport(ObsReportSettings{\n\t\tReceiverID:             receiverID,\n\t\tTransport:              transport,\n\t\tReceiverCreateSettings: receiver.Settings{ID: receiverID, TelemetrySettings: tt.NewTelemetrySettings(), BuildInfo: component.NewDefaultBuildInfo()},\n\t})\n\trequire.NoError(t, err)\n\tctx := rec.StartProfilesOp(context.Background())\n\trequire.NotNil(t, ctx)\n\trec.EndProfilesOp(ctx, format, 7, nil)\n\n\tmetadatatest.AssertEqualReceiverAcceptedProfileSamples(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\tValue: int64(7),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\tmetadatatest.AssertEqualReceiverRefusedProfileSamples(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\tValue: int64(0),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\tmetadatatest.AssertEqualReceiverFailedProfileSamples(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(internal.ReceiverKey, receiverID.String()),\n\t\t\t\t\tattribute.String(internal.TransportKey, transport)),\n\t\t\t\tValue: int64(0),\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\nfunc testTelemetry(t *testing.T, testFunc func(t *testing.T, tt *componenttest.Telemetry)) {\n\ttt := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tt.Shutdown(context.Background())) })\n\n\ttestFunc(t, tt)\n}\n"
  },
  {
    "path": "receiver/receivertest/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "receiver/receivertest/contract_checker.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage receivertest // import \"go.opentelemetry.io/collector/receiver/receivertest\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"maps\"\n\t\"math/rand/v2\"\n\t\"sync\"\n\t\"sync/atomic\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/receiver\"\n)\n\n// UniqueIDAttrName is the attribute name that is used in log records/spans/datapoints as the unique identifier.\nconst UniqueIDAttrName = \"test_id\"\n\n// UniqueIDAttrVal is the value type of the UniqueIDAttrName.\ntype UniqueIDAttrVal string\n\ntype Generator interface {\n\t// Start the generator and prepare to generate. Will be followed by calls to Generate().\n\t// Start() may be called again after Stop() is called to begin a new test scenario.\n\tStart()\n\n\t// Stop generating. There will be no more calls to Generate() until Start() is called again.\n\tStop()\n\n\t// Generate must generate and send at least one data element (span, log record or metric data point)\n\t// to the receiver and return a copy of generated element ids.\n\t// The generated data must contain uniquely identifiable elements, each with a\n\t// different value of attribute named UniqueIDAttrName.\n\t// CreateOneLogWithID() can be used a helper to create such logs.\n\t// May be called concurrently from multiple goroutines.\n\tGenerate() []UniqueIDAttrVal\n}\n\ntype CheckConsumeContractParams struct {\n\tT *testing.T\n\t// Factory that allows to create a receiver.\n\tFactory receiver.Factory\n\tSignal  pipeline.Signal\n\t// Config of the receiver to use.\n\tConfig component.Config\n\t// Generator that can send data to the receiver.\n\tGenerator Generator\n\t// GenerateCount specifies the number of times to call the generator.Generate()\n\t// for each test scenario.\n\tGenerateCount int\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// CheckConsumeContract checks the contract between the receiver and its next consumer. For the contract\n// description see ../doc.go. The checker will detect violations of contract on different scenarios: on success,\n// on permanent and non-permanent errors and mix of error types.\nfunc CheckConsumeContract(params CheckConsumeContractParams) {\n\t// Different scenarios to test for.\n\t// The decision function defines the testing scenario (i.e. to test for\n\t// success case or for error case or a mix of both). See for example randomErrorsConsumeDecision.\n\tscenarios := []struct {\n\t\tname         string\n\t\tdecisionFunc func(ids idSet) error\n\t}{\n\t\t{\n\t\t\tname: \"always_succeed\",\n\t\t\t// Always succeed. We expect all data to be delivered as is.\n\t\t\tdecisionFunc: func(idSet) error { return nil },\n\t\t},\n\t\t{\n\t\t\tname:         \"random_non_permanent_error\",\n\t\t\tdecisionFunc: randomNonPermanentErrorConsumeDecision,\n\t\t},\n\t\t{\n\t\t\tname:         \"random_permanent_error\",\n\t\t\tdecisionFunc: randomPermanentErrorConsumeDecision,\n\t\t},\n\t\t{\n\t\t\tname:         \"random_error\",\n\t\t\tdecisionFunc: randomErrorsConsumeDecision,\n\t\t},\n\t}\n\n\tfor _, scenario := range scenarios {\n\t\tparams.T.Run(\n\t\t\tscenario.name, func(*testing.T) {\n\t\t\t\tcheckConsumeContractScenario(params, scenario.decisionFunc)\n\t\t\t},\n\t\t)\n\t}\n}\n\nfunc checkConsumeContractScenario(params CheckConsumeContractParams, decisionFunc func(ids idSet) error) {\n\tconsumer := &mockConsumer{t: params.T, consumeDecisionFunc: decisionFunc, acceptedIDs: make(idSet), droppedIDs: make(idSet)}\n\tctx := context.Background()\n\n\t// Create and start the receiver.\n\tvar receiver component.Component\n\tvar err error\n\tswitch params.Signal {\n\tcase pipeline.SignalLogs:\n\t\treceiver, err = params.Factory.CreateLogs(ctx, NewNopSettings(params.Factory.Type()), params.Config, consumer)\n\tcase pipeline.SignalTraces:\n\t\treceiver, err = params.Factory.CreateTraces(ctx, NewNopSettings(params.Factory.Type()), params.Config, consumer)\n\tcase pipeline.SignalMetrics:\n\t\treceiver, err = params.Factory.CreateMetrics(ctx, NewNopSettings(params.Factory.Type()), params.Config, consumer)\n\tdefault:\n\t\trequire.FailNow(params.T, \"must specify a valid DataType to test for\")\n\t}\n\n\trequire.NoError(params.T, err)\n\n\terr = receiver.Start(ctx, componenttest.NewNopHost())\n\trequire.NoError(params.T, err)\n\n\t// Begin generating data to the receiver.\n\n\tgeneratedIDs := make(idSet)\n\tvar generatedIndex int64\n\tvar mux sync.Mutex\n\tvar wg sync.WaitGroup\n\n\tconst concurrency = 4\n\n\tparams.Generator.Start()\n\tdefer params.Generator.Stop()\n\n\t// Create concurrent goroutines that use the generator.\n\t// The total number of generator calls will be equal to params.GenerateCount.\n\n\tfor range concurrency {\n\t\twg.Go(func() {\n\t\t\tfor atomic.AddInt64(&generatedIndex, 1) <= int64(params.GenerateCount) {\n\t\t\t\tids := params.Generator.Generate()\n\t\t\t\trequire.NotEmpty(params.T, ids)\n\n\t\t\t\tmux.Lock()\n\t\t\t\tduplicates := generatedIDs.mergeSlice(ids)\n\t\t\t\tmux.Unlock()\n\n\t\t\t\t// Check that the generator works correctly. There may not be any duplicates in the\n\t\t\t\t// generated data set.\n\t\t\t\trequire.Empty(params.T, duplicates)\n\t\t\t}\n\t\t})\n\t}\n\n\t// Wait until all generator goroutines are done.\n\twg.Wait()\n\n\t// Wait until all data is seen by the consumer.\n\tassert.Eventually(params.T, func() bool {\n\t\t// Calculate the union of accepted and dropped data.\n\t\tacceptedAndDropped, duplicates := consumer.acceptedAndDropped()\n\t\tif len(duplicates) != 0 {\n\t\t\tassert.Failf(params.T, \"found duplicate elements in received and dropped data\", \"keys=%v\", duplicates)\n\t\t}\n\t\t// Compare accepted+dropped with generated. Once they are equal it means all data is seen by the consumer.\n\t\tmissingInOther, onlyInOther := generatedIDs.compare(acceptedAndDropped)\n\t\treturn len(missingInOther) == 0 && len(onlyInOther) == 0\n\t}, 5*time.Second, 10*time.Millisecond)\n\n\t// Do some final checks. Need the union of accepted and dropped data again.\n\tacceptedAndDropped, duplicates := consumer.acceptedAndDropped()\n\tif len(duplicates) != 0 {\n\t\tassert.Failf(params.T, \"found duplicate elements in accepted and dropped data\", \"keys=%v\", duplicates)\n\t}\n\n\t// Make sure generated and accepted+dropped are exactly the same.\n\n\tmissingInOther, onlyInOther := generatedIDs.compare(acceptedAndDropped)\n\tif len(missingInOther) != 0 {\n\t\tassert.Failf(params.T, \"found elements sent that were not delivered\", \"keys=%v\", missingInOther)\n\t}\n\tif len(onlyInOther) != 0 {\n\t\tassert.Failf(params.T, \"found elements in accepted and dropped data that was never sent\", \"keys=%v\", onlyInOther)\n\t}\n\n\terr = receiver.Shutdown(ctx)\n\trequire.NoError(params.T, err)\n\n\t// Print some stats to help debug test failures.\n\tfmt.Printf(\n\t\t\"Sent %d, accepted=%d, expected dropped=%d, non-permanent errors retried=%d\\n\",\n\t\tlen(generatedIDs),\n\t\tlen(consumer.acceptedIDs),\n\t\tlen(consumer.droppedIDs),\n\t\tconsumer.nonPermanentFailures,\n\t)\n}\n\n// idSet is a set of unique ids of data elements used in the test (logs, spans or metric data points).\ntype idSet map[UniqueIDAttrVal]bool\n\n// compare to another set and calculate the differences from this set.\nfunc (ds idSet) compare(other idSet) (missingInOther, onlyInOther []UniqueIDAttrVal) {\n\tfor k := range ds {\n\t\tif _, ok := other[k]; !ok {\n\t\t\tmissingInOther = append(missingInOther, k)\n\t\t}\n\t}\n\tfor k := range other {\n\t\tif _, ok := ds[k]; !ok {\n\t\t\tonlyInOther = append(onlyInOther, k)\n\t\t}\n\t}\n\treturn missingInOther, onlyInOther\n}\n\n// merge another set into this one and return a list of duplicate ids.\nfunc (ds idSet) merge(other idSet) (duplicates []UniqueIDAttrVal) {\n\tfor k, v := range other {\n\t\tif _, ok := ds[k]; ok {\n\t\t\tduplicates = append(duplicates, k)\n\t\t} else {\n\t\t\tds[k] = v\n\t\t}\n\t}\n\treturn duplicates\n}\n\n// mergeSlice merges another set into this one and return a list of duplicate ids.\nfunc (ds idSet) mergeSlice(other []UniqueIDAttrVal) (duplicates []UniqueIDAttrVal) {\n\tfor _, id := range other {\n\t\tif _, ok := ds[id]; ok {\n\t\t\tduplicates = append(duplicates, id)\n\t\t} else {\n\t\t\tds[id] = true\n\t\t}\n\t}\n\treturn duplicates\n}\n\n// union computes the union of this and another sets. A new set if created to return the result.\n// Also returns a list of any duplicate ids found.\nfunc (ds idSet) union(other idSet) (union idSet, duplicates []UniqueIDAttrVal) {\n\tunion = map[UniqueIDAttrVal]bool{}\n\tmaps.Copy(union, ds)\n\tfor k, v := range other {\n\t\tif _, ok := union[k]; ok {\n\t\t\tduplicates = append(duplicates, k)\n\t\t} else {\n\t\t\tunion[k] = v\n\t\t}\n\t}\n\treturn union, duplicates\n}\n\n// A function that returns a value indicating what the receiver's next consumer decides\n// to do as a result of ConsumeLogs/Trace/Metrics call.\n// The result of the decision function becomes the return value of ConsumeLogs/Trace/Metrics.\n// Supplying different decision functions allows to test different scenarios of the contract\n// between the receiver and it next consumer.\ntype consumeDecisionFunc func(ids idSet) error\n\nvar (\n\terrNonPermanent = errors.New(\"non permanent error\")\n\terrPermanent    = errors.New(\"permanent error\")\n)\n\n// randomNonPermanentErrorConsumeDecision is a decision function that succeeds approximately\n// half of the time and fails with a non-permanent error the rest of the time.\nfunc randomNonPermanentErrorConsumeDecision(idSet) error {\n\tif rand.Float32() < 0.5 {\n\t\treturn errNonPermanent\n\t}\n\treturn nil\n}\n\n// randomPermanentErrorConsumeDecision is a decision function that succeeds approximately\n// half of the time and fails with a permanent error the rest of the time.\nfunc randomPermanentErrorConsumeDecision(idSet) error {\n\tif rand.Float32() < 0.5 {\n\t\treturn consumererror.NewPermanent(errPermanent)\n\t}\n\treturn nil\n}\n\n// randomErrorsConsumeDecision is a decision function that succeeds approximately\n// a third of the time, fails with a permanent error the third of the time and fails with\n// a non-permanent error the rest of the time.\nfunc randomErrorsConsumeDecision(idSet) error {\n\tr := rand.Float64()\n\tthird := 1.0 / 3.0\n\tif r < third {\n\t\treturn consumererror.NewPermanent(errPermanent)\n\t}\n\tif r < 2*third {\n\t\treturn errNonPermanent\n\t}\n\treturn nil\n}\n\n// mockConsumer accepts or drops the data from the receiver based on the decision made by\n// consumeDecisionFunc and remembers the accepted and dropped data sets for later checks.\n// mockConsumer implements all 3 consume functions: ConsumeLogs/ConsumeTraces/ConsumeMetrics\n// and can be used for testing any of the 3 signals.\ntype mockConsumer struct {\n\tt                    *testing.T\n\tconsumeDecisionFunc  consumeDecisionFunc\n\tmux                  sync.Mutex\n\tacceptedIDs          idSet\n\tdroppedIDs           idSet\n\tnonPermanentFailures int\n}\n\nfunc (m *mockConsumer) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{}\n}\n\nfunc (m *mockConsumer) ConsumeTraces(_ context.Context, data ptrace.Traces) error {\n\tids, err := idSetFromTraces(data)\n\trequire.NoError(m.t, err)\n\treturn m.consume(ids)\n}\n\n// idSetFromTraces computes an idSet from given ptrace.Traces. The idSet will contain ids of all spans.\nfunc idSetFromTraces(data ptrace.Traces) (idSet, error) {\n\tds := map[UniqueIDAttrVal]bool{}\n\trss := data.ResourceSpans()\n\tfor i := 0; i < rss.Len(); i++ {\n\t\tils := rss.At(i).ScopeSpans()\n\t\tfor j := 0; j < ils.Len(); j++ {\n\t\t\tss := ils.At(j).Spans()\n\t\t\tfor k := 0; k < ss.Len(); k++ {\n\t\t\t\telem := ss.At(k)\n\t\t\t\tkey, exists := elem.Attributes().Get(UniqueIDAttrName)\n\t\t\t\tif !exists {\n\t\t\t\t\treturn ds, fmt.Errorf(\"invalid data element, attribute %q is missing\", UniqueIDAttrName)\n\t\t\t\t}\n\t\t\t\tif key.Type() != pcommon.ValueTypeStr {\n\t\t\t\t\treturn ds, fmt.Errorf(\"invalid data element, attribute %q is wrong type %v\", UniqueIDAttrName, key.Type())\n\t\t\t\t}\n\t\t\t\tds[UniqueIDAttrVal(key.Str())] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn ds, nil\n}\n\nfunc (m *mockConsumer) ConsumeLogs(_ context.Context, data plog.Logs) error {\n\tids, err := idSetFromLogs(data)\n\trequire.NoError(m.t, err)\n\treturn m.consume(ids)\n}\n\n// idSetFromLogs computes an idSet from given plog.Logs. The idSet will contain ids of all log records.\nfunc idSetFromLogs(data plog.Logs) (idSet, error) {\n\tds := map[UniqueIDAttrVal]bool{}\n\trss := data.ResourceLogs()\n\tfor i := 0; i < rss.Len(); i++ {\n\t\tils := rss.At(i).ScopeLogs()\n\t\tfor j := 0; j < ils.Len(); j++ {\n\t\t\tss := ils.At(j).LogRecords()\n\t\t\tfor k := 0; k < ss.Len(); k++ {\n\t\t\t\telem := ss.At(k)\n\t\t\t\tkey, exists := elem.Attributes().Get(UniqueIDAttrName)\n\t\t\t\tif !exists {\n\t\t\t\t\treturn ds, fmt.Errorf(\"invalid data element, attribute %q is missing\", UniqueIDAttrName)\n\t\t\t\t}\n\t\t\t\tif key.Type() != pcommon.ValueTypeStr {\n\t\t\t\t\treturn ds, fmt.Errorf(\"invalid data element, attribute %q is wrong type %v\", UniqueIDAttrName, key.Type())\n\t\t\t\t}\n\t\t\t\tds[UniqueIDAttrVal(key.Str())] = true\n\t\t\t}\n\t\t}\n\t}\n\treturn ds, nil\n}\n\nfunc (m *mockConsumer) ConsumeMetrics(_ context.Context, data pmetric.Metrics) error {\n\tids, err := idSetFromMetrics(data)\n\trequire.NoError(m.t, err)\n\treturn m.consume(ids)\n}\n\n// idSetFromMetrics computes an idSet from given pmetric.Metrics. The idSet will contain ids of all metric data points.\nfunc idSetFromMetrics(data pmetric.Metrics) (idSet, error) {\n\tds := map[UniqueIDAttrVal]bool{}\n\trss := data.ResourceMetrics()\n\tfor i := 0; i < rss.Len(); i++ {\n\t\tils := rss.At(i).ScopeMetrics()\n\t\tfor j := 0; j < ils.Len(); j++ {\n\t\t\tss := ils.At(j).Metrics()\n\t\t\tfor k := 0; k < ss.Len(); k++ {\n\t\t\t\telem := ss.At(k)\n\t\t\t\tswitch elem.Type() {\n\t\t\t\tcase pmetric.MetricTypeGauge:\n\t\t\t\t\tfor l := 0; l < elem.Gauge().DataPoints().Len(); l++ {\n\t\t\t\t\t\tdp := elem.Gauge().DataPoints().At(l)\n\t\t\t\t\t\tif err := idSetFromDataPoint(ds, dp.Attributes()); err != nil {\n\t\t\t\t\t\t\treturn ds, err\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase pmetric.MetricTypeSum:\n\t\t\t\t\tfor l := 0; l < elem.Sum().DataPoints().Len(); l++ {\n\t\t\t\t\t\tdp := elem.Sum().DataPoints().At(l)\n\t\t\t\t\t\tif err := idSetFromDataPoint(ds, dp.Attributes()); err != nil {\n\t\t\t\t\t\t\treturn ds, err\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase pmetric.MetricTypeSummary:\n\t\t\t\t\tfor l := 0; l < elem.Summary().DataPoints().Len(); l++ {\n\t\t\t\t\t\tdp := elem.Summary().DataPoints().At(l)\n\t\t\t\t\t\tif err := idSetFromDataPoint(ds, dp.Attributes()); err != nil {\n\t\t\t\t\t\t\treturn ds, err\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase pmetric.MetricTypeHistogram:\n\t\t\t\t\tfor l := 0; l < elem.Histogram().DataPoints().Len(); l++ {\n\t\t\t\t\t\tdp := elem.Histogram().DataPoints().At(l)\n\t\t\t\t\t\tif err := idSetFromDataPoint(ds, dp.Attributes()); err != nil {\n\t\t\t\t\t\t\treturn ds, err\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\tcase pmetric.MetricTypeExponentialHistogram:\n\t\t\t\t\tfor l := 0; l < elem.ExponentialHistogram().DataPoints().Len(); l++ {\n\t\t\t\t\t\tdp := elem.ExponentialHistogram().DataPoints().At(l)\n\t\t\t\t\t\tif err := idSetFromDataPoint(ds, dp.Attributes()); err != nil {\n\t\t\t\t\t\t\treturn ds, err\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn ds, nil\n}\n\nfunc idSetFromDataPoint(ds map[UniqueIDAttrVal]bool, attributes pcommon.Map) error {\n\tkey, exists := attributes.Get(UniqueIDAttrName)\n\tif !exists {\n\t\treturn fmt.Errorf(\"invalid data element, attribute %q is missing\", UniqueIDAttrName)\n\t}\n\tif key.Type() != pcommon.ValueTypeStr {\n\t\treturn fmt.Errorf(\"invalid data element, attribute %q is wrong type %v\", UniqueIDAttrName, key.Type())\n\t}\n\tds[UniqueIDAttrVal(key.Str())] = true\n\treturn nil\n}\n\n// consume the elements with the specified ids, regardless of the element data type.\nfunc (m *mockConsumer) consume(ids idSet) error {\n\tm.mux.Lock()\n\tdefer m.mux.Unlock()\n\n\t// Consult with user-defined decision function to decide what to do with the data.\n\tif err := m.consumeDecisionFunc(ids); err != nil {\n\t\t// The decision is to return an error to the receiver.\n\n\t\tif consumererror.IsPermanent(err) {\n\t\t\t// It is a permanent error, which means we need to drop the data.\n\t\t\t// Remember the ids of dropped elements.\n\t\t\tduplicates := m.droppedIDs.merge(ids)\n\t\t\trequire.Empty(m.t, duplicates, \"elements that were dropped previously were sent again\")\n\t\t} else {\n\t\t\t// It is a non-permanent error. Don't add it to the drop list. Remember the number of\n\t\t\t// failures to print at the end of the test.\n\t\t\tm.nonPermanentFailures++\n\t\t}\n\t\t// Return the error to the receiver.\n\t\treturn err\n\t}\n\n\t// The decision is a success. Remember the ids of the data in the accepted list.\n\tduplicates := m.acceptedIDs.merge(ids)\n\trequire.Empty(m.t, duplicates, \"elements that were accepted previously were sent again\")\n\treturn nil\n}\n\n// Calculate union of accepted and dropped ids.\n// Returns the union and the list of duplicates between the two sets (if any)\nfunc (m *mockConsumer) acceptedAndDropped() (acceptedAndDropped idSet, duplicates []UniqueIDAttrVal) {\n\tm.mux.Lock()\n\tdefer m.mux.Unlock()\n\treturn m.acceptedIDs.union(m.droppedIDs)\n}\n\nfunc CreateOneLogWithID(id UniqueIDAttrVal) plog.Logs {\n\tdata := plog.NewLogs()\n\tdata.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty().Attributes().PutStr(\n\t\tUniqueIDAttrName,\n\t\tstring(id),\n\t)\n\treturn data\n}\n\nfunc CreateGaugeMetricWithID(id UniqueIDAttrVal) pmetric.Metrics {\n\tdata := pmetric.NewMetrics()\n\tgauge := data.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()\n\tgauge.AppendEmpty().SetEmptyGauge().DataPoints().AppendEmpty().Attributes().PutStr(\n\t\tUniqueIDAttrName,\n\t\tstring(id),\n\t)\n\treturn data\n}\n\nfunc CreateSumMetricWithID(id UniqueIDAttrVal) pmetric.Metrics {\n\tdata := pmetric.NewMetrics()\n\tsum := data.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()\n\tsum.AppendEmpty().SetEmptySum().DataPoints().AppendEmpty().Attributes().PutStr(\n\t\tUniqueIDAttrName,\n\t\tstring(id),\n\t)\n\treturn data\n}\n\nfunc CreateSummaryMetricWithID(id UniqueIDAttrVal) pmetric.Metrics {\n\tdata := pmetric.NewMetrics()\n\tsummary := data.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()\n\tsummary.AppendEmpty().SetEmptySummary().DataPoints().AppendEmpty().Attributes().PutStr(\n\t\tUniqueIDAttrName,\n\t\tstring(id),\n\t)\n\treturn data\n}\n\nfunc CreateHistogramMetricWithID(id UniqueIDAttrVal) pmetric.Metrics {\n\tdata := pmetric.NewMetrics()\n\thistogram := data.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()\n\thistogram.AppendEmpty().SetEmptyHistogram().DataPoints().AppendEmpty().Attributes().PutStr(\n\t\tUniqueIDAttrName,\n\t\tstring(id),\n\t)\n\treturn data\n}\n\nfunc CreateExponentialHistogramMetricWithID(id UniqueIDAttrVal) pmetric.Metrics {\n\tdata := pmetric.NewMetrics()\n\texponentialHistogram := data.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics()\n\texponentialHistogram.AppendEmpty().SetEmptyExponentialHistogram().DataPoints().AppendEmpty().Attributes().PutStr(\n\t\tUniqueIDAttrName,\n\t\tstring(id),\n\t)\n\treturn data\n}\n\nfunc CreateOneSpanWithID(id UniqueIDAttrVal) ptrace.Traces {\n\tdata := ptrace.NewTraces()\n\tdata.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty().Attributes().PutStr(\n\t\tUniqueIDAttrName,\n\t\tstring(id),\n\t)\n\treturn data\n}\n"
  },
  {
    "path": "receiver/receivertest/contract_checker_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage receivertest\n\nimport (\n\t\"context\"\n\t\"strconv\"\n\t\"sync/atomic\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/receiver\"\n)\n\n// This file is an example that demonstrates how to use the CheckConsumeContract() function.\n// We declare a trivial example receiver, a data generator and then use them in TestConsumeContract().\n\ntype exampleReceiver struct {\n\tnextLogsConsumer    consumer.Logs\n\tnextTracesConsumer  consumer.Traces\n\tnextMetricsConsumer consumer.Metrics\n}\n\nfunc (s *exampleReceiver) Start(context.Context, component.Host) error {\n\treturn nil\n}\n\nfunc (s *exampleReceiver) Shutdown(context.Context) error {\n\treturn nil\n}\n\nfunc (s *exampleReceiver) ReceiveLogs(data plog.Logs) {\n\t// This very simple implementation demonstrates how a single items receiving should happen.\n\tfor {\n\t\terr := s.nextLogsConsumer.ConsumeLogs(context.Background(), data)\n\t\tif err != nil {\n\t\t\t// The next consumer returned an error.\n\t\t\tif !consumererror.IsPermanent(err) {\n\t\t\t\t// It is not a permanent error, so we must retry sending it again. In network-based\n\t\t\t\t// receivers instead we can ask our sender to re-retry the same data again later.\n\t\t\t\t// We may also pause here a bit if we don't want to hammer the next consumer.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t// If we are hear either the ConsumeLogs returned success or it returned a permanent error.\n\t\t// In either case we don't need to retry the same data, we are done.\n\t\treturn\n\t}\n}\n\nfunc (s *exampleReceiver) ReceiveMetrics(data pmetric.Metrics) {\n\t// This very simple implementation demonstrates how a single items receiving should happen.\n\tfor {\n\t\terr := s.nextMetricsConsumer.ConsumeMetrics(context.Background(), data)\n\t\tif err != nil {\n\t\t\t// The next consumer returned an error.\n\t\t\tif !consumererror.IsPermanent(err) {\n\t\t\t\t// It is not a permanent error, so we must retry sending it again. In network-based\n\t\t\t\t// receivers instead we can ask our sender to re-retry the same data again later.\n\t\t\t\t// We may also pause here a bit if we don't want to hammer the next consumer.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t// If we are hear either the ConsumeLogs returned success or it returned a permanent error.\n\t\t// In either case we don't need to retry the same data, we are done.\n\t\treturn\n\t}\n}\n\nfunc (s *exampleReceiver) ReceiveTraces(data ptrace.Traces) {\n\t// This very simple implementation demonstrates how a single items receiving should happen.\n\tfor {\n\t\terr := s.nextTracesConsumer.ConsumeTraces(context.Background(), data)\n\t\tif err != nil {\n\t\t\t// The next consumer returned an error.\n\t\t\tif !consumererror.IsPermanent(err) {\n\t\t\t\t// It is not a permanent error, so we must retry sending it again. In network-based\n\t\t\t\t// receivers instead we can ask our sender to re-retry the same data again later.\n\t\t\t\t// We may also pause here a bit if we don't want to hammer the next consumer.\n\t\t\t\tcontinue\n\t\t\t}\n\t\t}\n\t\t// If we are hear either the ConsumeLogs returned success or it returned a permanent error.\n\t\t// In either case we don't need to retry the same data, we are done.\n\t\treturn\n\t}\n}\n\n// A config for exampleReceiver.\ntype exampleReceiverConfig struct {\n\tgenerator Generator\n}\n\n// A generator that can send data to exampleReceiver.\ntype exampleLogGenerator struct {\n\tt           *testing.T\n\treceiver    *exampleReceiver\n\tsequenceNum int64\n}\n\nfunc (g *exampleLogGenerator) Start() {\n\tg.sequenceNum = 0\n}\n\nfunc (g *exampleLogGenerator) Stop() {}\n\nfunc (g *exampleLogGenerator) Generate() []UniqueIDAttrVal {\n\t// Make sure the id is atomically incremented. Generate() may be called concurrently.\n\tid := UniqueIDAttrVal(strconv.FormatInt(atomic.AddInt64(&g.sequenceNum, 1), 10))\n\n\tdata := CreateOneLogWithID(id)\n\n\t// Send the generated data to the receiver.\n\tg.receiver.ReceiveLogs(data)\n\n\t// And return the ids for bookkeeping by the test.\n\treturn []UniqueIDAttrVal{id}\n}\n\n// A generator that can send data to exampleReceiver.\ntype exampleTraceGenerator struct {\n\tt           *testing.T\n\treceiver    *exampleReceiver\n\tsequenceNum int64\n}\n\nfunc (g *exampleTraceGenerator) Start() {\n\tg.sequenceNum = 0\n}\n\nfunc (g *exampleTraceGenerator) Stop() {}\n\nfunc (g *exampleTraceGenerator) Generate() []UniqueIDAttrVal {\n\t// Make sure the id is atomically incremented. Generate() may be called concurrently.\n\tid := UniqueIDAttrVal(strconv.FormatInt(atomic.AddInt64(&g.sequenceNum, 1), 10))\n\n\tdata := CreateOneSpanWithID(id)\n\n\t// Send the generated data to the receiver.\n\tg.receiver.ReceiveTraces(data)\n\n\t// And return the ids for bookkeeping by the test.\n\treturn []UniqueIDAttrVal{id}\n}\n\n// A generator that can send data to exampleReceiver.\ntype exampleMetricGenerator struct {\n\tt           *testing.T\n\treceiver    *exampleReceiver\n\tsequenceNum int64\n}\n\nfunc (g *exampleMetricGenerator) Start() {\n\tg.sequenceNum = 0\n}\n\nfunc (g *exampleMetricGenerator) Stop() {}\n\nfunc (g *exampleMetricGenerator) Generate() []UniqueIDAttrVal {\n\t// Make sure the id is atomically incremented. Generate() may be called concurrently.\n\tnext := atomic.AddInt64(&g.sequenceNum, 1)\n\tid := UniqueIDAttrVal(strconv.FormatInt(next, 10))\n\n\tvar data pmetric.Metrics\n\tswitch next % 5 {\n\tcase 0:\n\t\tdata = CreateGaugeMetricWithID(id)\n\tcase 1:\n\t\tdata = CreateSumMetricWithID(id)\n\tcase 2:\n\t\tdata = CreateSummaryMetricWithID(id)\n\tcase 3:\n\t\tdata = CreateHistogramMetricWithID(id)\n\tcase 4:\n\t\tdata = CreateExponentialHistogramMetricWithID(id)\n\t}\n\n\t// Send the generated data to the receiver.\n\tg.receiver.ReceiveMetrics(data)\n\n\t// And return the ids for bookkeeping by the test.\n\treturn []UniqueIDAttrVal{id}\n}\n\nfunc newExampleFactory() receiver.Factory {\n\treturn receiver.NewFactory(\n\t\tcomponent.MustNewType(\"example_receiver\"),\n\t\tfunc() component.Config {\n\t\t\treturn &exampleReceiverConfig{}\n\t\t},\n\t\treceiver.WithLogs(createLog, component.StabilityLevelBeta),\n\t\treceiver.WithMetrics(createMetric, component.StabilityLevelBeta),\n\t\treceiver.WithTraces(createTrace, component.StabilityLevelBeta),\n\t)\n}\n\nfunc createTrace(_ context.Context, _ receiver.Settings, cfg component.Config, consumer consumer.Traces) (receiver.Traces, error) {\n\trcv := &exampleReceiver{nextTracesConsumer: consumer}\n\tcfg.(*exampleReceiverConfig).generator.(*exampleTraceGenerator).receiver = rcv\n\treturn rcv, nil\n}\n\nfunc createMetric(_ context.Context, _ receiver.Settings, cfg component.Config, consumer consumer.Metrics) (receiver.Metrics, error) {\n\trcv := &exampleReceiver{nextMetricsConsumer: consumer}\n\tcfg.(*exampleReceiverConfig).generator.(*exampleMetricGenerator).receiver = rcv\n\treturn rcv, nil\n}\n\nfunc createLog(\n\t_ context.Context,\n\t_ receiver.Settings,\n\tcfg component.Config,\n\tconsumer consumer.Logs,\n) (receiver.Logs, error) {\n\trcv := &exampleReceiver{nextLogsConsumer: consumer}\n\tcfg.(*exampleReceiverConfig).generator.(*exampleLogGenerator).receiver = rcv\n\treturn rcv, nil\n}\n\n// TestConsumeContract is an example of testing of the receiver for the contract between the\n// receiver and next consumer.\nfunc TestConsumeContract(t *testing.T) {\n\t// Number of log records to send per scenario.\n\tconst logsPerTest = 100\n\n\tgenerator := &exampleLogGenerator{t: t}\n\tcfg := &exampleReceiverConfig{generator: generator}\n\n\tparams := CheckConsumeContractParams{\n\t\tT:             t,\n\t\tFactory:       newExampleFactory(),\n\t\tSignal:        pipeline.SignalLogs,\n\t\tConfig:        cfg,\n\t\tGenerator:     generator,\n\t\tGenerateCount: logsPerTest,\n\t}\n\n\t// Run the contract checker. This will trigger test failures if any problems are found.\n\tCheckConsumeContract(params)\n}\n\n// TestConsumeMetricsContract is an example of testing of the receiver for the contract between the\n// receiver and next consumer.\nfunc TestConsumeMetricsContract(t *testing.T) {\n\t// Number of metric data points to send per scenario.\n\tconst metricsPerTest = 100\n\n\tgenerator := &exampleMetricGenerator{t: t}\n\tcfg := &exampleReceiverConfig{generator: generator}\n\n\tparams := CheckConsumeContractParams{\n\t\tT:             t,\n\t\tFactory:       newExampleFactory(),\n\t\tSignal:        pipeline.SignalMetrics,\n\t\tConfig:        cfg,\n\t\tGenerator:     generator,\n\t\tGenerateCount: metricsPerTest,\n\t}\n\n\t// Run the contract checker. This will trigger test failures if any problems are found.\n\tCheckConsumeContract(params)\n}\n\n// TestConsumeTracesContract is an example of testing of the receiver for the contract between the\n// receiver and next consumer.\nfunc TestConsumeTracesContract(t *testing.T) {\n\t// Number of trace spans to send per scenario.\n\tconst spansPerTest = 100\n\n\tgenerator := &exampleTraceGenerator{t: t}\n\tcfg := &exampleReceiverConfig{generator: generator}\n\n\tparams := CheckConsumeContractParams{\n\t\tT:             t,\n\t\tFactory:       newExampleFactory(),\n\t\tSignal:        pipeline.SignalTraces,\n\t\tConfig:        cfg,\n\t\tGenerator:     generator,\n\t\tGenerateCount: spansPerTest,\n\t}\n\n\t// Run the contract checker. This will trigger test failures if any problems are found.\n\tCheckConsumeContract(params)\n}\n\nfunc TestIDSetFromDataPoint(t *testing.T) {\n\trequire.Error(t, idSetFromDataPoint(map[UniqueIDAttrVal]bool{}, pcommon.NewMap()))\n\tm := pcommon.NewMap()\n\tm.PutStr(\"foo\", \"bar\")\n\trequire.Error(t, idSetFromDataPoint(map[UniqueIDAttrVal]bool{}, m))\n\tm.PutInt(UniqueIDAttrName, 64)\n\trequire.Error(t, idSetFromDataPoint(map[UniqueIDAttrVal]bool{}, m))\n\tm.PutStr(UniqueIDAttrName, \"myid\")\n\tresult := map[UniqueIDAttrVal]bool{}\n\trequire.NoError(t, idSetFromDataPoint(result, m))\n\trequire.True(t, result[\"myid\"])\n}\n\nfunc TestBadMetricPoint(t *testing.T) {\n\tfor _, test := range []struct {\n\t\tname    string\n\t\tmetrics pmetric.Metrics\n\t}{\n\t\t{\n\t\t\tname: \"gauge\",\n\t\t\tmetrics: func() pmetric.Metrics {\n\t\t\t\tm := pmetric.NewMetrics()\n\t\t\t\tm.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptyGauge().DataPoints().AppendEmpty()\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"sum\",\n\t\t\tmetrics: func() pmetric.Metrics {\n\t\t\t\tm := pmetric.NewMetrics()\n\t\t\t\tm.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptySum().DataPoints().AppendEmpty()\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"summary\",\n\t\t\tmetrics: func() pmetric.Metrics {\n\t\t\t\tm := pmetric.NewMetrics()\n\t\t\t\tm.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptySummary().DataPoints().AppendEmpty()\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"histogram\",\n\t\t\tmetrics: func() pmetric.Metrics {\n\t\t\t\tm := pmetric.NewMetrics()\n\t\t\t\tm.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptyHistogram().DataPoints().AppendEmpty()\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t},\n\t\t{\n\t\t\tname: \"exponential histogram\",\n\t\t\tmetrics: func() pmetric.Metrics {\n\t\t\t\tm := pmetric.NewMetrics()\n\t\t\t\tm.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptyExponentialHistogram().DataPoints().AppendEmpty()\n\t\t\t\treturn m\n\t\t\t}(),\n\t\t},\n\t} {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\t_, err := idSetFromMetrics(test.metrics)\n\t\t\trequire.Error(t, err)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "receiver/receivertest/go.mod",
    "content": "module go.opentelemetry.io/collector/receiver/receivertest\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/google/uuid v1.6.0\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/receiver v1.54.0\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/receiver => ../\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../xreceiver\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "receiver/receivertest/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "receiver/receivertest/metadata.yaml",
    "content": "type: receiver/receivertest\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "receiver/receivertest/nop_receiver.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage receivertest // import \"go.opentelemetry.io/collector/receiver/receivertest\"\n\nimport (\n\t\"context\"\n\n\t\"github.com/google/uuid\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n)\n\nvar NopType = component.MustNewType(\"nop\")\n\n// NewNopSettings returns a new nop settings for Create*Receiver functions with the given type.\nfunc NewNopSettings(typ component.Type) receiver.Settings {\n\treturn receiver.Settings{\n\t\tID:                component.NewIDWithName(typ, uuid.NewString()),\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t\tBuildInfo:         component.NewDefaultBuildInfo(),\n\t}\n}\n\n// NewNopFactory returns a receiver.Factory that constructs nop receivers supporting all data types.\nfunc NewNopFactory() receiver.Factory {\n\treturn xreceiver.NewFactory(\n\t\tNopType,\n\t\tfunc() component.Config { return &nopConfig{} },\n\t\txreceiver.WithTraces(createTraces, component.StabilityLevelStable),\n\t\txreceiver.WithMetrics(createMetrics, component.StabilityLevelStable),\n\t\txreceiver.WithLogs(createLogs, component.StabilityLevelStable),\n\t\txreceiver.WithProfiles(createProfiles, component.StabilityLevelAlpha),\n\t)\n}\n\ntype nopConfig struct{}\n\nfunc createTraces(context.Context, receiver.Settings, component.Config, consumer.Traces) (receiver.Traces, error) {\n\treturn nopInstance, nil\n}\n\nfunc createMetrics(context.Context, receiver.Settings, component.Config, consumer.Metrics) (receiver.Metrics, error) {\n\treturn nopInstance, nil\n}\n\nfunc createLogs(context.Context, receiver.Settings, component.Config, consumer.Logs) (receiver.Logs, error) {\n\treturn nopInstance, nil\n}\n\nfunc createProfiles(context.Context, receiver.Settings, component.Config, xconsumer.Profiles) (xreceiver.Profiles, error) {\n\treturn nopInstance, nil\n}\n\nvar nopInstance = &nopReceiver{}\n\n// nopReceiver acts as a receiver for testing purposes.\ntype nopReceiver struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n}\n"
  },
  {
    "path": "receiver/receivertest/nop_receiver_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage receivertest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n)\n\nfunc TestNewNopFactory(t *testing.T) {\n\tfactory := NewNopFactory()\n\trequire.NotNil(t, factory)\n\tassert.Equal(t, \"nop\", factory.Type().String())\n\tcfg := factory.CreateDefaultConfig()\n\tassert.Equal(t, &nopConfig{}, cfg)\n\n\ttraces, err := factory.CreateTraces(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, traces.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, traces.Shutdown(context.Background()))\n\n\tmetrics, err := factory.CreateMetrics(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, metrics.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, metrics.Shutdown(context.Background()))\n\n\tlogs, err := factory.CreateLogs(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, logs.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, logs.Shutdown(context.Background()))\n\n\tprofiles, err := factory.(xreceiver.Factory).CreateProfiles(context.Background(), NewNopSettings(NopType), cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.NoError(t, profiles.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.NoError(t, profiles.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "receiver/receivertest/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage receivertest\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "receiver/xreceiver/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "receiver/xreceiver/go.mod",
    "content": "module go.opentelemetry.io/collector/receiver/xreceiver\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/receiver v1.54.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/collector/consumer v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/receiver => ../\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "receiver/xreceiver/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII=\ngithub.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "receiver/xreceiver/metadata.yaml",
    "content": "type: xreceiver\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  class: pkg\n  codeowners:\n    active:\n      - mx-psi\n      - dmathieu\n  stability:\n    alpha: [profiles]\n"
  },
  {
    "path": "receiver/xreceiver/receiver.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xreceiver // import \"go.opentelemetry.io/collector/receiver/xreceiver\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/receiver\"\n)\n\n// Profiles receiver receives profiles.\n// Its purpose is to translate data from any format to the collector's internal profile format.\n// Profiles receiver feeds a xconsumer.Profiles with data.\n//\n// For example, it could be a pprof data source which translates pprof profiles into pprofile.Profiles.\ntype Profiles interface {\n\tcomponent.Component\n}\n\n// Factory is a factory interface for receivers.\n//\n// This interface cannot be directly implemented. Implementations must\n// use the NewFactory to implement it.\ntype Factory interface {\n\treceiver.Factory\n\n\t// CreateProfiles creates a Profiles based on this config.\n\t// If the receiver type does not support tracing or if the config is not valid\n\t// an error will be returned instead. `next` is never nil.\n\tCreateProfiles(ctx context.Context, set receiver.Settings, cfg component.Config, next xconsumer.Profiles) (Profiles, error)\n\n\t// ProfilesStability gets the stability level of the Profiles receiver.\n\tProfilesStability() component.StabilityLevel\n}\n\n// CreateProfilesFunc is the equivalent of Factory.CreateProfiles.\ntype CreateProfilesFunc func(context.Context, receiver.Settings, component.Config, xconsumer.Profiles) (Profiles, error)\n\n// FactoryOption apply changes to Factory.\ntype FactoryOption interface {\n\t// applyOption applies the option.\n\tapplyOption(o *factory)\n}\n\n// factoryOptionFunc is a FactoryOption created through a function.\ntype factoryOptionFunc func(*factory)\n\nfunc (f factoryOptionFunc) applyOption(o *factory) {\n\tf(o)\n}\n\ntype factory struct {\n\treceiver.Factory\n\tcomponentalias.TypeAliasHolder\n\topts                   []receiver.FactoryOption\n\tcreateProfilesFunc     CreateProfilesFunc\n\tprofilesStabilityLevel component.StabilityLevel\n}\n\nfunc (f *factory) ProfilesStability() component.StabilityLevel {\n\treturn f.profilesStabilityLevel\n}\n\nfunc (f *factory) CreateProfiles(ctx context.Context, set receiver.Settings, cfg component.Config, next xconsumer.Profiles) (Profiles, error) {\n\tif f.createProfilesFunc == nil {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\tif err := componentalias.ValidateComponentType(f.Factory, set.ID); err != nil {\n\t\treturn nil, err\n\t}\n\treturn f.createProfilesFunc(ctx, set, cfg, next)\n}\n\n// WithTraces overrides the default \"error not supported\" implementation for Factory.CreateTraces and the default \"undefined\" stability level.\nfunc WithTraces(createTraces receiver.CreateTracesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, receiver.WithTraces(createTraces, sl))\n\t})\n}\n\n// WithMetrics overrides the default \"error not supported\" implementation for Factory.CreateMetrics and the default \"undefined\" stability level.\nfunc WithMetrics(createMetrics receiver.CreateMetricsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, receiver.WithMetrics(createMetrics, sl))\n\t})\n}\n\n// WithLogs overrides the default \"error not supported\" implementation for Factory.CreateLogs and the default \"undefined\" stability level.\nfunc WithLogs(createLogs receiver.CreateLogsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, receiver.WithLogs(createLogs, sl))\n\t})\n}\n\n// WithProfiles overrides the default \"error not supported\" implementation for Factory.CreateProfiles and the default \"undefined\" stability level.\nfunc WithProfiles(createProfiles CreateProfilesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.profilesStabilityLevel = sl\n\t\to.createProfilesFunc = createProfiles\n\t})\n}\n\n// WithDeprecatedTypeAlias configures a deprecated type alias for the receiver. Only one alias is supported per receiver.\n// When the alias is used in configuration, a deprecation warning is automatically logged.\nfunc WithDeprecatedTypeAlias(alias component.Type) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.SetDeprecatedAlias(alias)\n\t})\n}\n\n// NewFactory creates a wrapped receiver.Factory with experimental capabilities.\nfunc NewFactory(cfgType component.Type, createDefaultConfig component.CreateDefaultConfigFunc, options ...FactoryOption) Factory {\n\tf := &factory{TypeAliasHolder: componentalias.NewTypeAliasHolder()}\n\tfor _, opt := range options {\n\t\topt.applyOption(f)\n\t}\n\tf.Factory = receiver.NewFactory(cfgType, createDefaultConfig, f.opts...)\n\tf.Factory.(componentalias.TypeAliasHolder).SetDeprecatedAlias(f.DeprecatedAlias())\n\treturn f\n}\n"
  },
  {
    "path": "receiver/xreceiver/receiver_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xreceiver\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/internal\"\n)\n\nvar testID = component.MustNewID(\"test\")\n\nfunc TestNewFactoryWithProfiles(t *testing.T) {\n\ttestType := component.MustNewType(\"test\")\n\tdefaultCfg := struct{}{}\n\tfactory := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg },\n\t\tWithProfiles(createProfiles, component.StabilityLevelAlpha),\n\t)\n\tassert.Equal(t, testType, factory.Type())\n\tassert.EqualValues(t, &defaultCfg, factory.CreateDefaultConfig())\n\n\tassert.Equal(t, component.StabilityLevelAlpha, factory.ProfilesStability())\n\t_, err := factory.CreateProfiles(context.Background(), receiver.Settings{ID: testID}, &defaultCfg, nil)\n\trequire.NoError(t, err)\n\twrongID := component.MustNewID(\"wrong\")\n\twrongIDErrStr := internal.ErrIDMismatch(wrongID, testType).Error()\n\t_, err = factory.CreateProfiles(context.Background(), receiver.Settings{ID: wrongID}, &defaultCfg, nil)\n\tassert.EqualError(t, err, wrongIDErrStr)\n}\n\nvar nopInstance = &nopReceiver{\n\tConsumer: consumertest.NewNop(),\n}\n\n// nopReceiver stores consumed traces and metrics for testing purposes.\ntype nopReceiver struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumertest.Consumer\n}\n\nfunc createProfiles(context.Context, receiver.Settings, component.Config, xconsumer.Profiles) (Profiles, error) {\n\treturn nopInstance, nil\n}\n\nfunc TestNewFactoryWithDeprecatedAlias(t *testing.T) {\n\ttestType := component.MustNewType(\"newname\")\n\taliasType := component.MustNewType(\"oldname\")\n\tdefaultCfg := struct{}{}\n\n\tf := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg },\n\t\tWithProfiles(createProfiles, component.StabilityLevelAlpha),\n\t\tWithDeprecatedTypeAlias(aliasType),\n\t)\n\n\tassert.Equal(t, testType, f.Type())\n\tassert.Equal(t, aliasType, f.(*factory).Factory.(componentalias.TypeAliasHolder).DeprecatedAlias())\n\tassert.EqualValues(t, &defaultCfg, f.CreateDefaultConfig())\n\n\t_, err := f.CreateProfiles(context.Background(), receiver.Settings{ID: component.MustNewID(\"newname\")}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = f.CreateProfiles(context.Background(), receiver.Settings{ID: component.MustNewID(\"oldname\")}, &defaultCfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\t_, err = f.CreateProfiles(context.Background(), receiver.Settings{ID: component.MustNewID(\"wrongname\")}, &defaultCfg, consumertest.NewNop())\n\trequire.Error(t, err)\n}\n"
  },
  {
    "path": "renovate.json",
    "content": "{\n  \"$schema\": \"https://docs.renovatebot.com/renovate-schema.json\",\n  \"labels\": [\n    \"renovatebot\",\n    \"dependencies\"\n  ],\n  \"constraints\": {\n    \"go\": \"1.25\"\n  },\n  \"extends\": [\n    \"config:recommended\",\n    \"helpers:pinGitHubActionDigests\"\n  ],\n  \"schedule\": [\n    \"on tuesday\"\n  ],\n  \"packageRules\": [\n    {\n      \"matchManagers\": [\n        \"gomod\"\n      ],\n      \"matchUpdateTypes\": [\n        \"pin\",\n        \"pinDigest\",\n        \"digest\",\n        \"lockFileMaintenance\",\n        \"rollback\",\n        \"bump\",\n        \"replacement\"\n      ],\n      \"enabled\": false\n    },\n    {\n      \"matchManagers\": [\n        \"gomod\"\n      ],\n      \"matchUpdateTypes\": [\n        \"major\"\n      ],\n      \"prBodyNotes\": [\n        \":warning: MAJOR VERSION UPDATE :warning: - please manually update this package\"\n      ],\n      \"labels\": [\n        \"dependency-major-update\"\n      ]\n    },\n    {\n      \"matchManagers\": [\n        \"dockerfile\"\n      ],\n      \"groupName\": \"dockerfile deps\"\n    },\n    {\n      \"matchManagers\": [\n        \"docker-compose\"\n      ],\n      \"groupName\": \"docker-compose deps\"\n    },\n    {\n      \"matchManagers\": [\n        \"github-actions\"\n      ],\n      \"groupName\": \"github-actions deps\"\n    },\n    {\n      \"matchManagers\": [\n        \"gomod\"\n      ],\n      \"matchSourceUrls\": [\n        \"https://github.com/open-telemetry/opentelemetry-go-contrib\"\n      ],\n      \"groupName\": \"All opentelemetry-go-contrib packages\"\n    },\n    {\n      \"matchManagers\": [\n        \"gomod\"\n      ],\n      \"groupName\": \"All go.opentelemetry.io/contrib packages\",\n      \"matchSourceUrls\": [\n        \"https://go.opentelemetry.io/otel{/,}**\"\n      ],\n      \"allowedVersions\": \"!/v0.59.*/\"\n    },\n    {\n      \"matchManagers\": [\n        \"gomod\"\n      ],\n      \"groupName\": \"All google.golang.org packages\",\n      \"matchPackageNames\": [\n        \"google.golang.org{/,}**\"\n      ]\n    },\n    {\n      \"matchManagers\": [\n        \"gomod\"\n      ],\n      \"groupName\": \"All golang.org/x packages\",\n      \"matchPackageNames\": [\n        \"golang.org/x{/,}**\"\n      ]\n    },\n    {\n      \"matchManagers\": [\n        \"gomod\"\n      ],\n      \"groupName\": \"All github.com/knadh/koanf packages\",\n      \"matchPackageNames\": [\n        \"github.com/knadh/koanf{/,}**\"\n      ]\n    },\n    {\n      \"matchManagers\": [\n        \"gomod\"\n      ],\n      \"groupName\": \"All go.opentelemetry.io/collector packages\",\n      \"matchPackageNames\": [\n        \"go.opentelemetry.io/collector{/,}**\"\n      ]\n    },\n    {\n      \"matchManagers\": [\n        \"gomod\"\n      ],\n      \"groupName\": \"All go.opentelemetry.io/build-tools packages\",\n      \"matchPackageNames\": [\n        \"go.opentelemetry.io/build-tools{/,}**\"\n      ]\n    },\n    {\n      \"matchManagers\": [\n        \"gomod\"\n      ],\n      \"matchDepTypes\": [\n        \"toolchain\"\n      ],\n      \"enabled\": false\n    }\n  ],\n  \"ignoreDeps\": [\n    \"github.com/mattn/go-ieproxy\"\n  ],\n  \"prConcurrentLimit\": 200,\n  \"suppressNotifications\": [\n    \"prEditedNotification\"\n  ],\n  \"postUpdateOptions\": [\n    \"gomodTidy\"\n  ]\n}\n"
  },
  {
    "path": "reports/distributions/contrib.yaml",
    "content": "name: contrib\nurl: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\nmaintainers: []\ncomponents:\n    connector:\n        - forward\n    exporter:\n        - debug\n        - nop\n        - otlp_grpc\n        - otlp_http\n    extension:\n        - zpages\n    pkg:\n        - service\n    processor:\n        - batch\n        - memory_limiter\n    receiver:\n        - nop\n        - otlp\n"
  },
  {
    "path": "reports/distributions/core.yaml",
    "content": "name: core\nurl: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\nmaintainers: []\ncomponents:\n    connector:\n        - forward\n    exporter:\n        - debug\n        - nop\n        - otlp_grpc\n        - otlp_http\n    extension:\n        - zpages\n    pkg:\n        - service\n    processor:\n        - batch\n        - memory_limiter\n    receiver:\n        - nop\n        - otlp\n"
  },
  {
    "path": "reports/distributions/k8s.yaml",
    "content": "name: k8s\nurl: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-k8s\nmaintainers: []\ncomponents:\n    connector:\n        - forward\n    exporter:\n        - debug\n        - nop\n        - otlp_grpc\n        - otlp_http\n    extension:\n        - zpages\n    processor:\n        - batch\n        - memory_limiter\n    receiver:\n        - otlp\n"
  },
  {
    "path": "reports/distributions/otlp.yaml",
    "content": "name: otlp\nurl: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-otlp\nmaintainers: []\ncomponents:\n    exporter:\n        - otlp_grpc\n        - otlp_http\n    receiver:\n        - otlp\n"
  },
  {
    "path": "scraper/Makefile",
    "content": "include ../Makefile.Common\n"
  },
  {
    "path": "scraper/README.md",
    "content": "# General Information\n\nA scraper defines how to connect and scrape telemetry data from an external source.\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [development]: metrics, logs   |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Apkg%2F%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Apkg%2F) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Apkg%2F%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Apkg%2F) |\n\n[development]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#development\n<!-- end autogenerated section -->\n"
  },
  {
    "path": "scraper/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\n// Package scraper allows to define pull based receivers that can be configured using the scraperreceiver.\npackage scraper // import \"go.opentelemetry.io/collector/scraper\"\n"
  },
  {
    "path": "scraper/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scraper // import \"go.opentelemetry.io/collector/scraper\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\n// Settings configures scraper creators.\ntype Settings struct {\n\t// ID returns the ID of the component that will be created.\n\tID component.ID\n\n\tcomponent.TelemetrySettings\n\n\t// BuildInfo can be used by components for informational purposes.\n\tBuildInfo component.BuildInfo\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// Factory is factory interface for scrapers.\n//\n// This interface cannot be directly implemented. Implementations must\n// use the NewFactory to implement it.\ntype Factory interface {\n\tcomponent.Factory\n\n\t// CreateLogs creates a Logs scraper based on this config.\n\t// If the scraper type does not support logs,\n\t// this function returns the error [pipeline.ErrSignalNotSupported].\n\tCreateLogs(ctx context.Context, set Settings, cfg component.Config) (Logs, error)\n\n\t// CreateMetrics creates a Metrics scraper based on this config.\n\t// If the scraper type does not support metrics,\n\t// this function returns the error [pipeline.ErrSignalNotSupported].\n\tCreateMetrics(ctx context.Context, set Settings, cfg component.Config) (Metrics, error)\n\n\t// LogsStability gets the stability level of the Logs scraper.\n\tLogsStability() component.StabilityLevel\n\n\t// MetricsStability gets the stability level of the Metrics scraper.\n\tMetricsStability() component.StabilityLevel\n\n\tunexportedFactoryFunc()\n}\n\n// FactoryOption apply changes to Options.\ntype FactoryOption interface {\n\t// applyOption applies the option.\n\tapplyOption(o *factory)\n}\n\nvar _ FactoryOption = (*factoryOptionFunc)(nil)\n\n// factoryOptionFunc is a FactoryOption created through a function.\ntype factoryOptionFunc func(*factory)\n\nfunc (f factoryOptionFunc) applyOption(o *factory) {\n\tf(o)\n}\n\ntype factory struct {\n\tcfgType component.Type\n\tcomponent.CreateDefaultConfigFunc\n\tcreateLogsFunc        CreateLogsFunc\n\tcreateMetricsFunc     CreateMetricsFunc\n\tlogsStabilityLevel    component.StabilityLevel\n\tmetricsStabilityLevel component.StabilityLevel\n}\n\nfunc (f *factory) Type() component.Type {\n\treturn f.cfgType\n}\n\nfunc (f *factory) unexportedFactoryFunc() {}\n\nfunc (f *factory) LogsStability() component.StabilityLevel {\n\treturn f.logsStabilityLevel\n}\n\nfunc (f *factory) MetricsStability() component.StabilityLevel {\n\treturn f.metricsStabilityLevel\n}\n\nfunc (f *factory) CreateLogs(ctx context.Context, set Settings, cfg component.Config) (Logs, error) {\n\tif f.createLogsFunc == nil {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\treturn f.createLogsFunc(ctx, set, cfg)\n}\n\nfunc (f *factory) CreateMetrics(ctx context.Context, set Settings, cfg component.Config) (Metrics, error) {\n\tif f.createMetricsFunc == nil {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\treturn f.createMetricsFunc(ctx, set, cfg)\n}\n\n// CreateLogsFunc is the equivalent of Factory.CreateLogs().\ntype CreateLogsFunc func(context.Context, Settings, component.Config) (Logs, error)\n\n// CreateMetricsFunc is the equivalent of Factory.CreateMetrics().\ntype CreateMetricsFunc func(context.Context, Settings, component.Config) (Metrics, error)\n\n// WithLogs overrides the default \"error not supported\" implementation for CreateLogs and the default \"undefined\" stability level.\nfunc WithLogs(createLogs CreateLogsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.logsStabilityLevel = sl\n\t\to.createLogsFunc = createLogs\n\t})\n}\n\n// WithMetrics overrides the default \"error not supported\" implementation for CreateMetrics and the default \"undefined\" stability level.\nfunc WithMetrics(createMetrics CreateMetricsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.metricsStabilityLevel = sl\n\t\to.createMetricsFunc = createMetrics\n\t})\n}\n\n// NewFactory returns a Factory.\nfunc NewFactory(cfgType component.Type, createDefaultConfig component.CreateDefaultConfigFunc, options ...FactoryOption) Factory {\n\tf := &factory{\n\t\tcfgType:                 cfgType,\n\t\tCreateDefaultConfigFunc: createDefaultConfig,\n\t}\n\tfor _, opt := range options {\n\t\topt.applyOption(f)\n\t}\n\treturn f\n}\n"
  },
  {
    "path": "scraper/factory_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scraper\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\nvar testType = component.MustNewType(\"test\")\n\nfunc nopSettings() Settings {\n\treturn Settings{\n\t\tID:                component.NewID(testType),\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t}\n}\n\nfunc TestNewFactory(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tf := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg })\n\tassert.Equal(t, testType, f.Type())\n\tassert.EqualValues(t, &defaultCfg, f.CreateDefaultConfig())\n\t_, err := f.CreateLogs(context.Background(), nopSettings(), &defaultCfg)\n\trequire.ErrorIs(t, err, pipeline.ErrSignalNotSupported)\n\t_, err = f.CreateMetrics(context.Background(), nopSettings(), &defaultCfg)\n\trequire.ErrorIs(t, err, pipeline.ErrSignalNotSupported)\n}\n\nfunc TestNewFactoryWithOptions(t *testing.T) {\n\ttestType := component.MustNewType(\"test\")\n\tdefaultCfg := struct{}{}\n\tf := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg },\n\t\tWithLogs(createLogs, component.StabilityLevelAlpha),\n\t\tWithMetrics(createMetrics, component.StabilityLevelAlpha))\n\tassert.Equal(t, testType, f.Type())\n\tassert.EqualValues(t, &defaultCfg, f.CreateDefaultConfig())\n\n\tassert.Equal(t, component.StabilityLevelAlpha, f.LogsStability())\n\t_, err := f.CreateLogs(context.Background(), Settings{}, &defaultCfg)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, component.StabilityLevelAlpha, f.MetricsStability())\n\t_, err = f.CreateMetrics(context.Background(), Settings{}, &defaultCfg)\n\trequire.NoError(t, err)\n}\n\nfunc createLogs(context.Context, Settings, component.Config) (Logs, error) {\n\treturn NewLogs(newTestScrapeLogsFunc(nil))\n}\n\nfunc createMetrics(context.Context, Settings, component.Config) (Metrics, error) {\n\treturn NewMetrics(newTestScrapeMetricsFunc(nil))\n}\n"
  },
  {
    "path": "scraper/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage scraper\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "scraper/go.mod",
    "content": "module go.opentelemetry.io/collector/scraper\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/multierr v1.11.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/pipeline => ../pipeline\n\nreplace go.opentelemetry.io/collector/pdata => ../pdata\n\nreplace go.opentelemetry.io/collector/component => ../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../component/componenttest\n\nreplace go.opentelemetry.io/collector/featuregate => ../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../internal/testutil\n"
  },
  {
    "path": "scraper/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "scraper/logs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scraper // import \"go.opentelemetry.io/collector/scraper\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\n// Logs is the base interface for logs scrapers.\ntype Logs interface {\n\tcomponent.Component\n\n\t// ScrapeLogs is the base interface to indicate that how should logs be scraped.\n\tScrapeLogs(context.Context) (plog.Logs, error)\n}\n\n// ScrapeLogsFunc is a helper function that is similar to Logs.ScrapeLogs.\ntype ScrapeLogsFunc ScrapeFunc[plog.Logs]\n\nfunc (sf ScrapeLogsFunc) ScrapeLogs(ctx context.Context) (plog.Logs, error) {\n\treturn sf(ctx)\n}\n\ntype logs struct {\n\tbaseScraper\n\tScrapeLogsFunc\n}\n\n// NewLogs creates a new Logs scraper.\nfunc NewLogs(scrape ScrapeLogsFunc, options ...Option) (Logs, error) {\n\tif scrape == nil {\n\t\treturn nil, errNilFunc\n\t}\n\tbs := &logs{\n\t\tbaseScraper:    newBaseScraper(options),\n\t\tScrapeLogsFunc: scrape,\n\t}\n\n\treturn bs, nil\n}\n"
  },
  {
    "path": "scraper/logs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scraper\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n)\n\nfunc TestNewLogs(t *testing.T) {\n\tmp, err := NewLogs(newTestScrapeLogsFunc(nil))\n\trequire.NoError(t, err)\n\n\trequire.NoError(t, mp.Start(context.Background(), componenttest.NewNopHost()))\n\tmd, err := mp.ScrapeLogs(context.Background())\n\trequire.NoError(t, err)\n\tassert.Equal(t, plog.NewLogs(), md)\n\trequire.NoError(t, mp.Shutdown(context.Background()))\n}\n\nfunc TestNewLogs_WithOptions(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tmp, err := NewLogs(newTestScrapeLogsFunc(nil),\n\t\tWithStart(func(context.Context, component.Host) error { return want }),\n\t\tWithShutdown(func(context.Context) error { return want }))\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, want, mp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.Equal(t, want, mp.Shutdown(context.Background()))\n}\n\nfunc TestNewLogs_NilRequiredFields(t *testing.T) {\n\t_, err := NewLogs(nil)\n\trequire.Error(t, err)\n}\n\nfunc TestNewLogs_ProcessLogsError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tmp, err := NewLogs(newTestScrapeLogsFunc(want))\n\trequire.NoError(t, err)\n\t_, err = mp.ScrapeLogs(context.Background())\n\trequire.ErrorIs(t, err, want)\n}\n\nfunc TestLogsConcurrency(t *testing.T) {\n\tmp, err := NewLogs(newTestScrapeLogsFunc(nil))\n\trequire.NoError(t, err)\n\trequire.NoError(t, mp.Start(context.Background(), componenttest.NewNopHost()))\n\n\tvar wg sync.WaitGroup\n\tfor range 10 {\n\t\twg.Go(func() {\n\t\t\tfor range 10000 {\n\t\t\t\t_, errScrape := mp.ScrapeLogs(context.Background())\n\t\t\t\tassert.NoError(t, errScrape)\n\t\t\t}\n\t\t})\n\t}\n\twg.Wait()\n\trequire.NoError(t, mp.Shutdown(context.Background()))\n}\n\nfunc newTestScrapeLogsFunc(retError error) ScrapeLogsFunc {\n\treturn func(_ context.Context) (plog.Logs, error) {\n\t\treturn plog.NewLogs(), retError\n\t}\n}\n"
  },
  {
    "path": "scraper/metadata.yaml",
    "content": "type: scraper\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  stability:\n    development: [metrics, logs]\n"
  },
  {
    "path": "scraper/metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scraper // import \"go.opentelemetry.io/collector/scraper\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\n// Metrics is the base interface for metrics scrapers.\ntype Metrics interface {\n\tcomponent.Component\n\n\tScrapeMetrics(context.Context) (pmetric.Metrics, error)\n}\n\n// ScrapeMetricsFunc is a helper function that is similar to Metrics.ScrapeMetrics.\ntype ScrapeMetricsFunc ScrapeFunc[pmetric.Metrics]\n\nfunc (sf ScrapeMetricsFunc) ScrapeMetrics(ctx context.Context) (pmetric.Metrics, error) {\n\treturn sf(ctx)\n}\n\ntype metrics struct {\n\tbaseScraper\n\tScrapeMetricsFunc\n}\n\n// NewMetrics creates a new Metrics scraper.\nfunc NewMetrics(scrape ScrapeMetricsFunc, options ...Option) (Metrics, error) {\n\tif scrape == nil {\n\t\treturn nil, errNilFunc\n\t}\n\tbs := &metrics{\n\t\tbaseScraper:       newBaseScraper(options),\n\t\tScrapeMetricsFunc: scrape,\n\t}\n\n\treturn bs, nil\n}\n"
  },
  {
    "path": "scraper/metrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scraper\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n)\n\nfunc TestNewMetrics(t *testing.T) {\n\tmp, err := NewMetrics(newTestScrapeMetricsFunc(nil))\n\trequire.NoError(t, err)\n\n\trequire.NoError(t, mp.Start(context.Background(), componenttest.NewNopHost()))\n\tmd, err := mp.ScrapeMetrics(context.Background())\n\trequire.NoError(t, err)\n\tassert.Equal(t, pmetric.NewMetrics(), md)\n\trequire.NoError(t, mp.Shutdown(context.Background()))\n}\n\nfunc TestNewMetrics_WithOptions(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tmp, err := NewMetrics(newTestScrapeMetricsFunc(nil),\n\t\tWithStart(func(context.Context, component.Host) error { return want }),\n\t\tWithShutdown(func(context.Context) error { return want }))\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, want, mp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.Equal(t, want, mp.Shutdown(context.Background()))\n}\n\nfunc TestNewMetrics_NilRequiredFields(t *testing.T) {\n\t_, err := NewMetrics(nil)\n\trequire.Error(t, err)\n}\n\nfunc TestNewMetrics_ProcessMetricsError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tmp, err := NewMetrics(newTestScrapeMetricsFunc(want))\n\trequire.NoError(t, err)\n\t_, err = mp.ScrapeMetrics(context.Background())\n\trequire.ErrorIs(t, err, want)\n}\n\nfunc TestMetricsConcurrency(t *testing.T) {\n\tincomingMetrics := pmetric.NewMetrics()\n\tdps := incomingMetrics.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptySum().DataPoints()\n\n\t// Add 2 data points to the incoming\n\tdps.AppendEmpty()\n\tdps.AppendEmpty()\n\n\tmp, err := NewMetrics(newTestScrapeMetricsFunc(nil))\n\trequire.NoError(t, err)\n\trequire.NoError(t, mp.Start(context.Background(), componenttest.NewNopHost()))\n\n\tvar wg sync.WaitGroup\n\tfor range 10 {\n\t\twg.Go(func() {\n\t\t\tfor range 10000 {\n\t\t\t\t_, errScrape := mp.ScrapeMetrics(context.Background())\n\t\t\t\tassert.NoError(t, errScrape)\n\t\t\t}\n\t\t})\n\t}\n\twg.Wait()\n\trequire.NoError(t, mp.Shutdown(context.Background()))\n}\n\nfunc newTestScrapeMetricsFunc(retError error) ScrapeMetricsFunc {\n\treturn func(_ context.Context) (pmetric.Metrics, error) {\n\t\treturn pmetric.NewMetrics(), retError\n\t}\n}\n"
  },
  {
    "path": "scraper/scraper.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scraper // import \"go.opentelemetry.io/collector/scraper\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar errNilFunc = errors.New(\"nil scrape func\")\n\n// ScrapeFunc scrapes data.\ntype ScrapeFunc[T any] func(context.Context) (T, error)\n\n// Option apply changes to internal options.\ntype Option interface {\n\tapply(*baseScraper)\n}\n\ntype scraperOptionFunc func(*baseScraper)\n\nfunc (of scraperOptionFunc) apply(e *baseScraper) {\n\tof(e)\n}\n\n// WithStart sets the function that will be called on startup.\nfunc WithStart(start component.StartFunc) Option {\n\treturn scraperOptionFunc(func(o *baseScraper) {\n\t\to.StartFunc = start\n\t})\n}\n\n// WithShutdown sets the function that will be called on shutdown.\nfunc WithShutdown(shutdown component.ShutdownFunc) Option {\n\treturn scraperOptionFunc(func(o *baseScraper) {\n\t\to.ShutdownFunc = shutdown\n\t})\n}\n\ntype baseScraper struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n}\n\n// newBaseScraper returns the internal settings starting from the default and applying all options.\nfunc newBaseScraper(options []Option) baseScraper {\n\t// Start from the default options:\n\tbs := baseScraper{}\n\n\tfor _, op := range options {\n\t\top.apply(&bs)\n\t}\n\n\treturn bs\n}\n"
  },
  {
    "path": "scraper/scrapererror/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package scrapererror provides custom error types for scrapers.\npackage scrapererror // import \"go.opentelemetry.io/collector/scraper/scrapererror\"\n"
  },
  {
    "path": "scraper/scrapererror/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scrapererror\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "scraper/scrapererror/partialscrapeerror.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scrapererror // import \"go.opentelemetry.io/collector/scraper/scrapererror\"\n\nimport \"errors\"\n\n// PartialScrapeError is an error to represent\n// that a subset of data were failed to be scraped.\ntype PartialScrapeError struct {\n\terror\n\tFailed int\n}\n\n// NewPartialScrapeError creates PartialScrapeError for failed data.\n// Use this error type only when a subset of data was failed to be scraped.\nfunc NewPartialScrapeError(err error, failed int) PartialScrapeError {\n\treturn PartialScrapeError{\n\t\terror:  err,\n\t\tFailed: failed,\n\t}\n}\n\n// IsPartialScrapeError checks if an error was wrapped with PartialScrapeError.\nfunc IsPartialScrapeError(err error) bool {\n\tvar partialScrapeErr PartialScrapeError\n\treturn errors.As(err, &partialScrapeErr)\n}\n"
  },
  {
    "path": "scraper/scrapererror/partialscrapeerror_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scrapererror\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestPartialScrapeError(t *testing.T) {\n\tfailed := 2\n\terr := errors.New(\"some error\")\n\tpartialErr := NewPartialScrapeError(err, failed)\n\trequire.EqualError(t, err, partialErr.Error())\n\tassert.Equal(t, failed, partialErr.Failed)\n}\n\nfunc TestIsPartialScrapeError(t *testing.T) {\n\terr := errors.New(\"testError\")\n\trequire.False(t, IsPartialScrapeError(err))\n\n\terr = NewPartialScrapeError(err, 2)\n\trequire.True(t, IsPartialScrapeError(err))\n}\n"
  },
  {
    "path": "scraper/scrapererror/scrapeerror.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scrapererror // import \"go.opentelemetry.io/collector/scraper/scrapererror\"\n\nimport (\n\t\"go.uber.org/multierr\"\n)\n\n// ScrapeErrors contains multiple PartialScrapeErrors and can also contain generic errors.\ntype ScrapeErrors struct {\n\terrs              []error\n\tfailedScrapeCount int\n}\n\n// AddPartial adds a PartialScrapeError with the provided failed count and error.\nfunc (s *ScrapeErrors) AddPartial(failed int, err error) {\n\ts.errs = append(s.errs, NewPartialScrapeError(err, failed))\n\ts.failedScrapeCount += failed\n}\n\n// Add adds a regular error.\nfunc (s *ScrapeErrors) Add(err error) {\n\ts.errs = append(s.errs, err)\n}\n\n// Combine converts a slice of errors into one error.\n// It will return a PartialScrapeError if at least one error in the slice is a PartialScrapeError.\nfunc (s *ScrapeErrors) Combine() error {\n\tpartialScrapeErr := false\n\tfor _, err := range s.errs {\n\t\tif IsPartialScrapeError(err) {\n\t\t\tpartialScrapeErr = true\n\t\t}\n\t}\n\n\tcombined := multierr.Combine(s.errs...)\n\tif !partialScrapeErr {\n\t\treturn combined\n\t}\n\n\treturn NewPartialScrapeError(combined, s.failedScrapeCount)\n}\n"
  },
  {
    "path": "scraper/scrapererror/scrapeerror_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scrapererror\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nfunc TestScrapeErrorsAddPartial(t *testing.T) {\n\terr1 := errors.New(\"err 1\")\n\terr2 := errors.New(\"err 2\")\n\texpected := []error{\n\t\tPartialScrapeError{error: err1, Failed: 1},\n\t\tPartialScrapeError{error: err2, Failed: 10},\n\t}\n\n\tvar errs ScrapeErrors\n\terrs.AddPartial(1, err1)\n\terrs.AddPartial(10, err2)\n\tassert.Equal(t, expected, errs.errs)\n}\n\nfunc TestScrapeErrorsAdd(t *testing.T) {\n\terr1 := errors.New(\"err a\")\n\terr2 := errors.New(\"err b\")\n\texpected := []error{err1, err2}\n\n\tvar errs ScrapeErrors\n\terrs.Add(err1)\n\terrs.Add(err2)\n\tassert.Equal(t, expected, errs.errs)\n}\n\nfunc TestScrapeErrorsCombine(t *testing.T) {\n\ttestCases := []struct {\n\t\terrs                func() ScrapeErrors\n\t\texpectedErr         string\n\t\texpectedFailedCount int\n\t\texpectNil           bool\n\t\texpectedScrape      bool\n\t}{\n\t\t{\n\t\t\terrs: func() ScrapeErrors {\n\t\t\t\tvar errs ScrapeErrors\n\t\t\t\treturn errs\n\t\t\t},\n\t\t\texpectNil: true,\n\t\t},\n\t\t{\n\t\t\terrs: func() ScrapeErrors {\n\t\t\t\tvar errs ScrapeErrors\n\t\t\t\terrs.AddPartial(10, errors.New(\"bad scrapes\"))\n\t\t\t\terrs.AddPartial(1, fmt.Errorf(\"err: %w\", errors.New(\"bad scrape\")))\n\t\t\t\treturn errs\n\t\t\t},\n\t\t\texpectedErr:         \"bad scrapes; err: bad scrape\",\n\t\t\texpectedFailedCount: 11,\n\t\t\texpectedScrape:      true,\n\t\t},\n\t\t{\n\t\t\terrs: func() ScrapeErrors {\n\t\t\t\tvar errs ScrapeErrors\n\t\t\t\terrs.Add(errors.New(\"bad regular\"))\n\t\t\t\terrs.Add(fmt.Errorf(\"err: %w\", errors.New(\"bad reg\")))\n\t\t\t\treturn errs\n\t\t\t},\n\t\t\texpectedErr: \"bad regular; err: bad reg\",\n\t\t},\n\t\t{\n\t\t\terrs: func() ScrapeErrors {\n\t\t\t\tvar errs ScrapeErrors\n\t\t\t\terrs.AddPartial(2, errors.New(\"bad two scrapes\"))\n\t\t\t\terrs.AddPartial(10, fmt.Errorf(\"%d scrapes failed: %w\", 10, errors.New(\"bad things happened\")))\n\t\t\t\terrs.Add(errors.New(\"bad event\"))\n\t\t\t\terrs.Add(fmt.Errorf(\"event: %w\", errors.New(\"something happened\")))\n\t\t\t\treturn errs\n\t\t\t},\n\t\t\texpectedErr:         \"bad two scrapes; 10 scrapes failed: bad things happened; bad event; event: something happened\",\n\t\t\texpectedFailedCount: 12,\n\t\t\texpectedScrape:      true,\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tscrapeErrs := tt.errs()\n\t\tif tt.expectNil {\n\t\t\trequire.NoError(t, scrapeErrs.Combine())\n\t\t\tcontinue\n\t\t}\n\t\trequire.EqualError(t, scrapeErrs.Combine(), tt.expectedErr)\n\t\tif tt.expectedScrape {\n\t\t\tvar partialScrapeErr PartialScrapeError\n\t\t\tif !errors.As(scrapeErrs.Combine(), &partialScrapeErr) {\n\t\t\t\tt.Errorf(\"%+v.Combine() = %q. Want: PartialScrapeError\", scrapeErrs, scrapeErrs.Combine())\n\t\t\t} else if tt.expectedFailedCount != partialScrapeErr.Failed {\n\t\t\t\tt.Errorf(\"%+v.Combine().Failed. Got %d Failed count. Want: %d\", scrapeErrs, partialScrapeErr.Failed, tt.expectedFailedCount)\n\t\t\t}\n\t\t}\n\t}\n}\n"
  },
  {
    "path": "scraper/scraperhelper/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "scraper/scraperhelper/README.md",
    "content": "# General Information\n\nA scraper defines how to connect and scrape telemetry data from an external source.\n\n<!-- status autogenerated section -->\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [beta]: metrics, logs   |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Apkg%2Fscraperhelper%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Apkg%2Fscraperhelper) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Apkg%2Fscraperhelper%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Apkg%2Fscraperhelper) |\n\n[beta]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#beta\n<!-- end autogenerated section -->\n"
  },
  {
    "path": "scraper/scraperhelper/config.schema.yaml",
    "content": "$defs:\n  controller_config:\n    description: ControllerConfig defines common settings for a scraper controller configuration. Scraper controller receivers can embed this struct, instead of receiver.Settings, and extend it with more fields if needed.\n    type: object\n    properties:\n      collection_interval:\n        description: CollectionInterval sets how frequently the scraper should be called and used as the context timeout to ensure that scrapers don't exceed the interval.\n        type: string\n        x-customType: time.Duration\n        format: duration\n      initial_delay:\n        description: InitialDelay sets the initial start delay for the scraper, any non positive value is assumed to be immediately.\n        type: string\n        x-customType: time.Duration\n        format: duration\n      timeout:\n        description: Timeout is an optional value used to set scraper's context deadline.\n        type: string\n        x-customType: time.Duration\n        format: duration\n"
  },
  {
    "path": "scraper/scraperhelper/controller.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scraperhelper // import \"go.opentelemetry.io/collector/scraper/scraperhelper\"\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/scraper\"\n\t\"go.opentelemetry.io/collector/scraper/scrapererror\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/internal/controller\"\n)\n\ntype ControllerConfig = controller.ControllerConfig\n\n// NewDefaultControllerConfig returns default scraper controller\n// settings with a collection interval of one minute.\nfunc NewDefaultControllerConfig() ControllerConfig {\n\treturn controller.NewDefaultControllerConfig()\n}\n\n// ControllerOption apply changes to internal options.\ntype ControllerOption interface {\n\tapply(*controllerOptions)\n}\n\ntype optionFunc func(*controllerOptions)\n\nfunc (of optionFunc) apply(e *controllerOptions) {\n\tof(e)\n}\n\n// AddMetricsScraper configures the scraper.Metrics to be called with the\n// specified options, and at the specified collection interval.\n//\n// Observability information will be reported, and the scraped metrics\n// will be passed to the next consumer.\nfunc AddMetricsScraper(t component.Type, sc scraper.Metrics) ControllerOption {\n\tf := scraper.NewFactory(t, nil,\n\t\tscraper.WithMetrics(func(context.Context, scraper.Settings, component.Config) (scraper.Metrics, error) {\n\t\t\treturn sc, nil\n\t\t}, component.StabilityLevelAlpha))\n\treturn AddFactoryWithConfig(f, nil)\n}\n\n// AddScraper configures the scraper.Metrics to be called with the\n// specified options, and at the specified collection interval.\n//\n// Observability information will be reported, and the scraped metrics\n// will be passed to the next consumer.\n//\n// Deprecated: [0.144.0] Use AddMetricsScraper instead.\nfunc AddScraper(t component.Type, sc scraper.Metrics) ControllerOption {\n\treturn AddMetricsScraper(t, sc)\n}\n\n// AddFactoryWithConfig configures the scraper.Factory and associated config that\n// will be used to create a new scraper. The created scraper will be called with\n// the specified options, and at the specified collection interval.\n//\n// Observability information will be reported, and the scraped metrics\n// will be passed to the next consumer.\nfunc AddFactoryWithConfig(f scraper.Factory, cfg component.Config) ControllerOption {\n\treturn optionFunc(func(o *controllerOptions) {\n\t\to.factoriesWithConfig = append(o.factoriesWithConfig, factoryWithConfig{f: f, cfg: cfg})\n\t})\n}\n\n// WithTickerChannel allows you to override the scraper controller's ticker\n// channel to specify when scrape is called. This is only expected to be\n// used by tests.\nfunc WithTickerChannel(tickerCh <-chan time.Time) ControllerOption {\n\treturn optionFunc(func(o *controllerOptions) {\n\t\to.tickerCh = tickerCh\n\t})\n}\n\ntype factoryWithConfig struct {\n\tf   scraper.Factory\n\tcfg component.Config\n}\n\ntype controllerOptions struct {\n\ttickerCh            <-chan time.Time\n\tfactoriesWithConfig []factoryWithConfig\n}\n\n// NewLogsController creates a receiver.Logs with the configured options, that can control multiple scraper.Logs.\nfunc NewLogsController(cfg *ControllerConfig,\n\trSet receiver.Settings,\n\tnextConsumer consumer.Logs,\n\toptions ...ControllerOption,\n) (receiver.Logs, error) {\n\tco := getOptions(options)\n\tscrapers := make([]scraper.Logs, 0, len(co.factoriesWithConfig))\n\tfor _, fwc := range co.factoriesWithConfig {\n\t\tset := controller.GetSettings(fwc.f.Type(), rSet)\n\t\ts, err := fwc.f.CreateLogs(context.Background(), set, fwc.cfg)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts, err = wrapObsLogs(s, rSet.ID, set.ID, set.TelemetrySettings)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tscrapers = append(scrapers, s)\n\t}\n\treturn controller.NewController[scraper.Logs](\n\t\tcfg, rSet, scrapers, func(c *controller.Controller[scraper.Logs]) { scrapeLogs(c, nextConsumer) }, co.tickerCh)\n}\n\n// NewMetricsController creates a receiver.Metrics with the configured options, that can control multiple scraper.Metrics.\nfunc NewMetricsController(cfg *ControllerConfig,\n\trSet receiver.Settings,\n\tnextConsumer consumer.Metrics,\n\toptions ...ControllerOption,\n) (receiver.Metrics, error) {\n\tco := getOptions(options)\n\tscrapers := make([]scraper.Metrics, 0, len(co.factoriesWithConfig))\n\tfor _, fwc := range co.factoriesWithConfig {\n\t\tset := controller.GetSettings(fwc.f.Type(), rSet)\n\t\ts, err := fwc.f.CreateMetrics(context.Background(), set, fwc.cfg)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts, err = wrapObsMetrics(s, rSet.ID, set.ID, set.TelemetrySettings)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tscrapers = append(scrapers, s)\n\t}\n\treturn controller.NewController[scraper.Metrics](\n\t\tcfg, rSet, scrapers, func(c *controller.Controller[scraper.Metrics]) { scrapeMetrics(c, nextConsumer) }, co.tickerCh)\n}\n\nfunc scrapeLogs(c *controller.Controller[scraper.Logs], nextConsumer consumer.Logs) {\n\tctx, done := controller.WithScrapeContext(c.Timeout)\n\tdefer done()\n\n\tlogs := plog.NewLogs()\n\tfor i := range c.Scrapers {\n\t\tmd, err := c.Scrapers[i].ScrapeLogs(ctx)\n\t\tif err != nil && !scrapererror.IsPartialScrapeError(err) {\n\t\t\tcontinue\n\t\t}\n\t\tmd.ResourceLogs().MoveAndAppendTo(logs.ResourceLogs())\n\t}\n\n\tlogRecordCount := logs.LogRecordCount()\n\tctx = c.Obsrecv.StartLogsOp(ctx)\n\terr := nextConsumer.ConsumeLogs(ctx, logs)\n\tc.Obsrecv.EndLogsOp(ctx, \"\", logRecordCount, err)\n}\n\nfunc scrapeMetrics(c *controller.Controller[scraper.Metrics], nextConsumer consumer.Metrics) {\n\tctx, done := controller.WithScrapeContext(c.Timeout)\n\tdefer done()\n\n\tmetrics := pmetric.NewMetrics()\n\tfor i := range c.Scrapers {\n\t\tmd, err := c.Scrapers[i].ScrapeMetrics(ctx)\n\t\tif err != nil && !scrapererror.IsPartialScrapeError(err) {\n\t\t\tcontinue\n\t\t}\n\t\tmd.ResourceMetrics().MoveAndAppendTo(metrics.ResourceMetrics())\n\t}\n\n\tdataPointCount := metrics.DataPointCount()\n\tctx = c.Obsrecv.StartMetricsOp(ctx)\n\terr := nextConsumer.ConsumeMetrics(ctx, metrics)\n\tc.Obsrecv.EndMetricsOp(ctx, \"\", dataPointCount, err)\n}\n\nfunc getOptions(options []ControllerOption) controllerOptions {\n\tco := controllerOptions{}\n\tfor _, op := range options {\n\t\top.apply(&co)\n\t}\n\treturn co\n}\n"
  },
  {
    "path": "scraper/scraperhelper/controller_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scraperhelper\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\tsdktrace \"go.opentelemetry.io/otel/sdk/trace\"\n\t\"go.uber.org/multierr\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n\t\"go.opentelemetry.io/collector/scraper\"\n\t\"go.opentelemetry.io/collector/scraper/scrapererror\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/internal/controller\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/internal/metadatatest\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/internal/testhelper\"\n)\n\ntype testScrape struct {\n\tch                chan int\n\ttimesScrapeCalled int\n\terr               error\n}\n\nfunc (ts *testScrape) scrapeLogs(context.Context) (plog.Logs, error) {\n\tts.timesScrapeCalled++\n\tts.ch <- ts.timesScrapeCalled\n\n\tif ts.err != nil {\n\t\treturn plog.Logs{}, ts.err\n\t}\n\n\tmd := plog.NewLogs()\n\tmd.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty().Body().SetStr(\"\")\n\treturn md, nil\n}\n\nfunc (ts *testScrape) scrapeMetrics(context.Context) (pmetric.Metrics, error) {\n\tts.timesScrapeCalled++\n\tts.ch <- ts.timesScrapeCalled\n\n\tif ts.err != nil {\n\t\treturn pmetric.Metrics{}, ts.err\n\t}\n\n\tmd := pmetric.NewMetrics()\n\tmd.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptyGauge().DataPoints().AppendEmpty()\n\treturn md, nil\n}\n\nfunc newTestNoDelaySettings() *ControllerConfig {\n\treturn &ControllerConfig{\n\t\tCollectionInterval: time.Second,\n\t\tInitialDelay:       0,\n\t}\n}\n\ntype scraperTestCase struct {\n\tname string\n\n\tscrapers                  int\n\tscraperControllerSettings *ControllerConfig\n\tscrapeErr                 error\n\texpectScraped             bool\n\n\tinitialize    bool\n\tclose         bool\n\tinitializeErr error\n\tcloseErr      error\n}\n\nfunc TestLogsScrapeController(t *testing.T) {\n\ttestCases := []scraperTestCase{\n\t\t{\n\t\t\tname: \"NoScrapers\",\n\t\t},\n\t\t{\n\t\t\tname:          \"AddLogsScrapersWithCollectionInterval\",\n\t\t\tscrapers:      2,\n\t\t\texpectScraped: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"AddLogsScrapers_ScrapeError\",\n\t\t\tscrapers:  2,\n\t\t\tscrapeErr: errors.New(\"err1\"),\n\t\t},\n\t\t{\n\t\t\tname:          \"AddLogsScrapersWithInitializeAndClose\",\n\t\t\tscrapers:      2,\n\t\t\tinitialize:    true,\n\t\t\texpectScraped: true,\n\t\t\tclose:         true,\n\t\t},\n\t\t{\n\t\t\tname:          \"AddLogsScrapersWithInitializeAndCloseErrors\",\n\t\t\tscrapers:      2,\n\t\t\tinitialize:    true,\n\t\t\tclose:         true,\n\t\t\tinitializeErr: errors.New(\"err1\"),\n\t\t\tcloseErr:      errors.New(\"err2\"),\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\treceiverID := component.MustNewID(\"receiver\")\n\t\t\ttel := componenttest.NewTelemetry()\n\t\t\tt.Cleanup(func() { require.NoError(t, tel.Shutdown(context.Background())) })\n\n\t\t\tset := tel.NewTelemetrySettings()\n\t\t\t_, parentSpan := set.TracerProvider.Tracer(\"test\").Start(context.Background(), t.Name())\n\t\t\tdefer parentSpan.End()\n\n\t\t\tinitializeChs := make([]chan bool, test.scrapers)\n\t\t\tscrapeLogsChs := make([]chan int, test.scrapers)\n\t\t\tcloseChs := make([]chan bool, test.scrapers)\n\t\t\toptions := configureLogOptions(t, test, initializeChs, scrapeLogsChs, closeChs)\n\n\t\t\ttickerCh := make(chan time.Time)\n\t\t\toptions = append(options, WithTickerChannel(tickerCh))\n\n\t\t\tsink := new(consumertest.LogsSink)\n\t\t\tcfg := newTestNoDelaySettings()\n\t\t\tif test.scraperControllerSettings != nil {\n\t\t\t\tcfg = test.scraperControllerSettings\n\t\t\t}\n\n\t\t\tmr, err := NewLogsController(cfg, receiver.Settings{ID: receiverID, TelemetrySettings: set, BuildInfo: component.NewDefaultBuildInfo()}, sink, options...)\n\t\t\trequire.NoError(t, err)\n\n\t\t\terr = mr.Start(context.Background(), componenttest.NewNopHost())\n\t\t\texpectedStartErr := getExpectedStartErr(test)\n\t\t\tif expectedStartErr != nil {\n\t\t\t\tassert.Equal(t, expectedStartErr, err)\n\t\t\t} else if test.initialize {\n\t\t\t\ttesthelper.AssertChannelsCalled(t, initializeChs, \"start was not called\")\n\t\t\t}\n\n\t\t\tconst iterations = 5\n\n\t\t\tif test.expectScraped || test.scrapeErr != nil {\n\t\t\t\t// validate that scrape is called at least N times for each configured scraper\n\t\t\t\tfor _, ch := range scrapeLogsChs {\n\t\t\t\t\t<-ch\n\t\t\t\t}\n\t\t\t\t// Consume the initial scrapes on start\n\t\t\t\tfor range iterations {\n\t\t\t\t\ttickerCh <- time.Now()\n\n\t\t\t\t\tfor _, ch := range scrapeLogsChs {\n\t\t\t\t\t\t<-ch\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// wait until all calls to scrape have completed\n\t\t\t\tif test.scrapeErr == nil {\n\t\t\t\t\trequire.Eventually(t, func() bool {\n\t\t\t\t\t\treturn sink.LogRecordCount() == (1+iterations)*(test.scrapers)\n\t\t\t\t\t}, time.Second, time.Millisecond)\n\t\t\t\t}\n\n\t\t\t\tif test.expectScraped {\n\t\t\t\t\tassert.GreaterOrEqual(t, sink.LogRecordCount(), iterations)\n\t\t\t\t}\n\n\t\t\t\tspans := tel.SpanRecorder.Ended()\n\t\t\t\tassertLogsReceiverSpan(t, spans)\n\t\t\t\ttesthelper.AssertScraperSpan(t, test.scrapeErr, spans, \"scraper/scraper/ScrapeLogs\")\n\t\t\t\tassertLogsScraperObsMetrics(t, tel, receiverID, component.MustNewID(\"scraper\"), test.scrapeErr, sink)\n\t\t\t}\n\n\t\t\terr = mr.Shutdown(context.Background())\n\t\t\texpectedShutdownErr := getExpectedShutdownErr(test)\n\t\t\tif expectedShutdownErr != nil {\n\t\t\t\tassert.EqualError(t, err, expectedShutdownErr.Error())\n\t\t\t} else if test.close {\n\t\t\t\ttesthelper.AssertChannelsCalled(t, closeChs, \"shutdown was not called\")\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestMetricsScrapeController(t *testing.T) {\n\ttestCases := []scraperTestCase{\n\t\t{\n\t\t\tname: \"NoScrapers\",\n\t\t},\n\t\t{\n\t\t\tname:          \"AddMetricsScrapersWithCollectionInterval\",\n\t\t\tscrapers:      2,\n\t\t\texpectScraped: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"AddMetricsScrapers_ScrapeError\",\n\t\t\tscrapers:  2,\n\t\t\tscrapeErr: errors.New(\"err1\"),\n\t\t},\n\t\t{\n\t\t\tname:          \"AddMetricsScrapersWithInitializeAndClose\",\n\t\t\tscrapers:      2,\n\t\t\tinitialize:    true,\n\t\t\texpectScraped: true,\n\t\t\tclose:         true,\n\t\t},\n\t\t{\n\t\t\tname:          \"AddMetricsScrapersWithInitializeAndCloseErrors\",\n\t\t\tscrapers:      2,\n\t\t\tinitialize:    true,\n\t\t\tclose:         true,\n\t\t\tinitializeErr: errors.New(\"err1\"),\n\t\t\tcloseErr:      errors.New(\"err2\"),\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\treceiverID := component.MustNewID(\"receiver\")\n\t\t\ttel := componenttest.NewTelemetry()\n\t\t\tt.Cleanup(func() { require.NoError(t, tel.Shutdown(context.Background())) })\n\n\t\t\tset := tel.NewTelemetrySettings()\n\t\t\t_, parentSpan := set.TracerProvider.Tracer(\"test\").Start(context.Background(), t.Name())\n\t\t\tdefer parentSpan.End()\n\n\t\t\tinitializeChs := make([]chan bool, test.scrapers)\n\t\t\tscrapeMetricsChs := make([]chan int, test.scrapers)\n\t\t\tcloseChs := make([]chan bool, test.scrapers)\n\t\t\toptions := configureMetricOptions(t, test, initializeChs, scrapeMetricsChs, closeChs)\n\n\t\t\ttickerCh := make(chan time.Time)\n\t\t\toptions = append(options, WithTickerChannel(tickerCh))\n\n\t\t\tsink := new(consumertest.MetricsSink)\n\t\t\tcfg := newTestNoDelaySettings()\n\t\t\tif test.scraperControllerSettings != nil {\n\t\t\t\tcfg = test.scraperControllerSettings\n\t\t\t}\n\n\t\t\tmr, err := NewMetricsController(cfg, receiver.Settings{ID: receiverID, TelemetrySettings: set, BuildInfo: component.NewDefaultBuildInfo()}, sink, options...)\n\t\t\trequire.NoError(t, err)\n\n\t\t\terr = mr.Start(context.Background(), componenttest.NewNopHost())\n\t\t\texpectedStartErr := getExpectedStartErr(test)\n\t\t\tif expectedStartErr != nil {\n\t\t\t\tassert.Equal(t, expectedStartErr, err)\n\t\t\t} else if test.initialize {\n\t\t\t\ttesthelper.AssertChannelsCalled(t, initializeChs, \"start was not called\")\n\t\t\t}\n\n\t\t\tconst iterations = 5\n\n\t\t\tif test.expectScraped || test.scrapeErr != nil {\n\t\t\t\t// validate that scrape is called at least N times for each configured scraper\n\t\t\t\tfor _, ch := range scrapeMetricsChs {\n\t\t\t\t\t<-ch\n\t\t\t\t}\n\t\t\t\t// Consume the initial scrapes on start\n\t\t\t\tfor range iterations {\n\t\t\t\t\ttickerCh <- time.Now()\n\n\t\t\t\t\tfor _, ch := range scrapeMetricsChs {\n\t\t\t\t\t\t<-ch\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// wait until all calls to scrape have completed\n\t\t\t\tif test.scrapeErr == nil {\n\t\t\t\t\trequire.Eventually(t, func() bool {\n\t\t\t\t\t\treturn sink.DataPointCount() == (1+iterations)*(test.scrapers)\n\t\t\t\t\t}, time.Second, time.Millisecond)\n\t\t\t\t}\n\n\t\t\t\tif test.expectScraped {\n\t\t\t\t\tassert.GreaterOrEqual(t, sink.DataPointCount(), iterations)\n\t\t\t\t}\n\n\t\t\t\tspans := tel.SpanRecorder.Ended()\n\t\t\t\tassertMetricsReceiverSpan(t, spans)\n\t\t\t\ttesthelper.AssertScraperSpan(t, test.scrapeErr, spans, \"scraper/scraper/ScrapeMetrics\")\n\t\t\t\tassertMetricsScraperObsMetrics(t, tel, receiverID, component.MustNewID(\"scraper\"), test.scrapeErr, sink)\n\t\t\t}\n\n\t\t\terr = mr.Shutdown(context.Background())\n\t\t\texpectedShutdownErr := getExpectedShutdownErr(test)\n\t\t\tif expectedShutdownErr != nil {\n\t\t\t\tassert.EqualError(t, err, expectedShutdownErr.Error())\n\t\t\t} else if test.close {\n\t\t\t\ttesthelper.AssertChannelsCalled(t, closeChs, \"shutdown was not called\")\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc configureLogOptions(t *testing.T, test scraperTestCase, initializeChs []chan bool, scrapeLogsChs []chan int, closeChs []chan bool) []ControllerOption {\n\tvar logsOptions []ControllerOption\n\n\tfor i := 0; i < test.scrapers; i++ {\n\t\tvar scraperOptions []scraper.Option\n\t\tif test.initialize {\n\t\t\tinitializeChs[i] = make(chan bool, 1)\n\t\t\tti := testhelper.NewTestInitialize(initializeChs[i], test.initializeErr)\n\t\t\tscraperOptions = append(scraperOptions, scraper.WithStart(ti.Start))\n\t\t}\n\t\tif test.close {\n\t\t\tcloseChs[i] = make(chan bool, 1)\n\t\t\ttc := testhelper.NewTestClose(closeChs[i], test.closeErr)\n\t\t\tscraperOptions = append(scraperOptions, scraper.WithShutdown(tc.Shutdown))\n\t\t}\n\n\t\tscrapeLogsChs[i] = make(chan int)\n\t\tts := &testScrape{ch: scrapeLogsChs[i], err: test.scrapeErr}\n\t\tscp, err := scraper.NewLogs(ts.scrapeLogs, scraperOptions...)\n\t\trequire.NoError(t, err)\n\n\t\tlogsOptions = append(logsOptions, addLogsScraper(component.MustNewType(\"scraper\"), scp))\n\t}\n\n\treturn logsOptions\n}\n\nfunc configureMetricOptions(t *testing.T, test scraperTestCase, initializeChs []chan bool, scrapeMetricsChs []chan int, closeChs []chan bool) []ControllerOption {\n\tvar metricOptions []ControllerOption\n\n\tfor i := 0; i < test.scrapers; i++ {\n\t\tvar scraperOptions []scraper.Option\n\t\tif test.initialize {\n\t\t\tinitializeChs[i] = make(chan bool, 1)\n\t\t\tti := testhelper.NewTestInitialize(initializeChs[i], test.initializeErr)\n\t\t\tscraperOptions = append(scraperOptions, scraper.WithStart(ti.Start))\n\t\t}\n\t\tif test.close {\n\t\t\tcloseChs[i] = make(chan bool, 1)\n\t\t\ttc := testhelper.NewTestClose(closeChs[i], test.closeErr)\n\t\t\tscraperOptions = append(scraperOptions, scraper.WithShutdown(tc.Shutdown))\n\t\t}\n\n\t\tscrapeMetricsChs[i] = make(chan int)\n\t\tts := &testScrape{ch: scrapeMetricsChs[i], err: test.scrapeErr}\n\t\tscp, err := scraper.NewMetrics(ts.scrapeMetrics, scraperOptions...)\n\t\trequire.NoError(t, err)\n\n\t\tmetricOptions = append(metricOptions, AddMetricsScraper(component.MustNewType(\"scraper\"), scp))\n\t}\n\n\treturn metricOptions\n}\n\nfunc getExpectedStartErr(test scraperTestCase) error {\n\treturn test.initializeErr\n}\n\nfunc getExpectedShutdownErr(test scraperTestCase) error {\n\tvar errs error\n\n\tif test.closeErr != nil {\n\t\tfor i := 0; i < test.scrapers; i++ {\n\t\t\terrs = multierr.Append(errs, test.closeErr)\n\t\t}\n\t}\n\n\treturn errs\n}\n\nfunc assertMetricsReceiverSpan(t *testing.T, spans []sdktrace.ReadOnlySpan) {\n\treceiverSpan := false\n\tfor _, span := range spans {\n\t\tif span.Name() == \"receiver/receiver/MetricsReceived\" {\n\t\t\treceiverSpan = true\n\t\t\tbreak\n\t\t}\n\t}\n\tassert.True(t, receiverSpan)\n}\n\nfunc assertLogsReceiverSpan(t *testing.T, spans []sdktrace.ReadOnlySpan) {\n\treceiverSpan := false\n\tfor _, span := range spans {\n\t\tif span.Name() == \"receiver/receiver/LogsReceived\" {\n\t\t\treceiverSpan = true\n\t\t\tbreak\n\t\t}\n\t}\n\tassert.True(t, receiverSpan)\n}\n\nfunc assertLogsScraperObsMetrics(t *testing.T, tel *componenttest.Telemetry, receiver, scraper component.ID, expectedErr error, sink *consumertest.LogsSink) {\n\tlogRecordCounts := 0\n\tfor _, md := range sink.AllLogs() {\n\t\tlogRecordCounts += md.LogRecordCount()\n\t}\n\n\texpectedScraped := int64(sink.LogRecordCount())\n\texpectedErrored := int64(0)\n\tif expectedErr != nil {\n\t\tvar partialError scrapererror.PartialScrapeError\n\t\tif errors.As(expectedErr, &partialError) {\n\t\t\texpectedErrored = int64(partialError.Failed)\n\t\t} else {\n\t\t\texpectedScraped = int64(0)\n\t\t\texpectedErrored = int64(sink.LogRecordCount())\n\t\t}\n\t}\n\n\tmetadatatest.AssertEqualScraperScrapedLogRecords(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(receiverKey, receiver.String()),\n\t\t\t\t\tattribute.String(scraperKey, scraper.String())),\n\t\t\t\tValue: expectedScraped,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\tmetadatatest.AssertEqualScraperErroredLogRecords(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(receiverKey, receiver.String()),\n\t\t\t\t\tattribute.String(scraperKey, scraper.String())),\n\t\t\t\tValue: expectedErrored,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\nfunc assertMetricsScraperObsMetrics(t *testing.T, tel *componenttest.Telemetry, receiver, scraper component.ID, expectedErr error, sink *consumertest.MetricsSink) {\n\tdataPointCounts := 0\n\tfor _, md := range sink.AllMetrics() {\n\t\tdataPointCounts += md.DataPointCount()\n\t}\n\n\texpectedScraped := int64(sink.DataPointCount())\n\texpectedErrored := int64(0)\n\tif expectedErr != nil {\n\t\tvar partialError scrapererror.PartialScrapeError\n\t\tif errors.As(expectedErr, &partialError) {\n\t\t\texpectedErrored = int64(partialError.Failed)\n\t\t} else {\n\t\t\texpectedScraped = int64(0)\n\t\t\texpectedErrored = int64(sink.DataPointCount())\n\t\t}\n\t}\n\n\tmetadatatest.AssertEqualScraperScrapedMetricPoints(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(receiverKey, receiver.String()),\n\t\t\t\t\tattribute.String(scraperKey, scraper.String())),\n\t\t\t\tValue: expectedScraped,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\tmetadatatest.AssertEqualScraperErroredMetricPoints(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(receiverKey, receiver.String()),\n\t\t\t\t\tattribute.String(scraperKey, scraper.String())),\n\t\t\t\tValue: expectedErrored,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\nfunc TestSingleLogsScraperPerInterval(t *testing.T) {\n\tscrapeCh := make(chan int, 10)\n\tts := &testScrape{ch: scrapeCh}\n\n\tcfg := newTestNoDelaySettings()\n\n\ttickerCh := make(chan time.Time)\n\n\tscp, err := scraper.NewLogs(ts.scrapeLogs)\n\trequire.NoError(t, err)\n\n\trecv, err := NewLogsController(\n\t\tcfg,\n\t\treceivertest.NewNopSettings(receivertest.NopType),\n\t\tnew(consumertest.LogsSink),\n\t\taddLogsScraper(component.MustNewType(\"scraper\"), scp),\n\t\tWithTickerChannel(tickerCh),\n\t)\n\trequire.NoError(t, err)\n\n\trequire.NoError(t, recv.Start(context.Background(), componenttest.NewNopHost()))\n\tdefer func() { require.NoError(t, recv.Shutdown(context.Background())) }()\n\n\ttickerCh <- time.Now()\n\n\tassert.Eventually(\n\t\tt,\n\t\tfunc() bool {\n\t\t\treturn <-scrapeCh == 2\n\t\t},\n\t\t300*time.Millisecond,\n\t\t100*time.Millisecond,\n\t\t\"Make sure the scraper channel is called twice\",\n\t)\n\n\tselect {\n\tcase <-scrapeCh:\n\t\tassert.Fail(t, \"Scrape was called more than twice\")\n\tcase <-time.After(100 * time.Millisecond):\n\t\treturn\n\t}\n}\n\nfunc TestSingleMetricsScraperPerInterval(t *testing.T) {\n\tscrapeCh := make(chan int, 10)\n\tts := &testScrape{ch: scrapeCh}\n\n\tcfg := newTestNoDelaySettings()\n\n\ttickerCh := make(chan time.Time)\n\n\tscp, err := scraper.NewMetrics(ts.scrapeMetrics)\n\trequire.NoError(t, err)\n\n\trecv, err := NewMetricsController(\n\t\tcfg,\n\t\treceivertest.NewNopSettings(receivertest.NopType),\n\t\tnew(consumertest.MetricsSink),\n\t\tAddMetricsScraper(component.MustNewType(\"scraper\"), scp),\n\t\tWithTickerChannel(tickerCh),\n\t)\n\trequire.NoError(t, err)\n\n\trequire.NoError(t, recv.Start(context.Background(), componenttest.NewNopHost()))\n\tdefer func() { require.NoError(t, recv.Shutdown(context.Background())) }()\n\n\ttickerCh <- time.Now()\n\n\tassert.Eventually(\n\t\tt,\n\t\tfunc() bool {\n\t\t\treturn <-scrapeCh == 2\n\t\t},\n\t\t300*time.Millisecond,\n\t\t100*time.Millisecond,\n\t\t\"Make sure the scraper channel is called twice\",\n\t)\n\n\tselect {\n\tcase <-scrapeCh:\n\t\tassert.Fail(t, \"Scrape was called more than twice\")\n\tcase <-time.After(100 * time.Millisecond):\n\t\treturn\n\t}\n}\n\nfunc TestLogsScraperControllerStartsOnInit(t *testing.T) {\n\tt.Parallel()\n\n\tts := &testScrape{\n\t\tch: make(chan int, 1),\n\t}\n\n\tscp, err := scraper.NewLogs(ts.scrapeLogs)\n\trequire.NoError(t, err, \"Must not error when creating scraper\")\n\n\tr, err := NewLogsController(\n\t\t&ControllerConfig{\n\t\t\tCollectionInterval: time.Hour,\n\t\t\tInitialDelay:       0,\n\t\t},\n\t\treceivertest.NewNopSettings(receivertest.NopType),\n\t\tnew(consumertest.LogsSink),\n\t\taddLogsScraper(component.MustNewType(\"scraper\"), scp),\n\t)\n\trequire.NoError(t, err, \"Must not error when creating scrape controller\")\n\n\tassert.NoError(t, r.Start(context.Background(), componenttest.NewNopHost()), \"Must not error on start\")\n\t<-time.After(500 * time.Nanosecond)\n\trequire.NoError(t, r.Shutdown(context.Background()), \"Must not have errored on shutdown\")\n\tassert.Equal(t, 1, ts.timesScrapeCalled, \"Must have been called as soon as the controller started\")\n}\n\nfunc TestMetricsScraperControllerStartsOnInit(t *testing.T) {\n\tt.Parallel()\n\n\tts := &testScrape{\n\t\tch: make(chan int, 1),\n\t}\n\n\tscp, err := scraper.NewMetrics(ts.scrapeMetrics)\n\trequire.NoError(t, err, \"Must not error when creating scraper\")\n\n\tr, err := NewMetricsController(\n\t\t&ControllerConfig{\n\t\t\tCollectionInterval: time.Hour,\n\t\t\tInitialDelay:       0,\n\t\t},\n\t\treceivertest.NewNopSettings(receivertest.NopType),\n\t\tnew(consumertest.MetricsSink),\n\t\tAddMetricsScraper(component.MustNewType(\"scraper\"), scp),\n\t)\n\trequire.NoError(t, err, \"Must not error when creating scrape controller\")\n\n\tassert.NoError(t, r.Start(context.Background(), componenttest.NewNopHost()), \"Must not error on start\")\n\t<-time.After(500 * time.Nanosecond)\n\trequire.NoError(t, r.Shutdown(context.Background()), \"Must not have errored on shutdown\")\n\tassert.Equal(t, 1, ts.timesScrapeCalled, \"Must have been called as soon as the controller started\")\n}\n\nfunc TestLogsScraperControllerInitialDelay(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"This requires real time to pass, skipping\")\n\t\treturn\n\t}\n\n\tt.Parallel()\n\n\tvar (\n\t\telapsed = make(chan time.Time, 1)\n\t\tcfg     = ControllerConfig{\n\t\t\tCollectionInterval: time.Second,\n\t\t\tInitialDelay:       300 * time.Millisecond,\n\t\t}\n\t)\n\n\tscp, err := scraper.NewLogs(func(context.Context) (plog.Logs, error) {\n\t\telapsed <- time.Now()\n\t\treturn plog.NewLogs(), nil\n\t})\n\trequire.NoError(t, err, \"Must not error when creating scraper\")\n\n\tr, err := NewLogsController(\n\t\t&cfg,\n\t\treceivertest.NewNopSettings(receivertest.NopType),\n\t\tnew(consumertest.LogsSink),\n\t\taddLogsScraper(component.MustNewType(\"scraper\"), scp),\n\t)\n\trequire.NoError(t, err, \"Must not error when creating receiver\")\n\n\tt0 := time.Now()\n\trequire.NoError(t, r.Start(context.Background(), componenttest.NewNopHost()), \"Must not error when starting\")\n\tt1 := <-elapsed\n\n\tassert.GreaterOrEqual(t, t1.Sub(t0), 300*time.Millisecond, \"Must have had 300ms pass as defined by initial delay\")\n\n\tassert.NoError(t, r.Shutdown(context.Background()), \"Must not error closing down\")\n}\n\nfunc TestMetricsScraperControllerInitialDelay(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"This requires real time to pass, skipping\")\n\t\treturn\n\t}\n\n\tt.Parallel()\n\n\tvar (\n\t\telapsed = make(chan time.Time, 1)\n\t\tcfg     = ControllerConfig{\n\t\t\tCollectionInterval: time.Second,\n\t\t\tInitialDelay:       300 * time.Millisecond,\n\t\t}\n\t)\n\n\tscp, err := scraper.NewMetrics(func(context.Context) (pmetric.Metrics, error) {\n\t\telapsed <- time.Now()\n\t\treturn pmetric.NewMetrics(), nil\n\t})\n\trequire.NoError(t, err, \"Must not error when creating scraper\")\n\n\tr, err := NewMetricsController(\n\t\t&cfg,\n\t\treceivertest.NewNopSettings(receivertest.NopType),\n\t\tnew(consumertest.MetricsSink),\n\t\tAddMetricsScraper(component.MustNewType(\"scraper\"), scp),\n\t)\n\trequire.NoError(t, err, \"Must not error when creating receiver\")\n\n\tt0 := time.Now()\n\trequire.NoError(t, r.Start(context.Background(), componenttest.NewNopHost()), \"Must not error when starting\")\n\tt1 := <-elapsed\n\n\tassert.GreaterOrEqual(t, t1.Sub(t0), 300*time.Millisecond, \"Must have had 300ms pass as defined by initial delay\")\n\n\tassert.NoError(t, r.Shutdown(context.Background()), \"Must not error closing down\")\n}\n\nfunc TestLogsScraperShutdownBeforeScrapeCanStart(t *testing.T) {\n\tcfg := ControllerConfig{\n\t\tCollectionInterval: time.Second,\n\t\tInitialDelay:       5 * time.Second,\n\t}\n\n\tscp, err := scraper.NewLogs(func(context.Context) (plog.Logs, error) {\n\t\t// make the scraper wait for long enough it would disrupt a shutdown.\n\t\ttime.Sleep(30 * time.Second)\n\t\treturn plog.NewLogs(), nil\n\t})\n\trequire.NoError(t, err, \"Must not error when creating scraper\")\n\n\tr, err := NewLogsController(\n\t\t&cfg,\n\t\treceivertest.NewNopSettings(receivertest.NopType),\n\t\tnew(consumertest.LogsSink),\n\t\taddLogsScraper(component.MustNewType(\"scraper\"), scp),\n\t)\n\trequire.NoError(t, err, \"Must not error when creating receiver\")\n\trequire.NoError(t, r.Start(context.Background(), componenttest.NewNopHost()))\n\tshutdown := make(chan struct{}, 1)\n\tgo func() {\n\t\tassert.NoError(t, r.Shutdown(context.Background()))\n\t\tclose(shutdown)\n\t}()\n\ttimer := time.NewTicker(10 * time.Second)\n\tselect {\n\tcase <-timer.C:\n\t\trequire.Fail(t, \"shutdown should not wait for scraping\")\n\tcase <-shutdown:\n\t}\n}\n\nfunc TestMetricsScraperShutdownBeforeScrapeCanStart(t *testing.T) {\n\tcfg := ControllerConfig{\n\t\tCollectionInterval: time.Second,\n\t\tInitialDelay:       5 * time.Second,\n\t}\n\n\tscp, err := scraper.NewMetrics(func(context.Context) (pmetric.Metrics, error) {\n\t\t// make the scraper wait for long enough it would disrupt a shutdown.\n\t\ttime.Sleep(30 * time.Second)\n\t\treturn pmetric.NewMetrics(), nil\n\t})\n\trequire.NoError(t, err, \"Must not error when creating scraper\")\n\n\tr, err := NewMetricsController(\n\t\t&cfg,\n\t\treceivertest.NewNopSettings(receivertest.NopType),\n\t\tnew(consumertest.MetricsSink),\n\t\tAddMetricsScraper(component.MustNewType(\"scraper\"), scp),\n\t)\n\trequire.NoError(t, err, \"Must not error when creating receiver\")\n\trequire.NoError(t, r.Start(context.Background(), componenttest.NewNopHost()))\n\tshutdown := make(chan struct{}, 1)\n\tgo func() {\n\t\tassert.NoError(t, r.Shutdown(context.Background()))\n\t\tclose(shutdown)\n\t}()\n\ttimer := time.NewTicker(10 * time.Second)\n\tselect {\n\tcase <-timer.C:\n\t\trequire.Fail(t, \"shutdown should not wait for scraping\")\n\tcase <-shutdown:\n\t}\n}\n\nfunc addLogsScraper(t component.Type, sc scraper.Logs) ControllerOption {\n\tf := scraper.NewFactory(t, nil,\n\t\tscraper.WithLogs(func(context.Context, scraper.Settings, component.Config) (scraper.Logs, error) {\n\t\t\treturn sc, nil\n\t\t}, component.StabilityLevelAlpha))\n\treturn AddFactoryWithConfig(f, nil)\n}\n\nfunc TestNewDefaultControllerConfig(t *testing.T) {\n\tcontrollerConfig := NewDefaultControllerConfig()\n\tintControllerConfig := controller.NewDefaultControllerConfig()\n\trequire.Equal(t, intControllerConfig, controllerConfig)\n}\n\nfunc TestNewMetricsController_ScraperIDInErrorLogs(t *testing.T) {\n\tt.Parallel()\n\n\tcore, observedLogs := observer.New(zap.ErrorLevel)\n\ttel := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tel.Shutdown(context.Background())) })\n\ttelset := tel.NewTelemetrySettings()\n\ttelset.Logger = zap.New(core)\n\n\treceiverID := component.MustNewID(\"fakeReceiver\")\n\tscraperType := component.MustNewType(\"fakeScraper\")\n\tscrapeErr := errors.New(\"scrape error\")\n\n\tscrapeCh := make(chan int, 1)\n\tts := &testScrape{ch: scrapeCh, err: scrapeErr}\n\tscp, err := scraper.NewMetrics(ts.scrapeMetrics)\n\trequire.NoError(t, err)\n\n\tcfg := newTestNoDelaySettings()\n\ttickerCh := make(chan time.Time)\n\n\trecv, err := NewMetricsController(\n\t\tcfg,\n\t\treceiver.Settings{ID: receiverID, TelemetrySettings: telset, BuildInfo: component.NewDefaultBuildInfo()},\n\t\tnew(consumertest.MetricsSink),\n\t\tAddMetricsScraper(scraperType, scp),\n\t\tWithTickerChannel(tickerCh),\n\t)\n\trequire.NoError(t, err)\n\trequire.NoError(t, recv.Start(context.Background(), componenttest.NewNopHost()))\n\tdefer func() { require.NoError(t, recv.Shutdown(context.Background())) }()\n\n\t<-scrapeCh\n\n\trequire.Eventually(t, func() bool {\n\t\treturn observedLogs.Len() >= 1\n\t}, time.Second, 10*time.Millisecond)\n\terrorLogs := observedLogs.FilterLevelExact(zap.ErrorLevel).All()\n\trequire.Len(t, errorLogs, 1)\n\n\tassert.Equal(t, \"Error scraping metrics\", errorLogs[0].Message)\n\tassert.Equal(t, scraperType.String(), errorLogs[0].ContextMap()[\"scraper\"])\n\tassert.Equal(t, scrapeErr.Error(), errorLogs[0].ContextMap()[\"error\"])\n\n\t// Verify the original receiver telemetry settings logger was NOT mutated\n\t// by logging something and checking it doesn't have the scraper field\n\ttelset.Logger.Error(\"test log from receiver\")\n\n\tallLogs := observedLogs.FilterLevelExact(zap.ErrorLevel).All()\n\trequire.Len(t, allLogs, 2)\n\n\treceiverLog := allLogs[1]\n\tassert.Equal(t, \"test log from receiver\", receiverLog.Message)\n\tassert.NotContains(t, receiverLog.ContextMap(), \"scraper\")\n}\n"
  },
  {
    "path": "scraper/scraperhelper/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\n// Package scraperhelper provides utilities for scrapers.\npackage scraperhelper // import \"go.opentelemetry.io/collector/scraper/scraperhelper\"\n"
  },
  {
    "path": "scraper/scraperhelper/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# scraperhelper\n\n## Internal Telemetry\n\nThe following telemetry is emitted by this component.\n\n### otelcol_scraper_errored_log_records\n\nNumber of log records that were unable to be scraped.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {datapoint} | Sum | Int | true | Alpha |\n\n### otelcol_scraper_errored_metric_points\n\nNumber of metric points that were unable to be scraped.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {datapoint} | Sum | Int | true | Alpha |\n\n### otelcol_scraper_scraped_log_records\n\nNumber of log records successfully scraped.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {datapoint} | Sum | Int | true | Alpha |\n\n### otelcol_scraper_scraped_metric_points\n\nNumber of metric points successfully scraped.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {datapoint} | Sum | Int | true | Alpha |\n"
  },
  {
    "path": "scraper/scraperhelper/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage scraperhelper\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "scraper/scraperhelper/go.mod",
    "content": "module go.opentelemetry.io/collector/scraper/scraperhelper\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/receiver v1.54.0\n\tgo.opentelemetry.io/collector/receiver/receiverhelper v0.148.0\n\tgo.opentelemetry.io/collector/receiver/receivertest v0.148.0\n\tgo.opentelemetry.io/collector/scraper v0.148.0\n\tgo.opentelemetry.io/otel v1.42.0\n\tgo.opentelemetry.io/otel/metric v1.42.0\n\tgo.opentelemetry.io/otel/sdk v1.42.0\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0\n\tgo.opentelemetry.io/otel/trace v1.42.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/multierr v1.11.0\n\tgo.uber.org/zap v1.27.1\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/scraper => ../\n\nreplace go.opentelemetry.io/collector/receiver => ../../receiver\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../../receiver/receivertest\n\nreplace go.opentelemetry.io/collector/receiver/receiverhelper => ../../receiver/receiverhelper\n\nreplace go.opentelemetry.io/collector/consumer => ../../consumer\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n"
  },
  {
    "path": "scraper/scraperhelper/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "scraper/scraperhelper/internal/controller/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage controller // import \"go.opentelemetry.io/collector/scraper/scraperhelper/internal/controller\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"go.uber.org/multierr\"\n)\n\nvar errNonPositiveInterval = errors.New(\"requires positive value\")\n\n// ControllerConfig defines common settings for a scraper controller\n// configuration. Scraper controller receivers can embed this struct, instead\n// of receiver.Settings, and extend it with more fields if needed.\ntype ControllerConfig struct {\n\t// CollectionInterval sets how frequently the scraper\n\t// should be called and used as the context timeout\n\t// to ensure that scrapers don't exceed the interval.\n\tCollectionInterval time.Duration `mapstructure:\"collection_interval\"`\n\t// InitialDelay sets the initial start delay for the scraper,\n\t// any non positive value is assumed to be immediately.\n\tInitialDelay time.Duration `mapstructure:\"initial_delay\"`\n\t// Timeout is an optional value used to set scraper's context deadline.\n\tTimeout time.Duration `mapstructure:\"timeout\"`\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n\n// NewDefaultControllerConfig returns default scraper controller\n// settings with a collection interval of one minute.\nfunc NewDefaultControllerConfig() ControllerConfig {\n\treturn ControllerConfig{\n\t\tCollectionInterval: time.Minute,\n\t\tInitialDelay:       time.Second,\n\t\tTimeout:            0,\n\t}\n}\n\nfunc (set *ControllerConfig) Validate() (errs error) {\n\tif set.CollectionInterval <= 0 {\n\t\terrs = multierr.Append(errs, fmt.Errorf(`\"collection_interval\": %w`, errNonPositiveInterval))\n\t}\n\tif set.Timeout < 0 {\n\t\terrs = multierr.Append(errs, fmt.Errorf(`\"timeout\": %w`, errNonPositiveInterval))\n\t}\n\treturn errs\n}\n"
  },
  {
    "path": "scraper/scraperhelper/internal/controller/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage controller // import \"go.opentelemetry.io/collector/scraper/scraperhelper/internal/controller\"\n\nimport (\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n)\n\nfunc TestScrapeControllerSettings(t *testing.T) {\n\tt.Parallel()\n\n\tfor _, tc := range []struct {\n\t\tname   string\n\t\tset    ControllerConfig\n\t\terrVal string\n\t}{\n\t\t{\n\t\t\tname:   \"default configuration\",\n\t\t\tset:    NewDefaultControllerConfig(),\n\t\t\terrVal: \"\",\n\t\t},\n\t\t{\n\t\t\tname:   \"zero value configuration\",\n\t\t\tset:    ControllerConfig{},\n\t\t\terrVal: `\"collection_interval\": requires positive value`,\n\t\t},\n\t\t{\n\t\t\tname: \"invalid timeout\",\n\t\t\tset: ControllerConfig{\n\t\t\t\tCollectionInterval: time.Minute,\n\t\t\t\tTimeout:            -1 * time.Minute,\n\t\t\t},\n\t\t\terrVal: `\"timeout\": requires positive value`,\n\t\t},\n\t} {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\tt.Parallel()\n\n\t\t\terr := tc.set.Validate()\n\t\t\tif tc.errVal == \"\" {\n\t\t\t\tassert.NoError(t, err, \"Must not error\")\n\t\t\t\treturn\n\t\t\t}\n\t\t\tassert.EqualError(t, err, tc.errVal, \"Must match the expected error\")\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "scraper/scraperhelper/internal/controller/controller.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// package controller provides functionality used in scraperhelper and xscraperhelper.\n\npackage controller // import \"go.opentelemetry.io/collector/scraper/scraperhelper/internal/controller\"\n\nimport (\n\t\"context\"\n\t\"sync\"\n\t\"time\"\n\n\t\"go.uber.org/multierr\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receiverhelper\"\n\t\"go.opentelemetry.io/collector/scraper\"\n)\n\ntype Controller[T component.Component] struct {\n\tcollectionInterval time.Duration\n\tinitialDelay       time.Duration\n\tTimeout            time.Duration\n\n\tScrapers   []T\n\tscrapeFunc func(*Controller[T])\n\ttickerCh   <-chan time.Time\n\n\tdone chan struct{}\n\twg   sync.WaitGroup\n\n\tObsrecv *receiverhelper.ObsReport\n}\n\nfunc NewController[T component.Component](\n\tcfg *ControllerConfig,\n\trSet receiver.Settings,\n\tscrapers []T,\n\tscrapeFunc func(*Controller[T]),\n\ttickerCh <-chan time.Time,\n) (*Controller[T], error) {\n\tobsrecv, err := receiverhelper.NewObsReport(receiverhelper.ObsReportSettings{\n\t\tReceiverID:             rSet.ID,\n\t\tTransport:              \"\",\n\t\tReceiverCreateSettings: rSet,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tcs := &Controller[T]{\n\t\tcollectionInterval: cfg.CollectionInterval,\n\t\tinitialDelay:       cfg.InitialDelay,\n\t\tTimeout:            cfg.Timeout,\n\t\tScrapers:           scrapers,\n\t\tscrapeFunc:         scrapeFunc,\n\t\tdone:               make(chan struct{}),\n\t\ttickerCh:           tickerCh,\n\t\tObsrecv:            obsrecv,\n\t}\n\n\treturn cs, nil\n}\n\n// Start the receiver, invoked during service start.\nfunc (sc *Controller[T]) Start(ctx context.Context, host component.Host) error {\n\tfor _, scrp := range sc.Scrapers {\n\t\tif err := scrp.Start(ctx, host); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tsc.startScraping()\n\treturn nil\n}\n\n// Shutdown the receiver, invoked during service shutdown.\nfunc (sc *Controller[T]) Shutdown(ctx context.Context) error {\n\t// Signal the goroutine to stop.\n\tclose(sc.done)\n\tsc.wg.Wait()\n\tvar errs error\n\tfor _, scrp := range sc.Scrapers {\n\t\terrs = multierr.Append(errs, scrp.Shutdown(ctx))\n\t}\n\n\treturn errs\n}\n\n// startScraping initiates a ticker that calls Scrape based on the configured\n// collection interval.\nfunc (sc *Controller[T]) startScraping() {\n\tsc.wg.Go(func() {\n\t\tif sc.initialDelay > 0 {\n\t\t\tselect {\n\t\t\tcase <-time.After(sc.initialDelay):\n\t\t\tcase <-sc.done:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\n\t\tif sc.tickerCh == nil {\n\t\t\tticker := time.NewTicker(sc.collectionInterval)\n\t\t\tdefer ticker.Stop()\n\n\t\t\tsc.tickerCh = ticker.C\n\t\t}\n\t\t// Call scrape method during initialization to ensure\n\t\t// that scrapers start from when the component starts\n\t\t// instead of waiting for the full duration to start.\n\t\tsc.scrapeFunc(sc)\n\t\tfor {\n\t\t\tselect {\n\t\t\tcase <-sc.tickerCh:\n\t\t\t\tsc.scrapeFunc(sc)\n\t\t\tcase <-sc.done:\n\t\t\t\treturn\n\t\t\t}\n\t\t}\n\t})\n}\n\nfunc GetSettings(sType component.Type, rSet receiver.Settings) scraper.Settings {\n\tid := component.NewID(sType)\n\ttelemetry := rSet.TelemetrySettings\n\ttelemetry.Logger = telemetry.Logger.With(zap.String(\"scraper\", id.String()))\n\treturn scraper.Settings{\n\t\tID:                id,\n\t\tTelemetrySettings: telemetry,\n\t\tBuildInfo:         rSet.BuildInfo,\n\t}\n}\n\n// WithScrapeContext will return a context that has no deadline if timeout is 0\n// which implies no explicit timeout had occurred, otherwise, a context\n// with a deadline of the provided timeout is returned.\nfunc WithScrapeContext(timeout time.Duration) (context.Context, context.CancelFunc) {\n\tif timeout == 0 {\n\t\treturn context.WithCancel(context.Background())\n\t}\n\treturn context.WithTimeout(context.Background(), timeout)\n}\n"
  },
  {
    "path": "scraper/scraperhelper/internal/metadata/generated_telemetry.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc Meter(settings component.TelemetrySettings) metric.Meter {\n\treturn settings.MeterProvider.Meter(\"go.opentelemetry.io/collector/scraper/scraperhelper\")\n}\n\nfunc Tracer(settings component.TelemetrySettings) trace.Tracer {\n\treturn settings.TracerProvider.Tracer(\"go.opentelemetry.io/collector/scraper/scraperhelper\")\n}\n\n// TelemetryBuilder provides an interface for components to report telemetry\n// as defined in metadata and user config.\ntype TelemetryBuilder struct {\n\tmeter                      metric.Meter\n\tmu                         sync.Mutex\n\tregistrations              []metric.Registration\n\tScraperErroredLogRecords   metric.Int64Counter\n\tScraperErroredMetricPoints metric.Int64Counter\n\tScraperScrapedLogRecords   metric.Int64Counter\n\tScraperScrapedMetricPoints metric.Int64Counter\n}\n\n// TelemetryBuilderOption applies changes to default builder.\ntype TelemetryBuilderOption interface {\n\tapply(*TelemetryBuilder)\n}\n\ntype telemetryBuilderOptionFunc func(mb *TelemetryBuilder)\n\nfunc (tbof telemetryBuilderOptionFunc) apply(mb *TelemetryBuilder) {\n\ttbof(mb)\n}\n\n// Shutdown unregister all registered callbacks for async instruments.\nfunc (builder *TelemetryBuilder) Shutdown() {\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tfor _, reg := range builder.registrations {\n\t\treg.Unregister()\n\t}\n}\n\n// NewTelemetryBuilder provides a struct with methods to update all internal telemetry\n// for a component\nfunc NewTelemetryBuilder(settings component.TelemetrySettings, options ...TelemetryBuilderOption) (*TelemetryBuilder, error) {\n\tbuilder := TelemetryBuilder{}\n\tfor _, op := range options {\n\t\top.apply(&builder)\n\t}\n\tbuilder.meter = Meter(settings)\n\tvar err, errs error\n\tbuilder.ScraperErroredLogRecords, err = builder.meter.Int64Counter(\n\t\t\"otelcol_scraper_errored_log_records\",\n\t\tmetric.WithDescription(\"Number of log records that were unable to be scraped. [Alpha]\"),\n\t\tmetric.WithUnit(\"{datapoint}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ScraperErroredMetricPoints, err = builder.meter.Int64Counter(\n\t\t\"otelcol_scraper_errored_metric_points\",\n\t\tmetric.WithDescription(\"Number of metric points that were unable to be scraped. [Alpha]\"),\n\t\tmetric.WithUnit(\"{datapoint}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ScraperScrapedLogRecords, err = builder.meter.Int64Counter(\n\t\t\"otelcol_scraper_scraped_log_records\",\n\t\tmetric.WithDescription(\"Number of log records successfully scraped. [Alpha]\"),\n\t\tmetric.WithUnit(\"{datapoint}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ScraperScrapedMetricPoints, err = builder.meter.Int64Counter(\n\t\t\"otelcol_scraper_scraped_metric_points\",\n\t\tmetric.WithDescription(\"Number of metric points successfully scraped. [Alpha]\"),\n\t\tmetric.WithUnit(\"{datapoint}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\treturn &builder, errs\n}\n"
  },
  {
    "path": "scraper/scraperhelper/internal/metadata/generated_telemetry_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/metric\"\n\tembeddedmetric \"go.opentelemetry.io/otel/metric/embedded\"\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\t\"go.opentelemetry.io/otel/trace\"\n\tembeddedtrace \"go.opentelemetry.io/otel/trace/embedded\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\ntype mockMeter struct {\n\tnoopmetric.Meter\n\tname string\n}\ntype mockMeterProvider struct {\n\tembeddedmetric.MeterProvider\n}\n\nfunc (m mockMeterProvider) Meter(name string, opts ...metric.MeterOption) metric.Meter {\n\treturn mockMeter{name: name}\n}\n\ntype mockTracer struct {\n\tnooptrace.Tracer\n\tname string\n}\n\ntype mockTracerProvider struct {\n\tembeddedtrace.TracerProvider\n}\n\nfunc (m mockTracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer {\n\treturn mockTracer{name: name}\n}\n\nfunc TestProviders(t *testing.T) {\n\tset := component.TelemetrySettings{\n\t\tMeterProvider:  mockMeterProvider{},\n\t\tTracerProvider: mockTracerProvider{},\n\t}\n\n\tmeter := Meter(set)\n\tif m, ok := meter.(mockMeter); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/scraper/scraperhelper\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockMeter\")\n\t}\n\n\ttracer := Tracer(set)\n\tif m, ok := tracer.(mockTracer); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/scraper/scraperhelper\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockTracer\")\n\t}\n}\n\nfunc TestNewTelemetryBuilder(t *testing.T) {\n\tset := componenttest.NewNopTelemetrySettings()\n\tapplied := false\n\t_, err := NewTelemetryBuilder(set, telemetryBuilderOptionFunc(func(b *TelemetryBuilder) {\n\t\tapplied = true\n\t}))\n\trequire.NoError(t, err)\n\trequire.True(t, applied)\n}\n"
  },
  {
    "path": "scraper/scraperhelper/internal/metadatatest/generated_telemetrytest.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\nfunc AssertEqualScraperErroredLogRecords(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_scraper_errored_log_records\",\n\t\tDescription: \"Number of log records that were unable to be scraped. [Alpha]\",\n\t\tUnit:        \"{datapoint}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_scraper_errored_log_records\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualScraperErroredMetricPoints(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_scraper_errored_metric_points\",\n\t\tDescription: \"Number of metric points that were unable to be scraped. [Alpha]\",\n\t\tUnit:        \"{datapoint}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_scraper_errored_metric_points\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualScraperScrapedLogRecords(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_scraper_scraped_log_records\",\n\t\tDescription: \"Number of log records successfully scraped. [Alpha]\",\n\t\tUnit:        \"{datapoint}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_scraper_scraped_log_records\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualScraperScrapedMetricPoints(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_scraper_scraped_metric_points\",\n\t\tDescription: \"Number of metric points successfully scraped. [Alpha]\",\n\t\tUnit:        \"{datapoint}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_scraper_scraped_metric_points\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n"
  },
  {
    "path": "scraper/scraperhelper/internal/metadatatest/generated_telemetrytest_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/internal/metadata\"\n)\n\nfunc TestSetupTelemetry(t *testing.T) {\n\ttestTel := componenttest.NewTelemetry()\n\ttb, err := metadata.NewTelemetryBuilder(testTel.NewTelemetrySettings())\n\trequire.NoError(t, err)\n\tdefer tb.Shutdown()\n\ttb.ScraperErroredLogRecords.Add(context.Background(), 1)\n\ttb.ScraperErroredMetricPoints.Add(context.Background(), 1)\n\ttb.ScraperScrapedLogRecords.Add(context.Background(), 1)\n\ttb.ScraperScrapedMetricPoints.Add(context.Background(), 1)\n\tAssertEqualScraperErroredLogRecords(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualScraperErroredMetricPoints(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualScraperScrapedLogRecords(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualScraperScrapedMetricPoints(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\n\trequire.NoError(t, testTel.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "scraper/scraperhelper/internal/testhelper/helper.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// package testhelper provides functionality used in tests in scraperhelper and xscraperhelper.\n\npackage testhelper // import \"go.opentelemetry.io/collector/scraper/scraperhelper/internal/testhelper\"\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"go.opentelemetry.io/otel/codes\"\n\tsdktrace \"go.opentelemetry.io/otel/sdk/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\ntype TestInitialize struct {\n\tch  chan bool\n\terr error\n}\n\nfunc NewTestInitialize(ch chan bool, err error) *TestInitialize {\n\treturn &TestInitialize{\n\t\tch:  ch,\n\t\terr: err,\n\t}\n}\n\nfunc (ts *TestInitialize) Start(context.Context, component.Host) error {\n\tts.ch <- true\n\treturn ts.err\n}\n\ntype TestClose struct {\n\tch  chan bool\n\terr error\n}\n\nfunc NewTestClose(ch chan bool, err error) *TestClose {\n\treturn &TestClose{\n\t\tch:  ch,\n\t\terr: err,\n\t}\n}\n\nfunc (ts *TestClose) Shutdown(context.Context) error {\n\tts.ch <- true\n\treturn ts.err\n}\n\nfunc AssertChannelCalled(t *testing.T, ch chan bool, message string) {\n\tselect {\n\tcase <-ch:\n\tdefault:\n\t\tassert.Fail(t, message)\n\t}\n}\n\nfunc AssertChannelsCalled(t *testing.T, chs []chan bool, message string) {\n\tfor _, ic := range chs {\n\t\tAssertChannelCalled(t, ic, message)\n\t}\n}\n\nfunc AssertScraperSpan(t *testing.T, expectedErr error, spans []sdktrace.ReadOnlySpan, expectedSpanName string) {\n\texpectedStatusCode := codes.Unset\n\texpectedStatusMessage := \"\"\n\tif expectedErr != nil {\n\t\texpectedStatusCode = codes.Error\n\t\texpectedStatusMessage = expectedErr.Error()\n\t}\n\n\tscraperSpan := false\n\tfor _, span := range spans {\n\t\tif span.Name() == expectedSpanName {\n\t\t\tscraperSpan = true\n\t\t\tassert.Equal(t, expectedStatusCode, span.Status().Code)\n\t\t\tassert.Equal(t, expectedStatusMessage, span.Status().Description)\n\t\t\tbreak\n\t\t}\n\t}\n\tassert.True(t, scraperSpan)\n}\n"
  },
  {
    "path": "scraper/scraperhelper/metadata.yaml",
    "content": "type: scraperhelper\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  stability:\n    beta: [metrics, logs]\n\ntelemetry:\n  metrics:\n    scraper_errored_log_records:\n      enabled: true\n      stability: alpha\n      description: Number of log records that were unable to be scraped.\n      unit: \"{datapoint}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    scraper_errored_metric_points:\n      enabled: true\n      stability: alpha\n      description: Number of metric points that were unable to be scraped.\n      unit: \"{datapoint}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    scraper_scraped_log_records:\n      enabled: true\n      stability: alpha\n      description: Number of log records successfully scraped.\n      unit: \"{datapoint}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    scraper_scraped_metric_points:\n      enabled: true\n      stability: alpha\n      description: Number of metric points successfully scraped.\n      unit: \"{datapoint}\"\n      sum:\n        value_type: int\n        monotonic: true\n"
  },
  {
    "path": "scraper/scraperhelper/obs_logs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scraperhelper // import \"go.opentelemetry.io/collector/scraper/scraperhelper\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/codes\"\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/scraper\"\n\t\"go.opentelemetry.io/collector/scraper/scrapererror\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/internal/metadata\"\n)\n\nconst (\n\t// scrapedLogRecordsKey used to identify log records scraped by the\n\t// Collector.\n\tscrapedLogRecordsKey = \"scraped_log_records\"\n\t// erroredLogRecordsKey used to identify log records errored (i.e.\n\t// unable to be scraped) by the Collector.\n\terroredLogRecordsKey = \"errored_log_records\"\n)\n\nfunc wrapObsLogs(sc scraper.Logs, receiverID, scraperID component.ID, set component.TelemetrySettings) (scraper.Logs, error) {\n\ttelemetryBuilder, errBuilder := metadata.NewTelemetryBuilder(set)\n\tif errBuilder != nil {\n\t\treturn nil, errBuilder\n\t}\n\n\ttracer := metadata.Tracer(set)\n\tspanName := scraperKey + spanNameSep + scraperID.String() + spanNameSep + \"ScrapeLogs\"\n\totelAttrs := metric.WithAttributeSet(attribute.NewSet(\n\t\tattribute.String(receiverKey, receiverID.String()),\n\t\tattribute.String(scraperKey, scraperID.String()),\n\t))\n\n\tscraperFuncs := func(ctx context.Context) (plog.Logs, error) {\n\t\tctx, span := tracer.Start(ctx, spanName)\n\t\tdefer span.End()\n\n\t\tmd, err := sc.ScrapeLogs(ctx)\n\t\tnumScrapedLogs := 0\n\t\tnumErroredLogs := 0\n\t\tif err != nil {\n\t\t\tset.Logger.Error(\"Error scraping logs\", zap.Error(err))\n\t\t\tvar partialErr scrapererror.PartialScrapeError\n\t\t\tif errors.As(err, &partialErr) {\n\t\t\t\tnumErroredLogs = partialErr.Failed\n\t\t\t\tnumScrapedLogs = md.LogRecordCount()\n\t\t\t}\n\t\t} else {\n\t\t\tnumScrapedLogs = md.LogRecordCount()\n\t\t}\n\n\t\ttelemetryBuilder.ScraperScrapedLogRecords.Add(ctx, int64(numScrapedLogs), otelAttrs)\n\t\ttelemetryBuilder.ScraperErroredLogRecords.Add(ctx, int64(numErroredLogs), otelAttrs)\n\n\t\t// end span according to errors\n\t\tif span.IsRecording() {\n\t\t\tspan.SetAttributes(\n\t\t\t\tattribute.String(formatKey, pipeline.SignalMetrics.String()),\n\t\t\t\tattribute.Int64(scrapedLogRecordsKey, int64(numScrapedLogs)),\n\t\t\t\tattribute.Int64(erroredLogRecordsKey, int64(numErroredLogs)),\n\t\t\t)\n\n\t\t\tif err != nil {\n\t\t\t\tspan.SetStatus(codes.Error, err.Error())\n\t\t\t}\n\t\t}\n\n\t\treturn md, err\n\t}\n\n\treturn scraper.NewLogs(scraperFuncs, scraper.WithStart(sc.Start), scraper.WithShutdown(sc.Shutdown))\n}\n"
  },
  {
    "path": "scraper/scraperhelper/obs_logs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scraperhelper\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/codes\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/scraper\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/internal/controller\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/internal/metadatatest\"\n)\n\nfunc TestScrapeLogsDataOp(t *testing.T) {\n\ttel := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tel.Shutdown(context.Background())) })\n\n\tset := tel.NewTelemetrySettings()\n\n\tparentCtx, parentSpan := set.TracerProvider.Tracer(\"test\").Start(context.Background(), t.Name())\n\tdefer parentSpan.End()\n\n\tparams := []testParams{\n\t\t{items: 23, err: partialErrFake},\n\t\t{items: 29, err: errFake},\n\t\t{items: 15, err: nil},\n\t}\n\tfor i := range params {\n\t\tsm, err := scraper.NewLogs(func(context.Context) (plog.Logs, error) {\n\t\t\treturn testdata.GenerateLogs(params[i].items), params[i].err\n\t\t})\n\t\trequire.NoError(t, err)\n\t\tsf, err := wrapObsLogs(sm, receiverID, scraperID, set)\n\t\trequire.NoError(t, err)\n\t\t_, err = sf.ScrapeLogs(parentCtx)\n\t\trequire.ErrorIs(t, err, params[i].err)\n\t}\n\n\tspans := tel.SpanRecorder.Ended()\n\trequire.Len(t, spans, len(params))\n\n\tvar scrapedLogRecords, erroredLogRecords int\n\tfor i, span := range spans {\n\t\tassert.Equal(t, \"scraper/\"+scraperID.String()+\"/ScrapeLogs\", span.Name())\n\t\tswitch {\n\t\tcase params[i].err == nil:\n\t\t\tscrapedLogRecords += params[i].items\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(scrapedLogRecordsKey, int64(params[i].items)))\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(erroredLogRecordsKey, 0))\n\t\t\tassert.Equal(t, codes.Unset, span.Status().Code)\n\t\tcase errors.Is(params[i].err, errFake):\n\t\t\t// Since we get an error, we cannot record any metrics because we don't know if the returned plog.Logs is valid instance.\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(scrapedLogRecordsKey, 0))\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(erroredLogRecordsKey, 0))\n\t\t\tassert.Equal(t, codes.Error, span.Status().Code)\n\t\t\tassert.Equal(t, params[i].err.Error(), span.Status().Description)\n\t\tcase errors.Is(params[i].err, partialErrFake):\n\t\t\tscrapedLogRecords += params[i].items\n\t\t\terroredLogRecords += 2\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(scrapedLogRecordsKey, int64(params[i].items)))\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(erroredLogRecordsKey, 2))\n\t\t\tassert.Equal(t, codes.Error, span.Status().Code)\n\t\t\tassert.Equal(t, params[i].err.Error(), span.Status().Description)\n\t\tdefault:\n\t\t\tt.Fatalf(\"unexpected err param: %v\", params[i].err)\n\t\t}\n\t}\n\n\tcheckScraperLogs(t, tel, receiverID, scraperID, int64(scrapedLogRecords), int64(erroredLogRecords))\n}\n\nfunc TestCheckScraperLogs(t *testing.T) {\n\ttel := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tel.Shutdown(context.Background())) })\n\n\tsm, err := scraper.NewLogs(func(context.Context) (plog.Logs, error) {\n\t\treturn testdata.GenerateLogs(7), nil\n\t})\n\trequire.NoError(t, err)\n\tsf, err := wrapObsLogs(sm, receiverID, scraperID, tel.NewTelemetrySettings())\n\trequire.NoError(t, err)\n\t_, err = sf.ScrapeLogs(context.Background())\n\trequire.NoError(t, err)\n\n\tcheckScraperLogs(t, tel, receiverID, scraperID, 7, 0)\n}\n\nfunc TestScrapeLogsDataOp_LogsScraperID(t *testing.T) {\n\ttel := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tel.Shutdown(context.Background())) })\n\n\tcore, observedLogs := observer.New(zap.ErrorLevel)\n\ttelset := tel.NewTelemetrySettings()\n\ttelset.Logger = zap.New(core)\n\n\trSet := receiver.Settings{\n\t\tID:                receiverID,\n\t\tTelemetrySettings: telset,\n\t}\n\tset := controller.GetSettings(scraperID.Type(), rSet)\n\n\tsm, err := scraper.NewLogs(func(context.Context) (plog.Logs, error) {\n\t\treturn plog.NewLogs(), errFake\n\t})\n\trequire.NoError(t, err)\n\tsf, err := wrapObsLogs(sm, receiverID, scraperID, set.TelemetrySettings)\n\trequire.NoError(t, err)\n\t_, err = sf.ScrapeLogs(context.Background())\n\trequire.ErrorIs(t, err, errFake)\n\n\terrorLogs := observedLogs.FilterLevelExact(zap.ErrorLevel).All()\n\trequire.Len(t, errorLogs, 1)\n\tassert.Equal(t, \"Error scraping logs\", errorLogs[0].Message)\n\tassert.Equal(t, scraperID.String(), errorLogs[0].ContextMap()[\"scraper\"])\n\tassert.Equal(t, errFake.Error(), errorLogs[0].ContextMap()[\"error\"])\n}\n\nfunc checkScraperLogs(t *testing.T, tel *componenttest.Telemetry, receiver, scraper component.ID, scrapedLogRecords, erroredLogRecords int64) {\n\tmetadatatest.AssertEqualScraperScrapedLogRecords(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(receiverKey, receiver.String()),\n\t\t\t\t\tattribute.String(scraperKey, scraper.String())),\n\t\t\t\tValue: scrapedLogRecords,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\tmetadatatest.AssertEqualScraperErroredLogRecords(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(receiverKey, receiver.String()),\n\t\t\t\t\tattribute.String(scraperKey, scraper.String())),\n\t\t\t\tValue: erroredLogRecords,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n"
  },
  {
    "path": "scraper/scraperhelper/obs_metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scraperhelper // import \"go.opentelemetry.io/collector/scraper/scraperhelper\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/codes\"\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/scraper\"\n\t\"go.opentelemetry.io/collector/scraper/scrapererror\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/internal/metadata\"\n)\n\nconst (\n\t// scraperKey used to identify scrapers in metrics and traces.\n\tscraperKey = \"scraper\"\n\t// scrapedMetricPointsKey used to identify metric points scraped by the\n\t// Collector.\n\tscrapedMetricPointsKey = \"scraped_metric_points\"\n\t// erroredMetricPointsKey used to identify metric points errored (i.e.\n\t// unable to be scraped) by the Collector.\n\terroredMetricPointsKey = \"errored_metric_points\"\n\n\tspanNameSep = \"/\"\n\t// receiverKey used to identify receivers in metrics and traces.\n\treceiverKey = \"receiver\"\n\t// FormatKey used to identify the format of the data received.\n\tformatKey = \"format\"\n)\n\nfunc wrapObsMetrics(sc scraper.Metrics, receiverID, scraperID component.ID, set component.TelemetrySettings) (scraper.Metrics, error) {\n\ttelemetryBuilder, errBuilder := metadata.NewTelemetryBuilder(set)\n\tif errBuilder != nil {\n\t\treturn nil, errBuilder\n\t}\n\n\ttracer := metadata.Tracer(set)\n\tspanName := scraperKey + spanNameSep + scraperID.String() + spanNameSep + \"ScrapeMetrics\"\n\totelAttrs := metric.WithAttributeSet(attribute.NewSet(\n\t\tattribute.String(receiverKey, receiverID.String()),\n\t\tattribute.String(scraperKey, scraperID.String()),\n\t))\n\n\tscraperFuncs := func(ctx context.Context) (pmetric.Metrics, error) {\n\t\tctx, span := tracer.Start(ctx, spanName)\n\t\tdefer span.End()\n\n\t\tmd, err := sc.ScrapeMetrics(ctx)\n\t\tnumScrapedMetrics := 0\n\t\tnumErroredMetrics := 0\n\t\tif err != nil {\n\t\t\tset.Logger.Error(\"Error scraping metrics\", zap.Error(err))\n\t\t\tvar partialErr scrapererror.PartialScrapeError\n\t\t\tif errors.As(err, &partialErr) {\n\t\t\t\tnumErroredMetrics = partialErr.Failed\n\t\t\t\tnumScrapedMetrics = md.MetricCount()\n\t\t\t}\n\t\t} else {\n\t\t\tnumScrapedMetrics = md.MetricCount()\n\t\t}\n\n\t\ttelemetryBuilder.ScraperScrapedMetricPoints.Add(ctx, int64(numScrapedMetrics), otelAttrs)\n\t\ttelemetryBuilder.ScraperErroredMetricPoints.Add(ctx, int64(numErroredMetrics), otelAttrs)\n\n\t\t// end span according to errors\n\t\tif span.IsRecording() {\n\t\t\tspan.SetAttributes(\n\t\t\t\tattribute.String(formatKey, pipeline.SignalMetrics.String()),\n\t\t\t\tattribute.Int64(scrapedMetricPointsKey, int64(numScrapedMetrics)),\n\t\t\t\tattribute.Int64(erroredMetricPointsKey, int64(numErroredMetrics)),\n\t\t\t)\n\n\t\t\tif err != nil {\n\t\t\t\tspan.SetStatus(codes.Error, err.Error())\n\t\t\t}\n\t\t}\n\n\t\treturn md, err\n\t}\n\n\treturn scraper.NewMetrics(scraperFuncs, scraper.WithStart(sc.Start), scraper.WithShutdown(sc.Shutdown))\n}\n"
  },
  {
    "path": "scraper/scraperhelper/obs_metrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scraperhelper\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/codes\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/scraper\"\n\t\"go.opentelemetry.io/collector/scraper/scrapererror\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/internal/controller\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/internal/metadatatest\"\n)\n\nvar (\n\treceiverID = component.MustNewID(\"fakeReceiver\")\n\tscraperID  = component.MustNewID(\"fakeScraper\")\n\n\terrFake        = errors.New(\"errFake\")\n\tpartialErrFake = scrapererror.NewPartialScrapeError(errFake, 2)\n)\n\ntype testParams struct {\n\titems int\n\terr   error\n}\n\nfunc TestScrapeMetricsDataOp(t *testing.T) {\n\ttel := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tel.Shutdown(context.Background())) })\n\n\tset := tel.NewTelemetrySettings()\n\tparentCtx, parentSpan := set.TracerProvider.Tracer(\"test\").Start(context.Background(), t.Name())\n\tdefer parentSpan.End()\n\n\tparams := []testParams{\n\t\t{items: 23, err: partialErrFake},\n\t\t{items: 29, err: errFake},\n\t\t{items: 15, err: nil},\n\t}\n\tfor i := range params {\n\t\tsm, err := scraper.NewMetrics(func(context.Context) (pmetric.Metrics, error) {\n\t\t\treturn testdata.GenerateMetrics(params[i].items), params[i].err\n\t\t})\n\t\trequire.NoError(t, err)\n\t\tsf, err := wrapObsMetrics(sm, receiverID, scraperID, set)\n\t\trequire.NoError(t, err)\n\t\t_, err = sf.ScrapeMetrics(parentCtx)\n\t\trequire.ErrorIs(t, err, params[i].err)\n\t}\n\n\tspans := tel.SpanRecorder.Ended()\n\trequire.Len(t, spans, len(params))\n\n\tvar scrapedMetricPoints, erroredMetricPoints int\n\tfor i, span := range spans {\n\t\tassert.Equal(t, \"scraper/\"+scraperID.String()+\"/ScrapeMetrics\", span.Name())\n\t\tswitch {\n\t\tcase params[i].err == nil:\n\t\t\tscrapedMetricPoints += params[i].items\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(scrapedMetricPointsKey, int64(params[i].items)))\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(erroredMetricPointsKey, 0))\n\t\t\tassert.Equal(t, codes.Unset, span.Status().Code)\n\t\tcase errors.Is(params[i].err, errFake):\n\t\t\t// Since we get an error, we cannot record any metrics because we don't know if the returned pmetric.Metrics is valid instance.\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(scrapedMetricPointsKey, 0))\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(erroredMetricPointsKey, 0))\n\t\t\tassert.Equal(t, codes.Error, span.Status().Code)\n\t\t\tassert.Equal(t, params[i].err.Error(), span.Status().Description)\n\t\tcase errors.Is(params[i].err, partialErrFake):\n\t\t\tscrapedMetricPoints += params[i].items\n\t\t\terroredMetricPoints += 2\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(scrapedMetricPointsKey, int64(params[i].items)))\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(erroredMetricPointsKey, 2))\n\t\t\tassert.Equal(t, codes.Error, span.Status().Code)\n\t\t\tassert.Equal(t, params[i].err.Error(), span.Status().Description)\n\t\tdefault:\n\t\t\tt.Fatalf(\"unexpected err param: %v\", params[i].err)\n\t\t}\n\t}\n\n\tcheckScraperMetrics(t, tel, receiverID, scraperID, int64(scrapedMetricPoints), int64(erroredMetricPoints))\n}\n\nfunc TestCheckScraperMetrics(t *testing.T) {\n\ttel := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tel.Shutdown(context.Background())) })\n\n\tsm, err := scraper.NewMetrics(func(context.Context) (pmetric.Metrics, error) {\n\t\treturn testdata.GenerateMetrics(7), nil\n\t})\n\trequire.NoError(t, err)\n\tsf, err := wrapObsMetrics(sm, receiverID, scraperID, tel.NewTelemetrySettings())\n\trequire.NoError(t, err)\n\t_, err = sf.ScrapeMetrics(context.Background())\n\trequire.NoError(t, err)\n\n\tcheckScraperMetrics(t, tel, receiverID, scraperID, 7, 0)\n}\n\nfunc TestScrapeMetricsDataOp_LogsScraperID(t *testing.T) {\n\ttel := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tel.Shutdown(context.Background())) })\n\n\tcore, observedLogs := observer.New(zap.ErrorLevel)\n\ttelset := tel.NewTelemetrySettings()\n\ttelset.Logger = zap.New(core)\n\n\trSet := receiver.Settings{\n\t\tID:                receiverID,\n\t\tTelemetrySettings: telset,\n\t}\n\tset := controller.GetSettings(scraperID.Type(), rSet)\n\n\tsm, err := scraper.NewMetrics(func(context.Context) (pmetric.Metrics, error) {\n\t\treturn pmetric.NewMetrics(), errFake\n\t})\n\trequire.NoError(t, err)\n\tsf, err := wrapObsMetrics(sm, receiverID, scraperID, set.TelemetrySettings)\n\trequire.NoError(t, err)\n\t_, err = sf.ScrapeMetrics(context.Background())\n\trequire.ErrorIs(t, err, errFake)\n\n\terrorLogs := observedLogs.FilterLevelExact(zap.ErrorLevel).All()\n\trequire.Len(t, errorLogs, 1)\n\tassert.Equal(t, \"Error scraping metrics\", errorLogs[0].Message)\n\tassert.Equal(t, scraperID.String(), errorLogs[0].ContextMap()[\"scraper\"])\n\tassert.Equal(t, errFake.Error(), errorLogs[0].ContextMap()[\"error\"])\n}\n\nfunc checkScraperMetrics(t *testing.T, tt *componenttest.Telemetry, receiver, scraper component.ID, scrapedMetricPoints, erroredMetricPoints int64) {\n\tmetadatatest.AssertEqualScraperScrapedMetricPoints(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(receiverKey, receiver.String()),\n\t\t\t\t\tattribute.String(scraperKey, scraper.String())),\n\t\t\t\tValue: scrapedMetricPoints,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\tmetadatatest.AssertEqualScraperErroredMetricPoints(t, tt,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(receiverKey, receiver.String()),\n\t\t\t\t\tattribute.String(scraperKey, scraper.String())),\n\t\t\t\tValue: erroredMetricPoints,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n"
  },
  {
    "path": "scraper/scraperhelper/xscraperhelper/Makefile",
    "content": "include ../../../Makefile.Common\n"
  },
  {
    "path": "scraper/scraperhelper/xscraperhelper/controller.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package xscraperhelper provides utilities for scrapers.\npackage xscraperhelper // import \"go.opentelemetry.io/collector/scraper/scraperhelper/xscraperhelper\"\n\nimport (\n\t\"context\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n\t\"go.opentelemetry.io/collector/scraper\"\n\t\"go.opentelemetry.io/collector/scraper/scrapererror\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/internal/controller\"\n\t\"go.opentelemetry.io/collector/scraper/xscraper\"\n)\n\nconst (\n\t// scraperKey used to identify scrapers in metrics and traces.\n\tscraperKey  = \"scraper\"\n\tspanNameSep = \"/\"\n\t// receiverKey used to identify receivers in metrics and traces.\n\treceiverKey = \"receiver\"\n\t// FormatKey used to identify the format of the data received.\n\tformatKey = \"format\"\n)\n\ntype factoryWithConfig struct {\n\tf   xscraper.Factory\n\tcfg component.Config\n}\n\ntype controllerOptions struct {\n\ttickerCh            <-chan time.Time\n\tfactoriesWithConfig []factoryWithConfig\n}\n\n// ControllerOption apply changes to internal options.\ntype ControllerOption interface {\n\tapply(*controllerOptions)\n}\n\ntype optionFunc func(*controllerOptions)\n\nfunc (of optionFunc) apply(e *controllerOptions) {\n\tof(e)\n}\n\n// AddProfilesScraper configures the xscraper.Profiles to be called with the specified options,\n// and at the specified collection interval.\n//\n// Observability information will be reported, and the scraped profiles\n// will be passed to the next consumer.\nfunc AddProfilesScraper(t component.Type, sc xscraper.Profiles) ControllerOption {\n\tf := xscraper.NewFactory(t, nil,\n\t\txscraper.WithProfiles(func(context.Context, scraper.Settings, component.Config) (xscraper.Profiles, error) {\n\t\t\treturn sc, nil\n\t\t}, component.StabilityLevelDevelopment))\n\treturn AddFactoryWithConfig(f, nil)\n}\n\n// AddFactoryWithConfig configures the scraper.Factory and associated config that\n// will be used to create a new scraper. The created scraper will be called with\n// the specified options, and at the specified collection interval.\n//\n// Observability information will be reported, and the scraped metrics\n// will be passed to the next consumer.\nfunc AddFactoryWithConfig(f xscraper.Factory, cfg component.Config) ControllerOption {\n\treturn optionFunc(func(o *controllerOptions) {\n\t\to.factoriesWithConfig = append(o.factoriesWithConfig, factoryWithConfig{f: f, cfg: cfg})\n\t})\n}\n\n// WithTickerChannel allows you to override the scraper controller's ticker\n// channel to specify when scrape is called. This is only expected to be\n// used by tests.\nfunc WithTickerChannel(tickerCh <-chan time.Time) ControllerOption {\n\treturn optionFunc(func(o *controllerOptions) {\n\t\to.tickerCh = tickerCh\n\t})\n}\n\n// NewProfilesController creates a receiver.Profiles with the configured options, that can control multiple xscraper.Profiles.\nfunc NewProfilesController(cfg *scraperhelper.ControllerConfig,\n\trSet receiver.Settings,\n\tnextConsumer xconsumer.Profiles,\n\toptions ...ControllerOption,\n) (xreceiver.Profiles, error) {\n\tco := getOptions(options)\n\tscrapers := make([]xscraper.Profiles, 0, len(co.factoriesWithConfig))\n\tfor _, fwc := range co.factoriesWithConfig {\n\t\tset := controller.GetSettings(fwc.f.Type(), rSet)\n\t\ts, err := fwc.f.CreateProfiles(context.Background(), set, fwc.cfg)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\ts, err = wrapObsProfiles(s, rSet.ID, set.ID, set.TelemetrySettings)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tscrapers = append(scrapers, s)\n\t}\n\treturn controller.NewController[xscraper.Profiles](\n\t\tcfg, rSet, scrapers, func(c *controller.Controller[xscraper.Profiles]) { scrapeProfiles(c, nextConsumer) }, co.tickerCh)\n}\n\nfunc getOptions(options []ControllerOption) controllerOptions {\n\tco := controllerOptions{}\n\tfor _, op := range options {\n\t\top.apply(&co)\n\t}\n\treturn co\n}\n\nfunc scrapeProfiles(c *controller.Controller[xscraper.Profiles], nextConsumer xconsumer.Profiles) {\n\tctx, done := controller.WithScrapeContext(c.Timeout)\n\tdefer done()\n\n\tprofiles := pprofile.NewProfiles()\n\tfor i := range c.Scrapers {\n\t\tmd, err := c.Scrapers[i].ScrapeProfiles(ctx)\n\t\tif err != nil && !scrapererror.IsPartialScrapeError(err) {\n\t\t\tcontinue\n\t\t}\n\t\tmd.ResourceProfiles().MoveAndAppendTo(profiles.ResourceProfiles())\n\t}\n\n\t// TODO: Add proper receiver observability for profiles when receiverhelper supports it\n\t// For now, we skip the obs report and just consume the profiles directly\n\t_ = nextConsumer.ConsumeProfiles(ctx, profiles)\n}\n"
  },
  {
    "path": "scraper/scraperhelper/xscraperhelper/controller_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package xscraperhelper provides utilities for scrapers.\npackage xscraperhelper // import \"go.opentelemetry.io/collector/scraper/scraperhelper/xscraperhelper\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\t\"go.uber.org/multierr\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n\t\"go.opentelemetry.io/collector/scraper\"\n\t\"go.opentelemetry.io/collector/scraper/scrapererror\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/internal/testhelper\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/xscraperhelper/internal/metadatatest\"\n\t\"go.opentelemetry.io/collector/scraper/xscraper\"\n)\n\ntype testScrape struct {\n\tch                chan int\n\ttimesScrapeCalled int\n\terr               error\n}\n\nfunc (ts *testScrape) scrapeProfiles(context.Context) (pprofile.Profiles, error) {\n\tts.timesScrapeCalled++\n\tts.ch <- ts.timesScrapeCalled\n\n\tif ts.err != nil {\n\t\treturn pprofile.Profiles{}, ts.err\n\t}\n\n\tmd := pprofile.NewProfiles()\n\tprofile := md.ResourceProfiles().AppendEmpty().ScopeProfiles().AppendEmpty().Profiles().AppendEmpty()\n\tprofile.Samples().AppendEmpty()\n\treturn md, nil\n}\n\nfunc newTestNoDelaySettings() *scraperhelper.ControllerConfig {\n\treturn &scraperhelper.ControllerConfig{\n\t\tCollectionInterval: time.Second,\n\t\tInitialDelay:       0,\n\t}\n}\n\ntype scraperTestCase struct {\n\tname string\n\n\tscrapers                  int\n\tscraperControllerSettings *scraperhelper.ControllerConfig\n\tscrapeErr                 error\n\texpectScraped             bool\n\n\tinitialize    bool\n\tclose         bool\n\tinitializeErr error\n\tcloseErr      error\n}\n\nfunc TestProfilesScrapeController(t *testing.T) {\n\ttestCases := []scraperTestCase{\n\t\t{\n\t\t\tname: \"NoScrapers\",\n\t\t},\n\t\t{\n\t\t\tname:          \"AddProfilesScrapersWithCollectionInterval\",\n\t\t\tscrapers:      2,\n\t\t\texpectScraped: true,\n\t\t},\n\t\t{\n\t\t\tname:      \"AddProfilesScrapers_ScrapeError\",\n\t\t\tscrapers:  2,\n\t\t\tscrapeErr: errors.New(\"err1\"),\n\t\t},\n\t\t{\n\t\t\tname:          \"AddProfilesScrapersWithInitializeAndClose\",\n\t\t\tscrapers:      2,\n\t\t\tinitialize:    true,\n\t\t\texpectScraped: true,\n\t\t\tclose:         true,\n\t\t},\n\t\t{\n\t\t\tname:          \"AddProfilesScrapersWithInitializeAndCloseErrors\",\n\t\t\tscrapers:      2,\n\t\t\tinitialize:    true,\n\t\t\tclose:         true,\n\t\t\tinitializeErr: errors.New(\"err1\"),\n\t\t\tcloseErr:      errors.New(\"err2\"),\n\t\t},\n\t}\n\n\tfor _, test := range testCases {\n\t\tt.Run(test.name, func(t *testing.T) {\n\t\t\treceiverID := component.MustNewID(\"receiver\")\n\t\t\ttel := componenttest.NewTelemetry()\n\t\t\tt.Cleanup(func() { require.NoError(t, tel.Shutdown(context.Background())) })\n\n\t\t\tset := tel.NewTelemetrySettings()\n\t\t\t_, parentSpan := set.TracerProvider.Tracer(\"test\").Start(context.Background(), t.Name())\n\t\t\tdefer parentSpan.End()\n\n\t\t\tinitializeChs := make([]chan bool, test.scrapers)\n\t\t\tscrapeProfilesChs := make([]chan int, test.scrapers)\n\t\t\tcloseChs := make([]chan bool, test.scrapers)\n\t\t\toptions := configureProfilesOptions(t, test, initializeChs, scrapeProfilesChs, closeChs)\n\n\t\t\ttickerCh := make(chan time.Time)\n\t\t\toptions = append(options, WithTickerChannel(tickerCh))\n\n\t\t\tsink := new(consumertest.ProfilesSink)\n\t\t\tcfg := newTestNoDelaySettings()\n\t\t\tif test.scraperControllerSettings != nil {\n\t\t\t\tcfg = test.scraperControllerSettings\n\t\t\t}\n\n\t\t\tmr, err := NewProfilesController(cfg, receiver.Settings{ID: receiverID, TelemetrySettings: set, BuildInfo: component.NewDefaultBuildInfo()}, sink, options...)\n\t\t\trequire.NoError(t, err)\n\n\t\t\terr = mr.Start(context.Background(), componenttest.NewNopHost())\n\t\t\texpectedStartErr := getExpectedStartErr(test)\n\t\t\tif expectedStartErr != nil {\n\t\t\t\tassert.Equal(t, expectedStartErr, err)\n\t\t\t} else if test.initialize {\n\t\t\t\ttesthelper.AssertChannelsCalled(t, initializeChs, \"start was not called\")\n\t\t\t}\n\n\t\t\tconst iterations = 5\n\n\t\t\tif test.expectScraped || test.scrapeErr != nil {\n\t\t\t\t// validate that scrape is called at least N times for each configured scraper\n\t\t\t\tfor _, ch := range scrapeProfilesChs {\n\t\t\t\t\t<-ch\n\t\t\t\t}\n\t\t\t\t// Consume the initial scrapes on start\n\t\t\t\tfor range iterations {\n\t\t\t\t\ttickerCh <- time.Now()\n\n\t\t\t\t\tfor _, ch := range scrapeProfilesChs {\n\t\t\t\t\t\t<-ch\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// wait until all calls to scrape have completed\n\t\t\t\tif test.scrapeErr == nil {\n\t\t\t\t\trequire.Eventually(t, func() bool {\n\t\t\t\t\t\treturn sink.SampleCount() == (1+iterations)*(test.scrapers)\n\t\t\t\t\t}, time.Second, time.Millisecond)\n\t\t\t\t}\n\n\t\t\t\tif test.expectScraped {\n\t\t\t\t\tassert.GreaterOrEqual(t, sink.SampleCount(), iterations)\n\t\t\t\t}\n\n\t\t\t\tspans := tel.SpanRecorder.Ended()\n\t\t\t\ttesthelper.AssertScraperSpan(t, test.scrapeErr, spans, \"scraper/scraper/ScrapeProfiles\")\n\t\t\t\tassertProfilesScraperObsMetrics(t, tel, receiverID, component.MustNewID(\"scraper\"), test.scrapeErr, sink)\n\t\t\t}\n\n\t\t\terr = mr.Shutdown(context.Background())\n\t\t\texpectedShutdownErr := getExpectedShutdownErr(test)\n\t\t\tif expectedShutdownErr != nil {\n\t\t\t\tassert.EqualError(t, err, expectedShutdownErr.Error())\n\t\t\t} else if test.close {\n\t\t\t\ttesthelper.AssertChannelsCalled(t, closeChs, \"shutdown was not called\")\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc getExpectedStartErr(test scraperTestCase) error {\n\treturn test.initializeErr\n}\n\nfunc getExpectedShutdownErr(test scraperTestCase) error {\n\tvar errs []error\n\n\tif test.closeErr != nil {\n\t\tfor i := 0; i < test.scrapers; i++ {\n\t\t\terrs = append(errs, test.closeErr)\n\t\t}\n\t}\n\n\treturn multierr.Combine(errs...)\n}\n\nfunc configureProfilesOptions(t *testing.T, test scraperTestCase, initializeChs []chan bool, scrapeProfilesChs []chan int, closeChs []chan bool) []ControllerOption {\n\tvar profilesOptions []ControllerOption\n\n\tfor i := 0; i < test.scrapers; i++ {\n\t\tscrapeProfilesChs[i] = make(chan int)\n\t\tts := &testScrape{ch: scrapeProfilesChs[i], err: test.scrapeErr}\n\n\t\tvar xscraperOptions []xscraper.Option\n\t\tif test.initialize {\n\t\t\tinitializeChs[i] = make(chan bool, 1)\n\t\t\tti := testhelper.NewTestInitialize(initializeChs[i], test.initializeErr)\n\t\t\txscraperOptions = append(xscraperOptions, xscraper.WithStart(ti.Start))\n\t\t}\n\t\tif test.close {\n\t\t\tcloseChs[i] = make(chan bool, 1)\n\t\t\ttc := testhelper.NewTestClose(closeChs[i], test.closeErr)\n\t\t\txscraperOptions = append(xscraperOptions, xscraper.WithShutdown(tc.Shutdown))\n\t\t}\n\n\t\tscp, err := xscraper.NewProfiles(ts.scrapeProfiles, xscraperOptions...)\n\t\trequire.NoError(t, err)\n\n\t\tprofilesOptions = append(profilesOptions, AddProfilesScraper(component.MustNewType(\"scraper\"), scp))\n\t}\n\n\treturn profilesOptions\n}\n\nfunc TestSingleProfilesScraperPerInterval(t *testing.T) {\n\tscrapeCh := make(chan int, 10)\n\tts := &testScrape{ch: scrapeCh}\n\n\tcfg := newTestNoDelaySettings()\n\n\ttickerCh := make(chan time.Time)\n\n\tscp, err := xscraper.NewProfiles(ts.scrapeProfiles)\n\trequire.NoError(t, err)\n\n\trecv, err := NewProfilesController(\n\t\tcfg,\n\t\treceivertest.NewNopSettings(receivertest.NopType),\n\t\tnew(consumertest.ProfilesSink),\n\t\tAddProfilesScraper(component.MustNewType(\"scraper\"), scp),\n\t\tWithTickerChannel(tickerCh),\n\t)\n\trequire.NoError(t, err)\n\n\trequire.NoError(t, recv.Start(context.Background(), componenttest.NewNopHost()))\n\tdefer func() { require.NoError(t, recv.Shutdown(context.Background())) }()\n\n\ttickerCh <- time.Now()\n\n\tassert.Eventually(\n\t\tt,\n\t\tfunc() bool {\n\t\t\treturn <-scrapeCh == 2\n\t\t},\n\t\t300*time.Millisecond,\n\t\t100*time.Millisecond,\n\t\t\"Make sure the scraper channel is called twice\",\n\t)\n\n\tselect {\n\tcase <-scrapeCh:\n\t\tassert.Fail(t, \"Scrape was called more than twice\")\n\tcase <-time.After(100 * time.Millisecond):\n\t\treturn\n\t}\n}\n\nfunc TestProfilesScraperControllerStartsOnInit(t *testing.T) {\n\tt.Parallel()\n\n\tts := &testScrape{\n\t\tch: make(chan int, 1),\n\t}\n\n\tscp, err := xscraper.NewProfiles(ts.scrapeProfiles)\n\trequire.NoError(t, err, \"Must not error when creating scraper\")\n\n\tr, err := NewProfilesController(\n\t\t&scraperhelper.ControllerConfig{\n\t\t\tCollectionInterval: time.Hour,\n\t\t\tInitialDelay:       0,\n\t\t},\n\t\treceivertest.NewNopSettings(receivertest.NopType),\n\t\tnew(consumertest.ProfilesSink),\n\t\tAddProfilesScraper(component.MustNewType(\"scraper\"), scp),\n\t)\n\trequire.NoError(t, err, \"Must not error when creating scrape controller\")\n\n\tassert.NoError(t, r.Start(context.Background(), componenttest.NewNopHost()), \"Must not error on start\")\n\t<-time.After(500 * time.Nanosecond)\n\trequire.NoError(t, r.Shutdown(context.Background()), \"Must not have errored on shutdown\")\n\tassert.Equal(t, 1, ts.timesScrapeCalled, \"Must have been called as soon as the controller started\")\n}\n\nfunc TestProfilesScraperControllerInitialDelay(t *testing.T) {\n\tif testing.Short() {\n\t\tt.Skip(\"This requires real time to pass, skipping\")\n\t\treturn\n\t}\n\n\tt.Parallel()\n\n\tvar (\n\t\telapsed = make(chan time.Time, 1)\n\t\tcfg     = scraperhelper.ControllerConfig{\n\t\t\tCollectionInterval: time.Second,\n\t\t\tInitialDelay:       300 * time.Millisecond,\n\t\t}\n\t)\n\n\tscp, err := xscraper.NewProfiles(func(context.Context) (pprofile.Profiles, error) {\n\t\telapsed <- time.Now()\n\t\treturn pprofile.NewProfiles(), nil\n\t})\n\trequire.NoError(t, err, \"Must not error when creating scraper\")\n\n\tr, err := NewProfilesController(\n\t\t&cfg,\n\t\treceivertest.NewNopSettings(receivertest.NopType),\n\t\tnew(consumertest.ProfilesSink),\n\t\tAddProfilesScraper(component.MustNewType(\"scraper\"), scp),\n\t)\n\trequire.NoError(t, err, \"Must not error when creating receiver\")\n\n\tt0 := time.Now()\n\trequire.NoError(t, r.Start(context.Background(), componenttest.NewNopHost()), \"Must not error when starting\")\n\tt1 := <-elapsed\n\n\tassert.GreaterOrEqual(t, t1.Sub(t0), 300*time.Millisecond, \"Must have had 300ms pass as defined by initial delay\")\n\n\tassert.NoError(t, r.Shutdown(context.Background()), \"Must not error closing down\")\n}\n\nfunc TestProfilesScraperShutdownBeforeScrapeCanStart(t *testing.T) {\n\tcfg := scraperhelper.ControllerConfig{\n\t\tCollectionInterval: time.Second,\n\t\tInitialDelay:       5 * time.Second,\n\t}\n\n\tscp, err := xscraper.NewProfiles(func(context.Context) (pprofile.Profiles, error) {\n\t\t// make the scraper wait for long enough it would disrupt a shutdown.\n\t\ttime.Sleep(30 * time.Second)\n\t\treturn pprofile.NewProfiles(), nil\n\t})\n\trequire.NoError(t, err, \"Must not error when creating scraper\")\n\n\tr, err := NewProfilesController(\n\t\t&cfg,\n\t\treceivertest.NewNopSettings(receivertest.NopType),\n\t\tnew(consumertest.ProfilesSink),\n\t\tAddProfilesScraper(component.MustNewType(\"scraper\"), scp),\n\t)\n\trequire.NoError(t, err, \"Must not error when creating receiver\")\n\trequire.NoError(t, r.Start(context.Background(), componenttest.NewNopHost()))\n\tshutdown := make(chan struct{}, 1)\n\tgo func() {\n\t\tassert.NoError(t, r.Shutdown(context.Background()))\n\t\tclose(shutdown)\n\t}()\n\ttimer := time.NewTicker(10 * time.Second)\n\tselect {\n\tcase <-timer.C:\n\t\trequire.Fail(t, \"shutdown should not wait for scraping\")\n\tcase <-shutdown:\n\t}\n}\n\nfunc assertProfilesScraperObsMetrics(t *testing.T, tel *componenttest.Telemetry, receiver, scraper component.ID, expectedErr error, sink *consumertest.ProfilesSink) {\n\tsampleCounts := 0\n\tfor _, md := range sink.AllProfiles() {\n\t\tsampleCounts += md.SampleCount()\n\t}\n\n\texpectedScraped := int64(sink.SampleCount())\n\texpectedErrored := int64(0)\n\tif expectedErr != nil {\n\t\tvar partialError scrapererror.PartialScrapeError\n\t\tif errors.As(expectedErr, &partialError) {\n\t\t\texpectedErrored = int64(partialError.Failed)\n\t\t} else {\n\t\t\texpectedScraped = int64(0)\n\t\t\texpectedErrored = int64(sink.SampleCount())\n\t\t}\n\t}\n\n\tmetadatatest.AssertEqualScraperScrapedProfileRecords(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(receiverKey, receiver.String()),\n\t\t\t\t\tattribute.String(scraperKey, scraper.String())),\n\t\t\t\tValue: expectedScraped,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\tmetadatatest.AssertEqualScraperErroredProfileRecords(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(receiverKey, receiver.String()),\n\t\t\t\t\tattribute.String(scraperKey, scraper.String())),\n\t\t\t\tValue: expectedErrored,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n\n// TestNewProfilesControllerCreateError tests that NewProfilesController returns an error\n// when the scraper factory's CreateProfiles method fails.\nfunc TestNewProfilesControllerCreateError(t *testing.T) {\n\texpectedErr := errors.New(\"create profiles error\")\n\tf := xscraper.NewFactory(component.MustNewType(\"scraper\"), nil,\n\t\txscraper.WithProfiles(func(context.Context, scraper.Settings, component.Config) (xscraper.Profiles, error) {\n\t\t\treturn nil, expectedErr\n\t\t}, component.StabilityLevelDevelopment))\n\n\tcfg := newTestNoDelaySettings()\n\t_, err := NewProfilesController(\n\t\tcfg,\n\t\treceivertest.NewNopSettings(receivertest.NopType),\n\t\tnew(consumertest.ProfilesSink),\n\t\tAddFactoryWithConfig(f, nil),\n\t)\n\n\trequire.Error(t, err)\n\tassert.Equal(t, expectedErr, err)\n}\n\n// errorMeter is a meter that returns errors when creating instruments.\ntype errorMeter struct {\n\tmetric.Meter\n}\n\nfunc (errorMeter) Int64Counter(string, ...metric.Int64CounterOption) (metric.Int64Counter, error) {\n\treturn nil, errors.New(\"counter creation error\")\n}\n\n// errorMeterProvider provides errorMeter instances.\ntype errorMeterProvider struct {\n\tmetric.MeterProvider\n}\n\nfunc (errorMeterProvider) Meter(string, ...metric.MeterOption) metric.Meter {\n\treturn errorMeter{}\n}\n\n// TestNewProfilesControllerTelemetryError tests that NewProfilesController returns an error\n// when telemetry builder creation fails.\nfunc TestNewProfilesControllerTelemetryError(t *testing.T) {\n\t// Create a scraper that works\n\tscp, err := xscraper.NewProfiles(func(context.Context) (pprofile.Profiles, error) {\n\t\treturn pprofile.NewProfiles(), nil\n\t})\n\trequire.NoError(t, err)\n\n\tf := xscraper.NewFactory(component.MustNewType(\"scraper\"), nil,\n\t\txscraper.WithProfiles(func(context.Context, scraper.Settings, component.Config) (xscraper.Profiles, error) {\n\t\t\treturn scp, nil\n\t\t}, component.StabilityLevelDevelopment))\n\n\t// Create telemetry settings with a meter provider that fails\n\tset := componenttest.NewNopTelemetrySettings()\n\tset.MeterProvider = errorMeterProvider{}\n\n\tcfg := newTestNoDelaySettings()\n\t_, err = NewProfilesController(\n\t\tcfg,\n\t\treceiver.Settings{\n\t\t\tID:                component.MustNewID(\"receiver\"),\n\t\t\tTelemetrySettings: set,\n\t\t\tBuildInfo:         component.NewDefaultBuildInfo(),\n\t\t},\n\t\tnew(consumertest.ProfilesSink),\n\t\tAddFactoryWithConfig(f, nil),\n\t)\n\n\t// The error should be from wrapObsProfiles failing due to telemetry builder creation\n\trequire.Error(t, err)\n\tassert.Contains(t, err.Error(), \"counter creation error\")\n}\n"
  },
  {
    "path": "scraper/scraperhelper/xscraperhelper/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\n// Package xscraperhelper provides utilities for scrapers.\npackage xscraperhelper // import \"go.opentelemetry.io/collector/scraper/scraperhelper/xscraperhelper\"\n"
  },
  {
    "path": "scraper/scraperhelper/xscraperhelper/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# xscraperhelper\n\n## Internal Telemetry\n\nThe following telemetry is emitted by this component.\n\n### otelcol_scraper_errored_profile_records\n\nNumber of profile records that were unable to be scraped.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {datapoint} | Sum | Int | true | Alpha |\n\n### otelcol_scraper_scraped_profile_records\n\nNumber of profile records successfully scraped.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {datapoint} | Sum | Int | true | Alpha |\n"
  },
  {
    "path": "scraper/scraperhelper/xscraperhelper/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage xscraperhelper\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "scraper/scraperhelper/xscraperhelper/go.mod",
    "content": "module go.opentelemetry.io/collector/scraper/scraperhelper/xscraperhelper\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0\n\tgo.opentelemetry.io/collector/receiver v1.54.0\n\tgo.opentelemetry.io/collector/receiver/receivertest v0.148.0\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0\n\tgo.opentelemetry.io/collector/scraper v0.148.0\n\tgo.opentelemetry.io/collector/scraper/scraperhelper v0.148.0\n\tgo.opentelemetry.io/collector/scraper/xscraper v0.148.0\n\tgo.opentelemetry.io/otel v1.42.0\n\tgo.opentelemetry.io/otel/metric v1.42.0\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0\n\tgo.opentelemetry.io/otel/trace v1.42.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/multierr v1.11.0\n\tgo.uber.org/zap v1.27.1\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/consumer v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/receiver/receiverhelper v0.148.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/scraper/scraperhelper => ..\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../../internal/testutil\n\nreplace go.opentelemetry.io/collector/featuregate => ../../../featuregate\n\nreplace go.opentelemetry.io/collector/receiver/receiverhelper => ../../../receiver/receiverhelper\n\nreplace go.opentelemetry.io/collector/pdata => ../../../pdata\n\nreplace go.opentelemetry.io/collector/scraper/xscraper => ../../xscraper\n\nreplace go.opentelemetry.io/collector/scraper => ../..\n\nreplace go.opentelemetry.io/collector/receiver => ../../../receiver\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/pipeline => ../../../pipeline\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../../../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../../component/componenttest\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/consumer => ../../../consumer\n\nreplace go.opentelemetry.io/collector/component => ../../../component\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../../../receiver/receivertest\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../../internal/componentalias\n"
  },
  {
    "path": "scraper/scraperhelper/xscraperhelper/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "scraper/scraperhelper/xscraperhelper/internal/metadata/generated_telemetry.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"errors\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc Meter(settings component.TelemetrySettings) metric.Meter {\n\treturn settings.MeterProvider.Meter(\"go.opentelemetry.io/collector/scraper/scraperhelper/xscraperhelper\")\n}\n\nfunc Tracer(settings component.TelemetrySettings) trace.Tracer {\n\treturn settings.TracerProvider.Tracer(\"go.opentelemetry.io/collector/scraper/scraperhelper/xscraperhelper\")\n}\n\n// TelemetryBuilder provides an interface for components to report telemetry\n// as defined in metadata and user config.\ntype TelemetryBuilder struct {\n\tmeter                        metric.Meter\n\tmu                           sync.Mutex\n\tregistrations                []metric.Registration\n\tScraperErroredProfileRecords metric.Int64Counter\n\tScraperScrapedProfileRecords metric.Int64Counter\n}\n\n// TelemetryBuilderOption applies changes to default builder.\ntype TelemetryBuilderOption interface {\n\tapply(*TelemetryBuilder)\n}\n\ntype telemetryBuilderOptionFunc func(mb *TelemetryBuilder)\n\nfunc (tbof telemetryBuilderOptionFunc) apply(mb *TelemetryBuilder) {\n\ttbof(mb)\n}\n\n// Shutdown unregister all registered callbacks for async instruments.\nfunc (builder *TelemetryBuilder) Shutdown() {\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tfor _, reg := range builder.registrations {\n\t\treg.Unregister()\n\t}\n}\n\n// NewTelemetryBuilder provides a struct with methods to update all internal telemetry\n// for a component\nfunc NewTelemetryBuilder(settings component.TelemetrySettings, options ...TelemetryBuilderOption) (*TelemetryBuilder, error) {\n\tbuilder := TelemetryBuilder{}\n\tfor _, op := range options {\n\t\top.apply(&builder)\n\t}\n\tbuilder.meter = Meter(settings)\n\tvar err, errs error\n\tbuilder.ScraperErroredProfileRecords, err = builder.meter.Int64Counter(\n\t\t\"otelcol_scraper_errored_profile_records\",\n\t\tmetric.WithDescription(\"Number of profile records that were unable to be scraped. [Alpha]\"),\n\t\tmetric.WithUnit(\"{datapoint}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ScraperScrapedProfileRecords, err = builder.meter.Int64Counter(\n\t\t\"otelcol_scraper_scraped_profile_records\",\n\t\tmetric.WithDescription(\"Number of profile records successfully scraped. [Alpha]\"),\n\t\tmetric.WithUnit(\"{datapoint}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\treturn &builder, errs\n}\n"
  },
  {
    "path": "scraper/scraperhelper/xscraperhelper/internal/metadata/generated_telemetry_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/metric\"\n\tembeddedmetric \"go.opentelemetry.io/otel/metric/embedded\"\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\t\"go.opentelemetry.io/otel/trace\"\n\tembeddedtrace \"go.opentelemetry.io/otel/trace/embedded\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\ntype mockMeter struct {\n\tnoopmetric.Meter\n\tname string\n}\ntype mockMeterProvider struct {\n\tembeddedmetric.MeterProvider\n}\n\nfunc (m mockMeterProvider) Meter(name string, opts ...metric.MeterOption) metric.Meter {\n\treturn mockMeter{name: name}\n}\n\ntype mockTracer struct {\n\tnooptrace.Tracer\n\tname string\n}\n\ntype mockTracerProvider struct {\n\tembeddedtrace.TracerProvider\n}\n\nfunc (m mockTracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer {\n\treturn mockTracer{name: name}\n}\n\nfunc TestProviders(t *testing.T) {\n\tset := component.TelemetrySettings{\n\t\tMeterProvider:  mockMeterProvider{},\n\t\tTracerProvider: mockTracerProvider{},\n\t}\n\n\tmeter := Meter(set)\n\tif m, ok := meter.(mockMeter); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/scraper/scraperhelper/xscraperhelper\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockMeter\")\n\t}\n\n\ttracer := Tracer(set)\n\tif m, ok := tracer.(mockTracer); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/scraper/scraperhelper/xscraperhelper\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockTracer\")\n\t}\n}\n\nfunc TestNewTelemetryBuilder(t *testing.T) {\n\tset := componenttest.NewNopTelemetrySettings()\n\tapplied := false\n\t_, err := NewTelemetryBuilder(set, telemetryBuilderOptionFunc(func(b *TelemetryBuilder) {\n\t\tapplied = true\n\t}))\n\trequire.NoError(t, err)\n\trequire.True(t, applied)\n}\n"
  },
  {
    "path": "scraper/scraperhelper/xscraperhelper/internal/metadatatest/generated_telemetrytest.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\nfunc AssertEqualScraperErroredProfileRecords(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_scraper_errored_profile_records\",\n\t\tDescription: \"Number of profile records that were unable to be scraped. [Alpha]\",\n\t\tUnit:        \"{datapoint}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_scraper_errored_profile_records\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualScraperScrapedProfileRecords(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_scraper_scraped_profile_records\",\n\t\tDescription: \"Number of profile records successfully scraped. [Alpha]\",\n\t\tUnit:        \"{datapoint}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_scraper_scraped_profile_records\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n"
  },
  {
    "path": "scraper/scraperhelper/xscraperhelper/internal/metadatatest/generated_telemetrytest_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/xscraperhelper/internal/metadata\"\n)\n\nfunc TestSetupTelemetry(t *testing.T) {\n\ttestTel := componenttest.NewTelemetry()\n\ttb, err := metadata.NewTelemetryBuilder(testTel.NewTelemetrySettings())\n\trequire.NoError(t, err)\n\tdefer tb.Shutdown()\n\ttb.ScraperErroredProfileRecords.Add(context.Background(), 1)\n\ttb.ScraperScrapedProfileRecords.Add(context.Background(), 1)\n\tAssertEqualScraperErroredProfileRecords(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualScraperScrapedProfileRecords(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\n\trequire.NoError(t, testTel.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "scraper/scraperhelper/xscraperhelper/metadata.yaml",
    "content": "type: xscraperhelper\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  codeowners:\n    active:\n      - florianl\n  stability:\n    alpha: [profiles]\n\ntelemetry:\n  metrics:\n    scraper_errored_profile_records:\n      enabled: true\n      stability: alpha\n      description: Number of profile records that were unable to be scraped.\n      unit: \"{datapoint}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    scraper_scraped_profile_records:\n      enabled: true\n      stability: alpha\n      description: Number of profile records successfully scraped.\n      unit: \"{datapoint}\"\n      sum:\n        value_type: int\n        monotonic: true\n"
  },
  {
    "path": "scraper/scraperhelper/xscraperhelper/obs_profiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package xscraperhelper provides utilities for scrapers.\npackage xscraperhelper // import \"go.opentelemetry.io/collector/scraper/scraperhelper/xscraperhelper\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/codes\"\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\t\"go.opentelemetry.io/collector/scraper/scrapererror\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/xscraperhelper/internal/metadata\"\n\t\"go.opentelemetry.io/collector/scraper/xscraper\"\n)\n\nconst (\n\n\t// scrapedProfileRecordsKey used to identify profile records scraped by the\n\t// Collector.\n\tscrapedProfileRecordsKey = \"scraped_profile_records\"\n\t// erroredProfileRecordsKey used to identify profile records errored (i.e.\n\t// unable to be scraped) by the Collector.\n\terroredProfileRecordsKey = \"errored_profile_records\"\n)\n\nfunc wrapObsProfiles(sc xscraper.Profiles, receiverID, scraperID component.ID, set component.TelemetrySettings) (xscraper.Profiles, error) {\n\ttelemetryBuilder, errBuilder := metadata.NewTelemetryBuilder(set)\n\tif errBuilder != nil {\n\t\treturn nil, errBuilder\n\t}\n\n\ttracer := metadata.Tracer(set)\n\tspanName := scraperKey + spanNameSep + scraperID.String() + spanNameSep + \"ScrapeProfiles\"\n\totelAttrs := metric.WithAttributeSet(attribute.NewSet(\n\t\tattribute.String(receiverKey, receiverID.String()),\n\t\tattribute.String(scraperKey, scraperID.String()),\n\t))\n\n\tscraperFuncs := func(ctx context.Context) (pprofile.Profiles, error) {\n\t\tctx, span := tracer.Start(ctx, spanName)\n\t\tdefer span.End()\n\n\t\tmd, err := sc.ScrapeProfiles(ctx)\n\t\tnumScrapedProfiles := 0\n\t\tnumErroredProfiles := 0\n\t\tif err != nil {\n\t\t\tset.Logger.Error(\"Error scraping profiles\", zap.Error(err))\n\t\t\tvar partialErr scrapererror.PartialScrapeError\n\t\t\tif errors.As(err, &partialErr) {\n\t\t\t\tnumErroredProfiles = partialErr.Failed\n\t\t\t\tnumScrapedProfiles = md.ProfileCount()\n\t\t\t}\n\t\t} else {\n\t\t\tnumScrapedProfiles = md.ProfileCount()\n\t\t}\n\n\t\ttelemetryBuilder.ScraperScrapedProfileRecords.Add(ctx, int64(numScrapedProfiles), otelAttrs)\n\t\ttelemetryBuilder.ScraperErroredProfileRecords.Add(ctx, int64(numErroredProfiles), otelAttrs)\n\n\t\t// end span according to errors\n\t\tif span.IsRecording() {\n\t\t\tspan.SetAttributes(\n\t\t\t\tattribute.String(formatKey, xpipeline.SignalProfiles.String()),\n\t\t\t\tattribute.Int64(scrapedProfileRecordsKey, int64(numScrapedProfiles)),\n\t\t\t\tattribute.Int64(erroredProfileRecordsKey, int64(numErroredProfiles)),\n\t\t\t)\n\n\t\t\tif err != nil {\n\t\t\t\tspan.SetStatus(codes.Error, err.Error())\n\t\t\t}\n\t\t}\n\n\t\treturn md, err\n\t}\n\n\treturn xscraper.NewProfiles(scraperFuncs, xscraper.WithStart(sc.Start), xscraper.WithShutdown(sc.Shutdown))\n}\n"
  },
  {
    "path": "scraper/scraperhelper/xscraperhelper/obs_profiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package xscraperhelper provides utilities for scrapers.\npackage xscraperhelper // import \"go.opentelemetry.io/collector/scraper/scraperhelper/xscraperhelper\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/codes\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/scraper/scrapererror\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/internal/controller\"\n\t\"go.opentelemetry.io/collector/scraper/scraperhelper/xscraperhelper/internal/metadatatest\"\n\t\"go.opentelemetry.io/collector/scraper/xscraper\"\n)\n\nvar (\n\treceiverID = component.MustNewID(\"fakeReceiver\")\n\tscraperID  = component.MustNewID(\"fakeScraper\")\n\n\terrFake        = errors.New(\"errFake\")\n\tpartialErrFake = scrapererror.NewPartialScrapeError(errFake, 2)\n)\n\ntype testParams struct {\n\titems int\n\terr   error\n}\n\nfunc TestScrapeProfilesDataOp(t *testing.T) {\n\ttel := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tel.Shutdown(context.Background())) })\n\n\tset := tel.NewTelemetrySettings()\n\n\tparentCtx, parentSpan := set.TracerProvider.Tracer(\"test\").Start(context.Background(), t.Name())\n\tdefer parentSpan.End()\n\n\tparams := []testParams{\n\t\t{items: 23, err: partialErrFake},\n\t\t{items: 29, err: errFake},\n\t\t{items: 15, err: nil},\n\t}\n\tfor i := range params {\n\t\tsm, err := xscraper.NewProfiles(func(context.Context) (pprofile.Profiles, error) {\n\t\t\treturn testdata.GenerateProfiles(params[i].items), params[i].err\n\t\t})\n\t\trequire.NoError(t, err)\n\t\tsf, err := wrapObsProfiles(sm, receiverID, scraperID, set)\n\t\trequire.NoError(t, err)\n\t\t_, err = sf.ScrapeProfiles(parentCtx)\n\t\trequire.ErrorIs(t, err, params[i].err)\n\t}\n\n\tspans := tel.SpanRecorder.Ended()\n\trequire.Len(t, spans, len(params))\n\n\tvar scrapedProfileRecords, erroredProfileRecords int\n\tfor i, span := range spans {\n\t\tassert.Equal(t, \"scraper/\"+scraperID.String()+\"/ScrapeProfiles\", span.Name())\n\t\tswitch {\n\t\tcase params[i].err == nil:\n\t\t\tscrapedProfileRecords += params[i].items\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(scrapedProfileRecordsKey, int64(params[i].items)))\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(erroredProfileRecordsKey, 0))\n\t\t\tassert.Equal(t, codes.Unset, span.Status().Code)\n\t\tcase errors.Is(params[i].err, errFake):\n\t\t\t// Since we get an error, we cannot record any metrics because we don't know if the returned pprofile.Profiles is valid instance.\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(scrapedProfileRecordsKey, 0))\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(erroredProfileRecordsKey, 0))\n\t\t\tassert.Equal(t, codes.Error, span.Status().Code)\n\t\t\tassert.Equal(t, params[i].err.Error(), span.Status().Description)\n\t\tcase errors.Is(params[i].err, partialErrFake):\n\t\t\tscrapedProfileRecords += params[i].items\n\t\t\terroredProfileRecords += 2\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(scrapedProfileRecordsKey, int64(params[i].items)))\n\t\t\trequire.Contains(t, span.Attributes(), attribute.Int64(erroredProfileRecordsKey, 2))\n\t\t\tassert.Equal(t, codes.Error, span.Status().Code)\n\t\t\tassert.Equal(t, params[i].err.Error(), span.Status().Description)\n\t\tdefault:\n\t\t\tt.Fatalf(\"unexpected err param: %v\", params[i].err)\n\t\t}\n\t}\n\n\tcheckScraperProfiles(t, tel, receiverID, scraperID, int64(scrapedProfileRecords), int64(erroredProfileRecords))\n}\n\nfunc TestCheckScraperProfiles(t *testing.T) {\n\ttel := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tel.Shutdown(context.Background())) })\n\n\tsm, err := xscraper.NewProfiles(func(context.Context) (pprofile.Profiles, error) {\n\t\treturn testdata.GenerateProfiles(7), nil\n\t})\n\trequire.NoError(t, err)\n\tsf, err := wrapObsProfiles(sm, receiverID, scraperID, tel.NewTelemetrySettings())\n\trequire.NoError(t, err)\n\t_, err = sf.ScrapeProfiles(context.Background())\n\trequire.NoError(t, err)\n\n\tcheckScraperProfiles(t, tel, receiverID, scraperID, 7, 0)\n}\n\nfunc TestScrapeProfilesDataOp_LogsScraperID(t *testing.T) {\n\ttel := componenttest.NewTelemetry()\n\tt.Cleanup(func() { require.NoError(t, tel.Shutdown(context.Background())) })\n\n\tcore, observedLogs := observer.New(zap.ErrorLevel)\n\ttelset := tel.NewTelemetrySettings()\n\ttelset.Logger = zap.New(core)\n\n\trSet := receiver.Settings{\n\t\tID:                receiverID,\n\t\tTelemetrySettings: telset,\n\t}\n\tset := controller.GetSettings(scraperID.Type(), rSet)\n\n\tsm, err := xscraper.NewProfiles(func(context.Context) (pprofile.Profiles, error) {\n\t\treturn pprofile.NewProfiles(), errFake\n\t})\n\trequire.NoError(t, err)\n\tsf, err := wrapObsProfiles(sm, receiverID, scraperID, set.TelemetrySettings)\n\trequire.NoError(t, err)\n\t_, err = sf.ScrapeProfiles(context.Background())\n\trequire.ErrorIs(t, err, errFake)\n\n\terrorLogs := observedLogs.FilterLevelExact(zap.ErrorLevel).All()\n\trequire.Len(t, errorLogs, 1)\n\tassert.Equal(t, \"Error scraping profiles\", errorLogs[0].Message)\n\tassert.Equal(t, scraperID.String(), errorLogs[0].ContextMap()[\"scraper\"])\n\tassert.Equal(t, errFake.Error(), errorLogs[0].ContextMap()[\"error\"])\n}\n\nfunc checkScraperProfiles(t *testing.T, tel *componenttest.Telemetry, receiver, scraper component.ID, scrapedProfileRecords, erroredProfileRecords int64) {\n\tmetadatatest.AssertEqualScraperScrapedProfileRecords(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(receiverKey, receiver.String()),\n\t\t\t\t\tattribute.String(scraperKey, scraper.String())),\n\t\t\t\tValue: scrapedProfileRecords,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n\n\tmetadatatest.AssertEqualScraperErroredProfileRecords(t, tel,\n\t\t[]metricdata.DataPoint[int64]{\n\t\t\t{\n\t\t\t\tAttributes: attribute.NewSet(\n\t\t\t\t\tattribute.String(receiverKey, receiver.String()),\n\t\t\t\t\tattribute.String(scraperKey, scraper.String())),\n\t\t\t\tValue: erroredProfileRecords,\n\t\t\t},\n\t\t}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreExemplars())\n}\n"
  },
  {
    "path": "scraper/scrapertest/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "scraper/scrapertest/go.mod",
    "content": "module go.opentelemetry.io/collector/scraper/scrapertest\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/google/uuid v1.6.0\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/scraper v0.148.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pipeline v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/scraper => ../\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n"
  },
  {
    "path": "scraper/scrapertest/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "scraper/scrapertest/metadata.yaml",
    "content": "type: scraper/scrapertest\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "scraper/scrapertest/settings.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage scrapertest // import \"go.opentelemetry.io/collector/scraper/scrapertest\"\n\nimport (\n\t\"github.com/google/uuid\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/scraper\"\n)\n\nvar NopType = component.MustNewType(\"nop\")\n\n// NewNopSettings returns a new nop scraper.Settings with the given type.\nfunc NewNopSettings(typ component.Type) scraper.Settings {\n\treturn scraper.Settings{\n\t\tID:                component.NewIDWithName(typ, uuid.NewString()),\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t\tBuildInfo:         component.NewDefaultBuildInfo(),\n\t}\n}\n"
  },
  {
    "path": "scraper/xscraper/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "scraper/xscraper/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\n// Package xscraper allows to define pull based receivers that can be configured using the scraperreceiver.\npackage xscraper // import \"go.opentelemetry.io/collector/scraper/xscraper\"\n"
  },
  {
    "path": "scraper/xscraper/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xscraper // import \"go.opentelemetry.io/collector/scraper/xscraper\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/scraper\"\n)\n\ntype Factory interface {\n\tscraper.Factory\n\n\t// CreateProfiles creates a Profiles scraper based on this config.\n\t// If the scraper type does not support profiles,\n\t// this function returns the error [pipeline.ErrSignalNotSupported].\n\tCreateProfiles(ctx context.Context, set scraper.Settings, cfg component.Config) (Profiles, error)\n\n\t// ProfilesStability gets the stability level of the Profiles scraper.\n\tProfilesStability() component.StabilityLevel\n}\n\n// FactoryOption apply changes to Options.\ntype FactoryOption interface {\n\t// applyOption applies the option.\n\tapplyOption(o *factory)\n}\n\nvar _ FactoryOption = (*factoryOptionFunc)(nil)\n\n// factoryOptionFunc is a FactoryOption created through a function.\ntype factoryOptionFunc func(*factory)\n\nfunc (f factoryOptionFunc) applyOption(o *factory) {\n\tf(o)\n}\n\ntype factory struct {\n\tscraper.Factory\n\topts []scraper.FactoryOption\n\n\tcreateProfilesFunc     CreateProfilesFunc\n\tprofilesStabilityLevel component.StabilityLevel\n}\n\nfunc (f *factory) ProfilesStability() component.StabilityLevel {\n\treturn f.profilesStabilityLevel\n}\n\nfunc (f *factory) CreateProfiles(ctx context.Context, set scraper.Settings, cfg component.Config) (Profiles, error) {\n\tif f.createProfilesFunc == nil {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\treturn f.createProfilesFunc(ctx, set, cfg)\n}\n\n// WithLogs overrides the default \"error not supported\" implementation for CreateLogs and the default \"undefined\" stability level.\nfunc WithLogs(createLogs scraper.CreateLogsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, scraper.WithLogs(createLogs, sl))\n\t})\n}\n\n// WithMetrics overrides the default \"error not supported\" implementation for CreateMetrics and the default \"undefined\" stability level.\nfunc WithMetrics(createMetrics scraper.CreateMetricsFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.opts = append(o.opts, scraper.WithMetrics(createMetrics, sl))\n\t})\n}\n\n// CreateProfilesFunc is the equivalent of Factory.CreateProfiles().\ntype CreateProfilesFunc func(context.Context, scraper.Settings, component.Config) (Profiles, error)\n\n// WithProfiles overrides the default \"error not supported\" implementation for CreateProfiles and the default \"undefined\" stability level.\nfunc WithProfiles(createProfiles CreateProfilesFunc, sl component.StabilityLevel) FactoryOption {\n\treturn factoryOptionFunc(func(o *factory) {\n\t\to.profilesStabilityLevel = sl\n\t\to.createProfilesFunc = createProfiles\n\t})\n}\n\n// NewFactory creates a Factory with experimental capabilities and wraps a scraper.Factory.\nfunc NewFactory(cfgType component.Type, createDefaultConfig component.CreateDefaultConfigFunc, options ...FactoryOption) Factory {\n\tf := &factory{}\n\tfor _, opt := range options {\n\t\topt.applyOption(f)\n\t}\n\tf.Factory = scraper.NewFactory(cfgType, createDefaultConfig, f.opts...)\n\treturn f\n}\n"
  },
  {
    "path": "scraper/xscraper/factory_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xscraper\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/scraper\"\n)\n\nvar testType = component.MustNewType(\"test\")\n\nfunc nopSettings() scraper.Settings {\n\treturn scraper.Settings{\n\t\tID:                component.NewID(testType),\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t}\n}\n\nfunc TestNewFactory(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tf := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg })\n\tassert.Equal(t, testType, f.Type())\n\tassert.EqualValues(t, &defaultCfg, f.CreateDefaultConfig())\n\t_, err := f.CreateProfiles(context.Background(), nopSettings(), &defaultCfg)\n\trequire.ErrorIs(t, err, pipeline.ErrSignalNotSupported)\n}\n\nfunc TestNewFactoryWithOptions(t *testing.T) {\n\ttestType := component.MustNewType(\"test\")\n\tdefaultCfg := struct{}{}\n\tf := NewFactory(\n\t\ttestType,\n\t\tfunc() component.Config { return &defaultCfg },\n\t\tWithLogs(createLogs, component.StabilityLevelAlpha),\n\t\tWithMetrics(createMetrics, component.StabilityLevelAlpha),\n\t\tWithProfiles(createProfiles, component.StabilityLevelDevelopment))\n\tassert.Equal(t, testType, f.Type())\n\tassert.EqualValues(t, &defaultCfg, f.CreateDefaultConfig())\n\n\tassert.Equal(t, component.StabilityLevelDevelopment, f.ProfilesStability())\n\t_, err := f.CreateProfiles(context.Background(), scraper.Settings{}, &defaultCfg)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, component.StabilityLevelAlpha, f.LogsStability())\n\t_, err = f.CreateLogs(context.Background(), scraper.Settings{}, &defaultCfg)\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, component.StabilityLevelAlpha, f.MetricsStability())\n\t_, err = f.CreateMetrics(context.Background(), scraper.Settings{}, &defaultCfg)\n\trequire.NoError(t, err)\n}\n\nfunc createProfiles(context.Context, scraper.Settings, component.Config) (Profiles, error) {\n\treturn NewProfiles(newTestScrapeProfilesFunc(nil))\n}\n\nfunc createLogs(context.Context, scraper.Settings, component.Config) (scraper.Logs, error) {\n\treturn scraper.NewLogs(newTestScrapeLogsFunc(nil))\n}\n\nfunc createMetrics(context.Context, scraper.Settings, component.Config) (scraper.Metrics, error) {\n\treturn scraper.NewMetrics(newTestScrapeMetricsFunc(nil))\n}\n\nfunc newTestScrapeLogsFunc(retError error) scraper.ScrapeLogsFunc {\n\treturn func(_ context.Context) (plog.Logs, error) {\n\t\treturn plog.NewLogs(), retError\n\t}\n}\n\nfunc newTestScrapeMetricsFunc(retError error) scraper.ScrapeMetricsFunc {\n\treturn func(_ context.Context) (pmetric.Metrics, error) {\n\t\treturn pmetric.NewMetrics(), retError\n\t}\n}\n"
  },
  {
    "path": "scraper/xscraper/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage xscraper\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "scraper/xscraper/go.mod",
    "content": "module go.opentelemetry.io/collector/scraper/xscraper\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/scraper v0.148.0\n\tgo.uber.org/goleak v1.3.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.1 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/pmezard/go-difflib v1.0.0 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n\tgolang.org/x/sys v0.41.0 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/pipeline => ../../pipeline\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/component => ../../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\nreplace go.opentelemetry.io/collector/scraper => ../../scraper\n\nreplace go.opentelemetry.io/collector/featuregate => ../../featuregate\n\nreplace go.opentelemetry.io/collector/pdata => ../../pdata\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n"
  },
  {
    "path": "scraper/xscraper/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngolang.org/x/sys v0.41.0 h1:Ivj+2Cp/ylzLiEU89QhWblYnOE9zerudt9Ftecq2C6k=\ngolang.org/x/sys v0.41.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "scraper/xscraper/metadata.yaml",
    "content": "type: xscraper\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  class: pkg\n  codeowners:\n    active:\n      - dmathieu\n      - florianl\n  stability:\n    alpha: [profiles]\n"
  },
  {
    "path": "scraper/xscraper/profiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xscraper // import \"go.opentelemetry.io/collector/scraper/xscraper\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/scraper\"\n)\n\n// Profiles is the base interface for profiles scrapers.\ntype Profiles interface {\n\tcomponent.Component\n\n\t// ScrapeProfiles is the base interface to indicate that how should profiles be scraped.\n\tScrapeProfiles(context.Context) (pprofile.Profiles, error)\n}\n\n// ScrapeProfilesFunc is a helper function.\ntype ScrapeProfilesFunc scraper.ScrapeFunc[pprofile.Profiles]\n\nfunc (sf ScrapeProfilesFunc) ScrapeProfiles(ctx context.Context) (pprofile.Profiles, error) {\n\treturn sf(ctx)\n}\n\ntype profiles struct {\n\tbaseScraper\n\tScrapeProfilesFunc\n}\n\n// NewProfiles creates a new Profiles scraper.\nfunc NewProfiles(scrape ScrapeProfilesFunc, options ...Option) (Profiles, error) {\n\tif scrape == nil {\n\t\treturn nil, errNilFunc\n\t}\n\tbs := &profiles{\n\t\tbaseScraper:        newBaseScraper(options),\n\t\tScrapeProfilesFunc: scrape,\n\t}\n\treturn bs, nil\n}\n"
  },
  {
    "path": "scraper/xscraper/profiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xscraper\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n)\n\nfunc TestNewProfiles(t *testing.T) {\n\tmp, err := NewProfiles(newTestScrapeProfilesFunc(nil))\n\trequire.NoError(t, err)\n\n\trequire.NoError(t, mp.Start(context.Background(), componenttest.NewNopHost()))\n\tmd, err := mp.ScrapeProfiles(context.Background())\n\trequire.NoError(t, err)\n\tassert.Equal(t, pprofile.NewProfiles(), md)\n\trequire.NoError(t, mp.Shutdown(context.Background()))\n}\n\nfunc TestNewProfiles_WithOptions(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tmp, err := NewProfiles(newTestScrapeProfilesFunc(nil),\n\t\tWithStart(func(context.Context, component.Host) error { return want }),\n\t\tWithShutdown(func(context.Context) error { return want }))\n\trequire.NoError(t, err)\n\n\tassert.Equal(t, want, mp.Start(context.Background(), componenttest.NewNopHost()))\n\tassert.Equal(t, want, mp.Shutdown(context.Background()))\n}\n\nfunc TestNewProfiles_NilRequiredFields(t *testing.T) {\n\t_, err := NewProfiles(nil)\n\trequire.Error(t, err)\n}\n\nfunc TestNewProfiles_ProcessProfilesError(t *testing.T) {\n\twant := errors.New(\"my_error\")\n\tmp, err := NewProfiles(newTestScrapeProfilesFunc(want))\n\trequire.NoError(t, err)\n\t_, err = mp.ScrapeProfiles(context.Background())\n\trequire.ErrorIs(t, err, want)\n}\n\nfunc TestProfilesConcurrency(t *testing.T) {\n\tmp, err := NewProfiles(newTestScrapeProfilesFunc(nil))\n\trequire.NoError(t, err)\n\trequire.NoError(t, mp.Start(context.Background(), componenttest.NewNopHost()))\n\n\tvar wg sync.WaitGroup\n\tfor range 10 {\n\t\twg.Go(func() {\n\t\t\tfor range 10000 {\n\t\t\t\t_, errScrape := mp.ScrapeProfiles(context.Background())\n\t\t\t\tassert.NoError(t, errScrape)\n\t\t\t}\n\t\t})\n\t}\n\twg.Wait()\n\trequire.NoError(t, mp.Shutdown(context.Background()))\n}\n\nfunc newTestScrapeProfilesFunc(retError error) ScrapeProfilesFunc {\n\treturn func(_ context.Context) (pprofile.Profiles, error) {\n\t\treturn pprofile.NewProfiles(), retError\n\t}\n}\n"
  },
  {
    "path": "scraper/xscraper/scraper.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage xscraper // import \"go.opentelemetry.io/collector/scraper/xscraper\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nvar errNilFunc = errors.New(\"nil scrape func\")\n\n// ScrapeFunc scrapes data.\ntype ScrapeFunc[T any] func(context.Context) (T, error)\n\n// Option apply changes to internal options.\ntype Option interface {\n\tapply(*baseScraper)\n}\n\ntype scraperOptionFunc func(*baseScraper)\n\nfunc (of scraperOptionFunc) apply(e *baseScraper) {\n\tof(e)\n}\n\n// WithStart sets the function that will be called on startup.\nfunc WithStart(start component.StartFunc) Option {\n\treturn scraperOptionFunc(func(o *baseScraper) {\n\t\to.StartFunc = start\n\t})\n}\n\n// WithShutdown sets the function that will be called on shutdown.\nfunc WithShutdown(shutdown component.ShutdownFunc) Option {\n\treturn scraperOptionFunc(func(o *baseScraper) {\n\t\to.ShutdownFunc = shutdown\n\t})\n}\n\ntype baseScraper struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n}\n\n// newBaseScraper returns the internal settings starting from the default and applying all options.\nfunc newBaseScraper(options []Option) baseScraper {\n\t// Start from the default options:\n\tbs := baseScraper{}\n\n\tfor _, op := range options {\n\t\top.apply(&bs)\n\t}\n\n\treturn bs\n}\n"
  },
  {
    "path": "service/Makefile",
    "content": "include ../Makefile.Common\n"
  },
  {
    "path": "service/README.md",
    "content": "<!-- status autogenerated section -->\n# Service\n| Status        |           |\n| ------------- |-----------|\n| Stability     | [development]: traces, metrics, logs, profiles   |\n| Issues        | [![Open issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aopen%20label%3Apkg%2Fservice%20&label=open&color=orange&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aopen+is%3Aissue+label%3Apkg%2Fservice) [![Closed issues](https://img.shields.io/github/issues-search/open-telemetry/opentelemetry-collector?query=is%3Aissue%20is%3Aclosed%20label%3Apkg%2Fservice%20&label=closed&color=blue&logo=opentelemetry)](https://github.com/open-telemetry/opentelemetry-collector/issues?q=is%3Aclosed+is%3Aissue+label%3Apkg%2Fservice) |\n\n[development]: https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/component-stability.md#development\n[core]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol\n[contrib]: https://github.com/open-telemetry/opentelemetry-collector-releases/tree/main/distributions/otelcol-contrib\n<!-- end autogenerated section -->\n"
  },
  {
    "path": "service/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage service // import \"go.opentelemetry.io/collector/service\"\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/service/extensions\"\n\t\"go.opentelemetry.io/collector/service/pipelines\"\n)\n\n// Config defines the configurable components of the Service.\ntype Config struct {\n\t// Telemetry is the configuration for collector's own telemetry.\n\tTelemetry component.Config `mapstructure:\"telemetry\"`\n\n\t// Extensions are the ordered list of extensions configured for the service.\n\tExtensions extensions.Config `mapstructure:\"extensions,omitempty\"`\n\n\t// Pipelines are the set of data pipelines configured for the service.\n\tPipelines pipelines.Config `mapstructure:\"pipelines\"`\n\n\t// prevent unkeyed literal initialization\n\t_ struct{}\n}\n"
  },
  {
    "path": "service/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage service\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/service/extensions\"\n\t\"go.opentelemetry.io/collector/service/pipelines\"\n)\n\nfunc TestConfigValidate(t *testing.T) {\n\ttestCases := []struct {\n\t\tname     string // test case name (also file name containing config yaml)\n\t\tcfgFn    func() *Config\n\t\texpected error\n\t}{\n\t\t{\n\t\t\tname:     \"valid\",\n\t\t\tcfgFn:    generateConfig,\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"valid-telemetry-config\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tcfg.Telemetry = fakeTelemetryConfig{Invalid: false}\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"duplicate-processor-reference\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tpipe := cfg.Pipelines[pipeline.NewID(pipeline.SignalTraces)]\n\t\t\t\tpipe.Processors = append(pipe.Processors, pipe.Processors...)\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errors.New(`references processor \"nop\" multiple times`),\n\t\t},\n\t\t{\n\t\t\tname: \"invalid-telemetry-config\",\n\t\t\tcfgFn: func() *Config {\n\t\t\t\tcfg := generateConfig()\n\t\t\t\tcfg.Telemetry = fakeTelemetryConfig{Invalid: true}\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errors.New(\"telemetry: invalid config\"),\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := tt.cfgFn()\n\t\t\terr := xconfmap.Validate(cfg)\n\t\t\tif tt.expected != nil {\n\t\t\t\tassert.ErrorContains(t, err, tt.expected.Error())\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestConfmapMarshalConfig(t *testing.T) {\n\tconf := confmap.New()\n\n\trequire.NoError(t, conf.Marshal(Config{\n\t\tTelemetry: fakeTelemetryConfig{},\n\t}))\n\tassert.Equal(t, map[string]any{\n\t\t\"pipelines\": map[string]any(nil),\n\t\t\"telemetry\": map[string]any{\"invalid\": false},\n\t}, conf.ToStringMap())\n}\n\nfunc generateConfig() *Config {\n\treturn &Config{\n\t\tExtensions: extensions.Config{component.MustNewID(\"nop\")},\n\t\tPipelines: pipelines.Config{\n\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t},\n\t\t},\n\t}\n}\n\ntype fakeTelemetryConfig struct {\n\tInvalid bool `mapstructure:\"invalid\"`\n}\n\nfunc (cfg fakeTelemetryConfig) Validate() error {\n\tif cfg.Invalid {\n\t\treturn errors.New(\"invalid config\")\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "service/documentation.md",
    "content": "[comment]: <> (Code generated by mdatagen. DO NOT EDIT.)\n\n# service\n\n## Internal Telemetry\n\nThe following telemetry is emitted by this component.\n\n### otelcol.connector.consumed.items\n\nNumber of items passed to the connector.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {item} | Sum | Int | true | Development |\n\n### otelcol.connector.produced.items\n\nNumber of items emitted from the connector.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {item} | Sum | Int | true | Development |\n\n### otelcol.exporter.consumed.items\n\nNumber of items passed to the exporter.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {item} | Sum | Int | true | Development |\n\n### otelcol_process_cpu_seconds\n\nTotal CPU user and system time in seconds\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| s | Sum | Double | true | Alpha |\n\n### otelcol_process_memory_rss\n\nTotal physical memory (resident set size)\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| By | Gauge | Int | Alpha |\n\n### otelcol_process_runtime_heap_alloc_bytes\n\nBytes of allocated heap objects (see 'go doc runtime.MemStats.HeapAlloc')\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| By | Gauge | Int | Alpha |\n\n### otelcol_process_runtime_total_alloc_bytes\n\nCumulative bytes allocated for heap objects (see 'go doc runtime.MemStats.TotalAlloc')\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| By | Sum | Int | true | Alpha |\n\n### otelcol_process_runtime_total_sys_memory_bytes\n\nTotal bytes of memory obtained from the OS (see 'go doc runtime.MemStats.Sys')\n\n| Unit | Metric Type | Value Type | Stability |\n| ---- | ----------- | ---------- | --------- |\n| By | Gauge | Int | Alpha |\n\n### otelcol_process_uptime\n\nUptime of the process\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| s | Sum | Double | true | Alpha |\n\n### otelcol.processor.consumed.items\n\nNumber of items passed to the processor.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {item} | Sum | Int | true | Development |\n\n### otelcol.processor.produced.items\n\nNumber of items emitted from the processor.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {item} | Sum | Int | true | Development |\n\n### otelcol.receiver.produced.items\n\nNumber of items emitted from the receiver.\n\n| Unit | Metric Type | Value Type | Monotonic | Stability |\n| ---- | ----------- | ---------- | --------- | --------- |\n| {item} | Sum | Int | true | Development |\n\n## Feature Gates\n\nThis component has the following feature gates:\n\n| Feature Gate | Stage | Description | From Version | To Version | Reference |\n| ------------ | ----- | ----------- | ------------ | ---------- | --------- |\n| `service.AllowNoPipelines` | alpha | Allow starting the Collector without starting any pipelines. | v0.122.0 | N/A | [Link](https://github.com/open-telemetry/opentelemetry-collector/pull/12613) |\n| `service.profilesSupport` | alpha | Controls whether profiles support can be enabled | v0.112.0 | N/A | [Link](https://github.com/open-telemetry/opentelemetry-collector/pull/11477) |\n| `telemetry.UseLocalHostAsDefaultMetricsAddress` | beta | Controls whether default Prometheus metrics server use localhost as the default host for their endpoints | v0.111.0 | N/A | [Link](https://github.com/open-telemetry/opentelemetry-collector/pull/11251) |\n| `telemetry.newPipelineTelemetry` | alpha | Injects component-identifying scope attributes in internal Collector metrics | v0.123.0 | N/A | [Link](https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/rfcs/component-universal-telemetry.md) |\n\nFor more information about feature gates, see the [Feature Gates](https://github.com/open-telemetry/opentelemetry-collector/blob/main/featuregate/README.md) documentation.\n"
  },
  {
    "path": "service/extensions/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensions // import \"go.opentelemetry.io/collector/service/extensions\"\n\nimport \"go.opentelemetry.io/collector/component\"\n\n// Config represents the ordered list of extensions configured for the service.\ntype Config []component.ID\n"
  },
  {
    "path": "service/extensions/extensions.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensions // import \"go.opentelemetry.io/collector/service/extensions\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"net/http\"\n\t\"sort\"\n\n\t\"go.uber.org/multierr\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componentstatus\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensioncapabilities\"\n\t\"go.opentelemetry.io/collector/service/internal/attribute\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n\t\"go.opentelemetry.io/collector/service/internal/componentattribute\"\n\t\"go.opentelemetry.io/collector/service/internal/status\"\n\t\"go.opentelemetry.io/collector/service/internal/zpages\"\n)\n\nconst zExtensionName = \"zextensionname\"\n\n// Extensions is a map of extensions created from extension configs.\ntype Extensions struct {\n\ttelemetry    component.TelemetrySettings\n\textMap       map[component.ID]extension.Extension\n\tinstanceIDs  map[component.ID]*componentstatus.InstanceID\n\textensionIDs []component.ID // start order (and reverse stop order)\n\treporter     status.Reporter\n}\n\n// Start starts all extensions.\nfunc (bes *Extensions) Start(ctx context.Context, host component.Host) error {\n\tbes.telemetry.Logger.Info(\"Starting extensions...\")\n\tfor _, extID := range bes.extensionIDs {\n\t\textLogger := componentattribute.LoggerWithAttributes(bes.telemetry.Logger,\n\t\t\tattribute.Extension(extID).Set().ToSlice())\n\t\textLogger.Info(\"Extension is starting...\")\n\t\tinstanceID := bes.instanceIDs[extID]\n\t\text := bes.extMap[extID]\n\t\tbes.reporter.ReportStatus(\n\t\t\tinstanceID,\n\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStarting),\n\t\t)\n\t\tif err := ext.Start(ctx, host); err != nil {\n\t\t\tbes.reporter.ReportStatus(\n\t\t\t\tinstanceID,\n\t\t\t\tcomponentstatus.NewPermanentErrorEvent(err),\n\t\t\t)\n\t\t\t// We log with zap.AddStacktrace(zap.DPanicLevel) to avoid adding the stack trace to the error log\n\t\t\textLogger.WithOptions(zap.AddStacktrace(zap.DPanicLevel)).Error(\"Failed to start extension\", zap.Error(err))\n\t\t\treturn err\n\t\t}\n\t\tbes.reporter.ReportOKIfStarting(instanceID)\n\t\textLogger.Info(\"Extension started.\")\n\t}\n\treturn nil\n}\n\n// Shutdown stops all extensions.\nfunc (bes *Extensions) Shutdown(ctx context.Context) error {\n\tbes.telemetry.Logger.Info(\"Stopping extensions...\")\n\tvar errs error\n\tfor i := len(bes.extensionIDs) - 1; i >= 0; i-- {\n\t\textID := bes.extensionIDs[i]\n\t\tinstanceID := bes.instanceIDs[extID]\n\t\text := bes.extMap[extID]\n\t\tbes.reporter.ReportStatus(\n\t\t\tinstanceID,\n\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopping),\n\t\t)\n\t\tif err := ext.Shutdown(ctx); err != nil {\n\t\t\tbes.reporter.ReportStatus(\n\t\t\t\tinstanceID,\n\t\t\t\tcomponentstatus.NewPermanentErrorEvent(err),\n\t\t\t)\n\t\t\terrs = multierr.Append(errs, err)\n\t\t\tcontinue\n\t\t}\n\t\tbes.reporter.ReportStatus(\n\t\t\tinstanceID,\n\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopped),\n\t\t)\n\t}\n\n\treturn errs\n}\n\nfunc (bes *Extensions) NotifyPipelineReady() error {\n\tfor _, extID := range bes.extensionIDs {\n\t\text := bes.extMap[extID]\n\t\tif pw, ok := ext.(extensioncapabilities.PipelineWatcher); ok {\n\t\t\tif err := pw.Ready(); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to notify extension %q: %w\", extID, err)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (bes *Extensions) NotifyPipelineNotReady() error {\n\tvar errs error\n\tfor _, extID := range bes.extensionIDs {\n\t\text := bes.extMap[extID]\n\t\tif pw, ok := ext.(extensioncapabilities.PipelineWatcher); ok {\n\t\t\terrs = multierr.Append(errs, pw.NotReady())\n\t\t}\n\t}\n\treturn errs\n}\n\nfunc (bes *Extensions) NotifyConfig(ctx context.Context, conf *confmap.Conf) error {\n\tvar errs error\n\tfor _, extID := range bes.extensionIDs {\n\t\text := bes.extMap[extID]\n\t\tif cw, ok := ext.(extensioncapabilities.ConfigWatcher); ok {\n\t\t\tclonedConf := confmap.NewFromStringMap(conf.ToStringMap())\n\t\t\terrs = multierr.Append(errs, cw.NotifyConfig(ctx, clonedConf))\n\t\t}\n\t}\n\treturn errs\n}\n\nfunc (bes *Extensions) NotifyComponentStatusChange(source *componentstatus.InstanceID, event *componentstatus.Event) {\n\tfor _, extID := range bes.extensionIDs {\n\t\text := bes.extMap[extID]\n\t\tif sw, ok := ext.(componentstatus.Watcher); ok {\n\t\t\tsw.ComponentStatusChanged(source, event)\n\t\t}\n\t}\n}\n\nfunc (bes *Extensions) GetExtensions() map[component.ID]component.Component {\n\tresult := make(map[component.ID]component.Component, len(bes.extMap))\n\tfor extID, v := range bes.extMap {\n\t\tresult[extID] = v\n\t}\n\treturn result\n}\n\nfunc (bes *Extensions) HandleZPages(w http.ResponseWriter, r *http.Request) {\n\textensionName := r.URL.Query().Get(zExtensionName)\n\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tzpages.WriteHTMLPageHeader(w, zpages.HeaderData{Title: \"Extensions\"})\n\tdata := zpages.SummaryExtensionsTableData{}\n\n\tdata.Rows = make([]zpages.SummaryExtensionsTableRowData, 0, len(bes.extMap))\n\tfor _, id := range bes.extensionIDs {\n\t\trow := zpages.SummaryExtensionsTableRowData{FullName: id.String()}\n\t\tdata.Rows = append(data.Rows, row)\n\t}\n\n\tsort.Slice(data.Rows, func(i, j int) bool {\n\t\treturn data.Rows[i].FullName < data.Rows[j].FullName\n\t})\n\tzpages.WriteHTMLExtensionsSummaryTable(w, data)\n\tif extensionName != \"\" {\n\t\tzpages.WriteHTMLComponentHeader(w, zpages.ComponentHeaderData{\n\t\t\tName: extensionName,\n\t\t})\n\t\t// TODO: Add config + status info.\n\t}\n\tzpages.WriteHTMLPageFooter(w)\n}\n\n// Settings holds configuration for building Extensions.\ntype Settings struct {\n\tTelemetry component.TelemetrySettings\n\tBuildInfo component.BuildInfo\n\n\t// Extensions builder for extensions.\n\tExtensions builders.Extension\n}\n\ntype Option interface {\n\tapply(*Extensions)\n}\n\ntype optionFunc func(*Extensions)\n\nfunc (of optionFunc) apply(e *Extensions) {\n\tof(e)\n}\n\nfunc WithReporter(reporter status.Reporter) Option {\n\treturn optionFunc(func(e *Extensions) {\n\t\te.reporter = reporter\n\t})\n}\n\n// New creates a new Extensions from Config.\nfunc New(ctx context.Context, set Settings, cfg Config, options ...Option) (*Extensions, error) {\n\texts := &Extensions{\n\t\ttelemetry:    set.Telemetry,\n\t\textMap:       make(map[component.ID]extension.Extension),\n\t\tinstanceIDs:  make(map[component.ID]*componentstatus.InstanceID),\n\t\textensionIDs: make([]component.ID, 0, len(cfg)),\n\t\treporter:     status.NewNopStatusReporter(),\n\t}\n\n\tfor _, opt := range options {\n\t\topt.apply(exts)\n\t}\n\n\tfor _, extID := range cfg {\n\t\tinstanceID := componentstatus.NewInstanceID(extID, component.KindExtension)\n\t\textSet := extension.Settings{\n\t\t\tID:                extID,\n\t\t\tTelemetrySettings: componentattribute.TelemetrySettingsWithAttributes(set.Telemetry, *attribute.Extension(extID).Set()),\n\t\t\tBuildInfo:         set.BuildInfo,\n\t\t}\n\n\t\text, err := set.Extensions.Create(ctx, extSet)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to create extension %q: %w\", extID, err)\n\t\t}\n\n\t\t// Check if the factory really created the extension.\n\t\tif ext == nil {\n\t\t\treturn nil, fmt.Errorf(\"factory for %q produced a nil extension\", extID)\n\t\t}\n\n\t\texts.extMap[extID] = ext\n\t\texts.instanceIDs[extID] = instanceID\n\t}\n\torder, err := computeOrder(exts)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\texts.extensionIDs = order\n\treturn exts, nil\n}\n"
  },
  {
    "path": "service/extensions/extensions_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensions\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"slices\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componentstatus\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensioncapabilities\"\n\t\"go.opentelemetry.io/collector/extension/extensiontest\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n\t\"go.opentelemetry.io/collector/service/internal/status\"\n)\n\nfunc TestBuildExtensions(t *testing.T) {\n\tnopExtensionFactory := extensiontest.NewNopFactory()\n\tnopExtensionConfig := nopExtensionFactory.CreateDefaultConfig()\n\terrExtensionFactory := newCreateErrorExtensionFactory()\n\terrExtensionConfig := errExtensionFactory.CreateDefaultConfig()\n\tbadExtensionFactory := newBadExtensionFactory()\n\tbadExtensionCfg := badExtensionFactory.CreateDefaultConfig()\n\n\ttests := []struct {\n\t\tname              string\n\t\tfactories         map[component.Type]extension.Factory\n\t\textensionsConfigs map[component.ID]component.Config\n\t\tconfig            Config\n\t\twantErrMsg        string\n\t}{\n\t\t{\n\t\t\tname: \"extension_not_configured\",\n\t\t\tconfig: Config{\n\t\t\t\tcomponent.MustNewID(\"myextension\"),\n\t\t\t},\n\t\t\twantErrMsg: \"failed to create extension \\\"myextension\\\": extension \\\"myextension\\\" is not configured\",\n\t\t},\n\t\t{\n\t\t\tname: \"missing_extension_factory\",\n\t\t\textensionsConfigs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"unknown\"): nopExtensionConfig,\n\t\t\t},\n\t\t\tconfig: Config{\n\t\t\t\tcomponent.MustNewID(\"unknown\"),\n\t\t\t},\n\t\t\twantErrMsg: \"failed to create extension \\\"unknown\\\": extension factory not available for: \\\"unknown\\\"\",\n\t\t},\n\t\t{\n\t\t\tname: \"error_on_create_extension\",\n\t\t\tfactories: map[component.Type]extension.Factory{\n\t\t\t\terrExtensionFactory.Type(): errExtensionFactory,\n\t\t\t},\n\t\t\textensionsConfigs: map[component.ID]component.Config{\n\t\t\t\tcomponent.NewID(errExtensionFactory.Type()): errExtensionConfig,\n\t\t\t},\n\t\t\tconfig: Config{\n\t\t\t\tcomponent.NewID(errExtensionFactory.Type()),\n\t\t\t},\n\t\t\twantErrMsg: \"failed to create extension \\\"err\\\": cannot create \\\"err\\\" extension type\",\n\t\t},\n\t\t{\n\t\t\tname: \"bad_factory\",\n\t\t\tfactories: map[component.Type]extension.Factory{\n\t\t\t\tbadExtensionFactory.Type(): badExtensionFactory,\n\t\t\t},\n\t\t\textensionsConfigs: map[component.ID]component.Config{\n\t\t\t\tcomponent.NewID(badExtensionFactory.Type()): badExtensionCfg,\n\t\t\t},\n\t\t\tconfig: Config{\n\t\t\t\tcomponent.NewID(badExtensionFactory.Type()),\n\t\t\t},\n\t\t\twantErrMsg: \"factory for \\\"bf\\\" produced a nil extension\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t_, err := New(context.Background(), Settings{\n\t\t\t\tTelemetry:  componenttest.NewNopTelemetrySettings(),\n\t\t\t\tBuildInfo:  component.NewDefaultBuildInfo(),\n\t\t\t\tExtensions: builders.NewExtension(tt.extensionsConfigs, tt.factories),\n\t\t\t}, tt.config)\n\t\t\trequire.Error(t, err)\n\t\t\tassert.EqualError(t, err, tt.wantErrMsg)\n\t\t})\n\t}\n}\n\ntype testOrderExt struct {\n\tname string\n\tdeps []string\n}\n\ntype testOrderCase struct {\n\ttestName   string\n\textensions []testOrderExt\n\torder      []string\n\terr        string\n}\n\nfunc TestOrdering(t *testing.T) {\n\ttests := []testOrderCase{\n\t\t{\n\t\t\ttestName:   \"no_deps\",\n\t\t\textensions: []testOrderExt{{name: \"\"}, {name: \"foo\"}, {name: \"bar\"}},\n\t\t\torder:      nil, // no predictable order\n\t\t},\n\t\t{\n\t\t\ttestName: \"deps\",\n\t\t\textensions: []testOrderExt{\n\t\t\t\t{name: \"foo\", deps: []string{\"bar\"}}, // foo -> bar\n\t\t\t\t{name: \"baz\", deps: []string{\"foo\"}}, // baz -> foo\n\t\t\t\t{name: \"bar\"},\n\t\t\t},\n\t\t\t// baz -> foo -> bar\n\t\t\torder: []string{\"recording/bar\", \"recording/foo\", \"recording/baz\"},\n\t\t},\n\t\t{\n\t\t\ttestName: \"deps_double\",\n\t\t\textensions: []testOrderExt{\n\t\t\t\t{name: \"foo\", deps: []string{\"bar\"}},        // foo -> bar\n\t\t\t\t{name: \"baz\", deps: []string{\"foo\", \"bar\"}}, // baz -> {foo, bar}\n\t\t\t\t{name: \"bar\"},\n\t\t\t},\n\t\t\t// baz -> foo -> bar\n\t\t\torder: []string{\"recording/bar\", \"recording/foo\", \"recording/baz\"},\n\t\t},\n\t\t{\n\t\t\ttestName: \"unknown_dep\",\n\t\t\textensions: []testOrderExt{\n\t\t\t\t{name: \"foo\", deps: []string{\"BAZ\"}},\n\t\t\t\t{name: \"bar\"},\n\t\t\t},\n\t\t\terr: \"unable to find extension\",\n\t\t},\n\t\t{\n\t\t\ttestName: \"circular\",\n\t\t\textensions: []testOrderExt{\n\t\t\t\t{name: \"foo\", deps: []string{\"bar\"}},\n\t\t\t\t{name: \"bar\", deps: []string{\"foo\"}},\n\t\t\t},\n\t\t\terr: \"unable to order extensions\",\n\t\t},\n\t}\n\tfor _, testCase := range tests {\n\t\tt.Run(testCase.testName, testCase.testOrdering)\n\t}\n}\n\nfunc (tc testOrderCase) testOrdering(t *testing.T) {\n\tvar startOrder []string\n\tvar shutdownOrder []string\n\n\trecordingExtensionFactory := newRecordingExtensionFactory(func(set extension.Settings, _ component.Host) error {\n\t\tstartOrder = append(startOrder, set.ID.String())\n\t\treturn nil\n\t}, func(set extension.Settings) error {\n\t\tshutdownOrder = append(shutdownOrder, set.ID.String())\n\t\treturn nil\n\t})\n\n\textCfgs := make(map[component.ID]component.Config)\n\textIDs := make([]component.ID, len(tc.extensions))\n\tfor i, ext := range tc.extensions {\n\t\textID := component.NewIDWithName(recordingExtensionFactory.Type(), ext.name)\n\t\textIDs[i] = extID\n\t\textCfgs[extID] = recordingExtensionConfig{dependencies: ext.deps}\n\t}\n\n\texts, err := New(context.Background(), Settings{\n\t\tTelemetry: componenttest.NewNopTelemetrySettings(),\n\t\tBuildInfo: component.NewDefaultBuildInfo(),\n\t\tExtensions: builders.NewExtension(\n\t\t\textCfgs,\n\t\t\tmap[component.Type]extension.Factory{\n\t\t\t\trecordingExtensionFactory.Type(): recordingExtensionFactory,\n\t\t\t}),\n\t}, Config(extIDs))\n\tif tc.err != \"\" {\n\t\trequire.ErrorContains(t, err, tc.err)\n\t\treturn\n\t}\n\trequire.NoError(t, err)\n\n\terr = exts.Start(context.Background(), componenttest.NewNopHost())\n\trequire.NoError(t, err)\n\terr = exts.Shutdown(context.Background())\n\trequire.NoError(t, err)\n\n\tif len(tc.order) > 0 {\n\t\trequire.Equal(t, tc.order, startOrder)\n\t\tslices.Reverse(shutdownOrder)\n\t\trequire.Equal(t, tc.order, shutdownOrder)\n\t}\n}\n\nfunc TestNotifyConfig(t *testing.T) {\n\tnotificationError := errors.New(\"Error processing config\")\n\tnopExtensionFactory := extensiontest.NewNopFactory()\n\tnopExtensionConfig := nopExtensionFactory.CreateDefaultConfig()\n\tn1ExtensionFactory := newConfigWatcherExtensionFactory(component.MustNewType(\"notifiable1\"), func() error { return nil })\n\tn1ExtensionConfig := n1ExtensionFactory.CreateDefaultConfig()\n\tn2ExtensionFactory := newConfigWatcherExtensionFactory(component.MustNewType(\"notifiable2\"), func() error { return nil })\n\tn2ExtensionConfig := n1ExtensionFactory.CreateDefaultConfig()\n\tnErrExtensionFactory := newConfigWatcherExtensionFactory(component.MustNewType(\"notifiableErr\"), func() error { return notificationError })\n\tnErrExtensionConfig := nErrExtensionFactory.CreateDefaultConfig()\n\n\ttests := []struct {\n\t\tname              string\n\t\tfactories         map[component.Type]extension.Factory\n\t\textensionsConfigs map[component.ID]component.Config\n\t\tserviceExtensions []component.ID\n\t\twantErrMsg        string\n\t\twant              error\n\t}{\n\t\t{\n\t\t\tname: \"No notifiable extensions\",\n\t\t\tfactories: map[component.Type]extension.Factory{\n\t\t\t\tcomponent.MustNewType(\"nop\"): nopExtensionFactory,\n\t\t\t},\n\t\t\textensionsConfigs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExtensionConfig,\n\t\t\t},\n\t\t\tserviceExtensions: []component.ID{\n\t\t\t\tcomponent.MustNewID(\"nop\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"One notifiable extension\",\n\t\t\tfactories: map[component.Type]extension.Factory{\n\t\t\t\tcomponent.MustNewType(\"notifiable1\"): n1ExtensionFactory,\n\t\t\t},\n\t\t\textensionsConfigs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"notifiable1\"): n1ExtensionConfig,\n\t\t\t},\n\t\t\tserviceExtensions: []component.ID{\n\t\t\t\tcomponent.MustNewID(\"notifiable1\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Multiple notifiable extensions\",\n\t\t\tfactories: map[component.Type]extension.Factory{\n\t\t\t\tcomponent.MustNewType(\"notifiable1\"): n1ExtensionFactory,\n\t\t\t\tcomponent.MustNewType(\"notifiable2\"): n2ExtensionFactory,\n\t\t\t},\n\t\t\textensionsConfigs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"notifiable1\"): n1ExtensionConfig,\n\t\t\t\tcomponent.MustNewID(\"notifiable2\"): n2ExtensionConfig,\n\t\t\t},\n\t\t\tserviceExtensions: []component.ID{\n\t\t\t\tcomponent.MustNewID(\"notifiable1\"),\n\t\t\t\tcomponent.MustNewID(\"notifiable2\"),\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"Errors in extension notification\",\n\t\t\tfactories: map[component.Type]extension.Factory{\n\t\t\t\tcomponent.MustNewType(\"notifiableErr\"): nErrExtensionFactory,\n\t\t\t},\n\t\t\textensionsConfigs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"notifiableErr\"): nErrExtensionConfig,\n\t\t\t},\n\t\t\tserviceExtensions: []component.ID{\n\t\t\t\tcomponent.MustNewID(\"notifiableErr\"),\n\t\t\t},\n\t\t\twant: notificationError,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\textensions, err := New(context.Background(), Settings{\n\t\t\t\tTelemetry:  componenttest.NewNopTelemetrySettings(),\n\t\t\t\tBuildInfo:  component.NewDefaultBuildInfo(),\n\t\t\t\tExtensions: builders.NewExtension(tt.extensionsConfigs, tt.factories),\n\t\t\t}, tt.serviceExtensions)\n\t\t\trequire.NoError(t, err)\n\t\t\terrs := extensions.NotifyConfig(context.Background(), confmap.NewFromStringMap(map[string]any{}))\n\t\t\tassert.Equal(t, tt.want, errs)\n\t\t})\n\t}\n}\n\ntype configWatcherExtension struct {\n\tfn func() error\n}\n\nfunc (comp *configWatcherExtension) Start(context.Context, component.Host) error {\n\treturn comp.fn()\n}\n\nfunc (comp *configWatcherExtension) Shutdown(context.Context) error {\n\treturn comp.fn()\n}\n\nfunc (comp *configWatcherExtension) NotifyConfig(context.Context, *confmap.Conf) error {\n\treturn comp.fn()\n}\n\nfunc newConfigWatcherExtension(fn func() error) *configWatcherExtension {\n\tcomp := &configWatcherExtension{\n\t\tfn: fn,\n\t}\n\n\treturn comp\n}\n\nfunc newConfigWatcherExtensionFactory(name component.Type, fn func() error) extension.Factory {\n\treturn extension.NewFactory(\n\t\tname,\n\t\tfunc() component.Config {\n\t\t\treturn &struct{}{}\n\t\t},\n\t\tfunc(context.Context, extension.Settings, component.Config) (extension.Extension, error) {\n\t\t\treturn newConfigWatcherExtension(fn), nil\n\t\t},\n\t\tcomponent.StabilityLevelDevelopment,\n\t)\n}\n\nfunc newBadExtensionFactory() extension.Factory {\n\treturn extension.NewFactory(\n\t\tcomponent.MustNewType(\"bf\"),\n\t\tfunc() component.Config {\n\t\t\treturn &struct{}{}\n\t\t},\n\t\tfunc(context.Context, extension.Settings, component.Config) (extension.Extension, error) {\n\t\t\treturn nil, nil\n\t\t},\n\t\tcomponent.StabilityLevelDevelopment,\n\t)\n}\n\nfunc newCreateErrorExtensionFactory() extension.Factory {\n\treturn extension.NewFactory(\n\t\tcomponent.MustNewType(\"err\"),\n\t\tfunc() component.Config {\n\t\t\treturn &struct{}{}\n\t\t},\n\t\tfunc(context.Context, extension.Settings, component.Config) (extension.Extension, error) {\n\t\t\treturn nil, errors.New(\"cannot create \\\"err\\\" extension type\")\n\t\t},\n\t\tcomponent.StabilityLevelDevelopment,\n\t)\n}\n\nfunc TestStatusReportedOnStartupShutdown(t *testing.T) {\n\t// compare two slices of status events ignoring timestamp\n\tassertEqualStatuses := func(t *testing.T, evts1, evts2 []*componentstatus.Event) {\n\t\tassert.Len(t, evts2, len(evts1))\n\t\tfor i := range evts1 {\n\t\t\tev1 := evts1[i]\n\t\t\tev2 := evts2[i]\n\t\t\tassert.Equal(t, ev1.Status(), ev2.Status())\n\t\t\tassert.Equal(t, ev1.Err(), ev2.Err())\n\t\t}\n\t}\n\n\tfor _, tt := range []struct {\n\t\tname             string\n\t\texpectedStatuses []*componentstatus.Event\n\t\tstartErr         error\n\t\tshutdownErr      error\n\t}{\n\t\t{\n\t\t\tname: \"successful startup/shutdown\",\n\t\t\texpectedStatuses: []*componentstatus.Event{\n\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStarting),\n\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusOK),\n\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopping),\n\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopped),\n\t\t\t},\n\t\t\tstartErr:    nil,\n\t\t\tshutdownErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"start error\",\n\t\t\texpectedStatuses: []*componentstatus.Event{\n\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStarting),\n\t\t\t\tcomponentstatus.NewPermanentErrorEvent(assert.AnError),\n\t\t\t},\n\t\t\tstartErr:    assert.AnError,\n\t\t\tshutdownErr: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"shutdown error\",\n\t\t\texpectedStatuses: []*componentstatus.Event{\n\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStarting),\n\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusOK),\n\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopping),\n\t\t\t\tcomponentstatus.NewPermanentErrorEvent(assert.AnError),\n\t\t\t},\n\t\t\tstartErr:    nil,\n\t\t\tshutdownErr: assert.AnError,\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tstatusType := component.MustNewType(\"statustest\")\n\t\t\tcompID := component.NewID(statusType)\n\t\t\tfactory := newStatusTestExtensionFactory(statusType, tt.startErr, tt.shutdownErr)\n\t\t\tconfig := factory.CreateDefaultConfig()\n\t\t\textensionsConfigs := map[component.ID]component.Config{\n\t\t\t\tcompID: config,\n\t\t\t}\n\t\t\tfactories := map[component.Type]extension.Factory{\n\t\t\t\tstatusType: factory,\n\t\t\t}\n\n\t\t\tvar actualStatuses []*componentstatus.Event\n\t\t\trep := status.NewReporter(func(_ *componentstatus.InstanceID, ev *componentstatus.Event) {\n\t\t\t\tactualStatuses = append(actualStatuses, ev)\n\t\t\t}, func(err error) {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t})\n\n\t\t\textensions, err := New(\n\t\t\t\tcontext.Background(),\n\t\t\t\tSettings{\n\t\t\t\t\tTelemetry:  componenttest.NewNopTelemetrySettings(),\n\t\t\t\t\tBuildInfo:  component.NewDefaultBuildInfo(),\n\t\t\t\t\tExtensions: builders.NewExtension(extensionsConfigs, factories),\n\t\t\t\t},\n\t\t\t\t[]component.ID{compID},\n\t\t\t\tWithReporter(rep),\n\t\t\t)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tassert.Equal(t, tt.startErr, extensions.Start(context.Background(), componenttest.NewNopHost()))\n\t\t\tif tt.startErr == nil {\n\t\t\t\tassert.Equal(t, tt.shutdownErr, extensions.Shutdown(context.Background()))\n\t\t\t}\n\t\t\tassertEqualStatuses(t, tt.expectedStatuses, actualStatuses)\n\t\t})\n\t}\n}\n\ntype statusTestExtension struct {\n\tstartErr    error\n\tshutdownErr error\n}\n\nfunc (ext *statusTestExtension) Start(context.Context, component.Host) error {\n\treturn ext.startErr\n}\n\nfunc (ext *statusTestExtension) Shutdown(context.Context) error {\n\treturn ext.shutdownErr\n}\n\nfunc newStatusTestExtension(startErr, shutdownErr error) *statusTestExtension {\n\treturn &statusTestExtension{\n\t\tstartErr:    startErr,\n\t\tshutdownErr: shutdownErr,\n\t}\n}\n\nfunc newStatusTestExtensionFactory(name component.Type, startErr, shutdownErr error) extension.Factory {\n\treturn extension.NewFactory(\n\t\tname,\n\t\tfunc() component.Config {\n\t\t\treturn &struct{}{}\n\t\t},\n\t\tfunc(context.Context, extension.Settings, component.Config) (extension.Extension, error) {\n\t\t\treturn newStatusTestExtension(startErr, shutdownErr), nil\n\t\t},\n\t\tcomponent.StabilityLevelDevelopment,\n\t)\n}\n\nfunc newRecordingExtensionFactory(startCallback func(set extension.Settings, host component.Host) error, shutdownCallback func(set extension.Settings) error) extension.Factory {\n\treturn extension.NewFactory(\n\t\tcomponent.MustNewType(\"recording\"),\n\t\tfunc() component.Config {\n\t\t\treturn &recordingExtensionConfig{}\n\t\t},\n\t\tfunc(_ context.Context, set extension.Settings, cfg component.Config) (extension.Extension, error) {\n\t\t\treturn &recordingExtension{\n\t\t\t\tconfig:           cfg.(recordingExtensionConfig),\n\t\t\t\tcreateSettings:   set,\n\t\t\t\tstartCallback:    startCallback,\n\t\t\t\tshutdownCallback: shutdownCallback,\n\t\t\t}, nil\n\t\t},\n\t\tcomponent.StabilityLevelDevelopment,\n\t)\n}\n\ntype recordingExtensionConfig struct {\n\tdependencies []string // names of dependencies of the same extension type\n}\n\ntype recordingExtension struct {\n\tconfig           recordingExtensionConfig\n\tstartCallback    func(set extension.Settings, host component.Host) error\n\tshutdownCallback func(set extension.Settings) error\n\tcreateSettings   extension.Settings\n}\n\nvar _ extensioncapabilities.Dependent = (*recordingExtension)(nil)\n\nfunc (ext *recordingExtension) Dependencies() []component.ID {\n\tif len(ext.config.dependencies) == 0 {\n\t\treturn nil\n\t}\n\tdeps := make([]component.ID, len(ext.config.dependencies))\n\tfor i, dep := range ext.config.dependencies {\n\t\tdeps[i] = component.MustNewIDWithName(\"recording\", dep)\n\t}\n\treturn deps\n}\n\nfunc (ext *recordingExtension) Start(_ context.Context, host component.Host) error {\n\treturn ext.startCallback(ext.createSettings, host)\n}\n\nfunc (ext *recordingExtension) Shutdown(context.Context) error {\n\treturn ext.shutdownCallback(ext.createSettings)\n}\n"
  },
  {
    "path": "service/extensions/graph.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensions // import \"go.opentelemetry.io/collector/service/extensions\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"gonum.org/v1/gonum/graph\"\n\t\"gonum.org/v1/gonum/graph/simple\"\n\t\"gonum.org/v1/gonum/graph/topo\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/extension/extensioncapabilities\"\n)\n\ntype node struct {\n\tnodeID int64\n\textID  component.ID\n}\n\nfunc (n node) ID() int64 {\n\treturn n.nodeID\n}\n\nfunc computeOrder(exts *Extensions) ([]component.ID, error) {\n\tgraph := simple.NewDirectedGraph()\n\tnodes := make(map[component.ID]*node)\n\tfor extID := range exts.extMap {\n\t\tn := &node{\n\t\t\tnodeID: int64(len(nodes) + 1),\n\t\t\textID:  extID,\n\t\t}\n\t\tgraph.AddNode(n)\n\t\tnodes[extID] = n\n\t}\n\tfor extID, ext := range exts.extMap {\n\t\tn := nodes[extID]\n\t\tif dep, ok := ext.(extensioncapabilities.Dependent); ok {\n\t\t\tfor _, depID := range dep.Dependencies() {\n\t\t\t\td, ok := nodes[depID]\n\t\t\t\tif !ok {\n\t\t\t\t\treturn nil, fmt.Errorf(\"unable to find extension %s on which extension %s depends\", depID, extID)\n\t\t\t\t}\n\t\t\t\tgraph.SetEdge(graph.NewEdge(d, n))\n\t\t\t}\n\t\t}\n\t}\n\torderedNodes, err := topo.Sort(graph)\n\tif err != nil {\n\t\treturn nil, cycleErr(err, topo.DirectedCyclesIn(graph))\n\t}\n\n\torder := make([]component.ID, len(orderedNodes))\n\tfor i, n := range orderedNodes {\n\t\torder[i] = n.(*node).extID\n\t}\n\treturn order, nil\n}\n\nfunc cycleErr(err error, cycles [][]graph.Node) error {\n\tvar topoErr topo.Unorderable\n\tif !errors.As(err, &topoErr) || len(cycles) == 0 || len(cycles[0]) == 0 {\n\t\treturn err\n\t}\n\n\tcycle := cycles[0]\n\tvar names []string\n\tfor _, n := range cycle {\n\t\tnode := n.(*node)\n\t\tnames = append(names, node.extID.String())\n\t}\n\tcycleStr := \"[\" + strings.Join(names, \" -> \") + \"]\"\n\treturn fmt.Errorf(\"unable to order extensions by dependencies, cycle found %s: %w\", cycleStr, err)\n}\n"
  },
  {
    "path": "service/extensions/graph_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensions // import \"go.opentelemetry.io/collector/service/extensions\"\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"gonum.org/v1/gonum/graph\"\n\t\"gonum.org/v1/gonum/graph/topo\"\n)\n\nfunc TestCycleErr(t *testing.T) {\n\terr := errors.New(\"foo\")\n\tassert.Equal(t, err, cycleErr(err, nil), \"cycleErr should return the error unchanged when it's unrecognized\")\n\n\tvar topoErr topo.Unorderable = [][]graph.Node{{}}\n\tassert.Equal(t, topoErr, cycleErr(topoErr, nil), \"cycleErr should return topo.Unorderable error unchanged when no cycles are found\")\n}\n"
  },
  {
    "path": "service/extensions/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage extensions\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "service/generated_package_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage service\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "service/go.mod",
    "content": "module go.opentelemetry.io/collector/service\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/google/uuid v1.6.0\n\tgithub.com/prometheus/client_model v0.6.2\n\tgithub.com/prometheus/common v0.67.5\n\tgithub.com/shirou/gopsutil/v4 v4.26.2\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/component/componentstatus v0.148.0\n\tgo.opentelemetry.io/collector/component/componenttest v0.148.0\n\tgo.opentelemetry.io/collector/config/confighttp v0.148.0\n\tgo.opentelemetry.io/collector/config/confignet v1.54.0\n\tgo.opentelemetry.io/collector/config/configtelemetry v0.148.0\n\tgo.opentelemetry.io/collector/confmap v1.54.0\n\tgo.opentelemetry.io/collector/confmap/xconfmap v0.148.0\n\tgo.opentelemetry.io/collector/connector v0.148.0\n\tgo.opentelemetry.io/collector/connector/connectortest v0.148.0\n\tgo.opentelemetry.io/collector/connector/xconnector v0.148.0\n\tgo.opentelemetry.io/collector/consumer v1.54.0\n\tgo.opentelemetry.io/collector/consumer/consumererror v0.148.0\n\tgo.opentelemetry.io/collector/consumer/consumertest v0.148.0\n\tgo.opentelemetry.io/collector/consumer/xconsumer v0.148.0\n\tgo.opentelemetry.io/collector/exporter v1.54.0\n\tgo.opentelemetry.io/collector/exporter/exportertest v0.148.0\n\tgo.opentelemetry.io/collector/exporter/xexporter v0.148.0\n\tgo.opentelemetry.io/collector/extension v1.54.0\n\tgo.opentelemetry.io/collector/extension/extensioncapabilities v0.148.0\n\tgo.opentelemetry.io/collector/extension/extensiontest v0.148.0\n\tgo.opentelemetry.io/collector/extension/zpagesextension v0.148.0\n\tgo.opentelemetry.io/collector/featuregate v1.54.0\n\tgo.opentelemetry.io/collector/internal/componentalias v0.148.0\n\tgo.opentelemetry.io/collector/internal/fanoutconsumer v0.148.0\n\tgo.opentelemetry.io/collector/internal/telemetry v0.148.0\n\tgo.opentelemetry.io/collector/internal/testutil v0.148.0\n\tgo.opentelemetry.io/collector/otelcol v0.148.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/pdata/pprofile v0.148.0\n\tgo.opentelemetry.io/collector/pdata/testdata v0.148.0\n\tgo.opentelemetry.io/collector/pdata/xpdata v0.148.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/pipeline/xpipeline v0.148.0\n\tgo.opentelemetry.io/collector/processor v1.54.0\n\tgo.opentelemetry.io/collector/processor/processortest v0.148.0\n\tgo.opentelemetry.io/collector/processor/xprocessor v0.148.0\n\tgo.opentelemetry.io/collector/receiver v1.54.0\n\tgo.opentelemetry.io/collector/receiver/receivertest v0.148.0\n\tgo.opentelemetry.io/collector/receiver/xreceiver v0.148.0\n\tgo.opentelemetry.io/collector/service/hostcapabilities v0.148.0\n\tgo.opentelemetry.io/collector/service/telemetry/telemetrytest v0.148.0\n\tgo.opentelemetry.io/contrib/bridges/otelzap v0.17.0\n\tgo.opentelemetry.io/contrib/otelconf v0.22.0\n\tgo.opentelemetry.io/contrib/propagators/b3 v1.42.0\n\tgo.opentelemetry.io/otel v1.42.0\n\tgo.opentelemetry.io/otel/log v0.18.0\n\tgo.opentelemetry.io/otel/metric v1.42.0\n\tgo.opentelemetry.io/otel/sdk v1.42.0\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0\n\tgo.opentelemetry.io/otel/trace v1.42.0\n\tgo.uber.org/goleak v1.3.0\n\tgo.uber.org/multierr v1.11.0\n\tgo.uber.org/zap v1.27.1\n\tgonum.org/v1/gonum v0.17.0\n)\n\nrequire (\n\tgithub.com/beorn7/perks v1.0.1 // indirect\n\tgithub.com/cenkalti/backoff/v5 v5.0.3 // indirect\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect\n\tgithub.com/ebitengine/purego v0.10.0 // indirect\n\tgithub.com/felixge/httpsnoop v1.0.4 // indirect\n\tgithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f // indirect\n\tgithub.com/fsnotify/fsnotify v1.9.0 // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/go-ole/go-ole v1.2.6 // indirect\n\tgithub.com/go-viper/mapstructure/v2 v2.5.0 // indirect\n\tgithub.com/gobwas/glob v0.2.3 // indirect\n\tgithub.com/golang/snappy v1.0.0 // indirect\n\tgithub.com/google/go-tpm v0.9.8 // indirect\n\tgithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/inconshreveable/mousetrap v1.1.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/klauspost/compress v1.18.4 // indirect\n\tgithub.com/knadh/koanf/maps v0.1.2 // indirect\n\tgithub.com/knadh/koanf/providers/confmap v1.0.0 // indirect\n\tgithub.com/knadh/koanf/v2 v2.3.3 // indirect\n\tgithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3 // indirect\n\tgithub.com/mitchellh/copystructure v1.2.0 // indirect\n\tgithub.com/mitchellh/reflectwalk v1.0.2 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect\n\tgithub.com/pierrec/lz4/v4 v4.1.26 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect\n\tgithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect\n\tgithub.com/prometheus/client_golang v1.23.2 // indirect\n\tgithub.com/prometheus/otlptranslator v1.0.0 // indirect\n\tgithub.com/prometheus/procfs v0.20.1 // indirect\n\tgithub.com/rs/cors v1.11.1 // indirect\n\tgithub.com/spf13/cobra v1.10.2 // indirect\n\tgithub.com/spf13/pflag v1.0.10 // indirect\n\tgithub.com/tklauser/go-sysconf v0.3.16 // indirect\n\tgithub.com/tklauser/numcpus v0.11.0 // indirect\n\tgithub.com/yusufpapurcu/wmi v1.2.4 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/client v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configauth v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configcompression v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configmiddleware v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configopaque v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configoptional v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/config/configtls v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionauth v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/extension/extensionmiddleware v0.148.0 // indirect\n\tgo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect\n\tgo.opentelemetry.io/contrib/zpages v0.67.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/prometheus v0.64.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/log v0.18.0 // indirect\n\tgo.opentelemetry.io/proto/otlp v1.10.0 // indirect\n\tgo.yaml.in/yaml/v2 v2.4.3 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/crypto v0.48.0 // indirect\n\tgolang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sys v0.42.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/connector => ../connector\n\nreplace go.opentelemetry.io/collector/connector/connectortest => ../connector/connectortest\n\nreplace go.opentelemetry.io/collector/component => ../component\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../component/componenttest\n\nreplace go.opentelemetry.io/collector/internal/telemetry => ../internal/telemetry/\n\nreplace go.opentelemetry.io/collector/component/componentstatus => ../component/componentstatus\n\nreplace go.opentelemetry.io/collector/pdata => ../pdata\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../pdata/testdata\n\nreplace go.opentelemetry.io/collector/extension/zpagesextension => ../extension/zpagesextension\n\nreplace go.opentelemetry.io/collector/extension => ../extension\n\nreplace go.opentelemetry.io/collector/exporter => ../exporter\n\nreplace go.opentelemetry.io/collector/confmap => ../confmap\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/config/configtelemetry => ../config/configtelemetry\n\nreplace go.opentelemetry.io/collector/pipeline => ../pipeline\n\nreplace go.opentelemetry.io/collector/processor => ../processor\n\nreplace go.opentelemetry.io/collector/processor/processortest => ../processor/processortest\n\nreplace go.opentelemetry.io/collector/consumer => ../consumer\n\nreplace go.opentelemetry.io/collector/service/hostcapabilities => ./hostcapabilities\n\nreplace go.opentelemetry.io/collector/service/telemetry/telemetrytest => ./telemetry/telemetrytest\n\nreplace go.opentelemetry.io/collector/receiver => ../receiver\n\nreplace go.opentelemetry.io/collector/featuregate => ../featuregate\n\nreplace go.opentelemetry.io/collector/config/configretry => ../config/configretry\n\nreplace go.opentelemetry.io/collector/extension/extensionauth => ../extension/extensionauth\n\nreplace go.opentelemetry.io/collector/extension/extensioncapabilities => ../extension/extensioncapabilities\n\nreplace go.opentelemetry.io/collector/config/configopaque => ../config/configopaque\n\nreplace go.opentelemetry.io/collector/config/confighttp => ../config/confighttp\n\nreplace go.opentelemetry.io/collector/config/configauth => ../config/configauth\n\nreplace go.opentelemetry.io/collector/config/configtls => ../config/configtls\n\nreplace go.opentelemetry.io/collector/config/configcompression => ../config/configcompression\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/client => ../client\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../receiver/receivertest\n\nreplace go.opentelemetry.io/collector/processor/xprocessor => ../processor/xprocessor\n\nreplace go.opentelemetry.io/collector/exporter/xexporter => ../exporter/xexporter\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/exporter/exportertest => ../exporter/exportertest\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/connector/xconnector => ../connector/xconnector\n\nreplace go.opentelemetry.io/collector/internal/fanoutconsumer => ../internal/fanoutconsumer\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../extension/extensiontest\n\nreplace go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest => ../extension/extensionauth/extensionauthtest\n\nreplace go.opentelemetry.io/collector/extension/xextension => ../extension/xextension\n\nreplace go.opentelemetry.io/collector/otelcol => ../otelcol\n\nreplace go.opentelemetry.io/collector/confmap/provider/fileprovider => ../confmap/provider/fileprovider\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ../extension/extensionmiddleware\n\nreplace go.opentelemetry.io/collector/config/configmiddleware => ../config/configmiddleware\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest => ../extension/extensionmiddleware/extensionmiddlewaretest\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper => ../exporter/exporterhelper\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../config/configoptional\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../internal/componentalias\n\nreplace go.opentelemetry.io/collector/config/confignet => ../config/confignet\n"
  },
  {
    "path": "service/go.sum",
    "content": "github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=\ngithub.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=\ngithub.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=\ngithub.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/ebitengine/purego v0.10.0 h1:QIw4xfpWT6GWTzaW5XEKy3HXoqrJGx1ijYHzTF0/ISU=\ngithub.com/ebitengine/purego v0.10.0/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ=\ngithub.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=\ngithub.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f h1:RJ+BDPLSHQO7cSjKBqjPJSbi1qfk9WcsjQDtZiw3dZw=\ngithub.com/foxboron/go-tpm-keyfiles v0.0.0-20251226215517-609e4778396f/go.mod h1:VHbbch/X4roIY22jL1s3qRbZhCiRIgUAF/PdSUcx2io=\ngithub.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=\ngithub.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY=\ngithub.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=\ngithub.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=\ngithub.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=\ngithub.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y=\ngithub.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=\ngithub.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/go-tpm v0.9.8 h1:slArAR9Ft+1ybZu0lBwpSmpwhRXaa85hWtMinMyRAWo=\ngithub.com/google/go-tpm v0.9.8/go.mod h1:h9jEsEECg7gtLis0upRBQU+GhYVH6jMjrFxI8u6bVUY=\ngithub.com/google/go-tpm-tools v0.4.7 h1:J3ycC8umYxM9A4eF73EofRZu4BxY0jjQnUnkhIBbvws=\ngithub.com/google/go-tpm-tools v0.4.7/go.mod h1:gSyXTZHe3fgbzb6WEGd90QucmsnT1SRdlye82gH8QjQ=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=\ngithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=\ngithub.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=\ngithub.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=\ngithub.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=\ngithub.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=\ngithub.com/knadh/koanf/maps v0.1.2 h1:RBfmAW5CnZT+PJ1CVc1QSJKf4Xu9kxfQgYVQSu8hpbo=\ngithub.com/knadh/koanf/maps v0.1.2/go.mod h1:npD/QZY3V6ghQDdcQzl1W4ICNVTkohC8E73eI2xW4yI=\ngithub.com/knadh/koanf/providers/confmap v1.0.0 h1:mHKLJTE7iXEys6deO5p6olAiZdG5zwp8Aebir+/EaRE=\ngithub.com/knadh/koanf/providers/confmap v1.0.0/go.mod h1:txHYHiI2hAtF0/0sCmcuol4IDcuQbKTybiB1nOcUo1A=\ngithub.com/knadh/koanf/v2 v2.3.3 h1:jLJC8XCRfLC7n4F+ZKKdBsbq1bfXTpuFhf4L7t94D94=\ngithub.com/knadh/koanf/v2 v2.3.3/go.mod h1:gRb40VRAbd4iJMYYD5IxZ6hfuopFcXBpc9bbQpZwo28=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=\ngithub.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=\ngithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3 h1:PwQumkgq4/acIiZhtifTV5OUqqiP82UAl0h87xj/l9k=\ngithub.com/lufia/plan9stats v0.0.0-20251013123823-9fd1530e3ec3/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=\ngithub.com/mitchellh/copystructure v1.2.0 h1:vpKXTN4ewci03Vljg/q9QvCGUDttBOGBIa15WveJJGw=\ngithub.com/mitchellh/copystructure v1.2.0/go.mod h1:qLl+cE2AmVv+CoeAwDPye/v+N2HKCj9FbZEVFJRxO9s=\ngithub.com/mitchellh/reflectwalk v1.0.2 h1:G2LzWKi524PWgd3mLHV8Y5k7s6XUvT0Gef6zxSIeXaQ=\ngithub.com/mitchellh/reflectwalk v1.0.2/go.mod h1:mSTlrgnPZtwu0c4WaC2kGObEpuNDbx0jmZXqmk4esnw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=\ngithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=\ngithub.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=\ngithub.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 h1:o4JXh1EVt9k/+g42oCprj/FisM4qX9L3sZB3upGN2ZU=\ngithub.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55/go.mod h1:OmDBASR4679mdNQnz2pUhc2G8CO2JrUAVFDRBDP/hJE=\ngithub.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=\ngithub.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=\ngithub.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=\ngithub.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=\ngithub.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=\ngithub.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=\ngithub.com/prometheus/otlptranslator v1.0.0 h1:s0LJW/iN9dkIH+EnhiD3BlkkP5QVIUVEoIwkU+A6qos=\ngithub.com/prometheus/otlptranslator v1.0.0/go.mod h1:vRYWnXvI6aWGpsdY/mOT/cbeVRBlPWtBNDb7kGR3uKM=\ngithub.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc=\ngithub.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=\ngithub.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=\ngithub.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=\ngithub.com/shirou/gopsutil/v4 v4.26.2 h1:X8i6sicvUFih4BmYIGT1m2wwgw2VG9YgrDTi7cIRGUI=\ngithub.com/shirou/gopsutil/v4 v4.26.2/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUNMGBtDkJBaLQ=\ngithub.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=\ngithub.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=\ngithub.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=\ngithub.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngithub.com/tklauser/go-sysconf v0.3.16 h1:frioLaCQSsF5Cy1jgRBrzr6t502KIIwQ0MArYICU0nA=\ngithub.com/tklauser/go-sysconf v0.3.16/go.mod h1:/qNL9xxDhc7tx3HSRsLWNnuzbVfh3e7gh/BmM179nYI=\ngithub.com/tklauser/numcpus v0.11.0 h1:nSTwhKH5e1dMNsCdVBukSZrURJRoHbSEQjdEbY+9RXw=\ngithub.com/tklauser/numcpus v0.11.0/go.mod h1:z+LwcLq54uWZTX0u/bGobaV34u6V7KNlTZejzM6/3MQ=\ngithub.com/yusufpapurcu/wmi v1.2.4 h1:zFUKzehAFReQwLys1b/iSMl+JQGSCSjtVqQn9bBrPo0=\ngithub.com/yusufpapurcu/wmi v1.2.4/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/contrib/bridges/otelzap v0.17.0 h1:oCltVHJcblcth2z9B9dRTeZIZTe2Sf9Ad9h8bcc+s8M=\ngo.opentelemetry.io/contrib/bridges/otelzap v0.17.0/go.mod h1:G/VE1A/hRn6mEWdfC8rMvSdQVGM64KUPi4XilLkwcQw=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=\ngo.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=\ngo.opentelemetry.io/contrib/otelconf v0.22.0 h1:+kpcfczGOFM85zDZyqQCzWefhovegfn24D0WwmQz0n4=\ngo.opentelemetry.io/contrib/otelconf v0.22.0/go.mod h1:ojdbOukO+JRDJQmJY2PRIZEg0UYVzcOuZR59hp7xffc=\ngo.opentelemetry.io/contrib/propagators/b3 v1.42.0 h1:B2Pew5ufEtgkjLF+tSkXjgYZXQr9m7aCm1wLKB0URbU=\ngo.opentelemetry.io/contrib/propagators/b3 v1.42.0/go.mod h1:iPgUcSEF5DORW6+yNbdw/YevUy+QqJ508ncjhrRSCjc=\ngo.opentelemetry.io/contrib/zpages v0.67.0 h1:cIUwWSVDovuLEbDIKreptjdxMuIhGiqwq0uL8YNaq1c=\ngo.opentelemetry.io/contrib/zpages v0.67.0/go.mod h1:vK8fsYHgPYg4Z/XDbFSEvItSGZDbjWTvjBOu8+AiDhc=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0 h1:deI9UQMoGFgrg5iLPgzueqFPHevDl+28YKfSpPTI6rY=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0/go.mod h1:PFx9NgpNUKXdf7J4Q3agRxMs3Y07QhTCVipKmLsMKnU=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0 h1:icqq3Z34UrEFk2u+HMhTtRsvo7Ues+eiJVjaJt62njs=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0/go.mod h1:W2m8P+d5Wn5kipj4/xmbt9uMqezEKfBjzVJadfABSBE=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0 h1:MdKucPl/HbzckWWEisiNqMPhRrAOQX8r4jTuGr636gk=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0/go.mod h1:RolT8tWtfHcjajEH5wFIZ4Dgh5jpPdFXYV9pTAk/qjc=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0 h1:H7O6RlGOMTizyl3R08Kn5pdM06bnH8oscSj7o11tmLA=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0/go.mod h1:mBFWu/WOVDkWWsR7Tx7h6EpQB8wsv7P0Yrh0Pb7othc=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 h1:THuZiwpQZuHPul65w4WcwEnkX2QIuMT+UFoOrygtoJw=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0/go.mod h1:J2pvYM5NGHofZ2/Ru6zw/TNWnEQp5crgyDeSrYpXkAw=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0 h1:zWWrB1U6nqhS/k6zYB74CjRpuiitRtLLi68VcgmOEto=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0/go.mod h1:2qXPNBX1OVRC0IwOnfo1ljoid+RD0QK3443EaqVlsOU=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 h1:uLXP+3mghfMf7XmV4PkGfFhFKuNWoCvvx5wP/wOXo0o=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0/go.mod h1:v0Tj04armyT59mnURNUJf7RCKcKzq+lgJs6QSjHjaTc=\ngo.opentelemetry.io/otel/exporters/prometheus v0.64.0 h1:g0LRDXMX/G1SEZtK8zl8Chm4K6GBwRkjPKE36LxiTYs=\ngo.opentelemetry.io/otel/exporters/prometheus v0.64.0/go.mod h1:UrgcjnarfdlBDP3GjDIJWe6HTprwSazNjwsI+Ru6hro=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0 h1:KJVjPD3rcPb98rIs3HznyJlrfx9ge5oJvxxlGR+P/7s=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0/go.mod h1:K3kRa2ckmHWQaTWQdPRHc7qGXASuVuoEQXzrvlA98Ws=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0 h1:lSZHgNHfbmQTPfuTmWVkEu8J8qXaQwuV30pjCcAUvP8=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0/go.mod h1:so9ounLcuoRDu033MW/E0AD4hhUjVqswrMF5FoZlBcw=\ngo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0 h1:s/1iRkCKDfhlh1JF26knRneorus8aOwVIDhvYx9WoDw=\ngo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0/go.mod h1:UI3wi0FXg1Pofb8ZBiBLhtMzgoTm1TYkMvn71fAqDzs=\ngo.opentelemetry.io/otel/log v0.18.0 h1:XgeQIIBjZZrliksMEbcwMZefoOSMI1hdjiLEiiB0bAg=\ngo.opentelemetry.io/otel/log v0.18.0/go.mod h1:KEV1kad0NofR3ycsiDH4Yjcoj0+8206I6Ox2QYFSNgI=\ngo.opentelemetry.io/otel/log/logtest v0.18.0 h1:2QeyoKJdIgK2LJhG1yn78o/zmpXx1EditeyRDREqVS8=\ngo.opentelemetry.io/otel/log/logtest v0.18.0/go.mod h1:v1vh3PYR9zIa5MK6HwkH2lMrLBg/Y9Of6Qc+krlesX0=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/log v0.18.0 h1:n8OyZr7t7otkeTnPTbDNom6rW16TBYGtvyy2Gk6buQw=\ngo.opentelemetry.io/otel/sdk/log v0.18.0/go.mod h1:C0+wxkTwKpOCZLrlJ3pewPiiQwpzycPI/u6W0Z9fuYk=\ngo.opentelemetry.io/otel/sdk/log/logtest v0.18.0 h1:l3mYuPsuBx6UKE47BVcPrZoZ0q/KER57vbj2qkgDLXA=\ngo.opentelemetry.io/otel/sdk/log/logtest v0.18.0/go.mod h1:7cHtiVJpZebB3wybTa4NG+FUo5NPe3PROz1FqB0+qdw=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=\ngo.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=\ngo.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/crypto v0.48.0 h1:/VRzVqiRSggnhY7gNRxPauEQ5Drw9haKdM0jqfcCFts=\ngolang.org/x/crypto v0.48.0/go.mod h1:r0kV5h3qnFPlQnBSrULhlsRfryS2pmewsg+XfMgkVos=\ngolang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa h1:Zt3DZoOFFYkKhDT3v7Lm9FDMEV06GpzjG2jrqW+QTE0=\ngolang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=\ngolang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=\ngolang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=\ngonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=\ngoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 h1:tu/dtnW1o3wfaxCOjSLn5IRX4YDcJrtlpzYkhHhGaC4=\ngoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171/go.mod h1:M5krXqk4GhBKvB596udGL3UyjL4I1+cTbK0orROM9ng=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "service/hostcapabilities/Makefile",
    "content": "include ../../Makefile.Common\n"
  },
  {
    "path": "service/hostcapabilities/go.mod",
    "content": "module go.opentelemetry.io/collector/service/hostcapabilities\n\ngo 1.25.0\n\nrequire (\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/pipeline v1.54.0\n\tgo.opentelemetry.io/collector/service v0.148.0\n)\n\nrequire (\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/collector/pdata v1.54.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/trace v1.42.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.uber.org/zap v1.27.1 // indirect\n)\n\nreplace (\n\tgo.opentelemetry.io/collector/client => ../../client\n\tgo.opentelemetry.io/collector/component => ../../component\n\tgo.opentelemetry.io/collector/component/componentstatus => ../../component/componentstatus\n\tgo.opentelemetry.io/collector/component/componenttest => ../../component/componenttest\n\tgo.opentelemetry.io/collector/config/configauth => ../../config/configauth\n\tgo.opentelemetry.io/collector/config/configcompression => ../../config/configcompression\n\tgo.opentelemetry.io/collector/config/confighttp => ../../config/confighttp\n\tgo.opentelemetry.io/collector/config/configopaque => ../../config/configopaque\n\tgo.opentelemetry.io/collector/config/configretry => ../../config/configretry\n\tgo.opentelemetry.io/collector/config/configtelemetry => ../../config/configtelemetry\n\tgo.opentelemetry.io/collector/config/configtls => ../../config/configtls\n\tgo.opentelemetry.io/collector/confmap => ../../confmap\n\tgo.opentelemetry.io/collector/confmap/xconfmap => ../../confmap/xconfmap\n\tgo.opentelemetry.io/collector/connector => ../../connector\n\tgo.opentelemetry.io/collector/connector/connectortest => ../../connector/connectortest\n\tgo.opentelemetry.io/collector/connector/xconnector => ../../connector/xconnector\n\tgo.opentelemetry.io/collector/consumer => ../../consumer\n\tgo.opentelemetry.io/collector/consumer/consumererror => ../../consumer/consumererror\n\tgo.opentelemetry.io/collector/consumer/consumertest => ../../consumer/consumertest\n\tgo.opentelemetry.io/collector/consumer/xconsumer => ../../consumer/xconsumer\n\tgo.opentelemetry.io/collector/exporter => ../../exporter\n\tgo.opentelemetry.io/collector/exporter/exportertest => ../../exporter/exportertest\n\tgo.opentelemetry.io/collector/exporter/xexporter => ../../exporter/xexporter\n\tgo.opentelemetry.io/collector/extension => ../../extension\n\tgo.opentelemetry.io/collector/extension/extensionauth => ../../extension/extensionauth\n\tgo.opentelemetry.io/collector/extension/extensionauth/extensionauthtest => ../../extension/extensionauth/extensionauthtest\n\tgo.opentelemetry.io/collector/extension/extensioncapabilities => ../../extension/extensioncapabilities\n\tgo.opentelemetry.io/collector/extension/extensiontest => ../../extension/extensiontest\n\tgo.opentelemetry.io/collector/extension/xextension => ../../extension/xextension\n\tgo.opentelemetry.io/collector/extension/zpagesextension => ../../extension/zpagesextension\n\tgo.opentelemetry.io/collector/featuregate => ../../featuregate\n\tgo.opentelemetry.io/collector/internal/fanoutconsumer => ../../internal/fanoutconsumer\n\tgo.opentelemetry.io/collector/internal/telemetry => ../../internal/telemetry\n\tgo.opentelemetry.io/collector/pdata => ../../pdata\n\tgo.opentelemetry.io/collector/pdata/pprofile => ../../pdata/pprofile\n\tgo.opentelemetry.io/collector/pdata/testdata => ../../pdata/testdata\n\tgo.opentelemetry.io/collector/pipeline => ../../pipeline\n\tgo.opentelemetry.io/collector/pipeline/xpipeline => ../../pipeline/xpipeline\n\tgo.opentelemetry.io/collector/processor => ../../processor\n\tgo.opentelemetry.io/collector/processor/processortest => ../../processor/processortest\n\tgo.opentelemetry.io/collector/processor/xprocessor => ../../processor/xprocessor\n\tgo.opentelemetry.io/collector/receiver => ../../receiver\n\tgo.opentelemetry.io/collector/receiver/receivertest => ../../receiver/receivertest\n\tgo.opentelemetry.io/collector/receiver/xreceiver => ../../receiver/xreceiver\n\n\tgo.opentelemetry.io/collector/service => ..\n)\n\nreplace go.opentelemetry.io/collector/otelcol => ../../otelcol\n\nreplace go.opentelemetry.io/collector/confmap/provider/fileprovider => ../../confmap/provider/fileprovider\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest => ../../extension/extensionmiddleware/extensionmiddlewaretest\n\nreplace go.opentelemetry.io/collector/config/configmiddleware => ../../config/configmiddleware\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ../../extension/extensionmiddleware\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper => ../../exporter/exporterhelper\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../../config/configoptional\n\nreplace go.opentelemetry.io/collector/service/telemetry/telemetrytest => ../telemetry/telemetrytest\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../internal/componentalias\n\nreplace go.opentelemetry.io/collector/config/confignet => ../../config/confignet\n"
  },
  {
    "path": "service/hostcapabilities/go.sum",
    "content": "github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "service/hostcapabilities/interfaces.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package hostcapabilities provides interfaces that can be implemented by the host\n// to provide additional capabilities.\npackage hostcapabilities // import \"go.opentelemetry.io/collector/service/hostcapabilities\"\n\nimport (\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/service/internal/moduleinfo\"\n)\n\n// ModuleInfo is an interface that may be implemented by the host to provide\n// information about modules that were used to build the host.\ntype ModuleInfo interface {\n\t// GetModuleInfos returns the module information for the host\n\t// i.e. Receivers, Processors, Exporters, Extensions, and Connectors\n\tGetModuleInfos() moduleinfo.ModuleInfos\n}\n\n// ExposeExporters is an interface that may be implemented by the host to provide\n// access to the exporters that were used to build the host.\n//\n// Deprecated: [v0.121.0] Will be removed in Service 1.0.\n// See: https://github.com/open-telemetry/opentelemetry-collector/issues/7370 for service 1.0\ntype ExposeExporters interface {\n\tGetExporters() map[pipeline.Signal]map[component.ID]component.Component\n}\n\n// ComponentFactory is an interface that may be implemented by the host to\n// provide a component's factory\ntype ComponentFactory interface {\n\t// GetFactory returns the component factory for the given\n\t// component type\n\tGetFactory(kind component.Kind, componentType component.Type) component.Factory\n}\n"
  },
  {
    "path": "service/hostcapabilities/metadata.yaml",
    "content": "type: service/hostcapabilities\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "service/internal/attribute/attribute.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage attribute // import \"go.opentelemetry.io/collector/service/internal/attribute\"\n\nimport (\n\t\"hash/fnv\"\n\t\"strings\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/internal/telemetry\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\nconst (\n\tcapabiltiesKind = \"capabilities\"\n\tfanoutKind      = \"fanout\"\n)\n\ntype Attributes struct {\n\tset attribute.Set\n\tid  int64\n}\n\nfunc newAttributes(attrs ...attribute.KeyValue) Attributes {\n\th := fnv.New64a()\n\tfor _, kv := range attrs {\n\t\th.Write([]byte(\"(\" + string(kv.Key) + \"|\" + kv.Value.AsString() + \")\"))\n\t}\n\treturn Attributes{\n\t\tset: attribute.NewSet(attrs...),\n\n\t\t// The graph identifies nodes by an int64 ID, but fnv gives us a uint64.\n\t\t// It is safe to cast because the meaning of the number is irrelevant.\n\t\t// We only care that each node has a unique 64 bit ID, which is unaltered by this cast.\n\t\tid: int64(h.Sum64()), // #nosec G115\n\t}\n}\n\nfunc (a Attributes) Set() *attribute.Set {\n\treturn &a.set\n}\n\nfunc (a Attributes) ID() int64 {\n\treturn a.id\n}\n\nfunc Receiver(pipelineType pipeline.Signal, id component.ID) Attributes {\n\treturn newAttributes(\n\t\tattribute.String(telemetry.ComponentKindKey, strings.ToLower(component.KindReceiver.String())),\n\t\tattribute.String(telemetry.SignalKey, pipelineType.String()),\n\t\tattribute.String(telemetry.ComponentIDKey, id.String()),\n\t)\n}\n\nfunc Processor(pipelineID pipeline.ID, id component.ID) Attributes {\n\treturn newAttributes(\n\t\tattribute.String(telemetry.ComponentKindKey, strings.ToLower(component.KindProcessor.String())),\n\t\tattribute.String(telemetry.SignalKey, pipelineID.Signal().String()),\n\t\tattribute.String(telemetry.PipelineIDKey, pipelineID.String()),\n\t\tattribute.String(telemetry.ComponentIDKey, id.String()),\n\t)\n}\n\nfunc Exporter(pipelineType pipeline.Signal, id component.ID) Attributes {\n\treturn newAttributes(\n\t\tattribute.String(telemetry.ComponentKindKey, strings.ToLower(component.KindExporter.String())),\n\t\tattribute.String(telemetry.SignalKey, pipelineType.String()),\n\t\tattribute.String(telemetry.ComponentIDKey, id.String()),\n\t)\n}\n\nfunc Connector(exprPipelineType, rcvrPipelineType pipeline.Signal, id component.ID) Attributes {\n\treturn newAttributes(\n\t\tattribute.String(telemetry.ComponentKindKey, strings.ToLower(component.KindConnector.String())),\n\t\tattribute.String(telemetry.SignalKey, exprPipelineType.String()),\n\t\tattribute.String(telemetry.SignalOutputKey, rcvrPipelineType.String()),\n\t\tattribute.String(telemetry.ComponentIDKey, id.String()),\n\t)\n}\n\nfunc Extension(id component.ID) Attributes {\n\treturn newAttributes(\n\t\tattribute.String(telemetry.ComponentKindKey, strings.ToLower(component.KindExtension.String())),\n\t\tattribute.String(telemetry.ComponentIDKey, id.String()),\n\t)\n}\n\nfunc Capabilities(pipelineID pipeline.ID) Attributes {\n\treturn newAttributes(\n\t\tattribute.String(telemetry.ComponentKindKey, capabiltiesKind),\n\t\tattribute.String(telemetry.PipelineIDKey, pipelineID.String()),\n\t)\n}\n\nfunc Fanout(pipelineID pipeline.ID) Attributes {\n\treturn newAttributes(\n\t\tattribute.String(telemetry.ComponentKindKey, fanoutKind),\n\t\tattribute.String(telemetry.PipelineIDKey, pipelineID.String()),\n\t)\n}\n"
  },
  {
    "path": "service/internal/attribute/attribute_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage attribute_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/internal/telemetry\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\t\"go.opentelemetry.io/collector/service/internal/attribute\"\n)\n\nvar (\n\tsignals = []pipeline.Signal{\n\t\tpipeline.SignalTraces,\n\t\tpipeline.SignalMetrics,\n\t\tpipeline.SignalLogs,\n\t\txpipeline.SignalProfiles,\n\t}\n\n\tcIDs = []component.ID{\n\t\tcomponent.MustNewID(\"foo\"),\n\t\tcomponent.MustNewID(\"foo2\"),\n\t\tcomponent.MustNewID(\"bar\"),\n\t}\n\n\tpIDs = []pipeline.ID{\n\t\tpipeline.NewID(pipeline.SignalTraces),\n\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"2\"),\n\t\tpipeline.NewID(pipeline.SignalMetrics),\n\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"2\"),\n\t\tpipeline.NewID(pipeline.SignalLogs),\n\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"2\"),\n\t\tpipeline.NewID(xpipeline.SignalProfiles),\n\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"2\"),\n\t}\n)\n\nfunc TestReceiver(t *testing.T) {\n\tfor _, sig := range signals {\n\t\tfor _, id := range cIDs {\n\t\t\tr := attribute.Receiver(sig, id)\n\t\t\tcomponentKind, ok := r.Set().Value(telemetry.ComponentKindKey)\n\t\t\trequire.True(t, ok)\n\t\t\trequire.Equal(t, \"receiver\", componentKind.AsString())\n\n\t\t\tsignal, ok := r.Set().Value(telemetry.SignalKey)\n\t\t\trequire.True(t, ok)\n\t\t\trequire.Equal(t, sig.String(), signal.AsString())\n\n\t\t\tcomponentID, ok := r.Set().Value(telemetry.ComponentIDKey)\n\t\t\trequire.True(t, ok)\n\t\t\trequire.Equal(t, id.String(), componentID.AsString())\n\t\t}\n\t}\n}\n\nfunc TestProcessor(t *testing.T) {\n\tfor _, pID := range pIDs {\n\t\tfor _, id := range cIDs {\n\t\t\tp := attribute.Processor(pID, id)\n\t\t\tcomponentKind, ok := p.Set().Value(telemetry.ComponentKindKey)\n\t\t\trequire.True(t, ok)\n\t\t\trequire.Equal(t, \"processor\", componentKind.AsString())\n\n\t\t\tpipelineID, ok := p.Set().Value(telemetry.PipelineIDKey)\n\t\t\trequire.True(t, ok)\n\t\t\trequire.Equal(t, pID.String(), pipelineID.AsString())\n\n\t\t\tcomponentID, ok := p.Set().Value(telemetry.ComponentIDKey)\n\t\t\trequire.True(t, ok)\n\t\t\trequire.Equal(t, id.String(), componentID.AsString())\n\t\t}\n\t}\n}\n\nfunc TestExporter(t *testing.T) {\n\tfor _, sig := range signals {\n\t\tfor _, id := range cIDs {\n\t\t\te := attribute.Exporter(sig, id)\n\t\t\tcomponentKind, ok := e.Set().Value(telemetry.ComponentKindKey)\n\t\t\trequire.True(t, ok)\n\t\t\trequire.Equal(t, \"exporter\", componentKind.AsString())\n\n\t\t\tsignal, ok := e.Set().Value(telemetry.SignalKey)\n\t\t\trequire.True(t, ok)\n\t\t\trequire.Equal(t, sig.String(), signal.AsString())\n\n\t\t\tcomponentID, ok := e.Set().Value(telemetry.ComponentIDKey)\n\t\t\trequire.True(t, ok)\n\t\t\trequire.Equal(t, id.String(), componentID.AsString())\n\t\t}\n\t}\n}\n\nfunc TestConnector(t *testing.T) {\n\tfor _, exprSig := range signals {\n\t\tfor _, rcvrSig := range signals {\n\t\t\tfor _, id := range cIDs {\n\t\t\t\tc := attribute.Connector(exprSig, rcvrSig, id)\n\t\t\t\tcomponentKind, ok := c.Set().Value(telemetry.ComponentKindKey)\n\t\t\t\trequire.True(t, ok)\n\t\t\t\trequire.Equal(t, \"connector\", componentKind.AsString())\n\n\t\t\t\tsignal, ok := c.Set().Value(telemetry.SignalKey)\n\t\t\t\trequire.True(t, ok)\n\t\t\t\trequire.Equal(t, exprSig.String(), signal.AsString())\n\n\t\t\t\tsignalOutput, ok := c.Set().Value(telemetry.SignalOutputKey)\n\t\t\t\trequire.True(t, ok)\n\t\t\t\trequire.Equal(t, rcvrSig.String(), signalOutput.AsString())\n\n\t\t\t\tcomponentID, ok := c.Set().Value(telemetry.ComponentIDKey)\n\t\t\t\trequire.True(t, ok)\n\t\t\t\trequire.Equal(t, id.String(), componentID.AsString())\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc TestExtension(t *testing.T) {\n\te := attribute.Extension(component.MustNewID(\"foo\"))\n\tcomponentKind, ok := e.Set().Value(telemetry.ComponentKindKey)\n\trequire.True(t, ok)\n\trequire.Equal(t, \"extension\", componentKind.AsString())\n}\n\nfunc TestSetEquality(t *testing.T) {\n\t// The sets are created independently but should be exactly equivalent.\n\t// We will ensure that corresponding elements are equal and that\n\t// non-corresponding elements are not equal.\n\tsetI, setJ := createExampleSets(), createExampleSets()\n\tfor i, ei := range setI {\n\t\tfor j, ej := range setJ {\n\t\t\tif i == j {\n\t\t\t\trequire.Equal(t, ei.ID(), ej.ID())\n\t\t\t\tsi, sj := ei.Set(), ej.Set()\n\t\t\t\trequire.True(t, si.Equals(sj))\n\t\t\t} else {\n\t\t\t\trequire.NotEqual(t, ei.ID(), ej.ID())\n\t\t\t\tsi, sj := ei.Set(), ej.Set()\n\t\t\t\trequire.False(t, si.Equals(sj))\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc createExampleSets() []attribute.Attributes {\n\tsets := []attribute.Attributes{}\n\n\t// Receiver examples.\n\tfor _, sig := range signals {\n\t\tfor _, id := range cIDs {\n\t\t\tsets = append(sets, attribute.Receiver(sig, id))\n\t\t}\n\t}\n\n\t// Processor examples.\n\tfor _, pID := range pIDs {\n\t\tfor _, cID := range cIDs {\n\t\t\tsets = append(sets, attribute.Processor(pID, cID))\n\t\t}\n\t}\n\n\t// Exporter examples.\n\tfor _, sig := range signals {\n\t\tfor _, id := range cIDs {\n\t\t\tsets = append(sets, attribute.Exporter(sig, id))\n\t\t}\n\t}\n\n\t// Connector examples.\n\tfor _, exprSig := range signals {\n\t\tfor _, rcvrSig := range signals {\n\t\t\tfor _, id := range cIDs {\n\t\t\t\tsets = append(sets, attribute.Connector(exprSig, rcvrSig, id))\n\t\t\t}\n\t\t}\n\t}\n\n\t// Capabilities examples.\n\tfor _, pID := range pIDs {\n\t\tsets = append(sets, attribute.Capabilities(pID))\n\t}\n\n\t// Fanout examples.\n\tfor _, pID := range pIDs {\n\t\tsets = append(sets, attribute.Fanout(pID))\n\t}\n\n\treturn sets\n}\n"
  },
  {
    "path": "service/internal/builders/builders.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builders // import \"go.opentelemetry.io/collector/service/internal/builders\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n)\n\nvar (\n\terrNilNextConsumer = errors.New(\"nil next Consumer\")\n\tNopType            = component.MustNewType(\"nop\")\n)\n\n// logStabilityLevel logs the stability level of a component. The log level is set to info for\n// undefined, unmaintained, deprecated and development. The log level is set to debug\n// for alpha, beta and stable.\nfunc logStabilityLevel(logger *zap.Logger, sl component.StabilityLevel) {\n\tif sl >= component.StabilityLevelAlpha {\n\t\tlogger.Debug(sl.LogMessage())\n\t} else {\n\t\tlogger.Info(sl.LogMessage())\n\t}\n}\n\n// logDeprecatedTypeAlias checks if the provided type is a deprecated alias and logs a warning if so.\nfunc logDeprecatedTypeAlias(logger *zap.Logger, factory component.Factory, usedType component.Type) {\n\ttah, ok := factory.(componentalias.TypeAliasHolder)\n\tif !ok {\n\t\treturn\n\t}\n\talias := tah.DeprecatedAlias()\n\tif alias.String() != \"\" && usedType == alias {\n\t\tlogger.Warn(fmt.Sprintf(\"%q alias is deprecated; use %q instead\", alias.String(), factory.Type().String()))\n\t}\n}\n"
  },
  {
    "path": "service/internal/builders/builders_test/connector_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builders\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/connectortest\"\n\t\"go.opentelemetry.io/collector/connector/xconnector\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/otelcol\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n)\n\nfunc TestConnectorBuilder(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tfactories, err := otelcol.MakeFactoryMap([]connector.Factory{\n\t\tconnector.NewFactory(component.MustNewType(\"err\"), nil),\n\t\txconnector.NewFactory(\n\t\t\tcomponent.MustNewType(\"all\"),\n\t\t\tfunc() component.Config { return &defaultCfg },\n\t\t\txconnector.WithTracesToTraces(createConnectorTracesToTraces, component.StabilityLevelDevelopment),\n\t\t\txconnector.WithTracesToMetrics(createConnectorTracesToMetrics, component.StabilityLevelDevelopment),\n\t\t\txconnector.WithTracesToLogs(createConnectorTracesToLogs, component.StabilityLevelDevelopment),\n\t\t\txconnector.WithTracesToProfiles(createConnectorTracesToProfiles, component.StabilityLevelDevelopment),\n\t\t\txconnector.WithMetricsToTraces(createConnectorMetricsToTraces, component.StabilityLevelAlpha),\n\t\t\txconnector.WithMetricsToMetrics(createConnectorMetricsToMetrics, component.StabilityLevelAlpha),\n\t\t\txconnector.WithMetricsToLogs(createConnectorMetricsToLogs, component.StabilityLevelAlpha),\n\t\t\txconnector.WithMetricsToProfiles(createConnectorMetricsToProfiles, component.StabilityLevelAlpha),\n\t\t\txconnector.WithLogsToTraces(createConnectorLogsToTraces, component.StabilityLevelDeprecated),\n\t\t\txconnector.WithLogsToMetrics(createConnectorLogsToMetrics, component.StabilityLevelDeprecated),\n\t\t\txconnector.WithLogsToLogs(createConnectorLogsToLogs, component.StabilityLevelDeprecated),\n\t\t\txconnector.WithLogsToProfiles(createConnectorLogsToProfiles, component.StabilityLevelDeprecated),\n\t\t\txconnector.WithProfilesToTraces(createxconnectorToTraces, component.StabilityLevelDevelopment),\n\t\t\txconnector.WithProfilesToMetrics(createxconnectorToMetrics, component.StabilityLevelDevelopment),\n\t\t\txconnector.WithProfilesToLogs(createxconnectorToLogs, component.StabilityLevelDevelopment),\n\t\t\txconnector.WithProfilesToProfiles(createxconnectorToProfiles, component.StabilityLevelDevelopment),\n\t\t),\n\t}...)\n\trequire.NoError(t, err)\n\n\ttestCases := []struct {\n\t\tname         string\n\t\tid           component.ID\n\t\terr          func(pipeline.Signal, pipeline.Signal) string\n\t\tnextTraces   consumer.Traces\n\t\tnextLogs     consumer.Logs\n\t\tnextMetrics  consumer.Metrics\n\t\tnextProfiles xconsumer.Profiles\n\t}{\n\t\t{\n\t\t\tname: \"unknown\",\n\t\t\tid:   component.MustNewID(\"unknown\"),\n\t\t\terr: func(pipeline.Signal, pipeline.Signal) string {\n\t\t\t\treturn \"connector factory not available for: \\\"unknown\\\"\"\n\t\t\t},\n\t\t\tnextTraces:   consumertest.NewNop(),\n\t\t\tnextLogs:     consumertest.NewNop(),\n\t\t\tnextMetrics:  consumertest.NewNop(),\n\t\t\tnextProfiles: consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname: \"err\",\n\t\t\tid:   component.MustNewID(\"err\"),\n\t\t\terr: func(expType, rcvType pipeline.Signal) string {\n\t\t\t\treturn fmt.Sprintf(\"connector \\\"err\\\" cannot connect from %s to %s: telemetry type is not supported\", expType, rcvType)\n\t\t\t},\n\t\t\tnextTraces:   consumertest.NewNop(),\n\t\t\tnextLogs:     consumertest.NewNop(),\n\t\t\tnextMetrics:  consumertest.NewNop(),\n\t\t\tnextProfiles: consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname: \"all\",\n\t\t\tid:   component.MustNewID(\"all\"),\n\t\t\terr: func(pipeline.Signal, pipeline.Signal) string {\n\t\t\t\treturn \"\"\n\t\t\t},\n\t\t\tnextTraces:   consumertest.NewNop(),\n\t\t\tnextLogs:     consumertest.NewNop(),\n\t\t\tnextMetrics:  consumertest.NewNop(),\n\t\t\tnextProfiles: consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname: \"all/named\",\n\t\t\tid:   component.MustNewIDWithName(\"all\", \"named\"),\n\t\t\terr: func(pipeline.Signal, pipeline.Signal) string {\n\t\t\t\treturn \"\"\n\t\t\t},\n\t\t\tnextTraces:   consumertest.NewNop(),\n\t\t\tnextLogs:     consumertest.NewNop(),\n\t\t\tnextMetrics:  consumertest.NewNop(),\n\t\t\tnextProfiles: consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname: \"no next consumer\",\n\t\t\tid:   component.MustNewID(\"unknown\"),\n\t\t\terr: func(_, _ pipeline.Signal) string {\n\t\t\t\treturn \"nil next Consumer\"\n\t\t\t},\n\t\t\tnextTraces:   nil,\n\t\t\tnextLogs:     nil,\n\t\t\tnextMetrics:  nil,\n\t\t\tnextProfiles: nil,\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfgs := map[component.ID]component.Config{tt.id: defaultCfg}\n\t\t\tb := builders.NewConnector(cfgs, factories)\n\n\t\t\tt2t, err := b.CreateTracesToTraces(context.Background(), createConnectorSettings(tt.id), tt.nextTraces)\n\t\t\tif expectedErr := tt.err(pipeline.SignalTraces, pipeline.SignalTraces); expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, expectedErr)\n\t\t\t\tassert.Nil(t, t2t)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopConnectorInstance, t2t)\n\t\t\t}\n\t\t\tt2m, err := b.CreateTracesToMetrics(context.Background(), createConnectorSettings(tt.id), tt.nextMetrics)\n\t\t\tif expectedErr := tt.err(pipeline.SignalTraces, pipeline.SignalMetrics); expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, expectedErr)\n\t\t\t\tassert.Nil(t, t2m)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopConnectorInstance, t2m)\n\t\t\t}\n\t\t\tt2l, err := b.CreateTracesToLogs(context.Background(), createConnectorSettings(tt.id), tt.nextLogs)\n\t\t\tif expectedErr := tt.err(pipeline.SignalTraces, pipeline.SignalLogs); expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, expectedErr)\n\t\t\t\tassert.Nil(t, t2l)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopConnectorInstance, t2l)\n\t\t\t}\n\t\t\tt2p, err := b.CreateTracesToProfiles(context.Background(), createConnectorSettings(tt.id), tt.nextProfiles)\n\t\t\tif expectedErr := tt.err(pipeline.SignalTraces, xpipeline.SignalProfiles); expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, expectedErr)\n\t\t\t\tassert.Nil(t, t2p)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopConnectorInstance, t2p)\n\t\t\t}\n\n\t\t\tm2t, err := b.CreateMetricsToTraces(context.Background(), createConnectorSettings(tt.id), tt.nextTraces)\n\t\t\tif expectedErr := tt.err(pipeline.SignalMetrics, pipeline.SignalTraces); expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, expectedErr)\n\t\t\t\tassert.Nil(t, m2t)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopConnectorInstance, m2t)\n\t\t\t}\n\n\t\t\tm2m, err := b.CreateMetricsToMetrics(context.Background(), createConnectorSettings(tt.id), tt.nextMetrics)\n\t\t\tif expectedErr := tt.err(pipeline.SignalMetrics, pipeline.SignalMetrics); expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, expectedErr)\n\t\t\t\tassert.Nil(t, m2m)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopConnectorInstance, m2m)\n\t\t\t}\n\n\t\t\tm2l, err := b.CreateMetricsToLogs(context.Background(), createConnectorSettings(tt.id), tt.nextLogs)\n\t\t\tif expectedErr := tt.err(pipeline.SignalMetrics, pipeline.SignalLogs); expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, expectedErr)\n\t\t\t\tassert.Nil(t, m2l)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopConnectorInstance, m2l)\n\t\t\t}\n\t\t\tm2p, err := b.CreateMetricsToProfiles(context.Background(), createConnectorSettings(tt.id), tt.nextProfiles)\n\t\t\tif expectedErr := tt.err(pipeline.SignalMetrics, xpipeline.SignalProfiles); expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, expectedErr)\n\t\t\t\tassert.Nil(t, m2p)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopConnectorInstance, m2p)\n\t\t\t}\n\n\t\t\tl2t, err := b.CreateLogsToTraces(context.Background(), createConnectorSettings(tt.id), tt.nextTraces)\n\t\t\tif expectedErr := tt.err(pipeline.SignalLogs, pipeline.SignalTraces); expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, expectedErr)\n\t\t\t\tassert.Nil(t, l2t)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopConnectorInstance, l2t)\n\t\t\t}\n\n\t\t\tl2m, err := b.CreateLogsToMetrics(context.Background(), createConnectorSettings(tt.id), tt.nextMetrics)\n\t\t\tif expectedErr := tt.err(pipeline.SignalLogs, pipeline.SignalMetrics); expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, expectedErr)\n\t\t\t\tassert.Nil(t, l2m)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopConnectorInstance, l2m)\n\t\t\t}\n\n\t\t\tl2l, err := b.CreateLogsToLogs(context.Background(), createConnectorSettings(tt.id), tt.nextLogs)\n\t\t\tif expectedErr := tt.err(pipeline.SignalLogs, pipeline.SignalLogs); expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, expectedErr)\n\t\t\t\tassert.Nil(t, l2l)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopConnectorInstance, l2l)\n\t\t\t}\n\t\t\tl2p, err := b.CreateLogsToProfiles(context.Background(), createConnectorSettings(tt.id), tt.nextProfiles)\n\t\t\tif expectedErr := tt.err(pipeline.SignalLogs, xpipeline.SignalProfiles); expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, expectedErr)\n\t\t\t\tassert.Nil(t, l2p)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopConnectorInstance, l2p)\n\t\t\t}\n\n\t\t\tp2t, err := b.CreateProfilesToTraces(context.Background(), createConnectorSettings(tt.id), tt.nextTraces)\n\t\t\tif expectedErr := tt.err(xpipeline.SignalProfiles, pipeline.SignalTraces); expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, expectedErr)\n\t\t\t\tassert.Nil(t, p2t)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopConnectorInstance, p2t)\n\t\t\t}\n\t\t\tp2m, err := b.CreateProfilesToMetrics(context.Background(), createConnectorSettings(tt.id), tt.nextMetrics)\n\t\t\tif expectedErr := tt.err(xpipeline.SignalProfiles, pipeline.SignalMetrics); expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, expectedErr)\n\t\t\t\tassert.Nil(t, p2m)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopConnectorInstance, p2m)\n\t\t\t}\n\t\t\tp2l, err := b.CreateProfilesToLogs(context.Background(), createConnectorSettings(tt.id), tt.nextLogs)\n\t\t\tif expectedErr := tt.err(xpipeline.SignalProfiles, pipeline.SignalLogs); expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, expectedErr)\n\t\t\t\tassert.Nil(t, p2l)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopConnectorInstance, p2l)\n\t\t\t}\n\t\t\tp2p, err := b.CreateProfilesToProfiles(context.Background(), createConnectorSettings(tt.id), tt.nextProfiles)\n\t\t\tif expectedErr := tt.err(xpipeline.SignalProfiles, xpipeline.SignalProfiles); expectedErr != \"\" {\n\t\t\t\tassert.EqualError(t, err, expectedErr)\n\t\t\t\tassert.Nil(t, p2p)\n\t\t\t} else {\n\t\t\t\tassert.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopConnectorInstance, p2p)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestConnectorBuilderMissingConfig(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tfactories, err := otelcol.MakeFactoryMap([]connector.Factory{\n\t\txconnector.NewFactory(\n\t\t\tcomponent.MustNewType(\"all\"),\n\t\t\tfunc() component.Config { return &defaultCfg },\n\t\t\txconnector.WithTracesToTraces(createConnectorTracesToTraces, component.StabilityLevelDevelopment),\n\t\t\txconnector.WithTracesToMetrics(createConnectorTracesToMetrics, component.StabilityLevelDevelopment),\n\t\t\txconnector.WithTracesToLogs(createConnectorTracesToLogs, component.StabilityLevelDevelopment),\n\t\t\txconnector.WithTracesToProfiles(createConnectorTracesToProfiles, component.StabilityLevelDevelopment),\n\t\t\txconnector.WithMetricsToTraces(createConnectorMetricsToTraces, component.StabilityLevelAlpha),\n\t\t\txconnector.WithMetricsToMetrics(createConnectorMetricsToMetrics, component.StabilityLevelAlpha),\n\t\t\txconnector.WithMetricsToLogs(createConnectorMetricsToLogs, component.StabilityLevelAlpha),\n\t\t\txconnector.WithMetricsToProfiles(createConnectorMetricsToProfiles, component.StabilityLevelAlpha),\n\t\t\txconnector.WithLogsToTraces(createConnectorLogsToTraces, component.StabilityLevelDeprecated),\n\t\t\txconnector.WithLogsToMetrics(createConnectorLogsToMetrics, component.StabilityLevelDeprecated),\n\t\t\txconnector.WithLogsToLogs(createConnectorLogsToLogs, component.StabilityLevelDeprecated),\n\t\t\txconnector.WithLogsToProfiles(createConnectorLogsToProfiles, component.StabilityLevelDeprecated),\n\t\t\txconnector.WithProfilesToTraces(createxconnectorToTraces, component.StabilityLevelDevelopment),\n\t\t\txconnector.WithProfilesToMetrics(createxconnectorToMetrics, component.StabilityLevelDevelopment),\n\t\t\txconnector.WithProfilesToLogs(createxconnectorToLogs, component.StabilityLevelDevelopment),\n\t\t\txconnector.WithProfilesToProfiles(createxconnectorToProfiles, component.StabilityLevelDevelopment),\n\t\t),\n\t}...)\n\n\trequire.NoError(t, err)\n\n\tbErr := builders.NewConnector(map[component.ID]component.Config{}, factories)\n\tmissingID := component.MustNewIDWithName(\"all\", \"missing\")\n\n\tt2t, err := bErr.CreateTracesToTraces(context.Background(), createConnectorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"connector \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, t2t)\n\n\tt2m, err := bErr.CreateTracesToMetrics(context.Background(), createConnectorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"connector \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, t2m)\n\n\tt2l, err := bErr.CreateTracesToLogs(context.Background(), createConnectorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"connector \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, t2l)\n\n\tt2p, err := bErr.CreateTracesToProfiles(context.Background(), createConnectorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"connector \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, t2p)\n\n\tm2t, err := bErr.CreateMetricsToTraces(context.Background(), createConnectorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"connector \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, m2t)\n\n\tm2m, err := bErr.CreateMetricsToMetrics(context.Background(), createConnectorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"connector \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, m2m)\n\n\tm2l, err := bErr.CreateMetricsToLogs(context.Background(), createConnectorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"connector \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, m2l)\n\n\tm2p, err := bErr.CreateMetricsToProfiles(context.Background(), createConnectorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"connector \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, m2p)\n\n\tl2t, err := bErr.CreateLogsToTraces(context.Background(), createConnectorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"connector \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, l2t)\n\n\tl2m, err := bErr.CreateLogsToMetrics(context.Background(), createConnectorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"connector \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, l2m)\n\n\tl2l, err := bErr.CreateLogsToLogs(context.Background(), createConnectorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"connector \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, l2l)\n\n\tl2p, err := bErr.CreateLogsToProfiles(context.Background(), createConnectorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"connector \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, l2p)\n\n\tp2t, err := bErr.CreateProfilesToTraces(context.Background(), createConnectorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"connector \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, p2t)\n\n\tp2m, err := bErr.CreateProfilesToMetrics(context.Background(), createConnectorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"connector \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, p2m)\n\n\tp2l, err := bErr.CreateProfilesToLogs(context.Background(), createConnectorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"connector \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, p2l)\n\n\tp2p, err := bErr.CreateProfilesToProfiles(context.Background(), createConnectorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"connector \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, p2p)\n}\n\nfunc TestConnectorBuilderGetters(t *testing.T) {\n\tfactories, err := otelcol.MakeFactoryMap([]connector.Factory{connector.NewFactory(component.MustNewType(\"foo\"), nil)}...)\n\trequire.NoError(t, err)\n\n\tcfgs := map[component.ID]component.Config{component.MustNewID(\"foo\"): struct{}{}}\n\tb := builders.NewConnector(cfgs, factories)\n\n\tassert.True(t, b.IsConfigured(component.MustNewID(\"foo\")))\n\tassert.False(t, b.IsConfigured(component.MustNewID(\"bar\")))\n\n\tassert.NotNil(t, b.Factory(component.MustNewID(\"foo\").Type()))\n\tassert.Nil(t, b.Factory(component.MustNewID(\"bar\").Type()))\n}\n\nfunc TestNewNopConnectorConfigsAndFactories(t *testing.T) {\n\tconfigs, factories := builders.NewNopConnectorConfigsAndFactories()\n\tbuilder := builders.NewConnector(configs, factories)\n\trequire.NotNil(t, builder)\n\n\tfactory := connectortest.NewNopFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tset := connectortest.NewNopSettings(factory.Type())\n\tset.ID = component.NewIDWithName(builders.NopType, \"conn\")\n\n\ttracesToTraces, err := factory.CreateTracesToTraces(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbTracesToTraces, err := builder.CreateTracesToTraces(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, tracesToTraces, bTracesToTraces)\n\n\ttracesToMetrics, err := factory.CreateTracesToMetrics(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbTracesToMetrics, err := builder.CreateTracesToMetrics(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, tracesToMetrics, bTracesToMetrics)\n\n\ttracesToLogs, err := factory.CreateTracesToLogs(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbTracesToLogs, err := builder.CreateTracesToLogs(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, tracesToLogs, bTracesToLogs)\n\n\ttracesToProfiles, err := factory.(xconnector.Factory).CreateTracesToProfiles(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbTracesToProfiles, err := builder.CreateTracesToProfiles(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, tracesToProfiles, bTracesToProfiles)\n\n\tmetricsToTraces, err := factory.CreateMetricsToTraces(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbMetricsToTraces, err := builder.CreateMetricsToTraces(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, metricsToTraces, bMetricsToTraces)\n\n\tmetricsToMetrics, err := factory.CreateMetricsToMetrics(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbMetricsToMetrics, err := builder.CreateMetricsToMetrics(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, metricsToMetrics, bMetricsToMetrics)\n\n\tmetricsToLogs, err := factory.CreateMetricsToLogs(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbMetricsToLogs, err := builder.CreateMetricsToLogs(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, metricsToLogs, bMetricsToLogs)\n\n\tmetricsToProfiles, err := factory.(xconnector.Factory).CreateMetricsToProfiles(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbMetricsToProfiles, err := builder.CreateMetricsToProfiles(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, metricsToProfiles, bMetricsToProfiles)\n\n\tlogsToTraces, err := factory.CreateLogsToTraces(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbLogsToTraces, err := builder.CreateLogsToTraces(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, logsToTraces, bLogsToTraces)\n\n\tlogsToMetrics, err := factory.CreateLogsToMetrics(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbLogsToMetrics, err := builder.CreateLogsToMetrics(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, logsToMetrics, bLogsToMetrics)\n\n\tlogsToLogs, err := factory.CreateLogsToLogs(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbLogsToLogs, err := builder.CreateLogsToLogs(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, logsToLogs, bLogsToLogs)\n\n\tlogsToProfiles, err := factory.(xconnector.Factory).CreateLogsToProfiles(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbLogsToProfiles, err := builder.CreateLogsToProfiles(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, logsToProfiles, bLogsToProfiles)\n\n\tprofilesToTraces, err := factory.(xconnector.Factory).CreateProfilesToTraces(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbProfilesToTraces, err := builder.CreateProfilesToTraces(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, profilesToTraces, bProfilesToTraces)\n\n\tprofilesToMetrics, err := factory.(xconnector.Factory).CreateProfilesToMetrics(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbProfilesToMetrics, err := builder.CreateProfilesToMetrics(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, profilesToMetrics, bProfilesToMetrics)\n\n\tprofilesToLogs, err := factory.(xconnector.Factory).CreateProfilesToLogs(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbProfilesToLogs, err := builder.CreateProfilesToLogs(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, profilesToLogs, bProfilesToLogs)\n\n\tprofilesToProfiles, err := factory.(xconnector.Factory).CreateProfilesToProfiles(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbProfilesToProfiles, err := builder.CreateProfilesToProfiles(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, profilesToProfiles, bProfilesToProfiles)\n}\n\nvar nopConnectorInstance = &nopConnector{\n\tConsumer: consumertest.NewNop(),\n}\n\n// nopConnector stores consumed traces and metrics for testing purposes.\ntype nopConnector struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumertest.Consumer\n}\n\nfunc createConnectorTracesToTraces(context.Context, connector.Settings, component.Config, consumer.Traces) (connector.Traces, error) {\n\treturn nopConnectorInstance, nil\n}\n\nfunc createConnectorTracesToMetrics(context.Context, connector.Settings, component.Config, consumer.Metrics) (connector.Traces, error) {\n\treturn nopConnectorInstance, nil\n}\n\nfunc createConnectorTracesToLogs(context.Context, connector.Settings, component.Config, consumer.Logs) (connector.Traces, error) {\n\treturn nopConnectorInstance, nil\n}\n\nfunc createConnectorTracesToProfiles(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (connector.Traces, error) {\n\treturn nopConnectorInstance, nil\n}\n\nfunc createConnectorMetricsToTraces(context.Context, connector.Settings, component.Config, consumer.Traces) (connector.Metrics, error) {\n\treturn nopConnectorInstance, nil\n}\n\nfunc createConnectorMetricsToMetrics(context.Context, connector.Settings, component.Config, consumer.Metrics) (connector.Metrics, error) {\n\treturn nopConnectorInstance, nil\n}\n\nfunc createConnectorMetricsToLogs(context.Context, connector.Settings, component.Config, consumer.Logs) (connector.Metrics, error) {\n\treturn nopConnectorInstance, nil\n}\n\nfunc createConnectorMetricsToProfiles(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (connector.Metrics, error) {\n\treturn nopConnectorInstance, nil\n}\n\nfunc createConnectorLogsToTraces(context.Context, connector.Settings, component.Config, consumer.Traces) (connector.Logs, error) {\n\treturn nopConnectorInstance, nil\n}\n\nfunc createConnectorLogsToMetrics(context.Context, connector.Settings, component.Config, consumer.Metrics) (connector.Logs, error) {\n\treturn nopConnectorInstance, nil\n}\n\nfunc createConnectorLogsToLogs(context.Context, connector.Settings, component.Config, consumer.Logs) (connector.Logs, error) {\n\treturn nopConnectorInstance, nil\n}\n\nfunc createConnectorLogsToProfiles(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (connector.Logs, error) {\n\treturn nopConnectorInstance, nil\n}\n\nfunc createxconnectorToTraces(context.Context, connector.Settings, component.Config, consumer.Traces) (xconnector.Profiles, error) {\n\treturn nopConnectorInstance, nil\n}\n\nfunc createxconnectorToMetrics(context.Context, connector.Settings, component.Config, consumer.Metrics) (xconnector.Profiles, error) {\n\treturn nopConnectorInstance, nil\n}\n\nfunc createxconnectorToLogs(context.Context, connector.Settings, component.Config, consumer.Logs) (xconnector.Profiles, error) {\n\treturn nopConnectorInstance, nil\n}\n\nfunc createxconnectorToProfiles(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (xconnector.Profiles, error) {\n\treturn nopConnectorInstance, nil\n}\n\nfunc createConnectorSettings(id component.ID) connector.Settings {\n\treturn connector.Settings{\n\t\tID:                id,\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t\tBuildInfo:         component.NewDefaultBuildInfo(),\n\t}\n}\n"
  },
  {
    "path": "service/internal/builders/builders_test/exporter_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builders\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n\t\"go.opentelemetry.io/collector/otelcol\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n)\n\nfunc TestExporterBuilder(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tfactories, err := otelcol.MakeFactoryMap([]exporter.Factory{\n\t\texporter.NewFactory(component.MustNewType(\"err\"), nil),\n\t\txexporter.NewFactory(\n\t\t\tcomponent.MustNewType(\"all\"),\n\t\t\tfunc() component.Config { return &defaultCfg },\n\t\t\txexporter.WithTraces(createExporterTraces, component.StabilityLevelDevelopment),\n\t\t\txexporter.WithMetrics(createExporterMetrics, component.StabilityLevelAlpha),\n\t\t\txexporter.WithLogs(createExporterLogs, component.StabilityLevelDeprecated),\n\t\t\txexporter.WithProfiles(createxexporter, component.StabilityLevelDevelopment),\n\t\t),\n\t}...)\n\trequire.NoError(t, err)\n\n\ttestCases := []struct {\n\t\tname string\n\t\tid   component.ID\n\t\terr  string\n\t}{\n\t\t{\n\t\t\tname: \"unknown\",\n\t\t\tid:   component.MustNewID(\"unknown\"),\n\t\t\terr:  \"exporter factory not available for: \\\"unknown\\\"\",\n\t\t},\n\t\t{\n\t\t\tname: \"err\",\n\t\t\tid:   component.MustNewID(\"err\"),\n\t\t\terr:  \"telemetry type is not supported\",\n\t\t},\n\t\t{\n\t\t\tname: \"all\",\n\t\t\tid:   component.MustNewID(\"all\"),\n\t\t},\n\t\t{\n\t\t\tname: \"all/named\",\n\t\t\tid:   component.MustNewIDWithName(\"all\", \"named\"),\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfgs := map[component.ID]component.Config{tt.id: defaultCfg}\n\t\t\tb := builders.NewExporter(cfgs, factories)\n\n\t\t\tte, err := b.CreateTraces(context.Background(), createExporterSettings(tt.id))\n\t\t\tif tt.err != \"\" {\n\t\t\t\trequire.EqualError(t, err, tt.err)\n\t\t\t\tassert.Nil(t, te)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopExporterInstance, te)\n\t\t\t}\n\n\t\t\tme, err := b.CreateMetrics(context.Background(), createExporterSettings(tt.id))\n\t\t\tif tt.err != \"\" {\n\t\t\t\trequire.EqualError(t, err, tt.err)\n\t\t\t\tassert.Nil(t, me)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopExporterInstance, me)\n\t\t\t}\n\n\t\t\tle, err := b.CreateLogs(context.Background(), createExporterSettings(tt.id))\n\t\t\tif tt.err != \"\" {\n\t\t\t\trequire.EqualError(t, err, tt.err)\n\t\t\t\tassert.Nil(t, le)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopExporterInstance, le)\n\t\t\t}\n\n\t\t\tpe, err := b.CreateProfiles(context.Background(), createExporterSettings(tt.id))\n\t\t\tif tt.err != \"\" {\n\t\t\t\trequire.EqualError(t, err, tt.err)\n\t\t\t\tassert.Nil(t, pe)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopExporterInstance, pe)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestExporterBuilderMissingConfig(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tfactories, err := otelcol.MakeFactoryMap([]exporter.Factory{\n\t\txexporter.NewFactory(\n\t\t\tcomponent.MustNewType(\"all\"),\n\t\t\tfunc() component.Config { return &defaultCfg },\n\t\t\txexporter.WithTraces(createExporterTraces, component.StabilityLevelDevelopment),\n\t\t\txexporter.WithMetrics(createExporterMetrics, component.StabilityLevelAlpha),\n\t\t\txexporter.WithLogs(createExporterLogs, component.StabilityLevelDeprecated),\n\t\t\txexporter.WithProfiles(createxexporter, component.StabilityLevelDevelopment),\n\t\t),\n\t}...)\n\n\trequire.NoError(t, err)\n\n\tbErr := builders.NewExporter(map[component.ID]component.Config{}, factories)\n\tmissingID := component.MustNewIDWithName(\"all\", \"missing\")\n\n\tte, err := bErr.CreateTraces(context.Background(), createExporterSettings(missingID))\n\trequire.EqualError(t, err, \"exporter \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, te)\n\n\tme, err := bErr.CreateMetrics(context.Background(), createExporterSettings(missingID))\n\trequire.EqualError(t, err, \"exporter \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, me)\n\n\tle, err := bErr.CreateLogs(context.Background(), createExporterSettings(missingID))\n\trequire.EqualError(t, err, \"exporter \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, le)\n\n\tpe, err := bErr.CreateProfiles(context.Background(), createExporterSettings(missingID))\n\trequire.EqualError(t, err, \"exporter \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, pe)\n}\n\nfunc TestExporterBuilderFactory(t *testing.T) {\n\tfactories, err := otelcol.MakeFactoryMap([]exporter.Factory{exporter.NewFactory(component.MustNewType(\"foo\"), nil)}...)\n\trequire.NoError(t, err)\n\n\tcfgs := map[component.ID]component.Config{component.MustNewID(\"foo\"): struct{}{}}\n\tb := builders.NewExporter(cfgs, factories)\n\n\tassert.NotNil(t, b.Factory(component.MustNewID(\"foo\").Type()))\n\tassert.Nil(t, b.Factory(component.MustNewID(\"bar\").Type()))\n}\n\nfunc TestNewNopExporterConfigsAndFactories(t *testing.T) {\n\tconfigs, factories := builders.NewNopExporterConfigsAndFactories()\n\tbuilder := builders.NewExporter(configs, factories)\n\trequire.NotNil(t, builder)\n\n\tfactory := exportertest.NewNopFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tset := exportertest.NewNopSettings(factory.Type())\n\tset.ID = component.NewID(builders.NopType)\n\n\ttraces, err := factory.CreateTraces(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\tbTraces, err := builder.CreateTraces(context.Background(), set)\n\trequire.NoError(t, err)\n\tassert.IsType(t, traces, bTraces)\n\n\tmetrics, err := factory.CreateMetrics(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\tbMetrics, err := builder.CreateMetrics(context.Background(), set)\n\trequire.NoError(t, err)\n\tassert.IsType(t, metrics, bMetrics)\n\n\tlogs, err := factory.CreateLogs(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\tbLogs, err := builder.CreateLogs(context.Background(), set)\n\trequire.NoError(t, err)\n\tassert.IsType(t, logs, bLogs)\n\n\tprofiles, err := factory.(xexporter.Factory).CreateProfiles(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\tbProfiles, err := builder.CreateProfiles(context.Background(), set)\n\trequire.NoError(t, err)\n\tassert.IsType(t, profiles, bProfiles)\n}\n\nvar nopExporterInstance = &nopExporter{\n\tConsumer: consumertest.NewNop(),\n}\n\n// nopExporter stores consumed traces, metrics, logs and profiles for testing purposes.\ntype nopExporter struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumertest.Consumer\n}\n\nfunc createExporterTraces(context.Context, exporter.Settings, component.Config) (exporter.Traces, error) {\n\treturn nopExporterInstance, nil\n}\n\nfunc createExporterMetrics(context.Context, exporter.Settings, component.Config) (exporter.Metrics, error) {\n\treturn nopExporterInstance, nil\n}\n\nfunc createExporterLogs(context.Context, exporter.Settings, component.Config) (exporter.Logs, error) {\n\treturn nopExporterInstance, nil\n}\n\nfunc createxexporter(context.Context, exporter.Settings, component.Config) (xexporter.Profiles, error) {\n\treturn nopExporterInstance, nil\n}\n\nfunc createExporterSettings(id component.ID) exporter.Settings {\n\treturn exporter.Settings{\n\t\tID:                id,\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t\tBuildInfo:         component.NewDefaultBuildInfo(),\n\t}\n}\n"
  },
  {
    "path": "service/internal/builders/builders_test/extension_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builders\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensiontest\"\n\t\"go.opentelemetry.io/collector/otelcol\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n)\n\nfunc TestExtensionBuilder(t *testing.T) {\n\ttestType := component.MustNewType(\"test\")\n\tdefaultCfg := struct{}{}\n\ttestID := component.NewID(testType)\n\tunknownID := component.MustNewID(\"unknown\")\n\n\tfactories, err := otelcol.MakeFactoryMap([]extension.Factory{\n\t\textension.NewFactory(\n\t\t\ttestType,\n\t\t\tfunc() component.Config { return &defaultCfg },\n\t\t\tfunc(_ context.Context, settings extension.Settings, _ component.Config) (extension.Extension, error) {\n\t\t\t\treturn nopExtension{Settings: settings}, nil\n\t\t\t},\n\t\t\tcomponent.StabilityLevelDevelopment),\n\t}...)\n\trequire.NoError(t, err)\n\n\tcfgs := map[component.ID]component.Config{testID: defaultCfg, unknownID: defaultCfg}\n\tb := builders.NewExtension(cfgs, factories)\n\n\te, err := b.Create(context.Background(), createExtensionSettings(testID))\n\trequire.NoError(t, err)\n\tassert.NotNil(t, e)\n\n\t// Check that the extension has access to the resource attributes.\n\tnop, ok := e.(nopExtension)\n\tassert.True(t, ok)\n\tassert.Equal(t, 0, nop.Settings.Resource.Attributes().Len())\n\n\tmissingType, err := b.Create(context.Background(), createExtensionSettings(unknownID))\n\trequire.EqualError(t, err, \"extension factory not available for: \\\"unknown\\\"\")\n\tassert.Nil(t, missingType)\n\n\tmissingCfg, err := b.Create(context.Background(), createExtensionSettings(component.NewIDWithName(testType, \"foo\")))\n\trequire.EqualError(t, err, \"extension \\\"test/foo\\\" is not configured\")\n\tassert.Nil(t, missingCfg)\n}\n\nfunc TestExtensionBuilderFactory(t *testing.T) {\n\tfactories, err := otelcol.MakeFactoryMap([]extension.Factory{extension.NewFactory(component.MustNewType(\"foo\"), nil, nil, component.StabilityLevelDevelopment)}...)\n\trequire.NoError(t, err)\n\n\tcfgs := map[component.ID]component.Config{component.MustNewID(\"foo\"): struct{}{}}\n\tb := builders.NewExtension(cfgs, factories)\n\n\tassert.NotNil(t, b.Factory(component.MustNewID(\"foo\").Type()))\n\tassert.Nil(t, b.Factory(component.MustNewID(\"bar\").Type()))\n}\n\nfunc TestNewNopExtensionConfigsAndFactories(t *testing.T) {\n\tconfigs, factories := builders.NewNopExtensionConfigsAndFactories()\n\tbuilder := builders.NewExtension(configs, factories)\n\trequire.NotNil(t, builder)\n\n\tfactory := extensiontest.NewNopFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tset := extensiontest.NewNopSettings(factory.Type())\n\tset.ID = component.NewID(builders.NopType)\n\n\text, err := factory.Create(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\tbExt, err := builder.Create(context.Background(), set)\n\trequire.NoError(t, err)\n\tassert.IsType(t, ext, bExt)\n}\n\ntype nopExtension struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\textension.Settings\n}\n\nfunc createExtensionSettings(id component.ID) extension.Settings {\n\treturn extension.Settings{\n\t\tID:                id,\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t\tBuildInfo:         component.NewDefaultBuildInfo(),\n\t}\n}\n"
  },
  {
    "path": "service/internal/builders/builders_test/processor_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builders\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/otelcol\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n\t\"go.opentelemetry.io/collector/processor/xprocessor\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n)\n\nfunc TestProcessorBuilder(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tfactories, err := otelcol.MakeFactoryMap([]processor.Factory{\n\t\tprocessor.NewFactory(component.MustNewType(\"err\"), nil),\n\t\txprocessor.NewFactory(\n\t\t\tcomponent.MustNewType(\"all\"),\n\t\t\tfunc() component.Config { return &defaultCfg },\n\t\t\txprocessor.WithTraces(createProcessorTraces, component.StabilityLevelDevelopment),\n\t\t\txprocessor.WithMetrics(createProcessorMetrics, component.StabilityLevelAlpha),\n\t\t\txprocessor.WithLogs(createProcessorLogs, component.StabilityLevelDeprecated),\n\t\t\txprocessor.WithProfiles(createxprocessor, component.StabilityLevelDevelopment),\n\t\t),\n\t}...)\n\trequire.NoError(t, err)\n\n\ttestCases := []struct {\n\t\tname         string\n\t\tid           component.ID\n\t\terr          string\n\t\tnextTraces   consumer.Traces\n\t\tnextLogs     consumer.Logs\n\t\tnextMetrics  consumer.Metrics\n\t\tnextProfiles xconsumer.Profiles\n\t}{\n\t\t{\n\t\t\tname:         \"unknown\",\n\t\t\tid:           component.MustNewID(\"unknown\"),\n\t\t\terr:          \"processor factory not available for: \\\"unknown\\\"\",\n\t\t\tnextTraces:   consumertest.NewNop(),\n\t\t\tnextLogs:     consumertest.NewNop(),\n\t\t\tnextMetrics:  consumertest.NewNop(),\n\t\t\tnextProfiles: consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname:         \"err\",\n\t\t\tid:           component.MustNewID(\"err\"),\n\t\t\terr:          \"telemetry type is not supported\",\n\t\t\tnextTraces:   consumertest.NewNop(),\n\t\t\tnextLogs:     consumertest.NewNop(),\n\t\t\tnextMetrics:  consumertest.NewNop(),\n\t\t\tnextProfiles: consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname:         \"all\",\n\t\t\tid:           component.MustNewID(\"all\"),\n\t\t\tnextTraces:   consumertest.NewNop(),\n\t\t\tnextLogs:     consumertest.NewNop(),\n\t\t\tnextMetrics:  consumertest.NewNop(),\n\t\t\tnextProfiles: consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname:         \"all/named\",\n\t\t\tid:           component.MustNewIDWithName(\"all\", \"named\"),\n\t\t\tnextTraces:   consumertest.NewNop(),\n\t\t\tnextLogs:     consumertest.NewNop(),\n\t\t\tnextMetrics:  consumertest.NewNop(),\n\t\t\tnextProfiles: consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname:         \"no next consumer\",\n\t\t\tid:           component.MustNewID(\"unknown\"),\n\t\t\terr:          \"nil next Consumer\",\n\t\t\tnextTraces:   nil,\n\t\t\tnextLogs:     nil,\n\t\t\tnextMetrics:  nil,\n\t\t\tnextProfiles: nil,\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfgs := map[component.ID]component.Config{tt.id: defaultCfg}\n\t\t\tb := builders.NewProcessor(cfgs, factories)\n\n\t\t\tte, err := b.CreateTraces(context.Background(), createProcessorSettings(tt.id), tt.nextTraces)\n\t\t\tif tt.err != \"\" {\n\t\t\t\trequire.EqualError(t, err, tt.err)\n\t\t\t\tassert.Nil(t, te)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopProcessorInstance, te)\n\t\t\t}\n\n\t\t\tme, err := b.CreateMetrics(context.Background(), createProcessorSettings(tt.id), tt.nextMetrics)\n\t\t\tif tt.err != \"\" {\n\t\t\t\trequire.EqualError(t, err, tt.err)\n\t\t\t\tassert.Nil(t, me)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopProcessorInstance, me)\n\t\t\t}\n\n\t\t\tle, err := b.CreateLogs(context.Background(), createProcessorSettings(tt.id), tt.nextLogs)\n\t\t\tif tt.err != \"\" {\n\t\t\t\trequire.EqualError(t, err, tt.err)\n\t\t\t\tassert.Nil(t, le)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopProcessorInstance, le)\n\t\t\t}\n\n\t\t\tpe, err := b.CreateProfiles(context.Background(), createProcessorSettings(tt.id), tt.nextProfiles)\n\t\t\tif tt.err != \"\" {\n\t\t\t\trequire.EqualError(t, err, tt.err)\n\t\t\t\tassert.Nil(t, pe)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopProcessorInstance, pe)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestProcessorBuilderMissingConfig(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tfactories, err := otelcol.MakeFactoryMap([]processor.Factory{\n\t\txprocessor.NewFactory(\n\t\t\tcomponent.MustNewType(\"all\"),\n\t\t\tfunc() component.Config { return &defaultCfg },\n\t\t\txprocessor.WithTraces(createProcessorTraces, component.StabilityLevelDevelopment),\n\t\t\txprocessor.WithMetrics(createProcessorMetrics, component.StabilityLevelAlpha),\n\t\t\txprocessor.WithLogs(createProcessorLogs, component.StabilityLevelDeprecated),\n\t\t\txprocessor.WithProfiles(createxprocessor, component.StabilityLevelDevelopment),\n\t\t),\n\t}...)\n\n\trequire.NoError(t, err)\n\n\tbErr := builders.NewProcessor(map[component.ID]component.Config{}, factories)\n\tmissingID := component.MustNewIDWithName(\"all\", \"missing\")\n\n\tte, err := bErr.CreateTraces(context.Background(), createProcessorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"processor \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, te)\n\n\tme, err := bErr.CreateMetrics(context.Background(), createProcessorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"processor \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, me)\n\n\tle, err := bErr.CreateLogs(context.Background(), createProcessorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"processor \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, le)\n\n\tpe, err := bErr.CreateProfiles(context.Background(), createProcessorSettings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"processor \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, pe)\n}\n\nfunc TestProcessorBuilderFactory(t *testing.T) {\n\tfactories, err := otelcol.MakeFactoryMap([]processor.Factory{processor.NewFactory(component.MustNewType(\"foo\"), nil)}...)\n\trequire.NoError(t, err)\n\n\tcfgs := map[component.ID]component.Config{component.MustNewID(\"foo\"): struct{}{}}\n\tb := builders.NewProcessor(cfgs, factories)\n\n\tassert.NotNil(t, b.Factory(component.MustNewID(\"foo\").Type()))\n\tassert.Nil(t, b.Factory(component.MustNewID(\"bar\").Type()))\n}\n\nfunc TestNewNopProcessorBuilder(t *testing.T) {\n\tconfigs, factories := builders.NewNopProcessorConfigsAndFactories()\n\tbuilder := builders.NewProcessor(configs, factories)\n\trequire.NotNil(t, builder)\n\n\tfactory := processortest.NewNopFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tset := processortest.NewNopSettings(factory.Type())\n\tset.ID = component.NewID(builders.NopType)\n\n\ttraces, err := factory.CreateTraces(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbTraces, err := builder.CreateTraces(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, traces, bTraces)\n\n\tmetrics, err := factory.CreateMetrics(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbMetrics, err := builder.CreateMetrics(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, metrics, bMetrics)\n\n\tlogs, err := factory.CreateLogs(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbLogs, err := builder.CreateLogs(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, logs, bLogs)\n\n\tprofiles, err := factory.(xprocessor.Factory).CreateProfiles(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbProfiles, err := builder.CreateProfiles(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, profiles, bProfiles)\n}\n\nvar nopProcessorInstance = &nopProcessor{\n\tConsumer: consumertest.NewNop(),\n}\n\n// nopProcessor stores consumed traces, metrics, logs and profiles for testing purposes.\ntype nopProcessor struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumertest.Consumer\n}\n\nfunc createProcessorTraces(context.Context, processor.Settings, component.Config, consumer.Traces) (processor.Traces, error) {\n\treturn nopProcessorInstance, nil\n}\n\nfunc createProcessorMetrics(context.Context, processor.Settings, component.Config, consumer.Metrics) (processor.Metrics, error) {\n\treturn nopProcessorInstance, nil\n}\n\nfunc createProcessorLogs(context.Context, processor.Settings, component.Config, consumer.Logs) (processor.Logs, error) {\n\treturn nopProcessorInstance, nil\n}\n\nfunc createxprocessor(context.Context, processor.Settings, component.Config, xconsumer.Profiles) (xprocessor.Profiles, error) {\n\treturn nopProcessorInstance, nil\n}\n\nfunc createProcessorSettings(id component.ID) processor.Settings {\n\treturn processor.Settings{\n\t\tID:                id,\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t\tBuildInfo:         component.NewDefaultBuildInfo(),\n\t}\n}\n"
  },
  {
    "path": "service/internal/builders/builders_test/receiver_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builders\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/otelcol\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n)\n\nfunc TestReceiverBuilder(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tfactories, err := otelcol.MakeFactoryMap([]receiver.Factory{\n\t\treceiver.NewFactory(component.MustNewType(\"err\"), nil),\n\t\txreceiver.NewFactory(\n\t\t\tcomponent.MustNewType(\"all\"),\n\t\t\tfunc() component.Config { return &defaultCfg },\n\t\t\txreceiver.WithTraces(createReceiverTraces, component.StabilityLevelDevelopment),\n\t\t\txreceiver.WithMetrics(createReceiverMetrics, component.StabilityLevelAlpha),\n\t\t\txreceiver.WithLogs(createReceiverLogs, component.StabilityLevelDeprecated),\n\t\t\txreceiver.WithProfiles(createReceiverProfiles, component.StabilityLevelAlpha),\n\t\t),\n\t}...)\n\trequire.NoError(t, err)\n\n\ttestCases := []struct {\n\t\tname         string\n\t\tid           component.ID\n\t\terr          string\n\t\tnextTraces   consumer.Traces\n\t\tnextLogs     consumer.Logs\n\t\tnextMetrics  consumer.Metrics\n\t\tnextProfiles xconsumer.Profiles\n\t}{\n\t\t{\n\t\t\tname:         \"unknown\",\n\t\t\tid:           component.MustNewID(\"unknown\"),\n\t\t\terr:          \"receiver factory not available for: \\\"unknown\\\"\",\n\t\t\tnextTraces:   consumertest.NewNop(),\n\t\t\tnextLogs:     consumertest.NewNop(),\n\t\t\tnextMetrics:  consumertest.NewNop(),\n\t\t\tnextProfiles: consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname:         \"err\",\n\t\t\tid:           component.MustNewID(\"err\"),\n\t\t\terr:          \"telemetry type is not supported\",\n\t\t\tnextTraces:   consumertest.NewNop(),\n\t\t\tnextLogs:     consumertest.NewNop(),\n\t\t\tnextMetrics:  consumertest.NewNop(),\n\t\t\tnextProfiles: consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname:         \"all\",\n\t\t\tid:           component.MustNewID(\"all\"),\n\t\t\tnextTraces:   consumertest.NewNop(),\n\t\t\tnextLogs:     consumertest.NewNop(),\n\t\t\tnextMetrics:  consumertest.NewNop(),\n\t\t\tnextProfiles: consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname:         \"all/named\",\n\t\t\tid:           component.MustNewIDWithName(\"all\", \"named\"),\n\t\t\tnextTraces:   consumertest.NewNop(),\n\t\t\tnextLogs:     consumertest.NewNop(),\n\t\t\tnextMetrics:  consumertest.NewNop(),\n\t\t\tnextProfiles: consumertest.NewNop(),\n\t\t},\n\t\t{\n\t\t\tname:         \"no next consumer\",\n\t\t\tid:           component.MustNewID(\"unknown\"),\n\t\t\terr:          \"nil next Consumer\",\n\t\t\tnextTraces:   nil,\n\t\t\tnextLogs:     nil,\n\t\t\tnextMetrics:  nil,\n\t\t\tnextProfiles: nil,\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfgs := map[component.ID]component.Config{tt.id: defaultCfg}\n\t\t\tb := builders.NewReceiver(cfgs, factories)\n\n\t\t\tte, err := b.CreateTraces(context.Background(), settings(tt.id), tt.nextTraces)\n\t\t\tif tt.err != \"\" {\n\t\t\t\trequire.EqualError(t, err, tt.err)\n\t\t\t\tassert.Nil(t, te)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopReceiverInstance, te)\n\t\t\t}\n\n\t\t\tme, err := b.CreateMetrics(context.Background(), settings(tt.id), tt.nextMetrics)\n\t\t\tif tt.err != \"\" {\n\t\t\t\trequire.EqualError(t, err, tt.err)\n\t\t\t\tassert.Nil(t, me)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopReceiverInstance, me)\n\t\t\t}\n\n\t\t\tle, err := b.CreateLogs(context.Background(), settings(tt.id), tt.nextLogs)\n\t\t\tif tt.err != \"\" {\n\t\t\t\trequire.EqualError(t, err, tt.err)\n\t\t\t\tassert.Nil(t, le)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopReceiverInstance, le)\n\t\t\t}\n\n\t\t\tpe, err := b.CreateProfiles(context.Background(), settings(tt.id), tt.nextProfiles)\n\t\t\tif tt.err != \"\" {\n\t\t\t\trequire.EqualError(t, err, tt.err)\n\t\t\t\tassert.Nil(t, pe)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\tassert.Equal(t, nopReceiverInstance, pe)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestReceiverBuilderMissingConfig(t *testing.T) {\n\tdefaultCfg := struct{}{}\n\tfactories, err := otelcol.MakeFactoryMap([]receiver.Factory{\n\t\txreceiver.NewFactory(\n\t\t\tcomponent.MustNewType(\"all\"),\n\t\t\tfunc() component.Config { return &defaultCfg },\n\t\t\txreceiver.WithTraces(createReceiverTraces, component.StabilityLevelDevelopment),\n\t\t\txreceiver.WithMetrics(createReceiverMetrics, component.StabilityLevelAlpha),\n\t\t\txreceiver.WithLogs(createReceiverLogs, component.StabilityLevelDeprecated),\n\t\t\txreceiver.WithProfiles(createReceiverProfiles, component.StabilityLevelAlpha),\n\t\t),\n\t}...)\n\n\trequire.NoError(t, err)\n\n\tbErr := builders.NewReceiver(map[component.ID]component.Config{}, factories)\n\tmissingID := component.MustNewIDWithName(\"all\", \"missing\")\n\n\tte, err := bErr.CreateTraces(context.Background(), settings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"receiver \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, te)\n\n\tme, err := bErr.CreateMetrics(context.Background(), settings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"receiver \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, me)\n\n\tle, err := bErr.CreateLogs(context.Background(), settings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"receiver \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, le)\n\n\tpe, err := bErr.CreateProfiles(context.Background(), settings(missingID), consumertest.NewNop())\n\trequire.EqualError(t, err, \"receiver \\\"all/missing\\\" is not configured\")\n\tassert.Nil(t, pe)\n}\n\nfunc TestReceiverBuilderFactory(t *testing.T) {\n\tfactories, err := otelcol.MakeFactoryMap([]receiver.Factory{receiver.NewFactory(component.MustNewType(\"foo\"), nil)}...)\n\trequire.NoError(t, err)\n\n\tcfgs := map[component.ID]component.Config{component.MustNewID(\"foo\"): struct{}{}}\n\tb := builders.NewReceiver(cfgs, factories)\n\n\tassert.NotNil(t, b.Factory(component.MustNewID(\"foo\").Type()))\n\tassert.Nil(t, b.Factory(component.MustNewID(\"bar\").Type()))\n}\n\nfunc TestNewNopReceiverConfigsAndFactories(t *testing.T) {\n\tconfigs, factories := builders.NewNopReceiverConfigsAndFactories()\n\tbuilder := builders.NewReceiver(configs, factories)\n\trequire.NotNil(t, builder)\n\n\tfactory := receivertest.NewNopFactory()\n\tcfg := factory.CreateDefaultConfig()\n\tset := receivertest.NewNopSettings(factory.Type())\n\tset.ID = component.NewID(builders.NopType)\n\n\ttraces, err := factory.CreateTraces(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbTraces, err := builder.CreateTraces(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, traces, bTraces)\n\n\tmetrics, err := factory.CreateMetrics(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbMetrics, err := builder.CreateMetrics(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, metrics, bMetrics)\n\n\tlogs, err := factory.CreateLogs(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbLogs, err := builder.CreateLogs(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, logs, bLogs)\n\n\tprofiles, err := factory.(xreceiver.Factory).CreateProfiles(context.Background(), set, cfg, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tbProfiles, err := builder.CreateProfiles(context.Background(), set, consumertest.NewNop())\n\trequire.NoError(t, err)\n\tassert.IsType(t, profiles, bProfiles)\n}\n\nfunc settings(id component.ID) receiver.Settings {\n\treturn receiver.Settings{\n\t\tID:                id,\n\t\tTelemetrySettings: componenttest.NewNopTelemetrySettings(),\n\t\tBuildInfo:         component.NewDefaultBuildInfo(),\n\t}\n}\n\nvar nopReceiverInstance = &nopReceiver{\n\tConsumer: consumertest.NewNop(),\n}\n\n// nopReceiver stores consumed traces and metrics for testing purposes.\ntype nopReceiver struct {\n\tcomponent.StartFunc\n\tcomponent.ShutdownFunc\n\tconsumertest.Consumer\n}\n\nfunc createReceiverTraces(context.Context, receiver.Settings, component.Config, consumer.Traces) (receiver.Traces, error) {\n\treturn nopReceiverInstance, nil\n}\n\nfunc createReceiverMetrics(context.Context, receiver.Settings, component.Config, consumer.Metrics) (receiver.Metrics, error) {\n\treturn nopReceiverInstance, nil\n}\n\nfunc createReceiverLogs(context.Context, receiver.Settings, component.Config, consumer.Logs) (receiver.Logs, error) {\n\treturn nopReceiverInstance, nil\n}\n\nfunc createReceiverProfiles(context.Context, receiver.Settings, component.Config, xconsumer.Profiles) (xreceiver.Profiles, error) {\n\treturn nopReceiverInstance, nil\n}\n"
  },
  {
    "path": "service/internal/builders/builders_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builders\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/internal/componentalias\"\n)\n\n// mockFactory is a test factory that implements component.Factory\ntype mockFactory struct {\n\tfactoryType component.Type\n}\n\nfunc (m *mockFactory) Type() component.Type {\n\treturn m.factoryType\n}\n\nfunc (m *mockFactory) CreateDefaultConfig() component.Config {\n\treturn nil\n}\n\n// mockFactoryWithAlias is a test factory that implements both component.Factory and componentalias.TypeAliasHolder\ntype mockFactoryWithAlias struct {\n\tfactoryType component.Type\n\taliasHolder componentalias.TypeAliasHolder\n}\n\nfunc (m *mockFactoryWithAlias) Type() component.Type {\n\treturn m.factoryType\n}\n\nfunc (m *mockFactoryWithAlias) CreateDefaultConfig() component.Config {\n\treturn nil\n}\n\nfunc (m *mockFactoryWithAlias) DeprecatedAlias() component.Type {\n\treturn m.aliasHolder.DeprecatedAlias()\n}\n\nfunc (m *mockFactoryWithAlias) SetDeprecatedAlias(alias component.Type) {\n\tm.aliasHolder.SetDeprecatedAlias(alias)\n}\n\nfunc TestLogDeprecatedTypeAlias(t *testing.T) {\n\ttests := []struct {\n\t\tname          string\n\t\tfactory       component.Factory\n\t\tusedType      component.Type\n\t\texpectWarning bool\n\t}{\n\t\t{\n\t\t\tname:          \"no_alias_holder\",\n\t\t\tfactory:       &mockFactory{factoryType: component.MustNewType(\"test\")},\n\t\t\tusedType:      component.MustNewType(\"test\"),\n\t\t\texpectWarning: false,\n\t\t},\n\t\t{\n\t\t\tname: \"no_alias_set\",\n\t\t\tfactory: &mockFactoryWithAlias{\n\t\t\t\tfactoryType: component.MustNewType(\"test\"),\n\t\t\t\taliasHolder: componentalias.NewTypeAliasHolder(),\n\t\t\t},\n\t\t\tusedType:      component.MustNewType(\"test\"),\n\t\t\texpectWarning: false,\n\t\t},\n\t\t{\n\t\t\tname: \"using_current_type\",\n\t\t\tfactory: func() component.Factory {\n\t\t\t\tf := &mockFactoryWithAlias{\n\t\t\t\t\tfactoryType: component.MustNewType(\"new\"),\n\t\t\t\t\taliasHolder: componentalias.NewTypeAliasHolder(),\n\t\t\t\t}\n\t\t\t\tf.aliasHolder.SetDeprecatedAlias(component.MustNewType(\"old\"))\n\t\t\t\treturn f\n\t\t\t}(),\n\t\t\tusedType:      component.MustNewType(\"new\"),\n\t\t\texpectWarning: false,\n\t\t},\n\t\t{\n\t\t\tname: \"using_deprecated_alias\",\n\t\t\tfactory: func() component.Factory {\n\t\t\t\tf := &mockFactoryWithAlias{\n\t\t\t\t\tfactoryType: component.MustNewType(\"new\"),\n\t\t\t\t\taliasHolder: componentalias.NewTypeAliasHolder(),\n\t\t\t\t}\n\t\t\t\tf.aliasHolder.SetDeprecatedAlias(component.MustNewType(\"old\"))\n\t\t\t\treturn f\n\t\t\t}(),\n\t\t\tusedType:      component.MustNewType(\"old\"),\n\t\t\texpectWarning: true,\n\t\t},\n\t\t{\n\t\t\tname: \"using_unrelated_type\",\n\t\t\tfactory: func() component.Factory {\n\t\t\t\tf := &mockFactoryWithAlias{\n\t\t\t\t\tfactoryType: component.MustNewType(\"new\"),\n\t\t\t\t\taliasHolder: componentalias.NewTypeAliasHolder(),\n\t\t\t\t}\n\t\t\t\tf.aliasHolder.SetDeprecatedAlias(component.MustNewType(\"old\"))\n\t\t\t\treturn f\n\t\t\t}(),\n\t\t\tusedType:      component.MustNewType(\"other\"),\n\t\t\texpectWarning: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcore, logs := observer.New(zap.WarnLevel)\n\t\t\tlogger := zap.New(core)\n\n\t\t\tlogDeprecatedTypeAlias(logger, tt.factory, tt.usedType)\n\n\t\t\tif tt.expectWarning && logs.Len() != 1 {\n\t\t\t\tt.Errorf(\"expected 1 warning log but got %d\", logs.Len())\n\t\t\t} else if !tt.expectWarning && logs.Len() > 0 {\n\t\t\t\tt.Errorf(\"expected no warning log but got %d\", logs.Len())\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "service/internal/builders/connector.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builders // import \"go.opentelemetry.io/collector/service/internal/builders\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/connectortest\"\n\t\"go.opentelemetry.io/collector/connector/xconnector\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n)\n\nfunc errDataTypes(id component.ID, from, to pipeline.Signal) error {\n\treturn fmt.Errorf(\"connector %q cannot connect from %s to %s: %w\", id, from, to, pipeline.ErrSignalNotSupported)\n}\n\n// ConnectorBuilder is a helper struct that given a set of Configs and Factories helps with creating connectors.\ntype ConnectorBuilder struct {\n\tcfgs      map[component.ID]component.Config\n\tfactories map[component.Type]connector.Factory\n}\n\n// NewConnector creates a new ConnectorBuilder to help with creating components form a set of configs and factories.\nfunc NewConnector(cfgs map[component.ID]component.Config, factories map[component.Type]connector.Factory) *ConnectorBuilder {\n\treturn &ConnectorBuilder{cfgs: cfgs, factories: factories}\n}\n\n// CreateTracesToTraces creates a Traces connector based on the settings and config.\nfunc (b *ConnectorBuilder) CreateTracesToTraces(ctx context.Context, set connector.Settings, next consumer.Traces) (connector.Traces, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"connector %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"connector factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.TracesToTracesStability())\n\treturn f.CreateTracesToTraces(ctx, set, cfg, next)\n}\n\n// CreateTracesToMetrics creates a Traces connector based on the settings and config.\nfunc (b *ConnectorBuilder) CreateTracesToMetrics(ctx context.Context, set connector.Settings, next consumer.Metrics) (connector.Traces, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"connector %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"connector factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.TracesToMetricsStability())\n\treturn f.CreateTracesToMetrics(ctx, set, cfg, next)\n}\n\n// CreateTracesToLogs creates a Traces connector based on the settings and config.\nfunc (b *ConnectorBuilder) CreateTracesToLogs(ctx context.Context, set connector.Settings, next consumer.Logs) (connector.Traces, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"connector %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"connector factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.TracesToLogsStability())\n\treturn f.CreateTracesToLogs(ctx, set, cfg, next)\n}\n\n// CreateTracesToProfiles creates a Traces connector based on the settings and config.\nfunc (b *ConnectorBuilder) CreateTracesToProfiles(ctx context.Context, set connector.Settings, next xconsumer.Profiles) (connector.Traces, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"connector %q is not configured\", set.ID)\n\t}\n\n\tconnFact, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"connector factory not available for: %q\", set.ID)\n\t}\n\n\tf, ok := connFact.(xconnector.Factory)\n\tif !ok {\n\t\treturn nil, errDataTypes(set.ID, pipeline.SignalTraces, xpipeline.SignalProfiles)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.TracesToProfilesStability())\n\treturn f.CreateTracesToProfiles(ctx, set, cfg, next)\n}\n\n// CreateMetricsToTraces creates a Metrics connector based on the settings and config.\nfunc (b *ConnectorBuilder) CreateMetricsToTraces(ctx context.Context, set connector.Settings, next consumer.Traces) (connector.Metrics, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"connector %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"connector factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.MetricsToTracesStability())\n\treturn f.CreateMetricsToTraces(ctx, set, cfg, next)\n}\n\n// CreateMetricsToMetrics creates a Metrics connector based on the settings and config.\nfunc (b *ConnectorBuilder) CreateMetricsToMetrics(ctx context.Context, set connector.Settings, next consumer.Metrics) (connector.Metrics, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"connector %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"connector factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.MetricsToMetricsStability())\n\treturn f.CreateMetricsToMetrics(ctx, set, cfg, next)\n}\n\n// CreateMetricsToLogs creates a Metrics connector based on the settings and config.\nfunc (b *ConnectorBuilder) CreateMetricsToLogs(ctx context.Context, set connector.Settings, next consumer.Logs) (connector.Metrics, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"connector %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"connector factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.MetricsToLogsStability())\n\treturn f.CreateMetricsToLogs(ctx, set, cfg, next)\n}\n\n// CreateMetricsToProfiles creates a Metrics connector based on the settings and config.\nfunc (b *ConnectorBuilder) CreateMetricsToProfiles(ctx context.Context, set connector.Settings, next xconsumer.Profiles) (connector.Metrics, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"connector %q is not configured\", set.ID)\n\t}\n\n\tconnFact, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"connector factory not available for: %q\", set.ID)\n\t}\n\n\tf, ok := connFact.(xconnector.Factory)\n\tif !ok {\n\t\treturn nil, errDataTypes(set.ID, pipeline.SignalMetrics, xpipeline.SignalProfiles)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.MetricsToProfilesStability())\n\treturn f.CreateMetricsToProfiles(ctx, set, cfg, next)\n}\n\n// CreateLogsToTraces creates a Logs connector based on the settings and config.\nfunc (b *ConnectorBuilder) CreateLogsToTraces(ctx context.Context, set connector.Settings, next consumer.Traces) (connector.Logs, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"connector %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"connector factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.LogsToTracesStability())\n\treturn f.CreateLogsToTraces(ctx, set, cfg, next)\n}\n\n// CreateLogsToMetrics creates a Logs connector based on the settings and config.\nfunc (b *ConnectorBuilder) CreateLogsToMetrics(ctx context.Context, set connector.Settings, next consumer.Metrics) (connector.Logs, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"connector %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"connector factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.LogsToMetricsStability())\n\treturn f.CreateLogsToMetrics(ctx, set, cfg, next)\n}\n\n// CreateLogsToLogs creates a Logs connector based on the settings and config.\nfunc (b *ConnectorBuilder) CreateLogsToLogs(ctx context.Context, set connector.Settings, next consumer.Logs) (connector.Logs, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"connector %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"connector factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.LogsToLogsStability())\n\treturn f.CreateLogsToLogs(ctx, set, cfg, next)\n}\n\n// CreateLogsToProfiles creates a Logs connector based on the settings and config.\nfunc (b *ConnectorBuilder) CreateLogsToProfiles(ctx context.Context, set connector.Settings, next xconsumer.Profiles) (connector.Logs, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"connector %q is not configured\", set.ID)\n\t}\n\n\tconnFact, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"connector factory not available for: %q\", set.ID)\n\t}\n\n\tf, ok := connFact.(xconnector.Factory)\n\tif !ok {\n\t\treturn nil, errDataTypes(set.ID, pipeline.SignalLogs, xpipeline.SignalProfiles)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.LogsToProfilesStability())\n\treturn f.CreateLogsToProfiles(ctx, set, cfg, next)\n}\n\n// CreateProfilesToTraces creates a Profiles connector based on the settings and config.\nfunc (b *ConnectorBuilder) CreateProfilesToTraces(ctx context.Context, set connector.Settings, next consumer.Traces) (xconnector.Profiles, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"connector %q is not configured\", set.ID)\n\t}\n\n\tconnFact, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"connector factory not available for: %q\", set.ID)\n\t}\n\n\tf, ok := connFact.(xconnector.Factory)\n\tif !ok {\n\t\treturn nil, errDataTypes(set.ID, xpipeline.SignalProfiles, pipeline.SignalTraces)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.ProfilesToTracesStability())\n\treturn f.CreateProfilesToTraces(ctx, set, cfg, next)\n}\n\n// CreateProfilesToMetrics creates a Profiles connector based on the settings and config.\nfunc (b *ConnectorBuilder) CreateProfilesToMetrics(ctx context.Context, set connector.Settings, next consumer.Metrics) (xconnector.Profiles, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"connector %q is not configured\", set.ID)\n\t}\n\n\tconnFact, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"connector factory not available for: %q\", set.ID)\n\t}\n\n\tf, ok := connFact.(xconnector.Factory)\n\tif !ok {\n\t\treturn nil, errDataTypes(set.ID, xpipeline.SignalProfiles, pipeline.SignalMetrics)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.ProfilesToMetricsStability())\n\treturn f.CreateProfilesToMetrics(ctx, set, cfg, next)\n}\n\n// CreateProfilesToLogs creates a Profiles connector based on the settings and config.\nfunc (b *ConnectorBuilder) CreateProfilesToLogs(ctx context.Context, set connector.Settings, next consumer.Logs) (xconnector.Profiles, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"connector %q is not configured\", set.ID)\n\t}\n\n\tconnFact, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"connector factory not available for: %q\", set.ID)\n\t}\n\n\tf, ok := connFact.(xconnector.Factory)\n\tif !ok {\n\t\treturn nil, errDataTypes(set.ID, xpipeline.SignalProfiles, pipeline.SignalLogs)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.ProfilesToLogsStability())\n\treturn f.CreateProfilesToLogs(ctx, set, cfg, next)\n}\n\n// CreateProfilesToProfiles creates a Profiles connector based on the settings and config.\nfunc (b *ConnectorBuilder) CreateProfilesToProfiles(ctx context.Context, set connector.Settings, next xconsumer.Profiles) (xconnector.Profiles, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"connector %q is not configured\", set.ID)\n\t}\n\n\tconnFact, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"connector factory not available for: %q\", set.ID)\n\t}\n\n\tf, ok := connFact.(xconnector.Factory)\n\tif !ok {\n\t\treturn nil, errDataTypes(set.ID, xpipeline.SignalProfiles, xpipeline.SignalProfiles)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.ProfilesToProfilesStability())\n\treturn f.CreateProfilesToProfiles(ctx, set, cfg, next)\n}\n\nfunc (b *ConnectorBuilder) IsConfigured(componentID component.ID) bool {\n\t_, ok := b.cfgs[componentID]\n\treturn ok\n}\n\nfunc (b *ConnectorBuilder) Factory(componentType component.Type) component.Factory {\n\treturn b.factories[componentType]\n}\n\n// NewNopConnectorConfigsAndFactories returns a configuration and factories that allows building a new nop connector.\nfunc NewNopConnectorConfigsAndFactories() (map[component.ID]component.Config, map[component.Type]connector.Factory) {\n\tnopFactory := connectortest.NewNopFactory()\n\t// Use a different ID than receivertest and exportertest to avoid ambiguous\n\t// configuration scenarios. Ambiguous IDs are detected in the 'otelcol' package,\n\t// but lower level packages such as 'service' assume that IDs are disambiguated.\n\tconnID := component.NewIDWithName(NopType, \"conn\")\n\n\tconfigs := map[component.ID]component.Config{\n\t\tconnID: nopFactory.CreateDefaultConfig(),\n\t}\n\tfactories := map[component.Type]connector.Factory{\n\t\tNopType: nopFactory,\n\t}\n\n\treturn configs, factories\n}\n"
  },
  {
    "path": "service/internal/builders/exporter.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builders // import \"go.opentelemetry.io/collector/service/internal/builders\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\n// ExporterBuilder is a helper struct that given a set of Configs and Factories helps with creating exporters.\ntype ExporterBuilder struct {\n\tcfgs      map[component.ID]component.Config\n\tfactories map[component.Type]exporter.Factory\n}\n\n// NewExporter creates a new ExporterBuilder to help with creating components form a set of configs and factories.\nfunc NewExporter(cfgs map[component.ID]component.Config, factories map[component.Type]exporter.Factory) *ExporterBuilder {\n\treturn &ExporterBuilder{cfgs: cfgs, factories: factories}\n}\n\n// CreateTraces creates a Traces exporter based on the settings and config.\nfunc (b *ExporterBuilder) CreateTraces(ctx context.Context, set exporter.Settings) (exporter.Traces, error) {\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"exporter %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"exporter factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.TracesStability())\n\treturn f.CreateTraces(ctx, set, cfg)\n}\n\n// CreateMetrics creates a Metrics exporter based on the settings and config.\nfunc (b *ExporterBuilder) CreateMetrics(ctx context.Context, set exporter.Settings) (exporter.Metrics, error) {\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"exporter %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"exporter factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.MetricsStability())\n\treturn f.CreateMetrics(ctx, set, cfg)\n}\n\n// CreateLogs creates a Logs exporter based on the settings and config.\nfunc (b *ExporterBuilder) CreateLogs(ctx context.Context, set exporter.Settings) (exporter.Logs, error) {\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"exporter %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"exporter factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.LogsStability())\n\treturn f.CreateLogs(ctx, set, cfg)\n}\n\n// CreateProfiles creates a Profiles exporter based on the settings and config.\nfunc (b *ExporterBuilder) CreateProfiles(ctx context.Context, set exporter.Settings) (xexporter.Profiles, error) {\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"exporter %q is not configured\", set.ID)\n\t}\n\n\texpFact, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"exporter factory not available for: %q\", set.ID)\n\t}\n\n\tf, ok := expFact.(xexporter.Factory)\n\tif !ok {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.ProfilesStability())\n\treturn f.CreateProfiles(ctx, set, cfg)\n}\n\nfunc (b *ExporterBuilder) Factory(componentType component.Type) component.Factory {\n\treturn b.factories[componentType]\n}\n\n// NewNopExporterConfigsAndFactories returns a configuration and factories that allows building a new nop exporter.\nfunc NewNopExporterConfigsAndFactories() (map[component.ID]component.Config, map[component.Type]exporter.Factory) {\n\tnopFactory := exportertest.NewNopFactory()\n\tconfigs := map[component.ID]component.Config{\n\t\tcomponent.NewID(NopType): nopFactory.CreateDefaultConfig(),\n\t}\n\tfactories := map[component.Type]exporter.Factory{\n\t\tNopType: nopFactory,\n\t}\n\n\treturn configs, factories\n}\n"
  },
  {
    "path": "service/internal/builders/extension.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builders // import \"go.opentelemetry.io/collector/service/internal/builders\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/extensiontest\"\n)\n\n// Extension is an interface that allows using implementations of the builder\n// from different packages.\ntype Extension interface {\n\tCreate(context.Context, extension.Settings) (extension.Extension, error)\n\tFactory(component.Type) component.Factory\n}\n\n// ExtensionBuilder is a helper struct that given a set of Configs and Factories helps with creating extensions.\ntype ExtensionBuilder struct {\n\tcfgs      map[component.ID]component.Config\n\tfactories map[component.Type]extension.Factory\n}\n\n// NewExtension creates a new ExtensionBuilder to help with creating\n// components form a set of configs and factories.\nfunc NewExtension(cfgs map[component.ID]component.Config, factories map[component.Type]extension.Factory) *ExtensionBuilder {\n\treturn &ExtensionBuilder{cfgs: cfgs, factories: factories}\n}\n\n// Create creates an extension based on the settings and configs available.\nfunc (b *ExtensionBuilder) Create(ctx context.Context, set extension.Settings) (extension.Extension, error) {\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"extension %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"extension factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.Stability())\n\treturn f.Create(ctx, set, cfg)\n}\n\nfunc (b *ExtensionBuilder) Factory(componentType component.Type) component.Factory {\n\treturn b.factories[componentType]\n}\n\n// NewNopExtensionConfigsAndFactories returns a configuration and factories that allows building a new nop processor.\nfunc NewNopExtensionConfigsAndFactories() (map[component.ID]component.Config, map[component.Type]extension.Factory) {\n\tnopFactory := extensiontest.NewNopFactory()\n\tconfigs := map[component.ID]component.Config{\n\t\tcomponent.NewID(NopType): nopFactory.CreateDefaultConfig(),\n\t}\n\tfactories := map[component.Type]extension.Factory{\n\t\tNopType: nopFactory,\n\t}\n\treturn configs, factories\n}\n"
  },
  {
    "path": "service/internal/builders/processor.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builders // import \"go.opentelemetry.io/collector/service/internal/builders\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n\t\"go.opentelemetry.io/collector/processor/xprocessor\"\n)\n\n// ProcessorBuilder processor is a helper struct that given a set of Configs\n// and Factories helps with creating processors.\ntype ProcessorBuilder struct {\n\tcfgs      map[component.ID]component.Config\n\tfactories map[component.Type]processor.Factory\n}\n\n// NewProcessor creates a new ProcessorBuilder to help with creating components form a set of configs and factories.\nfunc NewProcessor(cfgs map[component.ID]component.Config, factories map[component.Type]processor.Factory) *ProcessorBuilder {\n\treturn &ProcessorBuilder{cfgs: cfgs, factories: factories}\n}\n\n// CreateTraces creates a Traces processor based on the settings and config.\nfunc (b *ProcessorBuilder) CreateTraces(ctx context.Context, set processor.Settings, next consumer.Traces) (processor.Traces, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"processor %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"processor factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.TracesStability())\n\treturn f.CreateTraces(ctx, set, cfg, next)\n}\n\n// CreateMetrics creates a Metrics processor based on the settings and config.\nfunc (b *ProcessorBuilder) CreateMetrics(ctx context.Context, set processor.Settings, next consumer.Metrics) (processor.Metrics, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"processor %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"processor factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.MetricsStability())\n\treturn f.CreateMetrics(ctx, set, cfg, next)\n}\n\n// CreateLogs creates a Logs processor based on the settings and config.\nfunc (b *ProcessorBuilder) CreateLogs(ctx context.Context, set processor.Settings, next consumer.Logs) (processor.Logs, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"processor %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"processor factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.LogsStability())\n\treturn f.CreateLogs(ctx, set, cfg, next)\n}\n\n// CreateProfiles creates a Profiles processor based on the settings and config.\nfunc (b *ProcessorBuilder) CreateProfiles(ctx context.Context, set processor.Settings, next xconsumer.Profiles) (xprocessor.Profiles, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"processor %q is not configured\", set.ID)\n\t}\n\n\tprocFact, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"processor factory not available for: %q\", set.ID)\n\t}\n\n\tf, ok := procFact.(xprocessor.Factory)\n\tif !ok {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.ProfilesStability())\n\treturn f.CreateProfiles(ctx, set, cfg, next)\n}\n\nfunc (b *ProcessorBuilder) Factory(componentType component.Type) component.Factory {\n\treturn b.factories[componentType]\n}\n\n// NewNopProcessorConfigsAndFactories returns a configuration and factories that allows building a new nop processor.\nfunc NewNopProcessorConfigsAndFactories() (map[component.ID]component.Config, map[component.Type]processor.Factory) {\n\tnopFactory := processortest.NewNopFactory()\n\tconfigs := map[component.ID]component.Config{\n\t\tcomponent.NewID(NopType): nopFactory.CreateDefaultConfig(),\n\t}\n\tfactories := map[component.Type]processor.Factory{\n\t\tNopType: nopFactory,\n\t}\n\n\treturn configs, factories\n}\n"
  },
  {
    "path": "service/internal/builders/receiver.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage builders // import \"go.opentelemetry.io/collector/service/internal/builders\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n)\n\n// ReceiverBuilder receiver is a helper struct that given a set of Configs and\n// Factories helps with creating receivers.\ntype ReceiverBuilder struct {\n\tcfgs      map[component.ID]component.Config\n\tfactories map[component.Type]receiver.Factory\n}\n\n// NewReceiver creates a new ReceiverBuilder to help with creating\n// components form a set of configs and factories.\nfunc NewReceiver(cfgs map[component.ID]component.Config, factories map[component.Type]receiver.Factory) *ReceiverBuilder {\n\treturn &ReceiverBuilder{cfgs: cfgs, factories: factories}\n}\n\n// CreateTraces creates a Traces receiver based on the settings and config.\nfunc (b *ReceiverBuilder) CreateTraces(ctx context.Context, set receiver.Settings, next consumer.Traces) (receiver.Traces, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"receiver %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"receiver factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.TracesStability())\n\treturn f.CreateTraces(ctx, set, cfg, next)\n}\n\n// CreateMetrics creates a Metrics receiver based on the settings and config.\nfunc (b *ReceiverBuilder) CreateMetrics(ctx context.Context, set receiver.Settings, next consumer.Metrics) (receiver.Metrics, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"receiver %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"receiver factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.MetricsStability())\n\treturn f.CreateMetrics(ctx, set, cfg, next)\n}\n\n// CreateLogs creates a Logs receiver based on the settings and config.\nfunc (b *ReceiverBuilder) CreateLogs(ctx context.Context, set receiver.Settings, next consumer.Logs) (receiver.Logs, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"receiver %q is not configured\", set.ID)\n\t}\n\n\tf, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"receiver factory not available for: %q\", set.ID)\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.LogsStability())\n\treturn f.CreateLogs(ctx, set, cfg, next)\n}\n\n// CreateProfiles creates a Profiles receiver based on the settings and config.\nfunc (b *ReceiverBuilder) CreateProfiles(ctx context.Context, set receiver.Settings, next xconsumer.Profiles) (xreceiver.Profiles, error) {\n\tif next == nil {\n\t\treturn nil, errNilNextConsumer\n\t}\n\tcfg, existsCfg := b.cfgs[set.ID]\n\tif !existsCfg {\n\t\treturn nil, fmt.Errorf(\"receiver %q is not configured\", set.ID)\n\t}\n\n\trecvFact, existsFactory := b.factories[set.ID.Type()]\n\tif !existsFactory {\n\t\treturn nil, fmt.Errorf(\"receiver factory not available for: %q\", set.ID)\n\t}\n\n\tf, ok := recvFact.(xreceiver.Factory)\n\tif !ok {\n\t\treturn nil, pipeline.ErrSignalNotSupported\n\t}\n\n\tlogDeprecatedTypeAlias(set.Logger, f, set.ID.Type())\n\tlogStabilityLevel(set.Logger, f.ProfilesStability())\n\treturn f.CreateProfiles(ctx, set, cfg, next)\n}\n\nfunc (b *ReceiverBuilder) Factory(componentType component.Type) component.Factory {\n\treturn b.factories[componentType]\n}\n\n// NewNopReceiverConfigsAndFactories returns a configuration and factories that allows building a new nop receiver.\nfunc NewNopReceiverConfigsAndFactories() (map[component.ID]component.Config, map[component.Type]receiver.Factory) {\n\tnopFactory := receivertest.NewNopFactory()\n\tconfigs := map[component.ID]component.Config{\n\t\tcomponent.NewID(NopType): nopFactory.CreateDefaultConfig(),\n\t}\n\tfactories := map[component.Type]receiver.Factory{\n\t\tNopType: nopFactory,\n\t}\n\n\treturn configs, factories\n}\n"
  },
  {
    "path": "service/internal/capabilityconsumer/capabilities.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage capabilityconsumer // import \"go.opentelemetry.io/collector/service/internal/capabilityconsumer\"\n\nimport (\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n)\n\nfunc NewLogs(logs consumer.Logs, capabilities consumer.Capabilities) consumer.Logs {\n\tif logs.Capabilities() == capabilities {\n\t\treturn logs\n\t}\n\treturn capLogs{Logs: logs, cap: capabilities}\n}\n\ntype capLogs struct {\n\tconsumer.Logs\n\tcap consumer.Capabilities\n}\n\nfunc (mts capLogs) Capabilities() consumer.Capabilities {\n\treturn mts.cap\n}\n\nfunc NewMetrics(metrics consumer.Metrics, capabilities consumer.Capabilities) consumer.Metrics {\n\tif metrics.Capabilities() == capabilities {\n\t\treturn metrics\n\t}\n\treturn capMetrics{Metrics: metrics, cap: capabilities}\n}\n\ntype capMetrics struct {\n\tconsumer.Metrics\n\tcap consumer.Capabilities\n}\n\nfunc (mts capMetrics) Capabilities() consumer.Capabilities {\n\treturn mts.cap\n}\n\nfunc NewTraces(traces consumer.Traces, capabilities consumer.Capabilities) consumer.Traces {\n\tif traces.Capabilities() == capabilities {\n\t\treturn traces\n\t}\n\treturn capTraces{Traces: traces, cap: capabilities}\n}\n\ntype capTraces struct {\n\tconsumer.Traces\n\tcap consumer.Capabilities\n}\n\nfunc (mts capTraces) Capabilities() consumer.Capabilities {\n\treturn mts.cap\n}\n\nfunc NewProfiles(profiles xconsumer.Profiles, capabilities consumer.Capabilities) xconsumer.Profiles {\n\tif profiles.Capabilities() == capabilities {\n\t\treturn profiles\n\t}\n\treturn capProfiles{Profiles: profiles, cap: capabilities}\n}\n\ntype capProfiles struct {\n\txconsumer.Profiles\n\tcap consumer.Capabilities\n}\n\nfunc (mts capProfiles) Capabilities() consumer.Capabilities {\n\treturn mts.cap\n}\n"
  },
  {
    "path": "service/internal/capabilityconsumer/capabilities_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage capabilityconsumer\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nfunc TestLogs(t *testing.T) {\n\tsink := &consumertest.LogsSink{}\n\trequire.Equal(t, consumer.Capabilities{MutatesData: false}, sink.Capabilities())\n\n\tsame := NewLogs(sink, consumer.Capabilities{MutatesData: false})\n\tassert.Same(t, sink, same)\n\n\twrap := NewLogs(sink, consumer.Capabilities{MutatesData: true})\n\tassert.Equal(t, consumer.Capabilities{MutatesData: true}, wrap.Capabilities())\n\n\trequire.NoError(t, wrap.ConsumeLogs(context.Background(), testdata.GenerateLogs(1)))\n\tassert.Len(t, sink.AllLogs(), 1)\n\tassert.Equal(t, testdata.GenerateLogs(1), sink.AllLogs()[0])\n}\n\nfunc TestMetrics(t *testing.T) {\n\tsink := &consumertest.MetricsSink{}\n\trequire.Equal(t, consumer.Capabilities{MutatesData: false}, sink.Capabilities())\n\n\tsame := NewMetrics(sink, consumer.Capabilities{MutatesData: false})\n\tassert.Same(t, sink, same)\n\n\twrap := NewMetrics(sink, consumer.Capabilities{MutatesData: true})\n\tassert.Equal(t, consumer.Capabilities{MutatesData: true}, wrap.Capabilities())\n\n\trequire.NoError(t, wrap.ConsumeMetrics(context.Background(), testdata.GenerateMetrics(1)))\n\tassert.Len(t, sink.AllMetrics(), 1)\n\tassert.Equal(t, testdata.GenerateMetrics(1), sink.AllMetrics()[0])\n}\n\nfunc TestTraces(t *testing.T) {\n\tsink := &consumertest.TracesSink{}\n\trequire.Equal(t, consumer.Capabilities{MutatesData: false}, sink.Capabilities())\n\n\tsame := NewTraces(sink, consumer.Capabilities{MutatesData: false})\n\tassert.Same(t, sink, same)\n\n\twrap := NewTraces(sink, consumer.Capabilities{MutatesData: true})\n\tassert.Equal(t, consumer.Capabilities{MutatesData: true}, wrap.Capabilities())\n\n\trequire.NoError(t, wrap.ConsumeTraces(context.Background(), testdata.GenerateTraces(1)))\n\tassert.Len(t, sink.AllTraces(), 1)\n\tassert.Equal(t, testdata.GenerateTraces(1), sink.AllTraces()[0])\n}\n\nfunc TestProfiles(t *testing.T) {\n\tsink := &consumertest.ProfilesSink{}\n\trequire.Equal(t, consumer.Capabilities{MutatesData: false}, sink.Capabilities())\n\n\tsame := NewProfiles(sink, consumer.Capabilities{MutatesData: false})\n\tassert.Same(t, sink, same)\n\n\twrap := NewProfiles(sink, consumer.Capabilities{MutatesData: true})\n\tassert.Equal(t, consumer.Capabilities{MutatesData: true}, wrap.Capabilities())\n\n\trequire.NoError(t, wrap.ConsumeProfiles(context.Background(), testdata.GenerateProfiles(1)))\n\tassert.Len(t, sink.AllProfiles(), 1)\n\tassert.Equal(t, testdata.GenerateProfiles(1), sink.AllProfiles()[0])\n}\n"
  },
  {
    "path": "service/internal/capabilityconsumer/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage capabilityconsumer\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "service/internal/componentattribute/logger_zap.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componentattribute // import \"go.opentelemetry.io/collector/service/internal/componentattribute\"\n\nimport (\n\t\"slices\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\n\t\"go.opentelemetry.io/collector/internal/telemetry\"\n)\n\n// This wrapper around zapcore.Field tells the Zap -> OTel bridge that the field\n// should be turned into an instrumentation scope instead of a set of log record attributes.\ntype scopeAttributesField struct {\n\tfields []zapcore.Field\n\tattrs  []attribute.KeyValue\n}\n\nvar _ zapcore.ObjectMarshaler = scopeAttributesField{}\n\nfunc (saf scopeAttributesField) MarshalLogObject(enc zapcore.ObjectEncoder) error {\n\tfor _, field := range saf.fields {\n\t\tfield.AddTo(enc)\n\t}\n\treturn nil\n}\n\nfunc makeScopeField(attrs []attribute.KeyValue) zap.Field {\n\treturn zap.Inline(scopeAttributesField{\n\t\tfields: telemetry.ToZapFields(attrs),\n\t\tattrs:  attrs,\n\t})\n}\n\nfunc ExtractLogScopeAttributes(field zap.Field) ([]attribute.KeyValue, bool) {\n\tif field.Type != zapcore.InlineMarshalerType {\n\t\treturn nil, false\n\t}\n\tsaf, ok := field.Interface.(scopeAttributesField)\n\tif !ok {\n\t\treturn nil, false\n\t}\n\treturn saf.attrs, true\n}\n\ntype coreWithAttributes struct {\n\tzapcore.Core\n\tsourceCore zapcore.Core\n\tattrs      []attribute.KeyValue\n\twithFields []zap.Field\n}\n\nvar _ zapcore.Core = coreWithAttributes{}\n\nfunc (cwa coreWithAttributes) With(fields []zapcore.Field) zapcore.Core {\n\tcwa.withFields = append(cwa.withFields, fields...)\n\tcwa.Core = cwa.Core.With(fields)\n\treturn cwa\n}\n\nfunc LoggerWithAttributes(logger *zap.Logger, attrs []attribute.KeyValue) *zap.Logger {\n\treturn logger.WithOptions(zap.WrapCore(func(c zapcore.Core) zapcore.Core {\n\t\treturn coreWithAttributes{\n\t\t\tCore:       c.With([]zap.Field{makeScopeField(attrs)}),\n\t\t\tsourceCore: c,\n\t\t\tattrs:      attrs,\n\t\t}\n\t}))\n}\n\nfunc (cwa coreWithAttributes) DropInjectedAttributes(droppedAttrs ...string) zapcore.Core {\n\tcwa.attrs = slices.DeleteFunc(slices.Clone(cwa.attrs), func(kv attribute.KeyValue) bool {\n\t\treturn slices.Contains(droppedAttrs, string(kv.Key))\n\t})\n\tcwa.Core = cwa.sourceCore.With(append([]zap.Field{makeScopeField(cwa.attrs)}, cwa.withFields...))\n\treturn cwa\n}\n"
  },
  {
    "path": "service/internal/componentattribute/meter_provider.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componentattribute // import \"go.opentelemetry.io/collector/service/internal/componentattribute\"\n\nimport (\n\t\"slices\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/metric\"\n)\n\ntype meterProviderWithAttributes struct {\n\tmetric.MeterProvider\n\tattrs []attribute.KeyValue\n}\n\nfunc (mpwa meterProviderWithAttributes) Meter(name string, opts ...metric.MeterOption) metric.Meter {\n\tconf := metric.NewMeterConfig(opts...)\n\tattrSet := conf.InstrumentationAttributes()\n\t// prepend our attributes so they can be overwritten\n\tnewAttrs := append(slices.Clone(mpwa.attrs), attrSet.ToSlice()...)\n\t// append our attribute set option to overwrite the old one\n\topts = append(opts, metric.WithInstrumentationAttributes(newAttrs...))\n\treturn mpwa.MeterProvider.Meter(name, opts...)\n}\n\nfunc (mpwa meterProviderWithAttributes) DropInjectedAttributes(droppedAttrs ...string) metric.MeterProvider {\n\treturn meterProviderWithAttributes{\n\t\tMeterProvider: mpwa.MeterProvider,\n\t\tattrs: slices.DeleteFunc(slices.Clone(mpwa.attrs), func(kv attribute.KeyValue) bool {\n\t\t\treturn slices.Contains(droppedAttrs, string(kv.Key))\n\t\t}),\n\t}\n}\n"
  },
  {
    "path": "service/internal/componentattribute/telemetry.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componentattribute // import \"go.opentelemetry.io/collector/service/internal/componentattribute\"\n\nimport (\n\t\"go.opentelemetry.io/otel/attribute\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n)\n\nfunc TelemetrySettingsWithAttributes(ts component.TelemetrySettings, attrSet attribute.Set) component.TelemetrySettings {\n\tattrs := attrSet.ToSlice()\n\tts.Logger = LoggerWithAttributes(ts.Logger, attrs)\n\tts.TracerProvider = tracerProviderWithAttributes{\n\t\tTracerProvider: ts.TracerProvider,\n\t\tattrs:          attrs,\n\t}\n\tif metadata.TelemetryNewPipelineTelemetryFeatureGate.IsEnabled() {\n\t\tts.MeterProvider = meterProviderWithAttributes{\n\t\t\tMeterProvider: ts.MeterProvider,\n\t\t\tattrs:         attrs,\n\t\t}\n\t}\n\treturn ts\n}\n"
  },
  {
    "path": "service/internal/componentattribute/telemetry_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componentattribute_test\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/metric\"\n\tmetricSdk \"go.opentelemetry.io/otel/sdk/metric\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\ttraceSdk \"go.opentelemetry.io/otel/sdk/trace\"\n\t\"go.opentelemetry.io/otel/sdk/trace/tracetest\"\n\t\"go.opentelemetry.io/otel/trace\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/internal/telemetry\"\n\t\"go.opentelemetry.io/collector/service/internal/componentattribute\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n)\n\nfunc findScopeAttributesField(context []zap.Field) ([]attribute.KeyValue, bool) {\n\tfor _, field := range context {\n\t\tscope, ok := componentattribute.ExtractLogScopeAttributes(field)\n\t\tif ok {\n\t\t\treturn scope, true\n\t\t}\n\t}\n\treturn nil, false\n}\n\nfunc attributeSetJSON(t *testing.T, set attribute.Set) string {\n\tscopeBuf, err := json.Marshal(set.MarshalLog())\n\trequire.NoError(t, err)\n\treturn string(scopeBuf)\n}\n\nfunc getLogScopeAndFields(t *testing.T, logObs *observer.ObservedLogs) (string, string) {\n\tlogs := logObs.TakeAll()\n\trequire.Len(t, logs, 1)\n\tlog := logs[0]\n\trequire.Equal(t, \"test\", log.Message)\n\n\tscope, ok := findScopeAttributesField(log.Context)\n\trequire.True(t, ok, \"Failed to find ScopeAttributesField field\")\n\tscopeStr := attributeSetJSON(t, attribute.NewSet(scope...))\n\n\tenc := zapcore.NewJSONEncoder(zapcore.EncoderConfig{})\n\tfieldsBuf, err := enc.EncodeEntry(log.Entry, log.Context)\n\trequire.NoError(t, err)\n\tfieldsStr := strings.TrimSuffix(fieldsBuf.String(), \"\\n\")\n\n\treturn scopeStr, fieldsStr\n}\n\nfunc getSpanScope(t *testing.T, spanObs *tracetest.InMemoryExporter) string {\n\tspans := spanObs.GetSpans().Snapshots()\n\tspanObs.Reset()\n\trequire.Len(t, spans, 1)\n\tspan := spans[0]\n\trequire.Equal(t, \"test\", span.Name())\n\treturn attributeSetJSON(t, span.InstrumentationScope().Attributes)\n}\n\nfunc getMetricScope(t *testing.T, metricObs *metricSdk.ManualReader) string {\n\trm := metricdata.ResourceMetrics{}\n\terr := metricObs.Collect(t.Context(), &rm)\n\trequire.NoError(t, err)\n\trequire.Len(t, rm.ScopeMetrics, 1)\n\treturn attributeSetJSON(t, rm.ScopeMetrics[0].Scope.Attributes)\n}\n\ntype TestResults struct {\n\tLogScope    string\n\tLogFields   string\n\tSpanScope   string\n\tMetricScope string\n}\n\nfunc getScopes(t *testing.T, tswa component.TelemetrySettings, logObs *observer.ObservedLogs, spanObs *tracetest.InMemoryExporter, metricObs *metricSdk.ManualReader) TestResults {\n\t// Create new tracer, meter, and metric instrument\n\ttracer := tswa.TracerProvider.Tracer(\"test\", trace.WithInstrumentationAttributes(attribute.String(\"after\", \"val\")))\n\tmeter := tswa.MeterProvider.Meter(\"test\", metric.WithInstrumentationAttributes(attribute.String(\"after\", \"val\")))\n\tgauge, err := meter.Int64Gauge(\"test\")\n\trequire.NoError(t, err)\n\n\t// Emit a log, a span, and a metric point\n\ttswa.Logger.Info(\"test\", zap.String(\"manual\", \"val\"))\n\tlogScope, logFields := getLogScopeAndFields(t, logObs)\n\n\t_, span := tracer.Start(t.Context(), \"test\")\n\tspan.End()\n\n\tgauge.Record(t.Context(), 1)\n\n\t// Check resulting scope attributes\n\treturn TestResults{\n\t\tLogScope:    logScope,\n\t\tLogFields:   logFields,\n\t\tSpanScope:   getSpanScope(t, spanObs),\n\t\tMetricScope: getMetricScope(t, metricObs),\n\t}\n}\n\ntype tracerProviderWrapper struct {\n\ttrace.TracerProvider\n}\n\nfunc testTelemetryWithAttributes(t *testing.T, useTraceSdk bool) {\n\tprevState := metadata.TelemetryNewPipelineTelemetryFeatureGate.IsEnabled()\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.TelemetryNewPipelineTelemetryFeatureGate.ID(), true))\n\tdefer func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.TelemetryNewPipelineTelemetryFeatureGate.ID(), prevState))\n\t}()\n\n\t// Setup mock TelemetrySettings\n\tcore, logObs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tlogger = logger.With(zap.String(\"before\", \"val\"))\n\n\tspanObs := tracetest.NewInMemoryExporter()\n\tvar tracerProvider trace.TracerProvider = traceSdk.NewTracerProvider(traceSdk.WithSpanProcessor(traceSdk.NewSimpleSpanProcessor(spanObs)))\n\tif !useTraceSdk {\n\t\ttracerProvider = tracerProviderWrapper{TracerProvider: tracerProvider}\n\t}\n\n\t// Use delta temporality so points from the first step are no longer exported in the second step\n\tmetricObs := metricSdk.NewManualReader(metricSdk.WithTemporalitySelector(func(metricSdk.InstrumentKind) metricdata.Temporality {\n\t\treturn metricdata.DeltaTemporality\n\t}))\n\tmeterProvider := metricSdk.NewMeterProvider(metricSdk.WithReader(metricObs))\n\n\tts := component.TelemetrySettings{\n\t\tLogger:         logger,\n\t\tTracerProvider: tracerProvider,\n\t\tMeterProvider:  meterProvider,\n\t}\n\n\t// Inject attributes\n\ttswa := componentattribute.TelemetrySettingsWithAttributes(ts, attribute.NewSet(\n\t\tattribute.String(\"injected1\", \"val\"),\n\t\tattribute.String(\"injected2\", \"val\"),\n\t))\n\n\t// Check that SDK-only methods are accessible through Unwrap\n\twrapped, ok := tswa.TracerProvider.(interface {\n\t\tUnwrap() trace.TracerProvider\n\t})\n\tif assert.True(t, ok) {\n\t\t_, ok := wrapped.Unwrap().(interface {\n\t\t\tForceFlush(ctx context.Context) error\n\t\t})\n\t\tassert.Equal(t, useTraceSdk, ok)\n\t}\n\n\t// Add extra log attribute\n\ttswa.Logger = tswa.Logger.With(zap.String(\"after\", \"val\"))\n\n\tassert.Equal(t, TestResults{\n\t\tLogScope:    `{\"injected1\":\"val\",\"injected2\":\"val\"}`,\n\t\tLogFields:   `{\"before\":\"val\",\"injected1\":\"val\",\"injected2\":\"val\",\"after\":\"val\",\"manual\":\"val\"}`,\n\t\tSpanScope:   `{\"after\":\"val\",\"injected1\":\"val\",\"injected2\":\"val\"}`,\n\t\tMetricScope: `{\"after\":\"val\",\"injected1\":\"val\",\"injected2\":\"val\"}`,\n\t}, getScopes(t, tswa, logObs, spanObs, metricObs))\n\n\t// Drop one injected attribute\n\ttswa = telemetry.DropInjectedAttributes(tswa, \"injected1\")\n\n\t// Check scopes again\n\tassert.Equal(t, TestResults{\n\t\tLogScope:    `{\"injected2\":\"val\"}`,\n\t\tLogFields:   `{\"before\":\"val\",\"injected2\":\"val\",\"after\":\"val\",\"manual\":\"val\"}`,\n\t\tSpanScope:   `{\"after\":\"val\",\"injected2\":\"val\"}`,\n\t\tMetricScope: `{\"after\":\"val\",\"injected2\":\"val\"}`,\n\t}, getScopes(t, tswa, logObs, spanObs, metricObs))\n}\n\nfunc TestTelemetryWithAttributes(t *testing.T) {\n\tt.Run(\"sdk\", func(t *testing.T) {\n\t\ttestTelemetryWithAttributes(t, true)\n\t})\n\tt.Run(\"generic\", func(t *testing.T) {\n\t\ttestTelemetryWithAttributes(t, false)\n\t})\n}\n"
  },
  {
    "path": "service/internal/componentattribute/tracer_provider.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage componentattribute // import \"go.opentelemetry.io/collector/service/internal/componentattribute\"\n\nimport (\n\t\"slices\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/trace\"\n)\n\ntype tracerProviderWithAttributes struct {\n\ttrace.TracerProvider\n\tattrs []attribute.KeyValue\n}\n\nfunc (tpwa tracerProviderWithAttributes) Tracer(name string, options ...trace.TracerOption) trace.Tracer {\n\tconf := trace.NewTracerConfig(options...)\n\tattrSet := conf.InstrumentationAttributes()\n\t// prepend our attributes so they can be overwritten\n\tnewAttrs := append(slices.Clone(tpwa.attrs), attrSet.ToSlice()...)\n\t// append our attribute set option to overwrite the old one\n\toptions = append(options, trace.WithInstrumentationAttributes(newAttrs...))\n\treturn tpwa.TracerProvider.Tracer(name, options...)\n}\n\nfunc (tpwa tracerProviderWithAttributes) Unwrap() trace.TracerProvider {\n\treturn tpwa.TracerProvider\n}\n\nfunc (tpwa tracerProviderWithAttributes) DropInjectedAttributes(droppedAttrs ...string) trace.TracerProvider {\n\treturn tracerProviderWithAttributes{\n\t\tTracerProvider: tpwa.TracerProvider,\n\t\tattrs: slices.DeleteFunc(slices.Clone(tpwa.attrs), func(kv attribute.KeyValue) bool {\n\t\t\treturn slices.Contains(droppedAttrs, string(kv.Key))\n\t\t}),\n\t}\n}\n"
  },
  {
    "path": "service/internal/graph/capabilities.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage graph // import \"go.opentelemetry.io/collector/service/internal/graph\"\n\nimport (\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/service/internal/attribute\"\n)\n\nvar _ consumerNode = (*capabilitiesNode)(nil)\n\n// Every pipeline has a \"virtual\" capabilities node immediately after the receiver(s).\n// There are two purposes for this node:\n// 1. Present aggregated capabilities to receivers, such as whether the pipeline mutates data.\n// 2. Present a consistent \"first consumer\" for each pipeline.\n// The nodeID is derived from \"pipeline ID\".\ntype capabilitiesNode struct {\n\tattribute.Attributes\n\tpipelineID pipeline.ID\n\tbaseConsumer\n\tconsumer.ConsumeTracesFunc\n\tconsumer.ConsumeMetricsFunc\n\tconsumer.ConsumeLogsFunc\n\txconsumer.ConsumeProfilesFunc\n}\n\nfunc newCapabilitiesNode(pipelineID pipeline.ID) *capabilitiesNode {\n\treturn &capabilitiesNode{\n\t\tAttributes: attribute.Capabilities(pipelineID),\n\t\tpipelineID: pipelineID,\n\t}\n}\n\nfunc (n *capabilitiesNode) getConsumer() baseConsumer {\n\treturn n\n}\n"
  },
  {
    "path": "service/internal/graph/connector.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage graph // import \"go.opentelemetry.io/collector/service/internal/graph\"\n\nimport (\n\t\"context\"\n\n\totelattr \"go.opentelemetry.io/otel/attribute\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/xconnector\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\t\"go.opentelemetry.io/collector/service/internal/attribute\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n\t\"go.opentelemetry.io/collector/service/internal/capabilityconsumer\"\n\t\"go.opentelemetry.io/collector/service/internal/componentattribute\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n\t\"go.opentelemetry.io/collector/service/internal/obsconsumer\"\n\t\"go.opentelemetry.io/collector/service/internal/refconsumer\"\n)\n\nconst pipelineIDAttrKey = \"otelcol.pipeline.id\"\n\nvar _ consumerNode = (*connectorNode)(nil)\n\ntype connectorNode struct {\n\tattribute.Attributes\n\tcomponentID      component.ID\n\texprPipelineType pipeline.Signal\n\trcvrPipelineType pipeline.Signal\n\tcomponent.Component\n\tconsumer baseConsumer\n}\n\nfunc newConnectorNode(exprPipelineType, rcvrPipelineType pipeline.Signal, connID component.ID) *connectorNode {\n\treturn &connectorNode{\n\t\tAttributes:       attribute.Connector(exprPipelineType, rcvrPipelineType, connID),\n\t\tcomponentID:      connID,\n\t\texprPipelineType: exprPipelineType,\n\t\trcvrPipelineType: rcvrPipelineType,\n\t}\n}\n\nfunc (n *connectorNode) getConsumer() baseConsumer {\n\treturn n.consumer\n}\n\nfunc (n *connectorNode) buildComponent(\n\tctx context.Context,\n\ttel component.TelemetrySettings,\n\tinfo component.BuildInfo,\n\tbuilder *builders.ConnectorBuilder,\n\tnexts []baseConsumer,\n) error {\n\tset := connector.Settings{\n\t\tID:                n.componentID,\n\t\tTelemetrySettings: componentattribute.TelemetrySettingsWithAttributes(tel, *n.Set()),\n\t\tBuildInfo:         info,\n\t}\n\n\tswitch n.rcvrPipelineType {\n\tcase pipeline.SignalTraces:\n\t\treturn n.buildTraces(ctx, set, builder, nexts)\n\tcase pipeline.SignalMetrics:\n\t\treturn n.buildMetrics(ctx, set, builder, nexts)\n\tcase pipeline.SignalLogs:\n\t\treturn n.buildLogs(ctx, set, builder, nexts)\n\tcase xpipeline.SignalProfiles:\n\t\treturn n.buildProfiles(ctx, set, builder, nexts)\n\t}\n\treturn nil\n}\n\nfunc (n *connectorNode) buildTraces(\n\tctx context.Context,\n\tset connector.Settings,\n\tbuilder *builders.ConnectorBuilder,\n\tnexts []baseConsumer,\n) error {\n\ttb, err := metadata.NewTelemetryBuilder(set.TelemetrySettings)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tproducedSettings := obsconsumer.Settings{\n\t\tItemCounter: tb.ConnectorProducedItems,\n\t\tSizeCounter: tb.ConnectorProducedSize,\n\t\tLogger:      set.Logger,\n\t}\n\tconsumedSettings := obsconsumer.Settings{\n\t\tItemCounter: tb.ConnectorConsumedItems,\n\t\tSizeCounter: tb.ConnectorConsumedSize,\n\t\tLogger:      set.Logger,\n\t}\n\n\tconsumers := make(map[pipeline.ID]consumer.Traces, len(nexts))\n\tfor _, next := range nexts {\n\t\tconsumers[next.(*capabilitiesNode).pipelineID] = obsconsumer.NewTraces(\n\t\t\tnext.(consumer.Traces),\n\t\t\tproducedSettings,\n\t\t\tobsconsumer.WithStaticDataPointAttribute(\n\t\t\t\totelattr.String(\n\t\t\t\t\tpipelineIDAttrKey,\n\t\t\t\t\tnext.(*capabilitiesNode).pipelineID.String(),\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\t}\n\tnext := connector.NewTracesRouter(consumers)\n\n\tswitch n.exprPipelineType {\n\tcase pipeline.SignalTraces:\n\t\tn.Component, err = builder.CreateTracesToTraces(ctx, set, next)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Connectors which might pass along data must inherit capabilities of all nexts\n\t\tn.consumer = obsconsumer.NewTraces(\n\t\t\tcapabilityconsumer.NewTraces(\n\t\t\t\tn.Component.(consumer.Traces),\n\t\t\t\taggregateCap(n.Component.(consumer.Traces), nexts),\n\t\t\t),\n\t\t\tconsumedSettings,\n\t\t)\n\t\tn.consumer = refconsumer.NewTraces(n.consumer.(consumer.Traces))\n\tcase pipeline.SignalMetrics:\n\t\tn.Component, err = builder.CreateMetricsToTraces(ctx, set, next)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn.consumer = obsconsumer.NewMetrics(n.Component.(consumer.Metrics), consumedSettings)\n\t\tn.consumer = refconsumer.NewMetrics(n.consumer.(consumer.Metrics))\n\tcase pipeline.SignalLogs:\n\t\tn.Component, err = builder.CreateLogsToTraces(ctx, set, next)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn.consumer = obsconsumer.NewLogs(n.Component.(consumer.Logs), consumedSettings)\n\t\tn.consumer = refconsumer.NewLogs(n.consumer.(consumer.Logs))\n\tcase xpipeline.SignalProfiles:\n\t\tn.Component, err = builder.CreateProfilesToTraces(ctx, set, next)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn.consumer = obsconsumer.NewProfiles(n.Component.(xconsumer.Profiles), consumedSettings)\n\t\tn.consumer = refconsumer.NewProfiles(n.consumer.(xconsumer.Profiles))\n\t}\n\treturn nil\n}\n\nfunc (n *connectorNode) buildMetrics(\n\tctx context.Context,\n\tset connector.Settings,\n\tbuilder *builders.ConnectorBuilder,\n\tnexts []baseConsumer,\n) error {\n\ttb, err := metadata.NewTelemetryBuilder(set.TelemetrySettings)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tproducedSettings := obsconsumer.Settings{\n\t\tItemCounter: tb.ConnectorProducedItems,\n\t\tSizeCounter: tb.ConnectorProducedSize,\n\t\tLogger:      set.Logger,\n\t}\n\tconsumedSettings := obsconsumer.Settings{\n\t\tItemCounter: tb.ConnectorConsumedItems,\n\t\tSizeCounter: tb.ConnectorConsumedSize,\n\t\tLogger:      set.Logger,\n\t}\n\n\tconsumers := make(map[pipeline.ID]consumer.Metrics, len(nexts))\n\tfor _, next := range nexts {\n\t\tconsumers[next.(*capabilitiesNode).pipelineID] = obsconsumer.NewMetrics(\n\t\t\tnext.(consumer.Metrics),\n\t\t\tproducedSettings,\n\t\t\tobsconsumer.WithStaticDataPointAttribute(\n\t\t\t\totelattr.String(\n\t\t\t\t\tpipelineIDAttrKey,\n\t\t\t\t\tnext.(*capabilitiesNode).pipelineID.String(),\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\t}\n\tnext := connector.NewMetricsRouter(consumers)\n\n\tswitch n.exprPipelineType {\n\tcase pipeline.SignalMetrics:\n\t\tn.Component, err = builder.CreateMetricsToMetrics(ctx, set, next)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Connectors which might pass along data must inherit capabilities of all nexts\n\t\tn.consumer = obsconsumer.NewMetrics(\n\t\t\tcapabilityconsumer.NewMetrics(\n\t\t\t\tn.Component.(consumer.Metrics),\n\t\t\t\taggregateCap(n.Component.(consumer.Metrics), nexts),\n\t\t\t),\n\t\t\tconsumedSettings,\n\t\t)\n\t\tn.consumer = refconsumer.NewMetrics(n.consumer.(consumer.Metrics))\n\tcase pipeline.SignalTraces:\n\t\tn.Component, err = builder.CreateTracesToMetrics(ctx, set, next)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn.consumer = obsconsumer.NewTraces(n.Component.(consumer.Traces), consumedSettings)\n\t\tn.consumer = refconsumer.NewTraces(n.consumer.(consumer.Traces))\n\tcase pipeline.SignalLogs:\n\t\tn.Component, err = builder.CreateLogsToMetrics(ctx, set, next)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn.consumer = obsconsumer.NewLogs(n.Component.(consumer.Logs), consumedSettings)\n\t\tn.consumer = refconsumer.NewLogs(n.consumer.(consumer.Logs))\n\tcase xpipeline.SignalProfiles:\n\t\tn.Component, err = builder.CreateProfilesToMetrics(ctx, set, next)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn.consumer = obsconsumer.NewProfiles(n.Component.(xconsumer.Profiles), consumedSettings)\n\t\tn.consumer = refconsumer.NewProfiles(n.consumer.(xconsumer.Profiles))\n\t}\n\treturn nil\n}\n\nfunc (n *connectorNode) buildLogs(\n\tctx context.Context,\n\tset connector.Settings,\n\tbuilder *builders.ConnectorBuilder,\n\tnexts []baseConsumer,\n) error {\n\ttb, err := metadata.NewTelemetryBuilder(set.TelemetrySettings)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tproducedSettings := obsconsumer.Settings{\n\t\tItemCounter: tb.ConnectorProducedItems,\n\t\tSizeCounter: tb.ConnectorProducedSize,\n\t\tLogger:      set.Logger,\n\t}\n\tconsumedSettings := obsconsumer.Settings{\n\t\tItemCounter: tb.ConnectorConsumedItems,\n\t\tSizeCounter: tb.ConnectorConsumedSize,\n\t\tLogger:      set.Logger,\n\t}\n\n\tconsumers := make(map[pipeline.ID]consumer.Logs, len(nexts))\n\tfor _, next := range nexts {\n\t\tconsumers[next.(*capabilitiesNode).pipelineID] = obsconsumer.NewLogs(\n\t\t\tnext.(consumer.Logs),\n\t\t\tproducedSettings,\n\t\t\tobsconsumer.WithStaticDataPointAttribute(\n\t\t\t\totelattr.String(\n\t\t\t\t\tpipelineIDAttrKey,\n\t\t\t\t\tnext.(*capabilitiesNode).pipelineID.String(),\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\t}\n\tnext := connector.NewLogsRouter(consumers)\n\n\tswitch n.exprPipelineType {\n\tcase pipeline.SignalLogs:\n\t\tn.Component, err = builder.CreateLogsToLogs(ctx, set, next)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Connectors which might pass along data must inherit capabilities of all nexts\n\t\tn.consumer = obsconsumer.NewLogs(\n\t\t\tcapabilityconsumer.NewLogs(\n\t\t\t\tn.Component.(consumer.Logs),\n\t\t\t\taggregateCap(n.Component.(consumer.Logs), nexts),\n\t\t\t),\n\t\t\tconsumedSettings,\n\t\t)\n\t\tn.consumer = refconsumer.NewLogs(n.consumer.(consumer.Logs))\n\tcase pipeline.SignalTraces:\n\t\tn.Component, err = builder.CreateTracesToLogs(ctx, set, next)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn.consumer = obsconsumer.NewTraces(n.Component.(consumer.Traces), consumedSettings)\n\t\tn.consumer = refconsumer.NewTraces(n.consumer.(consumer.Traces))\n\tcase pipeline.SignalMetrics:\n\t\tn.Component, err = builder.CreateMetricsToLogs(ctx, set, next)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn.consumer = obsconsumer.NewMetrics(n.Component.(consumer.Metrics), consumedSettings)\n\t\tn.consumer = refconsumer.NewMetrics(n.consumer.(consumer.Metrics))\n\tcase xpipeline.SignalProfiles:\n\t\tn.Component, err = builder.CreateProfilesToLogs(ctx, set, next)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn.consumer = obsconsumer.NewProfiles(n.Component.(xconsumer.Profiles), consumedSettings)\n\t\tn.consumer = refconsumer.NewProfiles(n.consumer.(xconsumer.Profiles))\n\t}\n\treturn nil\n}\n\nfunc (n *connectorNode) buildProfiles(\n\tctx context.Context,\n\tset connector.Settings,\n\tbuilder *builders.ConnectorBuilder,\n\tnexts []baseConsumer,\n) error {\n\ttb, err := metadata.NewTelemetryBuilder(set.TelemetrySettings)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tproducedSettings := obsconsumer.Settings{\n\t\tItemCounter: tb.ConnectorProducedItems,\n\t\tSizeCounter: tb.ConnectorProducedSize,\n\t\tLogger:      set.Logger,\n\t}\n\tconsumedSettings := obsconsumer.Settings{\n\t\tItemCounter: tb.ConnectorConsumedItems,\n\t\tSizeCounter: tb.ConnectorConsumedSize,\n\t\tLogger:      set.Logger,\n\t}\n\n\tconsumers := make(map[pipeline.ID]xconsumer.Profiles, len(nexts))\n\tfor _, next := range nexts {\n\t\tconsumers[next.(*capabilitiesNode).pipelineID] = obsconsumer.NewProfiles(\n\t\t\tnext.(xconsumer.Profiles),\n\t\t\tproducedSettings,\n\t\t\tobsconsumer.WithStaticDataPointAttribute(\n\t\t\t\totelattr.String(\n\t\t\t\t\tpipelineIDAttrKey,\n\t\t\t\t\tnext.(*capabilitiesNode).pipelineID.String(),\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\t}\n\tnext := xconnector.NewProfilesRouter(consumers)\n\n\tswitch n.exprPipelineType {\n\tcase xpipeline.SignalProfiles:\n\t\tn.Component, err = builder.CreateProfilesToProfiles(ctx, set, next)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Connectors which might pass along data must inherit capabilities of all nexts\n\t\tn.consumer = obsconsumer.NewProfiles(\n\t\t\tcapabilityconsumer.NewProfiles(\n\t\t\t\tn.Component.(xconsumer.Profiles),\n\t\t\t\taggregateCap(n.Component.(xconsumer.Profiles), nexts),\n\t\t\t),\n\t\t\tconsumedSettings,\n\t\t)\n\t\tn.consumer = refconsumer.NewProfiles(n.consumer.(xconsumer.Profiles))\n\tcase pipeline.SignalTraces:\n\t\tn.Component, err = builder.CreateTracesToProfiles(ctx, set, next)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn.consumer = obsconsumer.NewTraces(n.Component.(consumer.Traces), consumedSettings)\n\t\tn.consumer = refconsumer.NewTraces(n.consumer.(consumer.Traces))\n\tcase pipeline.SignalMetrics:\n\t\tn.Component, err = builder.CreateMetricsToProfiles(ctx, set, next)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn.consumer = obsconsumer.NewMetrics(n.Component.(consumer.Metrics), consumedSettings)\n\t\tn.consumer = refconsumer.NewMetrics(n.consumer.(consumer.Metrics))\n\tcase pipeline.SignalLogs:\n\t\tn.Component, err = builder.CreateLogsToProfiles(ctx, set, next)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tn.consumer = obsconsumer.NewLogs(n.Component.(consumer.Logs), consumedSettings)\n\t\tn.consumer = refconsumer.NewLogs(n.consumer.(consumer.Logs))\n\t}\n\treturn nil\n}\n\n// When connecting pipelines of the same data type, the connector must\n// inherit the capabilities of pipelines in which it is acting as a receiver.\n// Since the incoming and outgoing data types are the same, we must also consider\n// that the connector itself may mutate the data and pass it along.\nfunc aggregateCap(base baseConsumer, nexts []baseConsumer) consumer.Capabilities {\n\tcapabilities := base.Capabilities()\n\tfor _, next := range nexts {\n\t\tcapabilities.MutatesData = capabilities.MutatesData || next.Capabilities().MutatesData\n\t}\n\treturn capabilities\n}\n"
  },
  {
    "path": "service/internal/graph/consumer.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage graph // import \"go.opentelemetry.io/collector/service/internal/graph\"\n\nimport (\n\t\"go.opentelemetry.io/collector/consumer\"\n)\n\n// baseConsumer redeclared here since not public in consumer package. May consider to make that public.\ntype baseConsumer interface {\n\tCapabilities() consumer.Capabilities\n}\n\ntype consumerNode interface {\n\tgetConsumer() baseConsumer\n}\n"
  },
  {
    "path": "service/internal/graph/exporter.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage graph // import \"go.opentelemetry.io/collector/service/internal/graph\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\t\"go.opentelemetry.io/collector/service/internal/attribute\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n\t\"go.opentelemetry.io/collector/service/internal/componentattribute\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n\t\"go.opentelemetry.io/collector/service/internal/obsconsumer\"\n\t\"go.opentelemetry.io/collector/service/internal/refconsumer\"\n)\n\nvar _ consumerNode = (*exporterNode)(nil)\n\n// An exporter instance can be shared by multiple pipelines of the same type.\n// Therefore, nodeID is derived from \"pipeline type\" and \"component ID\".\ntype exporterNode struct {\n\tattribute.Attributes\n\tcomponentID  component.ID\n\tpipelineType pipeline.Signal\n\tcomponent.Component\n\tconsumer baseConsumer\n}\n\nfunc newExporterNode(pipelineType pipeline.Signal, exprID component.ID) *exporterNode {\n\treturn &exporterNode{\n\t\tAttributes:   attribute.Exporter(pipelineType, exprID),\n\t\tcomponentID:  exprID,\n\t\tpipelineType: pipelineType,\n\t}\n}\n\nfunc (n *exporterNode) getConsumer() baseConsumer {\n\treturn n.consumer\n}\n\nfunc (n *exporterNode) buildComponent(\n\tctx context.Context,\n\ttel component.TelemetrySettings,\n\tinfo component.BuildInfo,\n\tbuilder *builders.ExporterBuilder,\n) error {\n\tset := exporter.Settings{\n\t\tID:                n.componentID,\n\t\tTelemetrySettings: componentattribute.TelemetrySettingsWithAttributes(tel, *n.Set()),\n\t\tBuildInfo:         info,\n\t}\n\n\ttb, err := metadata.NewTelemetryBuilder(set.TelemetrySettings)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tconsumedSettings := obsconsumer.Settings{\n\t\tItemCounter: tb.ExporterConsumedItems,\n\t\tSizeCounter: tb.ExporterConsumedSize,\n\t\tLogger:      set.Logger,\n\t}\n\n\tswitch n.pipelineType {\n\tcase pipeline.SignalTraces:\n\t\tn.Component, err = builder.CreateTraces(ctx, set)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %q exporter for data type %q: %w\", set.ID, n.pipelineType, err)\n\t\t}\n\t\tn.consumer = obsconsumer.NewTraces(n.Component.(consumer.Traces), consumedSettings)\n\t\tn.consumer = refconsumer.NewTraces(n.consumer.(consumer.Traces))\n\tcase pipeline.SignalMetrics:\n\t\tn.Component, err = builder.CreateMetrics(ctx, set)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %q exporter for data type %q: %w\", set.ID, n.pipelineType, err)\n\t\t}\n\t\tn.consumer = obsconsumer.NewMetrics(n.Component.(consumer.Metrics), consumedSettings)\n\t\tn.consumer = refconsumer.NewMetrics(n.consumer.(consumer.Metrics))\n\tcase pipeline.SignalLogs:\n\t\tn.Component, err = builder.CreateLogs(ctx, set)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %q exporter for data type %q: %w\", set.ID, n.pipelineType, err)\n\t\t}\n\t\tn.consumer = obsconsumer.NewLogs(n.Component.(consumer.Logs), consumedSettings)\n\t\tn.consumer = refconsumer.NewLogs(n.consumer.(consumer.Logs))\n\tcase xpipeline.SignalProfiles:\n\t\tn.Component, err = builder.CreateProfiles(ctx, set)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %q exporter for data type %q: %w\", set.ID, n.pipelineType, err)\n\t\t}\n\t\tn.consumer = obsconsumer.NewProfiles(n.Component.(xconsumer.Profiles), consumedSettings)\n\t\tn.consumer = refconsumer.NewProfiles(n.consumer.(xconsumer.Profiles))\n\tdefault:\n\t\treturn fmt.Errorf(\"error creating exporter %q for data type %q is not supported\", set.ID, n.pipelineType)\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "service/internal/graph/fanout.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage graph // import \"go.opentelemetry.io/collector/service/internal/graph\"\n\nimport (\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/service/internal/attribute\"\n)\n\nvar _ consumerNode = (*fanOutNode)(nil)\n\n// Each pipeline has one fan-out node before exporters.\n// Therefore, nodeID is derived from \"pipeline ID\".\ntype fanOutNode struct {\n\tattribute.Attributes\n\tpipelineID pipeline.ID\n\tbaseConsumer\n}\n\nfunc newFanOutNode(pipelineID pipeline.ID) *fanOutNode {\n\treturn &fanOutNode{\n\t\tAttributes: attribute.Fanout(pipelineID),\n\t\tpipelineID: pipelineID,\n\t}\n}\n\nfunc (n *fanOutNode) getConsumer() baseConsumer {\n\treturn n.baseConsumer\n}\n"
  },
  {
    "path": "service/internal/graph/graph.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package graph contains the internal graph representation of the pipelines.\n//\n// [Build] is the constructor for a [Graph] object.  The method calls out to helpers that transform the graph from a config\n// to a DAG of components.  The configuration undergoes additional validation here as well, and is used to instantiate\n// the components of the pipeline.\n//\n// [Graph.StartAll] starts all components in each pipeline.\n//\n// [Graph.ShutdownAll] stops all components in each pipeline.\npackage graph // import \"go.opentelemetry.io/collector/service/internal/graph\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"strings\"\n\n\t\"go.uber.org/multierr\"\n\t\"go.uber.org/zap\"\n\t\"gonum.org/v1/gonum/graph\"\n\t\"gonum.org/v1/gonum/graph/simple\"\n\t\"gonum.org/v1/gonum/graph/topo\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componentstatus\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/xconnector\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/internal/fanoutconsumer\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\t\"go.opentelemetry.io/collector/service/hostcapabilities\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n\t\"go.opentelemetry.io/collector/service/internal/capabilityconsumer\"\n\t\"go.opentelemetry.io/collector/service/internal/status\"\n\t\"go.opentelemetry.io/collector/service/pipelines\"\n)\n\n// Settings holds configuration for building builtPipelines.\ntype Settings struct {\n\tTelemetry component.TelemetrySettings\n\tBuildInfo component.BuildInfo\n\n\tReceiverBuilder  *builders.ReceiverBuilder\n\tProcessorBuilder *builders.ProcessorBuilder\n\tExporterBuilder  *builders.ExporterBuilder\n\tConnectorBuilder *builders.ConnectorBuilder\n\n\t// PipelineConfigs is a map of component.ID to PipelineConfig.\n\tPipelineConfigs pipelines.Config\n\n\tReportStatus status.ServiceStatusFunc\n}\n\ntype Graph struct {\n\t// All component instances represented as nodes, with directed edges indicating data flow.\n\tcomponentGraph *simple.DirectedGraph\n\n\t// Keep track of how nodes relate to pipelines, so we can declare edges in the graph.\n\tpipelines map[pipeline.ID]*pipelineNodes\n\n\t// Keep track of status source per node\n\tinstanceIDs map[int64]*componentstatus.InstanceID\n\n\ttelemetry component.TelemetrySettings\n}\n\n// Build builds a full pipeline graph.\n// Build also validates the configuration of the pipelines and does the actual initialization of each Component in the Graph.\nfunc Build(ctx context.Context, set Settings) (*Graph, error) {\n\tpipelines := &Graph{\n\t\tcomponentGraph: simple.NewDirectedGraph(),\n\t\tpipelines:      make(map[pipeline.ID]*pipelineNodes, len(set.PipelineConfigs)),\n\t\tinstanceIDs:    make(map[int64]*componentstatus.InstanceID),\n\t\ttelemetry:      set.Telemetry,\n\t}\n\tfor pipelineID := range set.PipelineConfigs {\n\t\tpipelines.pipelines[pipelineID] = &pipelineNodes{\n\t\t\treceivers: make(map[int64]graph.Node),\n\t\t\texporters: make(map[int64]graph.Node),\n\t\t}\n\t}\n\tif err := pipelines.createNodes(set); err != nil {\n\t\treturn nil, err\n\t}\n\tpipelines.createEdges()\n\terr := pipelines.buildComponents(ctx, set)\n\treturn pipelines, err\n}\n\n// Creates a node for each instance of a component and adds it to the graph.\n// Validates that connectors are configured to export and receive correctly.\nfunc (g *Graph) createNodes(set Settings) error {\n\t// Build a list of all connectors for easy reference.\n\tconnectors := make(map[component.ID]struct{})\n\n\t// Keep track of connectors and where they are used. (map[connectorID][]pipelineID).\n\tconnectorsAsExporter := make(map[component.ID][]pipeline.ID)\n\tconnectorsAsReceiver := make(map[component.ID][]pipeline.ID)\n\n\t// Build each pipelineNodes struct for each pipeline by parsing the pipelineCfg.\n\t// Also populates the connectors, connectorsAsExporter and connectorsAsReceiver maps.\n\tfor pipelineID, pipelineCfg := range set.PipelineConfigs {\n\t\tpipe := g.pipelines[pipelineID]\n\t\tfor _, recvID := range pipelineCfg.Receivers {\n\t\t\t// Checks if this receiver is a connector or a regular receiver.\n\t\t\tif set.ConnectorBuilder.IsConfigured(recvID) {\n\t\t\t\tconnectors[recvID] = struct{}{}\n\t\t\t\tconnectorsAsReceiver[recvID] = append(connectorsAsReceiver[recvID], pipelineID)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\trcvrNode := g.createReceiver(pipelineID, recvID)\n\t\t\tpipe.receivers[rcvrNode.ID()] = rcvrNode\n\t\t}\n\n\t\tpipe.capabilitiesNode = newCapabilitiesNode(pipelineID)\n\n\t\tfor _, procID := range pipelineCfg.Processors {\n\t\t\tprocNode := g.createProcessor(pipelineID, procID)\n\t\t\tpipe.processors = append(pipe.processors, procNode)\n\t\t}\n\n\t\tpipe.fanOutNode = newFanOutNode(pipelineID)\n\n\t\tfor _, exprID := range pipelineCfg.Exporters {\n\t\t\tif set.ConnectorBuilder.IsConfigured(exprID) {\n\t\t\t\tconnectors[exprID] = struct{}{}\n\t\t\t\tconnectorsAsExporter[exprID] = append(connectorsAsExporter[exprID], pipelineID)\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\texpNode := g.createExporter(pipelineID, exprID)\n\t\t\tpipe.exporters[expNode.ID()] = expNode\n\t\t}\n\t}\n\n\tfor connID := range connectors {\n\t\tfactory := set.ConnectorBuilder.Factory(connID.Type())\n\t\tif factory == nil {\n\t\t\treturn fmt.Errorf(\"connector factory not available for: %q\", connID.Type())\n\t\t}\n\t\tconnFactory := factory.(connector.Factory)\n\n\t\texpTypes := make(map[pipeline.Signal]bool)\n\t\tfor _, pipelineID := range connectorsAsExporter[connID] {\n\t\t\t// The presence of each key indicates how the connector is used as an exporter.\n\t\t\t// The value is initially set to false. Later we will set the value to true *if* we\n\t\t\t// confirm that there is a supported corresponding use as a receiver.\n\t\t\texpTypes[pipelineID.Signal()] = false\n\t\t}\n\t\trecTypes := make(map[pipeline.Signal]bool)\n\t\tfor _, pipelineID := range connectorsAsReceiver[connID] {\n\t\t\t// The presence of each key indicates how the connector is used as a receiver.\n\t\t\t// The value is initially set to false. Later we will set the value to true *if* we\n\t\t\t// confirm that there is a supported corresponding use as an exporter.\n\t\t\trecTypes[pipelineID.Signal()] = false\n\t\t}\n\n\t\tfor expType := range expTypes {\n\t\t\tfor recType := range recTypes {\n\t\t\t\t// Typechecks the connector's receiving and exporting datatypes.\n\t\t\t\tif connectorStability(connFactory, expType, recType) != component.StabilityLevelUndefined {\n\t\t\t\t\texpTypes[expType] = true\n\t\t\t\t\trecTypes[recType] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfor expType, supportedUse := range expTypes {\n\t\t\tif supportedUse {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"connector %q used as exporter in %v pipeline but not used in any supported receiver pipeline\", connID, formatPipelineNamesWithSignal(connectorsAsExporter[connID], expType))\n\t\t}\n\t\tfor recType, supportedUse := range recTypes {\n\t\t\tif supportedUse {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"connector %q used as receiver in %v pipeline but not used in any supported exporter pipeline\", connID, formatPipelineNamesWithSignal(connectorsAsReceiver[connID], recType))\n\t\t}\n\n\t\tfor _, eID := range connectorsAsExporter[connID] {\n\t\t\tfor _, rID := range connectorsAsReceiver[connID] {\n\t\t\t\tif connectorStability(connFactory, eID.Signal(), rID.Signal()) == component.StabilityLevelUndefined {\n\t\t\t\t\t// Connector is not supported for this combination, but we know it is used correctly elsewhere\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tconnNode := g.createConnector(eID, rID, connID)\n\n\t\t\t\tg.pipelines[eID].exporters[connNode.ID()] = connNode\n\t\t\t\tg.pipelines[rID].receivers[connNode.ID()] = connNode\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n// formatPipelineNamesWithSignal formats pipeline name with signal as \"signal[/name]\" format.\nfunc formatPipelineNamesWithSignal(pipelineIDs []pipeline.ID, signal pipeline.Signal) []string {\n\tvar formatted []string\n\tfor _, pid := range pipelineIDs {\n\t\tif pid.Signal() == signal {\n\t\t\tformatted = append(formatted, pid.String())\n\t\t}\n\t}\n\treturn formatted\n}\n\nfunc (g *Graph) createReceiver(pipelineID pipeline.ID, recvID component.ID) *receiverNode {\n\trcvrNode := newReceiverNode(pipelineID.Signal(), recvID)\n\tif node := g.componentGraph.Node(rcvrNode.ID()); node != nil {\n\t\tinstanceID := g.instanceIDs[node.ID()]\n\t\tg.instanceIDs[node.ID()] = instanceID.WithPipelines(pipelineID)\n\t\treturn node.(*receiverNode)\n\t}\n\tg.componentGraph.AddNode(rcvrNode)\n\tg.instanceIDs[rcvrNode.ID()] = componentstatus.NewInstanceID(\n\t\trecvID, component.KindReceiver, pipelineID,\n\t)\n\treturn rcvrNode\n}\n\nfunc (g *Graph) createProcessor(pipelineID pipeline.ID, procID component.ID) *processorNode {\n\tprocNode := newProcessorNode(pipelineID, procID)\n\tg.componentGraph.AddNode(procNode)\n\tg.instanceIDs[procNode.ID()] = componentstatus.NewInstanceID(\n\t\tprocID, component.KindProcessor, pipelineID,\n\t)\n\treturn procNode\n}\n\nfunc (g *Graph) createExporter(pipelineID pipeline.ID, exprID component.ID) *exporterNode {\n\texpNode := newExporterNode(pipelineID.Signal(), exprID)\n\tif node := g.componentGraph.Node(expNode.ID()); node != nil {\n\t\tinstanceID := g.instanceIDs[expNode.ID()]\n\t\tg.instanceIDs[expNode.ID()] = instanceID.WithPipelines(pipelineID)\n\t\treturn node.(*exporterNode)\n\t}\n\tg.componentGraph.AddNode(expNode)\n\tg.instanceIDs[expNode.ID()] = componentstatus.NewInstanceID(\n\t\texpNode.componentID, component.KindExporter, pipelineID,\n\t)\n\treturn expNode\n}\n\nfunc (g *Graph) createConnector(exprPipelineID, rcvrPipelineID pipeline.ID, connID component.ID) *connectorNode {\n\tconnNode := newConnectorNode(exprPipelineID.Signal(), rcvrPipelineID.Signal(), connID)\n\tif node := g.componentGraph.Node(connNode.ID()); node != nil {\n\t\tinstanceID := g.instanceIDs[connNode.ID()]\n\t\tg.instanceIDs[connNode.ID()] = instanceID.WithPipelines(exprPipelineID, rcvrPipelineID)\n\t\treturn node.(*connectorNode)\n\t}\n\tg.componentGraph.AddNode(connNode)\n\tg.instanceIDs[connNode.ID()] = componentstatus.NewInstanceID(\n\t\tconnNode.componentID, component.KindConnector, exprPipelineID, rcvrPipelineID,\n\t)\n\treturn connNode\n}\n\n// Iterates through the pipelines and creates edges between components.\nfunc (g *Graph) createEdges() {\n\tfor _, pg := range g.pipelines {\n\t\t// Draw edges from each receiver to the capability node.\n\t\tfor _, receiver := range pg.receivers {\n\t\t\tg.componentGraph.SetEdge(g.componentGraph.NewEdge(receiver, pg.capabilitiesNode))\n\t\t}\n\n\t\t// Iterates through processors, chaining them together.  starts with the capabilities node.\n\t\tvar from, to graph.Node\n\t\tfrom = pg.capabilitiesNode\n\t\tfor _, processor := range pg.processors {\n\t\t\tto = processor\n\t\t\tg.componentGraph.SetEdge(g.componentGraph.NewEdge(from, to))\n\t\t\tfrom = processor\n\t\t}\n\t\t// Always inserts a fanout node before any exporters. If there is only one\n\t\t// exporter, the fanout node is still created and acts as a noop.\n\t\tto = pg.fanOutNode\n\t\tg.componentGraph.SetEdge(g.componentGraph.NewEdge(from, to))\n\n\t\tfor _, exporter := range pg.exporters {\n\t\t\tg.componentGraph.SetEdge(g.componentGraph.NewEdge(pg.fanOutNode, exporter))\n\t\t}\n\t}\n}\n\n// Uses the already built graph g to instantiate the actual components for each component of each pipeline.\n// Handles calling the factories for each component - and hooking up each component to the next.\n// Also calculates whether each pipeline mutates data so the receiver can know whether it needs to clone the data.\nfunc (g *Graph) buildComponents(ctx context.Context, set Settings) error {\n\tnodes, err := topo.Sort(g.componentGraph)\n\tif err != nil {\n\t\treturn cycleErr(err, topo.DirectedCyclesIn(g.componentGraph))\n\t}\n\n\tfor i := len(nodes) - 1; i >= 0; i-- {\n\t\tnode := nodes[i]\n\n\t\tswitch n := node.(type) {\n\t\tcase *receiverNode:\n\t\t\terr = n.buildComponent(ctx, set.Telemetry, set.BuildInfo, set.ReceiverBuilder, g.nextConsumers(n.ID()))\n\t\tcase *processorNode:\n\t\t\t// nextConsumers is guaranteed to be length 1.  Either it is the next processor or it is the fanout node for the exporters.\n\t\t\terr = n.buildComponent(ctx, set.Telemetry, set.BuildInfo, set.ProcessorBuilder, g.nextConsumers(n.ID())[0])\n\t\tcase *exporterNode:\n\t\t\terr = n.buildComponent(ctx, set.Telemetry, set.BuildInfo, set.ExporterBuilder)\n\t\tcase *connectorNode:\n\t\t\terr = n.buildComponent(ctx, set.Telemetry, set.BuildInfo, set.ConnectorBuilder, g.nextConsumers(n.ID()))\n\t\tcase *capabilitiesNode:\n\t\t\tcapability := consumer.Capabilities{\n\t\t\t\t// The fanOutNode represents the aggregate capabilities of the exporters in the pipeline.\n\t\t\t\tMutatesData: g.pipelines[n.pipelineID].fanOutNode.getConsumer().Capabilities().MutatesData,\n\t\t\t}\n\t\t\tfor _, proc := range g.pipelines[n.pipelineID].processors {\n\t\t\t\tcapability.MutatesData = capability.MutatesData || proc.(*processorNode).getConsumer().Capabilities().MutatesData\n\t\t\t}\n\t\t\tnext := g.nextConsumers(n.ID())[0]\n\t\t\tswitch n.pipelineID.Signal() {\n\t\t\tcase pipeline.SignalTraces:\n\t\t\t\tcc := capabilityconsumer.NewTraces(next.(consumer.Traces), capability)\n\t\t\t\tn.baseConsumer = cc\n\t\t\t\tn.ConsumeTracesFunc = cc.ConsumeTraces\n\t\t\tcase pipeline.SignalMetrics:\n\t\t\t\tcc := capabilityconsumer.NewMetrics(next.(consumer.Metrics), capability)\n\t\t\t\tn.baseConsumer = cc\n\t\t\t\tn.ConsumeMetricsFunc = cc.ConsumeMetrics\n\t\t\tcase pipeline.SignalLogs:\n\t\t\t\tcc := capabilityconsumer.NewLogs(next.(consumer.Logs), capability)\n\t\t\t\tn.baseConsumer = cc\n\t\t\t\tn.ConsumeLogsFunc = cc.ConsumeLogs\n\t\t\tcase xpipeline.SignalProfiles:\n\t\t\t\tcc := capabilityconsumer.NewProfiles(next.(xconsumer.Profiles), capability)\n\t\t\t\tn.baseConsumer = cc\n\t\t\t\tn.ConsumeProfilesFunc = cc.ConsumeProfiles\n\t\t\t}\n\t\tcase *fanOutNode:\n\t\t\tnexts := g.nextConsumers(n.ID())\n\t\t\tswitch n.pipelineID.Signal() {\n\t\t\tcase pipeline.SignalTraces:\n\t\t\t\tconsumers := make([]consumer.Traces, 0, len(nexts))\n\t\t\t\tfor _, next := range nexts {\n\t\t\t\t\tconsumers = append(consumers, next.(consumer.Traces))\n\t\t\t\t}\n\t\t\t\tn.baseConsumer = fanoutconsumer.NewTraces(consumers)\n\t\t\tcase pipeline.SignalMetrics:\n\t\t\t\tconsumers := make([]consumer.Metrics, 0, len(nexts))\n\t\t\t\tfor _, next := range nexts {\n\t\t\t\t\tconsumers = append(consumers, next.(consumer.Metrics))\n\t\t\t\t}\n\t\t\t\tn.baseConsumer = fanoutconsumer.NewMetrics(consumers)\n\t\t\tcase pipeline.SignalLogs:\n\t\t\t\tconsumers := make([]consumer.Logs, 0, len(nexts))\n\t\t\t\tfor _, next := range nexts {\n\t\t\t\t\tconsumers = append(consumers, next.(consumer.Logs))\n\t\t\t\t}\n\t\t\t\tn.baseConsumer = fanoutconsumer.NewLogs(consumers)\n\t\t\tcase xpipeline.SignalProfiles:\n\t\t\t\tconsumers := make([]xconsumer.Profiles, 0, len(nexts))\n\t\t\t\tfor _, next := range nexts {\n\t\t\t\t\tconsumers = append(consumers, next.(xconsumer.Profiles))\n\t\t\t\t}\n\t\t\t\tn.baseConsumer = fanoutconsumer.NewProfiles(consumers)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// Find all nodes\nfunc (g *Graph) nextConsumers(nodeID int64) []baseConsumer {\n\tnextNodes := g.componentGraph.From(nodeID)\n\tnexts := make([]baseConsumer, 0, nextNodes.Len())\n\tfor nextNodes.Next() {\n\t\tnexts = append(nexts, nextNodes.Node().(consumerNode).getConsumer())\n\t}\n\treturn nexts\n}\n\n// A node-based representation of a pipeline configuration.\ntype pipelineNodes struct {\n\t// Use map to assist with deduplication of connector instances.\n\treceivers map[int64]graph.Node\n\n\t// The node to which receivers emit. Passes through to processors.\n\t// Easily accessible as the first node in a pipeline.\n\t*capabilitiesNode\n\n\t// The order of processors is very important. Therefore use a slice for processors.\n\tprocessors []graph.Node\n\n\t// Emits to exporters.\n\t*fanOutNode\n\n\t// Use map to assist with deduplication of connector instances.\n\texporters map[int64]graph.Node\n}\n\nfunc (g *Graph) StartAll(ctx context.Context, host *Host) error {\n\tif host == nil {\n\t\treturn errors.New(\"host cannot be nil\")\n\t}\n\n\tnodes, err := topo.Sort(g.componentGraph)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Start in reverse topological order so that downstream components\n\t// are started before upstream components. This ensures that each\n\t// component's consumer is ready to consume.\n\tfor i := len(nodes) - 1; i >= 0; i-- {\n\t\tnode := nodes[i]\n\t\tcomp, ok := node.(component.Component)\n\n\t\tif !ok {\n\t\t\t// Skip capabilities/fanout nodes\n\t\t\tcontinue\n\t\t}\n\n\t\tinstanceID := g.instanceIDs[node.ID()]\n\t\thost.Reporter.ReportStatus(\n\t\t\tinstanceID,\n\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStarting),\n\t\t)\n\n\t\tif compErr := comp.Start(ctx, &HostWrapper{Host: host, InstanceID: instanceID}); compErr != nil {\n\t\t\thost.Reporter.ReportStatus(\n\t\t\t\tinstanceID,\n\t\t\t\tcomponentstatus.NewPermanentErrorEvent(compErr),\n\t\t\t)\n\t\t\t// We log with zap.AddStacktrace(zap.DPanicLevel) to avoid adding the stack trace to the error log\n\t\t\tg.telemetry.Logger.WithOptions(zap.AddStacktrace(zap.DPanicLevel)).\n\t\t\t\tError(\"Failed to start component\",\n\t\t\t\t\tzap.Error(compErr),\n\t\t\t\t\tzap.String(\"type\", instanceID.Kind().String()),\n\t\t\t\t\tzap.String(\"id\", instanceID.ComponentID().String()),\n\t\t\t\t)\n\t\t\treturn fmt.Errorf(\"failed to start %q %s: %w\", instanceID.ComponentID().String(), strings.ToLower(instanceID.Kind().String()), compErr)\n\t\t}\n\n\t\thost.Reporter.ReportOKIfStarting(instanceID)\n\t}\n\treturn nil\n}\n\nfunc (g *Graph) ShutdownAll(ctx context.Context, reporter status.Reporter) error {\n\tnodes, err := topo.Sort(g.componentGraph)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\t// Stop in topological order so that upstream components\n\t// are stopped before downstream components.  This ensures\n\t// that each component has a chance to drain to its consumer\n\t// before the consumer is stopped.\n\tvar errs error\n\tfor i := range nodes {\n\t\tnode := nodes[i]\n\t\tcomp, ok := node.(component.Component)\n\n\t\tif !ok {\n\t\t\t// Skip capabilities/fanout nodes\n\t\t\tcontinue\n\t\t}\n\n\t\tinstanceID := g.instanceIDs[node.ID()]\n\t\treporter.ReportStatus(\n\t\t\tinstanceID,\n\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopping),\n\t\t)\n\n\t\tif compErr := comp.Shutdown(ctx); compErr != nil {\n\t\t\terrs = multierr.Append(errs, compErr)\n\t\t\treporter.ReportStatus(\n\t\t\t\tinstanceID,\n\t\t\t\tcomponentstatus.NewPermanentErrorEvent(compErr),\n\t\t\t)\n\t\t\tcontinue\n\t\t}\n\n\t\treporter.ReportStatus(\n\t\t\tinstanceID,\n\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopped),\n\t\t)\n\t}\n\treturn errs\n}\n\nfunc (g *Graph) GetExporters() map[pipeline.Signal]map[component.ID]component.Component {\n\texporters := make(map[pipeline.Signal]map[component.ID]component.Component)\n\texporters[pipeline.SignalTraces] = make(map[component.ID]component.Component)\n\texporters[pipeline.SignalMetrics] = make(map[component.ID]component.Component)\n\texporters[pipeline.SignalLogs] = make(map[component.ID]component.Component)\n\texporters[xpipeline.SignalProfiles] = make(map[component.ID]component.Component)\n\n\tfor _, pg := range g.pipelines {\n\t\tfor _, expNode := range pg.exporters {\n\t\t\t// Skip connectors, otherwise individual components can introduce cycles\n\t\t\tif expNode, ok := g.componentGraph.Node(expNode.ID()).(*exporterNode); ok {\n\t\t\t\texporters[expNode.pipelineType][expNode.componentID] = expNode.Component\n\t\t\t}\n\t\t}\n\t}\n\treturn exporters\n}\n\nfunc cycleErr(err error, cycles [][]graph.Node) error {\n\tvar topoErr topo.Unorderable\n\tif !errors.As(err, &topoErr) || len(cycles) == 0 || len(cycles[0]) == 0 {\n\t\treturn err\n\t}\n\n\t// There may be multiple cycles, but report only the first one.\n\tcycle := cycles[0]\n\n\t// The last node is a duplicate of the first node.\n\t// Remove it because we may start from a different node.\n\tcycle = cycle[:len(cycle)-1]\n\n\t// A cycle always contains a connector. For the sake of consistent\n\t// error messages report the cycle starting from a connector.\n\tfor i := 0; i < len(cycle); i++ {\n\t\tif _, ok := cycle[i].(*connectorNode); ok {\n\t\t\tcycle = append(cycle[i:], cycle[:i]...)\n\t\t\tbreak\n\t\t}\n\t}\n\n\t// Repeat the first node at the end to clarify the cycle\n\tcycle = append(cycle, cycle[0])\n\n\t// Build the error message\n\tcomponentDetails := make([]string, 0, len(cycle))\n\tfor _, node := range cycle {\n\t\tswitch n := node.(type) {\n\t\tcase *processorNode:\n\t\t\tcomponentDetails = append(componentDetails, fmt.Sprintf(\"processor %q in pipeline %q\", n.componentID, n.pipelineID.String()))\n\t\tcase *connectorNode:\n\t\t\tcomponentDetails = append(componentDetails, fmt.Sprintf(\"connector %q (%s to %s)\", n.componentID, n.exprPipelineType, n.rcvrPipelineType))\n\t\tdefault:\n\t\t\tcontinue // skip capabilities/fanout nodes\n\t\t}\n\t}\n\treturn fmt.Errorf(\"cycle detected: %s\", strings.Join(componentDetails, \" -> \"))\n}\n\nfunc connectorStability(f connector.Factory, expType, recType pipeline.Signal) component.StabilityLevel {\n\tswitch expType {\n\tcase pipeline.SignalTraces:\n\t\tswitch recType {\n\t\tcase pipeline.SignalTraces:\n\t\t\treturn f.TracesToTracesStability()\n\t\tcase pipeline.SignalMetrics:\n\t\t\treturn f.TracesToMetricsStability()\n\t\tcase pipeline.SignalLogs:\n\t\t\treturn f.TracesToLogsStability()\n\t\tcase xpipeline.SignalProfiles:\n\t\t\tfprof, ok := f.(xconnector.Factory)\n\t\t\tif !ok {\n\t\t\t\treturn component.StabilityLevelUndefined\n\t\t\t}\n\t\t\treturn fprof.TracesToProfilesStability()\n\t\t}\n\tcase pipeline.SignalMetrics:\n\t\tswitch recType {\n\t\tcase pipeline.SignalTraces:\n\t\t\treturn f.MetricsToTracesStability()\n\t\tcase pipeline.SignalMetrics:\n\t\t\treturn f.MetricsToMetricsStability()\n\t\tcase pipeline.SignalLogs:\n\t\t\treturn f.MetricsToLogsStability()\n\t\tcase xpipeline.SignalProfiles:\n\t\t\tfprof, ok := f.(xconnector.Factory)\n\t\t\tif !ok {\n\t\t\t\treturn component.StabilityLevelUndefined\n\t\t\t}\n\t\t\treturn fprof.MetricsToProfilesStability()\n\t\t}\n\tcase pipeline.SignalLogs:\n\t\tswitch recType {\n\t\tcase pipeline.SignalTraces:\n\t\t\treturn f.LogsToTracesStability()\n\t\tcase pipeline.SignalMetrics:\n\t\t\treturn f.LogsToMetricsStability()\n\t\tcase pipeline.SignalLogs:\n\t\t\treturn f.LogsToLogsStability()\n\t\tcase xpipeline.SignalProfiles:\n\t\t\tfprof, ok := f.(xconnector.Factory)\n\t\t\tif !ok {\n\t\t\t\treturn component.StabilityLevelUndefined\n\t\t\t}\n\t\t\treturn fprof.LogsToProfilesStability()\n\t\t}\n\tcase xpipeline.SignalProfiles:\n\t\tfprof, ok := f.(xconnector.Factory)\n\t\tif !ok {\n\t\t\treturn component.StabilityLevelUndefined\n\t\t}\n\t\tswitch recType {\n\t\tcase pipeline.SignalTraces:\n\t\t\treturn fprof.ProfilesToTracesStability()\n\t\tcase pipeline.SignalMetrics:\n\t\t\treturn fprof.ProfilesToMetricsStability()\n\t\tcase pipeline.SignalLogs:\n\t\t\treturn fprof.ProfilesToLogsStability()\n\t\tcase xpipeline.SignalProfiles:\n\t\t\treturn fprof.ProfilesToProfilesStability()\n\t\t}\n\t}\n\treturn component.StabilityLevelUndefined\n}\n\nvar (\n\t_ component.Host                   = (*HostWrapper)(nil)\n\t_ componentstatus.Reporter         = (*HostWrapper)(nil)\n\t_ hostcapabilities.ExposeExporters = (*HostWrapper)(nil) //nolint:staticcheck // SA1019\n)\n\ntype HostWrapper struct {\n\t*Host\n\tInstanceID *componentstatus.InstanceID\n}\n\nfunc (host *HostWrapper) Report(event *componentstatus.Event) {\n\thost.Reporter.ReportStatus(host.InstanceID, event)\n}\n"
  },
  {
    "path": "service/internal/graph/graph_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage graph\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"strings\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componentstatus\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/connectortest\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n\t\"go.opentelemetry.io/collector/service/internal/status\"\n\t\"go.opentelemetry.io/collector/service/internal/testcomponents\"\n\t\"go.opentelemetry.io/collector/service/pipelines\"\n)\n\nfunc TestConnectorPipelinesGraph(t *testing.T) {\n\tt.Run(\"with_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, true)\n\t\ttestConnectorPipelinesGraph(t)\n\t})\n\tt.Run(\"without_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, false)\n\t\ttestConnectorPipelinesGraph(t)\n\t})\n}\n\nfunc testConnectorPipelinesGraph(t *testing.T) {\n\ttests := []struct {\n\t\tname                string\n\t\tpipelineConfigs     pipelines.Config\n\t\texpectedPerExporter int // requires symmetry in Pipelines\n\t}{\n\t\t{\n\t\t\tname: \"pipelines_simple.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(xpipeline.SignalProfiles): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_simple_mutate.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(xpipeline.SignalProfiles): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_simple_multi_proc.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\"), component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\"), component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\"), component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(xpipeline.SignalProfiles): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\"), component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_simple_no_proc.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(xpipeline.SignalProfiles): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_multi.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\"), component.MustNewIDWithName(\"examplereceiver\", \"1\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\"), component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\"), component.MustNewIDWithName(\"exampleexporter\", \"1\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\"), component.MustNewIDWithName(\"examplereceiver\", \"1\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\"), component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\"), component.MustNewIDWithName(\"exampleexporter\", \"1\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\"), component.MustNewIDWithName(\"examplereceiver\", \"1\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\"), component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\"), component.MustNewIDWithName(\"exampleexporter\", \"1\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(xpipeline.SignalProfiles): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\"), component.MustNewIDWithName(\"examplereceiver\", \"1\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\"), component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\"), component.MustNewIDWithName(\"exampleexporter\", \"1\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 2,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_multi_no_proc.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"examplereceiver\"), component.MustNewIDWithName(\"examplereceiver\", \"1\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"exampleexporter\"), component.MustNewIDWithName(\"exampleexporter\", \"1\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"examplereceiver\"), component.MustNewIDWithName(\"examplereceiver\", \"1\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"exampleexporter\"), component.MustNewIDWithName(\"exampleexporter\", \"1\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"examplereceiver\"), component.MustNewIDWithName(\"examplereceiver\", \"1\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"exampleexporter\"), component.MustNewIDWithName(\"exampleexporter\", \"1\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(xpipeline.SignalProfiles): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"examplereceiver\"), component.MustNewIDWithName(\"examplereceiver\", \"1\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"exampleexporter\"), component.MustNewIDWithName(\"exampleexporter\", \"1\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 2,\n\t\t},\n\t\t{\n\t\t\tname: \"multi_pipeline_receivers_and_exporters.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"1\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"1\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"1\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(xpipeline.SignalProfiles): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"1\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 2,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_simple_traces.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")}, // mutate propagates upstream to connector\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_simple_metrics.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")}, // mutate propagates upstream to connector\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_simple_logs.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")}, // mutate propagates upstream to connector\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_simple_profiles.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")}, // mutate propagates upstream to connector\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_fork_merge_traces.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"type0\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"merge\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"type1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")}, // mutate propagates upstream to connector\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"merge\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"merge\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 2,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_fork_merge_metrics.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"type0\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"merge\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"type1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")}, // mutate propagates upstream to connector\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"merge\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"merge\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 2,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_fork_merge_logs.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"type0\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"merge\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"type1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")}, // mutate propagates upstream to connector\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"merge\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"merge\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 2,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_fork_merge_profiles.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"type0\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"merge\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"type1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")}, // mutate propagates upstream to connector\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"merge\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"merge\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 2,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_translate_from_traces.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(xpipeline.SignalProfiles): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_translate_from_metrics.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(xpipeline.SignalProfiles): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_translate_from_logs.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(xpipeline.SignalProfiles): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_translate_from_profiles.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(xpipeline.SignalProfiles): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_matrix_immutable.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"exampleconnector\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 4,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_matrix_mutable.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")}, // mutate propagates upstream to connector\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")}, // mutate propagates upstream to connector\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")}, // mutate propagates upstream to connector\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewIDWithName(\"exampleprocessor\", \"mutate\")}, // mutate propagates upstream to connector\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 4,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_lanes.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"mockforward\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"mockforward\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"mockforward\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"mockforward\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"mockforward\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"mockforward\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"mockforward\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"mockforward\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_mutate_traces.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"out0\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"middle\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"out1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 2,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_mutate_metrics.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"out0\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"middle\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"out1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 2,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_mutate_logs.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"out0\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"middle\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"out1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 2,\n\t\t},\n\t\t{\n\t\t\tname: \"pipelines_conn_mutate_profiles.yaml\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"out0\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"middle\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"mutate\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"out1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"exampleconnector\", \"mutate\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedPerExporter: 2,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\t// Build the pipeline\n\t\t\tset := Settings{\n\t\t\t\tTelemetry: componenttest.NewNopTelemetrySettings(),\n\t\t\t\tBuildInfo: component.NewDefaultBuildInfo(),\n\t\t\t\tReceiverBuilder: builders.NewReceiver(\n\t\t\t\t\tmap[component.ID]component.Config{\n\t\t\t\t\t\tcomponent.MustNewID(\"examplereceiver\"):              testcomponents.ExampleReceiverFactory.CreateDefaultConfig(),\n\t\t\t\t\t\tcomponent.MustNewIDWithName(\"examplereceiver\", \"1\"): testcomponents.ExampleReceiverFactory.CreateDefaultConfig(),\n\t\t\t\t\t},\n\t\t\t\t\tmap[component.Type]receiver.Factory{\n\t\t\t\t\t\ttestcomponents.ExampleReceiverFactory.Type(): testcomponents.ExampleReceiverFactory,\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t\tProcessorBuilder: builders.NewProcessor(\n\t\t\t\t\tmap[component.ID]component.Config{\n\t\t\t\t\t\tcomponent.MustNewID(\"exampleprocessor\"):                   testcomponents.ExampleProcessorFactory.CreateDefaultConfig(),\n\t\t\t\t\t\tcomponent.MustNewIDWithName(\"exampleprocessor\", \"mutate\"): testcomponents.ExampleProcessorFactory.CreateDefaultConfig(),\n\t\t\t\t\t},\n\t\t\t\t\tmap[component.Type]processor.Factory{\n\t\t\t\t\t\ttestcomponents.ExampleProcessorFactory.Type(): testcomponents.ExampleProcessorFactory,\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t\tExporterBuilder: builders.NewExporter(\n\t\t\t\t\tmap[component.ID]component.Config{\n\t\t\t\t\t\tcomponent.MustNewID(\"exampleexporter\"):              testcomponents.ExampleExporterFactory.CreateDefaultConfig(),\n\t\t\t\t\t\tcomponent.MustNewIDWithName(\"exampleexporter\", \"1\"): testcomponents.ExampleExporterFactory.CreateDefaultConfig(),\n\t\t\t\t\t},\n\t\t\t\t\tmap[component.Type]exporter.Factory{\n\t\t\t\t\t\ttestcomponents.ExampleExporterFactory.Type(): testcomponents.ExampleExporterFactory,\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t\tConnectorBuilder: builders.NewConnector(\n\t\t\t\t\tmap[component.ID]component.Config{\n\t\t\t\t\t\tcomponent.MustNewID(\"exampleconnector\"):                           testcomponents.ExampleConnectorFactory.CreateDefaultConfig(),\n\t\t\t\t\t\tcomponent.MustNewIDWithName(\"exampleconnector\", \"merge\"):          testcomponents.ExampleConnectorFactory.CreateDefaultConfig(),\n\t\t\t\t\t\tcomponent.MustNewIDWithName(\"exampleconnector\", \"mutate\"):         testcomponents.ExampleConnectorFactory.CreateDefaultConfig(),\n\t\t\t\t\t\tcomponent.MustNewIDWithName(\"exampleconnector\", \"inherit_mutate\"): testcomponents.ExampleConnectorFactory.CreateDefaultConfig(),\n\t\t\t\t\t\tcomponent.MustNewID(\"mockforward\"):                                testcomponents.MockForwardConnectorFactory.CreateDefaultConfig(),\n\t\t\t\t\t},\n\t\t\t\t\tmap[component.Type]connector.Factory{\n\t\t\t\t\t\ttestcomponents.ExampleConnectorFactory.Type():     testcomponents.ExampleConnectorFactory,\n\t\t\t\t\t\ttestcomponents.MockForwardConnectorFactory.Type(): testcomponents.MockForwardConnectorFactory,\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t\tPipelineConfigs: tt.pipelineConfigs,\n\t\t\t}\n\n\t\t\tpg, err := Build(context.Background(), set)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tassert.Len(t, pg.pipelines, len(tt.pipelineConfigs))\n\n\t\t\trequire.NoError(t, pg.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})}))\n\n\t\t\tmutatingPipelines := make(map[pipeline.ID]bool, len(tt.pipelineConfigs))\n\n\t\t\t// Check each pipeline individually, ensuring that all components are started\n\t\t\t// and that they have observed no signals yet.\n\t\t\tfor pipelineID, pipelineCfg := range tt.pipelineConfigs {\n\t\t\t\tpl, ok := pg.pipelines[pipelineID]\n\t\t\t\trequire.True(t, ok, \"expected to find pipeline: %s\", pipelineID.String())\n\n\t\t\t\t// Determine independently if the capabilities node should report MutateData as true\n\t\t\t\tvar expectMutatesData bool\n\t\t\t\tfor _, expr := range pipelineCfg.Exporters {\n\t\t\t\t\tif strings.Contains(expr.Name(), \"mutate\") {\n\t\t\t\t\t\texpectMutatesData = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tfor _, proc := range pipelineCfg.Processors {\n\t\t\t\t\tif proc.Name() == \"mutate\" {\n\t\t\t\t\t\texpectMutatesData = true\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tassert.Equal(t, expectMutatesData, pl.capabilitiesNode.getConsumer().Capabilities().MutatesData)\n\t\t\t\tmutatingPipelines[pipelineID] = expectMutatesData\n\n\t\t\t\texpectedReceivers, expectedExporters := expectedInstances(tt.pipelineConfigs, pipelineID)\n\t\t\t\trequire.Len(t, pl.receivers, expectedReceivers)\n\t\t\t\trequire.Len(t, pl.processors, len(pipelineCfg.Processors))\n\t\t\t\trequire.Len(t, pl.exporters, expectedExporters)\n\n\t\t\t\tfor _, n := range pl.exporters {\n\t\t\t\t\tswitch c := n.(type) {\n\t\t\t\t\tcase *exporterNode:\n\t\t\t\t\t\te := c.Component.(*testcomponents.ExampleExporter)\n\t\t\t\t\t\trequire.True(t, e.Started())\n\t\t\t\t\t\trequire.Empty(t, e.Traces)\n\t\t\t\t\t\trequire.Empty(t, e.Metrics)\n\t\t\t\t\t\trequire.Empty(t, e.Logs)\n\t\t\t\t\t\trequire.Empty(t, e.Profiles)\n\t\t\t\t\tcase *connectorNode:\n\t\t\t\t\t\trequire.True(t, c.Component.(*testcomponents.ExampleConnector).Started())\n\t\t\t\t\tdefault:\n\t\t\t\t\t\trequire.Fail(t, fmt.Sprintf(\"unexpected type %T\", c))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor _, n := range pl.processors {\n\t\t\t\t\trequire.True(t, n.(*processorNode).Component.(*testcomponents.ExampleProcessor).Started())\n\t\t\t\t}\n\n\t\t\t\tfor _, n := range pl.receivers {\n\t\t\t\t\tswitch c := n.(type) {\n\t\t\t\t\tcase *receiverNode:\n\t\t\t\t\t\trequire.True(t, c.Component.(*testcomponents.ExampleReceiver).Started())\n\t\t\t\t\tcase *connectorNode:\n\t\t\t\t\t\trequire.True(t, c.Component.(*testcomponents.ExampleConnector).Started())\n\t\t\t\t\tdefault:\n\t\t\t\t\t\trequire.Fail(t, fmt.Sprintf(\"unexpected type %T\", c))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Check that Connectors are correctly inheriting mutability from downstream Pipelines\n\t\t\tfor expPipelineID, expPipeline := range pg.pipelines {\n\t\t\t\tfor _, exp := range expPipeline.exporters {\n\t\t\t\t\texpConn, ok := exp.(*connectorNode)\n\t\t\t\t\tif !ok {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\tif expConn.getConsumer().Capabilities().MutatesData {\n\t\t\t\t\t\tcontinue\n\t\t\t\t\t}\n\t\t\t\t\t// find all the Pipelines of the same type where this connector is a receiver\n\t\t\t\t\tvar inheritMutatesData bool\n\t\t\t\t\tfor recPipelineID, recPipeline := range pg.pipelines {\n\t\t\t\t\t\tif recPipelineID == expPipelineID || recPipelineID.Signal() != expPipelineID.Signal() {\n\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t}\n\t\t\t\t\t\tfor _, rec := range recPipeline.receivers {\n\t\t\t\t\t\t\trecConn, ok := rec.(*connectorNode)\n\t\t\t\t\t\t\tif !ok || recConn.ID() != expConn.ID() {\n\t\t\t\t\t\t\t\tcontinue\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tinheritMutatesData = inheritMutatesData || mutatingPipelines[recPipelineID]\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\tassert.Equal(t, inheritMutatesData, expConn.getConsumer().Capabilities().MutatesData)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Push data into the Pipelines. The list of Receivers is retrieved directly from the overall\n\t\t\t// component graph because we do not want to duplicate signal inputs to Receivers that are\n\t\t\t// shared between Pipelines. The `allReceivers` function also excludes Connectors, which we do\n\t\t\t// not want to directly inject with signals.\n\t\t\tallReceivers := pg.getReceivers()\n\t\t\tfor _, c := range allReceivers[pipeline.SignalTraces] {\n\t\t\t\ttracesReceiver := c.(*testcomponents.ExampleReceiver)\n\t\t\t\trequire.NoError(t, tracesReceiver.ConsumeTraces(context.Background(), testdata.GenerateTraces(1)))\n\t\t\t}\n\t\t\tfor _, c := range allReceivers[pipeline.SignalMetrics] {\n\t\t\t\tmetricsReceiver := c.(*testcomponents.ExampleReceiver)\n\t\t\t\trequire.NoError(t, metricsReceiver.ConsumeMetrics(context.Background(), testdata.GenerateMetrics(1)))\n\t\t\t}\n\t\t\tfor _, c := range allReceivers[pipeline.SignalLogs] {\n\t\t\t\tlogsReceiver := c.(*testcomponents.ExampleReceiver)\n\t\t\t\trequire.NoError(t, logsReceiver.ConsumeLogs(context.Background(), testdata.GenerateLogs(1)))\n\t\t\t}\n\t\t\tfor _, c := range allReceivers[xpipeline.SignalProfiles] {\n\t\t\t\tprofilesReceiver := c.(*testcomponents.ExampleReceiver)\n\t\t\t\trequire.NoError(t, profilesReceiver.ConsumeProfiles(context.Background(), testdata.GenerateProfiles(1)))\n\t\t\t}\n\n\t\t\t// Shut down the entire component graph\n\t\t\trequire.NoError(t, pg.ShutdownAll(context.Background(), status.NewNopStatusReporter()))\n\n\t\t\t// Check each pipeline individually, ensuring that all components are stopped.\n\t\t\tfor pipelineID := range tt.pipelineConfigs {\n\t\t\t\tpl, ok := pg.pipelines[pipelineID]\n\t\t\t\trequire.True(t, ok, \"expected to find pipeline: %s\", pipelineID.String())\n\n\t\t\t\tfor _, n := range pl.receivers {\n\t\t\t\t\tswitch c := n.(type) {\n\t\t\t\t\tcase *receiverNode:\n\t\t\t\t\t\trequire.True(t, c.Component.(*testcomponents.ExampleReceiver).Stopped())\n\t\t\t\t\tcase *connectorNode:\n\t\t\t\t\t\trequire.True(t, c.Component.(*testcomponents.ExampleConnector).Stopped())\n\t\t\t\t\tdefault:\n\t\t\t\t\t\trequire.Fail(t, fmt.Sprintf(\"unexpected type %T\", c))\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tfor _, n := range pl.processors {\n\t\t\t\t\trequire.True(t, n.(*processorNode).Component.(*testcomponents.ExampleProcessor).Stopped())\n\t\t\t\t}\n\n\t\t\t\tfor _, n := range pl.exporters {\n\t\t\t\t\tswitch c := n.(type) {\n\t\t\t\t\tcase *exporterNode:\n\t\t\t\t\t\trequire.True(t, c.Component.(*testcomponents.ExampleExporter).Stopped())\n\t\t\t\t\tcase *connectorNode:\n\t\t\t\t\t\trequire.True(t, c.Component.(*testcomponents.ExampleConnector).Stopped())\n\t\t\t\t\tdefault:\n\t\t\t\t\t\trequire.Fail(t, fmt.Sprintf(\"unexpected type %T\", c))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Get the list of Exporters directly from the overall component graph. Like Receivers,\n\t\t\t// exclude Connectors and validate each exporter once regardless of sharing between Pipelines.\n\t\t\tallExporters := pg.GetExporters()\n\t\t\tfor _, e := range allExporters[pipeline.SignalTraces] {\n\t\t\t\ttracesExporter := e.(consumer.Traces).(*testcomponents.ExampleExporter)\n\t\t\t\tassert.Len(t, tracesExporter.Traces, tt.expectedPerExporter)\n\t\t\t\texpected := testdata.GenerateTraces(1)\n\t\t\t\tfor i := 0; i < tt.expectedPerExporter; i++ {\n\t\t\t\t\tassert.True(t, pref.EqualTraces(expected, tracesExporter.Traces[i]))\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, e := range allExporters[pipeline.SignalMetrics] {\n\t\t\t\tmetricsExporter := e.(consumer.Metrics).(*testcomponents.ExampleExporter)\n\t\t\t\tassert.Len(t, metricsExporter.Metrics, tt.expectedPerExporter)\n\t\t\t\texpected := testdata.GenerateMetrics(1)\n\t\t\t\tfor i := 0; i < tt.expectedPerExporter; i++ {\n\t\t\t\t\tassert.True(t, pref.EqualMetrics(expected, metricsExporter.Metrics[i]))\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, e := range allExporters[pipeline.SignalLogs] {\n\t\t\t\tlogsExporter := e.(consumer.Logs).(*testcomponents.ExampleExporter)\n\t\t\t\tassert.Len(t, logsExporter.Logs, tt.expectedPerExporter)\n\t\t\t\texpected := testdata.GenerateLogs(1)\n\t\t\t\tfor i := 0; i < tt.expectedPerExporter; i++ {\n\t\t\t\t\tassert.True(t, pref.EqualLogs(expected, logsExporter.Logs[i]))\n\t\t\t\t}\n\t\t\t}\n\t\t\tfor _, e := range allExporters[xpipeline.SignalProfiles] {\n\t\t\t\tprofilesExporter := e.(xconsumer.Profiles).(*testcomponents.ExampleExporter)\n\t\t\t\tassert.Len(t, profilesExporter.Profiles, tt.expectedPerExporter)\n\t\t\t\texpected := testdata.GenerateProfiles(1)\n\t\t\t\tfor i := 0; i < tt.expectedPerExporter; i++ {\n\t\t\t\t\tassert.True(t, pref.EqualProfiles(expected, profilesExporter.Profiles[i]))\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestInstances(t *testing.T) {\n\tt.Run(\"with_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, true)\n\t\ttestInstances(t)\n\t})\n\tt.Run(\"without_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, false)\n\t\ttestInstances(t)\n\t})\n}\n\nfunc testInstances(t *testing.T) {\n\ttests := []struct {\n\t\tname            string\n\t\tpipelineConfigs pipelines.Config\n\t\texpectInstances map[component.ID]int\n\t}{\n\t\t{\n\t\t\tname: \"one_pipeline_each_signal\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewID(xpipeline.SignalProfiles): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectInstances: map[component.ID]int{\n\t\t\t\tcomponent.MustNewID(\"examplereceiver\"):  4, // one per signal\n\t\t\t\tcomponent.MustNewID(\"exampleprocessor\"): 4, // one per pipeline\n\t\t\t\tcomponent.MustNewID(\"exampleexporter\"):  4, // one per signal\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"shared_by_signals\",\n\t\t\tpipelineConfigs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"2\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"2\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"2\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"2\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"examplereceiver\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"exampleprocessor\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"exampleexporter\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectInstances: map[component.ID]int{\n\t\t\t\tcomponent.MustNewID(\"examplereceiver\"):  4, // one per signal\n\t\t\t\tcomponent.MustNewID(\"exampleprocessor\"): 8, // one per pipeline\n\t\t\t\tcomponent.MustNewID(\"exampleexporter\"):  4, // one per signal\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tset := Settings{\n\t\t\t\tTelemetry: componenttest.NewNopTelemetrySettings(),\n\t\t\t\tBuildInfo: component.NewDefaultBuildInfo(),\n\t\t\t\tReceiverBuilder: builders.NewReceiver(\n\t\t\t\t\tmap[component.ID]component.Config{\n\t\t\t\t\t\tcomponent.MustNewID(\"examplereceiver\"): testcomponents.ExampleReceiverFactory.CreateDefaultConfig(),\n\t\t\t\t\t},\n\t\t\t\t\tmap[component.Type]receiver.Factory{\n\t\t\t\t\t\ttestcomponents.ExampleReceiverFactory.Type(): testcomponents.ExampleReceiverFactory,\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t\tProcessorBuilder: builders.NewProcessor(\n\t\t\t\t\tmap[component.ID]component.Config{\n\t\t\t\t\t\tcomponent.MustNewID(\"exampleprocessor\"): testcomponents.ExampleProcessorFactory.CreateDefaultConfig(),\n\t\t\t\t\t},\n\t\t\t\t\tmap[component.Type]processor.Factory{\n\t\t\t\t\t\ttestcomponents.ExampleProcessorFactory.Type(): testcomponents.ExampleProcessorFactory,\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t\tExporterBuilder: builders.NewExporter(\n\t\t\t\t\tmap[component.ID]component.Config{\n\t\t\t\t\t\tcomponent.MustNewID(\"exampleexporter\"): testcomponents.ExampleExporterFactory.CreateDefaultConfig(),\n\t\t\t\t\t},\n\t\t\t\t\tmap[component.Type]exporter.Factory{\n\t\t\t\t\t\ttestcomponents.ExampleExporterFactory.Type(): testcomponents.ExampleExporterFactory,\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t\tConnectorBuilder: builders.NewConnector(map[component.ID]component.Config{}, map[component.Type]connector.Factory{}),\n\t\t\t\tPipelineConfigs:  tt.pipelineConfigs,\n\t\t\t}\n\n\t\t\tpg, err := Build(context.Background(), set)\n\t\t\trequire.NoError(t, err)\n\n\t\t\trequire.Len(t, pg.pipelines, len(set.PipelineConfigs))\n\n\t\t\t// For each component id, build a map of the instances of that component.\n\t\t\t// Use graph.Node.ID() as the key to determine uniqueness of instances.\n\t\t\tcomponentInstances := map[component.ID]map[int64]struct{}{}\n\t\t\tfor _, pipeline := range pg.pipelines {\n\t\t\t\tfor _, n := range pipeline.receivers {\n\t\t\t\t\tr := n.(*receiverNode)\n\t\t\t\t\tif _, ok := componentInstances[r.componentID]; !ok {\n\t\t\t\t\t\tcomponentInstances[r.componentID] = map[int64]struct{}{}\n\t\t\t\t\t}\n\t\t\t\t\tcomponentInstances[r.componentID][n.ID()] = struct{}{}\n\t\t\t\t}\n\t\t\t\tfor _, n := range pipeline.processors {\n\t\t\t\t\tp := n.(*processorNode)\n\t\t\t\t\tif _, ok := componentInstances[p.componentID]; !ok {\n\t\t\t\t\t\tcomponentInstances[p.componentID] = map[int64]struct{}{}\n\t\t\t\t\t}\n\t\t\t\t\tcomponentInstances[p.componentID][n.ID()] = struct{}{}\n\t\t\t\t}\n\t\t\t\tfor _, n := range pipeline.exporters {\n\t\t\t\t\te := n.(*exporterNode)\n\t\t\t\t\tif _, ok := componentInstances[e.componentID]; !ok {\n\t\t\t\t\t\tcomponentInstances[e.componentID] = map[int64]struct{}{}\n\t\t\t\t\t}\n\t\t\t\t\tcomponentInstances[e.componentID][n.ID()] = struct{}{}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tvar totalExpected int\n\t\t\tfor id, instances := range componentInstances {\n\t\t\t\ttotalExpected += tt.expectInstances[id]\n\t\t\t\trequire.Len(t, instances, tt.expectInstances[id], id.String())\n\t\t\t}\n\t\t\ttotalExpected += len(tt.pipelineConfigs) * 2 // one fanout & one capabilities node per pipeline\n\t\t\trequire.Equal(t, totalExpected, pg.componentGraph.Nodes().Len())\n\t\t})\n\t}\n}\n\nfunc TestConnectorRouter(t *testing.T) {\n\tt.Run(\"with_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, true)\n\t\ttestConnectorRouter(t)\n\t})\n\tt.Run(\"without_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, false)\n\t\ttestConnectorRouter(t)\n\t})\n}\n\nfunc testConnectorRouter(t *testing.T) {\n\trcvrID := component.MustNewID(\"examplereceiver\")\n\trouteTracesID := component.MustNewIDWithName(\"examplerouter\", \"traces\")\n\trouteMetricsID := component.MustNewIDWithName(\"examplerouter\", \"metrics\")\n\trouteLogsID := component.MustNewIDWithName(\"examplerouter\", \"logs\")\n\trouteProfilesID := component.MustNewIDWithName(\"examplerouter\", \"profiles\")\n\texpRightID := component.MustNewIDWithName(\"exampleexporter\", \"right\")\n\texpLeftID := component.MustNewIDWithName(\"exampleexporter\", \"left\")\n\n\ttracesInID := pipeline.NewIDWithName(pipeline.SignalTraces, \"in\")\n\ttracesRightID := pipeline.NewIDWithName(pipeline.SignalTraces, \"right\")\n\ttracesLeftID := pipeline.NewIDWithName(pipeline.SignalTraces, \"left\")\n\n\tmetricsInID := pipeline.NewIDWithName(pipeline.SignalMetrics, \"in\")\n\tmetricsRightID := pipeline.NewIDWithName(pipeline.SignalMetrics, \"right\")\n\tmetricsLeftID := pipeline.NewIDWithName(pipeline.SignalMetrics, \"left\")\n\n\tlogsInID := pipeline.NewIDWithName(pipeline.SignalLogs, \"in\")\n\tlogsRightID := pipeline.NewIDWithName(pipeline.SignalLogs, \"right\")\n\tlogsLeftID := pipeline.NewIDWithName(pipeline.SignalLogs, \"left\")\n\n\tprofilesInID := pipeline.NewIDWithName(xpipeline.SignalProfiles, \"in\")\n\tprofilesRightID := pipeline.NewIDWithName(xpipeline.SignalProfiles, \"right\")\n\tprofilesLeftID := pipeline.NewIDWithName(xpipeline.SignalProfiles, \"left\")\n\n\tctx := context.Background()\n\tset := Settings{\n\t\tTelemetry: componenttest.NewNopTelemetrySettings(),\n\t\tBuildInfo: component.NewDefaultBuildInfo(),\n\t\tReceiverBuilder: builders.NewReceiver(\n\t\t\tmap[component.ID]component.Config{\n\t\t\t\trcvrID: testcomponents.ExampleReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tmap[component.Type]receiver.Factory{\n\t\t\t\ttestcomponents.ExampleReceiverFactory.Type(): testcomponents.ExampleReceiverFactory,\n\t\t\t},\n\t\t),\n\t\tExporterBuilder: builders.NewExporter(\n\t\t\tmap[component.ID]component.Config{\n\t\t\t\texpRightID: testcomponents.ExampleExporterFactory.CreateDefaultConfig(),\n\t\t\t\texpLeftID:  testcomponents.ExampleExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tmap[component.Type]exporter.Factory{\n\t\t\t\ttestcomponents.ExampleExporterFactory.Type(): testcomponents.ExampleExporterFactory,\n\t\t\t},\n\t\t),\n\t\tConnectorBuilder: builders.NewConnector(\n\t\t\tmap[component.ID]component.Config{\n\t\t\t\trouteTracesID: testcomponents.ExampleRouterConfig{\n\t\t\t\t\tTraces: &testcomponents.LeftRightConfig{\n\t\t\t\t\t\tRight: tracesRightID,\n\t\t\t\t\t\tLeft:  tracesLeftID,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\trouteMetricsID: testcomponents.ExampleRouterConfig{\n\t\t\t\t\tMetrics: &testcomponents.LeftRightConfig{\n\t\t\t\t\t\tRight: metricsRightID,\n\t\t\t\t\t\tLeft:  metricsLeftID,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\trouteLogsID: testcomponents.ExampleRouterConfig{\n\t\t\t\t\tLogs: &testcomponents.LeftRightConfig{\n\t\t\t\t\t\tRight: logsRightID,\n\t\t\t\t\t\tLeft:  logsLeftID,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\trouteProfilesID: testcomponents.ExampleRouterConfig{\n\t\t\t\t\tProfiles: &testcomponents.LeftRightConfig{\n\t\t\t\t\t\tRight: profilesRightID,\n\t\t\t\t\t\tLeft:  profilesLeftID,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tmap[component.Type]connector.Factory{\n\t\t\t\ttestcomponents.ExampleRouterFactory.Type(): testcomponents.ExampleRouterFactory,\n\t\t\t},\n\t\t),\n\t\tPipelineConfigs: pipelines.Config{\n\t\t\ttracesInID: {\n\t\t\t\tReceivers: []component.ID{rcvrID},\n\t\t\t\tExporters: []component.ID{routeTracesID},\n\t\t\t},\n\t\t\ttracesRightID: {\n\t\t\t\tReceivers: []component.ID{routeTracesID},\n\t\t\t\tExporters: []component.ID{expRightID},\n\t\t\t},\n\t\t\ttracesLeftID: {\n\t\t\t\tReceivers: []component.ID{routeTracesID},\n\t\t\t\tExporters: []component.ID{expLeftID},\n\t\t\t},\n\t\t\tmetricsInID: {\n\t\t\t\tReceivers: []component.ID{rcvrID},\n\t\t\t\tExporters: []component.ID{routeMetricsID},\n\t\t\t},\n\t\t\tmetricsRightID: {\n\t\t\t\tReceivers: []component.ID{routeMetricsID},\n\t\t\t\tExporters: []component.ID{expRightID},\n\t\t\t},\n\t\t\tmetricsLeftID: {\n\t\t\t\tReceivers: []component.ID{routeMetricsID},\n\t\t\t\tExporters: []component.ID{expLeftID},\n\t\t\t},\n\t\t\tlogsInID: {\n\t\t\t\tReceivers: []component.ID{rcvrID},\n\t\t\t\tExporters: []component.ID{routeLogsID},\n\t\t\t},\n\t\t\tlogsRightID: {\n\t\t\t\tReceivers: []component.ID{routeLogsID},\n\t\t\t\tExporters: []component.ID{expRightID},\n\t\t\t},\n\t\t\tlogsLeftID: {\n\t\t\t\tReceivers: []component.ID{routeLogsID},\n\t\t\t\tExporters: []component.ID{expLeftID},\n\t\t\t},\n\t\t\tprofilesInID: {\n\t\t\t\tReceivers: []component.ID{rcvrID},\n\t\t\t\tExporters: []component.ID{routeProfilesID},\n\t\t\t},\n\t\t\tprofilesRightID: {\n\t\t\t\tReceivers: []component.ID{routeProfilesID},\n\t\t\t\tExporters: []component.ID{expRightID},\n\t\t\t},\n\t\t\tprofilesLeftID: {\n\t\t\t\tReceivers: []component.ID{routeProfilesID},\n\t\t\t\tExporters: []component.ID{expLeftID},\n\t\t\t},\n\t\t},\n\t}\n\n\tpg, err := Build(ctx, set)\n\trequire.NoError(t, err)\n\n\tallReceivers := pg.getReceivers()\n\tallExporters := pg.GetExporters()\n\n\tassert.Len(t, pg.pipelines, len(set.PipelineConfigs))\n\n\t// Get a handle for the traces receiver and both Exporters\n\ttracesReceiver := allReceivers[pipeline.SignalTraces][rcvrID].(*testcomponents.ExampleReceiver)\n\ttracesRight := allExporters[pipeline.SignalTraces][expRightID].(*testcomponents.ExampleExporter)\n\ttracesLeft := allExporters[pipeline.SignalTraces][expLeftID].(*testcomponents.ExampleExporter)\n\n\t// Consume 1, validate it went right\n\trequire.NoError(t, tracesReceiver.ConsumeTraces(ctx, testdata.GenerateTraces(1)))\n\tassert.Len(t, tracesRight.Traces, 1)\n\tassert.Empty(t, tracesLeft.Traces)\n\n\t// Consume 1, validate it went left\n\trequire.NoError(t, tracesReceiver.ConsumeTraces(ctx, testdata.GenerateTraces(1)))\n\tassert.Len(t, tracesRight.Traces, 1)\n\tassert.Len(t, tracesLeft.Traces, 1)\n\n\t// Consume 3, validate 2 went right, 1 went left\n\tassert.NoError(t, tracesReceiver.ConsumeTraces(ctx, testdata.GenerateTraces(1)))\n\tassert.NoError(t, tracesReceiver.ConsumeTraces(ctx, testdata.GenerateTraces(1)))\n\tassert.NoError(t, tracesReceiver.ConsumeTraces(ctx, testdata.GenerateTraces(1)))\n\tassert.Len(t, tracesRight.Traces, 3)\n\tassert.Len(t, tracesLeft.Traces, 2)\n\n\t// Get a handle for the metrics receiver and both Exporters\n\tmetricsReceiver := allReceivers[pipeline.SignalMetrics][rcvrID].(*testcomponents.ExampleReceiver)\n\tmetricsRight := allExporters[pipeline.SignalMetrics][expRightID].(*testcomponents.ExampleExporter)\n\tmetricsLeft := allExporters[pipeline.SignalMetrics][expLeftID].(*testcomponents.ExampleExporter)\n\n\t// Consume 1, validate it went right\n\trequire.NoError(t, metricsReceiver.ConsumeMetrics(ctx, testdata.GenerateMetrics(1)))\n\tassert.Len(t, metricsRight.Metrics, 1)\n\tassert.Empty(t, metricsLeft.Metrics)\n\n\t// Consume 1, validate it went left\n\trequire.NoError(t, metricsReceiver.ConsumeMetrics(ctx, testdata.GenerateMetrics(1)))\n\tassert.Len(t, metricsRight.Metrics, 1)\n\tassert.Len(t, metricsLeft.Metrics, 1)\n\n\t// Consume 3, validate 2 went right, 1 went left\n\tassert.NoError(t, metricsReceiver.ConsumeMetrics(ctx, testdata.GenerateMetrics(1)))\n\tassert.NoError(t, metricsReceiver.ConsumeMetrics(ctx, testdata.GenerateMetrics(1)))\n\tassert.NoError(t, metricsReceiver.ConsumeMetrics(ctx, testdata.GenerateMetrics(1)))\n\tassert.Len(t, metricsRight.Metrics, 3)\n\tassert.Len(t, metricsLeft.Metrics, 2)\n\n\t// Get a handle for the logs receiver and both Exporters\n\tlogsReceiver := allReceivers[pipeline.SignalLogs][rcvrID].(*testcomponents.ExampleReceiver)\n\tlogsRight := allExporters[pipeline.SignalLogs][expRightID].(*testcomponents.ExampleExporter)\n\tlogsLeft := allExporters[pipeline.SignalLogs][expLeftID].(*testcomponents.ExampleExporter)\n\n\t// Consume 1, validate it went right\n\trequire.NoError(t, logsReceiver.ConsumeLogs(ctx, testdata.GenerateLogs(1)))\n\tassert.Len(t, logsRight.Logs, 1)\n\tassert.Empty(t, logsLeft.Logs)\n\n\t// Consume 1, validate it went left\n\trequire.NoError(t, logsReceiver.ConsumeLogs(ctx, testdata.GenerateLogs(1)))\n\tassert.Len(t, logsRight.Logs, 1)\n\tassert.Len(t, logsLeft.Logs, 1)\n\n\t// Consume 3, validate 2 went right, 1 went left\n\tassert.NoError(t, logsReceiver.ConsumeLogs(ctx, testdata.GenerateLogs(1)))\n\tassert.NoError(t, logsReceiver.ConsumeLogs(ctx, testdata.GenerateLogs(1)))\n\tassert.NoError(t, logsReceiver.ConsumeLogs(ctx, testdata.GenerateLogs(1)))\n\tassert.Len(t, logsRight.Logs, 3)\n\tassert.Len(t, logsLeft.Logs, 2)\n\n\t// Get a handle for the profiles receiver and both Exporters\n\tprofilesReceiver := allReceivers[xpipeline.SignalProfiles][rcvrID].(*testcomponents.ExampleReceiver)\n\tprofilesRight := allExporters[xpipeline.SignalProfiles][expRightID].(*testcomponents.ExampleExporter)\n\tprofilesLeft := allExporters[xpipeline.SignalProfiles][expLeftID].(*testcomponents.ExampleExporter)\n\n\t// Consume 1, validate it went right\n\trequire.NoError(t, profilesReceiver.ConsumeProfiles(ctx, testdata.GenerateProfiles(1)))\n\tassert.Len(t, profilesRight.Profiles, 1)\n\tassert.Empty(t, profilesLeft.Profiles)\n\n\t// Consume 1, validate it went left\n\trequire.NoError(t, profilesReceiver.ConsumeProfiles(ctx, testdata.GenerateProfiles(1)))\n\tassert.Len(t, profilesRight.Profiles, 1)\n\tassert.Len(t, profilesLeft.Profiles, 1)\n\n\t// Consume 3, validate 2 went right, 1 went left\n\tassert.NoError(t, profilesReceiver.ConsumeProfiles(ctx, testdata.GenerateProfiles(1)))\n\tassert.NoError(t, profilesReceiver.ConsumeProfiles(ctx, testdata.GenerateProfiles(1)))\n\tassert.NoError(t, profilesReceiver.ConsumeProfiles(ctx, testdata.GenerateProfiles(1)))\n\tassert.Len(t, profilesRight.Profiles, 3)\n\tassert.Len(t, profilesLeft.Profiles, 2)\n}\n\nfunc TestGraphBuildErrors(t *testing.T) {\n\tt.Run(\"with_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, true)\n\t\ttestGraphBuildErrors(t)\n\t})\n\tt.Run(\"without_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, false)\n\t\ttestGraphBuildErrors(t)\n\t})\n}\n\nfunc testGraphBuildErrors(t *testing.T) {\n\tnopReceiverFactory := receivertest.NewNopFactory()\n\tnopProcessorFactory := processortest.NewNopFactory()\n\tnopExporterFactory := exportertest.NewNopFactory()\n\tnopConnectorFactory := connectortest.NewNopFactory()\n\tmfConnectorFactory := testcomponents.MockForwardConnectorFactory\n\tbadReceiverFactory := newBadReceiverFactory()\n\tbadProcessorFactory := newBadProcessorFactory()\n\tbadExporterFactory := newBadExporterFactory()\n\tbadConnectorFactory := newBadConnectorFactory()\n\n\ttests := []struct {\n\t\tname          string\n\t\treceiverCfgs  map[component.ID]component.Config\n\t\tprocessorCfgs map[component.ID]component.Config\n\t\texporterCfgs  map[component.ID]component.Config\n\t\tconnectorCfgs map[component.ID]component.Config\n\t\tpipelineCfgs  pipelines.Config\n\t\texpected      string\n\t}{\n\t\t{\n\t\t\tname: \"not_supported_exporter_logs\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): badExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"bf\\\" exporter for data type \\\"logs\\\": telemetry type is not supported\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_exporter_metrics\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): badExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"bf\\\" exporter for data type \\\"metrics\\\": telemetry type is not supported\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_exporter_traces\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): badExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"bf\\\" exporter for data type \\\"traces\\\": telemetry type is not supported\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_exporter_profiles\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): badExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(xpipeline.SignalProfiles): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"bf\\\" exporter for data type \\\"profiles\\\": telemetry type is not supported\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_processor_logs\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tprocessorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): badProcessorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"bf\\\" processor, in pipeline \\\"logs\\\": telemetry type is not supported\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_processor_metrics\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tprocessorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): badProcessorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"bf\\\" processor, in pipeline \\\"metrics\\\": telemetry type is not supported\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_processor_traces\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tprocessorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): badProcessorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"bf\\\" processor, in pipeline \\\"traces\\\": telemetry type is not supported\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_processor_profiles\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tprocessorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): badProcessorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(xpipeline.SignalProfiles): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"bf\\\" processor, in pipeline \\\"profiles\\\": telemetry type is not supported\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_receiver_logs\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): badReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"bf\\\" receiver for data type \\\"logs\\\": telemetry type is not supported\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_receiver_metrics\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): badReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"bf\\\" receiver for data type \\\"metrics\\\": telemetry type is not supported\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_receiver_traces\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): badReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"bf\\\" receiver for data type \\\"traces\\\": telemetry type is not supported\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_receiver_profiles\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): badReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(xpipeline.SignalProfiles): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"bf\\\" receiver for data type \\\"profiles\\\": telemetry type is not supported\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_connector_traces_traces.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"connector \\\"bf\\\" used as exporter in [traces/in] pipeline but not used in any supported receiver pipeline\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_connector_traces_metrics.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"connector \\\"bf\\\" used as exporter in [traces/in] pipeline but not used in any supported receiver pipeline\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_connector_traces_logs.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"connector \\\"bf\\\" used as exporter in [traces/in] pipeline but not used in any supported receiver pipeline\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_connector_traces_profiles.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"connector \\\"bf\\\" used as exporter in [traces/in] pipeline but not used in any supported receiver pipeline\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_connector_metrics_traces.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"connector \\\"bf\\\" used as exporter in [metrics/in] pipeline but not used in any supported receiver pipeline\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_connector_metrics_metrics.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"connector \\\"bf\\\" used as exporter in [metrics/in] pipeline but not used in any supported receiver pipeline\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_connector_metrics_logs.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"connector \\\"bf\\\" used as exporter in [metrics/in] pipeline but not used in any supported receiver pipeline\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_connector_metrics_profiles.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"connector \\\"bf\\\" used as exporter in [metrics/in] pipeline but not used in any supported receiver pipeline\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_connector_logs_traces.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"connector \\\"bf\\\" used as exporter in [logs/in] pipeline but not used in any supported receiver pipeline\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_connector_logs_metrics.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"connector \\\"bf\\\" used as exporter in [logs/in] pipeline but not used in any supported receiver pipeline\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_connector_logs_logs.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"connector \\\"bf\\\" used as exporter in [logs/in] pipeline but not used in any supported receiver pipeline\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_connector_logs_profiles.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"connector \\\"bf\\\" used as exporter in [logs/in] pipeline but not used in any supported receiver pipeline\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_connector_profiles_traces.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"connector \\\"bf\\\" used as exporter in [profiles/in] pipeline but not used in any supported receiver pipeline\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_connector_profiles_metrics.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"connector \\\"bf\\\" used as exporter in [profiles/in] pipeline but not used in any supported receiver pipeline\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_connector_profiles_logs.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"connector \\\"bf\\\" used as exporter in [profiles/in] pipeline but not used in any supported receiver pipeline\",\n\t\t},\n\t\t{\n\t\t\tname: \"not_supported_connector_profiles_profiles.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"bf\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"bf\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"connector \\\"bf\\\" used as exporter in [profiles/in] pipeline but not used in any supported receiver pipeline\",\n\t\t},\n\t\t{\n\t\t\tname: \"orphaned-connector-use-as-exporter\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `connector \"nop/conn\" used as exporter in [metrics/in] pipeline but not used in any supported receiver pipeline`,\n\t\t},\n\t\t{\n\t\t\tname: \"orphaned-connector-use-as-receiver\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `connector \"nop/conn\" used as receiver in [traces/out] pipeline but not used in any supported exporter pipeline`,\n\t\t},\n\t\t{\n\t\t\tname: \"partially-orphaned-connector-use-as-exporter\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"mockforward\"): mfConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"mockforward\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"mockforward\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"mockforward\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `connector \"mockforward\" used as exporter in [metrics/in] pipeline but not used in any supported receiver pipeline`,\n\t\t},\n\t\t{\n\t\t\tname: \"partially-orphaned-connector-use-as-receiver\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"mockforward\"): mfConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"mockforward\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"mockforward\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"mockforward\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `connector \"mockforward\" used as receiver in [traces/out] pipeline but not used in any supported exporter pipeline`,\n\t\t},\n\t\t{\n\t\t\tname: \"not_allowed_simple_cycle_traces.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tprocessorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopProcessorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `cycle detected: ` +\n\t\t\t\t`connector \"nop/conn\" (traces to traces) -> ` +\n\t\t\t\t`processor \"nop\" in pipeline \"traces\" -> ` +\n\t\t\t\t`connector \"nop/conn\" (traces to traces)`,\n\t\t},\n\t\t{\n\t\t\tname: \"not_allowed_simple_cycle_metrics.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tprocessorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopProcessorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `cycle detected: ` +\n\t\t\t\t`connector \"nop/conn\" (metrics to metrics) -> ` +\n\t\t\t\t`processor \"nop\" in pipeline \"metrics\" -> ` +\n\t\t\t\t`connector \"nop/conn\" (metrics to metrics)`,\n\t\t},\n\t\t{\n\t\t\tname: \"not_allowed_simple_cycle_logs.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tprocessorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopProcessorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `cycle detected: ` +\n\t\t\t\t`connector \"nop/conn\" (logs to logs) -> ` +\n\t\t\t\t`processor \"nop\" in pipeline \"logs\" -> ` +\n\t\t\t\t`connector \"nop/conn\" (logs to logs)`,\n\t\t},\n\t\t{\n\t\t\tname: \"not_allowed_simple_cycle_profiles.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tprocessorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopProcessorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(xpipeline.SignalProfiles): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `cycle detected: ` +\n\t\t\t\t`connector \"nop/conn\" (profiles to profiles) -> ` +\n\t\t\t\t`processor \"nop\" in pipeline \"profiles\" -> ` +\n\t\t\t\t`connector \"nop/conn\" (profiles to profiles)`,\n\t\t},\n\t\t{\n\t\t\tname: \"not_allowed_deep_cycle_traces.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tprocessorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopProcessorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn\"):  nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn1\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn2\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn1\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"2\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn1\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn2\"), component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn2\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `cycle detected: ` +\n\t\t\t\t`connector \"nop/conn1\" (traces to traces) -> ` +\n\t\t\t\t`processor \"nop\" in pipeline \"traces/2\" -> ` +\n\t\t\t\t`connector \"nop/conn\" (traces to traces) -> ` +\n\t\t\t\t`processor \"nop\" in pipeline \"traces/1\" -> ` +\n\t\t\t\t`connector \"nop/conn1\" (traces to traces)`,\n\t\t},\n\t\t{\n\t\t\tname: \"not_allowed_deep_cycle_metrics.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tprocessorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopProcessorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn\"):  nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn1\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn2\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn1\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"2\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn1\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn2\"), component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn2\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `cycle detected: ` +\n\t\t\t\t`connector \"nop/conn1\" (metrics to metrics) -> ` +\n\t\t\t\t`processor \"nop\" in pipeline \"metrics/2\" -> ` +\n\t\t\t\t`connector \"nop/conn\" (metrics to metrics) -> ` +\n\t\t\t\t`processor \"nop\" in pipeline \"metrics/1\" -> ` +\n\t\t\t\t`connector \"nop/conn1\" (metrics to metrics)`,\n\t\t},\n\t\t{\n\t\t\tname: \"not_allowed_deep_cycle_logs.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tprocessorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopProcessorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn\"):  nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn1\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn2\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn1\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"2\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn1\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn2\"), component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn2\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `cycle detected: ` +\n\t\t\t\t`connector \"nop/conn\" (logs to logs) -> ` +\n\t\t\t\t`processor \"nop\" in pipeline \"logs/1\" -> ` +\n\t\t\t\t`connector \"nop/conn1\" (logs to logs) -> ` +\n\t\t\t\t`processor \"nop\" in pipeline \"logs/2\" -> ` +\n\t\t\t\t`connector \"nop/conn\" (logs to logs)`,\n\t\t},\n\t\t{\n\t\t\tname: \"not_allowed_deep_cycle_profiles.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tprocessorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopProcessorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn\"):  nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn1\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"conn2\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn1\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"2\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn1\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn2\"), component.MustNewIDWithName(\"nop\", \"conn\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(xpipeline.SignalProfiles, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"conn2\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `cycle detected: ` +\n\t\t\t\t`connector \"nop/conn1\" (profiles to profiles) -> ` +\n\t\t\t\t`processor \"nop\" in pipeline \"profiles/2\" -> ` +\n\t\t\t\t`connector \"nop/conn\" (profiles to profiles) -> ` +\n\t\t\t\t`processor \"nop\" in pipeline \"profiles/1\" -> ` +\n\t\t\t\t`connector \"nop/conn1\" (profiles to profiles)`,\n\t\t},\n\t\t{\n\t\t\tname: \"not_allowed_deep_cycle_multi_signal.yaml\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tprocessorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopProcessorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"fork\"):      nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"count\"):     nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"forkagain\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t\tcomponent.MustNewIDWithName(\"nop\", \"rawlog\"):    nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"fork\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"copy1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"fork\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"count\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"copy2\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"fork\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"forkagain\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"copy2a\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"forkagain\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"count\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"copy2b\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"forkagain\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"rawlog\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalMetrics, \"count\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"count\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"raw\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewIDWithName(\"nop\", \"rawlog\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewIDWithName(\"nop\", \"fork\")}, // cannot loop back to \"nop/fork\"\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: `cycle detected: ` +\n\t\t\t\t`connector \"nop/rawlog\" (traces to logs) -> ` +\n\t\t\t\t`processor \"nop\" in pipeline \"logs/raw\" -> ` +\n\t\t\t\t`connector \"nop/fork\" (logs to traces) -> ` +\n\t\t\t\t`processor \"nop\" in pipeline \"traces/copy2\" -> ` +\n\t\t\t\t`connector \"nop/forkagain\" (traces to traces) -> ` +\n\t\t\t\t`processor \"nop\" in pipeline \"traces/copy2b\" -> ` +\n\t\t\t\t`connector \"nop/rawlog\" (traces to logs)`,\n\t\t},\n\t\t{\n\t\t\tname: \"unknown_exporter_config\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\"), component.MustNewIDWithName(\"nop\", \"1\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"nop/1\\\" exporter for data type \\\"traces\\\": exporter \\\"nop/1\\\" is not configured\",\n\t\t},\n\t\t{\n\t\t\tname: \"unknown_exporter_factory\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"unknown\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"unknown\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"unknown\\\" exporter for data type \\\"traces\\\": exporter factory not available for: \\\"unknown\\\"\",\n\t\t},\n\t\t{\n\t\t\tname: \"unknown_processor_config\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tprocessorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopProcessorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\"), component.MustNewIDWithName(\"nop\", \"1\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"nop/1\\\" processor, in pipeline \\\"metrics\\\": processor \\\"nop/1\\\" is not configured\",\n\t\t},\n\t\t{\n\t\t\tname: \"unknown_processor_factory\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tprocessorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"unknown\"): nopProcessorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"unknown\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"unknown\\\" processor, in pipeline \\\"metrics\\\": processor factory not available for: \\\"unknown\\\"\",\n\t\t},\n\t\t{\n\t\t\tname: \"unknown_receiver_config\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\"), component.MustNewIDWithName(\"nop\", \"1\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"nop/1\\\" receiver for data type \\\"logs\\\": receiver \\\"nop/1\\\" is not configured\",\n\t\t},\n\t\t{\n\t\t\tname: \"unknown_receiver_factory\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"unknown\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"unknown\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"failed to create \\\"unknown\\\" receiver for data type \\\"logs\\\": receiver factory not available for: \\\"unknown\\\"\",\n\t\t},\n\t\t{\n\t\t\tname: \"unknown_connector_factory\",\n\t\t\treceiverCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\texporterCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"nop\"): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tconnectorCfgs: map[component.ID]component.Config{\n\t\t\t\tcomponent.MustNewID(\"unknown\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tpipelineCfgs: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"in\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"unknown\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"out\"): {\n\t\t\t\t\tReceivers: []component.ID{component.MustNewID(\"unknown\")},\n\t\t\t\t\tExporters: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpected: \"connector factory not available for: \\\"unknown\\\"\",\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tset := Settings{\n\t\t\t\tBuildInfo: component.NewDefaultBuildInfo(),\n\t\t\t\tTelemetry: componenttest.NewNopTelemetrySettings(),\n\t\t\t\tReceiverBuilder: builders.NewReceiver(\n\t\t\t\t\ttt.receiverCfgs,\n\t\t\t\t\tmap[component.Type]receiver.Factory{\n\t\t\t\t\t\tnopReceiverFactory.Type(): nopReceiverFactory,\n\t\t\t\t\t\tbadReceiverFactory.Type(): badReceiverFactory,\n\t\t\t\t\t}),\n\t\t\t\tProcessorBuilder: builders.NewProcessor(\n\t\t\t\t\ttt.processorCfgs,\n\t\t\t\t\tmap[component.Type]processor.Factory{\n\t\t\t\t\t\tnopProcessorFactory.Type(): nopProcessorFactory,\n\t\t\t\t\t\tbadProcessorFactory.Type(): badProcessorFactory,\n\t\t\t\t\t}),\n\t\t\t\tExporterBuilder: builders.NewExporter(\n\t\t\t\t\ttt.exporterCfgs,\n\t\t\t\t\tmap[component.Type]exporter.Factory{\n\t\t\t\t\t\tnopExporterFactory.Type(): nopExporterFactory,\n\t\t\t\t\t\tbadExporterFactory.Type(): badExporterFactory,\n\t\t\t\t\t}),\n\t\t\t\tConnectorBuilder: builders.NewConnector(\n\t\t\t\t\ttt.connectorCfgs,\n\t\t\t\t\tmap[component.Type]connector.Factory{\n\t\t\t\t\t\tnopConnectorFactory.Type(): nopConnectorFactory,\n\t\t\t\t\t\tbadConnectorFactory.Type(): badConnectorFactory,\n\t\t\t\t\t\tmfConnectorFactory.Type():  mfConnectorFactory,\n\t\t\t\t\t}),\n\t\t\t\tPipelineConfigs: tt.pipelineCfgs,\n\t\t\t}\n\t\t\t_, err := Build(context.Background(), set)\n\t\t\tassert.EqualError(t, err, tt.expected)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "service/internal/graph/host.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage graph // import \"go.opentelemetry.io/collector/service/internal/graph\"\n\nimport (\n\t\"net/http\"\n\t\"path\"\n\t\"runtime\"\n\t\"time\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componentstatus\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/service/extensions\"\n\t\"go.opentelemetry.io/collector/service/hostcapabilities\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n\t\"go.opentelemetry.io/collector/service/internal/moduleinfo\"\n\t\"go.opentelemetry.io/collector/service/internal/status\"\n\t\"go.opentelemetry.io/collector/service/internal/zpages\"\n)\n\nvar (\n\t_ component.Host                    = (*Host)(nil)\n\t_ hostcapabilities.ModuleInfo       = (*Host)(nil)\n\t_ hostcapabilities.ExposeExporters  = (*Host)(nil) //nolint:staticcheck // SA1019\n\t_ hostcapabilities.ComponentFactory = (*Host)(nil)\n)\n\ntype Host struct {\n\tAsyncErrorChannel chan error\n\tReceivers         *builders.ReceiverBuilder\n\tProcessors        *builders.ProcessorBuilder\n\tExporters         *builders.ExporterBuilder\n\tConnectors        *builders.ConnectorBuilder\n\tExtensions        *builders.ExtensionBuilder\n\n\tModuleInfos moduleinfo.ModuleInfos\n\tBuildInfo   component.BuildInfo\n\n\tPipelines         *Graph\n\tServiceExtensions *extensions.Extensions\n\n\tReporter status.Reporter\n}\n\nfunc (host *Host) GetFactory(kind component.Kind, componentType component.Type) component.Factory {\n\tswitch kind {\n\tcase component.KindReceiver:\n\t\treturn host.Receivers.Factory(componentType)\n\tcase component.KindProcessor:\n\t\treturn host.Processors.Factory(componentType)\n\tcase component.KindExporter:\n\t\treturn host.Exporters.Factory(componentType)\n\tcase component.KindConnector:\n\t\treturn host.Connectors.Factory(componentType)\n\tcase component.KindExtension:\n\t\treturn host.Extensions.Factory(componentType)\n\t}\n\treturn nil\n}\n\nfunc (host *Host) GetExtensions() map[component.ID]component.Component {\n\treturn host.ServiceExtensions.GetExtensions()\n}\n\nfunc (host *Host) GetModuleInfos() moduleinfo.ModuleInfos {\n\treturn host.ModuleInfos\n}\n\n// Deprecated: [0.79.0] This function will be removed in the future.\n// Several components in the contrib repository use this function so it cannot be removed\n// before those cases are removed. In most cases, use of this function can be replaced by a\n// connector. See https://github.com/open-telemetry/opentelemetry-collector/issues/7370 and\n// https://github.com/open-telemetry/opentelemetry-collector/pull/7390#issuecomment-1483710184\n// for additional information.\nfunc (host *Host) GetExporters() map[pipeline.Signal]map[component.ID]component.Component {\n\treturn host.Pipelines.GetExporters()\n}\n\nfunc (host *Host) NotifyComponentStatusChange(source *componentstatus.InstanceID, event *componentstatus.Event) {\n\thost.ServiceExtensions.NotifyComponentStatusChange(source, event)\n\tif event.Status() == componentstatus.StatusFatalError {\n\t\thost.AsyncErrorChannel <- event.Err()\n\t}\n}\n\nconst (\n\t// Paths\n\tzServicePath   = \"servicez\"\n\tzPipelinePath  = \"pipelinez\"\n\tzExtensionPath = \"extensionz\"\n\tzFeaturePath   = \"featurez\"\n)\n\n// InfoVar is a singleton instance of the Info struct.\nvar runtimeInfoVar [][2]string\n\nfunc init() {\n\truntimeInfoVar = [][2]string{\n\t\t{\"StartTimestamp\", time.Now().String()},\n\t\t{\"Go\", runtime.Version()},\n\t\t{\"OS\", runtime.GOOS},\n\t\t{\"Arch\", runtime.GOARCH},\n\t\t// Add other valuable runtime information here.\n\t}\n}\n\nfunc (host *Host) RegisterZPages(mux *http.ServeMux, pathPrefix string) {\n\tmux.HandleFunc(path.Join(pathPrefix, zServicePath), host.zPagesRequest)\n\tmux.HandleFunc(path.Join(pathPrefix, zPipelinePath), host.Pipelines.HandleZPages)\n\tmux.HandleFunc(path.Join(pathPrefix, zExtensionPath), host.ServiceExtensions.HandleZPages)\n\tmux.HandleFunc(path.Join(pathPrefix, zFeaturePath), handleFeaturezRequest)\n}\n\nfunc (host *Host) zPagesRequest(w http.ResponseWriter, _ *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tzpages.WriteHTMLPageHeader(w, zpages.HeaderData{Title: \"Service \" + host.BuildInfo.Command})\n\tzpages.WriteHTMLPropertiesTable(w, zpages.PropertiesTableData{Name: \"Build Info\", Properties: getBuildInfoProperties(host.BuildInfo)})\n\tzpages.WriteHTMLPropertiesTable(w, zpages.PropertiesTableData{Name: \"Runtime Info\", Properties: runtimeInfoVar})\n\tzpages.WriteHTMLComponentHeader(w, zpages.ComponentHeaderData{\n\t\tName:              \"Pipelines\",\n\t\tComponentEndpoint: zPipelinePath,\n\t\tLink:              true,\n\t})\n\tzpages.WriteHTMLComponentHeader(w, zpages.ComponentHeaderData{\n\t\tName:              \"Extensions\",\n\t\tComponentEndpoint: zExtensionPath,\n\t\tLink:              true,\n\t})\n\tzpages.WriteHTMLComponentHeader(w, zpages.ComponentHeaderData{\n\t\tName:              \"Features\",\n\t\tComponentEndpoint: zFeaturePath,\n\t\tLink:              true,\n\t})\n\tzpages.WriteHTMLPageFooter(w)\n}\n\nfunc handleFeaturezRequest(w http.ResponseWriter, _ *http.Request) {\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tzpages.WriteHTMLPageHeader(w, zpages.HeaderData{Title: \"Feature Gates\"})\n\tzpages.WriteHTMLFeaturesTable(w, getFeaturesTableData())\n\tzpages.WriteHTMLPageFooter(w)\n}\n\nfunc getFeaturesTableData() zpages.FeatureGateTableData {\n\tdata := zpages.FeatureGateTableData{}\n\tfeaturegate.GlobalRegistry().VisitAll(func(gate *featuregate.Gate) {\n\t\tdata.Rows = append(data.Rows, zpages.FeatureGateTableRowData{\n\t\t\tID:           gate.ID(),\n\t\t\tEnabled:      gate.IsEnabled(),\n\t\t\tDescription:  gate.Description(),\n\t\t\tStage:        gate.Stage().String(),\n\t\t\tFromVersion:  gate.FromVersion(),\n\t\t\tToVersion:    gate.ToVersion(),\n\t\t\tReferenceURL: gate.ReferenceURL(),\n\t\t})\n\t})\n\treturn data\n}\n\nfunc getBuildInfoProperties(buildInfo component.BuildInfo) [][2]string {\n\treturn [][2]string{\n\t\t{\"Command\", buildInfo.Command},\n\t\t{\"Description\", buildInfo.Description},\n\t\t{\"Version\", buildInfo.Version},\n\t}\n}\n"
  },
  {
    "path": "service/internal/graph/lifecycle_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage graph\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"gonum.org/v1/gonum/graph/simple\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componentstatus\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/connectortest\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/exportertest\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/processortest\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/receivertest\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n\t\"go.opentelemetry.io/collector/service/internal/status\"\n\t\"go.opentelemetry.io/collector/service/pipelines\"\n)\n\nfunc TestGraphStartStop(t *testing.T) {\n\tt.Run(\"with_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, true)\n\t\ttestGraphStartStop(t)\n\t})\n\tt.Run(\"without_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, false)\n\t\ttestGraphStartStop(t)\n\t})\n}\n\nfunc testGraphStartStop(t *testing.T) {\n\ttestCases := []struct {\n\t\tname  string\n\t\tedges [][2]component.ID\n\t}{\n\t\t{\n\t\t\tname: \"single\",\n\t\t\tedges: [][2]component.ID{\n\t\t\t\t{component.MustNewIDWithName(\"r\", \"1\"), component.MustNewIDWithName(\"p\", \"1\")},\n\t\t\t\t{component.MustNewIDWithName(\"r\", \"2\"), component.MustNewIDWithName(\"p\", \"1\")},\n\t\t\t\t{component.MustNewIDWithName(\"p\", \"1\"), component.MustNewIDWithName(\"p\", \"2\")},\n\t\t\t\t{component.MustNewIDWithName(\"p\", \"2\"), component.MustNewIDWithName(\"e\", \"1\")},\n\t\t\t\t{component.MustNewIDWithName(\"p\", \"1\"), component.MustNewIDWithName(\"e\", \"2\")},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"multi\",\n\t\t\tedges: [][2]component.ID{\n\t\t\t\t// Pipeline 1\n\t\t\t\t{component.MustNewIDWithName(\"r\", \"1\"), component.MustNewIDWithName(\"p\", \"1\")},\n\t\t\t\t{component.MustNewIDWithName(\"r\", \"2\"), component.MustNewIDWithName(\"p\", \"1\")},\n\t\t\t\t{component.MustNewIDWithName(\"p\", \"1\"), component.MustNewIDWithName(\"p\", \"2\")},\n\t\t\t\t{component.MustNewIDWithName(\"p\", \"2\"), component.MustNewIDWithName(\"e\", \"1\")},\n\t\t\t\t{component.MustNewIDWithName(\"p\", \"1\"), component.MustNewIDWithName(\"e\", \"2\")},\n\n\t\t\t\t// Pipeline 2, shares r1 and e2\n\t\t\t\t{component.MustNewIDWithName(\"r\", \"1\"), component.MustNewIDWithName(\"p\", \"3\")},\n\t\t\t\t{component.MustNewIDWithName(\"p\", \"3\"), component.MustNewIDWithName(\"e\", \"2\")},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"connected\",\n\t\t\tedges: [][2]component.ID{\n\t\t\t\t// Pipeline 1\n\t\t\t\t{component.MustNewIDWithName(\"r\", \"1\"), component.MustNewIDWithName(\"p\", \"1\")},\n\t\t\t\t{component.MustNewIDWithName(\"r\", \"2\"), component.MustNewIDWithName(\"p\", \"1\")},\n\t\t\t\t{component.MustNewIDWithName(\"p\", \"1\"), component.MustNewIDWithName(\"p\", \"2\")},\n\t\t\t\t{component.MustNewIDWithName(\"p\", \"2\"), component.MustNewIDWithName(\"e\", \"1\")},\n\t\t\t\t{component.MustNewIDWithName(\"p\", \"1\"), component.MustNewIDWithName(\"c\", \"1\")},\n\n\t\t\t\t// Pipeline 2, shares r1 and c1\n\t\t\t\t{component.MustNewIDWithName(\"r\", \"1\"), component.MustNewIDWithName(\"p\", \"3\")},\n\t\t\t\t{component.MustNewIDWithName(\"p\", \"3\"), component.MustNewIDWithName(\"c\", \"1\")},\n\n\t\t\t\t// Pipeline 3, emits to e2 and c2\n\t\t\t\t{component.MustNewIDWithName(\"c\", \"1\"), component.MustNewIDWithName(\"e\", \"2\")},\n\t\t\t\t{component.MustNewIDWithName(\"c\", \"1\"), component.MustNewIDWithName(\"c\", \"2\")},\n\n\t\t\t\t// Pipeline 4, also emits to e2\n\t\t\t\t{component.MustNewIDWithName(\"c\", \"2\"), component.MustNewIDWithName(\"e\", \"2\")},\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tctx := &contextWithOrder{\n\t\t\t\tContext: context.Background(),\n\t\t\t\torder:   map[component.ID]int{},\n\t\t\t}\n\n\t\t\tpg := &Graph{componentGraph: simple.NewDirectedGraph()}\n\t\t\tpg.telemetry = componenttest.NewNopTelemetrySettings()\n\t\t\tpg.instanceIDs = make(map[int64]*componentstatus.InstanceID)\n\n\t\t\tfor _, edge := range tt.edges {\n\t\t\t\tf, t := &testNode{id: edge[0]}, &testNode{id: edge[1]}\n\t\t\t\tpg.instanceIDs[f.ID()] = &componentstatus.InstanceID{}\n\t\t\t\tpg.instanceIDs[t.ID()] = &componentstatus.InstanceID{}\n\t\t\t\tpg.componentGraph.SetEdge(simple.Edge{F: f, T: t})\n\t\t\t}\n\n\t\t\trequire.NoError(t, pg.StartAll(ctx, &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})}))\n\t\t\tfor _, edge := range tt.edges {\n\t\t\t\tassert.Greater(t, ctx.order[edge[0]], ctx.order[edge[1]])\n\t\t\t}\n\n\t\t\tctx.order = map[component.ID]int{}\n\t\t\trequire.NoError(t, pg.ShutdownAll(ctx, status.NewNopStatusReporter()))\n\t\t\tfor _, edge := range tt.edges {\n\t\t\t\tassert.Less(t, ctx.order[edge[0]], ctx.order[edge[1]])\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestGraphStartStopCycle(t *testing.T) {\n\tt.Run(\"with_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, true)\n\t\ttestGraphStartStopCycle(t)\n\t})\n\tt.Run(\"without_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, false)\n\t\ttestGraphStartStopCycle(t)\n\t})\n}\n\nfunc testGraphStartStopCycle(t *testing.T) {\n\tpg := &Graph{componentGraph: simple.NewDirectedGraph()}\n\n\tr1 := &testNode{id: component.MustNewIDWithName(\"r\", \"1\")}\n\tp1 := &testNode{id: component.MustNewIDWithName(\"p\", \"1\")}\n\tc1 := &testNode{id: component.MustNewIDWithName(\"c\", \"1\")}\n\te1 := &testNode{id: component.MustNewIDWithName(\"e\", \"1\")}\n\n\tpg.instanceIDs = map[int64]*componentstatus.InstanceID{\n\t\tr1.ID(): {},\n\t\tp1.ID(): {},\n\t\tc1.ID(): {},\n\t\te1.ID(): {},\n\t}\n\n\tpg.componentGraph.SetEdge(simple.Edge{F: r1, T: p1})\n\tpg.componentGraph.SetEdge(simple.Edge{F: p1, T: c1})\n\tpg.componentGraph.SetEdge(simple.Edge{F: c1, T: e1})\n\tpg.componentGraph.SetEdge(simple.Edge{F: c1, T: p1}) // loop back\n\n\terr := pg.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})})\n\trequire.ErrorContains(t, err, `topo: no topological ordering: cyclic components`)\n\n\terr = pg.ShutdownAll(context.Background(), status.NewNopStatusReporter())\n\tassert.ErrorContains(t, err, `topo: no topological ordering: cyclic components`)\n}\n\nfunc TestGraphStartStopComponentError(t *testing.T) {\n\tt.Run(\"with_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, true)\n\t\ttestGraphStartStopComponentError(t)\n\t})\n\tt.Run(\"without_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, false)\n\t\ttestGraphStartStopComponentError(t)\n\t})\n}\n\nfunc testGraphStartStopComponentError(t *testing.T) {\n\tpg := &Graph{componentGraph: simple.NewDirectedGraph()}\n\tpg.telemetry = componenttest.NewNopTelemetrySettings()\n\tr1 := &testNode{\n\t\tid:       component.MustNewIDWithName(\"r\", \"1\"),\n\t\tstartErr: errors.New(\"foo\"),\n\t}\n\te1 := &testNode{\n\t\tid:          component.MustNewIDWithName(\"e\", \"1\"),\n\t\tshutdownErr: errors.New(\"bar\"),\n\t}\n\tpg.instanceIDs = map[int64]*componentstatus.InstanceID{\n\t\tr1.ID(): {},\n\t\te1.ID(): {},\n\t}\n\tpg.componentGraph.SetEdge(simple.Edge{\n\t\tF: r1,\n\t\tT: e1,\n\t})\n\trequire.ErrorIs(t, pg.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})}), r1.startErr)\n\tassert.EqualError(t, pg.ShutdownAll(context.Background(), status.NewNopStatusReporter()), \"bar\")\n}\n\n// This includes all tests from the previous implementation, plus a new one\n// relevant only to the new graph-based implementation.\nfunc TestGraphFailToStartAndShutdown(t *testing.T) {\n\tt.Run(\"with_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, true)\n\t\ttestGraphFailToStartAndShutdown(t)\n\t})\n\tt.Run(\"without_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, false)\n\t\ttestGraphFailToStartAndShutdown(t)\n\t})\n}\n\nfunc testGraphFailToStartAndShutdown(t *testing.T) {\n\terrReceiverFactory := newErrReceiverFactory()\n\terrProcessorFactory := newErrProcessorFactory()\n\terrExporterFactory := newErrExporterFactory()\n\terrConnectorFactory := newErrConnectorFactory()\n\tnopReceiverFactory := receivertest.NewNopFactory()\n\tnopProcessorFactory := processortest.NewNopFactory()\n\tnopExporterFactory := exportertest.NewNopFactory()\n\tnopConnectorFactory := connectortest.NewNopFactory()\n\n\tset := Settings{\n\t\tTelemetry: componenttest.NewNopTelemetrySettings(),\n\t\tBuildInfo: component.NewDefaultBuildInfo(),\n\t\tReceiverBuilder: builders.NewReceiver(\n\t\t\tmap[component.ID]component.Config{\n\t\t\t\tcomponent.NewID(nopReceiverFactory.Type()): nopReceiverFactory.CreateDefaultConfig(),\n\t\t\t\tcomponent.NewID(errReceiverFactory.Type()): errReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tmap[component.Type]receiver.Factory{\n\t\t\t\tnopReceiverFactory.Type(): nopReceiverFactory,\n\t\t\t\terrReceiverFactory.Type(): errReceiverFactory,\n\t\t\t}),\n\t\tProcessorBuilder: builders.NewProcessor(\n\t\t\tmap[component.ID]component.Config{\n\t\t\t\tcomponent.NewID(nopProcessorFactory.Type()): nopProcessorFactory.CreateDefaultConfig(),\n\t\t\t\tcomponent.NewID(errProcessorFactory.Type()): errProcessorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tmap[component.Type]processor.Factory{\n\t\t\t\tnopProcessorFactory.Type(): nopProcessorFactory,\n\t\t\t\terrProcessorFactory.Type(): errProcessorFactory,\n\t\t\t}),\n\t\tExporterBuilder: builders.NewExporter(\n\t\t\tmap[component.ID]component.Config{\n\t\t\t\tcomponent.NewID(nopExporterFactory.Type()): nopExporterFactory.CreateDefaultConfig(),\n\t\t\t\tcomponent.NewID(errExporterFactory.Type()): errExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tmap[component.Type]exporter.Factory{\n\t\t\t\tnopExporterFactory.Type(): nopExporterFactory,\n\t\t\t\terrExporterFactory.Type(): errExporterFactory,\n\t\t\t}),\n\t\tConnectorBuilder: builders.NewConnector(\n\t\t\tmap[component.ID]component.Config{\n\t\t\t\tcomponent.NewIDWithName(nopConnectorFactory.Type(), \"conn\"): nopConnectorFactory.CreateDefaultConfig(),\n\t\t\t\tcomponent.NewIDWithName(errConnectorFactory.Type(), \"conn\"): errConnectorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tmap[component.Type]connector.Factory{\n\t\t\t\tnopConnectorFactory.Type(): nopConnectorFactory,\n\t\t\t\terrConnectorFactory.Type(): errConnectorFactory,\n\t\t\t}),\n\t}\n\n\tdataTypes := []pipeline.Signal{pipeline.SignalTraces, pipeline.SignalMetrics, pipeline.SignalLogs}\n\tfor _, dt := range dataTypes {\n\t\tt.Run(dt.String()+\"/receiver\", func(t *testing.T) {\n\t\t\tset.PipelineConfigs = pipelines.Config{\n\t\t\t\tpipeline.NewID(dt): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\"), component.MustNewID(\"err\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t}\n\t\t\tpipelines, err := Build(context.Background(), set)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Error(t, pipelines.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})}))\n\t\t\tassert.Error(t, pipelines.ShutdownAll(context.Background(), status.NewNopStatusReporter()))\n\t\t})\n\n\t\tt.Run(dt.String()+\"/processor\", func(t *testing.T) {\n\t\t\tset.PipelineConfigs = pipelines.Config{\n\t\t\t\tpipeline.NewID(dt): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\"), component.MustNewID(\"err\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t},\n\t\t\t}\n\t\t\tpipelines, err := Build(context.Background(), set)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Error(t, pipelines.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})}))\n\t\t\tassert.Error(t, pipelines.ShutdownAll(context.Background(), status.NewNopStatusReporter()))\n\t\t})\n\n\t\tt.Run(dt.String()+\"/exporter\", func(t *testing.T) {\n\t\t\tset.PipelineConfigs = pipelines.Config{\n\t\t\t\tpipeline.NewID(dt): {\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\"), component.MustNewID(\"err\")},\n\t\t\t\t},\n\t\t\t}\n\t\t\tpipelines, err := Build(context.Background(), set)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Error(t, pipelines.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})}))\n\t\t\tassert.Error(t, pipelines.ShutdownAll(context.Background(), status.NewNopStatusReporter()))\n\t\t})\n\n\t\tfor _, dt2 := range dataTypes {\n\t\t\tt.Run(dt.String()+\"/\"+dt2.String()+\"/connector\", func(t *testing.T) {\n\t\t\t\tset.PipelineConfigs = pipelines.Config{\n\t\t\t\t\tpipeline.NewIDWithName(dt, \"in\"): {\n\t\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\"), component.MustNewIDWithName(\"err\", \"conn\")},\n\t\t\t\t\t},\n\t\t\t\t\tpipeline.NewIDWithName(dt2, \"out\"): {\n\t\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\"), component.MustNewIDWithName(\"err\", \"conn\")},\n\t\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t\tpipelines, err := Build(context.Background(), set)\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.Error(t, pipelines.StartAll(context.Background(), &Host{Reporter: status.NewReporter(func(*componentstatus.InstanceID, *componentstatus.Event) {}, func(error) {})}))\n\t\t\t\tassert.Error(t, pipelines.ShutdownAll(context.Background(), status.NewNopStatusReporter()))\n\t\t\t})\n\t\t}\n\t}\n}\n\nfunc TestStatusReportedOnStartupShutdown(t *testing.T) {\n\tt.Run(\"with_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, true)\n\t\ttestStatusReportedOnStartupShutdown(t)\n\t})\n\tt.Run(\"without_internal_telemetry\", func(t *testing.T) {\n\t\tsetObsConsumerGateForTest(t, false)\n\t\ttestStatusReportedOnStartupShutdown(t)\n\t})\n}\n\nfunc testStatusReportedOnStartupShutdown(t *testing.T) {\n\trNoErr := &testNode{id: component.MustNewIDWithName(\"r_no_err\", \"1\")}\n\trStErr := &testNode{id: component.MustNewIDWithName(\"r_st_err\", \"1\"), startErr: assert.AnError}\n\trSdErr := &testNode{id: component.MustNewIDWithName(\"r_sd_err\", \"1\"), shutdownErr: assert.AnError}\n\n\teNoErr := &testNode{id: component.MustNewIDWithName(\"e_no_err\", \"1\")}\n\teStErr := &testNode{id: component.MustNewIDWithName(\"e_st_err\", \"1\"), startErr: assert.AnError}\n\teSdErr := &testNode{id: component.MustNewIDWithName(\"e_sd_err\", \"1\"), shutdownErr: assert.AnError}\n\n\tinstanceIDs := map[*testNode]*componentstatus.InstanceID{\n\t\trNoErr: componentstatus.NewInstanceID(rNoErr.id, component.KindReceiver),\n\t\trStErr: componentstatus.NewInstanceID(rStErr.id, component.KindReceiver),\n\t\trSdErr: componentstatus.NewInstanceID(rSdErr.id, component.KindReceiver),\n\t\teNoErr: componentstatus.NewInstanceID(eNoErr.id, component.KindExporter),\n\t\teStErr: componentstatus.NewInstanceID(eStErr.id, component.KindExporter),\n\t\teSdErr: componentstatus.NewInstanceID(eSdErr.id, component.KindExporter),\n\t}\n\n\t// compare two maps of status events ignoring timestamp\n\tassertEqualStatuses := func(t *testing.T, evMap1, evMap2 map[*componentstatus.InstanceID][]*componentstatus.Event) {\n\t\tassert.Len(t, evMap2, len(evMap1))\n\t\tfor id, evts1 := range evMap1 {\n\t\t\tevts2 := evMap2[id]\n\t\t\tassert.Len(t, evts2, len(evts1))\n\t\t\tfor i := range evts1 {\n\t\t\t\tev1 := evts1[i]\n\t\t\t\tev2 := evts2[i]\n\t\t\t\tassert.Equal(t, ev1.Status(), ev2.Status())\n\t\t\t\tassert.Equal(t, ev1.Err(), ev2.Err())\n\t\t\t}\n\t\t}\n\t}\n\n\tfor _, tt := range []struct {\n\t\tname             string\n\t\tedge             [2]*testNode\n\t\texpectedStatuses map[*componentstatus.InstanceID][]*componentstatus.Event\n\t\tstartupErr       error\n\t\tshutdownErr      error\n\t}{\n\t\t{\n\t\t\tname: \"successful startup/shutdown\",\n\t\t\tedge: [2]*testNode{rNoErr, eNoErr},\n\t\t\texpectedStatuses: map[*componentstatus.InstanceID][]*componentstatus.Event{\n\t\t\t\tinstanceIDs[rNoErr]: {\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStarting),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusOK),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopping),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopped),\n\t\t\t\t},\n\t\t\t\tinstanceIDs[eNoErr]: {\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStarting),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusOK),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopping),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopped),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"early startup error\",\n\t\t\tedge: [2]*testNode{rNoErr, eStErr},\n\t\t\texpectedStatuses: map[*componentstatus.InstanceID][]*componentstatus.Event{\n\t\t\t\tinstanceIDs[eStErr]: {\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStarting),\n\t\t\t\t\tcomponentstatus.NewPermanentErrorEvent(assert.AnError),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopping),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopped),\n\t\t\t\t},\n\t\t\t},\n\t\t\tstartupErr: assert.AnError,\n\t\t},\n\t\t{\n\t\t\tname: \"late startup error\",\n\t\t\tedge: [2]*testNode{rStErr, eNoErr},\n\t\t\texpectedStatuses: map[*componentstatus.InstanceID][]*componentstatus.Event{\n\t\t\t\tinstanceIDs[rStErr]: {\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStarting),\n\t\t\t\t\tcomponentstatus.NewPermanentErrorEvent(assert.AnError),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopping),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopped),\n\t\t\t\t},\n\t\t\t\tinstanceIDs[eNoErr]: {\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStarting),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusOK),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopping),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopped),\n\t\t\t\t},\n\t\t\t},\n\t\t\tstartupErr: assert.AnError,\n\t\t},\n\t\t{\n\t\t\tname: \"early shutdown error\",\n\t\t\tedge: [2]*testNode{rSdErr, eNoErr},\n\t\t\texpectedStatuses: map[*componentstatus.InstanceID][]*componentstatus.Event{\n\t\t\t\tinstanceIDs[rSdErr]: {\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStarting),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusOK),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopping),\n\t\t\t\t\tcomponentstatus.NewPermanentErrorEvent(assert.AnError),\n\t\t\t\t},\n\t\t\t\tinstanceIDs[eNoErr]: {\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStarting),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusOK),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopping),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopped),\n\t\t\t\t},\n\t\t\t},\n\t\t\tshutdownErr: assert.AnError,\n\t\t},\n\t\t{\n\t\t\tname: \"late shutdown error\",\n\t\t\tedge: [2]*testNode{rNoErr, eSdErr},\n\t\t\texpectedStatuses: map[*componentstatus.InstanceID][]*componentstatus.Event{\n\t\t\t\tinstanceIDs[rNoErr]: {\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStarting),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusOK),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopping),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopped),\n\t\t\t\t},\n\t\t\t\tinstanceIDs[eSdErr]: {\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStarting),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusOK),\n\t\t\t\t\tcomponentstatus.NewEvent(componentstatus.StatusStopping),\n\t\t\t\t\tcomponentstatus.NewPermanentErrorEvent(assert.AnError),\n\t\t\t\t},\n\t\t\t},\n\t\t\tshutdownErr: assert.AnError,\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tpg := &Graph{componentGraph: simple.NewDirectedGraph()}\n\t\t\tpg.telemetry = componenttest.NewNopTelemetrySettings()\n\n\t\t\tactualStatuses := make(map[*componentstatus.InstanceID][]*componentstatus.Event)\n\t\t\trep := status.NewReporter(func(id *componentstatus.InstanceID, ev *componentstatus.Event) {\n\t\t\t\tactualStatuses[id] = append(actualStatuses[id], ev)\n\t\t\t}, func(error) {\n\t\t\t})\n\n\t\t\te0, e1 := tt.edge[0], tt.edge[1]\n\t\t\tpg.instanceIDs = map[int64]*componentstatus.InstanceID{\n\t\t\t\te0.ID(): instanceIDs[e0],\n\t\t\t\te1.ID(): instanceIDs[e1],\n\t\t\t}\n\t\t\tpg.componentGraph.SetEdge(simple.Edge{F: e0, T: e1})\n\n\t\t\trequire.ErrorIs(t, pg.StartAll(context.Background(), &Host{Reporter: rep}), tt.startupErr)\n\t\t\tassert.Equal(t, tt.shutdownErr, pg.ShutdownAll(context.Background(), rep))\n\t\t\tassertEqualStatuses(t, tt.expectedStatuses, actualStatuses)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "service/internal/graph/metadata.yaml",
    "content": "type: graph\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: service\n  codeowners:\n    emeritus:\n      - djaglowski\n"
  },
  {
    "path": "service/internal/graph/obs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage graph\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n\t\"go.opentelemetry.io/collector/service/internal/obsconsumer\"\n\t\"go.opentelemetry.io/collector/service/internal/testcomponents\"\n\t\"go.opentelemetry.io/collector/service/pipelines\"\n)\n\nfunc TestComponentInstrumentation(t *testing.T) {\n\tsetObsConsumerGateForTest(t, true)\n\t// All IDs have a name to ensure the \"otelcol.component.id\" attribute is not just the type\n\trcvrID := component.MustNewIDWithName(\"examplereceiver\", \"foo\")\n\tprocID := component.MustNewIDWithName(\"exampleprocessor\", \"bar\")\n\trouterID := component.MustNewIDWithName(\"examplerouter\", \"baz\")\n\texpRightID := component.MustNewIDWithName(\"exampleexporter\", \"right\")\n\texpLeftID := component.MustNewIDWithName(\"exampleexporter\", \"left\")\n\n\ttracesInID := pipeline.NewIDWithName(pipeline.SignalTraces, \"in\")\n\ttracesRightID := pipeline.NewIDWithName(pipeline.SignalTraces, \"right\")\n\ttracesLeftID := pipeline.NewIDWithName(pipeline.SignalTraces, \"left\")\n\n\tmetricsInID := pipeline.NewIDWithName(pipeline.SignalMetrics, \"in\")\n\tmetricsRightID := pipeline.NewIDWithName(pipeline.SignalMetrics, \"right\")\n\tmetricsLeftID := pipeline.NewIDWithName(pipeline.SignalMetrics, \"left\")\n\n\tlogsInID := pipeline.NewIDWithName(pipeline.SignalLogs, \"in\")\n\tlogsRightID := pipeline.NewIDWithName(pipeline.SignalLogs, \"right\")\n\tlogsLeftID := pipeline.NewIDWithName(pipeline.SignalLogs, \"left\")\n\n\tprofilesInID := pipeline.NewIDWithName(xpipeline.SignalProfiles, \"in\")\n\tprofilesRightID := pipeline.NewIDWithName(xpipeline.SignalProfiles, \"right\")\n\tprofilesLeftID := pipeline.NewIDWithName(xpipeline.SignalProfiles, \"left\")\n\n\tctx := context.Background()\n\ttestTel := componenttest.NewTelemetry()\n\tset := Settings{\n\t\tTelemetry: testTel.NewTelemetrySettings(),\n\t\tBuildInfo: component.NewDefaultBuildInfo(),\n\t\tReceiverBuilder: builders.NewReceiver(\n\t\t\tmap[component.ID]component.Config{\n\t\t\t\trcvrID: testcomponents.ExampleReceiverFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tmap[component.Type]receiver.Factory{\n\t\t\t\ttestcomponents.ExampleReceiverFactory.Type(): testcomponents.ExampleReceiverFactory,\n\t\t\t},\n\t\t),\n\t\tProcessorBuilder: builders.NewProcessor(\n\t\t\tmap[component.ID]component.Config{\n\t\t\t\tprocID: testcomponents.ExampleProcessorFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tmap[component.Type]processor.Factory{\n\t\t\t\ttestcomponents.ExampleProcessorFactory.Type(): testcomponents.ExampleProcessorFactory,\n\t\t\t},\n\t\t),\n\t\tExporterBuilder: builders.NewExporter(\n\t\t\tmap[component.ID]component.Config{\n\t\t\t\texpRightID: testcomponents.ExampleExporterFactory.CreateDefaultConfig(),\n\t\t\t\texpLeftID:  testcomponents.ExampleExporterFactory.CreateDefaultConfig(),\n\t\t\t},\n\t\t\tmap[component.Type]exporter.Factory{\n\t\t\t\ttestcomponents.ExampleExporterFactory.Type(): testcomponents.ExampleExporterFactory,\n\t\t\t},\n\t\t),\n\t\tConnectorBuilder: builders.NewConnector(\n\t\t\tmap[component.ID]component.Config{\n\t\t\t\trouterID: testcomponents.ExampleRouterConfig{\n\t\t\t\t\tTraces: &testcomponents.LeftRightConfig{\n\t\t\t\t\t\tRight: tracesRightID,\n\t\t\t\t\t\tLeft:  tracesLeftID,\n\t\t\t\t\t},\n\t\t\t\t\tMetrics: &testcomponents.LeftRightConfig{\n\t\t\t\t\t\tRight: metricsRightID,\n\t\t\t\t\t\tLeft:  metricsLeftID,\n\t\t\t\t\t},\n\t\t\t\t\tLogs: &testcomponents.LeftRightConfig{\n\t\t\t\t\t\tRight: logsRightID,\n\t\t\t\t\t\tLeft:  logsLeftID,\n\t\t\t\t\t},\n\t\t\t\t\tProfiles: &testcomponents.LeftRightConfig{\n\t\t\t\t\t\tRight: profilesRightID,\n\t\t\t\t\t\tLeft:  profilesLeftID,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\tmap[component.Type]connector.Factory{\n\t\t\t\ttestcomponents.ExampleRouterFactory.Type(): testcomponents.ExampleRouterFactory,\n\t\t\t},\n\t\t),\n\t\tPipelineConfigs: pipelines.Config{\n\t\t\ttracesInID: {\n\t\t\t\tReceivers:  []component.ID{rcvrID},\n\t\t\t\tProcessors: []component.ID{procID},\n\t\t\t\tExporters:  []component.ID{routerID},\n\t\t\t},\n\t\t\ttracesRightID: {\n\t\t\t\tReceivers: []component.ID{routerID},\n\t\t\t\tExporters: []component.ID{expRightID},\n\t\t\t},\n\t\t\ttracesLeftID: {\n\t\t\t\tReceivers: []component.ID{routerID},\n\t\t\t\tExporters: []component.ID{expLeftID},\n\t\t\t},\n\t\t\tmetricsInID: {\n\t\t\t\tReceivers:  []component.ID{rcvrID},\n\t\t\t\tProcessors: []component.ID{procID},\n\t\t\t\tExporters:  []component.ID{routerID},\n\t\t\t},\n\t\t\tmetricsRightID: {\n\t\t\t\tReceivers: []component.ID{routerID},\n\t\t\t\tExporters: []component.ID{expRightID},\n\t\t\t},\n\t\t\tmetricsLeftID: {\n\t\t\t\tReceivers: []component.ID{routerID},\n\t\t\t\tExporters: []component.ID{expLeftID},\n\t\t\t},\n\t\t\tlogsInID: {\n\t\t\t\tReceivers:  []component.ID{rcvrID},\n\t\t\t\tProcessors: []component.ID{procID},\n\t\t\t\tExporters:  []component.ID{routerID},\n\t\t\t},\n\t\t\tlogsRightID: {\n\t\t\t\tReceivers: []component.ID{routerID},\n\t\t\t\tExporters: []component.ID{expRightID},\n\t\t\t},\n\t\t\tlogsLeftID: {\n\t\t\t\tReceivers: []component.ID{routerID},\n\t\t\t\tExporters: []component.ID{expLeftID},\n\t\t\t},\n\t\t\tprofilesInID: {\n\t\t\t\tReceivers:  []component.ID{rcvrID},\n\t\t\t\tProcessors: []component.ID{procID},\n\t\t\t\tExporters:  []component.ID{routerID},\n\t\t\t},\n\t\t\tprofilesRightID: {\n\t\t\t\tReceivers: []component.ID{routerID},\n\t\t\t\tExporters: []component.ID{expRightID},\n\t\t\t},\n\t\t\tprofilesLeftID: {\n\t\t\t\tReceivers: []component.ID{routerID},\n\t\t\t\tExporters: []component.ID{expLeftID},\n\t\t\t},\n\t\t},\n\t}\n\n\tpg, err := Build(ctx, set)\n\trequire.NoError(t, err)\n\n\tallReceivers := pg.getReceivers()\n\n\tassert.Len(t, pg.pipelines, len(set.PipelineConfigs))\n\n\t// First 3 right, next 2 left\n\ttracesReceiver := allReceivers[pipeline.SignalTraces][rcvrID].(*testcomponents.ExampleReceiver)\n\trequire.NoError(t, tracesReceiver.ConsumeTraces(ctx, testdata.GenerateTraces(3)))\n\trequire.NoError(t, tracesReceiver.ConsumeTraces(ctx, testdata.GenerateTraces(2)))\n\n\t// First 5 right, next 4 left\n\tmetricsReceiver := allReceivers[pipeline.SignalMetrics][rcvrID].(*testcomponents.ExampleReceiver)\n\trequire.NoError(t, metricsReceiver.ConsumeMetrics(ctx, testdata.GenerateMetrics(5)))\n\trequire.NoError(t, metricsReceiver.ConsumeMetrics(ctx, testdata.GenerateMetrics(4)))\n\n\t// First 7 right, next 6 left\n\tlogsReceiver := allReceivers[pipeline.SignalLogs][rcvrID].(*testcomponents.ExampleReceiver)\n\trequire.NoError(t, logsReceiver.ConsumeLogs(ctx, testdata.GenerateLogs(7)))\n\trequire.NoError(t, logsReceiver.ConsumeLogs(ctx, testdata.GenerateLogs(6)))\n\n\t// First 9 right, next 8 left\n\tprofilesReceiver := allReceivers[xpipeline.SignalProfiles][rcvrID].(*testcomponents.ExampleReceiver)\n\trequire.NoError(t, profilesReceiver.ConsumeProfiles(ctx, testdata.GenerateProfiles(9)))\n\trequire.NoError(t, profilesReceiver.ConsumeProfiles(ctx, testdata.GenerateProfiles(8)))\n\n\t// TODO fix metric name prefix delimiter\n\texpectedScopeMetrics := simpleScopeMetrics{\n\t\t// Traces\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"receiver\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"examplereceiver/foo\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"traces\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.receiver.produced.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 5,\n\t\t\t},\n\t\t\t\"otelcol.receiver.produced.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 866,\n\t\t\t},\n\t\t},\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"processor\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"exampleprocessor/bar\"),\n\t\t\tattribute.String(\"otelcol.pipeline.id\", \"traces/in\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"traces\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.processor.consumed.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 5,\n\t\t\t},\n\t\t\t\"otelcol.processor.produced.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 5,\n\t\t\t},\n\t\t\t\"otelcol.processor.consumed.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 866,\n\t\t\t},\n\t\t\t\"otelcol.processor.produced.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 866,\n\t\t\t},\n\t\t},\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"connector\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"examplerouter/baz\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"traces\"),\n\t\t\tattribute.String(\"otelcol.signal.output\", \"traces\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.connector.consumed.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 5,\n\t\t\t},\n\t\t\t\"otelcol.connector.produced.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t\tattribute.String(\"otelcol.pipeline.id\", \"traces/right\"),\n\t\t\t\t): 3,\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t\tattribute.String(\"otelcol.pipeline.id\", \"traces/left\"),\n\t\t\t\t): 2,\n\t\t\t},\n\t\t\t\"otelcol.connector.consumed.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 866,\n\t\t\t},\n\t\t\t\"otelcol.connector.produced.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t\tattribute.String(\"otelcol.pipeline.id\", \"traces/right\"),\n\t\t\t\t): 528,\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t\tattribute.String(\"otelcol.pipeline.id\", \"traces/left\"),\n\t\t\t\t): 338,\n\t\t\t},\n\t\t},\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"exporter\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"exampleexporter/right\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"traces\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.exporter.consumed.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 3,\n\t\t\t},\n\t\t\t\"otelcol.exporter.consumed.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 528,\n\t\t\t},\n\t\t},\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"exporter\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"exampleexporter/left\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"traces\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.exporter.consumed.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 2,\n\t\t\t},\n\t\t\t\"otelcol.exporter.consumed.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 338,\n\t\t\t},\n\t\t},\n\n\t\t// Metrics\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"receiver\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"examplereceiver/foo\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"metrics\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.receiver.produced.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 18, // GenerateMetrics(9) produces 18 data points\n\t\t\t},\n\t\t\t\"otelcol.receiver.produced.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 1741, // GenerateMetrics(9) produces 18 data points\n\t\t\t},\n\t\t},\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"processor\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"exampleprocessor/bar\"),\n\t\t\tattribute.String(\"otelcol.pipeline.id\", \"metrics/in\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"metrics\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.processor.consumed.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 18, // GenerateMetrics(9) produces 18 data points\n\t\t\t},\n\t\t\t\"otelcol.processor.produced.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 18, // GenerateMetrics(9) produces 18 data points\n\t\t\t},\n\t\t\t\"otelcol.processor.consumed.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 1741, // GenerateMetrics(9) produces 18 data points\n\t\t\t},\n\t\t\t\"otelcol.processor.produced.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 1741, // GenerateMetrics(9) produces 18 data points\n\t\t\t},\n\t\t},\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"connector\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"examplerouter/baz\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"metrics\"),\n\t\t\tattribute.String(\"otelcol.signal.output\", \"metrics\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.connector.consumed.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 18, // GenerateMetrics(9) produces 18 data points\n\t\t\t},\n\t\t\t\"otelcol.connector.produced.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t\tattribute.String(\"otelcol.pipeline.id\", \"metrics/right\"),\n\t\t\t\t): 10, // GenerateMetrics(5) produces 10 data points\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t\tattribute.String(\"otelcol.pipeline.id\", \"metrics/left\"),\n\t\t\t\t): 8, // GenerateMetrics(4) produces 8 data points\n\t\t\t},\n\t\t\t\"otelcol.connector.consumed.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 1741, // GenerateMetrics(9) produces 18 data points\n\t\t\t},\n\t\t\t\"otelcol.connector.produced.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t\tattribute.String(\"otelcol.pipeline.id\", \"metrics/right\"),\n\t\t\t\t): 1035, // GenerateMetrics(5) produces 10 data points\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t\tattribute.String(\"otelcol.pipeline.id\", \"metrics/left\"),\n\t\t\t\t): 706, // GenerateMetrics(4) produces 8 data points\n\t\t\t},\n\t\t},\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"exporter\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"exampleexporter/right\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"metrics\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.exporter.consumed.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 10, // GenerateMetrics(5) produces 10 data points\n\t\t\t},\n\t\t\t\"otelcol.exporter.consumed.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 1035, // GenerateMetrics(9) produces 18 data points\n\t\t\t},\n\t\t},\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"exporter\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"exampleexporter/left\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"metrics\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.exporter.consumed.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 8, // GenerateMetrics(4) produces 8 data points\n\t\t\t},\n\t\t\t\"otelcol.exporter.consumed.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 706, // GenerateMetrics(9) produces 18 data points\n\t\t\t},\n\t\t},\n\n\t\t// Logs\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"receiver\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"examplereceiver/foo\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"logs\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.receiver.produced.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 13,\n\t\t\t},\n\t\t\t\"otelcol.receiver.produced.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 1363,\n\t\t\t},\n\t\t},\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"processor\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"exampleprocessor/bar\"),\n\t\t\tattribute.String(\"otelcol.pipeline.id\", \"logs/in\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"logs\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.processor.consumed.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 13,\n\t\t\t},\n\t\t\t\"otelcol.processor.produced.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 13,\n\t\t\t},\n\t\t\t\"otelcol.processor.consumed.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 1363,\n\t\t\t},\n\t\t\t\"otelcol.processor.produced.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 1363,\n\t\t\t},\n\t\t},\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"connector\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"examplerouter/baz\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"logs\"),\n\t\t\tattribute.String(\"otelcol.signal.output\", \"logs\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.connector.consumed.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 13,\n\t\t\t},\n\t\t\t\"otelcol.connector.produced.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t\tattribute.String(\"otelcol.pipeline.id\", \"logs/right\"),\n\t\t\t\t): 7,\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t\tattribute.String(\"otelcol.pipeline.id\", \"logs/left\"),\n\t\t\t\t): 6,\n\t\t\t},\n\t\t\t\"otelcol.connector.consumed.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 1363,\n\t\t\t},\n\t\t\t\"otelcol.connector.produced.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t\tattribute.String(\"otelcol.pipeline.id\", \"logs/right\"),\n\t\t\t\t): 737,\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t\tattribute.String(\"otelcol.pipeline.id\", \"logs/left\"),\n\t\t\t\t): 626,\n\t\t\t},\n\t\t},\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"exporter\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"exampleexporter/right\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"logs\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.exporter.consumed.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 7,\n\t\t\t},\n\t\t\t\"otelcol.exporter.consumed.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 737,\n\t\t\t},\n\t\t},\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"exporter\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"exampleexporter/left\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"logs\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.exporter.consumed.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 6,\n\t\t\t},\n\t\t\t\"otelcol.exporter.consumed.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 626,\n\t\t\t},\n\t\t},\n\n\t\t// Profiles\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"receiver\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"examplereceiver/foo\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"profiles\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.receiver.produced.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 17,\n\t\t\t},\n\t\t\t\"otelcol.receiver.produced.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 1055,\n\t\t\t},\n\t\t},\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"processor\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"exampleprocessor/bar\"),\n\t\t\tattribute.String(\"otelcol.pipeline.id\", \"profiles/in\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"profiles\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.processor.consumed.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 17,\n\t\t\t},\n\t\t\t\"otelcol.processor.produced.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 17,\n\t\t\t},\n\t\t\t\"otelcol.processor.consumed.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 1055,\n\t\t\t},\n\t\t\t\"otelcol.processor.produced.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 1055,\n\t\t\t},\n\t\t},\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"connector\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"examplerouter/baz\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"profiles\"),\n\t\t\tattribute.String(\"otelcol.signal.output\", \"profiles\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.connector.consumed.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 17,\n\t\t\t},\n\t\t\t\"otelcol.connector.produced.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t\tattribute.String(\"otelcol.pipeline.id\", \"profiles/right\"),\n\t\t\t\t): 9,\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t\tattribute.String(\"otelcol.pipeline.id\", \"profiles/left\"),\n\t\t\t\t): 8,\n\t\t\t},\n\t\t\t\"otelcol.connector.consumed.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 1055,\n\t\t\t},\n\t\t\t\"otelcol.connector.produced.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t\tattribute.String(\"otelcol.pipeline.id\", \"profiles/right\"),\n\t\t\t\t): 552,\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t\tattribute.String(\"otelcol.pipeline.id\", \"profiles/left\"),\n\t\t\t\t): 503,\n\t\t\t},\n\t\t},\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"exporter\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"exampleexporter/right\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"profiles\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.exporter.consumed.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 9,\n\t\t\t},\n\t\t\t\"otelcol.exporter.consumed.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 552,\n\t\t\t},\n\t\t},\n\t\tattribute.NewSet(\n\t\t\tattribute.String(\"otelcol.component.kind\", \"exporter\"),\n\t\t\tattribute.String(\"otelcol.component.id\", \"exampleexporter/left\"),\n\t\t\tattribute.String(\"otelcol.signal\", \"profiles\"),\n\t\t): simpleMetricMap{\n\t\t\t\"otelcol.exporter.consumed.items\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 8,\n\t\t\t},\n\t\t\t\"otelcol.exporter.consumed.size\": simpleMetric{\n\t\t\t\tattribute.NewSet(\n\t\t\t\t\tattribute.String(obsconsumer.ComponentOutcome, \"success\"),\n\t\t\t\t): 503,\n\t\t\t},\n\t\t},\n\t}\n\n\t// Verify telemetry was properly emitted by components\n\tvar rm metricdata.ResourceMetrics\n\trequire.NoError(t, testTel.Reader.Collect(ctx, &rm))\n\n\trequire.NotNil(t, rm)\n\trequire.NotNil(t, rm.ScopeMetrics)\n\n\tassert.Len(t, rm.ScopeMetrics, len(expectedScopeMetrics))\n\n\tfor _, actualScopeMetrics := range rm.ScopeMetrics {\n\t\texpectedScopeMetrics, ok := expectedScopeMetrics[actualScopeMetrics.Scope.Attributes]\n\t\trequire.True(t, ok)\n\n\t\tfor _, actualMetric := range actualScopeMetrics.Metrics {\n\t\t\texpectedMetric, ok := expectedScopeMetrics[actualMetric.Name]\n\t\t\trequire.True(t, ok)\n\n\t\t\tfor _, actualPoint := range actualMetric.Data.(metricdata.Sum[int64]).DataPoints {\n\t\t\t\texpectedPoint, ok := expectedMetric[actualPoint.Attributes]\n\t\t\t\trequire.True(t, ok)\n\n\t\t\t\tassert.Equal(t, int64(expectedPoint), actualPoint.Value)\n\t\t\t}\n\t\t}\n\t}\n\n\tassert.NoError(t, testTel.Shutdown(ctx))\n}\n\n// map[dataPointAttrs]value\ntype simpleMetric map[attribute.Set]int\n\n// map[metricName]simpleMetric\ntype simpleMetricMap map[string]simpleMetric\n\n// map[scopeAttrs]simpleMetricMap\ntype simpleScopeMetrics map[attribute.Set]simpleMetricMap\n"
  },
  {
    "path": "service/internal/graph/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage graph\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "service/internal/graph/processor.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage graph // import \"go.opentelemetry.io/collector/service/internal/graph\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/service/internal/attribute\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n\t\"go.opentelemetry.io/collector/service/internal/componentattribute\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n\t\"go.opentelemetry.io/collector/service/internal/obsconsumer\"\n\t\"go.opentelemetry.io/collector/service/internal/refconsumer\"\n)\n\nvar _ consumerNode = (*processorNode)(nil)\n\n// Every processor instance is unique to one pipeline.\n// Therefore, nodeID is derived from \"pipeline ID\" and \"component ID\".\ntype processorNode struct {\n\tattribute.Attributes\n\tcomponentID component.ID\n\tpipelineID  pipeline.ID\n\tcomponent.Component\n\tconsumer baseConsumer\n}\n\nfunc newProcessorNode(pipelineID pipeline.ID, procID component.ID) *processorNode {\n\treturn &processorNode{\n\t\tAttributes:  attribute.Processor(pipelineID, procID),\n\t\tcomponentID: procID,\n\t\tpipelineID:  pipelineID,\n\t}\n}\n\nfunc (n *processorNode) getConsumer() baseConsumer {\n\treturn n.consumer\n}\n\nfunc (n *processorNode) buildComponent(ctx context.Context,\n\ttel component.TelemetrySettings,\n\tinfo component.BuildInfo,\n\tbuilder *builders.ProcessorBuilder,\n\tnext baseConsumer,\n) error {\n\tset := processor.Settings{\n\t\tID:                n.componentID,\n\t\tTelemetrySettings: componentattribute.TelemetrySettingsWithAttributes(tel, *n.Set()),\n\t\tBuildInfo:         info,\n\t}\n\n\ttb, err := metadata.NewTelemetryBuilder(set.TelemetrySettings)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tproducedSettings := obsconsumer.Settings{\n\t\tItemCounter: tb.ProcessorProducedItems,\n\t\tSizeCounter: tb.ProcessorProducedSize,\n\t\tLogger:      set.Logger,\n\t}\n\tconsumedSettings := obsconsumer.Settings{\n\t\tItemCounter: tb.ProcessorConsumedItems,\n\t\tSizeCounter: tb.ProcessorConsumedSize,\n\t\tLogger:      set.Logger,\n\t}\n\n\tswitch n.pipelineID.Signal() {\n\tcase pipeline.SignalTraces:\n\t\tn.Component, err = builder.CreateTraces(ctx, set,\n\t\t\tobsconsumer.NewTraces(next.(consumer.Traces), producedSettings),\n\t\t)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %q processor, in pipeline %q: %w\", set.ID, n.pipelineID.String(), err)\n\t\t}\n\t\tn.consumer = obsconsumer.NewTraces(n.Component.(consumer.Traces), consumedSettings)\n\t\tn.consumer = refconsumer.NewTraces(n.consumer.(consumer.Traces))\n\tcase pipeline.SignalMetrics:\n\t\tn.Component, err = builder.CreateMetrics(ctx, set,\n\t\t\tobsconsumer.NewMetrics(next.(consumer.Metrics), producedSettings))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %q processor, in pipeline %q: %w\", set.ID, n.pipelineID.String(), err)\n\t\t}\n\t\tn.consumer = obsconsumer.NewMetrics(n.Component.(consumer.Metrics), consumedSettings)\n\t\tn.consumer = refconsumer.NewMetrics(n.consumer.(consumer.Metrics))\n\tcase pipeline.SignalLogs:\n\t\tn.Component, err = builder.CreateLogs(ctx, set,\n\t\t\tobsconsumer.NewLogs(next.(consumer.Logs), producedSettings))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %q processor, in pipeline %q: %w\", set.ID, n.pipelineID.String(), err)\n\t\t}\n\t\tn.consumer = obsconsumer.NewLogs(n.Component.(consumer.Logs), consumedSettings)\n\t\tn.consumer = refconsumer.NewLogs(n.consumer.(consumer.Logs))\n\tcase xpipeline.SignalProfiles:\n\t\tn.Component, err = builder.CreateProfiles(ctx, set,\n\t\t\tobsconsumer.NewProfiles(next.(xconsumer.Profiles), producedSettings))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to create %q processor, in pipeline %q: %w\", set.ID, n.pipelineID.String(), err)\n\t\t}\n\t\tn.consumer = obsconsumer.NewProfiles(n.Component.(xconsumer.Profiles), consumedSettings)\n\t\tn.consumer = refconsumer.NewProfiles(n.consumer.(xconsumer.Profiles))\n\tdefault:\n\t\treturn fmt.Errorf(\"error creating processor %q in pipeline %q, data type %q is not supported\", set.ID, n.pipelineID.String(), n.pipelineID.Signal())\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "service/internal/graph/receiver.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage graph // import \"go.opentelemetry.io/collector/service/internal/graph\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/internal/fanoutconsumer\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/service/internal/attribute\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n\t\"go.opentelemetry.io/collector/service/internal/componentattribute\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n\t\"go.opentelemetry.io/collector/service/internal/obsconsumer\"\n)\n\n// A receiver instance can be shared by multiple pipelines of the same type.\n// Therefore, nodeID is derived from \"pipeline type\" and \"component ID\".\ntype receiverNode struct {\n\tattribute.Attributes\n\tcomponentID  component.ID\n\tpipelineType pipeline.Signal\n\tcomponent.Component\n}\n\nfunc newReceiverNode(pipelineType pipeline.Signal, recvID component.ID) *receiverNode {\n\treturn &receiverNode{\n\t\tAttributes:   attribute.Receiver(pipelineType, recvID),\n\t\tcomponentID:  recvID,\n\t\tpipelineType: pipelineType,\n\t}\n}\n\nfunc (n *receiverNode) buildComponent(ctx context.Context,\n\ttel component.TelemetrySettings,\n\tinfo component.BuildInfo,\n\tbuilder *builders.ReceiverBuilder,\n\tnexts []baseConsumer,\n) error {\n\tset := receiver.Settings{\n\t\tID:                n.componentID,\n\t\tTelemetrySettings: componentattribute.TelemetrySettingsWithAttributes(tel, *n.Set()),\n\t\tBuildInfo:         info,\n\t}\n\n\ttb, err := metadata.NewTelemetryBuilder(set.TelemetrySettings)\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tproducedSettings := obsconsumer.Settings{\n\t\tItemCounter: tb.ReceiverProducedItems,\n\t\tSizeCounter: tb.ReceiverProducedSize,\n\t\tLogger:      set.Logger,\n\t}\n\n\tswitch n.pipelineType {\n\tcase pipeline.SignalTraces:\n\t\tvar consumers []consumer.Traces\n\t\tfor _, next := range nexts {\n\t\t\tconsumers = append(consumers, next.(consumer.Traces))\n\t\t}\n\t\tn.Component, err = builder.CreateTraces(ctx, set,\n\t\t\tobsconsumer.NewTraces(fanoutconsumer.NewTraces(consumers), producedSettings),\n\t\t)\n\tcase pipeline.SignalMetrics:\n\t\tvar consumers []consumer.Metrics\n\t\tfor _, next := range nexts {\n\t\t\tconsumers = append(consumers, next.(consumer.Metrics))\n\t\t}\n\t\tn.Component, err = builder.CreateMetrics(ctx, set,\n\t\t\tobsconsumer.NewMetrics(fanoutconsumer.NewMetrics(consumers), producedSettings))\n\tcase pipeline.SignalLogs:\n\t\tvar consumers []consumer.Logs\n\t\tfor _, next := range nexts {\n\t\t\tconsumers = append(consumers, next.(consumer.Logs))\n\t\t}\n\t\tn.Component, err = builder.CreateLogs(ctx, set,\n\t\t\tobsconsumer.NewLogs(fanoutconsumer.NewLogs(consumers), producedSettings))\n\tcase xpipeline.SignalProfiles:\n\t\tvar consumers []xconsumer.Profiles\n\t\tfor _, next := range nexts {\n\t\t\tconsumers = append(consumers, next.(xconsumer.Profiles))\n\t\t}\n\t\tn.Component, err = builder.CreateProfiles(ctx, set,\n\t\t\tobsconsumer.NewProfiles(fanoutconsumer.NewProfiles(consumers), producedSettings))\n\tdefault:\n\t\treturn fmt.Errorf(\"error creating receiver %q for data type %q is not supported\", set.ID, n.pipelineType)\n\t}\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to create %q receiver for data type %q: %w\", set.ID, n.pipelineType, err)\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "service/internal/graph/util_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage graph\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"hash/fnv\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/xconnector\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/xprocessor\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n\t\"go.opentelemetry.io/collector/service/pipelines\"\n)\n\nvar _ component.Component = (*testNode)(nil)\n\ntype testNode struct {\n\tid          component.ID\n\tstartErr    error\n\tshutdownErr error\n}\n\n// ID satisfies the graph.Node interface, allowing\n// testNode to be used in a simple.DirectedGraph\nfunc (n *testNode) ID() int64 {\n\th := fnv.New64a()\n\th.Write([]byte(n.id.String()))\n\n\t// The graph identifies nodes by an int64 ID, but fnv gives us a uint64.\n\t// It is safe to cast because the meaning of the number is irrelevant.\n\t// We only care that each node has a unique 64 bit ID, which is unaltered by this cast.\n\treturn int64(h.Sum64()) // #nosec G115\n}\n\nfunc (n *testNode) Start(ctx context.Context, _ component.Host) error {\n\tif n.startErr != nil {\n\t\treturn n.startErr\n\t}\n\tif cwo, ok := ctx.(*contextWithOrder); ok {\n\t\tcwo.record(n.id)\n\t}\n\treturn nil\n}\n\nfunc (n *testNode) Shutdown(ctx context.Context) error {\n\tif n.shutdownErr != nil {\n\t\treturn n.shutdownErr\n\t}\n\tif cwo, ok := ctx.(*contextWithOrder); ok {\n\t\tcwo.record(n.id)\n\t}\n\treturn nil\n}\n\ntype contextWithOrder struct {\n\tcontext.Context\n\tsync.Mutex\n\tnext  int\n\torder map[component.ID]int\n}\n\nfunc (c *contextWithOrder) record(id component.ID) {\n\tc.Lock()\n\tc.order[id] = c.next\n\tc.next++\n\tc.Unlock()\n}\n\nfunc (g *Graph) getReceivers() map[pipeline.Signal]map[component.ID]component.Component {\n\treceiversMap := make(map[pipeline.Signal]map[component.ID]component.Component)\n\treceiversMap[pipeline.SignalTraces] = make(map[component.ID]component.Component)\n\treceiversMap[pipeline.SignalMetrics] = make(map[component.ID]component.Component)\n\treceiversMap[pipeline.SignalLogs] = make(map[component.ID]component.Component)\n\treceiversMap[xpipeline.SignalProfiles] = make(map[component.ID]component.Component)\n\n\tfor _, pg := range g.pipelines {\n\t\tfor _, rcvrNode := range pg.receivers {\n\t\t\trcvrOrConnNode := g.componentGraph.Node(rcvrNode.ID())\n\t\t\trcvrNode, ok := rcvrOrConnNode.(*receiverNode)\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\treceiversMap[rcvrNode.pipelineType][rcvrNode.componentID] = rcvrNode.Component\n\t\t}\n\t}\n\treturn receiversMap\n}\n\n// Calculates the expected number of receiver and exporter instances in the specified pipeline.\n//\n// Expect one instance of each receiver and exporter, unless it is a connector.\n//\n// For Connectors:\n// - Let E equal the number of pipeline types in which the connector is used as an exporter.\n// - Let R equal the number of pipeline types in which the connector is used as a receiver.\n//\n// Within the graph as a whole, we expect E*R instances, i.e. one per combination of data types.\n//\n// However, within an individual pipeline, we expect:\n// - E instances of the connector as a receiver.\n// - R instances of the connector as an exporter.\nfunc expectedInstances(m pipelines.Config, pID pipeline.ID) (int, int) {\n\texConnectorType := component.MustNewType(\"exampleconnector\")\n\tvar r, e int\n\tfor _, rID := range m[pID].Receivers {\n\t\tif rID.Type() != exConnectorType {\n\t\t\tr++\n\t\t\tcontinue\n\t\t}\n\n\t\t// This is a connector. Count the pipeline types where it is an exporter.\n\t\ttypeMap := map[pipeline.Signal]bool{}\n\t\tfor pID, pCfg := range m {\n\t\t\tfor _, eID := range pCfg.Exporters {\n\t\t\t\tif eID == rID {\n\t\t\t\t\ttypeMap[pID.Signal()] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tr += len(typeMap)\n\t}\n\tfor _, eID := range m[pID].Exporters {\n\t\tif eID.Type() != exConnectorType {\n\t\t\te++\n\t\t\tcontinue\n\t\t}\n\n\t\t// This is a connector. Count the pipeline types where it is a receiver.\n\t\ttypeMap := map[pipeline.Signal]bool{}\n\t\tfor pID, pCfg := range m {\n\t\t\tfor _, rID := range pCfg.Receivers {\n\t\t\t\tif rID == eID {\n\t\t\t\t\ttypeMap[pID.Signal()] = true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\te += len(typeMap)\n\t}\n\treturn r, e\n}\n\nfunc newBadReceiverFactory() receiver.Factory {\n\treturn receiver.NewFactory(component.MustNewType(\"bf\"), func() component.Config {\n\t\treturn &struct{}{}\n\t})\n}\n\nfunc newBadProcessorFactory() processor.Factory {\n\treturn processor.NewFactory(component.MustNewType(\"bf\"), func() component.Config {\n\t\treturn &struct{}{}\n\t})\n}\n\nfunc newBadExporterFactory() exporter.Factory {\n\treturn exporter.NewFactory(component.MustNewType(\"bf\"), func() component.Config {\n\t\treturn &struct{}{}\n\t})\n}\n\nfunc newBadConnectorFactory() connector.Factory {\n\treturn connector.NewFactory(component.MustNewType(\"bf\"), func() component.Config {\n\t\treturn &struct{}{}\n\t})\n}\n\nfunc newErrReceiverFactory() receiver.Factory {\n\treturn xreceiver.NewFactory(component.MustNewType(\"err\"),\n\t\tfunc() component.Config { return &struct{}{} },\n\t\txreceiver.WithTraces(func(context.Context, receiver.Settings, component.Config, consumer.Traces) (receiver.Traces, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUndefined),\n\t\txreceiver.WithLogs(func(context.Context, receiver.Settings, component.Config, consumer.Logs) (receiver.Logs, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUndefined),\n\t\txreceiver.WithMetrics(func(context.Context, receiver.Settings, component.Config, consumer.Metrics) (receiver.Metrics, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUndefined),\n\t\txreceiver.WithProfiles(func(context.Context, receiver.Settings, component.Config, xconsumer.Profiles) (xreceiver.Profiles, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUndefined),\n\t)\n}\n\nfunc newErrProcessorFactory() processor.Factory {\n\treturn xprocessor.NewFactory(component.MustNewType(\"err\"),\n\t\tfunc() component.Config { return &struct{}{} },\n\t\txprocessor.WithTraces(func(context.Context, processor.Settings, component.Config, consumer.Traces) (processor.Traces, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUndefined),\n\t\txprocessor.WithLogs(func(context.Context, processor.Settings, component.Config, consumer.Logs) (processor.Logs, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUndefined),\n\t\txprocessor.WithMetrics(func(context.Context, processor.Settings, component.Config, consumer.Metrics) (processor.Metrics, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUndefined),\n\t\txprocessor.WithProfiles(func(context.Context, processor.Settings, component.Config, xconsumer.Profiles) (xprocessor.Profiles, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUndefined),\n\t)\n}\n\nfunc newErrExporterFactory() exporter.Factory {\n\treturn xexporter.NewFactory(component.MustNewType(\"err\"),\n\t\tfunc() component.Config { return &struct{}{} },\n\t\txexporter.WithTraces(func(context.Context, exporter.Settings, component.Config) (exporter.Traces, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUndefined),\n\t\txexporter.WithLogs(func(context.Context, exporter.Settings, component.Config) (exporter.Logs, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUndefined),\n\t\txexporter.WithMetrics(func(context.Context, exporter.Settings, component.Config) (exporter.Metrics, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUndefined),\n\t\txexporter.WithProfiles(func(context.Context, exporter.Settings, component.Config) (xexporter.Profiles, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUndefined),\n\t)\n}\n\nfunc newErrConnectorFactory() connector.Factory {\n\treturn xconnector.NewFactory(component.MustNewType(\"err\"), func() component.Config {\n\t\treturn &struct{}{}\n\t},\n\t\txconnector.WithTracesToTraces(func(context.Context, connector.Settings, component.Config, consumer.Traces) (connector.Traces, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUnmaintained),\n\t\txconnector.WithTracesToMetrics(func(context.Context, connector.Settings, component.Config, consumer.Metrics) (connector.Traces, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUnmaintained),\n\t\txconnector.WithTracesToLogs(func(context.Context, connector.Settings, component.Config, consumer.Logs) (connector.Traces, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUnmaintained),\n\t\txconnector.WithTracesToProfiles(func(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (connector.Traces, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUnmaintained),\n\n\t\txconnector.WithMetricsToTraces(func(context.Context, connector.Settings, component.Config, consumer.Traces) (connector.Metrics, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUnmaintained),\n\t\txconnector.WithMetricsToMetrics(func(context.Context, connector.Settings, component.Config, consumer.Metrics) (connector.Metrics, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUnmaintained),\n\t\txconnector.WithMetricsToLogs(func(context.Context, connector.Settings, component.Config, consumer.Logs) (connector.Metrics, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUnmaintained),\n\t\txconnector.WithMetricsToProfiles(func(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (connector.Metrics, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUnmaintained),\n\n\t\txconnector.WithLogsToTraces(func(context.Context, connector.Settings, component.Config, consumer.Traces) (connector.Logs, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUnmaintained),\n\t\txconnector.WithLogsToMetrics(func(context.Context, connector.Settings, component.Config, consumer.Metrics) (connector.Logs, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUnmaintained),\n\t\txconnector.WithLogsToLogs(func(context.Context, connector.Settings, component.Config, consumer.Logs) (connector.Logs, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUnmaintained),\n\t\txconnector.WithLogsToProfiles(func(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (connector.Logs, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUnmaintained),\n\n\t\txconnector.WithProfilesToTraces(func(context.Context, connector.Settings, component.Config, consumer.Traces) (xconnector.Profiles, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUnmaintained),\n\t\txconnector.WithProfilesToMetrics(func(context.Context, connector.Settings, component.Config, consumer.Metrics) (xconnector.Profiles, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUnmaintained),\n\t\txconnector.WithProfilesToLogs(func(context.Context, connector.Settings, component.Config, consumer.Logs) (xconnector.Profiles, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUnmaintained),\n\t\txconnector.WithProfilesToProfiles(func(context.Context, connector.Settings, component.Config, xconsumer.Profiles) (xconnector.Profiles, error) {\n\t\t\treturn &errComponent{}, nil\n\t\t}, component.StabilityLevelUnmaintained),\n\t)\n}\n\ntype errComponent struct {\n\tconsumertest.Consumer\n}\n\nfunc (e errComponent) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: false}\n}\n\nfunc (e errComponent) Start(context.Context, component.Host) error {\n\treturn errors.New(\"my error\")\n}\n\nfunc (e errComponent) Shutdown(context.Context) error {\n\treturn errors.New(\"my error\")\n}\n\nfunc setObsConsumerGateForTest(t *testing.T, enabled bool) {\n\tinitial := metadata.TelemetryNewPipelineTelemetryFeatureGate.IsEnabled()\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.TelemetryNewPipelineTelemetryFeatureGate.ID(), enabled))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.TelemetryNewPipelineTelemetryFeatureGate.ID(), initial))\n\t})\n}\n"
  },
  {
    "path": "service/internal/graph/zpages.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage graph // import \"go.opentelemetry.io/collector/service/internal/graph\"\n\nimport (\n\t\"net/http\"\n\t\"sort\"\n\n\t\"go.opentelemetry.io/collector/service/internal/zpages\"\n)\n\nconst (\n\n\t// URL Params\n\tzPipelineName  = \"pipelinenamez\"\n\tzComponentName = \"componentnamez\"\n\tzComponentKind = \"componentkindz\"\n)\n\nfunc (g *Graph) HandleZPages(w http.ResponseWriter, r *http.Request) {\n\tqValues := r.URL.Query()\n\tpipelineName := qValues.Get(zPipelineName)\n\tcomponentName := qValues.Get(zComponentName)\n\tcomponentKind := qValues.Get(zComponentKind)\n\n\tw.Header().Set(\"Content-Type\", \"text/html; charset=utf-8\")\n\tzpages.WriteHTMLPageHeader(w, zpages.HeaderData{Title: \"builtPipelines\"})\n\n\tsumData := zpages.SummaryPipelinesTableData{}\n\tsumData.Rows = make([]zpages.SummaryPipelinesTableRowData, 0, len(g.pipelines))\n\tfor c, p := range g.pipelines {\n\t\trecvIDs := make([]string, 0, len(p.receivers))\n\t\tfor _, c := range p.receivers {\n\t\t\tswitch n := c.(type) {\n\t\t\tcase *receiverNode:\n\t\t\t\trecvIDs = append(recvIDs, n.componentID.String())\n\t\t\tcase *connectorNode:\n\t\t\t\trecvIDs = append(recvIDs, n.componentID.String()+\" (connector)\")\n\t\t\t}\n\t\t}\n\t\tprocIDs := make([]string, 0, len(p.processors))\n\t\tfor _, c := range p.processors {\n\t\t\tprocIDs = append(procIDs, c.(*processorNode).componentID.String())\n\t\t}\n\t\texprIDs := make([]string, 0, len(p.exporters))\n\t\tfor _, c := range p.exporters {\n\t\t\tswitch n := c.(type) {\n\t\t\tcase *exporterNode:\n\t\t\t\texprIDs = append(exprIDs, n.componentID.String())\n\t\t\tcase *connectorNode:\n\t\t\t\texprIDs = append(exprIDs, n.componentID.String()+\" (connector)\")\n\t\t\t}\n\t\t}\n\n\t\tsumData.Rows = append(sumData.Rows, zpages.SummaryPipelinesTableRowData{\n\t\t\tFullName:    c.String(),\n\t\t\tInputType:   c.Signal().String(),\n\t\t\tMutatesData: p.capabilitiesNode.getConsumer().Capabilities().MutatesData,\n\t\t\tReceivers:   recvIDs,\n\t\t\tProcessors:  procIDs,\n\t\t\tExporters:   exprIDs,\n\t\t})\n\t}\n\tsort.Slice(sumData.Rows, func(i, j int) bool {\n\t\treturn sumData.Rows[i].FullName < sumData.Rows[j].FullName\n\t})\n\tzpages.WriteHTMLPipelinesSummaryTable(w, sumData)\n\n\tif pipelineName != \"\" && componentName != \"\" && componentKind != \"\" {\n\t\tfullName := componentName\n\t\tif componentKind == \"processor\" {\n\t\t\tfullName = pipelineName + \"/\" + componentName\n\t\t}\n\t\tzpages.WriteHTMLComponentHeader(w, zpages.ComponentHeaderData{\n\t\t\tName: componentKind + \": \" + fullName,\n\t\t})\n\t\t// TODO: Add config + status info.\n\t}\n\tzpages.WriteHTMLPageFooter(w)\n}\n"
  },
  {
    "path": "service/internal/metadata/generated_feature_gates.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"go.opentelemetry.io/collector/featuregate\"\n)\n\nvar ServiceAllowNoPipelinesFeatureGate = featuregate.GlobalRegistry().MustRegister(\n\t\"service.AllowNoPipelines\",\n\tfeaturegate.StageAlpha,\n\tfeaturegate.WithRegisterDescription(\"Allow starting the Collector without starting any pipelines.\"),\n\tfeaturegate.WithRegisterReferenceURL(\"https://github.com/open-telemetry/opentelemetry-collector/pull/12613\"),\n\tfeaturegate.WithRegisterFromVersion(\"v0.122.0\"),\n)\n\nvar ServiceProfilesSupportFeatureGate = featuregate.GlobalRegistry().MustRegister(\n\t\"service.profilesSupport\",\n\tfeaturegate.StageAlpha,\n\tfeaturegate.WithRegisterDescription(\"Controls whether profiles support can be enabled\"),\n\tfeaturegate.WithRegisterReferenceURL(\"https://github.com/open-telemetry/opentelemetry-collector/pull/11477\"),\n\tfeaturegate.WithRegisterFromVersion(\"v0.112.0\"),\n)\n\nvar TelemetryUseLocalHostAsDefaultMetricsAddressFeatureGate = featuregate.GlobalRegistry().MustRegister(\n\t\"telemetry.UseLocalHostAsDefaultMetricsAddress\",\n\tfeaturegate.StageBeta,\n\tfeaturegate.WithRegisterDescription(\"Controls whether default Prometheus metrics server use localhost as the default host for their endpoints\"),\n\tfeaturegate.WithRegisterReferenceURL(\"https://github.com/open-telemetry/opentelemetry-collector/pull/11251\"),\n\tfeaturegate.WithRegisterFromVersion(\"v0.111.0\"),\n)\n\nvar TelemetryNewPipelineTelemetryFeatureGate = featuregate.GlobalRegistry().MustRegister(\n\t\"telemetry.newPipelineTelemetry\",\n\tfeaturegate.StageAlpha,\n\tfeaturegate.WithRegisterDescription(\"Injects component-identifying scope attributes in internal Collector metrics\"),\n\tfeaturegate.WithRegisterReferenceURL(\"https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/rfcs/component-universal-telemetry.md\"),\n\tfeaturegate.WithRegisterFromVersion(\"v0.123.0\"),\n)\n"
  },
  {
    "path": "service/internal/metadata/generated_telemetry.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/metric/embedded\"\n\t\"go.opentelemetry.io/otel/trace\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\nfunc Meter(settings component.TelemetrySettings) metric.Meter {\n\treturn settings.MeterProvider.Meter(\"go.opentelemetry.io/collector/service\")\n}\n\nfunc Tracer(settings component.TelemetrySettings) trace.Tracer {\n\treturn settings.TracerProvider.Tracer(\"go.opentelemetry.io/collector/service\")\n}\n\n// TelemetryBuilder provides an interface for components to report telemetry\n// as defined in metadata and user config.\ntype TelemetryBuilder struct {\n\tmeter                             metric.Meter\n\tmu                                sync.Mutex\n\tregistrations                     []metric.Registration\n\tConnectorConsumedItems            metric.Int64Counter\n\tConnectorConsumedSize             metric.Int64Counter\n\tConnectorProducedItems            metric.Int64Counter\n\tConnectorProducedSize             metric.Int64Counter\n\tExporterConsumedItems             metric.Int64Counter\n\tExporterConsumedSize              metric.Int64Counter\n\tProcessCPUSeconds                 metric.Float64ObservableCounter\n\tProcessMemoryRss                  metric.Int64ObservableGauge\n\tProcessRuntimeHeapAllocBytes      metric.Int64ObservableGauge\n\tProcessRuntimeTotalAllocBytes     metric.Int64ObservableCounter\n\tProcessRuntimeTotalSysMemoryBytes metric.Int64ObservableGauge\n\tProcessUptime                     metric.Float64ObservableCounter\n\tProcessorConsumedItems            metric.Int64Counter\n\tProcessorConsumedSize             metric.Int64Counter\n\tProcessorProducedItems            metric.Int64Counter\n\tProcessorProducedSize             metric.Int64Counter\n\tReceiverProducedItems             metric.Int64Counter\n\tReceiverProducedSize              metric.Int64Counter\n}\n\n// TelemetryBuilderOption applies changes to default builder.\ntype TelemetryBuilderOption interface {\n\tapply(*TelemetryBuilder)\n}\n\ntype telemetryBuilderOptionFunc func(mb *TelemetryBuilder)\n\nfunc (tbof telemetryBuilderOptionFunc) apply(mb *TelemetryBuilder) {\n\ttbof(mb)\n}\n\n// RegisterProcessCPUSecondsCallback sets callback for observable ProcessCPUSeconds metric.\nfunc (builder *TelemetryBuilder) RegisterProcessCPUSecondsCallback(cb metric.Float64Callback) error {\n\treg, err := builder.meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {\n\t\tcb(ctx, &observerFloat64{inst: builder.ProcessCPUSeconds, obs: o})\n\t\treturn nil\n\t}, builder.ProcessCPUSeconds)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tbuilder.registrations = append(builder.registrations, reg)\n\treturn nil\n}\n\n// RegisterProcessMemoryRssCallback sets callback for observable ProcessMemoryRss metric.\nfunc (builder *TelemetryBuilder) RegisterProcessMemoryRssCallback(cb metric.Int64Callback) error {\n\treg, err := builder.meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {\n\t\tcb(ctx, &observerInt64{inst: builder.ProcessMemoryRss, obs: o})\n\t\treturn nil\n\t}, builder.ProcessMemoryRss)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tbuilder.registrations = append(builder.registrations, reg)\n\treturn nil\n}\n\n// RegisterProcessRuntimeHeapAllocBytesCallback sets callback for observable ProcessRuntimeHeapAllocBytes metric.\nfunc (builder *TelemetryBuilder) RegisterProcessRuntimeHeapAllocBytesCallback(cb metric.Int64Callback) error {\n\treg, err := builder.meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {\n\t\tcb(ctx, &observerInt64{inst: builder.ProcessRuntimeHeapAllocBytes, obs: o})\n\t\treturn nil\n\t}, builder.ProcessRuntimeHeapAllocBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tbuilder.registrations = append(builder.registrations, reg)\n\treturn nil\n}\n\n// RegisterProcessRuntimeTotalAllocBytesCallback sets callback for observable ProcessRuntimeTotalAllocBytes metric.\nfunc (builder *TelemetryBuilder) RegisterProcessRuntimeTotalAllocBytesCallback(cb metric.Int64Callback) error {\n\treg, err := builder.meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {\n\t\tcb(ctx, &observerInt64{inst: builder.ProcessRuntimeTotalAllocBytes, obs: o})\n\t\treturn nil\n\t}, builder.ProcessRuntimeTotalAllocBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tbuilder.registrations = append(builder.registrations, reg)\n\treturn nil\n}\n\n// RegisterProcessRuntimeTotalSysMemoryBytesCallback sets callback for observable ProcessRuntimeTotalSysMemoryBytes metric.\nfunc (builder *TelemetryBuilder) RegisterProcessRuntimeTotalSysMemoryBytesCallback(cb metric.Int64Callback) error {\n\treg, err := builder.meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {\n\t\tcb(ctx, &observerInt64{inst: builder.ProcessRuntimeTotalSysMemoryBytes, obs: o})\n\t\treturn nil\n\t}, builder.ProcessRuntimeTotalSysMemoryBytes)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tbuilder.registrations = append(builder.registrations, reg)\n\treturn nil\n}\n\n// RegisterProcessUptimeCallback sets callback for observable ProcessUptime metric.\nfunc (builder *TelemetryBuilder) RegisterProcessUptimeCallback(cb metric.Float64Callback) error {\n\treg, err := builder.meter.RegisterCallback(func(ctx context.Context, o metric.Observer) error {\n\t\tcb(ctx, &observerFloat64{inst: builder.ProcessUptime, obs: o})\n\t\treturn nil\n\t}, builder.ProcessUptime)\n\tif err != nil {\n\t\treturn err\n\t}\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tbuilder.registrations = append(builder.registrations, reg)\n\treturn nil\n}\n\ntype observerInt64 struct {\n\tembedded.Int64Observer\n\tinst metric.Int64Observable\n\tobs  metric.Observer\n}\n\nfunc (oi *observerInt64) Observe(value int64, opts ...metric.ObserveOption) {\n\toi.obs.ObserveInt64(oi.inst, value, opts...)\n}\n\ntype observerFloat64 struct {\n\tembedded.Float64Observer\n\tinst metric.Float64Observable\n\tobs  metric.Observer\n}\n\nfunc (oi *observerFloat64) Observe(value float64, opts ...metric.ObserveOption) {\n\toi.obs.ObserveFloat64(oi.inst, value, opts...)\n}\n\n// Shutdown unregister all registered callbacks for async instruments.\nfunc (builder *TelemetryBuilder) Shutdown() {\n\tbuilder.mu.Lock()\n\tdefer builder.mu.Unlock()\n\tfor _, reg := range builder.registrations {\n\t\treg.Unregister()\n\t}\n}\n\n// NewTelemetryBuilder provides a struct with methods to update all internal telemetry\n// for a component\nfunc NewTelemetryBuilder(settings component.TelemetrySettings, options ...TelemetryBuilderOption) (*TelemetryBuilder, error) {\n\tbuilder := TelemetryBuilder{}\n\tfor _, op := range options {\n\t\top.apply(&builder)\n\t}\n\tbuilder.meter = Meter(settings)\n\tvar err, errs error\n\tbuilder.ConnectorConsumedItems, err = builder.meter.Int64Counter(\n\t\t\"otelcol.connector.consumed.items\",\n\t\tmetric.WithDescription(\"Number of items passed to the connector. [Development]\"),\n\t\tmetric.WithUnit(\"{item}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ConnectorConsumedSize, err = builder.meter.Int64Counter(\n\t\t\"otelcol.connector.consumed.size\",\n\t\tmetric.WithDescription(\"Size of items passed to the connector, based on ProtoMarshaler.Sizer. [Development]\"),\n\t\tmetric.WithUnit(\"{item}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ConnectorProducedItems, err = builder.meter.Int64Counter(\n\t\t\"otelcol.connector.produced.items\",\n\t\tmetric.WithDescription(\"Number of items emitted from the connector. [Development]\"),\n\t\tmetric.WithUnit(\"{item}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ConnectorProducedSize, err = builder.meter.Int64Counter(\n\t\t\"otelcol.connector.produced.size\",\n\t\tmetric.WithDescription(\"Size of items emitted from the connector, based on ProtoMarshaler.Sizer. [Development]\"),\n\t\tmetric.WithUnit(\"{item}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ExporterConsumedItems, err = builder.meter.Int64Counter(\n\t\t\"otelcol.exporter.consumed.items\",\n\t\tmetric.WithDescription(\"Number of items passed to the exporter. [Development]\"),\n\t\tmetric.WithUnit(\"{item}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ExporterConsumedSize, err = builder.meter.Int64Counter(\n\t\t\"otelcol.exporter.consumed.size\",\n\t\tmetric.WithDescription(\"Size of items passed to the exporter, based on ProtoMarshaler.Sizer. [Development]\"),\n\t\tmetric.WithUnit(\"{item}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessCPUSeconds, err = builder.meter.Float64ObservableCounter(\n\t\t\"otelcol_process_cpu_seconds\",\n\t\tmetric.WithDescription(\"Total CPU user and system time in seconds [Alpha]\"),\n\t\tmetric.WithUnit(\"s\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessMemoryRss, err = builder.meter.Int64ObservableGauge(\n\t\t\"otelcol_process_memory_rss\",\n\t\tmetric.WithDescription(\"Total physical memory (resident set size) [Alpha]\"),\n\t\tmetric.WithUnit(\"By\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessRuntimeHeapAllocBytes, err = builder.meter.Int64ObservableGauge(\n\t\t\"otelcol_process_runtime_heap_alloc_bytes\",\n\t\tmetric.WithDescription(\"Bytes of allocated heap objects (see 'go doc runtime.MemStats.HeapAlloc') [Alpha]\"),\n\t\tmetric.WithUnit(\"By\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessRuntimeTotalAllocBytes, err = builder.meter.Int64ObservableCounter(\n\t\t\"otelcol_process_runtime_total_alloc_bytes\",\n\t\tmetric.WithDescription(\"Cumulative bytes allocated for heap objects (see 'go doc runtime.MemStats.TotalAlloc') [Alpha]\"),\n\t\tmetric.WithUnit(\"By\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessRuntimeTotalSysMemoryBytes, err = builder.meter.Int64ObservableGauge(\n\t\t\"otelcol_process_runtime_total_sys_memory_bytes\",\n\t\tmetric.WithDescription(\"Total bytes of memory obtained from the OS (see 'go doc runtime.MemStats.Sys') [Alpha]\"),\n\t\tmetric.WithUnit(\"By\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessUptime, err = builder.meter.Float64ObservableCounter(\n\t\t\"otelcol_process_uptime\",\n\t\tmetric.WithDescription(\"Uptime of the process [Alpha]\"),\n\t\tmetric.WithUnit(\"s\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessorConsumedItems, err = builder.meter.Int64Counter(\n\t\t\"otelcol.processor.consumed.items\",\n\t\tmetric.WithDescription(\"Number of items passed to the processor. [Development]\"),\n\t\tmetric.WithUnit(\"{item}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessorConsumedSize, err = builder.meter.Int64Counter(\n\t\t\"otelcol.processor.consumed.size\",\n\t\tmetric.WithDescription(\"Size of items passed to the processor, based on ProtoMarshaler.Sizer. [Development]\"),\n\t\tmetric.WithUnit(\"{item}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessorProducedItems, err = builder.meter.Int64Counter(\n\t\t\"otelcol.processor.produced.items\",\n\t\tmetric.WithDescription(\"Number of items emitted from the processor. [Development]\"),\n\t\tmetric.WithUnit(\"{item}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ProcessorProducedSize, err = builder.meter.Int64Counter(\n\t\t\"otelcol.processor.produced.size\",\n\t\tmetric.WithDescription(\"Size of items emitted from the processor, based on ProtoMarshaler.Sizer. [Development]\"),\n\t\tmetric.WithUnit(\"{item}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ReceiverProducedItems, err = builder.meter.Int64Counter(\n\t\t\"otelcol.receiver.produced.items\",\n\t\tmetric.WithDescription(\"Number of items emitted from the receiver. [Development]\"),\n\t\tmetric.WithUnit(\"{item}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\tbuilder.ReceiverProducedSize, err = builder.meter.Int64Counter(\n\t\t\"otelcol.receiver.produced.size\",\n\t\tmetric.WithDescription(\"Size of items emitted from the receiver, based on ProtoMarshaler.Sizer. [Development]\"),\n\t\tmetric.WithUnit(\"{item}\"),\n\t)\n\terrs = errors.Join(errs, err)\n\treturn &builder, errs\n}\n"
  },
  {
    "path": "service/internal/metadata/generated_telemetry_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadata\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/metric\"\n\tembeddedmetric \"go.opentelemetry.io/otel/metric/embedded\"\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\t\"go.opentelemetry.io/otel/trace\"\n\tembeddedtrace \"go.opentelemetry.io/otel/trace/embedded\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\ntype mockMeter struct {\n\tnoopmetric.Meter\n\tname string\n}\ntype mockMeterProvider struct {\n\tembeddedmetric.MeterProvider\n}\n\nfunc (m mockMeterProvider) Meter(name string, opts ...metric.MeterOption) metric.Meter {\n\treturn mockMeter{name: name}\n}\n\ntype mockTracer struct {\n\tnooptrace.Tracer\n\tname string\n}\n\ntype mockTracerProvider struct {\n\tembeddedtrace.TracerProvider\n}\n\nfunc (m mockTracerProvider) Tracer(name string, opts ...trace.TracerOption) trace.Tracer {\n\treturn mockTracer{name: name}\n}\n\nfunc TestProviders(t *testing.T) {\n\tset := component.TelemetrySettings{\n\t\tMeterProvider:  mockMeterProvider{},\n\t\tTracerProvider: mockTracerProvider{},\n\t}\n\n\tmeter := Meter(set)\n\tif m, ok := meter.(mockMeter); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/service\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockMeter\")\n\t}\n\n\ttracer := Tracer(set)\n\tif m, ok := tracer.(mockTracer); ok {\n\t\trequire.Equal(t, \"go.opentelemetry.io/collector/service\", m.name)\n\t} else {\n\t\trequire.Fail(t, \"returned Meter not mockTracer\")\n\t}\n}\n\nfunc TestNewTelemetryBuilder(t *testing.T) {\n\tset := componenttest.NewNopTelemetrySettings()\n\tapplied := false\n\t_, err := NewTelemetryBuilder(set, telemetryBuilderOptionFunc(func(b *TelemetryBuilder) {\n\t\tapplied = true\n\t}))\n\trequire.NoError(t, err)\n\trequire.True(t, applied)\n}\n"
  },
  {
    "path": "service/internal/metadatatest/generated_telemetrytest.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\nfunc AssertEqualConnectorConsumedItems(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol.connector.consumed.items\",\n\t\tDescription: \"Number of items passed to the connector. [Development]\",\n\t\tUnit:        \"{item}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol.connector.consumed.items\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualConnectorConsumedSize(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol.connector.consumed.size\",\n\t\tDescription: \"Size of items passed to the connector, based on ProtoMarshaler.Sizer. [Development]\",\n\t\tUnit:        \"{item}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol.connector.consumed.size\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualConnectorProducedItems(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol.connector.produced.items\",\n\t\tDescription: \"Number of items emitted from the connector. [Development]\",\n\t\tUnit:        \"{item}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol.connector.produced.items\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualConnectorProducedSize(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol.connector.produced.size\",\n\t\tDescription: \"Size of items emitted from the connector, based on ProtoMarshaler.Sizer. [Development]\",\n\t\tUnit:        \"{item}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol.connector.produced.size\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualExporterConsumedItems(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol.exporter.consumed.items\",\n\t\tDescription: \"Number of items passed to the exporter. [Development]\",\n\t\tUnit:        \"{item}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol.exporter.consumed.items\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualExporterConsumedSize(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol.exporter.consumed.size\",\n\t\tDescription: \"Size of items passed to the exporter, based on ProtoMarshaler.Sizer. [Development]\",\n\t\tUnit:        \"{item}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol.exporter.consumed.size\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessCPUSeconds(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[float64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_process_cpu_seconds\",\n\t\tDescription: \"Total CPU user and system time in seconds [Alpha]\",\n\t\tUnit:        \"s\",\n\t\tData: metricdata.Sum[float64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_process_cpu_seconds\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessMemoryRss(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_process_memory_rss\",\n\t\tDescription: \"Total physical memory (resident set size) [Alpha]\",\n\t\tUnit:        \"By\",\n\t\tData: metricdata.Gauge[int64]{\n\t\t\tDataPoints: dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_process_memory_rss\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessRuntimeHeapAllocBytes(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_process_runtime_heap_alloc_bytes\",\n\t\tDescription: \"Bytes of allocated heap objects (see 'go doc runtime.MemStats.HeapAlloc') [Alpha]\",\n\t\tUnit:        \"By\",\n\t\tData: metricdata.Gauge[int64]{\n\t\t\tDataPoints: dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_process_runtime_heap_alloc_bytes\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessRuntimeTotalAllocBytes(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_process_runtime_total_alloc_bytes\",\n\t\tDescription: \"Cumulative bytes allocated for heap objects (see 'go doc runtime.MemStats.TotalAlloc') [Alpha]\",\n\t\tUnit:        \"By\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_process_runtime_total_alloc_bytes\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessRuntimeTotalSysMemoryBytes(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_process_runtime_total_sys_memory_bytes\",\n\t\tDescription: \"Total bytes of memory obtained from the OS (see 'go doc runtime.MemStats.Sys') [Alpha]\",\n\t\tUnit:        \"By\",\n\t\tData: metricdata.Gauge[int64]{\n\t\t\tDataPoints: dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_process_runtime_total_sys_memory_bytes\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessUptime(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[float64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol_process_uptime\",\n\t\tDescription: \"Uptime of the process [Alpha]\",\n\t\tUnit:        \"s\",\n\t\tData: metricdata.Sum[float64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol_process_uptime\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessorConsumedItems(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol.processor.consumed.items\",\n\t\tDescription: \"Number of items passed to the processor. [Development]\",\n\t\tUnit:        \"{item}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol.processor.consumed.items\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessorConsumedSize(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol.processor.consumed.size\",\n\t\tDescription: \"Size of items passed to the processor, based on ProtoMarshaler.Sizer. [Development]\",\n\t\tUnit:        \"{item}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol.processor.consumed.size\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessorProducedItems(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol.processor.produced.items\",\n\t\tDescription: \"Number of items emitted from the processor. [Development]\",\n\t\tUnit:        \"{item}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol.processor.produced.items\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualProcessorProducedSize(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol.processor.produced.size\",\n\t\tDescription: \"Size of items emitted from the processor, based on ProtoMarshaler.Sizer. [Development]\",\n\t\tUnit:        \"{item}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol.processor.produced.size\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualReceiverProducedItems(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol.receiver.produced.items\",\n\t\tDescription: \"Number of items emitted from the receiver. [Development]\",\n\t\tUnit:        \"{item}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol.receiver.produced.items\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n\nfunc AssertEqualReceiverProducedSize(t *testing.T, tt *componenttest.Telemetry, dps []metricdata.DataPoint[int64], opts ...metricdatatest.Option) {\n\twant := metricdata.Metrics{\n\t\tName:        \"otelcol.receiver.produced.size\",\n\t\tDescription: \"Size of items emitted from the receiver, based on ProtoMarshaler.Sizer. [Development]\",\n\t\tUnit:        \"{item}\",\n\t\tData: metricdata.Sum[int64]{\n\t\t\tTemporality: metricdata.CumulativeTemporality,\n\t\t\tIsMonotonic: true,\n\t\t\tDataPoints:  dps,\n\t\t},\n\t}\n\tgot, err := tt.GetMetric(\"otelcol.receiver.produced.size\")\n\trequire.NoError(t, err)\n\tmetricdatatest.AssertEqual(t, want, got, opts...)\n}\n"
  },
  {
    "path": "service/internal/metadatatest/generated_telemetrytest_test.go",
    "content": "// Code generated by mdatagen. DO NOT EDIT.\n\npackage metadatatest\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n)\n\nfunc TestSetupTelemetry(t *testing.T) {\n\ttestTel := componenttest.NewTelemetry()\n\ttb, err := metadata.NewTelemetryBuilder(testTel.NewTelemetrySettings())\n\trequire.NoError(t, err)\n\tdefer tb.Shutdown()\n\trequire.NoError(t, tb.RegisterProcessCPUSecondsCallback(func(_ context.Context, observer metric.Float64Observer) error {\n\t\tobserver.Observe(1)\n\t\treturn nil\n\t}))\n\trequire.NoError(t, tb.RegisterProcessMemoryRssCallback(func(_ context.Context, observer metric.Int64Observer) error {\n\t\tobserver.Observe(1)\n\t\treturn nil\n\t}))\n\trequire.NoError(t, tb.RegisterProcessRuntimeHeapAllocBytesCallback(func(_ context.Context, observer metric.Int64Observer) error {\n\t\tobserver.Observe(1)\n\t\treturn nil\n\t}))\n\trequire.NoError(t, tb.RegisterProcessRuntimeTotalAllocBytesCallback(func(_ context.Context, observer metric.Int64Observer) error {\n\t\tobserver.Observe(1)\n\t\treturn nil\n\t}))\n\trequire.NoError(t, tb.RegisterProcessRuntimeTotalSysMemoryBytesCallback(func(_ context.Context, observer metric.Int64Observer) error {\n\t\tobserver.Observe(1)\n\t\treturn nil\n\t}))\n\trequire.NoError(t, tb.RegisterProcessUptimeCallback(func(_ context.Context, observer metric.Float64Observer) error {\n\t\tobserver.Observe(1)\n\t\treturn nil\n\t}))\n\ttb.ConnectorConsumedItems.Add(context.Background(), 1)\n\ttb.ConnectorConsumedSize.Add(context.Background(), 1)\n\ttb.ConnectorProducedItems.Add(context.Background(), 1)\n\ttb.ConnectorProducedSize.Add(context.Background(), 1)\n\ttb.ExporterConsumedItems.Add(context.Background(), 1)\n\ttb.ExporterConsumedSize.Add(context.Background(), 1)\n\ttb.ProcessorConsumedItems.Add(context.Background(), 1)\n\ttb.ProcessorConsumedSize.Add(context.Background(), 1)\n\ttb.ProcessorProducedItems.Add(context.Background(), 1)\n\ttb.ProcessorProducedSize.Add(context.Background(), 1)\n\ttb.ReceiverProducedItems.Add(context.Background(), 1)\n\ttb.ReceiverProducedSize.Add(context.Background(), 1)\n\tAssertEqualConnectorConsumedItems(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualConnectorConsumedSize(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualConnectorProducedItems(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualConnectorProducedSize(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualExporterConsumedItems(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualExporterConsumedSize(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessCPUSeconds(t, testTel,\n\t\t[]metricdata.DataPoint[float64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessMemoryRss(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessRuntimeHeapAllocBytes(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessRuntimeTotalAllocBytes(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessRuntimeTotalSysMemoryBytes(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessUptime(t, testTel,\n\t\t[]metricdata.DataPoint[float64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessorConsumedItems(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessorConsumedSize(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessorProducedItems(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualProcessorProducedSize(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualReceiverProducedItems(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\tAssertEqualReceiverProducedSize(t, testTel,\n\t\t[]metricdata.DataPoint[int64]{{Value: 1}},\n\t\tmetricdatatest.IgnoreTimestamp())\n\n\trequire.NoError(t, testTel.Shutdown(context.Background()))\n}\n"
  },
  {
    "path": "service/internal/metricviews/views.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage metricviews // import \"go.opentelemetry.io/collector/service/internal/metricviews\"\n\nimport (\n\tconfig \"go.opentelemetry.io/contrib/otelconf/v0.3.0\"\n\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n)\n\n// DefaultViews builds the default metric views used by the service.\nfunc DefaultViews(level configtelemetry.Level) []config.View {\n\tviews := []config.View{}\n\n\tif level < configtelemetry.LevelDetailed {\n\t\t// Drop all otelhttp and otelgrpc metrics if the level is not detailed.\n\t\tviews = append(views,\n\t\t\tdropViewOption(&config.ViewSelector{\n\t\t\t\tMeterName: ptr(\"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc\"),\n\t\t\t}),\n\t\t\tdropViewOption(&config.ViewSelector{\n\t\t\t\tMeterName: ptr(\"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\"),\n\t\t\t}),\n\t\t\t// Drop duration metric if the level is not detailed\n\t\t\tdropViewOption(&config.ViewSelector{\n\t\t\t\tMeterName:      ptr(\"go.opentelemetry.io/collector/processor/processorhelper\"),\n\t\t\t\tInstrumentName: ptr(\"otelcol_processor_internal_duration\"),\n\t\t\t}),\n\t\t)\n\t}\n\n\t// otel-arrow library metrics\n\t// See https://github.com/open-telemetry/otel-arrow/blob/c39257/pkg/otel/arrow_record/consumer.go#L174-L176\n\tif level < configtelemetry.LevelNormal {\n\t\tscope := ptr(\"otel-arrow/pkg/otel/arrow_record\")\n\t\tviews = append(views,\n\t\t\tdropViewOption(&config.ViewSelector{\n\t\t\t\tMeterName:      scope,\n\t\t\t\tInstrumentName: ptr(\"arrow_batch_records\"),\n\t\t\t}),\n\t\t\tdropViewOption(&config.ViewSelector{\n\t\t\t\tMeterName:      scope,\n\t\t\t\tInstrumentName: ptr(\"arrow_schema_resets\"),\n\t\t\t}),\n\t\t\tdropViewOption(&config.ViewSelector{\n\t\t\t\tMeterName:      scope,\n\t\t\t\tInstrumentName: ptr(\"arrow_memory_inuse\"),\n\t\t\t}),\n\t\t)\n\t}\n\n\t// contrib's internal/otelarrow/netstats metrics\n\t// See\n\t// - https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/a25f05/internal/otelarrow/netstats/netstats.go#L130\n\t// - https://github.com/open-telemetry/opentelemetry-collector-contrib/blob/a25f05/internal/otelarrow/netstats/netstats.go#L165\n\tif level < configtelemetry.LevelDetailed {\n\t\tscope := ptr(\"github.com/open-telemetry/opentelemetry-collector-contrib/internal/otelarrow/netstats\")\n\n\t\tviews = append(views,\n\t\t\t// Compressed size metrics.\n\t\t\tdropViewOption(&config.ViewSelector{\n\t\t\t\tMeterName:      scope,\n\t\t\t\tInstrumentName: ptr(\"otelcol_*_compressed_size\"),\n\t\t\t}),\n\t\t\tdropViewOption(&config.ViewSelector{\n\t\t\t\tMeterName:      scope,\n\t\t\t\tInstrumentName: ptr(\"otelcol_*_compressed_size\"),\n\t\t\t}),\n\n\t\t\t// makeRecvMetrics for exporters.\n\t\t\tdropViewOption(&config.ViewSelector{\n\t\t\t\tMeterName:      scope,\n\t\t\t\tInstrumentName: ptr(\"otelcol_exporter_recv\"),\n\t\t\t}),\n\t\t\tdropViewOption(&config.ViewSelector{\n\t\t\t\tMeterName:      scope,\n\t\t\t\tInstrumentName: ptr(\"otelcol_exporter_recv_wire\"),\n\t\t\t}),\n\n\t\t\t// makeSentMetrics for receivers.\n\t\t\tdropViewOption(&config.ViewSelector{\n\t\t\t\tMeterName:      scope,\n\t\t\t\tInstrumentName: ptr(\"otelcol_receiver_sent\"),\n\t\t\t}),\n\t\t\tdropViewOption(&config.ViewSelector{\n\t\t\t\tMeterName:      scope,\n\t\t\t\tInstrumentName: ptr(\"otelcol_receiver_sent_wire\"),\n\t\t\t}),\n\t\t)\n\t}\n\n\t// Batch exporter metrics\n\tif level < configtelemetry.LevelDetailed {\n\t\tscope := ptr(\"go.opentelemetry.io/collector/exporter/exporterhelper\")\n\t\tviews = append(views,\n\t\t\tdropViewOption(&config.ViewSelector{\n\t\t\t\tMeterName:      scope,\n\t\t\t\tInstrumentName: ptr(\"otelcol_exporter_queue_batch_send_size_bytes\"),\n\t\t\t}),\n\t\t\tdropViewOption(&config.ViewSelector{\n\t\t\t\tMeterName:      scope,\n\t\t\t\tInstrumentName: ptr(\"otelcol_exporter_queue_batch_send_size\"),\n\t\t\t}),\n\t\t\tconfig.View{\n\t\t\t\tSelector: &config.ViewSelector{\n\t\t\t\t\tMeterName:      scope,\n\t\t\t\t\tInstrumentName: ptr(\"otelcol_exporter_send_failed_*\"),\n\t\t\t\t},\n\t\t\t\tStream: &config.ViewStream{\n\t\t\t\t\tAttributeKeys: &config.IncludeExclude{\n\t\t\t\t\t\tExcluded: []string{\"error.type\", \"error.permanent\"},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t}\n\n\t// Batch processor metrics\n\tscope := ptr(\"go.opentelemetry.io/collector/processor/batchprocessor\")\n\tif level < configtelemetry.LevelNormal {\n\t\tviews = append(views, dropViewOption(&config.ViewSelector{\n\t\t\tMeterName: scope,\n\t\t}))\n\t} else if level < configtelemetry.LevelDetailed {\n\t\tviews = append(views, dropViewOption(&config.ViewSelector{\n\t\t\tMeterName:      scope,\n\t\t\tInstrumentName: ptr(\"otelcol_processor_batch_batch_send_size_bytes\"),\n\t\t}))\n\t}\n\n\t// Internal graph metrics\n\tgraphScope := ptr(\"go.opentelemetry.io/collector/service\")\n\tif level < configtelemetry.LevelDetailed {\n\t\tviews = append(views,\n\t\t\tdropViewOption(&config.ViewSelector{\n\t\t\t\tMeterName:      graphScope,\n\t\t\t\tInstrumentName: ptr(\"otelcol.*.consumed.size\"),\n\t\t\t}),\n\t\t\tdropViewOption(&config.ViewSelector{\n\t\t\t\tMeterName:      graphScope,\n\t\t\t\tInstrumentName: ptr(\"otelcol.*.produced.size\"),\n\t\t\t}))\n\t}\n\n\treturn views\n}\n\nfunc dropViewOption(selector *config.ViewSelector) config.View {\n\treturn config.View{\n\t\tSelector: selector,\n\t\tStream: &config.ViewStream{\n\t\t\tAggregation: &config.ViewStreamAggregation{\n\t\t\t\tDrop: config.ViewStreamAggregationDrop{},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc ptr[T any](v T) *T {\n\treturn &v\n}\n"
  },
  {
    "path": "service/internal/metricviews/views_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage metricviews\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n)\n\nfunc TestDefaultViews(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname  string\n\t\tlevel configtelemetry.Level\n\n\t\twantViewsCount int\n\t}{\n\t\t{\n\t\t\tname:           \"None\",\n\t\t\tlevel:          configtelemetry.LevelNone,\n\t\t\twantViewsCount: 18,\n\t\t},\n\t\t{\n\t\t\tname:           \"Basic\",\n\t\t\tlevel:          configtelemetry.LevelBasic,\n\t\t\twantViewsCount: 18,\n\t\t},\n\t\t{\n\t\t\tname:           \"Normal\",\n\t\t\tlevel:          configtelemetry.LevelNormal,\n\t\t\twantViewsCount: 15,\n\t\t},\n\t\t{\n\t\t\tname:           \"Detailed\",\n\t\t\tlevel:          configtelemetry.LevelDetailed,\n\t\t\twantViewsCount: 0,\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tviews := DefaultViews(tt.level)\n\t\t\tassert.Len(t, views, tt.wantViewsCount)\n\t\t})\n\t}\n}\n\nfunc TestDefaultViewsFiltersSendFailedAttributes(t *testing.T) {\n\ttests := []struct {\n\t\tname                         string\n\t\tlevel                        configtelemetry.Level\n\t\texpectSendFailedFilteredView bool\n\t}{\n\t\t{\n\t\t\tname:                         \"basic level filters send_failed attributes\",\n\t\t\tlevel:                        configtelemetry.LevelBasic,\n\t\t\texpectSendFailedFilteredView: true,\n\t\t},\n\t\t{\n\t\t\tname:                         \"normal level filters send_failed attributes\",\n\t\t\tlevel:                        configtelemetry.LevelNormal,\n\t\t\texpectSendFailedFilteredView: true,\n\t\t},\n\t\t{\n\t\t\tname:                         \"detailed level does not filter send_failed attributes\",\n\t\t\tlevel:                        configtelemetry.LevelDetailed,\n\t\t\texpectSendFailedFilteredView: false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tviews := DefaultViews(tt.level)\n\n\t\t\tfoundSendFailedView := false\n\t\t\tfor _, view := range views {\n\t\t\t\tif view.Selector == nil ||\n\t\t\t\t\tview.Selector.InstrumentName == nil ||\n\t\t\t\t\t*view.Selector.InstrumentName != \"otelcol_exporter_send_failed_*\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\tfoundSendFailedView = true\n\t\t\t\trequire.NotNil(t, view.Stream, \"send_failed view should have a stream\")\n\t\t\t\trequire.NotNil(t, view.Stream.AttributeKeys, \"send_failed view should have attribute keys\")\n\t\t\t\trequire.Equal(t, []string{\"error.type\", \"error.permanent\"}, view.Stream.AttributeKeys.Excluded,\n\t\t\t\t\t\"send_failed view should exclude 'error.type' and 'error.permanent' attributes\")\n\t\t\t\tbreak\n\t\t\t}\n\n\t\t\tif tt.expectSendFailedFilteredView {\n\t\t\t\tassert.True(t, foundSendFailedView,\n\t\t\t\t\t\"Expected to find send_failed attribute filtering view at level %s\", tt.level)\n\t\t\t} else {\n\t\t\t\tassert.False(t, foundSendFailedView,\n\t\t\t\t\t\"Did not expect to find send_failed attribute filtering view at level %s\", tt.level)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestDefaultViews_BatchExporterMetrics(t *testing.T) {\n\ttests := []struct {\n\t\tname             string\n\t\tlevel            configtelemetry.Level\n\t\tshouldDropBucket bool\n\t\tshouldDropBytes  bool\n\t}{\n\t\t{\n\t\t\tname:             \"basic level drops bytes\",\n\t\t\tlevel:            configtelemetry.LevelBasic,\n\t\t\tshouldDropBucket: true,\n\t\t\tshouldDropBytes:  true,\n\t\t},\n\t\t{\n\t\t\tname:             \"normal level drops bytes\",\n\t\t\tlevel:            configtelemetry.LevelNormal,\n\t\t\tshouldDropBucket: true,\n\t\t\tshouldDropBytes:  true,\n\t\t},\n\t\t{\n\t\t\tname:             \"detailed level does not drop bytes\",\n\t\t\tlevel:            configtelemetry.LevelDetailed,\n\t\t\tshouldDropBucket: false,\n\t\t\tshouldDropBytes:  false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tviews := DefaultViews(tt.level)\n\n\t\t\texporterHelperScope := \"go.opentelemetry.io/collector/exporter/exporterhelper\"\n\t\t\tbucketMetricName := \"otelcol_exporter_queue_batch_send_size\"\n\t\t\tbytesMetricName := \"otelcol_exporter_queue_batch_send_size_bytes\"\n\n\t\t\tvar foundBucketDrop, foundBytesDrop bool\n\t\t\tfor _, view := range views {\n\t\t\t\tif view.Selector != nil {\n\t\t\t\t\tif view.Selector.MeterName != nil && *view.Selector.MeterName == exporterHelperScope {\n\t\t\t\t\t\tif view.Selector.InstrumentName != nil {\n\t\t\t\t\t\t\tif *view.Selector.InstrumentName == bucketMetricName {\n\t\t\t\t\t\t\t\tfoundBucketDrop = true\n\t\t\t\t\t\t\t\t// Verify it's a drop view\n\t\t\t\t\t\t\t\trequire.NotNil(t, view.Stream)\n\t\t\t\t\t\t\t\trequire.NotNil(t, view.Stream.Aggregation)\n\t\t\t\t\t\t\t\trequire.NotNil(t, view.Stream.Aggregation.Drop)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tif *view.Selector.InstrumentName == bytesMetricName {\n\t\t\t\t\t\t\t\tfoundBytesDrop = true\n\t\t\t\t\t\t\t\t// Verify it's a drop view\n\t\t\t\t\t\t\t\trequire.NotNil(t, view.Stream)\n\t\t\t\t\t\t\t\trequire.NotNil(t, view.Stream.Aggregation)\n\t\t\t\t\t\t\t\trequire.NotNil(t, view.Stream.Aggregation.Drop)\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tassert.Equal(t, tt.shouldDropBucket, foundBucketDrop,\n\t\t\t\t\"bucket metric drop view should be %v for level %v\", tt.shouldDropBucket, tt.level)\n\t\t\tassert.Equal(t, tt.shouldDropBytes, foundBytesDrop,\n\t\t\t\t\"bytes metric drop view should be %v for level %v\", tt.shouldDropBytes, tt.level)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "service/internal/moduleinfo/moduleinfo.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage moduleinfo // import \"go.opentelemetry.io/collector/service/internal/moduleinfo\"\n\nimport \"go.opentelemetry.io/collector/component\"\n\ntype ModuleInfo struct {\n\t// BuilderRef is the raw string passed in the builder configuration used to build this service.\n\tBuilderRef string\n}\n\n// ModuleInfos describes the go module for each component.\ntype ModuleInfos struct {\n\tReceiver  map[component.Type]ModuleInfo\n\tProcessor map[component.Type]ModuleInfo\n\tExporter  map[component.Type]ModuleInfo\n\tExtension map[component.Type]ModuleInfo\n\tConnector map[component.Type]ModuleInfo\n}\n"
  },
  {
    "path": "service/internal/obsconsumer/consumer_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage obsconsumer_test\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\tsdkmetric \"go.opentelemetry.io/otel/sdk/metric\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/service/internal/obsconsumer\"\n)\n\ntype failingConsumer struct {\n\terr error\n}\n\nvar (\n\t_ consumer.Metrics   = (*failingConsumer)(nil)\n\t_ consumer.Logs      = (*failingConsumer)(nil)\n\t_ consumer.Traces    = (*failingConsumer)(nil)\n\t_ xconsumer.Profiles = (*failingConsumer)(nil)\n)\n\nfunc (*failingConsumer) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{}\n}\n\nfunc (fc *failingConsumer) ConsumeMetrics(_ context.Context, _ pmetric.Metrics) error {\n\treturn fc.err\n}\n\nfunc (fc *failingConsumer) ConsumeLogs(_ context.Context, _ plog.Logs) error {\n\treturn fc.err\n}\n\nfunc (fc *failingConsumer) ConsumeTraces(_ context.Context, _ ptrace.Traces) error {\n\treturn fc.err\n}\n\nfunc (fc *failingConsumer) ConsumeProfiles(_ context.Context, _ pprofile.Profiles) error {\n\treturn fc.err\n}\n\nfunc TestConsumeRefused(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\toriginalErr := errors.New(\"test error\")\n\texpectedErr := consumererror.NewDownstream(originalErr)\n\tmockConsumer := &failingConsumer{err: originalErr}\n\n\t// Use delta temporality so sums don't accumulate across tests\n\treader := sdkmetric.NewManualReader(sdkmetric.WithTemporalitySelector(func(_ sdkmetric.InstrumentKind) metricdata.Temporality {\n\t\treturn metricdata.DeltaTemporality\n\t}))\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\treceivedItemsCounter, err := meter.Int64Counter(\"received.items\")\n\trequire.NoError(t, err)\n\treceivedSizeCounter, err := meter.Int64Counter(\"received.size\")\n\trequire.NoError(t, err)\n\n\tproducedItemsCounter, err := meter.Int64Counter(\"produced.items\")\n\trequire.NoError(t, err)\n\tproducedSizeConter, err := meter.Int64Counter(\"produced.size\")\n\trequire.NoError(t, err)\n\n\tlogger := zap.NewNop()\n\treceivedSettings := obsconsumer.Settings{ItemCounter: receivedItemsCounter, SizeCounter: receivedSizeCounter, Logger: logger}\n\tproducedSettings := obsconsumer.Settings{ItemCounter: producedItemsCounter, SizeCounter: producedSizeConter, Logger: logger}\n\n\ttype testCase struct {\n\t\tname         string\n\t\ttestConsumer func() error\n\t}\n\n\ttestCases := []testCase{\n\t\t{\n\t\t\tname: \"metrics\",\n\t\t\ttestConsumer: func() error {\n\t\t\t\tconsumer1 := obsconsumer.NewMetrics(mockConsumer, receivedSettings)\n\t\t\t\tconsumer2 := obsconsumer.NewMetrics(consumer1, producedSettings)\n\t\t\t\tmd := pmetric.NewMetrics()\n\t\t\t\tmd.ResourceMetrics().AppendEmpty().ScopeMetrics().AppendEmpty().Metrics().AppendEmpty().SetEmptyGauge().DataPoints().AppendEmpty()\n\t\t\t\treturn consumer2.ConsumeMetrics(ctx, md)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"logs\",\n\t\t\ttestConsumer: func() error {\n\t\t\t\tconsumer1 := obsconsumer.NewLogs(mockConsumer, receivedSettings)\n\t\t\t\tconsumer2 := obsconsumer.NewLogs(consumer1, producedSettings)\n\t\t\t\tld := plog.NewLogs()\n\t\t\t\tld.ResourceLogs().AppendEmpty().ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()\n\t\t\t\treturn consumer2.ConsumeLogs(ctx, ld)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"traces\",\n\t\t\ttestConsumer: func() error {\n\t\t\t\tconsumer1 := obsconsumer.NewTraces(mockConsumer, receivedSettings)\n\t\t\t\tconsumer2 := obsconsumer.NewTraces(consumer1, producedSettings)\n\t\t\t\ttd := ptrace.NewTraces()\n\t\t\t\ttd.ResourceSpans().AppendEmpty().ScopeSpans().AppendEmpty().Spans().AppendEmpty()\n\t\t\t\treturn consumer2.ConsumeTraces(ctx, td)\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"profiles\",\n\t\t\ttestConsumer: func() error {\n\t\t\t\tconsumer1 := obsconsumer.NewProfiles(mockConsumer, receivedSettings)\n\t\t\t\tconsumer2 := obsconsumer.NewProfiles(consumer1, producedSettings)\n\t\t\t\tpd := pprofile.NewProfiles()\n\t\t\t\tpd.ResourceProfiles().AppendEmpty().ScopeProfiles().AppendEmpty().Profiles().AppendEmpty().Samples().AppendEmpty()\n\t\t\t\treturn consumer2.ConsumeProfiles(ctx, pd)\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tc := range testCases {\n\t\tt.Run(tc.name, func(t *testing.T) {\n\t\t\terr := tc.testConsumer()\n\t\t\tassert.Equal(t, expectedErr, err)\n\n\t\t\tvar rm metricdata.ResourceMetrics\n\t\t\terr = reader.Collect(ctx, &rm)\n\t\t\trequire.NoError(t, err)\n\t\t\trequire.Len(t, rm.ScopeMetrics, 1)\n\t\t\trequire.Len(t, rm.ScopeMetrics[0].Metrics, 4)\n\n\t\t\tvar receivedItemMetric, receivedSizeMetric metricdata.Metrics\n\t\t\tvar producedItemMetric, producedSizeMetric metricdata.Metrics\n\t\t\tfor _, m := range rm.ScopeMetrics[0].Metrics {\n\t\t\t\tswitch m.Name {\n\t\t\t\tcase \"received.items\":\n\t\t\t\t\treceivedItemMetric = m\n\t\t\t\tcase \"received.size\":\n\t\t\t\t\treceivedSizeMetric = m\n\t\t\t\tcase \"produced.items\":\n\t\t\t\t\tproducedItemMetric = m\n\t\t\t\tcase \"produced.size\":\n\t\t\t\t\tproducedSizeMetric = m\n\t\t\t\t}\n\t\t\t}\n\t\t\trequire.NotNil(t, receivedItemMetric)\n\t\t\trequire.NotNil(t, receivedSizeMetric)\n\t\t\trequire.NotNil(t, producedItemMetric)\n\t\t\trequire.NotNil(t, producedSizeMetric)\n\n\t\t\tdata := receivedItemMetric.Data.(metricdata.Sum[int64])\n\t\t\trequire.Len(t, data.DataPoints, 1)\n\t\t\trequire.Equal(t, int64(1), data.DataPoints[0].Value)\n\t\t\tattrs := data.DataPoints[0].Attributes\n\t\t\trequire.Equal(t, 1, attrs.Len())\n\t\t\tval, ok := attrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\t\t\trequire.True(t, ok)\n\t\t\trequire.Equal(t, \"failure\", val.Emit())\n\n\t\t\tdata = receivedSizeMetric.Data.(metricdata.Sum[int64])\n\t\t\trequire.Len(t, data.DataPoints, 1)\n\t\t\trequire.Positive(t, data.DataPoints[0].Value)\n\t\t\tattrs = data.DataPoints[0].Attributes\n\t\t\trequire.Equal(t, 1, attrs.Len())\n\t\t\tval, ok = attrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\t\t\trequire.True(t, ok)\n\t\t\trequire.Equal(t, \"failure\", val.Emit())\n\n\t\t\tdata = producedItemMetric.Data.(metricdata.Sum[int64])\n\t\t\trequire.Len(t, data.DataPoints, 1)\n\t\t\trequire.Equal(t, int64(1), data.DataPoints[0].Value)\n\t\t\tattrs = data.DataPoints[0].Attributes\n\t\t\trequire.Equal(t, 1, attrs.Len())\n\t\t\tval, ok = attrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\t\t\trequire.True(t, ok)\n\t\t\trequire.Equal(t, \"refused\", val.Emit())\n\n\t\t\tdata = producedSizeMetric.Data.(metricdata.Sum[int64])\n\t\t\trequire.Len(t, data.DataPoints, 1)\n\t\t\trequire.Positive(t, data.DataPoints[0].Value)\n\t\t\tattrs = data.DataPoints[0].Attributes\n\t\t\trequire.Equal(t, 1, attrs.Len())\n\t\t\tval, ok = attrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\t\t\trequire.True(t, ok)\n\t\t\trequire.Equal(t, \"refused\", val.Emit())\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "service/internal/obsconsumer/enabled.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage obsconsumer // import \"go.opentelemetry.io/collector/service/internal/obsconsumer\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/otel/metric\"\n)\n\ntype enabledInstrument interface {\n\tEnabled(context.Context) bool\n}\n\nfunc isEnabled(ctx context.Context, inst metric.Int64Counter) bool {\n\tei, ok := inst.(enabledInstrument)\n\treturn !ok || ei.Enabled(ctx)\n}\n"
  },
  {
    "path": "service/internal/obsconsumer/enabled_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage obsconsumer_test\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/otel/metric\"\n)\n\ntype disabledCounter struct {\n\tmetric.Int64Counter\n}\n\nfunc newDisabledCounter(embedded metric.Int64Counter) *disabledCounter {\n\treturn &disabledCounter{Int64Counter: embedded}\n}\n\nfunc (m *disabledCounter) Enabled(context.Context) bool {\n\treturn false\n}\n\nfunc (m *disabledCounter) Add(ctx context.Context, value int64, opts ...metric.AddOption) {\n\tm.Int64Counter.Add(ctx, value, opts...)\n}\n"
  },
  {
    "path": "service/internal/obsconsumer/gate_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage obsconsumer_test\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n)\n\nfunc setGateForTest(t *testing.T, enabled bool) {\n\tinitial := metadata.TelemetryNewPipelineTelemetryFeatureGate.IsEnabled()\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.TelemetryNewPipelineTelemetryFeatureGate.ID(), enabled))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.TelemetryNewPipelineTelemetryFeatureGate.ID(), initial))\n\t})\n}\n"
  },
  {
    "path": "service/internal/obsconsumer/logs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage obsconsumer // import \"go.opentelemetry.io/collector/service/internal/obsconsumer\"\n\nimport (\n\t\"context\"\n\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/internal/telemetry\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n)\n\nvar (\n\t_             consumer.Logs = obsLogs{}\n\tlogsMarshaler               = &plog.ProtoMarshaler{}\n)\n\nfunc NewLogs(cons consumer.Logs, set Settings, opts ...Option) consumer.Logs {\n\tif !metadata.TelemetryNewPipelineTelemetryFeatureGate.IsEnabled() {\n\t\treturn cons\n\t}\n\n\to := options{}\n\tfor _, opt := range opts {\n\t\topt(&o)\n\t}\n\n\tconsumerSet := Settings{\n\t\tItemCounter: set.ItemCounter,\n\t\tSizeCounter: set.SizeCounter,\n\t\tLogger:      set.Logger.With(telemetry.ToZapFields(o.staticDataPointAttributes)...),\n\t}\n\n\treturn obsLogs{\n\t\tconsumer:        cons,\n\t\tset:             consumerSet,\n\t\tcompiledOptions: o.compile(),\n\t}\n}\n\ntype obsLogs struct {\n\tconsumer consumer.Logs\n\tset      Settings\n\tcompiledOptions\n}\n\n// ConsumeLogs measures telemetry before calling ConsumeLogs because the data may be mutated downstream\nfunc (c obsLogs) ConsumeLogs(ctx context.Context, ld plog.Logs) error {\n\t// Use a pointer to so that deferred function can depend on the result of ConsumeLogs\n\tattrs := &c.withSuccessAttrs\n\n\titemCount := ld.LogRecordCount()\n\tdefer func() {\n\t\tc.set.ItemCounter.Add(ctx, int64(itemCount), *attrs)\n\t}()\n\n\tif isEnabled(ctx, c.set.SizeCounter) {\n\t\tbyteCount := int64(logsMarshaler.LogsSize(ld))\n\t\tdefer func() {\n\t\t\tc.set.SizeCounter.Add(ctx, byteCount, *attrs)\n\t\t}()\n\t}\n\n\terr := c.consumer.ConsumeLogs(ctx, ld)\n\tif err != nil {\n\t\tif consumererror.IsDownstream(err) {\n\t\t\tattrs = &c.withRefusedAttrs\n\t\t} else {\n\t\t\tattrs = &c.withFailureAttrs\n\t\t\terr = consumererror.NewDownstream(err)\n\t\t}\n\t\tif c.set.Logger.Core().Enabled(zap.DebugLevel) {\n\t\t\tc.set.Logger.Debug(\"Logs pipeline component had an error\", zap.Error(err), zap.Int(\"item count\", itemCount))\n\t\t}\n\t}\n\treturn err\n}\n\nfunc (c obsLogs) Capabilities() consumer.Capabilities {\n\treturn c.consumer.Capabilities()\n}\n"
  },
  {
    "path": "service/internal/obsconsumer/logs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage obsconsumer_test\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\tsdkmetric \"go.opentelemetry.io/otel/sdk/metric\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/service/internal/obsconsumer\"\n)\n\ntype mockLogsConsumer struct {\n\terr          error\n\tcapabilities consumer.Capabilities\n}\n\nfunc (m *mockLogsConsumer) ConsumeLogs(_ context.Context, _ plog.Logs) error {\n\treturn m.err\n}\n\nfunc (m *mockLogsConsumer) Capabilities() consumer.Capabilities {\n\treturn m.capabilities\n}\n\nfunc TestLogsNopWhenGateDisabled(t *testing.T) {\n\tsetGateForTest(t, false)\n\n\tmp := sdkmetric.NewMeterProvider()\n\tmeter := mp.Meter(\"test\")\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tcons := consumertest.NewNop()\n\trequire.Equal(t, cons, obsconsumer.NewLogs(cons, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: zap.NewNop()}))\n}\n\nfunc TestLogsItemsOnly(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\tmockConsumer := &mockLogsConsumer{}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\tsizeCounterDisabled := newDisabledCounter(sizeCounter)\n\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewLogs(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounterDisabled, Logger: logger})\n\n\tld := plog.NewLogs()\n\tr := ld.ResourceLogs().AppendEmpty()\n\tsl := r.ScopeLogs().AppendEmpty()\n\tsl.LogRecords().AppendEmpty()\n\n\terr = consumer.ConsumeLogs(ctx, ld)\n\trequire.NoError(t, err)\n\n\tvar rm metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &rm)\n\trequire.NoError(t, err)\n\trequire.Len(t, rm.ScopeMetrics, 1)\n\trequire.Len(t, rm.ScopeMetrics[0].Metrics, 1)\n\n\tmetric := rm.ScopeMetrics[0].Metrics[0]\n\trequire.Equal(t, \"item_counter\", metric.Name)\n\n\tdata := metric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, data.DataPoints, 1)\n\trequire.Equal(t, int64(1), data.DataPoints[0].Value)\n\n\tattrs := data.DataPoints[0].Attributes\n\trequire.Equal(t, 1, attrs.Len())\n\tval, ok := attrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\t// Check that the logger was not called\n\tassert.Empty(t, logs.All())\n}\n\nfunc TestLogsConsumeSuccess(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\tmockConsumer := &mockLogsConsumer{}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewLogs(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: logger})\n\n\tld := plog.NewLogs()\n\tr := ld.ResourceLogs().AppendEmpty()\n\tsl := r.ScopeLogs().AppendEmpty()\n\tsl.LogRecords().AppendEmpty()\n\n\terr = consumer.ConsumeLogs(ctx, ld)\n\trequire.NoError(t, err)\n\n\tvar rm metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &rm)\n\trequire.NoError(t, err)\n\trequire.Len(t, rm.ScopeMetrics, 1)\n\trequire.Len(t, rm.ScopeMetrics[0].Metrics, 2)\n\n\tvar itemMetric, sizeMetric metricdata.Metrics\n\tfor _, m := range rm.ScopeMetrics[0].Metrics {\n\t\tswitch m.Name {\n\t\tcase \"item_counter\":\n\t\t\titemMetric = m\n\t\tcase \"size_counter\":\n\t\t\tsizeMetric = m\n\t\t}\n\t}\n\trequire.NotNil(t, itemMetric)\n\trequire.NotNil(t, sizeMetric)\n\n\titemData := itemMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, itemData.DataPoints, 1)\n\trequire.Equal(t, int64(1), itemData.DataPoints[0].Value)\n\n\titemAttrs := itemData.DataPoints[0].Attributes\n\trequire.Equal(t, 1, itemAttrs.Len())\n\tval, ok := itemAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\tsizeData := sizeMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, sizeData.DataPoints, 1)\n\trequire.Positive(t, sizeData.DataPoints[0].Value)\n\n\tsizeAttrs := sizeData.DataPoints[0].Attributes\n\trequire.Equal(t, 1, sizeAttrs.Len())\n\tval, ok = sizeAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\t// Check that the logger was not called\n\tassert.Empty(t, logs.All())\n}\n\nfunc TestLogsConsumeFailure(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\texpectedErr := errors.New(\"test error\")\n\tdownstreamErr := consumererror.NewDownstream(expectedErr)\n\tmockConsumer := &mockLogsConsumer{err: expectedErr}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewLogs(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: logger})\n\n\tld := plog.NewLogs()\n\tr := ld.ResourceLogs().AppendEmpty()\n\tsl := r.ScopeLogs().AppendEmpty()\n\tsl.LogRecords().AppendEmpty()\n\n\terr = consumer.ConsumeLogs(ctx, ld)\n\tassert.Equal(t, downstreamErr, err)\n\n\tvar rm metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &rm)\n\trequire.NoError(t, err)\n\trequire.Len(t, rm.ScopeMetrics, 1)\n\trequire.Len(t, rm.ScopeMetrics[0].Metrics, 2)\n\n\tvar itemMetric, sizeMetric metricdata.Metrics\n\tfor _, m := range rm.ScopeMetrics[0].Metrics {\n\t\tswitch m.Name {\n\t\tcase \"item_counter\":\n\t\t\titemMetric = m\n\t\tcase \"size_counter\":\n\t\t\tsizeMetric = m\n\t\t}\n\t}\n\trequire.NotNil(t, itemMetric)\n\trequire.NotNil(t, sizeMetric)\n\n\titemData := itemMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, itemData.DataPoints, 1)\n\trequire.Equal(t, int64(1), itemData.DataPoints[0].Value)\n\n\titemAttrs := itemData.DataPoints[0].Attributes\n\trequire.Equal(t, 1, itemAttrs.Len())\n\tval, ok := itemAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"failure\", val.Emit())\n\n\trequire.NotNil(t, sizeMetric)\n\tsizeData := sizeMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, sizeData.DataPoints, 1)\n\trequire.Positive(t, sizeData.DataPoints[0].Value)\n\n\tsizeAttrs := sizeData.DataPoints[0].Attributes\n\trequire.Equal(t, 1, sizeAttrs.Len())\n\tval, ok = sizeAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"failure\", val.Emit())\n\n\t// Check that the logger was called with an error\n\trequire.Len(t, logs.All(), 1)\n\tassert.Contains(t, logs.All()[0].Message, \"Logs pipeline component had an error\")\n}\n\nfunc TestLogsWithStaticAttributes(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\tmockConsumer := &mockLogsConsumer{}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tstaticAttr := attribute.String(\"test\", \"value\")\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewLogs(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: logger},\n\t\tobsconsumer.WithStaticDataPointAttribute(staticAttr))\n\n\tld := plog.NewLogs()\n\tr := ld.ResourceLogs().AppendEmpty()\n\tsl := r.ScopeLogs().AppendEmpty()\n\tsl.LogRecords().AppendEmpty()\n\n\terr = consumer.ConsumeLogs(ctx, ld)\n\trequire.NoError(t, err)\n\n\tvar rm metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &rm)\n\trequire.NoError(t, err)\n\trequire.Len(t, rm.ScopeMetrics, 1)\n\trequire.Len(t, rm.ScopeMetrics[0].Metrics, 2)\n\n\tvar itemMetric, sizeMetric metricdata.Metrics\n\tfor _, m := range rm.ScopeMetrics[0].Metrics {\n\t\tswitch m.Name {\n\t\tcase \"item_counter\":\n\t\t\titemMetric = m\n\t\tcase \"size_counter\":\n\t\t\tsizeMetric = m\n\t\t}\n\t}\n\trequire.NotNil(t, itemMetric)\n\n\titemData := itemMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, itemData.DataPoints, 1)\n\trequire.Equal(t, int64(1), itemData.DataPoints[0].Value)\n\n\titemAttrs := itemData.DataPoints[0].Attributes\n\trequire.Equal(t, 2, itemAttrs.Len())\n\tval, ok := itemAttrs.Value(attribute.Key(\"test\"))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"value\", val.Emit())\n\tval, ok = itemAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\tsizeData := sizeMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, sizeData.DataPoints, 1)\n\trequire.Positive(t, sizeData.DataPoints[0].Value)\n\n\tsizeAttrs := sizeData.DataPoints[0].Attributes\n\trequire.Equal(t, 2, sizeAttrs.Len())\n\tval, ok = sizeAttrs.Value(attribute.Key(\"test\"))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"value\", val.Emit())\n\tval, ok = sizeAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\t// Check that the logger was not called\n\tassert.Empty(t, logs.All())\n}\n\nfunc TestLogsMultipleItemsMixedOutcomes(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\texpectedErr := errors.New(\"test error\")\n\tdownstreamErr := consumererror.NewDownstream(expectedErr)\n\tmockConsumer := &mockLogsConsumer{}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewLogs(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: logger})\n\n\t// First batch: 2 successful items\n\tld1 := plog.NewLogs()\n\tfor range 2 {\n\t\tr := ld1.ResourceLogs().AppendEmpty()\n\t\tsl := r.ScopeLogs().AppendEmpty()\n\t\tsl.LogRecords().AppendEmpty()\n\t}\n\terr = consumer.ConsumeLogs(ctx, ld1)\n\trequire.NoError(t, err)\n\n\t// Second batch: 1 failed item\n\tmockConsumer.err = expectedErr\n\tld2 := plog.NewLogs()\n\tr := ld2.ResourceLogs().AppendEmpty()\n\tsl := r.ScopeLogs().AppendEmpty()\n\tsl.LogRecords().AppendEmpty()\n\terr = consumer.ConsumeLogs(ctx, ld2)\n\tassert.Equal(t, downstreamErr, err)\n\n\t// Third batch: 2 successful items\n\tmockConsumer.err = nil\n\tld3 := plog.NewLogs()\n\tfor range 2 {\n\t\tr = ld3.ResourceLogs().AppendEmpty()\n\t\tsl = r.ScopeLogs().AppendEmpty()\n\t\tsl.LogRecords().AppendEmpty()\n\t}\n\terr = consumer.ConsumeLogs(ctx, ld3)\n\trequire.NoError(t, err)\n\n\t// Fourth batch: 1 failed item\n\tmockConsumer.err = expectedErr\n\tld4 := plog.NewLogs()\n\tr = ld4.ResourceLogs().AppendEmpty()\n\tsl = r.ScopeLogs().AppendEmpty()\n\tsl.LogRecords().AppendEmpty()\n\terr = consumer.ConsumeLogs(ctx, ld4)\n\tassert.Equal(t, downstreamErr, err)\n\n\tvar rm metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &rm)\n\trequire.NoError(t, err)\n\trequire.Len(t, rm.ScopeMetrics, 1)\n\trequire.Len(t, rm.ScopeMetrics[0].Metrics, 2)\n\n\tvar itemMetric, sizeMetric metricdata.Metrics\n\tfor _, m := range rm.ScopeMetrics[0].Metrics {\n\t\tswitch m.Name {\n\t\tcase \"item_counter\":\n\t\t\titemMetric = m\n\t\tcase \"size_counter\":\n\t\t\tsizeMetric = m\n\t\t}\n\t}\n\trequire.NotNil(t, itemMetric)\n\trequire.NotNil(t, sizeMetric)\n\n\titemData := itemMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, itemData.DataPoints, 2)\n\tsizeData := sizeMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, sizeData.DataPoints, 2)\n\n\tvar successDP, failureDP metricdata.DataPoint[int64]\n\tfor _, dp := range itemData.DataPoints {\n\t\tval, ok := dp.Attributes.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\t\tif ok && val.Emit() == \"success\" {\n\t\t\tsuccessDP = dp\n\t\t} else {\n\t\t\tfailureDP = dp\n\t\t}\n\t}\n\trequire.Equal(t, int64(4), successDP.Value)\n\trequire.Equal(t, int64(2), failureDP.Value)\n\n\tvar successSizeDP, failureSizeDP metricdata.DataPoint[int64]\n\tfor _, dp := range sizeData.DataPoints {\n\t\tval, ok := dp.Attributes.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\t\tif ok && val.Emit() == \"success\" {\n\t\t\tsuccessSizeDP = dp\n\t\t} else {\n\t\t\tfailureSizeDP = dp\n\t\t}\n\t}\n\trequire.Equal(t, int64(64), successSizeDP.Value)\n\trequire.Equal(t, int64(32), failureSizeDP.Value)\n\n\t// Check that the logger was called for errors\n\trequire.Len(t, logs.All(), 2)\n\tfor _, log := range logs.All() {\n\t\tassert.Contains(t, log.Message, \"Logs pipeline component had an error\")\n\t}\n}\n\nfunc TestLogsCapabilities(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tmockConsumer := &mockLogsConsumer{\n\t\tcapabilities: consumer.Capabilities{MutatesData: true},\n\t}\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\tsizeCounterDisabled := newDisabledCounter(sizeCounter)\n\n\t// Test with item counter only\n\tconsumer := obsconsumer.NewLogs(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounterDisabled, Logger: zap.NewNop()})\n\trequire.Equal(t, consumer.Capabilities(), mockConsumer.capabilities)\n\n\t// Test with both counters\n\tconsumer = obsconsumer.NewLogs(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: zap.NewNop()})\n\trequire.Equal(t, consumer.Capabilities(), mockConsumer.capabilities)\n}\n"
  },
  {
    "path": "service/internal/obsconsumer/metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage obsconsumer // import \"go.opentelemetry.io/collector/service/internal/obsconsumer\"\n\nimport (\n\t\"context\"\n\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/internal/telemetry\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n)\n\nvar (\n\t_                consumer.Metrics = obsMetrics{}\n\tmetricsMarshaler                  = &pmetric.ProtoMarshaler{}\n)\n\nfunc NewMetrics(cons consumer.Metrics, set Settings, opts ...Option) consumer.Metrics {\n\tif !metadata.TelemetryNewPipelineTelemetryFeatureGate.IsEnabled() {\n\t\treturn cons\n\t}\n\n\to := options{}\n\tfor _, opt := range opts {\n\t\topt(&o)\n\t}\n\n\tconsumerSet := Settings{\n\t\tItemCounter: set.ItemCounter,\n\t\tSizeCounter: set.SizeCounter,\n\t\tLogger:      set.Logger.With(telemetry.ToZapFields(o.staticDataPointAttributes)...),\n\t}\n\n\treturn obsMetrics{\n\t\tconsumer:        cons,\n\t\tset:             consumerSet,\n\t\tcompiledOptions: o.compile(),\n\t}\n}\n\ntype obsMetrics struct {\n\tconsumer consumer.Metrics\n\tset      Settings\n\tcompiledOptions\n}\n\n// ConsumeMetrics measures telemetry before calling ConsumeMetrics because the data may be mutated downstream\nfunc (c obsMetrics) ConsumeMetrics(ctx context.Context, md pmetric.Metrics) error {\n\t// Use a pointer to so that deferred function can depend on the result of ConsumeMetrics\n\tattrs := &c.withSuccessAttrs\n\n\titemCount := md.DataPointCount()\n\tdefer func() {\n\t\tc.set.ItemCounter.Add(ctx, int64(itemCount), *attrs)\n\t}()\n\n\tif isEnabled(ctx, c.set.SizeCounter) {\n\t\tbyteCount := int64(metricsMarshaler.MetricsSize(md))\n\t\tdefer func() {\n\t\t\tc.set.SizeCounter.Add(ctx, byteCount, *attrs)\n\t\t}()\n\t}\n\n\terr := c.consumer.ConsumeMetrics(ctx, md)\n\tif err != nil {\n\t\tif consumererror.IsDownstream(err) {\n\t\t\tattrs = &c.withRefusedAttrs\n\t\t} else {\n\t\t\tattrs = &c.withFailureAttrs\n\t\t\terr = consumererror.NewDownstream(err)\n\t\t}\n\t\tif c.set.Logger.Core().Enabled(zap.DebugLevel) {\n\t\t\tc.set.Logger.Debug(\"Metrics pipeline component had an error\", zap.Error(err), zap.Int(\"item count\", itemCount))\n\t\t}\n\t}\n\treturn err\n}\n\nfunc (c obsMetrics) Capabilities() consumer.Capabilities {\n\treturn c.consumer.Capabilities()\n}\n"
  },
  {
    "path": "service/internal/obsconsumer/metrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage obsconsumer_test\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\tsdkmetric \"go.opentelemetry.io/otel/sdk/metric\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/service/internal/obsconsumer\"\n)\n\ntype mockMetricsConsumer struct {\n\terr          error\n\tcapabilities consumer.Capabilities\n}\n\nfunc (m *mockMetricsConsumer) ConsumeMetrics(_ context.Context, _ pmetric.Metrics) error {\n\treturn m.err\n}\n\nfunc (m *mockMetricsConsumer) Capabilities() consumer.Capabilities {\n\treturn m.capabilities\n}\n\nfunc TestMetricsNopWhenGateDisabled(t *testing.T) {\n\tsetGateForTest(t, false)\n\tmp := sdkmetric.NewMeterProvider()\n\tmeter := mp.Meter(\"test\")\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tcons := consumertest.NewNop()\n\trequire.Equal(t, cons, obsconsumer.NewMetrics(cons, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: zap.NewNop()}))\n}\n\nfunc TestMetricsItemsOnly(t *testing.T) {\n\tsetGateForTest(t, true)\n\tctx := context.Background()\n\tmockConsumer := &mockMetricsConsumer{}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\tsizeCounterDisabled := newDisabledCounter(sizeCounter)\n\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewMetrics(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounterDisabled, Logger: logger})\n\n\tmd := pmetric.NewMetrics()\n\trm := md.ResourceMetrics().AppendEmpty()\n\tsm := rm.ScopeMetrics().AppendEmpty()\n\tm := sm.Metrics().AppendEmpty()\n\tm.SetEmptyGauge().DataPoints().AppendEmpty()\n\n\terr = consumer.ConsumeMetrics(ctx, md)\n\trequire.NoError(t, err)\n\n\tvar metrics metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &metrics)\n\trequire.NoError(t, err)\n\trequire.Len(t, metrics.ScopeMetrics, 1)\n\trequire.Len(t, metrics.ScopeMetrics[0].Metrics, 1)\n\n\tmetric := metrics.ScopeMetrics[0].Metrics[0]\n\trequire.Equal(t, \"item_counter\", metric.Name)\n\n\tdata := metric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, data.DataPoints, 1)\n\trequire.Equal(t, int64(1), data.DataPoints[0].Value)\n\n\tattrs := data.DataPoints[0].Attributes\n\trequire.Equal(t, 1, attrs.Len())\n\tval, ok := attrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\t// Check that the logger was not called\n\tassert.Empty(t, logs.All())\n}\n\nfunc TestMetricsConsumeSuccess(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\tmockConsumer := &mockMetricsConsumer{}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewMetrics(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: logger})\n\n\tmd := pmetric.NewMetrics()\n\tr := md.ResourceMetrics().AppendEmpty()\n\tsm := r.ScopeMetrics().AppendEmpty()\n\tm := sm.Metrics().AppendEmpty()\n\tm.SetEmptyGauge().DataPoints().AppendEmpty()\n\n\terr = consumer.ConsumeMetrics(ctx, md)\n\trequire.NoError(t, err)\n\n\tvar metrics metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &metrics)\n\trequire.NoError(t, err)\n\trequire.Len(t, metrics.ScopeMetrics, 1)\n\trequire.Len(t, metrics.ScopeMetrics[0].Metrics, 2)\n\n\tvar itemMetric, sizeMetric metricdata.Metrics\n\tfor _, m := range metrics.ScopeMetrics[0].Metrics {\n\t\tswitch m.Name {\n\t\tcase \"item_counter\":\n\t\t\titemMetric = m\n\t\tcase \"size_counter\":\n\t\t\tsizeMetric = m\n\t\t}\n\t}\n\trequire.NotNil(t, itemMetric)\n\trequire.NotNil(t, sizeMetric)\n\n\titemData := itemMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, itemData.DataPoints, 1)\n\trequire.Equal(t, int64(1), itemData.DataPoints[0].Value)\n\n\titemAttrs := itemData.DataPoints[0].Attributes\n\trequire.Equal(t, 1, itemAttrs.Len())\n\tval, ok := itemAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\tsizeData := sizeMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, sizeData.DataPoints, 1)\n\trequire.Positive(t, sizeData.DataPoints[0].Value)\n\n\tattrs := sizeData.DataPoints[0].Attributes\n\trequire.Equal(t, 1, attrs.Len())\n\tval, ok = attrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\t// Check that the logger was not called\n\tassert.Empty(t, logs.All())\n}\n\nfunc TestMetricsConsumeFailure(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\texpectedErr := errors.New(\"test error\")\n\tdownstreamErr := consumererror.NewDownstream(expectedErr)\n\tmockConsumer := &mockMetricsConsumer{err: expectedErr}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewMetrics(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: logger})\n\n\tmd := pmetric.NewMetrics()\n\tr := md.ResourceMetrics().AppendEmpty()\n\tsm := r.ScopeMetrics().AppendEmpty()\n\tm := sm.Metrics().AppendEmpty()\n\tm.SetEmptyGauge().DataPoints().AppendEmpty()\n\n\terr = consumer.ConsumeMetrics(ctx, md)\n\tassert.Equal(t, downstreamErr, err)\n\n\tvar metrics metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &metrics)\n\trequire.NoError(t, err)\n\trequire.Len(t, metrics.ScopeMetrics, 1)\n\trequire.Len(t, metrics.ScopeMetrics[0].Metrics, 2)\n\n\t// Find the item counter and size counter metrics\n\tvar itemMetric, sizeMetric metricdata.Metrics\n\tfor _, m := range metrics.ScopeMetrics[0].Metrics {\n\t\tswitch m.Name {\n\t\tcase \"item_counter\":\n\t\t\titemMetric = m\n\t\tcase \"size_counter\":\n\t\t\tsizeMetric = m\n\t\t}\n\t}\n\trequire.NotNil(t, itemMetric)\n\trequire.NotNil(t, sizeMetric)\n\n\titemData := itemMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, itemData.DataPoints, 1)\n\trequire.Equal(t, int64(1), itemData.DataPoints[0].Value)\n\n\titemAttrs := itemData.DataPoints[0].Attributes\n\trequire.Equal(t, 1, itemAttrs.Len())\n\tval, ok := itemAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"failure\", val.Emit())\n\n\tsizeData := sizeMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, sizeData.DataPoints, 1)\n\trequire.Positive(t, sizeData.DataPoints[0].Value)\n\n\tsizeAttrs := sizeData.DataPoints[0].Attributes\n\trequire.Equal(t, 1, sizeAttrs.Len())\n\tval, ok = sizeAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"failure\", val.Emit())\n\n\t// Check that the logger was called with an error\n\trequire.Len(t, logs.All(), 1)\n\tassert.Contains(t, logs.All()[0].Message, \"Metrics pipeline component had an error\")\n}\n\nfunc TestMetricsWithStaticAttributes(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\tmockConsumer := &mockMetricsConsumer{}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tstaticAttr := attribute.String(\"test\", \"value\")\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewMetrics(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: logger},\n\t\tobsconsumer.WithStaticDataPointAttribute(staticAttr))\n\n\tmd := pmetric.NewMetrics()\n\trm := md.ResourceMetrics().AppendEmpty()\n\trm.ScopeMetrics().AppendEmpty()\n\tsm := rm.ScopeMetrics().AppendEmpty()\n\tm := sm.Metrics().AppendEmpty()\n\tm.SetEmptyGauge().DataPoints().AppendEmpty()\n\n\terr = consumer.ConsumeMetrics(ctx, md)\n\trequire.NoError(t, err)\n\n\tvar metrics metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &metrics)\n\trequire.NoError(t, err)\n\trequire.Len(t, metrics.ScopeMetrics, 1)\n\trequire.Len(t, metrics.ScopeMetrics[0].Metrics, 2)\n\n\tvar itemMetric, sizeMetric metricdata.Metrics\n\tfor _, m := range metrics.ScopeMetrics[0].Metrics {\n\t\tswitch m.Name {\n\t\tcase \"item_counter\":\n\t\t\titemMetric = m\n\t\tcase \"size_counter\":\n\t\t\tsizeMetric = m\n\t\t}\n\t}\n\trequire.NotNil(t, itemMetric)\n\trequire.NotNil(t, sizeMetric)\n\n\titemData := itemMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, itemData.DataPoints, 1)\n\trequire.Equal(t, int64(1), itemData.DataPoints[0].Value)\n\n\titemAttrs := itemData.DataPoints[0].Attributes\n\trequire.Equal(t, 2, itemAttrs.Len())\n\tval, ok := itemAttrs.Value(attribute.Key(\"test\"))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"value\", val.Emit())\n\tval, ok = itemAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\tsizeData := sizeMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, sizeData.DataPoints, 1)\n\trequire.Positive(t, sizeData.DataPoints[0].Value)\n\n\tsizeAttrs := sizeData.DataPoints[0].Attributes\n\trequire.Equal(t, 2, sizeAttrs.Len())\n\tval, ok = sizeAttrs.Value(attribute.Key(\"test\"))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"value\", val.Emit())\n\tval, ok = sizeAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\t// Check that the logger was not called\n\tassert.Empty(t, logs.All())\n}\n\nfunc TestMetricsMultipleItemsMixedOutcomes(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\texpectedErr := errors.New(\"test error\")\n\tdownstreamErr := consumererror.NewDownstream(expectedErr)\n\tmockConsumer := &mockMetricsConsumer{}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewMetrics(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: logger})\n\n\t// First batch: 2 successful items\n\tmd1 := pmetric.NewMetrics()\n\tfor range 2 {\n\t\tr := md1.ResourceMetrics().AppendEmpty()\n\t\tsm := r.ScopeMetrics().AppendEmpty()\n\t\tm := sm.Metrics().AppendEmpty()\n\t\tm.SetEmptyGauge().DataPoints().AppendEmpty()\n\t}\n\terr = consumer.ConsumeMetrics(ctx, md1)\n\trequire.NoError(t, err)\n\n\t// Second batch: 1 failed item\n\tmockConsumer.err = expectedErr\n\tmd2 := pmetric.NewMetrics()\n\tr := md2.ResourceMetrics().AppendEmpty()\n\tsm := r.ScopeMetrics().AppendEmpty()\n\tm := sm.Metrics().AppendEmpty()\n\tm.SetEmptyGauge().DataPoints().AppendEmpty()\n\terr = consumer.ConsumeMetrics(ctx, md2)\n\tassert.Equal(t, downstreamErr, err)\n\n\t// Third batch: 2 successful items\n\tmockConsumer.err = nil\n\tmd3 := pmetric.NewMetrics()\n\tfor range 2 {\n\t\tr = md3.ResourceMetrics().AppendEmpty()\n\t\tsm = r.ScopeMetrics().AppendEmpty()\n\t\tm = sm.Metrics().AppendEmpty()\n\t\tm.SetEmptyGauge().DataPoints().AppendEmpty()\n\t}\n\terr = consumer.ConsumeMetrics(ctx, md3)\n\trequire.NoError(t, err)\n\n\t// Fourth batch: 1 failed item\n\tmockConsumer.err = expectedErr\n\tmd4 := pmetric.NewMetrics()\n\tr = md4.ResourceMetrics().AppendEmpty()\n\tsm = r.ScopeMetrics().AppendEmpty()\n\tm = sm.Metrics().AppendEmpty()\n\tm.SetEmptyGauge().DataPoints().AppendEmpty()\n\terr = consumer.ConsumeMetrics(ctx, md4)\n\tassert.Equal(t, downstreamErr, err)\n\n\tvar metrics metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &metrics)\n\trequire.NoError(t, err)\n\trequire.Len(t, metrics.ScopeMetrics, 1)\n\trequire.Len(t, metrics.ScopeMetrics[0].Metrics, 2)\n\n\tvar itemMetric, sizeMetric metricdata.Metrics\n\tfor _, m := range metrics.ScopeMetrics[0].Metrics {\n\t\tswitch m.Name {\n\t\tcase \"item_counter\":\n\t\t\titemMetric = m\n\t\tcase \"size_counter\":\n\t\t\tsizeMetric = m\n\t\t}\n\t}\n\trequire.NotNil(t, itemMetric)\n\trequire.NotNil(t, sizeMetric)\n\n\titemData := itemMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, itemData.DataPoints, 2)\n\tsizeData := sizeMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, sizeData.DataPoints, 2)\n\n\t// Find success and failure data points\n\tvar successDP, failureDP metricdata.DataPoint[int64]\n\tfor _, dp := range itemData.DataPoints {\n\t\tval, ok := dp.Attributes.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\t\tif ok && val.Emit() == \"success\" {\n\t\t\tsuccessDP = dp\n\t\t} else {\n\t\t\tfailureDP = dp\n\t\t}\n\t}\n\trequire.Equal(t, int64(4), successDP.Value)\n\trequire.Equal(t, int64(2), failureDP.Value)\n\n\tfor _, dp := range sizeData.DataPoints {\n\t\tval, ok := dp.Attributes.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\t\tif ok && val.Emit() == \"success\" {\n\t\t\tsuccessDP = dp\n\t\t} else {\n\t\t\tfailureDP = dp\n\t\t}\n\t}\n\trequire.Equal(t, int64(56), successDP.Value)\n\trequire.Equal(t, int64(28), failureDP.Value)\n\n\t// Check that the logger was called for errors\n\trequire.Len(t, logs.All(), 2)\n\tfor _, log := range logs.All() {\n\t\tassert.Contains(t, log.Message, \"Metrics pipeline component had an error\")\n\t}\n}\n\nfunc TestMetricsCapabilities(t *testing.T) {\n\tsetGateForTest(t, true)\n\tmockConsumer := &mockMetricsConsumer{\n\t\tcapabilities: consumer.Capabilities{MutatesData: true},\n\t}\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\tsizeCounterDisabled := newDisabledCounter(sizeCounter)\n\n\t// Test with item counter only\n\tconsumer := obsconsumer.NewMetrics(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounterDisabled, Logger: zap.NewNop()})\n\trequire.Equal(t, consumer.Capabilities(), mockConsumer.capabilities)\n\n\t// Test with both counters\n\tconsumer = obsconsumer.NewMetrics(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: zap.NewNop()})\n\trequire.Equal(t, consumer.Capabilities(), mockConsumer.capabilities)\n}\n"
  },
  {
    "path": "service/internal/obsconsumer/option.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage obsconsumer // import \"go.opentelemetry.io/collector/service/internal/obsconsumer\"\n\nimport (\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/metric\"\n)\n\nconst (\n\tComponentOutcome = \"otelcol.component.outcome\"\n)\n\n// Option modifies the consumer behavior.\ntype Option func(*options)\n\ntype options struct {\n\tstaticDataPointAttributes []attribute.KeyValue\n}\n\n// WithStaticDataPointAttribute returns an Option that adds a static attribute to data points.\nfunc WithStaticDataPointAttribute(attr attribute.KeyValue) Option {\n\treturn func(opts *options) {\n\t\topts.staticDataPointAttributes = append(opts.staticDataPointAttributes, attr)\n\t}\n}\n\ntype compiledOptions struct {\n\twithSuccessAttrs metric.AddOption\n\twithFailureAttrs metric.AddOption\n\twithRefusedAttrs metric.AddOption\n}\n\nfunc (o *options) compile() compiledOptions {\n\tsuccessAttrs := make([]attribute.KeyValue, 0, 1+len(o.staticDataPointAttributes))\n\tsuccessAttrs = append(successAttrs, attribute.String(ComponentOutcome, \"success\"))\n\tsuccessAttrs = append(successAttrs, o.staticDataPointAttributes...)\n\n\tfailureAttrs := make([]attribute.KeyValue, 0, 1+len(o.staticDataPointAttributes))\n\tfailureAttrs = append(failureAttrs, attribute.String(ComponentOutcome, \"failure\"))\n\tfailureAttrs = append(failureAttrs, o.staticDataPointAttributes...)\n\n\trefusedAttrs := make([]attribute.KeyValue, 0, 1+len(o.staticDataPointAttributes))\n\trefusedAttrs = append(refusedAttrs, attribute.String(ComponentOutcome, \"refused\"))\n\trefusedAttrs = append(refusedAttrs, o.staticDataPointAttributes...)\n\n\treturn compiledOptions{\n\t\twithSuccessAttrs: metric.WithAttributes(successAttrs...),\n\t\twithFailureAttrs: metric.WithAttributes(failureAttrs...),\n\t\twithRefusedAttrs: metric.WithAttributes(refusedAttrs...),\n\t}\n}\n"
  },
  {
    "path": "service/internal/obsconsumer/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage obsconsumer\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "service/internal/obsconsumer/profiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage obsconsumer // import \"go.opentelemetry.io/collector/service/internal/obsconsumer\"\n\nimport (\n\t\"context\"\n\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/internal/telemetry\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n)\n\nvar (\n\t_                 xconsumer.Profiles = obsProfiles{}\n\tprofilesMarshaler                    = pprofile.ProtoMarshaler{}\n)\n\nfunc NewProfiles(cons xconsumer.Profiles, set Settings, opts ...Option) xconsumer.Profiles {\n\tif !metadata.TelemetryNewPipelineTelemetryFeatureGate.IsEnabled() {\n\t\treturn cons\n\t}\n\n\to := options{}\n\tfor _, opt := range opts {\n\t\topt(&o)\n\t}\n\n\tconsumerSet := Settings{\n\t\tItemCounter: set.ItemCounter,\n\t\tSizeCounter: set.SizeCounter,\n\t\tLogger:      set.Logger.With(telemetry.ToZapFields(o.staticDataPointAttributes)...),\n\t}\n\n\treturn obsProfiles{\n\t\tconsumer:        cons,\n\t\tset:             consumerSet,\n\t\tcompiledOptions: o.compile(),\n\t}\n}\n\ntype obsProfiles struct {\n\tconsumer xconsumer.Profiles\n\tset      Settings\n\tcompiledOptions\n}\n\n// ConsumeProfiles measures telemetry before calling ConsumeProfiles because the data may be mutated downstream\nfunc (c obsProfiles) ConsumeProfiles(ctx context.Context, pd pprofile.Profiles) error {\n\t// Measure before calling ConsumeProfiles because the data may be mutated downstream\n\tattrs := &c.withSuccessAttrs\n\n\titemCount := pd.SampleCount()\n\tdefer func() {\n\t\tc.set.ItemCounter.Add(ctx, int64(itemCount), *attrs)\n\t}()\n\n\tif isEnabled(ctx, c.set.SizeCounter) {\n\t\tbyteCount := int64(profilesMarshaler.ProfilesSize(pd))\n\t\tdefer func() {\n\t\t\tc.set.SizeCounter.Add(ctx, byteCount, *attrs)\n\t\t}()\n\t}\n\n\terr := c.consumer.ConsumeProfiles(ctx, pd)\n\tif err != nil {\n\t\tif consumererror.IsDownstream(err) {\n\t\t\tattrs = &c.withRefusedAttrs\n\t\t} else {\n\t\t\tattrs = &c.withFailureAttrs\n\t\t\terr = consumererror.NewDownstream(err)\n\t\t}\n\t\tif c.set.Logger.Core().Enabled(zap.DebugLevel) {\n\t\t\tc.set.Logger.Debug(\"Profiles pipeline component had an error\", zap.Error(err), zap.Int(\"item count\", itemCount))\n\t\t}\n\t}\n\treturn err\n}\n\nfunc (c obsProfiles) Capabilities() consumer.Capabilities {\n\treturn c.consumer.Capabilities()\n}\n"
  },
  {
    "path": "service/internal/obsconsumer/profiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage obsconsumer_test\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\tsdkmetric \"go.opentelemetry.io/otel/sdk/metric\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/service/internal/obsconsumer\"\n)\n\ntype mockProfilesConsumer struct {\n\terr          error\n\tcapabilities consumer.Capabilities\n}\n\nfunc (m *mockProfilesConsumer) ConsumeProfiles(_ context.Context, _ pprofile.Profiles) error {\n\treturn m.err\n}\n\nfunc (m *mockProfilesConsumer) Capabilities() consumer.Capabilities {\n\treturn m.capabilities\n}\n\nfunc TestProfilesNopWhenGateDisabled(t *testing.T) {\n\tsetGateForTest(t, false)\n\n\tmp := sdkmetric.NewMeterProvider()\n\tmeter := mp.Meter(\"test\")\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tcons := consumertest.NewNop()\n\trequire.Equal(t, cons, obsconsumer.NewProfiles(cons, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: zap.NewNop()}))\n}\n\nfunc TestProfilesItemsOnly(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\tmockConsumer := &mockProfilesConsumer{}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\tsizeCounterDisabled := newDisabledCounter(sizeCounter)\n\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewProfiles(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounterDisabled, Logger: logger})\n\n\tpd := pprofile.NewProfiles()\n\tr := pd.ResourceProfiles().AppendEmpty()\n\tsp := r.ScopeProfiles().AppendEmpty()\n\tsp.Profiles().AppendEmpty().Samples().AppendEmpty()\n\n\terr = consumer.ConsumeProfiles(ctx, pd)\n\trequire.NoError(t, err)\n\n\tvar rm metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &rm)\n\trequire.NoError(t, err)\n\trequire.Len(t, rm.ScopeMetrics, 1)\n\trequire.Len(t, rm.ScopeMetrics[0].Metrics, 1)\n\n\tmetric := rm.ScopeMetrics[0].Metrics[0]\n\trequire.Equal(t, \"item_counter\", metric.Name)\n\n\tdata := metric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, data.DataPoints, 1)\n\trequire.Equal(t, int64(1), data.DataPoints[0].Value)\n\n\tattrs := data.DataPoints[0].Attributes\n\trequire.Equal(t, 1, attrs.Len())\n\tval, ok := attrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\t// Check that the logger was not called\n\tassert.Empty(t, logs.All())\n}\n\nfunc TestProfilesConsumeSuccess(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\tmockConsumer := &mockProfilesConsumer{}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewProfiles(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: logger})\n\n\tpd := pprofile.NewProfiles()\n\tr := pd.ResourceProfiles().AppendEmpty()\n\tsp := r.ScopeProfiles().AppendEmpty()\n\tsp.Profiles().AppendEmpty().Samples().AppendEmpty()\n\n\terr = consumer.ConsumeProfiles(ctx, pd)\n\trequire.NoError(t, err)\n\n\tvar rm metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &rm)\n\trequire.NoError(t, err)\n\trequire.Len(t, rm.ScopeMetrics, 1)\n\trequire.Len(t, rm.ScopeMetrics[0].Metrics, 2)\n\n\tvar itemMetric, sizeMetric metricdata.Metrics\n\tfor _, m := range rm.ScopeMetrics[0].Metrics {\n\t\tswitch m.Name {\n\t\tcase \"item_counter\":\n\t\t\titemMetric = m\n\t\tcase \"size_counter\":\n\t\t\tsizeMetric = m\n\t\t}\n\t}\n\trequire.NotNil(t, itemMetric)\n\trequire.NotNil(t, sizeMetric)\n\n\titemData := itemMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, itemData.DataPoints, 1)\n\trequire.Equal(t, int64(1), itemData.DataPoints[0].Value)\n\n\titemAttrs := itemData.DataPoints[0].Attributes\n\trequire.Equal(t, 1, itemAttrs.Len())\n\tval, ok := itemAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\tsizeData := sizeMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, sizeData.DataPoints, 1)\n\trequire.Positive(t, sizeData.DataPoints[0].Value)\n\n\tsizeAttrs := sizeData.DataPoints[0].Attributes\n\trequire.Equal(t, 1, sizeAttrs.Len())\n\tval, ok = sizeAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\t// Check that the logger was not called\n\tassert.Empty(t, logs.All())\n}\n\nfunc TestProfilesConsumeFailure(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\texpectedErr := errors.New(\"test error\")\n\tdownstreamErr := consumererror.NewDownstream(expectedErr)\n\tmockConsumer := &mockProfilesConsumer{err: expectedErr}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewProfiles(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: logger})\n\n\tpd := pprofile.NewProfiles()\n\tr := pd.ResourceProfiles().AppendEmpty()\n\tsp := r.ScopeProfiles().AppendEmpty()\n\tsp.Profiles().AppendEmpty().Samples().AppendEmpty()\n\n\terr = consumer.ConsumeProfiles(ctx, pd)\n\tassert.Equal(t, downstreamErr, err)\n\n\tvar rm metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &rm)\n\trequire.NoError(t, err)\n\trequire.Len(t, rm.ScopeMetrics, 1)\n\trequire.Len(t, rm.ScopeMetrics[0].Metrics, 2)\n\n\tvar itemMetric, sizeMetric metricdata.Metrics\n\tfor _, m := range rm.ScopeMetrics[0].Metrics {\n\t\tswitch m.Name {\n\t\tcase \"item_counter\":\n\t\t\titemMetric = m\n\t\tcase \"size_counter\":\n\t\t\tsizeMetric = m\n\t\t}\n\t}\n\trequire.NotNil(t, itemMetric)\n\trequire.NotNil(t, sizeMetric)\n\n\titemData := itemMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, itemData.DataPoints, 1)\n\trequire.Equal(t, int64(1), itemData.DataPoints[0].Value)\n\n\titemAttrs := itemData.DataPoints[0].Attributes\n\trequire.Equal(t, 1, itemAttrs.Len())\n\tval, ok := itemAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"failure\", val.Emit())\n\n\tsizeData := sizeMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, sizeData.DataPoints, 1)\n\trequire.Positive(t, sizeData.DataPoints[0].Value)\n\n\tsizeAttrs := sizeData.DataPoints[0].Attributes\n\trequire.Equal(t, 1, sizeAttrs.Len())\n\tval, ok = sizeAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"failure\", val.Emit())\n\n\t// Check that the logger was called with an error\n\trequire.Len(t, logs.All(), 1)\n\tassert.Contains(t, logs.All()[0].Message, \"Profiles pipeline component had an error\")\n}\n\nfunc TestProfilesWithStaticAttributes(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\tmockConsumer := &mockProfilesConsumer{}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tstaticAttr := attribute.String(\"test\", \"value\")\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewProfiles(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: logger},\n\t\tobsconsumer.WithStaticDataPointAttribute(staticAttr))\n\n\tpd := pprofile.NewProfiles()\n\tr := pd.ResourceProfiles().AppendEmpty()\n\tsp := r.ScopeProfiles().AppendEmpty()\n\tsp.Profiles().AppendEmpty().Samples().AppendEmpty()\n\n\terr = consumer.ConsumeProfiles(ctx, pd)\n\trequire.NoError(t, err)\n\n\tvar rm metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &rm)\n\trequire.NoError(t, err)\n\trequire.Len(t, rm.ScopeMetrics, 1)\n\trequire.Len(t, rm.ScopeMetrics[0].Metrics, 2)\n\n\tvar itemMetric, sizeMetric metricdata.Metrics\n\tfor _, m := range rm.ScopeMetrics[0].Metrics {\n\t\tswitch m.Name {\n\t\tcase \"item_counter\":\n\t\t\titemMetric = m\n\t\tcase \"size_counter\":\n\t\t\tsizeMetric = m\n\t\t}\n\t}\n\trequire.NotNil(t, itemMetric)\n\trequire.NotNil(t, sizeMetric)\n\n\titemData := itemMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, itemData.DataPoints, 1)\n\trequire.Equal(t, int64(1), itemData.DataPoints[0].Value)\n\n\titemAttrs := itemData.DataPoints[0].Attributes\n\trequire.Equal(t, 2, itemAttrs.Len())\n\tval, ok := itemAttrs.Value(attribute.Key(\"test\"))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"value\", val.Emit())\n\tval, ok = itemAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\tsizeData := sizeMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, sizeData.DataPoints, 1)\n\trequire.Positive(t, sizeData.DataPoints[0].Value)\n\n\tsizeAttrs := sizeData.DataPoints[0].Attributes\n\trequire.Equal(t, 2, sizeAttrs.Len())\n\tval, ok = sizeAttrs.Value(attribute.Key(\"test\"))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"value\", val.Emit())\n\tval, ok = sizeAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\t// Check that the logger was not called\n\tassert.Empty(t, logs.All())\n}\n\nfunc TestProfilesMultipleItemsMixedOutcomes(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\texpectedErr := errors.New(\"test error\")\n\tdownstreamErr := consumererror.NewDownstream(expectedErr)\n\tmockConsumer := &mockProfilesConsumer{}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewProfiles(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: logger})\n\n\t// First batch: 2 successful items\n\tpd1 := pprofile.NewProfiles()\n\tfor range 2 {\n\t\tr := pd1.ResourceProfiles().AppendEmpty()\n\t\tsp := r.ScopeProfiles().AppendEmpty()\n\t\tsp.Profiles().AppendEmpty().Samples().AppendEmpty()\n\t}\n\terr = consumer.ConsumeProfiles(ctx, pd1)\n\trequire.NoError(t, err)\n\n\t// Second batch: 1 failed item\n\tmockConsumer.err = expectedErr\n\tpd2 := pprofile.NewProfiles()\n\tr := pd2.ResourceProfiles().AppendEmpty()\n\tsp := r.ScopeProfiles().AppendEmpty()\n\tsp.Profiles().AppendEmpty().Samples().AppendEmpty()\n\terr = consumer.ConsumeProfiles(ctx, pd2)\n\tassert.Equal(t, downstreamErr, err)\n\n\t// Third batch: 2 successful items\n\tmockConsumer.err = nil\n\tpd3 := pprofile.NewProfiles()\n\tfor range 2 {\n\t\tr = pd3.ResourceProfiles().AppendEmpty()\n\t\tsp = r.ScopeProfiles().AppendEmpty()\n\t\tsp.Profiles().AppendEmpty().Samples().AppendEmpty()\n\t}\n\terr = consumer.ConsumeProfiles(ctx, pd3)\n\trequire.NoError(t, err)\n\n\t// Fourth batch: 1 failed item\n\tmockConsumer.err = expectedErr\n\tpd4 := pprofile.NewProfiles()\n\tr = pd4.ResourceProfiles().AppendEmpty()\n\tsp = r.ScopeProfiles().AppendEmpty()\n\tsp.Profiles().AppendEmpty().Samples().AppendEmpty()\n\terr = consumer.ConsumeProfiles(ctx, pd4)\n\tassert.Equal(t, downstreamErr, err)\n\n\tvar rm metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &rm)\n\trequire.NoError(t, err)\n\trequire.Len(t, rm.ScopeMetrics, 1)\n\trequire.Len(t, rm.ScopeMetrics[0].Metrics, 2)\n\n\tvar itemMetric, sizeMetric metricdata.Metrics\n\tfor _, m := range rm.ScopeMetrics[0].Metrics {\n\t\tswitch m.Name {\n\t\tcase \"item_counter\":\n\t\t\titemMetric = m\n\t\tcase \"size_counter\":\n\t\t\tsizeMetric = m\n\t\t}\n\t}\n\trequire.NotNil(t, itemMetric)\n\trequire.NotNil(t, sizeMetric)\n\n\titemData := itemMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, itemData.DataPoints, 2)\n\tsizeData := sizeMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, sizeData.DataPoints, 2)\n\n\tvar successDP, failureDP metricdata.DataPoint[int64]\n\tfor _, dp := range itemData.DataPoints {\n\t\tval, ok := dp.Attributes.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\t\tif ok && val.Emit() == \"success\" {\n\t\t\tsuccessDP = dp\n\t\t} else {\n\t\t\tfailureDP = dp\n\t\t}\n\t}\n\trequire.Equal(t, int64(4), successDP.Value)\n\trequire.Equal(t, int64(2), failureDP.Value)\n\n\tvar successSizeDP, failureSizeDP metricdata.DataPoint[int64]\n\tfor _, dp := range sizeData.DataPoints {\n\t\tval, ok := dp.Attributes.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\t\tif ok && val.Emit() == \"success\" {\n\t\t\tsuccessSizeDP = dp\n\t\t} else {\n\t\t\tfailureSizeDP = dp\n\t\t}\n\t}\n\trequire.Equal(t, int64(76), successSizeDP.Value)\n\trequire.Equal(t, int64(40), failureSizeDP.Value)\n\n\t// Check that the logger was called for errors\n\trequire.Len(t, logs.All(), 2)\n\tfor _, log := range logs.All() {\n\t\tassert.Contains(t, log.Message, \"Profiles pipeline component had an error\")\n\t}\n}\n\nfunc TestProfilesCapabilities(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tmockConsumer := &mockProfilesConsumer{\n\t\tcapabilities: consumer.Capabilities{MutatesData: true},\n\t}\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\tsizeCounterDisabled := newDisabledCounter(sizeCounter)\n\n\t// Test with item counter only\n\tconsumer := obsconsumer.NewProfiles(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounterDisabled, Logger: zap.NewNop()})\n\trequire.Equal(t, consumer.Capabilities(), mockConsumer.capabilities)\n\n\t// Test with both counters\n\tconsumer = obsconsumer.NewProfiles(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: zap.NewNop()})\n\trequire.Equal(t, consumer.Capabilities(), mockConsumer.capabilities)\n}\n"
  },
  {
    "path": "service/internal/obsconsumer/telemetry.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage obsconsumer // import \"go.opentelemetry.io/collector/service/internal/obsconsumer\"\n\nimport (\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.uber.org/zap\"\n)\n\n// Settings defines the settings for telemetry in the obsconsumer package.\ntype Settings struct {\n\t// ItemCounter is the metric to count the number of items processed.\n\tItemCounter metric.Int64Counter\n\n\t// SizeCounter is the metric to count the size of items processed.\n\tSizeCounter metric.Int64Counter\n\n\t// Logger is the logger for the obsconsumer package.\n\tLogger *zap.Logger\n}\n"
  },
  {
    "path": "service/internal/obsconsumer/traces.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage obsconsumer // import \"go.opentelemetry.io/collector/service/internal/obsconsumer\"\n\nimport (\n\t\"context\"\n\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/internal/telemetry\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n)\n\nvar (\n\t_               consumer.Traces = obsTraces{}\n\ttracesMarshaler                 = &ptrace.ProtoMarshaler{}\n)\n\nfunc NewTraces(cons consumer.Traces, set Settings, opts ...Option) consumer.Traces {\n\tif !metadata.TelemetryNewPipelineTelemetryFeatureGate.IsEnabled() {\n\t\treturn cons\n\t}\n\n\to := options{}\n\tfor _, opt := range opts {\n\t\topt(&o)\n\t}\n\n\tconsumerSet := Settings{\n\t\tItemCounter: set.ItemCounter,\n\t\tSizeCounter: set.SizeCounter,\n\t\tLogger:      set.Logger.With(telemetry.ToZapFields(o.staticDataPointAttributes)...),\n\t}\n\n\treturn obsTraces{\n\t\tconsumer:        cons,\n\t\tset:             consumerSet,\n\t\tcompiledOptions: o.compile(),\n\t}\n}\n\ntype obsTraces struct {\n\tconsumer consumer.Traces\n\tset      Settings\n\tcompiledOptions\n}\n\n// ConsumeTraces measures telemetry before calling ConsumeTraces because the data may be mutated downstream\nfunc (c obsTraces) ConsumeTraces(ctx context.Context, td ptrace.Traces) error {\n\t// Use a pointer to so that deferred function can depend on the result of ConsumeTraces\n\tattrs := &c.withSuccessAttrs\n\n\titemCount := td.SpanCount()\n\tdefer func() {\n\t\tc.set.ItemCounter.Add(ctx, int64(itemCount), *attrs)\n\t}()\n\n\tif isEnabled(ctx, c.set.SizeCounter) {\n\t\tbyteCount := int64(tracesMarshaler.TracesSize(td))\n\t\tdefer func() {\n\t\t\tc.set.SizeCounter.Add(ctx, byteCount, *attrs)\n\t\t}()\n\t}\n\n\terr := c.consumer.ConsumeTraces(ctx, td)\n\tif err != nil {\n\t\tif consumererror.IsDownstream(err) {\n\t\t\tattrs = &c.withRefusedAttrs\n\t\t} else {\n\t\t\tattrs = &c.withFailureAttrs\n\t\t\terr = consumererror.NewDownstream(err)\n\t\t}\n\t\tif c.set.Logger.Core().Enabled(zap.DebugLevel) {\n\t\t\tc.set.Logger.Debug(\"Traces pipeline component had an error\", zap.Error(err), zap.Int(\"item count\", itemCount))\n\t\t}\n\t}\n\treturn err\n}\n\nfunc (c obsTraces) Capabilities() consumer.Capabilities {\n\treturn c.consumer.Capabilities()\n}\n"
  },
  {
    "path": "service/internal/obsconsumer/traces_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage obsconsumer_test\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\tsdkmetric \"go.opentelemetry.io/otel/sdk/metric\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumererror\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/service/internal/obsconsumer\"\n)\n\ntype mockTracesConsumer struct {\n\terr          error\n\tcapabilities consumer.Capabilities\n}\n\nfunc (m *mockTracesConsumer) ConsumeTraces(_ context.Context, _ ptrace.Traces) error {\n\treturn m.err\n}\n\nfunc (m *mockTracesConsumer) Capabilities() consumer.Capabilities {\n\treturn m.capabilities\n}\n\nfunc TestTracesNopWhenGateDisabled(t *testing.T) {\n\tsetGateForTest(t, false)\n\n\tmp := sdkmetric.NewMeterProvider()\n\tmeter := mp.Meter(\"test\")\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tcons := consumertest.NewNop()\n\trequire.Equal(t, cons, obsconsumer.NewTraces(cons, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: zap.NewNop()}))\n}\n\nfunc TestTracesItemsOnly(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\tmockConsumer := &mockTracesConsumer{}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\tsizeCounterDisabled := newDisabledCounter(sizeCounter)\n\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewTraces(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounterDisabled, Logger: logger})\n\n\ttd := ptrace.NewTraces()\n\tr := td.ResourceSpans().AppendEmpty()\n\tss := r.ScopeSpans().AppendEmpty()\n\tss.Spans().AppendEmpty()\n\n\terr = consumer.ConsumeTraces(ctx, td)\n\trequire.NoError(t, err)\n\n\tvar metrics metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &metrics)\n\trequire.NoError(t, err)\n\trequire.Len(t, metrics.ScopeMetrics, 1)\n\trequire.Len(t, metrics.ScopeMetrics[0].Metrics, 1)\n\n\tmetric := metrics.ScopeMetrics[0].Metrics[0]\n\trequire.Equal(t, \"item_counter\", metric.Name)\n\n\tdata := metric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, data.DataPoints, 1)\n\trequire.Equal(t, int64(1), data.DataPoints[0].Value)\n\n\tattrs := data.DataPoints[0].Attributes\n\trequire.Equal(t, 1, attrs.Len())\n\tval, ok := attrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\t// Check that the logger was not called\n\tassert.Empty(t, logs.All())\n}\n\nfunc TestTracesConsumeSuccess(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\tmockConsumer := &mockTracesConsumer{}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewTraces(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: logger})\n\n\ttd := ptrace.NewTraces()\n\tr := td.ResourceSpans().AppendEmpty()\n\tss := r.ScopeSpans().AppendEmpty()\n\tss.Spans().AppendEmpty()\n\n\terr = consumer.ConsumeTraces(ctx, td)\n\trequire.NoError(t, err)\n\n\tvar rm metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &rm)\n\trequire.NoError(t, err)\n\trequire.Len(t, rm.ScopeMetrics, 1)\n\trequire.Len(t, rm.ScopeMetrics[0].Metrics, 2)\n\n\tvar itemMetric, sizeMetric metricdata.Metrics\n\tfor _, m := range rm.ScopeMetrics[0].Metrics {\n\t\tswitch m.Name {\n\t\tcase \"item_counter\":\n\t\t\titemMetric = m\n\t\tcase \"size_counter\":\n\t\t\tsizeMetric = m\n\t\t}\n\t}\n\trequire.NotNil(t, itemMetric)\n\trequire.NotNil(t, sizeMetric)\n\n\titemData := itemMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, itemData.DataPoints, 1)\n\trequire.Equal(t, int64(1), itemData.DataPoints[0].Value)\n\n\titemAttrs := itemData.DataPoints[0].Attributes\n\trequire.Equal(t, 1, itemAttrs.Len())\n\tval, ok := itemAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\tsizeData := sizeMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, sizeData.DataPoints, 1)\n\trequire.Positive(t, sizeData.DataPoints[0].Value)\n\n\tsizeAttrs := sizeData.DataPoints[0].Attributes\n\trequire.Equal(t, 1, sizeAttrs.Len())\n\tval, ok = sizeAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\t// Check that the logger was not called\n\tassert.Empty(t, logs.All())\n}\n\nfunc TestTracesConsumeFailure(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\texpectedErr := errors.New(\"test error\")\n\tdownstreamErr := consumererror.NewDownstream(expectedErr)\n\tmockConsumer := &mockTracesConsumer{err: expectedErr}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewTraces(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: logger})\n\n\ttd := ptrace.NewTraces()\n\tr := td.ResourceSpans().AppendEmpty()\n\tss := r.ScopeSpans().AppendEmpty()\n\tss.Spans().AppendEmpty()\n\n\terr = consumer.ConsumeTraces(ctx, td)\n\tassert.Equal(t, downstreamErr, err)\n\n\tvar rm metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &rm)\n\trequire.NoError(t, err)\n\trequire.Len(t, rm.ScopeMetrics, 1)\n\trequire.Len(t, rm.ScopeMetrics[0].Metrics, 2)\n\n\tvar itemMetric, sizeMetric metricdata.Metrics\n\tfor _, m := range rm.ScopeMetrics[0].Metrics {\n\t\tswitch m.Name {\n\t\tcase \"item_counter\":\n\t\t\titemMetric = m\n\t\tcase \"size_counter\":\n\t\t\tsizeMetric = m\n\t\t}\n\t}\n\trequire.NotNil(t, itemMetric)\n\trequire.NotNil(t, sizeMetric)\n\n\titemData := itemMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, itemData.DataPoints, 1)\n\trequire.Equal(t, int64(1), itemData.DataPoints[0].Value)\n\n\titemAttrs := itemData.DataPoints[0].Attributes\n\trequire.Equal(t, 1, itemAttrs.Len())\n\tval, ok := itemAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"failure\", val.Emit())\n\n\tsizeData := sizeMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, sizeData.DataPoints, 1)\n\trequire.Positive(t, sizeData.DataPoints[0].Value)\n\n\tsizeAttrs := sizeData.DataPoints[0].Attributes\n\trequire.Equal(t, 1, sizeAttrs.Len())\n\tval, ok = sizeAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"failure\", val.Emit())\n\n\t// Check that the logger was called with an error\n\trequire.Len(t, logs.All(), 1)\n\tassert.Contains(t, logs.All()[0].Message, \"Traces pipeline component had an error\")\n}\n\nfunc TestTracesWithStaticAttributes(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\tmockConsumer := &mockTracesConsumer{}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tstaticAttr := attribute.String(\"test\", \"value\")\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewTraces(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: logger},\n\t\tobsconsumer.WithStaticDataPointAttribute(staticAttr))\n\n\ttd := ptrace.NewTraces()\n\tr := td.ResourceSpans().AppendEmpty()\n\tss := r.ScopeSpans().AppendEmpty()\n\tss.Spans().AppendEmpty()\n\n\terr = consumer.ConsumeTraces(ctx, td)\n\trequire.NoError(t, err)\n\n\tvar rm metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &rm)\n\trequire.NoError(t, err)\n\trequire.Len(t, rm.ScopeMetrics, 1)\n\trequire.Len(t, rm.ScopeMetrics[0].Metrics, 2)\n\n\tvar itemMetric, sizeMetric metricdata.Metrics\n\tfor _, m := range rm.ScopeMetrics[0].Metrics {\n\t\tswitch m.Name {\n\t\tcase \"item_counter\":\n\t\t\titemMetric = m\n\t\tcase \"size_counter\":\n\t\t\tsizeMetric = m\n\t\t}\n\t}\n\trequire.NotNil(t, itemMetric)\n\trequire.NotNil(t, sizeMetric)\n\n\titemData := itemMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, itemData.DataPoints, 1)\n\trequire.Equal(t, int64(1), itemData.DataPoints[0].Value)\n\n\titemAttrs := itemData.DataPoints[0].Attributes\n\trequire.Equal(t, 2, itemAttrs.Len())\n\tval, ok := itemAttrs.Value(attribute.Key(\"test\"))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"value\", val.Emit())\n\tval, ok = itemAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\tsizeData := sizeMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, sizeData.DataPoints, 1)\n\trequire.Positive(t, sizeData.DataPoints[0].Value)\n\n\tsizeAttrs := sizeData.DataPoints[0].Attributes\n\trequire.Equal(t, 2, sizeAttrs.Len())\n\tval, ok = sizeAttrs.Value(attribute.Key(\"test\"))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"value\", val.Emit())\n\tval, ok = sizeAttrs.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\trequire.True(t, ok)\n\trequire.Equal(t, \"success\", val.Emit())\n\n\t// Check that the logger was not called\n\tassert.Empty(t, logs.All())\n}\n\nfunc TestTracesMultipleItemsMixedOutcomes(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tctx := context.Background()\n\texpectedErr := errors.New(\"test error\")\n\tdownstreamErr := consumererror.NewDownstream(expectedErr)\n\tmockConsumer := &mockTracesConsumer{}\n\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\n\tcore, logs := observer.New(zap.DebugLevel)\n\tlogger := zap.New(core)\n\tconsumer := obsconsumer.NewTraces(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: logger})\n\n\t// First batch: 2 successful items\n\ttd1 := ptrace.NewTraces()\n\tfor range 2 {\n\t\tr := td1.ResourceSpans().AppendEmpty()\n\t\tss := r.ScopeSpans().AppendEmpty()\n\t\tss.Spans().AppendEmpty()\n\t}\n\terr = consumer.ConsumeTraces(ctx, td1)\n\trequire.NoError(t, err)\n\n\t// Second batch: 1 failed item\n\tmockConsumer.err = expectedErr\n\ttd2 := ptrace.NewTraces()\n\tr := td2.ResourceSpans().AppendEmpty()\n\tss := r.ScopeSpans().AppendEmpty()\n\tss.Spans().AppendEmpty()\n\terr = consumer.ConsumeTraces(ctx, td2)\n\tassert.Equal(t, downstreamErr, err)\n\n\t// Third batch: 2 successful items\n\tmockConsumer.err = nil\n\ttd3 := ptrace.NewTraces()\n\tfor range 2 {\n\t\tr = td3.ResourceSpans().AppendEmpty()\n\t\tss = r.ScopeSpans().AppendEmpty()\n\t\tss.Spans().AppendEmpty()\n\t}\n\terr = consumer.ConsumeTraces(ctx, td3)\n\trequire.NoError(t, err)\n\n\t// Fourth batch: 1 failed item\n\tmockConsumer.err = expectedErr\n\ttd4 := ptrace.NewTraces()\n\tr = td4.ResourceSpans().AppendEmpty()\n\tss = r.ScopeSpans().AppendEmpty()\n\tss.Spans().AppendEmpty()\n\terr = consumer.ConsumeTraces(ctx, td4)\n\tassert.Equal(t, downstreamErr, err)\n\n\tvar rm metricdata.ResourceMetrics\n\terr = reader.Collect(ctx, &rm)\n\trequire.NoError(t, err)\n\trequire.Len(t, rm.ScopeMetrics, 1)\n\trequire.Len(t, rm.ScopeMetrics[0].Metrics, 2)\n\n\tvar itemMetric, sizeMetric metricdata.Metrics\n\tfor _, m := range rm.ScopeMetrics[0].Metrics {\n\t\tswitch m.Name {\n\t\tcase \"item_counter\":\n\t\t\titemMetric = m\n\t\tcase \"size_counter\":\n\t\t\tsizeMetric = m\n\t\t}\n\t}\n\trequire.NotNil(t, itemMetric)\n\trequire.NotNil(t, sizeMetric)\n\n\titemData := itemMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, itemData.DataPoints, 2)\n\tsizeData := sizeMetric.Data.(metricdata.Sum[int64])\n\trequire.Len(t, sizeData.DataPoints, 2)\n\n\t// Find success and failure data points\n\tvar successDP, failureDP metricdata.DataPoint[int64]\n\tfor _, dp := range itemData.DataPoints {\n\t\tval, ok := dp.Attributes.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\t\tif ok && val.Emit() == \"success\" {\n\t\t\tsuccessDP = dp\n\t\t} else {\n\t\t\tfailureDP = dp\n\t\t}\n\t}\n\trequire.Equal(t, int64(4), successDP.Value)\n\trequire.Equal(t, int64(2), failureDP.Value)\n\n\tvar successSizeDP, failureSizeDP metricdata.DataPoint[int64]\n\tfor _, dp := range sizeData.DataPoints {\n\t\tval, ok := dp.Attributes.Value(attribute.Key(obsconsumer.ComponentOutcome))\n\t\tif ok && val.Emit() == \"success\" {\n\t\t\tsuccessSizeDP = dp\n\t\t} else {\n\t\t\tfailureSizeDP = dp\n\t\t}\n\t}\n\trequire.Equal(t, int64(72), successSizeDP.Value)\n\trequire.Equal(t, int64(36), failureSizeDP.Value)\n\n\t// Check that the logger was called for errors\n\trequire.Len(t, logs.All(), 2)\n\tfor _, log := range logs.All() {\n\t\tassert.Contains(t, log.Message, \"Traces pipeline component had an error\")\n\t}\n}\n\nfunc TestTracesCapabilities(t *testing.T) {\n\tsetGateForTest(t, true)\n\n\tmockConsumer := &mockTracesConsumer{\n\t\tcapabilities: consumer.Capabilities{MutatesData: true},\n\t}\n\treader := sdkmetric.NewManualReader()\n\tmp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))\n\tmeter := mp.Meter(\"test\")\n\n\titemCounter, err := meter.Int64Counter(\"item_counter\")\n\trequire.NoError(t, err)\n\tsizeCounter, err := meter.Int64Counter(\"size_counter\")\n\trequire.NoError(t, err)\n\tsizeCounterDisabled := newDisabledCounter(sizeCounter)\n\n\t// Test with item counter only\n\tconsumer := obsconsumer.NewTraces(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounterDisabled, Logger: zap.NewNop()})\n\trequire.Equal(t, consumer.Capabilities(), mockConsumer.capabilities)\n\n\t// Test with both counters\n\tconsumer = obsconsumer.NewTraces(mockConsumer, obsconsumer.Settings{ItemCounter: itemCounter, SizeCounter: sizeCounter, Logger: zap.NewNop()})\n\trequire.Equal(t, consumer.Capabilities(), mockConsumer.capabilities)\n}\n"
  },
  {
    "path": "service/internal/proctelemetry/process_telemetry.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proctelemetry // import \"go.opentelemetry.io/collector/service/internal/proctelemetry\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"os\"\n\t\"runtime\"\n\t\"sync\"\n\t\"time\"\n\n\t\"github.com/shirou/gopsutil/v4/common\"\n\t\"github.com/shirou/gopsutil/v4/process\"\n\t\"go.opentelemetry.io/otel/metric\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n)\n\n// processMetrics is a struct that contains views related to process metrics (cpu, mem, etc)\ntype processMetrics struct {\n\tstartTimeUnixNano int64\n\tproc              *process.Process\n\tcontext           context.Context\n\n\t// mu protects everything bellow.\n\tmu         sync.Mutex\n\tlastMsRead time.Time\n\tms         *runtime.MemStats\n}\n\ntype RegisterOption interface {\n\tapply(*registerOption)\n}\n\ntype registerOption struct {\n\thostProc string\n}\n\ntype registerOptionFunc func(*registerOption)\n\nfunc (fn registerOptionFunc) apply(set *registerOption) {\n\tfn(set)\n}\n\n// WithHostProc overrides the /proc folder on Linux used by process telemetry.\nfunc WithHostProc(hostProc string) RegisterOption {\n\treturn registerOptionFunc(func(uo *registerOption) {\n\t\tuo.hostProc = hostProc\n\t})\n}\n\n// RegisterProcessMetrics creates a new set of processMetrics (mem, cpu) that can be used to measure\n// basic information about this process.\nfunc RegisterProcessMetrics(cfg component.TelemetrySettings, opts ...RegisterOption) error {\n\tset := registerOption{}\n\tfor _, opt := range opts {\n\t\topt.apply(&set)\n\t}\n\tvar err error\n\tpm := &processMetrics{\n\t\tstartTimeUnixNano: time.Now().UnixNano(),\n\t\tms:                &runtime.MemStats{},\n\t}\n\n\tctx := context.Background()\n\tif set.hostProc != \"\" {\n\t\tctx = context.WithValue(ctx, common.EnvKey, common.EnvMap{common.HostProcEnvKey: set.hostProc})\n\t}\n\tpm.context = ctx\n\tpm.proc, err = process.NewProcessWithContext(pm.context, int32(os.Getpid()))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\ttb, err := metadata.NewTelemetryBuilder(cfg)\n\tif err != nil {\n\t\treturn err\n\t}\n\treturn errors.Join(\n\t\ttb.RegisterProcessUptimeCallback(pm.updateProcessUptime),\n\t\ttb.RegisterProcessRuntimeHeapAllocBytesCallback(pm.updateAllocMem),\n\t\ttb.RegisterProcessRuntimeTotalAllocBytesCallback(pm.updateTotalAllocMem),\n\t\ttb.RegisterProcessRuntimeTotalSysMemoryBytesCallback(pm.updateSysMem),\n\t\ttb.RegisterProcessCPUSecondsCallback(pm.updateCPUSeconds),\n\t\ttb.RegisterProcessMemoryRssCallback(pm.updateRSSMemory),\n\t)\n}\n\nfunc (pm *processMetrics) updateProcessUptime(_ context.Context, obs metric.Float64Observer) error {\n\tnow := time.Now().UnixNano()\n\tobs.Observe(float64(now-pm.startTimeUnixNano) / 1e9)\n\treturn nil\n}\n\nfunc (pm *processMetrics) updateAllocMem(_ context.Context, obs metric.Int64Observer) error {\n\tpm.mu.Lock()\n\tdefer pm.mu.Unlock()\n\tpm.readMemStatsIfNeeded()\n\tobs.Observe(int64(pm.ms.Alloc))\n\treturn nil\n}\n\nfunc (pm *processMetrics) updateTotalAllocMem(_ context.Context, obs metric.Int64Observer) error {\n\tpm.mu.Lock()\n\tdefer pm.mu.Unlock()\n\tpm.readMemStatsIfNeeded()\n\tobs.Observe(int64(pm.ms.TotalAlloc))\n\treturn nil\n}\n\nfunc (pm *processMetrics) updateSysMem(_ context.Context, obs metric.Int64Observer) error {\n\tpm.mu.Lock()\n\tdefer pm.mu.Unlock()\n\tpm.readMemStatsIfNeeded()\n\tobs.Observe(int64(pm.ms.Sys))\n\treturn nil\n}\n\nfunc (pm *processMetrics) updateCPUSeconds(_ context.Context, obs metric.Float64Observer) error {\n\ttimes, err := pm.proc.TimesWithContext(pm.context) //nolint:contextcheck\n\tif err != nil {\n\t\treturn err\n\t}\n\n\tobs.Observe(times.User + times.System + times.Idle + times.Nice +\n\t\ttimes.Iowait + times.Irq + times.Softirq + times.Steal)\n\treturn nil\n}\n\nfunc (pm *processMetrics) updateRSSMemory(_ context.Context, obs metric.Int64Observer) error {\n\tmem, err := pm.proc.MemoryInfoWithContext(pm.context) //nolint:contextcheck\n\tif err != nil {\n\t\treturn err\n\t}\n\tobs.Observe(int64(mem.RSS))\n\treturn nil\n}\n\nfunc (pm *processMetrics) readMemStatsIfNeeded() {\n\tnow := time.Now()\n\t// If last time we read was less than one second ago just reuse the values\n\tif now.Sub(pm.lastMsRead) < time.Second {\n\t\treturn\n\t}\n\tpm.lastMsRead = now\n\truntime.ReadMemStats(pm.ms)\n}\n"
  },
  {
    "path": "service/internal/proctelemetry/process_telemetry_linux_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:build linux\n\npackage proctelemetry\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/service/internal/metadatatest\"\n)\n\nfunc TestProcessTelemetryWithHostProc(t *testing.T) {\n\t// Make the sure the environment variable value is not used.\n\tt.Setenv(\"HOST_PROC\", \"foo/bar\")\n\ttel := componenttest.NewTelemetry()\n\trequire.NoError(t, RegisterProcessMetrics(tel.NewTelemetrySettings(), WithHostProc(\"/proc\")))\n\n\tmetadatatest.AssertEqualProcessUptime(t, tel,\n\t\t[]metricdata.DataPoint[float64]{{}}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue())\n\n\tmetadatatest.AssertEqualProcessRuntimeHeapAllocBytes(t, tel,\n\t\t[]metricdata.DataPoint[int64]{{}}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue())\n\n\tmetadatatest.AssertEqualProcessRuntimeTotalAllocBytes(t, tel,\n\t\t[]metricdata.DataPoint[int64]{{}}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue())\n\n\tmetadatatest.AssertEqualProcessRuntimeTotalSysMemoryBytes(t, tel,\n\t\t[]metricdata.DataPoint[int64]{{}}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue())\n\n\tmetadatatest.AssertEqualProcessCPUSeconds(t, tel,\n\t\t[]metricdata.DataPoint[float64]{{}}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue())\n\n\tmetadatatest.AssertEqualProcessMemoryRss(t, tel,\n\t\t[]metricdata.DataPoint[int64]{{}}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue())\n}\n"
  },
  {
    "path": "service/internal/proctelemetry/process_telemetry_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage proctelemetry\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/service/internal/metadatatest\"\n)\n\nfunc TestProcessTelemetry(t *testing.T) {\n\ttel := componenttest.NewTelemetry()\n\trequire.NoError(t, RegisterProcessMetrics(tel.NewTelemetrySettings()))\n\n\tmetadatatest.AssertEqualProcessUptime(t, tel,\n\t\t[]metricdata.DataPoint[float64]{{}}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue())\n\n\tmetadatatest.AssertEqualProcessRuntimeHeapAllocBytes(t, tel,\n\t\t[]metricdata.DataPoint[int64]{{}}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue())\n\n\tmetadatatest.AssertEqualProcessRuntimeTotalAllocBytes(t, tel,\n\t\t[]metricdata.DataPoint[int64]{{}}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue())\n\n\tmetadatatest.AssertEqualProcessRuntimeTotalSysMemoryBytes(t, tel,\n\t\t[]metricdata.DataPoint[int64]{{}}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue())\n\n\tmetadatatest.AssertEqualProcessCPUSeconds(t, tel,\n\t\t[]metricdata.DataPoint[float64]{{}}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue())\n\n\tmetadatatest.AssertEqualProcessMemoryRss(t, tel,\n\t\t[]metricdata.DataPoint[int64]{{}}, metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue())\n}\n"
  },
  {
    "path": "service/internal/promtest/server_util.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage promtest // import \"go.opentelemetry.io/collector/service/internal/promtest\"\n\nimport (\n\t\"net\"\n\t\"strconv\"\n\t\"testing\"\n\n\tconfig \"go.opentelemetry.io/contrib/otelconf/v0.3.0\"\n\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n)\n\nfunc GetAvailableLocalIPv6AddressPrometheus(tb testing.TB) *config.Prometheus {\n\treturn addrToPrometheus(testutil.GetAvailableLocalIPv6Address(tb))\n}\n\nfunc GetAvailableLocalAddressPrometheus(tb testing.TB) *config.Prometheus {\n\treturn addrToPrometheus(testutil.GetAvailableLocalAddress(tb))\n}\n\nfunc addrToPrometheus(address string) *config.Prometheus {\n\thost, port, err := net.SplitHostPort(address)\n\tif host == \"::1\" {\n\t\thost = \"[::1]\"\n\t}\n\tif err != nil {\n\t\treturn nil\n\t}\n\tportInt, err := strconv.Atoi(port)\n\tif err != nil {\n\t\treturn nil\n\t}\n\treturn &config.Prometheus{\n\t\tHost:              &host,\n\t\tPort:              &portInt,\n\t\tWithoutScopeInfo:  ptr(true),\n\t\tWithoutUnits:      ptr(true),\n\t\tWithoutTypeSuffix: ptr(true),\n\t}\n}\n\nfunc ptr[T any](v T) *T {\n\treturn &v\n}\n"
  },
  {
    "path": "service/internal/refconsumer/logs.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage refconsumer // import \"go.opentelemetry.io/collector/service/internal/refconsumer\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n)\n\nfunc NewLogs(cons consumer.Logs) consumer.Logs {\n\treturn refLogs{\n\t\tconsumer: cons,\n\t}\n}\n\ntype refLogs struct {\n\tconsumer consumer.Logs\n}\n\n// ConsumeLogs measures telemetry before calling ConsumeLogs because the data may be mutated downstream\nfunc (c refLogs) ConsumeLogs(ctx context.Context, ld plog.Logs) error {\n\tif pref.MarkPipelineOwnedLogs(ld) {\n\t\tdefer pref.UnrefLogs(ld)\n\t}\n\treturn c.consumer.ConsumeLogs(ctx, ld)\n}\n\nfunc (c refLogs) Capabilities() consumer.Capabilities {\n\treturn c.consumer.Capabilities()\n}\n"
  },
  {
    "path": "service/internal/refconsumer/logs_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage refconsumer\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n)\n\nfunc TestLogsNopWhenGateDisabled(t *testing.T) {\n\tinitial := pref.UseProtoPooling.IsEnabled()\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(pref.UseProtoPooling.ID(), false))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.TelemetryNewPipelineTelemetryFeatureGate.ID(), initial))\n\t})\n\n\trefCons := NewLogs(consumertest.NewNop())\n\tld := testdata.GenerateLogs(10)\n\tassert.Equal(t, 10, ld.LogRecordCount())\n\trequire.NoError(t, refCons.ConsumeLogs(t.Context(), ld))\n\tassert.Equal(t, 10, ld.LogRecordCount())\n}\n\nfunc TestLogs(t *testing.T) {\n\tinitial := pref.UseProtoPooling.IsEnabled()\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(pref.UseProtoPooling.ID(), true))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.TelemetryNewPipelineTelemetryFeatureGate.ID(), initial))\n\t})\n\n\trefCons := NewLogs(consumertest.NewNop())\n\tld := testdata.GenerateLogs(10)\n\tassert.Equal(t, 10, ld.LogRecordCount())\n\trequire.NoError(t, refCons.ConsumeLogs(t.Context(), ld))\n\t// Data should be reset at this point.\n\tassert.Equal(t, 0, ld.LogRecordCount())\n}\n"
  },
  {
    "path": "service/internal/refconsumer/metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage refconsumer // import \"go.opentelemetry.io/collector/service/internal/refconsumer\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n)\n\nfunc NewMetrics(cons consumer.Metrics) consumer.Metrics {\n\treturn refMetrics{\n\t\tconsumer: cons,\n\t}\n}\n\ntype refMetrics struct {\n\tconsumer consumer.Metrics\n}\n\n// ConsumeMetrics measures telemetry before calling ConsumeMetrics because the data may be mutated downstream\nfunc (c refMetrics) ConsumeMetrics(ctx context.Context, ld pmetric.Metrics) error {\n\tif pref.MarkPipelineOwnedMetrics(ld) {\n\t\tdefer pref.UnrefMetrics(ld)\n\t}\n\treturn c.consumer.ConsumeMetrics(ctx, ld)\n}\n\nfunc (c refMetrics) Capabilities() consumer.Capabilities {\n\treturn c.consumer.Capabilities()\n}\n"
  },
  {
    "path": "service/internal/refconsumer/metrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage refconsumer\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n)\n\nfunc TestMetricsNopWhenGateDisabled(t *testing.T) {\n\tinitial := pref.UseProtoPooling.IsEnabled()\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(pref.UseProtoPooling.ID(), false))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.TelemetryNewPipelineTelemetryFeatureGate.ID(), initial))\n\t})\n\n\trefCons := NewMetrics(consumertest.NewNop())\n\tmd := testdata.GenerateMetrics(10)\n\tassert.Equal(t, 10, md.MetricCount())\n\trequire.NoError(t, refCons.ConsumeMetrics(t.Context(), md))\n\tassert.Equal(t, 10, md.MetricCount())\n}\n\nfunc TestMetrics(t *testing.T) {\n\tinitial := pref.UseProtoPooling.IsEnabled()\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(pref.UseProtoPooling.ID(), true))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.TelemetryNewPipelineTelemetryFeatureGate.ID(), initial))\n\t})\n\n\trefCons := NewMetrics(consumertest.NewNop())\n\tmd := testdata.GenerateMetrics(10)\n\tassert.Equal(t, 10, md.MetricCount())\n\trequire.NoError(t, refCons.ConsumeMetrics(t.Context(), md))\n\t// Data shoumd be reset at this point.\n\tassert.Equal(t, 0, md.MetricCount())\n}\n"
  },
  {
    "path": "service/internal/refconsumer/profiles.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage refconsumer // import \"go.opentelemetry.io/collector/service/internal/refconsumer\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n)\n\nfunc NewProfiles(cons xconsumer.Profiles) xconsumer.Profiles {\n\treturn refProfiles{\n\t\tconsumer: cons,\n\t}\n}\n\ntype refProfiles struct {\n\tconsumer xconsumer.Profiles\n}\n\n// ConsumeProfiles measures telemetry before calling ConsumeProfiles because the data may be mutated downstream\nfunc (c refProfiles) ConsumeProfiles(ctx context.Context, ld pprofile.Profiles) error {\n\tif pref.MarkPipelineOwnedProfiles(ld) {\n\t\tdefer pref.UnrefProfiles(ld)\n\t}\n\treturn c.consumer.ConsumeProfiles(ctx, ld)\n}\n\nfunc (c refProfiles) Capabilities() consumer.Capabilities {\n\treturn c.consumer.Capabilities()\n}\n"
  },
  {
    "path": "service/internal/refconsumer/profiles_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage refconsumer\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n)\n\nfunc TestProfilesNopWhenGateDisabled(t *testing.T) {\n\tinitial := pref.UseProtoPooling.IsEnabled()\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(pref.UseProtoPooling.ID(), false))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.TelemetryNewPipelineTelemetryFeatureGate.ID(), initial))\n\t})\n\n\trefCons := NewProfiles(consumertest.NewNop())\n\tpd := testdata.GenerateProfiles(10)\n\tassert.Equal(t, 10, pd.SampleCount())\n\trequire.NoError(t, refCons.ConsumeProfiles(t.Context(), pd))\n\tassert.Equal(t, 10, pd.SampleCount())\n}\n\nfunc TestProfiles(t *testing.T) {\n\tinitial := pref.UseProtoPooling.IsEnabled()\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(pref.UseProtoPooling.ID(), true))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.TelemetryNewPipelineTelemetryFeatureGate.ID(), initial))\n\t})\n\n\trefCons := NewProfiles(consumertest.NewNop())\n\tpd := testdata.GenerateProfiles(10)\n\tassert.Equal(t, 10, pd.SampleCount())\n\trequire.NoError(t, refCons.ConsumeProfiles(t.Context(), pd))\n\t// Data shoupd be reset at this point.\n\tassert.Equal(t, 0, pd.SampleCount())\n}\n"
  },
  {
    "path": "service/internal/refconsumer/traces.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage refconsumer // import \"go.opentelemetry.io/collector/service/internal/refconsumer\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n)\n\nfunc NewTraces(cons consumer.Traces) consumer.Traces {\n\treturn refTraces{\n\t\tconsumer: cons,\n\t}\n}\n\ntype refTraces struct {\n\tconsumer consumer.Traces\n}\n\n// ConsumeTraces measures telemetry before calling ConsumeTraces because the data may be mutated downstream\nfunc (c refTraces) ConsumeTraces(ctx context.Context, ld ptrace.Traces) error {\n\tif pref.MarkPipelineOwnedTraces(ld) {\n\t\tdefer pref.UnrefTraces(ld)\n\t}\n\treturn c.consumer.ConsumeTraces(ctx, ld)\n}\n\nfunc (c refTraces) Capabilities() consumer.Capabilities {\n\treturn c.consumer.Capabilities()\n}\n"
  },
  {
    "path": "service/internal/refconsumer/traces_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage refconsumer\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n)\n\nfunc TestTracesNopWhenGateDisabled(t *testing.T) {\n\tinitial := pref.UseProtoPooling.IsEnabled()\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(pref.UseProtoPooling.ID(), false))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.TelemetryNewPipelineTelemetryFeatureGate.ID(), initial))\n\t})\n\n\trefCons := NewTraces(consumertest.NewNop())\n\ttd := testdata.GenerateTraces(10)\n\tassert.Equal(t, 10, td.SpanCount())\n\trequire.NoError(t, refCons.ConsumeTraces(t.Context(), td))\n\tassert.Equal(t, 10, td.SpanCount())\n}\n\nfunc TestTraces(t *testing.T) {\n\tinitial := pref.UseProtoPooling.IsEnabled()\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(pref.UseProtoPooling.ID(), true))\n\tt.Cleanup(func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.TelemetryNewPipelineTelemetryFeatureGate.ID(), initial))\n\t})\n\n\trefCons := NewTraces(consumertest.NewNop())\n\ttd := testdata.GenerateTraces(10)\n\tassert.Equal(t, 10, td.SpanCount())\n\trequire.NoError(t, refCons.ConsumeTraces(t.Context(), td))\n\t// Data shoutd be reset at this point.\n\tassert.Equal(t, 0, td.SpanCount())\n}\n"
  },
  {
    "path": "service/internal/resource/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage resource // import \"go.opentelemetry.io/collector/service/internal/resource\"\n\nimport (\n\t\"github.com/google/uuid\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/sdk/resource\"\n\tsemconv \"go.opentelemetry.io/otel/semconv/v1.38.0\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\n// New resource from telemetry configuration.\nfunc New(buildInfo component.BuildInfo, resourceCfg map[string]*string) *resource.Resource {\n\tvar telAttrs []attribute.KeyValue\n\n\tfor k, v := range resourceCfg {\n\t\t// nil value indicates that the attribute should not be included in the telemetry.\n\t\tif v != nil {\n\t\t\ttelAttrs = append(telAttrs, attribute.String(k, *v))\n\t\t}\n\t}\n\n\tif _, ok := resourceCfg[string(semconv.ServiceNameKey)]; !ok {\n\t\t// AttributeServiceName is not specified in the config. Use the default service name.\n\t\ttelAttrs = append(telAttrs, semconv.ServiceNameKey.String(buildInfo.Command))\n\t}\n\n\tif _, ok := resourceCfg[string(semconv.ServiceInstanceIDKey)]; !ok {\n\t\t// AttributeServiceInstanceID is not specified in the config. Auto-generate one.\n\t\tinstanceUUID, _ := uuid.NewRandom()\n\t\tinstanceID := instanceUUID.String()\n\t\ttelAttrs = append(telAttrs, semconv.ServiceInstanceIDKey.String(instanceID))\n\t}\n\n\tif _, ok := resourceCfg[string(semconv.ServiceVersionKey)]; !ok {\n\t\t// AttributeServiceVersion is not specified in the config. Use the actual\n\t\t// build version.\n\t\ttelAttrs = append(telAttrs, semconv.ServiceVersionKey.String(buildInfo.Version))\n\t}\n\treturn resource.NewWithAttributes(semconv.SchemaURL, telAttrs...)\n}\n"
  },
  {
    "path": "service/internal/resource/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage resource\n\nimport (\n\t\"testing\"\n\n\t\"github.com/google/uuid\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tsdkresource \"go.opentelemetry.io/otel/sdk/resource\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nconst (\n\trandomUUIDSpecialValue = \"random-uuid\"\n)\n\nvar buildInfo = component.BuildInfo{\n\tCommand: \"otelcol\",\n\tVersion: \"1.0.0\",\n}\n\nfunc ptr[T any](v T) *T {\n\treturn &v\n}\n\nfunc TestNew(t *testing.T) {\n\ttests := []struct {\n\t\tname        string\n\t\tresourceCfg map[string]*string\n\t\twant        map[string]string\n\t}{\n\t\t{\n\t\t\tname:        \"empty\",\n\t\t\tresourceCfg: map[string]*string{},\n\t\t\twant: map[string]string{\n\t\t\t\t\"service.name\":        \"otelcol\",\n\t\t\t\t\"service.version\":     \"1.0.0\",\n\t\t\t\t\"service.instance.id\": randomUUIDSpecialValue,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"overwrite\",\n\t\t\tresourceCfg: map[string]*string{\n\t\t\t\t\"service.name\":        ptr(\"my-service\"),\n\t\t\t\t\"service.version\":     ptr(\"1.2.3\"),\n\t\t\t\t\"service.instance.id\": ptr(\"123\"),\n\t\t\t},\n\t\t\twant: map[string]string{\n\t\t\t\t\"service.name\":        \"my-service\",\n\t\t\t\t\"service.version\":     \"1.2.3\",\n\t\t\t\t\"service.instance.id\": \"123\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"remove\",\n\t\t\tresourceCfg: map[string]*string{\n\t\t\t\t\"service.name\":        nil,\n\t\t\t\t\"service.version\":     nil,\n\t\t\t\t\"service.instance.id\": nil,\n\t\t\t},\n\t\t\twant: map[string]string{},\n\t\t},\n\t\t{\n\t\t\tname: \"add\",\n\t\t\tresourceCfg: map[string]*string{\n\t\t\t\t\"host.name\": ptr(\"my-host\"),\n\t\t\t},\n\t\t\twant: map[string]string{\n\t\t\t\t\"service.name\":        \"otelcol\",\n\t\t\t\t\"service.version\":     \"1.0.0\",\n\t\t\t\t\"service.instance.id\": randomUUIDSpecialValue,\n\t\t\t\t\"host.name\":           \"my-host\",\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tres := New(buildInfo, tt.resourceCfg)\n\t\t\tgot := make(map[string]string)\n\t\t\tfor _, attr := range res.Attributes() {\n\t\t\t\tgot[string(attr.Key)] = attr.Value.Emit()\n\t\t\t}\n\n\t\t\tif tt.want[\"service.instance.id\"] == randomUUIDSpecialValue {\n\t\t\t\tassert.Contains(t, got, \"service.instance.id\")\n\n\t\t\t\t// Check that the value is a valid UUID.\n\t\t\t\t_, err := uuid.Parse(got[\"service.instance.id\"])\n\t\t\t\trequire.NoError(t, err)\n\n\t\t\t\t// Remove so that we can compare the rest of the map.\n\t\t\t\tdelete(got, \"service.instance.id\")\n\t\t\t\tdelete(tt.want, \"service.instance.id\")\n\t\t\t}\n\n\t\t\tassert.Equal(t, tt.want, got)\n\t\t})\n\t}\n}\n\nfunc pdataFromSdk(res *sdkresource.Resource) pcommon.Resource {\n\t// pcommon.NewResource is the best way to generate a new resource currently and is safe to use outside of tests.\n\t// Because the resource is signal agnostic, and we need a net new resource, not an existing one, this is the only\n\t// method of creating it without exposing internal packages.\n\tpcommonRes := pcommon.NewResource()\n\tfor _, keyValue := range res.Attributes() {\n\t\tpcommonRes.Attributes().PutStr(string(keyValue.Key), keyValue.Value.AsString())\n\t}\n\treturn pcommonRes\n}\n\nfunc TestBuildResource(t *testing.T) {\n\tbuildInfo := component.NewDefaultBuildInfo()\n\n\t// Check default config\n\tvar resMap map[string]*string\n\totelRes := New(buildInfo, resMap)\n\tres := pdataFromSdk(otelRes)\n\n\tassert.Equal(t, 3, res.Attributes().Len())\n\tvalue, ok := res.Attributes().Get(\"service.name\")\n\tassert.True(t, ok)\n\tassert.Equal(t, buildInfo.Command, value.AsString())\n\tvalue, ok = res.Attributes().Get(\"service.version\")\n\tassert.True(t, ok)\n\tassert.Equal(t, buildInfo.Version, value.AsString())\n\n\t_, ok = res.Attributes().Get(\"service.instance.id\")\n\tassert.True(t, ok)\n\n\t// Check override by nil\n\tresMap = map[string]*string{\n\t\t\"service.name\":        nil,\n\t\t\"service.version\":     nil,\n\t\t\"service.instance.id\": nil,\n\t}\n\totelRes = New(buildInfo, resMap)\n\tres = pdataFromSdk(otelRes)\n\n\t// Attributes should not exist since we nil-ified all.\n\tassert.Equal(t, 0, res.Attributes().Len())\n\n\t// Check override values\n\tstrPtr := func(v string) *string { return &v }\n\tresMap = map[string]*string{\n\t\t\"service.name\":        strPtr(\"a\"),\n\t\t\"service.version\":     strPtr(\"b\"),\n\t\t\"service.instance.id\": strPtr(\"c\"),\n\t}\n\totelRes = New(buildInfo, resMap)\n\tres = pdataFromSdk(otelRes)\n\n\tassert.Equal(t, 3, res.Attributes().Len())\n\tvalue, ok = res.Attributes().Get(\"service.name\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"a\", value.AsString())\n\tvalue, ok = res.Attributes().Get(\"service.version\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"b\", value.AsString())\n\tvalue, ok = res.Attributes().Get(\"service.instance.id\")\n\tassert.True(t, ok)\n\tassert.Equal(t, \"c\", value.AsString())\n}\n"
  },
  {
    "path": "service/internal/status/nop.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage status // import \"go.opentelemetry.io/collector/service/internal/status\"\n\nimport (\n\t\"go.opentelemetry.io/collector/component/componentstatus\"\n)\n\nfunc NewNopStatusReporter() Reporter {\n\treturn &nopStatusReporter{}\n}\n\ntype nopStatusReporter struct{}\n\nfunc (r *nopStatusReporter) Ready() {}\n\nfunc (r *nopStatusReporter) ReportStatus(*componentstatus.InstanceID, *componentstatus.Event) {}\n\nfunc (r *nopStatusReporter) ReportOKIfStarting(*componentstatus.InstanceID) {}\n"
  },
  {
    "path": "service/internal/status/nop_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage status // import \"go.opentelemetry.io/collector/service/internal/status\"\n\nimport \"testing\"\n\nfunc TestNopStatusReporter(*testing.T) {\n\tnop := NewNopStatusReporter()\n\tnop.ReportOKIfStarting(nil)\n\tnop.ReportStatus(nil, nil)\n}\n"
  },
  {
    "path": "service/internal/status/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage status\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "service/internal/status/status.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage status // import \"go.opentelemetry.io/collector/service/internal/status\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"sync\"\n\n\t\"go.opentelemetry.io/collector/component/componentstatus\"\n)\n\n// onTransitionFunc receives a componentstatus.Event on a successful state transition\ntype onTransitionFunc func(*componentstatus.Event)\n\n// errInvalidStateTransition is returned for invalid state transitions\nvar errInvalidStateTransition = errors.New(\"invalid state transition\")\n\n// fsm is a finite state machine that models transitions for component status\ntype fsm struct {\n\tcurrent      *componentstatus.Event\n\ttransitions  map[componentstatus.Status]map[componentstatus.Status]struct{}\n\tonTransition onTransitionFunc\n}\n\n// transition will attempt to execute a state transition. If it's successful, it calls the\n// onTransitionFunc with a Event representing the new state. Returns an error if the arguments\n// result in an invalid status, or if the state transition is not valid.\nfunc (m *fsm) transition(ev *componentstatus.Event) error {\n\tif _, ok := m.transitions[m.current.Status()][ev.Status()]; !ok {\n\t\treturn fmt.Errorf(\n\t\t\t\"cannot transition from %s to %s: %w\",\n\t\t\tm.current.Status(),\n\t\t\tev.Status(),\n\t\t\terrInvalidStateTransition,\n\t\t)\n\t}\n\tm.current = ev\n\tm.onTransition(ev)\n\treturn nil\n}\n\n// newFSM creates a state machine with all valid transitions for componentstatus.Status.\n// The initial state is set to componentstatus.StatusNone.\n// Transitions between the same status value are always allowed, as the new event may come with updated metadata.\nfunc newFSM(onTransition onTransitionFunc) *fsm {\n\treturn &fsm{\n\t\tcurrent:      componentstatus.NewEvent(componentstatus.StatusNone),\n\t\tonTransition: onTransition,\n\t\ttransitions: map[componentstatus.Status]map[componentstatus.Status]struct{}{\n\t\t\tcomponentstatus.StatusNone: {\n\t\t\t\tcomponentstatus.StatusStarting: {},\n\t\t\t},\n\t\t\tcomponentstatus.StatusStarting: {\n\t\t\t\tcomponentstatus.StatusOK:               {},\n\t\t\t\tcomponentstatus.StatusRecoverableError: {},\n\t\t\t\tcomponentstatus.StatusPermanentError:   {},\n\t\t\t\tcomponentstatus.StatusFatalError:       {},\n\t\t\t\tcomponentstatus.StatusStopping:         {},\n\t\t\t},\n\t\t\tcomponentstatus.StatusOK: {\n\t\t\t\tcomponentstatus.StatusOK:               {},\n\t\t\t\tcomponentstatus.StatusRecoverableError: {},\n\t\t\t\tcomponentstatus.StatusPermanentError:   {},\n\t\t\t\tcomponentstatus.StatusFatalError:       {},\n\t\t\t\tcomponentstatus.StatusStopping:         {},\n\t\t\t},\n\t\t\tcomponentstatus.StatusRecoverableError: {\n\t\t\t\tcomponentstatus.StatusRecoverableError: {},\n\t\t\t\tcomponentstatus.StatusOK:               {},\n\t\t\t\tcomponentstatus.StatusPermanentError:   {},\n\t\t\t\tcomponentstatus.StatusFatalError:       {},\n\t\t\t\tcomponentstatus.StatusStopping:         {},\n\t\t\t},\n\t\t\tcomponentstatus.StatusPermanentError: {\n\t\t\t\tcomponentstatus.StatusStopping: {},\n\t\t\t},\n\t\t\tcomponentstatus.StatusFatalError: {},\n\t\t\tcomponentstatus.StatusStopping: {\n\t\t\t\tcomponentstatus.StatusRecoverableError: {},\n\t\t\t\tcomponentstatus.StatusPermanentError:   {},\n\t\t\t\tcomponentstatus.StatusFatalError:       {},\n\t\t\t\tcomponentstatus.StatusStopped:          {},\n\t\t\t},\n\t\t\tcomponentstatus.StatusStopped: {},\n\t\t},\n\t}\n}\n\n// NotifyStatusFunc is the receiver of status events after successful state transitions\ntype NotifyStatusFunc func(*componentstatus.InstanceID, *componentstatus.Event)\n\n// InvalidTransitionFunc is the receiver of invalid transition errors\ntype InvalidTransitionFunc func(error)\n\n// ServiceStatusFunc is the expected type of ReportStatus\ntype ServiceStatusFunc func(*componentstatus.InstanceID, *componentstatus.Event)\n\n// ErrStatusNotReady is returned when trying to report status before service start\nvar ErrStatusNotReady = errors.New(\"report component status is not ready until service start\")\n\n// Reporter handles component status reporting\ntype Reporter interface {\n\tReportStatus(id *componentstatus.InstanceID, ev *componentstatus.Event)\n\tReportOKIfStarting(id *componentstatus.InstanceID)\n}\n\ntype reporter struct {\n\tmu                  sync.Mutex\n\tfsmMap              map[*componentstatus.InstanceID]*fsm\n\tonStatusChange      NotifyStatusFunc\n\tonInvalidTransition InvalidTransitionFunc\n}\n\n// NewReporter returns a reporter that will invoke the NotifyStatusFunc when a component's status\n// has changed.\nfunc NewReporter(onStatusChange NotifyStatusFunc, onInvalidTransition InvalidTransitionFunc) Reporter {\n\treturn &reporter{\n\t\tfsmMap:              make(map[*componentstatus.InstanceID]*fsm),\n\t\tonStatusChange:      onStatusChange,\n\t\tonInvalidTransition: onInvalidTransition,\n\t}\n}\n\n// ReportStatus reports status for the given InstanceID\nfunc (r *reporter) ReportStatus(\n\tid *componentstatus.InstanceID,\n\tev *componentstatus.Event,\n) {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\n\tif err := r.componentFSM(id).transition(ev); err != nil {\n\t\tr.onInvalidTransition(err)\n\t}\n}\n\nfunc (r *reporter) ReportOKIfStarting(id *componentstatus.InstanceID) {\n\tr.mu.Lock()\n\tdefer r.mu.Unlock()\n\tfsm := r.componentFSM(id)\n\tif fsm.current.Status() == componentstatus.StatusStarting {\n\t\tif err := fsm.transition(componentstatus.NewEvent(componentstatus.StatusOK)); err != nil {\n\t\t\tr.onInvalidTransition(err)\n\t\t}\n\t}\n}\n\n// Note: a lock must be acquired before calling this method.\nfunc (r *reporter) componentFSM(id *componentstatus.InstanceID) *fsm {\n\tfsm, ok := r.fsmMap[id]\n\tif !ok {\n\t\tfsm = newFSM(func(ev *componentstatus.Event) { r.onStatusChange(id, ev) })\n\t\tr.fsmMap[id] = fsm\n\t}\n\treturn fsm\n}\n\n// NewReportStatusFunc returns a function to be used as ReportStatus for componentstatus.TelemetrySettings\nfunc NewReportStatusFunc(\n\tid *componentstatus.InstanceID,\n\tsrvStatus ServiceStatusFunc,\n) func(*componentstatus.Event) {\n\treturn func(ev *componentstatus.Event) {\n\t\tsrvStatus(id, ev)\n\t}\n}\n"
  },
  {
    "path": "service/internal/status/status_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage status\n\nimport (\n\t\"fmt\"\n\t\"sync\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componentstatus\"\n)\n\nfunc TestStatusFSM(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname               string\n\t\treportedStatuses   []componentstatus.Status\n\t\texpectedStatuses   []componentstatus.Status\n\t\texpectedErrorCount int\n\t}{\n\t\t{\n\t\t\tname: \"successful startup and shutdown\",\n\t\t\treportedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusStopping,\n\t\t\t\tcomponentstatus.StatusStopped,\n\t\t\t},\n\t\t\texpectedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusStopping,\n\t\t\t\tcomponentstatus.StatusStopped,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"component recovered\",\n\t\t\treportedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusRecoverableError,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusStopping,\n\t\t\t\tcomponentstatus.StatusStopped,\n\t\t\t},\n\t\t\texpectedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusRecoverableError,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusStopping,\n\t\t\t\tcomponentstatus.StatusStopped,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"repeated OK and RecoverableError events are valid\",\n\t\t\treportedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusRecoverableError,\n\t\t\t\tcomponentstatus.StatusRecoverableError,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusStopping,\n\t\t\t\tcomponentstatus.StatusStopped,\n\t\t\t},\n\t\t\texpectedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusRecoverableError,\n\t\t\t\tcomponentstatus.StatusRecoverableError,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusStopping,\n\t\t\t\tcomponentstatus.StatusStopped,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"PermanentError is stoppable\",\n\t\t\treportedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusPermanentError,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusStopping,\n\t\t\t},\n\t\t\texpectedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusPermanentError,\n\t\t\t\tcomponentstatus.StatusStopping,\n\t\t\t},\n\t\t\texpectedErrorCount: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"FatalError is terminal\",\n\t\t\treportedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusFatalError,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t},\n\t\t\texpectedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusFatalError,\n\t\t\t},\n\t\t\texpectedErrorCount: 1,\n\t\t},\n\t\t{\n\t\t\tname: \"Stopped is terminal\",\n\t\t\treportedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusStopping,\n\t\t\t\tcomponentstatus.StatusStopped,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t},\n\t\t\texpectedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t\tcomponentstatus.StatusStopping,\n\t\t\t\tcomponentstatus.StatusStopped,\n\t\t\t},\n\t\t\texpectedErrorCount: 1,\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvar receivedStatuses []componentstatus.Status\n\t\t\tfsm := newFSM(\n\t\t\t\tfunc(ev *componentstatus.Event) {\n\t\t\t\t\treceivedStatuses = append(receivedStatuses, ev.Status())\n\t\t\t\t},\n\t\t\t)\n\n\t\t\terrorCount := 0\n\t\t\tfor _, status := range tt.reportedStatuses {\n\t\t\t\tif err := fsm.transition(componentstatus.NewEvent(status)); err != nil {\n\t\t\t\t\terrorCount++\n\t\t\t\t\trequire.ErrorIs(t, err, errInvalidStateTransition)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\trequire.Equal(t, tt.expectedErrorCount, errorCount)\n\t\t\trequire.Equal(t, tt.expectedStatuses, receivedStatuses)\n\t\t})\n\t}\n}\n\nfunc TestValidSeqsToStopped(t *testing.T) {\n\tevents := []*componentstatus.Event{\n\t\tcomponentstatus.NewEvent(componentstatus.StatusStarting),\n\t\tcomponentstatus.NewEvent(componentstatus.StatusOK),\n\t\tcomponentstatus.NewEvent(componentstatus.StatusRecoverableError),\n\t\tcomponentstatus.NewEvent(componentstatus.StatusPermanentError),\n\t\tcomponentstatus.NewEvent(componentstatus.StatusFatalError),\n\t}\n\n\tfor _, ev := range events {\n\t\tname := fmt.Sprintf(\"transition from: %s to: %s\", ev.Status(), componentstatus.StatusStopped)\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tfsm := newFSM(func(*componentstatus.Event) {})\n\t\t\tif ev.Status() != componentstatus.StatusStarting {\n\t\t\t\trequire.NoError(t, fsm.transition(componentstatus.NewEvent(componentstatus.StatusStarting)))\n\t\t\t}\n\t\t\trequire.NoError(t, fsm.transition(ev))\n\t\t\t// skipping to stopped is not allowed\n\t\t\terr := fsm.transition(componentstatus.NewEvent(componentstatus.StatusStopped))\n\t\t\trequire.ErrorIs(t, err, errInvalidStateTransition)\n\n\t\t\t// stopping -> stopped is allowed for non-fatal errors\n\t\t\terr = fsm.transition(componentstatus.NewEvent(componentstatus.StatusStopping))\n\t\t\tif ev.Status() == componentstatus.StatusFatalError {\n\t\t\t\trequire.ErrorIs(t, err, errInvalidStateTransition)\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.NoError(t, fsm.transition(componentstatus.NewEvent(componentstatus.StatusStopped)))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestStatusFuncs(t *testing.T) {\n\tid1 := &componentstatus.InstanceID{}\n\tid2 := &componentstatus.InstanceID{}\n\n\tactualStatuses := make(map[*componentstatus.InstanceID][]componentstatus.Status)\n\tstatusFunc := func(id *componentstatus.InstanceID, ev *componentstatus.Event) {\n\t\tactualStatuses[id] = append(actualStatuses[id], ev.Status())\n\t}\n\n\tstatuses1 := []componentstatus.Status{\n\t\tcomponentstatus.StatusStarting,\n\t\tcomponentstatus.StatusOK,\n\t\tcomponentstatus.StatusStopping,\n\t\tcomponentstatus.StatusStopped,\n\t}\n\n\tstatuses2 := []componentstatus.Status{\n\t\tcomponentstatus.StatusStarting,\n\t\tcomponentstatus.StatusOK,\n\t\tcomponentstatus.StatusRecoverableError,\n\t\tcomponentstatus.StatusOK,\n\t\tcomponentstatus.StatusStopping,\n\t\tcomponentstatus.StatusStopped,\n\t}\n\n\texpectedStatuses := map[*componentstatus.InstanceID][]componentstatus.Status{\n\t\tid1: statuses1,\n\t\tid2: statuses2,\n\t}\n\n\trep := NewReporter(statusFunc,\n\t\tfunc(err error) {\n\t\t\trequire.NoError(t, err)\n\t\t})\n\tcomp1Func := NewReportStatusFunc(id1, rep.ReportStatus)\n\tcomp2Func := NewReportStatusFunc(id2, rep.ReportStatus)\n\n\tfor _, st := range statuses1 {\n\t\tcomp1Func(componentstatus.NewEvent(st))\n\t}\n\n\tfor _, st := range statuses2 {\n\t\tcomp2Func(componentstatus.NewEvent(st))\n\t}\n\n\trequire.Equal(t, expectedStatuses, actualStatuses)\n}\n\nfunc TestStatusFuncsConcurrent(t *testing.T) {\n\tids := []*componentstatus.InstanceID{{}, {}, {}, {}}\n\tcount := 0\n\tstatusFunc := func(*componentstatus.InstanceID, *componentstatus.Event) {\n\t\tcount++\n\t}\n\trep := NewReporter(statusFunc,\n\t\tfunc(err error) {\n\t\t\trequire.NoError(t, err)\n\t\t})\n\n\twg := sync.WaitGroup{}\n\twg.Add(len(ids))\n\n\tfor _, id := range ids {\n\t\tgo func() {\n\t\t\tcompFn := NewReportStatusFunc(id, rep.ReportStatus)\n\t\t\tcompFn(componentstatus.NewEvent(componentstatus.StatusStarting))\n\t\t\tfor range 1000 {\n\t\t\t\tcompFn(componentstatus.NewEvent(componentstatus.StatusRecoverableError))\n\t\t\t\tcompFn(componentstatus.NewEvent(componentstatus.StatusOK))\n\t\t\t}\n\t\t\twg.Done()\n\t\t}()\n\t}\n\n\twg.Wait()\n\trequire.Equal(t, 8004, count)\n}\n\nfunc TestReportComponentOKIfStarting(t *testing.T) {\n\tfor _, tt := range []struct {\n\t\tname             string\n\t\tinitialStatuses  []componentstatus.Status\n\t\texpectedStatuses []componentstatus.Status\n\t}{\n\t\t{\n\t\t\tname: \"matching condition: StatusStarting\",\n\t\t\tinitialStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t},\n\t\t\texpectedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"non-matching condition StatusOK\",\n\t\t\tinitialStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t},\n\t\t\texpectedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusOK,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"non-matching condition RecoverableError\",\n\t\t\tinitialStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusRecoverableError,\n\t\t\t},\n\t\t\texpectedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusRecoverableError,\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"non-matching condition PermanentError\",\n\t\t\tinitialStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusPermanentError,\n\t\t\t},\n\t\t\texpectedStatuses: []componentstatus.Status{\n\t\t\t\tcomponentstatus.StatusStarting,\n\t\t\t\tcomponentstatus.StatusPermanentError,\n\t\t\t},\n\t\t},\n\t} {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tvar receivedStatuses []componentstatus.Status\n\n\t\t\trep := NewReporter(\n\t\t\t\tfunc(_ *componentstatus.InstanceID, ev *componentstatus.Event) {\n\t\t\t\t\treceivedStatuses = append(receivedStatuses, ev.Status())\n\t\t\t\t},\n\t\t\t\tfunc(err error) {\n\t\t\t\t\trequire.NoError(t, err)\n\t\t\t\t},\n\t\t\t)\n\n\t\t\tid := &componentstatus.InstanceID{}\n\t\t\tfor _, status := range tt.initialStatuses {\n\t\t\t\trep.ReportStatus(id, componentstatus.NewEvent(status))\n\t\t\t}\n\n\t\t\trep.ReportOKIfStarting(id)\n\n\t\t\trequire.Equal(t, tt.expectedStatuses, receivedStatuses)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "service/internal/testcomponents/example_connector.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testcomponents // import \"go.opentelemetry.io/collector/service/internal/testcomponents\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/xconnector\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n)\n\nvar connType = component.MustNewType(\"exampleconnector\")\n\n// ExampleConnectorFactory is factory for ExampleConnector.\nvar ExampleConnectorFactory = xconnector.NewFactory(\n\tconnType,\n\tcreateExampleConnectorDefaultConfig,\n\n\txconnector.WithTracesToTraces(createExampleTracesToTraces, component.StabilityLevelDevelopment),\n\txconnector.WithTracesToMetrics(createExampleTracesToMetrics, component.StabilityLevelDevelopment),\n\txconnector.WithTracesToLogs(createExampleTracesToLogs, component.StabilityLevelDevelopment),\n\txconnector.WithTracesToProfiles(createExampleTracesToProfiles, component.StabilityLevelDevelopment),\n\n\txconnector.WithMetricsToTraces(createExampleMetricsToTraces, component.StabilityLevelDevelopment),\n\txconnector.WithMetricsToMetrics(createExampleMetricsToMetrics, component.StabilityLevelDevelopment),\n\txconnector.WithMetricsToLogs(createExampleMetricsToLogs, component.StabilityLevelDevelopment),\n\txconnector.WithMetricsToProfiles(createExampleMetricsToProfiles, component.StabilityLevelDevelopment),\n\n\txconnector.WithLogsToTraces(createExampleLogsToTraces, component.StabilityLevelDevelopment),\n\txconnector.WithLogsToMetrics(createExampleLogsToMetrics, component.StabilityLevelDevelopment),\n\txconnector.WithLogsToLogs(createExampleLogsToLogs, component.StabilityLevelDevelopment),\n\txconnector.WithLogsToProfiles(createExampleLogsToProfiles, component.StabilityLevelDevelopment),\n\n\txconnector.WithProfilesToTraces(createExampleProfilesToTraces, component.StabilityLevelDevelopment),\n\txconnector.WithProfilesToMetrics(createExampleProfilesToMetrics, component.StabilityLevelDevelopment),\n\txconnector.WithProfilesToLogs(createExampleProfilesToLogs, component.StabilityLevelDevelopment),\n\txconnector.WithProfilesToProfiles(createExampleProfilesToProfiles, component.StabilityLevelDevelopment),\n)\n\nvar MockForwardConnectorFactory = xconnector.NewFactory(\n\tcomponent.MustNewType(\"mockforward\"),\n\tcreateExampleConnectorDefaultConfig,\n\txconnector.WithTracesToTraces(createExampleTracesToTraces, component.StabilityLevelDevelopment),\n\txconnector.WithMetricsToMetrics(createExampleMetricsToMetrics, component.StabilityLevelDevelopment),\n\txconnector.WithLogsToLogs(createExampleLogsToLogs, component.StabilityLevelDevelopment),\n\txconnector.WithProfilesToProfiles(createExampleProfilesToProfiles, component.StabilityLevelDevelopment),\n)\n\nfunc createExampleConnectorDefaultConfig() component.Config {\n\treturn &struct{}{}\n}\n\nfunc createExampleTracesToTraces(_ context.Context, set connector.Settings, _ component.Config, traces consumer.Traces) (connector.Traces, error) {\n\treturn &ExampleConnector{\n\t\tConsumeTracesFunc: traces.ConsumeTraces,\n\t\tmutatesData:       set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createExampleTracesToMetrics(_ context.Context, set connector.Settings, _ component.Config, metrics consumer.Metrics) (connector.Traces, error) {\n\treturn &ExampleConnector{\n\t\tConsumeTracesFunc: func(ctx context.Context, td ptrace.Traces) error {\n\t\t\treturn metrics.ConsumeMetrics(ctx, testdata.GenerateMetrics(td.SpanCount()))\n\t\t},\n\t\tmutatesData: set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createExampleTracesToLogs(_ context.Context, set connector.Settings, _ component.Config, logs consumer.Logs) (connector.Traces, error) {\n\treturn &ExampleConnector{\n\t\tConsumeTracesFunc: func(ctx context.Context, td ptrace.Traces) error {\n\t\t\treturn logs.ConsumeLogs(ctx, testdata.GenerateLogs(td.SpanCount()))\n\t\t},\n\t\tmutatesData: set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createExampleTracesToProfiles(_ context.Context, set connector.Settings, _ component.Config, profiles xconsumer.Profiles) (connector.Traces, error) {\n\treturn &ExampleConnector{\n\t\tConsumeTracesFunc: func(ctx context.Context, td ptrace.Traces) error {\n\t\t\treturn profiles.ConsumeProfiles(ctx, testdata.GenerateProfiles(td.SpanCount()))\n\t\t},\n\t\tmutatesData: set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createExampleMetricsToTraces(_ context.Context, set connector.Settings, _ component.Config, traces consumer.Traces) (connector.Metrics, error) {\n\treturn &ExampleConnector{\n\t\tConsumeMetricsFunc: func(ctx context.Context, md pmetric.Metrics) error {\n\t\t\treturn traces.ConsumeTraces(ctx, testdata.GenerateTraces(md.MetricCount()))\n\t\t},\n\t\tmutatesData: set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createExampleMetricsToMetrics(_ context.Context, set connector.Settings, _ component.Config, metrics consumer.Metrics) (connector.Metrics, error) {\n\treturn &ExampleConnector{\n\t\tConsumeMetricsFunc: metrics.ConsumeMetrics,\n\t\tmutatesData:        set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createExampleMetricsToLogs(_ context.Context, set connector.Settings, _ component.Config, logs consumer.Logs) (connector.Metrics, error) {\n\treturn &ExampleConnector{\n\t\tConsumeMetricsFunc: func(ctx context.Context, md pmetric.Metrics) error {\n\t\t\treturn logs.ConsumeLogs(ctx, testdata.GenerateLogs(md.MetricCount()))\n\t\t},\n\t\tmutatesData: set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createExampleMetricsToProfiles(_ context.Context, set connector.Settings, _ component.Config, profiles xconsumer.Profiles) (connector.Metrics, error) {\n\treturn &ExampleConnector{\n\t\tConsumeMetricsFunc: func(ctx context.Context, md pmetric.Metrics) error {\n\t\t\treturn profiles.ConsumeProfiles(ctx, testdata.GenerateProfiles(md.MetricCount()))\n\t\t},\n\t\tmutatesData: set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createExampleLogsToTraces(_ context.Context, set connector.Settings, _ component.Config, traces consumer.Traces) (connector.Logs, error) {\n\treturn &ExampleConnector{\n\t\tConsumeLogsFunc: func(ctx context.Context, ld plog.Logs) error {\n\t\t\treturn traces.ConsumeTraces(ctx, testdata.GenerateTraces(ld.LogRecordCount()))\n\t\t},\n\t\tmutatesData: set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createExampleLogsToMetrics(_ context.Context, set connector.Settings, _ component.Config, metrics consumer.Metrics) (connector.Logs, error) {\n\treturn &ExampleConnector{\n\t\tConsumeLogsFunc: func(ctx context.Context, ld plog.Logs) error {\n\t\t\treturn metrics.ConsumeMetrics(ctx, testdata.GenerateMetrics(ld.LogRecordCount()))\n\t\t},\n\t\tmutatesData: set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createExampleLogsToLogs(_ context.Context, set connector.Settings, _ component.Config, logs consumer.Logs) (connector.Logs, error) {\n\treturn &ExampleConnector{\n\t\tConsumeLogsFunc: logs.ConsumeLogs,\n\t\tmutatesData:     set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createExampleLogsToProfiles(_ context.Context, set connector.Settings, _ component.Config, profiles xconsumer.Profiles) (connector.Logs, error) {\n\treturn &ExampleConnector{\n\t\tConsumeLogsFunc: func(ctx context.Context, ld plog.Logs) error {\n\t\t\treturn profiles.ConsumeProfiles(ctx, testdata.GenerateProfiles(ld.LogRecordCount()))\n\t\t},\n\t\tmutatesData: set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createExampleProfilesToTraces(_ context.Context, set connector.Settings, _ component.Config, traces consumer.Traces) (xconnector.Profiles, error) {\n\treturn &ExampleConnector{\n\t\tConsumeProfilesFunc: func(ctx context.Context, _ pprofile.Profiles) error {\n\t\t\treturn traces.ConsumeTraces(ctx, testdata.GenerateTraces(1))\n\t\t},\n\t\tmutatesData: set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createExampleProfilesToMetrics(_ context.Context, set connector.Settings, _ component.Config, metrics consumer.Metrics) (xconnector.Profiles, error) {\n\treturn &ExampleConnector{\n\t\tConsumeProfilesFunc: func(ctx context.Context, _ pprofile.Profiles) error {\n\t\t\treturn metrics.ConsumeMetrics(ctx, testdata.GenerateMetrics(1))\n\t\t},\n\t\tmutatesData: set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createExampleProfilesToLogs(_ context.Context, set connector.Settings, _ component.Config, logs consumer.Logs) (xconnector.Profiles, error) {\n\treturn &ExampleConnector{\n\t\tConsumeProfilesFunc: func(ctx context.Context, _ pprofile.Profiles) error {\n\t\t\treturn logs.ConsumeLogs(ctx, testdata.GenerateLogs(1))\n\t\t},\n\t\tmutatesData: set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createExampleProfilesToProfiles(_ context.Context, set connector.Settings, _ component.Config, profiles xconsumer.Profiles) (xconnector.Profiles, error) {\n\treturn &ExampleConnector{\n\t\tConsumeProfilesFunc: profiles.ConsumeProfiles,\n\t\tmutatesData:         set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\ntype ExampleConnector struct {\n\tcomponentState\n\tconsumer.ConsumeTracesFunc\n\tconsumer.ConsumeMetricsFunc\n\tconsumer.ConsumeLogsFunc\n\txconsumer.ConsumeProfilesFunc\n\tmutatesData bool\n}\n\nfunc (c *ExampleConnector) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: c.mutatesData}\n}\n"
  },
  {
    "path": "service/internal/testcomponents/example_connector_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testcomponents\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\nfunc TestExampleConnector(t *testing.T) {\n\tconn := &ExampleConnector{}\n\thost := componenttest.NewNopHost()\n\tassert.False(t, conn.Started())\n\trequire.NoError(t, conn.Start(context.Background(), host))\n\tassert.True(t, conn.Started())\n\n\tassert.False(t, conn.Stopped())\n\trequire.NoError(t, conn.Shutdown(context.Background()))\n\tassert.True(t, conn.Stopped())\n}\n"
  },
  {
    "path": "service/internal/testcomponents/example_exporter.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testcomponents // import \"go.opentelemetry.io/collector/service/internal/testcomponents\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/exporter/xexporter\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/xpdata/pref\"\n)\n\nvar exporterType = component.MustNewType(\"exampleexporter\")\n\n// ExampleExporterFactory is factory for ExampleExporter.\nvar ExampleExporterFactory = xexporter.NewFactory(\n\texporterType,\n\tcreateExporterDefaultConfig,\n\txexporter.WithTraces(createTracesExporter, component.StabilityLevelDevelopment),\n\txexporter.WithMetrics(createMetricsExporter, component.StabilityLevelDevelopment),\n\txexporter.WithLogs(createLogsExporter, component.StabilityLevelDevelopment),\n\txexporter.WithProfiles(createProfilesExporter, component.StabilityLevelDevelopment),\n)\n\nfunc createExporterDefaultConfig() component.Config {\n\treturn &struct{}{}\n}\n\nfunc createTracesExporter(context.Context, exporter.Settings, component.Config) (exporter.Traces, error) {\n\treturn &ExampleExporter{}, nil\n}\n\nfunc createMetricsExporter(context.Context, exporter.Settings, component.Config) (exporter.Metrics, error) {\n\treturn &ExampleExporter{}, nil\n}\n\nfunc createLogsExporter(context.Context, exporter.Settings, component.Config) (exporter.Logs, error) {\n\treturn &ExampleExporter{}, nil\n}\n\nfunc createProfilesExporter(context.Context, exporter.Settings, component.Config) (xexporter.Profiles, error) {\n\treturn &ExampleExporter{}, nil\n}\n\n// ExampleExporter stores consumed traces, metrics, logs and profiles for testing purposes.\ntype ExampleExporter struct {\n\tcomponentState\n\tTraces   []ptrace.Traces\n\tMetrics  []pmetric.Metrics\n\tLogs     []plog.Logs\n\tProfiles []pprofile.Profiles\n}\n\n// ConsumeTraces receives ptrace.Traces for processing by the consumer.Traces.\nfunc (exp *ExampleExporter) ConsumeTraces(_ context.Context, td ptrace.Traces) error {\n\tpref.RefTraces(td)\n\texp.Traces = append(exp.Traces, td)\n\treturn nil\n}\n\n// ConsumeMetrics receives pmetric.Metrics for processing by the Metrics.\nfunc (exp *ExampleExporter) ConsumeMetrics(_ context.Context, md pmetric.Metrics) error {\n\tpref.RefMetrics(md)\n\texp.Metrics = append(exp.Metrics, md)\n\treturn nil\n}\n\n// ConsumeLogs receives plog.Logs for processing by the Logs.\nfunc (exp *ExampleExporter) ConsumeLogs(_ context.Context, ld plog.Logs) error {\n\tpref.RefLogs(ld)\n\texp.Logs = append(exp.Logs, ld)\n\treturn nil\n}\n\n// ConsumeProfiles receives pprofile.Profiles for processing by the xconsumer.Profiles.\nfunc (exp *ExampleExporter) ConsumeProfiles(_ context.Context, pd pprofile.Profiles) error {\n\tpref.RefProfiles(pd)\n\texp.Profiles = append(exp.Profiles, pd)\n\treturn nil\n}\n\nfunc (exp *ExampleExporter) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: false}\n}\n"
  },
  {
    "path": "service/internal/testcomponents/example_exporter_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testcomponents\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n)\n\nfunc TestExampleExporter(t *testing.T) {\n\texp := &ExampleExporter{}\n\thost := componenttest.NewNopHost()\n\tassert.False(t, exp.Started())\n\trequire.NoError(t, exp.Start(context.Background(), host))\n\tassert.True(t, exp.Started())\n\n\tassert.Empty(t, exp.Traces)\n\trequire.NoError(t, exp.ConsumeTraces(context.Background(), ptrace.NewTraces()))\n\tassert.Len(t, exp.Traces, 1)\n\n\tassert.Empty(t, exp.Metrics)\n\trequire.NoError(t, exp.ConsumeMetrics(context.Background(), pmetric.NewMetrics()))\n\tassert.Len(t, exp.Metrics, 1)\n\n\tassert.Empty(t, exp.Logs)\n\trequire.NoError(t, exp.ConsumeLogs(context.Background(), plog.NewLogs()))\n\tassert.Len(t, exp.Logs, 1)\n\n\tassert.Empty(t, exp.Profiles)\n\trequire.NoError(t, exp.ConsumeProfiles(context.Background(), pprofile.NewProfiles()))\n\tassert.Len(t, exp.Profiles, 1)\n\n\tassert.False(t, exp.Stopped())\n\trequire.NoError(t, exp.Shutdown(context.Background()))\n\tassert.True(t, exp.Stopped())\n}\n"
  },
  {
    "path": "service/internal/testcomponents/example_processor.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testcomponents // import \"go.opentelemetry.io/collector/service/internal/testcomponents\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/processor/xprocessor\"\n)\n\nvar procType = component.MustNewType(\"exampleprocessor\")\n\n// ExampleProcessorFactory is factory for ExampleProcessor.\nvar ExampleProcessorFactory = xprocessor.NewFactory(\n\tprocType,\n\tcreateDefaultConfig,\n\txprocessor.WithTraces(createTracesProcessor, component.StabilityLevelDevelopment),\n\txprocessor.WithMetrics(createMetricsProcessor, component.StabilityLevelDevelopment),\n\txprocessor.WithLogs(createLogsProcessor, component.StabilityLevelDevelopment),\n\txprocessor.WithProfiles(createProfilesProcessor, component.StabilityLevelDevelopment),\n)\n\n// CreateDefaultConfig creates the default configuration for the Processor.\nfunc createDefaultConfig() component.Config {\n\treturn &struct{}{}\n}\n\nfunc createTracesProcessor(_ context.Context, set processor.Settings, _ component.Config, nextConsumer consumer.Traces) (processor.Traces, error) {\n\treturn &ExampleProcessor{\n\t\tConsumeTracesFunc: nextConsumer.ConsumeTraces,\n\t\tmutatesData:       set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createMetricsProcessor(_ context.Context, set processor.Settings, _ component.Config, nextConsumer consumer.Metrics) (processor.Metrics, error) {\n\treturn &ExampleProcessor{\n\t\tConsumeMetricsFunc: nextConsumer.ConsumeMetrics,\n\t\tmutatesData:        set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createLogsProcessor(_ context.Context, set processor.Settings, _ component.Config, nextConsumer consumer.Logs) (processor.Logs, error) {\n\treturn &ExampleProcessor{\n\t\tConsumeLogsFunc: nextConsumer.ConsumeLogs,\n\t\tmutatesData:     set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\nfunc createProfilesProcessor(_ context.Context, set processor.Settings, _ component.Config, nextConsumer xconsumer.Profiles) (xprocessor.Profiles, error) {\n\treturn &ExampleProcessor{\n\t\tConsumeProfilesFunc: nextConsumer.ConsumeProfiles,\n\t\tmutatesData:         set.ID.Name() == \"mutate\",\n\t}, nil\n}\n\ntype ExampleProcessor struct {\n\tcomponentState\n\tconsumer.ConsumeTracesFunc\n\tconsumer.ConsumeMetricsFunc\n\tconsumer.ConsumeLogsFunc\n\txconsumer.ConsumeProfilesFunc\n\tmutatesData bool\n}\n\nfunc (ep *ExampleProcessor) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: ep.mutatesData}\n}\n"
  },
  {
    "path": "service/internal/testcomponents/example_processor_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testcomponents\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\nfunc TestExampleProcessor(t *testing.T) {\n\tprc := &ExampleProcessor{}\n\thost := componenttest.NewNopHost()\n\tassert.False(t, prc.Started())\n\trequire.NoError(t, prc.Start(context.Background(), host))\n\tassert.True(t, prc.Started())\n\n\tassert.False(t, prc.Stopped())\n\trequire.NoError(t, prc.Shutdown(context.Background()))\n\tassert.True(t, prc.Stopped())\n}\n"
  },
  {
    "path": "service/internal/testcomponents/example_receiver.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testcomponents // import \"go.opentelemetry.io/collector/service/internal/testcomponents\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/receiver/xreceiver\"\n)\n\nvar receiverType = component.MustNewType(\"examplereceiver\")\n\n// ExampleReceiverFactory is factory for ExampleReceiver.\nvar ExampleReceiverFactory = xreceiver.NewFactory(\n\treceiverType,\n\tcreateReceiverDefaultConfig,\n\txreceiver.WithTraces(createTracesReceiver, component.StabilityLevelDevelopment),\n\txreceiver.WithMetrics(createMetricsReceiver, component.StabilityLevelDevelopment),\n\txreceiver.WithLogs(createLogsReceiver, component.StabilityLevelDevelopment),\n\txreceiver.WithProfiles(createProfilesReceiver, component.StabilityLevelDevelopment),\n)\n\nfunc createReceiverDefaultConfig() component.Config {\n\treturn &struct{}{}\n}\n\n// createTraces creates a receiver.Traces based on this config.\nfunc createTracesReceiver(\n\t_ context.Context,\n\t_ receiver.Settings,\n\tcfg component.Config,\n\tnextConsumer consumer.Traces,\n) (receiver.Traces, error) {\n\ttr := createReceiver(cfg)\n\ttr.ConsumeTracesFunc = nextConsumer.ConsumeTraces\n\treturn tr, nil\n}\n\n// createMetrics creates a receiver.Metrics based on this config.\nfunc createMetricsReceiver(\n\t_ context.Context,\n\t_ receiver.Settings,\n\tcfg component.Config,\n\tnextConsumer consumer.Metrics,\n) (receiver.Metrics, error) {\n\tmr := createReceiver(cfg)\n\tmr.ConsumeMetricsFunc = nextConsumer.ConsumeMetrics\n\treturn mr, nil\n}\n\n// createLogs creates a receiver.Logs based on this config.\nfunc createLogsReceiver(\n\t_ context.Context,\n\t_ receiver.Settings,\n\tcfg component.Config,\n\tnextConsumer consumer.Logs,\n) (receiver.Logs, error) {\n\tlr := createReceiver(cfg)\n\tlr.ConsumeLogsFunc = nextConsumer.ConsumeLogs\n\treturn lr, nil\n}\n\n// createProfiles creates a receiver.Profiles based on this config.\nfunc createProfilesReceiver(\n\t_ context.Context,\n\t_ receiver.Settings,\n\tcfg component.Config,\n\tnextConsumer xconsumer.Profiles,\n) (xreceiver.Profiles, error) {\n\ttr := createReceiver(cfg)\n\ttr.ConsumeProfilesFunc = nextConsumer.ConsumeProfiles\n\treturn tr, nil\n}\n\nfunc createReceiver(cfg component.Config) *ExampleReceiver {\n\t// There must be one receiver for all data types. We maintain a map of\n\t// receivers per config.\n\n\t// Check to see if there is already a receiver for this config.\n\ter, ok := exampleReceivers[cfg]\n\tif !ok {\n\t\ter = &ExampleReceiver{}\n\t\t// Remember the receiver in the map\n\t\texampleReceivers[cfg] = er\n\t}\n\n\treturn er\n}\n\n// ExampleReceiver allows producing traces, metrics, logs and profiles for testing purposes.\ntype ExampleReceiver struct {\n\tcomponentState\n\tconsumer.ConsumeTracesFunc\n\tconsumer.ConsumeMetricsFunc\n\tconsumer.ConsumeLogsFunc\n\txconsumer.ConsumeProfilesFunc\n}\n\n// This is the map of already created example receivers for particular configurations.\n// We maintain this map because the receiver.Factory is asked trace and metric receivers separately\n// when it gets CreateTraces() and CreateMetrics() but they must not\n// create separate objects, they must use one Receiver object per configuration.\nvar exampleReceivers = map[component.Config]*ExampleReceiver{}\n"
  },
  {
    "path": "service/internal/testcomponents/example_receiver_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testcomponents\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n)\n\nfunc TestExampleReceiver(t *testing.T) {\n\trcv := &ExampleReceiver{}\n\thost := componenttest.NewNopHost()\n\tassert.False(t, rcv.Started())\n\trequire.NoError(t, rcv.Start(context.Background(), host))\n\tassert.True(t, rcv.Started())\n\n\tassert.False(t, rcv.Stopped())\n\trequire.NoError(t, rcv.Shutdown(context.Background()))\n\tassert.True(t, rcv.Stopped())\n}\n"
  },
  {
    "path": "service/internal/testcomponents/example_router.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testcomponents // import \"go.opentelemetry.io/collector/service/internal/testcomponents\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/xconnector\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pdata/plog\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pprofile\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\nvar routerType = component.MustNewType(\"examplerouter\")\n\n// ExampleRouterFactory is factory for ExampleRouter.\nvar ExampleRouterFactory = xconnector.NewFactory(\n\trouterType,\n\tcreateExampleRouterDefaultConfig,\n\txconnector.WithTracesToTraces(createExampleTracesRouter, component.StabilityLevelDevelopment),\n\txconnector.WithMetricsToMetrics(createExampleMetricsRouter, component.StabilityLevelDevelopment),\n\txconnector.WithLogsToLogs(createExampleLogsRouter, component.StabilityLevelDevelopment),\n\txconnector.WithProfilesToProfiles(createExampleProfilesRouter, component.StabilityLevelDevelopment),\n)\n\ntype LeftRightConfig struct {\n\tLeft  pipeline.ID `mapstructure:\"left\"`\n\tRight pipeline.ID `mapstructure:\"right\"`\n}\n\ntype ExampleRouterConfig struct {\n\tTraces   *LeftRightConfig `mapstructure:\"traces\"`\n\tMetrics  *LeftRightConfig `mapstructure:\"metrics\"`\n\tLogs     *LeftRightConfig `mapstructure:\"logs\"`\n\tProfiles *LeftRightConfig `mapstructure:\"profiles\"`\n}\n\nfunc createExampleRouterDefaultConfig() component.Config {\n\treturn &ExampleRouterConfig{}\n}\n\nfunc createExampleTracesRouter(_ context.Context, _ connector.Settings, cfg component.Config, traces consumer.Traces) (connector.Traces, error) {\n\tc := cfg.(ExampleRouterConfig)\n\tr := traces.(connector.TracesRouterAndConsumer)\n\tleft, _ := r.Consumer(c.Traces.Left)\n\tright, _ := r.Consumer(c.Traces.Right)\n\treturn &ExampleRouter{\n\t\ttracesRight: right,\n\t\ttracesLeft:  left,\n\t}, nil\n}\n\nfunc createExampleMetricsRouter(_ context.Context, _ connector.Settings, cfg component.Config, metrics consumer.Metrics) (connector.Metrics, error) {\n\tc := cfg.(ExampleRouterConfig)\n\tr := metrics.(connector.MetricsRouterAndConsumer)\n\tleft, _ := r.Consumer(c.Metrics.Left)\n\tright, _ := r.Consumer(c.Metrics.Right)\n\treturn &ExampleRouter{\n\t\tmetricsRight: right,\n\t\tmetricsLeft:  left,\n\t}, nil\n}\n\nfunc createExampleLogsRouter(_ context.Context, _ connector.Settings, cfg component.Config, logs consumer.Logs) (connector.Logs, error) {\n\tc := cfg.(ExampleRouterConfig)\n\tr := logs.(connector.LogsRouterAndConsumer)\n\tleft, _ := r.Consumer(c.Logs.Left)\n\tright, _ := r.Consumer(c.Logs.Right)\n\treturn &ExampleRouter{\n\t\tlogsRight: right,\n\t\tlogsLeft:  left,\n\t}, nil\n}\n\nfunc createExampleProfilesRouter(_ context.Context, _ connector.Settings, cfg component.Config, profiles xconsumer.Profiles) (xconnector.Profiles, error) {\n\tc := cfg.(ExampleRouterConfig)\n\tr := profiles.(xconnector.ProfilesRouterAndConsumer)\n\tleft, _ := r.Consumer(c.Profiles.Left)\n\tright, _ := r.Consumer(c.Profiles.Right)\n\treturn &ExampleRouter{\n\t\tprofilesRight: right,\n\t\tprofilesLeft:  left,\n\t}, nil\n}\n\ntype ExampleRouter struct {\n\tcomponentState\n\n\ttracesRight consumer.Traces\n\ttracesLeft  consumer.Traces\n\ttracesNum   int\n\n\tmetricsRight consumer.Metrics\n\tmetricsLeft  consumer.Metrics\n\tmetricsNum   int\n\n\tlogsRight consumer.Logs\n\tlogsLeft  consumer.Logs\n\tlogsNum   int\n\n\tprofilesRight xconsumer.Profiles\n\tprofilesLeft  xconsumer.Profiles\n\tprofilesNum   int\n}\n\nfunc (r *ExampleRouter) ConsumeTraces(ctx context.Context, td ptrace.Traces) error {\n\tr.tracesNum++\n\tif r.tracesNum%2 == 0 {\n\t\treturn r.tracesLeft.ConsumeTraces(ctx, td)\n\t}\n\treturn r.tracesRight.ConsumeTraces(ctx, td)\n}\n\nfunc (r *ExampleRouter) ConsumeMetrics(ctx context.Context, md pmetric.Metrics) error {\n\tr.metricsNum++\n\tif r.metricsNum%2 == 0 {\n\t\treturn r.metricsLeft.ConsumeMetrics(ctx, md)\n\t}\n\treturn r.metricsRight.ConsumeMetrics(ctx, md)\n}\n\nfunc (r *ExampleRouter) ConsumeLogs(ctx context.Context, ld plog.Logs) error {\n\tr.logsNum++\n\tif r.logsNum%2 == 0 {\n\t\treturn r.logsLeft.ConsumeLogs(ctx, ld)\n\t}\n\treturn r.logsRight.ConsumeLogs(ctx, ld)\n}\n\nfunc (r *ExampleRouter) ConsumeProfiles(ctx context.Context, td pprofile.Profiles) error {\n\tr.profilesNum++\n\tif r.profilesNum%2 == 0 {\n\t\treturn r.profilesLeft.ConsumeProfiles(ctx, td)\n\t}\n\treturn r.profilesRight.ConsumeProfiles(ctx, td)\n}\n\nfunc (r *ExampleRouter) Capabilities() consumer.Capabilities {\n\treturn consumer.Capabilities{MutatesData: false}\n}\n"
  },
  {
    "path": "service/internal/testcomponents/example_router_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testcomponents\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/connector/connectortest\"\n\t\"go.opentelemetry.io/collector/connector/xconnector\"\n\t\"go.opentelemetry.io/collector/consumer\"\n\t\"go.opentelemetry.io/collector/consumer/consumertest\"\n\t\"go.opentelemetry.io/collector/consumer/xconsumer\"\n\t\"go.opentelemetry.io/collector/pdata/testdata\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n)\n\nfunc TestExampleRouter(t *testing.T) {\n\tconn := &ExampleRouter{}\n\thost := componenttest.NewNopHost()\n\tassert.False(t, conn.Started())\n\trequire.NoError(t, conn.Start(context.Background(), host))\n\tassert.True(t, conn.Started())\n\n\tassert.False(t, conn.Stopped())\n\trequire.NoError(t, conn.Shutdown(context.Background()))\n\tassert.True(t, conn.Stopped())\n}\n\nfunc TestTracesRouter(t *testing.T) {\n\tleftID := pipeline.NewIDWithName(pipeline.SignalTraces, \"sink_left\")\n\trightID := pipeline.NewIDWithName(pipeline.SignalTraces, \"sink_right\")\n\n\tsinkLeft := new(consumertest.TracesSink)\n\tsinkRight := new(consumertest.TracesSink)\n\n\t// The service will build a router to give to every connector.\n\t// Many connectors will just call router.ConsumeTraces,\n\t// but some implementation will call RouteTraces instead.\n\trouter := connector.NewTracesRouter(\n\t\tmap[pipeline.ID]consumer.Traces{\n\t\t\tleftID:  sinkLeft,\n\t\t\trightID: sinkRight,\n\t\t})\n\n\tcfg := ExampleRouterConfig{Traces: &LeftRightConfig{Left: leftID, Right: rightID}}\n\ttr, err := ExampleRouterFactory.CreateTracesToTraces(\n\t\tcontext.Background(), connectortest.NewNopSettings(ExampleRouterFactory.Type()), cfg, router)\n\trequire.NoError(t, err)\n\tassert.False(t, tr.Capabilities().MutatesData)\n\n\ttd := testdata.GenerateTraces(1)\n\n\trequire.NoError(t, tr.ConsumeTraces(context.Background(), td))\n\tassert.Len(t, sinkRight.AllTraces(), 1)\n\tassert.Empty(t, sinkLeft.AllTraces())\n\n\trequire.NoError(t, tr.ConsumeTraces(context.Background(), td))\n\tassert.Len(t, sinkRight.AllTraces(), 1)\n\tassert.Len(t, sinkLeft.AllTraces(), 1)\n\n\tassert.NoError(t, tr.ConsumeTraces(context.Background(), td))\n\tassert.NoError(t, tr.ConsumeTraces(context.Background(), td))\n\tassert.NoError(t, tr.ConsumeTraces(context.Background(), td))\n\tassert.Len(t, sinkRight.AllTraces(), 3)\n\tassert.Len(t, sinkLeft.AllTraces(), 2)\n}\n\nfunc TestMetricsRouter(t *testing.T) {\n\tleftID := pipeline.NewIDWithName(pipeline.SignalTraces, \"sink_left\")\n\trightID := pipeline.NewIDWithName(pipeline.SignalTraces, \"sink_right\")\n\n\tsinkLeft := new(consumertest.MetricsSink)\n\tsinkRight := new(consumertest.MetricsSink)\n\n\t// The service will build a router to give to every connector.\n\t// Many connectors will just call router.ConsumeMetrics,\n\t// but some implementation will call RouteMetrics instead.\n\trouter := connector.NewMetricsRouter(\n\t\tmap[pipeline.ID]consumer.Metrics{\n\t\t\tleftID:  sinkLeft,\n\t\t\trightID: sinkRight,\n\t\t})\n\n\tcfg := ExampleRouterConfig{Metrics: &LeftRightConfig{Left: leftID, Right: rightID}}\n\tmr, err := ExampleRouterFactory.CreateMetricsToMetrics(\n\t\tcontext.Background(), connectortest.NewNopSettings(ExampleRouterFactory.Type()), cfg, router)\n\trequire.NoError(t, err)\n\tassert.False(t, mr.Capabilities().MutatesData)\n\n\tmd := testdata.GenerateMetrics(1)\n\n\trequire.NoError(t, mr.ConsumeMetrics(context.Background(), md))\n\tassert.Len(t, sinkRight.AllMetrics(), 1)\n\tassert.Empty(t, sinkLeft.AllMetrics())\n\n\trequire.NoError(t, mr.ConsumeMetrics(context.Background(), md))\n\tassert.Len(t, sinkRight.AllMetrics(), 1)\n\tassert.Len(t, sinkLeft.AllMetrics(), 1)\n\n\tassert.NoError(t, mr.ConsumeMetrics(context.Background(), md))\n\tassert.NoError(t, mr.ConsumeMetrics(context.Background(), md))\n\tassert.NoError(t, mr.ConsumeMetrics(context.Background(), md))\n\tassert.Len(t, sinkRight.AllMetrics(), 3)\n\tassert.Len(t, sinkLeft.AllMetrics(), 2)\n}\n\nfunc TestLogsRouter(t *testing.T) {\n\tleftID := pipeline.NewIDWithName(pipeline.SignalTraces, \"sink_left\")\n\trightID := pipeline.NewIDWithName(pipeline.SignalTraces, \"sink_right\")\n\n\tsinkLeft := new(consumertest.LogsSink)\n\tsinkRight := new(consumertest.LogsSink)\n\n\t// The service will build a router to give to every connector.\n\t// Many connectors will just call router.ConsumeLogs,\n\t// but some implementation will call RouteLogs instead.\n\trouter := connector.NewLogsRouter(\n\t\tmap[pipeline.ID]consumer.Logs{\n\t\t\tleftID:  sinkLeft,\n\t\t\trightID: sinkRight,\n\t\t})\n\n\tcfg := ExampleRouterConfig{Logs: &LeftRightConfig{Left: leftID, Right: rightID}}\n\tlr, err := ExampleRouterFactory.CreateLogsToLogs(\n\t\tcontext.Background(), connectortest.NewNopSettings(ExampleRouterFactory.Type()), cfg, router)\n\trequire.NoError(t, err)\n\tassert.False(t, lr.Capabilities().MutatesData)\n\n\tld := testdata.GenerateLogs(1)\n\n\trequire.NoError(t, lr.ConsumeLogs(context.Background(), ld))\n\tassert.Len(t, sinkRight.AllLogs(), 1)\n\tassert.Empty(t, sinkLeft.AllLogs())\n\n\trequire.NoError(t, lr.ConsumeLogs(context.Background(), ld))\n\tassert.Len(t, sinkRight.AllLogs(), 1)\n\tassert.Len(t, sinkLeft.AllLogs(), 1)\n\n\tassert.NoError(t, lr.ConsumeLogs(context.Background(), ld))\n\tassert.NoError(t, lr.ConsumeLogs(context.Background(), ld))\n\tassert.NoError(t, lr.ConsumeLogs(context.Background(), ld))\n\tassert.Len(t, sinkRight.AllLogs(), 3)\n\tassert.Len(t, sinkLeft.AllLogs(), 2)\n}\n\nfunc TestProfilesRouter(t *testing.T) {\n\tleftID := pipeline.NewIDWithName(pipeline.SignalTraces, \"sink_left\")\n\trightID := pipeline.NewIDWithName(pipeline.SignalTraces, \"sink_right\")\n\n\tsinkLeft := new(consumertest.ProfilesSink)\n\tsinkRight := new(consumertest.ProfilesSink)\n\n\t// The service will build a router to give to every connector.\n\t// Many connectors will just call router.ConsumeProfiles,\n\t// but some implementation will call RouteProfiles instead.\n\trouter := xconnector.NewProfilesRouter(\n\t\tmap[pipeline.ID]xconsumer.Profiles{\n\t\t\tleftID:  sinkLeft,\n\t\t\trightID: sinkRight,\n\t\t})\n\n\tcfg := ExampleRouterConfig{Profiles: &LeftRightConfig{Left: leftID, Right: rightID}}\n\ttr, err := ExampleRouterFactory.CreateProfilesToProfiles(\n\t\tcontext.Background(), connectortest.NewNopSettings(ExampleRouterFactory.Type()), cfg, router)\n\trequire.NoError(t, err)\n\tassert.False(t, tr.Capabilities().MutatesData)\n\n\ttd := testdata.GenerateProfiles(1)\n\n\trequire.NoError(t, tr.ConsumeProfiles(context.Background(), td))\n\tassert.Len(t, sinkRight.AllProfiles(), 1)\n\tassert.Empty(t, sinkLeft.AllProfiles())\n\n\trequire.NoError(t, tr.ConsumeProfiles(context.Background(), td))\n\tassert.Len(t, sinkRight.AllProfiles(), 1)\n\tassert.Len(t, sinkLeft.AllProfiles(), 1)\n\n\tassert.NoError(t, tr.ConsumeProfiles(context.Background(), td))\n\tassert.NoError(t, tr.ConsumeProfiles(context.Background(), td))\n\tassert.NoError(t, tr.ConsumeProfiles(context.Background(), td))\n\tassert.Len(t, sinkRight.AllProfiles(), 3)\n\tassert.Len(t, sinkLeft.AllProfiles(), 2)\n}\n"
  },
  {
    "path": "service/internal/testcomponents/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testcomponents\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "service/internal/testcomponents/stateful_component.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage testcomponents // import \"go.opentelemetry.io/collector/service/internal/testcomponents\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/collector/component\"\n)\n\ntype componentState struct {\n\tstarted bool\n\tstopped bool\n}\n\nfunc (cs *componentState) Started() bool {\n\treturn cs.started\n}\n\nfunc (cs *componentState) Stopped() bool {\n\treturn cs.stopped\n}\n\nfunc (cs *componentState) Start(context.Context, component.Host) error {\n\tcs.started = true\n\treturn nil\n}\n\nfunc (cs *componentState) Shutdown(context.Context) error {\n\tcs.stopped = true\n\treturn nil\n}\n"
  },
  {
    "path": "service/internal/zpages/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage zpages\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "service/internal/zpages/templates/component_header.html",
    "content": "{{$link := .Link}}\n{{- if $link -}}\n    <h6><a href=\"{{.ComponentEndpoint}}\">{{.Name}}</a></h6>\n{{- else -}}\n    <h6>{{.Name}}</h6>\n{{- end -}}"
  },
  {
    "path": "service/internal/zpages/templates/extensions_table.html",
    "content": "<table style=\"border-spacing: 0\">\n    {{range $rowindex, $row := .Rows}}\n        {{- if even $rowindex}}\n            <tr style=\"background: #eee\">\n        {{else}}\n            <tr>{{end -}}\n        <td style=\"text-align: center\"><a href=\"?zextensionname={{.FullName}}\">{{.FullName}}</a></td>\n        </tr>\n    {{end}}\n</table>"
  },
  {
    "path": "service/internal/zpages/templates/features_table.html",
    "content": "<table style=\"border-spacing: 0\">\n    <tr>\n        <td colspan=1 style=\"text-align: left\"><b>ID</b></td>\n        <td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        <td colspan=1 style=\"text-align: center\"><b>Enabled</b></td>\n        <td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        <td colspan=1 style=\"text-align: center\"><b>Description</b></td>\n        <td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        <td colspan=1 style=\"text-align: center\"><b>Stage</b></td>\n        <td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        <td colspan=1 style=\"text-align: center\"><b>From Version</b></td>\n        <td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        <td colspan=1 style=\"text-align: center\"><b>To Version</b></td>\n        <td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        <td colspan=1 style=\"text-align: center\"><b>Reference URL</b></td>\n    </tr>\n    {{range $rowindex, $row := .Rows}}\n        {{- if even $rowindex}}\n            <tr style=\"background: #eee\">\n        {{else}}\n            <tr>\n        {{end -}}\n            <td>{{$row.ID}}</td><td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n            <td>{{$row.Enabled}}</td><td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n            <td>{{$row.Description}}</td><td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n            <td>{{$row.Stage}}</td><td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n            <td>{{$row.FromVersion}}</td><td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n            <td>{{$row.ToVersion}}</td><td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n            <td>{{$row.ReferenceURL}}</td><td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        </tr>\n    {{end}}\n</table>\n"
  },
  {
    "path": "service/internal/zpages/templates/page_footer.html",
    "content": "</body>\n</html>"
  },
  {
    "path": "service/internal/zpages/templates/page_header.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\"><head>\n    <meta charset=\"utf-8\">\n    <title>{{.Title}}</title>\n    <link rel=\"shortcut icon\" href=\"https://opentelemetry.io/favicons/favicon.ico\"/>\n    <link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/icon?family=Material+Icons\">\n    <link rel=\"stylesheet\" href=\"https://code.getmdl.io/1.3.0/material.indigo-pink.min.css\">\n    <script defer src=\"https://code.getmdl.io/1.3.0/material.min.js\"></script>\n</head>\n<body>\n<h2>{{.Title}}</h2>"
  },
  {
    "path": "service/internal/zpages/templates/pipelines_table.html",
    "content": "<table style=\"border-spacing: 0\">\n    <tr>\n        <td colspan=1 style=\"text-align: left\"><b>FullName</b></td>\n        <td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        <td colspan=1 style=\"text-align: center\"><b>InputType</b></td>\n        <td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        <td colspan=1 style=\"text-align: center\"><b>MutatesData</b></td>\n        <td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        <td colspan=1 style=\"text-align: center\"><b>Receivers</b></td>\n        <td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        <td colspan=1 style=\"text-align: center\"><b>Processors</b></td>\n        <td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        <td colspan=1 style=\"text-align: center\"><b>Exporters</b></td>\n    </tr>\n    {{range $rowindex, $row := .Rows}}\n        {{- if even $rowindex}}\n            <tr style=\"background: #eee\">\n        {{else}}\n            <tr>{{end -}}\n        <td>{{$row.FullName}}</td><td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        <td>{{$row.InputType}}</td><td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        <td>{{$row.MutatesData}}</td><td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        <td style=\"text-align: center\">\n            {{range $recindex, $rec := $row.Receivers}}\n                <a href=\"?zpipelinename={{$row.FullName}}&zcomponentname={{$rec}}&zcomponentkind=receiver\">{{$rec}}</a>\n                <br>\n            {{end}}\n        </td><td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        <td style=\"text-align: center\">\n            &rarr;\n            {{range $proindex, $pro := $row.Processors}}\n                <a href=\"?zpipelinename={{$row.FullName}}&zcomponentname={{$pro}}&zcomponentkind=processor\">{{$pro}}</a>\n                &rarr;\n            {{end}}\n        </td><td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        <td style=\"text-align: center\">\n            {{range $expindex, $exp := $row.Exporters}}\n                <a href=\"?zpipelinename={{$row.FullName}}&zcomponentname={{$exp}}&zcomponentkind=exporter\">{{$exp}}</a>\n                <br>\n            {{end}}\n        </td>\n        </tr>\n    {{end}}\n</table>"
  },
  {
    "path": "service/internal/zpages/templates/properties_table.html",
    "content": "<b>{{.Name}}:</b>\n<table style=\"border-spacing: 0\">\n    {{ $index := 0 }}\n    {{range $index, $element := .Properties}}\n        {{- if even $index}}\n            <tr style=\"background: #eee\">\n        {{else}}\n            <tr>{{end -}}\n        <td style=\"text-align: center\"><b>{{$element|getKey}}</b></td>\n        <td>&nbsp;&nbsp;|&nbsp;&nbsp;</td>\n        <td style=\"text-align: center\">{{$element|getValue}}</td>\n        </tr>\n    {{end}}\n</table>"
  },
  {
    "path": "service/internal/zpages/templates.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage zpages // import \"go.opentelemetry.io/collector/service/internal/zpages\"\n\nimport (\n\t_ \"embed\"\n\t\"html/template\"\n\t\"io\"\n\t\"log\"\n)\n\nvar (\n\ttemplateFunctions = template.FuncMap{\n\t\t\"even\":     even,\n\t\t\"getKey\":   getKey,\n\t\t\"getValue\": getValue,\n\t}\n\n\t//go:embed templates/component_header.html\n\tcomponentHeaderBytes    []byte\n\tcomponentHeaderTemplate = parseTemplate(\"component_header\", componentHeaderBytes)\n\n\t//go:embed templates/extensions_table.html\n\textensionsTableBytes    []byte\n\textensionsTableTemplate = parseTemplate(\"extensions_table\", extensionsTableBytes)\n\n\t//go:embed templates/page_header.html\n\theaderBytes    []byte\n\theaderTemplate = parseTemplate(\"header\", headerBytes)\n\n\t//go:embed templates/page_footer.html\n\tfooterBytes    []byte\n\tfooterTemplate = parseTemplate(\"footer\", footerBytes)\n\n\t//go:embed templates/pipelines_table.html\n\tpipelinesTableBytes    []byte\n\tpipelinesTableTemplate = parseTemplate(\"pipelines_table\", pipelinesTableBytes)\n\n\t//go:embed templates/properties_table.html\n\tpropertiesTableBytes    []byte\n\tpropertiesTableTemplate = parseTemplate(\"properties_table\", propertiesTableBytes)\n\n\t//go:embed templates/features_table.html\n\tfeaturesTableBytes    []byte\n\tfeaturesTableTemplate = parseTemplate(\"features_table\", featuresTableBytes)\n)\n\nfunc parseTemplate(name string, bytes []byte) *template.Template {\n\treturn template.Must(template.New(name).Funcs(templateFunctions).Parse(string(bytes)))\n}\n\n// HeaderData contains data for the header template.\ntype HeaderData struct {\n\tTitle string\n}\n\n// WriteHTMLPageHeader writes the header.\nfunc WriteHTMLPageHeader(w io.Writer, hd HeaderData) {\n\tif err := headerTemplate.Execute(w, hd); err != nil {\n\t\tlog.Printf(\"zpages: executing template: %v\", err)\n\t}\n}\n\n// SummaryExtensionsTableData contains data for extensions summary table template.\ntype SummaryExtensionsTableData struct {\n\tRows []SummaryExtensionsTableRowData\n}\n\n// SummaryExtensionsTableRowData contains data for one row in extensions summary table template.\ntype SummaryExtensionsTableRowData struct {\n\tFullName string\n\tEnabled  bool\n}\n\n// WriteHTMLExtensionsSummaryTable writes the summary table for one component type (receivers, processors, exporters).\n// Id does not write the header or footer.\nfunc WriteHTMLExtensionsSummaryTable(w io.Writer, spd SummaryExtensionsTableData) {\n\tif err := extensionsTableTemplate.Execute(w, spd); err != nil {\n\t\tlog.Printf(\"zpages: executing template: %v\", err)\n\t}\n}\n\n// SummaryPipelinesTableData contains data for pipelines summary table template.\ntype SummaryPipelinesTableData struct {\n\tRows []SummaryPipelinesTableRowData\n}\n\n// SummaryPipelinesTableRowData contains data for one row in pipelines summary table template.\ntype SummaryPipelinesTableRowData struct {\n\tFullName    string\n\tInputType   string\n\tMutatesData bool\n\tReceivers   []string\n\tProcessors  []string\n\tExporters   []string\n}\n\n// WriteHTMLPipelinesSummaryTable writes the summary table for one component type (receivers, processors, exporters).\n// Id does not write the header or footer.\nfunc WriteHTMLPipelinesSummaryTable(w io.Writer, spd SummaryPipelinesTableData) {\n\tif err := pipelinesTableTemplate.Execute(w, spd); err != nil {\n\t\tlog.Printf(\"zpages: executing template: %v\", err)\n\t}\n}\n\n// ComponentHeaderData contains data for component header template.\ntype ComponentHeaderData struct {\n\tName              string\n\tComponentEndpoint string\n\tLink              bool\n}\n\n// WriteHTMLComponentHeader writes the header for components.\nfunc WriteHTMLComponentHeader(w io.Writer, chd ComponentHeaderData) {\n\tif err := componentHeaderTemplate.Execute(w, chd); err != nil {\n\t\tlog.Printf(\"zpages: executing template: %v\", err)\n\t}\n}\n\n// PropertiesTableData contains data for properties table template.\ntype PropertiesTableData struct {\n\tName       string\n\tProperties [][2]string\n}\n\n// WriteHTMLPropertiesTable writes the HTML for properties table.\nfunc WriteHTMLPropertiesTable(w io.Writer, chd PropertiesTableData) {\n\tif err := propertiesTableTemplate.Execute(w, chd); err != nil {\n\t\tlog.Printf(\"zpages: executing template: %v\", err)\n\t}\n}\n\n// WriteHTMLPageFooter writes the footer.\nfunc WriteHTMLPageFooter(w io.Writer) {\n\tif err := footerTemplate.Execute(w, nil); err != nil {\n\t\tlog.Printf(\"zpages: executing template: %v\", err)\n\t}\n}\n\nfunc even(x int) bool {\n\treturn x%2 == 0\n}\n\nfunc getKey(row [2]string) string {\n\treturn row[0]\n}\n\nfunc getValue(row [2]string) string {\n\treturn row[1]\n}\n\n// FeatureGateTableData contains data for feature gate table template.\ntype FeatureGateTableData struct {\n\tRows []FeatureGateTableRowData\n}\n\n// FeatureGateTableRowData contains data for one row in feature gate table template.\ntype FeatureGateTableRowData struct {\n\tID           string\n\tEnabled      bool\n\tDescription  string\n\tStage        string\n\tFromVersion  string\n\tToVersion    string\n\tReferenceURL string\n}\n\n// WriteHTMLFeaturesTable writes a table summarizing registered feature gates.\nfunc WriteHTMLFeaturesTable(w io.Writer, ftd FeatureGateTableData) {\n\tif err := featuresTableTemplate.Execute(w, ftd); err != nil {\n\t\tlog.Printf(\"zpages: executing template: %v\", err)\n\t}\n}\n"
  },
  {
    "path": "service/internal/zpages/templates_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage zpages\n\nimport (\n\t\"bytes\"\n\t\"html/template\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n)\n\nconst tmplBody = `\n        <p>{{.Index|even}}</p>\n        <p>{{.Element|getKey}}</p>\n        <p>{{.Element|getValue}}</p>\n`\n\nconst want = `\n        <p>true</p>\n        <p>key</p>\n        <p>value</p>\n`\n\ntype testFuncsInput struct {\n\tIndex   int\n\tElement [2]string\n}\n\nvar tmpl = template.Must(template.New(\"countTest\").Funcs(templateFunctions).Parse(tmplBody))\n\nfunc TestTemplateFuncs(t *testing.T) {\n\tbuf := new(bytes.Buffer)\n\tinput := testFuncsInput{\n\t\tIndex:   32,\n\t\tElement: [2]string{\"key\", \"value\"},\n\t}\n\trequire.NoError(t, tmpl.Execute(buf, input))\n\tassert.Equal(t, want, buf.String())\n}\n\nfunc TestNoCrash(t *testing.T) {\n\tbuf := new(bytes.Buffer)\n\tassert.NotPanics(t, func() { WriteHTMLPageHeader(buf, HeaderData{Title: \"Foo\"}) })\n\tassert.NotPanics(t, func() { WriteHTMLComponentHeader(buf, ComponentHeaderData{Name: \"Bar\"}) })\n\tassert.NotPanics(t, func() {\n\t\tWriteHTMLComponentHeader(buf, ComponentHeaderData{Name: \"Bar\", ComponentEndpoint: \"pagez\", Link: true})\n\t})\n\tassert.NotPanics(t, func() {\n\t\tWriteHTMLPipelinesSummaryTable(buf, SummaryPipelinesTableData{\n\t\t\tRows: []SummaryPipelinesTableRowData{{\n\t\t\t\tFullName:    \"test\",\n\t\t\t\tInputType:   \"metrics\",\n\t\t\t\tMutatesData: false,\n\t\t\t\tReceivers:   []string{\"oc\"},\n\t\t\t\tProcessors:  []string{\"nop\"},\n\t\t\t\tExporters:   []string{\"oc\"},\n\t\t\t}},\n\t\t})\n\t})\n\tassert.NotPanics(t, func() {\n\t\tWriteHTMLExtensionsSummaryTable(buf, SummaryExtensionsTableData{\n\t\t\tRows: []SummaryExtensionsTableRowData{{\n\t\t\t\tFullName: \"test\",\n\t\t\t}},\n\t\t})\n\t})\n\tassert.NotPanics(t, func() {\n\t\tWriteHTMLPropertiesTable(buf, PropertiesTableData{Name: \"Bar\", Properties: [][2]string{{\"key\", \"value\"}}})\n\t})\n\tassert.NotPanics(t, func() {\n\t\tWriteHTMLFeaturesTable(buf, FeatureGateTableData{Rows: []FeatureGateTableRowData{\n\t\t\t{\n\t\t\t\tID:          \"test\",\n\t\t\t\tEnabled:     false,\n\t\t\t\tDescription: \"test gate\",\n\t\t\t},\n\t\t}})\n\t})\n\tassert.NotPanics(t, func() { WriteHTMLPageFooter(buf) })\n\tassert.NotPanics(t, func() { WriteHTMLPageFooter(buf) })\n}\n"
  },
  {
    "path": "service/metadata.yaml",
    "content": "display_name: Service\ntype: service\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n  stability:\n    development: [traces, metrics, logs, profiles]\n  distributions: [core, contrib]\n\ntelemetry:\n  metrics:\n    connector.consumed.items:\n      prefix: otelcol.\n      enabled: true\n      stability: development\n      description: Number of items passed to the connector.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    connector.consumed.size:\n      prefix: otelcol.\n      enabled: false\n      stability: development\n      description: Size of items passed to the connector, based on ProtoMarshaler.Sizer.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    connector.produced.items:\n      prefix: otelcol.\n      enabled: true\n      stability: development\n      description: Number of items emitted from the connector.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    connector.produced.size:\n      prefix: otelcol.\n      enabled: false\n      stability: development\n      description: Size of items emitted from the connector, based on ProtoMarshaler.Sizer.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    exporter.consumed.items:\n      prefix: otelcol.\n      enabled: true\n      stability: development\n      description: Number of items passed to the exporter.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    exporter.consumed.size:\n      prefix: otelcol.\n      enabled: false\n      stability: development\n      description: Size of items passed to the exporter, based on ProtoMarshaler.Sizer.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    process_cpu_seconds:\n      enabled: true\n      stability: alpha\n      description: Total CPU user and system time in seconds\n      unit: s\n      sum:\n        async: true\n        value_type: double\n        monotonic: true\n\n    process_memory_rss:\n      enabled: true\n      stability: alpha\n      description: Total physical memory (resident set size)\n      unit: By\n      gauge:\n        async: true\n        value_type: int\n\n    process_runtime_heap_alloc_bytes:\n      enabled: true\n      stability: alpha\n      description: Bytes of allocated heap objects (see 'go doc runtime.MemStats.HeapAlloc')\n      unit: By\n      gauge:\n        async: true\n        value_type: int\n\n    process_runtime_total_alloc_bytes:\n      enabled: true\n      stability: alpha\n      description: Cumulative bytes allocated for heap objects (see 'go doc runtime.MemStats.TotalAlloc')\n      unit: By\n      sum:\n        async: true\n        value_type: int\n        monotonic: true\n\n    process_runtime_total_sys_memory_bytes:\n      enabled: true\n      stability: alpha\n      description: Total bytes of memory obtained from the OS (see 'go doc runtime.MemStats.Sys')\n      unit: By\n      gauge:\n        async: true\n        value_type: int\n\n    process_uptime:\n      enabled: true\n      stability: alpha\n      description: Uptime of the process\n      unit: s\n      sum:\n        async: true\n        value_type: double\n        monotonic: true\n\n    processor.consumed.items:\n      prefix: otelcol.\n      enabled: true\n      stability: development\n      description: Number of items passed to the processor.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    processor.consumed.size:\n      prefix: otelcol.\n      enabled: false\n      stability: development\n      description: Size of items passed to the processor, based on ProtoMarshaler.Sizer.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    processor.produced.items:\n      prefix: otelcol.\n      enabled: true\n      stability: development\n      description: Number of items emitted from the processor.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    processor.produced.size:\n      prefix: otelcol.\n      enabled: false\n      stability: development\n      description: Size of items emitted from the processor, based on ProtoMarshaler.Sizer.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    receiver.produced.items:\n      prefix: otelcol.\n      enabled: true\n      stability: development\n      description: Number of items emitted from the receiver.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n\n    receiver.produced.size:\n      prefix: otelcol.\n      enabled: false\n      stability: development\n      description: Size of items emitted from the receiver, based on ProtoMarshaler.Sizer.\n      unit: \"{item}\"\n      sum:\n        value_type: int\n        monotonic: true\n\nfeature_gates:\n  - id: service.AllowNoPipelines\n    description: 'Allow starting the Collector without starting any pipelines.'\n    stage: alpha\n    from_version: 'v0.122.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/pull/12613'\n  - id: service.profilesSupport\n    description: 'Controls whether profiles support can be enabled'\n    stage: alpha\n    from_version: 'v0.112.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/pull/11477'\n  - id: telemetry.UseLocalHostAsDefaultMetricsAddress\n    description: 'Controls whether default Prometheus metrics server use localhost as the default host for their endpoints'\n    stage: beta\n    from_version: 'v0.111.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/pull/11251'\n  - id: telemetry.newPipelineTelemetry\n    description: 'Injects component-identifying scope attributes in internal Collector metrics'\n    stage: alpha\n    from_version: 'v0.123.0'\n    reference_url: 'https://github.com/open-telemetry/opentelemetry-collector/blob/main/docs/rfcs/component-universal-telemetry.md'\n"
  },
  {
    "path": "service/pipelines/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pipelines // import \"go.opentelemetry.io/collector/service/pipelines\"\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n)\n\nvar (\n\terrMissingServicePipelines         = errors.New(\"service must have at least one pipeline\")\n\terrMissingServicePipelineReceivers = errors.New(\"must have at least one receiver\")\n\terrMissingServicePipelineExporters = errors.New(\"must have at least one exporter\")\n\n\tAllowNoPipelines = metadata.ServiceAllowNoPipelinesFeatureGate\n)\n\n// Config defines the configurable settings for service telemetry.\ntype Config map[pipeline.ID]*PipelineConfig\n\nfunc (cfg Config) Validate() error {\n\t// Must have at least one pipeline unless explicitly disabled.\n\tif !metadata.ServiceAllowNoPipelinesFeatureGate.IsEnabled() && len(cfg) == 0 {\n\t\treturn errMissingServicePipelines\n\t}\n\n\tif !metadata.ServiceProfilesSupportFeatureGate.IsEnabled() {\n\t\t// Check that all pipelines have at least one receiver and one exporter, and they reference\n\t\t// only configured components.\n\t\tfor pipelineID := range cfg {\n\t\t\tif pipelineID.Signal() == xpipeline.SignalProfiles {\n\t\t\t\treturn fmt.Errorf(\n\t\t\t\t\t\"pipeline %q: profiling signal support is at alpha level, gated under the %q feature gate\",\n\t\t\t\t\tpipelineID.String(),\n\t\t\t\t\tmetadata.ServiceProfilesSupportFeatureGate.ID(),\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n\n\treturn nil\n}\n\n// PipelineConfig defines the configuration of a Pipeline.\ntype PipelineConfig struct {\n\tReceivers  []component.ID `mapstructure:\"receivers\"`\n\tProcessors []component.ID `mapstructure:\"processors\"`\n\tExporters  []component.ID `mapstructure:\"exporters\"`\n}\n\nfunc (cfg *PipelineConfig) Validate() error {\n\t// Validate pipeline has at least one receiver.\n\tif len(cfg.Receivers) == 0 {\n\t\treturn errMissingServicePipelineReceivers\n\t}\n\n\t// Validate pipeline has at least one exporter.\n\tif len(cfg.Exporters) == 0 {\n\t\treturn errMissingServicePipelineExporters\n\t}\n\n\t// Validate no processors are duplicated within a pipeline.\n\tprocSet := make(map[component.ID]struct{}, len(cfg.Processors))\n\tfor _, ref := range cfg.Processors {\n\t\t// Ensure no processors are duplicated within the pipeline\n\t\tif _, exists := procSet[ref]; exists {\n\t\t\treturn fmt.Errorf(\"references processor %q multiple times\", ref)\n\t\t}\n\t\tprocSet[ref] = struct{}{}\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "service/pipelines/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pipelines\n\nimport (\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n)\n\nfunc TestConfigValidate(t *testing.T) {\n\ttestCases := []struct {\n\t\tname     string // test case name (also file name containing config yaml)\n\t\tcfgFn    func(*testing.T) Config\n\t\texpected error\n\t}{\n\t\t{\n\t\t\tname:     \"valid\",\n\t\t\tcfgFn:    generateConfig,\n\t\t\texpected: nil,\n\t\t},\n\t\t{\n\t\t\tname: \"duplicate-processor-reference\",\n\t\t\tcfgFn: func(*testing.T) Config {\n\t\t\t\tcfg := generateConfig(t)\n\t\t\t\tpipe := cfg[pipeline.NewID(pipeline.SignalTraces)]\n\t\t\t\tpipe.Processors = append(pipe.Processors, pipe.Processors...)\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errors.New(`references processor \"nop\" multiple times`),\n\t\t},\n\t\t{\n\t\t\tname: \"missing-pipeline-receivers\",\n\t\t\tcfgFn: func(*testing.T) Config {\n\t\t\t\tcfg := generateConfig(t)\n\t\t\t\tcfg[pipeline.NewID(pipeline.SignalTraces)].Receivers = nil\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errMissingServicePipelineReceivers,\n\t\t},\n\t\t{\n\t\t\tname: \"missing-pipeline-exporters\",\n\t\t\tcfgFn: func(*testing.T) Config {\n\t\t\t\tcfg := generateConfig(t)\n\t\t\t\tcfg[pipeline.NewID(pipeline.SignalTraces)].Exporters = nil\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errMissingServicePipelineExporters,\n\t\t},\n\t\t{\n\t\t\tname: \"missing-pipelines\",\n\t\t\tcfgFn: func(*testing.T) Config {\n\t\t\t\treturn nil\n\t\t\t},\n\t\t\texpected: errMissingServicePipelines,\n\t\t},\n\t\t{\n\t\t\tname: \"disabled-featuregate-profiles\",\n\t\t\tcfgFn: func(*testing.T) Config {\n\t\t\t\tcfg := generateConfig(t)\n\t\t\t\tcfg[pipeline.NewID(xpipeline.SignalProfiles)] = &PipelineConfig{\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t}\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: errors.New(`profiling signal support is at alpha level, gated under the \"service.profilesSupport\" feature gate`),\n\t\t},\n\t\t{\n\t\t\tname: \"enabled-featuregate-profiles\",\n\t\t\tcfgFn: func(t *testing.T) Config {\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ServiceProfilesSupportFeatureGate.ID(), true))\n\n\t\t\t\tcfg := generateConfig(t)\n\t\t\t\tcfg[pipeline.NewID(xpipeline.SignalProfiles)] = &PipelineConfig{\n\t\t\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\t\t}\n\t\t\t\treturn cfg\n\t\t\t},\n\t\t\texpected: nil,\n\t\t},\n\t}\n\n\tfor _, tt := range testCases {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcfg := tt.cfgFn(t)\n\t\t\tif tt.expected != nil {\n\t\t\t\trequire.ErrorContains(t, xconfmap.Validate(cfg), tt.expected.Error())\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, xconfmap.Validate(cfg))\n\t\t\t}\n\n\t\t\t// Clean up the profiles support gate, which may have been enabled in `cfgFn`.\n\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.ServiceProfilesSupportFeatureGate.ID(), false))\n\t\t})\n\t}\n}\n\nfunc TestNoPipelinesFeatureGate(t *testing.T) {\n\tcfg := Config{}\n\n\trequire.Error(t, xconfmap.Validate(cfg))\n\n\tgate := AllowNoPipelines\n\trequire.NoError(t, featuregate.GlobalRegistry().Set(gate.ID(), true))\n\tdefer func() {\n\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(gate.ID(), false))\n\t}()\n\n\trequire.NoError(t, xconfmap.Validate(cfg))\n}\n\nfunc generateConfig(t *testing.T) Config {\n\tt.Helper()\n\n\treturn map[pipeline.ID]*PipelineConfig{\n\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\tReceivers:  []component.ID{component.MustNewID(\"nop\")},\n\t\t\tProcessors: []component.ID{component.MustNewID(\"nop\")},\n\t\t\tExporters:  []component.ID{component.MustNewID(\"nop\")},\n\t\t},\n\t}\n}\n"
  },
  {
    "path": "service/pipelines/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage pipelines\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "service/service.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n//go:generate mdatagen metadata.yaml\n\npackage service // import \"go.opentelemetry.io/collector/service\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\t\"runtime\"\n\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\t\"go.uber.org/multierr\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/connector\"\n\t\"go.opentelemetry.io/collector/exporter\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/processor\"\n\t\"go.opentelemetry.io/collector/receiver\"\n\t\"go.opentelemetry.io/collector/service/extensions\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n\t\"go.opentelemetry.io/collector/service/internal/graph\"\n\t\"go.opentelemetry.io/collector/service/internal/metricviews\"\n\t\"go.opentelemetry.io/collector/service/internal/moduleinfo\"\n\t\"go.opentelemetry.io/collector/service/internal/proctelemetry\"\n\t\"go.opentelemetry.io/collector/service/internal/status\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n)\n\n// ModuleInfo describes the Go module for a particular component.\ntype ModuleInfo = moduleinfo.ModuleInfo\n\n// ModuleInfos describes the go module for all components.\ntype ModuleInfos = moduleinfo.ModuleInfos\n\n// Settings holds configuration for building a new Service.\ntype Settings struct {\n\t// BuildInfo provides collector start information.\n\tBuildInfo component.BuildInfo\n\n\t// CollectorConf contains the Collector's current configuration\n\tCollectorConf *confmap.Conf\n\n\t// Receivers configuration to its builder.\n\tReceiversConfigs   map[component.ID]component.Config\n\tReceiversFactories map[component.Type]receiver.Factory\n\n\t// Processors configuration to its builder.\n\tProcessorsConfigs   map[component.ID]component.Config\n\tProcessorsFactories map[component.Type]processor.Factory\n\n\t// exporters configuration to its builder.\n\tExportersConfigs   map[component.ID]component.Config\n\tExportersFactories map[component.Type]exporter.Factory\n\n\t// Connectors configuration to its builder.\n\tConnectorsConfigs   map[component.ID]component.Config\n\tConnectorsFactories map[component.Type]connector.Factory\n\n\t// Extensions builder for extensions.\n\tExtensions builders.Extension\n\n\t// Extensions configuration to its builder.\n\tExtensionsConfigs   map[component.ID]component.Config\n\tExtensionsFactories map[component.Type]extension.Factory\n\n\t// ModuleInfo describes the go module for each component.\n\tModuleInfos ModuleInfos\n\n\t// AsyncErrorChannel is the channel that is used to report fatal errors.\n\tAsyncErrorChannel chan error\n\n\t// LoggingOptions provides a way to change behavior of zap logging.\n\t//\n\t// These options will be appended to any options passed to BuildZapLogger.\n\t//\n\t// Deprecated [v0.142.0]: use BuildZapLogger instead. This field will be\n\t// removed in the future, and options must be injected through BuildZapLogger.\n\tLoggingOptions []zap.Option\n\n\t// BuildZapLogger holds an optional function for creating a Zap logger from\n\t// a zap.Config and options. If this is unspecified, zap.Config.Build will\n\t// be used.\n\t//\n\t// NOTE: in the future this field will be required.\n\tBuildZapLogger func(zap.Config, ...zap.Option) (*zap.Logger, error)\n\n\t// TelemetryFactory is the factory for creating internal telemetry providers.\n\tTelemetryFactory telemetry.Factory\n}\n\n// Service represents the implementation of a component.Host.\ntype Service struct {\n\tbuildInfo          component.BuildInfo\n\ttelemetrySettings  component.TelemetrySettings\n\thost               *graph.Host\n\tcollectorConf      *confmap.Conf\n\tloggerShutdownFunc component.ShutdownFunc\n\tmeterProvider      telemetry.MeterProvider\n\ttracerProvider     telemetry.TracerProvider\n}\n\n// New creates a new Service, its telemetry, and Components.\nfunc New(ctx context.Context, set Settings, cfg Config) (_ *Service, resultErr error) {\n\tsrv := &Service{\n\t\tbuildInfo: set.BuildInfo,\n\t\thost: &graph.Host{\n\t\t\tReceivers:  builders.NewReceiver(set.ReceiversConfigs, set.ReceiversFactories),\n\t\t\tProcessors: builders.NewProcessor(set.ProcessorsConfigs, set.ProcessorsFactories),\n\t\t\tExporters:  builders.NewExporter(set.ExportersConfigs, set.ExportersFactories),\n\t\t\tConnectors: builders.NewConnector(set.ConnectorsConfigs, set.ConnectorsFactories),\n\t\t\tExtensions: builders.NewExtension(set.ExtensionsConfigs, set.ExtensionsFactories),\n\n\t\t\tModuleInfos:       set.ModuleInfos,\n\t\t\tBuildInfo:         set.BuildInfo,\n\t\t\tAsyncErrorChannel: set.AsyncErrorChannel,\n\t\t},\n\t\tcollectorConf: set.CollectorConf,\n\t}\n\n\tif set.TelemetryFactory == nil {\n\t\treturn nil, errors.New(\"telemetry factory not provided\")\n\t}\n\n\t// Create the resource first. This ensures all telemetry providers\n\t// (logger, meter, tracer) use the same resource with a consistent service.instance.id.\n\ttelemetrySettings := telemetry.Settings{BuildInfo: set.BuildInfo}\n\tresource, err := set.TelemetryFactory.CreateResource(ctx, telemetrySettings, cfg.Telemetry)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create resource: %w\", err)\n\t}\n\ttelemetrySettings.Resource = &resource\n\n\t// Create a function for telemetry providers to build the Zap logger.\n\t// This injects any LoggingOptions specified in the Settings.\n\tbuildZapLogger := set.BuildZapLogger\n\tif buildZapLogger == nil {\n\t\tbuildZapLogger = zap.Config.Build\n\t}\n\tif len(set.LoggingOptions) > 0 {\n\t\torigBuildZapLogger := buildZapLogger\n\t\tbuildZapLogger = func(cfg zap.Config, opts ...zap.Option) (*zap.Logger, error) {\n\t\t\topts = append(opts, set.LoggingOptions...)\n\t\t\treturn origBuildZapLogger(cfg, opts...)\n\t\t}\n\t}\n\n\tloggerSettings := telemetry.LoggerSettings{\n\t\tSettings:       telemetrySettings,\n\t\tBuildZapLogger: buildZapLogger,\n\t}\n\tlogger, loggerShutdownFunc, err := set.TelemetryFactory.CreateLogger(ctx, loggerSettings, cfg.Telemetry)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create logger: %w\", err)\n\t}\n\tdefer func() {\n\t\tif resultErr != nil {\n\t\t\tlogger.Error(\"error found during service initialization\", zap.Error(resultErr))\n\t\t\tresultErr = multierr.Append(resultErr, loggerShutdownFunc.Shutdown(ctx))\n\t\t}\n\t}()\n\tsrv.loggerShutdownFunc = loggerShutdownFunc\n\n\tmeterSettings := telemetry.MeterSettings{\n\t\tSettings:     telemetrySettings,\n\t\tLogger:       logger,\n\t\tDefaultViews: metricviews.DefaultViews,\n\t}\n\tmeterProvider, err := set.TelemetryFactory.CreateMeterProvider(ctx, meterSettings, cfg.Telemetry)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create meter provider: %w\", err)\n\t}\n\tdefer func() {\n\t\tif resultErr != nil {\n\t\t\tresultErr = multierr.Append(resultErr, meterProvider.Shutdown(ctx))\n\t\t}\n\t}()\n\tsrv.meterProvider = meterProvider\n\n\ttracerSettings := telemetry.TracerSettings{\n\t\tSettings: telemetrySettings,\n\t\tLogger:   logger,\n\t}\n\ttracerProvider, err := set.TelemetryFactory.CreateTracerProvider(ctx, tracerSettings, cfg.Telemetry)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to create tracer provider: %w\", err)\n\t}\n\tdefer func() {\n\t\tif resultErr != nil {\n\t\t\tresultErr = multierr.Append(resultErr, tracerProvider.Shutdown(ctx))\n\t\t}\n\t}()\n\tsrv.tracerProvider = tracerProvider\n\n\tsrv.telemetrySettings = component.TelemetrySettings{\n\t\tLogger:         logger,\n\t\tMeterProvider:  meterProvider,\n\t\tTracerProvider: tracerProvider,\n\t\tResource:       resource,\n\t}\n\tsrv.host.Reporter = status.NewReporter(srv.host.NotifyComponentStatusChange, func(err error) {\n\t\tif errors.Is(err, status.ErrStatusNotReady) {\n\t\t\tlogger.Warn(\"Invalid transition\", zap.Error(err))\n\t\t}\n\t\t// ignore other errors as they represent invalid state transitions and are considered benign.\n\t})\n\n\terr = srv.initGraph(ctx, cfg)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// process the configuration and initialize the pipeline\n\terr = srv.initExtensions(ctx, cfg.Extensions)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\t// Register process metrics on supported OSes.\n\tif err := registerProcessMetrics(srv, runtime.GOOS, proctelemetry.RegisterProcessMetrics); err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn srv, nil\n}\n\n// Start starts the extensions and pipelines. If Start fails Shutdown should be called to ensure a clean state.\n// Start does the following steps in order:\n// 1. Start all extensions.\n// 2. Notify extensions about Collector configuration\n// 3. Start all pipelines.\n// 4. Notify extensions that the pipeline is ready.\nfunc (srv *Service) Start(ctx context.Context) error {\n\tsrv.telemetrySettings.Logger.Info(\"Starting \"+srv.buildInfo.Command+\"...\",\n\t\tzap.String(\"Version\", srv.buildInfo.Version),\n\t\tzap.Int(\"NumCPU\", runtime.NumCPU()),\n\t)\n\n\tif err := srv.host.ServiceExtensions.Start(ctx, srv.host); err != nil {\n\t\treturn fmt.Errorf(\"failed to start extensions: %w\", err)\n\t}\n\n\tif srv.collectorConf != nil {\n\t\tif err := srv.host.ServiceExtensions.NotifyConfig(ctx, srv.collectorConf); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\tif err := srv.host.Pipelines.StartAll(ctx, srv.host); err != nil {\n\t\treturn fmt.Errorf(\"cannot start pipelines: %w\", err)\n\t}\n\n\tif err := srv.host.ServiceExtensions.NotifyPipelineReady(); err != nil {\n\t\treturn err\n\t}\n\n\tsrv.telemetrySettings.Logger.Info(\"Everything is ready. Begin running and processing data.\")\n\treturn nil\n}\n\n// Shutdown the service. Shutdown will do the following steps in order:\n// 1. Notify extensions that the pipeline is shutting down.\n// 2. Shutdown all pipelines.\n// 3. Shutdown all extensions.\n// 4. Shutdown telemetry.\nfunc (srv *Service) Shutdown(ctx context.Context) error {\n\t// Accumulate errors and proceed with shutting down remaining components.\n\tvar errs error\n\n\t// Begin shutdown sequence.\n\tsrv.telemetrySettings.Logger.Info(\"Starting shutdown...\")\n\n\tif err := srv.host.ServiceExtensions.NotifyPipelineNotReady(); err != nil {\n\t\terrs = multierr.Append(errs, fmt.Errorf(\"failed to notify that pipeline is not ready: %w\", err))\n\t}\n\n\tif err := srv.host.Pipelines.ShutdownAll(ctx, srv.host.Reporter); err != nil {\n\t\terrs = multierr.Append(errs, fmt.Errorf(\"failed to shutdown pipelines: %w\", err))\n\t}\n\n\tif err := srv.host.ServiceExtensions.Shutdown(ctx); err != nil {\n\t\terrs = multierr.Append(errs, fmt.Errorf(\"failed to shutdown extensions: %w\", err))\n\t}\n\n\tsrv.telemetrySettings.Logger.Info(\"Shutdown complete.\")\n\n\t// Shut down telemetry providers in the reverse order of creation,\n\t// since the tracer and meter providers may use the logger.\n\tif err := srv.tracerProvider.Shutdown(ctx); err != nil {\n\t\terrs = multierr.Append(errs, fmt.Errorf(\"failed to shutdown tracer provider: %w\", err))\n\t}\n\tif err := srv.meterProvider.Shutdown(ctx); err != nil {\n\t\terrs = multierr.Append(errs, fmt.Errorf(\"failed to shutdown meter provider: %w\", err))\n\t}\n\tif err := srv.loggerShutdownFunc.Shutdown(ctx); err != nil {\n\t\terrs = multierr.Append(errs, fmt.Errorf(\"failed to shutdown logger: %w\", err))\n\t}\n\n\treturn errs\n}\n\n// Creates extensions.\nfunc (srv *Service) initExtensions(ctx context.Context, cfg extensions.Config) error {\n\tvar err error\n\textensionsSettings := extensions.Settings{\n\t\tTelemetry:  srv.telemetrySettings,\n\t\tBuildInfo:  srv.buildInfo,\n\t\tExtensions: srv.host.Extensions,\n\t}\n\tif srv.host.ServiceExtensions, err = extensions.New(ctx, extensionsSettings, cfg, extensions.WithReporter(srv.host.Reporter)); err != nil {\n\t\treturn fmt.Errorf(\"failed to build extensions: %w\", err)\n\t}\n\treturn nil\n}\n\n// Creates the pipeline graph.\nfunc (srv *Service) initGraph(ctx context.Context, cfg Config) error {\n\tvar err error\n\tif srv.host.Pipelines, err = graph.Build(ctx, graph.Settings{\n\t\tTelemetry:        srv.telemetrySettings,\n\t\tBuildInfo:        srv.buildInfo,\n\t\tReceiverBuilder:  srv.host.Receivers,\n\t\tProcessorBuilder: srv.host.Processors,\n\t\tExporterBuilder:  srv.host.Exporters,\n\t\tConnectorBuilder: srv.host.Connectors,\n\t\tPipelineConfigs:  cfg.Pipelines,\n\t\tReportStatus:     srv.host.Reporter.ReportStatus,\n\t}); err != nil {\n\t\treturn fmt.Errorf(\"failed to build pipelines: %w\", err)\n\t}\n\treturn nil\n}\n\n// Logger returns the logger created for this service.\n// This is a temporary API that may be removed soon after investigating how the collector should record different events.\nfunc (srv *Service) Logger() *zap.Logger {\n\treturn srv.telemetrySettings.Logger\n}\n\n// Validate verifies the graph by calling the internal graph.Build.\nfunc Validate(ctx context.Context, set Settings, cfg Config) error {\n\ttel := component.TelemetrySettings{\n\t\tLogger:         zap.NewNop(),\n\t\tTracerProvider: nooptrace.NewTracerProvider(),\n\t\tMeterProvider:  noopmetric.NewMeterProvider(),\n\t\tResource:       pcommon.NewResource(),\n\t}\n\t_, err := graph.Build(ctx, graph.Settings{\n\t\tTelemetry:        tel,\n\t\tBuildInfo:        set.BuildInfo,\n\t\tReceiverBuilder:  builders.NewReceiver(set.ReceiversConfigs, set.ReceiversFactories),\n\t\tProcessorBuilder: builders.NewProcessor(set.ProcessorsConfigs, set.ProcessorsFactories),\n\t\tExporterBuilder:  builders.NewExporter(set.ExportersConfigs, set.ExportersFactories),\n\t\tConnectorBuilder: builders.NewConnector(set.ConnectorsConfigs, set.ConnectorsFactories),\n\t\tPipelineConfigs:  cfg.Pipelines,\n\t})\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to build pipelines: %w\", err)\n\t}\n\treturn nil\n}\n\n// registerProcessMetrics registers process metrics on supported operating systems.\n//\n// Historically, attempting to register process metrics on unsupported platforms\n// (e.g. AIX) caused the Collector to fail at startup.\n// See https://github.com/open-telemetry/opentelemetry-collector/issues/12098\nfunc registerProcessMetrics(\n\tsrv *Service,\n\tgoos string,\n\tregister func(component.TelemetrySettings, ...proctelemetry.RegisterOption) error,\n) error {\n\tswitch goos {\n\t// Only support the OSes that we explicitly test and build for,\n\t// plus others that are known to have some support in gopsutil.\n\tcase \"linux\", \"darwin\", \"windows\", \"freebsd\", \"openbsd\", \"solaris\", \"plan9\":\n\t\tif err := register(srv.telemetrySettings); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to register process metrics: %w\", err)\n\t\t}\n\tdefault:\n\t\t// On unsupported OSes, log a warning and continue startup.\n\t\tsrv.telemetrySettings.Logger.Warn(\n\t\t\t\"Process metrics are disabled on this operating system\",\n\t\t\tzap.String(\"os\", goos),\n\t\t)\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "service/service_host_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage service\n\nimport (\n\t\"context\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componentstatus\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n)\n\nvar wrongType = component.MustNewType(\"wrong\")\n\nfunc TestService_Host_GetFactory(t *testing.T) {\n\tset := newNopSettings()\n\tsrv, err := New(context.Background(), set, newNopConfig())\n\trequire.NoError(t, err)\n\n\tassert.NoError(t, srv.Start(context.Background()))\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, srv.Shutdown(context.Background()))\n\t})\n\n\tassert.Nil(t, srv.host.GetFactory(component.KindReceiver, wrongType))\n\tassert.Equal(t, srv.host.Receivers.Factory(nopType), srv.host.GetFactory(component.KindReceiver, nopType))\n\n\tassert.Nil(t, srv.host.GetFactory(component.KindProcessor, wrongType))\n\tassert.Equal(t, srv.host.Processors.Factory(nopType), srv.host.GetFactory(component.KindProcessor, nopType))\n\n\tassert.Nil(t, srv.host.GetFactory(component.KindExporter, wrongType))\n\tassert.Equal(t, srv.host.Exporters.Factory(nopType), srv.host.GetFactory(component.KindExporter, nopType))\n\n\tassert.Nil(t, srv.host.GetFactory(component.KindConnector, wrongType))\n\tassert.Equal(t, srv.host.Connectors.Factory(nopType), srv.host.GetFactory(component.KindConnector, nopType))\n\n\tassert.Nil(t, srv.host.GetFactory(component.KindExtension, wrongType))\n\tassert.Equal(t, srv.host.Extensions.Factory(nopType), srv.host.GetFactory(component.KindExtension, nopType))\n\n\t// Try retrieve non existing component.Kind.\n\tassert.Nil(t, srv.host.GetFactory(component.Kind{}, nopType))\n}\n\nfunc TestService_Host_GetExtensions(t *testing.T) {\n\tsrv, err := New(context.Background(), newNopSettings(), newNopConfig())\n\trequire.NoError(t, err)\n\n\tassert.NoError(t, srv.Start(context.Background()))\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, srv.Shutdown(context.Background()))\n\t})\n\n\textMap := srv.host.GetExtensions()\n\n\tassert.Len(t, extMap, 1)\n\tassert.Contains(t, extMap, component.NewID(nopType))\n}\n\nfunc TestService_Host_GetExporters(t *testing.T) {\n\tsrv, err := New(context.Background(), newNopSettings(), newNopConfig())\n\trequire.NoError(t, err)\n\n\tassert.NoError(t, srv.Start(context.Background()))\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, srv.Shutdown(context.Background()))\n\t})\n\n\t//nolint:staticcheck\n\texpMap := srv.host.GetExporters()\n\n\tv, ok := expMap[pipeline.SignalTraces]\n\tassert.True(t, ok)\n\tassert.NotNil(t, v)\n\n\tassert.Len(t, expMap, 4)\n\tassert.Len(t, expMap[pipeline.SignalTraces], 1)\n\tassert.Contains(t, expMap[pipeline.SignalTraces], component.NewID(nopType))\n\tassert.Len(t, expMap[pipeline.SignalMetrics], 1)\n\tassert.Contains(t, expMap[pipeline.SignalMetrics], component.NewID(nopType))\n\tassert.Len(t, expMap[pipeline.SignalLogs], 1)\n\tassert.Contains(t, expMap[pipeline.SignalLogs], component.NewID(nopType))\n\tassert.Len(t, expMap[xpipeline.SignalProfiles], 1)\n\tassert.Contains(t, expMap[xpipeline.SignalProfiles], component.NewID(nopType))\n}\n\nfunc TestService_Host_FatalError(t *testing.T) {\n\tset := newNopSettings()\n\tset.AsyncErrorChannel = make(chan error)\n\n\tsrv, err := New(context.Background(), set, newNopConfig())\n\trequire.NoError(t, err)\n\n\tassert.NoError(t, srv.Start(context.Background()))\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, srv.Shutdown(context.Background()))\n\t})\n\n\tgo func() {\n\t\tev := componentstatus.NewFatalErrorEvent(assert.AnError)\n\t\tsrv.host.NotifyComponentStatusChange(&componentstatus.InstanceID{}, ev)\n\t}()\n\n\terr = <-srv.host.AsyncErrorChannel\n\n\trequire.ErrorIs(t, err, assert.AnError)\n}\n"
  },
  {
    "path": "service/service_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage service\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"net/http\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\totelconf \"go.opentelemetry.io/contrib/otelconf/v0.3.0\"\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\t\"go.opentelemetry.io/otel/sdk/metric\"\n\t\"go.opentelemetry.io/otel/sdk/metric/metricdata\"\n\tsdktrace \"go.opentelemetry.io/otel/sdk/trace\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/confighttp\"\n\t\"go.opentelemetry.io/collector/config/confignet\"\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/extension\"\n\t\"go.opentelemetry.io/collector/extension/zpagesextension\"\n\t\"go.opentelemetry.io/collector/internal/testutil\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/pipeline\"\n\t\"go.opentelemetry.io/collector/pipeline/xpipeline\"\n\t\"go.opentelemetry.io/collector/service/extensions\"\n\t\"go.opentelemetry.io/collector/service/internal/builders\"\n\t\"go.opentelemetry.io/collector/service/internal/proctelemetry\"\n\t\"go.opentelemetry.io/collector/service/pipelines\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n\t\"go.opentelemetry.io/collector/service/telemetry/telemetrytest\"\n)\n\nconst (\n\totelCommand = \"otelcoltest\"\n)\n\nvar nopType = component.MustNewType(\"nop\")\n\n// TestServiceTelemetryCleanupOnError tests that if newService errors due to an invalid config telemetry is cleaned up\n// and another service with a valid config can be started right after.\nfunc TestServiceTelemetryCleanupOnError(t *testing.T) {\n\tinvalidCfg := newNopConfig()\n\tinvalidCfg.Pipelines[pipeline.NewID(pipeline.SignalTraces)].Processors[0] = component.MustNewID(\"invalid\")\n\t// Create a service with an invalid config and expect an error\n\t_, err := New(context.Background(), newNopSettings(), invalidCfg)\n\trequire.Error(t, err)\n\n\t// Create a service with a valid config and expect no error\n\tsrv, err := New(context.Background(), newNopSettings(), newNopConfig())\n\trequire.NoError(t, err)\n\tassert.NoError(t, srv.Shutdown(context.Background()))\n}\n\nfunc TestServiceTelemetryLogging(t *testing.T) {\n\tobserverCore, observedLogs := observer.New(zapcore.WarnLevel)\n\tzapLogger := zap.New(observerCore)\n\n\tset := newNopSettings()\n\tset.BuildInfo = component.BuildInfo{Version: \"test version\", Command: otelCommand}\n\tset.TelemetryFactory = telemetry.NewFactory(\n\t\tfunc() component.Config { return nil },\n\t\ttelemetrytest.WithLogger(zapLogger, nil),\n\t)\n\n\tcfg := newNopConfig()\n\tsrv, err := New(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NoError(t, srv.Start(context.Background()))\n\tdefer func() {\n\t\tassert.NoError(t, srv.Shutdown(context.Background()))\n\t}()\n\n\trequire.NotNil(t, srv.telemetrySettings.Logger)\n\tassert.Equal(t, srv.telemetrySettings.Logger, srv.Logger())\n\tassert.Equal(t, zapcore.WarnLevel, srv.telemetrySettings.Logger.Level())\n\tsrv.telemetrySettings.Logger.Warn(\"warn_message\")\n\tsrv.telemetrySettings.Logger.Info(\"info_message\")\n\n\tentries := observedLogs.All()\n\trequire.Len(t, entries, 1)\n\tassert.Equal(t, \"warn_message\", entries[0].Message)\n}\n\nfunc TestServiceTelemetryLogging_Settings(t *testing.T) {\n\tobserverCore, observedLogs := observer.New(zapcore.WarnLevel)\n\tzapConfig := zap.Config{Encoding: \"foo\"}\n\n\tset := newNopSettings()\n\tset.BuildZapLogger = func(cfg zap.Config, opts ...zap.Option) (*zap.Logger, error) {\n\t\trequire.Equal(t, zapConfig, cfg)\n\t\treturn zap.New(observerCore, opts...), nil\n\t}\n\tset.LoggingOptions = []zap.Option{zap.Fields(zap.String(\"extra.field\", \"value\"))}\n\tset.BuildInfo = component.BuildInfo{Version: \"test version\", Command: otelCommand}\n\tset.TelemetryFactory = telemetry.NewFactory(\n\t\tfunc() component.Config { return nil },\n\t\ttelemetry.WithCreateLogger(\n\t\t\tfunc(_ context.Context, set telemetry.LoggerSettings, _ component.Config) (\n\t\t\t\t*zap.Logger, component.ShutdownFunc, error,\n\t\t\t) {\n\t\t\t\trequire.NotNil(t, set.BuildZapLogger)\n\t\t\t\trequire.Empty(t, set.ZapOptions)\n\t\t\t\tlogger, err := set.BuildZapLogger(zapConfig)\n\t\t\t\treturn logger, nil, err\n\t\t\t},\n\t\t),\n\t)\n\n\tcfg := newNopConfig()\n\tsrv, err := New(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NoError(t, srv.Start(context.Background()))\n\tdefer func() {\n\t\tassert.NoError(t, srv.Shutdown(context.Background()))\n\t}()\n\n\trequire.NotNil(t, srv.telemetrySettings.Logger)\n\tassert.Equal(t, srv.telemetrySettings.Logger, srv.Logger())\n\tassert.Equal(t, zapcore.WarnLevel, srv.telemetrySettings.Logger.Level())\n\tsrv.telemetrySettings.Logger.Warn(\"warn_message\")\n\n\tentries := observedLogs.All()\n\trequire.Len(t, entries, 1)\n\tassert.Contains(t, entries[0].ContextMap(), \"extra.field\")\n}\n\nfunc TestServiceTelemetryMetrics(t *testing.T) {\n\t// Start a service and check that metrics are produced as expected.\n\t// We do this twice to ensure that the server is stopped cleanly.\n\tfor range 2 {\n\t\treader := metric.NewManualReader()\n\t\tset := newNopSettings()\n\t\tset.TelemetryFactory = telemetry.NewFactory(\n\t\t\tfunc() component.Config { return nil },\n\t\t\ttelemetrytest.WithMeterProvider(\n\t\t\t\tmetric.NewMeterProvider(\n\t\t\t\t\tmetric.WithReader(reader),\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\n\t\tsrv, err := New(context.Background(), set, newNopConfig())\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, srv.Start(context.Background()))\n\n\t\tvar rm metricdata.ResourceMetrics\n\t\terr = reader.Collect(context.Background(), &rm)\n\t\trequire.NoError(t, err)\n\n\t\tassertMetrics(t, rm)\n\t\trequire.NoError(t, srv.Shutdown(context.Background()))\n\t}\n}\n\nfunc assertMetrics(t *testing.T, rm metricdata.ResourceMetrics) {\n\trequire.Len(t, rm.ScopeMetrics, 1)\n\tassert.Equal(t, \"go.opentelemetry.io/collector/service\", rm.ScopeMetrics[0].Scope.Name)\n\n\tactualNames := make([]string, len(rm.ScopeMetrics[0].Metrics))\n\tfor i, m := range rm.ScopeMetrics[0].Metrics {\n\t\tactualNames[i] = m.Name\n\t}\n\tassert.ElementsMatch(t, []string{\n\t\t\"otelcol_process_cpu_seconds\",\n\t\t\"otelcol_process_memory_rss\",\n\t\t\"otelcol_process_runtime_heap_alloc_bytes\",\n\t\t\"otelcol_process_runtime_total_alloc_bytes\",\n\t\t\"otelcol_process_runtime_total_sys_memory_bytes\",\n\t\t\"otelcol_process_uptime\",\n\t}, actualNames)\n}\n\nfunc TestServiceTelemetryDefaultViews(t *testing.T) {\n\tvar views []otelconf.View\n\tset := newNopSettings()\n\tset.TelemetryFactory = telemetry.NewFactory(\n\t\tfunc() component.Config { return nil },\n\t\ttelemetry.WithCreateMeterProvider(\n\t\t\tfunc(_ context.Context, set telemetry.MeterSettings, _ component.Config) (telemetry.MeterProvider, error) {\n\t\t\t\tviews = set.DefaultViews(configtelemetry.LevelBasic)\n\t\t\t\treturn telemetrytest.ShutdownMeterProvider{\n\t\t\t\t\tMeterProvider: noopmetric.NewMeterProvider(),\n\t\t\t\t}, nil\n\t\t\t},\n\t\t),\n\t)\n\n\tsrv, err := New(context.Background(), set, newNopConfig())\n\trequire.NoError(t, err)\n\trequire.NoError(t, srv.Start(context.Background()))\n\tdefer func() {\n\t\tassert.NoError(t, srv.Shutdown(context.Background()))\n\t}()\n\trequire.NotEmpty(t, views)\n}\n\n// TestServiceTelemetryZPages verifies that the zpages extension works correctly with servce telemetry.\nfunc TestServiceTelemetryZPages(t *testing.T) {\n\tt.Run(\"ipv4\", func(t *testing.T) {\n\t\ttestZPages(t, testutil.GetAvailableLocalAddress(t))\n\t})\n\tt.Run(\"ipv6\", func(t *testing.T) {\n\t\ttestZPages(t, testutil.GetAvailableLocalIPv6Address(t))\n\t})\n}\n\nfunc testZPages(t *testing.T, zpagesAddr string) {\n\tset := newNopSettings()\n\tset.BuildInfo = component.BuildInfo{Version: \"test version\", Command: otelCommand}\n\tset.ExtensionsConfigs = map[component.ID]component.Config{\n\t\tcomponent.MustNewID(\"zpages\"): &zpagesextension.Config{\n\t\t\tServerConfig: confighttp.ServerConfig{\n\t\t\t\tNetAddr: confignet.AddrConfig{\n\t\t\t\t\tEndpoint:  zpagesAddr,\n\t\t\t\t\tTransport: confignet.TransportTypeTCP,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tset.ExtensionsFactories = map[component.Type]extension.Factory{\n\t\tcomponent.MustNewType(\"zpages\"): zpagesextension.NewFactory(),\n\t}\n\n\tcfg := newNopConfig()\n\tcfg.Extensions = []component.ID{component.MustNewID(\"zpages\")}\n\n\t// The zpages extension will register/unregister a span processor with\n\t// the tracer provider if it implements the RegisterSpanProcessor and\n\t// UnregisterSpanProcessor methods of the opentelemetry-go SDK implementation.\n\t// Hence we use sdktrace below, rather than the noop tracer provider.\n\tset.TelemetryFactory = telemetry.NewFactory(\n\t\tfunc() component.Config { return nil },\n\t\ttelemetrytest.WithTracerProvider(sdktrace.NewTracerProvider()),\n\t)\n\n\t// Start a service and check that zpages is healthy.\n\t// We do this twice to ensure that the server is stopped cleanly.\n\tfor range 2 {\n\t\tsrv, err := New(context.Background(), set, cfg)\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, srv.Start(context.Background()))\n\n\t\tassert.Eventually(t, func() bool {\n\t\t\treturn zpagesHealthy(zpagesAddr)\n\t\t}, 10*time.Second, 100*time.Millisecond, \"zpages endpoint is not healthy\")\n\n\t\trequire.NoError(t, srv.Shutdown(context.Background()))\n\t}\n}\n\nfunc zpagesHealthy(zpagesAddr string) bool {\n\tpaths := []string{\n\t\t\"/debug/tracez\",\n\t\t\"/debug/pipelinez\",\n\t\t\"/debug/servicez\",\n\t\t\"/debug/extensionz\",\n\t}\n\n\tfor _, path := range paths {\n\t\tresp, err := http.Get(\"http://\" + zpagesAddr + path)\n\t\tif err != nil {\n\t\t\treturn false\n\t\t}\n\t\tif resp.Body.Close() != nil {\n\t\t\treturn false\n\t\t}\n\t\tif resp.StatusCode != http.StatusOK {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\n// TestServiceTelemetryRestart tests that the service starts and shuts down telemetry as expected.\nfunc TestServiceTelemetryRestart(t *testing.T) {\n\ttelemetryCreated := make(chan struct{}, 1)\n\ttelemetryShutdown := make(chan struct{}, 1)\n\n\tset := newNopSettings()\n\tset.TelemetryFactory = telemetry.NewFactory(\n\t\tfunc() component.Config { return nil },\n\t\ttelemetry.WithCreateTracerProvider(\n\t\t\tfunc(context.Context, telemetry.TracerSettings, component.Config) (telemetry.TracerProvider, error) {\n\t\t\t\ttelemetryCreated <- struct{}{}\n\t\t\t\treturn telemetrytest.ShutdownTracerProvider{\n\t\t\t\t\tTracerProvider: nooptrace.NewTracerProvider(),\n\t\t\t\t\tShutdownFunc: func(context.Context) error {\n\t\t\t\t\t\ttelemetryShutdown <- struct{}{}\n\t\t\t\t\t\treturn nil\n\t\t\t\t\t},\n\t\t\t\t}, nil\n\t\t\t},\n\t\t),\n\t)\n\n\tfor range 2 {\n\t\t// Create and start a service, telemetry should be created.\n\t\tsrv, err := New(context.Background(), set, newNopConfig())\n\t\trequire.NoError(t, err)\n\t\trequire.NoError(t, srv.Start(context.Background()))\n\t\t<-telemetryCreated\n\n\t\t// Shutdown the service, telemetry should be shutdown.\n\t\trequire.NoError(t, srv.Shutdown(context.Background()))\n\t\t<-telemetryShutdown\n\t}\n}\n\nfunc TestServiceTelemetryShutdownError(t *testing.T) {\n\tset := newNopSettings()\n\tset.TelemetryFactory = telemetry.NewFactory(\n\t\tfunc() component.Config { return nil },\n\t\ttelemetry.WithCreateLogger(\n\t\t\tfunc(context.Context, telemetry.LoggerSettings, component.Config) (*zap.Logger, component.ShutdownFunc, error) {\n\t\t\t\treturn zap.NewNop(), func(context.Context) error {\n\t\t\t\t\treturn errors.New(\"an exception occurred\")\n\t\t\t\t}, nil\n\t\t\t},\n\t\t),\n\t\ttelemetry.WithCreateMeterProvider(\n\t\t\tfunc(context.Context, telemetry.MeterSettings, component.Config) (telemetry.MeterProvider, error) {\n\t\t\t\treturn telemetrytest.ShutdownMeterProvider{\n\t\t\t\t\tMeterProvider: noopmetric.NewMeterProvider(),\n\t\t\t\t\tShutdownFunc: func(context.Context) error {\n\t\t\t\t\t\treturn errors.New(\"an exception occurred\")\n\t\t\t\t\t},\n\t\t\t\t}, nil\n\t\t\t},\n\t\t),\n\t\ttelemetry.WithCreateTracerProvider(\n\t\t\tfunc(context.Context, telemetry.TracerSettings, component.Config) (telemetry.TracerProvider, error) {\n\t\t\t\treturn telemetrytest.ShutdownTracerProvider{\n\t\t\t\t\tTracerProvider: nooptrace.NewTracerProvider(),\n\t\t\t\t\tShutdownFunc: func(context.Context) error {\n\t\t\t\t\t\treturn errors.New(\"an exception occurred\")\n\t\t\t\t\t},\n\t\t\t\t}, nil\n\t\t\t},\n\t\t),\n\t)\n\n\t// Create and start a service\n\tcfg := newNopConfig()\n\tsrv, err := New(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NoError(t, srv.Start(context.Background()))\n\n\t// Shutdown the service\n\terr = srv.Shutdown(context.Background())\n\tassert.EqualError(t, err, \"\"+\n\t\t\"failed to shutdown tracer provider: an exception occurred; \"+\n\t\t\"failed to shutdown meter provider: an exception occurred; \"+\n\t\t\"failed to shutdown logger: an exception occurred\",\n\t)\n}\n\nfunc TestExtensionNotificationFailure(t *testing.T) {\n\tset := newNopSettings()\n\tcfg := newNopConfig()\n\n\textName := component.MustNewType(\"configWatcher\")\n\tconfigWatcherExtensionFactory := newConfigWatcherExtensionFactory(extName)\n\tset.ExtensionsConfigs = map[component.ID]component.Config{component.NewID(extName): configWatcherExtensionFactory.CreateDefaultConfig()}\n\tset.ExtensionsFactories = map[component.Type]extension.Factory{extName: configWatcherExtensionFactory}\n\tcfg.Extensions = []component.ID{component.NewID(extName)}\n\n\t// Create a service\n\tsrv, err := New(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\n\t// Start the service\n\trequire.Error(t, srv.Start(context.Background()))\n\n\t// Shut down the service\n\trequire.NoError(t, srv.Shutdown(context.Background()))\n}\n\nfunc TestNilCollectorEffectiveConfig(t *testing.T) {\n\tset := newNopSettings()\n\tset.CollectorConf = nil\n\tcfg := newNopConfig()\n\n\textName := component.MustNewType(\"configWatcher\")\n\tconfigWatcherExtensionFactory := newConfigWatcherExtensionFactory(extName)\n\tset.ExtensionsConfigs = map[component.ID]component.Config{component.NewID(extName): configWatcherExtensionFactory.CreateDefaultConfig()}\n\tset.ExtensionsFactories = map[component.Type]extension.Factory{extName: configWatcherExtensionFactory}\n\tcfg.Extensions = []component.ID{component.NewID(extName)}\n\n\t// Create a service\n\tsrv, err := New(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\n\t// Start the service\n\trequire.NoError(t, srv.Start(context.Background()))\n\n\t// Shut down the service\n\trequire.NoError(t, srv.Shutdown(context.Background()))\n}\n\nfunc TestServiceTelemetryLogger(t *testing.T) {\n\tsrv, err := New(context.Background(), newNopSettings(), newNopConfig())\n\trequire.NoError(t, err)\n\n\tassert.NoError(t, srv.Start(context.Background()))\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, srv.Shutdown(context.Background()))\n\t})\n\tassert.NotNil(t, srv.telemetrySettings.Logger)\n}\n\nfunc TestServiceTelemetryCreateProvidersError(t *testing.T) {\n\tloggerOpt := telemetry.WithCreateLogger(\n\t\tfunc(context.Context, telemetry.LoggerSettings, component.Config) (*zap.Logger, component.ShutdownFunc, error) {\n\t\t\treturn nil, nil, errors.New(\"something went wrong\")\n\t\t},\n\t)\n\tmeterOpt := telemetry.WithCreateMeterProvider(\n\t\tfunc(context.Context, telemetry.MeterSettings, component.Config) (telemetry.MeterProvider, error) {\n\t\t\treturn nil, errors.New(\"something went wrong\")\n\t\t},\n\t)\n\ttracerOpt := telemetry.WithCreateTracerProvider(\n\t\tfunc(context.Context, telemetry.TracerSettings, component.Config) (telemetry.TracerProvider, error) {\n\t\t\treturn nil, errors.New(\"something went wrong\")\n\t\t},\n\t)\n\tresourceOpt := telemetry.WithCreateResource(\n\t\tfunc(context.Context, telemetry.Settings, component.Config) (pcommon.Resource, error) {\n\t\t\treturn pcommon.Resource{}, errors.New(\"something went wrong\")\n\t\t},\n\t)\n\n\ttype testcase struct {\n\t\topts        []telemetry.FactoryOption\n\t\texpectedErr string\n\t}\n\tfor name, tc := range map[string]testcase{\n\t\t\"CreateLogger\": {\n\t\t\topts:        []telemetry.FactoryOption{loggerOpt, meterOpt, tracerOpt},\n\t\t\texpectedErr: \"failed to create logger: something went wrong\",\n\t\t},\n\t\t\"CreateMeterProvider\": {\n\t\t\topts:        []telemetry.FactoryOption{meterOpt, tracerOpt},\n\t\t\texpectedErr: \"failed to create meter provider: something went wrong\",\n\t\t},\n\t\t\"CreateTracerProvider\": {\n\t\t\topts:        []telemetry.FactoryOption{tracerOpt},\n\t\t\texpectedErr: \"failed to create tracer provider: something went wrong\",\n\t\t},\n\t\t\"CreateResource\": {\n\t\t\topts:        []telemetry.FactoryOption{resourceOpt},\n\t\t\texpectedErr: \"failed to create resource: something went wrong\",\n\t\t},\n\t} {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tset := newNopSettings()\n\t\t\tset.TelemetryFactory = telemetry.NewFactory(func() component.Config { return nil }, tc.opts...)\n\t\t\t_, err := New(context.Background(), set, newNopConfig())\n\t\t\trequire.EqualError(t, err, tc.expectedErr)\n\t\t})\n\t}\n}\n\nfunc TestNew_NilTelemetryProvider(t *testing.T) {\n\tset := newNopSettings()\n\tset.TelemetryFactory = nil\n\t_, err := New(context.Background(), set, newNopConfig())\n\trequire.EqualError(t, err, \"telemetry factory not provided\")\n}\n\nfunc newNopSettings() Settings {\n\treceiversConfigs, receiversFactories := builders.NewNopReceiverConfigsAndFactories()\n\tprocessorsConfigs, processorsFactories := builders.NewNopProcessorConfigsAndFactories()\n\tconnectorsConfigs, connectorsFactories := builders.NewNopConnectorConfigsAndFactories()\n\texportersConfigs, exportersFactories := builders.NewNopExporterConfigsAndFactories()\n\textensionsConfigs, extensionsFactories := builders.NewNopExtensionConfigsAndFactories()\n\ttelemetryFactory := telemetry.NewFactory(func() component.Config { return nil })\n\n\treturn Settings{\n\t\tBuildInfo:           component.NewDefaultBuildInfo(),\n\t\tCollectorConf:       confmap.New(),\n\t\tReceiversConfigs:    receiversConfigs,\n\t\tReceiversFactories:  receiversFactories,\n\t\tProcessorsConfigs:   processorsConfigs,\n\t\tProcessorsFactories: processorsFactories,\n\t\tExportersConfigs:    exportersConfigs,\n\t\tExportersFactories:  exportersFactories,\n\t\tConnectorsConfigs:   connectorsConfigs,\n\t\tConnectorsFactories: connectorsFactories,\n\t\tExtensionsConfigs:   extensionsConfigs,\n\t\tExtensionsFactories: extensionsFactories,\n\t\tAsyncErrorChannel:   make(chan error),\n\t\tTelemetryFactory:    telemetryFactory,\n\t}\n}\n\nfunc newNopConfig() Config {\n\treturn newNopConfigPipelineConfigs(pipelines.Config{\n\t\tpipeline.NewID(pipeline.SignalTraces): {\n\t\t\tReceivers:  []component.ID{component.NewID(nopType)},\n\t\t\tProcessors: []component.ID{component.NewID(nopType)},\n\t\t\tExporters:  []component.ID{component.NewID(nopType)},\n\t\t},\n\t\tpipeline.NewID(pipeline.SignalMetrics): {\n\t\t\tReceivers:  []component.ID{component.NewID(nopType)},\n\t\t\tProcessors: []component.ID{component.NewID(nopType)},\n\t\t\tExporters:  []component.ID{component.NewID(nopType)},\n\t\t},\n\t\tpipeline.NewID(pipeline.SignalLogs): {\n\t\t\tReceivers:  []component.ID{component.NewID(nopType)},\n\t\t\tProcessors: []component.ID{component.NewID(nopType)},\n\t\t\tExporters:  []component.ID{component.NewID(nopType)},\n\t\t},\n\t\tpipeline.NewID(xpipeline.SignalProfiles): {\n\t\t\tReceivers:  []component.ID{component.NewID(nopType)},\n\t\t\tProcessors: []component.ID{component.NewID(nopType)},\n\t\t\tExporters:  []component.ID{component.NewID(nopType)},\n\t\t},\n\t})\n}\n\nfunc newNopConfigPipelineConfigs(pipelineCfgs pipelines.Config) Config {\n\treturn Config{\n\t\tExtensions: extensions.Config{component.NewID(nopType)},\n\t\tPipelines:  pipelineCfgs,\n\t}\n}\n\ntype configWatcherExtension struct{}\n\nfunc (comp *configWatcherExtension) Start(context.Context, component.Host) error {\n\treturn nil\n}\n\nfunc (comp *configWatcherExtension) Shutdown(context.Context) error {\n\treturn nil\n}\n\nfunc (comp *configWatcherExtension) NotifyConfig(context.Context, *confmap.Conf) error {\n\treturn errors.New(\"Failed to resolve config\")\n}\n\nfunc newConfigWatcherExtensionFactory(name component.Type) extension.Factory {\n\treturn extension.NewFactory(\n\t\tname,\n\t\tfunc() component.Config {\n\t\t\treturn &struct{}{}\n\t\t},\n\t\tfunc(context.Context, extension.Settings, component.Config) (extension.Extension, error) {\n\t\t\treturn &configWatcherExtension{}, nil\n\t\t},\n\t\tcomponent.StabilityLevelDevelopment,\n\t)\n}\n\nfunc TestValidateGraph(t *testing.T) {\n\ttestCases := map[string]struct {\n\t\tconnectorCfg  map[component.ID]component.Config\n\t\treceiverCfg   map[component.ID]component.Config\n\t\texporterCfg   map[component.ID]component.Config\n\t\tpipelinesCfg  pipelines.Config\n\t\texpectedError string\n\t}{\n\t\t\"Valid connector usage\": {\n\t\t\tconnectorCfg: map[component.ID]component.Config{\n\t\t\t\tcomponent.NewIDWithName(nopType, \"connector1\"): &struct{}{},\n\t\t\t},\n\t\t\treceiverCfg: map[component.ID]component.Config{\n\t\t\t\tcomponent.NewID(nopType): &struct{}{},\n\t\t\t},\n\t\t\texporterCfg: map[component.ID]component.Config{\n\t\t\t\tcomponent.NewID(nopType): &struct{}{},\n\t\t\t},\n\t\t\tpipelinesCfg: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.NewID(nopType)},\n\t\t\t\t\tProcessors: []component.ID{},\n\t\t\t\t\tExporters:  []component.ID{component.NewIDWithName(nopType, \"connector1\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.NewIDWithName(nopType, \"connector1\")},\n\t\t\t\t\tProcessors: []component.ID{},\n\t\t\t\t\tExporters:  []component.ID{component.NewID(nopType)},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedError: \"\",\n\t\t},\n\t\t\"Valid without Connector\": {\n\t\t\treceiverCfg: map[component.ID]component.Config{\n\t\t\t\tcomponent.NewID(nopType): &struct{}{},\n\t\t\t},\n\t\t\texporterCfg: map[component.ID]component.Config{\n\t\t\t\tcomponent.NewID(nopType): &struct{}{},\n\t\t\t},\n\t\t\tpipelinesCfg: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.NewID(nopType)},\n\t\t\t\t\tProcessors: []component.ID{},\n\t\t\t\t\tExporters:  []component.ID{component.NewID(nopType)},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.NewID(nopType)},\n\t\t\t\t\tProcessors: []component.ID{},\n\t\t\t\t\tExporters:  []component.ID{component.NewID(nopType)},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedError: \"\",\n\t\t},\n\t\t\"Connector used as exporter but not as receiver\": {\n\t\t\tconnectorCfg: map[component.ID]component.Config{\n\t\t\t\tcomponent.NewIDWithName(nopType, \"connector1\"): &struct{}{},\n\t\t\t},\n\t\t\treceiverCfg: map[component.ID]component.Config{\n\t\t\t\tcomponent.NewID(nopType): &struct{}{},\n\t\t\t},\n\t\t\texporterCfg: map[component.ID]component.Config{\n\t\t\t\tcomponent.NewID(nopType): &struct{}{},\n\t\t\t},\n\t\t\tpipelinesCfg: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"in1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.NewID(nopType)},\n\t\t\t\t\tProcessors: []component.ID{},\n\t\t\t\t\tExporters:  []component.ID{component.NewID(nopType)},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"in2\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.NewID(nopType)},\n\t\t\t\t\tProcessors: []component.ID{},\n\t\t\t\t\tExporters:  []component.ID{component.NewIDWithName(nopType, \"connector1\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.NewID(nopType)},\n\t\t\t\t\tProcessors: []component.ID{},\n\t\t\t\t\tExporters:  []component.ID{component.NewID(nopType)},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedError: `failed to build pipelines: connector \"nop/connector1\" used as exporter in [logs/in2] pipeline but not used in any supported receiver pipeline`,\n\t\t},\n\t\t\"Connector used as receiver but not as exporter\": {\n\t\t\tconnectorCfg: map[component.ID]component.Config{\n\t\t\t\tcomponent.NewIDWithName(nopType, \"connector1\"): &struct{}{},\n\t\t\t},\n\t\t\treceiverCfg: map[component.ID]component.Config{\n\t\t\t\tcomponent.NewID(nopType): &struct{}{},\n\t\t\t},\n\t\t\texporterCfg: map[component.ID]component.Config{\n\t\t\t\tcomponent.NewID(nopType): &struct{}{},\n\t\t\t},\n\t\t\tpipelinesCfg: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"in1\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.NewID(nopType)},\n\t\t\t\t\tProcessors: []component.ID{},\n\t\t\t\t\tExporters:  []component.ID{component.NewID(nopType)},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"in2\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.NewIDWithName(nopType, \"connector1\")},\n\t\t\t\t\tProcessors: []component.ID{},\n\t\t\t\t\tExporters:  []component.ID{component.NewID(nopType)},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalLogs, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.NewID(nopType)},\n\t\t\t\t\tProcessors: []component.ID{},\n\t\t\t\t\tExporters:  []component.ID{component.NewID(nopType)},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedError: `failed to build pipelines: connector \"nop/connector1\" used as receiver in [logs/in2] pipeline but not used in any supported exporter pipeline`,\n\t\t},\n\t\t\"Connector creates direct cycle between pipelines\": {\n\t\t\tconnectorCfg: map[component.ID]component.Config{\n\t\t\t\tcomponent.NewIDWithName(nopType, \"forward\"): &struct{}{},\n\t\t\t},\n\t\t\treceiverCfg: map[component.ID]component.Config{\n\t\t\t\tcomponent.NewID(nopType): &struct{}{},\n\t\t\t},\n\t\t\texporterCfg: map[component.ID]component.Config{\n\t\t\t\tcomponent.NewID(nopType): &struct{}{},\n\t\t\t},\n\t\t\tpipelinesCfg: pipelines.Config{\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"in\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.NewIDWithName(nopType, \"forward\")},\n\t\t\t\t\tProcessors: []component.ID{},\n\t\t\t\t\tExporters:  []component.ID{component.NewIDWithName(nopType, \"forward\")},\n\t\t\t\t},\n\t\t\t\tpipeline.NewIDWithName(pipeline.SignalTraces, \"out\"): {\n\t\t\t\t\tReceivers:  []component.ID{component.NewIDWithName(nopType, \"forward\")},\n\t\t\t\t\tProcessors: []component.ID{},\n\t\t\t\t\tExporters:  []component.ID{component.NewIDWithName(nopType, \"forward\")},\n\t\t\t\t},\n\t\t\t},\n\t\t\texpectedError: `failed to build pipelines: cycle detected: connector \"nop/forward\" (traces to traces) -> connector \"nop/forward\" (traces to traces)`,\n\t\t},\n\t}\n\n\t_, connectorsFactories := builders.NewNopConnectorConfigsAndFactories()\n\t_, receiversFactories := builders.NewNopReceiverConfigsAndFactories()\n\t_, exportersFactories := builders.NewNopExporterConfigsAndFactories()\n\n\tfor name, tc := range testCases {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tsettings := Settings{\n\t\t\t\tConnectorsConfigs:   tc.connectorCfg,\n\t\t\t\tConnectorsFactories: connectorsFactories,\n\t\t\t\tReceiversConfigs:    tc.receiverCfg,\n\t\t\t\tReceiversFactories:  receiversFactories,\n\t\t\t\tExportersConfigs:    tc.exporterCfg,\n\t\t\t\tExportersFactories:  exportersFactories,\n\t\t\t}\n\t\t\tcfg := Config{\n\t\t\t\tPipelines: tc.pipelinesCfg,\n\t\t\t}\n\n\t\t\terr := Validate(context.Background(), settings, cfg)\n\t\t\tif tc.expectedError == \"\" {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t} else {\n\t\t\t\trequire.Error(t, err)\n\t\t\t\tassert.Equal(t, tc.expectedError, err.Error())\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestRegisterProcessMetrics_UnsupportedOS_Warns(t *testing.T) {\n\tmockRegister := func(_ component.TelemetrySettings, _ ...proctelemetry.RegisterOption) error {\n\t\tt.Fatalf(\"should not be called on unsupported OS\")\n\t\treturn nil\n\t}\n\n\tcore, logs := observer.New(zapcore.WarnLevel)\n\tlogger := zap.New(core)\n\n\tsrv := &Service{\n\t\ttelemetrySettings: component.TelemetrySettings{Logger: logger},\n\t}\n\n\terr := registerProcessMetrics(srv, \"aix\", mockRegister)\n\n\trequire.NoError(t, err)\n\trequire.Equal(t, 1, logs.Len(), \"Expected exactly one warning log\")\n\tentry := logs.All()[0]\n\trequire.Equal(t, \"Process metrics are disabled on this operating system\", entry.Message)\n\trequire.Equal(t, \"aix\", entry.ContextMap()[\"os\"], \"Log should contain the OS field\")\n}\n\nfunc TestRegisterProcessMetrics_SupportedOS_CallsRegister(t *testing.T) {\n\tcalled := false\n\tmockRegister := func(_ component.TelemetrySettings, _ ...proctelemetry.RegisterOption) error {\n\t\tcalled = true\n\t\treturn nil\n\t}\n\n\tsrv := &Service{\n\t\ttelemetrySettings: component.TelemetrySettings{Logger: zap.NewNop()},\n\t}\n\n\terr := registerProcessMetrics(srv, \"linux\", mockRegister)\n\n\trequire.NoError(t, err)\n\trequire.True(t, called, \"Registration function should be called on supported OS\")\n}\n\nfunc TestRegisterProcessMetrics_SupportedOS_RegisterFails_ReturnsError(t *testing.T) {\n\twantErr := errors.New(\"boom\")\n\tmockRegister := func(_ component.TelemetrySettings, _ ...proctelemetry.RegisterOption) error {\n\t\treturn wantErr\n\t}\n\n\tsrv := &Service{\n\t\ttelemetrySettings: component.TelemetrySettings{Logger: zap.NewNop()},\n\t}\n\n\terr := registerProcessMetrics(srv, \"linux\", mockRegister)\n\n\trequire.Error(t, err)\n\trequire.ErrorIs(t, err, wantErr)\n\trequire.Contains(t, err.Error(), \"failed to register process metrics\")\n}\n"
  },
  {
    "path": "service/telemetry/doc.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\n// Package telemetry provides an abstract interface for creating\n// telemetry providers.\npackage telemetry // import \"go.opentelemetry.io/collector/service/telemetry\"\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/config.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelconftelemetry // import \"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\"\n\nimport (\n\t\"errors\"\n\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry/internal/migration\"\n)\n\n// Config defines the configurable settings for service telemetry.\ntype Config struct {\n\tLogs    LogsConfig    `mapstructure:\"logs\"`\n\tMetrics MetricsConfig `mapstructure:\"metrics\"`\n\tTraces  TracesConfig  `mapstructure:\"traces,omitempty\"`\n\n\t// Resource specifies user-defined attributes to include with all emitted telemetry.\n\t// Note that some attributes are added automatically (e.g. service.version) even\n\t// if they are not specified here. In order to suppress such attributes the\n\t// attribute must be specified in this map with null YAML value (nil string pointer).\n\tResource map[string]*string `mapstructure:\"resource,omitempty\"`\n}\n\n// LogsConfig defines the configurable settings for service telemetry logs.\n// This MUST be compatible with zap.Config. Cannot use directly zap.Config because\n// the collector uses mapstructure and not yaml tags.\ntype LogsConfig = migration.LogsConfigV030\n\n// LogsSamplingConfig sets a sampling strategy for the logger. Sampling caps the\n// global CPU and I/O load that logging puts on your process while attempting\n// to preserve a representative subset of your logs.\ntype LogsSamplingConfig = migration.LogsSamplingConfig\n\n// MetricsConfig exposes the common Telemetry configuration for one component.\n// Experimental: *NOTE* this structure is subject to change or removal in the future.\ntype MetricsConfig = migration.MetricsConfigV030\n\n// TracesConfig exposes the common Telemetry configuration for collector's internal spans.\n// Experimental: *NOTE* this structure is subject to change or removal in the future.\ntype TracesConfig = migration.TracesConfigV030\n\n// Validate checks whether the current configuration is valid\nfunc (c *Config) Validate() error {\n\t// Check when service telemetry metric level is not none, the metrics readers should not be empty\n\tif c.Metrics.Level != configtelemetry.LevelNone && len(c.Metrics.Readers) == 0 {\n\t\treturn errors.New(\"collector telemetry metrics reader should exist when metric level is not none\")\n\t}\n\n\tif c.Metrics.Views != nil && c.Metrics.Level != configtelemetry.LevelDetailed {\n\t\treturn errors.New(\"service::telemetry::metrics::views can only be set when service::telemetry::metrics::level is detailed\")\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/config_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelconftelemetry\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tconfig \"go.opentelemetry.io/contrib/otelconf/v0.3.0\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/confmap\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n\t\"go.opentelemetry.io/collector/confmap/xconfmap\"\n)\n\nfunc TestComponentConfigStruct(t *testing.T) {\n\trequire.NoError(t, componenttest.CheckConfigStruct(\n\t\tNewFactory().CreateDefaultConfig(),\n\t))\n}\n\nfunc TestUnmarshalDefaultConfig(t *testing.T) {\n\tfactory := NewFactory()\n\tcfg := factory.CreateDefaultConfig()\n\trequire.NoError(t, confmap.New().Unmarshal(&cfg))\n\tassert.Equal(t, factory.CreateDefaultConfig(), cfg)\n}\n\nfunc TestDefaultConfig_DoesNotEnableResourceConstantLabels(t *testing.T) {\n\tcfg := createDefaultConfig().(*Config)\n\trequire.Len(t, cfg.Metrics.Readers, 1)\n\trequire.NotNil(t, cfg.Metrics.Readers[0].Pull)\n\trequire.NotNil(t, cfg.Metrics.Readers[0].Pull.Exporter.Prometheus)\n\tassert.Nil(t, cfg.Metrics.Readers[0].Pull.Exporter.Prometheus.WithResourceConstantLabels)\n}\n\nfunc TestConfig(t *testing.T) {\n\tt.Parallel()\n\n\ttype testcase struct {\n\t\tsetup        func(*testing.T) // optional testcase setup\n\t\tconfig       *Config\n\t\tunmarshalErr string\n\t\tvalidateErr  string\n\t}\n\n\ttests := map[string]testcase{\n\t\t\"config_empty.yaml\": {\n\t\t\tconfig: createDefaultConfig().(*Config),\n\t\t},\n\t\t\"config_logs.yaml\": {\n\t\t\tconfig: func() *Config {\n\t\t\t\tcfg := createDefaultConfig().(*Config)\n\t\t\t\tcfg.Logs.Development = true\n\t\t\t\tcfg.Logs.DisableCaller = true\n\t\t\t\tcfg.Logs.DisableStacktrace = true\n\t\t\t\tcfg.Logs.InitialFields = map[string]any{\"fieldKey\": \"fieldValue\"}\n\t\t\t\tcfg.Logs.Level = zap.InfoLevel\n\t\t\t\tcfg.Logs.Sampling = &LogsSamplingConfig{\n\t\t\t\t\tEnabled:    false,\n\t\t\t\t\tTick:       1 * time.Second,\n\t\t\t\t\tInitial:    234,\n\t\t\t\t\tThereafter: 567,\n\t\t\t\t}\n\t\t\t\tcfg.Logs.Processors = []config.LogRecordProcessor{{\n\t\t\t\t\tBatch: &config.BatchLogRecordProcessor{\n\t\t\t\t\t\tExporter: config.LogRecordExporter{\n\t\t\t\t\t\t\tConsole: config.Console{},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t}}\n\t\t\t\treturn cfg\n\t\t\t}(),\n\t\t},\n\t\t\"config_metrics_empty_readers.yaml\": {\n\t\t\tconfig: func() *Config {\n\t\t\t\tcfg := createDefaultConfig().(*Config)\n\t\t\t\tcfg.Metrics.Level = configtelemetry.LevelNone\n\t\t\t\tcfg.Metrics.Readers = []config.MetricReader{}\n\t\t\t\treturn cfg\n\t\t\t}(),\n\t\t},\n\t\t\"config_invalid_unknown_field.yaml\": {\n\t\t\tunmarshalErr: `invalid keys: unknown`,\n\t\t},\n\t\t\"config_invalid_metrics_empty_readers.yaml\": {\n\t\t\tvalidateErr: `collector telemetry metrics reader should exist when metric level is not none`,\n\t\t},\n\t\t\"config_invalid_metrics_views_level.yaml\": {\n\t\t\tvalidateErr: `service::telemetry::metrics::views can only be set when service::telemetry::metrics::level is detailed`,\n\t\t},\n\t}\n\n\tfor filename, test := range tests {\n\t\tt.Run(filename, func(t *testing.T) {\n\t\t\tif test.setup != nil {\n\t\t\t\ttest.setup(t)\n\t\t\t}\n\n\t\t\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", filename))\n\t\t\trequire.NoError(t, err)\n\n\t\t\tcfg := createDefaultConfig().(*Config)\n\t\t\terr = cm.Unmarshal(cfg)\n\t\t\tif test.unmarshalErr != \"\" {\n\t\t\t\tassert.ErrorContains(t, err, test.unmarshalErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\n\t\t\terr = xconfmap.Validate(cfg)\n\t\t\tif test.validateErr != \"\" {\n\t\t\t\tassert.ErrorContains(t, err, test.validateErr)\n\t\t\t\treturn\n\t\t\t}\n\t\t\trequire.NoError(t, err)\n\n\t\t\tassert.Equal(t, test.config, cfg)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/factory.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelconftelemetry // import \"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\"\n\nimport (\n\t\"time\"\n\n\tconfig \"go.opentelemetry.io/contrib/otelconf/v0.3.0\"\n\t\"go.uber.org/zap/zapcore\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n)\n\n// NewFactory creates a new telemetry.Factory that uses otelconf\n// to configure opentelemetry-go SDK telemetry providers.\nfunc NewFactory() telemetry.Factory {\n\treturn telemetry.NewFactory(\n\t\tcreateDefaultConfig,\n\t\ttelemetry.WithCreateResource(createResource),\n\t\ttelemetry.WithCreateLogger(createLogger),\n\t\ttelemetry.WithCreateMeterProvider(createMeterProvider),\n\t\ttelemetry.WithCreateTracerProvider(createTracerProvider),\n\t)\n}\n\nfunc createDefaultConfig() component.Config {\n\tmetricsHost := \"localhost\"\n\tif !metadata.TelemetryUseLocalHostAsDefaultMetricsAddressFeatureGate.IsEnabled() {\n\t\tmetricsHost = \"\"\n\t}\n\n\treturn &Config{\n\t\tLogs: LogsConfig{\n\t\t\tLevel:       zapcore.InfoLevel,\n\t\t\tDevelopment: false,\n\t\t\tEncoding:    \"console\",\n\t\t\tSampling: &LogsSamplingConfig{\n\t\t\t\tEnabled:    true,\n\t\t\t\tTick:       10 * time.Second,\n\t\t\t\tInitial:    10,\n\t\t\t\tThereafter: 100,\n\t\t\t},\n\t\t\tOutputPaths:        []string{\"stderr\"},\n\t\t\tErrorOutputPaths:   []string{\"stderr\"},\n\t\t\tDisableCaller:      false,\n\t\t\tDisableStacktrace:  false,\n\t\t\tInitialFields:      map[string]any(nil),\n\t\t\tDisableZapResource: false,\n\t\t},\n\t\tMetrics: MetricsConfig{\n\t\t\tLevel: configtelemetry.LevelNormal,\n\t\t\tMeterProvider: config.MeterProvider{\n\t\t\t\tReaders: []config.MetricReader{\n\t\t\t\t\t{\n\t\t\t\t\t\tPull: &config.PullMetricReader{Exporter: config.PullMetricExporter{Prometheus: &config.Prometheus{\n\t\t\t\t\t\t\tWithoutScopeInfo:  ptr(true),\n\t\t\t\t\t\t\tWithoutUnits:      ptr(true),\n\t\t\t\t\t\t\tWithoutTypeSuffix: ptr(true),\n\t\t\t\t\t\t\tHost:              &metricsHost,\n\t\t\t\t\t\t\tPort:              ptr(8888),\n\t\t\t\t\t\t}}},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n\nfunc ptr[T any](v T) *T {\n\treturn &v\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/factory_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelconftelemetry\n\nimport (\n\t\"strconv\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/featuregate\"\n\t\"go.opentelemetry.io/collector/service/internal/metadata\"\n)\n\nfunc TestDefaultConfig(t *testing.T) {\n\ttests := []struct {\n\t\texpected string\n\t\tgate     bool\n\t}{\n\t\t{\n\t\t\texpected: \"localhost\",\n\t\t\tgate:     true,\n\t\t},\n\t\t{\n\t\t\texpected: \"\",\n\t\t\tgate:     false,\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(\"UseLocalHostAsDefaultMetricsAddress/\"+strconv.FormatBool(tt.gate), func(t *testing.T) {\n\t\t\tprev := metadata.TelemetryUseLocalHostAsDefaultMetricsAddressFeatureGate.IsEnabled()\n\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.TelemetryUseLocalHostAsDefaultMetricsAddressFeatureGate.ID(), tt.gate))\n\t\t\tdefer func() {\n\t\t\t\t// Restore previous value.\n\t\t\t\trequire.NoError(t, featuregate.GlobalRegistry().Set(metadata.TelemetryUseLocalHostAsDefaultMetricsAddressFeatureGate.ID(), prev))\n\t\t\t}()\n\t\t\tcfg := NewFactory().CreateDefaultConfig()\n\t\t\trequire.Len(t, cfg.(*Config).Metrics.Readers, 1)\n\t\t\tassert.Equal(t, tt.expected, *cfg.(*Config).Metrics.Readers[0].Pull.Exporter.Prometheus.Host)\n\t\t\tassert.Equal(t, 8888, *cfg.(*Config).Metrics.Readers[0].Pull.Exporter.Prometheus.Port)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/internal/migration/normalize.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage migration // import \"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry/internal/migration\"\n\nimport \"strings\"\n\nfunc normalizeEndpoint(endpoint string, insecure *bool) *string {\n\tif !strings.HasPrefix(endpoint, \"https://\") && !strings.HasPrefix(endpoint, \"http://\") {\n\t\tif insecure != nil && *insecure {\n\t\t\tendpoint = \"http://\" + endpoint\n\t\t} else {\n\t\t\tendpoint = \"https://\" + endpoint\n\t\t}\n\t}\n\treturn &endpoint\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/internal/migration/testdata/v0.2.0_logs.yaml",
    "content": "level: \"info\"\nprocessors:\n  - batch:\n      exporter:\n        otlp:\n          protocol: http/protobuf\n          endpoint: 127.0.0.1:4317\n          headers:\n            \"key1\": \"value1\"\n  - simple:\n      exporter:\n        console: {}\n  - simple:\n      exporter:\n        otlp:\n          protocol: http/protobuf\n          endpoint: http://127.0.0.1:4317\n          headers:\n            \"key1\": \"value1\"\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/internal/migration/testdata/v0.2.0_metrics.yaml",
    "content": "readers:\n  - periodic:\n      exporter:\n        otlp:\n          protocol: http/protobuf\n          endpoint: 127.0.0.1:4317\n          headers:\n            \"key1\": \"value1\"\n            \"key2\": \"value2\"\n  - pull:\n      exporter:\n        prometheus:\n          host: 127.0.0.1\n          port: 8902"
  },
  {
    "path": "service/telemetry/otelconftelemetry/internal/migration/testdata/v0.2.0_traces.yaml",
    "content": "processors:\n  - batch:\n      exporter:\n        otlp:\n          protocol: http/protobuf\n          endpoint: 127.0.0.1:4317\n          headers:\n            \"key1\": \"value1\"\n  - simple:\n      exporter:\n        console: {}\n  - simple:\n      exporter:\n        otlp:\n          protocol: http/protobuf\n          endpoint: http://127.0.0.1:4317\n          headers:\n            \"key1\": \"value1\"\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/internal/migration/testdata/v0.3.0_logs.yaml",
    "content": "level: \"info\"\nprocessors:\n  - batch:\n      exporter:\n        otlp:\n          protocol: http/protobuf\n          endpoint: 127.0.0.1:4317\n          headers:\n          - name: \"key1\"\n            value: \"value1\"\n  - simple:\n      exporter:\n        console: {}\n  - simple:\n      exporter:\n        otlp:\n          protocol: http/protobuf\n          endpoint: http://127.0.0.1:4317\n          headers:\n          - name: \"key1\"\n            value: \"value1\"\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/internal/migration/testdata/v0.3.0_metrics.yaml",
    "content": "level: detailed\nreaders:\n  - periodic:\n      exporter:\n        otlp:\n          protocol: http/protobuf\n          endpoint: 127.0.0.1:4317\n          headers:\n          - name: \"key1\"\n            value: \"value1\"\n  - pull:\n      exporter:\n        prometheus:\n          host: 127.0.0.1\n          port: 8902"
  },
  {
    "path": "service/telemetry/otelconftelemetry/internal/migration/testdata/v0.3.0_traces.yaml",
    "content": "level: \"none\"\nprocessors:\n  - batch:\n      exporter:\n        otlp:\n          protocol: http/protobuf\n          endpoint: 127.0.0.1:4317\n          headers:\n          - name: \"key1\"\n            value: \"value1\"\n  - simple:\n      exporter:\n        console: {}\n  - simple:\n      exporter:\n        otlp:\n          protocol: http/protobuf\n          endpoint: http://127.0.0.1:4317\n          headers:\n          - name: \"key1\"\n            value: \"value1\"\nsampler:\n  parent_based:\n    root:\n      trace_id_ratio_based:\n        ratio: 0.01\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/internal/migration/v0.2.0.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage migration // import \"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry/internal/migration\"\n\nimport (\n\tconfigv02 \"go.opentelemetry.io/contrib/otelconf/v0.2.0\"\n\tconfig \"go.opentelemetry.io/contrib/otelconf/v0.3.0\"\n\t\"go.uber.org/zap/zapcore\"\n\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n)\n\ntype tracesConfigV020 struct {\n\tLevel       configtelemetry.Level     `mapstructure:\"level\"`\n\tPropagators []string                  `mapstructure:\"propagators\"`\n\tProcessors  []configv02.SpanProcessor `mapstructure:\"processors\"`\n}\n\ntype metricsConfigV020 struct {\n\tLevel   configtelemetry.Level    `mapstructure:\"level\"`\n\tReaders []configv02.MetricReader `mapstructure:\"readers\"`\n}\n\ntype logsConfigV020 struct {\n\tLevel             zapcore.Level                  `mapstructure:\"level\"`\n\tDevelopment       bool                           `mapstructure:\"development\"`\n\tEncoding          string                         `mapstructure:\"encoding\"`\n\tDisableCaller     bool                           `mapstructure:\"disable_caller\"`\n\tDisableStacktrace bool                           `mapstructure:\"disable_stacktrace\"`\n\tSampling          *LogsSamplingConfig            `mapstructure:\"sampling\"`\n\tOutputPaths       []string                       `mapstructure:\"output_paths\"`\n\tErrorOutputPaths  []string                       `mapstructure:\"error_output_paths\"`\n\tInitialFields     map[string]any                 `mapstructure:\"initial_fields\"`\n\tProcessors        []configv02.LogRecordProcessor `mapstructure:\"processors\"`\n}\n\nfunc headersV02ToV03(in configv02.Headers) []config.NameStringValuePair {\n\theaders := make([]config.NameStringValuePair, 0, len(in))\n\tfor k, v := range in {\n\t\theaders = append(headers, config.NameStringValuePair{\n\t\t\tName:  k,\n\t\t\tValue: &v,\n\t\t})\n\t}\n\treturn headers\n}\n\nfunc otlpV02ToV03(in *configv02.OTLP) *config.OTLP {\n\tif in == nil {\n\t\treturn nil\n\t}\n\treturn &config.OTLP{\n\t\tCertificate:       in.Certificate,\n\t\tClientCertificate: in.ClientCertificate,\n\t\tClientKey:         in.ClientKey,\n\t\tCompression:       in.Compression,\n\t\tEndpoint:          normalizeEndpoint(in.Endpoint, in.Insecure),\n\t\tInsecure:          in.Insecure,\n\t\tProtocol:          &in.Protocol,\n\t\tTimeout:           in.Timeout,\n\t\tHeaders:           headersV02ToV03(in.Headers),\n\t}\n}\n\nfunc otlpMetricV02ToV03(in *configv02.OTLPMetric) *config.OTLPMetric {\n\tif in == nil {\n\t\treturn nil\n\t}\n\treturn &config.OTLPMetric{\n\t\tCertificate:       in.Certificate,\n\t\tClientCertificate: in.ClientCertificate,\n\t\tClientKey:         in.ClientKey,\n\t\tCompression:       in.Compression,\n\t\tEndpoint:          normalizeEndpoint(in.Endpoint, in.Insecure),\n\t\tInsecure:          in.Insecure,\n\t\tProtocol:          &in.Protocol,\n\t\tTimeout:           in.Timeout,\n\t\tHeaders:           headersV02ToV03(in.Headers),\n\t}\n}\n\nfunc zipkinV02ToV03(in *configv02.Zipkin) *config.Zipkin {\n\tif in == nil {\n\t\treturn nil\n\t}\n\treturn &config.Zipkin{\n\t\tEndpoint: &in.Endpoint,\n\t\tTimeout:  in.Timeout,\n\t}\n}\n\nfunc tracesConfigV02ToV03(v2 tracesConfigV020, v3 *TracesConfigV030) error {\n\tprocessors := make([]config.SpanProcessor, len(v2.Processors))\n\tfor idx, p := range v2.Processors {\n\t\tprocessors[idx] = config.SpanProcessor{}\n\t\tif p.Batch != nil {\n\t\t\tprocessors[idx].Batch = &config.BatchSpanProcessor{\n\t\t\t\tExportTimeout:      p.Batch.ExportTimeout,\n\t\t\t\tMaxExportBatchSize: p.Batch.MaxExportBatchSize,\n\t\t\t\tMaxQueueSize:       p.Batch.MaxQueueSize,\n\t\t\t\tScheduleDelay:      p.Batch.ScheduleDelay,\n\t\t\t\tExporter: config.SpanExporter{\n\t\t\t\t\tConsole:              config.Console(p.Batch.Exporter.Console),\n\t\t\t\t\tOTLP:                 otlpV02ToV03(p.Batch.Exporter.OTLP),\n\t\t\t\t\tZipkin:               zipkinV02ToV03(p.Batch.Exporter.Zipkin),\n\t\t\t\t\tAdditionalProperties: p.Batch.Exporter.AdditionalProperties,\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t\tif p.Simple != nil {\n\t\t\tprocessors[idx].Simple = &config.SimpleSpanProcessor{\n\t\t\t\tExporter: config.SpanExporter{\n\t\t\t\t\tConsole:              config.Console(p.Simple.Exporter.Console),\n\t\t\t\t\tOTLP:                 otlpV02ToV03(p.Simple.Exporter.OTLP),\n\t\t\t\t\tZipkin:               zipkinV02ToV03(p.Simple.Exporter.Zipkin),\n\t\t\t\t\tAdditionalProperties: p.Simple.Exporter.AdditionalProperties,\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t\tprocessors[idx].AdditionalProperties = p.AdditionalProperties\n\t}\n\tv3.Level = v2.Level\n\tv3.Propagators = v2.Propagators\n\tv3.Processors = processors\n\treturn nil\n}\n\nfunc prometheusV02ToV03(in *configv02.Prometheus) *config.Prometheus {\n\tif in == nil {\n\t\treturn nil\n\t}\n\treturn &config.Prometheus{\n\t\tHost:                       in.Host,\n\t\tPort:                       in.Port,\n\t\tWithoutScopeInfo:           in.WithoutScopeInfo,\n\t\tWithoutUnits:               in.WithoutUnits,\n\t\tWithoutTypeSuffix:          in.WithoutTypeSuffix,\n\t\tWithResourceConstantLabels: (*config.IncludeExclude)(in.WithResourceConstantLabels),\n\t}\n}\n\nfunc metricsConfigV02ToV03(v2 metricsConfigV020, v3 *MetricsConfigV030) error {\n\treaders := make([]config.MetricReader, len(v2.Readers))\n\tfor idx, p := range v2.Readers {\n\t\treaders[idx] = config.MetricReader{}\n\t\tif p.Periodic != nil {\n\t\t\treaders[idx].Periodic = &config.PeriodicMetricReader{\n\t\t\t\tInterval: p.Periodic.Interval,\n\t\t\t\tTimeout:  p.Periodic.Timeout,\n\t\t\t\tExporter: config.PushMetricExporter{\n\t\t\t\t\tConsole:              config.Console(p.Periodic.Exporter.Console),\n\t\t\t\t\tOTLP:                 otlpMetricV02ToV03(p.Periodic.Exporter.OTLP),\n\t\t\t\t\tAdditionalProperties: p.Periodic.Exporter.AdditionalProperties,\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t\tif p.Pull != nil {\n\t\t\treaders[idx].Pull = &config.PullMetricReader{\n\t\t\t\tExporter: config.PullMetricExporter{\n\t\t\t\t\tPrometheus:           prometheusV02ToV03(p.Pull.Exporter.Prometheus),\n\t\t\t\t\tAdditionalProperties: p.Pull.Exporter.AdditionalProperties,\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t}\n\tv3.Level = v2.Level\n\tv3.Readers = readers\n\treturn nil\n}\n\nfunc logsConfigV02ToV03(v2 logsConfigV020, v3 *LogsConfigV030) error {\n\tprocessors := make([]config.LogRecordProcessor, len(v2.Processors))\n\tfor idx, p := range v2.Processors {\n\t\tprocessors[idx] = config.LogRecordProcessor{}\n\t\tif p.Batch != nil {\n\t\t\tprocessors[idx].Batch = &config.BatchLogRecordProcessor{\n\t\t\t\tExportTimeout:      p.Batch.ExportTimeout,\n\t\t\t\tMaxExportBatchSize: p.Batch.MaxExportBatchSize,\n\t\t\t\tMaxQueueSize:       p.Batch.MaxQueueSize,\n\t\t\t\tScheduleDelay:      p.Batch.ScheduleDelay,\n\t\t\t\tExporter: config.LogRecordExporter{\n\t\t\t\t\tConsole:              config.Console(p.Batch.Exporter.Console),\n\t\t\t\t\tOTLP:                 otlpV02ToV03(p.Batch.Exporter.OTLP),\n\t\t\t\t\tAdditionalProperties: p.Batch.Exporter.AdditionalProperties,\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t\tif p.Simple != nil {\n\t\t\tprocessors[idx].Simple = &config.SimpleLogRecordProcessor{\n\t\t\t\tExporter: config.LogRecordExporter{\n\t\t\t\t\tConsole:              config.Console(p.Simple.Exporter.Console),\n\t\t\t\t\tOTLP:                 otlpV02ToV03(p.Simple.Exporter.OTLP),\n\t\t\t\t\tAdditionalProperties: p.Simple.Exporter.AdditionalProperties,\n\t\t\t\t},\n\t\t\t}\n\t\t}\n\t\tprocessors[idx].AdditionalProperties = p.AdditionalProperties\n\t}\n\tv3.Level = v2.Level\n\tv3.Development = v2.Development\n\tv3.Encoding = v2.Encoding\n\tv3.DisableCaller = v2.DisableCaller\n\tv3.DisableStacktrace = v2.DisableStacktrace\n\tv3.Sampling = v2.Sampling\n\tv3.OutputPaths = v2.OutputPaths\n\tv3.ErrorOutputPaths = v2.ErrorOutputPaths\n\tv3.InitialFields = v2.InitialFields\n\tv3.Processors = processors\n\treturn nil\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/internal/migration/v0.2.0_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage migration\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\tconfig \"go.opentelemetry.io/contrib/otelconf/v0.3.0\"\n\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n)\n\nfunc TestUnmarshalLogsConfigV020(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"v0.2.0_logs.yaml\"))\n\trequire.NoError(t, err)\n\n\tcfg := LogsConfigV030{\n\t\tEncoding: \"console\",\n\t}\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\trequire.Len(t, cfg.Processors, 3)\n\t// check the endpoint is prefixed w/ https\n\trequire.Equal(t, \"https://127.0.0.1:4317\", *cfg.Processors[0].Batch.Exporter.OTLP.Endpoint)\n\t// check the endpoint is prefixed w/ http\n\trequire.Equal(t, \"http://127.0.0.1:4317\", *cfg.Processors[2].Simple.Exporter.OTLP.Endpoint)\n\t// ensure defaults set in the original config object are not lost\n\trequire.Equal(t, \"console\", cfg.Encoding)\n}\n\nfunc TestUnmarshalTracesConfigV020(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"v0.2.0_traces.yaml\"))\n\trequire.NoError(t, err)\n\n\tcfg := TracesConfigV030{\n\t\tLevel: configtelemetry.LevelNone,\n\t}\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\trequire.Len(t, cfg.Processors, 3)\n\t// check the endpoint is prefixed w/ https\n\trequire.Equal(t, \"https://127.0.0.1:4317\", *cfg.Processors[0].Batch.Exporter.OTLP.Endpoint)\n\t// check the endpoint is prefixed w/ http\n\trequire.Equal(t, \"http://127.0.0.1:4317\", *cfg.Processors[2].Simple.Exporter.OTLP.Endpoint)\n\t// ensure defaults set in the original config object are not lost\n\trequire.Equal(t, configtelemetry.LevelNone, cfg.Level)\n}\n\nfunc TestUnmarshalMetricsConfigV020(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"v0.2.0_metrics.yaml\"))\n\trequire.NoError(t, err)\n\n\tcfg := MetricsConfigV030{\n\t\tLevel: configtelemetry.LevelBasic,\n\t}\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\trequire.Len(t, cfg.Readers, 2)\n\t// check the endpoint is prefixed w/ https\n\trequire.Equal(t, \"https://127.0.0.1:4317\", *cfg.Readers[0].Periodic.Exporter.OTLP.Endpoint)\n\trequire.ElementsMatch(t, []config.NameStringValuePair{{Name: \"key1\", Value: ptr(\"value1\")}, {Name: \"key2\", Value: ptr(\"value2\")}}, cfg.Readers[0].Periodic.Exporter.OTLP.Headers)\n\t// ensure defaults set in the original config object are not lost\n\trequire.Equal(t, configtelemetry.LevelBasic, cfg.Level)\n}\n\nfunc ptr[T any](v T) *T {\n\treturn &v\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/internal/migration/v0.3.0.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage migration // import \"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry/internal/migration\"\n\nimport (\n\t\"time\"\n\n\tconfig \"go.opentelemetry.io/contrib/otelconf/v0.3.0\"\n\t\"go.uber.org/zap/zapcore\"\n\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/confmap\"\n)\n\ntype TracesConfigV030 struct {\n\t// Level configures whether spans are emitted or not, the possible values are:\n\t//  - \"none\" indicates that no tracing data should be collected;\n\t//  - \"basic\" is the recommended and covers the basics of the service telemetry.\n\tLevel configtelemetry.Level `mapstructure:\"level\"`\n\t// Propagators is a list of TextMapPropagators from the supported propagators list. Currently,\n\t// tracecontext and  b3 are supported. By default, the value is set to empty list and\n\t// context propagation is disabled.\n\tPropagators []string `mapstructure:\"propagators\"`\n\n\tconfig.TracerProvider `mapstructure:\",squash\"`\n}\n\nfunc (c *TracesConfigV030) Unmarshal(conf *confmap.Conf) error {\n\tunmarshaled := *c\n\tif err := conf.Unmarshal(c); err != nil {\n\t\tv2TracesConfig := tracesConfigV020{\n\t\t\tLevel:       unmarshaled.Level,\n\t\t\tPropagators: unmarshaled.Propagators,\n\t\t}\n\t\t// try unmarshaling using v0.2.0 struct\n\t\tif e := conf.Unmarshal(&v2TracesConfig); e != nil {\n\t\t\t// error could not be resolved through backwards\n\t\t\t// compatibility attempts\n\t\t\treturn err\n\t\t}\n\t\t// TODO: add a warning log to tell users to migrate their config\n\t\treturn tracesConfigV02ToV03(v2TracesConfig, c)\n\t}\n\t// ensure endpoint normalization occurs\n\tfor _, r := range c.Processors {\n\t\tif r.Batch != nil {\n\t\t\tif r.Batch.Exporter.OTLP != nil {\n\t\t\t\tr.Batch.Exporter.OTLP.Endpoint = normalizeEndpoint(*r.Batch.Exporter.OTLP.Endpoint, r.Batch.Exporter.OTLP.Insecure)\n\t\t\t}\n\t\t}\n\t\tif r.Simple != nil {\n\t\t\tif r.Simple.Exporter.OTLP != nil && r.Simple.Exporter.OTLP.Endpoint != nil {\n\t\t\t\tr.Simple.Exporter.OTLP.Endpoint = normalizeEndpoint(*r.Simple.Exporter.OTLP.Endpoint, r.Simple.Exporter.OTLP.Insecure)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\ntype MetricsConfigV030 struct {\n\t// Level is the level of telemetry metrics, the possible values are:\n\t//  - \"none\" indicates that no telemetry data should be collected;\n\t//  - \"basic\" is the recommended and covers the basics of the service telemetry.\n\t//  - \"normal\" adds some other indicators on top of basic.\n\t//  - \"detailed\" adds dimensions and views to the previous levels.\n\tLevel configtelemetry.Level `mapstructure:\"level\"`\n\n\tconfig.MeterProvider `mapstructure:\",squash\"`\n}\n\nfunc (c *MetricsConfigV030) Unmarshal(conf *confmap.Conf) error {\n\tunmarshaled := *c\n\tif err := conf.Unmarshal(c); err != nil {\n\t\tv02 := metricsConfigV020{\n\t\t\tLevel: unmarshaled.Level,\n\t\t}\n\t\t// try unmarshaling using v0.2.0 struct\n\t\tif e := conf.Unmarshal(&v02); e != nil {\n\t\t\t// error could not be resolved through backwards\n\t\t\t// compatibility attempts\n\t\t\treturn err\n\t\t}\n\t\t// TODO: add a warning log to tell users to migrate their config\n\t\treturn metricsConfigV02ToV03(v02, c)\n\t}\n\t// ensure endpoint normalization occurs\n\tfor _, r := range c.Readers {\n\t\tif r.Periodic != nil {\n\t\t\tif r.Periodic.Exporter.OTLP != nil && r.Periodic.Exporter.OTLP.Endpoint != nil {\n\t\t\t\tr.Periodic.Exporter.OTLP.Endpoint = normalizeEndpoint(*r.Periodic.Exporter.OTLP.Endpoint, r.Periodic.Exporter.OTLP.Insecure)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\ntype LogsConfigV030 struct {\n\t// Level is the minimum enabled logging level.\n\t// (default = \"INFO\")\n\tLevel zapcore.Level `mapstructure:\"level\"`\n\n\t// Development puts the logger in development mode, which changes the\n\t// behavior of DPanicLevel and takes stacktraces more liberally.\n\t// (default = false)\n\tDevelopment bool `mapstructure:\"development,omitempty\"`\n\n\t// Encoding sets the logger's encoding.\n\t// Example values are \"json\", \"console\".\n\tEncoding string `mapstructure:\"encoding\"`\n\n\t// DisableCaller stops annotating logs with the calling function's file\n\t// name and line number. By default, all logs are annotated.\n\t// (default = false)\n\tDisableCaller bool `mapstructure:\"disable_caller,omitempty\"`\n\n\t// DisableStacktrace completely disables automatic stacktrace capturing. By\n\t// default, stacktraces are captured for WarnLevel and above logs in\n\t// development and ErrorLevel and above in production.\n\t// (default = false)\n\tDisableStacktrace bool `mapstructure:\"disable_stacktrace,omitempty\"`\n\n\t// Sampling sets a sampling policy.\n\t// Default:\n\t// \t\tsampling:\n\t//\t   \t\tenabled: true\n\t//\t   \t\ttick: 10s\n\t//\t   \t\tinitial: 10\n\t//\t   \t\tthereafter: 100\n\t// Sampling can be disabled by setting 'enabled' to false\n\tSampling *LogsSamplingConfig `mapstructure:\"sampling\"`\n\n\t// OutputPaths is a list of URLs or file paths to write logging output to.\n\t// The URLs could only be with \"file\" schema or without schema.\n\t// The URLs with \"file\" schema must be an absolute path.\n\t// The URLs without schema are treated as local file paths.\n\t// \"stdout\" and \"stderr\" are interpreted as os.Stdout and os.Stderr.\n\t// see details at Open in zap/writer.go.\n\t// (default = [\"stderr\"])\n\tOutputPaths []string `mapstructure:\"output_paths\"`\n\n\t// ErrorOutputPaths is a list of URLs or file paths to write zap internal logger errors to.\n\t// The URLs could only be with \"file\" schema or without schema.\n\t// The URLs with \"file\" schema must use absolute paths.\n\t// The URLs without schema are treated as local file paths.\n\t// \"stdout\" and \"stderr\" are interpreted as os.Stdout and os.Stderr.\n\t// see details at Open in zap/writer.go.\n\t//\n\t// Note that this setting only affects the zap internal logger errors.\n\t// (default = [\"stderr\"])\n\tErrorOutputPaths []string `mapstructure:\"error_output_paths\"`\n\n\t// InitialFields is a collection of fields to add to the root logger.\n\t// Example:\n\t//\n\t// \t\tinitial_fields:\n\t//\t   \t\tfoo: \"bar\"\n\t//\n\t// By default, there is no initial field.\n\tInitialFields map[string]any `mapstructure:\"initial_fields,omitempty\"`\n\n\t// Processors allow configuration of log record processors to emit logs to\n\t// any number of supported backends.\n\tProcessors []config.LogRecordProcessor `mapstructure:\"processors,omitempty\"`\n\n\t// DisableZapResource disables adding resource attributes to logs exported through Zap. This does not affect logs exported through OTLP.\n\tDisableZapResource bool `mapstructure:\"disable_zap_resource,omitempty\"`\n}\n\n// LogsSamplingConfig sets a sampling strategy for the logger. Sampling caps the\n// global CPU and I/O load that logging puts on your process while attempting\n// to preserve a representative subset of your logs.\ntype LogsSamplingConfig struct {\n\t// Enabled enable sampling logging\n\tEnabled bool `mapstructure:\"enabled\"`\n\t// Tick represents the interval in seconds that the logger apply each sampling.\n\tTick time.Duration `mapstructure:\"tick\"`\n\t// Initial represents the first M messages logged each Tick.\n\tInitial int `mapstructure:\"initial\"`\n\t// Thereafter represents the sampling rate, every Nth message will be sampled after Initial messages are logged during each Tick.\n\t// If Thereafter is zero, the logger will drop all the messages after the Initial each Tick.\n\tThereafter int `mapstructure:\"thereafter\"`\n}\n\nfunc (c *LogsConfigV030) Unmarshal(conf *confmap.Conf) error {\n\tunmarshaled := *c\n\tif err := conf.Unmarshal(c); err != nil {\n\t\tv02 := logsConfigV020{\n\t\t\tLevel:             unmarshaled.Level,\n\t\t\tDevelopment:       unmarshaled.Development,\n\t\t\tEncoding:          unmarshaled.Encoding,\n\t\t\tDisableCaller:     unmarshaled.DisableCaller,\n\t\t\tDisableStacktrace: unmarshaled.DisableStacktrace,\n\t\t\tSampling:          unmarshaled.Sampling,\n\t\t\tOutputPaths:       unmarshaled.OutputPaths,\n\t\t\tErrorOutputPaths:  unmarshaled.ErrorOutputPaths,\n\t\t\tInitialFields:     unmarshaled.InitialFields,\n\t\t}\n\t\t// try unmarshaling using v0.2.0 struct\n\t\tif e := conf.Unmarshal(&v02); e != nil {\n\t\t\t// error could not be resolved through backwards\n\t\t\t// compatibility attempts\n\t\t\treturn err\n\t\t}\n\t\t// TODO: add a warning log to tell users to migrate their config\n\t\treturn logsConfigV02ToV03(v02, c)\n\t}\n\t// ensure endpoint normalization occurs\n\tfor _, r := range c.Processors {\n\t\tif r.Batch != nil {\n\t\t\tif r.Batch.Exporter.OTLP != nil {\n\t\t\t\tr.Batch.Exporter.OTLP.Endpoint = normalizeEndpoint(*r.Batch.Exporter.OTLP.Endpoint, r.Batch.Exporter.OTLP.Insecure)\n\t\t\t}\n\t\t}\n\t\tif r.Simple != nil {\n\t\t\tif r.Simple.Exporter.OTLP != nil && r.Simple.Exporter.OTLP.Endpoint != nil {\n\t\t\t\tr.Simple.Exporter.OTLP.Endpoint = normalizeEndpoint(*r.Simple.Exporter.OTLP.Endpoint, r.Simple.Exporter.OTLP.Insecure)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/internal/migration/v0.3.0_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage migration\n\nimport (\n\t\"path/filepath\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/confmap/confmaptest\"\n)\n\nfunc TestUnmarshalLogsConfigV030(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"v0.3.0_logs.yaml\"))\n\trequire.NoError(t, err)\n\n\tcfg := LogsConfigV030{}\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\trequire.Len(t, cfg.Processors, 3)\n\t// check the endpoint is prefixed w/ https\n\trequire.Equal(t, \"https://127.0.0.1:4317\", *cfg.Processors[0].Batch.Exporter.OTLP.Endpoint)\n\t// check the endpoint is prefixed w/ http\n\trequire.Equal(t, \"http://127.0.0.1:4317\", *cfg.Processors[2].Simple.Exporter.OTLP.Endpoint)\n}\n\nfunc TestUnmarshalTracesConfigV030(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"v0.3.0_traces.yaml\"))\n\trequire.NoError(t, err)\n\n\tcfg := TracesConfigV030{}\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\trequire.Len(t, cfg.Processors, 3)\n\t// check the endpoint is prefixed w/ https\n\trequire.Equal(t, \"https://127.0.0.1:4317\", *cfg.Processors[0].Batch.Exporter.OTLP.Endpoint)\n\t// check the endpoint is prefixed w/ http\n\trequire.Equal(t, \"http://127.0.0.1:4317\", *cfg.Processors[2].Simple.Exporter.OTLP.Endpoint)\n}\n\nfunc TestUnmarshalMetricsConfigV030(t *testing.T) {\n\tcm, err := confmaptest.LoadConf(filepath.Join(\"testdata\", \"v0.3.0_metrics.yaml\"))\n\trequire.NoError(t, err)\n\n\tcfg := MetricsConfigV030{}\n\trequire.NoError(t, cm.Unmarshal(&cfg))\n\trequire.Len(t, cfg.Readers, 2)\n\n\t// check the endpoint is prefixed w/ https\n\trequire.Equal(t, \"https://127.0.0.1:4317\", *cfg.Readers[0].Periodic.Exporter.OTLP.Endpoint)\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/logger.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelconftelemetry // import \"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\"\n\nimport (\n\t\"context\"\n\n\totelconf \"go.opentelemetry.io/contrib/otelconf/v0.3.0\"\n\tsdkresource \"go.opentelemetry.io/otel/sdk/resource\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n)\n\n// createLogger creates a Logger and a LoggerProvider from Config.\nfunc createLogger(\n\tctx context.Context,\n\tset telemetry.LoggerSettings,\n\tcomponentConfig component.Config,\n) (*zap.Logger, component.ShutdownFunc, error) {\n\tcfg := componentConfig.(*Config)\n\tattrs := pcommonAttrsToOTelAttrs(set.Resource)\n\tres := sdkresource.NewWithAttributes(\"\", attrs...)\n\n\t// Copied from NewProductionConfig.\n\tec := zap.NewProductionEncoderConfig()\n\tec.EncodeTime = zapcore.ISO8601TimeEncoder\n\tzapCfg := zap.Config{\n\t\tLevel:             zap.NewAtomicLevelAt(cfg.Logs.Level),\n\t\tDevelopment:       cfg.Logs.Development,\n\t\tEncoding:          cfg.Logs.Encoding,\n\t\tEncoderConfig:     ec,\n\t\tOutputPaths:       cfg.Logs.OutputPaths,\n\t\tErrorOutputPaths:  cfg.Logs.ErrorOutputPaths,\n\t\tDisableCaller:     cfg.Logs.DisableCaller,\n\t\tDisableStacktrace: cfg.Logs.DisableStacktrace,\n\t\tInitialFields:     cfg.Logs.InitialFields,\n\t}\n\n\tif zapCfg.Encoding == \"console\" {\n\t\t// Human-readable timestamps for console format of logs.\n\t\tzapCfg.EncoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder\n\t}\n\n\tbuildZapLogger := set.BuildZapLogger\n\tif buildZapLogger == nil {\n\t\t// For backwards compatibility, use zap.Config.Build\n\t\t// if set.BuildZapLogger is not provided.\n\t\tbuildZapLogger = zap.Config.Build\n\t}\n\tlogger, err := buildZapLogger(zapCfg, set.ZapOptions...)\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// The attributes in res.Attributes(), which are generated in telemetry.go,\n\t// are added to logs exported through the LoggerProvider instantiated below.\n\t// To make sure they are also exposed in logs written to stdout, we add\n\t// them as fields to the Zap core created above using WrapCore. We do NOT\n\t// add them to the logger using With, because that would apply to all logs,\n\t// even ones exported through the core that wraps the LoggerProvider,\n\t// meaning that the attributes would be exported twice.\n\tif !cfg.Logs.DisableZapResource && res != nil && len(res.Attributes()) > 0 {\n\t\tlogger = logger.WithOptions(zap.WrapCore(func(c zapcore.Core) zapcore.Core {\n\t\t\tvar fields []zap.Field\n\t\t\tfor _, attr := range res.Attributes() {\n\t\t\t\tfields = append(fields, zap.String(string(attr.Key), attr.Value.Emit()))\n\t\t\t}\n\n\t\t\tr := zap.Dict(\"resource\", fields...)\n\t\t\treturn c.With([]zapcore.Field{r})\n\t\t}))\n\t}\n\n\tif cfg.Logs.Sampling != nil && cfg.Logs.Sampling.Enabled {\n\t\tlogger = logger.WithOptions(zap.WrapCore(func(core zapcore.Core) zapcore.Core {\n\t\t\treturn zapcore.NewSamplerWithOptions(\n\t\t\t\tcore,\n\t\t\t\tcfg.Logs.Sampling.Tick,\n\t\t\t\tcfg.Logs.Sampling.Initial,\n\t\t\t\tcfg.Logs.Sampling.Thereafter,\n\t\t\t)\n\t\t}))\n\t}\n\n\tsdk, err := newSDK(ctx, res, otelconf.OpenTelemetryConfiguration{\n\t\tLoggerProvider: &otelconf.LoggerProvider{\n\t\t\tProcessors: cfg.Logs.Processors,\n\t\t},\n\t})\n\tif err != nil {\n\t\treturn nil, nil, err\n\t}\n\n\t// Wrap the zap.Logger with a special zap.Core so scope attributes\n\t// can be added and removed dynamically, and tee logs to the\n\t// LoggerProvider.\n\tloggerProvider := sdk.LoggerProvider()\n\tlogger = logger.WithOptions(zap.WrapCore(func(core zapcore.Core) zapcore.Core {\n\t\tprovider := zapCoreProvider{\n\t\t\tsourceCore: core,\n\t\t\tlp:         loggerProvider,\n\t\t\tscopeName:  \"go.opentelemetry.io/collector/service\",\n\t\t}\n\t\treturn provider.newCore()\n\t}))\n\n\treturn logger, sdk.Shutdown, nil\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/logger_tee.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelconftelemetry // import \"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\"\n\nimport (\n\t\"slices\"\n\n\t\"go.opentelemetry.io/contrib/bridges/otelzap\"\n\t\"go.opentelemetry.io/otel/log\"\n\t\"go.uber.org/multierr\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\n\t\"go.opentelemetry.io/collector/service/internal/componentattribute\"\n)\n\ntype zapCoreProvider struct {\n\tsourceCore zapcore.Core\n\tlp         log.LoggerProvider\n\tscopeName  string\n}\n\nfunc (zcp *zapCoreProvider) newCore() zapCore {\n\treturn zapCore{\n\t\tsourceCore: zcp.sourceCore,\n\t\totelCore: otelzap.NewCore(\n\t\t\tzcp.scopeName,\n\t\t\totelzap.WithLoggerProvider(zcp.lp),\n\t\t),\n\t\tprovider: zcp,\n\t}\n}\n\n// This struct wraps the original Zap core in order to copy logs to a [log.LoggerProvider] using [otelzap].\n// For the copied logs, component attributes are injected as instrumentation scope attributes.\n//\n// Note that we intentionally do not use zapcore.NewTee here, because it will simply duplicate all log entries\n// to each core. The provided Zap core may have sampling or a minimum log level applied to it, so in order to\n// maintain consistency, we need to ensure that only the logs accepted by the provided core are copied to the\n// log.LoggerProvider.\ntype zapCore struct {\n\tsourceCore zapcore.Core // regular Zap core (logs to stderr)\n\totelCore   zapcore.Core // otelzap core (forwards to OTel Logger)\n\tprovider   *zapCoreProvider\n\twithFields []zap.Field // additional fields injected by the user using .With\n}\n\nvar _ zapcore.Core = zapCore{}\n\nfunc (zc zapCore) With(fields []zapcore.Field) zapcore.Core {\n\tzc.sourceCore = zc.sourceCore.With(fields)\n\tfields = slices.DeleteFunc(fields, func(field zapcore.Field) bool {\n\t\tscope, ok := componentattribute.ExtractLogScopeAttributes(field)\n\t\tif !ok {\n\t\t\treturn false\n\t\t}\n\t\t// Set scope attributes\n\t\tzc.otelCore = otelzap.NewCore(\n\t\t\tzc.provider.scopeName,\n\t\t\totelzap.WithLoggerProvider(zc.provider.lp),\n\t\t\totelzap.WithAttributes(scope...),\n\t\t).With(zc.withFields)\n\t\treturn true\n\t})\n\tzc.otelCore = zc.otelCore.With(fields)\n\tzc.withFields = append(slices.Clone(zc.withFields), fields...)\n\treturn zc\n}\n\nfunc (zc zapCore) Enabled(level zapcore.Level) bool {\n\treturn zc.sourceCore.Enabled(level)\n}\n\nfunc (zc zapCore) Check(entry zapcore.Entry, ce *zapcore.CheckedEntry) *zapcore.CheckedEntry {\n\tce = zc.sourceCore.Check(entry, ce)\n\tif ce != nil {\n\t\t// Only log to the otelzap core if the source core accepted the log entry.\n\t\tce = ce.AddCore(entry, zc.otelCore)\n\t}\n\treturn ce\n}\n\n// This function should never be called, since only the inner cores add themselves to the CheckedEntry.\n// But like zapcore.multiCore, we still implement it for compatibility with non-conforming users.\nfunc (zc zapCore) Write(entry zapcore.Entry, fields []zapcore.Field) error {\n\treturn multierr.Append(\n\t\tzc.sourceCore.Write(entry, fields),\n\t\tzc.otelCore.Write(entry, fields),\n\t)\n}\n\nfunc (zc zapCore) Sync() error {\n\treturn multierr.Append(\n\t\tzc.sourceCore.Sync(),\n\t\tzc.otelCore.Sync(),\n\t)\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/logger_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelconftelemetry // import \"go.opentelemetry.io/collector/service/telemetry\"\n\nimport (\n\t\"context\"\n\t\"encoding/json\"\n\t\"errors\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"strings\"\n\t\"testing\"\n\t\"time\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tconfig \"go.opentelemetry.io/contrib/otelconf/v0.3.0\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/component/componenttest\"\n\tinternalTelemetry \"go.opentelemetry.io/collector/internal/telemetry\"\n\t\"go.opentelemetry.io/collector/pdata/plog/plogotlp\"\n\t\"go.opentelemetry.io/collector/service/internal/componentattribute\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n)\n\nconst (\n\tversion       = \"1.2.3\"\n\tservice       = \"test-service\"\n\ttestAttribute = \"test-attribute\"\n\ttestValue     = \"test-value\"\n)\n\nfunc TestCreateLogger(t *testing.T) {\n\ttests := []struct {\n\t\tname         string\n\t\twantCoreType any\n\t\twantErr      error\n\t\tcfg          Config\n\t}{\n\t\t{\n\t\t\tname:    \"no log config\",\n\t\t\tcfg:     Config{},\n\t\t\twantErr: errors.New(\"no encoder name specified\"),\n\t\t},\n\t\t{\n\t\t\tname: \"log config with invalid processors\",\n\t\t\tcfg: Config{\n\t\t\t\tLogs: LogsConfig{\n\t\t\t\t\tLevel:             zapcore.DebugLevel,\n\t\t\t\t\tDevelopment:       true,\n\t\t\t\t\tEncoding:          \"console\",\n\t\t\t\t\tDisableCaller:     true,\n\t\t\t\t\tDisableStacktrace: true,\n\t\t\t\t\tInitialFields:     map[string]any{\"fieldKey\": \"filed-value\"},\n\t\t\t\t\tProcessors: []config.LogRecordProcessor{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tBatch: &config.BatchLogRecordProcessor{\n\t\t\t\t\t\t\t\tExporter: config.LogRecordExporter{\n\t\t\t\t\t\t\t\t\tOTLP: &config.OTLP{}, // missing required fields\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t\twantErr: errors.New(\"no valid log exporter\"),\n\t\t},\n\t\t{\n\t\t\tname: \"log config with no processors\",\n\t\t\tcfg: Config{\n\t\t\t\tLogs: LogsConfig{\n\t\t\t\t\tLevel:             zapcore.DebugLevel,\n\t\t\t\t\tDevelopment:       true,\n\t\t\t\t\tEncoding:          \"console\",\n\t\t\t\t\tDisableCaller:     true,\n\t\t\t\t\tDisableStacktrace: true,\n\t\t\t\t\tInitialFields:     map[string]any{\"fieldKey\": \"filed-value\"},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"log config with processors\",\n\t\t\tcfg: Config{\n\t\t\t\tLogs: LogsConfig{\n\t\t\t\t\tLevel:             zapcore.DebugLevel,\n\t\t\t\t\tDevelopment:       true,\n\t\t\t\t\tEncoding:          \"console\",\n\t\t\t\t\tDisableCaller:     true,\n\t\t\t\t\tDisableStacktrace: true,\n\t\t\t\t\tInitialFields:     map[string]any{\"fieldKey\": \"filed-value\"},\n\t\t\t\t\tProcessors: []config.LogRecordProcessor{\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tBatch: &config.BatchLogRecordProcessor{\n\t\t\t\t\t\t\t\tExporter: config.LogRecordExporter{\n\t\t\t\t\t\t\t\t\tConsole: config.Console{},\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"log config with sampling\",\n\t\t\tcfg: Config{\n\t\t\t\tLogs: LogsConfig{\n\t\t\t\t\tLevel:       zapcore.InfoLevel,\n\t\t\t\t\tDevelopment: false,\n\t\t\t\t\tEncoding:    \"console\",\n\t\t\t\t\tSampling: &LogsSamplingConfig{\n\t\t\t\t\t\tEnabled:    true,\n\t\t\t\t\t\tTick:       10 * time.Second,\n\t\t\t\t\t\tInitial:    10,\n\t\t\t\t\t\tThereafter: 100,\n\t\t\t\t\t},\n\t\t\t\t\tOutputPaths:       []string{\"stderr\"},\n\t\t\t\t\tErrorOutputPaths:  []string{\"stderr\"},\n\t\t\t\t\tDisableCaller:     false,\n\t\t\t\t\tDisableStacktrace: false,\n\t\t\t\t\tInitialFields:     map[string]any(nil),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"log config with `disable_resource_attributes` enabled\",\n\t\t\tcfg: Config{\n\t\t\t\tLogs: LogsConfig{\n\t\t\t\t\tLevel:              zapcore.InfoLevel,\n\t\t\t\t\tDevelopment:        false,\n\t\t\t\t\tEncoding:           \"console\",\n\t\t\t\t\tOutputPaths:        []string{\"stderr\"},\n\t\t\t\t\tErrorOutputPaths:   []string{\"stderr\"},\n\t\t\t\t\tDisableCaller:      false,\n\t\t\t\t\tDisableStacktrace:  false,\n\t\t\t\t\tInitialFields:      map[string]any(nil),\n\t\t\t\t\tDisableZapResource: true,\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tbuildInfo := component.BuildInfo{}\n\t\t\tfactory := NewFactory()\n\t\t\tresource, err := factory.CreateResource(context.Background(), telemetry.Settings{BuildInfo: buildInfo}, &tt.cfg)\n\t\t\trequire.NoError(t, err)\n\n\t\t\t_, provider, err := factory.CreateLogger(\n\t\t\t\tcontext.Background(), telemetry.LoggerSettings{\n\t\t\t\t\tSettings:       telemetry.Settings{BuildInfo: buildInfo, Resource: &resource},\n\t\t\t\t\tBuildZapLogger: zap.Config.Build,\n\t\t\t\t}, &tt.cfg,\n\t\t\t)\n\t\t\tif tt.wantErr != nil {\n\t\t\t\trequire.ErrorContains(t, err, tt.wantErr.Error())\n\t\t\t} else {\n\t\t\t\trequire.NoError(t, err)\n\t\t\t\trequire.NoError(t, provider.Shutdown(context.Background()))\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCreateLoggerWithResource(t *testing.T) {\n\ttests := []struct {\n\t\tname           string\n\t\tbuildInfo      component.BuildInfo\n\t\tresourceConfig map[string]*string\n\t\twantFields     map[string]string\n\t\tsetConfig      func(cfg *Config)\n\t}{\n\t\t{\n\t\t\tname: \"auto-populated fields only\",\n\t\t\tbuildInfo: component.BuildInfo{\n\t\t\t\tCommand: \"mycommand\",\n\t\t\t\tVersion: \"1.0.0\",\n\t\t\t},\n\t\t\tresourceConfig: map[string]*string{},\n\t\t\twantFields: map[string]string{\n\t\t\t\t\"service.name\":        \"mycommand\",\n\t\t\t\t\"service.version\":     \"1.0.0\",\n\t\t\t\t\"service.instance.id\": \"\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"override service.name\",\n\t\t\tbuildInfo: component.BuildInfo{\n\t\t\t\tCommand: \"mycommand\",\n\t\t\t\tVersion: \"1.0.0\",\n\t\t\t},\n\t\t\tresourceConfig: map[string]*string{\n\t\t\t\t\"service.name\": ptr(\"custom-service\"),\n\t\t\t},\n\t\t\twantFields: map[string]string{\n\t\t\t\t\"service.name\":        \"custom-service\",\n\t\t\t\t\"service.version\":     \"1.0.0\",\n\t\t\t\t\"service.instance.id\": \"\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"override service.version\",\n\t\t\tbuildInfo: component.BuildInfo{\n\t\t\t\tCommand: \"mycommand\",\n\t\t\t\tVersion: \"1.0.0\",\n\t\t\t},\n\t\t\tresourceConfig: map[string]*string{\n\t\t\t\t\"service.version\": ptr(\"2.0.0\"),\n\t\t\t},\n\t\t\twantFields: map[string]string{\n\t\t\t\t\"service.name\":        \"mycommand\",\n\t\t\t\t\"service.version\":     \"2.0.0\",\n\t\t\t\t\"service.instance.id\": \"\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"custom field with auto-populated\",\n\t\t\tbuildInfo: component.BuildInfo{\n\t\t\t\tCommand: \"mycommand\",\n\t\t\t\tVersion: \"1.0.0\",\n\t\t\t},\n\t\t\tresourceConfig: map[string]*string{\n\t\t\t\t\"custom.field\": ptr(\"custom-value\"),\n\t\t\t},\n\t\t\twantFields: map[string]string{\n\t\t\t\t\"service.name\":        \"mycommand\",\n\t\t\t\t\"service.version\":     \"1.0.0\",\n\t\t\t\t\"service.instance.id\": \"\", // Just check presence\n\t\t\t\t\"custom.field\":        \"custom-value\",\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname:           \"resource with no attributes\",\n\t\t\tbuildInfo:      component.BuildInfo{},\n\t\t\tresourceConfig: nil,\n\t\t\twantFields: map[string]string{\n\t\t\t\t// A random UUID is injected for service.instance.id by default\n\t\t\t\t\"service.instance.id\": \"\", // Just check presence\n\t\t\t},\n\t\t},\n\t\t{\n\t\t\tname: \"validate `DisableResourceAttributes=true` shouldn't add resource fields\",\n\t\t\tbuildInfo: component.BuildInfo{\n\t\t\t\tCommand: \"mycommand\",\n\t\t\t\tVersion: \"1.0.0\",\n\t\t\t},\n\t\t\tresourceConfig: map[string]*string{},\n\t\t\twantFields:     map[string]string{},\n\t\t\tsetConfig: func(cfg *Config) {\n\t\t\t\tcfg.Logs.DisableZapResource = true\n\t\t\t},\n\t\t},\n\t}\n\n\tfor _, tt := range tests {\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tcore, observedLogs := observer.New(zapcore.DebugLevel)\n\n\t\t\tcfg := &Config{\n\t\t\t\tLogs: LogsConfig{\n\t\t\t\t\tLevel:    zapcore.InfoLevel,\n\t\t\t\t\tEncoding: \"json\",\n\t\t\t\t},\n\t\t\t\tResource: tt.resourceConfig,\n\t\t\t}\n\t\t\tif tt.setConfig != nil {\n\t\t\t\ttt.setConfig(cfg)\n\t\t\t}\n\n\t\t\tresource, err := createResource(t.Context(), telemetry.Settings{BuildInfo: tt.buildInfo}, cfg)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tset := telemetry.LoggerSettings{\n\t\t\t\tSettings: telemetry.Settings{BuildInfo: tt.buildInfo, Resource: &resource},\n\t\t\t\tBuildZapLogger: func(zap.Config, ...zap.Option) (*zap.Logger, error) {\n\t\t\t\t\t// Redirect logs to the observer core\n\t\t\t\t\treturn zap.New(core), nil\n\t\t\t\t},\n\t\t\t}\n\n\t\t\tlogger, loggerProvider, err := createLogger(t.Context(), set, cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\tdefer func() {\n\t\t\t\tassert.NoError(t, loggerProvider.Shutdown(t.Context()))\n\t\t\t}()\n\n\t\t\tlogger.Info(\"Test log message\")\n\t\t\trequire.Len(t, observedLogs.All(), 1)\n\n\t\t\tentry := observedLogs.All()[0]\n\t\t\t// treat empty map as \"no expected fields\"\n\t\t\tif len(tt.wantFields) == 0 {\n\t\t\t\tassert.Empty(t, entry.Context)\n\t\t\t\treturn\n\t\t\t}\n\n\t\t\tassert.Equal(t, \"resource\", entry.Context[0].Key)\n\t\t\tdict := entry.Context[0].Interface.(zapcore.ObjectMarshaler)\n\t\t\tenc := zapcore.NewMapObjectEncoder()\n\t\t\trequire.NoError(t, dict.MarshalLogObject(enc))\n\n\t\t\t// Verify all expected fields\n\t\t\tfor k, v := range tt.wantFields {\n\t\t\t\tif k == \"service.instance.id\" {\n\t\t\t\t\t// For service.instance.id just verify it exists since it's auto-generated\n\t\t\t\t\tassert.Contains(t, enc.Fields, k)\n\t\t\t\t} else {\n\t\t\t\t\tassert.Equal(t, v, enc.Fields[k])\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc TestCreateLoggerZapOptions(t *testing.T) {\n\tbuildInfo := component.BuildInfo{}\n\tfactory := NewFactory()\n\tcfg := &Config{\n\t\tLogs: LogsConfig{\n\t\t\tLevel:    zapcore.InfoLevel,\n\t\t\tEncoding: \"json\",\n\t\t},\n\t}\n\tresource, err := factory.CreateResource(\n\t\tcontext.Background(), telemetry.Settings{BuildInfo: buildInfo}, cfg,\n\t)\n\trequire.NoError(t, err)\n\n\tcore, observedLogs := observer.New(zapcore.DebugLevel)\n\tset := telemetry.LoggerSettings{\n\t\tSettings: telemetry.Settings{BuildInfo: buildInfo, Resource: &resource},\n\n\t\t// Test deprecated behavior: no BuildZapLogger, but ZapOptions provided.\n\t\tBuildZapLogger: nil,\n\t\tZapOptions: []zap.Option{\n\t\t\tzap.WrapCore(func(zapcore.Core) zapcore.Core { return core }),\n\t\t},\n\t}\n\n\tlogger, provider, err := factory.CreateLogger(context.Background(), set, cfg)\n\trequire.NoError(t, err)\n\trequire.NotNil(t, provider)\n\tdefer func() {\n\t\tassert.NoError(t, provider.Shutdown(context.Background()))\n\t}()\n\n\ttestMessage := \"Test deprecated zap options\"\n\tlogger.Info(testMessage)\n\n\trequire.Len(t, observedLogs.All(), 1)\n\tlogEntry := observedLogs.All()[0]\n\tassert.Equal(t, testMessage, logEntry.Message)\n\tassert.Equal(t, zapcore.InfoLevel, logEntry.Level)\n}\n\nfunc TestLogger_OTLP(t *testing.T) {\n\t// Create a backend to receive the logs and assert the content\n\treceivedLogs := 0\n\tlogger := newOTLPLogger(t, zapcore.InfoLevel, func(req plogotlp.ExportRequest) {\n\t\tlogs := req.Logs()\n\t\trl := logs.ResourceLogs().At(0)\n\n\t\tresourceAttrs := rl.Resource().Attributes().AsRaw()\n\t\tassert.Equal(t, service, resourceAttrs[\"service.name\"])\n\t\tassert.Equal(t, version, resourceAttrs[\"service.version\"])\n\t\tassert.Equal(t, testValue, resourceAttrs[testAttribute])\n\n\t\t// Check that the resource attributes are not duplicated in the log records\n\t\tsl := rl.ScopeLogs().At(0)\n\t\tlogRecord := sl.LogRecords().At(0)\n\t\tattrs := logRecord.Attributes().AsRaw()\n\t\tassert.NotContains(t, attrs, \"service.name\")\n\t\tassert.NotContains(t, attrs, \"service.version\")\n\t\tassert.NotContains(t, attrs, testAttribute)\n\n\t\treceivedLogs++\n\t})\n\n\tconst totalLogs = 10\n\tfor range totalLogs {\n\t\tlogger.Info(\"Test log message\")\n\t}\n\n\t// Ensure the correct number of logs were received\n\trequire.Equal(t, totalLogs, receivedLogs)\n}\n\nfunc newOTLPLogger(t *testing.T, level zapcore.Level, handler func(plogotlp.ExportRequest)) *zap.Logger {\n\tsrv := createLogsBackend(t, \"/v1/logs\", handler)\n\tt.Cleanup(srv.Close)\n\n\tprocessors := []config.LogRecordProcessor{{\n\t\tSimple: &config.SimpleLogRecordProcessor{\n\t\t\tExporter: config.LogRecordExporter{\n\t\t\t\tOTLP: &config.OTLP{\n\t\t\t\t\tEndpoint: ptr(srv.URL),\n\t\t\t\t\tProtocol: ptr(\"http/protobuf\"),\n\t\t\t\t\tInsecure: ptr(true),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}}\n\n\tcfg := &Config{\n\t\tLogs: LogsConfig{\n\t\t\tLevel:      level,\n\t\t\tEncoding:   \"json\",\n\t\t\tProcessors: processors,\n\t\t\t// OutputPaths is empty, so logs are only\n\t\t\t// written to the OTLP processor\n\t\t},\n\t\tResource: map[string]*string{\n\t\t\t\"service.name\":    ptr(service),\n\t\t\t\"service.version\": ptr(version),\n\t\t\ttestAttribute:     ptr(testValue),\n\t\t},\n\t}\n\n\tresource, err := createResource(t.Context(), telemetry.Settings{}, cfg)\n\trequire.NoError(t, err)\n\n\tlogger, shutdown, err := createLogger(t.Context(), telemetry.LoggerSettings{\n\t\tSettings:       telemetry.Settings{Resource: &resource},\n\t\tBuildZapLogger: zap.Config.Build,\n\t}, cfg)\n\trequire.NoError(t, err)\n\tt.Cleanup(func() {\n\t\tassert.NoError(t, shutdown.Shutdown(context.WithoutCancel(t.Context())))\n\t})\n\treturn logger\n}\n\nfunc createLogsBackend(t *testing.T, endpoint string, handler func(plogotlp.ExportRequest)) *httptest.Server {\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(endpoint, func(_ http.ResponseWriter, request *http.Request) {\n\t\tbody, err := io.ReadAll(request.Body)\n\t\tassert.NoError(t, err)\n\t\tdefer request.Body.Close()\n\n\t\t// Unmarshal the protobuf body into logs\n\t\treq := plogotlp.NewExportRequest()\n\t\terr = req.UnmarshalProto(body)\n\t\tassert.NoError(t, err)\n\n\t\thandler(req)\n\t})\n\treturn httptest.NewServer(mux)\n}\n\nfunc TestLogAttributeInjection(t *testing.T) {\n\tcore, consoleLogs := observer.New(zapcore.DebugLevel)\n\n\tvar otlpLogs []plogotlp.ExportRequest\n\tsrv := createLogsBackend(t, \"/v1/logs\", func(req plogotlp.ExportRequest) {\n\t\totlpLogs = append(otlpLogs, req)\n\t})\n\tt.Cleanup(srv.Close)\n\n\tcfg := &Config{\n\t\tResource: map[string]*string{\n\t\t\t\"service.instance.id\": nil,\n\t\t\t\"service.name\":        nil,\n\t\t\t\"service.version\":     nil,\n\t\t},\n\t\tLogs: LogsConfig{\n\t\t\tEncoding: \"json\",\n\t\t\tProcessors: []config.LogRecordProcessor{{\n\t\t\t\tSimple: &config.SimpleLogRecordProcessor{\n\t\t\t\t\tExporter: config.LogRecordExporter{\n\t\t\t\t\t\tOTLP: &config.OTLP{\n\t\t\t\t\t\t\t// Send OTLP logs to the mock backend\n\t\t\t\t\t\t\tEndpoint: ptr(srv.URL),\n\t\t\t\t\t\t\tProtocol: ptr(\"http/protobuf\"),\n\t\t\t\t\t\t\tInsecure: ptr(true),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}},\n\t\t},\n\t}\n\n\tresource, err := createResource(t.Context(), telemetry.Settings{}, cfg)\n\trequire.NoError(t, err)\n\n\tset := telemetry.LoggerSettings{\n\t\tSettings: telemetry.Settings{Resource: &resource},\n\t\tBuildZapLogger: func(zap.Config, ...zap.Option) (*zap.Logger, error) {\n\t\t\t// Redirect console logs to the observer core\n\t\t\treturn zap.New(core), nil\n\t\t},\n\t}\n\n\tsourceLogger, loggerProvider, err := createLogger(t.Context(), set, cfg)\n\trequire.NoError(t, err)\n\tdefer func() {\n\t\tassert.NoError(t, loggerProvider.Shutdown(t.Context()))\n\t}()\n\n\tts := componenttest.NewNopTelemetrySettings()\n\tts.Logger = sourceLogger\n\tts = componentattribute.TelemetrySettingsWithAttributes(ts, attribute.NewSet(\n\t\tattribute.String(\"injected1\", \"val\"),\n\t\tattribute.String(\"injected2\", \"val\"),\n\t))\n\tts.Logger = ts.Logger.With(zap.String(\"after\", \"val\"))\n\n\tfields, scope := checkScopes(t, ts.Logger, consoleLogs, &otlpLogs)\n\tassert.JSONEq(t, `{\"injected1\":\"val\",\"injected2\":\"val\",\"after\":\"val\",\"manual\":\"val\"}`, fields)\n\tassert.JSONEq(t, `{\"injected1\":\"val\",\"injected2\":\"val\"}`, scope)\n\n\tts = internalTelemetry.DropInjectedAttributes(ts, \"injected1\")\n\n\tfields, scope = checkScopes(t, ts.Logger, consoleLogs, &otlpLogs)\n\tassert.JSONEq(t, `{\"injected2\":\"val\",\"after\":\"val\",\"manual\":\"val\"}`, fields)\n\tassert.JSONEq(t, `{\"injected2\":\"val\"}`, scope)\n}\n\nfunc checkScopes(t *testing.T, logger *zap.Logger, consoleLogs *observer.ObservedLogs, otlpLogs *[]plogotlp.ExportRequest) (string, string) {\n\tlogger.Info(\"Test log message\", zap.String(\"manual\", \"val\"))\n\n\trequire.Len(t, consoleLogs.All(), 1)\n\tlog := consoleLogs.TakeAll()[0]\n\tenc := zapcore.NewJSONEncoder(zapcore.EncoderConfig{})\n\tfieldsBuf, err := enc.EncodeEntry(log.Entry, log.Context)\n\trequire.NoError(t, err)\n\tfieldsStr := strings.TrimSuffix(fieldsBuf.String(), \"\\n\")\n\n\trequire.Len(t, *otlpLogs, 1)\n\treq := (*otlpLogs)[0]\n\t*otlpLogs = nil\n\trls := req.Logs().ResourceLogs()\n\trequire.Equal(t, 1, rls.Len())\n\tsls := rls.At(0).ScopeLogs()\n\trequire.Equal(t, 1, sls.Len())\n\tattrs := sls.At(0).Scope().Attributes()\n\tscopeBuf, err := json.Marshal(attrs.AsRaw())\n\trequire.NoError(t, err)\n\tscopeStr := string(scopeBuf)\n\n\treturn fieldsStr, scopeStr\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/metrics.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelconftelemetry // import \"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\"\n\nimport (\n\t\"context\"\n\n\tconfig \"go.opentelemetry.io/contrib/otelconf/v0.3.0\"\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\tsdkresource \"go.opentelemetry.io/otel/sdk/resource\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n)\n\nfunc createMeterProvider(\n\tctx context.Context,\n\tset telemetry.MeterSettings,\n\tcomponentConfig component.Config,\n) (telemetry.MeterProvider, error) {\n\tcfg := componentConfig.(*Config)\n\tif cfg.Metrics.Level == configtelemetry.LevelNone {\n\t\tset.Logger.Info(\"Internal metrics telemetry disabled\")\n\t\treturn noopMeterProvider{MeterProvider: noopmetric.NewMeterProvider()}, nil\n\t} else if cfg.Metrics.Views == nil && set.DefaultViews != nil {\n\t\tcfg.Metrics.Views = set.DefaultViews(cfg.Metrics.Level)\n\t}\n\n\tattrs := pcommonAttrsToOTelAttrs(set.Resource)\n\tres := sdkresource.NewWithAttributes(\"\", attrs...)\n\tmpConfig := cfg.Metrics.MeterProvider\n\tsdk, err := newSDK(ctx, res, config.OpenTelemetryConfiguration{\n\t\tMeterProvider: &mpConfig,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn sdk.MeterProvider().(telemetry.MeterProvider), nil\n}\n\ntype noopMeterProvider struct {\n\tnoopmetric.MeterProvider\n}\n\nfunc (noopMeterProvider) Shutdown(context.Context) error {\n\treturn nil\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/metrics_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelconftelemetry\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\t\"time\"\n\n\tio_prometheus_client \"github.com/prometheus/client_model/go\"\n\t\"github.com/prometheus/common/expfmt\"\n\t\"github.com/prometheus/common/model\"\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tconfig \"go.opentelemetry.io/contrib/otelconf/v0.3.0\"\n\t\"go.opentelemetry.io/otel/attribute\"\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric\"\n\t\"go.opentelemetry.io/collector/pdata/pmetric/pmetricotlp\"\n\t\"go.opentelemetry.io/collector/service/internal/promtest\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n)\n\nconst (\n\tmetricPrefix = \"otelcol_\"\n\totelPrefix   = \"otel_sdk_\"\n\tgrpcPrefix   = \"grpc_\"\n\thttpPrefix   = \"http_\"\n\tcounterName  = \"test_counter\"\n)\n\nvar testInstanceID = \"test_instance_id\"\n\nfunc TestCreateMeterProvider(t *testing.T) {\n\ttype metricValue struct {\n\t\tvalue  float64\n\t\tlabels map[string]string\n\t}\n\n\tfor _, tt := range []struct {\n\t\tname            string\n\t\texpectedMetrics map[string]metricValue\n\t}{\n\t\t{\n\t\t\tname: \"UseOpenTelemetryForInternalMetrics\",\n\t\t\texpectedMetrics: map[string]metricValue{\n\t\t\t\tmetricPrefix + otelPrefix + counterName: {\n\t\t\t\t\tvalue:  13,\n\t\t\t\t\tlabels: map[string]string{},\n\t\t\t\t},\n\t\t\t\tmetricPrefix + grpcPrefix + counterName: {\n\t\t\t\t\tvalue: 11,\n\t\t\t\t\tlabels: map[string]string{\n\t\t\t\t\t\t\"rpc_system\": \"grpc\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\tmetricPrefix + httpPrefix + counterName: {\n\t\t\t\t\tvalue: 10,\n\t\t\t\t\tlabels: map[string]string{\n\t\t\t\t\t\t\"http_request_method\": \"GET\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"target_info\": {\n\t\t\t\t\tvalue: 0,\n\t\t\t\t\tlabels: map[string]string{\n\t\t\t\t\t\t\"service_name\":        \"otelcol\",\n\t\t\t\t\t\t\"service_version\":     \"latest\",\n\t\t\t\t\t\t\"service_instance_id\": testInstanceID,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t\"promhttp_metric_handler_errors_total\": {\n\t\t\t\t\tvalue: 0,\n\t\t\t\t\tlabels: map[string]string{\n\t\t\t\t\t\t\"cause\": \"encoding\",\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t} {\n\t\tprom := promtest.GetAvailableLocalAddressPrometheus(t)\n\t\tendpoint := fmt.Sprintf(\"http://%s:%d/metrics\", *prom.Host, *prom.Port)\n\n\t\tcfg := createDefaultConfig().(*Config)\n\t\tcfg.Metrics = MetricsConfig{\n\t\t\tLevel: configtelemetry.LevelDetailed,\n\t\t\tMeterProvider: config.MeterProvider{\n\t\t\t\tReaders: []config.MetricReader{{\n\t\t\t\t\tPull: &config.PullMetricReader{\n\t\t\t\t\t\tExporter: config.PullMetricExporter{Prometheus: prom},\n\t\t\t\t\t},\n\t\t\t\t}},\n\t\t\t},\n\t\t}\n\t\tcfg.Resource = map[string]*string{\n\t\t\t\"service.name\":        ptr(\"otelcol\"),\n\t\t\t\"service.version\":     ptr(\"latest\"),\n\t\t\t\"service.instance.id\": ptr(testInstanceID),\n\t\t}\n\n\t\tt.Run(tt.name, func(t *testing.T) {\n\t\t\tresource, err := createResource(t.Context(), telemetry.Settings{}, cfg)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tmp, err := createMeterProvider(t.Context(), telemetry.MeterSettings{\n\t\t\t\tSettings: telemetry.Settings{Resource: &resource},\n\t\t\t}, cfg)\n\t\t\trequire.NoError(t, err)\n\t\t\tdefer func() {\n\t\t\t\tassert.NoError(t, mp.Shutdown(t.Context()))\n\t\t\t}()\n\n\t\t\tcreateTestMetrics(t, mp)\n\n\t\t\tmetrics := getMetricsFromPrometheus(t, endpoint)\n\t\t\trequire.Len(t, metrics, len(tt.expectedMetrics))\n\n\t\t\tfor metricName, metricValue := range tt.expectedMetrics {\n\t\t\t\tmf, present := metrics[metricName]\n\t\t\t\trequire.True(t, present, \"expected metric %q was not present\", metricName)\n\t\t\t\tif metricName == \"promhttp_metric_handler_errors_total\" {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t\trequire.Len(t, mf.Metric, 1, \"only one measure should exist for metric %q\", metricName)\n\n\t\t\t\tlabels := make(map[string]string)\n\t\t\t\tfor _, pair := range mf.Metric[0].Label {\n\t\t\t\t\tlabels[pair.GetName()] = pair.GetValue()\n\t\t\t\t}\n\n\t\t\t\trequire.Equal(t, metricValue.labels, labels, \"labels for metric %q was different than expected\", metricName)\n\t\t\t\trequire.InDelta(t, metricValue.value, mf.Metric[0].Counter.GetValue(), 0.01, \"value for metric %q was different than expected\", metricName)\n\t\t\t}\n\t\t})\n\t}\n}\n\nfunc createTestMetrics(t *testing.T, mp metric.MeterProvider) {\n\t// Creates a OTel Go counter\n\tcounter, err := mp.Meter(\"collector_test\").Int64Counter(metricPrefix+otelPrefix+counterName, metric.WithUnit(\"ms\"))\n\trequire.NoError(t, err)\n\tcounter.Add(context.Background(), 13)\n\n\tgrpcExampleCounter, err := mp.Meter(\"go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc\").Int64Counter(metricPrefix + grpcPrefix + counterName)\n\trequire.NoError(t, err)\n\tgrpcExampleCounter.Add(context.Background(), 11, metric.WithAttributeSet(attribute.NewSet(\n\t\tattribute.String(\"rpc.system\", \"grpc\"),\n\t)))\n\n\thttpExampleCounter, err := mp.Meter(\"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp\").Int64Counter(metricPrefix + httpPrefix + counterName)\n\trequire.NoError(t, err)\n\thttpExampleCounter.Add(context.Background(), 10, metric.WithAttributeSet(attribute.NewSet(\n\t\tattribute.String(\"http.request.method\", \"GET\"),\n\t)))\n}\n\nfunc getMetricsFromPrometheus(t *testing.T, endpoint string) map[string]*io_prometheus_client.MetricFamily {\n\tclient := &http.Client{\n\t\tTimeout: 10 * time.Second,\n\t}\n\n\treq, err := http.NewRequest(http.MethodGet, endpoint, http.NoBody)\n\trequire.NoError(t, err)\n\n\tvar rr *http.Response\n\tmaxRetries := 5\n\tfor i := range maxRetries {\n\t\trr, err = client.Do(req)\n\t\tif err == nil && rr.StatusCode == http.StatusOK {\n\t\t\tbreak\n\t\t}\n\n\t\t// skip sleep on last retry\n\t\tif i < maxRetries-1 {\n\t\t\ttime.Sleep(2 * time.Second) // Wait before retrying\n\t\t}\n\t}\n\trequire.NoError(t, err, \"failed to get metrics from Prometheus after %d attempts\", maxRetries)\n\trequire.Equal(t, http.StatusOK, rr.StatusCode, \"unexpected status code after %d attempts\", maxRetries)\n\tdefer rr.Body.Close()\n\n\tparser := expfmt.NewTextParser(model.UTF8Validation)\n\tparsed, err := parser.TextToMetricFamilies(rr.Body)\n\trequire.NoError(t, err)\n\n\treturn parsed\n}\n\nfunc TestCreateMeterProvider_Invalid(t *testing.T) {\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.Logs.Level = zapcore.FatalLevel\n\tcfg.Traces.Level = configtelemetry.LevelNone\n\tcfg.Metrics.Readers = []config.MetricReader{{\n\t\t// Invalid -- no OTLP protocol defined\n\t\tPeriodic: &config.PeriodicMetricReader{Exporter: config.PushMetricExporter{OTLP: &config.OTLPMetric{}}},\n\t}}\n\tresource, err := createResource(t.Context(), telemetry.Settings{}, cfg)\n\trequire.NoError(t, err)\n\n\t_, err = createMeterProvider(t.Context(), telemetry.MeterSettings{\n\t\tSettings: telemetry.Settings{Resource: &resource},\n\t}, cfg)\n\trequire.EqualError(t, err, \"no valid metric exporter\")\n}\n\nfunc TestCreateMeterProvider_Disabled(t *testing.T) {\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.Metrics.Readers = []config.MetricReader{{\n\t\t// Invalid -- no OTLP protocol defined\n\t\tPeriodic: &config.PeriodicMetricReader{Exporter: config.PushMetricExporter{OTLP: &config.OTLPMetric{}}},\n\t}}\n\n\tcore, observedLogs := observer.New(zapcore.DebugLevel)\n\n\tfactory := NewFactory()\n\tresource, err := factory.CreateResource(context.Background(), telemetry.Settings{}, cfg)\n\trequire.NoError(t, err)\n\n\tsettings := telemetry.MeterSettings{\n\t\tSettings: telemetry.Settings{Resource: &resource},\n\t}\n\tsettings.Logger = zap.New(core)\n\n\t_, err = factory.CreateMeterProvider(context.Background(), settings, cfg)\n\trequire.EqualError(t, err, \"no valid metric exporter\")\n\tassert.Zero(t, observedLogs.Len())\n\n\t// Setting Metrics.Level to LevelNone disables metrics,\n\t// so the invalid configuration should not cause an error.\n\tcfg.Metrics.Level = configtelemetry.LevelNone\n\tresource2, err := createResource(t.Context(), telemetry.Settings{}, cfg)\n\trequire.NoError(t, err)\n\tsettings.Resource = &resource2\n\n\tmp, err := createMeterProvider(t.Context(), settings, cfg)\n\trequire.NoError(t, err)\n\tassert.NoError(t, mp.Shutdown(t.Context()))\n\n\trequire.Equal(t, 1, observedLogs.Len())\n\tassert.Equal(t, \"Internal metrics telemetry disabled\", observedLogs.All()[0].Message)\n}\n\n// Test that the MeterProvider implements the 'Enabled' functionality.\n// See https://pkg.go.dev/go.opentelemetry.io/otel/sdk/metric/internal/x#readme-instrument-enabled.\nfunc TestInstrumentEnabled(t *testing.T) {\n\tprom := promtest.GetAvailableLocalAddressPrometheus(t)\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.Metrics.Readers = []config.MetricReader{{\n\t\tPull: &config.PullMetricReader{Exporter: config.PullMetricExporter{Prometheus: prom}},\n\t}}\n\n\tresource, err := createResource(t.Context(), telemetry.Settings{}, cfg)\n\trequire.NoError(t, err)\n\n\tmeterProvider, err := createMeterProvider(t.Context(), telemetry.MeterSettings{\n\t\tSettings: telemetry.Settings{Resource: &resource},\n\t}, cfg)\n\trequire.NoError(t, err)\n\tdefer func() {\n\t\tassert.NoError(t, meterProvider.Shutdown(t.Context()))\n\t}()\n\n\tmeter := meterProvider.Meter(\"go.opentelemetry.io/collector/service/telemetry\")\n\n\ttype enabledInstrument interface{ Enabled(context.Context) bool }\n\n\tintCnt, err := meter.Int64Counter(\"int64.counter\")\n\trequire.NoError(t, err)\n\tassert.Implements(t, new(enabledInstrument), intCnt)\n\n\tintUpDownCnt, err := meter.Int64UpDownCounter(\"int64.updowncounter\")\n\trequire.NoError(t, err)\n\tassert.Implements(t, new(enabledInstrument), intUpDownCnt)\n\n\tintHist, err := meter.Int64Histogram(\"int64.updowncounter\")\n\trequire.NoError(t, err)\n\tassert.Implements(t, new(enabledInstrument), intHist)\n\n\tintGauge, err := meter.Int64Gauge(\"int64.updowncounter\")\n\trequire.NoError(t, err)\n\tassert.Implements(t, new(enabledInstrument), intGauge)\n\n\tfloatCnt, err := meter.Float64Counter(\"int64.updowncounter\")\n\trequire.NoError(t, err)\n\tassert.Implements(t, new(enabledInstrument), floatCnt)\n\n\tfloatUpDownCnt, err := meter.Float64UpDownCounter(\"int64.updowncounter\")\n\trequire.NoError(t, err)\n\tassert.Implements(t, new(enabledInstrument), floatUpDownCnt)\n\n\tfloatHist, err := meter.Float64Histogram(\"int64.updowncounter\")\n\trequire.NoError(t, err)\n\tassert.Implements(t, new(enabledInstrument), floatHist)\n\n\tfloatGauge, err := meter.Float64Gauge(\"int64.updowncounter\")\n\trequire.NoError(t, err)\n\tassert.Implements(t, new(enabledInstrument), floatGauge)\n}\n\nfunc TestTelemetryMetrics_DefaultViews(t *testing.T) {\n\ttype testcase struct {\n\t\tconfiguredViews    []config.View\n\t\texpectedMeterNames []string\n\t}\n\n\tdefaultViews := func(level configtelemetry.Level) []config.View {\n\t\tassert.Equal(t, configtelemetry.LevelDetailed, level)\n\t\treturn []config.View{{\n\t\t\tSelector: &config.ViewSelector{\n\t\t\t\tMeterName: ptr(\"a\"),\n\t\t\t},\n\t\t\tStream: &config.ViewStream{\n\t\t\t\tAggregation: &config.ViewStreamAggregation{\n\t\t\t\t\tDrop: config.ViewStreamAggregationDrop{},\n\t\t\t\t},\n\t\t\t},\n\t\t}}\n\t}\n\n\tfor name, tc := range map[string]testcase{\n\t\t\"no_configured_views\": {\n\t\t\texpectedMeterNames: []string{\"b\", \"c\"},\n\t\t},\n\t\t\"configured_views\": {\n\t\t\tconfiguredViews: []config.View{{\n\t\t\t\tSelector: &config.ViewSelector{\n\t\t\t\t\tMeterName: ptr(\"b\"),\n\t\t\t\t},\n\t\t\t\tStream: &config.ViewStream{\n\t\t\t\t\tAggregation: &config.ViewStreamAggregation{\n\t\t\t\t\t\tDrop: config.ViewStreamAggregationDrop{},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}},\n\t\t\texpectedMeterNames: []string{\"a\", \"c\"},\n\t\t},\n\t} {\n\t\tt.Run(name, func(t *testing.T) {\n\t\t\tvar metrics pmetric.Metrics\n\t\t\tsrv := httptest.NewServer(http.HandlerFunc(func(_ http.ResponseWriter, req *http.Request) {\n\t\t\t\tbody, err := io.ReadAll(req.Body)\n\t\t\t\tassert.NoError(t, err)\n\n\t\t\t\texportRequest := pmetricotlp.NewExportRequest()\n\t\t\t\tassert.NoError(t, exportRequest.UnmarshalProto(body))\n\t\t\t\tmetrics = exportRequest.Metrics()\n\t\t\t}))\n\t\t\tdefer srv.Close()\n\n\t\t\tcfg := createDefaultConfig().(*Config)\n\t\t\tcfg.Metrics.Level = configtelemetry.LevelDetailed\n\t\t\tcfg.Metrics.Views = tc.configuredViews\n\t\t\tcfg.Metrics.Readers = []config.MetricReader{{\n\t\t\t\tPeriodic: &config.PeriodicMetricReader{\n\t\t\t\t\tExporter: config.PushMetricExporter{\n\t\t\t\t\t\tOTLP: &config.OTLPMetric{\n\t\t\t\t\t\t\tEndpoint: ptr(srv.URL),\n\t\t\t\t\t\t\tProtocol: ptr(\"http/protobuf\"),\n\t\t\t\t\t\t\tInsecure: ptr(true),\n\t\t\t\t\t\t},\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}}\n\n\t\t\tfactory := NewFactory()\n\t\t\tsettings := telemetry.MeterSettings{DefaultViews: defaultViews}\n\t\t\tprovider, err := factory.CreateMeterProvider(t.Context(), settings, cfg)\n\t\t\trequire.NoError(t, err)\n\n\t\t\tfor _, meterName := range []string{\"a\", \"b\", \"c\"} {\n\t\t\t\tcounter, _ := provider.Meter(meterName).Int64Counter(meterName + \".counter\")\n\t\t\t\tcounter.Add(t.Context(), 1)\n\t\t\t}\n\t\t\trequire.NoError(t, provider.Shutdown(t.Context())) // should flush metrics\n\n\t\t\tvar scopes []string\n\t\t\tfor _, rm := range metrics.ResourceMetrics().All() {\n\t\t\t\tfor _, sm := range rm.ScopeMetrics().All() {\n\t\t\t\t\tscopes = append(scopes, sm.Scope().Name())\n\t\t\t\t}\n\t\t\t}\n\t\t\tassert.ElementsMatch(t, tc.expectedMeterNames, scopes)\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/package_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelconftelemetry\n\nimport (\n\t\"testing\"\n\n\t\"go.uber.org/goleak\"\n)\n\nfunc TestMain(m *testing.M) {\n\tgoleak.VerifyTestMain(m)\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/resource.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelconftelemetry // import \"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\"\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"go.opentelemetry.io/otel/attribute\"\n\tsdkresource \"go.opentelemetry.io/otel/sdk/resource\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/service/internal/resource\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n)\n\nfunc createResource(\n\t_ context.Context,\n\tset telemetry.Settings,\n\tcomponentConfig component.Config,\n) (pcommon.Resource, error) {\n\tres := newResource(set, componentConfig.(*Config))\n\tpcommonRes := pcommon.NewResource()\n\tfor _, keyValue := range res.Attributes() {\n\t\tkey := string(keyValue.Key)\n\t\tpcommonRes.Attributes().PutStr(key, mustAttributeValueString(key, keyValue.Value))\n\t}\n\treturn pcommonRes, nil\n}\n\nfunc newResource(set telemetry.Settings, cfg *Config) *sdkresource.Resource {\n\treturn resource.New(set.BuildInfo, cfg.Resource)\n}\n\nfunc mustAttributeValueString(k string, v attribute.Value) string {\n\tif v.Type() != attribute.STRING {\n\t\t// We only support string-type resource attributes in the configuration.\n\t\tpanic(fmt.Errorf(\"attribute %q: expected string, got %s\", k, v.Type()))\n\t}\n\treturn v.AsString()\n}\n\n// pcommonAttrsToOTelAttrs gets the Resource attributes to OpenTelemetry attribute.KeyValue slice.\nfunc pcommonAttrsToOTelAttrs(resource *pcommon.Resource) []attribute.KeyValue {\n\tvar result []attribute.KeyValue\n\tif resource != nil {\n\t\tattrs := resource.Attributes()\n\t\tattrs.Range(func(k string, v pcommon.Value) bool {\n\t\t\tresult = append(result, attribute.String(k, v.AsString()))\n\t\t\treturn true\n\t\t})\n\t}\n\treturn result\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/resource_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelconftelemetry // import \"go.opentelemetry.io/collector/service/telemetry\"\n\nimport (\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n)\n\nfunc TestCreateResource(t *testing.T) {\n\tt.Run(\"default\", func(t *testing.T) {\n\t\tcfg := createDefaultConfig().(*Config)\n\t\tset := telemetry.Settings{BuildInfo: component.BuildInfo{Command: \"otelcol\", Version: \"latest\"}}\n\t\tres, err := createResource(t.Context(), set, cfg)\n\t\trequire.NoError(t, err)\n\n\t\traw := res.Attributes().AsRaw()\n\t\tassert.Contains(t, raw, \"service.instance.id\")\n\t\tdelete(raw, \"service.instance.id\") // remove since it's random\n\t\tassert.Equal(t, map[string]any{\n\t\t\t\"service.name\":    \"otelcol\",\n\t\t\t\"service.version\": \"latest\",\n\t\t}, raw)\n\t})\n\tt.Run(\"with resource attributes\", func(t *testing.T) {\n\t\tcfg := createDefaultConfig().(*Config)\n\t\tcfg.Resource = map[string]*string{\n\t\t\t\"extra.attr\":          ptr(\"value\"),\n\t\t\t\"service.name\":        ptr(\"custom-service\"),\n\t\t\t\"service.version\":     ptr(\"0.1.0\"),\n\t\t\t\"service.instance.id\": nil, // removes the attribute\n\t\t}\n\t\tset := telemetry.Settings{BuildInfo: component.BuildInfo{Command: \"otelcol\", Version: \"latest\"}}\n\t\tres, err := createResource(t.Context(), set, cfg)\n\t\trequire.NoError(t, err)\n\n\t\traw := res.Attributes().AsRaw()\n\t\tassert.Equal(t, map[string]any{\n\t\t\t\"extra.attr\":      \"value\",\n\t\t\t\"service.name\":    \"custom-service\",\n\t\t\t\"service.version\": \"0.1.0\",\n\t\t}, raw)\n\t})\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/sdk.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelconftelemetry // import \"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\"\n\nimport (\n\t\"context\"\n\n\tconfig \"go.opentelemetry.io/contrib/otelconf/v0.3.0\"\n\tsdkresource \"go.opentelemetry.io/otel/sdk/resource\"\n\tsemconv \"go.opentelemetry.io/otel/semconv/v1.38.0\"\n)\n\nfunc newSDK(ctx context.Context, res *sdkresource.Resource, conf config.OpenTelemetryConfiguration) (config.SDK, error) {\n\tresourceAttrs := make([]config.AttributeNameValue, 0, res.Len())\n\tfor _, r := range res.Attributes() {\n\t\tkey := string(r.Key)\n\t\tresourceAttrs = append(resourceAttrs, config.AttributeNameValue{\n\t\t\tName:  key,\n\t\t\tValue: mustAttributeValueString(key, r.Value),\n\t\t})\n\t}\n\tconf.Resource = &config.Resource{\n\t\tSchemaUrl:  ptr(semconv.SchemaURL),\n\t\tAttributes: resourceAttrs,\n\t}\n\treturn config.NewSDK(config.WithContext(ctx), config.WithOpenTelemetryConfiguration(conf))\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/testdata/config_deprecated_address.yaml",
    "content": "logs:\n  level: \"info\"\nmetrics:\n  level: \"basic\"\n  address: \"localhost:6666\"\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/testdata/config_deprecated_address_and_readers.yaml",
    "content": "logs:\n  level: \"info\"\nmetrics:\n  level: \"basic\"\n  address: \"192.168.0.1:6666\"\n  readers:\n    - pull:\n        exporter:\n          prometheus:\n            host: \"localhost\"\n            port: 9999\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/testdata/config_empty.yaml",
    "content": ""
  },
  {
    "path": "service/telemetry/otelconftelemetry/testdata/config_empty_readers.yaml",
    "content": "metrics:\n  level: \"basic\"\n  readers: []\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/testdata/config_invalid_deprecated_address.yaml",
    "content": "logs:\n  level: \"info\"\nmetrics:\n  level: \"basic\"\n  address: \"1212:212121:2121\"\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/testdata/config_invalid_metrics_empty_readers.yaml",
    "content": "metrics:\n  level: \"basic\"\n  readers: []\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/testdata/config_invalid_metrics_views_feature_gate.yaml",
    "content": "metrics:\n  level: detailed\n  views:\n    - selector: {}\n      stream: {}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/testdata/config_invalid_metrics_views_level.yaml",
    "content": "metrics:\n  level: basic\n  views:\n    - selector: {}\n      stream: {}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/testdata/config_invalid_unknown_field.yaml",
    "content": "metrics:\n  unknown: basic\n  views:\n    - selector: {}\n      stream: {}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/testdata/config_logs.yaml",
    "content": "logs:\n  level: info\n  development: true\n  disable_caller: true\n  disable_stacktrace: true\n  encoding: console\n  output_paths: [stderr]\n  error_output_paths: [stderr]\n  initial_fields:\n    fieldKey: fieldValue\n  sampling:\n    enabled: false\n    tick: 1s\n    initial: 234\n    thereafter: 567\n  processors:\n    - batch:\n        exporter:\n          console: {}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/testdata/config_metrics_empty_readers.yaml",
    "content": "metrics:\n  level: \"none\"\n  readers: []\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/tracer.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelconftelemetry // import \"go.opentelemetry.io/collector/service/telemetry/otelconftelemetry\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"fmt\"\n\n\tconfig \"go.opentelemetry.io/contrib/otelconf/v0.3.0\"\n\t\"go.opentelemetry.io/contrib/propagators/b3\"\n\t\"go.opentelemetry.io/otel\"\n\t\"go.opentelemetry.io/otel/propagation\"\n\tsdkresource \"go.opentelemetry.io/otel/sdk/resource\"\n\t\"go.opentelemetry.io/otel/trace\"\n\t\"go.opentelemetry.io/otel/trace/embedded\"\n\t\"go.opentelemetry.io/otel/trace/noop\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n)\n\nconst (\n\t// supported trace propagators\n\ttraceContextPropagator = \"tracecontext\"\n\tb3Propagator           = \"b3\"\n)\n\nfunc createTracerProvider(\n\tctx context.Context,\n\tset telemetry.TracerSettings,\n\tcomponentConfig component.Config,\n) (telemetry.TracerProvider, error) {\n\tcfg := componentConfig.(*Config)\n\tif cfg.Traces.Level == configtelemetry.LevelNone {\n\t\tset.Logger.Info(\"Internal trace telemetry disabled\")\n\t\treturn &noopNoContextTracerProvider{}, nil\n\t}\n\n\tpropagator, err := textMapPropagatorFromConfig(cfg.Traces.Propagators)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error creating propagator: %w\", err)\n\t}\n\totel.SetTextMapPropagator(propagator)\n\n\tattrs := pcommonAttrsToOTelAttrs(set.Resource)\n\tres := sdkresource.NewWithAttributes(\"\", attrs...)\n\tsdk, err := newSDK(ctx, res, config.OpenTelemetryConfiguration{\n\t\tTracerProvider: &cfg.Traces.TracerProvider,\n\t})\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\treturn sdk.TracerProvider().(telemetry.TracerProvider), nil\n}\n\nvar errUnsupportedPropagator = errors.New(\"unsupported trace propagator\")\n\ntype noopNoContextTracer struct {\n\tembedded.Tracer\n}\n\nvar noopSpan = noop.Span{}\n\nfunc (n *noopNoContextTracer) Start(ctx context.Context, _ string, _ ...trace.SpanStartOption) (context.Context, trace.Span) {\n\treturn ctx, noopSpan\n}\n\ntype noopNoContextTracerProvider struct {\n\tembedded.TracerProvider\n}\n\nfunc (n *noopNoContextTracerProvider) Shutdown(_ context.Context) error {\n\treturn nil\n}\n\nfunc (n *noopNoContextTracerProvider) Tracer(_ string, _ ...trace.TracerOption) trace.Tracer {\n\treturn &noopNoContextTracer{}\n}\n\nfunc textMapPropagatorFromConfig(props []string) (propagation.TextMapPropagator, error) {\n\tvar textMapPropagators []propagation.TextMapPropagator\n\tfor _, prop := range props {\n\t\tswitch prop {\n\t\tcase traceContextPropagator:\n\t\t\ttextMapPropagators = append(textMapPropagators, propagation.TraceContext{})\n\t\tcase b3Propagator:\n\t\t\ttextMapPropagators = append(textMapPropagators, b3.New())\n\t\tdefault:\n\t\t\treturn nil, errUnsupportedPropagator\n\t\t}\n\t}\n\treturn propagation.NewCompositeTextMapPropagator(textMapPropagators...), nil\n}\n"
  },
  {
    "path": "service/telemetry/otelconftelemetry/tracer_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage otelconftelemetry // import \"go.opentelemetry.io/collector/service/telemetry\"\n\nimport (\n\t\"context\"\n\t\"io\"\n\t\"net/http\"\n\t\"net/http/httptest\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tconfig \"go.opentelemetry.io/contrib/otelconf/v0.3.0\"\n\t\"go.opentelemetry.io/otel\"\n\t\"go.opentelemetry.io/otel/propagation\"\n\t\"go.uber.org/zap\"\n\t\"go.uber.org/zap/zapcore\"\n\t\"go.uber.org/zap/zaptest/observer\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace\"\n\t\"go.opentelemetry.io/collector/pdata/ptrace/ptraceotlp\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n)\n\nfunc TestCreateTracerProvider(t *testing.T) {\n\tvar received []ptrace.Traces\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/v1/traces\", func(_ http.ResponseWriter, req *http.Request) {\n\t\tbody, err := io.ReadAll(req.Body)\n\t\tassert.NoError(t, err)\n\n\t\texportRequest := ptraceotlp.NewExportRequest()\n\t\tassert.NoError(t, exportRequest.UnmarshalProto(body))\n\t\treceived = append(received, exportRequest.Traces())\n\t})\n\tsrv := httptest.NewServer(mux)\n\tdefer srv.Close()\n\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.Traces.Propagators = []string{\"b3\", \"tracecontext\"}\n\tcfg.Traces.Processors = []config.SpanProcessor{newOTLPSimpleSpanProcessor(srv)}\n\n\tresource, err := createResource(t.Context(), telemetry.Settings{\n\t\tBuildInfo: component.BuildInfo{Command: \"otelcol\", Version: \"latest\"},\n\t}, cfg)\n\trequire.NoError(t, err)\n\n\tprovider, err := createTracerProvider(t.Context(), telemetry.TracerSettings{\n\t\tSettings: telemetry.Settings{\n\t\t\tBuildInfo: component.BuildInfo{Command: \"otelcol\", Version: \"latest\"},\n\t\t\tResource:  &resource,\n\t\t},\n\t}, cfg)\n\trequire.NoError(t, err)\n\tdefer func() {\n\t\tassert.NoError(t, provider.Shutdown(t.Context()))\n\t}()\n\n\ttracer := provider.Tracer(\"test_tracer\")\n\t_, span := tracer.Start(context.Background(), \"test_span\")\n\tspan.End()\n\n\trequire.Len(t, received, 1)\n\ttraces := received[0]\n\trequire.Equal(t, 1, traces.SpanCount())\n\tassert.Equal(t, \"test_span\", traces.ResourceSpans().At(0).ScopeSpans().At(0).Spans().At(0).Name())\n}\n\nfunc TestCreateTracerProvider_Invalid(t *testing.T) {\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.Logs.Level = zapcore.FatalLevel\n\tcfg.Metrics.Level = configtelemetry.LevelNone\n\tcfg.Traces.Processors = []config.SpanProcessor{{\n\t\tSimple: &config.SimpleSpanProcessor{\n\t\t\tExporter: config.SpanExporter{\n\t\t\t\tOTLP: &config.OTLP{ /* missing endpoint, etc. */ },\n\t\t\t},\n\t\t},\n\t}}\n\tresource, err := createResource(t.Context(), telemetry.Settings{}, cfg)\n\trequire.NoError(t, err)\n\n\t_, err = createTracerProvider(t.Context(), telemetry.TracerSettings{\n\t\tSettings: telemetry.Settings{Resource: &resource},\n\t}, cfg)\n\trequire.EqualError(t, err, \"no valid span exporter\")\n}\n\nfunc TestCreateTracerProvider_Propagators(t *testing.T) {\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/v1/traces\", func(http.ResponseWriter, *http.Request) {})\n\tsrv := httptest.NewServer(mux)\n\tdefer srv.Close()\n\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.Traces.Propagators = []string{\"b3\", \"tracecontext\"}\n\tcfg.Traces.Processors = []config.SpanProcessor{newOTLPSimpleSpanProcessor(srv)}\n\n\tresource, err := createResource(t.Context(), telemetry.Settings{\n\t\tBuildInfo: component.BuildInfo{Command: \"otelcol\", Version: \"latest\"},\n\t}, cfg)\n\trequire.NoError(t, err)\n\n\tprovider, err := createTracerProvider(t.Context(), telemetry.TracerSettings{\n\t\tSettings: telemetry.Settings{\n\t\t\tBuildInfo: component.BuildInfo{Command: \"otelcol\", Version: \"latest\"},\n\t\t\tResource:  &resource,\n\t\t},\n\t}, cfg)\n\trequire.NoError(t, err)\n\tdefer func() {\n\t\tassert.NoError(t, provider.Shutdown(t.Context()))\n\t}()\n\n\tpropagator := otel.GetTextMapPropagator()\n\trequire.NotNil(t, propagator)\n\n\ttracer := provider.Tracer(\"test_tracer\")\n\tctx, span := tracer.Start(context.Background(), \"test_span\")\n\tmapCarrier := make(propagation.MapCarrier)\n\tpropagator.Inject(ctx, mapCarrier)\n\tspan.End()\n\n\tassert.Contains(t, mapCarrier, \"b3\")\n\tassert.Contains(t, mapCarrier, \"traceparent\")\n}\n\nfunc TestCreateTracerProvider_InvalidPropagator(t *testing.T) {\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.Traces.Propagators = []string{\"invalid\"}\n\n\tresource, err := createResource(t.Context(), telemetry.Settings{}, cfg)\n\trequire.NoError(t, err)\n\n\t_, err = createTracerProvider(t.Context(), telemetry.TracerSettings{\n\t\tSettings: telemetry.Settings{Resource: &resource},\n\t}, cfg)\n\tassert.EqualError(t, err, \"error creating propagator: unsupported trace propagator\")\n}\n\nfunc TestCreateTracerProvider_Disabled(t *testing.T) {\n\tvar received int\n\tmux := http.NewServeMux()\n\tmux.HandleFunc(\"/v1/traces\", func(http.ResponseWriter, *http.Request) {\n\t\treceived++\n\t})\n\tsrv := httptest.NewServer(mux)\n\tdefer srv.Close()\n\n\tcfg := createDefaultConfig().(*Config)\n\tcfg.Traces.Level = configtelemetry.LevelNone\n\tcfg.Traces.Processors = []config.SpanProcessor{newOTLPSimpleSpanProcessor(srv)}\n\n\tcore, observedLogs := observer.New(zapcore.DebugLevel)\n\n\tresource, err := createResource(t.Context(), telemetry.Settings{\n\t\tBuildInfo: component.BuildInfo{Command: \"otelcol\", Version: \"latest\"},\n\t}, cfg)\n\trequire.NoError(t, err)\n\n\tsettings := telemetry.TracerSettings{\n\t\tSettings: telemetry.Settings{\n\t\t\tBuildInfo: component.BuildInfo{Command: \"otelcol\", Version: \"latest\"},\n\t\t\tResource:  &resource,\n\t\t},\n\t\tLogger: zap.New(core),\n\t}\n\n\tprovider, err := createTracerProvider(t.Context(), settings, cfg)\n\trequire.NoError(t, err)\n\tdefer func() {\n\t\tassert.NoError(t, provider.Shutdown(t.Context()))\n\t}()\n\n\trequire.Equal(t, 1, observedLogs.Len())\n\tassert.Equal(t, \"Internal trace telemetry disabled\", observedLogs.All()[0].Message)\n\n\ttracer := provider.Tracer(\"test_tracer\")\n\t_, span := tracer.Start(context.Background(), \"test_span\")\n\tspan.End()\n\tassert.Equal(t, 0, received)\n}\n\nfunc newOTLPSimpleSpanProcessor(srv *httptest.Server) config.SpanProcessor {\n\treturn config.SpanProcessor{\n\t\tSimple: &config.SimpleSpanProcessor{\n\t\t\tExporter: config.SpanExporter{\n\t\t\t\tOTLP: &config.OTLP{\n\t\t\t\t\tEndpoint: ptr(srv.URL),\n\t\t\t\t\tProtocol: ptr(\"http/protobuf\"),\n\t\t\t\t\tInsecure: ptr(true),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t}\n}\n"
  },
  {
    "path": "service/telemetry/telemetry.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage telemetry // import \"go.opentelemetry.io/collector/service/telemetry\"\n\nimport (\n\t\"context\"\n\n\totelconf \"go.opentelemetry.io/contrib/otelconf/v0.3.0\"\n\t\"go.opentelemetry.io/otel/metric\"\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\t\"go.opentelemetry.io/otel/trace\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/config/configtelemetry\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\n// LoggerSettings holds settings for building logger providers.\ntype LoggerSettings struct {\n\tSettings\n\n\t// ZapOptions contains options for creating the zap logger.\n\t//\n\t// Deprecated [v0.142.0]: use BuildZapLogger instead.\n\t// This field will be removed in the future, and options\n\t// must be injected through BuildZapLogger.\n\tZapOptions []zap.Option\n\n\t// BuildZapLogger holds a function for building a *zap.Logger\n\t// from a zap.Config and options.\n\t//\n\t// If BuildZapLogger is nil, zap.Config.Build should be used.\n\t// NOTE: in the future this field will be required.\n\tBuildZapLogger func(zap.Config, ...zap.Option) (*zap.Logger, error)\n}\n\n// MeterSettings holds settings for building meter providers.\ntype MeterSettings struct {\n\tSettings\n\n\t// Logger is a zap.Logger that may be used for logging details\n\t// of the MeterProvider's construction, and by the MeterProvider\n\t// for logging its internal operations.\n\tLogger *zap.Logger\n\n\t// DefaultViews holds a function that returns default metric\n\t// views for the given internal telemetry metrics level.\n\t//\n\t// The meter provider is expected to use this if no user-provided\n\t// view configuration is supplied.\n\t//\n\t// TODO we should not use otelconf.View directly here, change\n\t// to something independent of otelconf.\n\tDefaultViews func(configtelemetry.Level) []otelconf.View\n}\n\n// TracerSettings holds settings for building tracer providers.\ntype TracerSettings struct {\n\tSettings\n\n\t// Logger is a zap.Logger that may be used for logging details\n\t// of the TracerProvider's construction, and by the TracerProvider\n\t// for logging its internal operations.\n\tLogger *zap.Logger\n}\n\n// Settings holds common settings for building telemetry providers.\ntype Settings struct {\n\t// BuildInfo contains build information about the collector.\n\tBuildInfo component.BuildInfo\n\n\t// Resource is the telemetry resource that should be used by all telemetry providers.\n\tResource *pcommon.Resource\n}\n\n// Factory is a factory interface for internal telemetry.\n//\n// This interface cannot be directly implemented. Implementations must\n// use the NewFactory to implement it.\n//\n// NOTE This API is experimental and will change soon - use at your own risk.\n// See https://github.com/open-telemetry/opentelemetry-collector/issues/4970\ntype Factory interface {\n\t// CreateDefaultConfig creates the default configuration for the telemetry.\n\tCreateDefaultConfig() component.Config\n\n\t// CreateResource creates a pcommon.Resource representing the collector.\n\t// This may be used by components in their internal telemetry.\n\tCreateResource(context.Context, Settings, component.Config) (pcommon.Resource, error)\n\n\t// CreateLogger creates a zap.Logger that may be used by components to\n\t// log their internal operations, along with a function that must be called\n\t// when the service is shutting down.\n\tCreateLogger(context.Context, LoggerSettings, component.Config) (*zap.Logger, component.ShutdownFunc, error)\n\n\t// CreateMeterProvider creates a metric.MeterProvider that may be used\n\t// by components to record metrics relating to their internal operations.\n\tCreateMeterProvider(context.Context, MeterSettings, component.Config) (MeterProvider, error)\n\n\t// CreateTracerProvider creates a trace.TracerProvider that may be used\n\t// by components to trace their internal operations.\n\t//\n\t// If the returned provider is a wrapper, consider implementing\n\t// the `Unwrap() trace.TracerProvider` method to grant components access to the underlying SDK.\n\tCreateTracerProvider(context.Context, TracerSettings, component.Config) (TracerProvider, error)\n\n\t// unexportedFactoryFunc is used to prevent external implementations of Factory.\n\tunexportedFactoryFunc()\n}\n\n// MeterProvider is a metric.MeterProvider that can be shutdown.\ntype MeterProvider interface {\n\tmetric.MeterProvider\n\tShutdown(context.Context) error\n}\n\n// TracerProvider is a trace.TracerProvider that can be shutdown.\ntype TracerProvider interface {\n\ttrace.TracerProvider\n\tShutdown(context.Context) error\n}\n\ntype FactoryOption interface {\n\tapplyOption(*factory)\n}\n\n// factoryOptionFunc is an FactoryOption created through a function.\ntype factoryOptionFunc func(*factory)\n\nfunc (f factoryOptionFunc) applyOption(o *factory) {\n\tf(o)\n}\n\ntype factory struct {\n\tcomponent.CreateDefaultConfigFunc\n\tcreateResourceFunc       CreateResourceFunc\n\tcreateLoggerFunc         CreateLoggerFunc\n\tcreateMeterProviderFunc  CreateMeterProviderFunc\n\tcreateTracerProviderFunc CreateTracerProviderFunc\n}\n\n// NewFactory returns a Factory.\nfunc NewFactory(createDefaultConfig component.CreateDefaultConfigFunc, opts ...FactoryOption) Factory {\n\tf := &factory{\n\t\tCreateDefaultConfigFunc: createDefaultConfig,\n\t}\n\tfor _, opt := range opts {\n\t\topt.applyOption(f)\n\t}\n\treturn f\n}\n\n// WithCreateResource overrides the default CreateResource implementation,\n// which creates an empty resource.\nfunc WithCreateResource(createResource CreateResourceFunc) FactoryOption {\n\treturn factoryOptionFunc(func(f *factory) {\n\t\tf.createResourceFunc = createResource\n\t})\n}\n\n// CreateResourceFunc is the equivalent of Factory.CreateResource.\ntype CreateResourceFunc func(context.Context, Settings, component.Config) (pcommon.Resource, error)\n\n// WithCreateLogger overrides the default CreateLogger implementation,\n// which creates a noop logger and noop logger provider.\nfunc WithCreateLogger(createLogger CreateLoggerFunc) FactoryOption {\n\treturn factoryOptionFunc(func(f *factory) {\n\t\tf.createLoggerFunc = createLogger\n\t})\n}\n\n// WithCreateLogger is the equivalent of Factory.CreateLogger.\ntype CreateLoggerFunc func(context.Context, LoggerSettings, component.Config) (*zap.Logger, component.ShutdownFunc, error)\n\n// WithCreateMeterProvider overrides the default CreateMeterProvider\nfunc WithCreateMeterProvider(createMeterProvider CreateMeterProviderFunc) FactoryOption {\n\treturn factoryOptionFunc(func(f *factory) {\n\t\tf.createMeterProviderFunc = createMeterProvider\n\t})\n}\n\n// CreateMeterProviderFunc is the equivalent of Factory.CreateMeterProvider.\ntype CreateMeterProviderFunc func(context.Context, MeterSettings, component.Config) (MeterProvider, error)\n\n// WithCreateTracerProvider overrides the default CreateTracerProvider\n// implementation, which creates a noop tracer provider.\nfunc WithCreateTracerProvider(createTracerProvider CreateTracerProviderFunc) FactoryOption {\n\treturn factoryOptionFunc(func(f *factory) {\n\t\tf.createTracerProviderFunc = createTracerProvider\n\t})\n}\n\n// CreateTracerProviderFunc is the equivalent of Factory.CreateTracerProvider.\ntype CreateTracerProviderFunc func(context.Context, TracerSettings, component.Config) (TracerProvider, error)\n\nfunc (*factory) unexportedFactoryFunc() {}\n\nfunc (f *factory) CreateResource(ctx context.Context, settings Settings, cfg component.Config) (pcommon.Resource, error) {\n\tif f.createResourceFunc == nil {\n\t\treturn pcommon.NewResource(), nil\n\t}\n\treturn f.createResourceFunc(ctx, settings, cfg)\n}\n\nfunc (f *factory) CreateLogger(ctx context.Context, settings LoggerSettings, cfg component.Config) (*zap.Logger, component.ShutdownFunc, error) {\n\tif f.createLoggerFunc == nil {\n\t\tlogger := zap.NewNop()\n\t\tnopShutdown := component.ShutdownFunc(nil)\n\t\treturn logger, nopShutdown, nil\n\t}\n\treturn f.createLoggerFunc(ctx, settings, cfg)\n}\n\nfunc (f *factory) CreateMeterProvider(ctx context.Context, settings MeterSettings, cfg component.Config) (MeterProvider, error) {\n\tif f.createMeterProviderFunc == nil {\n\t\treturn noopMeterProvider{MeterProvider: noopmetric.NewMeterProvider()}, nil\n\t}\n\treturn f.createMeterProviderFunc(ctx, settings, cfg)\n}\n\nfunc (f *factory) CreateTracerProvider(ctx context.Context, settings TracerSettings, cfg component.Config) (TracerProvider, error) {\n\tif f.createTracerProviderFunc == nil {\n\t\treturn noopTracerProvider{TracerProvider: nooptrace.NewTracerProvider()}, nil\n\t}\n\treturn f.createTracerProviderFunc(ctx, settings, cfg)\n}\n\ntype noopMeterProvider struct {\n\tnoopmetric.MeterProvider\n\tcomponent.ShutdownFunc\n}\n\ntype noopTracerProvider struct {\n\tnooptrace.TracerProvider\n\tcomponent.ShutdownFunc\n}\n"
  },
  {
    "path": "service/telemetry/telemetry_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage telemetry // import \"go.opentelemetry.io/collector/service/telemetry\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n)\n\nfunc TestNewFactory_CreateDefaultConfig(t *testing.T) {\n\tvar config component.Config = new(struct{})\n\tfactory := NewFactory(func() component.Config { return config })\n\trequire.NotNil(t, factory)\n\tassert.Equal(t, config, factory.CreateDefaultConfig())\n}\n\nfunc TestNewFactory_Defaults(t *testing.T) {\n\tfactory := NewFactory(nil)\n\trequire.NotNil(t, factory)\n\n\tres, err := factory.CreateResource(context.Background(), Settings{}, nil)\n\trequire.NoError(t, err)\n\tassert.Equal(t, pcommon.NewResource(), res)\n\n\tlogger, loggerShutdownFunc, err := factory.CreateLogger(context.Background(), LoggerSettings{}, nil)\n\trequire.NoError(t, err)\n\tassert.Equal(t, zap.NewNop(), logger)\n\tassert.Nil(t, loggerShutdownFunc)\n\n\tmeterProvider, err := factory.CreateMeterProvider(context.Background(), MeterSettings{}, nil)\n\trequire.NoError(t, err)\n\tassert.Equal(t, noopMeterProvider{MeterProvider: noopmetric.NewMeterProvider()}, meterProvider)\n\n\ttracerProvider, err := factory.CreateTracerProvider(context.Background(), TracerSettings{}, nil)\n\trequire.NoError(t, err)\n\tassert.Equal(t, noopTracerProvider{TracerProvider: nooptrace.NewTracerProvider()}, tracerProvider)\n}\n\nfunc TestNewFactory_Options(t *testing.T) {\n\tvar called []string\n\tfactory := NewFactory(nil, factoryOptionFunc(func(*factory) {\n\t\tcalled = append(called, \"option1\")\n\t}), factoryOptionFunc(func(*factory) {\n\t\tcalled = append(called, \"option2\")\n\t}))\n\trequire.NotNil(t, factory)\n\tassert.Equal(t, []string{\"option1\", \"option2\"}, called)\n}\n\nfunc TestNewFactory_CreateResource(t *testing.T) {\n\ttype contextKey struct{}\n\tvar config component.Config = new(struct{})\n\tsettings := Settings{\n\t\tBuildInfo: component.NewDefaultBuildInfo(),\n\t}\n\tctx := context.WithValue(context.Background(), contextKey{}, 123)\n\n\tdummyResource := pcommon.NewResource()\n\tdummyResource.Attributes().PutStr(\"what\", \"ever\")\n\tfactory := NewFactory(nil, WithCreateResource(\n\t\tfunc(ctx context.Context, set Settings, cfg component.Config) (pcommon.Resource, error) {\n\t\t\tassert.Equal(t, 123, ctx.Value(contextKey{}))\n\t\t\tassert.Equal(t, settings, set)\n\t\t\tassert.Equal(t, config, cfg)\n\t\t\treturn dummyResource, errors.New(\"not implemented\")\n\t\t},\n\t))\n\trequire.NotNil(t, factory)\n\n\tresource, err := factory.CreateResource(ctx, settings, config)\n\trequire.EqualError(t, err, \"not implemented\")\n\tassert.Equal(t, dummyResource, resource)\n}\n\nfunc TestNewFactory_CreateLogger(t *testing.T) {\n\ttype contextKey struct{}\n\tvar config component.Config = new(struct{})\n\tsettings := LoggerSettings{\n\t\tSettings: Settings{BuildInfo: component.NewDefaultBuildInfo()},\n\t}\n\tctx := context.WithValue(context.Background(), contextKey{}, 123)\n\n\tshutdownCalled := false\n\tdummyLogger := new(zap.Logger)\n\tfactory := NewFactory(nil, WithCreateLogger(\n\t\tfunc(ctx context.Context, set LoggerSettings, cfg component.Config) (*zap.Logger, component.ShutdownFunc, error) {\n\t\t\tassert.Equal(t, 123, ctx.Value(contextKey{}))\n\t\t\tassert.Equal(t, settings, set)\n\t\t\tassert.Equal(t, config, cfg)\n\t\t\tshutdownFunc := func(context.Context) error {\n\t\t\t\tshutdownCalled = true\n\t\t\t\treturn nil\n\t\t\t}\n\t\t\treturn dummyLogger, shutdownFunc, errors.New(\"not implemented\")\n\t\t},\n\t))\n\trequire.NotNil(t, factory)\n\n\tlogger, shutdownFunc, err := factory.CreateLogger(ctx, settings, config)\n\trequire.EqualError(t, err, \"not implemented\")\n\tassert.Equal(t, dummyLogger, logger)\n\trequire.NoError(t, shutdownFunc(context.Background()))\n\tassert.True(t, shutdownCalled)\n}\n\nfunc TestNewFactory_CreateMeterProvider(t *testing.T) {\n\ttype contextKey struct{}\n\tvar config component.Config = new(struct{})\n\tsettings := MeterSettings{\n\t\tSettings: Settings{BuildInfo: component.NewDefaultBuildInfo()},\n\t}\n\tctx := context.WithValue(context.Background(), contextKey{}, 123)\n\n\tvar dummyMeterProvider struct{ MeterProvider }\n\tfactory := NewFactory(nil, WithCreateMeterProvider(\n\t\tfunc(ctx context.Context, set MeterSettings, cfg component.Config) (MeterProvider, error) {\n\t\t\tassert.Equal(t, 123, ctx.Value(contextKey{}))\n\t\t\tassert.Equal(t, settings, set)\n\t\t\tassert.Equal(t, config, cfg)\n\t\t\treturn &dummyMeterProvider, errors.New(\"not implemented\")\n\t\t},\n\t))\n\trequire.NotNil(t, factory)\n\n\tmeterProvider, err := factory.CreateMeterProvider(ctx, settings, config)\n\trequire.EqualError(t, err, \"not implemented\")\n\tassert.Equal(t, &dummyMeterProvider, meterProvider)\n}\n\nfunc TestNewFactory_CreateTracerProvider(t *testing.T) {\n\ttype contextKey struct{}\n\tvar config component.Config = new(struct{})\n\tsettings := TracerSettings{\n\t\tSettings: Settings{BuildInfo: component.NewDefaultBuildInfo()},\n\t}\n\tctx := context.WithValue(context.Background(), contextKey{}, 123)\n\n\tvar dummyTracerProvider struct{ TracerProvider }\n\tfactory := NewFactory(nil, WithCreateTracerProvider(\n\t\tfunc(ctx context.Context, set TracerSettings, cfg component.Config) (TracerProvider, error) {\n\t\t\tassert.Equal(t, 123, ctx.Value(contextKey{}))\n\t\t\tassert.Equal(t, settings, set)\n\t\t\tassert.Equal(t, config, cfg)\n\t\t\treturn &dummyTracerProvider, errors.New(\"not implemented\")\n\t\t},\n\t))\n\trequire.NotNil(t, factory)\n\n\ttracerProvider, err := factory.CreateTracerProvider(ctx, settings, config)\n\trequire.EqualError(t, err, \"not implemented\")\n\tassert.Equal(t, &dummyTracerProvider, tracerProvider)\n}\n"
  },
  {
    "path": "service/telemetry/telemetrytest/Makefile",
    "content": "include ../../../Makefile.Common\n"
  },
  {
    "path": "service/telemetry/telemetrytest/go.mod",
    "content": "module go.opentelemetry.io/collector/service/telemetry/telemetrytest\n\ngo 1.25.0\n\nrequire (\n\tgithub.com/stretchr/testify v1.11.1\n\tgo.opentelemetry.io/collector/component v1.54.0\n\tgo.opentelemetry.io/collector/pdata v1.54.0\n\tgo.opentelemetry.io/collector/service v0.148.0\n\tgo.opentelemetry.io/otel/metric v1.42.0\n\tgo.opentelemetry.io/otel/trace v1.42.0\n\tgo.uber.org/zap v1.27.1\n)\n\nrequire (\n\tgithub.com/beorn7/perks v1.0.1 // indirect\n\tgithub.com/cenkalti/backoff/v5 v5.0.3 // indirect\n\tgithub.com/cespare/xxhash/v2 v2.3.0 // indirect\n\tgithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect\n\tgithub.com/go-logr/logr v1.4.3 // indirect\n\tgithub.com/go-logr/stdr v1.2.2 // indirect\n\tgithub.com/google/uuid v1.6.0 // indirect\n\tgithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 // indirect\n\tgithub.com/hashicorp/go-version v1.8.0 // indirect\n\tgithub.com/json-iterator/go v1.1.12 // indirect\n\tgithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect\n\tgithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect\n\tgithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect\n\tgithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect\n\tgithub.com/prometheus/client_golang v1.23.2 // indirect\n\tgithub.com/prometheus/client_model v0.6.2 // indirect\n\tgithub.com/prometheus/common v0.67.5 // indirect\n\tgithub.com/prometheus/otlptranslator v1.0.0 // indirect\n\tgithub.com/prometheus/procfs v0.20.1 // indirect\n\tgo.opentelemetry.io/auto/sdk v1.2.1 // indirect\n\tgo.opentelemetry.io/collector/config/configtelemetry v0.148.0 // indirect\n\tgo.opentelemetry.io/collector/featuregate v1.54.0 // indirect\n\tgo.opentelemetry.io/contrib/otelconf v0.22.0 // indirect\n\tgo.opentelemetry.io/otel v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/prometheus v0.64.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/log v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/sdk v1.42.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/log v0.18.0 // indirect\n\tgo.opentelemetry.io/otel/sdk/metric v1.42.0 // indirect\n\tgo.opentelemetry.io/proto/otlp v1.10.0 // indirect\n\tgo.uber.org/multierr v1.11.0 // indirect\n\tgo.yaml.in/yaml/v2 v2.4.3 // indirect\n\tgo.yaml.in/yaml/v3 v3.0.4 // indirect\n\tgolang.org/x/net v0.51.0 // indirect\n\tgolang.org/x/sys v0.42.0 // indirect\n\tgolang.org/x/text v0.34.0 // indirect\n\tgoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 // indirect\n\tgoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 // indirect\n\tgoogle.golang.org/grpc v1.79.3 // indirect\n\tgoogle.golang.org/protobuf v1.36.11 // indirect\n\tgopkg.in/yaml.v3 v3.0.1 // indirect\n)\n\nreplace go.opentelemetry.io/collector/component => ../../../component\n\nreplace go.opentelemetry.io/collector/internal/telemetry => ../../../internal/telemetry/\n\nreplace go.opentelemetry.io/collector/pdata => ../../../pdata\n\nreplace go.opentelemetry.io/collector/confmap => ../../../confmap\n\nreplace go.opentelemetry.io/collector/config/configtelemetry => ../../../config/configtelemetry\n\nreplace go.opentelemetry.io/collector/featuregate => ../../../featuregate\n\nreplace go.opentelemetry.io/collector/service => ../../\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware => ../../../extension/extensionmiddleware\n\nreplace go.opentelemetry.io/collector/config/configmiddleware => ../../../config/configmiddleware\n\nreplace go.opentelemetry.io/collector/receiver => ../../../receiver\n\nreplace go.opentelemetry.io/collector/processor/processortest => ../../../processor/processortest\n\nreplace go.opentelemetry.io/collector/processor/xprocessor => ../../../processor/xprocessor\n\nreplace go.opentelemetry.io/collector/processor => ../../../processor\n\nreplace go.opentelemetry.io/collector/pdata/xpdata => ../../../pdata/xpdata\n\nreplace go.opentelemetry.io/collector/pdata/pprofile => ../../../pdata/pprofile\n\nreplace go.opentelemetry.io/collector/extension/extensiontest => ../../../extension/extensiontest\n\nreplace go.opentelemetry.io/collector/exporter/xexporter => ../../../exporter/xexporter\n\nreplace go.opentelemetry.io/collector/consumer/consumertest => ../../../consumer/consumertest\n\nreplace go.opentelemetry.io/collector/pipeline => ../../../pipeline\n\nreplace go.opentelemetry.io/collector/receiver/xreceiver => ../../../receiver/xreceiver\n\nreplace go.opentelemetry.io/collector/pipeline/xpipeline => ../../../pipeline/xpipeline\n\nreplace go.opentelemetry.io/collector/pdata/testdata => ../../../pdata/testdata\n\nreplace go.opentelemetry.io/collector/otelcol => ../../../otelcol\n\nreplace go.opentelemetry.io/collector/extension/extensioncapabilities => ../../../extension/extensioncapabilities\n\nreplace go.opentelemetry.io/collector/extension/xextension => ../../../extension/xextension\n\nreplace go.opentelemetry.io/collector/exporter => ../../../exporter\n\nreplace go.opentelemetry.io/collector/config/configoptional => ../../../config/configoptional\n\nreplace go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest => ../../../extension/extensionmiddleware/extensionmiddlewaretest\n\nreplace go.opentelemetry.io/collector/config/configcompression => ../../../config/configcompression\n\nreplace go.opentelemetry.io/collector/extension => ../../../extension\n\nreplace go.opentelemetry.io/collector/exporter/exporterhelper => ../../../exporter/exporterhelper\n\nreplace go.opentelemetry.io/collector/consumer => ../../../consumer\n\nreplace go.opentelemetry.io/collector/consumer/xconsumer => ../../../consumer/xconsumer\n\nreplace go.opentelemetry.io/collector/consumer/consumererror => ../../../consumer/consumererror\n\nreplace go.opentelemetry.io/collector/connector => ../../../connector\n\nreplace go.opentelemetry.io/collector/confmap/xconfmap => ../../../confmap/xconfmap\n\nreplace go.opentelemetry.io/collector/config/configtls => ../../../config/configtls\n\nreplace go.opentelemetry.io/collector/service/hostcapabilities => ../../hostcapabilities\n\nreplace go.opentelemetry.io/collector/extension/zpagesextension => ../../../extension/zpagesextension\n\nreplace go.opentelemetry.io/collector/config/configretry => ../../../config/configretry\n\nreplace go.opentelemetry.io/collector/config/confighttp => ../../../config/confighttp\n\nreplace go.opentelemetry.io/collector/config/configopaque => ../../../config/configopaque\n\nreplace go.opentelemetry.io/collector/config/configauth => ../../../config/configauth\n\nreplace go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest => ../../../extension/extensionauth/extensionauthtest\n\nreplace go.opentelemetry.io/collector/client => ../../../client\n\nreplace go.opentelemetry.io/collector/receiver/receivertest => ../../../receiver/receivertest\n\nreplace go.opentelemetry.io/collector/confmap/provider/fileprovider => ../../../confmap/provider/fileprovider\n\nreplace go.opentelemetry.io/collector/internal/fanoutconsumer => ../../../internal/fanoutconsumer\n\nreplace go.opentelemetry.io/collector/exporter/exportertest => ../../../exporter/exportertest\n\nreplace go.opentelemetry.io/collector/extension/extensionauth => ../../../extension/extensionauth\n\nreplace go.opentelemetry.io/collector/connector/xconnector => ../../../connector/xconnector\n\nreplace go.opentelemetry.io/collector/connector/connectortest => ../../../connector/connectortest\n\nreplace go.opentelemetry.io/collector/component/componenttest => ../../../component/componenttest\n\nreplace go.opentelemetry.io/collector/component/componentstatus => ../../../component/componentstatus\n\nreplace go.opentelemetry.io/collector/internal/testutil => ../../../internal/testutil\n\nreplace go.opentelemetry.io/collector/internal/componentalias => ../../../internal/componentalias\n\nreplace go.opentelemetry.io/collector/config/confignet => ../../../config/confignet\n"
  },
  {
    "path": "service/telemetry/telemetrytest/go.sum",
    "content": "github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=\ngithub.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=\ngithub.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=\ngithub.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=\ngithub.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=\ngithub.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=\ngithub.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=\ngithub.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=\ngithub.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=\ngithub.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=\ngithub.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=\ngithub.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=\ngithub.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=\ngithub.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=\ngithub.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=\ngithub.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=\ngithub.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=\ngithub.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=\ngithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0 h1:HWRh5R2+9EifMyIHV7ZV+MIZqgz+PMpZ14Jynv3O2Zs=\ngithub.com/grpc-ecosystem/grpc-gateway/v2 v2.28.0/go.mod h1:JfhWUomR1baixubs02l85lZYYOm7LV6om4ceouMv45c=\ngithub.com/hashicorp/go-version v1.8.0 h1:KAkNb1HAiZd1ukkxDFGmokVZe1Xy9HG6NUp+bPle2i4=\ngithub.com/hashicorp/go-version v1.8.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=\ngithub.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=\ngithub.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=\ngithub.com/klauspost/compress v1.18.4 h1:RPhnKRAQ4Fh8zU2FY/6ZFDwTVTxgJ/EMydqSTzE9a2c=\ngithub.com/klauspost/compress v1.18.4/go.mod h1:R0h/fSBs8DE4ENlcrlib3PsXS61voFxhIs2DeRhCvJ4=\ngithub.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=\ngithub.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=\ngithub.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=\ngithub.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=\ngithub.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=\ngithub.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=\ngithub.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=\ngithub.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=\ngithub.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8=\ngithub.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=\ngithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=\ngithub.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=\ngithub.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=\ngithub.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=\ngithub.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=\ngithub.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=\ngithub.com/prometheus/common v0.67.5 h1:pIgK94WWlQt1WLwAC5j2ynLaBRDiinoAb86HZHTUGI4=\ngithub.com/prometheus/common v0.67.5/go.mod h1:SjE/0MzDEEAyrdr5Gqc6G+sXI67maCxzaT3A2+HqjUw=\ngithub.com/prometheus/otlptranslator v1.0.0 h1:s0LJW/iN9dkIH+EnhiD3BlkkP5QVIUVEoIwkU+A6qos=\ngithub.com/prometheus/otlptranslator v1.0.0/go.mod h1:vRYWnXvI6aWGpsdY/mOT/cbeVRBlPWtBNDb7kGR3uKM=\ngithub.com/prometheus/procfs v0.20.1 h1:XwbrGOIplXW/AU3YhIhLODXMJYyC1isLFfYCsTEycfc=\ngithub.com/prometheus/procfs v0.20.1/go.mod h1:o9EMBZGRyvDrSPH1RqdxhojkuXstoe4UlK79eF5TGGo=\ngithub.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=\ngithub.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=\ngithub.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=\ngithub.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=\ngo.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=\ngo.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=\ngo.opentelemetry.io/contrib/otelconf v0.22.0 h1:+kpcfczGOFM85zDZyqQCzWefhovegfn24D0WwmQz0n4=\ngo.opentelemetry.io/contrib/otelconf v0.22.0/go.mod h1:ojdbOukO+JRDJQmJY2PRIZEg0UYVzcOuZR59hp7xffc=\ngo.opentelemetry.io/otel v1.42.0 h1:lSQGzTgVR3+sgJDAU/7/ZMjN9Z+vUip7leaqBKy4sho=\ngo.opentelemetry.io/otel v1.42.0/go.mod h1:lJNsdRMxCUIWuMlVJWzecSMuNjE7dOYyWlqOXWkdqCc=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0 h1:deI9UQMoGFgrg5iLPgzueqFPHevDl+28YKfSpPTI6rY=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.18.0/go.mod h1:PFx9NgpNUKXdf7J4Q3agRxMs3Y07QhTCVipKmLsMKnU=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0 h1:icqq3Z34UrEFk2u+HMhTtRsvo7Ues+eiJVjaJt62njs=\ngo.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.18.0/go.mod h1:W2m8P+d5Wn5kipj4/xmbt9uMqezEKfBjzVJadfABSBE=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0 h1:MdKucPl/HbzckWWEisiNqMPhRrAOQX8r4jTuGr636gk=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.42.0/go.mod h1:RolT8tWtfHcjajEH5wFIZ4Dgh5jpPdFXYV9pTAk/qjc=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0 h1:H7O6RlGOMTizyl3R08Kn5pdM06bnH8oscSj7o11tmLA=\ngo.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.42.0/go.mod h1:mBFWu/WOVDkWWsR7Tx7h6EpQB8wsv7P0Yrh0Pb7othc=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0 h1:THuZiwpQZuHPul65w4WcwEnkX2QIuMT+UFoOrygtoJw=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace v1.42.0/go.mod h1:J2pvYM5NGHofZ2/Ru6zw/TNWnEQp5crgyDeSrYpXkAw=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0 h1:zWWrB1U6nqhS/k6zYB74CjRpuiitRtLLi68VcgmOEto=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.42.0/go.mod h1:2qXPNBX1OVRC0IwOnfo1ljoid+RD0QK3443EaqVlsOU=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0 h1:uLXP+3mghfMf7XmV4PkGfFhFKuNWoCvvx5wP/wOXo0o=\ngo.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.42.0/go.mod h1:v0Tj04armyT59mnURNUJf7RCKcKzq+lgJs6QSjHjaTc=\ngo.opentelemetry.io/otel/exporters/prometheus v0.64.0 h1:g0LRDXMX/G1SEZtK8zl8Chm4K6GBwRkjPKE36LxiTYs=\ngo.opentelemetry.io/otel/exporters/prometheus v0.64.0/go.mod h1:UrgcjnarfdlBDP3GjDIJWe6HTprwSazNjwsI+Ru6hro=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0 h1:KJVjPD3rcPb98rIs3HznyJlrfx9ge5oJvxxlGR+P/7s=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutlog v0.18.0/go.mod h1:K3kRa2ckmHWQaTWQdPRHc7qGXASuVuoEQXzrvlA98Ws=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0 h1:lSZHgNHfbmQTPfuTmWVkEu8J8qXaQwuV30pjCcAUvP8=\ngo.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.42.0/go.mod h1:so9ounLcuoRDu033MW/E0AD4hhUjVqswrMF5FoZlBcw=\ngo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0 h1:s/1iRkCKDfhlh1JF26knRneorus8aOwVIDhvYx9WoDw=\ngo.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.42.0/go.mod h1:UI3wi0FXg1Pofb8ZBiBLhtMzgoTm1TYkMvn71fAqDzs=\ngo.opentelemetry.io/otel/log v0.18.0 h1:XgeQIIBjZZrliksMEbcwMZefoOSMI1hdjiLEiiB0bAg=\ngo.opentelemetry.io/otel/log v0.18.0/go.mod h1:KEV1kad0NofR3ycsiDH4Yjcoj0+8206I6Ox2QYFSNgI=\ngo.opentelemetry.io/otel/metric v1.42.0 h1:2jXG+3oZLNXEPfNmnpxKDeZsFI5o4J+nz6xUlaFdF/4=\ngo.opentelemetry.io/otel/metric v1.42.0/go.mod h1:RlUN/7vTU7Ao/diDkEpQpnz3/92J9ko05BIwxYa2SSI=\ngo.opentelemetry.io/otel/sdk v1.42.0 h1:LyC8+jqk6UJwdrI/8VydAq/hvkFKNHZVIWuslJXYsDo=\ngo.opentelemetry.io/otel/sdk v1.42.0/go.mod h1:rGHCAxd9DAph0joO4W6OPwxjNTYWghRWmkHuGbayMts=\ngo.opentelemetry.io/otel/sdk/log v0.18.0 h1:n8OyZr7t7otkeTnPTbDNom6rW16TBYGtvyy2Gk6buQw=\ngo.opentelemetry.io/otel/sdk/log v0.18.0/go.mod h1:C0+wxkTwKpOCZLrlJ3pewPiiQwpzycPI/u6W0Z9fuYk=\ngo.opentelemetry.io/otel/sdk/log/logtest v0.18.0 h1:l3mYuPsuBx6UKE47BVcPrZoZ0q/KER57vbj2qkgDLXA=\ngo.opentelemetry.io/otel/sdk/log/logtest v0.18.0/go.mod h1:7cHtiVJpZebB3wybTa4NG+FUo5NPe3PROz1FqB0+qdw=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=\ngo.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=\ngo.opentelemetry.io/otel/trace v1.42.0 h1:OUCgIPt+mzOnaUTpOQcBiM/PLQ/Op7oq6g4LenLmOYY=\ngo.opentelemetry.io/otel/trace v1.42.0/go.mod h1:f3K9S+IFqnumBkKhRJMeaZeNk9epyhnCmQh/EysQCdc=\ngo.opentelemetry.io/proto/otlp v1.10.0 h1:IQRWgT5srOCYfiWnpqUYz9CVmbO8bFmKcwYxpuCSL2g=\ngo.opentelemetry.io/proto/otlp v1.10.0/go.mod h1:/CV4QoCR/S9yaPj8utp3lvQPoqMtxXdzn7ozvvozVqk=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0 h1:iR97Vs/ZDR+y9TfuP9b1XBtdPWeC+OMslIBmhcLU7jM=\ngo.opentelemetry.io/proto/slim/otlp v1.10.0/go.mod h1:lV9250stpjYLPNA5viFabIgP2QlUGRT1GdTgAf8SIUk=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0 h1:RUF5rO0hAlgiJt1fzQVzcVs3vZVNHIcMLgOgG4rWNcQ=\ngo.opentelemetry.io/proto/slim/otlp/collector/profiles/v1development v0.3.0/go.mod h1:I89cynRj8y+383o7tEQVg2SVA6SRgDVIouWPUVXjx0U=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0 h1:CQvJSldHRUN6Z8jsUeYv8J0lXRvygALXIzsmAeCcZE0=\ngo.opentelemetry.io/proto/slim/otlp/profiles/v1development v0.3.0/go.mod h1:xSQ+mEfJe/GjK1LXEyVOoSI1N9JV9ZI923X5kup43W4=\ngo.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=\ngo.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=\ngo.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=\ngo.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=\ngo.uber.org/zap v1.27.1 h1:08RqriUEv8+ArZRYSTXy1LeBScaMpVSTBhCeaZYfMYc=\ngo.uber.org/zap v1.27.1/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=\ngo.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=\ngo.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=\ngo.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=\ngo.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=\ngolang.org/x/net v0.51.0 h1:94R/GTO7mt3/4wIKpcR5gkGmRLOuE/2hNGeWq/GBIFo=\ngolang.org/x/net v0.51.0/go.mod h1:aamm+2QF5ogm02fjy5Bb7CQ0WMt1/WVM7FtyaTLlA9Y=\ngolang.org/x/sys v0.42.0 h1:omrd2nAlyT5ESRdCLYdm3+fMfNFE/+Rf4bDIQImRJeo=\ngolang.org/x/sys v0.42.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=\ngolang.org/x/text v0.34.0 h1:oL/Qq0Kdaqxa1KbNeMKwQq0reLCCaFtqu2eNuSeNHbk=\ngolang.org/x/text v0.34.0/go.mod h1:homfLqTYRFyVYemLBFl5GgL/DWEiH5wcsQ5gSh1yziA=\ngonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4=\ngonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E=\ngoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171 h1:tu/dtnW1o3wfaxCOjSLn5IRX4YDcJrtlpzYkhHhGaC4=\ngoogle.golang.org/genproto/googleapis/api v0.0.0-20260226221140-a57be14db171/go.mod h1:M5krXqk4GhBKvB596udGL3UyjL4I1+cTbK0orROM9ng=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171 h1:ggcbiqK8WWh6l1dnltU4BgWGIGo+EVYxCaAPih/zQXQ=\ngoogle.golang.org/genproto/googleapis/rpc v0.0.0-20260226221140-a57be14db171/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=\ngoogle.golang.org/grpc v1.79.3 h1:sybAEdRIEtvcD68Gx7dmnwjZKlyfuc61Dyo9pGXXkKE=\ngoogle.golang.org/grpc v1.79.3/go.mod h1:KmT0Kjez+0dde/v2j9vzwoAScgEPx/Bw1CYChhHLrHQ=\ngoogle.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=\ngoogle.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=\ngopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=\ngopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=\ngopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "service/telemetry/telemetrytest/metadata.yaml",
    "content": "type: service/telemetry/telemetrytest\ngithub_project: open-telemetry/opentelemetry-collector\n\nstatus:\n  disable_codecov_badge: true\n  class: pkg\n"
  },
  {
    "path": "service/telemetry/telemetrytest/providers.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage telemetrytest // import \"go.opentelemetry.io/collector/service/telemetry/telemetrytest\"\n\nimport (\n\t\"context\"\n\n\t\"go.opentelemetry.io/otel/metric\"\n\t\"go.opentelemetry.io/otel/trace\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/component\"\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n)\n\n// WithResource returns a telemetry.FactoryOption that configures the\n// factory's CreateResource method to return res.\nfunc WithResource(res pcommon.Resource) telemetry.FactoryOption {\n\treturn telemetry.WithCreateResource(\n\t\tfunc(context.Context, telemetry.Settings, component.Config) (pcommon.Resource, error) {\n\t\t\treturn res, nil\n\t\t},\n\t)\n}\n\n// WithLogger returns a telemetry.FactoryOption that configures the\n// factory's CreateLogger method to return logger and shutdown func.\nfunc WithLogger(logger *zap.Logger, shutdownFunc component.ShutdownFunc) telemetry.FactoryOption {\n\treturn telemetry.WithCreateLogger(\n\t\tfunc(context.Context, telemetry.LoggerSettings, component.Config) (\n\t\t\t*zap.Logger, component.ShutdownFunc, error,\n\t\t) {\n\t\t\treturn logger, shutdownFunc, nil\n\t\t},\n\t)\n}\n\n// WithMeterProvider returns a telemetry.FactoryOption that configures the\n// factory's CreateMeterProvider method to return provider. If provider does\n// not implement the Shutdown method, it will be wrapped with\n// ShutdownMeterProvider with a no-op shutdown func.\nfunc WithMeterProvider(provider metric.MeterProvider) telemetry.FactoryOption {\n\treturn telemetry.WithCreateMeterProvider(\n\t\tfunc(context.Context, telemetry.MeterSettings, component.Config) (\n\t\t\ttelemetry.MeterProvider, error,\n\t\t) {\n\t\t\twithShutdown, ok := provider.(telemetry.MeterProvider)\n\t\t\tif !ok {\n\t\t\t\twithShutdown = ShutdownMeterProvider{MeterProvider: provider}\n\t\t\t}\n\t\t\treturn withShutdown, nil\n\t\t},\n\t)\n}\n\n// WithTracerProvider returns a telemetry.FactoryOption that configures the\n// factory's CreateTracerProvider method to return provider. If provider does\n// not implement the Shutdown method, it will be wrapped with\n// ShutdownTracerProvider with a no-op shutdown func.\nfunc WithTracerProvider(provider trace.TracerProvider) telemetry.FactoryOption {\n\treturn telemetry.WithCreateTracerProvider(\n\t\tfunc(context.Context, telemetry.TracerSettings, component.Config) (\n\t\t\ttelemetry.TracerProvider, error,\n\t\t) {\n\t\t\twithShutdown, ok := provider.(telemetry.TracerProvider)\n\t\t\tif !ok {\n\t\t\t\twithShutdown = ShutdownTracerProvider{TracerProvider: provider}\n\t\t\t}\n\t\t\treturn withShutdown, nil\n\t\t},\n\t)\n}\n\ntype ShutdownMeterProvider struct {\n\tmetric.MeterProvider\n\tcomponent.ShutdownFunc\n}\n\ntype ShutdownTracerProvider struct {\n\ttrace.TracerProvider\n\tcomponent.ShutdownFunc\n}\n"
  },
  {
    "path": "service/telemetry/telemetrytest/providers_test.go",
    "content": "// Copyright The OpenTelemetry Authors\n// SPDX-License-Identifier: Apache-2.0\n\npackage telemetrytest // import \"go.opentelemetry.io/collector/service/telemetry/telemetrytest\"\n\nimport (\n\t\"context\"\n\t\"errors\"\n\t\"testing\"\n\n\t\"github.com/stretchr/testify/assert\"\n\t\"github.com/stretchr/testify/require\"\n\t\"go.opentelemetry.io/otel/metric\"\n\tnoopmetric \"go.opentelemetry.io/otel/metric/noop\"\n\t\"go.opentelemetry.io/otel/trace\"\n\tnooptrace \"go.opentelemetry.io/otel/trace/noop\"\n\t\"go.uber.org/zap\"\n\n\t\"go.opentelemetry.io/collector/pdata/pcommon\"\n\t\"go.opentelemetry.io/collector/service/telemetry\"\n)\n\nfunc TestWithResource(t *testing.T) {\n\tres := pcommon.NewResource()\n\tres.Attributes().PutStr(\"key\", \"value\")\n\n\tfactory := telemetry.NewFactory(nil, WithResource(res))\n\tcreatedResource, err := factory.CreateResource(context.Background(), telemetry.Settings{}, nil)\n\trequire.NoError(t, err)\n\tassert.Equal(t, res, createdResource)\n}\n\nfunc TestWithLogger(t *testing.T) {\n\tlogger := zap.NewNop()\n\tshutdownErr := errors.New(\"shutdown error\")\n\tshutdown := func(context.Context) error {\n\t\treturn shutdownErr\n\t}\n\n\tfactory := telemetry.NewFactory(nil, WithLogger(logger, shutdown))\n\tcreatedLogger, createdShutdown, err := factory.CreateLogger(context.Background(), telemetry.LoggerSettings{}, nil)\n\trequire.NoError(t, err)\n\tassert.Same(t, logger, createdLogger)\n\tassert.Same(t, shutdownErr, createdShutdown(t.Context()))\n}\n\nfunc TestWithMeterProvider(t *testing.T) {\n\ttest := func(t *testing.T, provider metric.MeterProvider, expected telemetry.MeterProvider) {\n\t\tfactory := telemetry.NewFactory(nil, WithMeterProvider(provider))\n\t\tcreatedProvider, err := factory.CreateMeterProvider(context.Background(), telemetry.MeterSettings{}, nil)\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, expected, createdProvider)\n\t}\n\tt.Run(\"Without Shutdown method\", func(t *testing.T) {\n\t\tprovider := noopmetric.NewMeterProvider()\n\t\ttest(t, provider, ShutdownMeterProvider{MeterProvider: provider})\n\t})\n\tt.Run(\"With Shutdown method\", func(t *testing.T) {\n\t\tprovider := new(struct{ telemetry.MeterProvider })\n\t\ttest(t, provider, provider)\n\t})\n}\n\nfunc TestWithTracerProvider(t *testing.T) {\n\ttest := func(t *testing.T, provider trace.TracerProvider, expected telemetry.TracerProvider) {\n\t\tfactory := telemetry.NewFactory(nil, WithTracerProvider(provider))\n\t\tcreatedProvider, err := factory.CreateTracerProvider(context.Background(), telemetry.TracerSettings{}, nil)\n\t\trequire.NoError(t, err)\n\t\tassert.Equal(t, expected, createdProvider)\n\t}\n\tt.Run(\"Without Shutdown method\", func(t *testing.T) {\n\t\tprovider := nooptrace.NewTracerProvider()\n\t\ttest(t, provider, ShutdownTracerProvider{TracerProvider: provider})\n\t})\n\tt.Run(\"With Shutdown method\", func(t *testing.T) {\n\t\tprovider := new(struct{ telemetry.TracerProvider })\n\t\ttest(t, provider, provider)\n\t})\n}\n"
  },
  {
    "path": "versions.yaml",
    "content": "# Copyright The OpenTelemetry Authors\n# SPDX-License-Identifier: Apache-2.0\n\nmodule-sets:\n  stable:\n    version: v1.54.0\n    modules:\n      - go.opentelemetry.io/collector/client\n      - go.opentelemetry.io/collector/featuregate\n      - go.opentelemetry.io/collector/pdata\n      - go.opentelemetry.io/collector/component\n      - go.opentelemetry.io/collector/confmap\n      - go.opentelemetry.io/collector/confmap/provider/envprovider\n      - go.opentelemetry.io/collector/confmap/provider/fileprovider\n      - go.opentelemetry.io/collector/confmap/provider/httpprovider\n      - go.opentelemetry.io/collector/confmap/provider/httpsprovider\n      - go.opentelemetry.io/collector/confmap/provider/yamlprovider\n      - go.opentelemetry.io/collector/config/configauth\n      - go.opentelemetry.io/collector/config/configopaque\n      - go.opentelemetry.io/collector/config/configoptional\n      - go.opentelemetry.io/collector/config/configcompression\n      - go.opentelemetry.io/collector/config/configretry\n      - go.opentelemetry.io/collector/config/configtls\n      - go.opentelemetry.io/collector/config/confignet\n      - go.opentelemetry.io/collector/config/configmiddleware\n      - go.opentelemetry.io/collector/consumer\n      - go.opentelemetry.io/collector/exporter\n      - go.opentelemetry.io/collector/extension\n      - go.opentelemetry.io/collector/extension/extensionauth\n      - go.opentelemetry.io/collector/pipeline\n      - go.opentelemetry.io/collector/processor\n      - go.opentelemetry.io/collector/receiver\n  beta:\n    version: v0.148.0\n    modules:\n      - go.opentelemetry.io/collector\n      - go.opentelemetry.io/collector/internal/componentalias\n      - go.opentelemetry.io/collector/internal/memorylimiter\n      - go.opentelemetry.io/collector/internal/fanoutconsumer\n      - go.opentelemetry.io/collector/internal/sharedcomponent\n      - go.opentelemetry.io/collector/internal/telemetry\n      - go.opentelemetry.io/collector/internal/testutil\n      - go.opentelemetry.io/collector/cmd/builder\n      - go.opentelemetry.io/collector/cmd/mdatagen\n      - go.opentelemetry.io/collector/component/componentstatus\n      - go.opentelemetry.io/collector/component/componenttest\n      - go.opentelemetry.io/collector/confmap/xconfmap\n      - go.opentelemetry.io/collector/config/configgrpc\n      - go.opentelemetry.io/collector/config/confighttp\n      - go.opentelemetry.io/collector/config/confighttp/xconfighttp\n      - go.opentelemetry.io/collector/config/configtelemetry\n      - go.opentelemetry.io/collector/connector\n      - go.opentelemetry.io/collector/connector/connectortest\n      - go.opentelemetry.io/collector/connector/forwardconnector\n      - go.opentelemetry.io/collector/connector/xconnector\n      - go.opentelemetry.io/collector/consumer/xconsumer\n      - go.opentelemetry.io/collector/consumer/consumererror\n      - go.opentelemetry.io/collector/consumer/consumererror/xconsumererror\n      - go.opentelemetry.io/collector/consumer/consumertest\n      - go.opentelemetry.io/collector/exporter/debugexporter\n      - go.opentelemetry.io/collector/exporter/exporterhelper\n      - go.opentelemetry.io/collector/exporter/exporterhelper/xexporterhelper\n      - go.opentelemetry.io/collector/exporter/exportertest\n      - go.opentelemetry.io/collector/exporter/nopexporter\n      - go.opentelemetry.io/collector/exporter/otlpexporter\n      - go.opentelemetry.io/collector/exporter/otlphttpexporter\n      - go.opentelemetry.io/collector/exporter/xexporter\n      - go.opentelemetry.io/collector/extension/extensionauth/extensionauthtest\n      - go.opentelemetry.io/collector/extension/extensioncapabilities\n      - go.opentelemetry.io/collector/extension/extensionmiddleware\n      - go.opentelemetry.io/collector/extension/extensionmiddleware/extensionmiddlewaretest\n      - go.opentelemetry.io/collector/extension/extensiontest\n      - go.opentelemetry.io/collector/extension/zpagesextension\n      - go.opentelemetry.io/collector/extension/memorylimiterextension\n      - go.opentelemetry.io/collector/extension/xextension\n      - go.opentelemetry.io/collector/otelcol\n      - go.opentelemetry.io/collector/otelcol/otelcoltest\n      - go.opentelemetry.io/collector/pdata/pprofile\n      - go.opentelemetry.io/collector/pdata/testdata\n      - go.opentelemetry.io/collector/pdata/xpdata\n      - go.opentelemetry.io/collector/pipeline/xpipeline\n      - go.opentelemetry.io/collector/processor/processortest\n      - go.opentelemetry.io/collector/processor/processorhelper\n      - go.opentelemetry.io/collector/processor/batchprocessor\n      - go.opentelemetry.io/collector/processor/memorylimiterprocessor\n      - go.opentelemetry.io/collector/processor/processorhelper/xprocessorhelper\n      - go.opentelemetry.io/collector/processor/xprocessor\n      - go.opentelemetry.io/collector/receiver/receiverhelper\n      - go.opentelemetry.io/collector/receiver/nopreceiver\n      - go.opentelemetry.io/collector/receiver/otlpreceiver\n      - go.opentelemetry.io/collector/receiver/receivertest\n      - go.opentelemetry.io/collector/receiver/xreceiver\n      - go.opentelemetry.io/collector/scraper\n      - go.opentelemetry.io/collector/scraper/scraperhelper\n      - go.opentelemetry.io/collector/scraper/scraperhelper/xscraperhelper\n      - go.opentelemetry.io/collector/scraper/scrapertest\n      - go.opentelemetry.io/collector/scraper/xscraper\n      - go.opentelemetry.io/collector/service\n      - go.opentelemetry.io/collector/service/hostcapabilities\n      - go.opentelemetry.io/collector/service/telemetry/telemetrytest\n      - go.opentelemetry.io/collector/filter\n\nexcluded-modules:\n  - go.opentelemetry.io/collector/cmd/otelcorecol\n  - go.opentelemetry.io/collector/internal/cmd/pdatagen\n  - go.opentelemetry.io/collector/internal/e2e\n  - go.opentelemetry.io/collector/internal/tools\n  - go.opentelemetry.io/collector/confmap/internal/e2e\n"
  }
]